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