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