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