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