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