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