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