9b5f27973013ef39607d8f32a1816535488c3f95
[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::Menu;
47 use SL::User;
48 use SL::Common;
49 use CGI;
50
51 sub _input_to_hash {
52   $main::lxdebug->enter_sub(2);
53
54   my $input = $_[0];
55   my %in    = ();
56   my @pairs = split(/&/, $input);
57
58   foreach (@pairs) {
59     my ($name, $value) = split(/=/, $_, 2);
60     $in{$name} = unescape(undef, $value);
61   }
62
63   $main::lxdebug->leave_sub(2);
64
65   return %in;
66 }
67
68 sub _request_to_hash {
69   $main::lxdebug->enter_sub(2);
70
71   my ($input) = @_;
72   my ($i,        $loc,  $key,    $val);
73   my (%ATTACH,   $f,    $header, $header_body, $len, $buf);
74   my ($boundary, @list, $size,   $body, $x, $blah, $name);
75
76   if ($ENV{'CONTENT_TYPE'}
77       && ($ENV{'CONTENT_TYPE'} =~ /multipart\/form-data; boundary=(.+)$/)) {
78     $boundary = quotemeta('--' . $1);
79     @list     = split(/$boundary/, $input);
80
81     # For some reason there are always 2 extra, that are empty
82     $size = @list - 2;
83
84     for ($x = 1; $x <= $size; $x++) {
85       $header_body = $list[$x];
86       $header_body =~ /\r\n\r\n|\n\n/;
87
88       # Here we split the header and body
89       $header = $`;
90       $body   = $';    #'
91       $body =~ s/\r\n$//;
92
93       # Now we try to get the file name
94       $name = $header;
95       $name =~ /name=\"(.+)\"/;
96       ($name, $blah) = split(/\"/, $1);
97
98       # If the form name is not attach, then we need to parse this like
99       # regular form data
100       if ($name ne "attach") {
101         $body =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
102         $ATTACH{$name} = $body;
103
104         # Otherwise it is an attachment and we need to finish it up
105       } elsif ($name eq "attach") {
106         $header =~ /filename=\"(.+)\"/;
107         $ATTACH{'FILE_NAME'} = $1;
108         $ATTACH{'FILE_NAME'} =~ s/\"//g;
109         $ATTACH{'FILE_NAME'} =~ s/\s//g;
110         $ATTACH{'FILE_CONTENT'} = $body;
111
112         for ($i = $x; $list[$i]; $i++) {
113           $list[$i] =~ s/^.+name=$//;
114           $list[$i] =~ /\"(\w+)\"/;
115           $ATTACH{$1} = $';    #'
116         }
117       }
118     }
119
120     $main::lxdebug->leave_sub(2);
121     return %ATTACH;
122
123       } else {
124     $main::lxdebug->leave_sub(2);
125     return _input_to_hash($input);
126   }
127 }
128
129 sub new {
130   $main::lxdebug->enter_sub();
131
132   my $type = shift;
133
134   my $self = {};
135
136   if ($LXDebug::watch_form) {
137     require SL::Watchdog;
138     tie %{ $self }, 'SL::Watchdog';
139   }
140
141   read(STDIN, $_, $ENV{CONTENT_LENGTH});
142
143   if ($ENV{QUERY_STRING}) {
144     $_ = $ENV{QUERY_STRING};
145   }
146
147   if ($ARGV[0]) {
148     $_ = $ARGV[0];
149   }
150
151   my %parameters = _request_to_hash($_);
152   map({ $self->{$_} = $parameters{$_}; } keys(%parameters));
153
154   $self->{action} = lc $self->{action};
155   $self->{action} =~ s/( |-|,|\#)/_/g;
156
157   $self->{version}   = "2.4.2";
158
159   $main::lxdebug->leave_sub();
160
161   bless $self, $type;
162 }
163
164 sub debug {
165   $main::lxdebug->enter_sub();
166
167   my ($self) = @_;
168
169   print "\n";
170
171   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
172
173   $main::lxdebug->leave_sub();
174 }
175
176 sub escape {
177   $main::lxdebug->enter_sub(2);
178
179   my ($self, $str) = @_;
180
181   $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
182
183   $main::lxdebug->leave_sub(2);
184
185   return $str;
186 }
187
188 sub unescape {
189   $main::lxdebug->enter_sub(2);
190
191   my ($self, $str) = @_;
192
193   $str =~ tr/+/ /;
194   $str =~ s/\\$//;
195
196   $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
197
198   $main::lxdebug->leave_sub(2);
199
200   return $str;
201 }
202
203 sub quote {
204   my ($self, $str) = @_;
205
206   if ($str && !ref($str)) {
207     $str =~ s/\"/&quot;/g;
208   }
209
210   $str;
211
212 }
213
214 sub unquote {
215   my ($self, $str) = @_;
216
217   if ($str && !ref($str)) {
218     $str =~ s/&quot;/\"/g;
219   }
220
221   $str;
222
223 }
224
225 sub quote_html {
226   $main::lxdebug->enter_sub(2);
227
228   my ($self, $str) = @_;
229
230   my %replace =
231     ('order' => ['"', '<', '>'],
232      '<'             => '&lt;',
233      '>'             => '&gt;',
234      '"'             => '&quot;',
235     );
236
237   map({ $str =~ s/$_/$replace{$_}/g; } @{ $replace{"order"} });
238
239   $main::lxdebug->leave_sub(2);
240
241   return $str;
242 }
243
244 sub hide_form {
245   my $self = shift;
246
247   if (@_) {
248     map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
249   } else {
250     for (sort keys %$self) {
251       next if (($_ eq "header") || (ref($self->{$_}) ne ""));
252       print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
253     }
254   }
255
256 }
257
258 sub error {
259   $main::lxdebug->enter_sub();
260
261   $main::lxdebug->show_backtrace();
262
263   my ($self, $msg) = @_;
264   if ($ENV{HTTP_USER_AGENT}) {
265     $msg =~ s/\n/<br>/g;
266     $self->show_generic_error($msg);
267
268   } else {
269
270     if ($self->{error_function}) {
271       &{ $self->{error_function} }($msg);
272     } else {
273       die "Error: $msg\n";
274     }
275   }
276
277   $main::lxdebug->leave_sub();
278 }
279
280 sub info {
281   $main::lxdebug->enter_sub();
282
283   my ($self, $msg) = @_;
284
285   if ($ENV{HTTP_USER_AGENT}) {
286     $msg =~ s/\n/<br>/g;
287
288     if (!$self->{header}) {
289       $self->header;
290       print qq|
291       <body>|;
292     }
293
294     print qq|
295
296     <p><b>$msg</b>
297     |;
298
299   } else {
300
301     if ($self->{info_function}) {
302       &{ $self->{info_function} }($msg);
303     } else {
304       print "$msg\n";
305     }
306   }
307
308   $main::lxdebug->leave_sub();
309 }
310
311 sub numtextrows {
312   $main::lxdebug->enter_sub();
313
314   my ($self, $str, $cols, $maxrows) = @_;
315
316   my $rows = 0;
317
318   map { $rows += int(((length) - 2) / $cols) + 1 } split /\r/, $str;
319
320   $maxrows = $rows unless defined $maxrows;
321
322   $main::lxdebug->leave_sub();
323
324   return ($rows > $maxrows) ? $maxrows : $rows;
325 }
326
327 sub dberror {
328   $main::lxdebug->enter_sub();
329
330   my ($self, $msg) = @_;
331
332   $self->error("$msg\n" . $DBI::errstr);
333
334   $main::lxdebug->leave_sub();
335 }
336
337 sub isblank {
338   $main::lxdebug->enter_sub();
339
340   my ($self, $name, $msg) = @_;
341
342   if ($self->{$name} =~ /^\s*$/) {
343     $self->error($msg);
344   }
345   $main::lxdebug->leave_sub();
346 }
347
348 sub header {
349   $main::lxdebug->enter_sub();
350
351   my ($self, $extra_code) = @_;
352
353   if ($self->{header}) {
354     $main::lxdebug->leave_sub();
355     return;
356   }
357
358   my ($stylesheet, $favicon);
359
360   if ($ENV{HTTP_USER_AGENT}) {
361
362     if ($self->{stylesheet} && (-f "css/$self->{stylesheet}")) {
363       $stylesheet =
364         qq|<LINK REL="stylesheet" HREF="css/$self->{stylesheet}" TYPE="text/css" TITLE="Lx-Office stylesheet">
365  |;
366     }
367
368     $self->{favicon}    = "favicon.ico" unless $self->{favicon};
369
370     if ($self->{favicon} && (-f "$self->{favicon}")) {
371       $favicon =
372         qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
373   |;
374     }
375
376     my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
377
378     if ($self->{landscape}) {
379       $pagelayout = qq|<style type="text/css">
380                         \@page { size:landscape; }
381                         </style>|;
382     }
383
384     my $fokus = qq|  document.$self->{fokus}.focus();| if ($self->{"fokus"});
385
386     #Set Calendar
387     my $jsscript = "";
388     if ($self->{jsscript} == 1) {
389
390       $jsscript = qq|
391         <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
392         <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
393         <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
394         <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
395         $self->{javascript}
396        |;
397     }
398
399     $self->{titlebar} =
400       ($self->{title})
401       ? "$self->{title} - $self->{titlebar}"
402       : $self->{titlebar};
403     my $ajax = "";
404     foreach $item (@ { $self->{AJAX} }) {
405       $ajax .= $item->show_javascript();
406     }
407     print qq|Content-Type: text/html; charset=${db_charset};
408
409 <html>
410 <head>
411   <title>$self->{titlebar}</title>
412   $stylesheet
413   $pagelayout
414   $favicon
415   <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
416   $jsscript
417   $ajax
418
419   <script type="text/javascript">
420   <!--
421     function fokus() {
422       $fokus
423     }
424   //-->
425   </script>
426
427   <meta name="robots" content="noindex,nofollow" />
428   <script type="text/javascript" src="js/highlight_input.js"></script>
429   <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
430
431   <script type="text/javascript" src="js/tabcontent.js">
432
433   /***********************************************
434   * Tab Content script- Dynamic Drive DHTML code library (www.dynamicdrive.com)
435   * This notice MUST stay intact for legal use
436   * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
437   ***********************************************/
438
439   </script>
440
441   $extra_code
442 </head>
443
444 |;
445   }
446   $self->{header} = 1;
447
448   $main::lxdebug->leave_sub();
449 }
450
451 sub parse_html_template {
452   $main::lxdebug->enter_sub();
453
454   my ($self, $file, $additional_params) = @_;
455   my $language;
456
457   if (!defined(%main::myconfig) || !defined($main::myconfig{"countrycode"})) {
458     $language = $main::language;
459   } else {
460     $language = $main::myconfig{"countrycode"};
461   }
462   $language = "de" unless ($language);
463
464   if (-f "templates/webpages/${file}_${language}.html") {
465     if ((-f ".developer") &&
466         (-f "templates/webpages/${file}_master.html") &&
467         ((stat("templates/webpages/${file}_master.html"))[9] >
468          (stat("templates/webpages/${file}_${language}.html"))[9])) {
469       my $info = "Developer information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
470         "Please re-run 'locales.pl' in 'locale/${language}'.";
471       print(qq|<pre>$info</pre>|);
472       die($info);
473     }
474
475     $file = "templates/webpages/${file}_${language}.html";
476   } elsif (-f "templates/webpages/${file}.html") {
477     $file = "templates/webpages/${file}.html";
478   } else {
479     my $info = "Web page template '${file}' not found.\n" .
480       "Please re-run 'locales.pl' in 'locale/${language}'.";
481     print(qq|<pre>$info</pre>|);
482     die($info);
483   }
484
485   my $template = HTML::Template->new("filename" => $file,
486                                      "die_on_bad_params" => 0,
487                                      "strict" => 0,
488                                      "case_sensitive" => 1,
489                                      "loop_context_vars" => 1,
490                                      "global_vars" => 1);
491
492   $additional_params = {} unless ($additional_params);
493   if ($self->{"DEBUG"}) {
494     $additional_params->{"DEBUG"} = $self->{"DEBUG"};
495   }
496
497   if ($additional_params->{"DEBUG"}) {
498     $additional_params->{"DEBUG"} =
499       "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
500   }
501
502   if (%main::myconfig) {
503     map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
504     my $jsc_dateformat = $main::myconfig{"dateformat"};
505     $jsc_dateformat =~ s/d+/\%d/gi;
506     $jsc_dateformat =~ s/m+/\%m/gi;
507     $jsc_dateformat =~ s/y+/\%Y/gi;
508     $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
509   }
510
511   $additional_params->{"conf_lizenzen"} = $main::lizenzen;
512   $additional_params->{"conf_latex_templates"} = $main::latex;
513   $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
514
515   my @additional_param_names = keys(%{$additional_params});
516   foreach my $key ($template->param()) {
517     my $param = $self->{$key};
518     $param = $additional_params->{$key} if (grep(/^${key}$/, @additional_param_names));
519     $param = [] if (($template->query("name" => $key) eq "LOOP") && (ref($param) ne "ARRAY"));
520     $template->param($key => $param);
521   }
522
523   my $output = $template->output();
524
525   $main::lxdebug->leave_sub();
526
527   return $output;
528 }
529
530 sub show_generic_error {
531   my ($self, $error, $title, $action) = @_;
532
533   my $add_params = {};
534   $add_params->{"title"} = $title if ($title);
535   $self->{"label_error"} = $error;
536
537   my @vars;
538   if ($action) {
539     map({ delete($self->{$_}); } qw(action));
540     map({ push(@vars, { "name" => $_, "value" => $self->{$_} })
541             if (!ref($self->{$_})); }
542         keys(%{$self}));
543     $add_params->{"SHOW_BUTTON"} = 1;
544     $add_params->{"BUTTON_LABEL"} = $action;
545   }
546   $add_params->{"VARIABLES"} = \@vars;
547
548   $self->header();
549   print($self->parse_html_template("generic/error", $add_params));
550
551   die("Error: $error\n");
552 }
553
554 sub show_generic_information {
555   my ($self, $error, $title) = @_;
556
557   my $add_params = {};
558   $add_params->{"title"} = $title if ($title);
559   $self->{"label_information"} = $error;
560
561   $self->header();
562   print($self->parse_html_template("generic/information", $add_params));
563
564   die("Information: $error\n");
565 }
566
567 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
568 # changed it to accept an arbitrary number of triggers - sschoeling
569 sub write_trigger {
570   $main::lxdebug->enter_sub();
571
572   my $self     = shift;
573   my $myconfig = shift;
574   my $qty      = shift;
575
576   # set dateform for jsscript
577   # default
578   my %dateformats = (
579     "dd.mm.yy" => "%d.%m.%Y",
580     "dd-mm-yy" => "%d-%m-%Y",
581     "dd/mm/yy" => "%d/%m/%Y",
582     "mm/dd/yy" => "%m/%d/%Y",
583     "mm-dd-yy" => "%m-%d-%Y",
584     "yyyy-mm-dd" => "%Y-%m-%d",
585     );
586
587   my $ifFormat = defined($dateformats{$myconfig{"dateformat"}}) ?
588     $dateformats{$myconfig{"dateformat"}} : "%d.%m.%Y";
589
590   my @triggers;
591   while ($#_ >= 2) {
592     push @triggers, qq|
593        Calendar.setup(
594       {
595       inputField : "| . (shift) . qq|",
596       ifFormat :"$ifFormat",
597       align : "| .  (shift) . qq|",
598       button : "| . (shift) . qq|"
599       }
600       );
601        |;
602   }
603   my $jsscript = qq|
604        <script type="text/javascript">
605        <!--| . join("", @triggers) . qq|//-->
606         </script>
607         |;
608
609   $main::lxdebug->leave_sub();
610
611   return $jsscript;
612 }    #end sub write_trigger
613
614 sub redirect {
615   $main::lxdebug->enter_sub();
616
617   my ($self, $msg) = @_;
618
619   if ($self->{callback}) {
620
621     ($script, $argv) = split(/\?/, $self->{callback});
622     exec("perl", "$script", $argv);
623
624   } else {
625
626     $self->info($msg);
627     exit;
628   }
629
630   $main::lxdebug->leave_sub();
631 }
632
633 # sort of columns removed - empty sub
634 sub sort_columns {
635   $main::lxdebug->enter_sub();
636
637   my ($self, @columns) = @_;
638
639   $main::lxdebug->leave_sub();
640
641   return @columns;
642 }
643 #
644 sub format_amount {
645   $main::lxdebug->enter_sub(2);
646
647   my ($self, $myconfig, $amount, $places, $dash) = @_;
648
649   if ($amount eq "") {
650     $amount = 0;
651   }
652   my $neg = ($amount =~ s/-//);
653
654   if (defined($places) && ($places ne '')) {
655     if ($places < 0) {
656       $amount *= 1;
657       $places *= -1;
658
659       my ($actual_places) = ($amount =~ /\.(\d+)/);
660       $actual_places = length($actual_places);
661       $places = $actual_places > $places ? $actual_places : $places;
662     }
663
664     $amount = $self->round_amount($amount, $places);
665   }
666
667   my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
668   my @p = split(/\./, $amount); # split amount at decimal point
669
670   $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
671
672   $amount = $p[0];
673   $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
674
675   $amount = do {
676     ($dash =~ /-/)    ? ($neg ? "($amount)"  : "$amount" )    :
677     ($dash =~ /DRCR/) ? ($neg ? "$amount DR" : "$amount CR" ) :
678                         ($neg ? "-$amount"   : "$amount" )    ;
679   };
680
681
682   $main::lxdebug->leave_sub(2);
683   return $amount;
684 }
685 #
686 sub parse_amount {
687   $main::lxdebug->enter_sub(2);
688
689   my ($self, $myconfig, $amount) = @_;
690
691   if (   ($myconfig->{numberformat} eq '1.000,00')
692       || ($myconfig->{numberformat} eq '1000,00')) {
693     $amount =~ s/\.//g;
694     $amount =~ s/,/\./;
695   }
696
697   if ($myconfig->{numberformat} eq "1'000.00") {
698     $amount =~ s/\'//g;
699   }
700
701   $amount =~ s/,//g;
702
703   $main::lxdebug->leave_sub(2);
704
705   return ($amount * 1);
706 }
707
708 sub round_amount {
709   $main::lxdebug->enter_sub(2);
710
711   my ($self, $amount, $places) = @_;
712   my $round_amount;
713
714   # Rounding like "Kaufmannsrunden"
715   # Descr. http://de.wikipedia.org/wiki/Rundung
716   # Inspired by
717   # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
718   # Solves Bug: 189
719   # Udo Spallek
720   $amount = $amount * (10**($places));
721   $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
722
723   $main::lxdebug->leave_sub(2);
724
725   return $round_amount;
726
727 }
728
729 sub parse_template {
730   $main::lxdebug->enter_sub();
731
732   my ($self, $myconfig, $userspath) = @_;
733   my ($template, $out);
734
735   local (*IN, *OUT);
736
737   $self->{"cwd"} = getcwd();
738   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
739
740   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
741     $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
742   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
743     $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
744     $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
745   } elsif (($self->{"format"} =~ /html/i) ||
746            (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
747     $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
748   } elsif (($self->{"format"} =~ /xml/i) ||
749              (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
750     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
751   } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
752     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
753   } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
754     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
755   } elsif ( defined $self->{'format'}) {
756     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
757   } elsif ( $self->{'format'} eq '' ) {
758     $self->error("No Outputformat given: $self->{'format'}");
759   } else { #Catch the rest
760     $self->error("Outputformat not defined: $self->{'format'}");
761   }
762
763   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
764   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
765
766   map({ $self->{"employee_${_}"} = $myconfig->{$_}; }
767       qw(email tel fax name signature company address businessnumber
768          co_ustid taxnumber duns));
769   map({ $self->{"employee_${_}"} =~ s/\\n/\n/g; }
770       qw(company address signature));
771   map({ $self->{$_} =~ s/\\n/\n/g; } qw(company address signature));
772
773   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
774
775   # OUT is used for the media, screen, printer, email
776   # for postscript we store a copy in a temporary file
777   my $fileid = time;
778   my $prepend_userspath;
779
780   if (!$self->{tmpfile}) {
781     $self->{tmpfile}   = "${fileid}.$self->{IN}";
782     $prepend_userspath = 1;
783   }
784
785   $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
786
787   $self->{tmpfile} =~ s|.*/||;
788   $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
789   $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
790
791   if ($template->uses_temp_file() || $self->{media} eq 'email') {
792     $out = $self->{OUT};
793     $self->{OUT} = ">$self->{tmpfile}";
794   }
795
796   if ($self->{OUT}) {
797     open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
798   } else {
799     open(OUT, ">-") or $self->error("STDOUT : $!");
800     $self->header;
801   }
802
803   if (!$template->parse(*OUT)) {
804     $self->cleanup();
805     $self->error("$self->{IN} : " . $template->get_error());
806   }
807
808   close(OUT);
809
810   if ($template->uses_temp_file() || $self->{media} eq 'email') {
811
812     if ($self->{media} eq 'email') {
813
814       use SL::Mailer;
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 =
1523     qq|SELECT shipto_id, shiptoname, shiptodepartment_1 | .
1524     qq|FROM shipto | .
1525     qq|WHERE trans_id = ?|;
1526
1527   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
1528
1529   $main::lxdebug->leave_sub();
1530 }
1531
1532 sub _get_printers {
1533   $main::lxdebug->enter_sub();
1534
1535   my ($self, $dbh, $key) = @_;
1536
1537   $key = "all_printers" unless ($key);
1538
1539   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
1540
1541   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1542
1543   $main::lxdebug->leave_sub();
1544 }
1545
1546 sub _get_charts {
1547   $main::lxdebug->enter_sub();
1548
1549   my ($self, $dbh, $params) = @_;
1550
1551   $key = $params->{key};
1552   $key = "all_charts" unless ($key);
1553
1554   my $transdate = quote_db_date($params->{transdate});
1555
1556   my $query =
1557     qq|SELECT c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
1558     qq|FROM chart c | .
1559     qq|LEFT JOIN taxkeys tk ON | .
1560     qq|(tk.id = (SELECT id FROM taxkeys | .
1561     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
1562     qq|          ORDER BY startdate DESC LIMIT 1)) | .
1563     qq|ORDER BY c.accno|;
1564
1565   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1566
1567   $main::lxdebug->leave_sub();
1568 }
1569
1570 sub _get_taxcharts {
1571   $main::lxdebug->enter_sub();
1572
1573   my ($self, $dbh, $key) = @_;
1574
1575   $key = "all_taxcharts" unless ($key);
1576
1577   my $query = qq|SELECT * FROM tax ORDER BY taxkey|;
1578
1579   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1580
1581   $main::lxdebug->leave_sub();
1582 }
1583
1584 sub _get_taxzones {
1585   $main::lxdebug->enter_sub();
1586
1587   my ($self, $dbh, $key) = @_;
1588
1589   $key = "all_taxzones" unless ($key);
1590
1591   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
1592
1593   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1594
1595   $main::lxdebug->leave_sub();
1596 }
1597
1598 sub _get_employees {
1599   $main::lxdebug->enter_sub();
1600
1601   my ($self, $dbh, $key) = @_;
1602
1603   $key = "all_employees" unless ($key);
1604   $self->{$key} =
1605     selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee|);
1606
1607   $main::lxdebug->leave_sub();
1608 }
1609
1610 sub _get_business_types {
1611   $main::lxdebug->enter_sub();
1612
1613   my ($self, $dbh, $key) = @_;
1614
1615   $key = "all_business_types" unless ($key);
1616   $self->{$key} =
1617     selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
1618
1619   $main::lxdebug->leave_sub();
1620 }
1621
1622 sub _get_languages {
1623   $main::lxdebug->enter_sub();
1624
1625   my ($self, $dbh, $key) = @_;
1626
1627   $key = "all_languages" unless ($key);
1628
1629   my $query = qq|SELECT * FROM language ORDER BY id|;
1630
1631   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1632
1633   $main::lxdebug->leave_sub();
1634 }
1635
1636 sub _get_dunning_configs {
1637   $main::lxdebug->enter_sub();
1638
1639   my ($self, $dbh, $key) = @_;
1640
1641   $key = "all_dunning_configs" unless ($key);
1642
1643   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
1644
1645   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1646
1647   $main::lxdebug->leave_sub();
1648 }
1649
1650 sub _get_currencies {
1651 $main::lxdebug->enter_sub();
1652
1653   my ($self, $dbh, $key) = @_;
1654
1655   $key = "all_currencies" unless ($key);
1656
1657   my $query = qq|SELECT curr AS currency FROM defaults|;
1658  
1659   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
1660
1661   $main::lxdebug->leave_sub();
1662 }
1663
1664 sub _get_payments {
1665 $main::lxdebug->enter_sub();
1666
1667   my ($self, $dbh, $key) = @_;
1668
1669   $key = "all_payments" unless ($key);
1670
1671   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
1672  
1673   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1674
1675   $main::lxdebug->leave_sub();
1676 }
1677
1678 sub _get_customers {
1679   $main::lxdebug->enter_sub();
1680
1681   my ($self, $dbh, $key) = @_;
1682
1683   $key = "all_customers" unless ($key);
1684
1685   my $query = qq|SELECT * FROM customer|;
1686
1687   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1688
1689   $main::lxdebug->leave_sub();
1690 }
1691
1692 sub _get_vendors {
1693   $main::lxdebug->enter_sub();
1694
1695   my ($self, $dbh, $key) = @_;
1696
1697   $key = "all_vendors" unless ($key);
1698
1699   my $query = qq|SELECT * FROM vendor|;
1700
1701   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1702
1703   $main::lxdebug->leave_sub();
1704 }
1705
1706 sub _get_departments {
1707   $main::lxdebug->enter_sub();
1708
1709   my ($self, $dbh, $key) = @_;
1710
1711   $key = "all_departments" unless ($key);
1712
1713   my $query = qq|SELECT * FROM department|;
1714
1715   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1716
1717   $main::lxdebug->leave_sub();
1718 }
1719
1720 sub get_lists {
1721   $main::lxdebug->enter_sub();
1722
1723   my $self = shift;
1724   my %params = @_;
1725
1726   my $dbh = $self->dbconnect(\%main::myconfig);
1727   my ($sth, $query, $ref);
1728
1729   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
1730   my $vc_id = $self->{"${vc}_id"};
1731
1732   if ($params{"contacts"}) {
1733     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
1734   }
1735
1736   if ($params{"shipto"}) {
1737     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
1738   }
1739
1740   if ($params{"projects"} || $params{"all_projects"}) {
1741     $self->_get_projects($dbh, $params{"all_projects"} ?
1742                          $params{"all_projects"} : $params{"projects"},
1743                          $params{"all_projects"} ? 1 : 0);
1744   }
1745
1746   if ($params{"printers"}) {
1747     $self->_get_printers($dbh, $params{"printers"});
1748   }
1749
1750   if ($params{"languages"}) {
1751     $self->_get_languages($dbh, $params{"languages"});
1752   }
1753
1754   if ($params{"charts"}) {
1755     $self->_get_charts($dbh, $params{"charts"});
1756   }
1757
1758   if ($params{"taxcharts"}) {
1759     $self->_get_taxcharts($dbh, $params{"taxcharts"});
1760   }
1761
1762   if ($params{"taxzones"}) {
1763     $self->_get_taxzones($dbh, $params{"taxzones"});
1764   }
1765
1766   if ($params{"employees"}) {
1767     $self->_get_employees($dbh, $params{"employees"});
1768   }
1769
1770   if ($params{"business_types"}) {
1771     $self->_get_business_types($dbh, $params{"business_types"});
1772   }
1773
1774   if ($params{"dunning_configs"}) {
1775     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
1776   }
1777   
1778   if($params{"currencies"}) {
1779     $self->_get_currencies($dbh, $params{"currencies"});
1780   }
1781   
1782   if($params{"customers"}) {
1783     $self->_get_customers($dbh, $params{"customers"});
1784   }
1785   
1786   if($params{"vendors"}) {
1787     $self->_get_vendors($dbh, $params{"vendors"});
1788   }
1789   
1790   if($params{"payments"}) {
1791     $self->_get_payments($dbh, $params{"payments"});
1792   }
1793
1794   if($params{"departments"}) {
1795     $self->_get_departments($dbh, $params{"departments"});
1796   }
1797
1798   $dbh->disconnect();
1799
1800   $main::lxdebug->leave_sub();
1801 }
1802
1803 # this sub gets the id and name from $table
1804 sub get_name {
1805   $main::lxdebug->enter_sub();
1806
1807   my ($self, $myconfig, $table) = @_;
1808
1809   # connect to database
1810   my $dbh = $self->dbconnect($myconfig);
1811
1812   $table = $table eq "customer" ? "customer" : "vendor";
1813   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
1814
1815   my ($query, @values);
1816
1817   if (!$self->{openinvoices}) {
1818     my $where;
1819     if ($self->{customernumber} ne "") {
1820       $where = qq|(vc.customernumber ILIKE ?)|;
1821       push(@values, '%' . $self->{customernumber} . '%');
1822     } else {
1823       $where = qq|(vc.name ILIKE ?)|;
1824       push(@values, '%' . $self->{$table} . '%');
1825     }
1826
1827     $query =
1828       qq~SELECT vc.id, vc.name,
1829            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
1830          FROM $table vc
1831          WHERE $where AND (NOT vc.obsolete)
1832          ORDER BY vc.name~;
1833   } else {
1834     $query =
1835       qq~SELECT DISTINCT vc.id, vc.name,
1836            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
1837          FROM $arap a
1838          JOIN $table vc ON (a.${table}_id = vc.id)
1839          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
1840          ORDER BY vc.name~;
1841     push(@values, '%' . $self->{$table} . '%');
1842   }
1843
1844   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
1845
1846   $main::lxdebug->leave_sub();
1847
1848   return scalar(@{ $self->{name_list} });
1849 }
1850
1851 # the selection sub is used in the AR, AP, IS, IR and OE module
1852 #
1853 sub all_vc {
1854   $main::lxdebug->enter_sub();
1855
1856   my ($self, $myconfig, $table, $module) = @_;
1857
1858   my $ref;
1859   my $dbh = $self->dbconnect($myconfig);
1860
1861   $table = $table eq "customer" ? "customer" : "vendor";
1862
1863   my $query = qq|SELECT count(*) FROM $table|;
1864   my ($count) = selectrow_query($self, $dbh, $query);
1865
1866   # build selection list
1867   if ($count < $myconfig->{vclimit}) {
1868     $query = qq|SELECT id, name, salesman_id
1869                 FROM $table WHERE NOT obsolete
1870                 ORDER BY name|;
1871     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
1872   }
1873
1874   # get self
1875   $self->get_employee($dbh);
1876
1877   # setup sales contacts
1878   $query = qq|SELECT e.id, e.name
1879               FROM employee e
1880               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
1881   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
1882
1883   # this is for self
1884   push(@{ $self->{all_employees} },
1885        { id   => $self->{employee_id},
1886          name => $self->{employee} });
1887
1888   # sort the whole thing
1889   @{ $self->{all_employees} } =
1890     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
1891
1892   if ($module eq 'AR') {
1893
1894     # prepare query for departments
1895     $query = qq|SELECT id, description
1896                 FROM department
1897                 WHERE role = 'P'
1898                 ORDER BY description|;
1899
1900   } else {
1901     $query = qq|SELECT id, description
1902                 FROM department
1903                 ORDER BY description|;
1904   }
1905
1906   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
1907
1908   # get languages
1909   $query = qq|SELECT id, description
1910               FROM language
1911               ORDER BY id|;
1912
1913   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
1914
1915   # get printer
1916   $query = qq|SELECT printer_description, id
1917               FROM printers
1918               ORDER BY printer_description|;
1919
1920   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
1921
1922   # get payment terms
1923   $query = qq|SELECT id, description
1924               FROM payment_terms
1925               ORDER BY sortkey|;
1926
1927   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
1928
1929   $dbh->disconnect;
1930
1931   $main::lxdebug->leave_sub();
1932 }
1933
1934 sub language_payment {
1935   $main::lxdebug->enter_sub();
1936
1937   my ($self, $myconfig) = @_;
1938
1939   my $dbh = $self->dbconnect($myconfig);
1940   # get languages
1941   my $query = qq|SELECT id, description
1942                  FROM language
1943                  ORDER BY id|;
1944
1945   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
1946
1947   # get printer
1948   $query = qq|SELECT printer_description, id
1949               FROM printers
1950               ORDER BY printer_description|;
1951
1952   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
1953
1954   # get payment terms
1955   $query = qq|SELECT id, description
1956               FROM payment_terms
1957               ORDER BY sortkey|;
1958
1959   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
1960
1961   # get buchungsgruppen
1962   $query = qq|SELECT id, description
1963               FROM buchungsgruppen|;
1964
1965   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
1966
1967   $dbh->disconnect;
1968   $main::lxdebug->leave_sub();
1969 }
1970
1971 # this is only used for reports
1972 sub all_departments {
1973   $main::lxdebug->enter_sub();
1974
1975   my ($self, $myconfig, $table) = @_;
1976
1977   my $dbh = $self->dbconnect($myconfig);
1978   my $where;
1979
1980   if ($table eq 'customer') {
1981     $where = "WHERE role = 'P' ";
1982   }
1983
1984   my $query = qq|SELECT id, description
1985                  FROM department
1986                  $where
1987                  ORDER BY description|;
1988   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
1989
1990   delete($self->{all_departments}) unless (@{ $self->{all_departments} });
1991
1992   $dbh->disconnect;
1993
1994   $main::lxdebug->leave_sub();
1995 }
1996
1997 sub create_links {
1998   $main::lxdebug->enter_sub();
1999
2000   my ($self, $module, $myconfig, $table) = @_;
2001
2002   my ($fld, $arap);
2003   if ($table eq "customer") {
2004     $fld = "buy";
2005     $arap = "ar";
2006   } else {
2007     $table = "vendor";
2008     $fld = "sell";
2009     $arap = "ap";
2010   }
2011
2012   $self->all_vc($myconfig, $table, $module);
2013
2014   # get last customers or vendors
2015   my ($query, $sth, $ref);
2016
2017   my $dbh = $self->dbconnect($myconfig);
2018   my %xkeyref = ();
2019
2020   if (!$self->{id}) {
2021
2022     my $transdate = "current_date";
2023     if ($self->{transdate}) {
2024       $transdate = $dbh->quote($self->{transdate});
2025     }
2026
2027     # now get the account numbers
2028     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2029                 FROM chart c, taxkeys tk
2030                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2031                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2032                 ORDER BY c.accno|;
2033
2034     $sth = $dbh->prepare($query);
2035
2036     do_statement($self, $sth, $query, '%' . $module . '%');
2037
2038     $self->{accounts} = "";
2039     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2040
2041       foreach my $key (split(/:/, $ref->{link})) {
2042         if ($key =~ /$module/) {
2043
2044           # cross reference for keys
2045           $xkeyref{ $ref->{accno} } = $key;
2046
2047           push @{ $self->{"${module}_links"}{$key} },
2048             { accno       => $ref->{accno},
2049               description => $ref->{description},
2050               taxkey      => $ref->{taxkey_id},
2051               tax_id      => $ref->{tax_id} };
2052
2053           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2054         }
2055       }
2056     }
2057   }
2058
2059   # get taxkeys and description
2060   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2061   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2062
2063   if (($module eq "AP") || ($module eq "AR")) {
2064     # get tax rates and description
2065     $query = qq|SELECT * FROM tax|;
2066     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2067   }
2068
2069   if ($self->{id}) {
2070     $query =
2071       qq|SELECT
2072            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2073            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2074            a.intnotes, a.department_id, a.amount AS oldinvtotal,
2075            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2076            c.name AS $table,
2077            d.description AS department,
2078            e.name AS employee
2079          FROM $arap a
2080          JOIN $table c ON (a.${table}_id = c.id)
2081          LEFT JOIN employee e ON (e.id = a.employee_id)
2082          LEFT JOIN department d ON (d.id = a.department_id)
2083          WHERE a.id = ?|;
2084     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2085
2086     foreach $key (keys %$ref) {
2087       $self->{$key} = $ref->{$key};
2088     }
2089
2090     my $transdate = "current_date";
2091     if ($self->{transdate}) {
2092       $transdate = $dbh->quote($self->{transdate});
2093     }
2094
2095     # now get the account numbers
2096     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2097                 FROM chart c
2098                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2099                 WHERE c.link LIKE ?
2100                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2101                     OR c.link LIKE '%_tax%')
2102                 ORDER BY c.accno|;
2103
2104     $sth = $dbh->prepare($query);
2105     do_statement($self, $sth, $query, "%$module%");
2106
2107     $self->{accounts} = "";
2108     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2109
2110       foreach my $key (split(/:/, $ref->{link})) {
2111         if ($key =~ /$module/) {
2112
2113           # cross reference for keys
2114           $xkeyref{ $ref->{accno} } = $key;
2115
2116           push @{ $self->{"${module}_links"}{$key} },
2117             { accno       => $ref->{accno},
2118               description => $ref->{description},
2119               taxkey      => $ref->{taxkey_id},
2120               tax_id      => $ref->{tax_id} };
2121
2122           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2123         }
2124       }
2125     }
2126
2127
2128     # get amounts from individual entries
2129     $query =
2130       qq|SELECT
2131            c.accno, c.description,
2132            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2133            p.projectnumber,
2134            t.rate, t.id
2135          FROM acc_trans a
2136          LEFT JOIN chart c ON (c.id = a.chart_id)
2137          LEFT JOIN project p ON (p.id = a.project_id)
2138          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2139                                     WHERE (tk.taxkey_id=a.taxkey) AND
2140                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2141                                         THEN tk.chart_id = a.chart_id
2142                                         ELSE 1 = 1
2143                                         END)
2144                                        OR (c.link='%tax%')) AND
2145                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2146          WHERE a.trans_id = ?
2147          AND a.fx_transaction = '0'
2148          ORDER BY a.oid, a.transdate|;
2149     $sth = $dbh->prepare($query);
2150     do_statement($self, $sth, $query, $self->{id});
2151
2152     # get exchangerate for currency
2153     $self->{exchangerate} =
2154       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2155     my $index = 0;
2156
2157     # store amounts in {acc_trans}{$key} for multiple accounts
2158     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2159       $ref->{exchangerate} =
2160         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2161       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2162         $index++;
2163       }
2164       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2165         $ref->{amount} *= -1;
2166       }
2167       $ref->{index} = $index;
2168
2169       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2170     }
2171
2172     $sth->finish;
2173     $query =
2174       qq|SELECT
2175            d.curr AS currencies, d.closedto, d.revtrans,
2176            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2177            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2178          FROM defaults d|;
2179     $ref = selectfirst_hashref_query($self, $dbh, $query);
2180     map { $self->{$_} = $ref->{$_} } keys %$ref;
2181
2182   } else {
2183
2184     # get date
2185     $query =
2186        qq|SELECT
2187             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2188             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2189             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2190           FROM defaults d|;
2191     $ref = selectfirst_hashref_query($self, $dbh, $query);
2192     map { $self->{$_} = $ref->{$_} } keys %$ref;
2193
2194     if ($self->{"$self->{vc}_id"}) {
2195
2196       # only setup currency
2197       ($self->{currency}) = split(/:/, $self->{currencies});
2198
2199     } else {
2200
2201       $self->lastname_used($dbh, $myconfig, $table, $module);
2202
2203       # get exchangerate for currency
2204       $self->{exchangerate} =
2205         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2206
2207     }
2208
2209   }
2210
2211   $dbh->disconnect;
2212
2213   $main::lxdebug->leave_sub();
2214 }
2215
2216 sub lastname_used {
2217   $main::lxdebug->enter_sub();
2218
2219   my ($self, $dbh, $myconfig, $table, $module) = @_;
2220
2221   my $arap  = ($table eq 'customer') ? "ar" : "ap";
2222   $table = $table eq "customer" ? "customer" : "vendor";
2223   my $where = "1 = 1";
2224
2225   if ($self->{type} =~ /_order/) {
2226     $arap  = 'oe';
2227     $where = "quotation = '0'";
2228   }
2229   if ($self->{type} =~ /_quotation/) {
2230     $arap  = 'oe';
2231     $where = "quotation = '1'";
2232   }
2233
2234   my $query = qq|SELECT MAX(id) FROM $arap
2235                  WHERE $where AND ${table}_id > 0|;
2236   my ($trans_id) = selectrow_query($self, $dbh, $query);
2237
2238   $trans_id *= 1;
2239   $query =
2240     qq|SELECT
2241          a.curr, a.${table}_id, a.department_id,
2242          d.description AS department,
2243          ct.name, current_date + ct.terms AS duedate
2244        FROM $arap a
2245        LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2246        LEFT JOIN department d ON (a.department_id = d.id)
2247        WHERE a.id = ?|;
2248   ($self->{currency},   $self->{"${table}_id"}, $self->{department_id},
2249    $self->{department}, $self->{$table},        $self->{duedate})
2250     = selectrow_query($self, $dbh, $query, $trans_id);
2251
2252   $main::lxdebug->leave_sub();
2253 }
2254
2255 sub current_date {
2256   $main::lxdebug->enter_sub();
2257
2258   my ($self, $myconfig, $thisdate, $days) = @_;
2259
2260   my $dbh = $self->dbconnect($myconfig);
2261   my $query;
2262
2263   $days *= 1;
2264   if ($thisdate) {
2265     my $dateformat = $myconfig->{dateformat};
2266     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2267     $thisdate = $dbh->quote($thisdate);
2268     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2269   } else {
2270     $query = qq|SELECT current_date AS thisdate|;
2271   }
2272
2273   ($thisdate) = selectrow_query($self, $dbh, $query);
2274
2275   $dbh->disconnect;
2276
2277   $main::lxdebug->leave_sub();
2278
2279   return $thisdate;
2280 }
2281
2282 sub like {
2283   $main::lxdebug->enter_sub();
2284
2285   my ($self, $string) = @_;
2286
2287   if ($string !~ /%/) {
2288     $string = "%$string%";
2289   }
2290
2291   $string =~ s/\'/\'\'/g;
2292
2293   $main::lxdebug->leave_sub();
2294
2295   return $string;
2296 }
2297
2298 sub redo_rows {
2299   $main::lxdebug->enter_sub();
2300
2301   my ($self, $flds, $new, $count, $numrows) = @_;
2302
2303   my @ndx = ();
2304
2305   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } }
2306     (1 .. $count);
2307
2308   my $i = 0;
2309
2310   # fill rows
2311   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2312     $i++;
2313     $j = $item->{ndx} - 1;
2314     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2315   }
2316
2317   # delete empty rows
2318   for $i ($count + 1 .. $numrows) {
2319     map { delete $self->{"${_}_$i"} } @{$flds};
2320   }
2321
2322   $main::lxdebug->leave_sub();
2323 }
2324
2325 sub update_status {
2326   $main::lxdebug->enter_sub();
2327
2328   my ($self, $myconfig) = @_;
2329
2330   my ($i, $id);
2331
2332   my $dbh = $self->dbconnect_noauto($myconfig);
2333
2334   my $query = qq|DELETE FROM status
2335                  WHERE (formname = ?) AND (trans_id = ?)|;
2336   my $sth = prepare_query($self, $dbh, $query);
2337
2338   if ($self->{formname} =~ /(check|receipt)/) {
2339     for $i (1 .. $self->{rowcount}) {
2340       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
2341     }
2342   } else {
2343     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
2344   }
2345   $sth->finish();
2346
2347   my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
2348   my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
2349
2350   my %queued = split / /, $self->{queued};
2351   my @values;
2352
2353   if ($self->{formname} =~ /(check|receipt)/) {
2354
2355     # this is a check or receipt, add one entry for each lineitem
2356     my ($accno) = split /--/, $self->{account};
2357     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
2358                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
2359     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
2360     $sth = prepare_query($self, $dbh, $query);
2361
2362     for $i (1 .. $self->{rowcount}) {
2363       if ($self->{"checked_$i"}) {
2364         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
2365       }
2366     }
2367     $sth->finish();
2368
2369   } else {
2370     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2371                 VALUES (?, ?, ?, ?, ?)|;
2372     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
2373              $queued{$self->{formname}}, $self->{formname});
2374   }
2375
2376   $dbh->commit;
2377   $dbh->disconnect;
2378
2379   $main::lxdebug->leave_sub();
2380 }
2381
2382 sub save_status {
2383   $main::lxdebug->enter_sub();
2384
2385   my ($self, $dbh) = @_;
2386
2387   my ($query, $printed, $emailed);
2388
2389   my $formnames  = $self->{printed};
2390   my $emailforms = $self->{emailed};
2391
2392   my $query = qq|DELETE FROM status
2393                  WHERE (formname = ?) AND (trans_id = ?)|;
2394   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
2395
2396   # this only applies to the forms
2397   # checks and receipts are posted when printed or queued
2398
2399   if ($self->{queued}) {
2400     my %queued = split / /, $self->{queued};
2401
2402     foreach my $formname (keys %queued) {
2403       $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
2404       $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
2405
2406       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2407                   VALUES (?, ?, ?, ?, ?)|;
2408       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
2409
2410       $formnames  =~ s/$self->{formname}//;
2411       $emailforms =~ s/$self->{formname}//;
2412
2413     }
2414   }
2415
2416   # save printed, emailed info
2417   $formnames  =~ s/^ +//g;
2418   $emailforms =~ s/^ +//g;
2419
2420   my %status = ();
2421   map { $status{$_}{printed} = 1 } split / +/, $formnames;
2422   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
2423
2424   foreach my $formname (keys %status) {
2425     $printed = ($formnames  =~ /$self->{formname}/) ? "1" : "0";
2426     $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
2427
2428     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
2429                 VALUES (?, ?, ?, ?)|;
2430     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
2431   }
2432
2433   $main::lxdebug->leave_sub();
2434 }
2435
2436 #--- 4 locale ---#
2437 # $main::locale->text('SAVED')
2438 # $main::locale->text('DELETED')
2439 # $main::locale->text('ADDED')
2440 # $main::locale->text('PAYMENT POSTED')
2441 # $main::locale->text('POSTED')
2442 # $main::locale->text('POSTED AS NEW')
2443 # $main::locale->text('ELSE')
2444 # $main::locale->text('SAVED FOR DUNNING')
2445 # $main::locale->text('DUNNING STARTED')
2446 # $main::locale->text('PRINTED')
2447 # $main::locale->text('MAILED')
2448 # $main::locale->text('SCREENED')
2449 # $main::locale->text('CANCELED')
2450 # $main::locale->text('invoice')
2451 # $main::locale->text('proforma')
2452 # $main::locale->text('sales_order')
2453 # $main::locale->text('packing_list')
2454 # $main::locale->text('pick_list')
2455 # $main::locale->text('purchase_order')
2456 # $main::locale->text('bin_list')
2457 # $main::locale->text('sales_quotation')
2458 # $main::locale->text('request_quotation')
2459
2460 sub save_history {
2461   $main::lxdebug->enter_sub();
2462
2463   my $self = shift();
2464   my $dbh = shift();
2465
2466   if(!exists $self->{employee_id}) {
2467     &get_employee($self, $dbh);
2468   }
2469
2470   my $query =
2471     qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
2472     qq|VALUES (?, ?, ?, ?, ?)|;
2473   my @values = (conv_i($self->{id}), conv_i($self->{employee_id}),
2474                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
2475   do_query($self, $dbh, $query, @values);
2476
2477   $main::lxdebug->leave_sub();
2478 }
2479
2480 sub get_history {
2481   $main::lxdebug->enter_sub();
2482
2483   my $self = shift();
2484   my $dbh = shift();
2485   my $trans_id = shift();
2486   my $restriction = shift();
2487   my @tempArray;
2488   my $i = 0;
2489   if ($trans_id ne "") {
2490     my $query =
2491       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 | .
2492       qq|FROM history_erp h | .
2493       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
2494       qq|WHERE trans_id = ? |
2495       . $restriction;
2496
2497     my $sth = $dbh->prepare($query) || $self->dberror($query);
2498
2499     $sth->execute($trans_id) || $self->dberror("$query ($trans_id)");
2500
2501     while(my $hash_ref = $sth->fetchrow_hashref()) {
2502       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
2503       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
2504       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
2505       $tempArray[$i++] = $hash_ref;
2506     }
2507     $main::lxdebug->leave_sub() and return \@tempArray 
2508       if ($i > 0 && $tempArray[0] ne "");
2509   }
2510   $main::lxdebug->leave_sub();
2511   return 0;
2512 }
2513
2514 sub update_defaults {
2515   $main::lxdebug->enter_sub();
2516
2517   my ($self, $myconfig, $fld, $provided_dbh) = @_;
2518
2519   my $dbh;
2520   if ($provided_dbh) {
2521     $dbh = $provided_dbh;
2522   } else {
2523     $dbh = $self->dbconnect_noauto($myconfig);
2524   }
2525   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
2526   my $sth   = $dbh->prepare($query);
2527
2528   $sth->execute || $self->dberror($query);
2529   my ($var) = $sth->fetchrow_array;
2530   $sth->finish;
2531
2532   $var =~ s/\d+$/ sprintf '%0*d', length($&), $&+1 /e;
2533   $var ||= 1;
2534
2535   $query = qq|UPDATE defaults SET $fld = ?|;
2536   do_query($self, $dbh, $query, $var);
2537
2538   if (!$provided_dbh) {
2539     $dbh->commit;
2540     $dbh->disconnect;
2541   }
2542
2543   $main::lxdebug->leave_sub();
2544
2545   return $var;
2546 }
2547
2548 sub update_business {
2549   $main::lxdebug->enter_sub();
2550
2551   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
2552
2553   my $dbh;
2554   if ($provided_dbh) {
2555     $dbh = $provided_dbh;
2556   } else {
2557     $dbh = $self->dbconnect_noauto($myconfig);
2558   }
2559   my $query =
2560     qq|SELECT customernumberinit FROM business
2561        WHERE id = ? FOR UPDATE|;
2562   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
2563
2564   $var =~ s/\d+$/ sprintf '%0*d', length($&), $&+1 /e;
2565   
2566   $query = qq|UPDATE business
2567               SET customernumberinit = ?
2568               WHERE id = ?|;
2569   do_query($self, $dbh, $query, $var, $business_id);
2570
2571   if (!$provided_dbh) {
2572     $dbh->commit;
2573     $dbh->disconnect;
2574   }
2575
2576   $main::lxdebug->leave_sub();
2577
2578   return $var;
2579 }
2580
2581 sub get_partsgroup {
2582   $main::lxdebug->enter_sub();
2583
2584   my ($self, $myconfig, $p) = @_;
2585
2586   my $dbh = $self->dbconnect($myconfig);
2587
2588   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
2589                  FROM partsgroup pg
2590                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
2591   my @values;
2592
2593   if ($p->{searchitems} eq 'part') {
2594     $query .= qq|WHERE p.inventory_accno_id > 0|;
2595   }
2596   if ($p->{searchitems} eq 'service') {
2597     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
2598   }
2599   if ($p->{searchitems} eq 'assembly') {
2600     $query .= qq|WHERE p.assembly = '1'|;
2601   }
2602   if ($p->{searchitems} eq 'labor') {
2603     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
2604   }
2605
2606   $query .= qq|ORDER BY partsgroup|;
2607
2608   if ($p->{all}) {
2609     $query = qq|SELECT id, partsgroup FROM partsgroup
2610                 ORDER BY partsgroup|;
2611   }
2612
2613   if ($p->{language_code}) {
2614     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
2615                   t.description AS translation
2616                 FROM partsgroup pg
2617                 JOIN parts p ON (p.partsgroup_id = pg.id)
2618                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
2619                 ORDER BY translation|;
2620     @values = ($p->{language_code});
2621   }
2622
2623   $self->{all_partsgroup} = selectall_hashref_query($self, $dbh, $query, @values);
2624
2625   $dbh->disconnect;
2626   $main::lxdebug->leave_sub();
2627 }
2628
2629 sub get_pricegroup {
2630   $main::lxdebug->enter_sub();
2631
2632   my ($self, $myconfig, $p) = @_;
2633
2634   my $dbh = $self->dbconnect($myconfig);
2635
2636   my $query = qq|SELECT p.id, p.pricegroup
2637                  FROM pricegroup p|;
2638
2639   $query .= qq| ORDER BY pricegroup|;
2640
2641   if ($p->{all}) {
2642     $query = qq|SELECT id, pricegroup FROM pricegroup
2643                 ORDER BY pricegroup|;
2644   }
2645
2646   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
2647
2648   $dbh->disconnect;
2649
2650   $main::lxdebug->leave_sub();
2651 }
2652
2653 sub all_years {
2654 # usage $form->all_years($myconfig, [$dbh])
2655 # return list of all years where bookings found
2656 # (@all_years)
2657
2658   $main::lxdebug->enter_sub();
2659
2660   my ($self, $myconfig, $dbh) = @_;
2661
2662   my $disconnect = 0;
2663   if (! $dbh) {
2664     $dbh = $self->dbconnect($myconfig);
2665     $disconnect = 1;
2666   }
2667
2668   # get years
2669   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
2670                    (SELECT MAX(transdate) FROM acc_trans)|;
2671   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
2672
2673   if ($myconfig->{dateformat} =~ /^yy/) {
2674     ($startdate) = split /\W/, $startdate;
2675     ($enddate) = split /\W/, $enddate;
2676   } else {
2677     (@_) = split /\W/, $startdate;
2678     $startdate = $_[2];
2679     (@_) = split /\W/, $enddate;
2680     $enddate = $_[2];
2681   }
2682
2683   my @all_years;
2684   $startdate = substr($startdate,0,4);
2685   $enddate = substr($enddate,0,4);
2686
2687   while ($enddate >= $startdate) {
2688     push @all_years, $enddate--;
2689   }
2690
2691   $dbh->disconnect if $disconnect;
2692
2693   return @all_years;
2694
2695   $main::lxdebug->leave_sub();
2696 }
2697
2698
2699 1;