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