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