928d75fa383a6563391558769332d08809a28f1e
[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}     = qq|$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 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_lists {
1542   $main::lxdebug->enter_sub();
1543
1544   my $self = shift;
1545   my %params = @_;
1546
1547   my $dbh = $self->dbconnect(\%main::myconfig);
1548   my ($sth, $query, $ref);
1549
1550   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
1551   my $vc_id = $self->{"${vc}_id"};
1552
1553   if ($params{"contacts"}) {
1554     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
1555   }
1556
1557   if ($params{"shipto"}) {
1558     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
1559   }
1560
1561   if ($params{"projects"} || $params{"all_projects"}) {
1562     $self->_get_projects($dbh, $params{"all_projects"} ?
1563                          $params{"all_projects"} : $params{"projects"},
1564                          $params{"all_projects"} ? 1 : 0);
1565   }
1566
1567   if ($params{"printers"}) {
1568     $self->_get_printers($dbh, $params{"printers"});
1569   }
1570
1571   if ($params{"charts"}) {
1572     $self->_get_charts($dbh, $params{"charts"});
1573   }
1574
1575   if ($params{"taxcharts"}) {
1576     $self->_get_taxcharts($dbh, $params{"taxcharts"});
1577   }
1578
1579   if ($params{"employees"}) {
1580     $self->_get_employees($dbh, $params{"employees"});
1581   }
1582
1583   if ($params{"business_types"}) {
1584     $self->_get_business_types($dbh, $params{"business_types"});
1585   }
1586
1587   $dbh->disconnect();
1588
1589   $main::lxdebug->leave_sub();
1590 }
1591
1592 # this sub gets the id and name from $table
1593 sub get_name {
1594   $main::lxdebug->enter_sub();
1595
1596   my ($self, $myconfig, $table) = @_;
1597
1598   # connect to database
1599   my $dbh = $self->dbconnect($myconfig);
1600
1601   $table = $table eq "customer" ? "customer" : "vendor";
1602   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
1603
1604   my ($query, @values);
1605
1606   if (!$self->{openinvoices}) {
1607     my $where;
1608     if ($self->{customernumber} ne "") {
1609       $where = qq|(vc.customernumber ILIKE ?)|;
1610       push(@values, '%' . $self->{customernumber} . '%');
1611     } else {
1612       $where = qq|(vc.name ILIKE ?)|;
1613       push(@values, '%' . $self->{$table} . '%');
1614     }
1615
1616     $query =
1617       qq~SELECT vc.id, vc.name,
1618            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
1619          FROM $table vc
1620          WHERE $where AND (NOT vc.obsolete)
1621          ORDER BY vc.name~;
1622   } else {
1623     $query =
1624       qq~SELECT DISTINCT vc.id, vc.name,
1625            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
1626          FROM $arap a
1627          JOIN $table vc ON (a.${table}_id = vc.id)
1628          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
1629          ORDER BY vc.name~;
1630     push(@values, '%' . $self->{$table} . '%');
1631   }
1632
1633   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
1634
1635   $main::lxdebug->leave_sub();
1636
1637   return scalar(@{ $self->{name_list} });
1638 }
1639
1640 # the selection sub is used in the AR, AP, IS, IR and OE module
1641 #
1642 sub all_vc {
1643   $main::lxdebug->enter_sub();
1644
1645   my ($self, $myconfig, $table, $module) = @_;
1646
1647   my $ref;
1648   my $dbh = $self->dbconnect($myconfig);
1649
1650   $table = $table eq "customer" ? "customer" : "vendor";
1651
1652   my $query = qq|SELECT count(*) FROM $table|;
1653   my ($count) = selectrow_query($self, $dbh, $query);
1654
1655   # build selection list
1656   if ($count < $myconfig->{vclimit}) {
1657     $query = qq|SELECT id, name, salesman_id
1658                 FROM $table WHERE NOT obsolete
1659                 ORDER BY name|;
1660     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
1661   }
1662
1663   # get self
1664   $self->get_employee($dbh);
1665
1666   # setup sales contacts
1667   $query = qq|SELECT e.id, e.name
1668               FROM employee e
1669               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
1670   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
1671
1672   # this is for self
1673   push(@{ $self->{all_employees} },
1674        { id   => $self->{employee_id},
1675          name => $self->{employee} });
1676
1677   # sort the whole thing
1678   @{ $self->{all_employees} } =
1679     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
1680
1681   if ($module eq 'AR') {
1682
1683     # prepare query for departments
1684     $query = qq|SELECT id, description
1685                 FROM department
1686                 WHERE role = 'P'
1687                 ORDER BY description|;
1688
1689   } else {
1690     $query = qq|SELECT id, description
1691                 FROM department
1692                 ORDER BY description|;
1693   }
1694
1695   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
1696
1697   # get languages
1698   $query = qq|SELECT id, description
1699               FROM language
1700               ORDER BY id|;
1701
1702   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
1703
1704   # get printer
1705   $query = qq|SELECT printer_description, id
1706               FROM printers
1707               ORDER BY printer_description|;
1708
1709   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
1710
1711   # get payment terms
1712   $query = qq|SELECT id, description
1713               FROM payment_terms
1714               ORDER BY sortkey|;
1715
1716   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
1717
1718   $dbh->disconnect;
1719
1720   $main::lxdebug->leave_sub();
1721 }
1722
1723 sub language_payment {
1724   $main::lxdebug->enter_sub();
1725
1726   my ($self, $myconfig) = @_;
1727
1728   my $dbh = $self->dbconnect($myconfig);
1729   # get languages
1730   my $query = qq|SELECT id, description
1731                  FROM language
1732                  ORDER BY id|;
1733
1734   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
1735
1736   # get printer
1737   $query = qq|SELECT printer_description, id
1738               FROM printers
1739               ORDER BY printer_description|;
1740
1741   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
1742
1743   # get payment terms
1744   $query = qq|SELECT id, description
1745               FROM payment_terms
1746               ORDER BY sortkey|;
1747
1748   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
1749
1750   # get buchungsgruppen
1751   $query = qq|SELECT id, description
1752               FROM buchungsgruppen|;
1753
1754   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
1755
1756   $dbh->disconnect;
1757   $main::lxdebug->leave_sub();
1758 }
1759
1760 # this is only used for reports
1761 sub all_departments {
1762   $main::lxdebug->enter_sub();
1763
1764   my ($self, $myconfig, $table) = @_;
1765
1766   my $dbh = $self->dbconnect($myconfig);
1767   my $where;
1768
1769   if ($table eq 'customer') {
1770     $where = "WHERE role = 'P' ";
1771   }
1772
1773   my $query = qq|SELECT id, description
1774                  FROM department
1775                  $where
1776                  ORDER BY description|;
1777   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
1778
1779   delete($self->{all_departments}) unless (@{ $self->{all_departments} });
1780
1781   $dbh->disconnect;
1782
1783   $main::lxdebug->leave_sub();
1784 }
1785
1786 sub create_links {
1787   $main::lxdebug->enter_sub();
1788
1789   my ($self, $module, $myconfig, $table) = @_;
1790
1791   my ($fld, $arap);
1792   if ($table eq "customer") {
1793     $fld = "buy";
1794     $arap = "ar";
1795   } else {
1796     $table = "vendor";
1797     $fld = "sell";
1798     $arap = "ap";
1799   }
1800
1801   $self->all_vc($myconfig, $table, $module);
1802
1803   # get last customers or vendors
1804   my ($query, $sth, $ref);
1805
1806   my $dbh = $self->dbconnect($myconfig);
1807   my %xkeyref = ();
1808
1809   if (!$self->{id}) {
1810
1811     my $transdate = "current_date";
1812     if ($self->{transdate}) {
1813       $transdate = $dbh->quote($self->{transdate});
1814     }
1815
1816     # now get the account numbers
1817     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
1818                 FROM chart c, taxkeys tk
1819                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
1820                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
1821                 ORDER BY c.accno|;
1822
1823     $sth = $dbh->prepare($query);
1824
1825     do_statement($form, $sth, $query, '%' . $module . '%');
1826
1827     $self->{accounts} = "";
1828     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1829
1830       foreach my $key (split(/:/, $ref->{link})) {
1831         if ($key =~ /$module/) {
1832
1833           # cross reference for keys
1834           $xkeyref{ $ref->{accno} } = $key;
1835
1836           push @{ $self->{"${module}_links"}{$key} },
1837             { accno       => $ref->{accno},
1838               description => $ref->{description},
1839               taxkey      => $ref->{taxkey_id},
1840               tax_id      => $ref->{tax_id} };
1841
1842           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
1843         }
1844       }
1845     }
1846   }
1847
1848   # get taxkeys and description
1849   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
1850   $self->{TAXKEY} = selectall_hashref_query($form, $dbh, $query);
1851
1852   # get tax zones
1853   $query = qq|SELECT id, description FROM tax_zones|;
1854   $self->{TAXZONE} = selectall_hashref_query($form, $dbh, $query);
1855
1856   if (($module eq "AP") || ($module eq "AR")) {
1857     # get tax rates and description
1858     $query = qq|SELECT * FROM tax|;
1859     $self->{TAX} = selectall_hashref_query($form, $dbh, $query);
1860   }
1861
1862   if ($self->{id}) {
1863     $query =
1864       qq|SELECT
1865            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
1866            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
1867            a.intnotes, a.department_id, a.amount AS oldinvtotal,
1868            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
1869            c.name AS $table,
1870            d.description AS department,
1871            e.name AS employee
1872          FROM $arap a
1873          JOIN $table c ON (a.${table}_id = c.id)
1874          LEFT JOIN employee e ON (e.id = a.employee_id)
1875          LEFT JOIN department d ON (d.id = a.department_id)
1876          WHERE a.id = ?|;
1877     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
1878
1879     foreach $key (keys %$ref) {
1880       $self->{$key} = $ref->{$key};
1881     }
1882
1883     my $transdate = "current_date";
1884     if ($self->{transdate}) {
1885       $transdate = $dbh->quote($self->{transdate});
1886     }
1887
1888     # now get the account numbers
1889     $query = qq|
1890       SELECT
1891         c.accno, c.description, c.link, c.taxkey_id,
1892         tk.tax_id
1893       FROM chart c
1894       LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
1895       WHERE (c.link LIKE ?) AND (tk.chart_id = c.id) AND NOT (c.link LIKE '%_tax%')
1896       ORDER BY c.accno|;
1897
1898     $sth = $dbh->prepare($query);
1899     do_statement($form, $sth, $query, "%" . $module . "%");
1900
1901     $self->{accounts} = "";
1902     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1903
1904       foreach my $key (split(/:/, $ref->{link})) {
1905         if ($key =~ /$module/) {
1906
1907           # cross reference for keys
1908           $xkeyref{ $ref->{accno} } = $key;
1909
1910           push @{ $self->{"${module}_links"}{$key} },
1911             { accno       => $ref->{accno},
1912               description => $ref->{description},
1913               taxkey      => $ref->{taxkey_id},
1914               tax_id      => $ref->{tax_id} };
1915
1916           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
1917         }
1918       }
1919     }
1920
1921
1922     # get amounts from individual entries
1923     $query =
1924       qq|SELECT
1925            c.accno, c.description,
1926            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
1927            p.projectnumber,
1928            t.rate, t.id
1929          FROM acc_trans a
1930          LEFT JOIN chart c ON (c.id = a.chart_id)
1931          LEFT JOIN project p ON (p.id = a.project_id)
1932          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
1933                                     WHERE (tk.taxkey_id=a.taxkey) AND
1934                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
1935                                         THEN tk.chart_id = a.chart_id
1936                                         ELSE 1 = 1
1937                                         END)
1938                                        OR (c.link='%tax%')) AND
1939                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
1940          WHERE a.trans_id = ?
1941          AND a.fx_transaction = '0'
1942          ORDER BY a.oid, a.transdate|;
1943     $sth = $dbh->prepare($query);
1944     do_statement($form, $sth, $query, $self->{id});
1945
1946     # get exchangerate for currency
1947     $self->{exchangerate} =
1948       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
1949     my $index = 0;
1950
1951     # store amounts in {acc_trans}{$key} for multiple accounts
1952     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1953       $ref->{exchangerate} =
1954         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
1955       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
1956         $index++;
1957       }
1958       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
1959         $ref->{amount} *= -1;
1960       }
1961       $ref->{index} = $index;
1962
1963       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
1964     }
1965
1966     $sth->finish;
1967     $query =
1968       qq|SELECT
1969            d.curr AS currencies, d.closedto, d.revtrans,
1970            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
1971            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
1972          FROM defaults d|;
1973     $ref = selectfirst_hashref_query($self, $dbh, $query);
1974     map { $self->{$_} = $ref->{$_} } keys %$ref;
1975
1976   } else {
1977
1978     # get date
1979     $query =
1980        qq|SELECT
1981             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
1982             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
1983             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
1984           FROM defaults d|;
1985     $ref = selectfirst_hashref_query($self, $dbh, $query);
1986     map { $self->{$_} = $ref->{$_} } keys %$ref;
1987
1988     if ($self->{"$self->{vc}_id"}) {
1989
1990       # only setup currency
1991       ($self->{currency}) = split(/:/, $self->{currencies});
1992
1993     } else {
1994
1995       $self->lastname_used($dbh, $myconfig, $table, $module);
1996
1997       # get exchangerate for currency
1998       $self->{exchangerate} =
1999         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2000
2001     }
2002
2003   }
2004
2005   $dbh->disconnect;
2006
2007   $main::lxdebug->leave_sub();
2008 }
2009
2010 sub lastname_used {
2011   $main::lxdebug->enter_sub();
2012
2013   my ($self, $dbh, $myconfig, $table, $module) = @_;
2014
2015   my $arap  = ($table eq 'customer') ? "ar" : "ap";
2016   $table = $table eq "customer" ? "customer" : "vendor";
2017   my $where = "1 = 1";
2018
2019   if ($self->{type} =~ /_order/) {
2020     $arap  = 'oe';
2021     $where = "quotation = '0'";
2022   }
2023   if ($self->{type} =~ /_quotation/) {
2024     $arap  = 'oe';
2025     $where = "quotation = '1'";
2026   }
2027
2028   my $query = qq|SELECT MAX(id) FROM $arap
2029                  WHERE $where AND ${table}_id > 0|;
2030   my ($trans_id) = selectrow_query($self, $dbh, $query);
2031
2032   $trans_id *= 1;
2033   $query =
2034     qq|SELECT
2035          a.curr, a.${table}_id, a.department_id,
2036          d.description AS department,
2037          ct.name, current_date + ct.terms AS duedate
2038        FROM $arap a
2039        LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2040        LEFT JOIN department d ON (a.department_id = d.id)
2041        WHERE a.id = ?|;
2042   ($self->{currency},   $self->{"${table}_id"}, $self->{department_id},
2043    $self->{department}, $self->{$table},        $self->{duedate})
2044     = selectrow_query($self, $dbh, $query, $trans_id);
2045
2046   $main::lxdebug->leave_sub();
2047 }
2048
2049 sub current_date {
2050   $main::lxdebug->enter_sub();
2051
2052   my ($self, $myconfig, $thisdate, $days) = @_;
2053
2054   my $dbh = $self->dbconnect($myconfig);
2055   my $query;
2056
2057   $days *= 1;
2058   if ($thisdate) {
2059     my $dateformat = $myconfig->{dateformat};
2060     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2061     $thisdate = $dbh->quote($thisdate);
2062     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2063   } else {
2064     $query = qq|SELECT current_date AS thisdate|;
2065   }
2066
2067   ($thisdate) = selectrow_query($self, $dbh, $query);
2068
2069   $dbh->disconnect;
2070
2071   $main::lxdebug->leave_sub();
2072
2073   return $thisdate;
2074 }
2075
2076 sub like {
2077   $main::lxdebug->enter_sub();
2078
2079   my ($self, $string) = @_;
2080
2081   if ($string !~ /%/) {
2082     $string = "%$string%";
2083   }
2084
2085   $string =~ s/\'/\'\'/g;
2086
2087   $main::lxdebug->leave_sub();
2088
2089   return $string;
2090 }
2091
2092 sub redo_rows {
2093   $main::lxdebug->enter_sub();
2094
2095   my ($self, $flds, $new, $count, $numrows) = @_;
2096
2097   my @ndx = ();
2098
2099   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } }
2100     (1 .. $count);
2101
2102   my $i = 0;
2103
2104   # fill rows
2105   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2106     $i++;
2107     $j = $item->{ndx} - 1;
2108     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2109   }
2110
2111   # delete empty rows
2112   for $i ($count + 1 .. $numrows) {
2113     map { delete $self->{"${_}_$i"} } @{$flds};
2114   }
2115
2116   $main::lxdebug->leave_sub();
2117 }
2118
2119 sub update_status {
2120   $main::lxdebug->enter_sub();
2121
2122   my ($self, $myconfig) = @_;
2123
2124   my ($i, $id);
2125
2126   my $dbh = $self->dbconnect_noauto($myconfig);
2127
2128   my $query = qq|DELETE FROM status
2129                  WHERE (formname = ?) AND (trans_id = ?)|;
2130   my $sth = prepare_query($self, $dbh, $query);
2131
2132   if ($self->{formname} =~ /(check|receipt)/) {
2133     for $i (1 .. $self->{rowcount}) {
2134       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
2135     }
2136   } else {
2137     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
2138   }
2139   $sth->finish();
2140
2141   my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
2142   my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
2143
2144   my %queued = split / /, $self->{queued};
2145   my @values;
2146
2147   if ($self->{formname} =~ /(check|receipt)/) {
2148
2149     # this is a check or receipt, add one entry for each lineitem
2150     my ($accno) = split /--/, $self->{account};
2151     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
2152                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
2153     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
2154     $sth = prepare_query($self, $dbh, $query);
2155
2156     for $i (1 .. $self->{rowcount}) {
2157       if ($self->{"checked_$i"}) {
2158         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
2159       }
2160     }
2161     $sth->finish();
2162
2163   } else {
2164     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2165                 VALUES (?, ?, ?, ?, ?)|;
2166     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
2167              $queued{$self->{formname}}, $self->{formname});
2168   }
2169
2170   $dbh->commit;
2171   $dbh->disconnect;
2172
2173   $main::lxdebug->leave_sub();
2174 }
2175
2176 sub save_status {
2177   $main::lxdebug->enter_sub();
2178
2179   my ($self, $dbh) = @_;
2180
2181   my ($query, $printed, $emailed);
2182
2183   my $formnames  = $self->{printed};
2184   my $emailforms = $self->{emailed};
2185
2186   my $query = qq|DELETE FROM status
2187                  WHERE (formname = ?) AND (trans_id = ?)|;
2188   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
2189
2190   # this only applies to the forms
2191   # checks and receipts are posted when printed or queued
2192
2193   if ($self->{queued}) {
2194     my %queued = split / /, $self->{queued};
2195
2196     foreach my $formname (keys %queued) {
2197       $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
2198       $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
2199
2200       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2201                   VALUES (?, ?, ?, ?, ?)|;
2202       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
2203
2204       $formnames  =~ s/$self->{formname}//;
2205       $emailforms =~ s/$self->{formname}//;
2206
2207     }
2208   }
2209
2210   # save printed, emailed info
2211   $formnames  =~ s/^ +//g;
2212   $emailforms =~ s/^ +//g;
2213
2214   my %status = ();
2215   map { $status{$_}{printed} = 1 } split / +/, $formnames;
2216   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
2217
2218   foreach my $formname (keys %status) {
2219     $printed = ($formnames  =~ /$self->{formname}/) ? "1" : "0";
2220     $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
2221
2222     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
2223                 VALUES (?, ?, ?, ?)|;
2224     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
2225   }
2226
2227   $main::lxdebug->leave_sub();
2228 }
2229
2230 #--- 4 locale ---#
2231 # $main::locale->text('SAVED')
2232 # $main::locale->text('DELETED')
2233 # $main::locale->text('ADDED')
2234 # $main::locale->text('PAYMENT POSTED')
2235 # $main::locale->text('POSTED')
2236 # $main::locale->text('POSTED AS NEW')
2237 # $main::locale->text('ELSE')
2238 # $main::locale->text('SAVED FOR DUNNING')
2239 # $main::locale->text('DUNNING STARTED')
2240 # $main::locale->text('PRINTED')
2241 # $main::locale->text('MAILED')
2242 # $main::locale->text('SCREENED')
2243 # $main::locale->text('invoice')
2244 # $main::locale->text('proforma')
2245 # $main::locale->text('sales_order')
2246 # $main::locale->text('packing_list')
2247 # $main::locale->text('pick_list')
2248 # $main::locale->text('purchase_order')
2249 # $main::locale->text('bin_list')
2250 # $main::locale->text('sales_quotation')
2251 # $main::locale->text('request_quotation')
2252
2253 sub save_history {
2254   $main::lxdebug->enter_sub();
2255
2256   my $self = shift();
2257   my $dbh = shift();
2258
2259   if(!exists $self->{employee_id}) {
2260     &get_employee($self, $dbh);
2261   }
2262
2263   my $query =
2264     qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done) | .
2265     qq|VALUES (?, ?, ?, ?)|;
2266   my @values = (conv_i($self->{id}), conv_i($self->{employee_id}),
2267                 $self->{addition}, $self->{what_done});
2268   do_query($self, $dbh, $query, @values);
2269
2270   $main::lxdebug->leave_sub();
2271 }
2272
2273 sub get_history {
2274   $main::lxdebug->enter_sub();
2275
2276   my $self = shift();
2277   my $dbh = shift();
2278   my $trans_id = shift();
2279   my $restriction = shift();
2280   my @tempArray;
2281   my $i = 0;
2282   if ($trans_id ne "") {
2283     my $query =
2284       qq|SELECT h.employee_id, h.itime::timestamp(0) AS itime, h.addition, h.what_done, emp.name | .
2285       qq|FROM history_erp h | .
2286       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
2287       qq|WHERE trans_id = ? |
2288       . $restriction;
2289
2290     my $sth = $dbh->prepare($query) || $self->dberror($query);
2291
2292     $sth->execute($trans_id) || $self->dberror("$query ($trans_id)");
2293
2294     while(my $hash_ref = $sth->fetchrow_hashref()) {
2295       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
2296       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
2297       $tempArray[$i++] = $hash_ref;
2298     }
2299     $main::lxdebug->leave_sub() and return \@tempArray
2300       if ($i > 0 && $tempArray[0] ne "");
2301   }
2302   $main::lxdebug->leave_sub();
2303   return 0;
2304 }
2305
2306 sub update_defaults {
2307   $main::lxdebug->enter_sub();
2308
2309   my ($self, $myconfig, $fld, $provided_dbh) = @_;
2310
2311   my $dbh;
2312   if ($provided_dbh) {
2313     $dbh = $provided_dbh;
2314   } else {
2315     $dbh = $self->dbconnect_noauto($myconfig);
2316   }
2317   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
2318   my $sth   = $dbh->prepare($query);
2319
2320   $sth->execute || $self->dberror($query);
2321   my ($var) = $sth->fetchrow_array;
2322   $sth->finish;
2323
2324   if ($var =~ /^(.*?)(\d+)$/) {
2325     $var = "$1" . ($2 + 1);
2326   } else {
2327     $var++;
2328   }
2329
2330   $query = qq|UPDATE defaults SET $fld = ?|;
2331   do_query($self, $dbh, $query, $var);
2332
2333   if (!$provided_dbh) {
2334     $dbh->commit;
2335     $dbh->disconnect;
2336   }
2337
2338   $main::lxdebug->leave_sub();
2339
2340   return $var;
2341 }
2342
2343 sub update_business {
2344   $main::lxdebug->enter_sub();
2345
2346   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
2347
2348   my $dbh;
2349   if ($provided_dbh) {
2350     $dbh = $provided_dbh;
2351   } else {
2352     $dbh = $self->dbconnect_noauto($myconfig);
2353   }
2354   my $query =
2355     qq|SELECT customernumberinit FROM business
2356        WHERE id = ? FOR UPDATE|;
2357   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
2358
2359   if ($var ne "") {
2360     if ($var =~ /^(.*?)(\d+)$/) {
2361       $var = "$1" . ($2 + 1);
2362     } else {
2363       $var++;
2364     }
2365   }
2366   $query = qq|UPDATE business
2367               SET customernumberinit = ?
2368               WHERE id = ?|;
2369   do_query($self, $dbh, $query, $var, $business_id);
2370
2371   if (!$provided_dbh) {
2372     $dbh->commit;
2373     $dbh->disconnect;
2374   }
2375
2376   $main::lxdebug->leave_sub();
2377
2378   return $var;
2379 }
2380
2381 sub get_partsgroup {
2382   $main::lxdebug->enter_sub();
2383
2384   my ($self, $myconfig, $p) = @_;
2385
2386   my $dbh = $self->dbconnect($myconfig);
2387
2388   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
2389                  FROM partsgroup pg
2390                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
2391   my @values;
2392
2393   if ($p->{searchitems} eq 'part') {
2394     $query .= qq|WHERE p.inventory_accno_id > 0|;
2395   }
2396   if ($p->{searchitems} eq 'service') {
2397     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
2398   }
2399   if ($p->{searchitems} eq 'assembly') {
2400     $query .= qq|WHERE p.assembly = '1'|;
2401   }
2402   if ($p->{searchitems} eq 'labor') {
2403     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
2404   }
2405
2406   $query .= qq|ORDER BY partsgroup|;
2407
2408   if ($p->{all}) {
2409     $query = qq|SELECT id, partsgroup FROM partsgroup
2410                 ORDER BY partsgroup|;
2411   }
2412
2413   if ($p->{language_code}) {
2414     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
2415                   t.description AS translation
2416                 FROM partsgroup pg
2417                 JOIN parts p ON (p.partsgroup_id = pg.id)
2418                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
2419                 ORDER BY translation|;
2420     @values = ($p->{language_code});
2421   }
2422
2423   $self->{all_partsgroup} = selectall_hashref_query($self, $dbh, $query, @values);
2424
2425   $dbh->disconnect;
2426   $main::lxdebug->leave_sub();
2427 }
2428
2429 sub get_pricegroup {
2430   $main::lxdebug->enter_sub();
2431
2432   my ($self, $myconfig, $p) = @_;
2433
2434   my $dbh = $self->dbconnect($myconfig);
2435
2436   my $query = qq|SELECT p.id, p.pricegroup
2437                  FROM pricegroup p|;
2438
2439   $query .= qq| ORDER BY pricegroup|;
2440
2441   if ($p->{all}) {
2442     $query = qq|SELECT id, pricegroup FROM pricegroup
2443                 ORDER BY pricegroup|;
2444   }
2445
2446   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
2447
2448   $dbh->disconnect;
2449
2450   $main::lxdebug->leave_sub();
2451 }
2452
2453 sub all_years {
2454 # usage $form->all_years($myconfig, [$dbh])
2455 # return list of all years where bookings found
2456 # (@all_years)
2457
2458   $main::lxdebug->enter_sub();
2459
2460   my ($self, $myconfig, $dbh) = @_;
2461
2462   my $disconnect = 0;
2463   if (! $dbh) {
2464     $dbh = $self->dbconnect($myconfig);
2465     $disconnect = 1;
2466   }
2467
2468   # get years
2469   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
2470                    (SELECT MAX(transdate) FROM acc_trans)|;
2471   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
2472
2473   if ($myconfig->{dateformat} =~ /^yy/) {
2474     ($startdate) = split /\W/, $startdate;
2475     ($enddate) = split /\W/, $enddate;
2476   } else {
2477     (@_) = split /\W/, $startdate;
2478     $startdate = $_[2];
2479     (@_) = split /\W/, $enddate;
2480     $enddate = $_[2];
2481   }
2482
2483   my @all_years;
2484   $startdate = substr($startdate,0,4);
2485   $enddate = substr($enddate,0,4);
2486
2487   while ($enddate >= $startdate) {
2488     push @all_years, $enddate--;
2489   }
2490
2491   $dbh->disconnect if $disconnect;
2492
2493   return @all_years;
2494
2495   $main::lxdebug->leave_sub();
2496 }
2497
2498
2499 1;