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