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