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