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