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