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