Zahlungskonditionen: Zahlenwerte auf zwei Stellen gerundet ausgeben.
[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 Template;
44 use SL::Template;
45 use CGI::Ajax;
46 use SL::DBUtils;
47 use SL::Mailer;
48 use SL::Menu;
49 use SL::User;
50 use SL::Common;
51 use CGI;
52
53 my $standard_dbh;
54
55 sub DESTROY {
56   if ($standard_dbh) {
57     $standard_dbh->disconnect();
58     undef $standard_dbh;
59   }
60 }
61
62 sub _input_to_hash {
63   $main::lxdebug->enter_sub(2);
64
65   my $input = $_[0];
66   my %in    = ();
67   my @pairs = split(/&/, $input);
68
69   foreach (@pairs) {
70     my ($name, $value) = split(/=/, $_, 2);
71     $in{$name} = unescape(undef, $value);
72   }
73
74   $main::lxdebug->leave_sub(2);
75
76   return %in;
77 }
78
79 sub _request_to_hash {
80   $main::lxdebug->enter_sub(2);
81
82   my ($input) = @_;
83
84   if (!$ENV{'CONTENT_TYPE'}
85       || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
86     $main::lxdebug->leave_sub(2);
87     return _input_to_hash($input);
88   }
89
90   my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr);
91   my %params;
92
93   my $boundary = '--' . $1;
94
95   foreach my $line (split m/\n/, $input) {
96     last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
97
98     if (($line eq $boundary) || ($line eq "$boundary\r")) {
99       $params{$name} =~ s|\r?\n$|| if $name;
100
101       undef $name, $filename;
102
103       $headers_done   = 0;
104       $content_type   = "text/plain";
105       $boundary_found = 1;
106       $need_cr        = 0;
107
108       next;
109     }
110
111     next unless $boundary_found;
112
113     if (!$headers_done) {
114       $line =~ s/[\r\n]*$//;
115
116       if (!$line) {
117         $headers_done = 1;
118         next;
119       }
120
121       if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
122         if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
123           $filename = $1;
124           substr $line, $-[0], $+[0] - $-[0], "";
125         }
126
127         if ($line =~ m|name\s*=\s*"(.*?)"|i) {
128           $name = $1;
129           substr $line, $-[0], $+[0] - $-[0], "";
130         }
131
132         $params{$name}    = "";
133         $params{FILENAME} = $filename if ($filename);
134
135         next;
136       }
137
138       if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
139         $content_type = $1;
140       }
141
142       next;
143     }
144
145     next unless $name;
146
147     $params{$name} .= "${line}\n";
148   }
149
150   $params{$name} =~ s|\r?\n$|| if $name;
151
152   $main::lxdebug->leave_sub(2);
153   return %params;
154 }
155
156 sub new {
157   $main::lxdebug->enter_sub();
158
159   my $type = shift;
160
161   my $self = {};
162
163   if ($LXDebug::watch_form) {
164     require SL::Watchdog;
165     tie %{ $self }, 'SL::Watchdog';
166   }
167
168   read(STDIN, $_, $ENV{CONTENT_LENGTH});
169
170   if ($ENV{QUERY_STRING}) {
171     $_ = $ENV{QUERY_STRING};
172   }
173
174   if ($ARGV[0]) {
175     $_ = $ARGV[0];
176   }
177
178   my %parameters = _request_to_hash($_);
179   map({ $self->{$_} = $parameters{$_}; } keys(%parameters));
180
181   $self->{action} = lc $self->{action};
182   $self->{action} =~ s/( |-|,|\#)/_/g;
183
184   $self->{version}   = "2.4.3";
185
186   $main::lxdebug->leave_sub();
187
188   bless $self, $type;
189 }
190
191 sub debug {
192   $main::lxdebug->enter_sub();
193
194   my ($self) = @_;
195
196   print "\n";
197
198   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
199
200   $main::lxdebug->leave_sub();
201 }
202
203 sub escape {
204   $main::lxdebug->enter_sub(2);
205
206   my ($self, $str) = @_;
207
208   $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
209
210   $main::lxdebug->leave_sub(2);
211
212   return $str;
213 }
214
215 sub unescape {
216   $main::lxdebug->enter_sub(2);
217
218   my ($self, $str) = @_;
219
220   $str =~ tr/+/ /;
221   $str =~ s/\\$//;
222
223   $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
224
225   $main::lxdebug->leave_sub(2);
226
227   return $str;
228 }
229
230 sub quote {
231   my ($self, $str) = @_;
232
233   if ($str && !ref($str)) {
234     $str =~ s/\"/&quot;/g;
235   }
236
237   $str;
238
239 }
240
241 sub unquote {
242   my ($self, $str) = @_;
243
244   if ($str && !ref($str)) {
245     $str =~ s/&quot;/\"/g;
246   }
247
248   $str;
249
250 }
251
252 sub quote_html {
253   $main::lxdebug->enter_sub(2);
254
255   my ($self, $str) = @_;
256
257   my %replace =
258     ('order' => ['"', '<', '>'],
259      '<'             => '&lt;',
260      '>'             => '&gt;',
261      '"'             => '&quot;',
262     );
263
264   map({ $str =~ s/$_/$replace{$_}/g; } @{ $replace{"order"} });
265
266   $main::lxdebug->leave_sub(2);
267
268   return $str;
269 }
270
271 sub hide_form {
272   my $self = shift;
273
274   if (@_) {
275     map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
276   } else {
277     for (sort keys %$self) {
278       next if (($_ eq "header") || (ref($self->{$_}) ne ""));
279       print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
280     }
281   }
282
283 }
284
285 sub error {
286   $main::lxdebug->enter_sub();
287
288   $main::lxdebug->show_backtrace();
289
290   my ($self, $msg) = @_;
291   if ($ENV{HTTP_USER_AGENT}) {
292     $msg =~ s/\n/<br>/g;
293     $self->show_generic_error($msg);
294
295   } else {
296
297     if ($self->{error_function}) {
298       &{ $self->{error_function} }($msg);
299     } else {
300       die "Error: $msg\n";
301     }
302   }
303
304   $main::lxdebug->leave_sub();
305 }
306
307 sub info {
308   $main::lxdebug->enter_sub();
309
310   my ($self, $msg) = @_;
311
312   if ($ENV{HTTP_USER_AGENT}) {
313     $msg =~ s/\n/<br>/g;
314
315     if (!$self->{header}) {
316       $self->header;
317       print qq|
318       <body>|;
319     }
320
321     print qq|
322
323     <p><b>$msg</b>
324     |;
325
326   } else {
327
328     if ($self->{info_function}) {
329       &{ $self->{info_function} }($msg);
330     } else {
331       print "$msg\n";
332     }
333   }
334
335   $main::lxdebug->leave_sub();
336 }
337
338 sub numtextrows {
339   $main::lxdebug->enter_sub();
340
341   my ($self, $str, $cols, $maxrows) = @_;
342
343   my $rows = 0;
344
345   map { $rows += int(((length) - 2) / $cols) + 1 } split /\r/, $str;
346
347   $maxrows = $rows unless defined $maxrows;
348
349   $main::lxdebug->leave_sub();
350
351   return ($rows > $maxrows) ? $maxrows : $rows;
352 }
353
354 sub dberror {
355   $main::lxdebug->enter_sub();
356
357   my ($self, $msg) = @_;
358
359   $self->error("$msg\n" . $DBI::errstr);
360
361   $main::lxdebug->leave_sub();
362 }
363
364 sub isblank {
365   $main::lxdebug->enter_sub();
366
367   my ($self, $name, $msg) = @_;
368
369   if ($self->{$name} =~ /^\s*$/) {
370     $self->error($msg);
371   }
372   $main::lxdebug->leave_sub();
373 }
374
375 sub header {
376   $main::lxdebug->enter_sub();
377
378   my ($self, $extra_code) = @_;
379
380   if ($self->{header}) {
381     $main::lxdebug->leave_sub();
382     return;
383   }
384
385   my ($stylesheet, $favicon);
386
387   if ($ENV{HTTP_USER_AGENT}) {
388
389     my $stylesheets = "$self->{stylesheet} $self->{stylesheets}";
390
391     $stylesheets =~ s|^\s*||;
392     $stylesheets =~ s|\s*$||;
393     foreach my $file (split m/\s+/, $stylesheets) {
394       $file =~ s|.*/||;
395       next if (! -f "css/$file");
396
397       $stylesheet .= qq|<link rel="stylesheet" href="css/$file" TYPE="text/css" TITLE="Lx-Office stylesheet">\n|;
398     }
399
400     $self->{favicon}    = "favicon.ico" unless $self->{favicon};
401
402     if ($self->{favicon} && (-f "$self->{favicon}")) {
403       $favicon =
404         qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
405   |;
406     }
407
408     my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
409
410     if ($self->{landscape}) {
411       $pagelayout = qq|<style type="text/css">
412                         \@page { size:landscape; }
413                         </style>|;
414     }
415
416     my $fokus = qq|  document.$self->{fokus}.focus();| if ($self->{"fokus"});
417
418     #Set Calendar
419     my $jsscript = "";
420     if ($self->{jsscript} == 1) {
421
422       $jsscript = qq|
423         <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
424         <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
425         <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
426         <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
427         $self->{javascript}
428        |;
429     }
430
431     $self->{titlebar} =
432       ($self->{title})
433       ? "$self->{title} - $self->{titlebar}"
434       : $self->{titlebar};
435     my $ajax = "";
436     foreach $item (@ { $self->{AJAX} }) {
437       $ajax .= $item->show_javascript();
438     }
439     print qq|Content-Type: text/html; charset=${db_charset};
440
441 <html>
442 <head>
443   <title>$self->{titlebar}</title>
444   $stylesheet
445   $pagelayout
446   $favicon
447   <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
448   $jsscript
449   $ajax
450
451   <script type="text/javascript">
452   <!--
453     function fokus() {
454       $fokus
455     }
456   //-->
457   </script>
458
459   <meta name="robots" content="noindex,nofollow" />
460   <script type="text/javascript" src="js/highlight_input.js"></script>
461   <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
462
463   <script type="text/javascript" src="js/tabcontent.js">
464
465   /***********************************************
466   * Tab Content script- Dynamic Drive DHTML code library (www.dynamicdrive.com)
467   * This notice MUST stay intact for legal use
468   * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
469   ***********************************************/
470
471   </script>
472
473   $extra_code
474 </head>
475
476 |;
477   }
478   $self->{header} = 1;
479
480   $main::lxdebug->leave_sub();
481 }
482
483 sub _prepare_html_template {
484   $main::lxdebug->enter_sub();
485
486   my ($self, $file, $additional_params) = @_;
487   my $language;
488
489   if (!defined(%main::myconfig) || !defined($main::myconfig{"countrycode"})) {
490     $language = $main::language;
491   } else {
492     $language = $main::myconfig{"countrycode"};
493   }
494   $language = "de" unless ($language);
495
496   if (-f "templates/webpages/${file}_${language}.html") {
497     if ((-f ".developer") &&
498         (-f "templates/webpages/${file}_master.html") &&
499         ((stat("templates/webpages/${file}_master.html"))[9] >
500          (stat("templates/webpages/${file}_${language}.html"))[9])) {
501       my $info = "Developer information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
502         "Please re-run 'locales.pl' in 'locale/${language}'.";
503       print(qq|<pre>$info</pre>|);
504       die($info);
505     }
506
507     $file = "templates/webpages/${file}_${language}.html";
508   } elsif (-f "templates/webpages/${file}.html") {
509     $file = "templates/webpages/${file}.html";
510   } else {
511     my $info = "Web page template '${file}' not found.\n" .
512       "Please re-run 'locales.pl' in 'locale/${language}'.";
513     print(qq|<pre>$info</pre>|);
514     die($info);
515   }
516
517   if ($self->{"DEBUG"}) {
518     $additional_params->{"DEBUG"} = $self->{"DEBUG"};
519   }
520
521   if ($additional_params->{"DEBUG"}) {
522     $additional_params->{"DEBUG"} =
523       "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
524   }
525
526   if (%main::myconfig) {
527     map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
528     my $jsc_dateformat = $main::myconfig{"dateformat"};
529     $jsc_dateformat =~ s/d+/\%d/gi;
530     $jsc_dateformat =~ s/m+/\%m/gi;
531     $jsc_dateformat =~ s/y+/\%Y/gi;
532     $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
533   }
534
535   $additional_params->{"conf_webdav"}                 = $main::webdav;
536   $additional_params->{"conf_lizenzen"}               = $main::lizenzen;
537   $additional_params->{"conf_latex_templates"}        = $main::latex;
538   $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
539
540   if (%main::debug_options) {
541     map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
542   }
543
544   $main::lxdebug->leave_sub();
545
546   return $file;
547 }
548
549 sub parse_html_template {
550   $main::lxdebug->enter_sub();
551
552   my ($self, $file, $additional_params) = @_;
553
554   $additional_params ||= { };
555
556   $file = $self->_prepare_html_template($file, $additional_params);
557
558   my $template = HTML::Template->new("filename" => $file,
559                                      "die_on_bad_params" => 0,
560                                      "strict" => 0,
561                                      "case_sensitive" => 1,
562                                      "loop_context_vars" => 1,
563                                      "global_vars" => 1);
564
565   foreach my $key ($template->param()) {
566     my $param = $additional_params->{$key} || $self->{$key};
567     $param = [] if (($template->query("name" => $key) eq "LOOP") && (ref($param) ne "ARRAY"));
568     $template->param($key => $param);
569   }
570
571   my $output = $template->output();
572
573   $output = $main::locale->{iconv}->convert($output) if ($main::locale);
574
575   $main::lxdebug->leave_sub();
576
577   return $output;
578 }
579
580 sub parse_html_template2 {
581   $main::lxdebug->enter_sub();
582
583   my ($self, $file, $additional_params) = @_;
584
585   $additional_params ||= { };
586
587   $file = $self->_prepare_html_template($file, $additional_params);
588
589   my $template = Template->new({ 'INTERPOLATE' => 0,
590                                  'EVAL_PERL'   => 0,
591                                  'ABSOLUTE'    => 1,
592                                  'CACHE_SIZE'  => 0,
593                                }) || die;
594
595   map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
596
597   my $output;
598   $template->process($file, $additional_params, \$output);
599
600   $output = $main::locale->{iconv}->convert($output) if ($main::locale);
601
602   $main::lxdebug->leave_sub();
603
604   return $output;
605 }
606
607 sub show_generic_error {
608   my ($self, $error, $title, $action) = @_;
609
610   my $add_params = {};
611   $add_params->{"title"} = $title if ($title);
612   $self->{"label_error"} = $error;
613
614   my @vars;
615   if ($action) {
616     map({ delete($self->{$_}); } qw(action));
617     map({ push(@vars, { "name" => $_, "value" => $self->{$_} })
618             if (!ref($self->{$_})); }
619         keys(%{$self}));
620     $add_params->{"SHOW_BUTTON"} = 1;
621     $add_params->{"BUTTON_LABEL"} = $action;
622   }
623   $add_params->{"VARIABLES"} = \@vars;
624
625   $self->header();
626   print($self->parse_html_template("generic/error", $add_params));
627
628   die("Error: $error\n");
629 }
630
631 sub show_generic_information {
632   my ($self, $error, $title) = @_;
633
634   my $add_params = {};
635   $add_params->{"title"} = $title if ($title);
636   $self->{"label_information"} = $error;
637
638   $self->header();
639   print($self->parse_html_template("generic/information", $add_params));
640
641   die("Information: $error\n");
642 }
643
644 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
645 # changed it to accept an arbitrary number of triggers - sschoeling
646 sub write_trigger {
647   $main::lxdebug->enter_sub();
648
649   my $self     = shift;
650   my $myconfig = shift;
651   my $qty      = shift;
652
653   # set dateform for jsscript
654   # default
655   my %dateformats = (
656     "dd.mm.yy" => "%d.%m.%Y",
657     "dd-mm-yy" => "%d-%m-%Y",
658     "dd/mm/yy" => "%d/%m/%Y",
659     "mm/dd/yy" => "%m/%d/%Y",
660     "mm-dd-yy" => "%m-%d-%Y",
661     "yyyy-mm-dd" => "%Y-%m-%d",
662     );
663
664   my $ifFormat = defined($dateformats{$myconfig{"dateformat"}}) ?
665     $dateformats{$myconfig{"dateformat"}} : "%d.%m.%Y";
666
667   my @triggers;
668   while ($#_ >= 2) {
669     push @triggers, qq|
670        Calendar.setup(
671       {
672       inputField : "| . (shift) . qq|",
673       ifFormat :"$ifFormat",
674       align : "| .  (shift) . qq|",
675       button : "| . (shift) . qq|"
676       }
677       );
678        |;
679   }
680   my $jsscript = qq|
681        <script type="text/javascript">
682        <!--| . join("", @triggers) . qq|//-->
683         </script>
684         |;
685
686   $main::lxdebug->leave_sub();
687
688   return $jsscript;
689 }    #end sub write_trigger
690
691 sub redirect {
692   $main::lxdebug->enter_sub();
693
694   my ($self, $msg) = @_;
695
696   if ($self->{callback}) {
697
698     ($script, $argv) = split(/\?/, $self->{callback}, 2);
699     $script =~ s|.*/||;
700     $script =~ s|[^a-zA-Z0-9_\.]||g;
701     exec("perl", "$script", $argv);
702
703   } else {
704
705     $self->info($msg);
706     exit;
707   }
708
709   $main::lxdebug->leave_sub();
710 }
711
712 # sort of columns removed - empty sub
713 sub sort_columns {
714   $main::lxdebug->enter_sub();
715
716   my ($self, @columns) = @_;
717
718   $main::lxdebug->leave_sub();
719
720   return @columns;
721 }
722 #
723 sub format_amount {
724   $main::lxdebug->enter_sub(2);
725
726   my ($self, $myconfig, $amount, $places, $dash) = @_;
727
728   if ($amount eq "") {
729     $amount = 0;
730   }
731   my $neg = ($amount =~ s/-//);
732
733   if (defined($places) && ($places ne '')) {
734     if ($places < 0) {
735       $amount *= 1;
736       $places *= -1;
737
738       my ($actual_places) = ($amount =~ /\.(\d+)/);
739       $actual_places = length($actual_places);
740       $places = $actual_places > $places ? $actual_places : $places;
741     }
742
743     $amount = $self->round_amount($amount, $places);
744   }
745
746   my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
747   my @p = split(/\./, $amount); # split amount at decimal point
748
749   $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
750
751   $amount = $p[0];
752   $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
753
754   $amount = do {
755     ($dash =~ /-/)    ? ($neg ? "($amount)"  : "$amount" )    :
756     ($dash =~ /DRCR/) ? ($neg ? "$amount DR" : "$amount CR" ) :
757                         ($neg ? "-$amount"   : "$amount" )    ;
758   };
759
760
761   $main::lxdebug->leave_sub(2);
762   return $amount;
763 }
764 #
765 sub parse_amount {
766   $main::lxdebug->enter_sub(2);
767
768   my ($self, $myconfig, $amount) = @_;
769
770   if (   ($myconfig->{numberformat} eq '1.000,00')
771       || ($myconfig->{numberformat} eq '1000,00')) {
772     $amount =~ s/\.//g;
773     $amount =~ s/,/\./;
774   }
775
776   if ($myconfig->{numberformat} eq "1'000.00") {
777     $amount =~ s/\'//g;
778   }
779
780   $amount =~ s/,//g;
781
782   $main::lxdebug->leave_sub(2);
783
784   return ($amount * 1);
785 }
786
787 sub round_amount {
788   $main::lxdebug->enter_sub(2);
789
790   my ($self, $amount, $places) = @_;
791   my $round_amount;
792
793   # Rounding like "Kaufmannsrunden"
794   # Descr. http://de.wikipedia.org/wiki/Rundung
795   # Inspired by
796   # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
797   # Solves Bug: 189
798   # Udo Spallek
799   $amount = $amount * (10**($places));
800   $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
801
802   $main::lxdebug->leave_sub(2);
803
804   return $round_amount;
805
806 }
807
808 sub parse_template {
809   $main::lxdebug->enter_sub();
810
811   my ($self, $myconfig, $userspath) = @_;
812   my ($template, $out);
813
814   local (*IN, *OUT);
815
816   $self->{"cwd"} = getcwd();
817   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
818
819   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
820     $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
821   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
822     $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
823     $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
824   } elsif (($self->{"format"} =~ /html/i) ||
825            (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
826     $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
827   } elsif (($self->{"format"} =~ /xml/i) ||
828              (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
829     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
830   } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
831     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
832   } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
833     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
834   } elsif ( defined $self->{'format'}) {
835     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
836   } elsif ( $self->{'format'} eq '' ) {
837     $self->error("No Outputformat given: $self->{'format'}");
838   } else { #Catch the rest
839     $self->error("Outputformat not defined: $self->{'format'}");
840   }
841
842   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
843   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
844
845   map({ $self->{"employee_${_}"} = $myconfig->{$_}; }
846       qw(email tel fax name signature company address businessnumber
847          co_ustid taxnumber duns));
848   map({ $self->{"employee_${_}"} =~ s/\\n/\n/g; }
849       qw(company address signature));
850   map({ $self->{$_} =~ s/\\n/\n/g; } qw(company address signature));
851
852   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
853
854   # OUT is used for the media, screen, printer, email
855   # for postscript we store a copy in a temporary file
856   my $fileid = time;
857   my $prepend_userspath;
858
859   if (!$self->{tmpfile}) {
860     $self->{tmpfile}   = "${fileid}.$self->{IN}";
861     $prepend_userspath = 1;
862   }
863
864   $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
865
866   $self->{tmpfile} =~ s|.*/||;
867   $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
868   $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
869
870   if ($template->uses_temp_file() || $self->{media} eq 'email') {
871     $out = $self->{OUT};
872     $self->{OUT} = ">$self->{tmpfile}";
873   }
874
875   if ($self->{OUT}) {
876     open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
877   } else {
878     open(OUT, ">-") or $self->error("STDOUT : $!");
879     $self->header;
880   }
881
882   if (!$template->parse(*OUT)) {
883     $self->cleanup();
884     $self->error("$self->{IN} : " . $template->get_error());
885   }
886
887   close(OUT);
888
889   if ($template->uses_temp_file() || $self->{media} eq 'email') {
890
891     if ($self->{media} eq 'email') {
892
893       my $mail = new Mailer;
894
895       map { $mail->{$_} = $self->{$_} }
896         qw(cc bcc subject message version format);
897       $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
898       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
899       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
900       $mail->{fileid} = "$fileid.";
901       $myconfig->{signature} =~ s/\\r\\n/\\n/g;
902
903       # if we send html or plain text inline
904       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
905         $mail->{contenttype} = "text/html";
906
907         $mail->{message}       =~ s/\r\n/<br>\n/g;
908         $myconfig->{signature} =~ s/\\n/<br>\n/g;
909         $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
910
911         open(IN, $self->{tmpfile})
912           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
913         while (<IN>) {
914           $mail->{message} .= $_;
915         }
916
917         close(IN);
918
919       } else {
920
921         if (!$self->{"do_not_attach"}) {
922           @{ $mail->{attachments} } =
923             ({ "filename" => $self->{"tmpfile"},
924                "name" => $self->{"attachment_filename"} ?
925                  $self->{"attachment_filename"} : $self->{"tmpfile"} });
926         }
927
928         $mail->{message}       =~ s/\r\n/\n/g;
929         $myconfig->{signature} =~ s/\\n/\n/g;
930         $mail->{message} .= "\n-- \n$myconfig->{signature}";
931
932       }
933
934       my $err = $mail->send();
935       $self->error($self->cleanup . "$err") if ($err);
936
937     } else {
938
939       $self->{OUT} = $out;
940
941       my $numbytes = (-s $self->{tmpfile});
942       open(IN, $self->{tmpfile})
943         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
944
945       $self->{copies} = 1 unless $self->{media} eq 'printer';
946
947       chdir("$self->{cwd}");
948       #print(STDERR "Kopien $self->{copies}\n");
949       #print(STDERR "OUT $self->{OUT}\n");
950       for my $i (1 .. $self->{copies}) {
951         if ($self->{OUT}) {
952           open(OUT, $self->{OUT})
953             or $self->error($self->cleanup . "$self->{OUT} : $!");
954         } else {
955           $self->{attachment_filename} = ($self->{attachment_filename}) 
956                                        ? $self->{attachment_filename}
957                                        : $self->generate_attachment_filename();
958
959           # launch application
960           print qq|Content-Type: | . $template->get_mime_type() . qq|
961 Content-Disposition: attachment; filename="$self->{attachment_filename}"
962 Content-Length: $numbytes
963
964 |;
965
966           open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
967
968         }
969
970         while (<IN>) {
971           print OUT $_;
972         }
973
974         close(OUT);
975
976         seek IN, 0, 0;
977       }
978
979       close(IN);
980     }
981
982   }
983
984   $self->cleanup;
985
986   chdir("$self->{cwd}");
987   $main::lxdebug->leave_sub();
988 }
989
990 sub get_formname_translation {
991   my ($self, $formname) = @_;
992
993   $formname ||= $self->{formname};
994
995   my %formname_translations = (
996      bin_list            => $main::locale->text('Bin List'),
997      credit_note         => $main::locale->text('Credit Note'),
998      invoice             => $main::locale->text('Invoice'),
999      packing_list        => $main::locale->text('Packing List'),
1000      pick_list           => $main::locale->text('Pick List'),
1001      proforma            => $main::locale->text('Proforma Invoice'),
1002      purchase_order      => $main::locale->text('Purchase Order'),
1003      request_quotation   => $main::locale->text('RFQ'),
1004      sales_order         => $main::locale->text('Confirmation'),
1005      sales_quotation     => $main::locale->text('Quotation'),
1006      storno_invoice      => $main::locale->text('Storno Invoice'),
1007      storno_packing_list => $main::locale->text('Storno Packing List'),
1008   );
1009
1010   return $formname_translations{$formname}
1011 }
1012
1013 sub generate_attachment_filename {
1014   my ($self) = @_;
1015
1016   my $attachment_filename = $self->get_formname_translation();
1017   my $prefix = 
1018       (grep { $self->{"type"} eq $_ } qw(invoice credit_note)) ? "inv"
1019     : ($self->{"type"} =~ /_quotation$/)                       ? "quo"
1020     :                                                            "ord";
1021
1022   if ($attachment_filename && $self->{"${prefix}number"}) {
1023     $attachment_filename .= "_" . $self->{"${prefix}number"}
1024                             . (  $self->{format} =~ /pdf/i          ? ".pdf"
1025                                : $self->{format} =~ /postscript/i   ? ".ps"
1026                                : $self->{format} =~ /opendocument/i ? ".odt"
1027                                : $self->{format} =~ /html/i         ? ".html"
1028                                :                                      "");
1029     $attachment_filename =~ s/ /_/g;
1030     my %umlaute = ( "ä" => "ae", "ö" => "oe", "ü" => "ue", 
1031                     "Ä" => "Ae", "Ö" => "Oe", "Ãœ" => "Ue", "ß" => "ss");
1032     map { $attachment_filename =~ s/$_/$umlaute{$_}/g } keys %umlaute;
1033   } else {
1034     $attachment_filename = "";
1035   }
1036
1037   return $attachment_filename;
1038 }
1039
1040 sub cleanup {
1041   $main::lxdebug->enter_sub();
1042
1043   my $self = shift;
1044
1045   chdir("$self->{tmpdir}");
1046
1047   my @err = ();
1048   if (-f "$self->{tmpfile}.err") {
1049     open(FH, "$self->{tmpfile}.err");
1050     @err = <FH>;
1051     close(FH);
1052   }
1053
1054   if ($self->{tmpfile}) {
1055     $self->{tmpfile} =~ s|.*/||g;
1056     # strip extension
1057     $self->{tmpfile} =~ s/\.\w+$//g;
1058     my $tmpfile = $self->{tmpfile};
1059     unlink(<$tmpfile.*>);
1060   }
1061
1062   chdir("$self->{cwd}");
1063
1064   $main::lxdebug->leave_sub();
1065
1066   return "@err";
1067 }
1068
1069 sub datetonum {
1070   $main::lxdebug->enter_sub();
1071
1072   my ($self, $date, $myconfig) = @_;
1073
1074   if ($date && $date =~ /\D/) {
1075
1076     if ($myconfig->{dateformat} =~ /^yy/) {
1077       ($yy, $mm, $dd) = split /\D/, $date;
1078     }
1079     if ($myconfig->{dateformat} =~ /^mm/) {
1080       ($mm, $dd, $yy) = split /\D/, $date;
1081     }
1082     if ($myconfig->{dateformat} =~ /^dd/) {
1083       ($dd, $mm, $yy) = split /\D/, $date;
1084     }
1085
1086     $dd *= 1;
1087     $mm *= 1;
1088     $yy = ($yy < 70) ? $yy + 2000 : $yy;
1089     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1090
1091     $dd = "0$dd" if ($dd < 10);
1092     $mm = "0$mm" if ($mm < 10);
1093
1094     $date = "$yy$mm$dd";
1095   }
1096
1097   $main::lxdebug->leave_sub();
1098
1099   return $date;
1100 }
1101
1102 # Database routines used throughout
1103
1104 sub dbconnect {
1105   $main::lxdebug->enter_sub(2);
1106
1107   my ($self, $myconfig) = @_;
1108
1109   # connect to database
1110   my $dbh =
1111     DBI->connect($myconfig->{dbconnect},
1112                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
1113     or $self->dberror;
1114
1115   # set db options
1116   if ($myconfig->{dboptions}) {
1117     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1118   }
1119
1120   $main::lxdebug->leave_sub(2);
1121
1122   return $dbh;
1123 }
1124
1125 sub dbconnect_noauto {
1126   $main::lxdebug->enter_sub();
1127
1128   my ($self, $myconfig) = @_;
1129   
1130   # connect to database
1131   $dbh =
1132     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1133                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
1134     or $self->dberror;
1135
1136   # set db options
1137   if ($myconfig->{dboptions}) {
1138     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1139   }
1140
1141   $main::lxdebug->leave_sub();
1142
1143   return $dbh;
1144 }
1145
1146 sub get_standard_dbh {
1147   $main::lxdebug->enter_sub(2);
1148
1149   my ($self, $myconfig) = @_;
1150
1151   $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1152
1153   $main::lxdebug->leave_sub(2);
1154
1155   return $standard_dbh;
1156 }
1157
1158 sub update_balance {
1159   $main::lxdebug->enter_sub();
1160
1161   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1162
1163   # if we have a value, go do it
1164   if ($value != 0) {
1165
1166     # retrieve balance from table
1167     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1168     my $sth = prepare_execute_query($self, $dbh, $query, @values);
1169     my ($balance) = $sth->fetchrow_array;
1170     $sth->finish;
1171
1172     $balance += $value;
1173
1174     # update balance
1175     $query = "UPDATE $table SET $field = $balance WHERE $where";
1176     do_query($self, $dbh, $query, @values);
1177   }
1178   $main::lxdebug->leave_sub();
1179 }
1180
1181 sub update_exchangerate {
1182   $main::lxdebug->enter_sub();
1183
1184   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1185
1186   # some sanity check for currency
1187   if ($curr eq '') {
1188     $main::lxdebug->leave_sub();
1189     return;
1190   }  
1191   my $query = qq|SELECT curr FROM defaults|;
1192
1193   my ($currency) = selectrow_query($self, $dbh, $query);
1194   my ($defaultcurrency) = split m/:/, $currency;
1195
1196
1197   if ($curr eq $defaultcurrency) {
1198     $main::lxdebug->leave_sub();
1199     return;
1200   }
1201
1202   my $query = qq|SELECT e.curr FROM exchangerate e
1203                  WHERE e.curr = ? AND e.transdate = ?
1204                  FOR UPDATE|;
1205   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1206
1207   if ($buy == 0) {
1208     $buy = "";
1209   }
1210   if ($sell == 0) {
1211     $sell = "";
1212   }
1213
1214   $buy = conv_i($buy, "NULL");
1215   $sell = conv_i($sell, "NULL");
1216
1217   my $set;
1218   if ($buy != 0 && $sell != 0) {
1219     $set = "buy = $buy, sell = $sell";
1220   } elsif ($buy != 0) {
1221     $set = "buy = $buy";
1222   } elsif ($sell != 0) {
1223     $set = "sell = $sell";
1224   }
1225
1226   if ($sth->fetchrow_array) {
1227     $query = qq|UPDATE exchangerate
1228                 SET $set
1229                 WHERE curr = ?
1230                 AND transdate = ?|;
1231     
1232   } else {
1233     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1234                 VALUES (?, $buy, $sell, ?)|;
1235   }
1236   $sth->finish;
1237   do_query($self, $dbh, $query, $curr, $transdate);
1238
1239   $main::lxdebug->leave_sub();
1240 }
1241
1242 sub save_exchangerate {
1243   $main::lxdebug->enter_sub();
1244
1245   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1246
1247   my $dbh = $self->dbconnect($myconfig);
1248
1249   my ($buy, $sell);
1250
1251   $buy  = $rate if $fld eq 'buy';
1252   $sell = $rate if $fld eq 'sell';
1253
1254
1255   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1256
1257
1258   $dbh->disconnect;
1259
1260   $main::lxdebug->leave_sub();
1261 }
1262
1263 sub get_exchangerate {
1264   $main::lxdebug->enter_sub();
1265
1266   my ($self, $dbh, $curr, $transdate, $fld) = @_;
1267
1268   unless ($transdate) {
1269     $main::lxdebug->leave_sub();
1270     return 1;
1271   }
1272
1273   my $query = qq|SELECT curr FROM defaults|;
1274
1275   my ($currency) = selectrow_query($self, $dbh, $query);
1276   my ($defaultcurrency) = split m/:/, $currency;
1277
1278   if ($currency eq $defaultcurrency) {
1279     $main::lxdebug->leave_sub();
1280     return 1;
1281   }
1282
1283   my $query = qq|SELECT e.$fld FROM exchangerate e
1284                  WHERE e.curr = ? AND e.transdate = ?|;
1285   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1286
1287
1288
1289   $main::lxdebug->leave_sub();
1290
1291   return $exchangerate;
1292 }
1293
1294 sub check_exchangerate {
1295   $main::lxdebug->enter_sub();
1296
1297   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1298
1299   unless ($transdate) {
1300     $main::lxdebug->leave_sub();
1301     return "";
1302   }
1303
1304   my ($defaultcurrency) = $self->get_default_currency($myconfig);
1305
1306   if ($currency eq $defaultcurrency) {
1307     $main::lxdebug->leave_sub();
1308     return 1;
1309   }
1310
1311   my $dbh   = $self->get_standard_dbh($myconfig);
1312   my $query = qq|SELECT e.$fld FROM exchangerate e
1313                  WHERE e.curr = ? AND e.transdate = ?|;
1314
1315   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1316
1317   $exchangerate = 1 if ($exchangerate eq "");
1318
1319   $main::lxdebug->leave_sub();
1320
1321   return $exchangerate;
1322 }
1323
1324 sub get_default_currency {
1325   $main::lxdebug->enter_sub();
1326
1327   my ($self, $myconfig) = @_;
1328   my $dbh = $self->get_standard_dbh($myconfig);
1329
1330   my $query = qq|SELECT curr FROM defaults|;
1331
1332   my ($curr)            = selectrow_query($self, $dbh, $query);
1333   my ($defaultcurrency) = split m/:/, $curr;
1334
1335   $main::lxdebug->leave_sub();
1336
1337   return $defaultcurrency;
1338 }
1339
1340
1341 sub set_payment_options {
1342   $main::lxdebug->enter_sub();
1343
1344   my ($self, $myconfig, $transdate) = @_;
1345
1346   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1347
1348   my $dbh = $self->get_standard_dbh($myconfig);
1349
1350   my $query =
1351     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1352     qq|FROM payment_terms p | .
1353     qq|WHERE p.id = ?|;
1354
1355   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1356    $self->{payment_terms}) =
1357      selectrow_query($self, $dbh, $query, $self->{payment_id});
1358
1359   if ($transdate eq "") {
1360     if ($self->{invdate}) {
1361       $transdate = $self->{invdate};
1362     } else {
1363       $transdate = $self->{transdate};
1364     }
1365   }
1366
1367   $query =
1368     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1369     qq|FROM payment_terms|;
1370   ($self->{netto_date}, $self->{skonto_date}) =
1371     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1372
1373   my ($invtotal, $total);
1374   my (%amounts, %formatted_amounts);
1375
1376   if ($self->{type} =~ /_order$/) {
1377     $amounts{invtotal} = $self->{ordtotal};
1378     $amounts{total}    = $self->{ordtotal};
1379
1380   } elsif ($self->{type} =~ /_quotation$/) {
1381     $amounts{invtotal} = $self->{quototal};
1382     $amounts{total}    = $self->{quototal};
1383
1384   } else {
1385     $amounts{invtotal} = $self->{invtotal};
1386     $amounts{total}    = $self->{total};
1387   }
1388
1389   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1390
1391   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
1392   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1393   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
1394
1395   foreach (keys %amounts) {
1396     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
1397     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1398   }
1399
1400   if ($self->{"language_id"}) {
1401     $query =
1402       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1403       qq|FROM translation_payment_terms t | .
1404       qq|LEFT JOIN language l ON t.language_id = l.id | .
1405       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1406     my ($description_long, $output_numberformat, $output_dateformat,
1407       $output_longdates) =
1408       selectrow_query($self, $dbh, $query,
1409                       $self->{"language_id"}, $self->{"payment_id"});
1410
1411     $self->{payment_terms} = $description_long if ($description_long);
1412
1413     if ($output_dateformat) {
1414       foreach my $key (qw(netto_date skonto_date)) {
1415         $self->{$key} =
1416           $main::locale->reformat_date($myconfig, $self->{$key},
1417                                        $output_dateformat,
1418                                        $output_longdates);
1419       }
1420     }
1421
1422     if ($output_numberformat &&
1423         ($output_numberformat ne $myconfig->{"numberformat"})) {
1424       my $saved_numberformat = $myconfig->{"numberformat"};
1425       $myconfig->{"numberformat"} = $output_numberformat;
1426       map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1427       $myconfig->{"numberformat"} = $saved_numberformat;
1428     }
1429   }
1430
1431   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1432   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1433   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1434   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1435   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1436   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1437   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1438
1439   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1440
1441   $main::lxdebug->leave_sub();
1442
1443 }
1444
1445 sub get_template_language {
1446   $main::lxdebug->enter_sub();
1447
1448   my ($self, $myconfig) = @_;
1449
1450   my $template_code = "";
1451
1452   if ($self->{language_id}) {
1453     my $dbh = $self->get_standard_dbh($myconfig);
1454     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1455     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1456   }
1457
1458   $main::lxdebug->leave_sub();
1459
1460   return $template_code;
1461 }
1462
1463 sub get_printer_code {
1464   $main::lxdebug->enter_sub();
1465
1466   my ($self, $myconfig) = @_;
1467
1468   my $template_code = "";
1469
1470   if ($self->{printer_id}) {
1471     my $dbh = $self->get_standard_dbh($myconfig);
1472     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1473     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1474   }
1475
1476   $main::lxdebug->leave_sub();
1477
1478   return $template_code;
1479 }
1480
1481 sub get_shipto {
1482   $main::lxdebug->enter_sub();
1483
1484   my ($self, $myconfig) = @_;
1485
1486   my $template_code = "";
1487
1488   if ($self->{shipto_id}) {
1489     my $dbh = $self->get_standard_dbh($myconfig);
1490     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1491     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1492     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1493   }
1494
1495   $main::lxdebug->leave_sub();
1496 }
1497
1498 sub add_shipto {
1499   $main::lxdebug->enter_sub();
1500
1501   my ($self, $dbh, $id, $module) = @_;
1502
1503   my $shipto;
1504   my @values;
1505
1506   foreach my $item (qw(name department_1 department_2 street zipcode city country
1507                        contact phone fax email)) {
1508     if ($self->{"shipto$item"}) {
1509       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1510     }
1511     push(@values, $self->{"shipto${item}"});
1512   }
1513
1514   if ($shipto) {
1515     if ($self->{shipto_id}) {
1516       my $query = qq|UPDATE shipto set
1517                        shiptoname = ?,
1518                        shiptodepartment_1 = ?,
1519                        shiptodepartment_2 = ?,
1520                        shiptostreet = ?,
1521                        shiptozipcode = ?,
1522                        shiptocity = ?,
1523                        shiptocountry = ?,
1524                        shiptocontact = ?,
1525                        shiptophone = ?,
1526                        shiptofax = ?,
1527                        shiptoemail = ?
1528                      WHERE shipto_id = ?|;
1529       do_query($self, $dbh, $query, @values, $self->{shipto_id});
1530     } else {
1531       my $query = qq|SELECT * FROM shipto
1532                      WHERE shiptoname = ? AND
1533                        shiptodepartment_1 = ? AND
1534                        shiptodepartment_2 = ? AND
1535                        shiptostreet = ? AND
1536                        shiptozipcode = ? AND
1537                        shiptocity = ? AND
1538                        shiptocountry = ? AND
1539                        shiptocontact = ? AND
1540                        shiptophone = ? AND
1541                        shiptofax = ? AND
1542                        shiptoemail = ? AND
1543                        module = ? AND 
1544                        trans_id = ?|;
1545       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1546       if(!$insert_check){
1547         $query =
1548           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1549                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
1550                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
1551              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1552         do_query($self, $dbh, $query, $id, @values, $module);
1553       }
1554     }
1555   }
1556
1557   $main::lxdebug->leave_sub();
1558 }
1559
1560 sub get_employee {
1561   $main::lxdebug->enter_sub();
1562
1563   my ($self, $dbh) = @_;
1564
1565   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1566   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1567   $self->{"employee_id"} *= 1;
1568
1569   $main::lxdebug->leave_sub();
1570 }
1571
1572 sub get_salesman {
1573   $main::lxdebug->enter_sub();
1574
1575   my ($self, $myconfig, $salesman_id) = @_;
1576
1577   $main::lxdebug->leave_sub() and return unless $salesman_id;
1578
1579   my $dbh = $self->get_standard_dbh($myconfig);
1580
1581   my ($login) =
1582     selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|,
1583                     $salesman_id);
1584
1585   if ($login) {
1586     my $user = new User($main::memberfile, $login);
1587     map({ $self->{"salesman_$_"} = $user->{$_}; }
1588         qw(address businessnumber co_ustid company duns email fax name
1589            taxnumber tel));
1590     $self->{salesman_login} = $login;
1591
1592     $self->{salesman_name} = $login
1593       if ($self->{salesman_name} eq "");
1594
1595     map({ $self->{"salesman_$_"} =~ s/\\n/\n/g; } qw(address company));
1596   }
1597
1598   $main::lxdebug->leave_sub();
1599 }
1600
1601 sub get_duedate {
1602   $main::lxdebug->enter_sub();
1603
1604   my ($self, $myconfig) = @_;
1605
1606   my $dbh = $self->get_standard_dbh($myconfig);
1607   my $query = qq|SELECT current_date + terms_netto FROM payment_terms WHERE id = ?|;
1608   ($self->{duedate}) = selectrow_query($self, $dbh, $query, $self->{payment_id});
1609
1610   $main::lxdebug->leave_sub();
1611 }
1612
1613 sub _get_contacts {
1614   $main::lxdebug->enter_sub();
1615
1616   my ($self, $dbh, $id, $key) = @_;
1617
1618   $key = "all_contacts" unless ($key);
1619
1620   my $query =
1621     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
1622     qq|FROM contacts | .
1623     qq|WHERE cp_cv_id = ? | .
1624     qq|ORDER BY lower(cp_name)|;
1625
1626   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
1627
1628   $main::lxdebug->leave_sub();
1629 }
1630
1631 sub _get_projects {
1632   $main::lxdebug->enter_sub();
1633
1634   my ($self, $dbh, $key) = @_;
1635
1636   my ($all, $old_id, $where, @values);
1637
1638   if (ref($key) eq "HASH") {
1639     my $params = $key;
1640
1641     $key = "ALL_PROJECTS";
1642
1643     foreach my $p (keys(%{$params})) {
1644       if ($p eq "all") {
1645         $all = $params->{$p};
1646       } elsif ($p eq "old_id") {
1647         $old_id = $params->{$p};
1648       } elsif ($p eq "key") {
1649         $key = $params->{$p};
1650       }
1651     }
1652   }
1653
1654   if (!$all) {
1655     $where = "WHERE active ";
1656     if ($old_id) {
1657       if (ref($old_id) eq "ARRAY") {
1658         my @ids = grep({ $_ } @{$old_id});
1659         if (@ids) {
1660           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
1661           push(@values, @ids);
1662         }
1663       } else {
1664         $where .= " OR (id = ?) ";
1665         push(@values, $old_id);
1666       }
1667     }
1668   }
1669
1670   my $query =
1671     qq|SELECT id, projectnumber, description, active | .
1672     qq|FROM project | .
1673     $where .
1674     qq|ORDER BY lower(projectnumber)|;
1675
1676   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
1677
1678   $main::lxdebug->leave_sub();
1679 }
1680
1681 sub _get_shipto {
1682   $main::lxdebug->enter_sub();
1683
1684   my ($self, $dbh, $vc_id, $key) = @_;
1685
1686   $key = "all_shipto" unless ($key);
1687
1688   # get shipping addresses
1689   my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
1690
1691   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
1692
1693   $main::lxdebug->leave_sub();
1694 }
1695
1696 sub _get_printers {
1697   $main::lxdebug->enter_sub();
1698
1699   my ($self, $dbh, $key) = @_;
1700
1701   $key = "all_printers" unless ($key);
1702
1703   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
1704
1705   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1706
1707   $main::lxdebug->leave_sub();
1708 }
1709
1710 sub _get_charts {
1711   $main::lxdebug->enter_sub();
1712
1713   my ($self, $dbh, $params) = @_;
1714
1715   $key = $params->{key};
1716   $key = "all_charts" unless ($key);
1717
1718   my $transdate = quote_db_date($params->{transdate});
1719
1720   my $query =
1721     qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
1722     qq|FROM chart c | .
1723     qq|LEFT JOIN taxkeys tk ON | .
1724     qq|(tk.id = (SELECT id FROM taxkeys | .
1725     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
1726     qq|          ORDER BY startdate DESC LIMIT 1)) | .
1727     qq|ORDER BY c.accno|;
1728
1729   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1730
1731   $main::lxdebug->leave_sub();
1732 }
1733
1734 sub _get_taxcharts {
1735   $main::lxdebug->enter_sub();
1736
1737   my ($self, $dbh, $key) = @_;
1738
1739   $key = "all_taxcharts" unless ($key);
1740
1741   my $query = qq|SELECT * FROM tax ORDER BY taxkey|;
1742
1743   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1744
1745   $main::lxdebug->leave_sub();
1746 }
1747
1748 sub _get_taxzones {
1749   $main::lxdebug->enter_sub();
1750
1751   my ($self, $dbh, $key) = @_;
1752
1753   $key = "all_taxzones" unless ($key);
1754
1755   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
1756
1757   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1758
1759   $main::lxdebug->leave_sub();
1760 }
1761
1762 sub _get_employees {
1763   $main::lxdebug->enter_sub();
1764
1765   my ($self, $dbh, $default_key, $key) = @_;
1766
1767   $key = $default_key unless ($key);
1768   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY name|);
1769
1770   $main::lxdebug->leave_sub();
1771 }
1772
1773 sub _get_business_types {
1774   $main::lxdebug->enter_sub();
1775
1776   my ($self, $dbh, $key) = @_;
1777
1778   $key = "all_business_types" unless ($key);
1779   $self->{$key} =
1780     selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
1781
1782   $main::lxdebug->leave_sub();
1783 }
1784
1785 sub _get_languages {
1786   $main::lxdebug->enter_sub();
1787
1788   my ($self, $dbh, $key) = @_;
1789
1790   $key = "all_languages" unless ($key);
1791
1792   my $query = qq|SELECT * FROM language ORDER BY id|;
1793
1794   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1795
1796   $main::lxdebug->leave_sub();
1797 }
1798
1799 sub _get_dunning_configs {
1800   $main::lxdebug->enter_sub();
1801
1802   my ($self, $dbh, $key) = @_;
1803
1804   $key = "all_dunning_configs" unless ($key);
1805
1806   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
1807
1808   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1809
1810   $main::lxdebug->leave_sub();
1811 }
1812
1813 sub _get_currencies {
1814 $main::lxdebug->enter_sub();
1815
1816   my ($self, $dbh, $key) = @_;
1817
1818   $key = "all_currencies" unless ($key);
1819
1820   my $query = qq|SELECT curr AS currency FROM defaults|;
1821  
1822   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
1823
1824   $main::lxdebug->leave_sub();
1825 }
1826
1827 sub _get_payments {
1828 $main::lxdebug->enter_sub();
1829
1830   my ($self, $dbh, $key) = @_;
1831
1832   $key = "all_payments" unless ($key);
1833
1834   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
1835  
1836   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1837
1838   $main::lxdebug->leave_sub();
1839 }
1840
1841 sub _get_customers {
1842   $main::lxdebug->enter_sub();
1843
1844   my ($self, $dbh, $key) = @_;
1845
1846   $key = "all_customers" unless ($key);
1847
1848   my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name|;
1849
1850   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1851
1852   $main::lxdebug->leave_sub();
1853 }
1854
1855 sub _get_vendors {
1856   $main::lxdebug->enter_sub();
1857
1858   my ($self, $dbh, $key) = @_;
1859
1860   $key = "all_vendors" unless ($key);
1861
1862   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
1863
1864   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1865
1866   $main::lxdebug->leave_sub();
1867 }
1868
1869 sub _get_departments {
1870   $main::lxdebug->enter_sub();
1871
1872   my ($self, $dbh, $key) = @_;
1873
1874   $key = "all_departments" unless ($key);
1875
1876   my $query = qq|SELECT * FROM department ORDER BY description|;
1877
1878   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1879
1880   $main::lxdebug->leave_sub();
1881 }
1882
1883 sub get_lists {
1884   $main::lxdebug->enter_sub();
1885
1886   my $self = shift;
1887   my %params = @_;
1888
1889   my $dbh = $self->get_standard_dbh(\%main::myconfig);
1890   my ($sth, $query, $ref);
1891
1892   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
1893   my $vc_id = $self->{"${vc}_id"};
1894
1895   if ($params{"contacts"}) {
1896     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
1897   }
1898
1899   if ($params{"shipto"}) {
1900     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
1901   }
1902
1903   if ($params{"projects"} || $params{"all_projects"}) {
1904     $self->_get_projects($dbh, $params{"all_projects"} ?
1905                          $params{"all_projects"} : $params{"projects"},
1906                          $params{"all_projects"} ? 1 : 0);
1907   }
1908
1909   if ($params{"printers"}) {
1910     $self->_get_printers($dbh, $params{"printers"});
1911   }
1912
1913   if ($params{"languages"}) {
1914     $self->_get_languages($dbh, $params{"languages"});
1915   }
1916
1917   if ($params{"charts"}) {
1918     $self->_get_charts($dbh, $params{"charts"});
1919   }
1920
1921   if ($params{"taxcharts"}) {
1922     $self->_get_taxcharts($dbh, $params{"taxcharts"});
1923   }
1924
1925   if ($params{"taxzones"}) {
1926     $self->_get_taxzones($dbh, $params{"taxzones"});
1927   }
1928
1929   if ($params{"employees"}) {
1930     $self->_get_employees($dbh, "all_employees", $params{"employees"});
1931   }
1932   
1933   if ($params{"salesmen"}) {
1934     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
1935   }
1936
1937   if ($params{"business_types"}) {
1938     $self->_get_business_types($dbh, $params{"business_types"});
1939   }
1940
1941   if ($params{"dunning_configs"}) {
1942     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
1943   }
1944   
1945   if($params{"currencies"}) {
1946     $self->_get_currencies($dbh, $params{"currencies"});
1947   }
1948   
1949   if($params{"customers"}) {
1950     $self->_get_customers($dbh, $params{"customers"});
1951   }
1952   
1953   if($params{"vendors"}) {
1954     $self->_get_vendors($dbh, $params{"vendors"});
1955   }
1956   
1957   if($params{"payments"}) {
1958     $self->_get_payments($dbh, $params{"payments"});
1959   }
1960
1961   if($params{"departments"}) {
1962     $self->_get_departments($dbh, $params{"departments"});
1963   }
1964
1965   $main::lxdebug->leave_sub();
1966 }
1967
1968 # this sub gets the id and name from $table
1969 sub get_name {
1970   $main::lxdebug->enter_sub();
1971
1972   my ($self, $myconfig, $table) = @_;
1973
1974   # connect to database
1975   my $dbh = $self->get_standard_dbh($myconfig);
1976
1977   $table = $table eq "customer" ? "customer" : "vendor";
1978   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
1979
1980   my ($query, @values);
1981
1982   if (!$self->{openinvoices}) {
1983     my $where;
1984     if ($self->{customernumber} ne "") {
1985       $where = qq|(vc.customernumber ILIKE ?)|;
1986       push(@values, '%' . $self->{customernumber} . '%');
1987     } else {
1988       $where = qq|(vc.name ILIKE ?)|;
1989       push(@values, '%' . $self->{$table} . '%');
1990     }
1991
1992     $query =
1993       qq~SELECT vc.id, vc.name,
1994            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
1995          FROM $table vc
1996          WHERE $where AND (NOT vc.obsolete)
1997          ORDER BY vc.name~;
1998   } else {
1999     $query =
2000       qq~SELECT DISTINCT vc.id, vc.name,
2001            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2002          FROM $arap a
2003          JOIN $table vc ON (a.${table}_id = vc.id)
2004          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2005          ORDER BY vc.name~;
2006     push(@values, '%' . $self->{$table} . '%');
2007   }
2008
2009   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2010
2011   $main::lxdebug->leave_sub();
2012
2013   return scalar(@{ $self->{name_list} });
2014 }
2015
2016 # the selection sub is used in the AR, AP, IS, IR and OE module
2017 #
2018 sub all_vc {
2019   $main::lxdebug->enter_sub();
2020
2021   my ($self, $myconfig, $table, $module) = @_;
2022
2023   my $ref;
2024   my $dbh = $self->get_standard_dbh($myconfig);
2025
2026   $table = $table eq "customer" ? "customer" : "vendor";
2027
2028   my $query = qq|SELECT count(*) FROM $table|;
2029   my ($count) = selectrow_query($self, $dbh, $query);
2030
2031   # build selection list
2032   if ($count < $myconfig->{vclimit}) {
2033     $query = qq|SELECT id, name, salesman_id
2034                 FROM $table WHERE NOT obsolete
2035                 ORDER BY name|;
2036     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2037   }
2038
2039   # get self
2040   $self->get_employee($dbh);
2041
2042   # setup sales contacts
2043   $query = qq|SELECT e.id, e.name
2044               FROM employee e
2045               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2046   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2047
2048   # this is for self
2049   push(@{ $self->{all_employees} },
2050        { id   => $self->{employee_id},
2051          name => $self->{employee} });
2052
2053   # sort the whole thing
2054   @{ $self->{all_employees} } =
2055     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2056
2057   if ($module eq 'AR') {
2058
2059     # prepare query for departments
2060     $query = qq|SELECT id, description
2061                 FROM department
2062                 WHERE role = 'P'
2063                 ORDER BY description|;
2064
2065   } else {
2066     $query = qq|SELECT id, description
2067                 FROM department
2068                 ORDER BY description|;
2069   }
2070
2071   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2072
2073   # get languages
2074   $query = qq|SELECT id, description
2075               FROM language
2076               ORDER BY id|;
2077
2078   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2079
2080   # get printer
2081   $query = qq|SELECT printer_description, id
2082               FROM printers
2083               ORDER BY printer_description|;
2084
2085   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2086
2087   # get payment terms
2088   $query = qq|SELECT id, description
2089               FROM payment_terms
2090               ORDER BY sortkey|;
2091
2092   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2093
2094   $main::lxdebug->leave_sub();
2095 }
2096
2097 sub language_payment {
2098   $main::lxdebug->enter_sub();
2099
2100   my ($self, $myconfig) = @_;
2101
2102   my $dbh = $self->get_standard_dbh($myconfig);
2103   # get languages
2104   my $query = qq|SELECT id, description
2105                  FROM language
2106                  ORDER BY id|;
2107
2108   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2109
2110   # get printer
2111   $query = qq|SELECT printer_description, id
2112               FROM printers
2113               ORDER BY printer_description|;
2114
2115   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2116
2117   # get payment terms
2118   $query = qq|SELECT id, description
2119               FROM payment_terms
2120               ORDER BY sortkey|;
2121
2122   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2123
2124   # get buchungsgruppen
2125   $query = qq|SELECT id, description
2126               FROM buchungsgruppen|;
2127
2128   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2129
2130   $main::lxdebug->leave_sub();
2131 }
2132
2133 # this is only used for reports
2134 sub all_departments {
2135   $main::lxdebug->enter_sub();
2136
2137   my ($self, $myconfig, $table) = @_;
2138
2139   my $dbh = $self->get_standard_dbh($myconfig);
2140   my $where;
2141
2142   if ($table eq 'customer') {
2143     $where = "WHERE role = 'P' ";
2144   }
2145
2146   my $query = qq|SELECT id, description
2147                  FROM department
2148                  $where
2149                  ORDER BY description|;
2150   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2151
2152   delete($self->{all_departments}) unless (@{ $self->{all_departments} });
2153
2154   $main::lxdebug->leave_sub();
2155 }
2156
2157 sub create_links {
2158   $main::lxdebug->enter_sub();
2159
2160   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2161
2162   my ($fld, $arap);
2163   if ($table eq "customer") {
2164     $fld = "buy";
2165     $arap = "ar";
2166   } else {
2167     $table = "vendor";
2168     $fld = "sell";
2169     $arap = "ap";
2170   }
2171
2172   $self->all_vc($myconfig, $table, $module);
2173
2174   # get last customers or vendors
2175   my ($query, $sth, $ref);
2176
2177   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2178   my %xkeyref = ();
2179
2180   if (!$self->{id}) {
2181
2182     my $transdate = "current_date";
2183     if ($self->{transdate}) {
2184       $transdate = $dbh->quote($self->{transdate});
2185     }
2186
2187     # now get the account numbers
2188     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2189                 FROM chart c, taxkeys tk
2190                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2191                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2192                 ORDER BY c.accno|;
2193
2194     $sth = $dbh->prepare($query);
2195
2196     do_statement($self, $sth, $query, '%' . $module . '%');
2197
2198     $self->{accounts} = "";
2199     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2200
2201       foreach my $key (split(/:/, $ref->{link})) {
2202         if ($key =~ /$module/) {
2203
2204           # cross reference for keys
2205           $xkeyref{ $ref->{accno} } = $key;
2206
2207           push @{ $self->{"${module}_links"}{$key} },
2208             { accno       => $ref->{accno},
2209               description => $ref->{description},
2210               taxkey      => $ref->{taxkey_id},
2211               tax_id      => $ref->{tax_id} };
2212
2213           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2214         }
2215       }
2216     }
2217   }
2218
2219   # get taxkeys and description
2220   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2221   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2222
2223   if (($module eq "AP") || ($module eq "AR")) {
2224     # get tax rates and description
2225     $query = qq|SELECT * FROM tax|;
2226     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2227   }
2228
2229   if ($self->{id}) {
2230     $query =
2231       qq|SELECT
2232            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2233            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2234            a.intnotes, a.department_id, a.amount AS oldinvtotal,
2235            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2236            c.name AS $table,
2237            d.description AS department,
2238            e.name AS employee
2239          FROM $arap a
2240          JOIN $table c ON (a.${table}_id = c.id)
2241          LEFT JOIN employee e ON (e.id = a.employee_id)
2242          LEFT JOIN department d ON (d.id = a.department_id)
2243          WHERE a.id = ?|;
2244     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2245
2246     foreach $key (keys %$ref) {
2247       $self->{$key} = $ref->{$key};
2248     }
2249
2250     my $transdate = "current_date";
2251     if ($self->{transdate}) {
2252       $transdate = $dbh->quote($self->{transdate});
2253     }
2254
2255     # now get the account numbers
2256     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2257                 FROM chart c
2258                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2259                 WHERE c.link LIKE ?
2260                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2261                     OR c.link LIKE '%_tax%')
2262                 ORDER BY c.accno|;
2263
2264     $sth = $dbh->prepare($query);
2265     do_statement($self, $sth, $query, "%$module%");
2266
2267     $self->{accounts} = "";
2268     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2269
2270       foreach my $key (split(/:/, $ref->{link})) {
2271         if ($key =~ /$module/) {
2272
2273           # cross reference for keys
2274           $xkeyref{ $ref->{accno} } = $key;
2275
2276           push @{ $self->{"${module}_links"}{$key} },
2277             { accno       => $ref->{accno},
2278               description => $ref->{description},
2279               taxkey      => $ref->{taxkey_id},
2280               tax_id      => $ref->{tax_id} };
2281
2282           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2283         }
2284       }
2285     }
2286
2287
2288     # get amounts from individual entries
2289     $query =
2290       qq|SELECT
2291            c.accno, c.description,
2292            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2293            p.projectnumber,
2294            t.rate, t.id
2295          FROM acc_trans a
2296          LEFT JOIN chart c ON (c.id = a.chart_id)
2297          LEFT JOIN project p ON (p.id = a.project_id)
2298          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2299                                     WHERE (tk.taxkey_id=a.taxkey) AND
2300                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2301                                         THEN tk.chart_id = a.chart_id
2302                                         ELSE 1 = 1
2303                                         END)
2304                                        OR (c.link='%tax%')) AND
2305                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2306          WHERE a.trans_id = ?
2307          AND a.fx_transaction = '0'
2308          ORDER BY a.oid, a.transdate|;
2309     $sth = $dbh->prepare($query);
2310     do_statement($self, $sth, $query, $self->{id});
2311
2312     # get exchangerate for currency
2313     $self->{exchangerate} =
2314       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2315     my $index = 0;
2316
2317     # store amounts in {acc_trans}{$key} for multiple accounts
2318     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2319       $ref->{exchangerate} =
2320         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2321       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2322         $index++;
2323       }
2324       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2325         $ref->{amount} *= -1;
2326       }
2327       $ref->{index} = $index;
2328
2329       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2330     }
2331
2332     $sth->finish;
2333     $query =
2334       qq|SELECT
2335            d.curr AS currencies, d.closedto, d.revtrans,
2336            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2337            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2338          FROM defaults d|;
2339     $ref = selectfirst_hashref_query($self, $dbh, $query);
2340     map { $self->{$_} = $ref->{$_} } keys %$ref;
2341
2342   } else {
2343
2344     # get date
2345     $query =
2346        qq|SELECT
2347             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2348             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2349             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2350           FROM defaults d|;
2351     $ref = selectfirst_hashref_query($self, $dbh, $query);
2352     map { $self->{$_} = $ref->{$_} } keys %$ref;
2353
2354     if ($self->{"$self->{vc}_id"}) {
2355
2356       # only setup currency
2357       ($self->{currency}) = split(/:/, $self->{currencies});
2358
2359     } else {
2360
2361       $self->lastname_used($dbh, $myconfig, $table, $module);
2362
2363       # get exchangerate for currency
2364       $self->{exchangerate} =
2365         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2366
2367     }
2368
2369   }
2370
2371   $main::lxdebug->leave_sub();
2372 }
2373
2374 sub lastname_used {
2375   $main::lxdebug->enter_sub();
2376
2377   my ($self, $dbh, $myconfig, $table, $module) = @_;
2378
2379   my $arap  = ($table eq 'customer') ? "ar" : "ap";
2380   $table = $table eq "customer" ? "customer" : "vendor";
2381   my $where = "1 = 1";
2382
2383   if ($self->{type} =~ /_order/) {
2384     $arap  = 'oe';
2385     $where = "quotation = '0'";
2386   }
2387   if ($self->{type} =~ /_quotation/) {
2388     $arap  = 'oe';
2389     $where = "quotation = '1'";
2390   }
2391
2392   my $query = qq|SELECT MAX(id) FROM $arap
2393                  WHERE $where AND ${table}_id > 0|;
2394   my ($trans_id) = selectrow_query($self, $dbh, $query);
2395
2396   $trans_id *= 1;
2397   $query =
2398     qq|SELECT
2399          a.curr, a.${table}_id, a.department_id,
2400          d.description AS department,
2401          ct.name, current_date + ct.terms AS duedate
2402        FROM $arap a
2403        LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2404        LEFT JOIN department d ON (a.department_id = d.id)
2405        WHERE a.id = ?|;
2406   ($self->{currency},   $self->{"${table}_id"}, $self->{department_id},
2407    $self->{department}, $self->{$table},        $self->{duedate})
2408     = selectrow_query($self, $dbh, $query, $trans_id);
2409
2410   $main::lxdebug->leave_sub();
2411 }
2412
2413 sub current_date {
2414   $main::lxdebug->enter_sub();
2415
2416   my ($self, $myconfig, $thisdate, $days) = @_;
2417
2418   my $dbh = $self->get_standard_dbh($myconfig);
2419   my $query;
2420
2421   $days *= 1;
2422   if ($thisdate) {
2423     my $dateformat = $myconfig->{dateformat};
2424     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2425     $thisdate = $dbh->quote($thisdate);
2426     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2427   } else {
2428     $query = qq|SELECT current_date AS thisdate|;
2429   }
2430
2431   ($thisdate) = selectrow_query($self, $dbh, $query);
2432
2433   $main::lxdebug->leave_sub();
2434
2435   return $thisdate;
2436 }
2437
2438 sub like {
2439   $main::lxdebug->enter_sub();
2440
2441   my ($self, $string) = @_;
2442
2443   if ($string !~ /%/) {
2444     $string = "%$string%";
2445   }
2446
2447   $string =~ s/\'/\'\'/g;
2448
2449   $main::lxdebug->leave_sub();
2450
2451   return $string;
2452 }
2453
2454 sub redo_rows {
2455   $main::lxdebug->enter_sub();
2456
2457   my ($self, $flds, $new, $count, $numrows) = @_;
2458
2459   my @ndx = ();
2460
2461   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } }
2462     (1 .. $count);
2463
2464   my $i = 0;
2465
2466   # fill rows
2467   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2468     $i++;
2469     $j = $item->{ndx} - 1;
2470     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2471   }
2472
2473   # delete empty rows
2474   for $i ($count + 1 .. $numrows) {
2475     map { delete $self->{"${_}_$i"} } @{$flds};
2476   }
2477
2478   $main::lxdebug->leave_sub();
2479 }
2480
2481 sub update_status {
2482   $main::lxdebug->enter_sub();
2483
2484   my ($self, $myconfig) = @_;
2485
2486   my ($i, $id);
2487
2488   my $dbh = $self->dbconnect_noauto($myconfig);
2489
2490   my $query = qq|DELETE FROM status
2491                  WHERE (formname = ?) AND (trans_id = ?)|;
2492   my $sth = prepare_query($self, $dbh, $query);
2493
2494   if ($self->{formname} =~ /(check|receipt)/) {
2495     for $i (1 .. $self->{rowcount}) {
2496       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
2497     }
2498   } else {
2499     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
2500   }
2501   $sth->finish();
2502
2503   my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
2504   my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
2505
2506   my %queued = split / /, $self->{queued};
2507   my @values;
2508
2509   if ($self->{formname} =~ /(check|receipt)/) {
2510
2511     # this is a check or receipt, add one entry for each lineitem
2512     my ($accno) = split /--/, $self->{account};
2513     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
2514                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
2515     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
2516     $sth = prepare_query($self, $dbh, $query);
2517
2518     for $i (1 .. $self->{rowcount}) {
2519       if ($self->{"checked_$i"}) {
2520         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
2521       }
2522     }
2523     $sth->finish();
2524
2525   } else {
2526     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2527                 VALUES (?, ?, ?, ?, ?)|;
2528     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
2529              $queued{$self->{formname}}, $self->{formname});
2530   }
2531
2532   $dbh->commit;
2533   $dbh->disconnect;
2534
2535   $main::lxdebug->leave_sub();
2536 }
2537
2538 sub save_status {
2539   $main::lxdebug->enter_sub();
2540
2541   my ($self, $dbh) = @_;
2542
2543   my ($query, $printed, $emailed);
2544
2545   my $formnames  = $self->{printed};
2546   my $emailforms = $self->{emailed};
2547
2548   my $query = qq|DELETE FROM status
2549                  WHERE (formname = ?) AND (trans_id = ?)|;
2550   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
2551
2552   # this only applies to the forms
2553   # checks and receipts are posted when printed or queued
2554
2555   if ($self->{queued}) {
2556     my %queued = split / /, $self->{queued};
2557
2558     foreach my $formname (keys %queued) {
2559       $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
2560       $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
2561
2562       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2563                   VALUES (?, ?, ?, ?, ?)|;
2564       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
2565
2566       $formnames  =~ s/$self->{formname}//;
2567       $emailforms =~ s/$self->{formname}//;
2568
2569     }
2570   }
2571
2572   # save printed, emailed info
2573   $formnames  =~ s/^ +//g;
2574   $emailforms =~ s/^ +//g;
2575
2576   my %status = ();
2577   map { $status{$_}{printed} = 1 } split / +/, $formnames;
2578   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
2579
2580   foreach my $formname (keys %status) {
2581     $printed = ($formnames  =~ /$self->{formname}/) ? "1" : "0";
2582     $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
2583
2584     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
2585                 VALUES (?, ?, ?, ?)|;
2586     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
2587   }
2588
2589   $main::lxdebug->leave_sub();
2590 }
2591
2592 #--- 4 locale ---#
2593 # $main::locale->text('SAVED')
2594 # $main::locale->text('DELETED')
2595 # $main::locale->text('ADDED')
2596 # $main::locale->text('PAYMENT POSTED')
2597 # $main::locale->text('POSTED')
2598 # $main::locale->text('POSTED AS NEW')
2599 # $main::locale->text('ELSE')
2600 # $main::locale->text('SAVED FOR DUNNING')
2601 # $main::locale->text('DUNNING STARTED')
2602 # $main::locale->text('PRINTED')
2603 # $main::locale->text('MAILED')
2604 # $main::locale->text('SCREENED')
2605 # $main::locale->text('CANCELED')
2606 # $main::locale->text('invoice')
2607 # $main::locale->text('proforma')
2608 # $main::locale->text('sales_order')
2609 # $main::locale->text('packing_list')
2610 # $main::locale->text('pick_list')
2611 # $main::locale->text('purchase_order')
2612 # $main::locale->text('bin_list')
2613 # $main::locale->text('sales_quotation')
2614 # $main::locale->text('request_quotation')
2615
2616 sub save_history {
2617   $main::lxdebug->enter_sub();
2618
2619   my $self = shift();
2620   my $dbh = shift();
2621
2622   if(!exists $self->{employee_id}) {
2623     &get_employee($self, $dbh);
2624   }
2625
2626   my $query =
2627    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
2628    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
2629   my @values = (conv_i($self->{id}), $self->{login},
2630                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
2631   do_query($self, $dbh, $query, @values);
2632
2633   $main::lxdebug->leave_sub();
2634 }
2635
2636 sub get_history {
2637   $main::lxdebug->enter_sub();
2638
2639   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
2640   my ($orderBy, $desc) = split(/\-\-/, $order);
2641   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
2642   my @tempArray;
2643   my $i = 0;
2644   if ($trans_id ne "") {
2645     my $query =
2646       qq|SELECT h.employee_id, h.itime::timestamp(0) AS itime, h.addition, h.what_done, emp.name, h.snumbers, h.trans_id AS id | .
2647       qq|FROM history_erp h | .
2648       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
2649       qq|WHERE trans_id = | . $trans_id
2650       . $restriction . qq| |
2651       . $order;
2652       
2653     my $sth = $dbh->prepare($query) || $self->dberror($query);
2654
2655     $sth->execute() || $self->dberror("$query");
2656
2657     while(my $hash_ref = $sth->fetchrow_hashref()) {
2658       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
2659       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
2660       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
2661       $tempArray[$i++] = $hash_ref;
2662     }
2663     $main::lxdebug->leave_sub() and return \@tempArray 
2664       if ($i > 0 && $tempArray[0] ne "");
2665   }
2666   $main::lxdebug->leave_sub();
2667   return 0;
2668 }
2669
2670 sub update_defaults {
2671   $main::lxdebug->enter_sub();
2672
2673   my ($self, $myconfig, $fld, $provided_dbh) = @_;
2674
2675   my $dbh;
2676   if ($provided_dbh) {
2677     $dbh = $provided_dbh;
2678   } else {
2679     $dbh = $self->dbconnect_noauto($myconfig);
2680   }
2681   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
2682   my $sth   = $dbh->prepare($query);
2683
2684   $sth->execute || $self->dberror($query);
2685   my ($var) = $sth->fetchrow_array;
2686   $sth->finish;
2687
2688   if ($var =~ m/\d+$/) {
2689     my $new_var  = (substr $var, $-[0]) * 1 + 1;
2690     my $len_diff = length($var) - $-[0] - length($new_var);
2691     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
2692
2693   } else {
2694     $var = $var . '1';
2695   }
2696
2697   $query = qq|UPDATE defaults SET $fld = ?|;
2698   do_query($self, $dbh, $query, $var);
2699
2700   if (!$provided_dbh) {
2701     $dbh->commit;
2702     $dbh->disconnect;
2703   }
2704
2705   $main::lxdebug->leave_sub();
2706
2707   return $var;
2708 }
2709
2710 sub update_business {
2711   $main::lxdebug->enter_sub();
2712
2713   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
2714
2715   my $dbh;
2716   if ($provided_dbh) {
2717     $dbh = $provided_dbh;
2718   } else {
2719     $dbh = $self->dbconnect_noauto($myconfig);
2720   }
2721   my $query =
2722     qq|SELECT customernumberinit FROM business
2723        WHERE id = ? FOR UPDATE|;
2724   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
2725
2726   if ($var =~ m/\d+$/) {
2727     my $new_var  = (substr $var, $-[0]) * 1 + 1;
2728     my $len_diff = length($var) - $-[0] - length($new_var);
2729     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
2730
2731   } else {
2732     $var = $var . '1';
2733   }
2734
2735   $query = qq|UPDATE business
2736               SET customernumberinit = ?
2737               WHERE id = ?|;
2738   do_query($self, $dbh, $query, $var, $business_id);
2739
2740   if (!$provided_dbh) {
2741     $dbh->commit;
2742     $dbh->disconnect;
2743   }
2744
2745   $main::lxdebug->leave_sub();
2746
2747   return $var;
2748 }
2749
2750 sub get_partsgroup {
2751   $main::lxdebug->enter_sub();
2752
2753   my ($self, $myconfig, $p) = @_;
2754
2755   my $dbh = $self->get_standard_dbh($myconfig);
2756
2757   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
2758                  FROM partsgroup pg
2759                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
2760   my @values;
2761
2762   if ($p->{searchitems} eq 'part') {
2763     $query .= qq|WHERE p.inventory_accno_id > 0|;
2764   }
2765   if ($p->{searchitems} eq 'service') {
2766     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
2767   }
2768   if ($p->{searchitems} eq 'assembly') {
2769     $query .= qq|WHERE p.assembly = '1'|;
2770   }
2771   if ($p->{searchitems} eq 'labor') {
2772     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
2773   }
2774
2775   $query .= qq|ORDER BY partsgroup|;
2776
2777   if ($p->{all}) {
2778     $query = qq|SELECT id, partsgroup FROM partsgroup
2779                 ORDER BY partsgroup|;
2780   }
2781
2782   if ($p->{language_code}) {
2783     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
2784                   t.description AS translation
2785                 FROM partsgroup pg
2786                 JOIN parts p ON (p.partsgroup_id = pg.id)
2787                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
2788                 ORDER BY translation|;
2789     @values = ($p->{language_code});
2790   }
2791
2792   $self->{all_partsgroup} = selectall_hashref_query($self, $dbh, $query, @values);
2793
2794   $main::lxdebug->leave_sub();
2795 }
2796
2797 sub get_pricegroup {
2798   $main::lxdebug->enter_sub();
2799
2800   my ($self, $myconfig, $p) = @_;
2801
2802   my $dbh = $self->get_standard_dbh($myconfig);
2803
2804   my $query = qq|SELECT p.id, p.pricegroup
2805                  FROM pricegroup p|;
2806
2807   $query .= qq| ORDER BY pricegroup|;
2808
2809   if ($p->{all}) {
2810     $query = qq|SELECT id, pricegroup FROM pricegroup
2811                 ORDER BY pricegroup|;
2812   }
2813
2814   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
2815
2816   $main::lxdebug->leave_sub();
2817 }
2818
2819 sub all_years {
2820 # usage $form->all_years($myconfig, [$dbh])
2821 # return list of all years where bookings found
2822 # (@all_years)
2823
2824   $main::lxdebug->enter_sub();
2825
2826   my ($self, $myconfig, $dbh) = @_;
2827
2828   $dbh ||= $self->get_standard_dbh($myconfig);
2829
2830   # get years
2831   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
2832                    (SELECT MAX(transdate) FROM acc_trans)|;
2833   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
2834
2835   if ($myconfig->{dateformat} =~ /^yy/) {
2836     ($startdate) = split /\W/, $startdate;
2837     ($enddate) = split /\W/, $enddate;
2838   } else {
2839     (@_) = split /\W/, $startdate;
2840     $startdate = $_[2];
2841     (@_) = split /\W/, $enddate;
2842     $enddate = $_[2];
2843   }
2844
2845   my @all_years;
2846   $startdate = substr($startdate,0,4);
2847   $enddate = substr($enddate,0,4);
2848
2849   while ($enddate >= $startdate) {
2850     push @all_years, $enddate--;
2851   }
2852
2853   return @all_years;
2854
2855   $main::lxdebug->leave_sub();
2856 }
2857
2858 1;