Locales für -r4298
[kivitendo-erp.git] / SL / Form.pm
1 #====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 1998-2002
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 # Contributors: Thomas Bayen <bayen@gmx.de>
16 #               Antti Kaihola <akaihola@siba.fi>
17 #               Moritz Bunkus (tex code)
18 #
19 # This program is free software; you can redistribute it and/or modify
20 # it under the terms of the GNU General Public License as published by
21 # the Free Software Foundation; either version 2 of the License, or
22 # (at your option) any later version.
23 #
24 # This program is distributed in the hope that it will be useful,
25 # but WITHOUT ANY WARRANTY; without even the implied warranty of
26 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27 # GNU General Public License for more details.
28 # You should have received a copy of the GNU General Public License
29 # along with this program; if not, write to the Free Software
30 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
31 #======================================================================
32 # Utilities for parsing forms
33 # and supporting routines for linking account numbers
34 # used in AR, AP and IS, IR modules
35 #
36 #======================================================================
37
38 package Form;
39
40 #use strict;
41
42 use Data::Dumper;
43
44 use CGI;
45 use CGI::Ajax;
46 use Cwd;
47 use IO::File;
48 use SL::Auth;
49 use SL::Auth::DB;
50 use SL::Auth::LDAP;
51 use SL::AM;
52 use SL::Common;
53 use SL::DBUtils;
54 use SL::Mailer;
55 use SL::Menu;
56 use SL::Template;
57 use SL::User;
58 use Template;
59 use List::Util qw(first max min sum);
60
61 my $standard_dbh;
62
63 END {
64   if ($standard_dbh) {
65     $standard_dbh->disconnect();
66     undef $standard_dbh;
67   }
68 }
69
70 =item _store_value()
71
72 parses a complex var name, and stores it in the form.
73
74 syntax:
75   $form->_store_value($key, $value);
76
77 keys must start with a string, and can contain various tokens.
78 supported key structures are:
79
80 1. simple access
81   simple key strings work as expected
82
83   id => $form->{id}
84
85 2. hash access.
86   separating two keys by a dot (.) will result in a hash lookup for the inner value
87   this is similar to the behaviour of java and templating mechanisms.
88
89   filter.description => $form->{filter}->{description}
90
91 3. array+hashref access
92
93   adding brackets ([]) before the dot will cause the next hash to be put into an array.
94   using [+] instead of [] will force a new array index. this is useful for recurring
95   data structures like part lists. put a [+] into the first varname, and use [] on the
96   following ones.
97
98   repeating these names in your template:
99
100     invoice.items[+].id
101     invoice.items[].parts_id
102
103   will result in:
104
105     $form->{invoice}->{items}->[
106       {
107         id       => ...
108         parts_id => ...
109       },
110       {
111         id       => ...
112         parts_id => ...
113       }
114       ...
115     ]
116
117 4. arrays
118
119   using brackets at the end of a name will result in a pure array to be created.
120   note that you mustn't use [+], which is reserved for array+hash access and will
121   result in undefined behaviour in array context.
122
123   filter.status[]  => $form->{status}->[ val1, val2, ... ]
124
125 =cut
126 sub _store_value {
127   $main::lxdebug->enter_sub(2);
128
129   my $self  = shift;
130   my $key   = shift;
131   my $value = shift;
132
133   my @tokens = split /((?:\[\+?\])?(?:\.|$))/, $key;
134
135   my $curr;
136
137   if (scalar @tokens) {
138      $curr = \ $self->{ shift @tokens };
139   }
140
141   while (@tokens) {
142     my $sep = shift @tokens;
143     my $key = shift @tokens;
144
145     $curr = \ $$curr->[++$#$$curr], next if $sep eq '[]';
146     $curr = \ $$curr->[max 0, $#$$curr]  if $sep eq '[].';
147     $curr = \ $$curr->[++$#$$curr]       if $sep eq '[+].';
148     $curr = \ $$curr->{$key}
149   }
150
151   $$curr = $value;
152
153   $main::lxdebug->leave_sub(2);
154
155   return $curr;
156 }
157
158 sub _input_to_hash {
159   $main::lxdebug->enter_sub(2);
160
161   my $self  = shift;
162   my $input = shift;
163
164   my @pairs = split(/&/, $input);
165
166   foreach (@pairs) {
167     my ($key, $value) = split(/=/, $_, 2);
168     $self->_store_value($self->unescape($key), $self->unescape($value)) if ($key);
169   }
170
171   $main::lxdebug->leave_sub(2);
172 }
173
174 sub _request_to_hash {
175   $main::lxdebug->enter_sub(2);
176
177   my $self  = shift;
178   my $input = shift;
179
180   if (!$ENV{'CONTENT_TYPE'}
181       || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
182
183     $self->_input_to_hash($input);
184
185     $main::lxdebug->leave_sub(2);
186     return;
187   }
188
189   my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr, $previous);
190
191   my $boundary = '--' . $1;
192
193   foreach my $line (split m/\n/, $input) {
194     last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
195
196     if (($line eq $boundary) || ($line eq "$boundary\r")) {
197       ${ $previous } =~ s|\r?\n$|| if $previous;
198
199       undef $previous;
200       undef $filename;
201
202       $headers_done   = 0;
203       $content_type   = "text/plain";
204       $boundary_found = 1;
205       $need_cr        = 0;
206
207       next;
208     }
209
210     next unless $boundary_found;
211
212     if (!$headers_done) {
213       $line =~ s/[\r\n]*$//;
214
215       if (!$line) {
216         $headers_done = 1;
217         next;
218       }
219
220       if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
221         if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
222           $filename = $1;
223           substr $line, $-[0], $+[0] - $-[0], "";
224         }
225
226         if ($line =~ m|name\s*=\s*"(.*?)"|i) {
227           $name = $1;
228           substr $line, $-[0], $+[0] - $-[0], "";
229         }
230
231         $previous         = $self->_store_value($name, '') if ($name);
232         $self->{FILENAME} = $filename if ($filename);
233
234         next;
235       }
236
237       if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
238         $content_type = $1;
239       }
240
241       next;
242     }
243
244     next unless $previous;
245
246     ${ $previous } .= "${line}\n";
247   }
248
249   ${ $previous } =~ s|\r?\n$|| if $previous;
250
251   $main::lxdebug->leave_sub(2);
252 }
253
254 sub _recode_recursively {
255   $main::lxdebug->enter_sub();
256   my ($iconv, $param) = @_;
257
258   if (ref $param eq 'HASH') {
259     foreach my $key (keys %{ $param }) {
260       if (!ref $param->{$key}) {
261         $param->{$key} = $iconv->convert($param->{$key});
262       } else {
263         _recode_recursively($iconv, $param->{$key});
264       }
265     }
266
267   } elsif (ref $param eq 'ARRAY') {
268     foreach my $idx (0 .. scalar(@{ $param }) - 1) {
269       if (!ref $param->[$idx]) {
270         $param->[$idx] = $iconv->convert($param->[$idx]);
271       } else {
272         _recode_recursively($iconv, $param->[$idx]);
273       }
274     }
275   }
276   $main::lxdebug->leave_sub();
277 }
278
279 sub new {
280   $main::lxdebug->enter_sub();
281
282   my $type = shift;
283
284   my $self = {};
285
286   if ($LXDebug::watch_form) {
287     require SL::Watchdog;
288     tie %{ $self }, 'SL::Watchdog';
289   }
290
291   read(STDIN, $_, $ENV{CONTENT_LENGTH});
292
293   if ($ENV{QUERY_STRING}) {
294     $_ = $ENV{QUERY_STRING};
295   }
296
297   if ($ARGV[0]) {
298     $_ = $ARGV[0];
299   }
300
301   bless $self, $type;
302
303   $self->_request_to_hash($_);
304
305   my $db_charset   = $main::dbcharset;
306   $db_charset    ||= Common::DEFAULT_CHARSET;
307
308   if ($self->{INPUT_ENCODING} && (lc $self->{INPUT_ENCODING} ne $db_charset)) {
309     require Text::Iconv;
310     my $iconv = Text::Iconv->new($self->{INPUT_ENCODING}, $db_charset);
311
312     _recode_recursively($iconv, $self);
313
314     delete $self{INPUT_ENCODING};
315   }
316
317   $self->{action}  =  lc $self->{action};
318   $self->{action}  =~ s/( |-|,|\#)/_/g;
319
320   $self->{version} =  "2.6.0";
321
322   $main::lxdebug->leave_sub();
323
324   return $self;
325 }
326
327 sub _flatten_variables_rec {
328   $main::lxdebug->enter_sub(2);
329
330   my $self   = shift;
331   my $curr   = shift;
332   my $prefix = shift;
333   my $key    = shift;
334
335   my @result;
336
337   if ('' eq ref $curr->{$key}) {
338     @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
339
340   } elsif ('HASH' eq ref $curr->{$key}) {
341     foreach my $hash_key (sort keys %{ $curr->{$key} }) {
342       push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
343     }
344
345   } else {
346     foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
347       my $first_array_entry = 1;
348
349       foreach my $hash_key (sort keys %{ $curr->{$key}->[$idx] }) {
350         push @result, $self->_flatten_variables_rec($curr->{$key}->[$idx], $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
351         $first_array_entry = 0;
352       }
353     }
354   }
355
356   $main::lxdebug->leave_sub(2);
357
358   return @result;
359 }
360
361 sub flatten_variables {
362   $main::lxdebug->enter_sub(2);
363
364   my $self = shift;
365   my @keys = @_;
366
367   my @variables;
368
369   foreach (@keys) {
370     push @variables, $self->_flatten_variables_rec($self, '', $_);
371   }
372
373   $main::lxdebug->leave_sub(2);
374
375   return @variables;
376 }
377
378 sub flatten_standard_variables {
379   $main::lxdebug->enter_sub(2);
380
381   my $self      = shift;
382   my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar version), @_);
383
384   my @variables;
385
386   foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
387     push @variables, $self->_flatten_variables_rec($self, '', $_);
388   }
389
390   $main::lxdebug->leave_sub(2);
391
392   return @variables;
393 }
394
395 sub debug {
396   $main::lxdebug->enter_sub();
397
398   my ($self) = @_;
399
400   print "\n";
401
402   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
403
404   $main::lxdebug->leave_sub();
405 }
406
407 sub dumper {
408   $main::lxdebug->enter_sub(2);
409
410   my $self          = shift;
411   my $password      = $self->{password};
412
413   $self->{password} = 'X' x 8;
414
415   local $Data::Dumper::Sortkeys = 1;
416   my $output                    = Dumper($self);
417
418   $self->{password} = $password;
419
420   $main::lxdebug->leave_sub(2);
421
422   return $output;
423 }
424
425 sub escape {
426   $main::lxdebug->enter_sub(2);
427
428   my ($self, $str) = @_;
429
430   $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
431
432   $main::lxdebug->leave_sub(2);
433
434   return $str;
435 }
436
437 sub unescape {
438   $main::lxdebug->enter_sub(2);
439
440   my ($self, $str) = @_;
441
442   $str =~ tr/+/ /;
443   $str =~ s/\\$//;
444
445   $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
446
447   $main::lxdebug->leave_sub(2);
448
449   return $str;
450 }
451
452 sub quote {
453   $main::lxdebug->enter_sub();
454   my ($self, $str) = @_;
455
456   if ($str && !ref($str)) {
457     $str =~ s/\"/&quot;/g;
458   }
459
460   $main::lxdebug->leave_sub();
461
462   return $str;
463 }
464
465 sub unquote {
466   $main::lxdebug->enter_sub();
467   my ($self, $str) = @_;
468
469   if ($str && !ref($str)) {
470     $str =~ s/&quot;/\"/g;
471   }
472
473   $main::lxdebug->leave_sub();
474
475   return $str;
476 }
477
478 sub hide_form {
479   $main::lxdebug->enter_sub();
480   my $self = shift;
481
482   if (@_) {
483     map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
484   } else {
485     for (sort keys %$self) {
486       next if (($_ eq "header") || (ref($self->{$_}) ne ""));
487       print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
488     }
489   }
490   $main::lxdebug->leave_sub();
491 }
492
493 sub error {
494   $main::lxdebug->enter_sub();
495
496   $main::lxdebug->show_backtrace();
497
498   my ($self, $msg) = @_;
499   if ($ENV{HTTP_USER_AGENT}) {
500     $msg =~ s/\n/<br>/g;
501     $self->show_generic_error($msg);
502
503   } else {
504
505     die "Error: $msg\n";
506   }
507
508   $main::lxdebug->leave_sub();
509 }
510
511 sub info {
512   $main::lxdebug->enter_sub();
513
514   my ($self, $msg) = @_;
515
516   if ($ENV{HTTP_USER_AGENT}) {
517     $msg =~ s/\n/<br>/g;
518
519     if (!$self->{header}) {
520       $self->header;
521       print qq|
522       <body>|;
523     }
524
525     print qq|
526
527     <p><b>$msg</b>
528     |;
529
530   } else {
531
532     if ($self->{info_function}) {
533       &{ $self->{info_function} }($msg);
534     } else {
535       print "$msg\n";
536     }
537   }
538
539   $main::lxdebug->leave_sub();
540 }
541
542 # calculates the number of rows in a textarea based on the content and column number
543 # can be capped with maxrows
544 sub numtextrows {
545   $main::lxdebug->enter_sub();
546   my ($self, $str, $cols, $maxrows, $minrows) = @_;
547
548   $minrows ||= 1;
549
550   my $rows   = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
551   $maxrows ||= $rows;
552
553   $main::lxdebug->leave_sub();
554
555   return max(min($rows, $maxrows), $minrows);
556 }
557
558 sub dberror {
559   $main::lxdebug->enter_sub();
560
561   my ($self, $msg) = @_;
562
563   $self->error("$msg\n" . $DBI::errstr);
564
565   $main::lxdebug->leave_sub();
566 }
567
568 sub isblank {
569   $main::lxdebug->enter_sub();
570
571   my ($self, $name, $msg) = @_;
572
573   my $curr = $self;
574   foreach my $part (split m/\./, $name) {
575     if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
576       $self->error($msg);
577     }
578     $curr = $curr->{$part};
579   }
580
581   $main::lxdebug->leave_sub();
582 }
583
584 sub create_http_response {
585   $main::lxdebug->enter_sub();
586
587   my $self     = shift;
588   my %params   = @_;
589
590   my $cgi      = $main::cgi;
591   $cgi       ||= CGI->new('');
592
593   my $base_path;
594
595   if ($ENV{HTTP_X_FORWARDED_FOR}) {
596     $base_path =  $ENV{HTTP_REFERER};
597     $base_path =~ s|^.*?://.*?/|/|;
598   } else {
599     $base_path =  $ENV{REQUEST_URI};
600   }
601   $base_path =~ s|[^/]+$||;
602   $base_path =~ s|/$||;
603
604   my $session_cookie;
605   if (defined $main::auth) {
606     my $session_cookie_value   = $main::auth->get_session_id();
607     $session_cookie_value    ||= 'NO_SESSION';
608
609     $session_cookie = $cgi->cookie('-name'  => $main::auth->get_session_cookie_name(),
610                                    '-value' => $session_cookie_value,
611                                    '-path'  => $base_path);
612   }
613
614   my %cgi_params = ('-type' => $params{content_type});
615   $cgi_params{'-charset'} = $params{charset} if ($params{charset});
616
617   my $output = $cgi->header('-cookie' => $session_cookie,
618                             %cgi_params);
619
620   $main::lxdebug->leave_sub();
621
622   return $output;
623 }
624
625
626 sub header {
627   $main::lxdebug->enter_sub();
628
629   my ($self, $extra_code) = @_;
630
631   if ($self->{header}) {
632     $main::lxdebug->leave_sub();
633     return;
634   }
635
636   my ($stylesheet, $favicon, $pagelayout);
637
638   if ($ENV{HTTP_USER_AGENT}) {
639     my $doctype;
640
641     if ($ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+\d/) {
642       # Only set the DOCTYPE for Internet Explorer. Other browsers have problems displaying the menu otherwise.
643       $doctype = qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n|;
644     }
645
646     my $stylesheets = "$self->{stylesheet} $self->{stylesheets}";
647
648     $stylesheets =~ s|^\s*||;
649     $stylesheets =~ s|\s*$||;
650     foreach my $file (split m/\s+/, $stylesheets) {
651       $file =~ s|.*/||;
652       next if (! -f "css/$file");
653
654       $stylesheet .= qq|<link rel="stylesheet" href="css/$file" TYPE="text/css" TITLE="Lx-Office stylesheet">\n|;
655     }
656
657     $self->{favicon}    = "favicon.ico" unless $self->{favicon};
658
659     if ($self->{favicon} && (-f "$self->{favicon}")) {
660       $favicon =
661         qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
662   |;
663     }
664
665     my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
666
667     if ($self->{landscape}) {
668       $pagelayout = qq|<style type="text/css">
669                         \@page { size:landscape; }
670                         </style>|;
671     }
672
673     my $fokus = qq|  document.$self->{fokus}.focus();| if ($self->{"fokus"});
674
675     #Set Calendar
676     my $jsscript = "";
677     if ($self->{jsscript} == 1) {
678
679       $jsscript = qq|
680         <script type="text/javascript" src="js/common.js"></script>
681         <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
682         <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
683         <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
684         <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
685         $self->{javascript}
686        |;
687     }
688
689     $self->{titlebar} =
690       ($self->{title})
691       ? "$self->{title} - $self->{titlebar}"
692       : $self->{titlebar};
693     my $ajax = "";
694     foreach my $item (@ { $self->{AJAX} }) {
695       $ajax .= $item->show_javascript();
696     }
697
698     print $self->create_http_response('content_type' => 'text/html',
699                                       'charset'      => $db_charset,);
700     print qq|${doctype}<html>
701 <head>
702   <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
703   <title>$self->{titlebar}</title>
704   $stylesheet
705   $pagelayout
706   $favicon
707   $jsscript
708   $ajax
709
710   <script type="text/javascript">
711   <!--
712     function focus() {
713       $fokus
714     }
715   //-->
716   </script>
717
718   <meta name="robots" content="noindex,nofollow" />
719   <script type="text/javascript" src="js/highlight_input.js"></script>
720
721   <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
722   <script type="text/javascript" src="js/tabcontent.js">
723
724   /***********************************************
725    * Tab Content script v2.2- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
726    * This notice MUST stay intact for legal use
727    * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
728    ***********************************************/
729
730   </script>
731
732   $extra_code
733 </head>
734
735 |;
736   }
737   $self->{header} = 1;
738
739   $main::lxdebug->leave_sub();
740 }
741
742 sub ajax_response_header {
743   $main::lxdebug->enter_sub();
744
745   my ($self) = @_;
746
747   my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
748   my $cgi        = $main::cgi || CGI->new('');
749   my $output     = $cgi->header('-charset' => $db_charset);
750
751   $main::lxdebug->leave_sub();
752
753   return $output;
754 }
755
756 sub _prepare_html_template {
757   $main::lxdebug->enter_sub();
758
759   my ($self, $file, $additional_params) = @_;
760   my $language;
761
762   if (!defined(%main::myconfig) || !defined($main::myconfig{"countrycode"})) {
763     $language = $main::language;
764   } else {
765     $language = $main::myconfig{"countrycode"};
766   }
767   $language = "de" unless ($language);
768
769   if (-f "templates/webpages/${file}_${language}.html") {
770     if ((-f ".developer") &&
771         (-f "templates/webpages/${file}_master.html") &&
772         ((stat("templates/webpages/${file}_master.html"))[9] >
773          (stat("templates/webpages/${file}_${language}.html"))[9])) {
774       my $info = "Developer information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
775         "Please re-run 'locales.pl' in 'locale/${language}'.";
776       print(qq|<pre>$info</pre>|);
777       die($info);
778     }
779
780     $file = "templates/webpages/${file}_${language}.html";
781   } elsif (-f "templates/webpages/${file}.html") {
782     $file = "templates/webpages/${file}.html";
783   } else {
784     my $info = "Web page template '${file}' not found.\n" .
785       "Please re-run 'locales.pl' in 'locale/${language}'.";
786     print(qq|<pre>$info</pre>|);
787     die($info);
788   }
789
790   if ($self->{"DEBUG"}) {
791     $additional_params->{"DEBUG"} = $self->{"DEBUG"};
792   }
793
794   if ($additional_params->{"DEBUG"}) {
795     $additional_params->{"DEBUG"} =
796       "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
797   }
798
799   if (%main::myconfig) {
800     map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
801     my $jsc_dateformat = $main::myconfig{"dateformat"};
802     $jsc_dateformat =~ s/d+/\%d/gi;
803     $jsc_dateformat =~ s/m+/\%m/gi;
804     $jsc_dateformat =~ s/y+/\%Y/gi;
805     $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
806   }
807
808   $additional_params->{"conf_dbcharset"}              = $main::dbcharset;
809   $additional_params->{"conf_webdav"}                 = $main::webdav;
810   $additional_params->{"conf_lizenzen"}               = $main::lizenzen;
811   $additional_params->{"conf_latex_templates"}        = $main::latex;
812   $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
813
814   if (%main::debug_options) {
815     map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
816   }
817
818   if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
819     while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
820       $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
821     }
822   }
823
824   $main::lxdebug->leave_sub();
825
826   return $file;
827 }
828
829 sub parse_html_template {
830   $main::lxdebug->enter_sub();
831
832   my ($self, $file, $additional_params) = @_;
833
834   $additional_params ||= { };
835
836   $file = $self->_prepare_html_template($file, $additional_params);
837
838   my $template = Template->new({ 'INTERPOLATE'  => 0,
839                                  'EVAL_PERL'    => 0,
840                                  'ABSOLUTE'     => 1,
841                                  'CACHE_SIZE'   => 0,
842                                  'PLUGIN_BASE'  => 'SL::Template::Plugin',
843                                  'INCLUDE_PATH' => '.:templates/webpages',
844                                }) || die;
845
846   map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
847
848   my $in = IO::File->new($file, 'r');
849
850   if (!$in) {
851     print STDERR "Error opening template file: $!";
852     $main::lxdebug->leave_sub();
853     return '';
854   }
855
856   my $input = join('', <$in>);
857   $in->close();
858
859   if ($main::locale) {
860     $input = $main::locale->{iconv}->convert($input);
861   }
862
863   my $output;
864   if (!$template->process(\$input, $additional_params, \$output)) {
865     print STDERR $template->error();
866   }
867
868   $main::lxdebug->leave_sub();
869
870   return $output;
871 }
872
873 sub show_generic_error {
874   $main::lxdebug->enter_sub();
875
876   my ($self, $error, %params) = @_;
877
878   my $add_params = {
879     'title_error' => $params{title},
880     'label_error' => $error,
881   };
882
883   if ($params{action}) {
884     my @vars;
885
886     map { delete($self->{$_}); } qw(action);
887     map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
888
889     $add_params->{SHOW_BUTTON}  = 1;
890     $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
891     $add_params->{VARIABLES}    = \@vars;
892
893   } elsif ($params{back_button}) {
894     $add_params->{SHOW_BACK_BUTTON} = 1;
895   }
896
897   $self->{title} = $params{title} if $params{title};
898
899   $self->header();
900   print $self->parse_html_template("generic/error", $add_params);
901
902   $main::lxdebug->leave_sub();
903
904   die("Error: $error\n");
905 }
906
907 sub show_generic_information {
908   $main::lxdebug->enter_sub();
909
910   my ($self, $text, $title) = @_;
911
912   my $add_params = {
913     'title_information' => $title,
914     'label_information' => $text,
915   };
916
917   $self->{title} = $title if ($title);
918
919   $self->header();
920   print $self->parse_html_template("generic/information", $add_params);
921
922   $main::lxdebug->leave_sub();
923
924   die("Information: $text\n");
925 }
926
927 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
928 # changed it to accept an arbitrary number of triggers - sschoeling
929 sub write_trigger {
930   $main::lxdebug->enter_sub();
931
932   my $self     = shift;
933   my $myconfig = shift;
934   my $qty      = shift;
935
936   # set dateform for jsscript
937   # default
938   my %dateformats = (
939     "dd.mm.yy" => "%d.%m.%Y",
940     "dd-mm-yy" => "%d-%m-%Y",
941     "dd/mm/yy" => "%d/%m/%Y",
942     "mm/dd/yy" => "%m/%d/%Y",
943     "mm-dd-yy" => "%m-%d-%Y",
944     "yyyy-mm-dd" => "%Y-%m-%d",
945     );
946
947   my $ifFormat = defined($dateformats{$myconfig->{"dateformat"}}) ?
948     $dateformats{$myconfig->{"dateformat"}} : "%d.%m.%Y";
949
950   my @triggers;
951   while ($#_ >= 2) {
952     push @triggers, qq|
953        Calendar.setup(
954       {
955       inputField : "| . (shift) . qq|",
956       ifFormat :"$ifFormat",
957       align : "| .  (shift) . qq|",
958       button : "| . (shift) . qq|"
959       }
960       );
961        |;
962   }
963   my $jsscript = qq|
964        <script type="text/javascript">
965        <!--| . join("", @triggers) . qq|//-->
966         </script>
967         |;
968
969   $main::lxdebug->leave_sub();
970
971   return $jsscript;
972 }    #end sub write_trigger
973
974 sub redirect {
975   $main::lxdebug->enter_sub();
976
977   my ($self, $msg) = @_;
978
979   if ($self->{callback}) {
980
981     my ($script, $argv) = split(/\?/, $self->{callback}, 2);
982     $script =~ s|.*/||;
983     $script =~ s|[^a-zA-Z0-9_\.]||g;
984     exec("perl", "$script", $argv);
985
986   } else {
987
988     $self->info($msg);
989     exit;
990   }
991
992   $main::lxdebug->leave_sub();
993 }
994
995 # sort of columns removed - empty sub
996 sub sort_columns {
997   $main::lxdebug->enter_sub();
998
999   my ($self, @columns) = @_;
1000
1001   $main::lxdebug->leave_sub();
1002
1003   return @columns;
1004 }
1005 #
1006 sub format_amount {
1007   $main::lxdebug->enter_sub(2);
1008
1009   my ($self, $myconfig, $amount, $places, $dash) = @_;
1010
1011   if ($amount eq "") {
1012     $amount = 0;
1013   }
1014
1015   # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
1016
1017   my $neg = ($amount =~ s/^-//);
1018   my $exp = ($amount =~ m/[e]/) ? 1 : 0;
1019
1020   if (defined($places) && ($places ne '')) {
1021     if (not $exp) {
1022       if ($places < 0) {
1023         $amount *= 1;
1024         $places *= -1;
1025
1026         my ($actual_places) = ($amount =~ /\.(\d+)/);
1027         $actual_places = length($actual_places);
1028         $places = $actual_places > $places ? $actual_places : $places;
1029       }
1030     }
1031     $amount = $self->round_amount($amount, $places);
1032   }
1033
1034   my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
1035   my @p = split(/\./, $amount); # split amount at decimal point
1036
1037   $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
1038
1039   $amount = $p[0];
1040   $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
1041
1042   $amount = do {
1043     ($dash =~ /-/)    ? ($neg ? "($amount)"                            : "$amount" )                              :
1044     ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
1045                         ($neg ? "-$amount"                             : "$amount" )                              ;
1046   };
1047
1048
1049   $main::lxdebug->leave_sub(2);
1050   return $amount;
1051 }
1052
1053 sub format_amount_units {
1054   $main::lxdebug->enter_sub();
1055
1056   my $self             = shift;
1057   my %params           = @_;
1058
1059   my $myconfig         = \%main::myconfig;
1060   my $amount           = $params{amount} * 1;
1061   my $places           = $params{places};
1062   my $part_unit_name   = $params{part_unit};
1063   my $amount_unit_name = $params{amount_unit};
1064   my $conv_units       = $params{conv_units};
1065   my $max_places       = $params{max_places};
1066
1067   if (!$part_unit_name) {
1068     $main::lxdebug->leave_sub();
1069     return '';
1070   }
1071
1072   AM->retrieve_all_units();
1073   my $all_units        = $main::all_units;
1074
1075   if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
1076     $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
1077   }
1078
1079   if (!scalar @{ $conv_units }) {
1080     my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
1081     $main::lxdebug->leave_sub();
1082     return $result;
1083   }
1084
1085   my $part_unit  = $all_units->{$part_unit_name};
1086   my $conv_unit  = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
1087
1088   $amount       *= $conv_unit->{factor};
1089
1090   my @values;
1091   my $num;
1092
1093   foreach my $unit (@$conv_units) {
1094     my $last = $unit->{name} eq $part_unit->{name};
1095     if (!$last) {
1096       $num     = int($amount / $unit->{factor});
1097       $amount -= $num * $unit->{factor};
1098     }
1099
1100     if ($last ? $amount : $num) {
1101       push @values, { "unit"   => $unit->{name},
1102                       "amount" => $last ? $amount / $unit->{factor} : $num,
1103                       "places" => $last ? $places : 0 };
1104     }
1105
1106     last if $last;
1107   }
1108
1109   if (!@values) {
1110     push @values, { "unit"   => $part_unit_name,
1111                     "amount" => 0,
1112                     "places" => 0 };
1113   }
1114
1115   my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
1116
1117   $main::lxdebug->leave_sub();
1118
1119   return $result;
1120 }
1121
1122 sub format_string {
1123   $main::lxdebug->enter_sub(2);
1124
1125   my $self  = shift;
1126   my $input = shift;
1127
1128   $input =~ s/(^|[^\#]) \#  (\d+)  /$1$_[$2 - 1]/gx;
1129   $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
1130   $input =~ s/\#\#/\#/g;
1131
1132   $main::lxdebug->leave_sub(2);
1133
1134   return $input;
1135 }
1136
1137 #
1138
1139 sub parse_amount {
1140   $main::lxdebug->enter_sub(2);
1141
1142   my ($self, $myconfig, $amount) = @_;
1143
1144   if (   ($myconfig->{numberformat} eq '1.000,00')
1145       || ($myconfig->{numberformat} eq '1000,00')) {
1146     $amount =~ s/\.//g;
1147     $amount =~ s/,/\./;
1148   }
1149
1150   if ($myconfig->{numberformat} eq "1'000.00") {
1151     $amount =~ s/\'//g;
1152   }
1153
1154   $amount =~ s/,//g;
1155
1156   $main::lxdebug->leave_sub(2);
1157
1158   return ($amount * 1);
1159 }
1160
1161 sub round_amount {
1162   $main::lxdebug->enter_sub(2);
1163
1164   my ($self, $amount, $places) = @_;
1165   my $round_amount;
1166
1167   # Rounding like "Kaufmannsrunden"
1168   # Descr. http://de.wikipedia.org/wiki/Rundung
1169   # Inspired by
1170   # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
1171   # Solves Bug: 189
1172   # Udo Spallek
1173   $amount = $amount * (10**($places));
1174   $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
1175
1176   $main::lxdebug->leave_sub(2);
1177
1178   return $round_amount;
1179
1180 }
1181
1182 sub parse_template {
1183   $main::lxdebug->enter_sub();
1184
1185   my ($self, $myconfig, $userspath) = @_;
1186   my ($template, $out);
1187
1188   local (*IN, *OUT);
1189
1190   $self->{"cwd"} = getcwd();
1191   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
1192
1193   my $ext_for_format;
1194
1195   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
1196     $template       = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1197     $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
1198
1199   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
1200     $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
1201     $template         = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1202     $ext_for_format   = 'pdf';
1203
1204   } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
1205     $template       = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1206     $ext_for_format = 'html';
1207
1208   } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
1209     $template       = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1210     $ext_for_format = 'xml';
1211
1212   } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
1213     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1214
1215   } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
1216     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1217
1218   } elsif ( defined $self->{'format'}) {
1219     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
1220
1221   } elsif ( $self->{'format'} eq '' ) {
1222     $self->error("No Outputformat given: $self->{'format'}");
1223
1224   } else { #Catch the rest
1225     $self->error("Outputformat not defined: $self->{'format'}");
1226   }
1227
1228   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
1229   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
1230
1231   if (!$self->{employee_id}) {
1232     map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
1233   }
1234
1235   map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
1236
1237   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
1238
1239   # OUT is used for the media, screen, printer, email
1240   # for postscript we store a copy in a temporary file
1241   my $fileid = time;
1242   my $prepend_userspath;
1243
1244   if (!$self->{tmpfile}) {
1245     $self->{tmpfile}   = "${fileid}.$self->{IN}";
1246     $prepend_userspath = 1;
1247   }
1248
1249   $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
1250
1251   $self->{tmpfile} =~ s|.*/||;
1252   $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
1253   $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
1254
1255   if ($template->uses_temp_file() || $self->{media} eq 'email') {
1256     $out = $self->{OUT};
1257     $self->{OUT} = ">$self->{tmpfile}";
1258   }
1259
1260   if ($self->{OUT}) {
1261     open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
1262   } else {
1263     open(OUT, ">-") or $self->error("STDOUT : $!");
1264     $self->header;
1265   }
1266
1267   if (!$template->parse(*OUT)) {
1268     $self->cleanup();
1269     $self->error("$self->{IN} : " . $template->get_error());
1270   }
1271
1272   close(OUT);
1273
1274   if ($template->uses_temp_file() || $self->{media} eq 'email') {
1275
1276     if ($self->{media} eq 'email') {
1277
1278       my $mail = new Mailer;
1279
1280       map { $mail->{$_} = $self->{$_} }
1281         qw(cc bcc subject message version format);
1282       $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
1283       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1284       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1285       $mail->{fileid} = "$fileid.";
1286       $myconfig->{signature} =~ s/\r//g;
1287
1288       # if we send html or plain text inline
1289       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1290         $mail->{contenttype} = "text/html";
1291
1292         $mail->{message}       =~ s/\r//g;
1293         $mail->{message}       =~ s/\n/<br>\n/g;
1294         $myconfig->{signature} =~ s/\n/<br>\n/g;
1295         $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
1296
1297         open(IN, $self->{tmpfile})
1298           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1299         while (<IN>) {
1300           $mail->{message} .= $_;
1301         }
1302
1303         close(IN);
1304
1305       } else {
1306
1307         if (!$self->{"do_not_attach"}) {
1308           my $attachment_name  =  $self->{attachment_filename} || $self->{tmpfile};
1309           $attachment_name     =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
1310           $mail->{attachments} =  [{ "filename" => $self->{tmpfile},
1311                                      "name"     => $attachment_name }];
1312         }
1313
1314         $mail->{message}  =~ s/\r//g;
1315         $mail->{message} .=  "\n-- \n$myconfig->{signature}";
1316
1317       }
1318
1319       my $err = $mail->send();
1320       $self->error($self->cleanup . "$err") if ($err);
1321
1322     } else {
1323
1324       $self->{OUT} = $out;
1325
1326       my $numbytes = (-s $self->{tmpfile});
1327       open(IN, $self->{tmpfile})
1328         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1329
1330       $self->{copies} = 1 unless $self->{media} eq 'printer';
1331
1332       chdir("$self->{cwd}");
1333       #print(STDERR "Kopien $self->{copies}\n");
1334       #print(STDERR "OUT $self->{OUT}\n");
1335       for my $i (1 .. $self->{copies}) {
1336         if ($self->{OUT}) {
1337           open(OUT, $self->{OUT})
1338             or $self->error($self->cleanup . "$self->{OUT} : $!");
1339         } else {
1340           $self->{attachment_filename} = ($self->{attachment_filename})
1341                                        ? $self->{attachment_filename}
1342                                        : $self->generate_attachment_filename();
1343
1344           # launch application
1345           print qq|Content-Type: | . $template->get_mime_type() . qq|
1346 Content-Disposition: attachment; filename="$self->{attachment_filename}"
1347 Content-Length: $numbytes
1348
1349 |;
1350
1351           open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
1352
1353         }
1354
1355         while (<IN>) {
1356           print OUT $_;
1357         }
1358
1359         close(OUT);
1360
1361         seek IN, 0, 0;
1362       }
1363
1364       close(IN);
1365     }
1366
1367   }
1368
1369   $self->cleanup;
1370
1371   chdir("$self->{cwd}");
1372   $main::lxdebug->leave_sub();
1373 }
1374
1375 sub get_formname_translation {
1376   $main::lxdebug->enter_sub();
1377   my ($self, $formname) = @_;
1378
1379   $formname ||= $self->{formname};
1380
1381   my %formname_translations = (
1382     bin_list                => $main::locale->text('Bin List'),
1383     credit_note             => $main::locale->text('Credit Note'),
1384     invoice                 => $main::locale->text('Invoice'),
1385     packing_list            => $main::locale->text('Packing List'),
1386     pick_list               => $main::locale->text('Pick List'),
1387     proforma                => $main::locale->text('Proforma Invoice'),
1388     purchase_order          => $main::locale->text('Purchase Order'),
1389     request_quotation       => $main::locale->text('RFQ'),
1390     sales_order             => $main::locale->text('Confirmation'),
1391     sales_quotation         => $main::locale->text('Quotation'),
1392     storno_invoice          => $main::locale->text('Storno Invoice'),
1393     storno_packing_list     => $main::locale->text('Storno Packing List'),
1394     sales_delivery_order    => $main::locale->text('Delivery Order'),
1395     purchase_delivery_order => $main::locale->text('Delivery Order'),
1396   );
1397
1398   $main::lxdebug->leave_sub();
1399   return $formname_translations{$formname}
1400 }
1401
1402 sub get_number_prefix_for_type {
1403   $main::lxdebug->enter_sub();
1404   my ($self) = @_;
1405
1406   my $prefix =
1407       (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1408     : ($self->{type} =~ /_quotation$/)                        ? 'quo'
1409     : ($self->{type} =~ /_delivery_order$/)                   ? 'do'
1410     :                                                           'ord';
1411
1412   $main::lxdebug->leave_sub();
1413   return $prefix;
1414 }
1415
1416 sub get_extension_for_format {
1417   $main::lxdebug->enter_sub();
1418   my ($self)    = @_;
1419
1420   my $extension = $self->{format} =~ /pdf/i          ? ".pdf"
1421                 : $self->{format} =~ /postscript/i   ? ".ps"
1422                 : $self->{format} =~ /opendocument/i ? ".odt"
1423                 : $self->{format} =~ /html/i         ? ".html"
1424                 :                                      "";
1425
1426   $main::lxdebug->leave_sub();
1427   return $extension;
1428 }
1429
1430 sub generate_attachment_filename {
1431   $main::lxdebug->enter_sub();
1432   my ($self) = @_;
1433
1434   my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1435   my $prefix              = $self->get_number_prefix_for_type();
1436
1437   if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1438     $attachment_filename .= ' (' . $main::locale->text('Preview') . ')' . $self->get_extension_for_format();
1439
1440   } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1441     $attachment_filename .=  "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1442
1443   } else {
1444     $attachment_filename = "";
1445   }
1446
1447   $attachment_filename =  $main::locale->quote_special_chars('filenames', $attachment_filename);
1448   $attachment_filename =~ s|[\s/\\]+|_|g;
1449
1450   $main::lxdebug->leave_sub();
1451   return $attachment_filename;
1452 }
1453
1454 sub generate_email_subject {
1455   $main::lxdebug->enter_sub();
1456   my ($self) = @_;
1457
1458   my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1459   my $prefix  = $self->get_number_prefix_for_type();
1460
1461   if ($subject && $self->{"${prefix}number"}) {
1462     $subject .= " " . $self->{"${prefix}number"}
1463   }
1464
1465   $main::lxdebug->leave_sub();
1466   return $subject;
1467 }
1468
1469 sub cleanup {
1470   $main::lxdebug->enter_sub();
1471
1472   my $self = shift;
1473
1474   chdir("$self->{tmpdir}");
1475
1476   my @err = ();
1477   if (-f "$self->{tmpfile}.err") {
1478     open(FH, "$self->{tmpfile}.err");
1479     @err = <FH>;
1480     close(FH);
1481   }
1482
1483   if ($self->{tmpfile}) {
1484     $self->{tmpfile} =~ s|.*/||g;
1485     # strip extension
1486     $self->{tmpfile} =~ s/\.\w+$//g;
1487     my $tmpfile = $self->{tmpfile};
1488     unlink(<$tmpfile.*>);
1489   }
1490
1491   chdir("$self->{cwd}");
1492
1493   $main::lxdebug->leave_sub();
1494
1495   return "@err";
1496 }
1497
1498 sub datetonum {
1499   $main::lxdebug->enter_sub();
1500
1501   my ($self, $date, $myconfig) = @_;
1502   my ($yy, $mm, $dd);
1503
1504   if ($date && $date =~ /\D/) {
1505
1506     if ($myconfig->{dateformat} =~ /^yy/) {
1507       ($yy, $mm, $dd) = split /\D/, $date;
1508     }
1509     if ($myconfig->{dateformat} =~ /^mm/) {
1510       ($mm, $dd, $yy) = split /\D/, $date;
1511     }
1512     if ($myconfig->{dateformat} =~ /^dd/) {
1513       ($dd, $mm, $yy) = split /\D/, $date;
1514     }
1515
1516     $dd *= 1;
1517     $mm *= 1;
1518     $yy = ($yy < 70) ? $yy + 2000 : $yy;
1519     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1520
1521     $dd = "0$dd" if ($dd < 10);
1522     $mm = "0$mm" if ($mm < 10);
1523
1524     $date = "$yy$mm$dd";
1525   }
1526
1527   $main::lxdebug->leave_sub();
1528
1529   return $date;
1530 }
1531
1532 # Database routines used throughout
1533
1534 sub dbconnect {
1535   $main::lxdebug->enter_sub(2);
1536
1537   my ($self, $myconfig) = @_;
1538
1539   # connect to database
1540   my $dbh =
1541     DBI->connect($myconfig->{dbconnect},
1542                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
1543     or $self->dberror;
1544
1545   # set db options
1546   if ($myconfig->{dboptions}) {
1547     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1548   }
1549
1550   $main::lxdebug->leave_sub(2);
1551
1552   return $dbh;
1553 }
1554
1555 sub dbconnect_noauto {
1556   $main::lxdebug->enter_sub();
1557
1558   my ($self, $myconfig) = @_;
1559
1560   # connect to database
1561   my $dbh =
1562     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1563                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
1564     or $self->dberror;
1565
1566   # set db options
1567   if ($myconfig->{dboptions}) {
1568     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1569   }
1570
1571   $main::lxdebug->leave_sub();
1572
1573   return $dbh;
1574 }
1575
1576 sub get_standard_dbh {
1577   $main::lxdebug->enter_sub(2);
1578
1579   my ($self, $myconfig) = @_;
1580
1581   if ($standard_dbh && !$standard_dbh->{Active}) {
1582     $main::lxdebug->message(LXDebug::INFO, "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
1583     undef $standard_dbh;
1584   }
1585
1586   $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1587
1588   $main::lxdebug->leave_sub(2);
1589
1590   return $standard_dbh;
1591 }
1592
1593 sub date_closed {
1594   $main::lxdebug->enter_sub();
1595
1596   my ($self, $date, $myconfig) = @_;
1597   my $dbh = $self->dbconnect($myconfig);
1598
1599   my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1600   my $sth = prepare_execute_query($self, $dbh, $query, $date);
1601   my ($closed) = $sth->fetchrow_array;
1602
1603   $main::lxdebug->leave_sub();
1604
1605   return $closed;
1606 }
1607
1608 sub update_balance {
1609   $main::lxdebug->enter_sub();
1610
1611   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1612
1613   # if we have a value, go do it
1614   if ($value != 0) {
1615
1616     # retrieve balance from table
1617     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1618     my $sth = prepare_execute_query($self, $dbh, $query, @values);
1619     my ($balance) = $sth->fetchrow_array;
1620     $sth->finish;
1621
1622     $balance += $value;
1623
1624     # update balance
1625     $query = "UPDATE $table SET $field = $balance WHERE $where";
1626     do_query($self, $dbh, $query, @values);
1627   }
1628   $main::lxdebug->leave_sub();
1629 }
1630
1631 sub update_exchangerate {
1632   $main::lxdebug->enter_sub();
1633
1634   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1635   my ($query);
1636   # some sanity check for currency
1637   if ($curr eq '') {
1638     $main::lxdebug->leave_sub();
1639     return;
1640   }
1641   $query = qq|SELECT curr FROM defaults|;
1642
1643   my ($currency) = selectrow_query($self, $dbh, $query);
1644   my ($defaultcurrency) = split m/:/, $currency;
1645
1646
1647   if ($curr eq $defaultcurrency) {
1648     $main::lxdebug->leave_sub();
1649     return;
1650   }
1651
1652   $query = qq|SELECT e.curr FROM exchangerate e
1653                  WHERE e.curr = ? AND e.transdate = ?
1654                  FOR UPDATE|;
1655   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1656
1657   if ($buy == 0) {
1658     $buy = "";
1659   }
1660   if ($sell == 0) {
1661     $sell = "";
1662   }
1663
1664   $buy = conv_i($buy, "NULL");
1665   $sell = conv_i($sell, "NULL");
1666
1667   my $set;
1668   if ($buy != 0 && $sell != 0) {
1669     $set = "buy = $buy, sell = $sell";
1670   } elsif ($buy != 0) {
1671     $set = "buy = $buy";
1672   } elsif ($sell != 0) {
1673     $set = "sell = $sell";
1674   }
1675
1676   if ($sth->fetchrow_array) {
1677     $query = qq|UPDATE exchangerate
1678                 SET $set
1679                 WHERE curr = ?
1680                 AND transdate = ?|;
1681
1682   } else {
1683     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1684                 VALUES (?, $buy, $sell, ?)|;
1685   }
1686   $sth->finish;
1687   do_query($self, $dbh, $query, $curr, $transdate);
1688
1689   $main::lxdebug->leave_sub();
1690 }
1691
1692 sub save_exchangerate {
1693   $main::lxdebug->enter_sub();
1694
1695   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1696
1697   my $dbh = $self->dbconnect($myconfig);
1698
1699   my ($buy, $sell);
1700
1701   $buy  = $rate if $fld eq 'buy';
1702   $sell = $rate if $fld eq 'sell';
1703
1704
1705   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1706
1707
1708   $dbh->disconnect;
1709
1710   $main::lxdebug->leave_sub();
1711 }
1712
1713 sub get_exchangerate {
1714   $main::lxdebug->enter_sub();
1715
1716   my ($self, $dbh, $curr, $transdate, $fld) = @_;
1717   my ($query);
1718
1719   unless ($transdate) {
1720     $main::lxdebug->leave_sub();
1721     return 1;
1722   }
1723
1724   $query = qq|SELECT curr FROM defaults|;
1725
1726   my ($currency) = selectrow_query($self, $dbh, $query);
1727   my ($defaultcurrency) = split m/:/, $currency;
1728
1729   if ($currency eq $defaultcurrency) {
1730     $main::lxdebug->leave_sub();
1731     return 1;
1732   }
1733
1734   $query = qq|SELECT e.$fld FROM exchangerate e
1735                  WHERE e.curr = ? AND e.transdate = ?|;
1736   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1737
1738
1739
1740   $main::lxdebug->leave_sub();
1741
1742   return $exchangerate;
1743 }
1744
1745 sub check_exchangerate {
1746   $main::lxdebug->enter_sub();
1747
1748   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1749
1750   if ($fld !~/^buy|sell$/) {
1751     $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1752   }
1753
1754   unless ($transdate) {
1755     $main::lxdebug->leave_sub();
1756     return "";
1757   }
1758
1759   my ($defaultcurrency) = $self->get_default_currency($myconfig);
1760
1761   if ($currency eq $defaultcurrency) {
1762     $main::lxdebug->leave_sub();
1763     return 1;
1764   }
1765
1766   my $dbh   = $self->get_standard_dbh($myconfig);
1767   my $query = qq|SELECT e.$fld FROM exchangerate e
1768                  WHERE e.curr = ? AND e.transdate = ?|;
1769
1770   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1771
1772   $main::lxdebug->leave_sub();
1773
1774   return $exchangerate;
1775 }
1776
1777 sub get_default_currency {
1778   $main::lxdebug->enter_sub();
1779
1780   my ($self, $myconfig) = @_;
1781   my $dbh = $self->get_standard_dbh($myconfig);
1782
1783   my $query = qq|SELECT curr FROM defaults|;
1784
1785   my ($curr)            = selectrow_query($self, $dbh, $query);
1786   my ($defaultcurrency) = split m/:/, $curr;
1787
1788   $main::lxdebug->leave_sub();
1789
1790   return $defaultcurrency;
1791 }
1792
1793
1794 sub set_payment_options {
1795   $main::lxdebug->enter_sub();
1796
1797   my ($self, $myconfig, $transdate) = @_;
1798
1799   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1800
1801   my $dbh = $self->get_standard_dbh($myconfig);
1802
1803   my $query =
1804     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1805     qq|FROM payment_terms p | .
1806     qq|WHERE p.id = ?|;
1807
1808   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1809    $self->{payment_terms}) =
1810      selectrow_query($self, $dbh, $query, $self->{payment_id});
1811
1812   if ($transdate eq "") {
1813     if ($self->{invdate}) {
1814       $transdate = $self->{invdate};
1815     } else {
1816       $transdate = $self->{transdate};
1817     }
1818   }
1819
1820   $query =
1821     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1822     qq|FROM payment_terms|;
1823   ($self->{netto_date}, $self->{skonto_date}) =
1824     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1825
1826   my ($invtotal, $total);
1827   my (%amounts, %formatted_amounts);
1828
1829   if ($self->{type} =~ /_order$/) {
1830     $amounts{invtotal} = $self->{ordtotal};
1831     $amounts{total}    = $self->{ordtotal};
1832
1833   } elsif ($self->{type} =~ /_quotation$/) {
1834     $amounts{invtotal} = $self->{quototal};
1835     $amounts{total}    = $self->{quototal};
1836
1837   } else {
1838     $amounts{invtotal} = $self->{invtotal};
1839     $amounts{total}    = $self->{total};
1840   }
1841
1842   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1843
1844   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
1845   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1846   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
1847
1848   foreach (keys %amounts) {
1849     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
1850     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1851   }
1852
1853   if ($self->{"language_id"}) {
1854     $query =
1855       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1856       qq|FROM translation_payment_terms t | .
1857       qq|LEFT JOIN language l ON t.language_id = l.id | .
1858       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1859     my ($description_long, $output_numberformat, $output_dateformat,
1860       $output_longdates) =
1861       selectrow_query($self, $dbh, $query,
1862                       $self->{"language_id"}, $self->{"payment_id"});
1863
1864     $self->{payment_terms} = $description_long if ($description_long);
1865
1866     if ($output_dateformat) {
1867       foreach my $key (qw(netto_date skonto_date)) {
1868         $self->{$key} =
1869           $main::locale->reformat_date($myconfig, $self->{$key},
1870                                        $output_dateformat,
1871                                        $output_longdates);
1872       }
1873     }
1874
1875     if ($output_numberformat &&
1876         ($output_numberformat ne $myconfig->{"numberformat"})) {
1877       my $saved_numberformat = $myconfig->{"numberformat"};
1878       $myconfig->{"numberformat"} = $output_numberformat;
1879       map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1880       $myconfig->{"numberformat"} = $saved_numberformat;
1881     }
1882   }
1883
1884   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1885   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1886   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1887   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1888   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1889   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1890   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1891
1892   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1893
1894   $main::lxdebug->leave_sub();
1895
1896 }
1897
1898 sub get_template_language {
1899   $main::lxdebug->enter_sub();
1900
1901   my ($self, $myconfig) = @_;
1902
1903   my $template_code = "";
1904
1905   if ($self->{language_id}) {
1906     my $dbh = $self->get_standard_dbh($myconfig);
1907     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1908     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1909   }
1910
1911   $main::lxdebug->leave_sub();
1912
1913   return $template_code;
1914 }
1915
1916 sub get_printer_code {
1917   $main::lxdebug->enter_sub();
1918
1919   my ($self, $myconfig) = @_;
1920
1921   my $template_code = "";
1922
1923   if ($self->{printer_id}) {
1924     my $dbh = $self->get_standard_dbh($myconfig);
1925     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1926     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1927   }
1928
1929   $main::lxdebug->leave_sub();
1930
1931   return $template_code;
1932 }
1933
1934 sub get_shipto {
1935   $main::lxdebug->enter_sub();
1936
1937   my ($self, $myconfig) = @_;
1938
1939   my $template_code = "";
1940
1941   if ($self->{shipto_id}) {
1942     my $dbh = $self->get_standard_dbh($myconfig);
1943     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1944     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1945     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1946   }
1947
1948   $main::lxdebug->leave_sub();
1949 }
1950
1951 sub add_shipto {
1952   $main::lxdebug->enter_sub();
1953
1954   my ($self, $dbh, $id, $module) = @_;
1955
1956   my $shipto;
1957   my @values;
1958
1959   foreach my $item (qw(name department_1 department_2 street zipcode city country
1960                        contact phone fax email)) {
1961     if ($self->{"shipto$item"}) {
1962       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1963     }
1964     push(@values, $self->{"shipto${item}"});
1965   }
1966
1967   if ($shipto) {
1968     if ($self->{shipto_id}) {
1969       my $query = qq|UPDATE shipto set
1970                        shiptoname = ?,
1971                        shiptodepartment_1 = ?,
1972                        shiptodepartment_2 = ?,
1973                        shiptostreet = ?,
1974                        shiptozipcode = ?,
1975                        shiptocity = ?,
1976                        shiptocountry = ?,
1977                        shiptocontact = ?,
1978                        shiptophone = ?,
1979                        shiptofax = ?,
1980                        shiptoemail = ?
1981                      WHERE shipto_id = ?|;
1982       do_query($self, $dbh, $query, @values, $self->{shipto_id});
1983     } else {
1984       my $query = qq|SELECT * FROM shipto
1985                      WHERE shiptoname = ? AND
1986                        shiptodepartment_1 = ? AND
1987                        shiptodepartment_2 = ? AND
1988                        shiptostreet = ? AND
1989                        shiptozipcode = ? AND
1990                        shiptocity = ? AND
1991                        shiptocountry = ? AND
1992                        shiptocontact = ? AND
1993                        shiptophone = ? AND
1994                        shiptofax = ? AND
1995                        shiptoemail = ? AND
1996                        module = ? AND
1997                        trans_id = ?|;
1998       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1999       if(!$insert_check){
2000         $query =
2001           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
2002                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
2003                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
2004              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
2005         do_query($self, $dbh, $query, $id, @values, $module);
2006       }
2007     }
2008   }
2009
2010   $main::lxdebug->leave_sub();
2011 }
2012
2013 sub get_employee {
2014   $main::lxdebug->enter_sub();
2015
2016   my ($self, $dbh) = @_;
2017
2018   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
2019   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
2020   $self->{"employee_id"} *= 1;
2021
2022   $main::lxdebug->leave_sub();
2023 }
2024
2025 sub get_employee_data {
2026   $main::lxdebug->enter_sub();
2027
2028   my $self     = shift;
2029   my %params   = @_;
2030
2031   Common::check_params(\%params, qw(prefix));
2032   Common::check_params_x(\%params, qw(id));
2033
2034   if (!$params{id}) {
2035     $main::lxdebug->leave_sub();
2036     return;
2037   }
2038
2039   my $myconfig = \%main::myconfig;
2040   my $dbh      = $params{dbh} || $self->get_standard_dbh($myconfig);
2041
2042   my ($login)  = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
2043
2044   if ($login) {
2045     my $user = User->new($login);
2046     map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
2047
2048     $self->{$params{prefix} . '_login'}   = $login;
2049     $self->{$params{prefix} . '_name'}  ||= $login;
2050   }
2051
2052   $main::lxdebug->leave_sub();
2053 }
2054
2055 sub get_duedate {
2056   $main::lxdebug->enter_sub();
2057
2058   my ($self, $myconfig, $reference_date) = @_;
2059
2060   my $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
2061
2062   my $dbh            = $self->get_standard_dbh($myconfig);
2063   my $query          = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
2064   my ($duedate)      = selectrow_query($self, $dbh, $query, $self->{payment_id});
2065
2066   $main::lxdebug->leave_sub();
2067
2068   return $duedate;
2069 }
2070
2071 sub _get_contacts {
2072   $main::lxdebug->enter_sub();
2073
2074   my ($self, $dbh, $id, $key) = @_;
2075
2076   $key = "all_contacts" unless ($key);
2077
2078   if (!$id) {
2079     $self->{$key} = [];
2080     $main::lxdebug->leave_sub();
2081     return;
2082   }
2083
2084   my $query =
2085     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
2086     qq|FROM contacts | .
2087     qq|WHERE cp_cv_id = ? | .
2088     qq|ORDER BY lower(cp_name)|;
2089
2090   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
2091
2092   $main::lxdebug->leave_sub();
2093 }
2094
2095 sub _get_projects {
2096   $main::lxdebug->enter_sub();
2097
2098   my ($self, $dbh, $key) = @_;
2099
2100   my ($all, $old_id, $where, @values);
2101
2102   if (ref($key) eq "HASH") {
2103     my $params = $key;
2104
2105     $key = "ALL_PROJECTS";
2106
2107     foreach my $p (keys(%{$params})) {
2108       if ($p eq "all") {
2109         $all = $params->{$p};
2110       } elsif ($p eq "old_id") {
2111         $old_id = $params->{$p};
2112       } elsif ($p eq "key") {
2113         $key = $params->{$p};
2114       }
2115     }
2116   }
2117
2118   if (!$all) {
2119     $where = "WHERE active ";
2120     if ($old_id) {
2121       if (ref($old_id) eq "ARRAY") {
2122         my @ids = grep({ $_ } @{$old_id});
2123         if (@ids) {
2124           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
2125           push(@values, @ids);
2126         }
2127       } else {
2128         $where .= " OR (id = ?) ";
2129         push(@values, $old_id);
2130       }
2131     }
2132   }
2133
2134   my $query =
2135     qq|SELECT id, projectnumber, description, active | .
2136     qq|FROM project | .
2137     $where .
2138     qq|ORDER BY lower(projectnumber)|;
2139
2140   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2141
2142   $main::lxdebug->leave_sub();
2143 }
2144
2145 sub _get_shipto {
2146   $main::lxdebug->enter_sub();
2147
2148   my ($self, $dbh, $vc_id, $key) = @_;
2149
2150   $key = "all_shipto" unless ($key);
2151
2152   if ($vc_id) {
2153     # get shipping addresses
2154     my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2155
2156     $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2157
2158   } else {
2159     $self->{$key} = [];
2160   }
2161
2162   $main::lxdebug->leave_sub();
2163 }
2164
2165 sub _get_printers {
2166   $main::lxdebug->enter_sub();
2167
2168   my ($self, $dbh, $key) = @_;
2169
2170   $key = "all_printers" unless ($key);
2171
2172   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2173
2174   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2175
2176   $main::lxdebug->leave_sub();
2177 }
2178
2179 sub _get_charts {
2180   $main::lxdebug->enter_sub();
2181
2182   my ($self, $dbh, $params) = @_;
2183   my ($key);
2184
2185   $key = $params->{key};
2186   $key = "all_charts" unless ($key);
2187
2188   my $transdate = quote_db_date($params->{transdate});
2189
2190   my $query =
2191     qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
2192     qq|FROM chart c | .
2193     qq|LEFT JOIN taxkeys tk ON | .
2194     qq|(tk.id = (SELECT id FROM taxkeys | .
2195     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2196     qq|          ORDER BY startdate DESC LIMIT 1)) | .
2197     qq|ORDER BY c.accno|;
2198
2199   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2200
2201   $main::lxdebug->leave_sub();
2202 }
2203
2204 sub _get_taxcharts {
2205   $main::lxdebug->enter_sub();
2206
2207   my ($self, $dbh, $params) = @_;
2208
2209   my $key = "all_taxcharts";
2210   my @where;
2211
2212   if (ref $params eq 'HASH') {
2213     $key = $params->{key} if ($params->{key});
2214     if ($params->{module} eq 'AR') {
2215       push @where, 'taxkey NOT IN (8, 9, 18, 19)';
2216
2217     } elsif ($params->{module} eq 'AP') {
2218       push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
2219     }
2220
2221   } elsif ($params) {
2222     $key = $params;
2223   }
2224
2225   my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
2226
2227   my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
2228
2229   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2230
2231   $main::lxdebug->leave_sub();
2232 }
2233
2234 sub _get_taxzones {
2235   $main::lxdebug->enter_sub();
2236
2237   my ($self, $dbh, $key) = @_;
2238
2239   $key = "all_taxzones" unless ($key);
2240
2241   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
2242
2243   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2244
2245   $main::lxdebug->leave_sub();
2246 }
2247
2248 sub _get_employees {
2249   $main::lxdebug->enter_sub();
2250
2251   my ($self, $dbh, $default_key, $key) = @_;
2252
2253   $key = $default_key unless ($key);
2254   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
2255
2256   $main::lxdebug->leave_sub();
2257 }
2258
2259 sub _get_business_types {
2260   $main::lxdebug->enter_sub();
2261
2262   my ($self, $dbh, $key) = @_;
2263
2264   $key = "all_business_types" unless ($key);
2265   $self->{$key} =
2266     selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
2267
2268   $main::lxdebug->leave_sub();
2269 }
2270
2271 sub _get_languages {
2272   $main::lxdebug->enter_sub();
2273
2274   my ($self, $dbh, $key) = @_;
2275
2276   $key = "all_languages" unless ($key);
2277
2278   my $query = qq|SELECT * FROM language ORDER BY id|;
2279
2280   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2281
2282   $main::lxdebug->leave_sub();
2283 }
2284
2285 sub _get_dunning_configs {
2286   $main::lxdebug->enter_sub();
2287
2288   my ($self, $dbh, $key) = @_;
2289
2290   $key = "all_dunning_configs" unless ($key);
2291
2292   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2293
2294   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2295
2296   $main::lxdebug->leave_sub();
2297 }
2298
2299 sub _get_currencies {
2300 $main::lxdebug->enter_sub();
2301
2302   my ($self, $dbh, $key) = @_;
2303
2304   $key = "all_currencies" unless ($key);
2305
2306   my $query = qq|SELECT curr AS currency FROM defaults|;
2307
2308   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2309
2310   $main::lxdebug->leave_sub();
2311 }
2312
2313 sub _get_payments {
2314 $main::lxdebug->enter_sub();
2315
2316   my ($self, $dbh, $key) = @_;
2317
2318   $key = "all_payments" unless ($key);
2319
2320   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
2321
2322   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2323
2324   $main::lxdebug->leave_sub();
2325 }
2326
2327 sub _get_customers {
2328   $main::lxdebug->enter_sub();
2329
2330   my ($self, $dbh, $key, $limit) = @_;
2331
2332   $key = "all_customers" unless ($key);
2333   my $limit_clause = "LIMIT $limit" if $limit;
2334
2335   my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name $limit_clause|;
2336
2337   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2338
2339   $main::lxdebug->leave_sub();
2340 }
2341
2342 sub _get_vendors {
2343   $main::lxdebug->enter_sub();
2344
2345   my ($self, $dbh, $key) = @_;
2346
2347   $key = "all_vendors" unless ($key);
2348
2349   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2350
2351   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2352
2353   $main::lxdebug->leave_sub();
2354 }
2355
2356 sub _get_departments {
2357   $main::lxdebug->enter_sub();
2358
2359   my ($self, $dbh, $key) = @_;
2360
2361   $key = "all_departments" unless ($key);
2362
2363   my $query = qq|SELECT * FROM department ORDER BY description|;
2364
2365   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2366
2367   $main::lxdebug->leave_sub();
2368 }
2369
2370 sub _get_warehouses {
2371   $main::lxdebug->enter_sub();
2372
2373   my ($self, $dbh, $param) = @_;
2374
2375   my ($key, $bins_key);
2376
2377   if ('' eq ref $param) {
2378     $key = $param;
2379
2380   } else {
2381     $key      = $param->{key};
2382     $bins_key = $param->{bins};
2383   }
2384
2385   my $query = qq|SELECT w.* FROM warehouse w
2386                  WHERE (NOT w.invalid) AND
2387                    ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2388                  ORDER BY w.sortkey|;
2389
2390   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2391
2392   if ($bins_key) {
2393     $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
2394     my $sth = prepare_query($self, $dbh, $query);
2395
2396     foreach my $warehouse (@{ $self->{$key} }) {
2397       do_statement($self, $sth, $query, $warehouse->{id});
2398       $warehouse->{$bins_key} = [];
2399
2400       while (my $ref = $sth->fetchrow_hashref()) {
2401         push @{ $warehouse->{$bins_key} }, $ref;
2402       }
2403     }
2404     $sth->finish();
2405   }
2406
2407   $main::lxdebug->leave_sub();
2408 }
2409
2410 sub _get_simple {
2411   $main::lxdebug->enter_sub();
2412
2413   my ($self, $dbh, $table, $key, $sortkey) = @_;
2414
2415   my $query  = qq|SELECT * FROM $table|;
2416   $query    .= qq| ORDER BY $sortkey| if ($sortkey);
2417
2418   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2419
2420   $main::lxdebug->leave_sub();
2421 }
2422
2423 #sub _get_groups {
2424 #  $main::lxdebug->enter_sub();
2425 #
2426 #  my ($self, $dbh, $key) = @_;
2427 #
2428 #  $key ||= "all_groups";
2429 #
2430 #  my $groups = $main::auth->read_groups();
2431 #
2432 #  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2433 #
2434 #  $main::lxdebug->leave_sub();
2435 #}
2436
2437 sub get_lists {
2438   $main::lxdebug->enter_sub();
2439
2440   my $self = shift;
2441   my %params = @_;
2442
2443   my $dbh = $self->get_standard_dbh(\%main::myconfig);
2444   my ($sth, $query, $ref);
2445
2446   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2447   my $vc_id = $self->{"${vc}_id"};
2448
2449   if ($params{"contacts"}) {
2450     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2451   }
2452
2453   if ($params{"shipto"}) {
2454     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2455   }
2456
2457   if ($params{"projects"} || $params{"all_projects"}) {
2458     $self->_get_projects($dbh, $params{"all_projects"} ?
2459                          $params{"all_projects"} : $params{"projects"},
2460                          $params{"all_projects"} ? 1 : 0);
2461   }
2462
2463   if ($params{"printers"}) {
2464     $self->_get_printers($dbh, $params{"printers"});
2465   }
2466
2467   if ($params{"languages"}) {
2468     $self->_get_languages($dbh, $params{"languages"});
2469   }
2470
2471   if ($params{"charts"}) {
2472     $self->_get_charts($dbh, $params{"charts"});
2473   }
2474
2475   if ($params{"taxcharts"}) {
2476     $self->_get_taxcharts($dbh, $params{"taxcharts"});
2477   }
2478
2479   if ($params{"taxzones"}) {
2480     $self->_get_taxzones($dbh, $params{"taxzones"});
2481   }
2482
2483   if ($params{"employees"}) {
2484     $self->_get_employees($dbh, "all_employees", $params{"employees"});
2485   }
2486
2487   if ($params{"salesmen"}) {
2488     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2489   }
2490
2491   if ($params{"business_types"}) {
2492     $self->_get_business_types($dbh, $params{"business_types"});
2493   }
2494
2495   if ($params{"dunning_configs"}) {
2496     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2497   }
2498
2499   if($params{"currencies"}) {
2500     $self->_get_currencies($dbh, $params{"currencies"});
2501   }
2502
2503   if($params{"customers"}) {
2504     if (ref $params{"customers"} eq 'HASH') {
2505       $self->_get_customers($dbh, $params{"customers"}{key}, $params{"customers"}{limit});
2506     } else {
2507       $self->_get_customers($dbh, $params{"customers"});
2508     }
2509   }
2510
2511   if($params{"vendors"}) {
2512     if (ref $params{"vendors"} eq 'HASH') {
2513       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2514     } else {
2515       $self->_get_vendors($dbh, $params{"vendors"});
2516     }
2517   }
2518
2519   if($params{"payments"}) {
2520     $self->_get_payments($dbh, $params{"payments"});
2521   }
2522
2523   if($params{"departments"}) {
2524     $self->_get_departments($dbh, $params{"departments"});
2525   }
2526
2527   if ($params{price_factors}) {
2528     $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2529   }
2530
2531   if ($params{warehouses}) {
2532     $self->_get_warehouses($dbh, $params{warehouses});
2533   }
2534
2535 #  if ($params{groups}) {
2536 #    $self->_get_groups($dbh, $params{groups});
2537 #  }
2538
2539   if ($params{partsgroup}) {
2540     $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2541   }
2542
2543   $main::lxdebug->leave_sub();
2544 }
2545
2546 # this sub gets the id and name from $table
2547 sub get_name {
2548   $main::lxdebug->enter_sub();
2549
2550   my ($self, $myconfig, $table) = @_;
2551
2552   # connect to database
2553   my $dbh = $self->get_standard_dbh($myconfig);
2554
2555   $table = $table eq "customer" ? "customer" : "vendor";
2556   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2557
2558   my ($query, @values);
2559
2560   if (!$self->{openinvoices}) {
2561     my $where;
2562     if ($self->{customernumber} ne "") {
2563       $where = qq|(vc.customernumber ILIKE ?)|;
2564       push(@values, '%' . $self->{customernumber} . '%');
2565     } else {
2566       $where = qq|(vc.name ILIKE ?)|;
2567       push(@values, '%' . $self->{$table} . '%');
2568     }
2569
2570     $query =
2571       qq~SELECT vc.id, vc.name,
2572            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2573          FROM $table vc
2574          WHERE $where AND (NOT vc.obsolete)
2575          ORDER BY vc.name~;
2576   } else {
2577     $query =
2578       qq~SELECT DISTINCT vc.id, vc.name,
2579            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2580          FROM $arap a
2581          JOIN $table vc ON (a.${table}_id = vc.id)
2582          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2583          ORDER BY vc.name~;
2584     push(@values, '%' . $self->{$table} . '%');
2585   }
2586
2587   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2588
2589   $main::lxdebug->leave_sub();
2590
2591   return scalar(@{ $self->{name_list} });
2592 }
2593
2594 # the selection sub is used in the AR, AP, IS, IR and OE module
2595 #
2596 sub all_vc {
2597   $main::lxdebug->enter_sub();
2598
2599   my ($self, $myconfig, $table, $module) = @_;
2600
2601   my $ref;
2602   my $dbh = $self->get_standard_dbh($myconfig);
2603
2604   $table = $table eq "customer" ? "customer" : "vendor";
2605
2606   my $query = qq|SELECT count(*) FROM $table|;
2607   my ($count) = selectrow_query($self, $dbh, $query);
2608
2609   # build selection list
2610   if ($count < $myconfig->{vclimit}) {
2611     $query = qq|SELECT id, name, salesman_id
2612                 FROM $table WHERE NOT obsolete
2613                 ORDER BY name|;
2614     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2615   }
2616
2617   # get self
2618   $self->get_employee($dbh);
2619
2620   # setup sales contacts
2621   $query = qq|SELECT e.id, e.name
2622               FROM employee e
2623               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2624   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2625
2626   # this is for self
2627   push(@{ $self->{all_employees} },
2628        { id   => $self->{employee_id},
2629          name => $self->{employee} });
2630
2631   # sort the whole thing
2632   @{ $self->{all_employees} } =
2633     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2634
2635   if ($module eq 'AR') {
2636
2637     # prepare query for departments
2638     $query = qq|SELECT id, description
2639                 FROM department
2640                 WHERE role = 'P'
2641                 ORDER BY description|;
2642
2643   } else {
2644     $query = qq|SELECT id, description
2645                 FROM department
2646                 ORDER BY description|;
2647   }
2648
2649   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2650
2651   # get languages
2652   $query = qq|SELECT id, description
2653               FROM language
2654               ORDER BY id|;
2655
2656   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2657
2658   # get printer
2659   $query = qq|SELECT printer_description, id
2660               FROM printers
2661               ORDER BY printer_description|;
2662
2663   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2664
2665   # get payment terms
2666   $query = qq|SELECT id, description
2667               FROM payment_terms
2668               ORDER BY sortkey|;
2669
2670   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2671
2672   $main::lxdebug->leave_sub();
2673 }
2674
2675 sub language_payment {
2676   $main::lxdebug->enter_sub();
2677
2678   my ($self, $myconfig) = @_;
2679
2680   my $dbh = $self->get_standard_dbh($myconfig);
2681   # get languages
2682   my $query = qq|SELECT id, description
2683                  FROM language
2684                  ORDER BY id|;
2685
2686   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2687
2688   # get printer
2689   $query = qq|SELECT printer_description, id
2690               FROM printers
2691               ORDER BY printer_description|;
2692
2693   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2694
2695   # get payment terms
2696   $query = qq|SELECT id, description
2697               FROM payment_terms
2698               ORDER BY sortkey|;
2699
2700   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2701
2702   # get buchungsgruppen
2703   $query = qq|SELECT id, description
2704               FROM buchungsgruppen|;
2705
2706   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2707
2708   $main::lxdebug->leave_sub();
2709 }
2710
2711 # this is only used for reports
2712 sub all_departments {
2713   $main::lxdebug->enter_sub();
2714
2715   my ($self, $myconfig, $table) = @_;
2716
2717   my $dbh = $self->get_standard_dbh($myconfig);
2718   my $where;
2719
2720   if ($table eq 'customer') {
2721     $where = "WHERE role = 'P' ";
2722   }
2723
2724   my $query = qq|SELECT id, description
2725                  FROM department
2726                  $where
2727                  ORDER BY description|;
2728   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2729
2730   delete($self->{all_departments}) unless (@{ $self->{all_departments} });
2731
2732   $main::lxdebug->leave_sub();
2733 }
2734
2735 sub create_links {
2736   $main::lxdebug->enter_sub();
2737
2738   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2739
2740   my ($fld, $arap);
2741   if ($table eq "customer") {
2742     $fld = "buy";
2743     $arap = "ar";
2744   } else {
2745     $table = "vendor";
2746     $fld = "sell";
2747     $arap = "ap";
2748   }
2749
2750   $self->all_vc($myconfig, $table, $module);
2751
2752   # get last customers or vendors
2753   my ($query, $sth, $ref);
2754
2755   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2756   my %xkeyref = ();
2757
2758   if (!$self->{id}) {
2759
2760     my $transdate = "current_date";
2761     if ($self->{transdate}) {
2762       $transdate = $dbh->quote($self->{transdate});
2763     }
2764
2765     # now get the account numbers
2766     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2767                 FROM chart c, taxkeys tk
2768                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2769                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2770                 ORDER BY c.accno|;
2771
2772     $sth = $dbh->prepare($query);
2773
2774     do_statement($self, $sth, $query, '%' . $module . '%');
2775
2776     $self->{accounts} = "";
2777     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2778
2779       foreach my $key (split(/:/, $ref->{link})) {
2780         if ($key =~ /\Q$module\E/) {
2781
2782           # cross reference for keys
2783           $xkeyref{ $ref->{accno} } = $key;
2784
2785           push @{ $self->{"${module}_links"}{$key} },
2786             { accno       => $ref->{accno},
2787               description => $ref->{description},
2788               taxkey      => $ref->{taxkey_id},
2789               tax_id      => $ref->{tax_id} };
2790
2791           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2792         }
2793       }
2794     }
2795   }
2796
2797   # get taxkeys and description
2798   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2799   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2800
2801   if (($module eq "AP") || ($module eq "AR")) {
2802     # get tax rates and description
2803     $query = qq|SELECT * FROM tax|;
2804     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2805   }
2806
2807   if ($self->{id}) {
2808     $query =
2809       qq|SELECT
2810            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2811            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2812            a.intnotes, a.department_id, a.amount AS oldinvtotal,
2813            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2814            c.name AS $table,
2815            d.description AS department,
2816            e.name AS employee
2817          FROM $arap a
2818          JOIN $table c ON (a.${table}_id = c.id)
2819          LEFT JOIN employee e ON (e.id = a.employee_id)
2820          LEFT JOIN department d ON (d.id = a.department_id)
2821          WHERE a.id = ?|;
2822     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2823
2824     foreach my $key (keys %$ref) {
2825       $self->{$key} = $ref->{$key};
2826     }
2827
2828     my $transdate = "current_date";
2829     if ($self->{transdate}) {
2830       $transdate = $dbh->quote($self->{transdate});
2831     }
2832
2833     # now get the account numbers
2834     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2835                 FROM chart c
2836                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2837                 WHERE c.link LIKE ?
2838                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2839                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2840                 ORDER BY c.accno|;
2841
2842     $sth = $dbh->prepare($query);
2843     do_statement($self, $sth, $query, "%$module%");
2844
2845     $self->{accounts} = "";
2846     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2847
2848       foreach my $key (split(/:/, $ref->{link})) {
2849         if ($key =~ /\Q$module\E/) {
2850
2851           # cross reference for keys
2852           $xkeyref{ $ref->{accno} } = $key;
2853
2854           push @{ $self->{"${module}_links"}{$key} },
2855             { accno       => $ref->{accno},
2856               description => $ref->{description},
2857               taxkey      => $ref->{taxkey_id},
2858               tax_id      => $ref->{tax_id} };
2859
2860           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2861         }
2862       }
2863     }
2864
2865
2866     # get amounts from individual entries
2867     $query =
2868       qq|SELECT
2869            c.accno, c.description,
2870            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2871            p.projectnumber,
2872            t.rate, t.id
2873          FROM acc_trans a
2874          LEFT JOIN chart c ON (c.id = a.chart_id)
2875          LEFT JOIN project p ON (p.id = a.project_id)
2876          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2877                                     WHERE (tk.taxkey_id=a.taxkey) AND
2878                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2879                                         THEN tk.chart_id = a.chart_id
2880                                         ELSE 1 = 1
2881                                         END)
2882                                        OR (c.link='%tax%')) AND
2883                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2884          WHERE a.trans_id = ?
2885          AND a.fx_transaction = '0'
2886          ORDER BY a.acc_trans_id, a.transdate|;
2887     $sth = $dbh->prepare($query);
2888     do_statement($self, $sth, $query, $self->{id});
2889
2890     # get exchangerate for currency
2891     $self->{exchangerate} =
2892       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2893     my $index = 0;
2894
2895     # store amounts in {acc_trans}{$key} for multiple accounts
2896     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2897       $ref->{exchangerate} =
2898         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2899       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2900         $index++;
2901       }
2902       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2903         $ref->{amount} *= -1;
2904       }
2905       $ref->{index} = $index;
2906
2907       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2908     }
2909
2910     $sth->finish;
2911     $query =
2912       qq|SELECT
2913            d.curr AS currencies, d.closedto, d.revtrans,
2914            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2915            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2916          FROM defaults d|;
2917     $ref = selectfirst_hashref_query($self, $dbh, $query);
2918     map { $self->{$_} = $ref->{$_} } keys %$ref;
2919
2920   } else {
2921
2922     # get date
2923     $query =
2924        qq|SELECT
2925             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2926             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2927             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2928           FROM defaults d|;
2929     $ref = selectfirst_hashref_query($self, $dbh, $query);
2930     map { $self->{$_} = $ref->{$_} } keys %$ref;
2931
2932     if ($self->{"$self->{vc}_id"}) {
2933
2934       # only setup currency
2935       ($self->{currency}) = split(/:/, $self->{currencies});
2936
2937     } else {
2938
2939       $self->lastname_used($dbh, $myconfig, $table, $module);
2940
2941       # get exchangerate for currency
2942       $self->{exchangerate} =
2943         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2944
2945     }
2946
2947   }
2948
2949   $main::lxdebug->leave_sub();
2950 }
2951
2952 sub lastname_used {
2953   $main::lxdebug->enter_sub();
2954
2955   my ($self, $dbh, $myconfig, $table, $module) = @_;
2956
2957   my ($arap, $where);
2958
2959   $table         = $table eq "customer" ? "customer" : "vendor";
2960   my %column_map = ("a.curr"                  => "currency",
2961                     "a.${table}_id"           => "${table}_id",
2962                     "a.department_id"         => "department_id",
2963                     "d.description"           => "department",
2964                     "ct.name"                 => $table,
2965                     "current_date + ct.terms" => "duedate",
2966     );
2967
2968   if ($self->{type} =~ /delivery_order/) {
2969     $arap  = 'delivery_orders';
2970     delete $column_map{"a.curr"};
2971
2972   } elsif ($self->{type} =~ /_order/) {
2973     $arap  = 'oe';
2974     $where = "quotation = '0'";
2975
2976   } elsif ($self->{type} =~ /_quotation/) {
2977     $arap  = 'oe';
2978     $where = "quotation = '1'";
2979
2980   } elsif ($table eq 'customer') {
2981     $arap  = 'ar';
2982
2983   } else {
2984     $arap  = 'ap';
2985
2986   }
2987
2988   $where           = "($where) AND" if ($where);
2989   my $query        = qq|SELECT MAX(id) FROM $arap
2990                         WHERE $where ${table}_id > 0|;
2991   my ($trans_id)   = selectrow_query($self, $dbh, $query);
2992   $trans_id       *= 1;
2993
2994   my $column_spec  = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2995   $query           = qq|SELECT $column_spec
2996                         FROM $arap a
2997                         LEFT JOIN $table     ct ON (a.${table}_id = ct.id)
2998                         LEFT JOIN department d  ON (a.department_id = d.id)
2999                         WHERE a.id = ?|;
3000   my $ref          = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
3001
3002   map { $self->{$_} = $ref->{$_} } values %column_map;
3003
3004   $main::lxdebug->leave_sub();
3005 }
3006
3007 sub current_date {
3008   $main::lxdebug->enter_sub();
3009
3010   my ($self, $myconfig, $thisdate, $days) = @_;
3011
3012   my $dbh = $self->get_standard_dbh($myconfig);
3013   my $query;
3014
3015   $days *= 1;
3016   if ($thisdate) {
3017     my $dateformat = $myconfig->{dateformat};
3018     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
3019     $thisdate = $dbh->quote($thisdate);
3020     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
3021   } else {
3022     $query = qq|SELECT current_date AS thisdate|;
3023   }
3024
3025   ($thisdate) = selectrow_query($self, $dbh, $query);
3026
3027   $main::lxdebug->leave_sub();
3028
3029   return $thisdate;
3030 }
3031
3032 sub like {
3033   $main::lxdebug->enter_sub();
3034
3035   my ($self, $string) = @_;
3036
3037   if ($string !~ /%/) {
3038     $string = "%$string%";
3039   }
3040
3041   $string =~ s/\'/\'\'/g;
3042
3043   $main::lxdebug->leave_sub();
3044
3045   return $string;
3046 }
3047
3048 sub redo_rows {
3049   $main::lxdebug->enter_sub();
3050
3051   my ($self, $flds, $new, $count, $numrows) = @_;
3052
3053   my @ndx = ();
3054
3055   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
3056
3057   my $i = 0;
3058
3059   # fill rows
3060   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
3061     $i++;
3062     my $j = $item->{ndx} - 1;
3063     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
3064   }
3065
3066   # delete empty rows
3067   for $i ($count + 1 .. $numrows) {
3068     map { delete $self->{"${_}_$i"} } @{$flds};
3069   }
3070
3071   $main::lxdebug->leave_sub();
3072 }
3073
3074 sub update_status {
3075   $main::lxdebug->enter_sub();
3076
3077   my ($self, $myconfig) = @_;
3078
3079   my ($i, $id);
3080
3081   my $dbh = $self->dbconnect_noauto($myconfig);
3082
3083   my $query = qq|DELETE FROM status
3084                  WHERE (formname = ?) AND (trans_id = ?)|;
3085   my $sth = prepare_query($self, $dbh, $query);
3086
3087   if ($self->{formname} =~ /(check|receipt)/) {
3088     for $i (1 .. $self->{rowcount}) {
3089       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
3090     }
3091   } else {
3092     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
3093   }
3094   $sth->finish();
3095
3096   my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3097   my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3098
3099   my %queued = split / /, $self->{queued};
3100   my @values;
3101
3102   if ($self->{formname} =~ /(check|receipt)/) {
3103
3104     # this is a check or receipt, add one entry for each lineitem
3105     my ($accno) = split /--/, $self->{account};
3106     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3107                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3108     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3109     $sth = prepare_query($self, $dbh, $query);
3110
3111     for $i (1 .. $self->{rowcount}) {
3112       if ($self->{"checked_$i"}) {
3113         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3114       }
3115     }
3116     $sth->finish();
3117
3118   } else {
3119     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3120                 VALUES (?, ?, ?, ?, ?)|;
3121     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3122              $queued{$self->{formname}}, $self->{formname});
3123   }
3124
3125   $dbh->commit;
3126   $dbh->disconnect;
3127
3128   $main::lxdebug->leave_sub();
3129 }
3130
3131 sub save_status {
3132   $main::lxdebug->enter_sub();
3133
3134   my ($self, $dbh) = @_;
3135
3136   my ($query, $printed, $emailed);
3137
3138   my $formnames  = $self->{printed};
3139   my $emailforms = $self->{emailed};
3140
3141   $query = qq|DELETE FROM status
3142                  WHERE (formname = ?) AND (trans_id = ?)|;
3143   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3144
3145   # this only applies to the forms
3146   # checks and receipts are posted when printed or queued
3147
3148   if ($self->{queued}) {
3149     my %queued = split / /, $self->{queued};
3150
3151     foreach my $formname (keys %queued) {
3152       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3153       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3154
3155       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3156                   VALUES (?, ?, ?, ?, ?)|;
3157       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3158
3159       $formnames  =~ s/\Q$self->{formname}\E//;
3160       $emailforms =~ s/\Q$self->{formname}\E//;
3161
3162     }
3163   }
3164
3165   # save printed, emailed info
3166   $formnames  =~ s/^ +//g;
3167   $emailforms =~ s/^ +//g;
3168
3169   my %status = ();
3170   map { $status{$_}{printed} = 1 } split / +/, $formnames;
3171   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3172
3173   foreach my $formname (keys %status) {
3174     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
3175     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3176
3177     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3178                 VALUES (?, ?, ?, ?)|;
3179     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3180   }
3181
3182   $main::lxdebug->leave_sub();
3183 }
3184
3185 #--- 4 locale ---#
3186 # $main::locale->text('SAVED')
3187 # $main::locale->text('DELETED')
3188 # $main::locale->text('ADDED')
3189 # $main::locale->text('PAYMENT POSTED')
3190 # $main::locale->text('POSTED')
3191 # $main::locale->text('POSTED AS NEW')
3192 # $main::locale->text('ELSE')
3193 # $main::locale->text('SAVED FOR DUNNING')
3194 # $main::locale->text('DUNNING STARTED')
3195 # $main::locale->text('PRINTED')
3196 # $main::locale->text('MAILED')
3197 # $main::locale->text('SCREENED')
3198 # $main::locale->text('CANCELED')
3199 # $main::locale->text('invoice')
3200 # $main::locale->text('proforma')
3201 # $main::locale->text('sales_order')
3202 # $main::locale->text('packing_list')
3203 # $main::locale->text('pick_list')
3204 # $main::locale->text('purchase_order')
3205 # $main::locale->text('bin_list')
3206 # $main::locale->text('sales_quotation')
3207 # $main::locale->text('request_quotation')
3208
3209 sub save_history {
3210   $main::lxdebug->enter_sub();
3211
3212   my $self = shift();
3213   my $dbh = shift();
3214
3215   if(!exists $self->{employee_id}) {
3216     &get_employee($self, $dbh);
3217   }
3218
3219   my $query =
3220    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3221    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3222   my @values = (conv_i($self->{id}), $self->{login},
3223                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3224   do_query($self, $dbh, $query, @values);
3225
3226   $main::lxdebug->leave_sub();
3227 }
3228
3229 sub get_history {
3230   $main::lxdebug->enter_sub();
3231
3232   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3233   my ($orderBy, $desc) = split(/\-\-/, $order);
3234   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3235   my @tempArray;
3236   my $i = 0;
3237   if ($trans_id ne "") {
3238     my $query =
3239       qq|SELECT h.employee_id, h.itime::timestamp(0) AS itime, h.addition, h.what_done, emp.name, h.snumbers, h.trans_id AS id | .
3240       qq|FROM history_erp h | .
3241       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3242       qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3243       $order;
3244
3245     my $sth = $dbh->prepare($query) || $self->dberror($query);
3246
3247     $sth->execute() || $self->dberror("$query");
3248
3249     while(my $hash_ref = $sth->fetchrow_hashref()) {
3250       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3251       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3252       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3253       $tempArray[$i++] = $hash_ref;
3254     }
3255     $main::lxdebug->leave_sub() and return \@tempArray
3256       if ($i > 0 && $tempArray[0] ne "");
3257   }
3258   $main::lxdebug->leave_sub();
3259   return 0;
3260 }
3261
3262 sub update_defaults {
3263   $main::lxdebug->enter_sub();
3264
3265   my ($self, $myconfig, $fld, $provided_dbh) = @_;
3266
3267   my $dbh;
3268   if ($provided_dbh) {
3269     $dbh = $provided_dbh;
3270   } else {
3271     $dbh = $self->dbconnect_noauto($myconfig);
3272   }
3273   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3274   my $sth   = $dbh->prepare($query);
3275
3276   $sth->execute || $self->dberror($query);
3277   my ($var) = $sth->fetchrow_array;
3278   $sth->finish;
3279
3280   if ($var =~ m/\d+$/) {
3281     my $new_var  = (substr $var, $-[0]) * 1 + 1;
3282     my $len_diff = length($var) - $-[0] - length($new_var);
3283     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3284
3285   } else {
3286     $var = $var . '1';
3287   }
3288
3289   $query = qq|UPDATE defaults SET $fld = ?|;
3290   do_query($self, $dbh, $query, $var);
3291
3292   if (!$provided_dbh) {
3293     $dbh->commit;
3294     $dbh->disconnect;
3295   }
3296
3297   $main::lxdebug->leave_sub();
3298
3299   return $var;
3300 }
3301
3302 =item update_business
3303
3304 PARAMS (not named):
3305  \%config,     - config hashref
3306  $business_id, - business id
3307  $dbh          - optional database handle
3308
3309 handles business (thats customer/vendor types) sequences.
3310
3311 special behaviour for empty strings in customerinitnumber field:
3312 will in this case not increase the value, and return undef.
3313
3314 =cut
3315 sub update_business {
3316   $main::lxdebug->enter_sub();
3317
3318   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3319
3320   my $dbh;
3321   if ($provided_dbh) {
3322     $dbh = $provided_dbh;
3323   } else {
3324     $dbh = $self->dbconnect_noauto($myconfig);
3325   }
3326   my $query =
3327     qq|SELECT customernumberinit FROM business
3328        WHERE id = ? FOR UPDATE|;
3329   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3330
3331   return undef unless $var;
3332
3333   if ($var =~ m/\d+$/) {
3334     my $new_var  = (substr $var, $-[0]) * 1 + 1;
3335     my $len_diff = length($var) - $-[0] - length($new_var);
3336     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3337
3338   } else {
3339     $var = $var . '1';
3340   }
3341
3342   $query = qq|UPDATE business
3343               SET customernumberinit = ?
3344               WHERE id = ?|;
3345   do_query($self, $dbh, $query, $var, $business_id);
3346
3347   if (!$provided_dbh) {
3348     $dbh->commit;
3349     $dbh->disconnect;
3350   }
3351
3352   $main::lxdebug->leave_sub();
3353
3354   return $var;
3355 }
3356
3357 sub get_partsgroup {
3358   $main::lxdebug->enter_sub();
3359
3360   my ($self, $myconfig, $p) = @_;
3361   my $target = $p->{target} || 'all_partsgroup';
3362
3363   my $dbh = $self->get_standard_dbh($myconfig);
3364
3365   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3366                  FROM partsgroup pg
3367                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
3368   my @values;
3369
3370   if ($p->{searchitems} eq 'part') {
3371     $query .= qq|WHERE p.inventory_accno_id > 0|;
3372   }
3373   if ($p->{searchitems} eq 'service') {
3374     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3375   }
3376   if ($p->{searchitems} eq 'assembly') {
3377     $query .= qq|WHERE p.assembly = '1'|;
3378   }
3379   if ($p->{searchitems} eq 'labor') {
3380     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3381   }
3382
3383   $query .= qq|ORDER BY partsgroup|;
3384
3385   if ($p->{all}) {
3386     $query = qq|SELECT id, partsgroup FROM partsgroup
3387                 ORDER BY partsgroup|;
3388   }
3389
3390   if ($p->{language_code}) {
3391     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3392                   t.description AS translation
3393                 FROM partsgroup pg
3394                 JOIN parts p ON (p.partsgroup_id = pg.id)
3395                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3396                 ORDER BY translation|;
3397     @values = ($p->{language_code});
3398   }
3399
3400   $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3401
3402   $main::lxdebug->leave_sub();
3403 }
3404
3405 sub get_pricegroup {
3406   $main::lxdebug->enter_sub();
3407
3408   my ($self, $myconfig, $p) = @_;
3409
3410   my $dbh = $self->get_standard_dbh($myconfig);
3411
3412   my $query = qq|SELECT p.id, p.pricegroup
3413                  FROM pricegroup p|;
3414
3415   $query .= qq| ORDER BY pricegroup|;
3416
3417   if ($p->{all}) {
3418     $query = qq|SELECT id, pricegroup FROM pricegroup
3419                 ORDER BY pricegroup|;
3420   }
3421
3422   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3423
3424   $main::lxdebug->leave_sub();
3425 }
3426
3427 sub all_years {
3428 # usage $form->all_years($myconfig, [$dbh])
3429 # return list of all years where bookings found
3430 # (@all_years)
3431
3432   $main::lxdebug->enter_sub();
3433
3434   my ($self, $myconfig, $dbh) = @_;
3435
3436   $dbh ||= $self->get_standard_dbh($myconfig);
3437
3438   # get years
3439   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3440                    (SELECT MAX(transdate) FROM acc_trans)|;
3441   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3442
3443   if ($myconfig->{dateformat} =~ /^yy/) {
3444     ($startdate) = split /\W/, $startdate;
3445     ($enddate) = split /\W/, $enddate;
3446   } else {
3447     (@_) = split /\W/, $startdate;
3448     $startdate = $_[2];
3449     (@_) = split /\W/, $enddate;
3450     $enddate = $_[2];
3451   }
3452
3453   my @all_years;
3454   $startdate = substr($startdate,0,4);
3455   $enddate = substr($enddate,0,4);
3456
3457   while ($enddate >= $startdate) {
3458     push @all_years, $enddate--;
3459   }
3460
3461   return @all_years;
3462
3463   $main::lxdebug->leave_sub();
3464 }
3465
3466 sub backup_vars {
3467   $main::lxdebug->enter_sub();
3468   my $self = shift;
3469   my @vars = @_;
3470
3471   map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3472
3473   $main::lxdebug->leave_sub();
3474 }
3475
3476 sub restore_vars {
3477   $main::lxdebug->enter_sub();
3478
3479   my $self = shift;
3480   my @vars = @_;
3481
3482   map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3483
3484   $main::lxdebug->leave_sub();
3485 }
3486
3487 1;