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