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