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