3606073f995a55d5195100e720dcf26f18fcded6
[kivitendo-erp.git] / SL / Form.pm
1 #====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 1998-2002
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 # Contributors: Thomas Bayen <bayen@gmx.de>
16 #               Antti Kaihola <akaihola@siba.fi>
17 #               Moritz Bunkus (tex code)
18 #
19 # This program is free software; you can redistribute it and/or modify
20 # it under the terms of the GNU General Public License as published by
21 # the Free Software Foundation; either version 2 of the License, or
22 # (at your option) any later version.
23 #
24 # This program is distributed in the hope that it will be useful,
25 # but WITHOUT ANY WARRANTY; without even the implied warranty of
26 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27 # GNU General Public License for more details.
28 # You should have received a copy of the GNU General Public License
29 # along with this program; if not, write to the Free Software
30 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
31 #======================================================================
32 # Utilities for parsing forms
33 # and supporting routines for linking account numbers
34 # used in AR, AP and IS, IR modules
35 #
36 #======================================================================
37
38 package Form;
39 use Data::Dumper;
40
41 use Cwd;
42 use HTML::Template;
43 use SL::Template;
44 use CGI::Ajax;
45 use SL::Menu;
46 use CGI;
47
48 sub _input_to_hash {
49   $main::lxdebug->enter_sub(2);
50
51   my $input = $_[0];
52   my %in    = ();
53   my @pairs = split(/&/, $input);
54
55   foreach (@pairs) {
56     my ($name, $value) = split(/=/, $_, 2);
57     $in{$name} = unescape(undef, $value);
58   }
59
60   $main::lxdebug->leave_sub(2);
61
62   return %in;
63 }
64
65 sub _request_to_hash {
66   $main::lxdebug->enter_sub(2);
67
68   my ($input) = @_;
69   my ($i,        $loc,  $key,    $val);
70   my (%ATTACH,   $f,    $header, $header_body, $len, $buf);
71   my ($boundary, @list, $size,   $body, $x, $blah, $name);
72
73   if ($ENV{'CONTENT_TYPE'}
74       && ($ENV{'CONTENT_TYPE'} =~ /multipart\/form-data; boundary=(.+)$/)) {
75     $boundary = quotemeta('--' . $1);
76     @list     = split(/$boundary/, $input);
77
78     # For some reason there are always 2 extra, that are empty
79     $size = @list - 2;
80
81     for ($x = 1; $x <= $size; $x++) {
82       $header_body = $list[$x];
83       $header_body =~ /\r\n\r\n|\n\n/;
84
85       # Here we split the header and body
86       $header = $`;
87       $body   = $';    #'
88       $body =~ s/\r\n$//;
89
90       # Now we try to get the file name
91       $name = $header;
92       $name =~ /name=\"(.+)\"/;
93       ($name, $blah) = split(/\"/, $1);
94
95       # If the form name is not attach, then we need to parse this like
96       # regular form data
97       if ($name ne "attach") {
98         $body =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
99         $ATTACH{$name} = $body;
100
101         # Otherwise it is an attachment and we need to finish it up
102       } elsif ($name eq "attach") {
103         $header =~ /filename=\"(.+)\"/;
104         $ATTACH{'FILE_NAME'} = $1;
105         $ATTACH{'FILE_NAME'} =~ s/\"//g;
106         $ATTACH{'FILE_NAME'} =~ s/\s//g;
107         $ATTACH{'FILE_CONTENT'} = $body;
108
109         for ($i = $x; $list[$i]; $i++) {
110           $list[$i] =~ s/^.+name=$//;
111           $list[$i] =~ /\"(\w+)\"/;
112           $ATTACH{$1} = $';    #'
113         }
114       }
115     }
116
117     $main::lxdebug->leave_sub(2);
118     return %ATTACH;
119
120       } else {
121     $main::lxdebug->leave_sub(2);
122     return _input_to_hash($input);
123   }
124 }
125
126 sub new {
127   $main::lxdebug->enter_sub();
128
129   my $type = shift;
130
131   my $self = {};
132
133   read(STDIN, $_, $ENV{CONTENT_LENGTH});
134
135   if ($ENV{QUERY_STRING}) {
136     $_ = $ENV{QUERY_STRING};
137   }
138
139   if ($ARGV[0]) {
140     $_ = $ARGV[0];
141   }
142
143   my %parameters = _request_to_hash($_);
144   map({ $self->{$_} = $parameters{$_}; } keys(%parameters));
145
146   $self->{action} = lc $self->{action};
147   $self->{action} =~ s/( |-|,|\#)/_/g;
148
149   $self->{version}   = "2.4.0";
150
151   $main::lxdebug->leave_sub();
152
153   bless $self, $type;
154 }
155
156 sub debug {
157   $main::lxdebug->enter_sub();
158
159   my ($self) = @_;
160
161   print "\n";
162
163   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
164
165   $main::lxdebug->leave_sub();
166 }
167
168 sub escape {
169   $main::lxdebug->enter_sub(2);
170
171   my ($self, $str, $beenthere) = @_;
172
173   # for Apache 2 we escape strings twice
174   #if (($ENV{SERVER_SOFTWARE} =~ /Apache\/2/) && !$beenthere) {
175   #  $str = $self->escape($str, 1);
176   #}
177
178   $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
179
180   $main::lxdebug->leave_sub(2);
181
182   return $str;
183 }
184
185 sub unescape {
186   $main::lxdebug->enter_sub(2);
187
188   my ($self, $str) = @_;
189
190   $str =~ tr/+/ /;
191   $str =~ s/\\$//;
192
193   $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
194
195   $main::lxdebug->leave_sub(2);
196
197   return $str;
198 }
199
200 sub quote {
201   my ($self, $str) = @_;
202
203   if ($str && !ref($str)) {
204     $str =~ s/\"/&quot;/g;
205   }
206
207   $str;
208
209 }
210
211 sub unquote {
212   my ($self, $str) = @_;
213
214   if ($str && !ref($str)) {
215     $str =~ s/&quot;/\"/g;
216   }
217
218   $str;
219
220 }
221
222 sub 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   } elsif (($self->{"format"} =~ /xml/i) ||
758              (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
759     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
760   } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
761     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);  
762   } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
763     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
764   } elsif ( defined $self->{'format'}) {
765     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
766   } elsif ( $self->{'format'} eq '' ) {
767     $self->error("No Outputformat given: $self->{'format'}");
768   } else { #Catch the rest
769     $self->error("Outputformat not defined: $self->{'format'}");  
770   }
771
772   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
773   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
774
775   map({ $self->{"employee_${_}"} = $myconfig->{$_}; }
776       qw(email tel fax name signature company address businessnumber));
777
778   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
779
780   # OUT is used for the media, screen, printer, email
781   # for postscript we store a copy in a temporary file
782   my $fileid = time;
783   $self->{tmpfile} = "$userspath/${fileid}.$self->{IN}" if ( $self->{tmpfile} eq '' );
784   if ($template->uses_temp_file() || $self->{media} eq 'email') {
785     $out = $self->{OUT};
786     $self->{OUT} = ">$self->{tmpfile}";
787   }
788
789   if ($self->{OUT}) {
790     open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
791   } else {
792     open(OUT, ">-") or $self->error("STDOUT : $!");
793     $self->header;
794   }
795
796   if (!$template->parse(*OUT)) {
797     $self->cleanup();
798     $self->error("$self->{IN} : " . $template->get_error());
799   }
800
801   close(OUT);
802
803   if ($template->uses_temp_file() || $self->{media} eq 'email') {
804
805     if ($self->{media} eq 'email') {
806
807       use SL::Mailer;
808
809       my $mail = new Mailer;
810
811       map { $mail->{$_} = $self->{$_} }
812         qw(cc bcc subject message version format charset);
813       $mail->{to}     = qq|$self->{email}|;
814       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
815       $mail->{fileid} = "$fileid.";
816       $myconfig->{signature} =~ s/\\r\\n/\\n/g;
817
818       # if we send html or plain text inline
819       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
820         $mail->{contenttype} = "text/html";
821
822         $mail->{message}       =~ s/\r\n/<br>\n/g;
823         $myconfig->{signature} =~ s/\\n/<br>\n/g;
824         $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
825
826         open(IN, $self->{tmpfile})
827           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
828         while (<IN>) {
829           $mail->{message} .= $_;
830         }
831
832         close(IN);
833
834       } else {
835
836         @{ $mail->{attachments} } = ($self->{tmpfile}) unless ($form->{do_not_attach});
837
838         $mail->{message}       =~ s/\r\n/\n/g;
839         $myconfig->{signature} =~ s/\\n/\n/g;
840         $mail->{message} .= "\n-- \n$myconfig->{signature}";
841
842       }
843
844       my $err = $mail->send($out);
845       $self->error($self->cleanup . "$err") if ($err);
846
847     } else {
848
849       $self->{OUT} = $out;
850
851       my $numbytes = (-s $self->{tmpfile});
852       open(IN, $self->{tmpfile})
853         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
854
855       $self->{copies} = 1 unless $self->{media} eq 'printer';
856
857       chdir("$self->{cwd}");
858       #print(STDERR "Kopien $self->{copies}\n");
859       #print(STDERR "OUT $self->{OUT}\n");
860       for my $i (1 .. $self->{copies}) {
861         if ($self->{OUT}) {
862           open(OUT, $self->{OUT})
863             or $self->error($self->cleanup . "$self->{OUT} : $!");
864         } else {
865
866           # launch application
867           print qq|Content-Type: | . $template->get_mime_type() . qq|
868 Content-Disposition: attachment; filename="$self->{tmpfile}"
869 Content-Length: $numbytes
870
871 |;
872
873           open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
874
875         }
876
877         while (<IN>) {
878           print OUT $_;
879         }
880
881         close(OUT);
882
883         seek IN, 0, 0;
884       }
885
886       close(IN);
887     }
888
889   }
890
891   $self->cleanup;
892
893   chdir("$self->{cwd}");
894   $main::lxdebug->leave_sub();
895 }
896
897 sub cleanup {
898   $main::lxdebug->enter_sub();
899
900   my $self = shift;
901
902   chdir("$self->{tmpdir}");
903
904   my @err = ();
905   if (-f "$self->{tmpfile}.err") {
906     open(FH, "$self->{tmpfile}.err");
907     @err = <FH>;
908     close(FH);
909   }
910
911   if ($self->{tmpfile}) {
912     $self->{tmpfile} =~ s|.*/||g;
913     # strip extension
914     $self->{tmpfile} =~ s/\.\w+$//g;
915     my $tmpfile = $self->{tmpfile};
916     unlink(<$tmpfile.*>);
917   }
918
919   chdir("$self->{cwd}");
920
921   $main::lxdebug->leave_sub();
922
923   return "@err";
924 }
925
926 sub datetonum {
927   $main::lxdebug->enter_sub();
928
929   my ($self, $date, $myconfig) = @_;
930
931   if ($date && $date =~ /\D/) {
932
933     if ($myconfig->{dateformat} =~ /^yy/) {
934       ($yy, $mm, $dd) = split /\D/, $date;
935     }
936     if ($myconfig->{dateformat} =~ /^mm/) {
937       ($mm, $dd, $yy) = split /\D/, $date;
938     }
939     if ($myconfig->{dateformat} =~ /^dd/) {
940       ($dd, $mm, $yy) = split /\D/, $date;
941     }
942
943     $dd *= 1;
944     $mm *= 1;
945     $yy = ($yy < 70) ? $yy + 2000 : $yy;
946     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
947
948     $dd = "0$dd" if ($dd < 10);
949     $mm = "0$mm" if ($mm < 10);
950
951     $date = "$yy$mm$dd";
952   }
953
954   $main::lxdebug->leave_sub();
955
956   return $date;
957 }
958
959 # Database routines used throughout
960
961 sub dbconnect {
962   $main::lxdebug->enter_sub();
963
964   my ($self, $myconfig) = @_;
965
966   # connect to database
967   my $dbh =
968     DBI->connect($myconfig->{dbconnect},
969                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
970     or $self->dberror;
971
972   # set db options
973   if ($myconfig->{dboptions}) {
974     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
975   }
976
977   $main::lxdebug->leave_sub();
978
979   return $dbh;
980 }
981
982 sub dbconnect_noauto {
983   $main::lxdebug->enter_sub();
984
985   my ($self, $myconfig) = @_;
986
987   # connect to database
988   $dbh =
989     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
990                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
991     or $self->dberror;
992
993   # set db options
994   if ($myconfig->{dboptions}) {
995     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
996   }
997
998   $main::lxdebug->leave_sub();
999
1000   return $dbh;
1001 }
1002
1003 sub update_balance {
1004   $main::lxdebug->enter_sub();
1005
1006   my ($self, $dbh, $table, $field, $where, $value) = @_;
1007
1008   # if we have a value, go do it
1009   if ($value != 0) {
1010
1011     # retrieve balance from table
1012     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1013     my $sth   = $dbh->prepare($query);
1014
1015     $sth->execute || $self->dberror($query);
1016     my ($balance) = $sth->fetchrow_array;
1017     $sth->finish;
1018
1019     $balance += $value;
1020
1021     # update balance
1022     $query = "UPDATE $table SET $field = $balance WHERE $where";
1023     $dbh->do($query) || $self->dberror($query);
1024   }
1025   $main::lxdebug->leave_sub();
1026 }
1027
1028 sub update_exchangerate {
1029   $main::lxdebug->enter_sub();
1030
1031   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1032
1033   # some sanity check for currency
1034   if ($curr eq '') {
1035     $main::lxdebug->leave_sub();
1036     return;
1037   }
1038
1039   my $query = qq|SELECT e.curr FROM exchangerate e
1040                  WHERE e.curr = '$curr'
1041                  AND e.transdate = '$transdate'
1042                  FOR UPDATE|;
1043   my $sth = $dbh->prepare($query);
1044   $sth->execute || $self->dberror($query);
1045
1046   my $set;
1047   if ($buy != 0 && $sell != 0) {
1048     $set = "buy = $buy, sell = $sell";
1049   } elsif ($buy != 0) {
1050     $set = "buy = $buy";
1051   } elsif ($sell != 0) {
1052     $set = "sell = $sell";
1053   }
1054
1055   if ($sth->fetchrow_array) {
1056     $query = qq|UPDATE exchangerate
1057                 SET $set
1058                 WHERE curr = '$curr'
1059                 AND transdate = '$transdate'|;
1060   } else {
1061     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1062                 VALUES ('$curr', $buy, $sell, '$transdate')|;
1063   }
1064   $sth->finish;
1065   $dbh->do($query) || $self->dberror($query);
1066
1067   $main::lxdebug->leave_sub();
1068 }
1069
1070 sub save_exchangerate {
1071   $main::lxdebug->enter_sub();
1072
1073   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1074
1075   my $dbh = $self->dbconnect($myconfig);
1076
1077   my ($buy, $sell) = (0, 0);
1078   $buy  = $rate if $fld eq 'buy';
1079   $sell = $rate if $fld eq 'sell';
1080
1081   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1082
1083   $dbh->disconnect;
1084
1085   $main::lxdebug->leave_sub();
1086 }
1087
1088 sub get_exchangerate {
1089   $main::lxdebug->enter_sub();
1090
1091   my ($self, $dbh, $curr, $transdate, $fld) = @_;
1092
1093   unless ($transdate) {
1094     $main::lxdebug->leave_sub();
1095     return "";
1096   }
1097
1098   my $query = qq|SELECT e.$fld FROM exchangerate e
1099                  WHERE e.curr = '$curr'
1100                  AND e.transdate = '$transdate'|;
1101   my $sth = $dbh->prepare($query);
1102   $sth->execute || $self->dberror($query);
1103
1104   my ($exchangerate) = $sth->fetchrow_array;
1105   $sth->finish;
1106
1107   if ($exchangerate == 0) {
1108     $exchangerate = 1;
1109   }
1110
1111   $main::lxdebug->leave_sub();
1112
1113   return $exchangerate;
1114 }
1115
1116 sub set_payment_options {
1117   $main::lxdebug->enter_sub();
1118
1119   my ($self, $myconfig, $transdate) = @_;
1120
1121   if ($self->{payment_id}) {
1122
1123     my $dbh = $self->dbconnect($myconfig);
1124
1125
1126     my $query = qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long FROM payment_terms p
1127                   WHERE p.id = $self->{payment_id}|;
1128     my $sth = $dbh->prepare($query);
1129     $sth->execute || $self->dberror($query);
1130   
1131     ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto}, $self->{payment_terms}) = $sth->fetchrow_array;
1132
1133     $sth->finish;
1134     my $query = qq|SELECT date '$transdate' + $self->{terms_netto} AS netto_date,date '$transdate' + $self->{terms_skonto} AS skonto_date  FROM payment_terms
1135                   LIMIT 1|;
1136     my $sth = $dbh->prepare($query);
1137     $sth->execute || $self->dberror($query);    
1138     ($self->{netto_date}, $self->{skonto_date}) = $sth->fetchrow_array;
1139     $sth->finish;
1140
1141     $self->{skonto_amount} = $self->format_amount($myconfig, ($self->parse_amount($myconfig, $self->{subtotal}) * $self->{percent_skonto}), 2);
1142
1143     $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1144     $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1145     $self->{payment_terms} =~ s/<%skonto_amount%>/$self->{skonto_amount}/g;
1146
1147     $dbh->disconnect;
1148   }
1149
1150   $main::lxdebug->leave_sub();
1151
1152 }
1153
1154 sub check_exchangerate {
1155   $main::lxdebug->enter_sub();
1156
1157   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1158
1159   unless ($transdate) {
1160     $main::lxdebug->leave_sub();
1161     return "";
1162   }
1163
1164   my $dbh = $self->dbconnect($myconfig);
1165
1166   my $query = qq|SELECT e.$fld FROM exchangerate e
1167                  WHERE e.curr = '$currency'
1168                  AND e.transdate = '$transdate'|;
1169   my $sth = $dbh->prepare($query);
1170   $sth->execute || $self->dberror($query);
1171
1172   my ($exchangerate) = $sth->fetchrow_array;
1173   $sth->finish;
1174   $dbh->disconnect;
1175
1176   $main::lxdebug->leave_sub();
1177
1178   return $exchangerate;
1179 }
1180
1181 sub get_template_language {
1182   $main::lxdebug->enter_sub();
1183
1184   my ($self, $myconfig) = @_;
1185
1186   my $template_code = "";
1187
1188   if ($self->{language_id}) {
1189
1190     my $dbh = $self->dbconnect($myconfig);
1191
1192
1193     my $query = qq|SELECT l.template_code FROM language l
1194                   WHERE l.id = $self->{language_id}|;
1195     my $sth = $dbh->prepare($query);
1196     $sth->execute || $self->dberror($query);
1197   
1198     ($template_code) = $sth->fetchrow_array;
1199     $sth->finish;
1200     $dbh->disconnect;
1201   }
1202
1203   $main::lxdebug->leave_sub();
1204
1205   return $template_code;
1206 }
1207
1208 sub get_printer_code {
1209   $main::lxdebug->enter_sub();
1210
1211   my ($self, $myconfig) = @_;
1212
1213   my $template_code = "";
1214
1215   if ($self->{printer_id}) {
1216
1217     my $dbh = $self->dbconnect($myconfig);
1218
1219
1220     my $query = qq|SELECT p.template_code,p.printer_command FROM printers p
1221                   WHERE p.id = $self->{printer_id}|;
1222     my $sth = $dbh->prepare($query);
1223     $sth->execute || $self->dberror($query);
1224   
1225     ($template_code, $self->{printer_command}) = $sth->fetchrow_array;
1226     $sth->finish;
1227     $dbh->disconnect;
1228   }
1229
1230   $main::lxdebug->leave_sub();
1231
1232   return $template_code;
1233 }
1234
1235 sub get_shipto {
1236   $main::lxdebug->enter_sub();
1237
1238   my ($self, $myconfig) = @_;
1239
1240   my $template_code = "";
1241
1242   if ($self->{shipto_id}) {
1243
1244     my $dbh = $self->dbconnect($myconfig);
1245
1246
1247     my $query = qq|SELECT s.* FROM shipto s
1248                   WHERE s.shipto_id = $self->{shipto_id}|;
1249     my $sth = $dbh->prepare($query);
1250     $sth->execute || $self->dberror($query);
1251     $ref = $sth->fetchrow_hashref(NAME_lc);
1252     map { $form->{$_} = $ref->{$_} } keys %$ref;
1253     $sth->finish;  
1254     $dbh->disconnect;
1255   }
1256
1257   $main::lxdebug->leave_sub();
1258
1259 }
1260
1261 sub add_shipto {
1262   $main::lxdebug->enter_sub();
1263
1264   my ($self, $dbh, $id, $module) = @_;
1265 ##LINET
1266   my $shipto;
1267   foreach my $item (
1268     qw(name department_1 department_2 street zipcode city country contact phone fax email)
1269     ) {
1270     if ($self->{"shipto$item"}) {
1271       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1272     }
1273     $self->{"shipto$item"} =~ s/\'/\'\'/g;
1274   }
1275   if ($shipto) {
1276     if ($self->{shipto_id}) {
1277       my $query = qq| UPDATE shipto set
1278                       shiptoname = '$self->{shiptoname}',
1279                       shiptodepartment_1 = '$self->{shiptodepartment_1}',
1280                       shiptodepartment_2 = '$self->{shiptodepartment_2}',
1281                       shiptostreet = '$self->{shiptostreet}',
1282                       shiptozipcode = '$self->{shiptozipcode}',
1283                       shiptocity = '$self->{shiptocity}',
1284                       shiptocountry = '$self->{shiptocountry}',
1285                       shiptocontact = '$self->{shiptocontact}',
1286                       shiptophone = '$self->{shiptophone}',
1287                       shiptofax = '$self->{shiptofax}',
1288                       shiptoemail = '$self->{shiptoemail}'
1289                       WHERE shipto_id = $self->{shipto_id}|;
1290       $dbh->do($query) || $self->dberror($query);
1291     } else {
1292       my $query =
1293       qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2, shiptostreet,
1294                    shiptozipcode, shiptocity, shiptocountry, shiptocontact,
1295                    shiptophone, shiptofax, shiptoemail, module) VALUES ($id,
1296                    '$self->{shiptoname}', '$self->{shiptodepartment_1}', '$self->{shiptodepartment_2}', '$self->{shiptostreet}',
1297                    '$self->{shiptozipcode}', '$self->{shiptocity}',
1298                    '$self->{shiptocountry}', '$self->{shiptocontact}',
1299                    '$self->{shiptophone}', '$self->{shiptofax}',
1300                    '$self->{shiptoemail}', '$module')|;
1301       $dbh->do($query) || $self->dberror($query);
1302     }
1303   }
1304 ##/LINET
1305   $main::lxdebug->leave_sub();
1306 }
1307
1308 sub get_employee {
1309   $main::lxdebug->enter_sub();
1310
1311   my ($self, $dbh) = @_;
1312
1313   my $query = qq|SELECT e.id, e.name FROM employee e
1314                  WHERE e.login = '$self->{login}'|;
1315   my $sth = $dbh->prepare($query);
1316   $sth->execute || $self->dberror($query);
1317
1318   ($self->{employee_id}, $self->{employee}) = $sth->fetchrow_array;
1319   $self->{employee_id} *= 1;
1320
1321   $sth->finish;
1322
1323   $main::lxdebug->leave_sub();
1324 }
1325
1326 # get other contact for transaction and form - html/tex
1327 sub get_contact {
1328   $main::lxdebug->enter_sub();
1329
1330   my ($self, $dbh, $id) = @_;
1331
1332   my $query = qq|SELECT c.*
1333               FROM contacts c
1334               WHERE cp_id=$id|;
1335   $sth = $dbh->prepare($query);
1336   $sth->execute || $self->dberror($query);
1337
1338   $ref = $sth->fetchrow_hashref(NAME_lc);
1339
1340   push @{ $self->{$_} }, $ref;
1341
1342   $sth->finish;
1343   $main::lxdebug->leave_sub();
1344 }
1345
1346 # get contacts for id, if no contact return {"","","","",""}
1347 sub get_contacts {
1348   $main::lxdebug->enter_sub();
1349
1350   my ($self, $dbh, $id) = @_;
1351
1352   my $query = qq|SELECT c.cp_id, c.cp_cv_id, c.cp_name, c.cp_givenname, c.cp_abteilung
1353               FROM contacts c
1354               WHERE cp_cv_id=$id|;
1355   my $sth = $dbh->prepare($query);
1356   $sth->execute || $self->dberror($query);
1357
1358   my $i = 0;
1359   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1360     push @{ $self->{all_contacts} }, $ref;
1361     $i++;
1362   }
1363
1364   if ($i == 0) {
1365     push @{ $self->{all_contacts} }, { { "", "", "", "", "", "" } };
1366   }
1367   $sth->finish;
1368   $main::lxdebug->leave_sub();
1369 }
1370
1371 # this sub gets the id and name from $table
1372 sub get_name {
1373   $main::lxdebug->enter_sub();
1374
1375   my ($self, $myconfig, $table) = @_;
1376
1377   # connect to database
1378   my $dbh = $self->dbconnect($myconfig);
1379
1380   my $name           = $self->like(lc $self->{$table});
1381   my $customernumber = $self->like(lc $self->{customernumber});
1382
1383   if ($self->{customernumber} ne "") {
1384     $query = qq~SELECT c.id, c.name,
1385                   c.street || ' ' || c.zipcode || ' ' || c.city || ' ' || c.country AS address
1386                   FROM $table c
1387                   WHERE (lower(c.customernumber) LIKE '$customernumber') AND (not c.obsolete)
1388                   ORDER BY c.name~;
1389   } else {
1390     $query = qq~SELECT c.id, c.name,
1391                  c.street || ' ' || c.zipcode || ' ' || c.city || ' ' || c.country AS address
1392                  FROM $table c
1393                  WHERE (lower(c.name) LIKE '$name') AND (not c.obsolete)
1394                  ORDER BY c.name~;
1395   }
1396
1397   if ($self->{openinvoices}) {
1398     $query = qq~SELECT DISTINCT c.id, c.name,
1399                 c.street || ' ' || c.zipcode || ' ' || c.city || ' ' || c.country AS address
1400                 FROM $self->{arap} a
1401                 JOIN $table c ON (a.${table}_id = c.id)
1402                 WHERE NOT a.amount = a.paid
1403                 AND lower(c.name) LIKE '$name'
1404                 ORDER BY c.name~;
1405   }
1406   my $sth = $dbh->prepare($query);
1407
1408   $sth->execute || $self->dberror($query);
1409
1410   my $i = 0;
1411   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1412     push(@{ $self->{name_list} }, $ref);
1413     $i++;
1414   }
1415   $sth->finish;
1416   $dbh->disconnect;
1417
1418   $main::lxdebug->leave_sub();
1419
1420   return $i;
1421 }
1422
1423 # the selection sub is used in the AR, AP, IS, IR and OE module
1424 #
1425 sub all_vc {
1426   $main::lxdebug->enter_sub();
1427
1428   my ($self, $myconfig, $table, $module) = @_;
1429
1430   my $ref;
1431   my $dbh = $self->dbconnect($myconfig);
1432
1433   my $query = qq|SELECT count(*) FROM $table|;
1434   my $sth   = $dbh->prepare($query);
1435   $sth->execute || $self->dberror($query);
1436   my ($count) = $sth->fetchrow_array;
1437   $sth->finish;
1438
1439   # build selection list
1440   if ($count < $myconfig->{vclimit}) {
1441     $query = qq|SELECT id, name
1442                 FROM $table WHERE not obsolete
1443                 ORDER BY name|;
1444     $sth = $dbh->prepare($query);
1445     $sth->execute || $self->dberror($query);
1446
1447     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1448       push @{ $self->{"all_$table"} }, $ref;
1449     }
1450
1451     $sth->finish;
1452
1453   }
1454
1455   # get self
1456   $self->get_employee($dbh);
1457
1458   # setup sales contacts
1459   $query = qq|SELECT e.id, e.name
1460               FROM employee e
1461               WHERE e.sales = '1'
1462               AND NOT e.id = $self->{employee_id}|;
1463   $sth = $dbh->prepare($query);
1464   $sth->execute || $self->dberror($query);
1465
1466   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1467     push @{ $self->{all_employees} }, $ref;
1468   }
1469   $sth->finish;
1470
1471   # this is for self
1472   push @{ $self->{all_employees} },
1473     { id   => $self->{employee_id},
1474       name => $self->{employee} };
1475
1476   # sort the whole thing
1477   @{ $self->{all_employees} } =
1478     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
1479
1480   if ($module eq 'AR') {
1481
1482     # prepare query for departments
1483     $query = qq|SELECT d.id, d.description
1484                 FROM department d
1485                 WHERE d.role = 'P'
1486                 ORDER BY 2|;
1487
1488   } else {
1489     $query = qq|SELECT d.id, d.description
1490                 FROM department d
1491                 ORDER BY 2|;
1492   }
1493
1494   $sth = $dbh->prepare($query);
1495   $sth->execute || $self->dberror($query);
1496
1497   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1498     push @{ $self->{all_departments} }, $ref;
1499   }
1500   $sth->finish;
1501
1502   # get languages
1503   $query = qq|SELECT id, description
1504               FROM language
1505               ORDER BY 1|;
1506   $sth = $dbh->prepare($query);
1507   $sth->execute || $form->dberror($query);
1508
1509   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1510     push @{ $self->{languages} }, $ref;
1511   }
1512   $sth->finish;
1513
1514   # get printer
1515   $query = qq|SELECT printer_description, id
1516               FROM printers
1517               ORDER BY 1|;
1518   $sth = $dbh->prepare($query);
1519   $sth->execute || $form->dberror($query);
1520
1521   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1522     push @{ $self->{printers} }, $ref;
1523   }
1524   $sth->finish;
1525
1526
1527   # get payment terms
1528   $query = qq|SELECT id, description
1529               FROM payment_terms
1530               ORDER BY 1|;
1531   $sth = $dbh->prepare($query);
1532   $sth->execute || $form->dberror($query);
1533
1534   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1535     push @{ $self->{payment_terms} }, $ref;
1536   }
1537   $sth->finish;
1538   $dbh->disconnect;
1539   $main::lxdebug->leave_sub();
1540 }
1541
1542
1543 sub language_payment {
1544   $main::lxdebug->enter_sub();
1545
1546   my ($self, $myconfig) = @_;
1547   undef $self->{languages};
1548   undef $self->{payment_terms};
1549   undef $self->{printers};
1550
1551   my $ref;
1552   my $dbh = $self->dbconnect($myconfig);
1553   # get languages
1554   my $query = qq|SELECT id, description
1555               FROM language
1556               ORDER BY 1|;
1557   my $sth = $dbh->prepare($query);
1558   $sth->execute || $form->dberror($query);
1559
1560   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1561     push @{ $self->{languages} }, $ref;
1562   }
1563   $sth->finish;
1564
1565   # get printer
1566   $query = qq|SELECT printer_description, id
1567               FROM printers
1568               ORDER BY 1|;
1569   $sth = $dbh->prepare($query);
1570   $sth->execute || $form->dberror($query);
1571
1572   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1573     push @{ $self->{printers} }, $ref;
1574   }
1575   $sth->finish;
1576
1577   # get payment terms
1578   $query = qq|SELECT id, description
1579               FROM payment_terms
1580               ORDER BY 1|;
1581   $sth = $dbh->prepare($query);
1582   $sth->execute || $form->dberror($query);
1583
1584   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1585     push @{ $self->{payment_terms} }, $ref;
1586   }
1587   $sth->finish;
1588
1589   # get buchungsgruppen
1590   $query = qq|SELECT id, description
1591               FROM buchungsgruppen|;
1592   $sth = $dbh->prepare($query);
1593   $sth->execute || $form->dberror($query);
1594
1595   $self->{BUCHUNGSGRUPPEN} = [];
1596   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1597     push @{ $self->{BUCHUNGSGRUPPEN} }, $ref;
1598   }
1599   $sth->finish;
1600
1601   $dbh->disconnect;
1602   $main::lxdebug->leave_sub();
1603 }
1604
1605 # this is only used for reports
1606 sub all_departments {
1607   $main::lxdebug->enter_sub();
1608
1609   my ($self, $myconfig, $table) = @_;
1610
1611   my $dbh   = $self->dbconnect($myconfig);
1612   my $where = "1 = 1";
1613
1614   if (defined $table) {
1615     if ($table eq 'customer') {
1616       $where = " d.role = 'P'";
1617     }
1618   }
1619
1620   my $query = qq|SELECT d.id, d.description
1621                  FROM department d
1622                  WHERE $where
1623                  ORDER BY 2|;
1624   my $sth = $dbh->prepare($query);
1625   $sth->execute || $self->dberror($query);
1626
1627   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1628     push @{ $self->{all_departments} }, $ref;
1629   }
1630   $sth->finish;
1631
1632   $dbh->disconnect;
1633
1634   $main::lxdebug->leave_sub();
1635 }
1636
1637 sub create_links {
1638   $main::lxdebug->enter_sub();
1639
1640   my ($self, $module, $myconfig, $table) = @_;
1641
1642   $self->all_vc($myconfig, $table, $module);
1643
1644   # get last customers or vendors
1645   my ($query, $sth);
1646
1647   my $dbh = $self->dbconnect($myconfig);
1648   my %xkeyref = ();
1649
1650   if (!$self->{id}) {
1651
1652     my $transdate = "current_date";
1653     if ($self->{transdate}) {
1654       $transdate = qq|'$self->{transdate}'|;
1655     }
1656   
1657     # now get the account numbers
1658     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
1659                 FROM chart c, taxkeys tk
1660                 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)
1661                 ORDER BY c.accno|;
1662   
1663     $sth = $dbh->prepare($query);
1664     $sth->execute || $self->dberror($query);
1665   
1666     $self->{accounts} = "";
1667     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1668   
1669       foreach my $key (split(/:/, $ref->{link})) {
1670         if ($key =~ /$module/) {
1671   
1672           # cross reference for keys
1673           $xkeyref{ $ref->{accno} } = $key;
1674   
1675           push @{ $self->{"${module}_links"}{$key} },
1676             { accno       => $ref->{accno},
1677               description => $ref->{description},
1678               taxkey      => $ref->{taxkey_id},
1679               tax_id      => $ref->{tax_id} };
1680   
1681           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
1682         }
1683       }
1684     }
1685   }
1686
1687   # get taxkeys and description
1688   $query = qq|SELECT id, taxkey, taxdescription
1689               FROM tax|;
1690   $sth = $dbh->prepare($query);
1691   $sth->execute || $self->dberror($query);
1692
1693   $ref = $sth->fetchrow_hashref(NAME_lc);
1694
1695   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1696     push @{ $self->{TAXKEY} }, $ref;
1697   }
1698
1699   $sth->finish;
1700
1701
1702   # get tax zones
1703   $query = qq|SELECT id, description
1704               FROM tax_zones|;
1705   $sth = $dbh->prepare($query);
1706   $sth->execute || $form->dberror($query);
1707
1708
1709   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1710     push @{ $self->{TAXZONE} }, $ref;
1711   }
1712   $sth->finish;
1713
1714   if (($module eq "AP") || ($module eq "AR")) {
1715
1716     # get tax rates and description
1717     $query = qq| SELECT * FROM tax t|;
1718     $sth   = $dbh->prepare($query);
1719     $sth->execute || $self->dberror($query);
1720     $self->{TAX} = ();
1721     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1722       push @{ $self->{TAX} }, $ref;
1723     }
1724     $sth->finish;
1725   }
1726
1727   if ($self->{id}) {
1728     my $arap = ($table eq 'customer') ? 'ar' : 'ap';
1729
1730     $query = qq|SELECT a.cp_id, a.invnumber, a.transdate,
1731                 a.${table}_id, a.datepaid, a.duedate, a.ordnumber,
1732                 a.taxincluded, a.curr AS currency, a.notes, a.intnotes,
1733                 c.name AS $table, a.department_id, d.description AS department,
1734                 a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
1735                 a.employee_id, e.name AS employee, a.gldate, a.type
1736                 FROM $arap a
1737                 JOIN $table c ON (a.${table}_id = c.id)
1738                 LEFT JOIN employee e ON (e.id = a.employee_id)
1739                 LEFT JOIN department d ON (d.id = a.department_id)
1740                 WHERE a.id = $self->{id}|;
1741     $sth = $dbh->prepare($query);
1742     $sth->execute || $self->dberror($query);
1743
1744     $ref = $sth->fetchrow_hashref(NAME_lc);
1745     foreach $key (keys %$ref) {
1746       $self->{$key} = $ref->{$key};
1747     }
1748     $sth->finish;
1749
1750
1751     my $transdate = "current_date";
1752     if ($self->{transdate}) {
1753       $transdate = qq|'$self->{transdate}'|;
1754     }
1755   
1756     # now get the account numbers
1757     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
1758                 FROM chart c, taxkeys tk
1759                 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%'))
1760                 ORDER BY c.accno|;
1761   
1762     $sth = $dbh->prepare($query);
1763     $sth->execute || $self->dberror($query);
1764   
1765     $self->{accounts} = "";
1766     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1767   
1768       foreach my $key (split(/:/, $ref->{link})) {
1769         if ($key =~ /$module/) {
1770   
1771           # cross reference for keys
1772           $xkeyref{ $ref->{accno} } = $key;
1773   
1774           push @{ $self->{"${module}_links"}{$key} },
1775             { accno       => $ref->{accno},
1776               description => $ref->{description},
1777               taxkey      => $ref->{taxkey_id},
1778               tax_id      => $ref->{tax_id} };
1779   
1780           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
1781         }
1782       }
1783     }
1784
1785
1786     # get amounts from individual entries
1787     $query = qq|SELECT c.accno, c.description, a.source, a.amount, a.memo,
1788                 a.transdate, a.cleared, a.project_id, p.projectnumber, a.taxkey, t.rate, t.id
1789                 FROM acc_trans a
1790                 JOIN chart c ON (c.id = a.chart_id)
1791                 LEFT JOIN project p ON (p.id = a.project_id)
1792                 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)) 
1793                 WHERE a.trans_id = $self->{id}
1794                 AND a.fx_transaction = '0'
1795                 ORDER BY a.oid,a.transdate|;
1796     $sth = $dbh->prepare($query);
1797     $sth->execute || $self->dberror($query);
1798
1799     my $fld = ($table eq 'customer') ? 'buy' : 'sell';
1800
1801     # get exchangerate for currency
1802     $self->{exchangerate} =
1803       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate},
1804                               $fld);
1805     my $index = 0;
1806
1807     # store amounts in {acc_trans}{$key} for multiple accounts
1808     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1809       $ref->{exchangerate} =
1810         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate},
1811                                 $fld);
1812       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
1813         $index++;
1814       }
1815       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
1816         $ref->{amount} *= -1;
1817       }
1818       $ref->{index} = $index;
1819
1820       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
1821     }
1822
1823     $sth->finish;
1824     $query = qq|SELECT d.curr AS currencies, d.closedto, d.revtrans,
1825                   (SELECT c.accno FROM chart c
1826                    WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
1827                   (SELECT c.accno FROM chart c
1828                    WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
1829                 FROM defaults d|;
1830     $sth = $dbh->prepare($query);
1831     $sth->execute || $self->dberror($query);
1832
1833     $ref = $sth->fetchrow_hashref(NAME_lc);
1834     map { $self->{$_} = $ref->{$_} } keys %$ref;
1835     $sth->finish;
1836
1837   } else {
1838
1839     # get date
1840     $query = qq|SELECT current_date AS transdate,
1841                 d.curr AS currencies, d.closedto, d.revtrans,
1842                   (SELECT c.accno FROM chart c
1843                    WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
1844                   (SELECT c.accno FROM chart c
1845                    WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
1846                 FROM defaults d|;
1847     $sth = $dbh->prepare($query);
1848     $sth->execute || $self->dberror($query);
1849
1850     $ref = $sth->fetchrow_hashref(NAME_lc);
1851     map { $self->{$_} = $ref->{$_} } keys %$ref;
1852     $sth->finish;
1853
1854     if ($self->{"$self->{vc}_id"}) {
1855
1856       # only setup currency
1857       ($self->{currency}) = split(/:/, $self->{currencies});
1858
1859     } else {
1860
1861       $self->lastname_used($dbh, $myconfig, $table, $module);
1862
1863       my $fld = ($table eq 'customer') ? 'buy' : 'sell';
1864
1865       # get exchangerate for currency
1866       $self->{exchangerate} =
1867         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate},
1868                                 $fld);
1869
1870     }
1871
1872   }
1873
1874   $sth->finish;
1875
1876   $dbh->disconnect;
1877
1878   $main::lxdebug->leave_sub();
1879 }
1880
1881 sub lastname_used {
1882   $main::lxdebug->enter_sub();
1883
1884   my ($self, $dbh, $myconfig, $table, $module) = @_;
1885
1886   my $arap  = ($table eq 'customer') ? "ar" : "ap";
1887   my $where = "1 = 1";
1888
1889   if ($self->{type} =~ /_order/) {
1890     $arap  = 'oe';
1891     $where = "quotation = '0'";
1892   }
1893   if ($self->{type} =~ /_quotation/) {
1894     $arap  = 'oe';
1895     $where = "quotation = '1'";
1896   }
1897
1898   my $query = qq|SELECT MAX(id) FROM $arap
1899                               WHERE $where
1900                               AND ${table}_id > 0|;
1901   my $sth = $dbh->prepare($query);
1902   $sth->execute || $self->dberror($query);
1903
1904   my ($trans_id) = $sth->fetchrow_array;
1905   $sth->finish;
1906
1907   $trans_id *= 1;
1908   $query = qq|SELECT ct.name, a.curr, a.${table}_id,
1909               current_date + ct.terms AS duedate, a.department_id,
1910               d.description AS department
1911               FROM $arap a
1912               JOIN $table ct ON (a.${table}_id = ct.id)
1913               LEFT JOIN department d ON (a.department_id = d.id)
1914               WHERE a.id = $trans_id|;
1915   $sth = $dbh->prepare($query);
1916   $sth->execute || $self->dberror($query);
1917
1918   ($self->{$table},  $self->{currency},      $self->{"${table}_id"},
1919    $self->{duedate}, $self->{department_id}, $self->{department})
1920     = $sth->fetchrow_array;
1921   $sth->finish;
1922
1923   $main::lxdebug->leave_sub();
1924 }
1925
1926 sub current_date {
1927   $main::lxdebug->enter_sub();
1928
1929   my ($self, $myconfig, $thisdate, $days) = @_;
1930
1931   my $dbh = $self->dbconnect($myconfig);
1932   my ($sth, $query);
1933
1934   $days *= 1;
1935   if ($thisdate) {
1936     my $dateformat = $myconfig->{dateformat};
1937     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1938
1939     $query = qq|SELECT to_date('$thisdate', '$dateformat') + $days AS thisdate
1940                 FROM defaults|;
1941     $sth = $dbh->prepare($query);
1942     $sth->execute || $self->dberror($query);
1943   } else {
1944     $query = qq|SELECT current_date AS thisdate
1945                 FROM defaults|;
1946     $sth = $dbh->prepare($query);
1947     $sth->execute || $self->dberror($query);
1948   }
1949
1950   ($thisdate) = $sth->fetchrow_array;
1951   $sth->finish;
1952
1953   $dbh->disconnect;
1954
1955   $main::lxdebug->leave_sub();
1956
1957   return $thisdate;
1958 }
1959
1960 sub like {
1961   $main::lxdebug->enter_sub();
1962
1963   my ($self, $string) = @_;
1964
1965   if ($string !~ /%/) {
1966     $string = "%$string%";
1967   }
1968
1969   $string =~ s/\'/\'\'/g;
1970
1971   $main::lxdebug->leave_sub();
1972
1973   return $string;
1974 }
1975
1976 sub redo_rows {
1977   $main::lxdebug->enter_sub();
1978
1979   my ($self, $flds, $new, $count, $numrows) = @_;
1980
1981   my @ndx = ();
1982
1983   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } }
1984     (1 .. $count);
1985
1986   my $i = 0;
1987
1988   # fill rows
1989   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
1990     $i++;
1991     $j = $item->{ndx} - 1;
1992     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
1993   }
1994
1995   # delete empty rows
1996   for $i ($count + 1 .. $numrows) {
1997     map { delete $self->{"${_}_$i"} } @{$flds};
1998   }
1999
2000   $main::lxdebug->leave_sub();
2001 }
2002
2003 sub update_status {
2004   $main::lxdebug->enter_sub();
2005
2006   my ($self, $myconfig) = @_;
2007
2008   my ($i, $id);
2009
2010   my $dbh = $self->dbconnect_noauto($myconfig);
2011
2012   my $query = qq|DELETE FROM status
2013                  WHERE formname = '$self->{formname}'
2014                  AND trans_id = ?|;
2015   my $sth = $dbh->prepare($query) || $self->dberror($query);
2016
2017   if ($self->{formname} =~ /(check|receipt)/) {
2018     for $i (1 .. $self->{rowcount}) {
2019       $sth->execute($self->{"id_$i"} * 1) || $self->dberror($query);
2020       $sth->finish;
2021     }
2022   } else {
2023     $sth->execute($self->{id}) || $self->dberror($query);
2024     $sth->finish;
2025   }
2026
2027   my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
2028   my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
2029
2030   my %queued = split / /, $self->{queued};
2031
2032   if ($self->{formname} =~ /(check|receipt)/) {
2033
2034     # this is a check or receipt, add one entry for each lineitem
2035     my ($accno) = split /--/, $self->{account};
2036     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname,
2037                 chart_id) VALUES (?, '$printed',
2038                 '$queued{$self->{formname}}', '$self->{prinform}',
2039                 (SELECT c.id FROM chart c WHERE c.accno = '$accno'))|;
2040     $sth = $dbh->prepare($query) || $self->dberror($query);
2041
2042     for $i (1 .. $self->{rowcount}) {
2043       if ($self->{"checked_$i"}) {
2044         $sth->execute($self->{"id_$i"}) || $self->dberror($query);
2045         $sth->finish;
2046       }
2047     }
2048   } else {
2049     $query = qq|INSERT INTO status (trans_id, printed, emailed,
2050                 spoolfile, formname)
2051                 VALUES ($self->{id}, '$printed', '$emailed',
2052                 '$queued{$self->{formname}}', '$self->{formname}')|;
2053     $dbh->do($query) || $self->dberror($query);
2054   }
2055
2056   $dbh->commit;
2057   $dbh->disconnect;
2058
2059   $main::lxdebug->leave_sub();
2060 }
2061
2062 sub save_status {
2063   $main::lxdebug->enter_sub();
2064
2065   my ($self, $dbh) = @_;
2066
2067   my ($query, $printed, $emailed);
2068
2069   my $formnames  = $self->{printed};
2070   my $emailforms = $self->{emailed};
2071
2072   my $query = qq|DELETE FROM status
2073                  WHERE formname = '$self->{formname}'
2074                  AND trans_id = $self->{id}|;
2075   $dbh->do($query) || $self->dberror($query);
2076
2077   # this only applies to the forms
2078   # checks and receipts are posted when printed or queued
2079
2080   if ($self->{queued}) {
2081     my %queued = split / /, $self->{queued};
2082
2083     foreach my $formname (keys %queued) {
2084       $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
2085       $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
2086
2087       $query = qq|INSERT INTO status (trans_id, printed, emailed,
2088                   spoolfile, formname)
2089                   VALUES ($self->{id}, '$printed', '$emailed',
2090                   '$queued{$formname}', '$formname')|;
2091       $dbh->do($query) || $self->dberror($query);
2092
2093       $formnames  =~ s/$self->{formname}//;
2094       $emailforms =~ s/$self->{formname}//;
2095
2096     }
2097   }
2098
2099   # save printed, emailed info
2100   $formnames  =~ s/^ +//g;
2101   $emailforms =~ s/^ +//g;
2102
2103   my %status = ();
2104   map { $status{$_}{printed} = 1 } split / +/, $formnames;
2105   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
2106
2107   foreach my $formname (keys %status) {
2108     $printed = ($formnames  =~ /$self->{formname}/) ? "1" : "0";
2109     $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
2110
2111     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
2112                 VALUES ($self->{id}, '$printed', '$emailed', '$formname')|;
2113     $dbh->do($query) || $self->dberror($query);
2114   }
2115
2116   $main::lxdebug->leave_sub();
2117 }
2118
2119 sub update_defaults {
2120   $main::lxdebug->enter_sub();
2121
2122   my ($self, $myconfig, $fld) = @_;
2123
2124   my $dbh   = $self->dbconnect_noauto($myconfig);
2125   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
2126   my $sth   = $dbh->prepare($query);
2127
2128   $sth->execute || $self->dberror($query);
2129   my ($var) = $sth->fetchrow_array;
2130   $sth->finish;
2131
2132   $var++;
2133
2134   $query = qq|UPDATE defaults
2135               SET $fld = '$var'|;
2136   $dbh->do($query) || $self->dberror($query);
2137
2138   $dbh->commit;
2139   $dbh->disconnect;
2140
2141   $main::lxdebug->leave_sub();
2142
2143   return $var;
2144 }
2145
2146 sub update_business {
2147   $main::lxdebug->enter_sub();
2148
2149   my ($self, $myconfig, $business_id) = @_;
2150
2151   my $dbh   = $self->dbconnect_noauto($myconfig);
2152   my $query =
2153     qq|SELECT customernumberinit FROM business  WHERE id=$business_id FOR UPDATE|;
2154   my $sth = $dbh->prepare($query);
2155
2156   $sth->execute || $self->dberror($query);
2157   my ($var) = $sth->fetchrow_array;
2158   $sth->finish;
2159   if ($var ne "") {
2160     $var++;
2161   }
2162   $query = qq|UPDATE business
2163               SET customernumberinit = '$var' WHERE id=$business_id|;
2164   $dbh->do($query) || $self->dberror($query);
2165
2166   $dbh->commit;
2167   $dbh->disconnect;
2168
2169   $main::lxdebug->leave_sub();
2170
2171   return $var;
2172 }
2173
2174 sub get_salesman {
2175   $main::lxdebug->enter_sub();
2176
2177   my ($self, $myconfig, $salesman) = @_;
2178
2179   my $dbh   = $self->dbconnect($myconfig);
2180   my $query =
2181     qq|SELECT id, name FROM customer  WHERE (customernumber ilike '%$salesman%' OR name ilike '%$salesman%') AND business_id in (SELECT id from business WHERE salesman)|;
2182   my $sth = $dbh->prepare($query);
2183   $sth->execute || $self->dberror($query);
2184
2185   my $i = 0;
2186   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2187     push(@{ $self->{salesman_list} }, $ref);
2188     $i++;
2189   }
2190   $dbh->commit;
2191   $main::lxdebug->leave_sub();
2192
2193   return $i;
2194 }
2195
2196 sub get_partsgroup {
2197   $main::lxdebug->enter_sub();
2198
2199   my ($self, $myconfig, $p) = @_;
2200
2201   my $dbh = $self->dbconnect($myconfig);
2202
2203   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
2204                  FROM partsgroup pg
2205                  JOIN parts p ON (p.partsgroup_id = pg.id)|;
2206
2207   if ($p->{searchitems} eq 'part') {
2208     $query .= qq|
2209                  WHERE p.inventory_accno_id > 0|;
2210   }
2211   if ($p->{searchitems} eq 'service') {
2212     $query .= qq|
2213                  WHERE p.inventory_accno_id IS NULL|;
2214   }
2215   if ($p->{searchitems} eq 'assembly') {
2216     $query .= qq|
2217                  WHERE p.assembly = '1'|;
2218   }
2219   if ($p->{searchitems} eq 'labor') {
2220     $query .= qq|
2221                  WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
2222   }
2223
2224   $query .= qq|
2225                  ORDER BY partsgroup|;
2226
2227   if ($p->{all}) {
2228     $query = qq|SELECT id, partsgroup FROM partsgroup
2229                 ORDER BY partsgroup|;
2230   }
2231
2232   if ($p->{language_code}) {
2233     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
2234                 t.description AS translation
2235                 FROM partsgroup pg
2236                 JOIN parts p ON (p.partsgroup_id = pg.id)
2237                 LEFT JOIN translation t ON (t.trans_id = pg.id AND t.language_code = '$p->{language_code}')
2238                 ORDER BY translation|;
2239   }
2240
2241   my $sth = $dbh->prepare($query);
2242   $sth->execute || $self->dberror($query);
2243
2244   $self->{all_partsgroup} = ();
2245   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2246     push @{ $self->{all_partsgroup} }, $ref;
2247   }
2248   $sth->finish;
2249   $dbh->disconnect;
2250   $main::lxdebug->leave_sub();
2251 }
2252
2253 sub get_pricegroup {
2254   $main::lxdebug->enter_sub();
2255
2256   my ($self, $myconfig, $p) = @_;
2257
2258   my $dbh = $self->dbconnect($myconfig);
2259
2260   my $query = qq|SELECT p.id, p.pricegroup
2261                  FROM pricegroup p|;
2262
2263   $query .= qq|
2264                  ORDER BY pricegroup|;
2265
2266   if ($p->{all}) {
2267     $query = qq|SELECT id, pricegroup FROM pricegroup
2268                 ORDER BY pricegroup|;
2269   }
2270
2271   my $sth = $dbh->prepare($query);
2272   $sth->execute || $self->dberror($query);
2273
2274   $self->{all_pricegroup} = ();
2275   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2276     push @{ $self->{all_pricegroup} }, $ref;
2277   }
2278   $sth->finish;
2279   $dbh->disconnect;
2280
2281   $main::lxdebug->leave_sub();
2282 }
2283
2284 sub audittrail {
2285   my ($self, $dbh, $myconfig, $audittrail) = @_;
2286
2287   # table, $reference, $formname, $action, $id, $transdate) = @_;
2288
2289   my $query;
2290   my $rv;
2291   my $disconnect;
2292
2293   if (!$dbh) {
2294     $dbh        = $self->dbconnect($myconfig);
2295     $disconnect = 1;
2296   }
2297
2298   # if we have an id add audittrail, otherwise get a new timestamp
2299
2300   if ($audittrail->{id}) {
2301
2302     $query = qq|SELECT audittrail FROM defaults|;
2303
2304     if ($dbh->selectrow_array($query)) {
2305       my ($null, $employee_id) = $self->get_employee($dbh);
2306
2307       if ($self->{audittrail} && !$myconfig) {
2308         chop $self->{audittrail};
2309
2310         my @a = split /\|/, $self->{audittrail};
2311         my %newtrail = ();
2312         my $key;
2313         my $i;
2314         my @flds = qw(tablename reference formname action transdate);
2315
2316         # put into hash and remove dups
2317         while (@a) {
2318           $key = "$a[2]$a[3]";
2319           $i   = 0;
2320           $newtrail{$key} = { map { $_ => $a[$i++] } @flds };
2321           splice @a, 0, 5;
2322         }
2323
2324         $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
2325                     formname, action, employee_id, transdate)
2326                     VALUES ($audittrail->{id}, ?, ?,
2327                     ?, ?, $employee_id, ?)|;
2328         my $sth = $dbh->prepare($query) || $self->dberror($query);
2329
2330         foreach $key (
2331           sort {
2332             $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate}
2333           } keys %newtrail
2334           ) {
2335           $i = 1;
2336           for (@flds) { $sth->bind_param($i++, $newtrail{$key}{$_}) }
2337
2338           $sth->execute || $self->dberror;
2339           $sth->finish;
2340         }
2341       }
2342
2343       if ($audittrail->{transdate}) {
2344         $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
2345                     formname, action, employee_id, transdate) VALUES (
2346                     $audittrail->{id}, '$audittrail->{tablename}', |
2347           . $dbh->quote($audittrail->{reference}) . qq|,
2348                     '$audittrail->{formname}', '$audittrail->{action}',
2349                     $employee_id, '$audittrail->{transdate}')|;
2350       } else {
2351         $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
2352                     formname, action, employee_id) VALUES ($audittrail->{id},
2353                     '$audittrail->{tablename}', |
2354           . $dbh->quote($audittrail->{reference}) . qq|,
2355                     '$audittrail->{formname}', '$audittrail->{action}',
2356                     $employee_id)|;
2357       }
2358       $dbh->do($query);
2359     }
2360   } else {
2361
2362     $query = qq|SELECT current_timestamp FROM defaults|;
2363     my ($timestamp) = $dbh->selectrow_array($query);
2364
2365     $rv =
2366       "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
2367   }
2368
2369   $dbh->disconnect if $disconnect;
2370
2371   $rv;
2372
2373 }
2374
2375 package Locale;
2376
2377 sub new {
2378   $main::lxdebug->enter_sub();
2379
2380   my ($type, $country, $NLS_file) = @_;
2381   my $self = {};
2382
2383   if ($country && -d "locale/$country") {
2384     local *IN;
2385     $self->{countrycode} = $country;
2386     if (open(IN, "locale/$country/$NLS_file")) {
2387       my $code = join("", <IN>);
2388       eval($code);
2389       close(IN);
2390     }
2391   }
2392
2393   $self->{NLS_file} = $NLS_file;
2394
2395   push @{ $self->{LONG_MONTH} },
2396     ("January",   "February", "March",    "April",
2397      "May ",      "June",     "July",     "August",
2398      "September", "October",  "November", "December");
2399   push @{ $self->{SHORT_MONTH} },
2400     (qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec));
2401
2402   $main::lxdebug->leave_sub();
2403
2404   bless $self, $type;
2405 }
2406
2407 sub text {
2408   my ($self, $text) = @_;
2409
2410   return (exists $self->{texts}{$text}) ? $self->{texts}{$text} : $text;
2411 }
2412
2413 sub findsub {
2414   $main::lxdebug->enter_sub();
2415
2416   my ($self, $text) = @_;
2417
2418   if (exists $self->{subs}{$text}) {
2419     $text = $self->{subs}{$text};
2420   } else {
2421     if ($self->{countrycode} && $self->{NLS_file}) {
2422       Form->error(
2423          "$text not defined in locale/$self->{countrycode}/$self->{NLS_file}");
2424     }
2425   }
2426
2427   $main::lxdebug->leave_sub();
2428
2429   return $text;
2430 }
2431
2432 sub date {
2433   $main::lxdebug->enter_sub();
2434
2435   my ($self, $myconfig, $date, $longformat) = @_;
2436
2437   my $longdate  = "";
2438   my $longmonth = ($longformat) ? 'LONG_MONTH' : 'SHORT_MONTH';
2439
2440   if ($date) {
2441
2442     # get separator
2443     $spc = $myconfig->{dateformat};
2444     $spc =~ s/\w//g;
2445     $spc = substr($spc, 1, 1);
2446
2447     if ($date =~ /\D/) {
2448       if ($myconfig->{dateformat} =~ /^yy/) {
2449         ($yy, $mm, $dd) = split /\D/, $date;
2450       }
2451       if ($myconfig->{dateformat} =~ /^mm/) {
2452         ($mm, $dd, $yy) = split /\D/, $date;
2453       }
2454       if ($myconfig->{dateformat} =~ /^dd/) {
2455         ($dd, $mm, $yy) = split /\D/, $date;
2456       }
2457     } else {
2458       $date = substr($date, 2);
2459       ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
2460     }
2461
2462     $dd *= 1;
2463     $mm--;
2464     $yy = ($yy < 70) ? $yy + 2000 : $yy;
2465     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
2466
2467     if ($myconfig->{dateformat} =~ /^dd/) {
2468       if (defined $longformat && $longformat == 0) {
2469         $mm++;
2470         $dd = "0$dd" if ($dd < 10);
2471         $mm = "0$mm" if ($mm < 10);
2472         $longdate = "$dd$spc$mm$spc$yy";
2473       } else {
2474         $longdate = "$dd";
2475         $longdate .= ($spc eq '.') ? ". " : " ";
2476         $longdate .= &text($self, $self->{$longmonth}[$mm]) . " $yy";
2477       }
2478     } elsif ($myconfig->{dateformat} eq "yyyy-mm-dd") {
2479
2480       # Use German syntax with the ISO date style "yyyy-mm-dd" because
2481       # Lx-Office is mainly used in Germany or German speaking countries.
2482       if (defined $longformat && $longformat == 0) {
2483         $mm++;
2484         $dd = "0$dd" if ($dd < 10);
2485         $mm = "0$mm" if ($mm < 10);
2486         $longdate = "$yy-$mm-$dd";
2487       } else {
2488         $longdate = "$dd. ";
2489         $longdate .= &text($self, $self->{$longmonth}[$mm]) . " $yy";
2490       }
2491     } else {
2492       if (defined $longformat && $longformat == 0) {
2493         $mm++;
2494         $dd = "0$dd" if ($dd < 10);
2495         $mm = "0$mm" if ($mm < 10);
2496         $longdate = "$mm$spc$dd$spc$yy";
2497       } else {
2498         $longdate = &text($self, $self->{$longmonth}[$mm]) . " $dd, $yy";
2499       }
2500     }
2501
2502   }
2503
2504   $main::lxdebug->leave_sub();
2505
2506   return $longdate;
2507 }
2508
2509 sub parse_date {
2510   $main::lxdebug->enter_sub();
2511
2512   my ($self, $myconfig, $date, $longformat) = @_;
2513
2514   unless ($date) {
2515     $main::lxdebug->leave_sub();
2516     return ();
2517   }
2518
2519   # get separator
2520   $spc = $myconfig->{dateformat};
2521   $spc =~ s/\w//g;
2522   $spc = substr($spc, 1, 1);
2523
2524   if ($date =~ /\D/) {
2525     if ($myconfig->{dateformat} =~ /^yy/) {
2526       ($yy, $mm, $dd) = split /\D/, $date;
2527     } elsif ($myconfig->{dateformat} =~ /^mm/) {
2528       ($mm, $dd, $yy) = split /\D/, $date;
2529     } elsif ($myconfig->{dateformat} =~ /^dd/) {
2530       ($dd, $mm, $yy) = split /\D/, $date;
2531     }
2532   } else {
2533     $date = substr($date, 2);
2534     ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
2535   }
2536
2537   $dd *= 1;
2538   $mm *= 1;
2539   $yy = ($yy < 70) ? $yy + 2000 : $yy;
2540   $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
2541
2542   $main::lxdebug->leave_sub();
2543   return ($yy, $mm, $dd);
2544 }
2545
2546 sub reformat_date {
2547   $main::lxdebug->enter_sub();
2548
2549   my ($self, $myconfig, $date, $output_format, $longformat) = @_;
2550
2551   $main::lxdebug->leave_sub() and return "" unless ($date);
2552
2553   my ($yy, $mm, $dd) = $self->parse_date($myconfig, $date);
2554
2555   $output_format =~ /d+/;
2556   substr($output_format, $-[0], $+[0] - $-[0]) =
2557     sprintf("%0" . (length($&)) . "d", $dd);
2558
2559   $output_format =~ /m+/;
2560   substr($output_format, $-[0], $+[0] - $-[0]) =
2561     sprintf("%0" . (length($&)) . "d", $mm);
2562
2563   $output_format =~ /y+/;
2564   if (length($&) == 2) {
2565     $yy -= $yy >= 2000 ? 2000 : 1900;
2566   }
2567   substr($output_format, $-[0], $+[0] - $-[0]) =
2568     sprintf("%0" . (length($&)) . "d", $yy);
2569
2570   $main::lxdebug->leave_sub();
2571
2572   return $output_format;
2573 }
2574
2575 1;