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