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