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