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