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