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