"Als bezahlt markieren" Button-Funktion in die common.pl verlegt.
[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 use Data::Dumper;
40
41 use Cwd;
42 use HTML::Template;
43 use SL::Template;
44 use CGI::Ajax;
45 use SL::DBUtils;
46 use SL::Mailer;
47 use SL::Menu;
48 use SL::User;
49 use SL::Common;
50 use CGI;
51
52 my $standard_dbh;
53
54 sub DESTROY {
55   if ($standard_dbh) {
56     $standard_dbh->disconnect();
57     undef $standard_dbh;
58   }
59 }
60
61 sub _input_to_hash {
62   $main::lxdebug->enter_sub(2);
63
64   my $input = $_[0];
65   my %in    = ();
66   my @pairs = split(/&/, $input);
67
68   foreach (@pairs) {
69     my ($name, $value) = split(/=/, $_, 2);
70     $in{$name} = unescape(undef, $value);
71   }
72
73   $main::lxdebug->leave_sub(2);
74
75   return %in;
76 }
77
78 sub _request_to_hash {
79   $main::lxdebug->enter_sub(2);
80
81   my ($input) = @_;
82
83   if (!$ENV{'CONTENT_TYPE'}
84       || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
85     $main::lxdebug->leave_sub(2);
86     return _input_to_hash($input);
87   }
88
89   my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr);
90   my %params;
91
92   my $boundary = '--' . $1;
93
94   foreach my $line (split m/\n/, $input) {
95     last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
96
97     if (($line eq $boundary) || ($line eq "$boundary\r")) {
98       $params{$name} =~ s|\r?\n$|| if $name;
99
100       undef $name, $filename;
101
102       $headers_done   = 0;
103       $content_type   = "text/plain";
104       $boundary_found = 1;
105       $need_cr        = 0;
106
107       next;
108     }
109
110     next unless $boundary_found;
111
112     if (!$headers_done) {
113       $line =~ s/[\r\n]*$//;
114
115       if (!$line) {
116         $headers_done = 1;
117         next;
118       }
119
120       if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
121         if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
122           $filename = $1;
123           substr $line, $-[0], $+[0] - $-[0], "";
124         }
125
126         if ($line =~ m|name\s*=\s*"(.*?)"|i) {
127           $name = $1;
128           substr $line, $-[0], $+[0] - $-[0], "";
129         }
130
131         $params{$name}    = "";
132         $params{FILENAME} = $filename if ($filename);
133
134         next;
135       }
136
137       if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
138         $content_type = $1;
139       }
140
141       next;
142     }
143
144     next unless $name;
145
146     $params{$name} .= "${line}\n";
147   }
148
149   $params{$name} =~ s|\r?\n$|| if $name;
150
151   $main::lxdebug->leave_sub(2);
152   return %params;
153 }
154
155 sub new {
156   $main::lxdebug->enter_sub();
157
158   my $type = shift;
159
160   my $self = {};
161
162   if ($LXDebug::watch_form) {
163     require SL::Watchdog;
164     tie %{ $self }, 'SL::Watchdog';
165   }
166
167   read(STDIN, $_, $ENV{CONTENT_LENGTH});
168
169   if ($ENV{QUERY_STRING}) {
170     $_ = $ENV{QUERY_STRING};
171   }
172
173   if ($ARGV[0]) {
174     $_ = $ARGV[0];
175   }
176
177   my %parameters = _request_to_hash($_);
178   map({ $self->{$_} = $parameters{$_}; } keys(%parameters));
179
180   $self->{action} = lc $self->{action};
181   $self->{action} =~ s/( |-|,|\#)/_/g;
182
183   $self->{version}   = "2.4.2";
184
185   $main::lxdebug->leave_sub();
186
187   bless $self, $type;
188 }
189
190 sub debug {
191   $main::lxdebug->enter_sub();
192
193   my ($self) = @_;
194
195   print "\n";
196
197   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
198
199   $main::lxdebug->leave_sub();
200 }
201
202 sub escape {
203   $main::lxdebug->enter_sub(2);
204
205   my ($self, $str) = @_;
206
207   $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
208
209   $main::lxdebug->leave_sub(2);
210
211   return $str;
212 }
213
214 sub unescape {
215   $main::lxdebug->enter_sub(2);
216
217   my ($self, $str) = @_;
218
219   $str =~ tr/+/ /;
220   $str =~ s/\\$//;
221
222   $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
223
224   $main::lxdebug->leave_sub(2);
225
226   return $str;
227 }
228
229 sub quote {
230   my ($self, $str) = @_;
231
232   if ($str && !ref($str)) {
233     $str =~ s/\"/&quot;/g;
234   }
235
236   $str;
237
238 }
239
240 sub unquote {
241   my ($self, $str) = @_;
242
243   if ($str && !ref($str)) {
244     $str =~ s/&quot;/\"/g;
245   }
246
247   $str;
248
249 }
250
251 sub quote_html {
252   $main::lxdebug->enter_sub(2);
253
254   my ($self, $str) = @_;
255
256   my %replace =
257     ('order' => ['"', '<', '>'],
258      '<'             => '&lt;',
259      '>'             => '&gt;',
260      '"'             => '&quot;',
261     );
262
263   map({ $str =~ s/$_/$replace{$_}/g; } @{ $replace{"order"} });
264
265   $main::lxdebug->leave_sub(2);
266
267   return $str;
268 }
269
270 sub hide_form {
271   my $self = shift;
272
273   if (@_) {
274     map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
275   } else {
276     for (sort keys %$self) {
277       next if (($_ eq "header") || (ref($self->{$_}) ne ""));
278       print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
279     }
280   }
281
282 }
283
284 sub error {
285   $main::lxdebug->enter_sub();
286
287   $main::lxdebug->show_backtrace();
288
289   my ($self, $msg) = @_;
290   if ($ENV{HTTP_USER_AGENT}) {
291     $msg =~ s/\n/<br>/g;
292     $self->show_generic_error($msg);
293
294   } else {
295
296     if ($self->{error_function}) {
297       &{ $self->{error_function} }($msg);
298     } else {
299       die "Error: $msg\n";
300     }
301   }
302
303   $main::lxdebug->leave_sub();
304 }
305
306 sub info {
307   $main::lxdebug->enter_sub();
308
309   my ($self, $msg) = @_;
310
311   if ($ENV{HTTP_USER_AGENT}) {
312     $msg =~ s/\n/<br>/g;
313
314     if (!$self->{header}) {
315       $self->header;
316       print qq|
317       <body>|;
318     }
319
320     print qq|
321
322     <p><b>$msg</b>
323     |;
324
325   } else {
326
327     if ($self->{info_function}) {
328       &{ $self->{info_function} }($msg);
329     } else {
330       print "$msg\n";
331     }
332   }
333
334   $main::lxdebug->leave_sub();
335 }
336
337 sub numtextrows {
338   $main::lxdebug->enter_sub();
339
340   my ($self, $str, $cols, $maxrows) = @_;
341
342   my $rows = 0;
343
344   map { $rows += int(((length) - 2) / $cols) + 1 } split /\r/, $str;
345
346   $maxrows = $rows unless defined $maxrows;
347
348   $main::lxdebug->leave_sub();
349
350   return ($rows > $maxrows) ? $maxrows : $rows;
351 }
352
353 sub dberror {
354   $main::lxdebug->enter_sub();
355
356   my ($self, $msg) = @_;
357
358   $self->error("$msg\n" . $DBI::errstr);
359
360   $main::lxdebug->leave_sub();
361 }
362
363 sub isblank {
364   $main::lxdebug->enter_sub();
365
366   my ($self, $name, $msg) = @_;
367
368   if ($self->{$name} =~ /^\s*$/) {
369     $self->error($msg);
370   }
371   $main::lxdebug->leave_sub();
372 }
373
374 sub header {
375   $main::lxdebug->enter_sub();
376
377   my ($self, $extra_code) = @_;
378
379   if ($self->{header}) {
380     $main::lxdebug->leave_sub();
381     return;
382   }
383
384   my ($stylesheet, $favicon);
385
386   if ($ENV{HTTP_USER_AGENT}) {
387
388     if ($self->{stylesheet} && (-f "css/$self->{stylesheet}")) {
389       $stylesheet =
390         qq|<LINK REL="stylesheet" HREF="css/$self->{stylesheet}" TYPE="text/css" TITLE="Lx-Office stylesheet">
391  |;
392     }
393
394     $self->{favicon}    = "favicon.ico" unless $self->{favicon};
395
396     if ($self->{favicon} && (-f "$self->{favicon}")) {
397       $favicon =
398         qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
399   |;
400     }
401
402     my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
403
404     if ($self->{landscape}) {
405       $pagelayout = qq|<style type="text/css">
406                         \@page { size:landscape; }
407                         </style>|;
408     }
409
410     my $fokus = qq|  document.$self->{fokus}.focus();| if ($self->{"fokus"});
411
412     #Set Calendar
413     my $jsscript = "";
414     if ($self->{jsscript} == 1) {
415
416       $jsscript = qq|
417         <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
418         <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
419         <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
420         <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
421         $self->{javascript}
422        |;
423     }
424
425     $self->{titlebar} =
426       ($self->{title})
427       ? "$self->{title} - $self->{titlebar}"
428       : $self->{titlebar};
429     my $ajax = "";
430     foreach $item (@ { $self->{AJAX} }) {
431       $ajax .= $item->show_javascript();
432     }
433     print qq|Content-Type: text/html; charset=${db_charset};
434
435 <html>
436 <head>
437   <title>$self->{titlebar}</title>
438   $stylesheet
439   $pagelayout
440   $favicon
441   <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
442   $jsscript
443   $ajax
444
445   <script type="text/javascript">
446   <!--
447     function fokus() {
448       $fokus
449     }
450   //-->
451   </script>
452
453   <meta name="robots" content="noindex,nofollow" />
454   <script type="text/javascript" src="js/highlight_input.js"></script>
455   <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
456
457   <script type="text/javascript" src="js/tabcontent.js">
458
459   /***********************************************
460   * Tab Content script- Dynamic Drive DHTML code library (www.dynamicdrive.com)
461   * This notice MUST stay intact for legal use
462   * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
463   ***********************************************/
464
465   </script>
466
467   $extra_code
468 </head>
469
470 |;
471   }
472   $self->{header} = 1;
473
474   $main::lxdebug->leave_sub();
475 }
476
477 sub parse_html_template {
478   $main::lxdebug->enter_sub();
479
480   my ($self, $file, $additional_params) = @_;
481   my $language;
482
483   if (!defined(%main::myconfig) || !defined($main::myconfig{"countrycode"})) {
484     $language = $main::language;
485   } else {
486     $language = $main::myconfig{"countrycode"};
487   }
488   $language = "de" unless ($language);
489
490   if (-f "templates/webpages/${file}_${language}.html") {
491     if ((-f ".developer") &&
492         (-f "templates/webpages/${file}_master.html") &&
493         ((stat("templates/webpages/${file}_master.html"))[9] >
494          (stat("templates/webpages/${file}_${language}.html"))[9])) {
495       my $info = "Developer information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
496         "Please re-run 'locales.pl' in 'locale/${language}'.";
497       print(qq|<pre>$info</pre>|);
498       die($info);
499     }
500
501     $file = "templates/webpages/${file}_${language}.html";
502   } elsif (-f "templates/webpages/${file}.html") {
503     $file = "templates/webpages/${file}.html";
504   } else {
505     my $info = "Web page template '${file}' not found.\n" .
506       "Please re-run 'locales.pl' in 'locale/${language}'.";
507     print(qq|<pre>$info</pre>|);
508     die($info);
509   }
510
511   my $template = HTML::Template->new("filename" => $file,
512                                      "die_on_bad_params" => 0,
513                                      "strict" => 0,
514                                      "case_sensitive" => 1,
515                                      "loop_context_vars" => 1,
516                                      "global_vars" => 1);
517
518   $additional_params = {} unless ($additional_params);
519   if ($self->{"DEBUG"}) {
520     $additional_params->{"DEBUG"} = $self->{"DEBUG"};
521   }
522
523   if ($additional_params->{"DEBUG"}) {
524     $additional_params->{"DEBUG"} =
525       "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
526   }
527
528   if (%main::myconfig) {
529     map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
530     my $jsc_dateformat = $main::myconfig{"dateformat"};
531     $jsc_dateformat =~ s/d+/\%d/gi;
532     $jsc_dateformat =~ s/m+/\%m/gi;
533     $jsc_dateformat =~ s/y+/\%Y/gi;
534     $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
535   }
536
537   $additional_params->{"conf_webdav"}                 = $main::webdav;
538   $additional_params->{"conf_lizenzen"}               = $main::lizenzen;
539   $additional_params->{"conf_latex_templates"}        = $main::latex;
540   $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
541
542   my @additional_param_names = keys(%{$additional_params});
543   foreach my $key ($template->param()) {
544     my $param = $self->{$key};
545     $param = $additional_params->{$key} if (grep(/^${key}$/, @additional_param_names));
546     $param = [] if (($template->query("name" => $key) eq "LOOP") && (ref($param) ne "ARRAY"));
547     $template->param($key => $param);
548   }
549
550   my $output = $template->output();
551
552   $main::lxdebug->leave_sub();
553
554   return $output;
555 }
556
557 sub show_generic_error {
558   my ($self, $error, $title, $action) = @_;
559
560   my $add_params = {};
561   $add_params->{"title"} = $title if ($title);
562   $self->{"label_error"} = $error;
563
564   my @vars;
565   if ($action) {
566     map({ delete($self->{$_}); } qw(action));
567     map({ push(@vars, { "name" => $_, "value" => $self->{$_} })
568             if (!ref($self->{$_})); }
569         keys(%{$self}));
570     $add_params->{"SHOW_BUTTON"} = 1;
571     $add_params->{"BUTTON_LABEL"} = $action;
572   }
573   $add_params->{"VARIABLES"} = \@vars;
574
575   $self->header();
576   print($self->parse_html_template("generic/error", $add_params));
577
578   die("Error: $error\n");
579 }
580
581 sub show_generic_information {
582   my ($self, $error, $title) = @_;
583
584   my $add_params = {};
585   $add_params->{"title"} = $title if ($title);
586   $self->{"label_information"} = $error;
587
588   $self->header();
589   print($self->parse_html_template("generic/information", $add_params));
590
591   die("Information: $error\n");
592 }
593
594 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
595 # changed it to accept an arbitrary number of triggers - sschoeling
596 sub write_trigger {
597   $main::lxdebug->enter_sub();
598
599   my $self     = shift;
600   my $myconfig = shift;
601   my $qty      = shift;
602
603   # set dateform for jsscript
604   # default
605   my %dateformats = (
606     "dd.mm.yy" => "%d.%m.%Y",
607     "dd-mm-yy" => "%d-%m-%Y",
608     "dd/mm/yy" => "%d/%m/%Y",
609     "mm/dd/yy" => "%m/%d/%Y",
610     "mm-dd-yy" => "%m-%d-%Y",
611     "yyyy-mm-dd" => "%Y-%m-%d",
612     );
613
614   my $ifFormat = defined($dateformats{$myconfig{"dateformat"}}) ?
615     $dateformats{$myconfig{"dateformat"}} : "%d.%m.%Y";
616
617   my @triggers;
618   while ($#_ >= 2) {
619     push @triggers, qq|
620        Calendar.setup(
621       {
622       inputField : "| . (shift) . qq|",
623       ifFormat :"$ifFormat",
624       align : "| .  (shift) . qq|",
625       button : "| . (shift) . qq|"
626       }
627       );
628        |;
629   }
630   my $jsscript = qq|
631        <script type="text/javascript">
632        <!--| . join("", @triggers) . qq|//-->
633         </script>
634         |;
635
636   $main::lxdebug->leave_sub();
637
638   return $jsscript;
639 }    #end sub write_trigger
640
641 sub redirect {
642   $main::lxdebug->enter_sub();
643
644   my ($self, $msg) = @_;
645
646   if ($self->{callback}) {
647
648     ($script, $argv) = split(/\?/, $self->{callback});
649     exec("perl", "$script", $argv);
650
651   } else {
652
653     $self->info($msg);
654     exit;
655   }
656
657   $main::lxdebug->leave_sub();
658 }
659
660 # sort of columns removed - empty sub
661 sub sort_columns {
662   $main::lxdebug->enter_sub();
663
664   my ($self, @columns) = @_;
665
666   $main::lxdebug->leave_sub();
667
668   return @columns;
669 }
670 #
671 sub format_amount {
672   $main::lxdebug->enter_sub(2);
673
674   my ($self, $myconfig, $amount, $places, $dash) = @_;
675
676   if ($amount eq "") {
677     $amount = 0;
678   }
679   my $neg = ($amount =~ s/-//);
680
681   if (defined($places) && ($places ne '')) {
682     if ($places < 0) {
683       $amount *= 1;
684       $places *= -1;
685
686       my ($actual_places) = ($amount =~ /\.(\d+)/);
687       $actual_places = length($actual_places);
688       $places = $actual_places > $places ? $actual_places : $places;
689     }
690
691     $amount = $self->round_amount($amount, $places);
692   }
693
694   my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
695   my @p = split(/\./, $amount); # split amount at decimal point
696
697   $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
698
699   $amount = $p[0];
700   $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
701
702   $amount = do {
703     ($dash =~ /-/)    ? ($neg ? "($amount)"  : "$amount" )    :
704     ($dash =~ /DRCR/) ? ($neg ? "$amount DR" : "$amount CR" ) :
705                         ($neg ? "-$amount"   : "$amount" )    ;
706   };
707
708
709   $main::lxdebug->leave_sub(2);
710   return $amount;
711 }
712 #
713 sub parse_amount {
714   $main::lxdebug->enter_sub(2);
715
716   my ($self, $myconfig, $amount) = @_;
717
718   if (   ($myconfig->{numberformat} eq '1.000,00')
719       || ($myconfig->{numberformat} eq '1000,00')) {
720     $amount =~ s/\.//g;
721     $amount =~ s/,/\./;
722   }
723
724   if ($myconfig->{numberformat} eq "1'000.00") {
725     $amount =~ s/\'//g;
726   }
727
728   $amount =~ s/,//g;
729
730   $main::lxdebug->leave_sub(2);
731
732   return ($amount * 1);
733 }
734
735 sub round_amount {
736   $main::lxdebug->enter_sub(2);
737
738   my ($self, $amount, $places) = @_;
739   my $round_amount;
740
741   # Rounding like "Kaufmannsrunden"
742   # Descr. http://de.wikipedia.org/wiki/Rundung
743   # Inspired by
744   # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
745   # Solves Bug: 189
746   # Udo Spallek
747   $amount = $amount * (10**($places));
748   $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
749
750   $main::lxdebug->leave_sub(2);
751
752   return $round_amount;
753
754 }
755
756 sub parse_template {
757   $main::lxdebug->enter_sub();
758
759   my ($self, $myconfig, $userspath) = @_;
760   my ($template, $out);
761
762   local (*IN, *OUT);
763
764   $self->{"cwd"} = getcwd();
765   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
766
767   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
768     $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
769   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
770     $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
771     $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
772   } elsif (($self->{"format"} =~ /html/i) ||
773            (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
774     $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
775   } elsif (($self->{"format"} =~ /xml/i) ||
776              (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
777     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
778   } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
779     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
780   } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
781     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
782   } elsif ( defined $self->{'format'}) {
783     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
784   } elsif ( $self->{'format'} eq '' ) {
785     $self->error("No Outputformat given: $self->{'format'}");
786   } else { #Catch the rest
787     $self->error("Outputformat not defined: $self->{'format'}");
788   }
789
790   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
791   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
792
793   map({ $self->{"employee_${_}"} = $myconfig->{$_}; }
794       qw(email tel fax name signature company address businessnumber
795          co_ustid taxnumber duns));
796   map({ $self->{"employee_${_}"} =~ s/\\n/\n/g; }
797       qw(company address signature));
798   map({ $self->{$_} =~ s/\\n/\n/g; } qw(company address signature));
799
800   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
801
802   # OUT is used for the media, screen, printer, email
803   # for postscript we store a copy in a temporary file
804   my $fileid = time;
805   my $prepend_userspath;
806
807   if (!$self->{tmpfile}) {
808     $self->{tmpfile}   = "${fileid}.$self->{IN}";
809     $prepend_userspath = 1;
810   }
811
812   $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
813
814   $self->{tmpfile} =~ s|.*/||;
815   $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
816   $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
817
818   if ($template->uses_temp_file() || $self->{media} eq 'email') {
819     $out = $self->{OUT};
820     $self->{OUT} = ">$self->{tmpfile}";
821   }
822
823   if ($self->{OUT}) {
824     open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
825   } else {
826     open(OUT, ">-") or $self->error("STDOUT : $!");
827     $self->header;
828   }
829
830   if (!$template->parse(*OUT)) {
831     $self->cleanup();
832     $self->error("$self->{IN} : " . $template->get_error());
833   }
834
835   close(OUT);
836
837   if ($template->uses_temp_file() || $self->{media} eq 'email') {
838
839     if ($self->{media} eq 'email') {
840
841       my $mail = new Mailer;
842
843       map { $mail->{$_} = $self->{$_} }
844         qw(cc bcc subject message version format);
845       $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
846       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
847       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
848       $mail->{fileid} = "$fileid.";
849       $myconfig->{signature} =~ s/\\r\\n/\\n/g;
850
851       # if we send html or plain text inline
852       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
853         $mail->{contenttype} = "text/html";
854
855         $mail->{message}       =~ s/\r\n/<br>\n/g;
856         $myconfig->{signature} =~ s/\\n/<br>\n/g;
857         $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
858
859         open(IN, $self->{tmpfile})
860           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
861         while (<IN>) {
862           $mail->{message} .= $_;
863         }
864
865         close(IN);
866
867       } else {
868
869         if (!$self->{"do_not_attach"}) {
870           @{ $mail->{attachments} } =
871             ({ "filename" => $self->{"tmpfile"},
872                "name" => $self->{"attachment_filename"} ?
873                  $self->{"attachment_filename"} : $self->{"tmpfile"} });
874         }
875
876         $mail->{message}       =~ s/\r\n/\n/g;
877         $myconfig->{signature} =~ s/\\n/\n/g;
878         $mail->{message} .= "\n-- \n$myconfig->{signature}";
879
880       }
881
882       my $err = $mail->send();
883       $self->error($self->cleanup . "$err") if ($err);
884
885     } else {
886
887       $self->{OUT} = $out;
888
889       my $numbytes = (-s $self->{tmpfile});
890       open(IN, $self->{tmpfile})
891         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
892
893       $self->{copies} = 1 unless $self->{media} eq 'printer';
894
895       chdir("$self->{cwd}");
896       #print(STDERR "Kopien $self->{copies}\n");
897       #print(STDERR "OUT $self->{OUT}\n");
898       for my $i (1 .. $self->{copies}) {
899         if ($self->{OUT}) {
900           open(OUT, $self->{OUT})
901             or $self->error($self->cleanup . "$self->{OUT} : $!");
902         } else {
903           $self->{attachment_filename} = ($self->{attachment_filename}) 
904                                        ? $self->{attachment_filename}
905                                        : $self->generate_attachment_filename();
906
907           # launch application
908           print qq|Content-Type: | . $template->get_mime_type() . qq|
909 Content-Disposition: attachment; filename="$self->{attachment_filename}"
910 Content-Length: $numbytes
911
912 |;
913
914           open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
915
916         }
917
918         while (<IN>) {
919           print OUT $_;
920         }
921
922         close(OUT);
923
924         seek IN, 0, 0;
925       }
926
927       close(IN);
928     }
929
930   }
931
932   $self->cleanup;
933
934   chdir("$self->{cwd}");
935   $main::lxdebug->leave_sub();
936 }
937
938 sub generate_attachment_filename {
939   my ($self) = @_;
940
941   my %formname_translations = (
942      bin_list            => $main::locale->text('Bin List'),
943      credit_note         => $main::locale->text('Credit Note'),
944      invoice             => $main::locale->text('Invoice'),
945      packing_list        => $main::locale->text('Packing List'),
946      pick_list           => $main::locale->text('Pick List'),
947      proforma            => $main::locale->text('Proforma Invoice'),
948      purchase_order      => $main::locale->text('Purchase Order'),
949      request_quotation   => $main::locale->text('RFQ'),
950      sales_order         => $main::locale->text('Confirmation'),
951      sales_quotation     => $main::locale->text('Quotation'),
952      storno_invoice      => $main::locale->text('Storno Invoice'),
953      storno_packing_list => $main::locale->text('Storno Packing List'),
954   );
955
956   my $attachment_filename = $formname_translations{$self->{"formname"}};
957   my $prefix = 
958       (grep { $self->{"type"} eq $_ } qw(invoice credit_note)) ? "inv"
959     : ($self->{"type"} =~ /_quotation$/)                       ? "quo"
960     :                                                            "ord";
961
962   if ($attachment_filename && $self->{"${prefix}number"}) {
963     $attachment_filename .= "_" . $self->{"${prefix}number"}
964                             . (  $self->{format} =~ /pdf/i          ? ".pdf"
965                                : $self->{format} =~ /postscript/i   ? ".ps"
966                                : $self->{format} =~ /opendocument/i ? ".odt"
967                                : $self->{format} =~ /html/i         ? ".html"
968                                :                                      "");
969     $attachment_filename =~ s/ /_/g;
970     my %umlaute = ( "ä" => "ae", "ö" => "oe", "ü" => "ue", 
971                     "Ä" => "Ae", "Ö" => "Oe", "Ãœ" => "Ue", "ß" => "ss");
972     map { $attachment_filename =~ s/$_/$umlaute{$_}/g } keys %umlaute;
973   } else {
974     $attachment_filename = "";
975   }
976
977   return $attachment_filename;
978 }
979
980 sub cleanup {
981   $main::lxdebug->enter_sub();
982
983   my $self = shift;
984
985   chdir("$self->{tmpdir}");
986
987   my @err = ();
988   if (-f "$self->{tmpfile}.err") {
989     open(FH, "$self->{tmpfile}.err");
990     @err = <FH>;
991     close(FH);
992   }
993
994   if ($self->{tmpfile}) {
995     $self->{tmpfile} =~ s|.*/||g;
996     # strip extension
997     $self->{tmpfile} =~ s/\.\w+$//g;
998     my $tmpfile = $self->{tmpfile};
999     unlink(<$tmpfile.*>);
1000   }
1001
1002   chdir("$self->{cwd}");
1003
1004   $main::lxdebug->leave_sub();
1005
1006   return "@err";
1007 }
1008
1009 sub datetonum {
1010   $main::lxdebug->enter_sub();
1011
1012   my ($self, $date, $myconfig) = @_;
1013
1014   if ($date && $date =~ /\D/) {
1015
1016     if ($myconfig->{dateformat} =~ /^yy/) {
1017       ($yy, $mm, $dd) = split /\D/, $date;
1018     }
1019     if ($myconfig->{dateformat} =~ /^mm/) {
1020       ($mm, $dd, $yy) = split /\D/, $date;
1021     }
1022     if ($myconfig->{dateformat} =~ /^dd/) {
1023       ($dd, $mm, $yy) = split /\D/, $date;
1024     }
1025
1026     $dd *= 1;
1027     $mm *= 1;
1028     $yy = ($yy < 70) ? $yy + 2000 : $yy;
1029     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1030
1031     $dd = "0$dd" if ($dd < 10);
1032     $mm = "0$mm" if ($mm < 10);
1033
1034     $date = "$yy$mm$dd";
1035   }
1036
1037   $main::lxdebug->leave_sub();
1038
1039   return $date;
1040 }
1041
1042 # Database routines used throughout
1043
1044 sub dbconnect {
1045   $main::lxdebug->enter_sub(2);
1046
1047   my ($self, $myconfig) = @_;
1048
1049   # connect to database
1050   my $dbh =
1051     DBI->connect($myconfig->{dbconnect},
1052                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
1053     or $self->dberror;
1054
1055   # set db options
1056   if ($myconfig->{dboptions}) {
1057     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1058   }
1059
1060   $main::lxdebug->leave_sub(2);
1061
1062   return $dbh;
1063 }
1064
1065 sub dbconnect_noauto {
1066   $main::lxdebug->enter_sub();
1067
1068   my ($self, $myconfig) = @_;
1069   
1070   # connect to database
1071   $dbh =
1072     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1073                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
1074     or $self->dberror;
1075
1076   # set db options
1077   if ($myconfig->{dboptions}) {
1078     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1079   }
1080
1081   $main::lxdebug->leave_sub();
1082
1083   return $dbh;
1084 }
1085
1086 sub get_standard_dbh {
1087   $main::lxdebug->enter_sub(2);
1088
1089   my ($self, $myconfig) = @_;
1090
1091   $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1092
1093   $main::lxdebug->leave_sub(2);
1094
1095   return $standard_dbh;
1096 }
1097
1098 sub update_balance {
1099   $main::lxdebug->enter_sub();
1100
1101   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1102
1103   # if we have a value, go do it
1104   if ($value != 0) {
1105
1106     # retrieve balance from table
1107     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1108     my $sth = prepare_execute_query($self, $dbh, $query, @values);
1109     my ($balance) = $sth->fetchrow_array;
1110     $sth->finish;
1111
1112     $balance += $value;
1113
1114     # update balance
1115     $query = "UPDATE $table SET $field = $balance WHERE $where";
1116     do_query($self, $dbh, $query, @values);
1117   }
1118   $main::lxdebug->leave_sub();
1119 }
1120
1121 sub update_exchangerate {
1122   $main::lxdebug->enter_sub();
1123
1124   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1125
1126   # some sanity check for currency
1127   if ($curr eq '') {
1128     $main::lxdebug->leave_sub();
1129     return;
1130   }
1131
1132   my $query = qq|SELECT e.curr FROM exchangerate e
1133                  WHERE e.curr = ? AND e.transdate = ?
1134                  FOR UPDATE|;
1135   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1136
1137   my $set;
1138   if ($buy != 0 && $sell != 0) {
1139     $set = "buy = $buy, sell = $sell";
1140   } elsif ($buy != 0) {
1141     $set = "buy = $buy";
1142   } elsif ($sell != 0) {
1143     $set = "sell = $sell";
1144   }
1145
1146   if ($sth->fetchrow_array) {
1147     $query = qq|UPDATE exchangerate
1148                 SET $set
1149                 WHERE curr = ?
1150                 AND transdate = ?|;
1151   } else {
1152     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1153                 VALUES (?, $buy, $sell, ?)|;
1154   }
1155   $sth->finish;
1156   do_query($self, $dbh, $query, $curr, $transdate);
1157
1158   $main::lxdebug->leave_sub();
1159 }
1160
1161 sub save_exchangerate {
1162   $main::lxdebug->enter_sub();
1163
1164   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1165
1166   my $dbh = $self->dbconnect($myconfig);
1167
1168   my ($buy, $sell) = (0, 0);
1169   $buy  = $rate if $fld eq 'buy';
1170   $sell = $rate if $fld eq 'sell';
1171
1172   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1173
1174   $dbh->disconnect;
1175
1176   $main::lxdebug->leave_sub();
1177 }
1178
1179 sub get_exchangerate {
1180   $main::lxdebug->enter_sub();
1181
1182   my ($self, $dbh, $curr, $transdate, $fld) = @_;
1183
1184   unless ($transdate) {
1185     $main::lxdebug->leave_sub();
1186     return 1;
1187   }
1188
1189   my $query = qq|SELECT e.$fld FROM exchangerate e
1190                  WHERE e.curr = ? AND e.transdate = ?|;
1191   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1192
1193   if (!$exchangerate) {
1194     $exchangerate = 1;
1195   }
1196
1197   $main::lxdebug->leave_sub();
1198
1199   return $exchangerate;
1200 }
1201
1202 sub check_exchangerate {
1203   $main::lxdebug->enter_sub();
1204
1205   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1206
1207   unless ($transdate) {
1208     $main::lxdebug->leave_sub();
1209     return "";
1210   }
1211
1212   my $dbh = $self->dbconnect($myconfig);
1213
1214   my $query = qq|SELECT e.$fld FROM exchangerate e
1215                  WHERE e.curr = ? AND e.transdate = ?|;
1216   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1217   $dbh->disconnect();
1218
1219   $exchangerate = 1 if ($exchangerate == 0);
1220   $exchangerate = 1 if ($exchangerate eq "");
1221
1222   $main::lxdebug->leave_sub();
1223
1224   return $exchangerate;
1225 }
1226
1227 sub set_payment_options {
1228   $main::lxdebug->enter_sub();
1229
1230   my ($self, $myconfig, $transdate) = @_;
1231
1232   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1233
1234   my $dbh = $self->get_standard_dbh($myconfig);
1235
1236   my $query =
1237     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1238     qq|FROM payment_terms p | .
1239     qq|WHERE p.id = ?|;
1240
1241   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1242    $self->{payment_terms}) =
1243      selectrow_query($self, $dbh, $query, $self->{payment_id});
1244
1245   if ($transdate eq "") {
1246     if ($self->{invdate}) {
1247       $transdate = $self->{invdate};
1248     } else {
1249       $transdate = $self->{transdate};
1250     }
1251   }
1252
1253   $query =
1254     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1255     qq|FROM payment_terms|;
1256   ($self->{netto_date}, $self->{skonto_date}) =
1257     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1258
1259   my $total = ($self->{invtotal}) ? $self->{invtotal} : $self->{ordtotal};
1260   my $skonto_amount = $self->parse_amount($myconfig, $total) *
1261     $self->{percent_skonto};
1262
1263   $self->{skonto_amount} =
1264     $self->format_amount($myconfig, $skonto_amount, 2);
1265
1266   if ($self->{"language_id"}) {
1267     $query =
1268       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1269       qq|FROM translation_payment_terms t | .
1270       qq|LEFT JOIN language l ON t.language_id = l.id | .
1271       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1272     my ($description_long, $output_numberformat, $output_dateformat,
1273       $output_longdates) =
1274       selectrow_query($self, $dbh, $query,
1275                       $self->{"language_id"}, $self->{"payment_id"});
1276
1277     $self->{payment_terms} = $description_long if ($description_long);
1278
1279     if ($output_dateformat) {
1280       foreach my $key (qw(netto_date skonto_date)) {
1281         $self->{$key} =
1282           $main::locale->reformat_date($myconfig, $self->{$key},
1283                                        $output_dateformat,
1284                                        $output_longdates);
1285       }
1286     }
1287
1288     if ($output_numberformat &&
1289         ($output_numberformat ne $myconfig->{"numberformat"})) {
1290       my $saved_numberformat = $myconfig->{"numberformat"};
1291       $myconfig->{"numberformat"} = $output_numberformat;
1292       $self->{skonto_amount} =
1293         $self->format_amount($myconfig, $skonto_amount, 2);
1294       $myconfig->{"numberformat"} = $saved_numberformat;
1295     }
1296   }
1297
1298   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1299   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1300   $self->{payment_terms} =~ s/<%skonto_amount%>/$self->{skonto_amount}/g;
1301   $self->{payment_terms} =~ s/<%total%>/$self->{total}/g;
1302   $self->{payment_terms} =~ s/<%invtotal%>/$self->{invtotal}/g;
1303   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1304   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1305   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1306   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1307   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1308
1309   $main::lxdebug->leave_sub();
1310
1311 }
1312
1313 sub get_template_language {
1314   $main::lxdebug->enter_sub();
1315
1316   my ($self, $myconfig) = @_;
1317
1318   my $template_code = "";
1319
1320   if ($self->{language_id}) {
1321     my $dbh = $self->get_standard_dbh($myconfig);
1322     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1323     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1324   }
1325
1326   $main::lxdebug->leave_sub();
1327
1328   return $template_code;
1329 }
1330
1331 sub get_printer_code {
1332   $main::lxdebug->enter_sub();
1333
1334   my ($self, $myconfig) = @_;
1335
1336   my $template_code = "";
1337
1338   if ($self->{printer_id}) {
1339     my $dbh = $self->get_standard_dbh($myconfig);
1340     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1341     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1342   }
1343
1344   $main::lxdebug->leave_sub();
1345
1346   return $template_code;
1347 }
1348
1349 sub get_shipto {
1350   $main::lxdebug->enter_sub();
1351
1352   my ($self, $myconfig) = @_;
1353
1354   my $template_code = "";
1355
1356   if ($self->{shipto_id}) {
1357     my $dbh = $self->get_standard_dbh($myconfig);
1358     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1359     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1360     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1361   }
1362
1363   $main::lxdebug->leave_sub();
1364 }
1365
1366 sub add_shipto {
1367   $main::lxdebug->enter_sub();
1368
1369   my ($self, $dbh, $id, $module) = @_;
1370
1371   my $shipto;
1372   my @values;
1373   foreach my $item (qw(name department_1 department_2 street zipcode city country
1374                        contact phone fax email)) {
1375     if ($self->{"shipto$item"}) {
1376       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1377     }
1378     push(@values, $self->{"shipto${item}"});
1379   }
1380   if ($shipto) {
1381     if ($self->{shipto_id}) {
1382       my $query = qq|UPDATE shipto set
1383                        shiptoname = ?,
1384                        shiptodepartment_1 = ?,
1385                        shiptodepartment_2 = ?,
1386                        shiptostreet = ?,
1387                        shiptozipcode = ?,
1388                        shiptocity = ?,
1389                        shiptocountry = ?,
1390                        shiptocontact = ?,
1391                        shiptophone = ?,
1392                        shiptofax = ?,
1393                        shiptoemail = ?
1394                      WHERE shipto_id = ?|;
1395       do_query($self, $dbh, $query, @values, $self->{shipto_id});
1396     } else {
1397       my $query = qq|SELECT * FROM shipto
1398                      WHERE shiptoname = ? AND
1399                        shiptodepartment_1 = ? AND
1400                        shiptodepartment_2 = ? AND
1401                        shiptostreet = ? AND
1402                        shiptozipcode = ? AND
1403                        shiptocity = ? AND
1404                        shiptocountry = ? AND
1405                        shiptocontact = ? AND
1406                        shiptophone = ? AND
1407                        shiptofax = ? AND
1408                        shiptoemail = ?|;
1409       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values);
1410       if(!$insert_check){
1411         $query =
1412           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1413                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
1414                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
1415              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1416         do_query($self, $dbh, $query, $id, @values, $module);
1417       }
1418     }
1419   }
1420
1421   $main::lxdebug->leave_sub();
1422 }
1423
1424 sub get_employee {
1425   $main::lxdebug->enter_sub();
1426
1427   my ($self, $dbh) = @_;
1428
1429   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1430   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1431   $self->{"employee_id"} *= 1;
1432
1433   $main::lxdebug->leave_sub();
1434 }
1435
1436 sub get_salesman {
1437   $main::lxdebug->enter_sub();
1438
1439   my ($self, $myconfig, $salesman_id) = @_;
1440
1441   $main::lxdebug->leave_sub() and return unless $salesman_id;
1442
1443   my $dbh = $self->get_standard_dbh($myconfig);
1444
1445   my ($login) =
1446     selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|,
1447                     $salesman_id);
1448
1449   if ($login) {
1450     my $user = new User($main::memberfile, $login);
1451     map({ $self->{"salesman_$_"} = $user->{$_}; }
1452         qw(address businessnumber co_ustid company duns email fax name
1453            taxnumber tel));
1454     $self->{salesman_login} = $login;
1455
1456     $self->{salesman_name} = $login
1457       if ($self->{salesman_name} eq "");
1458
1459     map({ $self->{"salesman_$_"} =~ s/\\n/\n/g; } qw(address company));
1460   }
1461
1462   $main::lxdebug->leave_sub();
1463 }
1464
1465 sub get_duedate {
1466   $main::lxdebug->enter_sub();
1467
1468   my ($self, $myconfig) = @_;
1469
1470   my $dbh = $self->get_standard_dbh($myconfig);
1471   my $query = qq|SELECT current_date + terms_netto FROM payment_terms WHERE id = ?|;
1472   ($self->{duedate}) = selectrow_query($self, $dbh, $query, $self->{payment_id});
1473
1474   $main::lxdebug->leave_sub();
1475 }
1476
1477 sub _get_contacts {
1478   $main::lxdebug->enter_sub();
1479
1480   my ($self, $dbh, $id, $key) = @_;
1481
1482   $key = "all_contacts" unless ($key);
1483
1484   my $query =
1485     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
1486     qq|FROM contacts | .
1487     qq|WHERE cp_cv_id = ? | .
1488     qq|ORDER BY lower(cp_name)|;
1489
1490   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
1491
1492   $main::lxdebug->leave_sub();
1493 }
1494
1495 sub _get_projects {
1496   $main::lxdebug->enter_sub();
1497
1498   my ($self, $dbh, $key) = @_;
1499
1500   my ($all, $old_id, $where, @values);
1501
1502   if (ref($key) eq "HASH") {
1503     my $params = $key;
1504
1505     $key = "ALL_PROJECTS";
1506
1507     foreach my $p (keys(%{$params})) {
1508       if ($p eq "all") {
1509         $all = $params->{$p};
1510       } elsif ($p eq "old_id") {
1511         $old_id = $params->{$p};
1512       } elsif ($p eq "key") {
1513         $key = $params->{$p};
1514       }
1515     }
1516   }
1517
1518   if (!$all) {
1519     $where = "WHERE active ";
1520     if ($old_id) {
1521       if (ref($old_id) eq "ARRAY") {
1522         my @ids = grep({ $_ } @{$old_id});
1523         if (@ids) {
1524           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
1525           push(@values, @ids);
1526         }
1527       } else {
1528         $where .= " OR (id = ?) ";
1529         push(@values, $old_id);
1530       }
1531     }
1532   }
1533
1534   my $query =
1535     qq|SELECT id, projectnumber, description, active | .
1536     qq|FROM project | .
1537     $where .
1538     qq|ORDER BY lower(projectnumber)|;
1539
1540   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
1541
1542   $main::lxdebug->leave_sub();
1543 }
1544
1545 sub _get_shipto {
1546   $main::lxdebug->enter_sub();
1547
1548   my ($self, $dbh, $vc_id, $key) = @_;
1549
1550   $key = "all_shipto" unless ($key);
1551
1552   # get shipping addresses
1553   my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
1554
1555   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
1556
1557   $main::lxdebug->leave_sub();
1558 }
1559
1560 sub _get_printers {
1561   $main::lxdebug->enter_sub();
1562
1563   my ($self, $dbh, $key) = @_;
1564
1565   $key = "all_printers" unless ($key);
1566
1567   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
1568
1569   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1570
1571   $main::lxdebug->leave_sub();
1572 }
1573
1574 sub _get_charts {
1575   $main::lxdebug->enter_sub();
1576
1577   my ($self, $dbh, $params) = @_;
1578
1579   $key = $params->{key};
1580   $key = "all_charts" unless ($key);
1581
1582   my $transdate = quote_db_date($params->{transdate});
1583
1584   my $query =
1585     qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
1586     qq|FROM chart c | .
1587     qq|LEFT JOIN taxkeys tk ON | .
1588     qq|(tk.id = (SELECT id FROM taxkeys | .
1589     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
1590     qq|          ORDER BY startdate DESC LIMIT 1)) | .
1591     qq|ORDER BY c.accno|;
1592
1593   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1594
1595   $main::lxdebug->leave_sub();
1596 }
1597
1598 sub _get_taxcharts {
1599   $main::lxdebug->enter_sub();
1600
1601   my ($self, $dbh, $key) = @_;
1602
1603   $key = "all_taxcharts" unless ($key);
1604
1605   my $query = qq|SELECT * FROM tax ORDER BY taxkey|;
1606
1607   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1608
1609   $main::lxdebug->leave_sub();
1610 }
1611
1612 sub _get_taxzones {
1613   $main::lxdebug->enter_sub();
1614
1615   my ($self, $dbh, $key) = @_;
1616
1617   $key = "all_taxzones" unless ($key);
1618
1619   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
1620
1621   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1622
1623   $main::lxdebug->leave_sub();
1624 }
1625
1626 sub _get_employees {
1627   $main::lxdebug->enter_sub();
1628
1629   my ($self, $dbh, $default_key, $key) = @_;
1630
1631   $key = $default_key unless ($key);
1632   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY name|);
1633
1634   $main::lxdebug->leave_sub();
1635 }
1636
1637 sub _get_business_types {
1638   $main::lxdebug->enter_sub();
1639
1640   my ($self, $dbh, $key) = @_;
1641
1642   $key = "all_business_types" unless ($key);
1643   $self->{$key} =
1644     selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
1645
1646   $main::lxdebug->leave_sub();
1647 }
1648
1649 sub _get_languages {
1650   $main::lxdebug->enter_sub();
1651
1652   my ($self, $dbh, $key) = @_;
1653
1654   $key = "all_languages" unless ($key);
1655
1656   my $query = qq|SELECT * FROM language ORDER BY id|;
1657
1658   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1659
1660   $main::lxdebug->leave_sub();
1661 }
1662
1663 sub _get_dunning_configs {
1664   $main::lxdebug->enter_sub();
1665
1666   my ($self, $dbh, $key) = @_;
1667
1668   $key = "all_dunning_configs" unless ($key);
1669
1670   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
1671
1672   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1673
1674   $main::lxdebug->leave_sub();
1675 }
1676
1677 sub _get_currencies {
1678 $main::lxdebug->enter_sub();
1679
1680   my ($self, $dbh, $key) = @_;
1681
1682   $key = "all_currencies" unless ($key);
1683
1684   my $query = qq|SELECT curr AS currency FROM defaults|;
1685  
1686   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
1687
1688   $main::lxdebug->leave_sub();
1689 }
1690
1691 sub _get_payments {
1692 $main::lxdebug->enter_sub();
1693
1694   my ($self, $dbh, $key) = @_;
1695
1696   $key = "all_payments" unless ($key);
1697
1698   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
1699  
1700   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1701
1702   $main::lxdebug->leave_sub();
1703 }
1704
1705 sub _get_customers {
1706   $main::lxdebug->enter_sub();
1707
1708   my ($self, $dbh, $key) = @_;
1709
1710   $key = "all_customers" unless ($key);
1711
1712   my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name|;
1713
1714   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1715
1716   $main::lxdebug->leave_sub();
1717 }
1718
1719 sub _get_vendors {
1720   $main::lxdebug->enter_sub();
1721
1722   my ($self, $dbh, $key) = @_;
1723
1724   $key = "all_vendors" unless ($key);
1725
1726   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
1727
1728   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1729
1730   $main::lxdebug->leave_sub();
1731 }
1732
1733 sub _get_departments {
1734   $main::lxdebug->enter_sub();
1735
1736   my ($self, $dbh, $key) = @_;
1737
1738   $key = "all_departments" unless ($key);
1739
1740   my $query = qq|SELECT * FROM department ORDER BY description|;
1741
1742   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1743
1744   $main::lxdebug->leave_sub();
1745 }
1746
1747 sub get_lists {
1748   $main::lxdebug->enter_sub();
1749
1750   my $self = shift;
1751   my %params = @_;
1752
1753   my $dbh = $self->get_standard_dbh(\%main::myconfig);
1754   my ($sth, $query, $ref);
1755
1756   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
1757   my $vc_id = $self->{"${vc}_id"};
1758
1759   if ($params{"contacts"}) {
1760     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
1761   }
1762
1763   if ($params{"shipto"}) {
1764     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
1765   }
1766
1767   if ($params{"projects"} || $params{"all_projects"}) {
1768     $self->_get_projects($dbh, $params{"all_projects"} ?
1769                          $params{"all_projects"} : $params{"projects"},
1770                          $params{"all_projects"} ? 1 : 0);
1771   }
1772
1773   if ($params{"printers"}) {
1774     $self->_get_printers($dbh, $params{"printers"});
1775   }
1776
1777   if ($params{"languages"}) {
1778     $self->_get_languages($dbh, $params{"languages"});
1779   }
1780
1781   if ($params{"charts"}) {
1782     $self->_get_charts($dbh, $params{"charts"});
1783   }
1784
1785   if ($params{"taxcharts"}) {
1786     $self->_get_taxcharts($dbh, $params{"taxcharts"});
1787   }
1788
1789   if ($params{"taxzones"}) {
1790     $self->_get_taxzones($dbh, $params{"taxzones"});
1791   }
1792
1793   if ($params{"employees"}) {
1794     $self->_get_employees($dbh, "all_employees", $params{"employees"});
1795   }
1796   
1797   if ($params{"salesmen"}) {
1798     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
1799   }
1800
1801   if ($params{"business_types"}) {
1802     $self->_get_business_types($dbh, $params{"business_types"});
1803   }
1804
1805   if ($params{"dunning_configs"}) {
1806     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
1807   }
1808   
1809   if($params{"currencies"}) {
1810     $self->_get_currencies($dbh, $params{"currencies"});
1811   }
1812   
1813   if($params{"customers"}) {
1814     $self->_get_customers($dbh, $params{"customers"});
1815   }
1816   
1817   if($params{"vendors"}) {
1818     $self->_get_vendors($dbh, $params{"vendors"});
1819   }
1820   
1821   if($params{"payments"}) {
1822     $self->_get_payments($dbh, $params{"payments"});
1823   }
1824
1825   if($params{"departments"}) {
1826     $self->_get_departments($dbh, $params{"departments"});
1827   }
1828
1829   $main::lxdebug->leave_sub();
1830 }
1831
1832 # this sub gets the id and name from $table
1833 sub get_name {
1834   $main::lxdebug->enter_sub();
1835
1836   my ($self, $myconfig, $table) = @_;
1837
1838   # connect to database
1839   my $dbh = $self->get_standard_dbh($myconfig);
1840
1841   $table = $table eq "customer" ? "customer" : "vendor";
1842   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
1843
1844   my ($query, @values);
1845
1846   if (!$self->{openinvoices}) {
1847     my $where;
1848     if ($self->{customernumber} ne "") {
1849       $where = qq|(vc.customernumber ILIKE ?)|;
1850       push(@values, '%' . $self->{customernumber} . '%');
1851     } else {
1852       $where = qq|(vc.name ILIKE ?)|;
1853       push(@values, '%' . $self->{$table} . '%');
1854     }
1855
1856     $query =
1857       qq~SELECT vc.id, vc.name,
1858            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
1859          FROM $table vc
1860          WHERE $where AND (NOT vc.obsolete)
1861          ORDER BY vc.name~;
1862   } else {
1863     $query =
1864       qq~SELECT DISTINCT vc.id, vc.name,
1865            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
1866          FROM $arap a
1867          JOIN $table vc ON (a.${table}_id = vc.id)
1868          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
1869          ORDER BY vc.name~;
1870     push(@values, '%' . $self->{$table} . '%');
1871   }
1872
1873   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
1874
1875   $main::lxdebug->leave_sub();
1876
1877   return scalar(@{ $self->{name_list} });
1878 }
1879
1880 # the selection sub is used in the AR, AP, IS, IR and OE module
1881 #
1882 sub all_vc {
1883   $main::lxdebug->enter_sub();
1884
1885   my ($self, $myconfig, $table, $module) = @_;
1886
1887   my $ref;
1888   my $dbh = $self->get_standard_dbh($myconfig);
1889
1890   $table = $table eq "customer" ? "customer" : "vendor";
1891
1892   my $query = qq|SELECT count(*) FROM $table|;
1893   my ($count) = selectrow_query($self, $dbh, $query);
1894
1895   # build selection list
1896   if ($count < $myconfig->{vclimit}) {
1897     $query = qq|SELECT id, name, salesman_id
1898                 FROM $table WHERE NOT obsolete
1899                 ORDER BY name|;
1900     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
1901   }
1902
1903   # get self
1904   $self->get_employee($dbh);
1905
1906   # setup sales contacts
1907   $query = qq|SELECT e.id, e.name
1908               FROM employee e
1909               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
1910   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
1911
1912   # this is for self
1913   push(@{ $self->{all_employees} },
1914        { id   => $self->{employee_id},
1915          name => $self->{employee} });
1916
1917   # sort the whole thing
1918   @{ $self->{all_employees} } =
1919     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
1920
1921   if ($module eq 'AR') {
1922
1923     # prepare query for departments
1924     $query = qq|SELECT id, description
1925                 FROM department
1926                 WHERE role = 'P'
1927                 ORDER BY description|;
1928
1929   } else {
1930     $query = qq|SELECT id, description
1931                 FROM department
1932                 ORDER BY description|;
1933   }
1934
1935   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
1936
1937   # get languages
1938   $query = qq|SELECT id, description
1939               FROM language
1940               ORDER BY id|;
1941
1942   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
1943
1944   # get printer
1945   $query = qq|SELECT printer_description, id
1946               FROM printers
1947               ORDER BY printer_description|;
1948
1949   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
1950
1951   # get payment terms
1952   $query = qq|SELECT id, description
1953               FROM payment_terms
1954               ORDER BY sortkey|;
1955
1956   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
1957
1958   $main::lxdebug->leave_sub();
1959 }
1960
1961 sub language_payment {
1962   $main::lxdebug->enter_sub();
1963
1964   my ($self, $myconfig) = @_;
1965
1966   my $dbh = $self->get_standard_dbh($myconfig);
1967   # get languages
1968   my $query = qq|SELECT id, description
1969                  FROM language
1970                  ORDER BY id|;
1971
1972   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
1973
1974   # get printer
1975   $query = qq|SELECT printer_description, id
1976               FROM printers
1977               ORDER BY printer_description|;
1978
1979   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
1980
1981   # get payment terms
1982   $query = qq|SELECT id, description
1983               FROM payment_terms
1984               ORDER BY sortkey|;
1985
1986   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
1987
1988   # get buchungsgruppen
1989   $query = qq|SELECT id, description
1990               FROM buchungsgruppen|;
1991
1992   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
1993
1994   $main::lxdebug->leave_sub();
1995 }
1996
1997 # this is only used for reports
1998 sub all_departments {
1999   $main::lxdebug->enter_sub();
2000
2001   my ($self, $myconfig, $table) = @_;
2002
2003   my $dbh = $self->get_standard_dbh($myconfig);
2004   my $where;
2005
2006   if ($table eq 'customer') {
2007     $where = "WHERE role = 'P' ";
2008   }
2009
2010   my $query = qq|SELECT id, description
2011                  FROM department
2012                  $where
2013                  ORDER BY description|;
2014   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2015
2016   delete($self->{all_departments}) unless (@{ $self->{all_departments} });
2017
2018   $main::lxdebug->leave_sub();
2019 }
2020
2021 sub create_links {
2022   $main::lxdebug->enter_sub();
2023
2024   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2025
2026   my ($fld, $arap);
2027   if ($table eq "customer") {
2028     $fld = "buy";
2029     $arap = "ar";
2030   } else {
2031     $table = "vendor";
2032     $fld = "sell";
2033     $arap = "ap";
2034   }
2035
2036   $self->all_vc($myconfig, $table, $module);
2037
2038   # get last customers or vendors
2039   my ($query, $sth, $ref);
2040
2041   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2042   my %xkeyref = ();
2043
2044   if (!$self->{id}) {
2045
2046     my $transdate = "current_date";
2047     if ($self->{transdate}) {
2048       $transdate = $dbh->quote($self->{transdate});
2049     }
2050
2051     # now get the account numbers
2052     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2053                 FROM chart c, taxkeys tk
2054                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2055                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2056                 ORDER BY c.accno|;
2057
2058     $sth = $dbh->prepare($query);
2059
2060     do_statement($self, $sth, $query, '%' . $module . '%');
2061
2062     $self->{accounts} = "";
2063     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2064
2065       foreach my $key (split(/:/, $ref->{link})) {
2066         if ($key =~ /$module/) {
2067
2068           # cross reference for keys
2069           $xkeyref{ $ref->{accno} } = $key;
2070
2071           push @{ $self->{"${module}_links"}{$key} },
2072             { accno       => $ref->{accno},
2073               description => $ref->{description},
2074               taxkey      => $ref->{taxkey_id},
2075               tax_id      => $ref->{tax_id} };
2076
2077           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2078         }
2079       }
2080     }
2081   }
2082
2083   # get taxkeys and description
2084   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2085   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2086
2087   if (($module eq "AP") || ($module eq "AR")) {
2088     # get tax rates and description
2089     $query = qq|SELECT * FROM tax|;
2090     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2091   }
2092
2093   if ($self->{id}) {
2094     $query =
2095       qq|SELECT
2096            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2097            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2098            a.intnotes, a.department_id, a.amount AS oldinvtotal,
2099            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2100            c.name AS $table,
2101            d.description AS department,
2102            e.name AS employee
2103          FROM $arap a
2104          JOIN $table c ON (a.${table}_id = c.id)
2105          LEFT JOIN employee e ON (e.id = a.employee_id)
2106          LEFT JOIN department d ON (d.id = a.department_id)
2107          WHERE a.id = ?|;
2108     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2109
2110     foreach $key (keys %$ref) {
2111       $self->{$key} = $ref->{$key};
2112     }
2113
2114     my $transdate = "current_date";
2115     if ($self->{transdate}) {
2116       $transdate = $dbh->quote($self->{transdate});
2117     }
2118
2119     # now get the account numbers
2120     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2121                 FROM chart c
2122                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2123                 WHERE c.link LIKE ?
2124                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2125                     OR c.link LIKE '%_tax%')
2126                 ORDER BY c.accno|;
2127
2128     $sth = $dbh->prepare($query);
2129     do_statement($self, $sth, $query, "%$module%");
2130
2131     $self->{accounts} = "";
2132     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2133
2134       foreach my $key (split(/:/, $ref->{link})) {
2135         if ($key =~ /$module/) {
2136
2137           # cross reference for keys
2138           $xkeyref{ $ref->{accno} } = $key;
2139
2140           push @{ $self->{"${module}_links"}{$key} },
2141             { accno       => $ref->{accno},
2142               description => $ref->{description},
2143               taxkey      => $ref->{taxkey_id},
2144               tax_id      => $ref->{tax_id} };
2145
2146           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2147         }
2148       }
2149     }
2150
2151
2152     # get amounts from individual entries
2153     $query =
2154       qq|SELECT
2155            c.accno, c.description,
2156            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2157            p.projectnumber,
2158            t.rate, t.id
2159          FROM acc_trans a
2160          LEFT JOIN chart c ON (c.id = a.chart_id)
2161          LEFT JOIN project p ON (p.id = a.project_id)
2162          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2163                                     WHERE (tk.taxkey_id=a.taxkey) AND
2164                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2165                                         THEN tk.chart_id = a.chart_id
2166                                         ELSE 1 = 1
2167                                         END)
2168                                        OR (c.link='%tax%')) AND
2169                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2170          WHERE a.trans_id = ?
2171          AND a.fx_transaction = '0'
2172          ORDER BY a.oid, a.transdate|;
2173     $sth = $dbh->prepare($query);
2174     do_statement($self, $sth, $query, $self->{id});
2175
2176     # get exchangerate for currency
2177     $self->{exchangerate} =
2178       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2179     my $index = 0;
2180
2181     # store amounts in {acc_trans}{$key} for multiple accounts
2182     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2183       $ref->{exchangerate} =
2184         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2185       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2186         $index++;
2187       }
2188       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2189         $ref->{amount} *= -1;
2190       }
2191       $ref->{index} = $index;
2192
2193       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2194     }
2195
2196     $sth->finish;
2197     $query =
2198       qq|SELECT
2199            d.curr AS currencies, d.closedto, d.revtrans,
2200            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2201            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2202          FROM defaults d|;
2203     $ref = selectfirst_hashref_query($self, $dbh, $query);
2204     map { $self->{$_} = $ref->{$_} } keys %$ref;
2205
2206   } else {
2207
2208     # get date
2209     $query =
2210        qq|SELECT
2211             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2212             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2213             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2214           FROM defaults d|;
2215     $ref = selectfirst_hashref_query($self, $dbh, $query);
2216     map { $self->{$_} = $ref->{$_} } keys %$ref;
2217
2218     if ($self->{"$self->{vc}_id"}) {
2219
2220       # only setup currency
2221       ($self->{currency}) = split(/:/, $self->{currencies});
2222
2223     } else {
2224
2225       $self->lastname_used($dbh, $myconfig, $table, $module);
2226
2227       # get exchangerate for currency
2228       $self->{exchangerate} =
2229         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2230
2231     }
2232
2233   }
2234
2235   $main::lxdebug->leave_sub();
2236 }
2237
2238 sub lastname_used {
2239   $main::lxdebug->enter_sub();
2240
2241   my ($self, $dbh, $myconfig, $table, $module) = @_;
2242
2243   my $arap  = ($table eq 'customer') ? "ar" : "ap";
2244   $table = $table eq "customer" ? "customer" : "vendor";
2245   my $where = "1 = 1";
2246
2247   if ($self->{type} =~ /_order/) {
2248     $arap  = 'oe';
2249     $where = "quotation = '0'";
2250   }
2251   if ($self->{type} =~ /_quotation/) {
2252     $arap  = 'oe';
2253     $where = "quotation = '1'";
2254   }
2255
2256   my $query = qq|SELECT MAX(id) FROM $arap
2257                  WHERE $where AND ${table}_id > 0|;
2258   my ($trans_id) = selectrow_query($self, $dbh, $query);
2259
2260   $trans_id *= 1;
2261   $query =
2262     qq|SELECT
2263          a.curr, a.${table}_id, a.department_id,
2264          d.description AS department,
2265          ct.name, current_date + ct.terms AS duedate
2266        FROM $arap a
2267        LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2268        LEFT JOIN department d ON (a.department_id = d.id)
2269        WHERE a.id = ?|;
2270   ($self->{currency},   $self->{"${table}_id"}, $self->{department_id},
2271    $self->{department}, $self->{$table},        $self->{duedate})
2272     = selectrow_query($self, $dbh, $query, $trans_id);
2273
2274   $main::lxdebug->leave_sub();
2275 }
2276
2277 sub current_date {
2278   $main::lxdebug->enter_sub();
2279
2280   my ($self, $myconfig, $thisdate, $days) = @_;
2281
2282   my $dbh = $self->get_standard_dbh($myconfig);
2283   my $query;
2284
2285   $days *= 1;
2286   if ($thisdate) {
2287     my $dateformat = $myconfig->{dateformat};
2288     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2289     $thisdate = $dbh->quote($thisdate);
2290     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2291   } else {
2292     $query = qq|SELECT current_date AS thisdate|;
2293   }
2294
2295   ($thisdate) = selectrow_query($self, $dbh, $query);
2296
2297   $main::lxdebug->leave_sub();
2298
2299   return $thisdate;
2300 }
2301
2302 sub like {
2303   $main::lxdebug->enter_sub();
2304
2305   my ($self, $string) = @_;
2306
2307   if ($string !~ /%/) {
2308     $string = "%$string%";
2309   }
2310
2311   $string =~ s/\'/\'\'/g;
2312
2313   $main::lxdebug->leave_sub();
2314
2315   return $string;
2316 }
2317
2318 sub redo_rows {
2319   $main::lxdebug->enter_sub();
2320
2321   my ($self, $flds, $new, $count, $numrows) = @_;
2322
2323   my @ndx = ();
2324
2325   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } }
2326     (1 .. $count);
2327
2328   my $i = 0;
2329
2330   # fill rows
2331   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2332     $i++;
2333     $j = $item->{ndx} - 1;
2334     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2335   }
2336
2337   # delete empty rows
2338   for $i ($count + 1 .. $numrows) {
2339     map { delete $self->{"${_}_$i"} } @{$flds};
2340   }
2341
2342   $main::lxdebug->leave_sub();
2343 }
2344
2345 sub update_status {
2346   $main::lxdebug->enter_sub();
2347
2348   my ($self, $myconfig) = @_;
2349
2350   my ($i, $id);
2351
2352   my $dbh = $self->dbconnect_noauto($myconfig);
2353
2354   my $query = qq|DELETE FROM status
2355                  WHERE (formname = ?) AND (trans_id = ?)|;
2356   my $sth = prepare_query($self, $dbh, $query);
2357
2358   if ($self->{formname} =~ /(check|receipt)/) {
2359     for $i (1 .. $self->{rowcount}) {
2360       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
2361     }
2362   } else {
2363     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
2364   }
2365   $sth->finish();
2366
2367   my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
2368   my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
2369
2370   my %queued = split / /, $self->{queued};
2371   my @values;
2372
2373   if ($self->{formname} =~ /(check|receipt)/) {
2374
2375     # this is a check or receipt, add one entry for each lineitem
2376     my ($accno) = split /--/, $self->{account};
2377     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
2378                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
2379     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
2380     $sth = prepare_query($self, $dbh, $query);
2381
2382     for $i (1 .. $self->{rowcount}) {
2383       if ($self->{"checked_$i"}) {
2384         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
2385       }
2386     }
2387     $sth->finish();
2388
2389   } else {
2390     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2391                 VALUES (?, ?, ?, ?, ?)|;
2392     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
2393              $queued{$self->{formname}}, $self->{formname});
2394   }
2395
2396   $dbh->commit;
2397   $dbh->disconnect;
2398
2399   $main::lxdebug->leave_sub();
2400 }
2401
2402 sub save_status {
2403   $main::lxdebug->enter_sub();
2404
2405   my ($self, $dbh) = @_;
2406
2407   my ($query, $printed, $emailed);
2408
2409   my $formnames  = $self->{printed};
2410   my $emailforms = $self->{emailed};
2411
2412   my $query = qq|DELETE FROM status
2413                  WHERE (formname = ?) AND (trans_id = ?)|;
2414   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
2415
2416   # this only applies to the forms
2417   # checks and receipts are posted when printed or queued
2418
2419   if ($self->{queued}) {
2420     my %queued = split / /, $self->{queued};
2421
2422     foreach my $formname (keys %queued) {
2423       $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
2424       $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
2425
2426       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2427                   VALUES (?, ?, ?, ?, ?)|;
2428       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
2429
2430       $formnames  =~ s/$self->{formname}//;
2431       $emailforms =~ s/$self->{formname}//;
2432
2433     }
2434   }
2435
2436   # save printed, emailed info
2437   $formnames  =~ s/^ +//g;
2438   $emailforms =~ s/^ +//g;
2439
2440   my %status = ();
2441   map { $status{$_}{printed} = 1 } split / +/, $formnames;
2442   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
2443
2444   foreach my $formname (keys %status) {
2445     $printed = ($formnames  =~ /$self->{formname}/) ? "1" : "0";
2446     $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
2447
2448     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
2449                 VALUES (?, ?, ?, ?)|;
2450     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
2451   }
2452
2453   $main::lxdebug->leave_sub();
2454 }
2455
2456 #--- 4 locale ---#
2457 # $main::locale->text('SAVED')
2458 # $main::locale->text('DELETED')
2459 # $main::locale->text('ADDED')
2460 # $main::locale->text('PAYMENT POSTED')
2461 # $main::locale->text('POSTED')
2462 # $main::locale->text('POSTED AS NEW')
2463 # $main::locale->text('ELSE')
2464 # $main::locale->text('SAVED FOR DUNNING')
2465 # $main::locale->text('DUNNING STARTED')
2466 # $main::locale->text('PRINTED')
2467 # $main::locale->text('MAILED')
2468 # $main::locale->text('SCREENED')
2469 # $main::locale->text('CANCELED')
2470 # $main::locale->text('invoice')
2471 # $main::locale->text('proforma')
2472 # $main::locale->text('sales_order')
2473 # $main::locale->text('packing_list')
2474 # $main::locale->text('pick_list')
2475 # $main::locale->text('purchase_order')
2476 # $main::locale->text('bin_list')
2477 # $main::locale->text('sales_quotation')
2478 # $main::locale->text('request_quotation')
2479
2480 sub save_history {
2481   $main::lxdebug->enter_sub();
2482
2483   my $self = shift();
2484   my $dbh = shift();
2485
2486   if(!exists $self->{employee_id}) {
2487     &get_employee($self, $dbh);
2488   }
2489
2490   my $query =
2491    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
2492    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
2493   my @values = (conv_i($self->{id}), $self->{login},
2494                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
2495   do_query($self, $dbh, $query, @values);
2496
2497   $main::lxdebug->leave_sub();
2498 }
2499
2500 sub get_history {
2501   $main::lxdebug->enter_sub();
2502
2503   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
2504   my ($orderBy, $desc) = split(/\-\-/, $order);
2505   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
2506   my @tempArray;
2507   my $i = 0;
2508   if ($trans_id ne "") {
2509     my $query =
2510       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 | .
2511       qq|FROM history_erp h | .
2512       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
2513       qq|WHERE trans_id = | . $trans_id
2514       . $restriction . qq| |
2515       . $order;
2516       
2517     my $sth = $dbh->prepare($query) || $self->dberror($query);
2518
2519     $sth->execute() || $self->dberror("$query");
2520
2521     while(my $hash_ref = $sth->fetchrow_hashref()) {
2522       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
2523       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
2524       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
2525       $tempArray[$i++] = $hash_ref;
2526     }
2527     $main::lxdebug->leave_sub() and return \@tempArray 
2528       if ($i > 0 && $tempArray[0] ne "");
2529   }
2530   $main::lxdebug->leave_sub();
2531   return 0;
2532 }
2533
2534 sub update_defaults {
2535   $main::lxdebug->enter_sub();
2536
2537   my ($self, $myconfig, $fld, $provided_dbh) = @_;
2538
2539   my $dbh;
2540   if ($provided_dbh) {
2541     $dbh = $provided_dbh;
2542   } else {
2543     $dbh = $self->dbconnect_noauto($myconfig);
2544   }
2545   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
2546   my $sth   = $dbh->prepare($query);
2547
2548   $sth->execute || $self->dberror($query);
2549   my ($var) = $sth->fetchrow_array;
2550   $sth->finish;
2551
2552   $var =~ s/\d+$/ sprintf '%0*d', length($&), $&+1 /e;
2553   $var ||= 1;
2554
2555   $query = qq|UPDATE defaults SET $fld = ?|;
2556   do_query($self, $dbh, $query, $var);
2557
2558   if (!$provided_dbh) {
2559     $dbh->commit;
2560     $dbh->disconnect;
2561   }
2562
2563   $main::lxdebug->leave_sub();
2564
2565   return $var;
2566 }
2567
2568 sub update_business {
2569   $main::lxdebug->enter_sub();
2570
2571   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
2572
2573   my $dbh;
2574   if ($provided_dbh) {
2575     $dbh = $provided_dbh;
2576   } else {
2577     $dbh = $self->dbconnect_noauto($myconfig);
2578   }
2579   my $query =
2580     qq|SELECT customernumberinit FROM business
2581        WHERE id = ? FOR UPDATE|;
2582   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
2583
2584   $var =~ s/\d+$/ sprintf '%0*d', length($&), $&+1 /e;
2585   
2586   $query = qq|UPDATE business
2587               SET customernumberinit = ?
2588               WHERE id = ?|;
2589   do_query($self, $dbh, $query, $var, $business_id);
2590
2591   if (!$provided_dbh) {
2592     $dbh->commit;
2593     $dbh->disconnect;
2594   }
2595
2596   $main::lxdebug->leave_sub();
2597
2598   return $var;
2599 }
2600
2601 sub get_partsgroup {
2602   $main::lxdebug->enter_sub();
2603
2604   my ($self, $myconfig, $p) = @_;
2605
2606   my $dbh = $self->get_standard_dbh($myconfig);
2607
2608   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
2609                  FROM partsgroup pg
2610                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
2611   my @values;
2612
2613   if ($p->{searchitems} eq 'part') {
2614     $query .= qq|WHERE p.inventory_accno_id > 0|;
2615   }
2616   if ($p->{searchitems} eq 'service') {
2617     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
2618   }
2619   if ($p->{searchitems} eq 'assembly') {
2620     $query .= qq|WHERE p.assembly = '1'|;
2621   }
2622   if ($p->{searchitems} eq 'labor') {
2623     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
2624   }
2625
2626   $query .= qq|ORDER BY partsgroup|;
2627
2628   if ($p->{all}) {
2629     $query = qq|SELECT id, partsgroup FROM partsgroup
2630                 ORDER BY partsgroup|;
2631   }
2632
2633   if ($p->{language_code}) {
2634     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
2635                   t.description AS translation
2636                 FROM partsgroup pg
2637                 JOIN parts p ON (p.partsgroup_id = pg.id)
2638                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
2639                 ORDER BY translation|;
2640     @values = ($p->{language_code});
2641   }
2642
2643   $self->{all_partsgroup} = selectall_hashref_query($self, $dbh, $query, @values);
2644
2645   $main::lxdebug->leave_sub();
2646 }
2647
2648 sub get_pricegroup {
2649   $main::lxdebug->enter_sub();
2650
2651   my ($self, $myconfig, $p) = @_;
2652
2653   my $dbh = $self->get_standard_dbh($myconfig);
2654
2655   my $query = qq|SELECT p.id, p.pricegroup
2656                  FROM pricegroup p|;
2657
2658   $query .= qq| ORDER BY pricegroup|;
2659
2660   if ($p->{all}) {
2661     $query = qq|SELECT id, pricegroup FROM pricegroup
2662                 ORDER BY pricegroup|;
2663   }
2664
2665   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
2666
2667   $main::lxdebug->leave_sub();
2668 }
2669
2670 sub all_years {
2671 # usage $form->all_years($myconfig, [$dbh])
2672 # return list of all years where bookings found
2673 # (@all_years)
2674
2675   $main::lxdebug->enter_sub();
2676
2677   my ($self, $myconfig, $dbh) = @_;
2678
2679   $dbh ||= $self->get_standard_dbh($myconfig);
2680
2681   # get years
2682   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
2683                    (SELECT MAX(transdate) FROM acc_trans)|;
2684   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
2685
2686   if ($myconfig->{dateformat} =~ /^yy/) {
2687     ($startdate) = split /\W/, $startdate;
2688     ($enddate) = split /\W/, $enddate;
2689   } else {
2690     (@_) = split /\W/, $startdate;
2691     $startdate = $_[2];
2692     (@_) = split /\W/, $enddate;
2693     $enddate = $_[2];
2694   }
2695
2696   my @all_years;
2697   $startdate = substr($startdate,0,4);
2698   $enddate = substr($enddate,0,4);
2699
2700   while ($enddate >= $startdate) {
2701     push @all_years, $enddate--;
2702   }
2703
2704   return @all_years;
2705
2706   $main::lxdebug->leave_sub();
2707 }
2708
2709 1;