Zwei Funktionen, die als erstes Argument myconfig erwarten auf \%::myconfig defaulted.
[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     = shift;
1771   my $myconfig = shift || \%::myconfig;
1772   my $dbh      = $self->get_standard_dbh($myconfig);
1773
1774   my $query = qq|SELECT curr FROM defaults|;
1775
1776   my ($curr)     = selectrow_query($self, $dbh, $query);
1777   my @currencies = grep { $_ } map { s/\s//g; $_ } split m/:/, $curr;
1778
1779   $main::lxdebug->leave_sub();
1780
1781   return @currencies;
1782 }
1783
1784 sub get_default_currency {
1785   $main::lxdebug->enter_sub();
1786
1787   my ($self, $myconfig) = @_;
1788   my @currencies        = $self->get_all_currencies($myconfig);
1789
1790   $main::lxdebug->leave_sub();
1791
1792   return $currencies[0];
1793 }
1794
1795 sub set_payment_options {
1796   $main::lxdebug->enter_sub();
1797
1798   my ($self, $myconfig, $transdate) = @_;
1799
1800   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1801
1802   my $dbh = $self->get_standard_dbh($myconfig);
1803
1804   my $query =
1805     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1806     qq|FROM payment_terms p | .
1807     qq|WHERE p.id = ?|;
1808
1809   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1810    $self->{payment_terms}) =
1811      selectrow_query($self, $dbh, $query, $self->{payment_id});
1812
1813   if ($transdate eq "") {
1814     if ($self->{invdate}) {
1815       $transdate = $self->{invdate};
1816     } else {
1817       $transdate = $self->{transdate};
1818     }
1819   }
1820
1821   $query =
1822     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1823     qq|FROM payment_terms|;
1824   ($self->{netto_date}, $self->{skonto_date}) =
1825     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1826
1827   my ($invtotal, $total);
1828   my (%amounts, %formatted_amounts);
1829
1830   if ($self->{type} =~ /_order$/) {
1831     $amounts{invtotal} = $self->{ordtotal};
1832     $amounts{total}    = $self->{ordtotal};
1833
1834   } elsif ($self->{type} =~ /_quotation$/) {
1835     $amounts{invtotal} = $self->{quototal};
1836     $amounts{total}    = $self->{quototal};
1837
1838   } else {
1839     $amounts{invtotal} = $self->{invtotal};
1840     $amounts{total}    = $self->{total};
1841   }
1842   $amounts{skonto_in_percent} = 100.0 * $self->{percent_skonto};
1843
1844   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1845
1846   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
1847   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1848   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
1849
1850   foreach (keys %amounts) {
1851     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
1852     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1853   }
1854
1855   if ($self->{"language_id"}) {
1856     $query =
1857       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1858       qq|FROM translation_payment_terms t | .
1859       qq|LEFT JOIN language l ON t.language_id = l.id | .
1860       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1861     my ($description_long, $output_numberformat, $output_dateformat,
1862       $output_longdates) =
1863       selectrow_query($self, $dbh, $query,
1864                       $self->{"language_id"}, $self->{"payment_id"});
1865
1866     $self->{payment_terms} = $description_long if ($description_long);
1867
1868     if ($output_dateformat) {
1869       foreach my $key (qw(netto_date skonto_date)) {
1870         $self->{$key} =
1871           $main::locale->reformat_date($myconfig, $self->{$key},
1872                                        $output_dateformat,
1873                                        $output_longdates);
1874       }
1875     }
1876
1877     if ($output_numberformat &&
1878         ($output_numberformat ne $myconfig->{"numberformat"})) {
1879       my $saved_numberformat = $myconfig->{"numberformat"};
1880       $myconfig->{"numberformat"} = $output_numberformat;
1881       map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1882       $myconfig->{"numberformat"} = $saved_numberformat;
1883     }
1884   }
1885
1886   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1887   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1888   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1889   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1890   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1891   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1892   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1893
1894   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1895
1896   $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
1897
1898   $main::lxdebug->leave_sub();
1899
1900 }
1901
1902 sub get_template_language {
1903   $main::lxdebug->enter_sub();
1904
1905   my ($self, $myconfig) = @_;
1906
1907   my $template_code = "";
1908
1909   if ($self->{language_id}) {
1910     my $dbh = $self->get_standard_dbh($myconfig);
1911     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1912     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1913   }
1914
1915   $main::lxdebug->leave_sub();
1916
1917   return $template_code;
1918 }
1919
1920 sub get_printer_code {
1921   $main::lxdebug->enter_sub();
1922
1923   my ($self, $myconfig) = @_;
1924
1925   my $template_code = "";
1926
1927   if ($self->{printer_id}) {
1928     my $dbh = $self->get_standard_dbh($myconfig);
1929     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1930     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1931   }
1932
1933   $main::lxdebug->leave_sub();
1934
1935   return $template_code;
1936 }
1937
1938 sub get_shipto {
1939   $main::lxdebug->enter_sub();
1940
1941   my ($self, $myconfig) = @_;
1942
1943   my $template_code = "";
1944
1945   if ($self->{shipto_id}) {
1946     my $dbh = $self->get_standard_dbh($myconfig);
1947     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1948     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1949     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1950   }
1951
1952   $main::lxdebug->leave_sub();
1953 }
1954
1955 sub add_shipto {
1956   $main::lxdebug->enter_sub();
1957
1958   my ($self, $dbh, $id, $module) = @_;
1959
1960   my $shipto;
1961   my @values;
1962
1963   foreach my $item (qw(name department_1 department_2 street zipcode city country
1964                        contact phone fax email)) {
1965     if ($self->{"shipto$item"}) {
1966       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1967     }
1968     push(@values, $self->{"shipto${item}"});
1969   }
1970
1971   if ($shipto) {
1972     if ($self->{shipto_id}) {
1973       my $query = qq|UPDATE shipto set
1974                        shiptoname = ?,
1975                        shiptodepartment_1 = ?,
1976                        shiptodepartment_2 = ?,
1977                        shiptostreet = ?,
1978                        shiptozipcode = ?,
1979                        shiptocity = ?,
1980                        shiptocountry = ?,
1981                        shiptocontact = ?,
1982                        shiptophone = ?,
1983                        shiptofax = ?,
1984                        shiptoemail = ?
1985                      WHERE shipto_id = ?|;
1986       do_query($self, $dbh, $query, @values, $self->{shipto_id});
1987     } else {
1988       my $query = qq|SELECT * FROM shipto
1989                      WHERE shiptoname = ? AND
1990                        shiptodepartment_1 = ? AND
1991                        shiptodepartment_2 = ? AND
1992                        shiptostreet = ? AND
1993                        shiptozipcode = ? AND
1994                        shiptocity = ? AND
1995                        shiptocountry = ? AND
1996                        shiptocontact = ? AND
1997                        shiptophone = ? AND
1998                        shiptofax = ? AND
1999                        shiptoemail = ? AND
2000                        module = ? AND
2001                        trans_id = ?|;
2002       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
2003       if(!$insert_check){
2004         $query =
2005           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
2006                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
2007                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
2008              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
2009         do_query($self, $dbh, $query, $id, @values, $module);
2010       }
2011     }
2012   }
2013
2014   $main::lxdebug->leave_sub();
2015 }
2016
2017 sub get_employee {
2018   $main::lxdebug->enter_sub();
2019
2020   my ($self, $dbh) = @_;
2021
2022   $dbh ||= $self->get_standard_dbh(\%main::myconfig);
2023
2024   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
2025   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
2026   $self->{"employee_id"} *= 1;
2027
2028   $main::lxdebug->leave_sub();
2029 }
2030
2031 sub get_employee_data {
2032   $main::lxdebug->enter_sub();
2033
2034   my $self     = shift;
2035   my %params   = @_;
2036
2037   Common::check_params(\%params, qw(prefix));
2038   Common::check_params_x(\%params, qw(id));
2039
2040   if (!$params{id}) {
2041     $main::lxdebug->leave_sub();
2042     return;
2043   }
2044
2045   my $myconfig = \%main::myconfig;
2046   my $dbh      = $params{dbh} || $self->get_standard_dbh($myconfig);
2047
2048   my ($login)  = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
2049
2050   if ($login) {
2051     my $user = User->new($login);
2052     map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
2053
2054     $self->{$params{prefix} . '_login'}   = $login;
2055     $self->{$params{prefix} . '_name'}  ||= $login;
2056   }
2057
2058   $main::lxdebug->leave_sub();
2059 }
2060
2061 sub get_duedate {
2062   $main::lxdebug->enter_sub();
2063
2064   my ($self, $myconfig, $reference_date) = @_;
2065
2066   $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
2067
2068   my $dbh         = $self->get_standard_dbh($myconfig);
2069   my $query       = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
2070   my ($duedate)   = selectrow_query($self, $dbh, $query, $self->{payment_id});
2071
2072   $main::lxdebug->leave_sub();
2073
2074   return $duedate;
2075 }
2076
2077 sub _get_contacts {
2078   $main::lxdebug->enter_sub();
2079
2080   my ($self, $dbh, $id, $key) = @_;
2081
2082   $key = "all_contacts" unless ($key);
2083
2084   if (!$id) {
2085     $self->{$key} = [];
2086     $main::lxdebug->leave_sub();
2087     return;
2088   }
2089
2090   my $query =
2091     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
2092     qq|FROM contacts | .
2093     qq|WHERE cp_cv_id = ? | .
2094     qq|ORDER BY lower(cp_name)|;
2095
2096   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
2097
2098   $main::lxdebug->leave_sub();
2099 }
2100
2101 sub _get_projects {
2102   $main::lxdebug->enter_sub();
2103
2104   my ($self, $dbh, $key) = @_;
2105
2106   my ($all, $old_id, $where, @values);
2107
2108   if (ref($key) eq "HASH") {
2109     my $params = $key;
2110
2111     $key = "ALL_PROJECTS";
2112
2113     foreach my $p (keys(%{$params})) {
2114       if ($p eq "all") {
2115         $all = $params->{$p};
2116       } elsif ($p eq "old_id") {
2117         $old_id = $params->{$p};
2118       } elsif ($p eq "key") {
2119         $key = $params->{$p};
2120       }
2121     }
2122   }
2123
2124   if (!$all) {
2125     $where = "WHERE active ";
2126     if ($old_id) {
2127       if (ref($old_id) eq "ARRAY") {
2128         my @ids = grep({ $_ } @{$old_id});
2129         if (@ids) {
2130           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
2131           push(@values, @ids);
2132         }
2133       } else {
2134         $where .= " OR (id = ?) ";
2135         push(@values, $old_id);
2136       }
2137     }
2138   }
2139
2140   my $query =
2141     qq|SELECT id, projectnumber, description, active | .
2142     qq|FROM project | .
2143     $where .
2144     qq|ORDER BY lower(projectnumber)|;
2145
2146   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2147
2148   $main::lxdebug->leave_sub();
2149 }
2150
2151 sub _get_shipto {
2152   $main::lxdebug->enter_sub();
2153
2154   my ($self, $dbh, $vc_id, $key) = @_;
2155
2156   $key = "all_shipto" unless ($key);
2157
2158   if ($vc_id) {
2159     # get shipping addresses
2160     my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2161
2162     $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2163
2164   } else {
2165     $self->{$key} = [];
2166   }
2167
2168   $main::lxdebug->leave_sub();
2169 }
2170
2171 sub _get_printers {
2172   $main::lxdebug->enter_sub();
2173
2174   my ($self, $dbh, $key) = @_;
2175
2176   $key = "all_printers" unless ($key);
2177
2178   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2179
2180   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2181
2182   $main::lxdebug->leave_sub();
2183 }
2184
2185 sub _get_charts {
2186   $main::lxdebug->enter_sub();
2187
2188   my ($self, $dbh, $params) = @_;
2189   my ($key);
2190
2191   $key = $params->{key};
2192   $key = "all_charts" unless ($key);
2193
2194   my $transdate = quote_db_date($params->{transdate});
2195
2196   my $query =
2197     qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
2198     qq|FROM chart c | .
2199     qq|LEFT JOIN taxkeys tk ON | .
2200     qq|(tk.id = (SELECT id FROM taxkeys | .
2201     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2202     qq|          ORDER BY startdate DESC LIMIT 1)) | .
2203     qq|ORDER BY c.accno|;
2204
2205   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2206
2207   $main::lxdebug->leave_sub();
2208 }
2209
2210 sub _get_taxcharts {
2211   $main::lxdebug->enter_sub();
2212
2213   my ($self, $dbh, $params) = @_;
2214
2215   my $key = "all_taxcharts";
2216   my @where;
2217
2218   if (ref $params eq 'HASH') {
2219     $key = $params->{key} if ($params->{key});
2220     if ($params->{module} eq 'AR') {
2221       push @where, 'taxkey NOT IN (8, 9, 18, 19)';
2222
2223     } elsif ($params->{module} eq 'AP') {
2224       push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
2225     }
2226
2227   } elsif ($params) {
2228     $key = $params;
2229   }
2230
2231   my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
2232
2233   my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
2234
2235   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2236
2237   $main::lxdebug->leave_sub();
2238 }
2239
2240 sub _get_taxzones {
2241   $main::lxdebug->enter_sub();
2242
2243   my ($self, $dbh, $key) = @_;
2244
2245   $key = "all_taxzones" unless ($key);
2246
2247   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
2248
2249   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2250
2251   $main::lxdebug->leave_sub();
2252 }
2253
2254 sub _get_employees {
2255   $main::lxdebug->enter_sub();
2256
2257   my ($self, $dbh, $default_key, $key) = @_;
2258
2259   $key = $default_key unless ($key);
2260   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
2261
2262   $main::lxdebug->leave_sub();
2263 }
2264
2265 sub _get_business_types {
2266   $main::lxdebug->enter_sub();
2267
2268   my ($self, $dbh, $key) = @_;
2269
2270   my $options       = ref $key eq 'HASH' ? $key : { key => $key };
2271   $options->{key} ||= "all_business_types";
2272   my $where         = '';
2273
2274   if (exists $options->{salesman}) {
2275     $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
2276   }
2277
2278   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
2279
2280   $main::lxdebug->leave_sub();
2281 }
2282
2283 sub _get_languages {
2284   $main::lxdebug->enter_sub();
2285
2286   my ($self, $dbh, $key) = @_;
2287
2288   $key = "all_languages" unless ($key);
2289
2290   my $query = qq|SELECT * FROM language ORDER BY id|;
2291
2292   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2293
2294   $main::lxdebug->leave_sub();
2295 }
2296
2297 sub _get_dunning_configs {
2298   $main::lxdebug->enter_sub();
2299
2300   my ($self, $dbh, $key) = @_;
2301
2302   $key = "all_dunning_configs" unless ($key);
2303
2304   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2305
2306   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2307
2308   $main::lxdebug->leave_sub();
2309 }
2310
2311 sub _get_currencies {
2312 $main::lxdebug->enter_sub();
2313
2314   my ($self, $dbh, $key) = @_;
2315
2316   $key = "all_currencies" unless ($key);
2317
2318   my $query = qq|SELECT curr AS currency FROM defaults|;
2319
2320   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2321
2322   $main::lxdebug->leave_sub();
2323 }
2324
2325 sub _get_payments {
2326 $main::lxdebug->enter_sub();
2327
2328   my ($self, $dbh, $key) = @_;
2329
2330   $key = "all_payments" unless ($key);
2331
2332   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
2333
2334   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2335
2336   $main::lxdebug->leave_sub();
2337 }
2338
2339 sub _get_customers {
2340   $main::lxdebug->enter_sub();
2341
2342   my ($self, $dbh, $key) = @_;
2343
2344   my $options        = ref $key eq 'HASH' ? $key : { key => $key };
2345   $options->{key}  ||= "all_customers";
2346   my $limit_clause   = "LIMIT $options->{limit}" if $options->{limit};
2347   my $where          = $options->{business_is_salesman} ? qq| AND business_id IN (SELECT id FROM business WHERE salesman)| : '';
2348
2349   my $query = qq|SELECT * FROM customer WHERE NOT obsolete $where ORDER BY name $limit_clause|;
2350   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
2351
2352   $main::lxdebug->leave_sub();
2353 }
2354
2355 sub _get_vendors {
2356   $main::lxdebug->enter_sub();
2357
2358   my ($self, $dbh, $key) = @_;
2359
2360   $key = "all_vendors" unless ($key);
2361
2362   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2363
2364   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2365
2366   $main::lxdebug->leave_sub();
2367 }
2368
2369 sub _get_departments {
2370   $main::lxdebug->enter_sub();
2371
2372   my ($self, $dbh, $key) = @_;
2373
2374   $key = "all_departments" unless ($key);
2375
2376   my $query = qq|SELECT * FROM department ORDER BY description|;
2377
2378   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2379
2380   $main::lxdebug->leave_sub();
2381 }
2382
2383 sub _get_warehouses {
2384   $main::lxdebug->enter_sub();
2385
2386   my ($self, $dbh, $param) = @_;
2387
2388   my ($key, $bins_key);
2389
2390   if ('' eq ref $param) {
2391     $key = $param;
2392
2393   } else {
2394     $key      = $param->{key};
2395     $bins_key = $param->{bins};
2396   }
2397
2398   my $query = qq|SELECT w.* FROM warehouse w
2399                  WHERE (NOT w.invalid) AND
2400                    ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2401                  ORDER BY w.sortkey|;
2402
2403   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2404
2405   if ($bins_key) {
2406     $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
2407     my $sth = prepare_query($self, $dbh, $query);
2408
2409     foreach my $warehouse (@{ $self->{$key} }) {
2410       do_statement($self, $sth, $query, $warehouse->{id});
2411       $warehouse->{$bins_key} = [];
2412
2413       while (my $ref = $sth->fetchrow_hashref()) {
2414         push @{ $warehouse->{$bins_key} }, $ref;
2415       }
2416     }
2417     $sth->finish();
2418   }
2419
2420   $main::lxdebug->leave_sub();
2421 }
2422
2423 sub _get_simple {
2424   $main::lxdebug->enter_sub();
2425
2426   my ($self, $dbh, $table, $key, $sortkey) = @_;
2427
2428   my $query  = qq|SELECT * FROM $table|;
2429   $query    .= qq| ORDER BY $sortkey| if ($sortkey);
2430
2431   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2432
2433   $main::lxdebug->leave_sub();
2434 }
2435
2436 #sub _get_groups {
2437 #  $main::lxdebug->enter_sub();
2438 #
2439 #  my ($self, $dbh, $key) = @_;
2440 #
2441 #  $key ||= "all_groups";
2442 #
2443 #  my $groups = $main::auth->read_groups();
2444 #
2445 #  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2446 #
2447 #  $main::lxdebug->leave_sub();
2448 #}
2449
2450 sub get_lists {
2451   $main::lxdebug->enter_sub();
2452
2453   my $self = shift;
2454   my %params = @_;
2455
2456   my $dbh = $self->get_standard_dbh(\%main::myconfig);
2457   my ($sth, $query, $ref);
2458
2459   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2460   my $vc_id = $self->{"${vc}_id"};
2461
2462   if ($params{"contacts"}) {
2463     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2464   }
2465
2466   if ($params{"shipto"}) {
2467     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2468   }
2469
2470   if ($params{"projects"} || $params{"all_projects"}) {
2471     $self->_get_projects($dbh, $params{"all_projects"} ?
2472                          $params{"all_projects"} : $params{"projects"},
2473                          $params{"all_projects"} ? 1 : 0);
2474   }
2475
2476   if ($params{"printers"}) {
2477     $self->_get_printers($dbh, $params{"printers"});
2478   }
2479
2480   if ($params{"languages"}) {
2481     $self->_get_languages($dbh, $params{"languages"});
2482   }
2483
2484   if ($params{"charts"}) {
2485     $self->_get_charts($dbh, $params{"charts"});
2486   }
2487
2488   if ($params{"taxcharts"}) {
2489     $self->_get_taxcharts($dbh, $params{"taxcharts"});
2490   }
2491
2492   if ($params{"taxzones"}) {
2493     $self->_get_taxzones($dbh, $params{"taxzones"});
2494   }
2495
2496   if ($params{"employees"}) {
2497     $self->_get_employees($dbh, "all_employees", $params{"employees"});
2498   }
2499
2500   if ($params{"salesmen"}) {
2501     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2502   }
2503
2504   if ($params{"business_types"}) {
2505     $self->_get_business_types($dbh, $params{"business_types"});
2506   }
2507
2508   if ($params{"dunning_configs"}) {
2509     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2510   }
2511
2512   if($params{"currencies"}) {
2513     $self->_get_currencies($dbh, $params{"currencies"});
2514   }
2515
2516   if($params{"customers"}) {
2517     $self->_get_customers($dbh, $params{"customers"});
2518   }
2519
2520   if($params{"vendors"}) {
2521     if (ref $params{"vendors"} eq 'HASH') {
2522       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2523     } else {
2524       $self->_get_vendors($dbh, $params{"vendors"});
2525     }
2526   }
2527
2528   if($params{"payments"}) {
2529     $self->_get_payments($dbh, $params{"payments"});
2530   }
2531
2532   if($params{"departments"}) {
2533     $self->_get_departments($dbh, $params{"departments"});
2534   }
2535
2536   if ($params{price_factors}) {
2537     $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2538   }
2539
2540   if ($params{warehouses}) {
2541     $self->_get_warehouses($dbh, $params{warehouses});
2542   }
2543
2544 #  if ($params{groups}) {
2545 #    $self->_get_groups($dbh, $params{groups});
2546 #  }
2547
2548   if ($params{partsgroup}) {
2549     $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2550   }
2551
2552   $main::lxdebug->leave_sub();
2553 }
2554
2555 # this sub gets the id and name from $table
2556 sub get_name {
2557   $main::lxdebug->enter_sub();
2558
2559   my ($self, $myconfig, $table) = @_;
2560
2561   # connect to database
2562   my $dbh = $self->get_standard_dbh($myconfig);
2563
2564   $table = $table eq "customer" ? "customer" : "vendor";
2565   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2566
2567   my ($query, @values);
2568
2569   if (!$self->{openinvoices}) {
2570     my $where;
2571     if ($self->{customernumber} ne "") {
2572       $where = qq|(vc.customernumber ILIKE ?)|;
2573       push(@values, '%' . $self->{customernumber} . '%');
2574     } else {
2575       $where = qq|(vc.name ILIKE ?)|;
2576       push(@values, '%' . $self->{$table} . '%');
2577     }
2578
2579     $query =
2580       qq~SELECT vc.id, vc.name,
2581            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2582          FROM $table vc
2583          WHERE $where AND (NOT vc.obsolete)
2584          ORDER BY vc.name~;
2585   } else {
2586     $query =
2587       qq~SELECT DISTINCT vc.id, vc.name,
2588            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2589          FROM $arap a
2590          JOIN $table vc ON (a.${table}_id = vc.id)
2591          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2592          ORDER BY vc.name~;
2593     push(@values, '%' . $self->{$table} . '%');
2594   }
2595
2596   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2597
2598   $main::lxdebug->leave_sub();
2599
2600   return scalar(@{ $self->{name_list} });
2601 }
2602
2603 # the selection sub is used in the AR, AP, IS, IR and OE module
2604 #
2605 sub all_vc {
2606   $main::lxdebug->enter_sub();
2607
2608   my ($self, $myconfig, $table, $module) = @_;
2609
2610   my $ref;
2611   my $dbh = $self->get_standard_dbh($myconfig);
2612
2613   $table = $table eq "customer" ? "customer" : "vendor";
2614
2615   my $query = qq|SELECT count(*) FROM $table|;
2616   my ($count) = selectrow_query($self, $dbh, $query);
2617
2618   # build selection list
2619   if ($count <= $myconfig->{vclimit}) {
2620     $query = qq|SELECT id, name, salesman_id
2621                 FROM $table WHERE NOT obsolete
2622                 ORDER BY name|;
2623     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2624   }
2625
2626   # get self
2627   $self->get_employee($dbh);
2628
2629   # setup sales contacts
2630   $query = qq|SELECT e.id, e.name
2631               FROM employee e
2632               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2633   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2634
2635   # this is for self
2636   push(@{ $self->{all_employees} },
2637        { id   => $self->{employee_id},
2638          name => $self->{employee} });
2639
2640   # sort the whole thing
2641   @{ $self->{all_employees} } =
2642     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2643
2644   if ($module eq 'AR') {
2645
2646     # prepare query for departments
2647     $query = qq|SELECT id, description
2648                 FROM department
2649                 WHERE role = 'P'
2650                 ORDER BY description|;
2651
2652   } else {
2653     $query = qq|SELECT id, description
2654                 FROM department
2655                 ORDER BY description|;
2656   }
2657
2658   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2659
2660   # get languages
2661   $query = qq|SELECT id, description
2662               FROM language
2663               ORDER BY id|;
2664
2665   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2666
2667   # get printer
2668   $query = qq|SELECT printer_description, id
2669               FROM printers
2670               ORDER BY printer_description|;
2671
2672   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2673
2674   # get payment terms
2675   $query = qq|SELECT id, description
2676               FROM payment_terms
2677               ORDER BY sortkey|;
2678
2679   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2680
2681   $main::lxdebug->leave_sub();
2682 }
2683
2684 sub language_payment {
2685   $main::lxdebug->enter_sub();
2686
2687   my ($self, $myconfig) = @_;
2688
2689   my $dbh = $self->get_standard_dbh($myconfig);
2690   # get languages
2691   my $query = qq|SELECT id, description
2692                  FROM language
2693                  ORDER BY id|;
2694
2695   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2696
2697   # get printer
2698   $query = qq|SELECT printer_description, id
2699               FROM printers
2700               ORDER BY printer_description|;
2701
2702   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2703
2704   # get payment terms
2705   $query = qq|SELECT id, description
2706               FROM payment_terms
2707               ORDER BY sortkey|;
2708
2709   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2710
2711   # get buchungsgruppen
2712   $query = qq|SELECT id, description
2713               FROM buchungsgruppen|;
2714
2715   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2716
2717   $main::lxdebug->leave_sub();
2718 }
2719
2720 # this is only used for reports
2721 sub all_departments {
2722   $main::lxdebug->enter_sub();
2723
2724   my ($self, $myconfig, $table) = @_;
2725
2726   my $dbh = $self->get_standard_dbh($myconfig);
2727   my $where;
2728
2729   if ($table eq 'customer') {
2730     $where = "WHERE role = 'P' ";
2731   }
2732
2733   my $query = qq|SELECT id, description
2734                  FROM department
2735                  $where
2736                  ORDER BY description|;
2737   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2738
2739   delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2740
2741   $main::lxdebug->leave_sub();
2742 }
2743
2744 sub create_links {
2745   $main::lxdebug->enter_sub();
2746
2747   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2748
2749   my ($fld, $arap);
2750   if ($table eq "customer") {
2751     $fld = "buy";
2752     $arap = "ar";
2753   } else {
2754     $table = "vendor";
2755     $fld = "sell";
2756     $arap = "ap";
2757   }
2758
2759   $self->all_vc($myconfig, $table, $module);
2760
2761   # get last customers or vendors
2762   my ($query, $sth, $ref);
2763
2764   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2765   my %xkeyref = ();
2766
2767   if (!$self->{id}) {
2768
2769     my $transdate = "current_date";
2770     if ($self->{transdate}) {
2771       $transdate = $dbh->quote($self->{transdate});
2772     }
2773
2774     # now get the account numbers
2775     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2776                 FROM chart c, taxkeys tk
2777                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2778                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2779                 ORDER BY c.accno|;
2780
2781     $sth = $dbh->prepare($query);
2782
2783     do_statement($self, $sth, $query, '%' . $module . '%');
2784
2785     $self->{accounts} = "";
2786     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2787
2788       foreach my $key (split(/:/, $ref->{link})) {
2789         if ($key =~ /\Q$module\E/) {
2790
2791           # cross reference for keys
2792           $xkeyref{ $ref->{accno} } = $key;
2793
2794           push @{ $self->{"${module}_links"}{$key} },
2795             { accno       => $ref->{accno},
2796               description => $ref->{description},
2797               taxkey      => $ref->{taxkey_id},
2798               tax_id      => $ref->{tax_id} };
2799
2800           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2801         }
2802       }
2803     }
2804   }
2805
2806   # get taxkeys and description
2807   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2808   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2809
2810   if (($module eq "AP") || ($module eq "AR")) {
2811     # get tax rates and description
2812     $query = qq|SELECT * FROM tax|;
2813     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2814   }
2815
2816   if ($self->{id}) {
2817     $query =
2818       qq|SELECT
2819            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2820            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2821            a.intnotes, a.department_id, a.amount AS oldinvtotal,
2822            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2823            c.name AS $table,
2824            d.description AS department,
2825            e.name AS employee
2826          FROM $arap a
2827          JOIN $table c ON (a.${table}_id = c.id)
2828          LEFT JOIN employee e ON (e.id = a.employee_id)
2829          LEFT JOIN department d ON (d.id = a.department_id)
2830          WHERE a.id = ?|;
2831     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2832
2833     foreach my $key (keys %$ref) {
2834       $self->{$key} = $ref->{$key};
2835     }
2836
2837     my $transdate = "current_date";
2838     if ($self->{transdate}) {
2839       $transdate = $dbh->quote($self->{transdate});
2840     }
2841
2842     # now get the account numbers
2843     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2844                 FROM chart c
2845                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2846                 WHERE c.link LIKE ?
2847                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2848                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2849                 ORDER BY c.accno|;
2850
2851     $sth = $dbh->prepare($query);
2852     do_statement($self, $sth, $query, "%$module%");
2853
2854     $self->{accounts} = "";
2855     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2856
2857       foreach my $key (split(/:/, $ref->{link})) {
2858         if ($key =~ /\Q$module\E/) {
2859
2860           # cross reference for keys
2861           $xkeyref{ $ref->{accno} } = $key;
2862
2863           push @{ $self->{"${module}_links"}{$key} },
2864             { accno       => $ref->{accno},
2865               description => $ref->{description},
2866               taxkey      => $ref->{taxkey_id},
2867               tax_id      => $ref->{tax_id} };
2868
2869           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2870         }
2871       }
2872     }
2873
2874
2875     # get amounts from individual entries
2876     $query =
2877       qq|SELECT
2878            c.accno, c.description,
2879            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2880            p.projectnumber,
2881            t.rate, t.id
2882          FROM acc_trans a
2883          LEFT JOIN chart c ON (c.id = a.chart_id)
2884          LEFT JOIN project p ON (p.id = a.project_id)
2885          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2886                                     WHERE (tk.taxkey_id=a.taxkey) AND
2887                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2888                                         THEN tk.chart_id = a.chart_id
2889                                         ELSE 1 = 1
2890                                         END)
2891                                        OR (c.link='%tax%')) AND
2892                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2893          WHERE a.trans_id = ?
2894          AND a.fx_transaction = '0'
2895          ORDER BY a.acc_trans_id, a.transdate|;
2896     $sth = $dbh->prepare($query);
2897     do_statement($self, $sth, $query, $self->{id});
2898
2899     # get exchangerate for currency
2900     $self->{exchangerate} =
2901       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2902     my $index = 0;
2903
2904     # store amounts in {acc_trans}{$key} for multiple accounts
2905     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2906       $ref->{exchangerate} =
2907         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2908       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2909         $index++;
2910       }
2911       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2912         $ref->{amount} *= -1;
2913       }
2914       $ref->{index} = $index;
2915
2916       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2917     }
2918
2919     $sth->finish;
2920     $query =
2921       qq|SELECT
2922            d.curr AS currencies, d.closedto, d.revtrans,
2923            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2924            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2925          FROM defaults d|;
2926     $ref = selectfirst_hashref_query($self, $dbh, $query);
2927     map { $self->{$_} = $ref->{$_} } keys %$ref;
2928
2929   } else {
2930
2931     # get date
2932     $query =
2933        qq|SELECT
2934             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2935             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2936             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2937           FROM defaults d|;
2938     $ref = selectfirst_hashref_query($self, $dbh, $query);
2939     map { $self->{$_} = $ref->{$_} } keys %$ref;
2940
2941     if ($self->{"$self->{vc}_id"}) {
2942
2943       # only setup currency
2944       ($self->{currency}) = split(/:/, $self->{currencies});
2945
2946     } else {
2947
2948       $self->lastname_used($dbh, $myconfig, $table, $module);
2949
2950       # get exchangerate for currency
2951       $self->{exchangerate} =
2952         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2953
2954     }
2955
2956   }
2957
2958   $main::lxdebug->leave_sub();
2959 }
2960
2961 sub lastname_used {
2962   $main::lxdebug->enter_sub();
2963
2964   my ($self, $dbh, $myconfig, $table, $module) = @_;
2965
2966   my ($arap, $where);
2967
2968   $table         = $table eq "customer" ? "customer" : "vendor";
2969   my %column_map = ("a.curr"                  => "currency",
2970                     "a.${table}_id"           => "${table}_id",
2971                     "a.department_id"         => "department_id",
2972                     "d.description"           => "department",
2973                     "ct.name"                 => $table,
2974                     "current_date + ct.terms" => "duedate",
2975     );
2976
2977   if ($self->{type} =~ /delivery_order/) {
2978     $arap  = 'delivery_orders';
2979     delete $column_map{"a.curr"};
2980
2981   } elsif ($self->{type} =~ /_order/) {
2982     $arap  = 'oe';
2983     $where = "quotation = '0'";
2984
2985   } elsif ($self->{type} =~ /_quotation/) {
2986     $arap  = 'oe';
2987     $where = "quotation = '1'";
2988
2989   } elsif ($table eq 'customer') {
2990     $arap  = 'ar';
2991
2992   } else {
2993     $arap  = 'ap';
2994
2995   }
2996
2997   $where           = "($where) AND" if ($where);
2998   my $query        = qq|SELECT MAX(id) FROM $arap
2999                         WHERE $where ${table}_id > 0|;
3000   my ($trans_id)   = selectrow_query($self, $dbh, $query);
3001   $trans_id       *= 1;
3002
3003   my $column_spec  = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
3004   $query           = qq|SELECT $column_spec
3005                         FROM $arap a
3006                         LEFT JOIN $table     ct ON (a.${table}_id = ct.id)
3007                         LEFT JOIN department d  ON (a.department_id = d.id)
3008                         WHERE a.id = ?|;
3009   my $ref          = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
3010
3011   map { $self->{$_} = $ref->{$_} } values %column_map;
3012
3013   $main::lxdebug->leave_sub();
3014 }
3015
3016 sub current_date {
3017   $main::lxdebug->enter_sub();
3018
3019   my $self     = shift;
3020   my $myconfig = shift || \%::myconfig;
3021   my ($thisdate, $days) = @_;
3022
3023   my $dbh = $self->get_standard_dbh($myconfig);
3024   my $query;
3025
3026   $days *= 1;
3027   if ($thisdate) {
3028     my $dateformat = $myconfig->{dateformat};
3029     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
3030     $thisdate = $dbh->quote($thisdate);
3031     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
3032   } else {
3033     $query = qq|SELECT current_date AS thisdate|;
3034   }
3035
3036   ($thisdate) = selectrow_query($self, $dbh, $query);
3037
3038   $main::lxdebug->leave_sub();
3039
3040   return $thisdate;
3041 }
3042
3043 sub like {
3044   $main::lxdebug->enter_sub();
3045
3046   my ($self, $string) = @_;
3047
3048   if ($string !~ /%/) {
3049     $string = "%$string%";
3050   }
3051
3052   $string =~ s/\'/\'\'/g;
3053
3054   $main::lxdebug->leave_sub();
3055
3056   return $string;
3057 }
3058
3059 sub redo_rows {
3060   $main::lxdebug->enter_sub();
3061
3062   my ($self, $flds, $new, $count, $numrows) = @_;
3063
3064   my @ndx = ();
3065
3066   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
3067
3068   my $i = 0;
3069
3070   # fill rows
3071   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
3072     $i++;
3073     my $j = $item->{ndx} - 1;
3074     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
3075   }
3076
3077   # delete empty rows
3078   for $i ($count + 1 .. $numrows) {
3079     map { delete $self->{"${_}_$i"} } @{$flds};
3080   }
3081
3082   $main::lxdebug->leave_sub();
3083 }
3084
3085 sub update_status {
3086   $main::lxdebug->enter_sub();
3087
3088   my ($self, $myconfig) = @_;
3089
3090   my ($i, $id);
3091
3092   my $dbh = $self->dbconnect_noauto($myconfig);
3093
3094   my $query = qq|DELETE FROM status
3095                  WHERE (formname = ?) AND (trans_id = ?)|;
3096   my $sth = prepare_query($self, $dbh, $query);
3097
3098   if ($self->{formname} =~ /(check|receipt)/) {
3099     for $i (1 .. $self->{rowcount}) {
3100       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
3101     }
3102   } else {
3103     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
3104   }
3105   $sth->finish();
3106
3107   my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3108   my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3109
3110   my %queued = split / /, $self->{queued};
3111   my @values;
3112
3113   if ($self->{formname} =~ /(check|receipt)/) {
3114
3115     # this is a check or receipt, add one entry for each lineitem
3116     my ($accno) = split /--/, $self->{account};
3117     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3118                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3119     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3120     $sth = prepare_query($self, $dbh, $query);
3121
3122     for $i (1 .. $self->{rowcount}) {
3123       if ($self->{"checked_$i"}) {
3124         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3125       }
3126     }
3127     $sth->finish();
3128
3129   } else {
3130     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3131                 VALUES (?, ?, ?, ?, ?)|;
3132     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3133              $queued{$self->{formname}}, $self->{formname});
3134   }
3135
3136   $dbh->commit;
3137   $dbh->disconnect;
3138
3139   $main::lxdebug->leave_sub();
3140 }
3141
3142 sub save_status {
3143   $main::lxdebug->enter_sub();
3144
3145   my ($self, $dbh) = @_;
3146
3147   my ($query, $printed, $emailed);
3148
3149   my $formnames  = $self->{printed};
3150   my $emailforms = $self->{emailed};
3151
3152   $query = qq|DELETE FROM status
3153                  WHERE (formname = ?) AND (trans_id = ?)|;
3154   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3155
3156   # this only applies to the forms
3157   # checks and receipts are posted when printed or queued
3158
3159   if ($self->{queued}) {
3160     my %queued = split / /, $self->{queued};
3161
3162     foreach my $formname (keys %queued) {
3163       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3164       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3165
3166       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3167                   VALUES (?, ?, ?, ?, ?)|;
3168       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3169
3170       $formnames  =~ s/\Q$self->{formname}\E//;
3171       $emailforms =~ s/\Q$self->{formname}\E//;
3172
3173     }
3174   }
3175
3176   # save printed, emailed info
3177   $formnames  =~ s/^ +//g;
3178   $emailforms =~ s/^ +//g;
3179
3180   my %status = ();
3181   map { $status{$_}{printed} = 1 } split / +/, $formnames;
3182   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3183
3184   foreach my $formname (keys %status) {
3185     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
3186     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3187
3188     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3189                 VALUES (?, ?, ?, ?)|;
3190     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3191   }
3192
3193   $main::lxdebug->leave_sub();
3194 }
3195
3196 #--- 4 locale ---#
3197 # $main::locale->text('SAVED')
3198 # $main::locale->text('DELETED')
3199 # $main::locale->text('ADDED')
3200 # $main::locale->text('PAYMENT POSTED')
3201 # $main::locale->text('POSTED')
3202 # $main::locale->text('POSTED AS NEW')
3203 # $main::locale->text('ELSE')
3204 # $main::locale->text('SAVED FOR DUNNING')
3205 # $main::locale->text('DUNNING STARTED')
3206 # $main::locale->text('PRINTED')
3207 # $main::locale->text('MAILED')
3208 # $main::locale->text('SCREENED')
3209 # $main::locale->text('CANCELED')
3210 # $main::locale->text('invoice')
3211 # $main::locale->text('proforma')
3212 # $main::locale->text('sales_order')
3213 # $main::locale->text('packing_list')
3214 # $main::locale->text('pick_list')
3215 # $main::locale->text('purchase_order')
3216 # $main::locale->text('bin_list')
3217 # $main::locale->text('sales_quotation')
3218 # $main::locale->text('request_quotation')
3219
3220 sub save_history {
3221   $main::lxdebug->enter_sub();
3222
3223   my $self = shift();
3224   my $dbh = shift();
3225
3226   if(!exists $self->{employee_id}) {
3227     &get_employee($self, $dbh);
3228   }
3229
3230   my $query =
3231    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3232    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3233   my @values = (conv_i($self->{id}), $self->{login},
3234                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3235   do_query($self, $dbh, $query, @values);
3236
3237   $main::lxdebug->leave_sub();
3238 }
3239
3240 sub get_history {
3241   $main::lxdebug->enter_sub();
3242
3243   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3244   my ($orderBy, $desc) = split(/\-\-/, $order);
3245   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3246   my @tempArray;
3247   my $i = 0;
3248   if ($trans_id ne "") {
3249     my $query =
3250       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 | .
3251       qq|FROM history_erp h | .
3252       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3253       qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3254       $order;
3255
3256     my $sth = $dbh->prepare($query) || $self->dberror($query);
3257
3258     $sth->execute() || $self->dberror("$query");
3259
3260     while(my $hash_ref = $sth->fetchrow_hashref()) {
3261       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3262       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3263       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3264       $tempArray[$i++] = $hash_ref;
3265     }
3266     $main::lxdebug->leave_sub() and return \@tempArray
3267       if ($i > 0 && $tempArray[0] ne "");
3268   }
3269   $main::lxdebug->leave_sub();
3270   return 0;
3271 }
3272
3273 sub update_defaults {
3274   $main::lxdebug->enter_sub();
3275
3276   my ($self, $myconfig, $fld, $provided_dbh) = @_;
3277
3278   my $dbh;
3279   if ($provided_dbh) {
3280     $dbh = $provided_dbh;
3281   } else {
3282     $dbh = $self->dbconnect_noauto($myconfig);
3283   }
3284   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3285   my $sth   = $dbh->prepare($query);
3286
3287   $sth->execute || $self->dberror($query);
3288   my ($var) = $sth->fetchrow_array;
3289   $sth->finish;
3290
3291   if ($var =~ m/\d+$/) {
3292     my $new_var  = (substr $var, $-[0]) * 1 + 1;
3293     my $len_diff = length($var) - $-[0] - length($new_var);
3294     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3295
3296   } else {
3297     $var = $var . '1';
3298   }
3299
3300   $query = qq|UPDATE defaults SET $fld = ?|;
3301   do_query($self, $dbh, $query, $var);
3302
3303   if (!$provided_dbh) {
3304     $dbh->commit;
3305     $dbh->disconnect;
3306   }
3307
3308   $main::lxdebug->leave_sub();
3309
3310   return $var;
3311 }
3312
3313 sub update_business {
3314   $main::lxdebug->enter_sub();
3315
3316   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3317
3318   my $dbh;
3319   if ($provided_dbh) {
3320     $dbh = $provided_dbh;
3321   } else {
3322     $dbh = $self->dbconnect_noauto($myconfig);
3323   }
3324   my $query =
3325     qq|SELECT customernumberinit FROM business
3326        WHERE id = ? FOR UPDATE|;
3327   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3328
3329   return undef unless $var;
3330
3331   if ($var =~ m/\d+$/) {
3332     my $new_var  = (substr $var, $-[0]) * 1 + 1;
3333     my $len_diff = length($var) - $-[0] - length($new_var);
3334     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3335
3336   } else {
3337     $var = $var . '1';
3338   }
3339
3340   $query = qq|UPDATE business
3341               SET customernumberinit = ?
3342               WHERE id = ?|;
3343   do_query($self, $dbh, $query, $var, $business_id);
3344
3345   if (!$provided_dbh) {
3346     $dbh->commit;
3347     $dbh->disconnect;
3348   }
3349
3350   $main::lxdebug->leave_sub();
3351
3352   return $var;
3353 }
3354
3355 sub get_partsgroup {
3356   $main::lxdebug->enter_sub();
3357
3358   my ($self, $myconfig, $p) = @_;
3359   my $target = $p->{target} || 'all_partsgroup';
3360
3361   my $dbh = $self->get_standard_dbh($myconfig);
3362
3363   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3364                  FROM partsgroup pg
3365                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
3366   my @values;
3367
3368   if ($p->{searchitems} eq 'part') {
3369     $query .= qq|WHERE p.inventory_accno_id > 0|;
3370   }
3371   if ($p->{searchitems} eq 'service') {
3372     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3373   }
3374   if ($p->{searchitems} eq 'assembly') {
3375     $query .= qq|WHERE p.assembly = '1'|;
3376   }
3377   if ($p->{searchitems} eq 'labor') {
3378     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3379   }
3380
3381   $query .= qq|ORDER BY partsgroup|;
3382
3383   if ($p->{all}) {
3384     $query = qq|SELECT id, partsgroup FROM partsgroup
3385                 ORDER BY partsgroup|;
3386   }
3387
3388   if ($p->{language_code}) {
3389     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3390                   t.description AS translation
3391                 FROM partsgroup pg
3392                 JOIN parts p ON (p.partsgroup_id = pg.id)
3393                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3394                 ORDER BY translation|;
3395     @values = ($p->{language_code});
3396   }
3397
3398   $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3399
3400   $main::lxdebug->leave_sub();
3401 }
3402
3403 sub get_pricegroup {
3404   $main::lxdebug->enter_sub();
3405
3406   my ($self, $myconfig, $p) = @_;
3407
3408   my $dbh = $self->get_standard_dbh($myconfig);
3409
3410   my $query = qq|SELECT p.id, p.pricegroup
3411                  FROM pricegroup p|;
3412
3413   $query .= qq| ORDER BY pricegroup|;
3414
3415   if ($p->{all}) {
3416     $query = qq|SELECT id, pricegroup FROM pricegroup
3417                 ORDER BY pricegroup|;
3418   }
3419
3420   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3421
3422   $main::lxdebug->leave_sub();
3423 }
3424
3425 sub all_years {
3426 # usage $form->all_years($myconfig, [$dbh])
3427 # return list of all years where bookings found
3428 # (@all_years)
3429
3430   $main::lxdebug->enter_sub();
3431
3432   my ($self, $myconfig, $dbh) = @_;
3433
3434   $dbh ||= $self->get_standard_dbh($myconfig);
3435
3436   # get years
3437   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3438                    (SELECT MAX(transdate) FROM acc_trans)|;
3439   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3440
3441   if ($myconfig->{dateformat} =~ /^yy/) {
3442     ($startdate) = split /\W/, $startdate;
3443     ($enddate) = split /\W/, $enddate;
3444   } else {
3445     (@_) = split /\W/, $startdate;
3446     $startdate = $_[2];
3447     (@_) = split /\W/, $enddate;
3448     $enddate = $_[2];
3449   }
3450
3451   my @all_years;
3452   $startdate = substr($startdate,0,4);
3453   $enddate = substr($enddate,0,4);
3454
3455   while ($enddate >= $startdate) {
3456     push @all_years, $enddate--;
3457   }
3458
3459   return @all_years;
3460
3461   $main::lxdebug->leave_sub();
3462 }
3463
3464 sub backup_vars {
3465   $main::lxdebug->enter_sub();
3466   my $self = shift;
3467   my @vars = @_;
3468
3469   map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3470
3471   $main::lxdebug->leave_sub();
3472 }
3473
3474 sub restore_vars {
3475   $main::lxdebug->enter_sub();
3476
3477   my $self = shift;
3478   my @vars = @_;
3479
3480   map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3481
3482   $main::lxdebug->leave_sub();
3483 }
3484
3485 1;
3486
3487 __END__
3488
3489 =head1 NAME
3490
3491 SL::Form.pm - main data object.
3492
3493 =head1 SYNOPSIS
3494
3495 This is the main data object of Lx-Office.
3496 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3497 Points of interest for a beginner are:
3498
3499  - $form->error            - renders a generic error in html. accepts an error message
3500  - $form->get_standard_dbh - returns a database connection for the
3501
3502 =head1 SPECIAL FUNCTIONS
3503
3504 =over 4
3505
3506 =item _store_value()
3507
3508 parses a complex var name, and stores it in the form.
3509
3510 syntax:
3511   $form->_store_value($key, $value);
3512
3513 keys must start with a string, and can contain various tokens.
3514 supported key structures are:
3515
3516 1. simple access
3517   simple key strings work as expected
3518
3519   id => $form->{id}
3520
3521 2. hash access.
3522   separating two keys by a dot (.) will result in a hash lookup for the inner value
3523   this is similar to the behaviour of java and templating mechanisms.
3524
3525   filter.description => $form->{filter}->{description}
3526
3527 3. array+hashref access
3528
3529   adding brackets ([]) before the dot will cause the next hash to be put into an array.
3530   using [+] instead of [] will force a new array index. this is useful for recurring
3531   data structures like part lists. put a [+] into the first varname, and use [] on the
3532   following ones.
3533
3534   repeating these names in your template:
3535
3536     invoice.items[+].id
3537     invoice.items[].parts_id
3538
3539   will result in:
3540
3541     $form->{invoice}->{items}->[
3542       {
3543         id       => ...
3544         parts_id => ...
3545       },
3546       {
3547         id       => ...
3548         parts_id => ...
3549       }
3550       ...
3551     ]
3552
3553 4. arrays
3554
3555   using brackets at the end of a name will result in a pure array to be created.
3556   note that you mustn't use [+], which is reserved for array+hash access and will
3557   result in undefined behaviour in array context.
3558
3559   filter.status[]  => $form->{status}->[ val1, val2, ... ]
3560
3561 =item update_business PARAMS
3562
3563 PARAMS (not named):
3564  \%config,     - config hashref
3565  $business_id, - business id
3566  $dbh          - optional database handle
3567
3568 handles business (thats customer/vendor types) sequences.
3569
3570 special behaviour for empty strings in customerinitnumber field:
3571 will in this case not increase the value, and return undef.
3572
3573 =item redirect_header $url
3574
3575 Generates a HTTP redirection header for the new C<$url>. Constructs an
3576 absolute URL including scheme, host name and port. If C<$url> is a
3577 relative URL then it is considered relative to Lx-Office base URL.
3578
3579 This function C<die>s if headers have already been created with
3580 C<$::form-E<gt>header>.
3581
3582 Examples:
3583
3584   print $::form->redirect_header('oe.pl?action=edit&id=1234');
3585   print $::form->redirect_header('http://www.lx-office.org/');
3586
3587 =back
3588
3589 =cut