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