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