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