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