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