464405ca40eae528f61cf8632e7298cc4c0b73e3
[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   $output = $main::locale->{iconv}->convert($output) if ($main::locale);
553
554   $main::lxdebug->leave_sub();
555
556   return $output;
557 }
558
559 sub show_generic_error {
560   my ($self, $error, $title, $action) = @_;
561
562   my $add_params = {};
563   $add_params->{"title"} = $title if ($title);
564   $self->{"label_error"} = $error;
565
566   my @vars;
567   if ($action) {
568     map({ delete($self->{$_}); } qw(action));
569     map({ push(@vars, { "name" => $_, "value" => $self->{$_} })
570             if (!ref($self->{$_})); }
571         keys(%{$self}));
572     $add_params->{"SHOW_BUTTON"} = 1;
573     $add_params->{"BUTTON_LABEL"} = $action;
574   }
575   $add_params->{"VARIABLES"} = \@vars;
576
577   $self->header();
578   print($self->parse_html_template("generic/error", $add_params));
579
580   die("Error: $error\n");
581 }
582
583 sub show_generic_information {
584   my ($self, $error, $title) = @_;
585
586   my $add_params = {};
587   $add_params->{"title"} = $title if ($title);
588   $self->{"label_information"} = $error;
589
590   $self->header();
591   print($self->parse_html_template("generic/information", $add_params));
592
593   die("Information: $error\n");
594 }
595
596 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
597 # changed it to accept an arbitrary number of triggers - sschoeling
598 sub write_trigger {
599   $main::lxdebug->enter_sub();
600
601   my $self     = shift;
602   my $myconfig = shift;
603   my $qty      = shift;
604
605   # set dateform for jsscript
606   # default
607   my %dateformats = (
608     "dd.mm.yy" => "%d.%m.%Y",
609     "dd-mm-yy" => "%d-%m-%Y",
610     "dd/mm/yy" => "%d/%m/%Y",
611     "mm/dd/yy" => "%m/%d/%Y",
612     "mm-dd-yy" => "%m-%d-%Y",
613     "yyyy-mm-dd" => "%Y-%m-%d",
614     );
615
616   my $ifFormat = defined($dateformats{$myconfig{"dateformat"}}) ?
617     $dateformats{$myconfig{"dateformat"}} : "%d.%m.%Y";
618
619   my @triggers;
620   while ($#_ >= 2) {
621     push @triggers, qq|
622        Calendar.setup(
623       {
624       inputField : "| . (shift) . qq|",
625       ifFormat :"$ifFormat",
626       align : "| .  (shift) . qq|",
627       button : "| . (shift) . qq|"
628       }
629       );
630        |;
631   }
632   my $jsscript = qq|
633        <script type="text/javascript">
634        <!--| . join("", @triggers) . qq|//-->
635         </script>
636         |;
637
638   $main::lxdebug->leave_sub();
639
640   return $jsscript;
641 }    #end sub write_trigger
642
643 sub redirect {
644   $main::lxdebug->enter_sub();
645
646   my ($self, $msg) = @_;
647
648   if ($self->{callback}) {
649
650     ($script, $argv) = split(/\?/, $self->{callback});
651     exec("perl", "$script", $argv);
652
653   } else {
654
655     $self->info($msg);
656     exit;
657   }
658
659   $main::lxdebug->leave_sub();
660 }
661
662 # sort of columns removed - empty sub
663 sub sort_columns {
664   $main::lxdebug->enter_sub();
665
666   my ($self, @columns) = @_;
667
668   $main::lxdebug->leave_sub();
669
670   return @columns;
671 }
672 #
673 sub format_amount {
674   $main::lxdebug->enter_sub(2);
675
676   my ($self, $myconfig, $amount, $places, $dash) = @_;
677
678   if ($amount eq "") {
679     $amount = 0;
680   }
681   my $neg = ($amount =~ s/-//);
682
683   if (defined($places) && ($places ne '')) {
684     if ($places < 0) {
685       $amount *= 1;
686       $places *= -1;
687
688       my ($actual_places) = ($amount =~ /\.(\d+)/);
689       $actual_places = length($actual_places);
690       $places = $actual_places > $places ? $actual_places : $places;
691     }
692
693     $amount = $self->round_amount($amount, $places);
694   }
695
696   my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
697   my @p = split(/\./, $amount); # split amount at decimal point
698
699   $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
700
701   $amount = $p[0];
702   $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
703
704   $amount = do {
705     ($dash =~ /-/)    ? ($neg ? "($amount)"  : "$amount" )    :
706     ($dash =~ /DRCR/) ? ($neg ? "$amount DR" : "$amount CR" ) :
707                         ($neg ? "-$amount"   : "$amount" )    ;
708   };
709
710
711   $main::lxdebug->leave_sub(2);
712   return $amount;
713 }
714 #
715 sub parse_amount {
716   $main::lxdebug->enter_sub(2);
717
718   my ($self, $myconfig, $amount) = @_;
719
720   if (   ($myconfig->{numberformat} eq '1.000,00')
721       || ($myconfig->{numberformat} eq '1000,00')) {
722     $amount =~ s/\.//g;
723     $amount =~ s/,/\./;
724   }
725
726   if ($myconfig->{numberformat} eq "1'000.00") {
727     $amount =~ s/\'//g;
728   }
729
730   $amount =~ s/,//g;
731
732   $main::lxdebug->leave_sub(2);
733
734   return ($amount * 1);
735 }
736
737 sub round_amount {
738   $main::lxdebug->enter_sub(2);
739
740   my ($self, $amount, $places) = @_;
741   my $round_amount;
742
743   # Rounding like "Kaufmannsrunden"
744   # Descr. http://de.wikipedia.org/wiki/Rundung
745   # Inspired by
746   # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
747   # Solves Bug: 189
748   # Udo Spallek
749   $amount = $amount * (10**($places));
750   $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
751
752   $main::lxdebug->leave_sub(2);
753
754   return $round_amount;
755
756 }
757
758 sub parse_template {
759   $main::lxdebug->enter_sub();
760
761   my ($self, $myconfig, $userspath) = @_;
762   my ($template, $out);
763
764   local (*IN, *OUT);
765
766   $self->{"cwd"} = getcwd();
767   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
768
769   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
770     $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
771   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
772     $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
773     $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
774   } elsif (($self->{"format"} =~ /html/i) ||
775            (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
776     $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
777   } elsif (($self->{"format"} =~ /xml/i) ||
778              (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
779     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
780   } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
781     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
782   } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
783     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
784   } elsif ( defined $self->{'format'}) {
785     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
786   } elsif ( $self->{'format'} eq '' ) {
787     $self->error("No Outputformat given: $self->{'format'}");
788   } else { #Catch the rest
789     $self->error("Outputformat not defined: $self->{'format'}");
790   }
791
792   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
793   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
794
795   map({ $self->{"employee_${_}"} = $myconfig->{$_}; }
796       qw(email tel fax name signature company address businessnumber
797          co_ustid taxnumber duns));
798   map({ $self->{"employee_${_}"} =~ s/\\n/\n/g; }
799       qw(company address signature));
800   map({ $self->{$_} =~ s/\\n/\n/g; } qw(company address signature));
801
802   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
803
804   # OUT is used for the media, screen, printer, email
805   # for postscript we store a copy in a temporary file
806   my $fileid = time;
807   my $prepend_userspath;
808
809   if (!$self->{tmpfile}) {
810     $self->{tmpfile}   = "${fileid}.$self->{IN}";
811     $prepend_userspath = 1;
812   }
813
814   $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
815
816   $self->{tmpfile} =~ s|.*/||;
817   $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
818   $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
819
820   if ($template->uses_temp_file() || $self->{media} eq 'email') {
821     $out = $self->{OUT};
822     $self->{OUT} = ">$self->{tmpfile}";
823   }
824
825   if ($self->{OUT}) {
826     open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
827   } else {
828     open(OUT, ">-") or $self->error("STDOUT : $!");
829     $self->header;
830   }
831
832   if (!$template->parse(*OUT)) {
833     $self->cleanup();
834     $self->error("$self->{IN} : " . $template->get_error());
835   }
836
837   close(OUT);
838
839   if ($template->uses_temp_file() || $self->{media} eq 'email') {
840
841     if ($self->{media} eq 'email') {
842
843       my $mail = new Mailer;
844
845       map { $mail->{$_} = $self->{$_} }
846         qw(cc bcc subject message version format);
847       $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
848       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
849       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
850       $mail->{fileid} = "$fileid.";
851       $myconfig->{signature} =~ s/\\r\\n/\\n/g;
852
853       # if we send html or plain text inline
854       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
855         $mail->{contenttype} = "text/html";
856
857         $mail->{message}       =~ s/\r\n/<br>\n/g;
858         $myconfig->{signature} =~ s/\\n/<br>\n/g;
859         $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
860
861         open(IN, $self->{tmpfile})
862           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
863         while (<IN>) {
864           $mail->{message} .= $_;
865         }
866
867         close(IN);
868
869       } else {
870
871         if (!$self->{"do_not_attach"}) {
872           @{ $mail->{attachments} } =
873             ({ "filename" => $self->{"tmpfile"},
874                "name" => $self->{"attachment_filename"} ?
875                  $self->{"attachment_filename"} : $self->{"tmpfile"} });
876         }
877
878         $mail->{message}       =~ s/\r\n/\n/g;
879         $myconfig->{signature} =~ s/\\n/\n/g;
880         $mail->{message} .= "\n-- \n$myconfig->{signature}";
881
882       }
883
884       my $err = $mail->send();
885       $self->error($self->cleanup . "$err") if ($err);
886
887     } else {
888
889       $self->{OUT} = $out;
890
891       my $numbytes = (-s $self->{tmpfile});
892       open(IN, $self->{tmpfile})
893         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
894
895       $self->{copies} = 1 unless $self->{media} eq 'printer';
896
897       chdir("$self->{cwd}");
898       #print(STDERR "Kopien $self->{copies}\n");
899       #print(STDERR "OUT $self->{OUT}\n");
900       for my $i (1 .. $self->{copies}) {
901         if ($self->{OUT}) {
902           open(OUT, $self->{OUT})
903             or $self->error($self->cleanup . "$self->{OUT} : $!");
904         } else {
905           $self->{attachment_filename} = ($self->{attachment_filename}) 
906                                        ? $self->{attachment_filename}
907                                        : $self->generate_attachment_filename();
908
909           # launch application
910           print qq|Content-Type: | . $template->get_mime_type() . qq|
911 Content-Disposition: attachment; filename="$self->{attachment_filename}"
912 Content-Length: $numbytes
913
914 |;
915
916           open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
917
918         }
919
920         while (<IN>) {
921           print OUT $_;
922         }
923
924         close(OUT);
925
926         seek IN, 0, 0;
927       }
928
929       close(IN);
930     }
931
932   }
933
934   $self->cleanup;
935
936   chdir("$self->{cwd}");
937   $main::lxdebug->leave_sub();
938 }
939
940 sub generate_attachment_filename {
941   my ($self) = @_;
942
943   my %formname_translations = (
944      bin_list            => $main::locale->text('Bin List'),
945      credit_note         => $main::locale->text('Credit Note'),
946      invoice             => $main::locale->text('Invoice'),
947      packing_list        => $main::locale->text('Packing List'),
948      pick_list           => $main::locale->text('Pick List'),
949      proforma            => $main::locale->text('Proforma Invoice'),
950      purchase_order      => $main::locale->text('Purchase Order'),
951      request_quotation   => $main::locale->text('RFQ'),
952      sales_order         => $main::locale->text('Confirmation'),
953      sales_quotation     => $main::locale->text('Quotation'),
954      storno_invoice      => $main::locale->text('Storno Invoice'),
955      storno_packing_list => $main::locale->text('Storno Packing List'),
956   );
957
958   my $attachment_filename = $formname_translations{$self->{"formname"}};
959   my $prefix = 
960       (grep { $self->{"type"} eq $_ } qw(invoice credit_note)) ? "inv"
961     : ($self->{"type"} =~ /_quotation$/)                       ? "quo"
962     :                                                            "ord";
963
964   if ($attachment_filename && $self->{"${prefix}number"}) {
965     $attachment_filename .= "_" . $self->{"${prefix}number"}
966                             . (  $self->{format} =~ /pdf/i          ? ".pdf"
967                                : $self->{format} =~ /postscript/i   ? ".ps"
968                                : $self->{format} =~ /opendocument/i ? ".odt"
969                                : $self->{format} =~ /html/i         ? ".html"
970                                :                                      "");
971     $attachment_filename =~ s/ /_/g;
972     my %umlaute = ( "ä" => "ae", "ö" => "oe", "ü" => "ue", 
973                     "Ä" => "Ae", "Ö" => "Oe", "Ãœ" => "Ue", "ß" => "ss");
974     map { $attachment_filename =~ s/$_/$umlaute{$_}/g } keys %umlaute;
975   } else {
976     $attachment_filename = "";
977   }
978
979   return $attachment_filename;
980 }
981
982 sub cleanup {
983   $main::lxdebug->enter_sub();
984
985   my $self = shift;
986
987   chdir("$self->{tmpdir}");
988
989   my @err = ();
990   if (-f "$self->{tmpfile}.err") {
991     open(FH, "$self->{tmpfile}.err");
992     @err = <FH>;
993     close(FH);
994   }
995
996   if ($self->{tmpfile}) {
997     $self->{tmpfile} =~ s|.*/||g;
998     # strip extension
999     $self->{tmpfile} =~ s/\.\w+$//g;
1000     my $tmpfile = $self->{tmpfile};
1001     unlink(<$tmpfile.*>);
1002   }
1003
1004   chdir("$self->{cwd}");
1005
1006   $main::lxdebug->leave_sub();
1007
1008   return "@err";
1009 }
1010
1011 sub datetonum {
1012   $main::lxdebug->enter_sub();
1013
1014   my ($self, $date, $myconfig) = @_;
1015
1016   if ($date && $date =~ /\D/) {
1017
1018     if ($myconfig->{dateformat} =~ /^yy/) {
1019       ($yy, $mm, $dd) = split /\D/, $date;
1020     }
1021     if ($myconfig->{dateformat} =~ /^mm/) {
1022       ($mm, $dd, $yy) = split /\D/, $date;
1023     }
1024     if ($myconfig->{dateformat} =~ /^dd/) {
1025       ($dd, $mm, $yy) = split /\D/, $date;
1026     }
1027
1028     $dd *= 1;
1029     $mm *= 1;
1030     $yy = ($yy < 70) ? $yy + 2000 : $yy;
1031     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1032
1033     $dd = "0$dd" if ($dd < 10);
1034     $mm = "0$mm" if ($mm < 10);
1035
1036     $date = "$yy$mm$dd";
1037   }
1038
1039   $main::lxdebug->leave_sub();
1040
1041   return $date;
1042 }
1043
1044 # Database routines used throughout
1045
1046 sub dbconnect {
1047   $main::lxdebug->enter_sub(2);
1048
1049   my ($self, $myconfig) = @_;
1050
1051   # connect to database
1052   my $dbh =
1053     DBI->connect($myconfig->{dbconnect},
1054                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
1055     or $self->dberror;
1056
1057   # set db options
1058   if ($myconfig->{dboptions}) {
1059     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1060   }
1061
1062   $main::lxdebug->leave_sub(2);
1063
1064   return $dbh;
1065 }
1066
1067 sub dbconnect_noauto {
1068   $main::lxdebug->enter_sub();
1069
1070   my ($self, $myconfig) = @_;
1071   
1072   # connect to database
1073   $dbh =
1074     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1075                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
1076     or $self->dberror;
1077
1078   # set db options
1079   if ($myconfig->{dboptions}) {
1080     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1081   }
1082
1083   $main::lxdebug->leave_sub();
1084
1085   return $dbh;
1086 }
1087
1088 sub get_standard_dbh {
1089   $main::lxdebug->enter_sub(2);
1090
1091   my ($self, $myconfig) = @_;
1092
1093   $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1094
1095   $main::lxdebug->leave_sub(2);
1096
1097   return $standard_dbh;
1098 }
1099
1100 sub update_balance {
1101   $main::lxdebug->enter_sub();
1102
1103   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1104
1105   # if we have a value, go do it
1106   if ($value != 0) {
1107
1108     # retrieve balance from table
1109     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1110     my $sth = prepare_execute_query($self, $dbh, $query, @values);
1111     my ($balance) = $sth->fetchrow_array;
1112     $sth->finish;
1113
1114     $balance += $value;
1115
1116     # update balance
1117     $query = "UPDATE $table SET $field = $balance WHERE $where";
1118     do_query($self, $dbh, $query, @values);
1119   }
1120   $main::lxdebug->leave_sub();
1121 }
1122
1123 sub update_exchangerate {
1124   $main::lxdebug->enter_sub();
1125
1126   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1127
1128   # some sanity check for currency
1129   if ($curr eq '') {
1130     $main::lxdebug->leave_sub();
1131     return;
1132   }  
1133   my $query = qq|SELECT curr FROM defaults|;
1134
1135   my ($currency) = selectrow_query($self, $dbh, $query);
1136   my ($defaultcurrency) = split m/:/, $currency;
1137
1138
1139   if ($curr eq $defaultcurrency) {
1140     $main::lxdebug->leave_sub();
1141     return;
1142   }
1143
1144   my $query = qq|SELECT e.curr FROM exchangerate e
1145                  WHERE e.curr = ? AND e.transdate = ?
1146                  FOR UPDATE|;
1147   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1148
1149   if ($buy == 0) {
1150     $buy = "";
1151   }
1152   if ($sell == 0) {
1153     $sell = "";
1154   }
1155
1156   $buy = conv_i($buy, "NULL");
1157   $sell = conv_i($sell, "NULL");
1158
1159   my $set;
1160   if ($buy != 0 && $sell != 0) {
1161     $set = "buy = $buy, sell = $sell";
1162   } elsif ($buy != 0) {
1163     $set = "buy = $buy";
1164   } elsif ($sell != 0) {
1165     $set = "sell = $sell";
1166   }
1167
1168   if ($sth->fetchrow_array) {
1169     $query = qq|UPDATE exchangerate
1170                 SET $set
1171                 WHERE curr = ?
1172                 AND transdate = ?|;
1173     
1174   } else {
1175     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1176                 VALUES (?, $buy, $sell, ?)|;
1177   }
1178   $sth->finish;
1179   do_query($self, $dbh, $query, $curr, $transdate);
1180
1181   $main::lxdebug->leave_sub();
1182 }
1183
1184 sub save_exchangerate {
1185   $main::lxdebug->enter_sub();
1186
1187   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1188
1189   my $dbh = $self->dbconnect($myconfig);
1190
1191   my ($buy, $sell);
1192
1193   $buy  = $rate if $fld eq 'buy';
1194   $sell = $rate if $fld eq 'sell';
1195
1196
1197   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1198
1199
1200   $dbh->disconnect;
1201
1202   $main::lxdebug->leave_sub();
1203 }
1204
1205 sub get_exchangerate {
1206   $main::lxdebug->enter_sub();
1207
1208   my ($self, $dbh, $curr, $transdate, $fld) = @_;
1209
1210   unless ($transdate) {
1211     $main::lxdebug->leave_sub();
1212     return 1;
1213   }
1214
1215   my $query = qq|SELECT curr FROM defaults|;
1216
1217   my ($currency) = selectrow_query($self, $dbh, $query);
1218   my ($defaultcurrency) = split m/:/, $currency;
1219
1220   if ($currency eq $defaultcurrency) {
1221     $main::lxdebug->leave_sub();
1222     return 1;
1223   }
1224
1225   my $query = qq|SELECT e.$fld FROM exchangerate e
1226                  WHERE e.curr = ? AND e.transdate = ?|;
1227   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1228
1229
1230
1231   $main::lxdebug->leave_sub();
1232
1233   return $exchangerate;
1234 }
1235
1236 sub check_exchangerate {
1237   $main::lxdebug->enter_sub();
1238
1239   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1240
1241   unless ($transdate) {
1242     $main::lxdebug->leave_sub();
1243     return "";
1244   }
1245
1246   my ($defaultcurrency) = $self->get_default_currency($myconfig);
1247
1248   if ($currency eq $defaultcurrency) {
1249     $main::lxdebug->leave_sub();
1250     return 1;
1251   }
1252
1253   my $dbh   = $self->get_standard_dbh($myconfig);
1254   my $query = qq|SELECT e.$fld FROM exchangerate e
1255                  WHERE e.curr = ? AND e.transdate = ?|;
1256
1257   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1258
1259   $exchangerate = 1 if ($exchangerate eq "");
1260
1261   $main::lxdebug->leave_sub();
1262
1263   return $exchangerate;
1264 }
1265
1266 sub get_default_currency {
1267   $main::lxdebug->enter_sub();
1268
1269   my ($self, $myconfig) = @_;
1270   my $dbh = $self->get_standard_dbh($myconfig);
1271
1272   my $query = qq|SELECT curr FROM defaults|;
1273
1274   my ($curr)            = selectrow_query($self, $dbh, $query);
1275   my ($defaultcurrency) = split m/:/, $curr;
1276
1277   $main::lxdebug->leave_sub();
1278
1279   return $defaultcurrency;
1280 }
1281
1282
1283 sub set_payment_options {
1284   $main::lxdebug->enter_sub();
1285
1286   my ($self, $myconfig, $transdate) = @_;
1287
1288   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1289
1290   my $dbh = $self->get_standard_dbh($myconfig);
1291
1292   my $query =
1293     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1294     qq|FROM payment_terms p | .
1295     qq|WHERE p.id = ?|;
1296
1297   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1298    $self->{payment_terms}) =
1299      selectrow_query($self, $dbh, $query, $self->{payment_id});
1300
1301   if ($transdate eq "") {
1302     if ($self->{invdate}) {
1303       $transdate = $self->{invdate};
1304     } else {
1305       $transdate = $self->{transdate};
1306     }
1307   }
1308
1309   $query =
1310     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1311     qq|FROM payment_terms|;
1312   ($self->{netto_date}, $self->{skonto_date}) =
1313     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1314
1315   my $total = ($self->{invtotal}) ? $self->{invtotal} : $self->{ordtotal};
1316   my $skonto_amount = $self->parse_amount($myconfig, $total) *
1317     $self->{percent_skonto};
1318
1319   $self->{skonto_amount} =
1320     $self->format_amount($myconfig, $skonto_amount, 2);
1321
1322   if ($self->{"language_id"}) {
1323     $query =
1324       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1325       qq|FROM translation_payment_terms t | .
1326       qq|LEFT JOIN language l ON t.language_id = l.id | .
1327       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1328     my ($description_long, $output_numberformat, $output_dateformat,
1329       $output_longdates) =
1330       selectrow_query($self, $dbh, $query,
1331                       $self->{"language_id"}, $self->{"payment_id"});
1332
1333     $self->{payment_terms} = $description_long if ($description_long);
1334
1335     if ($output_dateformat) {
1336       foreach my $key (qw(netto_date skonto_date)) {
1337         $self->{$key} =
1338           $main::locale->reformat_date($myconfig, $self->{$key},
1339                                        $output_dateformat,
1340                                        $output_longdates);
1341       }
1342     }
1343
1344     if ($output_numberformat &&
1345         ($output_numberformat ne $myconfig->{"numberformat"})) {
1346       my $saved_numberformat = $myconfig->{"numberformat"};
1347       $myconfig->{"numberformat"} = $output_numberformat;
1348       $self->{skonto_amount} =
1349         $self->format_amount($myconfig, $skonto_amount, 2);
1350       $myconfig->{"numberformat"} = $saved_numberformat;
1351     }
1352   }
1353
1354   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1355   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1356   $self->{payment_terms} =~ s/<%skonto_amount%>/$self->{skonto_amount}/g;
1357   $self->{payment_terms} =~ s/<%total%>/$self->{total}/g;
1358   $self->{payment_terms} =~ s/<%invtotal%>/$self->{invtotal}/g;
1359   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1360   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1361   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1362   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1363   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1364
1365   $main::lxdebug->leave_sub();
1366
1367 }
1368
1369 sub get_template_language {
1370   $main::lxdebug->enter_sub();
1371
1372   my ($self, $myconfig) = @_;
1373
1374   my $template_code = "";
1375
1376   if ($self->{language_id}) {
1377     my $dbh = $self->get_standard_dbh($myconfig);
1378     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1379     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1380   }
1381
1382   $main::lxdebug->leave_sub();
1383
1384   return $template_code;
1385 }
1386
1387 sub get_printer_code {
1388   $main::lxdebug->enter_sub();
1389
1390   my ($self, $myconfig) = @_;
1391
1392   my $template_code = "";
1393
1394   if ($self->{printer_id}) {
1395     my $dbh = $self->get_standard_dbh($myconfig);
1396     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1397     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1398   }
1399
1400   $main::lxdebug->leave_sub();
1401
1402   return $template_code;
1403 }
1404
1405 sub get_shipto {
1406   $main::lxdebug->enter_sub();
1407
1408   my ($self, $myconfig) = @_;
1409
1410   my $template_code = "";
1411
1412   if ($self->{shipto_id}) {
1413     my $dbh = $self->get_standard_dbh($myconfig);
1414     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1415     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1416     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1417   }
1418
1419   $main::lxdebug->leave_sub();
1420 }
1421
1422 sub add_shipto {
1423   $main::lxdebug->enter_sub();
1424
1425   my ($self, $dbh, $id, $module) = @_;
1426
1427   my $shipto;
1428   my @values;
1429   foreach my $item (qw(name department_1 department_2 street zipcode city country
1430                        contact phone fax email)) {
1431     if ($self->{"shipto$item"}) {
1432       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1433     }
1434     push(@values, $self->{"shipto${item}"});
1435   }
1436   if ($shipto) {
1437     if ($self->{shipto_id}) {
1438       my $query = qq|UPDATE shipto set
1439                        shiptoname = ?,
1440                        shiptodepartment_1 = ?,
1441                        shiptodepartment_2 = ?,
1442                        shiptostreet = ?,
1443                        shiptozipcode = ?,
1444                        shiptocity = ?,
1445                        shiptocountry = ?,
1446                        shiptocontact = ?,
1447                        shiptophone = ?,
1448                        shiptofax = ?,
1449                        shiptoemail = ?
1450                      WHERE shipto_id = ?|;
1451       do_query($self, $dbh, $query, @values, $self->{shipto_id});
1452     } else {
1453       my $query = qq|SELECT * FROM shipto
1454                      WHERE shiptoname = ? AND
1455                        shiptodepartment_1 = ? AND
1456                        shiptodepartment_2 = ? AND
1457                        shiptostreet = ? AND
1458                        shiptozipcode = ? AND
1459                        shiptocity = ? AND
1460                        shiptocountry = ? AND
1461                        shiptocontact = ? AND
1462                        shiptophone = ? AND
1463                        shiptofax = ? AND
1464                        shiptoemail = ?|;
1465       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values);
1466       if(!$insert_check){
1467         $query =
1468           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1469                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
1470                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
1471              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1472         do_query($self, $dbh, $query, $id, @values, $module);
1473       }
1474     }
1475   }
1476
1477   $main::lxdebug->leave_sub();
1478 }
1479
1480 sub get_employee {
1481   $main::lxdebug->enter_sub();
1482
1483   my ($self, $dbh) = @_;
1484
1485   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1486   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1487   $self->{"employee_id"} *= 1;
1488
1489   $main::lxdebug->leave_sub();
1490 }
1491
1492 sub get_salesman {
1493   $main::lxdebug->enter_sub();
1494
1495   my ($self, $myconfig, $salesman_id) = @_;
1496
1497   $main::lxdebug->leave_sub() and return unless $salesman_id;
1498
1499   my $dbh = $self->get_standard_dbh($myconfig);
1500
1501   my ($login) =
1502     selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|,
1503                     $salesman_id);
1504
1505   if ($login) {
1506     my $user = new User($main::memberfile, $login);
1507     map({ $self->{"salesman_$_"} = $user->{$_}; }
1508         qw(address businessnumber co_ustid company duns email fax name
1509            taxnumber tel));
1510     $self->{salesman_login} = $login;
1511
1512     $self->{salesman_name} = $login
1513       if ($self->{salesman_name} eq "");
1514
1515     map({ $self->{"salesman_$_"} =~ s/\\n/\n/g; } qw(address company));
1516   }
1517
1518   $main::lxdebug->leave_sub();
1519 }
1520
1521 sub get_duedate {
1522   $main::lxdebug->enter_sub();
1523
1524   my ($self, $myconfig) = @_;
1525
1526   my $dbh = $self->get_standard_dbh($myconfig);
1527   my $query = qq|SELECT current_date + terms_netto FROM payment_terms WHERE id = ?|;
1528   ($self->{duedate}) = selectrow_query($self, $dbh, $query, $self->{payment_id});
1529
1530   $main::lxdebug->leave_sub();
1531 }
1532
1533 sub _get_contacts {
1534   $main::lxdebug->enter_sub();
1535
1536   my ($self, $dbh, $id, $key) = @_;
1537
1538   $key = "all_contacts" unless ($key);
1539
1540   my $query =
1541     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
1542     qq|FROM contacts | .
1543     qq|WHERE cp_cv_id = ? | .
1544     qq|ORDER BY lower(cp_name)|;
1545
1546   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
1547
1548   $main::lxdebug->leave_sub();
1549 }
1550
1551 sub _get_projects {
1552   $main::lxdebug->enter_sub();
1553
1554   my ($self, $dbh, $key) = @_;
1555
1556   my ($all, $old_id, $where, @values);
1557
1558   if (ref($key) eq "HASH") {
1559     my $params = $key;
1560
1561     $key = "ALL_PROJECTS";
1562
1563     foreach my $p (keys(%{$params})) {
1564       if ($p eq "all") {
1565         $all = $params->{$p};
1566       } elsif ($p eq "old_id") {
1567         $old_id = $params->{$p};
1568       } elsif ($p eq "key") {
1569         $key = $params->{$p};
1570       }
1571     }
1572   }
1573
1574   if (!$all) {
1575     $where = "WHERE active ";
1576     if ($old_id) {
1577       if (ref($old_id) eq "ARRAY") {
1578         my @ids = grep({ $_ } @{$old_id});
1579         if (@ids) {
1580           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
1581           push(@values, @ids);
1582         }
1583       } else {
1584         $where .= " OR (id = ?) ";
1585         push(@values, $old_id);
1586       }
1587     }
1588   }
1589
1590   my $query =
1591     qq|SELECT id, projectnumber, description, active | .
1592     qq|FROM project | .
1593     $where .
1594     qq|ORDER BY lower(projectnumber)|;
1595
1596   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
1597
1598   $main::lxdebug->leave_sub();
1599 }
1600
1601 sub _get_shipto {
1602   $main::lxdebug->enter_sub();
1603
1604   my ($self, $dbh, $vc_id, $key) = @_;
1605
1606   $key = "all_shipto" unless ($key);
1607
1608   # get shipping addresses
1609   my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
1610
1611   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
1612
1613   $main::lxdebug->leave_sub();
1614 }
1615
1616 sub _get_printers {
1617   $main::lxdebug->enter_sub();
1618
1619   my ($self, $dbh, $key) = @_;
1620
1621   $key = "all_printers" unless ($key);
1622
1623   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
1624
1625   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1626
1627   $main::lxdebug->leave_sub();
1628 }
1629
1630 sub _get_charts {
1631   $main::lxdebug->enter_sub();
1632
1633   my ($self, $dbh, $params) = @_;
1634
1635   $key = $params->{key};
1636   $key = "all_charts" unless ($key);
1637
1638   my $transdate = quote_db_date($params->{transdate});
1639
1640   my $query =
1641     qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
1642     qq|FROM chart c | .
1643     qq|LEFT JOIN taxkeys tk ON | .
1644     qq|(tk.id = (SELECT id FROM taxkeys | .
1645     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
1646     qq|          ORDER BY startdate DESC LIMIT 1)) | .
1647     qq|ORDER BY c.accno|;
1648
1649   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1650
1651   $main::lxdebug->leave_sub();
1652 }
1653
1654 sub _get_taxcharts {
1655   $main::lxdebug->enter_sub();
1656
1657   my ($self, $dbh, $key) = @_;
1658
1659   $key = "all_taxcharts" unless ($key);
1660
1661   my $query = qq|SELECT * FROM tax ORDER BY taxkey|;
1662
1663   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1664
1665   $main::lxdebug->leave_sub();
1666 }
1667
1668 sub _get_taxzones {
1669   $main::lxdebug->enter_sub();
1670
1671   my ($self, $dbh, $key) = @_;
1672
1673   $key = "all_taxzones" unless ($key);
1674
1675   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
1676
1677   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1678
1679   $main::lxdebug->leave_sub();
1680 }
1681
1682 sub _get_employees {
1683   $main::lxdebug->enter_sub();
1684
1685   my ($self, $dbh, $default_key, $key) = @_;
1686
1687   $key = $default_key unless ($key);
1688   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY name|);
1689
1690   $main::lxdebug->leave_sub();
1691 }
1692
1693 sub _get_business_types {
1694   $main::lxdebug->enter_sub();
1695
1696   my ($self, $dbh, $key) = @_;
1697
1698   $key = "all_business_types" unless ($key);
1699   $self->{$key} =
1700     selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
1701
1702   $main::lxdebug->leave_sub();
1703 }
1704
1705 sub _get_languages {
1706   $main::lxdebug->enter_sub();
1707
1708   my ($self, $dbh, $key) = @_;
1709
1710   $key = "all_languages" unless ($key);
1711
1712   my $query = qq|SELECT * FROM language ORDER BY id|;
1713
1714   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1715
1716   $main::lxdebug->leave_sub();
1717 }
1718
1719 sub _get_dunning_configs {
1720   $main::lxdebug->enter_sub();
1721
1722   my ($self, $dbh, $key) = @_;
1723
1724   $key = "all_dunning_configs" unless ($key);
1725
1726   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
1727
1728   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1729
1730   $main::lxdebug->leave_sub();
1731 }
1732
1733 sub _get_currencies {
1734 $main::lxdebug->enter_sub();
1735
1736   my ($self, $dbh, $key) = @_;
1737
1738   $key = "all_currencies" unless ($key);
1739
1740   my $query = qq|SELECT curr AS currency FROM defaults|;
1741  
1742   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
1743
1744   $main::lxdebug->leave_sub();
1745 }
1746
1747 sub _get_payments {
1748 $main::lxdebug->enter_sub();
1749
1750   my ($self, $dbh, $key) = @_;
1751
1752   $key = "all_payments" unless ($key);
1753
1754   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
1755  
1756   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1757
1758   $main::lxdebug->leave_sub();
1759 }
1760
1761 sub _get_customers {
1762   $main::lxdebug->enter_sub();
1763
1764   my ($self, $dbh, $key) = @_;
1765
1766   $key = "all_customers" unless ($key);
1767
1768   my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name|;
1769
1770   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1771
1772   $main::lxdebug->leave_sub();
1773 }
1774
1775 sub _get_vendors {
1776   $main::lxdebug->enter_sub();
1777
1778   my ($self, $dbh, $key) = @_;
1779
1780   $key = "all_vendors" unless ($key);
1781
1782   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
1783
1784   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1785
1786   $main::lxdebug->leave_sub();
1787 }
1788
1789 sub _get_departments {
1790   $main::lxdebug->enter_sub();
1791
1792   my ($self, $dbh, $key) = @_;
1793
1794   $key = "all_departments" unless ($key);
1795
1796   my $query = qq|SELECT * FROM department ORDER BY description|;
1797
1798   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1799
1800   $main::lxdebug->leave_sub();
1801 }
1802
1803 sub get_lists {
1804   $main::lxdebug->enter_sub();
1805
1806   my $self = shift;
1807   my %params = @_;
1808
1809   my $dbh = $self->get_standard_dbh(\%main::myconfig);
1810   my ($sth, $query, $ref);
1811
1812   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
1813   my $vc_id = $self->{"${vc}_id"};
1814
1815   if ($params{"contacts"}) {
1816     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
1817   }
1818
1819   if ($params{"shipto"}) {
1820     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
1821   }
1822
1823   if ($params{"projects"} || $params{"all_projects"}) {
1824     $self->_get_projects($dbh, $params{"all_projects"} ?
1825                          $params{"all_projects"} : $params{"projects"},
1826                          $params{"all_projects"} ? 1 : 0);
1827   }
1828
1829   if ($params{"printers"}) {
1830     $self->_get_printers($dbh, $params{"printers"});
1831   }
1832
1833   if ($params{"languages"}) {
1834     $self->_get_languages($dbh, $params{"languages"});
1835   }
1836
1837   if ($params{"charts"}) {
1838     $self->_get_charts($dbh, $params{"charts"});
1839   }
1840
1841   if ($params{"taxcharts"}) {
1842     $self->_get_taxcharts($dbh, $params{"taxcharts"});
1843   }
1844
1845   if ($params{"taxzones"}) {
1846     $self->_get_taxzones($dbh, $params{"taxzones"});
1847   }
1848
1849   if ($params{"employees"}) {
1850     $self->_get_employees($dbh, "all_employees", $params{"employees"});
1851   }
1852   
1853   if ($params{"salesmen"}) {
1854     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
1855   }
1856
1857   if ($params{"business_types"}) {
1858     $self->_get_business_types($dbh, $params{"business_types"});
1859   }
1860
1861   if ($params{"dunning_configs"}) {
1862     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
1863   }
1864   
1865   if($params{"currencies"}) {
1866     $self->_get_currencies($dbh, $params{"currencies"});
1867   }
1868   
1869   if($params{"customers"}) {
1870     $self->_get_customers($dbh, $params{"customers"});
1871   }
1872   
1873   if($params{"vendors"}) {
1874     $self->_get_vendors($dbh, $params{"vendors"});
1875   }
1876   
1877   if($params{"payments"}) {
1878     $self->_get_payments($dbh, $params{"payments"});
1879   }
1880
1881   if($params{"departments"}) {
1882     $self->_get_departments($dbh, $params{"departments"});
1883   }
1884
1885   $main::lxdebug->leave_sub();
1886 }
1887
1888 # this sub gets the id and name from $table
1889 sub get_name {
1890   $main::lxdebug->enter_sub();
1891
1892   my ($self, $myconfig, $table) = @_;
1893
1894   # connect to database
1895   my $dbh = $self->get_standard_dbh($myconfig);
1896
1897   $table = $table eq "customer" ? "customer" : "vendor";
1898   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
1899
1900   my ($query, @values);
1901
1902   if (!$self->{openinvoices}) {
1903     my $where;
1904     if ($self->{customernumber} ne "") {
1905       $where = qq|(vc.customernumber ILIKE ?)|;
1906       push(@values, '%' . $self->{customernumber} . '%');
1907     } else {
1908       $where = qq|(vc.name ILIKE ?)|;
1909       push(@values, '%' . $self->{$table} . '%');
1910     }
1911
1912     $query =
1913       qq~SELECT vc.id, vc.name,
1914            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
1915          FROM $table vc
1916          WHERE $where AND (NOT vc.obsolete)
1917          ORDER BY vc.name~;
1918   } else {
1919     $query =
1920       qq~SELECT DISTINCT vc.id, vc.name,
1921            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
1922          FROM $arap a
1923          JOIN $table vc ON (a.${table}_id = vc.id)
1924          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
1925          ORDER BY vc.name~;
1926     push(@values, '%' . $self->{$table} . '%');
1927   }
1928
1929   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
1930
1931   $main::lxdebug->leave_sub();
1932
1933   return scalar(@{ $self->{name_list} });
1934 }
1935
1936 # the selection sub is used in the AR, AP, IS, IR and OE module
1937 #
1938 sub all_vc {
1939   $main::lxdebug->enter_sub();
1940
1941   my ($self, $myconfig, $table, $module) = @_;
1942
1943   my $ref;
1944   my $dbh = $self->get_standard_dbh($myconfig);
1945
1946   $table = $table eq "customer" ? "customer" : "vendor";
1947
1948   my $query = qq|SELECT count(*) FROM $table|;
1949   my ($count) = selectrow_query($self, $dbh, $query);
1950
1951   # build selection list
1952   if ($count < $myconfig->{vclimit}) {
1953     $query = qq|SELECT id, name, salesman_id
1954                 FROM $table WHERE NOT obsolete
1955                 ORDER BY name|;
1956     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
1957   }
1958
1959   # get self
1960   $self->get_employee($dbh);
1961
1962   # setup sales contacts
1963   $query = qq|SELECT e.id, e.name
1964               FROM employee e
1965               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
1966   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
1967
1968   # this is for self
1969   push(@{ $self->{all_employees} },
1970        { id   => $self->{employee_id},
1971          name => $self->{employee} });
1972
1973   # sort the whole thing
1974   @{ $self->{all_employees} } =
1975     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
1976
1977   if ($module eq 'AR') {
1978
1979     # prepare query for departments
1980     $query = qq|SELECT id, description
1981                 FROM department
1982                 WHERE role = 'P'
1983                 ORDER BY description|;
1984
1985   } else {
1986     $query = qq|SELECT id, description
1987                 FROM department
1988                 ORDER BY description|;
1989   }
1990
1991   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
1992
1993   # get languages
1994   $query = qq|SELECT id, description
1995               FROM language
1996               ORDER BY id|;
1997
1998   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
1999
2000   # get printer
2001   $query = qq|SELECT printer_description, id
2002               FROM printers
2003               ORDER BY printer_description|;
2004
2005   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2006
2007   # get payment terms
2008   $query = qq|SELECT id, description
2009               FROM payment_terms
2010               ORDER BY sortkey|;
2011
2012   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2013
2014   $main::lxdebug->leave_sub();
2015 }
2016
2017 sub language_payment {
2018   $main::lxdebug->enter_sub();
2019
2020   my ($self, $myconfig) = @_;
2021
2022   my $dbh = $self->get_standard_dbh($myconfig);
2023   # get languages
2024   my $query = qq|SELECT id, description
2025                  FROM language
2026                  ORDER BY id|;
2027
2028   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2029
2030   # get printer
2031   $query = qq|SELECT printer_description, id
2032               FROM printers
2033               ORDER BY printer_description|;
2034
2035   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2036
2037   # get payment terms
2038   $query = qq|SELECT id, description
2039               FROM payment_terms
2040               ORDER BY sortkey|;
2041
2042   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2043
2044   # get buchungsgruppen
2045   $query = qq|SELECT id, description
2046               FROM buchungsgruppen|;
2047
2048   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2049
2050   $main::lxdebug->leave_sub();
2051 }
2052
2053 # this is only used for reports
2054 sub all_departments {
2055   $main::lxdebug->enter_sub();
2056
2057   my ($self, $myconfig, $table) = @_;
2058
2059   my $dbh = $self->get_standard_dbh($myconfig);
2060   my $where;
2061
2062   if ($table eq 'customer') {
2063     $where = "WHERE role = 'P' ";
2064   }
2065
2066   my $query = qq|SELECT id, description
2067                  FROM department
2068                  $where
2069                  ORDER BY description|;
2070   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2071
2072   delete($self->{all_departments}) unless (@{ $self->{all_departments} });
2073
2074   $main::lxdebug->leave_sub();
2075 }
2076
2077 sub create_links {
2078   $main::lxdebug->enter_sub();
2079
2080   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2081
2082   my ($fld, $arap);
2083   if ($table eq "customer") {
2084     $fld = "buy";
2085     $arap = "ar";
2086   } else {
2087     $table = "vendor";
2088     $fld = "sell";
2089     $arap = "ap";
2090   }
2091
2092   $self->all_vc($myconfig, $table, $module);
2093
2094   # get last customers or vendors
2095   my ($query, $sth, $ref);
2096
2097   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2098   my %xkeyref = ();
2099
2100   if (!$self->{id}) {
2101
2102     my $transdate = "current_date";
2103     if ($self->{transdate}) {
2104       $transdate = $dbh->quote($self->{transdate});
2105     }
2106
2107     # now get the account numbers
2108     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2109                 FROM chart c, taxkeys tk
2110                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2111                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2112                 ORDER BY c.accno|;
2113
2114     $sth = $dbh->prepare($query);
2115
2116     do_statement($self, $sth, $query, '%' . $module . '%');
2117
2118     $self->{accounts} = "";
2119     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2120
2121       foreach my $key (split(/:/, $ref->{link})) {
2122         if ($key =~ /$module/) {
2123
2124           # cross reference for keys
2125           $xkeyref{ $ref->{accno} } = $key;
2126
2127           push @{ $self->{"${module}_links"}{$key} },
2128             { accno       => $ref->{accno},
2129               description => $ref->{description},
2130               taxkey      => $ref->{taxkey_id},
2131               tax_id      => $ref->{tax_id} };
2132
2133           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2134         }
2135       }
2136     }
2137   }
2138
2139   # get taxkeys and description
2140   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2141   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2142
2143   if (($module eq "AP") || ($module eq "AR")) {
2144     # get tax rates and description
2145     $query = qq|SELECT * FROM tax|;
2146     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2147   }
2148
2149   if ($self->{id}) {
2150     $query =
2151       qq|SELECT
2152            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2153            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2154            a.intnotes, a.department_id, a.amount AS oldinvtotal,
2155            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2156            c.name AS $table,
2157            d.description AS department,
2158            e.name AS employee
2159          FROM $arap a
2160          JOIN $table c ON (a.${table}_id = c.id)
2161          LEFT JOIN employee e ON (e.id = a.employee_id)
2162          LEFT JOIN department d ON (d.id = a.department_id)
2163          WHERE a.id = ?|;
2164     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2165
2166     foreach $key (keys %$ref) {
2167       $self->{$key} = $ref->{$key};
2168     }
2169
2170     my $transdate = "current_date";
2171     if ($self->{transdate}) {
2172       $transdate = $dbh->quote($self->{transdate});
2173     }
2174
2175     # now get the account numbers
2176     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2177                 FROM chart c
2178                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2179                 WHERE c.link LIKE ?
2180                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2181                     OR c.link LIKE '%_tax%')
2182                 ORDER BY c.accno|;
2183
2184     $sth = $dbh->prepare($query);
2185     do_statement($self, $sth, $query, "%$module%");
2186
2187     $self->{accounts} = "";
2188     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2189
2190       foreach my $key (split(/:/, $ref->{link})) {
2191         if ($key =~ /$module/) {
2192
2193           # cross reference for keys
2194           $xkeyref{ $ref->{accno} } = $key;
2195
2196           push @{ $self->{"${module}_links"}{$key} },
2197             { accno       => $ref->{accno},
2198               description => $ref->{description},
2199               taxkey      => $ref->{taxkey_id},
2200               tax_id      => $ref->{tax_id} };
2201
2202           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2203         }
2204       }
2205     }
2206
2207
2208     # get amounts from individual entries
2209     $query =
2210       qq|SELECT
2211            c.accno, c.description,
2212            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2213            p.projectnumber,
2214            t.rate, t.id
2215          FROM acc_trans a
2216          LEFT JOIN chart c ON (c.id = a.chart_id)
2217          LEFT JOIN project p ON (p.id = a.project_id)
2218          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2219                                     WHERE (tk.taxkey_id=a.taxkey) AND
2220                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2221                                         THEN tk.chart_id = a.chart_id
2222                                         ELSE 1 = 1
2223                                         END)
2224                                        OR (c.link='%tax%')) AND
2225                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2226          WHERE a.trans_id = ?
2227          AND a.fx_transaction = '0'
2228          ORDER BY a.oid, a.transdate|;
2229     $sth = $dbh->prepare($query);
2230     do_statement($self, $sth, $query, $self->{id});
2231
2232     # get exchangerate for currency
2233     $self->{exchangerate} =
2234       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2235     my $index = 0;
2236
2237     # store amounts in {acc_trans}{$key} for multiple accounts
2238     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2239       $ref->{exchangerate} =
2240         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2241       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2242         $index++;
2243       }
2244       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2245         $ref->{amount} *= -1;
2246       }
2247       $ref->{index} = $index;
2248
2249       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2250     }
2251
2252     $sth->finish;
2253     $query =
2254       qq|SELECT
2255            d.curr AS currencies, d.closedto, d.revtrans,
2256            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2257            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2258          FROM defaults d|;
2259     $ref = selectfirst_hashref_query($self, $dbh, $query);
2260     map { $self->{$_} = $ref->{$_} } keys %$ref;
2261
2262   } else {
2263
2264     # get date
2265     $query =
2266        qq|SELECT
2267             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2268             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2269             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2270           FROM defaults d|;
2271     $ref = selectfirst_hashref_query($self, $dbh, $query);
2272     map { $self->{$_} = $ref->{$_} } keys %$ref;
2273
2274     if ($self->{"$self->{vc}_id"}) {
2275
2276       # only setup currency
2277       ($self->{currency}) = split(/:/, $self->{currencies});
2278
2279     } else {
2280
2281       $self->lastname_used($dbh, $myconfig, $table, $module);
2282
2283       # get exchangerate for currency
2284       $self->{exchangerate} =
2285         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2286
2287     }
2288
2289   }
2290
2291   $main::lxdebug->leave_sub();
2292 }
2293
2294 sub lastname_used {
2295   $main::lxdebug->enter_sub();
2296
2297   my ($self, $dbh, $myconfig, $table, $module) = @_;
2298
2299   my $arap  = ($table eq 'customer') ? "ar" : "ap";
2300   $table = $table eq "customer" ? "customer" : "vendor";
2301   my $where = "1 = 1";
2302
2303   if ($self->{type} =~ /_order/) {
2304     $arap  = 'oe';
2305     $where = "quotation = '0'";
2306   }
2307   if ($self->{type} =~ /_quotation/) {
2308     $arap  = 'oe';
2309     $where = "quotation = '1'";
2310   }
2311
2312   my $query = qq|SELECT MAX(id) FROM $arap
2313                  WHERE $where AND ${table}_id > 0|;
2314   my ($trans_id) = selectrow_query($self, $dbh, $query);
2315
2316   $trans_id *= 1;
2317   $query =
2318     qq|SELECT
2319          a.curr, a.${table}_id, a.department_id,
2320          d.description AS department,
2321          ct.name, current_date + ct.terms AS duedate
2322        FROM $arap a
2323        LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2324        LEFT JOIN department d ON (a.department_id = d.id)
2325        WHERE a.id = ?|;
2326   ($self->{currency},   $self->{"${table}_id"}, $self->{department_id},
2327    $self->{department}, $self->{$table},        $self->{duedate})
2328     = selectrow_query($self, $dbh, $query, $trans_id);
2329
2330   $main::lxdebug->leave_sub();
2331 }
2332
2333 sub current_date {
2334   $main::lxdebug->enter_sub();
2335
2336   my ($self, $myconfig, $thisdate, $days) = @_;
2337
2338   my $dbh = $self->get_standard_dbh($myconfig);
2339   my $query;
2340
2341   $days *= 1;
2342   if ($thisdate) {
2343     my $dateformat = $myconfig->{dateformat};
2344     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2345     $thisdate = $dbh->quote($thisdate);
2346     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2347   } else {
2348     $query = qq|SELECT current_date AS thisdate|;
2349   }
2350
2351   ($thisdate) = selectrow_query($self, $dbh, $query);
2352
2353   $main::lxdebug->leave_sub();
2354
2355   return $thisdate;
2356 }
2357
2358 sub like {
2359   $main::lxdebug->enter_sub();
2360
2361   my ($self, $string) = @_;
2362
2363   if ($string !~ /%/) {
2364     $string = "%$string%";
2365   }
2366
2367   $string =~ s/\'/\'\'/g;
2368
2369   $main::lxdebug->leave_sub();
2370
2371   return $string;
2372 }
2373
2374 sub redo_rows {
2375   $main::lxdebug->enter_sub();
2376
2377   my ($self, $flds, $new, $count, $numrows) = @_;
2378
2379   my @ndx = ();
2380
2381   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } }
2382     (1 .. $count);
2383
2384   my $i = 0;
2385
2386   # fill rows
2387   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2388     $i++;
2389     $j = $item->{ndx} - 1;
2390     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2391   }
2392
2393   # delete empty rows
2394   for $i ($count + 1 .. $numrows) {
2395     map { delete $self->{"${_}_$i"} } @{$flds};
2396   }
2397
2398   $main::lxdebug->leave_sub();
2399 }
2400
2401 sub update_status {
2402   $main::lxdebug->enter_sub();
2403
2404   my ($self, $myconfig) = @_;
2405
2406   my ($i, $id);
2407
2408   my $dbh = $self->dbconnect_noauto($myconfig);
2409
2410   my $query = qq|DELETE FROM status
2411                  WHERE (formname = ?) AND (trans_id = ?)|;
2412   my $sth = prepare_query($self, $dbh, $query);
2413
2414   if ($self->{formname} =~ /(check|receipt)/) {
2415     for $i (1 .. $self->{rowcount}) {
2416       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
2417     }
2418   } else {
2419     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
2420   }
2421   $sth->finish();
2422
2423   my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
2424   my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
2425
2426   my %queued = split / /, $self->{queued};
2427   my @values;
2428
2429   if ($self->{formname} =~ /(check|receipt)/) {
2430
2431     # this is a check or receipt, add one entry for each lineitem
2432     my ($accno) = split /--/, $self->{account};
2433     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
2434                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
2435     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
2436     $sth = prepare_query($self, $dbh, $query);
2437
2438     for $i (1 .. $self->{rowcount}) {
2439       if ($self->{"checked_$i"}) {
2440         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
2441       }
2442     }
2443     $sth->finish();
2444
2445   } else {
2446     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2447                 VALUES (?, ?, ?, ?, ?)|;
2448     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
2449              $queued{$self->{formname}}, $self->{formname});
2450   }
2451
2452   $dbh->commit;
2453   $dbh->disconnect;
2454
2455   $main::lxdebug->leave_sub();
2456 }
2457
2458 sub save_status {
2459   $main::lxdebug->enter_sub();
2460
2461   my ($self, $dbh) = @_;
2462
2463   my ($query, $printed, $emailed);
2464
2465   my $formnames  = $self->{printed};
2466   my $emailforms = $self->{emailed};
2467
2468   my $query = qq|DELETE FROM status
2469                  WHERE (formname = ?) AND (trans_id = ?)|;
2470   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
2471
2472   # this only applies to the forms
2473   # checks and receipts are posted when printed or queued
2474
2475   if ($self->{queued}) {
2476     my %queued = split / /, $self->{queued};
2477
2478     foreach my $formname (keys %queued) {
2479       $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
2480       $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
2481
2482       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2483                   VALUES (?, ?, ?, ?, ?)|;
2484       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
2485
2486       $formnames  =~ s/$self->{formname}//;
2487       $emailforms =~ s/$self->{formname}//;
2488
2489     }
2490   }
2491
2492   # save printed, emailed info
2493   $formnames  =~ s/^ +//g;
2494   $emailforms =~ s/^ +//g;
2495
2496   my %status = ();
2497   map { $status{$_}{printed} = 1 } split / +/, $formnames;
2498   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
2499
2500   foreach my $formname (keys %status) {
2501     $printed = ($formnames  =~ /$self->{formname}/) ? "1" : "0";
2502     $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
2503
2504     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
2505                 VALUES (?, ?, ?, ?)|;
2506     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
2507   }
2508
2509   $main::lxdebug->leave_sub();
2510 }
2511
2512 #--- 4 locale ---#
2513 # $main::locale->text('SAVED')
2514 # $main::locale->text('DELETED')
2515 # $main::locale->text('ADDED')
2516 # $main::locale->text('PAYMENT POSTED')
2517 # $main::locale->text('POSTED')
2518 # $main::locale->text('POSTED AS NEW')
2519 # $main::locale->text('ELSE')
2520 # $main::locale->text('SAVED FOR DUNNING')
2521 # $main::locale->text('DUNNING STARTED')
2522 # $main::locale->text('PRINTED')
2523 # $main::locale->text('MAILED')
2524 # $main::locale->text('SCREENED')
2525 # $main::locale->text('CANCELED')
2526 # $main::locale->text('invoice')
2527 # $main::locale->text('proforma')
2528 # $main::locale->text('sales_order')
2529 # $main::locale->text('packing_list')
2530 # $main::locale->text('pick_list')
2531 # $main::locale->text('purchase_order')
2532 # $main::locale->text('bin_list')
2533 # $main::locale->text('sales_quotation')
2534 # $main::locale->text('request_quotation')
2535
2536 sub save_history {
2537   $main::lxdebug->enter_sub();
2538
2539   my $self = shift();
2540   my $dbh = shift();
2541
2542   if(!exists $self->{employee_id}) {
2543     &get_employee($self, $dbh);
2544   }
2545
2546   my $query =
2547    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
2548    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
2549   my @values = (conv_i($self->{id}), $self->{login},
2550                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
2551   do_query($self, $dbh, $query, @values);
2552
2553   $main::lxdebug->leave_sub();
2554 }
2555
2556 sub get_history {
2557   $main::lxdebug->enter_sub();
2558
2559   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
2560   my ($orderBy, $desc) = split(/\-\-/, $order);
2561   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
2562   my @tempArray;
2563   my $i = 0;
2564   if ($trans_id ne "") {
2565     my $query =
2566       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 | .
2567       qq|FROM history_erp h | .
2568       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
2569       qq|WHERE trans_id = | . $trans_id
2570       . $restriction . qq| |
2571       . $order;
2572       
2573     my $sth = $dbh->prepare($query) || $self->dberror($query);
2574
2575     $sth->execute() || $self->dberror("$query");
2576
2577     while(my $hash_ref = $sth->fetchrow_hashref()) {
2578       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
2579       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
2580       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
2581       $tempArray[$i++] = $hash_ref;
2582     }
2583     $main::lxdebug->leave_sub() and return \@tempArray 
2584       if ($i > 0 && $tempArray[0] ne "");
2585   }
2586   $main::lxdebug->leave_sub();
2587   return 0;
2588 }
2589
2590 sub update_defaults {
2591   $main::lxdebug->enter_sub();
2592
2593   my ($self, $myconfig, $fld, $provided_dbh) = @_;
2594
2595   my $dbh;
2596   if ($provided_dbh) {
2597     $dbh = $provided_dbh;
2598   } else {
2599     $dbh = $self->dbconnect_noauto($myconfig);
2600   }
2601   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
2602   my $sth   = $dbh->prepare($query);
2603
2604   $sth->execute || $self->dberror($query);
2605   my ($var) = $sth->fetchrow_array;
2606   $sth->finish;
2607
2608   $var =~ s/\d+$/ sprintf '%0*d', length($&), $&+1 /e;
2609   $var ||= 1;
2610
2611   $query = qq|UPDATE defaults SET $fld = ?|;
2612   do_query($self, $dbh, $query, $var);
2613
2614   if (!$provided_dbh) {
2615     $dbh->commit;
2616     $dbh->disconnect;
2617   }
2618
2619   $main::lxdebug->leave_sub();
2620
2621   return $var;
2622 }
2623
2624 sub update_business {
2625   $main::lxdebug->enter_sub();
2626
2627   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
2628
2629   my $dbh;
2630   if ($provided_dbh) {
2631     $dbh = $provided_dbh;
2632   } else {
2633     $dbh = $self->dbconnect_noauto($myconfig);
2634   }
2635   my $query =
2636     qq|SELECT customernumberinit FROM business
2637        WHERE id = ? FOR UPDATE|;
2638   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
2639
2640   $var =~ s/\d+$/ sprintf '%0*d', length($&), $&+1 /e;
2641   
2642   $query = qq|UPDATE business
2643               SET customernumberinit = ?
2644               WHERE id = ?|;
2645   do_query($self, $dbh, $query, $var, $business_id);
2646
2647   if (!$provided_dbh) {
2648     $dbh->commit;
2649     $dbh->disconnect;
2650   }
2651
2652   $main::lxdebug->leave_sub();
2653
2654   return $var;
2655 }
2656
2657 sub get_partsgroup {
2658   $main::lxdebug->enter_sub();
2659
2660   my ($self, $myconfig, $p) = @_;
2661
2662   my $dbh = $self->get_standard_dbh($myconfig);
2663
2664   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
2665                  FROM partsgroup pg
2666                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
2667   my @values;
2668
2669   if ($p->{searchitems} eq 'part') {
2670     $query .= qq|WHERE p.inventory_accno_id > 0|;
2671   }
2672   if ($p->{searchitems} eq 'service') {
2673     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
2674   }
2675   if ($p->{searchitems} eq 'assembly') {
2676     $query .= qq|WHERE p.assembly = '1'|;
2677   }
2678   if ($p->{searchitems} eq 'labor') {
2679     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
2680   }
2681
2682   $query .= qq|ORDER BY partsgroup|;
2683
2684   if ($p->{all}) {
2685     $query = qq|SELECT id, partsgroup FROM partsgroup
2686                 ORDER BY partsgroup|;
2687   }
2688
2689   if ($p->{language_code}) {
2690     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
2691                   t.description AS translation
2692                 FROM partsgroup pg
2693                 JOIN parts p ON (p.partsgroup_id = pg.id)
2694                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
2695                 ORDER BY translation|;
2696     @values = ($p->{language_code});
2697   }
2698
2699   $self->{all_partsgroup} = selectall_hashref_query($self, $dbh, $query, @values);
2700
2701   $main::lxdebug->leave_sub();
2702 }
2703
2704 sub get_pricegroup {
2705   $main::lxdebug->enter_sub();
2706
2707   my ($self, $myconfig, $p) = @_;
2708
2709   my $dbh = $self->get_standard_dbh($myconfig);
2710
2711   my $query = qq|SELECT p.id, p.pricegroup
2712                  FROM pricegroup p|;
2713
2714   $query .= qq| ORDER BY pricegroup|;
2715
2716   if ($p->{all}) {
2717     $query = qq|SELECT id, pricegroup FROM pricegroup
2718                 ORDER BY pricegroup|;
2719   }
2720
2721   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
2722
2723   $main::lxdebug->leave_sub();
2724 }
2725
2726 sub all_years {
2727 # usage $form->all_years($myconfig, [$dbh])
2728 # return list of all years where bookings found
2729 # (@all_years)
2730
2731   $main::lxdebug->enter_sub();
2732
2733   my ($self, $myconfig, $dbh) = @_;
2734
2735   $dbh ||= $self->get_standard_dbh($myconfig);
2736
2737   # get years
2738   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
2739                    (SELECT MAX(transdate) FROM acc_trans)|;
2740   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
2741
2742   if ($myconfig->{dateformat} =~ /^yy/) {
2743     ($startdate) = split /\W/, $startdate;
2744     ($enddate) = split /\W/, $enddate;
2745   } else {
2746     (@_) = split /\W/, $startdate;
2747     $startdate = $_[2];
2748     (@_) = split /\W/, $enddate;
2749     $enddate = $_[2];
2750   }
2751
2752   my @all_years;
2753   $startdate = substr($startdate,0,4);
2754   $enddate = substr($enddate,0,4);
2755
2756   while ($enddate >= $startdate) {
2757     push @all_years, $enddate--;
2758   }
2759
2760   return @all_years;
2761
2762   $main::lxdebug->leave_sub();
2763 }
2764
2765 1;