7e5c8736db5c5125792284ce23f4f451b32dae2e
[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   map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2) } keys %amounts;
1396
1397   if ($self->{"language_id"}) {
1398     $query =
1399       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1400       qq|FROM translation_payment_terms t | .
1401       qq|LEFT JOIN language l ON t.language_id = l.id | .
1402       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1403     my ($description_long, $output_numberformat, $output_dateformat,
1404       $output_longdates) =
1405       selectrow_query($self, $dbh, $query,
1406                       $self->{"language_id"}, $self->{"payment_id"});
1407
1408     $self->{payment_terms} = $description_long if ($description_long);
1409
1410     if ($output_dateformat) {
1411       foreach my $key (qw(netto_date skonto_date)) {
1412         $self->{$key} =
1413           $main::locale->reformat_date($myconfig, $self->{$key},
1414                                        $output_dateformat,
1415                                        $output_longdates);
1416       }
1417     }
1418
1419     if ($output_numberformat &&
1420         ($output_numberformat ne $myconfig->{"numberformat"})) {
1421       my $saved_numberformat = $myconfig->{"numberformat"};
1422       $myconfig->{"numberformat"} = $output_numberformat;
1423       map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1424       $myconfig->{"numberformat"} = $saved_numberformat;
1425     }
1426   }
1427
1428   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1429   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1430   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1431   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1432   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1433   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1434   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1435
1436   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1437
1438   $main::lxdebug->leave_sub();
1439
1440 }
1441
1442 sub get_template_language {
1443   $main::lxdebug->enter_sub();
1444
1445   my ($self, $myconfig) = @_;
1446
1447   my $template_code = "";
1448
1449   if ($self->{language_id}) {
1450     my $dbh = $self->get_standard_dbh($myconfig);
1451     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1452     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1453   }
1454
1455   $main::lxdebug->leave_sub();
1456
1457   return $template_code;
1458 }
1459
1460 sub get_printer_code {
1461   $main::lxdebug->enter_sub();
1462
1463   my ($self, $myconfig) = @_;
1464
1465   my $template_code = "";
1466
1467   if ($self->{printer_id}) {
1468     my $dbh = $self->get_standard_dbh($myconfig);
1469     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1470     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1471   }
1472
1473   $main::lxdebug->leave_sub();
1474
1475   return $template_code;
1476 }
1477
1478 sub get_shipto {
1479   $main::lxdebug->enter_sub();
1480
1481   my ($self, $myconfig) = @_;
1482
1483   my $template_code = "";
1484
1485   if ($self->{shipto_id}) {
1486     my $dbh = $self->get_standard_dbh($myconfig);
1487     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1488     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1489     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1490   }
1491
1492   $main::lxdebug->leave_sub();
1493 }
1494
1495 sub add_shipto {
1496   $main::lxdebug->enter_sub();
1497
1498   my ($self, $dbh, $id, $module) = @_;
1499
1500   my $shipto;
1501   my @values;
1502
1503   foreach my $item (qw(name department_1 department_2 street zipcode city country
1504                        contact phone fax email)) {
1505     if ($self->{"shipto$item"}) {
1506       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1507     }
1508     push(@values, $self->{"shipto${item}"});
1509   }
1510
1511   if ($shipto) {
1512     if ($self->{shipto_id}) {
1513       my $query = qq|UPDATE shipto set
1514                        shiptoname = ?,
1515                        shiptodepartment_1 = ?,
1516                        shiptodepartment_2 = ?,
1517                        shiptostreet = ?,
1518                        shiptozipcode = ?,
1519                        shiptocity = ?,
1520                        shiptocountry = ?,
1521                        shiptocontact = ?,
1522                        shiptophone = ?,
1523                        shiptofax = ?,
1524                        shiptoemail = ?
1525                      WHERE shipto_id = ?|;
1526       do_query($self, $dbh, $query, @values, $self->{shipto_id});
1527     } else {
1528       my $query = qq|SELECT * FROM shipto
1529                      WHERE shiptoname = ? AND
1530                        shiptodepartment_1 = ? AND
1531                        shiptodepartment_2 = ? AND
1532                        shiptostreet = ? AND
1533                        shiptozipcode = ? AND
1534                        shiptocity = ? AND
1535                        shiptocountry = ? AND
1536                        shiptocontact = ? AND
1537                        shiptophone = ? AND
1538                        shiptofax = ? AND
1539                        shiptoemail = ? AND
1540                        module = ? AND 
1541                        trans_id = ?|;
1542       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1543       if(!$insert_check){
1544         $query =
1545           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1546                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
1547                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
1548              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1549         do_query($self, $dbh, $query, $id, @values, $module);
1550       }
1551     }
1552   }
1553
1554   $main::lxdebug->leave_sub();
1555 }
1556
1557 sub get_employee {
1558   $main::lxdebug->enter_sub();
1559
1560   my ($self, $dbh) = @_;
1561
1562   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1563   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1564   $self->{"employee_id"} *= 1;
1565
1566   $main::lxdebug->leave_sub();
1567 }
1568
1569 sub get_salesman {
1570   $main::lxdebug->enter_sub();
1571
1572   my ($self, $myconfig, $salesman_id) = @_;
1573
1574   $main::lxdebug->leave_sub() and return unless $salesman_id;
1575
1576   my $dbh = $self->get_standard_dbh($myconfig);
1577
1578   my ($login) =
1579     selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|,
1580                     $salesman_id);
1581
1582   if ($login) {
1583     my $user = new User($main::memberfile, $login);
1584     map({ $self->{"salesman_$_"} = $user->{$_}; }
1585         qw(address businessnumber co_ustid company duns email fax name
1586            taxnumber tel));
1587     $self->{salesman_login} = $login;
1588
1589     $self->{salesman_name} = $login
1590       if ($self->{salesman_name} eq "");
1591
1592     map({ $self->{"salesman_$_"} =~ s/\\n/\n/g; } qw(address company));
1593   }
1594
1595   $main::lxdebug->leave_sub();
1596 }
1597
1598 sub get_duedate {
1599   $main::lxdebug->enter_sub();
1600
1601   my ($self, $myconfig) = @_;
1602
1603   my $dbh = $self->get_standard_dbh($myconfig);
1604   my $query = qq|SELECT current_date + terms_netto FROM payment_terms WHERE id = ?|;
1605   ($self->{duedate}) = selectrow_query($self, $dbh, $query, $self->{payment_id});
1606
1607   $main::lxdebug->leave_sub();
1608 }
1609
1610 sub _get_contacts {
1611   $main::lxdebug->enter_sub();
1612
1613   my ($self, $dbh, $id, $key) = @_;
1614
1615   $key = "all_contacts" unless ($key);
1616
1617   my $query =
1618     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
1619     qq|FROM contacts | .
1620     qq|WHERE cp_cv_id = ? | .
1621     qq|ORDER BY lower(cp_name)|;
1622
1623   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
1624
1625   $main::lxdebug->leave_sub();
1626 }
1627
1628 sub _get_projects {
1629   $main::lxdebug->enter_sub();
1630
1631   my ($self, $dbh, $key) = @_;
1632
1633   my ($all, $old_id, $where, @values);
1634
1635   if (ref($key) eq "HASH") {
1636     my $params = $key;
1637
1638     $key = "ALL_PROJECTS";
1639
1640     foreach my $p (keys(%{$params})) {
1641       if ($p eq "all") {
1642         $all = $params->{$p};
1643       } elsif ($p eq "old_id") {
1644         $old_id = $params->{$p};
1645       } elsif ($p eq "key") {
1646         $key = $params->{$p};
1647       }
1648     }
1649   }
1650
1651   if (!$all) {
1652     $where = "WHERE active ";
1653     if ($old_id) {
1654       if (ref($old_id) eq "ARRAY") {
1655         my @ids = grep({ $_ } @{$old_id});
1656         if (@ids) {
1657           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
1658           push(@values, @ids);
1659         }
1660       } else {
1661         $where .= " OR (id = ?) ";
1662         push(@values, $old_id);
1663       }
1664     }
1665   }
1666
1667   my $query =
1668     qq|SELECT id, projectnumber, description, active | .
1669     qq|FROM project | .
1670     $where .
1671     qq|ORDER BY lower(projectnumber)|;
1672
1673   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
1674
1675   $main::lxdebug->leave_sub();
1676 }
1677
1678 sub _get_shipto {
1679   $main::lxdebug->enter_sub();
1680
1681   my ($self, $dbh, $vc_id, $key) = @_;
1682
1683   $key = "all_shipto" unless ($key);
1684
1685   # get shipping addresses
1686   my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
1687
1688   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
1689
1690   $main::lxdebug->leave_sub();
1691 }
1692
1693 sub _get_printers {
1694   $main::lxdebug->enter_sub();
1695
1696   my ($self, $dbh, $key) = @_;
1697
1698   $key = "all_printers" unless ($key);
1699
1700   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
1701
1702   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1703
1704   $main::lxdebug->leave_sub();
1705 }
1706
1707 sub _get_charts {
1708   $main::lxdebug->enter_sub();
1709
1710   my ($self, $dbh, $params) = @_;
1711
1712   $key = $params->{key};
1713   $key = "all_charts" unless ($key);
1714
1715   my $transdate = quote_db_date($params->{transdate});
1716
1717   my $query =
1718     qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
1719     qq|FROM chart c | .
1720     qq|LEFT JOIN taxkeys tk ON | .
1721     qq|(tk.id = (SELECT id FROM taxkeys | .
1722     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
1723     qq|          ORDER BY startdate DESC LIMIT 1)) | .
1724     qq|ORDER BY c.accno|;
1725
1726   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1727
1728   $main::lxdebug->leave_sub();
1729 }
1730
1731 sub _get_taxcharts {
1732   $main::lxdebug->enter_sub();
1733
1734   my ($self, $dbh, $key) = @_;
1735
1736   $key = "all_taxcharts" unless ($key);
1737
1738   my $query = qq|SELECT * FROM tax ORDER BY taxkey|;
1739
1740   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1741
1742   $main::lxdebug->leave_sub();
1743 }
1744
1745 sub _get_taxzones {
1746   $main::lxdebug->enter_sub();
1747
1748   my ($self, $dbh, $key) = @_;
1749
1750   $key = "all_taxzones" unless ($key);
1751
1752   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
1753
1754   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1755
1756   $main::lxdebug->leave_sub();
1757 }
1758
1759 sub _get_employees {
1760   $main::lxdebug->enter_sub();
1761
1762   my ($self, $dbh, $default_key, $key) = @_;
1763
1764   $key = $default_key unless ($key);
1765   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY name|);
1766
1767   $main::lxdebug->leave_sub();
1768 }
1769
1770 sub _get_business_types {
1771   $main::lxdebug->enter_sub();
1772
1773   my ($self, $dbh, $key) = @_;
1774
1775   $key = "all_business_types" unless ($key);
1776   $self->{$key} =
1777     selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
1778
1779   $main::lxdebug->leave_sub();
1780 }
1781
1782 sub _get_languages {
1783   $main::lxdebug->enter_sub();
1784
1785   my ($self, $dbh, $key) = @_;
1786
1787   $key = "all_languages" unless ($key);
1788
1789   my $query = qq|SELECT * FROM language ORDER BY id|;
1790
1791   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1792
1793   $main::lxdebug->leave_sub();
1794 }
1795
1796 sub _get_dunning_configs {
1797   $main::lxdebug->enter_sub();
1798
1799   my ($self, $dbh, $key) = @_;
1800
1801   $key = "all_dunning_configs" unless ($key);
1802
1803   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
1804
1805   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1806
1807   $main::lxdebug->leave_sub();
1808 }
1809
1810 sub _get_currencies {
1811 $main::lxdebug->enter_sub();
1812
1813   my ($self, $dbh, $key) = @_;
1814
1815   $key = "all_currencies" unless ($key);
1816
1817   my $query = qq|SELECT curr AS currency FROM defaults|;
1818  
1819   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
1820
1821   $main::lxdebug->leave_sub();
1822 }
1823
1824 sub _get_payments {
1825 $main::lxdebug->enter_sub();
1826
1827   my ($self, $dbh, $key) = @_;
1828
1829   $key = "all_payments" unless ($key);
1830
1831   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
1832  
1833   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1834
1835   $main::lxdebug->leave_sub();
1836 }
1837
1838 sub _get_customers {
1839   $main::lxdebug->enter_sub();
1840
1841   my ($self, $dbh, $key) = @_;
1842
1843   $key = "all_customers" unless ($key);
1844
1845   my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name|;
1846
1847   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1848
1849   $main::lxdebug->leave_sub();
1850 }
1851
1852 sub _get_vendors {
1853   $main::lxdebug->enter_sub();
1854
1855   my ($self, $dbh, $key) = @_;
1856
1857   $key = "all_vendors" unless ($key);
1858
1859   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
1860
1861   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1862
1863   $main::lxdebug->leave_sub();
1864 }
1865
1866 sub _get_departments {
1867   $main::lxdebug->enter_sub();
1868
1869   my ($self, $dbh, $key) = @_;
1870
1871   $key = "all_departments" unless ($key);
1872
1873   my $query = qq|SELECT * FROM department ORDER BY description|;
1874
1875   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1876
1877   $main::lxdebug->leave_sub();
1878 }
1879
1880 sub get_lists {
1881   $main::lxdebug->enter_sub();
1882
1883   my $self = shift;
1884   my %params = @_;
1885
1886   my $dbh = $self->get_standard_dbh(\%main::myconfig);
1887   my ($sth, $query, $ref);
1888
1889   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
1890   my $vc_id = $self->{"${vc}_id"};
1891
1892   if ($params{"contacts"}) {
1893     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
1894   }
1895
1896   if ($params{"shipto"}) {
1897     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
1898   }
1899
1900   if ($params{"projects"} || $params{"all_projects"}) {
1901     $self->_get_projects($dbh, $params{"all_projects"} ?
1902                          $params{"all_projects"} : $params{"projects"},
1903                          $params{"all_projects"} ? 1 : 0);
1904   }
1905
1906   if ($params{"printers"}) {
1907     $self->_get_printers($dbh, $params{"printers"});
1908   }
1909
1910   if ($params{"languages"}) {
1911     $self->_get_languages($dbh, $params{"languages"});
1912   }
1913
1914   if ($params{"charts"}) {
1915     $self->_get_charts($dbh, $params{"charts"});
1916   }
1917
1918   if ($params{"taxcharts"}) {
1919     $self->_get_taxcharts($dbh, $params{"taxcharts"});
1920   }
1921
1922   if ($params{"taxzones"}) {
1923     $self->_get_taxzones($dbh, $params{"taxzones"});
1924   }
1925
1926   if ($params{"employees"}) {
1927     $self->_get_employees($dbh, "all_employees", $params{"employees"});
1928   }
1929   
1930   if ($params{"salesmen"}) {
1931     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
1932   }
1933
1934   if ($params{"business_types"}) {
1935     $self->_get_business_types($dbh, $params{"business_types"});
1936   }
1937
1938   if ($params{"dunning_configs"}) {
1939     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
1940   }
1941   
1942   if($params{"currencies"}) {
1943     $self->_get_currencies($dbh, $params{"currencies"});
1944   }
1945   
1946   if($params{"customers"}) {
1947     $self->_get_customers($dbh, $params{"customers"});
1948   }
1949   
1950   if($params{"vendors"}) {
1951     $self->_get_vendors($dbh, $params{"vendors"});
1952   }
1953   
1954   if($params{"payments"}) {
1955     $self->_get_payments($dbh, $params{"payments"});
1956   }
1957
1958   if($params{"departments"}) {
1959     $self->_get_departments($dbh, $params{"departments"});
1960   }
1961
1962   $main::lxdebug->leave_sub();
1963 }
1964
1965 # this sub gets the id and name from $table
1966 sub get_name {
1967   $main::lxdebug->enter_sub();
1968
1969   my ($self, $myconfig, $table) = @_;
1970
1971   # connect to database
1972   my $dbh = $self->get_standard_dbh($myconfig);
1973
1974   $table = $table eq "customer" ? "customer" : "vendor";
1975   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
1976
1977   my ($query, @values);
1978
1979   if (!$self->{openinvoices}) {
1980     my $where;
1981     if ($self->{customernumber} ne "") {
1982       $where = qq|(vc.customernumber ILIKE ?)|;
1983       push(@values, '%' . $self->{customernumber} . '%');
1984     } else {
1985       $where = qq|(vc.name ILIKE ?)|;
1986       push(@values, '%' . $self->{$table} . '%');
1987     }
1988
1989     $query =
1990       qq~SELECT vc.id, vc.name,
1991            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
1992          FROM $table vc
1993          WHERE $where AND (NOT vc.obsolete)
1994          ORDER BY vc.name~;
1995   } else {
1996     $query =
1997       qq~SELECT DISTINCT vc.id, vc.name,
1998            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
1999          FROM $arap a
2000          JOIN $table vc ON (a.${table}_id = vc.id)
2001          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2002          ORDER BY vc.name~;
2003     push(@values, '%' . $self->{$table} . '%');
2004   }
2005
2006   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2007
2008   $main::lxdebug->leave_sub();
2009
2010   return scalar(@{ $self->{name_list} });
2011 }
2012
2013 # the selection sub is used in the AR, AP, IS, IR and OE module
2014 #
2015 sub all_vc {
2016   $main::lxdebug->enter_sub();
2017
2018   my ($self, $myconfig, $table, $module) = @_;
2019
2020   my $ref;
2021   my $dbh = $self->get_standard_dbh($myconfig);
2022
2023   $table = $table eq "customer" ? "customer" : "vendor";
2024
2025   my $query = qq|SELECT count(*) FROM $table|;
2026   my ($count) = selectrow_query($self, $dbh, $query);
2027
2028   # build selection list
2029   if ($count < $myconfig->{vclimit}) {
2030     $query = qq|SELECT id, name, salesman_id
2031                 FROM $table WHERE NOT obsolete
2032                 ORDER BY name|;
2033     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2034   }
2035
2036   # get self
2037   $self->get_employee($dbh);
2038
2039   # setup sales contacts
2040   $query = qq|SELECT e.id, e.name
2041               FROM employee e
2042               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2043   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2044
2045   # this is for self
2046   push(@{ $self->{all_employees} },
2047        { id   => $self->{employee_id},
2048          name => $self->{employee} });
2049
2050   # sort the whole thing
2051   @{ $self->{all_employees} } =
2052     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2053
2054   if ($module eq 'AR') {
2055
2056     # prepare query for departments
2057     $query = qq|SELECT id, description
2058                 FROM department
2059                 WHERE role = 'P'
2060                 ORDER BY description|;
2061
2062   } else {
2063     $query = qq|SELECT id, description
2064                 FROM department
2065                 ORDER BY description|;
2066   }
2067
2068   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2069
2070   # get languages
2071   $query = qq|SELECT id, description
2072               FROM language
2073               ORDER BY id|;
2074
2075   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2076
2077   # get printer
2078   $query = qq|SELECT printer_description, id
2079               FROM printers
2080               ORDER BY printer_description|;
2081
2082   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2083
2084   # get payment terms
2085   $query = qq|SELECT id, description
2086               FROM payment_terms
2087               ORDER BY sortkey|;
2088
2089   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2090
2091   $main::lxdebug->leave_sub();
2092 }
2093
2094 sub language_payment {
2095   $main::lxdebug->enter_sub();
2096
2097   my ($self, $myconfig) = @_;
2098
2099   my $dbh = $self->get_standard_dbh($myconfig);
2100   # get languages
2101   my $query = qq|SELECT id, description
2102                  FROM language
2103                  ORDER BY id|;
2104
2105   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2106
2107   # get printer
2108   $query = qq|SELECT printer_description, id
2109               FROM printers
2110               ORDER BY printer_description|;
2111
2112   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2113
2114   # get payment terms
2115   $query = qq|SELECT id, description
2116               FROM payment_terms
2117               ORDER BY sortkey|;
2118
2119   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2120
2121   # get buchungsgruppen
2122   $query = qq|SELECT id, description
2123               FROM buchungsgruppen|;
2124
2125   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2126
2127   $main::lxdebug->leave_sub();
2128 }
2129
2130 # this is only used for reports
2131 sub all_departments {
2132   $main::lxdebug->enter_sub();
2133
2134   my ($self, $myconfig, $table) = @_;
2135
2136   my $dbh = $self->get_standard_dbh($myconfig);
2137   my $where;
2138
2139   if ($table eq 'customer') {
2140     $where = "WHERE role = 'P' ";
2141   }
2142
2143   my $query = qq|SELECT id, description
2144                  FROM department
2145                  $where
2146                  ORDER BY description|;
2147   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2148
2149   delete($self->{all_departments}) unless (@{ $self->{all_departments} });
2150
2151   $main::lxdebug->leave_sub();
2152 }
2153
2154 sub create_links {
2155   $main::lxdebug->enter_sub();
2156
2157   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2158
2159   my ($fld, $arap);
2160   if ($table eq "customer") {
2161     $fld = "buy";
2162     $arap = "ar";
2163   } else {
2164     $table = "vendor";
2165     $fld = "sell";
2166     $arap = "ap";
2167   }
2168
2169   $self->all_vc($myconfig, $table, $module);
2170
2171   # get last customers or vendors
2172   my ($query, $sth, $ref);
2173
2174   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2175   my %xkeyref = ();
2176
2177   if (!$self->{id}) {
2178
2179     my $transdate = "current_date";
2180     if ($self->{transdate}) {
2181       $transdate = $dbh->quote($self->{transdate});
2182     }
2183
2184     # now get the account numbers
2185     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2186                 FROM chart c, taxkeys tk
2187                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2188                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2189                 ORDER BY c.accno|;
2190
2191     $sth = $dbh->prepare($query);
2192
2193     do_statement($self, $sth, $query, '%' . $module . '%');
2194
2195     $self->{accounts} = "";
2196     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2197
2198       foreach my $key (split(/:/, $ref->{link})) {
2199         if ($key =~ /$module/) {
2200
2201           # cross reference for keys
2202           $xkeyref{ $ref->{accno} } = $key;
2203
2204           push @{ $self->{"${module}_links"}{$key} },
2205             { accno       => $ref->{accno},
2206               description => $ref->{description},
2207               taxkey      => $ref->{taxkey_id},
2208               tax_id      => $ref->{tax_id} };
2209
2210           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2211         }
2212       }
2213     }
2214   }
2215
2216   # get taxkeys and description
2217   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2218   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2219
2220   if (($module eq "AP") || ($module eq "AR")) {
2221     # get tax rates and description
2222     $query = qq|SELECT * FROM tax|;
2223     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2224   }
2225
2226   if ($self->{id}) {
2227     $query =
2228       qq|SELECT
2229            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2230            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2231            a.intnotes, a.department_id, a.amount AS oldinvtotal,
2232            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2233            c.name AS $table,
2234            d.description AS department,
2235            e.name AS employee
2236          FROM $arap a
2237          JOIN $table c ON (a.${table}_id = c.id)
2238          LEFT JOIN employee e ON (e.id = a.employee_id)
2239          LEFT JOIN department d ON (d.id = a.department_id)
2240          WHERE a.id = ?|;
2241     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2242
2243     foreach $key (keys %$ref) {
2244       $self->{$key} = $ref->{$key};
2245     }
2246
2247     my $transdate = "current_date";
2248     if ($self->{transdate}) {
2249       $transdate = $dbh->quote($self->{transdate});
2250     }
2251
2252     # now get the account numbers
2253     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2254                 FROM chart c
2255                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2256                 WHERE c.link LIKE ?
2257                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2258                     OR c.link LIKE '%_tax%')
2259                 ORDER BY c.accno|;
2260
2261     $sth = $dbh->prepare($query);
2262     do_statement($self, $sth, $query, "%$module%");
2263
2264     $self->{accounts} = "";
2265     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2266
2267       foreach my $key (split(/:/, $ref->{link})) {
2268         if ($key =~ /$module/) {
2269
2270           # cross reference for keys
2271           $xkeyref{ $ref->{accno} } = $key;
2272
2273           push @{ $self->{"${module}_links"}{$key} },
2274             { accno       => $ref->{accno},
2275               description => $ref->{description},
2276               taxkey      => $ref->{taxkey_id},
2277               tax_id      => $ref->{tax_id} };
2278
2279           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2280         }
2281       }
2282     }
2283
2284
2285     # get amounts from individual entries
2286     $query =
2287       qq|SELECT
2288            c.accno, c.description,
2289            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2290            p.projectnumber,
2291            t.rate, t.id
2292          FROM acc_trans a
2293          LEFT JOIN chart c ON (c.id = a.chart_id)
2294          LEFT JOIN project p ON (p.id = a.project_id)
2295          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2296                                     WHERE (tk.taxkey_id=a.taxkey) AND
2297                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2298                                         THEN tk.chart_id = a.chart_id
2299                                         ELSE 1 = 1
2300                                         END)
2301                                        OR (c.link='%tax%')) AND
2302                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2303          WHERE a.trans_id = ?
2304          AND a.fx_transaction = '0'
2305          ORDER BY a.oid, a.transdate|;
2306     $sth = $dbh->prepare($query);
2307     do_statement($self, $sth, $query, $self->{id});
2308
2309     # get exchangerate for currency
2310     $self->{exchangerate} =
2311       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2312     my $index = 0;
2313
2314     # store amounts in {acc_trans}{$key} for multiple accounts
2315     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2316       $ref->{exchangerate} =
2317         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2318       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2319         $index++;
2320       }
2321       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2322         $ref->{amount} *= -1;
2323       }
2324       $ref->{index} = $index;
2325
2326       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2327     }
2328
2329     $sth->finish;
2330     $query =
2331       qq|SELECT
2332            d.curr AS currencies, d.closedto, d.revtrans,
2333            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2334            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2335          FROM defaults d|;
2336     $ref = selectfirst_hashref_query($self, $dbh, $query);
2337     map { $self->{$_} = $ref->{$_} } keys %$ref;
2338
2339   } else {
2340
2341     # get date
2342     $query =
2343        qq|SELECT
2344             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2345             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2346             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2347           FROM defaults d|;
2348     $ref = selectfirst_hashref_query($self, $dbh, $query);
2349     map { $self->{$_} = $ref->{$_} } keys %$ref;
2350
2351     if ($self->{"$self->{vc}_id"}) {
2352
2353       # only setup currency
2354       ($self->{currency}) = split(/:/, $self->{currencies});
2355
2356     } else {
2357
2358       $self->lastname_used($dbh, $myconfig, $table, $module);
2359
2360       # get exchangerate for currency
2361       $self->{exchangerate} =
2362         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2363
2364     }
2365
2366   }
2367
2368   $main::lxdebug->leave_sub();
2369 }
2370
2371 sub lastname_used {
2372   $main::lxdebug->enter_sub();
2373
2374   my ($self, $dbh, $myconfig, $table, $module) = @_;
2375
2376   my $arap  = ($table eq 'customer') ? "ar" : "ap";
2377   $table = $table eq "customer" ? "customer" : "vendor";
2378   my $where = "1 = 1";
2379
2380   if ($self->{type} =~ /_order/) {
2381     $arap  = 'oe';
2382     $where = "quotation = '0'";
2383   }
2384   if ($self->{type} =~ /_quotation/) {
2385     $arap  = 'oe';
2386     $where = "quotation = '1'";
2387   }
2388
2389   my $query = qq|SELECT MAX(id) FROM $arap
2390                  WHERE $where AND ${table}_id > 0|;
2391   my ($trans_id) = selectrow_query($self, $dbh, $query);
2392
2393   $trans_id *= 1;
2394   $query =
2395     qq|SELECT
2396          a.curr, a.${table}_id, a.department_id,
2397          d.description AS department,
2398          ct.name, current_date + ct.terms AS duedate
2399        FROM $arap a
2400        LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2401        LEFT JOIN department d ON (a.department_id = d.id)
2402        WHERE a.id = ?|;
2403   ($self->{currency},   $self->{"${table}_id"}, $self->{department_id},
2404    $self->{department}, $self->{$table},        $self->{duedate})
2405     = selectrow_query($self, $dbh, $query, $trans_id);
2406
2407   $main::lxdebug->leave_sub();
2408 }
2409
2410 sub current_date {
2411   $main::lxdebug->enter_sub();
2412
2413   my ($self, $myconfig, $thisdate, $days) = @_;
2414
2415   my $dbh = $self->get_standard_dbh($myconfig);
2416   my $query;
2417
2418   $days *= 1;
2419   if ($thisdate) {
2420     my $dateformat = $myconfig->{dateformat};
2421     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2422     $thisdate = $dbh->quote($thisdate);
2423     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2424   } else {
2425     $query = qq|SELECT current_date AS thisdate|;
2426   }
2427
2428   ($thisdate) = selectrow_query($self, $dbh, $query);
2429
2430   $main::lxdebug->leave_sub();
2431
2432   return $thisdate;
2433 }
2434
2435 sub like {
2436   $main::lxdebug->enter_sub();
2437
2438   my ($self, $string) = @_;
2439
2440   if ($string !~ /%/) {
2441     $string = "%$string%";
2442   }
2443
2444   $string =~ s/\'/\'\'/g;
2445
2446   $main::lxdebug->leave_sub();
2447
2448   return $string;
2449 }
2450
2451 sub redo_rows {
2452   $main::lxdebug->enter_sub();
2453
2454   my ($self, $flds, $new, $count, $numrows) = @_;
2455
2456   my @ndx = ();
2457
2458   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } }
2459     (1 .. $count);
2460
2461   my $i = 0;
2462
2463   # fill rows
2464   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2465     $i++;
2466     $j = $item->{ndx} - 1;
2467     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2468   }
2469
2470   # delete empty rows
2471   for $i ($count + 1 .. $numrows) {
2472     map { delete $self->{"${_}_$i"} } @{$flds};
2473   }
2474
2475   $main::lxdebug->leave_sub();
2476 }
2477
2478 sub update_status {
2479   $main::lxdebug->enter_sub();
2480
2481   my ($self, $myconfig) = @_;
2482
2483   my ($i, $id);
2484
2485   my $dbh = $self->dbconnect_noauto($myconfig);
2486
2487   my $query = qq|DELETE FROM status
2488                  WHERE (formname = ?) AND (trans_id = ?)|;
2489   my $sth = prepare_query($self, $dbh, $query);
2490
2491   if ($self->{formname} =~ /(check|receipt)/) {
2492     for $i (1 .. $self->{rowcount}) {
2493       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
2494     }
2495   } else {
2496     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
2497   }
2498   $sth->finish();
2499
2500   my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
2501   my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
2502
2503   my %queued = split / /, $self->{queued};
2504   my @values;
2505
2506   if ($self->{formname} =~ /(check|receipt)/) {
2507
2508     # this is a check or receipt, add one entry for each lineitem
2509     my ($accno) = split /--/, $self->{account};
2510     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
2511                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
2512     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
2513     $sth = prepare_query($self, $dbh, $query);
2514
2515     for $i (1 .. $self->{rowcount}) {
2516       if ($self->{"checked_$i"}) {
2517         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
2518       }
2519     }
2520     $sth->finish();
2521
2522   } else {
2523     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2524                 VALUES (?, ?, ?, ?, ?)|;
2525     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
2526              $queued{$self->{formname}}, $self->{formname});
2527   }
2528
2529   $dbh->commit;
2530   $dbh->disconnect;
2531
2532   $main::lxdebug->leave_sub();
2533 }
2534
2535 sub save_status {
2536   $main::lxdebug->enter_sub();
2537
2538   my ($self, $dbh) = @_;
2539
2540   my ($query, $printed, $emailed);
2541
2542   my $formnames  = $self->{printed};
2543   my $emailforms = $self->{emailed};
2544
2545   my $query = qq|DELETE FROM status
2546                  WHERE (formname = ?) AND (trans_id = ?)|;
2547   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
2548
2549   # this only applies to the forms
2550   # checks and receipts are posted when printed or queued
2551
2552   if ($self->{queued}) {
2553     my %queued = split / /, $self->{queued};
2554
2555     foreach my $formname (keys %queued) {
2556       $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
2557       $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
2558
2559       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2560                   VALUES (?, ?, ?, ?, ?)|;
2561       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
2562
2563       $formnames  =~ s/$self->{formname}//;
2564       $emailforms =~ s/$self->{formname}//;
2565
2566     }
2567   }
2568
2569   # save printed, emailed info
2570   $formnames  =~ s/^ +//g;
2571   $emailforms =~ s/^ +//g;
2572
2573   my %status = ();
2574   map { $status{$_}{printed} = 1 } split / +/, $formnames;
2575   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
2576
2577   foreach my $formname (keys %status) {
2578     $printed = ($formnames  =~ /$self->{formname}/) ? "1" : "0";
2579     $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
2580
2581     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
2582                 VALUES (?, ?, ?, ?)|;
2583     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
2584   }
2585
2586   $main::lxdebug->leave_sub();
2587 }
2588
2589 #--- 4 locale ---#
2590 # $main::locale->text('SAVED')
2591 # $main::locale->text('DELETED')
2592 # $main::locale->text('ADDED')
2593 # $main::locale->text('PAYMENT POSTED')
2594 # $main::locale->text('POSTED')
2595 # $main::locale->text('POSTED AS NEW')
2596 # $main::locale->text('ELSE')
2597 # $main::locale->text('SAVED FOR DUNNING')
2598 # $main::locale->text('DUNNING STARTED')
2599 # $main::locale->text('PRINTED')
2600 # $main::locale->text('MAILED')
2601 # $main::locale->text('SCREENED')
2602 # $main::locale->text('CANCELED')
2603 # $main::locale->text('invoice')
2604 # $main::locale->text('proforma')
2605 # $main::locale->text('sales_order')
2606 # $main::locale->text('packing_list')
2607 # $main::locale->text('pick_list')
2608 # $main::locale->text('purchase_order')
2609 # $main::locale->text('bin_list')
2610 # $main::locale->text('sales_quotation')
2611 # $main::locale->text('request_quotation')
2612
2613 sub save_history {
2614   $main::lxdebug->enter_sub();
2615
2616   my $self = shift();
2617   my $dbh = shift();
2618
2619   if(!exists $self->{employee_id}) {
2620     &get_employee($self, $dbh);
2621   }
2622
2623   my $query =
2624    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
2625    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
2626   my @values = (conv_i($self->{id}), $self->{login},
2627                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
2628   do_query($self, $dbh, $query, @values);
2629
2630   $main::lxdebug->leave_sub();
2631 }
2632
2633 sub get_history {
2634   $main::lxdebug->enter_sub();
2635
2636   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
2637   my ($orderBy, $desc) = split(/\-\-/, $order);
2638   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
2639   my @tempArray;
2640   my $i = 0;
2641   if ($trans_id ne "") {
2642     my $query =
2643       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 | .
2644       qq|FROM history_erp h | .
2645       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
2646       qq|WHERE trans_id = | . $trans_id
2647       . $restriction . qq| |
2648       . $order;
2649       
2650     my $sth = $dbh->prepare($query) || $self->dberror($query);
2651
2652     $sth->execute() || $self->dberror("$query");
2653
2654     while(my $hash_ref = $sth->fetchrow_hashref()) {
2655       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
2656       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
2657       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
2658       $tempArray[$i++] = $hash_ref;
2659     }
2660     $main::lxdebug->leave_sub() and return \@tempArray 
2661       if ($i > 0 && $tempArray[0] ne "");
2662   }
2663   $main::lxdebug->leave_sub();
2664   return 0;
2665 }
2666
2667 sub update_defaults {
2668   $main::lxdebug->enter_sub();
2669
2670   my ($self, $myconfig, $fld, $provided_dbh) = @_;
2671
2672   my $dbh;
2673   if ($provided_dbh) {
2674     $dbh = $provided_dbh;
2675   } else {
2676     $dbh = $self->dbconnect_noauto($myconfig);
2677   }
2678   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
2679   my $sth   = $dbh->prepare($query);
2680
2681   $sth->execute || $self->dberror($query);
2682   my ($var) = $sth->fetchrow_array;
2683   $sth->finish;
2684
2685   if ($var =~ m/\d+$/) {
2686     my $new_var  = (substr $var, $-[0]) * 1 + 1;
2687     my $len_diff = length($var) - $-[0] - length($new_var);
2688     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
2689
2690   } else {
2691     $var = $var . '1';
2692   }
2693
2694   $query = qq|UPDATE defaults SET $fld = ?|;
2695   do_query($self, $dbh, $query, $var);
2696
2697   if (!$provided_dbh) {
2698     $dbh->commit;
2699     $dbh->disconnect;
2700   }
2701
2702   $main::lxdebug->leave_sub();
2703
2704   return $var;
2705 }
2706
2707 sub update_business {
2708   $main::lxdebug->enter_sub();
2709
2710   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
2711
2712   my $dbh;
2713   if ($provided_dbh) {
2714     $dbh = $provided_dbh;
2715   } else {
2716     $dbh = $self->dbconnect_noauto($myconfig);
2717   }
2718   my $query =
2719     qq|SELECT customernumberinit FROM business
2720        WHERE id = ? FOR UPDATE|;
2721   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
2722
2723   if ($var =~ m/\d+$/) {
2724     my $new_var  = (substr $var, $-[0]) * 1 + 1;
2725     my $len_diff = length($var) - $-[0] - length($new_var);
2726     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
2727
2728   } else {
2729     $var = $var . '1';
2730   }
2731
2732   $query = qq|UPDATE business
2733               SET customernumberinit = ?
2734               WHERE id = ?|;
2735   do_query($self, $dbh, $query, $var, $business_id);
2736
2737   if (!$provided_dbh) {
2738     $dbh->commit;
2739     $dbh->disconnect;
2740   }
2741
2742   $main::lxdebug->leave_sub();
2743
2744   return $var;
2745 }
2746
2747 sub get_partsgroup {
2748   $main::lxdebug->enter_sub();
2749
2750   my ($self, $myconfig, $p) = @_;
2751
2752   my $dbh = $self->get_standard_dbh($myconfig);
2753
2754   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
2755                  FROM partsgroup pg
2756                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
2757   my @values;
2758
2759   if ($p->{searchitems} eq 'part') {
2760     $query .= qq|WHERE p.inventory_accno_id > 0|;
2761   }
2762   if ($p->{searchitems} eq 'service') {
2763     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
2764   }
2765   if ($p->{searchitems} eq 'assembly') {
2766     $query .= qq|WHERE p.assembly = '1'|;
2767   }
2768   if ($p->{searchitems} eq 'labor') {
2769     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
2770   }
2771
2772   $query .= qq|ORDER BY partsgroup|;
2773
2774   if ($p->{all}) {
2775     $query = qq|SELECT id, partsgroup FROM partsgroup
2776                 ORDER BY partsgroup|;
2777   }
2778
2779   if ($p->{language_code}) {
2780     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
2781                   t.description AS translation
2782                 FROM partsgroup pg
2783                 JOIN parts p ON (p.partsgroup_id = pg.id)
2784                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
2785                 ORDER BY translation|;
2786     @values = ($p->{language_code});
2787   }
2788
2789   $self->{all_partsgroup} = selectall_hashref_query($self, $dbh, $query, @values);
2790
2791   $main::lxdebug->leave_sub();
2792 }
2793
2794 sub get_pricegroup {
2795   $main::lxdebug->enter_sub();
2796
2797   my ($self, $myconfig, $p) = @_;
2798
2799   my $dbh = $self->get_standard_dbh($myconfig);
2800
2801   my $query = qq|SELECT p.id, p.pricegroup
2802                  FROM pricegroup p|;
2803
2804   $query .= qq| ORDER BY pricegroup|;
2805
2806   if ($p->{all}) {
2807     $query = qq|SELECT id, pricegroup FROM pricegroup
2808                 ORDER BY pricegroup|;
2809   }
2810
2811   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
2812
2813   $main::lxdebug->leave_sub();
2814 }
2815
2816 sub all_years {
2817 # usage $form->all_years($myconfig, [$dbh])
2818 # return list of all years where bookings found
2819 # (@all_years)
2820
2821   $main::lxdebug->enter_sub();
2822
2823   my ($self, $myconfig, $dbh) = @_;
2824
2825   $dbh ||= $self->get_standard_dbh($myconfig);
2826
2827   # get years
2828   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
2829                    (SELECT MAX(transdate) FROM acc_trans)|;
2830   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
2831
2832   if ($myconfig->{dateformat} =~ /^yy/) {
2833     ($startdate) = split /\W/, $startdate;
2834     ($enddate) = split /\W/, $enddate;
2835   } else {
2836     (@_) = split /\W/, $startdate;
2837     $startdate = $_[2];
2838     (@_) = split /\W/, $enddate;
2839     $enddate = $_[2];
2840   }
2841
2842   my @all_years;
2843   $startdate = substr($startdate,0,4);
2844   $enddate = substr($enddate,0,4);
2845
2846   while ($enddate >= $startdate) {
2847     push @all_years, $enddate--;
2848   }
2849
2850   return @all_years;
2851
2852   $main::lxdebug->leave_sub();
2853 }
2854
2855 1;