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