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