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