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