Optionale minimale Excel-Unterstützung für Druckvorlagen (Austausch von Platzhalter...
[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 ( $self->{"format"} =~ /excel/i ) {
1182     $template = ExcelTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1183     $ext_for_format = 'xls';
1184
1185   } elsif ( defined $self->{'format'}) {
1186     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
1187
1188   } elsif ( $self->{'format'} eq '' ) {
1189     $self->error("No Outputformat given: $self->{'format'}");
1190
1191   } else { #Catch the rest
1192     $self->error("Outputformat not defined: $self->{'format'}");
1193   }
1194
1195   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
1196   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
1197
1198   if (!$self->{employee_id}) {
1199     map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
1200   }
1201
1202   map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
1203
1204   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
1205
1206   # OUT is used for the media, screen, printer, email
1207   # for postscript we store a copy in a temporary file
1208   my $fileid = time;
1209   my $prepend_userspath;
1210
1211   if (!$self->{tmpfile}) {
1212     $self->{tmpfile}   = "${fileid}.$self->{IN}";
1213     $prepend_userspath = 1;
1214   }
1215
1216   $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
1217
1218   $self->{tmpfile} =~ s|.*/||;
1219   $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
1220   $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
1221
1222   if ($template->uses_temp_file() || $self->{media} eq 'email') {
1223     $out = $self->{OUT};
1224     $self->{OUT} = ">$self->{tmpfile}";
1225   }
1226
1227   if ($self->{OUT}) {
1228     open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
1229   } else {
1230     open(OUT, ">-") or $self->error("STDOUT : $!");
1231     $self->header;
1232   }
1233
1234   if (!$template->parse(*OUT)) {
1235     $self->cleanup();
1236     $self->error("$self->{IN} : " . $template->get_error());
1237   }
1238
1239   close(OUT);
1240
1241   if ($template->uses_temp_file() || $self->{media} eq 'email') {
1242
1243     if ($self->{media} eq 'email') {
1244
1245       my $mail = new Mailer;
1246
1247       map { $mail->{$_} = $self->{$_} }
1248         qw(cc bcc subject message version format);
1249       $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
1250       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1251       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1252       $mail->{fileid} = "$fileid.";
1253       $myconfig->{signature} =~ s/\r//g;
1254
1255       # if we send html or plain text inline
1256       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1257         $mail->{contenttype} = "text/html";
1258
1259         $mail->{message}       =~ s/\r//g;
1260         $mail->{message}       =~ s/\n/<br>\n/g;
1261         $myconfig->{signature} =~ s/\n/<br>\n/g;
1262         $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
1263
1264         open(IN, $self->{tmpfile})
1265           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1266         while (<IN>) {
1267           $mail->{message} .= $_;
1268         }
1269
1270         close(IN);
1271
1272       } else {
1273
1274         if (!$self->{"do_not_attach"}) {
1275           my $attachment_name  =  $self->{attachment_filename} || $self->{tmpfile};
1276           $attachment_name     =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
1277           $mail->{attachments} =  [{ "filename" => $self->{tmpfile},
1278                                      "name"     => $attachment_name }];
1279         }
1280
1281         $mail->{message}  =~ s/\r//g;
1282         $mail->{message} .=  "\n-- \n$myconfig->{signature}";
1283
1284       }
1285
1286       my $err = $mail->send();
1287       $self->error($self->cleanup . "$err") if ($err);
1288
1289     } else {
1290
1291       $self->{OUT} = $out;
1292
1293       my $numbytes = (-s $self->{tmpfile});
1294       open(IN, $self->{tmpfile})
1295         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1296
1297       $self->{copies} = 1 unless $self->{media} eq 'printer';
1298
1299       chdir("$self->{cwd}");
1300       #print(STDERR "Kopien $self->{copies}\n");
1301       #print(STDERR "OUT $self->{OUT}\n");
1302       for my $i (1 .. $self->{copies}) {
1303         if ($self->{OUT}) {
1304           open(OUT, $self->{OUT})
1305             or $self->error($self->cleanup . "$self->{OUT} : $!");
1306         } else {
1307           $self->{attachment_filename} = ($self->{attachment_filename})
1308                                        ? $self->{attachment_filename}
1309                                        : $self->generate_attachment_filename();
1310
1311           # launch application
1312           print qq|Content-Type: | . $template->get_mime_type() . qq|
1313 Content-Disposition: attachment; filename="$self->{attachment_filename}"
1314 Content-Length: $numbytes
1315
1316 |;
1317
1318           open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
1319
1320         }
1321
1322         while (<IN>) {
1323           print OUT $_;
1324
1325         }
1326
1327         close(OUT);
1328
1329         seek IN, 0, 0;
1330       }
1331
1332       close(IN);
1333     }
1334
1335   }
1336
1337   $self->cleanup;
1338
1339   chdir("$self->{cwd}");
1340   $main::lxdebug->leave_sub();
1341 }
1342
1343 sub get_formname_translation {
1344   $main::lxdebug->enter_sub();
1345   my ($self, $formname) = @_;
1346
1347   $formname ||= $self->{formname};
1348
1349   my %formname_translations = (
1350     bin_list                => $main::locale->text('Bin List'),
1351     credit_note             => $main::locale->text('Credit Note'),
1352     invoice                 => $main::locale->text('Invoice'),
1353     packing_list            => $main::locale->text('Packing List'),
1354     pick_list               => $main::locale->text('Pick List'),
1355     proforma                => $main::locale->text('Proforma Invoice'),
1356     purchase_order          => $main::locale->text('Purchase Order'),
1357     request_quotation       => $main::locale->text('RFQ'),
1358     sales_order             => $main::locale->text('Confirmation'),
1359     sales_quotation         => $main::locale->text('Quotation'),
1360     storno_invoice          => $main::locale->text('Storno Invoice'),
1361     storno_packing_list     => $main::locale->text('Storno Packing List'),
1362     sales_delivery_order    => $main::locale->text('Delivery Order'),
1363     purchase_delivery_order => $main::locale->text('Delivery Order'),
1364     dunning                 => $main::locale->text('Dunning'),
1365   );
1366
1367   $main::lxdebug->leave_sub();
1368   return $formname_translations{$formname}
1369 }
1370
1371 sub get_number_prefix_for_type {
1372   $main::lxdebug->enter_sub();
1373   my ($self) = @_;
1374
1375   my $prefix =
1376       (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1377     : ($self->{type} =~ /_quotation$/)                        ? 'quo'
1378     : ($self->{type} =~ /_delivery_order$/)                   ? 'do'
1379     :                                                           'ord';
1380
1381   $main::lxdebug->leave_sub();
1382   return $prefix;
1383 }
1384
1385 sub get_extension_for_format {
1386   $main::lxdebug->enter_sub();
1387   my ($self)    = @_;
1388
1389   my $extension = $self->{format} =~ /pdf/i          ? ".pdf"
1390                 : $self->{format} =~ /postscript/i   ? ".ps"
1391                 : $self->{format} =~ /opendocument/i ? ".odt"
1392                 : $self->{format} =~ /excel/i        ? ".xls"
1393                 : $self->{format} =~ /html/i         ? ".html"
1394                 :                                      "";
1395
1396   $main::lxdebug->leave_sub();
1397   return $extension;
1398 }
1399
1400 sub generate_attachment_filename {
1401   $main::lxdebug->enter_sub();
1402   my ($self) = @_;
1403
1404   my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1405   my $prefix              = $self->get_number_prefix_for_type();
1406
1407   if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1408     $attachment_filename .= ' (' . $main::locale->text('Preview') . ')' . $self->get_extension_for_format();
1409
1410   } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1411     $attachment_filename .=  "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1412
1413   } else {
1414     $attachment_filename = "";
1415   }
1416
1417   $attachment_filename =  $main::locale->quote_special_chars('filenames', $attachment_filename);
1418   $attachment_filename =~ s|[\s/\\]+|_|g;
1419
1420   $main::lxdebug->leave_sub();
1421   return $attachment_filename;
1422 }
1423
1424 sub generate_email_subject {
1425   $main::lxdebug->enter_sub();
1426   my ($self) = @_;
1427
1428   my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1429   my $prefix  = $self->get_number_prefix_for_type();
1430
1431   if ($subject && $self->{"${prefix}number"}) {
1432     $subject .= " " . $self->{"${prefix}number"}
1433   }
1434
1435   $main::lxdebug->leave_sub();
1436   return $subject;
1437 }
1438
1439 sub cleanup {
1440   $main::lxdebug->enter_sub();
1441
1442   my $self = shift;
1443
1444   chdir("$self->{tmpdir}");
1445
1446   my @err = ();
1447   if (-f "$self->{tmpfile}.err") {
1448     open(FH, "$self->{tmpfile}.err");
1449     @err = <FH>;
1450     close(FH);
1451   }
1452
1453   if ($self->{tmpfile} && ! $::keep_temp_files) {
1454     $self->{tmpfile} =~ s|.*/||g;
1455     # strip extension
1456     $self->{tmpfile} =~ s/\.\w+$//g;
1457     my $tmpfile = $self->{tmpfile};
1458     unlink(<$tmpfile.*>);
1459   }
1460
1461   chdir("$self->{cwd}");
1462
1463   $main::lxdebug->leave_sub();
1464
1465   return "@err";
1466 }
1467
1468 sub datetonum {
1469   $main::lxdebug->enter_sub();
1470
1471   my ($self, $date, $myconfig) = @_;
1472   my ($yy, $mm, $dd);
1473
1474   if ($date && $date =~ /\D/) {
1475
1476     if ($myconfig->{dateformat} =~ /^yy/) {
1477       ($yy, $mm, $dd) = split /\D/, $date;
1478     }
1479     if ($myconfig->{dateformat} =~ /^mm/) {
1480       ($mm, $dd, $yy) = split /\D/, $date;
1481     }
1482     if ($myconfig->{dateformat} =~ /^dd/) {
1483       ($dd, $mm, $yy) = split /\D/, $date;
1484     }
1485
1486     $dd *= 1;
1487     $mm *= 1;
1488     $yy = ($yy < 70) ? $yy + 2000 : $yy;
1489     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1490
1491     $dd = "0$dd" if ($dd < 10);
1492     $mm = "0$mm" if ($mm < 10);
1493
1494     $date = "$yy$mm$dd";
1495   }
1496
1497   $main::lxdebug->leave_sub();
1498
1499   return $date;
1500 }
1501
1502 # Database routines used throughout
1503
1504 sub dbconnect {
1505   $main::lxdebug->enter_sub(2);
1506
1507   my ($self, $myconfig) = @_;
1508
1509   # connect to database
1510   my $dbh =
1511     DBI->connect($myconfig->{dbconnect},
1512                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
1513     or $self->dberror;
1514
1515   # set db options
1516   if ($myconfig->{dboptions}) {
1517     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1518   }
1519
1520   $main::lxdebug->leave_sub(2);
1521
1522   return $dbh;
1523 }
1524
1525 sub dbconnect_noauto {
1526   $main::lxdebug->enter_sub();
1527
1528   my ($self, $myconfig) = @_;
1529
1530   # connect to database
1531   my $dbh =
1532     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1533                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
1534     or $self->dberror;
1535
1536   # set db options
1537   if ($myconfig->{dboptions}) {
1538     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1539   }
1540
1541   $main::lxdebug->leave_sub();
1542
1543   return $dbh;
1544 }
1545
1546 sub get_standard_dbh {
1547   $main::lxdebug->enter_sub(2);
1548
1549   my ($self, $myconfig) = @_;
1550
1551   if ($standard_dbh && !$standard_dbh->{Active}) {
1552     $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
1553     undef $standard_dbh;
1554   }
1555
1556   $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1557
1558   $main::lxdebug->leave_sub(2);
1559
1560   return $standard_dbh;
1561 }
1562
1563 sub date_closed {
1564   $main::lxdebug->enter_sub();
1565
1566   my ($self, $date, $myconfig) = @_;
1567   my $dbh = $self->dbconnect($myconfig);
1568
1569   my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1570   my $sth = prepare_execute_query($self, $dbh, $query, $date);
1571   my ($closed) = $sth->fetchrow_array;
1572
1573   $main::lxdebug->leave_sub();
1574
1575   return $closed;
1576 }
1577
1578 sub update_balance {
1579   $main::lxdebug->enter_sub();
1580
1581   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1582
1583   # if we have a value, go do it
1584   if ($value != 0) {
1585
1586     # retrieve balance from table
1587     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1588     my $sth = prepare_execute_query($self, $dbh, $query, @values);
1589     my ($balance) = $sth->fetchrow_array;
1590     $sth->finish;
1591
1592     $balance += $value;
1593
1594     # update balance
1595     $query = "UPDATE $table SET $field = $balance WHERE $where";
1596     do_query($self, $dbh, $query, @values);
1597   }
1598   $main::lxdebug->leave_sub();
1599 }
1600
1601 sub update_exchangerate {
1602   $main::lxdebug->enter_sub();
1603
1604   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1605   my ($query);
1606   # some sanity check for currency
1607   if ($curr eq '') {
1608     $main::lxdebug->leave_sub();
1609     return;
1610   }
1611   $query = qq|SELECT curr FROM defaults|;
1612
1613   my ($currency) = selectrow_query($self, $dbh, $query);
1614   my ($defaultcurrency) = split m/:/, $currency;
1615
1616
1617   if ($curr eq $defaultcurrency) {
1618     $main::lxdebug->leave_sub();
1619     return;
1620   }
1621
1622   $query = qq|SELECT e.curr FROM exchangerate e
1623                  WHERE e.curr = ? AND e.transdate = ?
1624                  FOR UPDATE|;
1625   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1626
1627   if ($buy == 0) {
1628     $buy = "";
1629   }
1630   if ($sell == 0) {
1631     $sell = "";
1632   }
1633
1634   $buy = conv_i($buy, "NULL");
1635   $sell = conv_i($sell, "NULL");
1636
1637   my $set;
1638   if ($buy != 0 && $sell != 0) {
1639     $set = "buy = $buy, sell = $sell";
1640   } elsif ($buy != 0) {
1641     $set = "buy = $buy";
1642   } elsif ($sell != 0) {
1643     $set = "sell = $sell";
1644   }
1645
1646   if ($sth->fetchrow_array) {
1647     $query = qq|UPDATE exchangerate
1648                 SET $set
1649                 WHERE curr = ?
1650                 AND transdate = ?|;
1651
1652   } else {
1653     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1654                 VALUES (?, $buy, $sell, ?)|;
1655   }
1656   $sth->finish;
1657   do_query($self, $dbh, $query, $curr, $transdate);
1658
1659   $main::lxdebug->leave_sub();
1660 }
1661
1662 sub save_exchangerate {
1663   $main::lxdebug->enter_sub();
1664
1665   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1666
1667   my $dbh = $self->dbconnect($myconfig);
1668
1669   my ($buy, $sell);
1670
1671   $buy  = $rate if $fld eq 'buy';
1672   $sell = $rate if $fld eq 'sell';
1673
1674
1675   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1676
1677
1678   $dbh->disconnect;
1679
1680   $main::lxdebug->leave_sub();
1681 }
1682
1683 sub get_exchangerate {
1684   $main::lxdebug->enter_sub();
1685
1686   my ($self, $dbh, $curr, $transdate, $fld) = @_;
1687   my ($query);
1688
1689   unless ($transdate) {
1690     $main::lxdebug->leave_sub();
1691     return 1;
1692   }
1693
1694   $query = qq|SELECT curr FROM defaults|;
1695
1696   my ($currency) = selectrow_query($self, $dbh, $query);
1697   my ($defaultcurrency) = split m/:/, $currency;
1698
1699   if ($currency eq $defaultcurrency) {
1700     $main::lxdebug->leave_sub();
1701     return 1;
1702   }
1703
1704   $query = qq|SELECT e.$fld FROM exchangerate e
1705                  WHERE e.curr = ? AND e.transdate = ?|;
1706   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1707
1708
1709
1710   $main::lxdebug->leave_sub();
1711
1712   return $exchangerate;
1713 }
1714
1715 sub check_exchangerate {
1716   $main::lxdebug->enter_sub();
1717
1718   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1719
1720   if ($fld !~/^buy|sell$/) {
1721     $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1722   }
1723
1724   unless ($transdate) {
1725     $main::lxdebug->leave_sub();
1726     return "";
1727   }
1728
1729   my ($defaultcurrency) = $self->get_default_currency($myconfig);
1730
1731   if ($currency eq $defaultcurrency) {
1732     $main::lxdebug->leave_sub();
1733     return 1;
1734   }
1735
1736   my $dbh   = $self->get_standard_dbh($myconfig);
1737   my $query = qq|SELECT e.$fld FROM exchangerate e
1738                  WHERE e.curr = ? AND e.transdate = ?|;
1739
1740   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1741
1742   $main::lxdebug->leave_sub();
1743
1744   return $exchangerate;
1745 }
1746
1747 sub get_all_currencies {
1748   $main::lxdebug->enter_sub();
1749
1750   my ($self, $myconfig) = @_;
1751   my $dbh = $self->get_standard_dbh($myconfig);
1752
1753   my $query = qq|SELECT curr FROM defaults|;
1754
1755   my ($curr)     = selectrow_query($self, $dbh, $query);
1756   my @currencies = grep { $_ } map { s/\s//g; $_ } split m/:/, $curr;
1757
1758   $main::lxdebug->leave_sub();
1759
1760   return @currencies;
1761 }
1762
1763 sub get_default_currency {
1764   $main::lxdebug->enter_sub();
1765
1766   my ($self, $myconfig) = @_;
1767   my @currencies        = $self->get_all_currencies($myconfig);
1768
1769   $main::lxdebug->leave_sub();
1770
1771   return $currencies[0];
1772 }
1773
1774 sub set_payment_options {
1775   $main::lxdebug->enter_sub();
1776
1777   my ($self, $myconfig, $transdate) = @_;
1778
1779   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1780
1781   my $dbh = $self->get_standard_dbh($myconfig);
1782
1783   my $query =
1784     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1785     qq|FROM payment_terms p | .
1786     qq|WHERE p.id = ?|;
1787
1788   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1789    $self->{payment_terms}) =
1790      selectrow_query($self, $dbh, $query, $self->{payment_id});
1791
1792   if ($transdate eq "") {
1793     if ($self->{invdate}) {
1794       $transdate = $self->{invdate};
1795     } else {
1796       $transdate = $self->{transdate};
1797     }
1798   }
1799
1800   $query =
1801     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1802     qq|FROM payment_terms|;
1803   ($self->{netto_date}, $self->{skonto_date}) =
1804     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1805
1806   my ($invtotal, $total);
1807   my (%amounts, %formatted_amounts);
1808
1809   if ($self->{type} =~ /_order$/) {
1810     $amounts{invtotal} = $self->{ordtotal};
1811     $amounts{total}    = $self->{ordtotal};
1812
1813   } elsif ($self->{type} =~ /_quotation$/) {
1814     $amounts{invtotal} = $self->{quototal};
1815     $amounts{total}    = $self->{quototal};
1816
1817   } else {
1818     $amounts{invtotal} = $self->{invtotal};
1819     $amounts{total}    = $self->{total};
1820   }
1821   $amounts{skonto_in_percent} = 100.0 * $self->{percent_skonto};
1822
1823   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1824
1825   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
1826   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1827   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
1828
1829   foreach (keys %amounts) {
1830     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
1831     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1832   }
1833
1834   if ($self->{"language_id"}) {
1835     $query =
1836       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1837       qq|FROM translation_payment_terms t | .
1838       qq|LEFT JOIN language l ON t.language_id = l.id | .
1839       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1840     my ($description_long, $output_numberformat, $output_dateformat,
1841       $output_longdates) =
1842       selectrow_query($self, $dbh, $query,
1843                       $self->{"language_id"}, $self->{"payment_id"});
1844
1845     $self->{payment_terms} = $description_long if ($description_long);
1846
1847     if ($output_dateformat) {
1848       foreach my $key (qw(netto_date skonto_date)) {
1849         $self->{$key} =
1850           $main::locale->reformat_date($myconfig, $self->{$key},
1851                                        $output_dateformat,
1852                                        $output_longdates);
1853       }
1854     }
1855
1856     if ($output_numberformat &&
1857         ($output_numberformat ne $myconfig->{"numberformat"})) {
1858       my $saved_numberformat = $myconfig->{"numberformat"};
1859       $myconfig->{"numberformat"} = $output_numberformat;
1860       map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1861       $myconfig->{"numberformat"} = $saved_numberformat;
1862     }
1863   }
1864
1865   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1866   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1867   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1868   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1869   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1870   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1871   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1872
1873   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1874
1875   $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
1876
1877   $main::lxdebug->leave_sub();
1878
1879 }
1880
1881 sub get_template_language {
1882   $main::lxdebug->enter_sub();
1883
1884   my ($self, $myconfig) = @_;
1885
1886   my $template_code = "";
1887
1888   if ($self->{language_id}) {
1889     my $dbh = $self->get_standard_dbh($myconfig);
1890     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1891     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1892   }
1893
1894   $main::lxdebug->leave_sub();
1895
1896   return $template_code;
1897 }
1898
1899 sub get_printer_code {
1900   $main::lxdebug->enter_sub();
1901
1902   my ($self, $myconfig) = @_;
1903
1904   my $template_code = "";
1905
1906   if ($self->{printer_id}) {
1907     my $dbh = $self->get_standard_dbh($myconfig);
1908     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1909     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1910   }
1911
1912   $main::lxdebug->leave_sub();
1913
1914   return $template_code;
1915 }
1916
1917 sub get_shipto {
1918   $main::lxdebug->enter_sub();
1919
1920   my ($self, $myconfig) = @_;
1921
1922   my $template_code = "";
1923
1924   if ($self->{shipto_id}) {
1925     my $dbh = $self->get_standard_dbh($myconfig);
1926     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1927     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1928     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1929   }
1930
1931   $main::lxdebug->leave_sub();
1932 }
1933
1934 sub add_shipto {
1935   $main::lxdebug->enter_sub();
1936
1937   my ($self, $dbh, $id, $module) = @_;
1938
1939   my $shipto;
1940   my @values;
1941
1942   foreach my $item (qw(name department_1 department_2 street zipcode city country
1943                        contact phone fax email)) {
1944     if ($self->{"shipto$item"}) {
1945       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1946     }
1947     push(@values, $self->{"shipto${item}"});
1948   }
1949
1950   if ($shipto) {
1951     if ($self->{shipto_id}) {
1952       my $query = qq|UPDATE shipto set
1953                        shiptoname = ?,
1954                        shiptodepartment_1 = ?,
1955                        shiptodepartment_2 = ?,
1956                        shiptostreet = ?,
1957                        shiptozipcode = ?,
1958                        shiptocity = ?,
1959                        shiptocountry = ?,
1960                        shiptocontact = ?,
1961                        shiptophone = ?,
1962                        shiptofax = ?,
1963                        shiptoemail = ?
1964                      WHERE shipto_id = ?|;
1965       do_query($self, $dbh, $query, @values, $self->{shipto_id});
1966     } else {
1967       my $query = qq|SELECT * FROM shipto
1968                      WHERE shiptoname = ? AND
1969                        shiptodepartment_1 = ? AND
1970                        shiptodepartment_2 = ? AND
1971                        shiptostreet = ? AND
1972                        shiptozipcode = ? AND
1973                        shiptocity = ? AND
1974                        shiptocountry = ? AND
1975                        shiptocontact = ? AND
1976                        shiptophone = ? AND
1977                        shiptofax = ? AND
1978                        shiptoemail = ? AND
1979                        module = ? AND
1980                        trans_id = ?|;
1981       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1982       if(!$insert_check){
1983         $query =
1984           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1985                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
1986                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
1987              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1988         do_query($self, $dbh, $query, $id, @values, $module);
1989       }
1990     }
1991   }
1992
1993   $main::lxdebug->leave_sub();
1994 }
1995
1996 sub get_employee {
1997   $main::lxdebug->enter_sub();
1998
1999   my ($self, $dbh) = @_;
2000
2001   $dbh ||= $self->get_standard_dbh(\%main::myconfig);
2002
2003   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
2004   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
2005   $self->{"employee_id"} *= 1;
2006
2007   $main::lxdebug->leave_sub();
2008 }
2009
2010 sub get_employee_data {
2011   $main::lxdebug->enter_sub();
2012
2013   my $self     = shift;
2014   my %params   = @_;
2015
2016   Common::check_params(\%params, qw(prefix));
2017   Common::check_params_x(\%params, qw(id));
2018
2019   if (!$params{id}) {
2020     $main::lxdebug->leave_sub();
2021     return;
2022   }
2023
2024   my $myconfig = \%main::myconfig;
2025   my $dbh      = $params{dbh} || $self->get_standard_dbh($myconfig);
2026
2027   my ($login)  = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
2028
2029   if ($login) {
2030     my $user = User->new($login);
2031     map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
2032
2033     $self->{$params{prefix} . '_login'}   = $login;
2034     $self->{$params{prefix} . '_name'}  ||= $login;
2035   }
2036
2037   $main::lxdebug->leave_sub();
2038 }
2039
2040 sub get_duedate {
2041   $main::lxdebug->enter_sub();
2042
2043   my ($self, $myconfig, $reference_date) = @_;
2044
2045   $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
2046
2047   my $dbh         = $self->get_standard_dbh($myconfig);
2048   my $query       = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
2049   my ($duedate)   = selectrow_query($self, $dbh, $query, $self->{payment_id});
2050
2051   $main::lxdebug->leave_sub();
2052
2053   return $duedate;
2054 }
2055
2056 sub _get_contacts {
2057   $main::lxdebug->enter_sub();
2058
2059   my ($self, $dbh, $id, $key) = @_;
2060
2061   $key = "all_contacts" unless ($key);
2062
2063   if (!$id) {
2064     $self->{$key} = [];
2065     $main::lxdebug->leave_sub();
2066     return;
2067   }
2068
2069   my $query =
2070     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
2071     qq|FROM contacts | .
2072     qq|WHERE cp_cv_id = ? | .
2073     qq|ORDER BY lower(cp_name)|;
2074
2075   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
2076
2077   $main::lxdebug->leave_sub();
2078 }
2079
2080 sub _get_projects {
2081   $main::lxdebug->enter_sub();
2082
2083   my ($self, $dbh, $key) = @_;
2084
2085   my ($all, $old_id, $where, @values);
2086
2087   if (ref($key) eq "HASH") {
2088     my $params = $key;
2089
2090     $key = "ALL_PROJECTS";
2091
2092     foreach my $p (keys(%{$params})) {
2093       if ($p eq "all") {
2094         $all = $params->{$p};
2095       } elsif ($p eq "old_id") {
2096         $old_id = $params->{$p};
2097       } elsif ($p eq "key") {
2098         $key = $params->{$p};
2099       }
2100     }
2101   }
2102
2103   if (!$all) {
2104     $where = "WHERE active ";
2105     if ($old_id) {
2106       if (ref($old_id) eq "ARRAY") {
2107         my @ids = grep({ $_ } @{$old_id});
2108         if (@ids) {
2109           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
2110           push(@values, @ids);
2111         }
2112       } else {
2113         $where .= " OR (id = ?) ";
2114         push(@values, $old_id);
2115       }
2116     }
2117   }
2118
2119   my $query =
2120     qq|SELECT id, projectnumber, description, active | .
2121     qq|FROM project | .
2122     $where .
2123     qq|ORDER BY lower(projectnumber)|;
2124
2125   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2126
2127   $main::lxdebug->leave_sub();
2128 }
2129
2130 sub _get_shipto {
2131   $main::lxdebug->enter_sub();
2132
2133   my ($self, $dbh, $vc_id, $key) = @_;
2134
2135   $key = "all_shipto" unless ($key);
2136
2137   if ($vc_id) {
2138     # get shipping addresses
2139     my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2140
2141     $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2142
2143   } else {
2144     $self->{$key} = [];
2145   }
2146
2147   $main::lxdebug->leave_sub();
2148 }
2149
2150 sub _get_printers {
2151   $main::lxdebug->enter_sub();
2152
2153   my ($self, $dbh, $key) = @_;
2154
2155   $key = "all_printers" unless ($key);
2156
2157   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2158
2159   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2160
2161   $main::lxdebug->leave_sub();
2162 }
2163
2164 sub _get_charts {
2165   $main::lxdebug->enter_sub();
2166
2167   my ($self, $dbh, $params) = @_;
2168   my ($key);
2169
2170   $key = $params->{key};
2171   $key = "all_charts" unless ($key);
2172
2173   my $transdate = quote_db_date($params->{transdate});
2174
2175   my $query =
2176     qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
2177     qq|FROM chart c | .
2178     qq|LEFT JOIN taxkeys tk ON | .
2179     qq|(tk.id = (SELECT id FROM taxkeys | .
2180     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2181     qq|          ORDER BY startdate DESC LIMIT 1)) | .
2182     qq|ORDER BY c.accno|;
2183
2184   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2185
2186   $main::lxdebug->leave_sub();
2187 }
2188
2189 sub _get_taxcharts {
2190   $main::lxdebug->enter_sub();
2191
2192   my ($self, $dbh, $params) = @_;
2193
2194   my $key = "all_taxcharts";
2195   my @where;
2196
2197   if (ref $params eq 'HASH') {
2198     $key = $params->{key} if ($params->{key});
2199     if ($params->{module} eq 'AR') {
2200       push @where, 'taxkey NOT IN (8, 9, 18, 19)';
2201
2202     } elsif ($params->{module} eq 'AP') {
2203       push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
2204     }
2205
2206   } elsif ($params) {
2207     $key = $params;
2208   }
2209
2210   my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
2211
2212   my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
2213
2214   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2215
2216   $main::lxdebug->leave_sub();
2217 }
2218
2219 sub _get_taxzones {
2220   $main::lxdebug->enter_sub();
2221
2222   my ($self, $dbh, $key) = @_;
2223
2224   $key = "all_taxzones" unless ($key);
2225
2226   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
2227
2228   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2229
2230   $main::lxdebug->leave_sub();
2231 }
2232
2233 sub _get_employees {
2234   $main::lxdebug->enter_sub();
2235
2236   my ($self, $dbh, $default_key, $key) = @_;
2237
2238   $key = $default_key unless ($key);
2239   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
2240
2241   $main::lxdebug->leave_sub();
2242 }
2243
2244 sub _get_business_types {
2245   $main::lxdebug->enter_sub();
2246
2247   my ($self, $dbh, $key) = @_;
2248
2249   my $options       = ref $key eq 'HASH' ? $key : { key => $key };
2250   $options->{key} ||= "all_business_types";
2251   my $where         = '';
2252
2253   if (exists $options->{salesman}) {
2254     $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
2255   }
2256
2257   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
2258
2259   $main::lxdebug->leave_sub();
2260 }
2261
2262 sub _get_languages {
2263   $main::lxdebug->enter_sub();
2264
2265   my ($self, $dbh, $key) = @_;
2266
2267   $key = "all_languages" unless ($key);
2268
2269   my $query = qq|SELECT * FROM language ORDER BY id|;
2270
2271   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2272
2273   $main::lxdebug->leave_sub();
2274 }
2275
2276 sub _get_dunning_configs {
2277   $main::lxdebug->enter_sub();
2278
2279   my ($self, $dbh, $key) = @_;
2280
2281   $key = "all_dunning_configs" unless ($key);
2282
2283   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2284
2285   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2286
2287   $main::lxdebug->leave_sub();
2288 }
2289
2290 sub _get_currencies {
2291 $main::lxdebug->enter_sub();
2292
2293   my ($self, $dbh, $key) = @_;
2294
2295   $key = "all_currencies" unless ($key);
2296
2297   my $query = qq|SELECT curr AS currency FROM defaults|;
2298
2299   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2300
2301   $main::lxdebug->leave_sub();
2302 }
2303
2304 sub _get_payments {
2305 $main::lxdebug->enter_sub();
2306
2307   my ($self, $dbh, $key) = @_;
2308
2309   $key = "all_payments" unless ($key);
2310
2311   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
2312
2313   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2314
2315   $main::lxdebug->leave_sub();
2316 }
2317
2318 sub _get_customers {
2319   $main::lxdebug->enter_sub();
2320
2321   my ($self, $dbh, $key) = @_;
2322
2323   my $options        = ref $key eq 'HASH' ? $key : { key => $key };
2324   $options->{key}  ||= "all_customers";
2325   my $limit_clause   = "LIMIT $options->{limit}" if $options->{limit};
2326   my $where          = $options->{business_is_salesman} ? qq| AND business_id IN (SELECT id FROM business WHERE salesman)| : '';
2327
2328   my $query = qq|SELECT * FROM customer WHERE NOT obsolete $where ORDER BY name $limit_clause|;
2329   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
2330
2331   $main::lxdebug->leave_sub();
2332 }
2333
2334 sub _get_vendors {
2335   $main::lxdebug->enter_sub();
2336
2337   my ($self, $dbh, $key) = @_;
2338
2339   $key = "all_vendors" unless ($key);
2340
2341   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2342
2343   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2344
2345   $main::lxdebug->leave_sub();
2346 }
2347
2348 sub _get_departments {
2349   $main::lxdebug->enter_sub();
2350
2351   my ($self, $dbh, $key) = @_;
2352
2353   $key = "all_departments" unless ($key);
2354
2355   my $query = qq|SELECT * FROM department ORDER BY description|;
2356
2357   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2358
2359   $main::lxdebug->leave_sub();
2360 }
2361
2362 sub _get_warehouses {
2363   $main::lxdebug->enter_sub();
2364
2365   my ($self, $dbh, $param) = @_;
2366
2367   my ($key, $bins_key);
2368
2369   if ('' eq ref $param) {
2370     $key = $param;
2371
2372   } else {
2373     $key      = $param->{key};
2374     $bins_key = $param->{bins};
2375   }
2376
2377   my $query = qq|SELECT w.* FROM warehouse w
2378                  WHERE (NOT w.invalid) AND
2379                    ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2380                  ORDER BY w.sortkey|;
2381
2382   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2383
2384   if ($bins_key) {
2385     $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
2386     my $sth = prepare_query($self, $dbh, $query);
2387
2388     foreach my $warehouse (@{ $self->{$key} }) {
2389       do_statement($self, $sth, $query, $warehouse->{id});
2390       $warehouse->{$bins_key} = [];
2391
2392       while (my $ref = $sth->fetchrow_hashref()) {
2393         push @{ $warehouse->{$bins_key} }, $ref;
2394       }
2395     }
2396     $sth->finish();
2397   }
2398
2399   $main::lxdebug->leave_sub();
2400 }
2401
2402 sub _get_simple {
2403   $main::lxdebug->enter_sub();
2404
2405   my ($self, $dbh, $table, $key, $sortkey) = @_;
2406
2407   my $query  = qq|SELECT * FROM $table|;
2408   $query    .= qq| ORDER BY $sortkey| if ($sortkey);
2409
2410   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2411
2412   $main::lxdebug->leave_sub();
2413 }
2414
2415 #sub _get_groups {
2416 #  $main::lxdebug->enter_sub();
2417 #
2418 #  my ($self, $dbh, $key) = @_;
2419 #
2420 #  $key ||= "all_groups";
2421 #
2422 #  my $groups = $main::auth->read_groups();
2423 #
2424 #  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2425 #
2426 #  $main::lxdebug->leave_sub();
2427 #}
2428
2429 sub get_lists {
2430   $main::lxdebug->enter_sub();
2431
2432   my $self = shift;
2433   my %params = @_;
2434
2435   my $dbh = $self->get_standard_dbh(\%main::myconfig);
2436   my ($sth, $query, $ref);
2437
2438   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2439   my $vc_id = $self->{"${vc}_id"};
2440
2441   if ($params{"contacts"}) {
2442     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2443   }
2444
2445   if ($params{"shipto"}) {
2446     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2447   }
2448
2449   if ($params{"projects"} || $params{"all_projects"}) {
2450     $self->_get_projects($dbh, $params{"all_projects"} ?
2451                          $params{"all_projects"} : $params{"projects"},
2452                          $params{"all_projects"} ? 1 : 0);
2453   }
2454
2455   if ($params{"printers"}) {
2456     $self->_get_printers($dbh, $params{"printers"});
2457   }
2458
2459   if ($params{"languages"}) {
2460     $self->_get_languages($dbh, $params{"languages"});
2461   }
2462
2463   if ($params{"charts"}) {
2464     $self->_get_charts($dbh, $params{"charts"});
2465   }
2466
2467   if ($params{"taxcharts"}) {
2468     $self->_get_taxcharts($dbh, $params{"taxcharts"});
2469   }
2470
2471   if ($params{"taxzones"}) {
2472     $self->_get_taxzones($dbh, $params{"taxzones"});
2473   }
2474
2475   if ($params{"employees"}) {
2476     $self->_get_employees($dbh, "all_employees", $params{"employees"});
2477   }
2478
2479   if ($params{"salesmen"}) {
2480     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2481   }
2482
2483   if ($params{"business_types"}) {
2484     $self->_get_business_types($dbh, $params{"business_types"});
2485   }
2486
2487   if ($params{"dunning_configs"}) {
2488     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2489   }
2490
2491   if($params{"currencies"}) {
2492     $self->_get_currencies($dbh, $params{"currencies"});
2493   }
2494
2495   if($params{"customers"}) {
2496     $self->_get_customers($dbh, $params{"customers"});
2497   }
2498
2499   if($params{"vendors"}) {
2500     if (ref $params{"vendors"} eq 'HASH') {
2501       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2502     } else {
2503       $self->_get_vendors($dbh, $params{"vendors"});
2504     }
2505   }
2506
2507   if($params{"payments"}) {
2508     $self->_get_payments($dbh, $params{"payments"});
2509   }
2510
2511   if($params{"departments"}) {
2512     $self->_get_departments($dbh, $params{"departments"});
2513   }
2514
2515   if ($params{price_factors}) {
2516     $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2517   }
2518
2519   if ($params{warehouses}) {
2520     $self->_get_warehouses($dbh, $params{warehouses});
2521   }
2522
2523 #  if ($params{groups}) {
2524 #    $self->_get_groups($dbh, $params{groups});
2525 #  }
2526
2527   if ($params{partsgroup}) {
2528     $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2529   }
2530
2531   $main::lxdebug->leave_sub();
2532 }
2533
2534 # this sub gets the id and name from $table
2535 sub get_name {
2536   $main::lxdebug->enter_sub();
2537
2538   my ($self, $myconfig, $table) = @_;
2539
2540   # connect to database
2541   my $dbh = $self->get_standard_dbh($myconfig);
2542
2543   $table = $table eq "customer" ? "customer" : "vendor";
2544   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2545
2546   my ($query, @values);
2547
2548   if (!$self->{openinvoices}) {
2549     my $where;
2550     if ($self->{customernumber} ne "") {
2551       $where = qq|(vc.customernumber ILIKE ?)|;
2552       push(@values, '%' . $self->{customernumber} . '%');
2553     } else {
2554       $where = qq|(vc.name ILIKE ?)|;
2555       push(@values, '%' . $self->{$table} . '%');
2556     }
2557
2558     $query =
2559       qq~SELECT vc.id, vc.name,
2560            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2561          FROM $table vc
2562          WHERE $where AND (NOT vc.obsolete)
2563          ORDER BY vc.name~;
2564   } else {
2565     $query =
2566       qq~SELECT DISTINCT vc.id, vc.name,
2567            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2568          FROM $arap a
2569          JOIN $table vc ON (a.${table}_id = vc.id)
2570          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2571          ORDER BY vc.name~;
2572     push(@values, '%' . $self->{$table} . '%');
2573   }
2574
2575   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2576
2577   $main::lxdebug->leave_sub();
2578
2579   return scalar(@{ $self->{name_list} });
2580 }
2581
2582 # the selection sub is used in the AR, AP, IS, IR and OE module
2583 #
2584 sub all_vc {
2585   $main::lxdebug->enter_sub();
2586
2587   my ($self, $myconfig, $table, $module) = @_;
2588
2589   my $ref;
2590   my $dbh = $self->get_standard_dbh($myconfig);
2591
2592   $table = $table eq "customer" ? "customer" : "vendor";
2593
2594   my $query = qq|SELECT count(*) FROM $table|;
2595   my ($count) = selectrow_query($self, $dbh, $query);
2596
2597   # build selection list
2598   if ($count <= $myconfig->{vclimit}) {
2599     $query = qq|SELECT id, name, salesman_id
2600                 FROM $table WHERE NOT obsolete
2601                 ORDER BY name|;
2602     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2603   }
2604
2605   # get self
2606   $self->get_employee($dbh);
2607
2608   # setup sales contacts
2609   $query = qq|SELECT e.id, e.name
2610               FROM employee e
2611               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2612   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2613
2614   # this is for self
2615   push(@{ $self->{all_employees} },
2616        { id   => $self->{employee_id},
2617          name => $self->{employee} });
2618
2619   # sort the whole thing
2620   @{ $self->{all_employees} } =
2621     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2622
2623   if ($module eq 'AR') {
2624
2625     # prepare query for departments
2626     $query = qq|SELECT id, description
2627                 FROM department
2628                 WHERE role = 'P'
2629                 ORDER BY description|;
2630
2631   } else {
2632     $query = qq|SELECT id, description
2633                 FROM department
2634                 ORDER BY description|;
2635   }
2636
2637   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2638
2639   # get languages
2640   $query = qq|SELECT id, description
2641               FROM language
2642               ORDER BY id|;
2643
2644   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2645
2646   # get printer
2647   $query = qq|SELECT printer_description, id
2648               FROM printers
2649               ORDER BY printer_description|;
2650
2651   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2652
2653   # get payment terms
2654   $query = qq|SELECT id, description
2655               FROM payment_terms
2656               ORDER BY sortkey|;
2657
2658   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2659
2660   $main::lxdebug->leave_sub();
2661 }
2662
2663 sub language_payment {
2664   $main::lxdebug->enter_sub();
2665
2666   my ($self, $myconfig) = @_;
2667
2668   my $dbh = $self->get_standard_dbh($myconfig);
2669   # get languages
2670   my $query = qq|SELECT id, description
2671                  FROM language
2672                  ORDER BY id|;
2673
2674   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2675
2676   # get printer
2677   $query = qq|SELECT printer_description, id
2678               FROM printers
2679               ORDER BY printer_description|;
2680
2681   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2682
2683   # get payment terms
2684   $query = qq|SELECT id, description
2685               FROM payment_terms
2686               ORDER BY sortkey|;
2687
2688   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2689
2690   # get buchungsgruppen
2691   $query = qq|SELECT id, description
2692               FROM buchungsgruppen|;
2693
2694   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2695
2696   $main::lxdebug->leave_sub();
2697 }
2698
2699 # this is only used for reports
2700 sub all_departments {
2701   $main::lxdebug->enter_sub();
2702
2703   my ($self, $myconfig, $table) = @_;
2704
2705   my $dbh = $self->get_standard_dbh($myconfig);
2706   my $where;
2707
2708   if ($table eq 'customer') {
2709     $where = "WHERE role = 'P' ";
2710   }
2711
2712   my $query = qq|SELECT id, description
2713                  FROM department
2714                  $where
2715                  ORDER BY description|;
2716   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2717
2718   delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2719
2720   $main::lxdebug->leave_sub();
2721 }
2722
2723 sub create_links {
2724   $main::lxdebug->enter_sub();
2725
2726   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2727
2728   my ($fld, $arap);
2729   if ($table eq "customer") {
2730     $fld = "buy";
2731     $arap = "ar";
2732   } else {
2733     $table = "vendor";
2734     $fld = "sell";
2735     $arap = "ap";
2736   }
2737
2738   $self->all_vc($myconfig, $table, $module);
2739
2740   # get last customers or vendors
2741   my ($query, $sth, $ref);
2742
2743   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2744   my %xkeyref = ();
2745
2746   if (!$self->{id}) {
2747
2748     my $transdate = "current_date";
2749     if ($self->{transdate}) {
2750       $transdate = $dbh->quote($self->{transdate});
2751     }
2752
2753     # now get the account numbers
2754     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2755                 FROM chart c, taxkeys tk
2756                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2757                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2758                 ORDER BY c.accno|;
2759
2760     $sth = $dbh->prepare($query);
2761
2762     do_statement($self, $sth, $query, '%' . $module . '%');
2763
2764     $self->{accounts} = "";
2765     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2766
2767       foreach my $key (split(/:/, $ref->{link})) {
2768         if ($key =~ /\Q$module\E/) {
2769
2770           # cross reference for keys
2771           $xkeyref{ $ref->{accno} } = $key;
2772
2773           push @{ $self->{"${module}_links"}{$key} },
2774             { accno       => $ref->{accno},
2775               description => $ref->{description},
2776               taxkey      => $ref->{taxkey_id},
2777               tax_id      => $ref->{tax_id} };
2778
2779           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2780         }
2781       }
2782     }
2783   }
2784
2785   # get taxkeys and description
2786   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2787   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2788
2789   if (($module eq "AP") || ($module eq "AR")) {
2790     # get tax rates and description
2791     $query = qq|SELECT * FROM tax|;
2792     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2793   }
2794
2795   if ($self->{id}) {
2796     $query =
2797       qq|SELECT
2798            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2799            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2800            a.intnotes, a.department_id, a.amount AS oldinvtotal,
2801            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2802            c.name AS $table,
2803            d.description AS department,
2804            e.name AS employee
2805          FROM $arap a
2806          JOIN $table c ON (a.${table}_id = c.id)
2807          LEFT JOIN employee e ON (e.id = a.employee_id)
2808          LEFT JOIN department d ON (d.id = a.department_id)
2809          WHERE a.id = ?|;
2810     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2811
2812     foreach my $key (keys %$ref) {
2813       $self->{$key} = $ref->{$key};
2814     }
2815
2816     my $transdate = "current_date";
2817     if ($self->{transdate}) {
2818       $transdate = $dbh->quote($self->{transdate});
2819     }
2820
2821     # now get the account numbers
2822     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2823                 FROM chart c
2824                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2825                 WHERE c.link LIKE ?
2826                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2827                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2828                 ORDER BY c.accno|;
2829
2830     $sth = $dbh->prepare($query);
2831     do_statement($self, $sth, $query, "%$module%");
2832
2833     $self->{accounts} = "";
2834     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2835
2836       foreach my $key (split(/:/, $ref->{link})) {
2837         if ($key =~ /\Q$module\E/) {
2838
2839           # cross reference for keys
2840           $xkeyref{ $ref->{accno} } = $key;
2841
2842           push @{ $self->{"${module}_links"}{$key} },
2843             { accno       => $ref->{accno},
2844               description => $ref->{description},
2845               taxkey      => $ref->{taxkey_id},
2846               tax_id      => $ref->{tax_id} };
2847
2848           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2849         }
2850       }
2851     }
2852
2853
2854     # get amounts from individual entries
2855     $query =
2856       qq|SELECT
2857            c.accno, c.description,
2858            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2859            p.projectnumber,
2860            t.rate, t.id
2861          FROM acc_trans a
2862          LEFT JOIN chart c ON (c.id = a.chart_id)
2863          LEFT JOIN project p ON (p.id = a.project_id)
2864          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2865                                     WHERE (tk.taxkey_id=a.taxkey) AND
2866                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2867                                         THEN tk.chart_id = a.chart_id
2868                                         ELSE 1 = 1
2869                                         END)
2870                                        OR (c.link='%tax%')) AND
2871                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2872          WHERE a.trans_id = ?
2873          AND a.fx_transaction = '0'
2874          ORDER BY a.acc_trans_id, a.transdate|;
2875     $sth = $dbh->prepare($query);
2876     do_statement($self, $sth, $query, $self->{id});
2877
2878     # get exchangerate for currency
2879     $self->{exchangerate} =
2880       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2881     my $index = 0;
2882
2883     # store amounts in {acc_trans}{$key} for multiple accounts
2884     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2885       $ref->{exchangerate} =
2886         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2887       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2888         $index++;
2889       }
2890       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2891         $ref->{amount} *= -1;
2892       }
2893       $ref->{index} = $index;
2894
2895       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2896     }
2897
2898     $sth->finish;
2899     $query =
2900       qq|SELECT
2901            d.curr AS currencies, d.closedto, d.revtrans,
2902            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2903            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2904          FROM defaults d|;
2905     $ref = selectfirst_hashref_query($self, $dbh, $query);
2906     map { $self->{$_} = $ref->{$_} } keys %$ref;
2907
2908   } else {
2909
2910     # get date
2911     $query =
2912        qq|SELECT
2913             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2914             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2915             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2916           FROM defaults d|;
2917     $ref = selectfirst_hashref_query($self, $dbh, $query);
2918     map { $self->{$_} = $ref->{$_} } keys %$ref;
2919
2920     if ($self->{"$self->{vc}_id"}) {
2921
2922       # only setup currency
2923       ($self->{currency}) = split(/:/, $self->{currencies});
2924
2925     } else {
2926
2927       $self->lastname_used($dbh, $myconfig, $table, $module);
2928
2929       # get exchangerate for currency
2930       $self->{exchangerate} =
2931         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2932
2933     }
2934
2935   }
2936
2937   $main::lxdebug->leave_sub();
2938 }
2939
2940 sub lastname_used {
2941   $main::lxdebug->enter_sub();
2942
2943   my ($self, $dbh, $myconfig, $table, $module) = @_;
2944
2945   my ($arap, $where);
2946
2947   $table         = $table eq "customer" ? "customer" : "vendor";
2948   my %column_map = ("a.curr"                  => "currency",
2949                     "a.${table}_id"           => "${table}_id",
2950                     "a.department_id"         => "department_id",
2951                     "d.description"           => "department",
2952                     "ct.name"                 => $table,
2953                     "current_date + ct.terms" => "duedate",
2954     );
2955
2956   if ($self->{type} =~ /delivery_order/) {
2957     $arap  = 'delivery_orders';
2958     delete $column_map{"a.curr"};
2959
2960   } elsif ($self->{type} =~ /_order/) {
2961     $arap  = 'oe';
2962     $where = "quotation = '0'";
2963
2964   } elsif ($self->{type} =~ /_quotation/) {
2965     $arap  = 'oe';
2966     $where = "quotation = '1'";
2967
2968   } elsif ($table eq 'customer') {
2969     $arap  = 'ar';
2970
2971   } else {
2972     $arap  = 'ap';
2973
2974   }
2975
2976   $where           = "($where) AND" if ($where);
2977   my $query        = qq|SELECT MAX(id) FROM $arap
2978                         WHERE $where ${table}_id > 0|;
2979   my ($trans_id)   = selectrow_query($self, $dbh, $query);
2980   $trans_id       *= 1;
2981
2982   my $column_spec  = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2983   $query           = qq|SELECT $column_spec
2984                         FROM $arap a
2985                         LEFT JOIN $table     ct ON (a.${table}_id = ct.id)
2986                         LEFT JOIN department d  ON (a.department_id = d.id)
2987                         WHERE a.id = ?|;
2988   my $ref          = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
2989
2990   map { $self->{$_} = $ref->{$_} } values %column_map;
2991
2992   $main::lxdebug->leave_sub();
2993 }
2994
2995 sub current_date {
2996   $main::lxdebug->enter_sub();
2997
2998   my $self              = shift;
2999   my $myconfig          = shift  || \%::myconfig;
3000   my ($thisdate, $days) = @_;
3001
3002   my $dbh = $self->get_standard_dbh($myconfig);
3003   my $query;
3004
3005   $days *= 1;
3006   if ($thisdate) {
3007     my $dateformat = $myconfig->{dateformat};
3008     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
3009     $thisdate = $dbh->quote($thisdate);
3010     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
3011   } else {
3012     $query = qq|SELECT current_date AS thisdate|;
3013   }
3014
3015   ($thisdate) = selectrow_query($self, $dbh, $query);
3016
3017   $main::lxdebug->leave_sub();
3018
3019   return $thisdate;
3020 }
3021
3022 sub like {
3023   $main::lxdebug->enter_sub();
3024
3025   my ($self, $string) = @_;
3026
3027   if ($string !~ /%/) {
3028     $string = "%$string%";
3029   }
3030
3031   $string =~ s/\'/\'\'/g;
3032
3033   $main::lxdebug->leave_sub();
3034
3035   return $string;
3036 }
3037
3038 sub redo_rows {
3039   $main::lxdebug->enter_sub();
3040
3041   my ($self, $flds, $new, $count, $numrows) = @_;
3042
3043   my @ndx = ();
3044
3045   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
3046
3047   my $i = 0;
3048
3049   # fill rows
3050   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
3051     $i++;
3052     my $j = $item->{ndx} - 1;
3053     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
3054   }
3055
3056   # delete empty rows
3057   for $i ($count + 1 .. $numrows) {
3058     map { delete $self->{"${_}_$i"} } @{$flds};
3059   }
3060
3061   $main::lxdebug->leave_sub();
3062 }
3063
3064 sub update_status {
3065   $main::lxdebug->enter_sub();
3066
3067   my ($self, $myconfig) = @_;
3068
3069   my ($i, $id);
3070
3071   my $dbh = $self->dbconnect_noauto($myconfig);
3072
3073   my $query = qq|DELETE FROM status
3074                  WHERE (formname = ?) AND (trans_id = ?)|;
3075   my $sth = prepare_query($self, $dbh, $query);
3076
3077   if ($self->{formname} =~ /(check|receipt)/) {
3078     for $i (1 .. $self->{rowcount}) {
3079       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
3080     }
3081   } else {
3082     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
3083   }
3084   $sth->finish();
3085
3086   my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3087   my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3088
3089   my %queued = split / /, $self->{queued};
3090   my @values;
3091
3092   if ($self->{formname} =~ /(check|receipt)/) {
3093
3094     # this is a check or receipt, add one entry for each lineitem
3095     my ($accno) = split /--/, $self->{account};
3096     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3097                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3098     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3099     $sth = prepare_query($self, $dbh, $query);
3100
3101     for $i (1 .. $self->{rowcount}) {
3102       if ($self->{"checked_$i"}) {
3103         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3104       }
3105     }
3106     $sth->finish();
3107
3108   } else {
3109     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3110                 VALUES (?, ?, ?, ?, ?)|;
3111     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3112              $queued{$self->{formname}}, $self->{formname});
3113   }
3114
3115   $dbh->commit;
3116   $dbh->disconnect;
3117
3118   $main::lxdebug->leave_sub();
3119 }
3120
3121 sub save_status {
3122   $main::lxdebug->enter_sub();
3123
3124   my ($self, $dbh) = @_;
3125
3126   my ($query, $printed, $emailed);
3127
3128   my $formnames  = $self->{printed};
3129   my $emailforms = $self->{emailed};
3130
3131   $query = qq|DELETE FROM status
3132                  WHERE (formname = ?) AND (trans_id = ?)|;
3133   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3134
3135   # this only applies to the forms
3136   # checks and receipts are posted when printed or queued
3137
3138   if ($self->{queued}) {
3139     my %queued = split / /, $self->{queued};
3140
3141     foreach my $formname (keys %queued) {
3142       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3143       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3144
3145       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3146                   VALUES (?, ?, ?, ?, ?)|;
3147       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3148
3149       $formnames  =~ s/\Q$self->{formname}\E//;
3150       $emailforms =~ s/\Q$self->{formname}\E//;
3151
3152     }
3153   }
3154
3155   # save printed, emailed info
3156   $formnames  =~ s/^ +//g;
3157   $emailforms =~ s/^ +//g;
3158
3159   my %status = ();
3160   map { $status{$_}{printed} = 1 } split / +/, $formnames;
3161   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3162
3163   foreach my $formname (keys %status) {
3164     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
3165     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3166
3167     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3168                 VALUES (?, ?, ?, ?)|;
3169     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3170   }
3171
3172   $main::lxdebug->leave_sub();
3173 }
3174
3175 #--- 4 locale ---#
3176 # $main::locale->text('SAVED')
3177 # $main::locale->text('DELETED')
3178 # $main::locale->text('ADDED')
3179 # $main::locale->text('PAYMENT POSTED')
3180 # $main::locale->text('POSTED')
3181 # $main::locale->text('POSTED AS NEW')
3182 # $main::locale->text('ELSE')
3183 # $main::locale->text('SAVED FOR DUNNING')
3184 # $main::locale->text('DUNNING STARTED')
3185 # $main::locale->text('PRINTED')
3186 # $main::locale->text('MAILED')
3187 # $main::locale->text('SCREENED')
3188 # $main::locale->text('CANCELED')
3189 # $main::locale->text('invoice')
3190 # $main::locale->text('proforma')
3191 # $main::locale->text('sales_order')
3192 # $main::locale->text('packing_list')
3193 # $main::locale->text('pick_list')
3194 # $main::locale->text('purchase_order')
3195 # $main::locale->text('bin_list')
3196 # $main::locale->text('sales_quotation')
3197 # $main::locale->text('request_quotation')
3198
3199 sub save_history {
3200   $main::lxdebug->enter_sub();
3201
3202   my $self = shift();
3203   my $dbh = shift();
3204
3205   if(!exists $self->{employee_id}) {
3206     &get_employee($self, $dbh);
3207   }
3208
3209   my $query =
3210    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3211    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3212   my @values = (conv_i($self->{id}), $self->{login},
3213                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3214   do_query($self, $dbh, $query, @values);
3215
3216   $main::lxdebug->leave_sub();
3217 }
3218
3219 sub get_history {
3220   $main::lxdebug->enter_sub();
3221
3222   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3223   my ($orderBy, $desc) = split(/\-\-/, $order);
3224   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3225   my @tempArray;
3226   my $i = 0;
3227   if ($trans_id ne "") {
3228     my $query =
3229       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 | .
3230       qq|FROM history_erp h | .
3231       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3232       qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3233       $order;
3234
3235     my $sth = $dbh->prepare($query) || $self->dberror($query);
3236
3237     $sth->execute() || $self->dberror("$query");
3238
3239     while(my $hash_ref = $sth->fetchrow_hashref()) {
3240       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3241       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3242       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3243       $tempArray[$i++] = $hash_ref;
3244     }
3245     $main::lxdebug->leave_sub() and return \@tempArray
3246       if ($i > 0 && $tempArray[0] ne "");
3247   }
3248   $main::lxdebug->leave_sub();
3249   return 0;
3250 }
3251
3252 sub update_defaults {
3253   $main::lxdebug->enter_sub();
3254
3255   my ($self, $myconfig, $fld, $provided_dbh) = @_;
3256
3257   my $dbh;
3258   if ($provided_dbh) {
3259     $dbh = $provided_dbh;
3260   } else {
3261     $dbh = $self->dbconnect_noauto($myconfig);
3262   }
3263   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3264   my $sth   = $dbh->prepare($query);
3265
3266   $sth->execute || $self->dberror($query);
3267   my ($var) = $sth->fetchrow_array;
3268   $sth->finish;
3269
3270   if ($var =~ m/\d+$/) {
3271     my $new_var  = (substr $var, $-[0]) * 1 + 1;
3272     my $len_diff = length($var) - $-[0] - length($new_var);
3273     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3274
3275   } else {
3276     $var = $var . '1';
3277   }
3278
3279   $query = qq|UPDATE defaults SET $fld = ?|;
3280   do_query($self, $dbh, $query, $var);
3281
3282   if (!$provided_dbh) {
3283     $dbh->commit;
3284     $dbh->disconnect;
3285   }
3286
3287   $main::lxdebug->leave_sub();
3288
3289   return $var;
3290 }
3291
3292 sub update_business {
3293   $main::lxdebug->enter_sub();
3294
3295   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3296
3297   my $dbh;
3298   if ($provided_dbh) {
3299     $dbh = $provided_dbh;
3300   } else {
3301     $dbh = $self->dbconnect_noauto($myconfig);
3302   }
3303   my $query =
3304     qq|SELECT customernumberinit FROM business
3305        WHERE id = ? FOR UPDATE|;
3306   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3307
3308   return undef unless $var;
3309
3310   if ($var =~ m/\d+$/) {
3311     my $new_var  = (substr $var, $-[0]) * 1 + 1;
3312     my $len_diff = length($var) - $-[0] - length($new_var);
3313     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3314
3315   } else {
3316     $var = $var . '1';
3317   }
3318
3319   $query = qq|UPDATE business
3320               SET customernumberinit = ?
3321               WHERE id = ?|;
3322   do_query($self, $dbh, $query, $var, $business_id);
3323
3324   if (!$provided_dbh) {
3325     $dbh->commit;
3326     $dbh->disconnect;
3327   }
3328
3329   $main::lxdebug->leave_sub();
3330
3331   return $var;
3332 }
3333
3334 sub get_partsgroup {
3335   $main::lxdebug->enter_sub();
3336
3337   my ($self, $myconfig, $p) = @_;
3338   my $target = $p->{target} || 'all_partsgroup';
3339
3340   my $dbh = $self->get_standard_dbh($myconfig);
3341
3342   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3343                  FROM partsgroup pg
3344                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
3345   my @values;
3346
3347   if ($p->{searchitems} eq 'part') {
3348     $query .= qq|WHERE p.inventory_accno_id > 0|;
3349   }
3350   if ($p->{searchitems} eq 'service') {
3351     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3352   }
3353   if ($p->{searchitems} eq 'assembly') {
3354     $query .= qq|WHERE p.assembly = '1'|;
3355   }
3356   if ($p->{searchitems} eq 'labor') {
3357     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3358   }
3359
3360   $query .= qq|ORDER BY partsgroup|;
3361
3362   if ($p->{all}) {
3363     $query = qq|SELECT id, partsgroup FROM partsgroup
3364                 ORDER BY partsgroup|;
3365   }
3366
3367   if ($p->{language_code}) {
3368     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3369                   t.description AS translation
3370                 FROM partsgroup pg
3371                 JOIN parts p ON (p.partsgroup_id = pg.id)
3372                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3373                 ORDER BY translation|;
3374     @values = ($p->{language_code});
3375   }
3376
3377   $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3378
3379   $main::lxdebug->leave_sub();
3380 }
3381
3382 sub get_pricegroup {
3383   $main::lxdebug->enter_sub();
3384
3385   my ($self, $myconfig, $p) = @_;
3386
3387   my $dbh = $self->get_standard_dbh($myconfig);
3388
3389   my $query = qq|SELECT p.id, p.pricegroup
3390                  FROM pricegroup p|;
3391
3392   $query .= qq| ORDER BY pricegroup|;
3393
3394   if ($p->{all}) {
3395     $query = qq|SELECT id, pricegroup FROM pricegroup
3396                 ORDER BY pricegroup|;
3397   }
3398
3399   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3400
3401   $main::lxdebug->leave_sub();
3402 }
3403
3404 sub all_years {
3405 # usage $form->all_years($myconfig, [$dbh])
3406 # return list of all years where bookings found
3407 # (@all_years)
3408
3409   $main::lxdebug->enter_sub();
3410
3411   my ($self, $myconfig, $dbh) = @_;
3412
3413   $dbh ||= $self->get_standard_dbh($myconfig);
3414
3415   # get years
3416   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3417                    (SELECT MAX(transdate) FROM acc_trans)|;
3418   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3419
3420   if ($myconfig->{dateformat} =~ /^yy/) {
3421     ($startdate) = split /\W/, $startdate;
3422     ($enddate) = split /\W/, $enddate;
3423   } else {
3424     (@_) = split /\W/, $startdate;
3425     $startdate = $_[2];
3426     (@_) = split /\W/, $enddate;
3427     $enddate = $_[2];
3428   }
3429
3430   my @all_years;
3431   $startdate = substr($startdate,0,4);
3432   $enddate = substr($enddate,0,4);
3433
3434   while ($enddate >= $startdate) {
3435     push @all_years, $enddate--;
3436   }
3437
3438   return @all_years;
3439
3440   $main::lxdebug->leave_sub();
3441 }
3442
3443 sub backup_vars {
3444   $main::lxdebug->enter_sub();
3445   my $self = shift;
3446   my @vars = @_;
3447
3448   map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3449
3450   $main::lxdebug->leave_sub();
3451 }
3452
3453 sub restore_vars {
3454   $main::lxdebug->enter_sub();
3455
3456   my $self = shift;
3457   my @vars = @_;
3458
3459   map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3460
3461   $main::lxdebug->leave_sub();
3462 }
3463
3464 1;
3465
3466 __END__
3467
3468 =head1 NAME
3469
3470 SL::Form.pm - main data object.
3471
3472 =head1 SYNOPSIS
3473
3474 This is the main data object of Lx-Office.
3475 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3476 Points of interest for a beginner are:
3477
3478  - $form->error            - renders a generic error in html. accepts an error message
3479  - $form->get_standard_dbh - returns a database connection for the
3480
3481 =head1 SPECIAL FUNCTIONS
3482
3483 =over 4
3484
3485 =item _store_value()
3486
3487 parses a complex var name, and stores it in the form.
3488
3489 syntax:
3490   $form->_store_value($key, $value);
3491
3492 keys must start with a string, and can contain various tokens.
3493 supported key structures are:
3494
3495 1. simple access
3496   simple key strings work as expected
3497
3498   id => $form->{id}
3499
3500 2. hash access.
3501   separating two keys by a dot (.) will result in a hash lookup for the inner value
3502   this is similar to the behaviour of java and templating mechanisms.
3503
3504   filter.description => $form->{filter}->{description}
3505
3506 3. array+hashref access
3507
3508   adding brackets ([]) before the dot will cause the next hash to be put into an array.
3509   using [+] instead of [] will force a new array index. this is useful for recurring
3510   data structures like part lists. put a [+] into the first varname, and use [] on the
3511   following ones.
3512
3513   repeating these names in your template:
3514
3515     invoice.items[+].id
3516     invoice.items[].parts_id
3517
3518   will result in:
3519
3520     $form->{invoice}->{items}->[
3521       {
3522         id       => ...
3523         parts_id => ...
3524       },
3525       {
3526         id       => ...
3527         parts_id => ...
3528       }
3529       ...
3530     ]
3531
3532 4. arrays
3533
3534   using brackets at the end of a name will result in a pure array to be created.
3535   note that you mustn't use [+], which is reserved for array+hash access and will
3536   result in undefined behaviour in array context.
3537
3538   filter.status[]  => $form->{status}->[ val1, val2, ... ]
3539
3540 =item update_business PARAMS
3541
3542 PARAMS (not named):
3543  \%config,     - config hashref
3544  $business_id, - business id
3545  $dbh          - optional database handle
3546
3547 handles business (thats customer/vendor types) sequences.
3548
3549 special behaviour for empty strings in customerinitnumber field:
3550 will in this case not increase the value, and return undef.
3551
3552 =back
3553
3554 =cut