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