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