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