Falschen Spaltennamen korrigiert.
[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   my $query = qq|SELECT curr FROM defaults|;
1132
1133   my ($currency) = selectrow_query($self, $dbh, $query);
1134   my ($defaultcurrency) = split m/:/, $currency;
1135
1136
1137   if ($curr eq $defaultcurrency) {
1138     $main::lxdebug->leave_sub();
1139     return;
1140   }
1141
1142   my $query = qq|SELECT e.curr FROM exchangerate e
1143                  WHERE e.curr = ? AND e.transdate = ?
1144                  FOR UPDATE|;
1145   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1146
1147   if ($buy == 0) {
1148     $buy = "";
1149   }
1150   if ($sell == 0) {
1151     $sell = "";
1152   }
1153
1154   $buy = conv_i($buy, "NULL");
1155   $sell = conv_i($sell, "NULL");
1156
1157   my $set;
1158   if ($buy != 0 && $sell != 0) {
1159     $set = "buy = $buy, sell = $sell";
1160   } elsif ($buy != 0) {
1161     $set = "buy = $buy";
1162   } elsif ($sell != 0) {
1163     $set = "sell = $sell";
1164   }
1165
1166   if ($sth->fetchrow_array) {
1167     $query = qq|UPDATE exchangerate
1168                 SET $set
1169                 WHERE curr = ?
1170                 AND transdate = ?|;
1171     
1172   } else {
1173     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1174                 VALUES (?, $buy, $sell, ?)|;
1175   }
1176   $sth->finish;
1177   do_query($self, $dbh, $query, $curr, $transdate);
1178
1179   $main::lxdebug->leave_sub();
1180 }
1181
1182 sub save_exchangerate {
1183   $main::lxdebug->enter_sub();
1184
1185   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1186
1187   my $dbh = $self->dbconnect($myconfig);
1188
1189   my ($buy, $sell);
1190
1191   $buy  = $rate if $fld eq 'buy';
1192   $sell = $rate if $fld eq 'sell';
1193
1194
1195   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1196
1197
1198   $dbh->disconnect;
1199
1200   $main::lxdebug->leave_sub();
1201 }
1202
1203 sub get_exchangerate {
1204   $main::lxdebug->enter_sub();
1205
1206   my ($self, $dbh, $curr, $transdate, $fld) = @_;
1207
1208   unless ($transdate) {
1209     $main::lxdebug->leave_sub();
1210     return 1;
1211   }
1212
1213   my $query = qq|SELECT curr FROM defaults|;
1214
1215   my ($currency) = selectrow_query($self, $dbh, $query);
1216   my ($defaultcurrency) = split m/:/, $currency;
1217
1218   if ($currency eq $defaultcurrency) {
1219     $main::lxdebug->leave_sub();
1220     return 1;
1221   }
1222
1223   my $query = qq|SELECT e.$fld FROM exchangerate e
1224                  WHERE e.curr = ? AND e.transdate = ?|;
1225   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1226
1227
1228
1229   $main::lxdebug->leave_sub();
1230
1231   return $exchangerate;
1232 }
1233
1234 sub check_exchangerate {
1235   $main::lxdebug->enter_sub();
1236
1237   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1238
1239   unless ($transdate) {
1240     $main::lxdebug->leave_sub();
1241     return "";
1242   }
1243
1244   my ($defaultcurrency) = $self->get_default_currency($myconfig);
1245
1246   if ($currency eq $defaultcurrency) {
1247     $main::lxdebug->leave_sub();
1248     return 1;
1249   }
1250
1251   my $dbh   = $self->get_standard_dbh($myconfig);
1252   my $query = qq|SELECT e.$fld FROM exchangerate e
1253                  WHERE e.curr = ? AND e.transdate = ?|;
1254
1255   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1256
1257   $exchangerate = 1 if ($exchangerate eq "");
1258
1259   $main::lxdebug->leave_sub();
1260
1261   return $exchangerate;
1262 }
1263
1264 sub get_default_currency {
1265   $main::lxdebug->enter_sub();
1266
1267   my ($self, $myconfig) = @_;
1268   my $dbh = $self->get_standard_dbh($myconfig);
1269
1270   my $query = qq|SELECT curr FROM defaults|;
1271
1272   my ($curr)            = selectrow_query($self, $dbh, $query);
1273   my ($defaultcurrency) = split m/:/, $curr;
1274
1275   $main::lxdebug->leave_sub();
1276
1277   return $defaultcurrency;
1278 }
1279
1280
1281 sub set_payment_options {
1282   $main::lxdebug->enter_sub();
1283
1284   my ($self, $myconfig, $transdate) = @_;
1285
1286   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1287
1288   my $dbh = $self->get_standard_dbh($myconfig);
1289
1290   my $query =
1291     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1292     qq|FROM payment_terms p | .
1293     qq|WHERE p.id = ?|;
1294
1295   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1296    $self->{payment_terms}) =
1297      selectrow_query($self, $dbh, $query, $self->{payment_id});
1298
1299   if ($transdate eq "") {
1300     if ($self->{invdate}) {
1301       $transdate = $self->{invdate};
1302     } else {
1303       $transdate = $self->{transdate};
1304     }
1305   }
1306
1307   $query =
1308     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1309     qq|FROM payment_terms|;
1310   ($self->{netto_date}, $self->{skonto_date}) =
1311     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1312
1313   my $total = ($self->{invtotal}) ? $self->{invtotal} : $self->{ordtotal};
1314   my $skonto_amount = $self->parse_amount($myconfig, $total) *
1315     $self->{percent_skonto};
1316
1317   $self->{skonto_amount} =
1318     $self->format_amount($myconfig, $skonto_amount, 2);
1319
1320   if ($self->{"language_id"}) {
1321     $query =
1322       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1323       qq|FROM translation_payment_terms t | .
1324       qq|LEFT JOIN language l ON t.language_id = l.id | .
1325       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1326     my ($description_long, $output_numberformat, $output_dateformat,
1327       $output_longdates) =
1328       selectrow_query($self, $dbh, $query,
1329                       $self->{"language_id"}, $self->{"payment_id"});
1330
1331     $self->{payment_terms} = $description_long if ($description_long);
1332
1333     if ($output_dateformat) {
1334       foreach my $key (qw(netto_date skonto_date)) {
1335         $self->{$key} =
1336           $main::locale->reformat_date($myconfig, $self->{$key},
1337                                        $output_dateformat,
1338                                        $output_longdates);
1339       }
1340     }
1341
1342     if ($output_numberformat &&
1343         ($output_numberformat ne $myconfig->{"numberformat"})) {
1344       my $saved_numberformat = $myconfig->{"numberformat"};
1345       $myconfig->{"numberformat"} = $output_numberformat;
1346       $self->{skonto_amount} =
1347         $self->format_amount($myconfig, $skonto_amount, 2);
1348       $myconfig->{"numberformat"} = $saved_numberformat;
1349     }
1350   }
1351
1352   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1353   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1354   $self->{payment_terms} =~ s/<%skonto_amount%>/$self->{skonto_amount}/g;
1355   $self->{payment_terms} =~ s/<%total%>/$self->{total}/g;
1356   $self->{payment_terms} =~ s/<%invtotal%>/$self->{invtotal}/g;
1357   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1358   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1359   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1360   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1361   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1362
1363   $main::lxdebug->leave_sub();
1364
1365 }
1366
1367 sub get_template_language {
1368   $main::lxdebug->enter_sub();
1369
1370   my ($self, $myconfig) = @_;
1371
1372   my $template_code = "";
1373
1374   if ($self->{language_id}) {
1375     my $dbh = $self->get_standard_dbh($myconfig);
1376     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1377     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1378   }
1379
1380   $main::lxdebug->leave_sub();
1381
1382   return $template_code;
1383 }
1384
1385 sub get_printer_code {
1386   $main::lxdebug->enter_sub();
1387
1388   my ($self, $myconfig) = @_;
1389
1390   my $template_code = "";
1391
1392   if ($self->{printer_id}) {
1393     my $dbh = $self->get_standard_dbh($myconfig);
1394     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1395     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1396   }
1397
1398   $main::lxdebug->leave_sub();
1399
1400   return $template_code;
1401 }
1402
1403 sub get_shipto {
1404   $main::lxdebug->enter_sub();
1405
1406   my ($self, $myconfig) = @_;
1407
1408   my $template_code = "";
1409
1410   if ($self->{shipto_id}) {
1411     my $dbh = $self->get_standard_dbh($myconfig);
1412     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1413     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1414     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1415   }
1416
1417   $main::lxdebug->leave_sub();
1418 }
1419
1420 sub add_shipto {
1421   $main::lxdebug->enter_sub();
1422
1423   my ($self, $dbh, $id, $module) = @_;
1424
1425   my $shipto;
1426   my @values;
1427   foreach my $item (qw(name department_1 department_2 street zipcode city country
1428                        contact phone fax email)) {
1429     if ($self->{"shipto$item"}) {
1430       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1431     }
1432     push(@values, $self->{"shipto${item}"});
1433   }
1434   if ($shipto) {
1435     if ($self->{shipto_id}) {
1436       my $query = qq|UPDATE shipto set
1437                        shiptoname = ?,
1438                        shiptodepartment_1 = ?,
1439                        shiptodepartment_2 = ?,
1440                        shiptostreet = ?,
1441                        shiptozipcode = ?,
1442                        shiptocity = ?,
1443                        shiptocountry = ?,
1444                        shiptocontact = ?,
1445                        shiptophone = ?,
1446                        shiptofax = ?,
1447                        shiptoemail = ?
1448                      WHERE shipto_id = ?|;
1449       do_query($self, $dbh, $query, @values, $self->{shipto_id});
1450     } else {
1451       my $query = qq|SELECT * FROM shipto
1452                      WHERE shiptoname = ? AND
1453                        shiptodepartment_1 = ? AND
1454                        shiptodepartment_2 = ? AND
1455                        shiptostreet = ? AND
1456                        shiptozipcode = ? AND
1457                        shiptocity = ? AND
1458                        shiptocountry = ? AND
1459                        shiptocontact = ? AND
1460                        shiptophone = ? AND
1461                        shiptofax = ? AND
1462                        shiptoemail = ?|;
1463       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values);
1464       if(!$insert_check){
1465         $query =
1466           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1467                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
1468                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
1469              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1470         do_query($self, $dbh, $query, $id, @values, $module);
1471       }
1472     }
1473   }
1474
1475   $main::lxdebug->leave_sub();
1476 }
1477
1478 sub get_employee {
1479   $main::lxdebug->enter_sub();
1480
1481   my ($self, $dbh) = @_;
1482
1483   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1484   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1485   $self->{"employee_id"} *= 1;
1486
1487   $main::lxdebug->leave_sub();
1488 }
1489
1490 sub get_salesman {
1491   $main::lxdebug->enter_sub();
1492
1493   my ($self, $myconfig, $salesman_id) = @_;
1494
1495   $main::lxdebug->leave_sub() and return unless $salesman_id;
1496
1497   my $dbh = $self->get_standard_dbh($myconfig);
1498
1499   my ($login) =
1500     selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|,
1501                     $salesman_id);
1502
1503   if ($login) {
1504     my $user = new User($main::memberfile, $login);
1505     map({ $self->{"salesman_$_"} = $user->{$_}; }
1506         qw(address businessnumber co_ustid company duns email fax name
1507            taxnumber tel));
1508     $self->{salesman_login} = $login;
1509
1510     $self->{salesman_name} = $login
1511       if ($self->{salesman_name} eq "");
1512
1513     map({ $self->{"salesman_$_"} =~ s/\\n/\n/g; } qw(address company));
1514   }
1515
1516   $main::lxdebug->leave_sub();
1517 }
1518
1519 sub get_duedate {
1520   $main::lxdebug->enter_sub();
1521
1522   my ($self, $myconfig) = @_;
1523
1524   my $dbh = $self->get_standard_dbh($myconfig);
1525   my $query = qq|SELECT current_date + terms_netto FROM payment_terms WHERE id = ?|;
1526   ($self->{duedate}) = selectrow_query($self, $dbh, $query, $self->{payment_id});
1527
1528   $main::lxdebug->leave_sub();
1529 }
1530
1531 sub _get_contacts {
1532   $main::lxdebug->enter_sub();
1533
1534   my ($self, $dbh, $id, $key) = @_;
1535
1536   $key = "all_contacts" unless ($key);
1537
1538   my $query =
1539     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
1540     qq|FROM contacts | .
1541     qq|WHERE cp_cv_id = ? | .
1542     qq|ORDER BY lower(cp_name)|;
1543
1544   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
1545
1546   $main::lxdebug->leave_sub();
1547 }
1548
1549 sub _get_projects {
1550   $main::lxdebug->enter_sub();
1551
1552   my ($self, $dbh, $key) = @_;
1553
1554   my ($all, $old_id, $where, @values);
1555
1556   if (ref($key) eq "HASH") {
1557     my $params = $key;
1558
1559     $key = "ALL_PROJECTS";
1560
1561     foreach my $p (keys(%{$params})) {
1562       if ($p eq "all") {
1563         $all = $params->{$p};
1564       } elsif ($p eq "old_id") {
1565         $old_id = $params->{$p};
1566       } elsif ($p eq "key") {
1567         $key = $params->{$p};
1568       }
1569     }
1570   }
1571
1572   if (!$all) {
1573     $where = "WHERE active ";
1574     if ($old_id) {
1575       if (ref($old_id) eq "ARRAY") {
1576         my @ids = grep({ $_ } @{$old_id});
1577         if (@ids) {
1578           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
1579           push(@values, @ids);
1580         }
1581       } else {
1582         $where .= " OR (id = ?) ";
1583         push(@values, $old_id);
1584       }
1585     }
1586   }
1587
1588   my $query =
1589     qq|SELECT id, projectnumber, description, active | .
1590     qq|FROM project | .
1591     $where .
1592     qq|ORDER BY lower(projectnumber)|;
1593
1594   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
1595
1596   $main::lxdebug->leave_sub();
1597 }
1598
1599 sub _get_shipto {
1600   $main::lxdebug->enter_sub();
1601
1602   my ($self, $dbh, $vc_id, $key) = @_;
1603
1604   $key = "all_shipto" unless ($key);
1605
1606   # get shipping addresses
1607   my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
1608
1609   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
1610
1611   $main::lxdebug->leave_sub();
1612 }
1613
1614 sub _get_printers {
1615   $main::lxdebug->enter_sub();
1616
1617   my ($self, $dbh, $key) = @_;
1618
1619   $key = "all_printers" unless ($key);
1620
1621   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
1622
1623   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1624
1625   $main::lxdebug->leave_sub();
1626 }
1627
1628 sub _get_charts {
1629   $main::lxdebug->enter_sub();
1630
1631   my ($self, $dbh, $params) = @_;
1632
1633   $key = $params->{key};
1634   $key = "all_charts" unless ($key);
1635
1636   my $transdate = quote_db_date($params->{transdate});
1637
1638   my $query =
1639     qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
1640     qq|FROM chart c | .
1641     qq|LEFT JOIN taxkeys tk ON | .
1642     qq|(tk.id = (SELECT id FROM taxkeys | .
1643     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
1644     qq|          ORDER BY startdate DESC LIMIT 1)) | .
1645     qq|ORDER BY c.accno|;
1646
1647   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1648
1649   $main::lxdebug->leave_sub();
1650 }
1651
1652 sub _get_taxcharts {
1653   $main::lxdebug->enter_sub();
1654
1655   my ($self, $dbh, $key) = @_;
1656
1657   $key = "all_taxcharts" unless ($key);
1658
1659   my $query = qq|SELECT * FROM tax ORDER BY taxkey|;
1660
1661   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1662
1663   $main::lxdebug->leave_sub();
1664 }
1665
1666 sub _get_taxzones {
1667   $main::lxdebug->enter_sub();
1668
1669   my ($self, $dbh, $key) = @_;
1670
1671   $key = "all_taxzones" unless ($key);
1672
1673   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
1674
1675   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1676
1677   $main::lxdebug->leave_sub();
1678 }
1679
1680 sub _get_employees {
1681   $main::lxdebug->enter_sub();
1682
1683   my ($self, $dbh, $default_key, $key) = @_;
1684
1685   $key = $default_key unless ($key);
1686   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY name|);
1687
1688   $main::lxdebug->leave_sub();
1689 }
1690
1691 sub _get_business_types {
1692   $main::lxdebug->enter_sub();
1693
1694   my ($self, $dbh, $key) = @_;
1695
1696   $key = "all_business_types" unless ($key);
1697   $self->{$key} =
1698     selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
1699
1700   $main::lxdebug->leave_sub();
1701 }
1702
1703 sub _get_languages {
1704   $main::lxdebug->enter_sub();
1705
1706   my ($self, $dbh, $key) = @_;
1707
1708   $key = "all_languages" unless ($key);
1709
1710   my $query = qq|SELECT * FROM language ORDER BY id|;
1711
1712   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1713
1714   $main::lxdebug->leave_sub();
1715 }
1716
1717 sub _get_dunning_configs {
1718   $main::lxdebug->enter_sub();
1719
1720   my ($self, $dbh, $key) = @_;
1721
1722   $key = "all_dunning_configs" unless ($key);
1723
1724   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
1725
1726   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1727
1728   $main::lxdebug->leave_sub();
1729 }
1730
1731 sub _get_currencies {
1732 $main::lxdebug->enter_sub();
1733
1734   my ($self, $dbh, $key) = @_;
1735
1736   $key = "all_currencies" unless ($key);
1737
1738   my $query = qq|SELECT curr AS currency FROM defaults|;
1739  
1740   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
1741
1742   $main::lxdebug->leave_sub();
1743 }
1744
1745 sub _get_payments {
1746 $main::lxdebug->enter_sub();
1747
1748   my ($self, $dbh, $key) = @_;
1749
1750   $key = "all_payments" unless ($key);
1751
1752   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
1753  
1754   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1755
1756   $main::lxdebug->leave_sub();
1757 }
1758
1759 sub _get_customers {
1760   $main::lxdebug->enter_sub();
1761
1762   my ($self, $dbh, $key) = @_;
1763
1764   $key = "all_customers" unless ($key);
1765
1766   my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name|;
1767
1768   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1769
1770   $main::lxdebug->leave_sub();
1771 }
1772
1773 sub _get_vendors {
1774   $main::lxdebug->enter_sub();
1775
1776   my ($self, $dbh, $key) = @_;
1777
1778   $key = "all_vendors" unless ($key);
1779
1780   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
1781
1782   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1783
1784   $main::lxdebug->leave_sub();
1785 }
1786
1787 sub _get_departments {
1788   $main::lxdebug->enter_sub();
1789
1790   my ($self, $dbh, $key) = @_;
1791
1792   $key = "all_departments" unless ($key);
1793
1794   my $query = qq|SELECT * FROM department ORDER BY description|;
1795
1796   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1797
1798   $main::lxdebug->leave_sub();
1799 }
1800
1801 sub get_lists {
1802   $main::lxdebug->enter_sub();
1803
1804   my $self = shift;
1805   my %params = @_;
1806
1807   my $dbh = $self->get_standard_dbh(\%main::myconfig);
1808   my ($sth, $query, $ref);
1809
1810   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
1811   my $vc_id = $self->{"${vc}_id"};
1812
1813   if ($params{"contacts"}) {
1814     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
1815   }
1816
1817   if ($params{"shipto"}) {
1818     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
1819   }
1820
1821   if ($params{"projects"} || $params{"all_projects"}) {
1822     $self->_get_projects($dbh, $params{"all_projects"} ?
1823                          $params{"all_projects"} : $params{"projects"},
1824                          $params{"all_projects"} ? 1 : 0);
1825   }
1826
1827   if ($params{"printers"}) {
1828     $self->_get_printers($dbh, $params{"printers"});
1829   }
1830
1831   if ($params{"languages"}) {
1832     $self->_get_languages($dbh, $params{"languages"});
1833   }
1834
1835   if ($params{"charts"}) {
1836     $self->_get_charts($dbh, $params{"charts"});
1837   }
1838
1839   if ($params{"taxcharts"}) {
1840     $self->_get_taxcharts($dbh, $params{"taxcharts"});
1841   }
1842
1843   if ($params{"taxzones"}) {
1844     $self->_get_taxzones($dbh, $params{"taxzones"});
1845   }
1846
1847   if ($params{"employees"}) {
1848     $self->_get_employees($dbh, "all_employees", $params{"employees"});
1849   }
1850   
1851   if ($params{"salesmen"}) {
1852     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
1853   }
1854
1855   if ($params{"business_types"}) {
1856     $self->_get_business_types($dbh, $params{"business_types"});
1857   }
1858
1859   if ($params{"dunning_configs"}) {
1860     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
1861   }
1862   
1863   if($params{"currencies"}) {
1864     $self->_get_currencies($dbh, $params{"currencies"});
1865   }
1866   
1867   if($params{"customers"}) {
1868     $self->_get_customers($dbh, $params{"customers"});
1869   }
1870   
1871   if($params{"vendors"}) {
1872     $self->_get_vendors($dbh, $params{"vendors"});
1873   }
1874   
1875   if($params{"payments"}) {
1876     $self->_get_payments($dbh, $params{"payments"});
1877   }
1878
1879   if($params{"departments"}) {
1880     $self->_get_departments($dbh, $params{"departments"});
1881   }
1882
1883   $main::lxdebug->leave_sub();
1884 }
1885
1886 # this sub gets the id and name from $table
1887 sub get_name {
1888   $main::lxdebug->enter_sub();
1889
1890   my ($self, $myconfig, $table) = @_;
1891
1892   # connect to database
1893   my $dbh = $self->get_standard_dbh($myconfig);
1894
1895   $table = $table eq "customer" ? "customer" : "vendor";
1896   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
1897
1898   my ($query, @values);
1899
1900   if (!$self->{openinvoices}) {
1901     my $where;
1902     if ($self->{customernumber} ne "") {
1903       $where = qq|(vc.customernumber ILIKE ?)|;
1904       push(@values, '%' . $self->{customernumber} . '%');
1905     } else {
1906       $where = qq|(vc.name ILIKE ?)|;
1907       push(@values, '%' . $self->{$table} . '%');
1908     }
1909
1910     $query =
1911       qq~SELECT vc.id, vc.name,
1912            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
1913          FROM $table vc
1914          WHERE $where AND (NOT vc.obsolete)
1915          ORDER BY vc.name~;
1916   } else {
1917     $query =
1918       qq~SELECT DISTINCT vc.id, vc.name,
1919            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
1920          FROM $arap a
1921          JOIN $table vc ON (a.${table}_id = vc.id)
1922          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
1923          ORDER BY vc.name~;
1924     push(@values, '%' . $self->{$table} . '%');
1925   }
1926
1927   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
1928
1929   $main::lxdebug->leave_sub();
1930
1931   return scalar(@{ $self->{name_list} });
1932 }
1933
1934 # the selection sub is used in the AR, AP, IS, IR and OE module
1935 #
1936 sub all_vc {
1937   $main::lxdebug->enter_sub();
1938
1939   my ($self, $myconfig, $table, $module) = @_;
1940
1941   my $ref;
1942   my $dbh = $self->get_standard_dbh($myconfig);
1943
1944   $table = $table eq "customer" ? "customer" : "vendor";
1945
1946   my $query = qq|SELECT count(*) FROM $table|;
1947   my ($count) = selectrow_query($self, $dbh, $query);
1948
1949   # build selection list
1950   if ($count < $myconfig->{vclimit}) {
1951     $query = qq|SELECT id, name, salesman_id
1952                 FROM $table WHERE NOT obsolete
1953                 ORDER BY name|;
1954     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
1955   }
1956
1957   # get self
1958   $self->get_employee($dbh);
1959
1960   # setup sales contacts
1961   $query = qq|SELECT e.id, e.name
1962               FROM employee e
1963               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
1964   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
1965
1966   # this is for self
1967   push(@{ $self->{all_employees} },
1968        { id   => $self->{employee_id},
1969          name => $self->{employee} });
1970
1971   # sort the whole thing
1972   @{ $self->{all_employees} } =
1973     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
1974
1975   if ($module eq 'AR') {
1976
1977     # prepare query for departments
1978     $query = qq|SELECT id, description
1979                 FROM department
1980                 WHERE role = 'P'
1981                 ORDER BY description|;
1982
1983   } else {
1984     $query = qq|SELECT id, description
1985                 FROM department
1986                 ORDER BY description|;
1987   }
1988
1989   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
1990
1991   # get languages
1992   $query = qq|SELECT id, description
1993               FROM language
1994               ORDER BY id|;
1995
1996   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
1997
1998   # get printer
1999   $query = qq|SELECT printer_description, id
2000               FROM printers
2001               ORDER BY printer_description|;
2002
2003   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2004
2005   # get payment terms
2006   $query = qq|SELECT id, description
2007               FROM payment_terms
2008               ORDER BY sortkey|;
2009
2010   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2011
2012   $main::lxdebug->leave_sub();
2013 }
2014
2015 sub language_payment {
2016   $main::lxdebug->enter_sub();
2017
2018   my ($self, $myconfig) = @_;
2019
2020   my $dbh = $self->get_standard_dbh($myconfig);
2021   # get languages
2022   my $query = qq|SELECT id, description
2023                  FROM language
2024                  ORDER BY id|;
2025
2026   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2027
2028   # get printer
2029   $query = qq|SELECT printer_description, id
2030               FROM printers
2031               ORDER BY printer_description|;
2032
2033   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2034
2035   # get payment terms
2036   $query = qq|SELECT id, description
2037               FROM payment_terms
2038               ORDER BY sortkey|;
2039
2040   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2041
2042   # get buchungsgruppen
2043   $query = qq|SELECT id, description
2044               FROM buchungsgruppen|;
2045
2046   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2047
2048   $main::lxdebug->leave_sub();
2049 }
2050
2051 # this is only used for reports
2052 sub all_departments {
2053   $main::lxdebug->enter_sub();
2054
2055   my ($self, $myconfig, $table) = @_;
2056
2057   my $dbh = $self->get_standard_dbh($myconfig);
2058   my $where;
2059
2060   if ($table eq 'customer') {
2061     $where = "WHERE role = 'P' ";
2062   }
2063
2064   my $query = qq|SELECT id, description
2065                  FROM department
2066                  $where
2067                  ORDER BY description|;
2068   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2069
2070   delete($self->{all_departments}) unless (@{ $self->{all_departments} });
2071
2072   $main::lxdebug->leave_sub();
2073 }
2074
2075 sub create_links {
2076   $main::lxdebug->enter_sub();
2077
2078   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2079
2080   my ($fld, $arap);
2081   if ($table eq "customer") {
2082     $fld = "buy";
2083     $arap = "ar";
2084   } else {
2085     $table = "vendor";
2086     $fld = "sell";
2087     $arap = "ap";
2088   }
2089
2090   $self->all_vc($myconfig, $table, $module);
2091
2092   # get last customers or vendors
2093   my ($query, $sth, $ref);
2094
2095   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2096   my %xkeyref = ();
2097
2098   if (!$self->{id}) {
2099
2100     my $transdate = "current_date";
2101     if ($self->{transdate}) {
2102       $transdate = $dbh->quote($self->{transdate});
2103     }
2104
2105     # now get the account numbers
2106     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2107                 FROM chart c, taxkeys tk
2108                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2109                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2110                 ORDER BY c.accno|;
2111
2112     $sth = $dbh->prepare($query);
2113
2114     do_statement($self, $sth, $query, '%' . $module . '%');
2115
2116     $self->{accounts} = "";
2117     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2118
2119       foreach my $key (split(/:/, $ref->{link})) {
2120         if ($key =~ /$module/) {
2121
2122           # cross reference for keys
2123           $xkeyref{ $ref->{accno} } = $key;
2124
2125           push @{ $self->{"${module}_links"}{$key} },
2126             { accno       => $ref->{accno},
2127               description => $ref->{description},
2128               taxkey      => $ref->{taxkey_id},
2129               tax_id      => $ref->{tax_id} };
2130
2131           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2132         }
2133       }
2134     }
2135   }
2136
2137   # get taxkeys and description
2138   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2139   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2140
2141   if (($module eq "AP") || ($module eq "AR")) {
2142     # get tax rates and description
2143     $query = qq|SELECT * FROM tax|;
2144     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2145   }
2146
2147   if ($self->{id}) {
2148     $query =
2149       qq|SELECT
2150            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2151            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2152            a.intnotes, a.department_id, a.amount AS oldinvtotal,
2153            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2154            c.name AS $table,
2155            d.description AS department,
2156            e.name AS employee
2157          FROM $arap a
2158          JOIN $table c ON (a.${table}_id = c.id)
2159          LEFT JOIN employee e ON (e.id = a.employee_id)
2160          LEFT JOIN department d ON (d.id = a.department_id)
2161          WHERE a.id = ?|;
2162     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2163
2164     foreach $key (keys %$ref) {
2165       $self->{$key} = $ref->{$key};
2166     }
2167
2168     my $transdate = "current_date";
2169     if ($self->{transdate}) {
2170       $transdate = $dbh->quote($self->{transdate});
2171     }
2172
2173     # now get the account numbers
2174     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2175                 FROM chart c
2176                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2177                 WHERE c.link LIKE ?
2178                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2179                     OR c.link LIKE '%_tax%')
2180                 ORDER BY c.accno|;
2181
2182     $sth = $dbh->prepare($query);
2183     do_statement($self, $sth, $query, "%$module%");
2184
2185     $self->{accounts} = "";
2186     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2187
2188       foreach my $key (split(/:/, $ref->{link})) {
2189         if ($key =~ /$module/) {
2190
2191           # cross reference for keys
2192           $xkeyref{ $ref->{accno} } = $key;
2193
2194           push @{ $self->{"${module}_links"}{$key} },
2195             { accno       => $ref->{accno},
2196               description => $ref->{description},
2197               taxkey      => $ref->{taxkey_id},
2198               tax_id      => $ref->{tax_id} };
2199
2200           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2201         }
2202       }
2203     }
2204
2205
2206     # get amounts from individual entries
2207     $query =
2208       qq|SELECT
2209            c.accno, c.description,
2210            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2211            p.projectnumber,
2212            t.rate, t.id
2213          FROM acc_trans a
2214          LEFT JOIN chart c ON (c.id = a.chart_id)
2215          LEFT JOIN project p ON (p.id = a.project_id)
2216          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2217                                     WHERE (tk.taxkey_id=a.taxkey) AND
2218                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2219                                         THEN tk.chart_id = a.chart_id
2220                                         ELSE 1 = 1
2221                                         END)
2222                                        OR (c.link='%tax%')) AND
2223                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2224          WHERE a.trans_id = ?
2225          AND a.fx_transaction = '0'
2226          ORDER BY a.oid, a.transdate|;
2227     $sth = $dbh->prepare($query);
2228     do_statement($self, $sth, $query, $self->{id});
2229
2230     # get exchangerate for currency
2231     $self->{exchangerate} =
2232       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2233     my $index = 0;
2234
2235     # store amounts in {acc_trans}{$key} for multiple accounts
2236     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2237       $ref->{exchangerate} =
2238         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2239       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2240         $index++;
2241       }
2242       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2243         $ref->{amount} *= -1;
2244       }
2245       $ref->{index} = $index;
2246
2247       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2248     }
2249
2250     $sth->finish;
2251     $query =
2252       qq|SELECT
2253            d.curr AS currencies, d.closedto, d.revtrans,
2254            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2255            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2256          FROM defaults d|;
2257     $ref = selectfirst_hashref_query($self, $dbh, $query);
2258     map { $self->{$_} = $ref->{$_} } keys %$ref;
2259
2260   } else {
2261
2262     # get date
2263     $query =
2264        qq|SELECT
2265             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2266             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2267             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2268           FROM defaults d|;
2269     $ref = selectfirst_hashref_query($self, $dbh, $query);
2270     map { $self->{$_} = $ref->{$_} } keys %$ref;
2271
2272     if ($self->{"$self->{vc}_id"}) {
2273
2274       # only setup currency
2275       ($self->{currency}) = split(/:/, $self->{currencies});
2276
2277     } else {
2278
2279       $self->lastname_used($dbh, $myconfig, $table, $module);
2280
2281       # get exchangerate for currency
2282       $self->{exchangerate} =
2283         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2284
2285     }
2286
2287   }
2288
2289   $main::lxdebug->leave_sub();
2290 }
2291
2292 sub lastname_used {
2293   $main::lxdebug->enter_sub();
2294
2295   my ($self, $dbh, $myconfig, $table, $module) = @_;
2296
2297   my $arap  = ($table eq 'customer') ? "ar" : "ap";
2298   $table = $table eq "customer" ? "customer" : "vendor";
2299   my $where = "1 = 1";
2300
2301   if ($self->{type} =~ /_order/) {
2302     $arap  = 'oe';
2303     $where = "quotation = '0'";
2304   }
2305   if ($self->{type} =~ /_quotation/) {
2306     $arap  = 'oe';
2307     $where = "quotation = '1'";
2308   }
2309
2310   my $query = qq|SELECT MAX(id) FROM $arap
2311                  WHERE $where AND ${table}_id > 0|;
2312   my ($trans_id) = selectrow_query($self, $dbh, $query);
2313
2314   $trans_id *= 1;
2315   $query =
2316     qq|SELECT
2317          a.curr, a.${table}_id, a.department_id,
2318          d.description AS department,
2319          ct.name, current_date + ct.terms AS duedate
2320        FROM $arap a
2321        LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2322        LEFT JOIN department d ON (a.department_id = d.id)
2323        WHERE a.id = ?|;
2324   ($self->{currency},   $self->{"${table}_id"}, $self->{department_id},
2325    $self->{department}, $self->{$table},        $self->{duedate})
2326     = selectrow_query($self, $dbh, $query, $trans_id);
2327
2328   $main::lxdebug->leave_sub();
2329 }
2330
2331 sub current_date {
2332   $main::lxdebug->enter_sub();
2333
2334   my ($self, $myconfig, $thisdate, $days) = @_;
2335
2336   my $dbh = $self->get_standard_dbh($myconfig);
2337   my $query;
2338
2339   $days *= 1;
2340   if ($thisdate) {
2341     my $dateformat = $myconfig->{dateformat};
2342     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2343     $thisdate = $dbh->quote($thisdate);
2344     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2345   } else {
2346     $query = qq|SELECT current_date AS thisdate|;
2347   }
2348
2349   ($thisdate) = selectrow_query($self, $dbh, $query);
2350
2351   $main::lxdebug->leave_sub();
2352
2353   return $thisdate;
2354 }
2355
2356 sub like {
2357   $main::lxdebug->enter_sub();
2358
2359   my ($self, $string) = @_;
2360
2361   if ($string !~ /%/) {
2362     $string = "%$string%";
2363   }
2364
2365   $string =~ s/\'/\'\'/g;
2366
2367   $main::lxdebug->leave_sub();
2368
2369   return $string;
2370 }
2371
2372 sub redo_rows {
2373   $main::lxdebug->enter_sub();
2374
2375   my ($self, $flds, $new, $count, $numrows) = @_;
2376
2377   my @ndx = ();
2378
2379   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } }
2380     (1 .. $count);
2381
2382   my $i = 0;
2383
2384   # fill rows
2385   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2386     $i++;
2387     $j = $item->{ndx} - 1;
2388     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2389   }
2390
2391   # delete empty rows
2392   for $i ($count + 1 .. $numrows) {
2393     map { delete $self->{"${_}_$i"} } @{$flds};
2394   }
2395
2396   $main::lxdebug->leave_sub();
2397 }
2398
2399 sub update_status {
2400   $main::lxdebug->enter_sub();
2401
2402   my ($self, $myconfig) = @_;
2403
2404   my ($i, $id);
2405
2406   my $dbh = $self->dbconnect_noauto($myconfig);
2407
2408   my $query = qq|DELETE FROM status
2409                  WHERE (formname = ?) AND (trans_id = ?)|;
2410   my $sth = prepare_query($self, $dbh, $query);
2411
2412   if ($self->{formname} =~ /(check|receipt)/) {
2413     for $i (1 .. $self->{rowcount}) {
2414       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
2415     }
2416   } else {
2417     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
2418   }
2419   $sth->finish();
2420
2421   my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
2422   my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
2423
2424   my %queued = split / /, $self->{queued};
2425   my @values;
2426
2427   if ($self->{formname} =~ /(check|receipt)/) {
2428
2429     # this is a check or receipt, add one entry for each lineitem
2430     my ($accno) = split /--/, $self->{account};
2431     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
2432                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
2433     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
2434     $sth = prepare_query($self, $dbh, $query);
2435
2436     for $i (1 .. $self->{rowcount}) {
2437       if ($self->{"checked_$i"}) {
2438         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
2439       }
2440     }
2441     $sth->finish();
2442
2443   } else {
2444     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2445                 VALUES (?, ?, ?, ?, ?)|;
2446     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
2447              $queued{$self->{formname}}, $self->{formname});
2448   }
2449
2450   $dbh->commit;
2451   $dbh->disconnect;
2452
2453   $main::lxdebug->leave_sub();
2454 }
2455
2456 sub save_status {
2457   $main::lxdebug->enter_sub();
2458
2459   my ($self, $dbh) = @_;
2460
2461   my ($query, $printed, $emailed);
2462
2463   my $formnames  = $self->{printed};
2464   my $emailforms = $self->{emailed};
2465
2466   my $query = qq|DELETE FROM status
2467                  WHERE (formname = ?) AND (trans_id = ?)|;
2468   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
2469
2470   # this only applies to the forms
2471   # checks and receipts are posted when printed or queued
2472
2473   if ($self->{queued}) {
2474     my %queued = split / /, $self->{queued};
2475
2476     foreach my $formname (keys %queued) {
2477       $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
2478       $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
2479
2480       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2481                   VALUES (?, ?, ?, ?, ?)|;
2482       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
2483
2484       $formnames  =~ s/$self->{formname}//;
2485       $emailforms =~ s/$self->{formname}//;
2486
2487     }
2488   }
2489
2490   # save printed, emailed info
2491   $formnames  =~ s/^ +//g;
2492   $emailforms =~ s/^ +//g;
2493
2494   my %status = ();
2495   map { $status{$_}{printed} = 1 } split / +/, $formnames;
2496   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
2497
2498   foreach my $formname (keys %status) {
2499     $printed = ($formnames  =~ /$self->{formname}/) ? "1" : "0";
2500     $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
2501
2502     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
2503                 VALUES (?, ?, ?, ?)|;
2504     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
2505   }
2506
2507   $main::lxdebug->leave_sub();
2508 }
2509
2510 #--- 4 locale ---#
2511 # $main::locale->text('SAVED')
2512 # $main::locale->text('DELETED')
2513 # $main::locale->text('ADDED')
2514 # $main::locale->text('PAYMENT POSTED')
2515 # $main::locale->text('POSTED')
2516 # $main::locale->text('POSTED AS NEW')
2517 # $main::locale->text('ELSE')
2518 # $main::locale->text('SAVED FOR DUNNING')
2519 # $main::locale->text('DUNNING STARTED')
2520 # $main::locale->text('PRINTED')
2521 # $main::locale->text('MAILED')
2522 # $main::locale->text('SCREENED')
2523 # $main::locale->text('CANCELED')
2524 # $main::locale->text('invoice')
2525 # $main::locale->text('proforma')
2526 # $main::locale->text('sales_order')
2527 # $main::locale->text('packing_list')
2528 # $main::locale->text('pick_list')
2529 # $main::locale->text('purchase_order')
2530 # $main::locale->text('bin_list')
2531 # $main::locale->text('sales_quotation')
2532 # $main::locale->text('request_quotation')
2533
2534 sub save_history {
2535   $main::lxdebug->enter_sub();
2536
2537   my $self = shift();
2538   my $dbh = shift();
2539
2540   if(!exists $self->{employee_id}) {
2541     &get_employee($self, $dbh);
2542   }
2543
2544   my $query =
2545    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
2546    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
2547   my @values = (conv_i($self->{id}), $self->{login},
2548                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
2549   do_query($self, $dbh, $query, @values);
2550
2551   $main::lxdebug->leave_sub();
2552 }
2553
2554 sub get_history {
2555   $main::lxdebug->enter_sub();
2556
2557   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
2558   my ($orderBy, $desc) = split(/\-\-/, $order);
2559   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
2560   my @tempArray;
2561   my $i = 0;
2562   if ($trans_id ne "") {
2563     my $query =
2564       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 | .
2565       qq|FROM history_erp h | .
2566       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
2567       qq|WHERE trans_id = | . $trans_id
2568       . $restriction . qq| |
2569       . $order;
2570       
2571     my $sth = $dbh->prepare($query) || $self->dberror($query);
2572
2573     $sth->execute() || $self->dberror("$query");
2574
2575     while(my $hash_ref = $sth->fetchrow_hashref()) {
2576       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
2577       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
2578       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
2579       $tempArray[$i++] = $hash_ref;
2580     }
2581     $main::lxdebug->leave_sub() and return \@tempArray 
2582       if ($i > 0 && $tempArray[0] ne "");
2583   }
2584   $main::lxdebug->leave_sub();
2585   return 0;
2586 }
2587
2588 sub update_defaults {
2589   $main::lxdebug->enter_sub();
2590
2591   my ($self, $myconfig, $fld, $provided_dbh) = @_;
2592
2593   my $dbh;
2594   if ($provided_dbh) {
2595     $dbh = $provided_dbh;
2596   } else {
2597     $dbh = $self->dbconnect_noauto($myconfig);
2598   }
2599   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
2600   my $sth   = $dbh->prepare($query);
2601
2602   $sth->execute || $self->dberror($query);
2603   my ($var) = $sth->fetchrow_array;
2604   $sth->finish;
2605
2606   $var =~ s/\d+$/ sprintf '%0*d', length($&), $&+1 /e;
2607   $var ||= 1;
2608
2609   $query = qq|UPDATE defaults SET $fld = ?|;
2610   do_query($self, $dbh, $query, $var);
2611
2612   if (!$provided_dbh) {
2613     $dbh->commit;
2614     $dbh->disconnect;
2615   }
2616
2617   $main::lxdebug->leave_sub();
2618
2619   return $var;
2620 }
2621
2622 sub update_business {
2623   $main::lxdebug->enter_sub();
2624
2625   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
2626
2627   my $dbh;
2628   if ($provided_dbh) {
2629     $dbh = $provided_dbh;
2630   } else {
2631     $dbh = $self->dbconnect_noauto($myconfig);
2632   }
2633   my $query =
2634     qq|SELECT customernumberinit FROM business
2635        WHERE id = ? FOR UPDATE|;
2636   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
2637
2638   $var =~ s/\d+$/ sprintf '%0*d', length($&), $&+1 /e;
2639   
2640   $query = qq|UPDATE business
2641               SET customernumberinit = ?
2642               WHERE id = ?|;
2643   do_query($self, $dbh, $query, $var, $business_id);
2644
2645   if (!$provided_dbh) {
2646     $dbh->commit;
2647     $dbh->disconnect;
2648   }
2649
2650   $main::lxdebug->leave_sub();
2651
2652   return $var;
2653 }
2654
2655 sub get_partsgroup {
2656   $main::lxdebug->enter_sub();
2657
2658   my ($self, $myconfig, $p) = @_;
2659
2660   my $dbh = $self->get_standard_dbh($myconfig);
2661
2662   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
2663                  FROM partsgroup pg
2664                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
2665   my @values;
2666
2667   if ($p->{searchitems} eq 'part') {
2668     $query .= qq|WHERE p.inventory_accno_id > 0|;
2669   }
2670   if ($p->{searchitems} eq 'service') {
2671     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
2672   }
2673   if ($p->{searchitems} eq 'assembly') {
2674     $query .= qq|WHERE p.assembly = '1'|;
2675   }
2676   if ($p->{searchitems} eq 'labor') {
2677     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
2678   }
2679
2680   $query .= qq|ORDER BY partsgroup|;
2681
2682   if ($p->{all}) {
2683     $query = qq|SELECT id, partsgroup FROM partsgroup
2684                 ORDER BY partsgroup|;
2685   }
2686
2687   if ($p->{language_code}) {
2688     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
2689                   t.description AS translation
2690                 FROM partsgroup pg
2691                 JOIN parts p ON (p.partsgroup_id = pg.id)
2692                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
2693                 ORDER BY translation|;
2694     @values = ($p->{language_code});
2695   }
2696
2697   $self->{all_partsgroup} = selectall_hashref_query($self, $dbh, $query, @values);
2698
2699   $main::lxdebug->leave_sub();
2700 }
2701
2702 sub get_pricegroup {
2703   $main::lxdebug->enter_sub();
2704
2705   my ($self, $myconfig, $p) = @_;
2706
2707   my $dbh = $self->get_standard_dbh($myconfig);
2708
2709   my $query = qq|SELECT p.id, p.pricegroup
2710                  FROM pricegroup p|;
2711
2712   $query .= qq| ORDER BY pricegroup|;
2713
2714   if ($p->{all}) {
2715     $query = qq|SELECT id, pricegroup FROM pricegroup
2716                 ORDER BY pricegroup|;
2717   }
2718
2719   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
2720
2721   $main::lxdebug->leave_sub();
2722 }
2723
2724 sub all_years {
2725 # usage $form->all_years($myconfig, [$dbh])
2726 # return list of all years where bookings found
2727 # (@all_years)
2728
2729   $main::lxdebug->enter_sub();
2730
2731   my ($self, $myconfig, $dbh) = @_;
2732
2733   $dbh ||= $self->get_standard_dbh($myconfig);
2734
2735   # get years
2736   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
2737                    (SELECT MAX(transdate) FROM acc_trans)|;
2738   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
2739
2740   if ($myconfig->{dateformat} =~ /^yy/) {
2741     ($startdate) = split /\W/, $startdate;
2742     ($enddate) = split /\W/, $enddate;
2743   } else {
2744     (@_) = split /\W/, $startdate;
2745     $startdate = $_[2];
2746     (@_) = split /\W/, $enddate;
2747     $enddate = $_[2];
2748   }
2749
2750   my @all_years;
2751   $startdate = substr($startdate,0,4);
2752   $enddate = substr($enddate,0,4);
2753
2754   while ($enddate >= $startdate) {
2755     push @all_years, $enddate--;
2756   }
2757
2758   return @all_years;
2759
2760   $main::lxdebug->leave_sub();
2761 }
2762
2763 1;