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