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