Anpassung der Routinen von Kreditoren und Debitorenbuchungen auf das neue Steuersystem
[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   my %xkeyref = ();
1638
1639   if (!$self->{id}) {
1640
1641     my $transdate = "current_date";
1642     if ($self->{transdate}) {
1643       $transdate = qq|'$self->{transdate}'|;
1644     }
1645   
1646     # now get the account numbers
1647     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
1648                 FROM chart c, taxkeys tk
1649                 WHERE c.link LIKE '%$module%' AND c.id=tk.chart_id AND tk.id = (SELECT id from taxkeys where taxkeys.chart_id =c.id AND startdate<=$transdate ORDER BY startdate desc LIMIT 1)
1650                 ORDER BY c.accno|;
1651   
1652     $sth = $dbh->prepare($query);
1653     $sth->execute || $self->dberror($query);
1654   
1655     $self->{accounts} = "";
1656     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1657   
1658       foreach my $key (split /:/, $ref->{link}) {
1659         if ($key =~ /$module/) {
1660   
1661           # cross reference for keys
1662           $xkeyref{ $ref->{accno} } = $key;
1663   
1664           push @{ $self->{"${module}_links"}{$key} },
1665             { accno       => $ref->{accno},
1666               description => $ref->{description},
1667               taxkey      => $ref->{taxkey_id},
1668               tax_id      => $ref->{tax_id} };
1669   
1670           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
1671         }
1672       }
1673     }
1674   }
1675
1676   # get taxkeys and description
1677   $query = qq|SELECT id, taxkey, taxdescription
1678               FROM tax|;
1679   $sth = $dbh->prepare($query);
1680   $sth->execute || $self->dberror($query);
1681
1682   $ref = $sth->fetchrow_hashref(NAME_lc);
1683
1684   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1685     push @{ $self->{TAXKEY} }, $ref;
1686   }
1687
1688   $sth->finish;
1689
1690
1691   # get tax zones
1692   $query = qq|SELECT id, description
1693               FROM tax_zones|;
1694   $sth = $dbh->prepare($query);
1695   $sth->execute || $form->dberror($query);
1696
1697
1698   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1699     push @{ $self->{TAXZONE} }, $ref;
1700   }
1701   $sth->finish;
1702
1703   if (($module eq "AP") || ($module eq "AR")) {
1704
1705     # get tax rates and description
1706     $query = qq| SELECT * FROM tax t|;
1707     $sth   = $dbh->prepare($query);
1708     $sth->execute || $self->dberror($query);
1709     $self->{TAX} = ();
1710     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1711       push @{ $self->{TAX} }, $ref;
1712     }
1713     $sth->finish;
1714   }
1715
1716   if ($self->{id}) {
1717     my $arap = ($table eq 'customer') ? 'ar' : 'ap';
1718
1719     $query = qq|SELECT a.cp_id, a.invnumber, a.transdate,
1720                 a.${table}_id, a.datepaid, a.duedate, a.ordnumber,
1721                 a.taxincluded, a.curr AS currency, a.notes, a.intnotes,
1722                 c.name AS $table, a.department_id, d.description AS department,
1723                 a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
1724                 a.employee_id, e.name AS employee, a.gldate, a.type
1725                 FROM $arap a
1726                 JOIN $table c ON (a.${table}_id = c.id)
1727                 LEFT JOIN employee e ON (e.id = a.employee_id)
1728                 LEFT JOIN department d ON (d.id = a.department_id)
1729                 WHERE a.id = $self->{id}|;
1730     $sth = $dbh->prepare($query);
1731     $sth->execute || $self->dberror($query);
1732
1733     $ref = $sth->fetchrow_hashref(NAME_lc);
1734     foreach $key (keys %$ref) {
1735       $self->{$key} = $ref->{$key};
1736     }
1737     $sth->finish;
1738
1739
1740     my $transdate = "current_date";
1741     if ($self->{transdate}) {
1742       $transdate = qq|'$self->{transdate}'|;
1743     }
1744   
1745     # now get the account numbers
1746     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
1747                 FROM chart c, taxkeys tk
1748                 WHERE c.link LIKE '%$module%' AND (((tk.chart_id=c.id) AND NOT(c.link like '%_tax%')) OR (NOT(tk.chart_id=c.id) AND (c.link like '%_tax%'))) AND (((tk.id = (SELECT id from taxkeys where taxkeys.chart_id =c.id AND startdate<=$transdate ORDER BY startdate desc LIMIT 1)) AND NOT(c.link like '%_tax%')) OR (c.link like '%_tax%'))
1749                 ORDER BY c.accno|;
1750   
1751     $sth = $dbh->prepare($query);
1752     $sth->execute || $self->dberror($query);
1753   
1754     $self->{accounts} = "";
1755     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1756   
1757       foreach my $key (split /:/, $ref->{link}) {
1758         if ($key =~ /$module/) {
1759   
1760           # cross reference for keys
1761           $xkeyref{ $ref->{accno} } = $key;
1762   
1763           push @{ $self->{"${module}_links"}{$key} },
1764             { accno       => $ref->{accno},
1765               description => $ref->{description},
1766               taxkey      => $ref->{taxkey_id},
1767               tax_id      => $ref->{tax_id} };
1768   
1769           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
1770         }
1771       }
1772     }
1773
1774
1775     # get amounts from individual entries
1776     $query = qq|SELECT c.accno, c.description, a.source, a.amount, a.memo,
1777                 a.transdate, a.cleared, a.project_id, p.projectnumber, a.taxkey, t.rate, t.id
1778                 FROM acc_trans a
1779                 JOIN chart c ON (c.id = a.chart_id)
1780                 LEFT JOIN project p ON (p.id = a.project_id)
1781                 LEFT JOIN tax t ON (t.id=(SELECT tk.tax_id from taxkeys tk WHERE (tk.taxkey_id=a.taxkey) AND ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id=a.taxkey) THEN tk.chart_id=a.chart_id ELSE 1=1 END) OR (c.link='%tax%')) AND startdate <=a.transdate ORDER BY startdate DESC LIMIT 1)) 
1782                 WHERE a.trans_id = $self->{id}
1783                 AND a.fx_transaction = '0'
1784                 ORDER BY a.oid,a.transdate|;
1785     $sth = $dbh->prepare($query);
1786     $sth->execute || $self->dberror($query);
1787
1788     my $fld = ($table eq 'customer') ? 'buy' : 'sell';
1789
1790     # get exchangerate for currency
1791     $self->{exchangerate} =
1792       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate},
1793                               $fld);
1794     my $index = 0;
1795
1796     # store amounts in {acc_trans}{$key} for multiple accounts
1797     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1798       $ref->{exchangerate} =
1799         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate},
1800                                 $fld);
1801       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
1802         $index++;
1803       }
1804       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
1805         $ref->{amount} *= -1;
1806       }
1807       $ref->{index} = $index;
1808
1809       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
1810     }
1811
1812     $sth->finish;
1813     $query = qq|SELECT d.curr AS currencies, d.closedto, d.revtrans,
1814                   (SELECT c.accno FROM chart c
1815                    WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
1816                   (SELECT c.accno FROM chart c
1817                    WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
1818                 FROM defaults d|;
1819     $sth = $dbh->prepare($query);
1820     $sth->execute || $self->dberror($query);
1821
1822     $ref = $sth->fetchrow_hashref(NAME_lc);
1823     map { $self->{$_} = $ref->{$_} } keys %$ref;
1824     $sth->finish;
1825
1826   } else {
1827
1828     # get date
1829     $query = qq|SELECT current_date AS transdate,
1830                 d.curr AS currencies, d.closedto, d.revtrans,
1831                   (SELECT c.accno FROM chart c
1832                    WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
1833                   (SELECT c.accno FROM chart c
1834                    WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
1835                 FROM defaults d|;
1836     $sth = $dbh->prepare($query);
1837     $sth->execute || $self->dberror($query);
1838
1839     $ref = $sth->fetchrow_hashref(NAME_lc);
1840     map { $self->{$_} = $ref->{$_} } keys %$ref;
1841     $sth->finish;
1842
1843     if ($self->{"$self->{vc}_id"}) {
1844
1845       # only setup currency
1846       ($self->{currency}) = split /:/, $self->{currencies};
1847
1848     } else {
1849
1850       $self->lastname_used($dbh, $myconfig, $table, $module);
1851
1852       my $fld = ($table eq 'customer') ? 'buy' : 'sell';
1853
1854       # get exchangerate for currency
1855       $self->{exchangerate} =
1856         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate},
1857                                 $fld);
1858
1859     }
1860
1861   }
1862
1863   $sth->finish;
1864
1865   $dbh->disconnect;
1866
1867   $main::lxdebug->leave_sub();
1868 }
1869
1870 sub lastname_used {
1871   $main::lxdebug->enter_sub();
1872
1873   my ($self, $dbh, $myconfig, $table, $module) = @_;
1874
1875   my $arap  = ($table eq 'customer') ? "ar" : "ap";
1876   my $where = "1 = 1";
1877
1878   if ($self->{type} =~ /_order/) {
1879     $arap  = 'oe';
1880     $where = "quotation = '0'";
1881   }
1882   if ($self->{type} =~ /_quotation/) {
1883     $arap  = 'oe';
1884     $where = "quotation = '1'";
1885   }
1886
1887   my $query = qq|SELECT MAX(id) FROM $arap
1888                               WHERE $where
1889                               AND ${table}_id > 0|;
1890   my $sth = $dbh->prepare($query);
1891   $sth->execute || $self->dberror($query);
1892
1893   my ($trans_id) = $sth->fetchrow_array;
1894   $sth->finish;
1895
1896   $trans_id *= 1;
1897   $query = qq|SELECT ct.name, a.curr, a.${table}_id,
1898               current_date + ct.terms AS duedate, a.department_id,
1899               d.description AS department
1900               FROM $arap a
1901               JOIN $table ct ON (a.${table}_id = ct.id)
1902               LEFT JOIN department d ON (a.department_id = d.id)
1903               WHERE a.id = $trans_id|;
1904   $sth = $dbh->prepare($query);
1905   $sth->execute || $self->dberror($query);
1906
1907   ($self->{$table},  $self->{currency},      $self->{"${table}_id"},
1908    $self->{duedate}, $self->{department_id}, $self->{department})
1909     = $sth->fetchrow_array;
1910   $sth->finish;
1911
1912   $main::lxdebug->leave_sub();
1913 }
1914
1915 sub current_date {
1916   $main::lxdebug->enter_sub();
1917
1918   my ($self, $myconfig, $thisdate, $days) = @_;
1919
1920   my $dbh = $self->dbconnect($myconfig);
1921   my ($sth, $query);
1922
1923   $days *= 1;
1924   if ($thisdate) {
1925     my $dateformat = $myconfig->{dateformat};
1926     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1927
1928     $query = qq|SELECT to_date('$thisdate', '$dateformat') + $days AS thisdate
1929                 FROM defaults|;
1930     $sth = $dbh->prepare($query);
1931     $sth->execute || $self->dberror($query);
1932   } else {
1933     $query = qq|SELECT current_date AS thisdate
1934                 FROM defaults|;
1935     $sth = $dbh->prepare($query);
1936     $sth->execute || $self->dberror($query);
1937   }
1938
1939   ($thisdate) = $sth->fetchrow_array;
1940   $sth->finish;
1941
1942   $dbh->disconnect;
1943
1944   $main::lxdebug->leave_sub();
1945
1946   return $thisdate;
1947 }
1948
1949 sub like {
1950   $main::lxdebug->enter_sub();
1951
1952   my ($self, $string) = @_;
1953
1954   if ($string !~ /%/) {
1955     $string = "%$string%";
1956   }
1957
1958   $string =~ s/\'/\'\'/g;
1959
1960   $main::lxdebug->leave_sub();
1961
1962   return $string;
1963 }
1964
1965 sub redo_rows {
1966   $main::lxdebug->enter_sub();
1967
1968   my ($self, $flds, $new, $count, $numrows) = @_;
1969
1970   my @ndx = ();
1971
1972   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } }
1973     (1 .. $count);
1974
1975   my $i = 0;
1976
1977   # fill rows
1978   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
1979     $i++;
1980     $j = $item->{ndx} - 1;
1981     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
1982   }
1983
1984   # delete empty rows
1985   for $i ($count + 1 .. $numrows) {
1986     map { delete $self->{"${_}_$i"} } @{$flds};
1987   }
1988
1989   $main::lxdebug->leave_sub();
1990 }
1991
1992 sub update_status {
1993   $main::lxdebug->enter_sub();
1994
1995   my ($self, $myconfig) = @_;
1996
1997   my ($i, $id);
1998
1999   my $dbh = $self->dbconnect_noauto($myconfig);
2000
2001   my $query = qq|DELETE FROM status
2002                  WHERE formname = '$self->{formname}'
2003                  AND trans_id = ?|;
2004   my $sth = $dbh->prepare($query) || $self->dberror($query);
2005
2006   if ($self->{formname} =~ /(check|receipt)/) {
2007     for $i (1 .. $self->{rowcount}) {
2008       $sth->execute($self->{"id_$i"} * 1) || $self->dberror($query);
2009       $sth->finish;
2010     }
2011   } else {
2012     $sth->execute($self->{id}) || $self->dberror($query);
2013     $sth->finish;
2014   }
2015
2016   my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
2017   my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
2018
2019   my %queued = split / /, $self->{queued};
2020
2021   if ($self->{formname} =~ /(check|receipt)/) {
2022
2023     # this is a check or receipt, add one entry for each lineitem
2024     my ($accno) = split /--/, $self->{account};
2025     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname,
2026                 chart_id) VALUES (?, '$printed',
2027                 '$queued{$self->{formname}}', '$self->{prinform}',
2028                 (SELECT c.id FROM chart c WHERE c.accno = '$accno'))|;
2029     $sth = $dbh->prepare($query) || $self->dberror($query);
2030
2031     for $i (1 .. $self->{rowcount}) {
2032       if ($self->{"checked_$i"}) {
2033         $sth->execute($self->{"id_$i"}) || $self->dberror($query);
2034         $sth->finish;
2035       }
2036     }
2037   } else {
2038     $query = qq|INSERT INTO status (trans_id, printed, emailed,
2039                 spoolfile, formname)
2040                 VALUES ($self->{id}, '$printed', '$emailed',
2041                 '$queued{$self->{formname}}', '$self->{formname}')|;
2042     $dbh->do($query) || $self->dberror($query);
2043   }
2044
2045   $dbh->commit;
2046   $dbh->disconnect;
2047
2048   $main::lxdebug->leave_sub();
2049 }
2050
2051 sub save_status {
2052   $main::lxdebug->enter_sub();
2053
2054   my ($self, $dbh) = @_;
2055
2056   my ($query, $printed, $emailed);
2057
2058   my $formnames  = $self->{printed};
2059   my $emailforms = $self->{emailed};
2060
2061   my $query = qq|DELETE FROM status
2062                  WHERE formname = '$self->{formname}'
2063                  AND trans_id = $self->{id}|;
2064   $dbh->do($query) || $self->dberror($query);
2065
2066   # this only applies to the forms
2067   # checks and receipts are posted when printed or queued
2068
2069   if ($self->{queued}) {
2070     my %queued = split / /, $self->{queued};
2071
2072     foreach my $formname (keys %queued) {
2073       $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
2074       $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
2075
2076       $query = qq|INSERT INTO status (trans_id, printed, emailed,
2077                   spoolfile, formname)
2078                   VALUES ($self->{id}, '$printed', '$emailed',
2079                   '$queued{$formname}', '$formname')|;
2080       $dbh->do($query) || $self->dberror($query);
2081
2082       $formnames  =~ s/$self->{formname}//;
2083       $emailforms =~ s/$self->{formname}//;
2084
2085     }
2086   }
2087
2088   # save printed, emailed info
2089   $formnames  =~ s/^ +//g;
2090   $emailforms =~ s/^ +//g;
2091
2092   my %status = ();
2093   map { $status{$_}{printed} = 1 } split / +/, $formnames;
2094   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
2095
2096   foreach my $formname (keys %status) {
2097     $printed = ($formnames  =~ /$self->{formname}/) ? "1" : "0";
2098     $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
2099
2100     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
2101                 VALUES ($self->{id}, '$printed', '$emailed', '$formname')|;
2102     $dbh->do($query) || $self->dberror($query);
2103   }
2104
2105   $main::lxdebug->leave_sub();
2106 }
2107
2108 sub update_defaults {
2109   $main::lxdebug->enter_sub();
2110
2111   my ($self, $myconfig, $fld) = @_;
2112
2113   my $dbh   = $self->dbconnect_noauto($myconfig);
2114   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
2115   my $sth   = $dbh->prepare($query);
2116
2117   $sth->execute || $self->dberror($query);
2118   my ($var) = $sth->fetchrow_array;
2119   $sth->finish;
2120
2121   $var++;
2122
2123   $query = qq|UPDATE defaults
2124               SET $fld = '$var'|;
2125   $dbh->do($query) || $self->dberror($query);
2126
2127   $dbh->commit;
2128   $dbh->disconnect;
2129
2130   $main::lxdebug->leave_sub();
2131
2132   return $var;
2133 }
2134
2135 sub update_business {
2136   $main::lxdebug->enter_sub();
2137
2138   my ($self, $myconfig, $business_id) = @_;
2139
2140   my $dbh   = $self->dbconnect_noauto($myconfig);
2141   my $query =
2142     qq|SELECT customernumberinit FROM business  WHERE id=$business_id FOR UPDATE|;
2143   my $sth = $dbh->prepare($query);
2144
2145   $sth->execute || $self->dberror($query);
2146   my ($var) = $sth->fetchrow_array;
2147   $sth->finish;
2148   if ($var ne "") {
2149     $var++;
2150   }
2151   $query = qq|UPDATE business
2152               SET customernumberinit = '$var' WHERE id=$business_id|;
2153   $dbh->do($query) || $self->dberror($query);
2154
2155   $dbh->commit;
2156   $dbh->disconnect;
2157
2158   $main::lxdebug->leave_sub();
2159
2160   return $var;
2161 }
2162
2163 sub get_salesman {
2164   $main::lxdebug->enter_sub();
2165
2166   my ($self, $myconfig, $salesman) = @_;
2167
2168   my $dbh   = $self->dbconnect($myconfig);
2169   my $query =
2170     qq|SELECT id, name FROM customer  WHERE (customernumber ilike '%$salesman%' OR name ilike '%$salesman%') AND business_id in (SELECT id from business WHERE salesman)|;
2171   my $sth = $dbh->prepare($query);
2172   $sth->execute || $self->dberror($query);
2173
2174   my $i = 0;
2175   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2176     push(@{ $self->{salesman_list} }, $ref);
2177     $i++;
2178   }
2179   $dbh->commit;
2180   $main::lxdebug->leave_sub();
2181
2182   return $i;
2183 }
2184
2185 sub get_partsgroup {
2186   $main::lxdebug->enter_sub();
2187
2188   my ($self, $myconfig, $p) = @_;
2189
2190   my $dbh = $self->dbconnect($myconfig);
2191
2192   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
2193                  FROM partsgroup pg
2194                  JOIN parts p ON (p.partsgroup_id = pg.id)|;
2195
2196   if ($p->{searchitems} eq 'part') {
2197     $query .= qq|
2198                  WHERE p.inventory_accno_id > 0|;
2199   }
2200   if ($p->{searchitems} eq 'service') {
2201     $query .= qq|
2202                  WHERE p.inventory_accno_id IS NULL|;
2203   }
2204   if ($p->{searchitems} eq 'assembly') {
2205     $query .= qq|
2206                  WHERE p.assembly = '1'|;
2207   }
2208   if ($p->{searchitems} eq 'labor') {
2209     $query .= qq|
2210                  WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
2211   }
2212
2213   $query .= qq|
2214                  ORDER BY partsgroup|;
2215
2216   if ($p->{all}) {
2217     $query = qq|SELECT id, partsgroup FROM partsgroup
2218                 ORDER BY partsgroup|;
2219   }
2220
2221   if ($p->{language_code}) {
2222     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
2223                 t.description AS translation
2224                 FROM partsgroup pg
2225                 JOIN parts p ON (p.partsgroup_id = pg.id)
2226                 LEFT JOIN translation t ON (t.trans_id = pg.id AND t.language_code = '$p->{language_code}')
2227                 ORDER BY translation|;
2228   }
2229
2230   my $sth = $dbh->prepare($query);
2231   $sth->execute || $self->dberror($query);
2232
2233   $self->{all_partsgroup} = ();
2234   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2235     push @{ $self->{all_partsgroup} }, $ref;
2236   }
2237   $sth->finish;
2238   $dbh->disconnect;
2239   $main::lxdebug->leave_sub();
2240 }
2241
2242 sub get_pricegroup {
2243   $main::lxdebug->enter_sub();
2244
2245   my ($self, $myconfig, $p) = @_;
2246
2247   my $dbh = $self->dbconnect($myconfig);
2248
2249   my $query = qq|SELECT p.id, p.pricegroup
2250                  FROM pricegroup p|;
2251
2252   $query .= qq|
2253                  ORDER BY pricegroup|;
2254
2255   if ($p->{all}) {
2256     $query = qq|SELECT id, pricegroup FROM pricegroup
2257                 ORDER BY pricegroup|;
2258   }
2259
2260   my $sth = $dbh->prepare($query);
2261   $sth->execute || $self->dberror($query);
2262
2263   $self->{all_pricegroup} = ();
2264   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2265     push @{ $self->{all_pricegroup} }, $ref;
2266   }
2267   $sth->finish;
2268   $dbh->disconnect;
2269
2270   $main::lxdebug->leave_sub();
2271 }
2272
2273 sub audittrail {
2274   my ($self, $dbh, $myconfig, $audittrail) = @_;
2275
2276   # table, $reference, $formname, $action, $id, $transdate) = @_;
2277
2278   my $query;
2279   my $rv;
2280   my $disconnect;
2281
2282   if (!$dbh) {
2283     $dbh        = $self->dbconnect($myconfig);
2284     $disconnect = 1;
2285   }
2286
2287   # if we have an id add audittrail, otherwise get a new timestamp
2288
2289   if ($audittrail->{id}) {
2290
2291     $query = qq|SELECT audittrail FROM defaults|;
2292
2293     if ($dbh->selectrow_array($query)) {
2294       my ($null, $employee_id) = $self->get_employee($dbh);
2295
2296       if ($self->{audittrail} && !$myconfig) {
2297         chop $self->{audittrail};
2298
2299         my @a = split /\|/, $self->{audittrail};
2300         my %newtrail = ();
2301         my $key;
2302         my $i;
2303         my @flds = qw(tablename reference formname action transdate);
2304
2305         # put into hash and remove dups
2306         while (@a) {
2307           $key = "$a[2]$a[3]";
2308           $i   = 0;
2309           $newtrail{$key} = { map { $_ => $a[$i++] } @flds };
2310           splice @a, 0, 5;
2311         }
2312
2313         $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
2314                     formname, action, employee_id, transdate)
2315                     VALUES ($audittrail->{id}, ?, ?,
2316                     ?, ?, $employee_id, ?)|;
2317         my $sth = $dbh->prepare($query) || $self->dberror($query);
2318
2319         foreach $key (
2320           sort {
2321             $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate}
2322           } keys %newtrail
2323           ) {
2324           $i = 1;
2325           for (@flds) { $sth->bind_param($i++, $newtrail{$key}{$_}) }
2326
2327           $sth->execute || $self->dberror;
2328           $sth->finish;
2329         }
2330       }
2331
2332       if ($audittrail->{transdate}) {
2333         $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
2334                     formname, action, employee_id, transdate) VALUES (
2335                     $audittrail->{id}, '$audittrail->{tablename}', |
2336           . $dbh->quote($audittrail->{reference}) . qq|,
2337                     '$audittrail->{formname}', '$audittrail->{action}',
2338                     $employee_id, '$audittrail->{transdate}')|;
2339       } else {
2340         $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
2341                     formname, action, employee_id) VALUES ($audittrail->{id},
2342                     '$audittrail->{tablename}', |
2343           . $dbh->quote($audittrail->{reference}) . qq|,
2344                     '$audittrail->{formname}', '$audittrail->{action}',
2345                     $employee_id)|;
2346       }
2347       $dbh->do($query);
2348     }
2349   } else {
2350
2351     $query = qq|SELECT current_timestamp FROM defaults|;
2352     my ($timestamp) = $dbh->selectrow_array($query);
2353
2354     $rv =
2355       "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
2356   }
2357
2358   $dbh->disconnect if $disconnect;
2359
2360   $rv;
2361
2362 }
2363
2364 package Locale;
2365
2366 sub new {
2367   $main::lxdebug->enter_sub();
2368
2369   my ($type, $country, $NLS_file) = @_;
2370   my $self = {};
2371
2372   if ($country && -d "locale/$country") {
2373     local *IN;
2374     $self->{countrycode} = $country;
2375     if (open(IN, "locale/$country/$NLS_file")) {
2376       my $code = join("", <IN>);
2377       eval($code);
2378       close(IN);
2379     }
2380   }
2381
2382   $self->{NLS_file} = $NLS_file;
2383
2384   push @{ $self->{LONG_MONTH} },
2385     ("January",   "February", "March",    "April",
2386      "May ",      "June",     "July",     "August",
2387      "September", "October",  "November", "December");
2388   push @{ $self->{SHORT_MONTH} },
2389     (qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec));
2390
2391   $main::lxdebug->leave_sub();
2392
2393   bless $self, $type;
2394 }
2395
2396 sub text {
2397   my ($self, $text) = @_;
2398
2399   return (exists $self->{texts}{$text}) ? $self->{texts}{$text} : $text;
2400 }
2401
2402 sub findsub {
2403   $main::lxdebug->enter_sub();
2404
2405   my ($self, $text) = @_;
2406
2407   if (exists $self->{subs}{$text}) {
2408     $text = $self->{subs}{$text};
2409   } else {
2410     if ($self->{countrycode} && $self->{NLS_file}) {
2411       Form->error(
2412          "$text not defined in locale/$self->{countrycode}/$self->{NLS_file}");
2413     }
2414   }
2415
2416   $main::lxdebug->leave_sub();
2417
2418   return $text;
2419 }
2420
2421 sub date {
2422   $main::lxdebug->enter_sub();
2423
2424   my ($self, $myconfig, $date, $longformat) = @_;
2425
2426   my $longdate  = "";
2427   my $longmonth = ($longformat) ? 'LONG_MONTH' : 'SHORT_MONTH';
2428
2429   if ($date) {
2430
2431     # get separator
2432     $spc = $myconfig->{dateformat};
2433     $spc =~ s/\w//g;
2434     $spc = substr($spc, 1, 1);
2435
2436     if ($date =~ /\D/) {
2437       if ($myconfig->{dateformat} =~ /^yy/) {
2438         ($yy, $mm, $dd) = split /\D/, $date;
2439       }
2440       if ($myconfig->{dateformat} =~ /^mm/) {
2441         ($mm, $dd, $yy) = split /\D/, $date;
2442       }
2443       if ($myconfig->{dateformat} =~ /^dd/) {
2444         ($dd, $mm, $yy) = split /\D/, $date;
2445       }
2446     } else {
2447       $date = substr($date, 2);
2448       ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
2449     }
2450
2451     $dd *= 1;
2452     $mm--;
2453     $yy = ($yy < 70) ? $yy + 2000 : $yy;
2454     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
2455
2456     if ($myconfig->{dateformat} =~ /^dd/) {
2457       if (defined $longformat && $longformat == 0) {
2458         $mm++;
2459         $dd = "0$dd" if ($dd < 10);
2460         $mm = "0$mm" if ($mm < 10);
2461         $longdate = "$dd$spc$mm$spc$yy";
2462       } else {
2463         $longdate = "$dd";
2464         $longdate .= ($spc eq '.') ? ". " : " ";
2465         $longdate .= &text($self, $self->{$longmonth}[$mm]) . " $yy";
2466       }
2467     } elsif ($myconfig->{dateformat} eq "yyyy-mm-dd") {
2468
2469       # Use German syntax with the ISO date style "yyyy-mm-dd" because
2470       # Lx-Office is mainly used in Germany or German speaking countries.
2471       if (defined $longformat && $longformat == 0) {
2472         $mm++;
2473         $dd = "0$dd" if ($dd < 10);
2474         $mm = "0$mm" if ($mm < 10);
2475         $longdate = "$yy-$mm-$dd";
2476       } else {
2477         $longdate = "$dd. ";
2478         $longdate .= &text($self, $self->{$longmonth}[$mm]) . " $yy";
2479       }
2480     } else {
2481       if (defined $longformat && $longformat == 0) {
2482         $mm++;
2483         $dd = "0$dd" if ($dd < 10);
2484         $mm = "0$mm" if ($mm < 10);
2485         $longdate = "$mm$spc$dd$spc$yy";
2486       } else {
2487         $longdate = &text($self, $self->{$longmonth}[$mm]) . " $dd, $yy";
2488       }
2489     }
2490
2491   }
2492
2493   $main::lxdebug->leave_sub();
2494
2495   return $longdate;
2496 }
2497
2498 sub parse_date {
2499   $main::lxdebug->enter_sub();
2500
2501   my ($self, $myconfig, $date, $longformat) = @_;
2502
2503   unless ($date) {
2504     $main::lxdebug->leave_sub();
2505     return ();
2506   }
2507
2508   # get separator
2509   $spc = $myconfig->{dateformat};
2510   $spc =~ s/\w//g;
2511   $spc = substr($spc, 1, 1);
2512
2513   if ($date =~ /\D/) {
2514     if ($myconfig->{dateformat} =~ /^yy/) {
2515       ($yy, $mm, $dd) = split /\D/, $date;
2516     } elsif ($myconfig->{dateformat} =~ /^mm/) {
2517       ($mm, $dd, $yy) = split /\D/, $date;
2518     } elsif ($myconfig->{dateformat} =~ /^dd/) {
2519       ($dd, $mm, $yy) = split /\D/, $date;
2520     }
2521   } else {
2522     $date = substr($date, 2);
2523     ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
2524   }
2525
2526   $dd *= 1;
2527   $mm *= 1;
2528   $yy = ($yy < 70) ? $yy + 2000 : $yy;
2529   $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
2530
2531   $main::lxdebug->leave_sub();
2532   return ($yy, $mm, $dd);
2533 }
2534
2535 1;