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