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