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