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