e4c4dd5b78bb5f3f5814fe654cf74df468d35c14
[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 use List::Util qw(max min sum);
53
54 my $standard_dbh;
55
56 sub DESTROY {
57   if ($standard_dbh) {
58     $standard_dbh->disconnect();
59     undef $standard_dbh;
60   }
61 }
62
63 sub _input_to_hash {
64   $main::lxdebug->enter_sub(2);
65
66   my $input = $_[0];
67   my %in    = ();
68   my @pairs = split(/&/, $input);
69
70   foreach (@pairs) {
71     my ($name, $value) = split(/=/, $_, 2);
72     $in{$name} = unescape(undef, $value);
73   }
74
75   $main::lxdebug->leave_sub(2);
76
77   return %in;
78 }
79
80 sub _request_to_hash {
81   $main::lxdebug->enter_sub(2);
82
83   my ($input) = @_;
84
85   if (!$ENV{'CONTENT_TYPE'}
86       || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
87     $main::lxdebug->leave_sub(2);
88     return _input_to_hash($input);
89   }
90
91   my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr);
92   my %params;
93
94   my $boundary = '--' . $1;
95
96   foreach my $line (split m/\n/, $input) {
97     last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
98
99     if (($line eq $boundary) || ($line eq "$boundary\r")) {
100       $params{$name} =~ s|\r?\n$|| if $name;
101
102       undef $name;
103       undef $filename;
104
105       $headers_done   = 0;
106       $content_type   = "text/plain";
107       $boundary_found = 1;
108       $need_cr        = 0;
109
110       next;
111     }
112
113     next unless $boundary_found;
114
115     if (!$headers_done) {
116       $line =~ s/[\r\n]*$//;
117
118       if (!$line) {
119         $headers_done = 1;
120         next;
121       }
122
123       if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
124         if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
125           $filename = $1;
126           substr $line, $-[0], $+[0] - $-[0], "";
127         }
128
129         if ($line =~ m|name\s*=\s*"(.*?)"|i) {
130           $name = $1;
131           substr $line, $-[0], $+[0] - $-[0], "";
132         }
133
134         $params{$name}    = "";
135         $params{FILENAME} = $filename if ($filename);
136
137         next;
138       }
139
140       if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
141         $content_type = $1;
142       }
143
144       next;
145     }
146
147     next unless $name;
148
149     $params{$name} .= "${line}\n";
150   }
151
152   $params{$name} =~ s|\r?\n$|| if $name;
153
154   $main::lxdebug->leave_sub(2);
155   return %params;
156 }
157
158 sub new {
159   $main::lxdebug->enter_sub();
160
161   my $type = shift;
162
163   my $self = {};
164
165   if ($LXDebug::watch_form) {
166     require SL::Watchdog;
167     tie %{ $self }, 'SL::Watchdog';
168   }
169
170   read(STDIN, $_, $ENV{CONTENT_LENGTH});
171
172   if ($ENV{QUERY_STRING}) {
173     $_ = $ENV{QUERY_STRING};
174   }
175
176   if ($ARGV[0]) {
177     $_ = $ARGV[0];
178   }
179
180   my %parameters = _request_to_hash($_);
181   map({ $self->{$_} = $parameters{$_}; } keys(%parameters));
182
183   $self->{action} = lc $self->{action};
184   $self->{action} =~ s/( |-|,|\#)/_/g;
185
186   $self->{version}   = "2.4.3";
187
188   $main::lxdebug->leave_sub();
189
190   bless $self, $type;
191 }
192
193 sub debug {
194   $main::lxdebug->enter_sub();
195
196   my ($self) = @_;
197
198   print "\n";
199
200   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
201
202   $main::lxdebug->leave_sub();
203 }
204
205 sub escape {
206   $main::lxdebug->enter_sub(2);
207
208   my ($self, $str) = @_;
209
210   $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
211
212   $main::lxdebug->leave_sub(2);
213
214   return $str;
215 }
216
217 sub unescape {
218   $main::lxdebug->enter_sub(2);
219
220   my ($self, $str) = @_;
221
222   $str =~ tr/+/ /;
223   $str =~ s/\\$//;
224
225   $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
226
227   $main::lxdebug->leave_sub(2);
228
229   return $str;
230 }
231
232 sub quote {
233   my ($self, $str) = @_;
234
235   if ($str && !ref($str)) {
236     $str =~ s/\"/&quot;/g;
237   }
238
239   $str;
240
241 }
242
243 sub unquote {
244   my ($self, $str) = @_;
245
246   if ($str && !ref($str)) {
247     $str =~ s/&quot;/\"/g;
248   }
249
250   $str;
251
252 }
253
254 sub quote_html {
255   $main::lxdebug->enter_sub(2);
256
257   my ($self, $str) = @_;
258
259   my %replace =
260     ('order' => ['"', '<', '>'],
261      '<'             => '&lt;',
262      '>'             => '&gt;',
263      '"'             => '&quot;',
264     );
265
266   map({ $str =~ s/$_/$replace{$_}/g; } @{ $replace{"order"} });
267
268   $main::lxdebug->leave_sub(2);
269
270   return $str;
271 }
272
273 sub hide_form {
274   my $self = shift;
275
276   if (@_) {
277     map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
278   } else {
279     for (sort keys %$self) {
280       next if (($_ eq "header") || (ref($self->{$_}) ne ""));
281       print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
282     }
283   }
284
285 }
286
287 sub error {
288   $main::lxdebug->enter_sub();
289
290   $main::lxdebug->show_backtrace();
291
292   my ($self, $msg) = @_;
293   if ($ENV{HTTP_USER_AGENT}) {
294     $msg =~ s/\n/<br>/g;
295     $self->show_generic_error($msg);
296
297   } else {
298
299     die "Error: $msg\n";
300   }
301
302   $main::lxdebug->leave_sub();
303 }
304
305 sub info {
306   $main::lxdebug->enter_sub();
307
308   my ($self, $msg) = @_;
309
310   if ($ENV{HTTP_USER_AGENT}) {
311     $msg =~ s/\n/<br>/g;
312
313     if (!$self->{header}) {
314       $self->header;
315       print qq|
316       <body>|;
317     }
318
319     print qq|
320
321     <p><b>$msg</b>
322     |;
323
324   } else {
325
326     if ($self->{info_function}) {
327       &{ $self->{info_function} }($msg);
328     } else {
329       print "$msg\n";
330     }
331   }
332
333   $main::lxdebug->leave_sub();
334 }
335
336 # calculates the number of rows in a textarea based on the content and column number
337 # can be capped with maxrows
338 sub numtextrows {
339   $main::lxdebug->enter_sub();
340   my ($self, $str, $cols, $maxrows) = @_;
341
342   my $rows   = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
343   $maxrows ||= $rows;
344
345   $main::lxdebug->leave_sub();
346   return min $rows, $maxrows;
347 }
348
349 sub dberror {
350   $main::lxdebug->enter_sub();
351
352   my ($self, $msg) = @_;
353
354   $self->error("$msg\n" . $DBI::errstr);
355
356   $main::lxdebug->leave_sub();
357 }
358
359 sub isblank {
360   $main::lxdebug->enter_sub();
361
362   my ($self, $name, $msg) = @_;
363
364   if ($self->{$name} =~ /^\s*$/) {
365     $self->error($msg);
366   }
367   $main::lxdebug->leave_sub();
368 }
369
370 sub header {
371   $main::lxdebug->enter_sub();
372
373   my ($self, $extra_code) = @_;
374
375   if ($self->{header}) {
376     $main::lxdebug->leave_sub();
377     return;
378   }
379
380   my ($stylesheet, $favicon);
381
382   if ($ENV{HTTP_USER_AGENT}) {
383
384     my $stylesheets = "$self->{stylesheet} $self->{stylesheets}";
385
386     $stylesheets =~ s|^\s*||;
387     $stylesheets =~ s|\s*$||;
388     foreach my $file (split m/\s+/, $stylesheets) {
389       $file =~ s|.*/||;
390       next if (! -f "css/$file");
391
392       $stylesheet .= qq|<link rel="stylesheet" href="css/$file" TYPE="text/css" TITLE="Lx-Office stylesheet">\n|;
393     }
394
395     $self->{favicon}    = "favicon.ico" unless $self->{favicon};
396
397     if ($self->{favicon} && (-f "$self->{favicon}")) {
398       $favicon =
399         qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
400   |;
401     }
402
403     my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
404
405     if ($self->{landscape}) {
406       $pagelayout = qq|<style type="text/css">
407                         \@page { size:landscape; }
408                         </style>|;
409     }
410
411     my $fokus = qq|  document.$self->{fokus}.focus();| if ($self->{"fokus"});
412
413     #Set Calendar
414     my $jsscript = "";
415     if ($self->{jsscript} == 1) {
416
417       $jsscript = qq|
418         <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
419         <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
420         <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
421         <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
422         $self->{javascript}
423        |;
424     }
425
426     $self->{titlebar} =
427       ($self->{title})
428       ? "$self->{title} - $self->{titlebar}"
429       : $self->{titlebar};
430     my $ajax = "";
431     foreach $item (@ { $self->{AJAX} }) {
432       $ajax .= $item->show_javascript();
433     }
434     print qq|Content-Type: text/html; charset=${db_charset};
435
436 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
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                                  'PLUGIN_BASE' => 'SL::Template::Plugin',
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   my ($query);
1210   # some sanity check for currency
1211   if ($curr eq '') {
1212     $main::lxdebug->leave_sub();
1213     return;
1214   }  
1215   $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   $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   my ($query);
1292
1293   unless ($transdate) {
1294     $main::lxdebug->leave_sub();
1295     return 1;
1296   }
1297
1298   $query = qq|SELECT curr FROM defaults|;
1299
1300   my ($currency) = selectrow_query($self, $dbh, $query);
1301   my ($defaultcurrency) = split m/:/, $currency;
1302
1303   if ($currency eq $defaultcurrency) {
1304     $main::lxdebug->leave_sub();
1305     return 1;
1306   }
1307
1308   $query = qq|SELECT e.$fld FROM exchangerate e
1309                  WHERE e.curr = ? AND e.transdate = ?|;
1310   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1311
1312
1313
1314   $main::lxdebug->leave_sub();
1315
1316   return $exchangerate;
1317 }
1318
1319 sub check_exchangerate {
1320   $main::lxdebug->enter_sub();
1321
1322   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1323
1324   unless ($transdate) {
1325     $main::lxdebug->leave_sub();
1326     return "";
1327   }
1328
1329   my ($defaultcurrency) = $self->get_default_currency($myconfig);
1330
1331   if ($currency eq $defaultcurrency) {
1332     $main::lxdebug->leave_sub();
1333     return 1;
1334   }
1335
1336   my $dbh   = $self->get_standard_dbh($myconfig);
1337   my $query = qq|SELECT e.$fld FROM exchangerate e
1338                  WHERE e.curr = ? AND e.transdate = ?|;
1339
1340   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1341
1342   $exchangerate = 1 if ($exchangerate eq "");
1343
1344   $main::lxdebug->leave_sub();
1345
1346   return $exchangerate;
1347 }
1348
1349 sub get_default_currency {
1350   $main::lxdebug->enter_sub();
1351
1352   my ($self, $myconfig) = @_;
1353   my $dbh = $self->get_standard_dbh($myconfig);
1354
1355   my $query = qq|SELECT curr FROM defaults|;
1356
1357   my ($curr)            = selectrow_query($self, $dbh, $query);
1358   my ($defaultcurrency) = split m/:/, $curr;
1359
1360   $main::lxdebug->leave_sub();
1361
1362   return $defaultcurrency;
1363 }
1364
1365
1366 sub set_payment_options {
1367   $main::lxdebug->enter_sub();
1368
1369   my ($self, $myconfig, $transdate) = @_;
1370
1371   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1372
1373   my $dbh = $self->get_standard_dbh($myconfig);
1374
1375   my $query =
1376     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1377     qq|FROM payment_terms p | .
1378     qq|WHERE p.id = ?|;
1379
1380   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1381    $self->{payment_terms}) =
1382      selectrow_query($self, $dbh, $query, $self->{payment_id});
1383
1384   if ($transdate eq "") {
1385     if ($self->{invdate}) {
1386       $transdate = $self->{invdate};
1387     } else {
1388       $transdate = $self->{transdate};
1389     }
1390   }
1391
1392   $query =
1393     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1394     qq|FROM payment_terms|;
1395   ($self->{netto_date}, $self->{skonto_date}) =
1396     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1397
1398   my ($invtotal, $total);
1399   my (%amounts, %formatted_amounts);
1400
1401   if ($self->{type} =~ /_order$/) {
1402     $amounts{invtotal} = $self->{ordtotal};
1403     $amounts{total}    = $self->{ordtotal};
1404
1405   } elsif ($self->{type} =~ /_quotation$/) {
1406     $amounts{invtotal} = $self->{quototal};
1407     $amounts{total}    = $self->{quototal};
1408
1409   } else {
1410     $amounts{invtotal} = $self->{invtotal};
1411     $amounts{total}    = $self->{total};
1412   }
1413
1414   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1415
1416   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
1417   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1418   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
1419
1420   foreach (keys %amounts) {
1421     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
1422     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1423   }
1424
1425   if ($self->{"language_id"}) {
1426     $query =
1427       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1428       qq|FROM translation_payment_terms t | .
1429       qq|LEFT JOIN language l ON t.language_id = l.id | .
1430       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1431     my ($description_long, $output_numberformat, $output_dateformat,
1432       $output_longdates) =
1433       selectrow_query($self, $dbh, $query,
1434                       $self->{"language_id"}, $self->{"payment_id"});
1435
1436     $self->{payment_terms} = $description_long if ($description_long);
1437
1438     if ($output_dateformat) {
1439       foreach my $key (qw(netto_date skonto_date)) {
1440         $self->{$key} =
1441           $main::locale->reformat_date($myconfig, $self->{$key},
1442                                        $output_dateformat,
1443                                        $output_longdates);
1444       }
1445     }
1446
1447     if ($output_numberformat &&
1448         ($output_numberformat ne $myconfig->{"numberformat"})) {
1449       my $saved_numberformat = $myconfig->{"numberformat"};
1450       $myconfig->{"numberformat"} = $output_numberformat;
1451       map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1452       $myconfig->{"numberformat"} = $saved_numberformat;
1453     }
1454   }
1455
1456   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1457   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1458   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1459   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1460   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1461   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1462   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1463
1464   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1465
1466   $main::lxdebug->leave_sub();
1467
1468 }
1469
1470 sub get_template_language {
1471   $main::lxdebug->enter_sub();
1472
1473   my ($self, $myconfig) = @_;
1474
1475   my $template_code = "";
1476
1477   if ($self->{language_id}) {
1478     my $dbh = $self->get_standard_dbh($myconfig);
1479     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1480     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1481   }
1482
1483   $main::lxdebug->leave_sub();
1484
1485   return $template_code;
1486 }
1487
1488 sub get_printer_code {
1489   $main::lxdebug->enter_sub();
1490
1491   my ($self, $myconfig) = @_;
1492
1493   my $template_code = "";
1494
1495   if ($self->{printer_id}) {
1496     my $dbh = $self->get_standard_dbh($myconfig);
1497     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1498     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1499   }
1500
1501   $main::lxdebug->leave_sub();
1502
1503   return $template_code;
1504 }
1505
1506 sub get_shipto {
1507   $main::lxdebug->enter_sub();
1508
1509   my ($self, $myconfig) = @_;
1510
1511   my $template_code = "";
1512
1513   if ($self->{shipto_id}) {
1514     my $dbh = $self->get_standard_dbh($myconfig);
1515     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1516     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1517     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1518   }
1519
1520   $main::lxdebug->leave_sub();
1521 }
1522
1523 sub add_shipto {
1524   $main::lxdebug->enter_sub();
1525
1526   my ($self, $dbh, $id, $module) = @_;
1527
1528   my $shipto;
1529   my @values;
1530
1531   foreach my $item (qw(name department_1 department_2 street zipcode city country
1532                        contact phone fax email)) {
1533     if ($self->{"shipto$item"}) {
1534       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1535     }
1536     push(@values, $self->{"shipto${item}"});
1537   }
1538
1539   if ($shipto) {
1540     if ($self->{shipto_id}) {
1541       my $query = qq|UPDATE shipto set
1542                        shiptoname = ?,
1543                        shiptodepartment_1 = ?,
1544                        shiptodepartment_2 = ?,
1545                        shiptostreet = ?,
1546                        shiptozipcode = ?,
1547                        shiptocity = ?,
1548                        shiptocountry = ?,
1549                        shiptocontact = ?,
1550                        shiptophone = ?,
1551                        shiptofax = ?,
1552                        shiptoemail = ?
1553                      WHERE shipto_id = ?|;
1554       do_query($self, $dbh, $query, @values, $self->{shipto_id});
1555     } else {
1556       my $query = qq|SELECT * FROM shipto
1557                      WHERE shiptoname = ? AND
1558                        shiptodepartment_1 = ? AND
1559                        shiptodepartment_2 = ? AND
1560                        shiptostreet = ? AND
1561                        shiptozipcode = ? AND
1562                        shiptocity = ? AND
1563                        shiptocountry = ? AND
1564                        shiptocontact = ? AND
1565                        shiptophone = ? AND
1566                        shiptofax = ? AND
1567                        shiptoemail = ? AND
1568                        module = ? AND 
1569                        trans_id = ?|;
1570       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1571       if(!$insert_check){
1572         $query =
1573           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1574                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
1575                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
1576              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1577         do_query($self, $dbh, $query, $id, @values, $module);
1578       }
1579     }
1580   }
1581
1582   $main::lxdebug->leave_sub();
1583 }
1584
1585 sub get_employee {
1586   $main::lxdebug->enter_sub();
1587
1588   my ($self, $dbh) = @_;
1589
1590   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1591   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1592   $self->{"employee_id"} *= 1;
1593
1594   $main::lxdebug->leave_sub();
1595 }
1596
1597 sub get_salesman {
1598   $main::lxdebug->enter_sub();
1599
1600   my ($self, $myconfig, $salesman_id) = @_;
1601
1602   $main::lxdebug->leave_sub() and return unless $salesman_id;
1603
1604   my $dbh = $self->get_standard_dbh($myconfig);
1605
1606   my ($login) =
1607     selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|,
1608                     $salesman_id);
1609
1610   if ($login) {
1611     my $user = new User($main::memberfile, $login);
1612     map({ $self->{"salesman_$_"} = $user->{$_}; }
1613         qw(address businessnumber co_ustid company duns email fax name
1614            taxnumber tel));
1615     $self->{salesman_login} = $login;
1616
1617     $self->{salesman_name} = $login
1618       if ($self->{salesman_name} eq "");
1619
1620     map({ $self->{"salesman_$_"} =~ s/\\n/\n/g; } qw(address company));
1621   }
1622
1623   $main::lxdebug->leave_sub();
1624 }
1625
1626 sub get_duedate {
1627   $main::lxdebug->enter_sub();
1628
1629   my ($self, $myconfig) = @_;
1630
1631   my $dbh = $self->get_standard_dbh($myconfig);
1632   my $query = qq|SELECT current_date + terms_netto FROM payment_terms WHERE id = ?|;
1633   ($self->{duedate}) = selectrow_query($self, $dbh, $query, $self->{payment_id});
1634
1635   $main::lxdebug->leave_sub();
1636 }
1637
1638 sub _get_contacts {
1639   $main::lxdebug->enter_sub();
1640
1641   my ($self, $dbh, $id, $key) = @_;
1642
1643   $key = "all_contacts" unless ($key);
1644
1645   my $query =
1646     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
1647     qq|FROM contacts | .
1648     qq|WHERE cp_cv_id = ? | .
1649     qq|ORDER BY lower(cp_name)|;
1650
1651   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
1652
1653   $main::lxdebug->leave_sub();
1654 }
1655
1656 sub _get_projects {
1657   $main::lxdebug->enter_sub();
1658
1659   my ($self, $dbh, $key) = @_;
1660
1661   my ($all, $old_id, $where, @values);
1662
1663   if (ref($key) eq "HASH") {
1664     my $params = $key;
1665
1666     $key = "ALL_PROJECTS";
1667
1668     foreach my $p (keys(%{$params})) {
1669       if ($p eq "all") {
1670         $all = $params->{$p};
1671       } elsif ($p eq "old_id") {
1672         $old_id = $params->{$p};
1673       } elsif ($p eq "key") {
1674         $key = $params->{$p};
1675       }
1676     }
1677   }
1678
1679   if (!$all) {
1680     $where = "WHERE active ";
1681     if ($old_id) {
1682       if (ref($old_id) eq "ARRAY") {
1683         my @ids = grep({ $_ } @{$old_id});
1684         if (@ids) {
1685           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
1686           push(@values, @ids);
1687         }
1688       } else {
1689         $where .= " OR (id = ?) ";
1690         push(@values, $old_id);
1691       }
1692     }
1693   }
1694
1695   my $query =
1696     qq|SELECT id, projectnumber, description, active | .
1697     qq|FROM project | .
1698     $where .
1699     qq|ORDER BY lower(projectnumber)|;
1700
1701   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
1702
1703   $main::lxdebug->leave_sub();
1704 }
1705
1706 sub _get_shipto {
1707   $main::lxdebug->enter_sub();
1708
1709   my ($self, $dbh, $vc_id, $key) = @_;
1710
1711   $key = "all_shipto" unless ($key);
1712
1713   # get shipping addresses
1714   my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
1715
1716   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
1717
1718   $main::lxdebug->leave_sub();
1719 }
1720
1721 sub _get_printers {
1722   $main::lxdebug->enter_sub();
1723
1724   my ($self, $dbh, $key) = @_;
1725
1726   $key = "all_printers" unless ($key);
1727
1728   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
1729
1730   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1731
1732   $main::lxdebug->leave_sub();
1733 }
1734
1735 sub _get_charts {
1736   $main::lxdebug->enter_sub();
1737
1738   my ($self, $dbh, $params) = @_;
1739
1740   $key = $params->{key};
1741   $key = "all_charts" unless ($key);
1742
1743   my $transdate = quote_db_date($params->{transdate});
1744
1745   my $query =
1746     qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
1747     qq|FROM chart c | .
1748     qq|LEFT JOIN taxkeys tk ON | .
1749     qq|(tk.id = (SELECT id FROM taxkeys | .
1750     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
1751     qq|          ORDER BY startdate DESC LIMIT 1)) | .
1752     qq|ORDER BY c.accno|;
1753
1754   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1755
1756   $main::lxdebug->leave_sub();
1757 }
1758
1759 sub _get_taxcharts {
1760   $main::lxdebug->enter_sub();
1761
1762   my ($self, $dbh, $key) = @_;
1763
1764   $key = "all_taxcharts" unless ($key);
1765
1766   my $query = qq|SELECT * FROM tax ORDER BY taxkey|;
1767
1768   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1769
1770   $main::lxdebug->leave_sub();
1771 }
1772
1773 sub _get_taxzones {
1774   $main::lxdebug->enter_sub();
1775
1776   my ($self, $dbh, $key) = @_;
1777
1778   $key = "all_taxzones" unless ($key);
1779
1780   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
1781
1782   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1783
1784   $main::lxdebug->leave_sub();
1785 }
1786
1787 sub _get_employees {
1788   $main::lxdebug->enter_sub();
1789
1790   my ($self, $dbh, $default_key, $key) = @_;
1791
1792   $key = $default_key unless ($key);
1793   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY name|);
1794
1795   $main::lxdebug->leave_sub();
1796 }
1797
1798 sub _get_business_types {
1799   $main::lxdebug->enter_sub();
1800
1801   my ($self, $dbh, $key) = @_;
1802
1803   $key = "all_business_types" unless ($key);
1804   $self->{$key} =
1805     selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
1806
1807   $main::lxdebug->leave_sub();
1808 }
1809
1810 sub _get_languages {
1811   $main::lxdebug->enter_sub();
1812
1813   my ($self, $dbh, $key) = @_;
1814
1815   $key = "all_languages" unless ($key);
1816
1817   my $query = qq|SELECT * FROM language ORDER BY id|;
1818
1819   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1820
1821   $main::lxdebug->leave_sub();
1822 }
1823
1824 sub _get_dunning_configs {
1825   $main::lxdebug->enter_sub();
1826
1827   my ($self, $dbh, $key) = @_;
1828
1829   $key = "all_dunning_configs" unless ($key);
1830
1831   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
1832
1833   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1834
1835   $main::lxdebug->leave_sub();
1836 }
1837
1838 sub _get_currencies {
1839 $main::lxdebug->enter_sub();
1840
1841   my ($self, $dbh, $key) = @_;
1842
1843   $key = "all_currencies" unless ($key);
1844
1845   my $query = qq|SELECT curr AS currency FROM defaults|;
1846  
1847   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
1848
1849   $main::lxdebug->leave_sub();
1850 }
1851
1852 sub _get_payments {
1853 $main::lxdebug->enter_sub();
1854
1855   my ($self, $dbh, $key) = @_;
1856
1857   $key = "all_payments" unless ($key);
1858
1859   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
1860  
1861   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1862
1863   $main::lxdebug->leave_sub();
1864 }
1865
1866 sub _get_customers {
1867   $main::lxdebug->enter_sub();
1868
1869   my ($self, $dbh, $key, $limit) = @_;
1870
1871   $key = "all_customers" unless ($key);
1872   $limit_clause = "LIMIT $limit" if $limit;
1873
1874   my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name $limit_clause|;
1875
1876   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1877
1878   $main::lxdebug->leave_sub();
1879 }
1880
1881 sub _get_vendors {
1882   $main::lxdebug->enter_sub();
1883
1884   my ($self, $dbh, $key) = @_;
1885
1886   $key = "all_vendors" unless ($key);
1887
1888   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
1889
1890   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1891
1892   $main::lxdebug->leave_sub();
1893 }
1894
1895 sub _get_departments {
1896   $main::lxdebug->enter_sub();
1897
1898   my ($self, $dbh, $key) = @_;
1899
1900   $key = "all_departments" unless ($key);
1901
1902   my $query = qq|SELECT * FROM department ORDER BY description|;
1903
1904   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1905
1906   $main::lxdebug->leave_sub();
1907 }
1908
1909 sub _get_price_factors {
1910   $main::lxdebug->enter_sub();
1911
1912   my ($self, $dbh, $key) = @_;
1913
1914   $key ||= "all_price_factors";
1915
1916   my $query = qq|SELECT * FROM price_factors ORDER BY sortkey|;
1917
1918   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1919
1920   $main::lxdebug->leave_sub();
1921 }
1922
1923 sub get_lists {
1924   $main::lxdebug->enter_sub();
1925
1926   my $self = shift;
1927   my %params = @_;
1928
1929   my $dbh = $self->get_standard_dbh(\%main::myconfig);
1930   my ($sth, $query, $ref);
1931
1932   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
1933   my $vc_id = $self->{"${vc}_id"};
1934
1935   if ($params{"contacts"}) {
1936     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
1937   }
1938
1939   if ($params{"shipto"}) {
1940     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
1941   }
1942
1943   if ($params{"projects"} || $params{"all_projects"}) {
1944     $self->_get_projects($dbh, $params{"all_projects"} ?
1945                          $params{"all_projects"} : $params{"projects"},
1946                          $params{"all_projects"} ? 1 : 0);
1947   }
1948
1949   if ($params{"printers"}) {
1950     $self->_get_printers($dbh, $params{"printers"});
1951   }
1952
1953   if ($params{"languages"}) {
1954     $self->_get_languages($dbh, $params{"languages"});
1955   }
1956
1957   if ($params{"charts"}) {
1958     $self->_get_charts($dbh, $params{"charts"});
1959   }
1960
1961   if ($params{"taxcharts"}) {
1962     $self->_get_taxcharts($dbh, $params{"taxcharts"});
1963   }
1964
1965   if ($params{"taxzones"}) {
1966     $self->_get_taxzones($dbh, $params{"taxzones"});
1967   }
1968
1969   if ($params{"employees"}) {
1970     $self->_get_employees($dbh, "all_employees", $params{"employees"});
1971   }
1972   
1973   if ($params{"salesmen"}) {
1974     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
1975   }
1976
1977   if ($params{"business_types"}) {
1978     $self->_get_business_types($dbh, $params{"business_types"});
1979   }
1980
1981   if ($params{"dunning_configs"}) {
1982     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
1983   }
1984   
1985   if($params{"currencies"}) {
1986     $self->_get_currencies($dbh, $params{"currencies"});
1987   }
1988   
1989   if($params{"customers"}) {
1990     if (ref $params{"customers"} eq 'HASH') {
1991       $self->_get_customers($dbh, $params{"customers"}{key}, $params{"customers"}{limit});
1992     } else {
1993       $self->_get_customers($dbh, $params{"customers"});
1994     }
1995   }
1996   
1997   if($params{"vendors"}) {
1998     if (ref $params{"vendors"} eq 'HASH') {
1999       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2000     } else {
2001       $self->_get_vendors($dbh, $params{"vendors"});
2002     }
2003   }
2004   
2005   if($params{"payments"}) {
2006     $self->_get_payments($dbh, $params{"payments"});
2007   }
2008
2009   if($params{"departments"}) {
2010     $self->_get_departments($dbh, $params{"departments"});
2011   }
2012
2013   if ($params{price_factors}) {
2014     $self->_get_price_factors($dbh, $params{price_factors});
2015   }
2016
2017   $main::lxdebug->leave_sub();
2018 }
2019
2020 # this sub gets the id and name from $table
2021 sub get_name {
2022   $main::lxdebug->enter_sub();
2023
2024   my ($self, $myconfig, $table) = @_;
2025
2026   # connect to database
2027   my $dbh = $self->get_standard_dbh($myconfig);
2028
2029   $table = $table eq "customer" ? "customer" : "vendor";
2030   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2031
2032   my ($query, @values);
2033
2034   if (!$self->{openinvoices}) {
2035     my $where;
2036     if ($self->{customernumber} ne "") {
2037       $where = qq|(vc.customernumber ILIKE ?)|;
2038       push(@values, '%' . $self->{customernumber} . '%');
2039     } else {
2040       $where = qq|(vc.name ILIKE ?)|;
2041       push(@values, '%' . $self->{$table} . '%');
2042     }
2043
2044     $query =
2045       qq~SELECT vc.id, vc.name,
2046            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2047          FROM $table vc
2048          WHERE $where AND (NOT vc.obsolete)
2049          ORDER BY vc.name~;
2050   } else {
2051     $query =
2052       qq~SELECT DISTINCT vc.id, vc.name,
2053            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2054          FROM $arap a
2055          JOIN $table vc ON (a.${table}_id = vc.id)
2056          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2057          ORDER BY vc.name~;
2058     push(@values, '%' . $self->{$table} . '%');
2059   }
2060
2061   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2062
2063   $main::lxdebug->leave_sub();
2064
2065   return scalar(@{ $self->{name_list} });
2066 }
2067
2068 # the selection sub is used in the AR, AP, IS, IR and OE module
2069 #
2070 sub all_vc {
2071   $main::lxdebug->enter_sub();
2072
2073   my ($self, $myconfig, $table, $module) = @_;
2074
2075   my $ref;
2076   my $dbh = $self->get_standard_dbh($myconfig);
2077
2078   $table = $table eq "customer" ? "customer" : "vendor";
2079
2080   my $query = qq|SELECT count(*) FROM $table|;
2081   my ($count) = selectrow_query($self, $dbh, $query);
2082
2083   # build selection list
2084   if ($count < $myconfig->{vclimit}) {
2085     $query = qq|SELECT id, name, salesman_id
2086                 FROM $table WHERE NOT obsolete
2087                 ORDER BY name|;
2088     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2089   }
2090
2091   # get self
2092   $self->get_employee($dbh);
2093
2094   # setup sales contacts
2095   $query = qq|SELECT e.id, e.name
2096               FROM employee e
2097               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2098   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2099
2100   # this is for self
2101   push(@{ $self->{all_employees} },
2102        { id   => $self->{employee_id},
2103          name => $self->{employee} });
2104
2105   # sort the whole thing
2106   @{ $self->{all_employees} } =
2107     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2108
2109   if ($module eq 'AR') {
2110
2111     # prepare query for departments
2112     $query = qq|SELECT id, description
2113                 FROM department
2114                 WHERE role = 'P'
2115                 ORDER BY description|;
2116
2117   } else {
2118     $query = qq|SELECT id, description
2119                 FROM department
2120                 ORDER BY description|;
2121   }
2122
2123   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2124
2125   # get languages
2126   $query = qq|SELECT id, description
2127               FROM language
2128               ORDER BY id|;
2129
2130   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2131
2132   # get printer
2133   $query = qq|SELECT printer_description, id
2134               FROM printers
2135               ORDER BY printer_description|;
2136
2137   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2138
2139   # get payment terms
2140   $query = qq|SELECT id, description
2141               FROM payment_terms
2142               ORDER BY sortkey|;
2143
2144   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2145
2146   $main::lxdebug->leave_sub();
2147 }
2148
2149 sub language_payment {
2150   $main::lxdebug->enter_sub();
2151
2152   my ($self, $myconfig) = @_;
2153
2154   my $dbh = $self->get_standard_dbh($myconfig);
2155   # get languages
2156   my $query = qq|SELECT id, description
2157                  FROM language
2158                  ORDER BY id|;
2159
2160   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2161
2162   # get printer
2163   $query = qq|SELECT printer_description, id
2164               FROM printers
2165               ORDER BY printer_description|;
2166
2167   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2168
2169   # get payment terms
2170   $query = qq|SELECT id, description
2171               FROM payment_terms
2172               ORDER BY sortkey|;
2173
2174   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2175
2176   # get buchungsgruppen
2177   $query = qq|SELECT id, description
2178               FROM buchungsgruppen|;
2179
2180   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2181
2182   $main::lxdebug->leave_sub();
2183 }
2184
2185 # this is only used for reports
2186 sub all_departments {
2187   $main::lxdebug->enter_sub();
2188
2189   my ($self, $myconfig, $table) = @_;
2190
2191   my $dbh = $self->get_standard_dbh($myconfig);
2192   my $where;
2193
2194   if ($table eq 'customer') {
2195     $where = "WHERE role = 'P' ";
2196   }
2197
2198   my $query = qq|SELECT id, description
2199                  FROM department
2200                  $where
2201                  ORDER BY description|;
2202   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2203
2204   delete($self->{all_departments}) unless (@{ $self->{all_departments} });
2205
2206   $main::lxdebug->leave_sub();
2207 }
2208
2209 sub create_links {
2210   $main::lxdebug->enter_sub();
2211
2212   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2213
2214   my ($fld, $arap);
2215   if ($table eq "customer") {
2216     $fld = "buy";
2217     $arap = "ar";
2218   } else {
2219     $table = "vendor";
2220     $fld = "sell";
2221     $arap = "ap";
2222   }
2223
2224   $self->all_vc($myconfig, $table, $module);
2225
2226   # get last customers or vendors
2227   my ($query, $sth, $ref);
2228
2229   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2230   my %xkeyref = ();
2231
2232   if (!$self->{id}) {
2233
2234     my $transdate = "current_date";
2235     if ($self->{transdate}) {
2236       $transdate = $dbh->quote($self->{transdate});
2237     }
2238
2239     # now get the account numbers
2240     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2241                 FROM chart c, taxkeys tk
2242                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2243                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2244                 ORDER BY c.accno|;
2245
2246     $sth = $dbh->prepare($query);
2247
2248     do_statement($self, $sth, $query, '%' . $module . '%');
2249
2250     $self->{accounts} = "";
2251     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2252
2253       foreach my $key (split(/:/, $ref->{link})) {
2254         if ($key =~ /\Q$module\E/) {
2255
2256           # cross reference for keys
2257           $xkeyref{ $ref->{accno} } = $key;
2258
2259           push @{ $self->{"${module}_links"}{$key} },
2260             { accno       => $ref->{accno},
2261               description => $ref->{description},
2262               taxkey      => $ref->{taxkey_id},
2263               tax_id      => $ref->{tax_id} };
2264
2265           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2266         }
2267       }
2268     }
2269   }
2270
2271   # get taxkeys and description
2272   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2273   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2274
2275   if (($module eq "AP") || ($module eq "AR")) {
2276     # get tax rates and description
2277     $query = qq|SELECT * FROM tax|;
2278     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2279   }
2280
2281   if ($self->{id}) {
2282     $query =
2283       qq|SELECT
2284            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2285            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2286            a.intnotes, a.department_id, a.amount AS oldinvtotal,
2287            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2288            c.name AS $table,
2289            d.description AS department,
2290            e.name AS employee
2291          FROM $arap a
2292          JOIN $table c ON (a.${table}_id = c.id)
2293          LEFT JOIN employee e ON (e.id = a.employee_id)
2294          LEFT JOIN department d ON (d.id = a.department_id)
2295          WHERE a.id = ?|;
2296     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2297
2298     foreach $key (keys %$ref) {
2299       $self->{$key} = $ref->{$key};
2300     }
2301
2302     my $transdate = "current_date";
2303     if ($self->{transdate}) {
2304       $transdate = $dbh->quote($self->{transdate});
2305     }
2306
2307     # now get the account numbers
2308     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2309                 FROM chart c
2310                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2311                 WHERE c.link LIKE ?
2312                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2313                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2314                 ORDER BY c.accno|;
2315
2316     $sth = $dbh->prepare($query);
2317     do_statement($self, $sth, $query, "%$module%");
2318
2319     $self->{accounts} = "";
2320     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2321
2322       foreach my $key (split(/:/, $ref->{link})) {
2323         if ($key =~ /\Q$module\E/) {
2324
2325           # cross reference for keys
2326           $xkeyref{ $ref->{accno} } = $key;
2327
2328           push @{ $self->{"${module}_links"}{$key} },
2329             { accno       => $ref->{accno},
2330               description => $ref->{description},
2331               taxkey      => $ref->{taxkey_id},
2332               tax_id      => $ref->{tax_id} };
2333
2334           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2335         }
2336       }
2337     }
2338
2339
2340     # get amounts from individual entries
2341     $query =
2342       qq|SELECT
2343            c.accno, c.description,
2344            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2345            p.projectnumber,
2346            t.rate, t.id
2347          FROM acc_trans a
2348          LEFT JOIN chart c ON (c.id = a.chart_id)
2349          LEFT JOIN project p ON (p.id = a.project_id)
2350          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2351                                     WHERE (tk.taxkey_id=a.taxkey) AND
2352                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2353                                         THEN tk.chart_id = a.chart_id
2354                                         ELSE 1 = 1
2355                                         END)
2356                                        OR (c.link='%tax%')) AND
2357                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2358          WHERE a.trans_id = ?
2359          AND a.fx_transaction = '0'
2360          ORDER BY a.oid, a.transdate|;
2361     $sth = $dbh->prepare($query);
2362     do_statement($self, $sth, $query, $self->{id});
2363
2364     # get exchangerate for currency
2365     $self->{exchangerate} =
2366       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2367     my $index = 0;
2368
2369     # store amounts in {acc_trans}{$key} for multiple accounts
2370     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2371       $ref->{exchangerate} =
2372         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2373       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2374         $index++;
2375       }
2376       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2377         $ref->{amount} *= -1;
2378       }
2379       $ref->{index} = $index;
2380
2381       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2382     }
2383
2384     $sth->finish;
2385     $query =
2386       qq|SELECT
2387            d.curr AS currencies, d.closedto, d.revtrans,
2388            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2389            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2390          FROM defaults d|;
2391     $ref = selectfirst_hashref_query($self, $dbh, $query);
2392     map { $self->{$_} = $ref->{$_} } keys %$ref;
2393
2394   } else {
2395
2396     # get date
2397     $query =
2398        qq|SELECT
2399             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2400             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2401             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2402           FROM defaults d|;
2403     $ref = selectfirst_hashref_query($self, $dbh, $query);
2404     map { $self->{$_} = $ref->{$_} } keys %$ref;
2405
2406     if ($self->{"$self->{vc}_id"}) {
2407
2408       # only setup currency
2409       ($self->{currency}) = split(/:/, $self->{currencies});
2410
2411     } else {
2412
2413       $self->lastname_used($dbh, $myconfig, $table, $module);
2414
2415       # get exchangerate for currency
2416       $self->{exchangerate} =
2417         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2418
2419     }
2420
2421   }
2422
2423   $main::lxdebug->leave_sub();
2424 }
2425
2426 sub lastname_used {
2427   $main::lxdebug->enter_sub();
2428
2429   my ($self, $dbh, $myconfig, $table, $module) = @_;
2430
2431   my $arap  = ($table eq 'customer') ? "ar" : "ap";
2432   $table = $table eq "customer" ? "customer" : "vendor";
2433   my $where = "1 = 1";
2434
2435   if ($self->{type} =~ /_order/) {
2436     $arap  = 'oe';
2437     $where = "quotation = '0'";
2438   }
2439   if ($self->{type} =~ /_quotation/) {
2440     $arap  = 'oe';
2441     $where = "quotation = '1'";
2442   }
2443
2444   my $query = qq|SELECT MAX(id) FROM $arap
2445                  WHERE $where AND ${table}_id > 0|;
2446   my ($trans_id) = selectrow_query($self, $dbh, $query);
2447
2448   $trans_id *= 1;
2449   $query =
2450     qq|SELECT
2451          a.curr, a.${table}_id, a.department_id,
2452          d.description AS department,
2453          ct.name, current_date + ct.terms AS duedate
2454        FROM $arap a
2455        LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2456        LEFT JOIN department d ON (a.department_id = d.id)
2457        WHERE a.id = ?|;
2458   ($self->{currency},   $self->{"${table}_id"}, $self->{department_id},
2459    $self->{department}, $self->{$table},        $self->{duedate})
2460     = selectrow_query($self, $dbh, $query, $trans_id);
2461
2462   $main::lxdebug->leave_sub();
2463 }
2464
2465 sub current_date {
2466   $main::lxdebug->enter_sub();
2467
2468   my ($self, $myconfig, $thisdate, $days) = @_;
2469
2470   my $dbh = $self->get_standard_dbh($myconfig);
2471   my $query;
2472
2473   $days *= 1;
2474   if ($thisdate) {
2475     my $dateformat = $myconfig->{dateformat};
2476     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2477     $thisdate = $dbh->quote($thisdate);
2478     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2479   } else {
2480     $query = qq|SELECT current_date AS thisdate|;
2481   }
2482
2483   ($thisdate) = selectrow_query($self, $dbh, $query);
2484
2485   $main::lxdebug->leave_sub();
2486
2487   return $thisdate;
2488 }
2489
2490 sub like {
2491   $main::lxdebug->enter_sub();
2492
2493   my ($self, $string) = @_;
2494
2495   if ($string !~ /%/) {
2496     $string = "%$string%";
2497   }
2498
2499   $string =~ s/\'/\'\'/g;
2500
2501   $main::lxdebug->leave_sub();
2502
2503   return $string;
2504 }
2505
2506 sub redo_rows {
2507   $main::lxdebug->enter_sub();
2508
2509   my ($self, $flds, $new, $count, $numrows) = @_;
2510
2511   my @ndx = ();
2512
2513   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
2514
2515   my $i = 0;
2516
2517   # fill rows
2518   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2519     $i++;
2520     $j = $item->{ndx} - 1;
2521     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2522   }
2523
2524   # delete empty rows
2525   for $i ($count + 1 .. $numrows) {
2526     map { delete $self->{"${_}_$i"} } @{$flds};
2527   }
2528
2529   $main::lxdebug->leave_sub();
2530 }
2531
2532 sub update_status {
2533   $main::lxdebug->enter_sub();
2534
2535   my ($self, $myconfig) = @_;
2536
2537   my ($i, $id);
2538
2539   my $dbh = $self->dbconnect_noauto($myconfig);
2540
2541   my $query = qq|DELETE FROM status
2542                  WHERE (formname = ?) AND (trans_id = ?)|;
2543   my $sth = prepare_query($self, $dbh, $query);
2544
2545   if ($self->{formname} =~ /(check|receipt)/) {
2546     for $i (1 .. $self->{rowcount}) {
2547       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
2548     }
2549   } else {
2550     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
2551   }
2552   $sth->finish();
2553
2554   my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2555   my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2556
2557   my %queued = split / /, $self->{queued};
2558   my @values;
2559
2560   if ($self->{formname} =~ /(check|receipt)/) {
2561
2562     # this is a check or receipt, add one entry for each lineitem
2563     my ($accno) = split /--/, $self->{account};
2564     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
2565                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
2566     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
2567     $sth = prepare_query($self, $dbh, $query);
2568
2569     for $i (1 .. $self->{rowcount}) {
2570       if ($self->{"checked_$i"}) {
2571         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
2572       }
2573     }
2574     $sth->finish();
2575
2576   } else {
2577     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2578                 VALUES (?, ?, ?, ?, ?)|;
2579     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
2580              $queued{$self->{formname}}, $self->{formname});
2581   }
2582
2583   $dbh->commit;
2584   $dbh->disconnect;
2585
2586   $main::lxdebug->leave_sub();
2587 }
2588
2589 sub save_status {
2590   $main::lxdebug->enter_sub();
2591
2592   my ($self, $dbh) = @_;
2593
2594   my ($query, $printed, $emailed);
2595
2596   my $formnames  = $self->{printed};
2597   my $emailforms = $self->{emailed};
2598
2599   $query = qq|DELETE FROM status
2600                  WHERE (formname = ?) AND (trans_id = ?)|;
2601   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
2602
2603   # this only applies to the forms
2604   # checks and receipts are posted when printed or queued
2605
2606   if ($self->{queued}) {
2607     my %queued = split / /, $self->{queued};
2608
2609     foreach my $formname (keys %queued) {
2610       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2611       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2612
2613       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2614                   VALUES (?, ?, ?, ?, ?)|;
2615       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
2616
2617       $formnames  =~ s/\Q$self->{formname}\E//;
2618       $emailforms =~ s/\Q$self->{formname}\E//;
2619
2620     }
2621   }
2622
2623   # save printed, emailed info
2624   $formnames  =~ s/^ +//g;
2625   $emailforms =~ s/^ +//g;
2626
2627   my %status = ();
2628   map { $status{$_}{printed} = 1 } split / +/, $formnames;
2629   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
2630
2631   foreach my $formname (keys %status) {
2632     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
2633     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
2634
2635     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
2636                 VALUES (?, ?, ?, ?)|;
2637     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
2638   }
2639
2640   $main::lxdebug->leave_sub();
2641 }
2642
2643 #--- 4 locale ---#
2644 # $main::locale->text('SAVED')
2645 # $main::locale->text('DELETED')
2646 # $main::locale->text('ADDED')
2647 # $main::locale->text('PAYMENT POSTED')
2648 # $main::locale->text('POSTED')
2649 # $main::locale->text('POSTED AS NEW')
2650 # $main::locale->text('ELSE')
2651 # $main::locale->text('SAVED FOR DUNNING')
2652 # $main::locale->text('DUNNING STARTED')
2653 # $main::locale->text('PRINTED')
2654 # $main::locale->text('MAILED')
2655 # $main::locale->text('SCREENED')
2656 # $main::locale->text('CANCELED')
2657 # $main::locale->text('invoice')
2658 # $main::locale->text('proforma')
2659 # $main::locale->text('sales_order')
2660 # $main::locale->text('packing_list')
2661 # $main::locale->text('pick_list')
2662 # $main::locale->text('purchase_order')
2663 # $main::locale->text('bin_list')
2664 # $main::locale->text('sales_quotation')
2665 # $main::locale->text('request_quotation')
2666
2667 sub save_history {
2668   $main::lxdebug->enter_sub();
2669
2670   my $self = shift();
2671   my $dbh = shift();
2672
2673   if(!exists $self->{employee_id}) {
2674     &get_employee($self, $dbh);
2675   }
2676
2677   my $query =
2678    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
2679    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
2680   my @values = (conv_i($self->{id}), $self->{login},
2681                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
2682   do_query($self, $dbh, $query, @values);
2683
2684   $main::lxdebug->leave_sub();
2685 }
2686
2687 sub get_history {
2688   $main::lxdebug->enter_sub();
2689
2690   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
2691   my ($orderBy, $desc) = split(/\-\-/, $order);
2692   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
2693   my @tempArray;
2694   my $i = 0;
2695   if ($trans_id ne "") {
2696     my $query =
2697       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 | .
2698       qq|FROM history_erp h | .
2699       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
2700       qq|WHERE trans_id = | . $trans_id
2701       . $restriction . qq| |
2702       . $order;
2703       
2704     my $sth = $dbh->prepare($query) || $self->dberror($query);
2705
2706     $sth->execute() || $self->dberror("$query");
2707
2708     while(my $hash_ref = $sth->fetchrow_hashref()) {
2709       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
2710       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
2711       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
2712       $tempArray[$i++] = $hash_ref;
2713     }
2714     $main::lxdebug->leave_sub() and return \@tempArray 
2715       if ($i > 0 && $tempArray[0] ne "");
2716   }
2717   $main::lxdebug->leave_sub();
2718   return 0;
2719 }
2720
2721 sub update_defaults {
2722   $main::lxdebug->enter_sub();
2723
2724   my ($self, $myconfig, $fld, $provided_dbh) = @_;
2725
2726   my $dbh;
2727   if ($provided_dbh) {
2728     $dbh = $provided_dbh;
2729   } else {
2730     $dbh = $self->dbconnect_noauto($myconfig);
2731   }
2732   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
2733   my $sth   = $dbh->prepare($query);
2734
2735   $sth->execute || $self->dberror($query);
2736   my ($var) = $sth->fetchrow_array;
2737   $sth->finish;
2738
2739   if ($var =~ m/\d+$/) {
2740     my $new_var  = (substr $var, $-[0]) * 1 + 1;
2741     my $len_diff = length($var) - $-[0] - length($new_var);
2742     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
2743
2744   } else {
2745     $var = $var . '1';
2746   }
2747
2748   $query = qq|UPDATE defaults SET $fld = ?|;
2749   do_query($self, $dbh, $query, $var);
2750
2751   if (!$provided_dbh) {
2752     $dbh->commit;
2753     $dbh->disconnect;
2754   }
2755
2756   $main::lxdebug->leave_sub();
2757
2758   return $var;
2759 }
2760
2761 sub update_business {
2762   $main::lxdebug->enter_sub();
2763
2764   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
2765
2766   my $dbh;
2767   if ($provided_dbh) {
2768     $dbh = $provided_dbh;
2769   } else {
2770     $dbh = $self->dbconnect_noauto($myconfig);
2771   }
2772   my $query =
2773     qq|SELECT customernumberinit FROM business
2774        WHERE id = ? FOR UPDATE|;
2775   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
2776
2777   if ($var =~ m/\d+$/) {
2778     my $new_var  = (substr $var, $-[0]) * 1 + 1;
2779     my $len_diff = length($var) - $-[0] - length($new_var);
2780     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
2781
2782   } else {
2783     $var = $var . '1';
2784   }
2785
2786   $query = qq|UPDATE business
2787               SET customernumberinit = ?
2788               WHERE id = ?|;
2789   do_query($self, $dbh, $query, $var, $business_id);
2790
2791   if (!$provided_dbh) {
2792     $dbh->commit;
2793     $dbh->disconnect;
2794   }
2795
2796   $main::lxdebug->leave_sub();
2797
2798   return $var;
2799 }
2800
2801 sub get_partsgroup {
2802   $main::lxdebug->enter_sub();
2803
2804   my ($self, $myconfig, $p) = @_;
2805
2806   my $dbh = $self->get_standard_dbh($myconfig);
2807
2808   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
2809                  FROM partsgroup pg
2810                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
2811   my @values;
2812
2813   if ($p->{searchitems} eq 'part') {
2814     $query .= qq|WHERE p.inventory_accno_id > 0|;
2815   }
2816   if ($p->{searchitems} eq 'service') {
2817     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
2818   }
2819   if ($p->{searchitems} eq 'assembly') {
2820     $query .= qq|WHERE p.assembly = '1'|;
2821   }
2822   if ($p->{searchitems} eq 'labor') {
2823     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
2824   }
2825
2826   $query .= qq|ORDER BY partsgroup|;
2827
2828   if ($p->{all}) {
2829     $query = qq|SELECT id, partsgroup FROM partsgroup
2830                 ORDER BY partsgroup|;
2831   }
2832
2833   if ($p->{language_code}) {
2834     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
2835                   t.description AS translation
2836                 FROM partsgroup pg
2837                 JOIN parts p ON (p.partsgroup_id = pg.id)
2838                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
2839                 ORDER BY translation|;
2840     @values = ($p->{language_code});
2841   }
2842
2843   $self->{all_partsgroup} = selectall_hashref_query($self, $dbh, $query, @values);
2844
2845   $main::lxdebug->leave_sub();
2846 }
2847
2848 sub get_pricegroup {
2849   $main::lxdebug->enter_sub();
2850
2851   my ($self, $myconfig, $p) = @_;
2852
2853   my $dbh = $self->get_standard_dbh($myconfig);
2854
2855   my $query = qq|SELECT p.id, p.pricegroup
2856                  FROM pricegroup p|;
2857
2858   $query .= qq| ORDER BY pricegroup|;
2859
2860   if ($p->{all}) {
2861     $query = qq|SELECT id, pricegroup FROM pricegroup
2862                 ORDER BY pricegroup|;
2863   }
2864
2865   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
2866
2867   $main::lxdebug->leave_sub();
2868 }
2869
2870 sub all_years {
2871 # usage $form->all_years($myconfig, [$dbh])
2872 # return list of all years where bookings found
2873 # (@all_years)
2874
2875   $main::lxdebug->enter_sub();
2876
2877   my ($self, $myconfig, $dbh) = @_;
2878
2879   $dbh ||= $self->get_standard_dbh($myconfig);
2880
2881   # get years
2882   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
2883                    (SELECT MAX(transdate) FROM acc_trans)|;
2884   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
2885
2886   if ($myconfig->{dateformat} =~ /^yy/) {
2887     ($startdate) = split /\W/, $startdate;
2888     ($enddate) = split /\W/, $enddate;
2889   } else {
2890     (@_) = split /\W/, $startdate;
2891     $startdate = $_[2];
2892     (@_) = split /\W/, $enddate;
2893     $enddate = $_[2];
2894   }
2895
2896   my @all_years;
2897   $startdate = substr($startdate,0,4);
2898   $enddate = substr($enddate,0,4);
2899
2900   while ($enddate >= $startdate) {
2901     push @all_years, $enddate--;
2902   }
2903
2904   return @all_years;
2905
2906   $main::lxdebug->leave_sub();
2907 }
2908
2909 1;