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