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