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