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