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