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