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