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