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