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