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