Die Funktion Form::parse_html_template2() in Form::parse_html_template() umbenannt...
[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                                }) || die;
564
565   map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
566
567   my $output;
568   if (!$template->process($file, $additional_params, \$output)) {
569     print STDERR $template->error();
570   }
571
572   $output = $main::locale->{iconv}->convert($output) if ($main::locale);
573
574   $main::lxdebug->leave_sub();
575
576   return $output;
577 }
578
579 sub show_generic_error {
580   my ($self, $error, $title, $action) = @_;
581
582   my $add_params = {
583     'title_error' => $title,
584     'label_error' => $error,
585   };
586
587   my @vars;
588   if ($action) {
589     map({ delete($self->{$_}); } qw(action));
590     map({ push(@vars, { "name" => $_, "value" => $self->{$_} })
591             if (!ref($self->{$_})); }
592         keys(%{$self}));
593     $add_params->{"SHOW_BUTTON"} = 1;
594     $add_params->{"BUTTON_LABEL"} = $action;
595   }
596   $add_params->{"VARIABLES"} = \@vars;
597
598   $self->{title} = $title if ($title);
599
600   $self->header();
601   print $self->parse_html_template("generic/error", $add_params);
602
603   die("Error: $error\n");
604 }
605
606 sub show_generic_information {
607   my ($self, $text, $title) = @_;
608
609   my $add_params = {
610     'title_information' => $title,
611     'label_information' => $text,
612   };
613
614   $self->{title} = $title if ($title);
615
616   $self->header();
617   print $self->parse_html_template("generic/information", $add_params);
618
619   die("Information: $error\n");
620 }
621
622 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
623 # changed it to accept an arbitrary number of triggers - sschoeling
624 sub write_trigger {
625   $main::lxdebug->enter_sub();
626
627   my $self     = shift;
628   my $myconfig = shift;
629   my $qty      = shift;
630
631   # set dateform for jsscript
632   # default
633   my %dateformats = (
634     "dd.mm.yy" => "%d.%m.%Y",
635     "dd-mm-yy" => "%d-%m-%Y",
636     "dd/mm/yy" => "%d/%m/%Y",
637     "mm/dd/yy" => "%m/%d/%Y",
638     "mm-dd-yy" => "%m-%d-%Y",
639     "yyyy-mm-dd" => "%Y-%m-%d",
640     );
641
642   my $ifFormat = defined($dateformats{$myconfig{"dateformat"}}) ?
643     $dateformats{$myconfig{"dateformat"}} : "%d.%m.%Y";
644
645   my @triggers;
646   while ($#_ >= 2) {
647     push @triggers, qq|
648        Calendar.setup(
649       {
650       inputField : "| . (shift) . qq|",
651       ifFormat :"$ifFormat",
652       align : "| .  (shift) . qq|",
653       button : "| . (shift) . qq|"
654       }
655       );
656        |;
657   }
658   my $jsscript = qq|
659        <script type="text/javascript">
660        <!--| . join("", @triggers) . qq|//-->
661         </script>
662         |;
663
664   $main::lxdebug->leave_sub();
665
666   return $jsscript;
667 }    #end sub write_trigger
668
669 sub redirect {
670   $main::lxdebug->enter_sub();
671
672   my ($self, $msg) = @_;
673
674   if ($self->{callback}) {
675
676     ($script, $argv) = split(/\?/, $self->{callback}, 2);
677     $script =~ s|.*/||;
678     $script =~ s|[^a-zA-Z0-9_\.]||g;
679     exec("perl", "$script", $argv);
680
681   } else {
682
683     $self->info($msg);
684     exit;
685   }
686
687   $main::lxdebug->leave_sub();
688 }
689
690 # sort of columns removed - empty sub
691 sub sort_columns {
692   $main::lxdebug->enter_sub();
693
694   my ($self, @columns) = @_;
695
696   $main::lxdebug->leave_sub();
697
698   return @columns;
699 }
700 #
701 sub format_amount {
702   $main::lxdebug->enter_sub(2);
703
704   my ($self, $myconfig, $amount, $places, $dash) = @_;
705
706   if ($amount eq "") {
707     $amount = 0;
708   }
709   
710   # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
711   
712   my $neg = ($amount =~ s/^-//);
713   my $exp = ($amount =~ m/[e]/) ? 1 : 0;
714   
715   if (defined($places) && ($places ne '')) {
716     if (not $exp) {
717       if ($places < 0) {
718         $amount *= 1;
719         $places *= -1;
720
721         my ($actual_places) = ($amount =~ /\.(\d+)/);
722         $actual_places = length($actual_places);
723         $places = $actual_places > $places ? $actual_places : $places;
724       }
725     }
726     $amount = $self->round_amount($amount, $places);
727   }
728
729   my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
730   my @p = split(/\./, $amount); # split amount at decimal point
731
732   $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
733
734   $amount = $p[0];
735   $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
736
737   $amount = do {
738     ($dash =~ /-/)    ? ($neg ? "($amount)"  : "$amount" )    :
739     ($dash =~ /DRCR/) ? ($neg ? "$amount DR" : "$amount CR" ) :
740                         ($neg ? "-$amount"   : "$amount" )    ;
741   };
742
743
744   $main::lxdebug->leave_sub(2);
745   return $amount;
746 }
747 #
748
749 sub format_string {
750   $main::lxdebug->enter_sub(2);
751
752   my $self  = shift;
753   my $input = shift;
754
755   $input =~ s/(^|[^\#]) \#  (\d+)  /$1$_[$2 - 1]/gx;
756   $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
757   $input =~ s/\#\#/\#/g;
758
759   $main::lxdebug->leave_sub(2);
760
761   return $input;
762 }
763
764 sub parse_amount {
765   $main::lxdebug->enter_sub(2);
766
767   my ($self, $myconfig, $amount) = @_;
768
769   if (   ($myconfig->{numberformat} eq '1.000,00')
770       || ($myconfig->{numberformat} eq '1000,00')) {
771     $amount =~ s/\.//g;
772     $amount =~ s/,/\./;
773   }
774
775   if ($myconfig->{numberformat} eq "1'000.00") {
776     $amount =~ s/\'//g;
777   }
778
779   $amount =~ s/,//g;
780
781   $main::lxdebug->leave_sub(2);
782
783   return ($amount * 1);
784 }
785
786 sub round_amount {
787   $main::lxdebug->enter_sub(2);
788
789   my ($self, $amount, $places) = @_;
790   my $round_amount;
791
792   # Rounding like "Kaufmannsrunden"
793   # Descr. http://de.wikipedia.org/wiki/Rundung
794   # Inspired by
795   # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
796   # Solves Bug: 189
797   # Udo Spallek
798   $amount = $amount * (10**($places));
799   $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
800
801   $main::lxdebug->leave_sub(2);
802
803   return $round_amount;
804
805 }
806
807 sub parse_template {
808   $main::lxdebug->enter_sub();
809
810   my ($self, $myconfig, $userspath) = @_;
811   my ($template, $out);
812
813   local (*IN, *OUT);
814
815   $self->{"cwd"} = getcwd();
816   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
817
818   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
819     $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
820   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
821     $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
822     $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
823   } elsif (($self->{"format"} =~ /html/i) ||
824            (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
825     $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
826   } elsif (($self->{"format"} =~ /xml/i) ||
827              (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
828     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
829   } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
830     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
831   } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
832     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
833   } elsif ( defined $self->{'format'}) {
834     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
835   } elsif ( $self->{'format'} eq '' ) {
836     $self->error("No Outputformat given: $self->{'format'}");
837   } else { #Catch the rest
838     $self->error("Outputformat not defined: $self->{'format'}");
839   }
840
841   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
842   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
843
844   map({ $self->{"employee_${_}"} = $myconfig->{$_}; }
845       qw(email tel fax name signature company address businessnumber
846          co_ustid taxnumber duns));
847   map({ $self->{"employee_${_}"} =~ s/\\n/\n/g; }
848       qw(company address signature));
849   map({ $self->{$_} =~ s/\\n/\n/g; } qw(company address signature));
850
851   map({ $self->{"${_}"} = $myconfig->{$_}; }
852       qw(co_ustid));
853               
854
855   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
856
857   # OUT is used for the media, screen, printer, email
858   # for postscript we store a copy in a temporary file
859   my $fileid = time;
860   my $prepend_userspath;
861
862   if (!$self->{tmpfile}) {
863     $self->{tmpfile}   = "${fileid}.$self->{IN}";
864     $prepend_userspath = 1;
865   }
866
867   $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
868
869   $self->{tmpfile} =~ s|.*/||;
870   $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
871   $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
872
873   if ($template->uses_temp_file() || $self->{media} eq 'email') {
874     $out = $self->{OUT};
875     $self->{OUT} = ">$self->{tmpfile}";
876   }
877
878   if ($self->{OUT}) {
879     open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
880   } else {
881     open(OUT, ">-") or $self->error("STDOUT : $!");
882     $self->header;
883   }
884
885   if (!$template->parse(*OUT)) {
886     $self->cleanup();
887     $self->error("$self->{IN} : " . $template->get_error());
888   }
889
890   close(OUT);
891
892   if ($template->uses_temp_file() || $self->{media} eq 'email') {
893
894     if ($self->{media} eq 'email') {
895
896       my $mail = new Mailer;
897
898       map { $mail->{$_} = $self->{$_} }
899         qw(cc bcc subject message version format);
900       $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
901       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
902       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
903       $mail->{fileid} = "$fileid.";
904       $myconfig->{signature} =~ s/\\r\\n/\\n/g;
905
906       # if we send html or plain text inline
907       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
908         $mail->{contenttype} = "text/html";
909
910         $mail->{message}       =~ s/\r\n/<br>\n/g;
911         $myconfig->{signature} =~ s/\\n/<br>\n/g;
912         $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
913
914         open(IN, $self->{tmpfile})
915           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
916         while (<IN>) {
917           $mail->{message} .= $_;
918         }
919
920         close(IN);
921
922       } else {
923
924         if (!$self->{"do_not_attach"}) {
925           @{ $mail->{attachments} } =
926             ({ "filename" => $self->{"tmpfile"},
927                "name" => $self->{"attachment_filename"} ?
928                  $self->{"attachment_filename"} : $self->{"tmpfile"} });
929         }
930
931         $mail->{message}       =~ s/\r\n/\n/g;
932         $myconfig->{signature} =~ s/\\n/\n/g;
933         $mail->{message} .= "\n-- \n$myconfig->{signature}";
934
935       }
936
937       my $err = $mail->send();
938       $self->error($self->cleanup . "$err") if ($err);
939
940     } else {
941
942       $self->{OUT} = $out;
943
944       my $numbytes = (-s $self->{tmpfile});
945       open(IN, $self->{tmpfile})
946         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
947
948       $self->{copies} = 1 unless $self->{media} eq 'printer';
949
950       chdir("$self->{cwd}");
951       #print(STDERR "Kopien $self->{copies}\n");
952       #print(STDERR "OUT $self->{OUT}\n");
953       for my $i (1 .. $self->{copies}) {
954         if ($self->{OUT}) {
955           open(OUT, $self->{OUT})
956             or $self->error($self->cleanup . "$self->{OUT} : $!");
957         } else {
958           $self->{attachment_filename} = ($self->{attachment_filename}) 
959                                        ? $self->{attachment_filename}
960                                        : $self->generate_attachment_filename();
961
962           # launch application
963           print qq|Content-Type: | . $template->get_mime_type() . qq|
964 Content-Disposition: attachment; filename="$self->{attachment_filename}"
965 Content-Length: $numbytes
966
967 |;
968
969           open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
970
971         }
972
973         while (<IN>) {
974           print OUT $_;
975         }
976
977         close(OUT);
978
979         seek IN, 0, 0;
980       }
981
982       close(IN);
983     }
984
985   }
986
987   $self->cleanup;
988
989   chdir("$self->{cwd}");
990   $main::lxdebug->leave_sub();
991 }
992
993 sub get_formname_translation {
994   my ($self, $formname) = @_;
995
996   $formname ||= $self->{formname};
997
998   my %formname_translations = (
999     bin_list            => $main::locale->text('Bin List'),
1000     credit_note         => $main::locale->text('Credit Note'),
1001     invoice             => $main::locale->text('Invoice'),
1002     packing_list        => $main::locale->text('Packing List'),
1003     pick_list           => $main::locale->text('Pick List'),
1004     proforma            => $main::locale->text('Proforma Invoice'),
1005     purchase_order      => $main::locale->text('Purchase Order'),
1006     request_quotation   => $main::locale->text('RFQ'),
1007     sales_order         => $main::locale->text('Confirmation'),
1008     sales_quotation     => $main::locale->text('Quotation'),
1009     storno_invoice      => $main::locale->text('Storno Invoice'),
1010     storno_packing_list => $main::locale->text('Storno Packing List'),
1011   );
1012
1013   return $formname_translations{$formname}
1014 }
1015
1016 sub generate_attachment_filename {
1017   my ($self) = @_;
1018
1019   my $attachment_filename = $self->get_formname_translation();
1020   my $prefix = 
1021       (grep { $self->{"type"} eq $_ } qw(invoice credit_note)) ? "inv"
1022     : ($self->{"type"} =~ /_quotation$/)                       ? "quo"
1023     :                                                            "ord";
1024
1025   if ($attachment_filename && $self->{"${prefix}number"}) {
1026     $attachment_filename .= "_" . $self->{"${prefix}number"}
1027                             . (  $self->{format} =~ /pdf/i          ? ".pdf"
1028                                : $self->{format} =~ /postscript/i   ? ".ps"
1029                                : $self->{format} =~ /opendocument/i ? ".odt"
1030                                : $self->{format} =~ /html/i         ? ".html"
1031                                :                                      "");
1032     $attachment_filename =~ s/ /_/g;
1033     my %umlaute = ( "ä" => "ae", "ö" => "oe", "ü" => "ue", 
1034                     "Ä" => "Ae", "Ö" => "Oe", "Ãœ" => "Ue", "ß" => "ss");
1035     map { $attachment_filename =~ s/$_/$umlaute{$_}/g } keys %umlaute;
1036   } else {
1037     $attachment_filename = "";
1038   }
1039
1040   return $attachment_filename;
1041 }
1042
1043 sub cleanup {
1044   $main::lxdebug->enter_sub();
1045
1046   my $self = shift;
1047
1048   chdir("$self->{tmpdir}");
1049
1050   my @err = ();
1051   if (-f "$self->{tmpfile}.err") {
1052     open(FH, "$self->{tmpfile}.err");
1053     @err = <FH>;
1054     close(FH);
1055   }
1056
1057   if ($self->{tmpfile}) {
1058     $self->{tmpfile} =~ s|.*/||g;
1059     # strip extension
1060     $self->{tmpfile} =~ s/\.\w+$//g;
1061     my $tmpfile = $self->{tmpfile};
1062     unlink(<$tmpfile.*>);
1063   }
1064
1065   chdir("$self->{cwd}");
1066
1067   $main::lxdebug->leave_sub();
1068
1069   return "@err";
1070 }
1071
1072 sub datetonum {
1073   $main::lxdebug->enter_sub();
1074
1075   my ($self, $date, $myconfig) = @_;
1076
1077   if ($date && $date =~ /\D/) {
1078
1079     if ($myconfig->{dateformat} =~ /^yy/) {
1080       ($yy, $mm, $dd) = split /\D/, $date;
1081     }
1082     if ($myconfig->{dateformat} =~ /^mm/) {
1083       ($mm, $dd, $yy) = split /\D/, $date;
1084     }
1085     if ($myconfig->{dateformat} =~ /^dd/) {
1086       ($dd, $mm, $yy) = split /\D/, $date;
1087     }
1088
1089     $dd *= 1;
1090     $mm *= 1;
1091     $yy = ($yy < 70) ? $yy + 2000 : $yy;
1092     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1093
1094     $dd = "0$dd" if ($dd < 10);
1095     $mm = "0$mm" if ($mm < 10);
1096
1097     $date = "$yy$mm$dd";
1098   }
1099
1100   $main::lxdebug->leave_sub();
1101
1102   return $date;
1103 }
1104
1105 # Database routines used throughout
1106
1107 sub dbconnect {
1108   $main::lxdebug->enter_sub(2);
1109
1110   my ($self, $myconfig) = @_;
1111
1112   # connect to database
1113   my $dbh =
1114     DBI->connect($myconfig->{dbconnect},
1115                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
1116     or $self->dberror;
1117
1118   # set db options
1119   if ($myconfig->{dboptions}) {
1120     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1121   }
1122
1123   $main::lxdebug->leave_sub(2);
1124
1125   return $dbh;
1126 }
1127
1128 sub dbconnect_noauto {
1129   $main::lxdebug->enter_sub();
1130
1131   my ($self, $myconfig) = @_;
1132   
1133   # connect to database
1134   $dbh =
1135     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1136                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
1137     or $self->dberror;
1138
1139   # set db options
1140   if ($myconfig->{dboptions}) {
1141     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1142   }
1143
1144   $main::lxdebug->leave_sub();
1145
1146   return $dbh;
1147 }
1148
1149 sub get_standard_dbh {
1150   $main::lxdebug->enter_sub(2);
1151
1152   my ($self, $myconfig) = @_;
1153
1154   $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1155
1156   $main::lxdebug->leave_sub(2);
1157
1158   return $standard_dbh;
1159 }
1160
1161 sub update_balance {
1162   $main::lxdebug->enter_sub();
1163
1164   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1165
1166   # if we have a value, go do it
1167   if ($value != 0) {
1168
1169     # retrieve balance from table
1170     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1171     my $sth = prepare_execute_query($self, $dbh, $query, @values);
1172     my ($balance) = $sth->fetchrow_array;
1173     $sth->finish;
1174
1175     $balance += $value;
1176
1177     # update balance
1178     $query = "UPDATE $table SET $field = $balance WHERE $where";
1179     do_query($self, $dbh, $query, @values);
1180   }
1181   $main::lxdebug->leave_sub();
1182 }
1183
1184 sub update_exchangerate {
1185   $main::lxdebug->enter_sub();
1186
1187   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1188   my ($query);
1189   # some sanity check for currency
1190   if ($curr eq '') {
1191     $main::lxdebug->leave_sub();
1192     return;
1193   }  
1194   $query = qq|SELECT curr FROM defaults|;
1195
1196   my ($currency) = selectrow_query($self, $dbh, $query);
1197   my ($defaultcurrency) = split m/:/, $currency;
1198
1199
1200   if ($curr eq $defaultcurrency) {
1201     $main::lxdebug->leave_sub();
1202     return;
1203   }
1204
1205   $query = qq|SELECT e.curr FROM exchangerate e
1206                  WHERE e.curr = ? AND e.transdate = ?
1207                  FOR UPDATE|;
1208   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1209
1210   if ($buy == 0) {
1211     $buy = "";
1212   }
1213   if ($sell == 0) {
1214     $sell = "";
1215   }
1216
1217   $buy = conv_i($buy, "NULL");
1218   $sell = conv_i($sell, "NULL");
1219
1220   my $set;
1221   if ($buy != 0 && $sell != 0) {
1222     $set = "buy = $buy, sell = $sell";
1223   } elsif ($buy != 0) {
1224     $set = "buy = $buy";
1225   } elsif ($sell != 0) {
1226     $set = "sell = $sell";
1227   }
1228
1229   if ($sth->fetchrow_array) {
1230     $query = qq|UPDATE exchangerate
1231                 SET $set
1232                 WHERE curr = ?
1233                 AND transdate = ?|;
1234     
1235   } else {
1236     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1237                 VALUES (?, $buy, $sell, ?)|;
1238   }
1239   $sth->finish;
1240   do_query($self, $dbh, $query, $curr, $transdate);
1241
1242   $main::lxdebug->leave_sub();
1243 }
1244
1245 sub save_exchangerate {
1246   $main::lxdebug->enter_sub();
1247
1248   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1249
1250   my $dbh = $self->dbconnect($myconfig);
1251
1252   my ($buy, $sell);
1253
1254   $buy  = $rate if $fld eq 'buy';
1255   $sell = $rate if $fld eq 'sell';
1256
1257
1258   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1259
1260
1261   $dbh->disconnect;
1262
1263   $main::lxdebug->leave_sub();
1264 }
1265
1266 sub get_exchangerate {
1267   $main::lxdebug->enter_sub();
1268
1269   my ($self, $dbh, $curr, $transdate, $fld) = @_;
1270   my ($query);
1271
1272   unless ($transdate) {
1273     $main::lxdebug->leave_sub();
1274     return 1;
1275   }
1276
1277   $query = qq|SELECT curr FROM defaults|;
1278
1279   my ($currency) = selectrow_query($self, $dbh, $query);
1280   my ($defaultcurrency) = split m/:/, $currency;
1281
1282   if ($currency eq $defaultcurrency) {
1283     $main::lxdebug->leave_sub();
1284     return 1;
1285   }
1286
1287   $query = qq|SELECT e.$fld FROM exchangerate e
1288                  WHERE e.curr = ? AND e.transdate = ?|;
1289   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1290
1291
1292
1293   $main::lxdebug->leave_sub();
1294
1295   return $exchangerate;
1296 }
1297
1298 sub check_exchangerate {
1299   $main::lxdebug->enter_sub();
1300
1301   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1302
1303   unless ($transdate) {
1304     $main::lxdebug->leave_sub();
1305     return "";
1306   }
1307
1308   my ($defaultcurrency) = $self->get_default_currency($myconfig);
1309
1310   if ($currency eq $defaultcurrency) {
1311     $main::lxdebug->leave_sub();
1312     return 1;
1313   }
1314
1315   my $dbh   = $self->get_standard_dbh($myconfig);
1316   my $query = qq|SELECT e.$fld FROM exchangerate e
1317                  WHERE e.curr = ? AND e.transdate = ?|;
1318
1319   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1320
1321   $exchangerate = 1 if ($exchangerate eq "");
1322
1323   $main::lxdebug->leave_sub();
1324
1325   return $exchangerate;
1326 }
1327
1328 sub get_default_currency {
1329   $main::lxdebug->enter_sub();
1330
1331   my ($self, $myconfig) = @_;
1332   my $dbh = $self->get_standard_dbh($myconfig);
1333
1334   my $query = qq|SELECT curr FROM defaults|;
1335
1336   my ($curr)            = selectrow_query($self, $dbh, $query);
1337   my ($defaultcurrency) = split m/:/, $curr;
1338
1339   $main::lxdebug->leave_sub();
1340
1341   return $defaultcurrency;
1342 }
1343
1344
1345 sub set_payment_options {
1346   $main::lxdebug->enter_sub();
1347
1348   my ($self, $myconfig, $transdate) = @_;
1349
1350   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1351
1352   my $dbh = $self->get_standard_dbh($myconfig);
1353
1354   my $query =
1355     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1356     qq|FROM payment_terms p | .
1357     qq|WHERE p.id = ?|;
1358
1359   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1360    $self->{payment_terms}) =
1361      selectrow_query($self, $dbh, $query, $self->{payment_id});
1362
1363   if ($transdate eq "") {
1364     if ($self->{invdate}) {
1365       $transdate = $self->{invdate};
1366     } else {
1367       $transdate = $self->{transdate};
1368     }
1369   }
1370
1371   $query =
1372     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1373     qq|FROM payment_terms|;
1374   ($self->{netto_date}, $self->{skonto_date}) =
1375     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1376
1377   my ($invtotal, $total);
1378   my (%amounts, %formatted_amounts);
1379
1380   if ($self->{type} =~ /_order$/) {
1381     $amounts{invtotal} = $self->{ordtotal};
1382     $amounts{total}    = $self->{ordtotal};
1383
1384   } elsif ($self->{type} =~ /_quotation$/) {
1385     $amounts{invtotal} = $self->{quototal};
1386     $amounts{total}    = $self->{quototal};
1387
1388   } else {
1389     $amounts{invtotal} = $self->{invtotal};
1390     $amounts{total}    = $self->{total};
1391   }
1392
1393   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1394
1395   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
1396   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1397   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
1398
1399   foreach (keys %amounts) {
1400     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
1401     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1402   }
1403
1404   if ($self->{"language_id"}) {
1405     $query =
1406       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1407       qq|FROM translation_payment_terms t | .
1408       qq|LEFT JOIN language l ON t.language_id = l.id | .
1409       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1410     my ($description_long, $output_numberformat, $output_dateformat,
1411       $output_longdates) =
1412       selectrow_query($self, $dbh, $query,
1413                       $self->{"language_id"}, $self->{"payment_id"});
1414
1415     $self->{payment_terms} = $description_long if ($description_long);
1416
1417     if ($output_dateformat) {
1418       foreach my $key (qw(netto_date skonto_date)) {
1419         $self->{$key} =
1420           $main::locale->reformat_date($myconfig, $self->{$key},
1421                                        $output_dateformat,
1422                                        $output_longdates);
1423       }
1424     }
1425
1426     if ($output_numberformat &&
1427         ($output_numberformat ne $myconfig->{"numberformat"})) {
1428       my $saved_numberformat = $myconfig->{"numberformat"};
1429       $myconfig->{"numberformat"} = $output_numberformat;
1430       map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1431       $myconfig->{"numberformat"} = $saved_numberformat;
1432     }
1433   }
1434
1435   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1436   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1437   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1438   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1439   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1440   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1441   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1442
1443   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1444
1445   $main::lxdebug->leave_sub();
1446
1447 }
1448
1449 sub get_template_language {
1450   $main::lxdebug->enter_sub();
1451
1452   my ($self, $myconfig) = @_;
1453
1454   my $template_code = "";
1455
1456   if ($self->{language_id}) {
1457     my $dbh = $self->get_standard_dbh($myconfig);
1458     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1459     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1460   }
1461
1462   $main::lxdebug->leave_sub();
1463
1464   return $template_code;
1465 }
1466
1467 sub get_printer_code {
1468   $main::lxdebug->enter_sub();
1469
1470   my ($self, $myconfig) = @_;
1471
1472   my $template_code = "";
1473
1474   if ($self->{printer_id}) {
1475     my $dbh = $self->get_standard_dbh($myconfig);
1476     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1477     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1478   }
1479
1480   $main::lxdebug->leave_sub();
1481
1482   return $template_code;
1483 }
1484
1485 sub get_shipto {
1486   $main::lxdebug->enter_sub();
1487
1488   my ($self, $myconfig) = @_;
1489
1490   my $template_code = "";
1491
1492   if ($self->{shipto_id}) {
1493     my $dbh = $self->get_standard_dbh($myconfig);
1494     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1495     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1496     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1497   }
1498
1499   $main::lxdebug->leave_sub();
1500 }
1501
1502 sub add_shipto {
1503   $main::lxdebug->enter_sub();
1504
1505   my ($self, $dbh, $id, $module) = @_;
1506
1507   my $shipto;
1508   my @values;
1509
1510   foreach my $item (qw(name department_1 department_2 street zipcode city country
1511                        contact phone fax email)) {
1512     if ($self->{"shipto$item"}) {
1513       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1514     }
1515     push(@values, $self->{"shipto${item}"});
1516   }
1517
1518   if ($shipto) {
1519     if ($self->{shipto_id}) {
1520       my $query = qq|UPDATE shipto set
1521                        shiptoname = ?,
1522                        shiptodepartment_1 = ?,
1523                        shiptodepartment_2 = ?,
1524                        shiptostreet = ?,
1525                        shiptozipcode = ?,
1526                        shiptocity = ?,
1527                        shiptocountry = ?,
1528                        shiptocontact = ?,
1529                        shiptophone = ?,
1530                        shiptofax = ?,
1531                        shiptoemail = ?
1532                      WHERE shipto_id = ?|;
1533       do_query($self, $dbh, $query, @values, $self->{shipto_id});
1534     } else {
1535       my $query = qq|SELECT * FROM shipto
1536                      WHERE shiptoname = ? AND
1537                        shiptodepartment_1 = ? AND
1538                        shiptodepartment_2 = ? AND
1539                        shiptostreet = ? AND
1540                        shiptozipcode = ? AND
1541                        shiptocity = ? AND
1542                        shiptocountry = ? AND
1543                        shiptocontact = ? AND
1544                        shiptophone = ? AND
1545                        shiptofax = ? AND
1546                        shiptoemail = ? AND
1547                        module = ? AND 
1548                        trans_id = ?|;
1549       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1550       if(!$insert_check){
1551         $query =
1552           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1553                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
1554                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
1555              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1556         do_query($self, $dbh, $query, $id, @values, $module);
1557       }
1558     }
1559   }
1560
1561   $main::lxdebug->leave_sub();
1562 }
1563
1564 sub get_employee {
1565   $main::lxdebug->enter_sub();
1566
1567   my ($self, $dbh) = @_;
1568
1569   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1570   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1571   $self->{"employee_id"} *= 1;
1572
1573   $main::lxdebug->leave_sub();
1574 }
1575
1576 sub get_salesman {
1577   $main::lxdebug->enter_sub();
1578
1579   my ($self, $myconfig, $salesman_id) = @_;
1580
1581   $main::lxdebug->leave_sub() and return unless $salesman_id;
1582
1583   my $dbh = $self->get_standard_dbh($myconfig);
1584
1585   my ($login) =
1586     selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|,
1587                     $salesman_id);
1588
1589   if ($login) {
1590     my $user = new User($main::memberfile, $login);
1591     map({ $self->{"salesman_$_"} = $user->{$_}; }
1592         qw(address businessnumber co_ustid company duns email fax name
1593            taxnumber tel));
1594     $self->{salesman_login} = $login;
1595
1596     $self->{salesman_name} = $login
1597       if ($self->{salesman_name} eq "");
1598
1599     map({ $self->{"salesman_$_"} =~ s/\\n/\n/g; } qw(address company));
1600   }
1601
1602   $main::lxdebug->leave_sub();
1603 }
1604
1605 sub get_duedate {
1606   $main::lxdebug->enter_sub();
1607
1608   my ($self, $myconfig) = @_;
1609
1610   my $dbh = $self->get_standard_dbh($myconfig);
1611   my $query = qq|SELECT current_date + terms_netto FROM payment_terms WHERE id = ?|;
1612   ($self->{duedate}) = selectrow_query($self, $dbh, $query, $self->{payment_id});
1613
1614   $main::lxdebug->leave_sub();
1615 }
1616
1617 sub _get_contacts {
1618   $main::lxdebug->enter_sub();
1619
1620   my ($self, $dbh, $id, $key) = @_;
1621
1622   $key = "all_contacts" unless ($key);
1623
1624   my $query =
1625     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
1626     qq|FROM contacts | .
1627     qq|WHERE cp_cv_id = ? | .
1628     qq|ORDER BY lower(cp_name)|;
1629
1630   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
1631
1632   $main::lxdebug->leave_sub();
1633 }
1634
1635 sub _get_projects {
1636   $main::lxdebug->enter_sub();
1637
1638   my ($self, $dbh, $key) = @_;
1639
1640   my ($all, $old_id, $where, @values);
1641
1642   if (ref($key) eq "HASH") {
1643     my $params = $key;
1644
1645     $key = "ALL_PROJECTS";
1646
1647     foreach my $p (keys(%{$params})) {
1648       if ($p eq "all") {
1649         $all = $params->{$p};
1650       } elsif ($p eq "old_id") {
1651         $old_id = $params->{$p};
1652       } elsif ($p eq "key") {
1653         $key = $params->{$p};
1654       }
1655     }
1656   }
1657
1658   if (!$all) {
1659     $where = "WHERE active ";
1660     if ($old_id) {
1661       if (ref($old_id) eq "ARRAY") {
1662         my @ids = grep({ $_ } @{$old_id});
1663         if (@ids) {
1664           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
1665           push(@values, @ids);
1666         }
1667       } else {
1668         $where .= " OR (id = ?) ";
1669         push(@values, $old_id);
1670       }
1671     }
1672   }
1673
1674   my $query =
1675     qq|SELECT id, projectnumber, description, active | .
1676     qq|FROM project | .
1677     $where .
1678     qq|ORDER BY lower(projectnumber)|;
1679
1680   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
1681
1682   $main::lxdebug->leave_sub();
1683 }
1684
1685 sub _get_shipto {
1686   $main::lxdebug->enter_sub();
1687
1688   my ($self, $dbh, $vc_id, $key) = @_;
1689
1690   $key = "all_shipto" unless ($key);
1691
1692   # get shipping addresses
1693   my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
1694
1695   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
1696
1697   $main::lxdebug->leave_sub();
1698 }
1699
1700 sub _get_printers {
1701   $main::lxdebug->enter_sub();
1702
1703   my ($self, $dbh, $key) = @_;
1704
1705   $key = "all_printers" unless ($key);
1706
1707   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
1708
1709   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1710
1711   $main::lxdebug->leave_sub();
1712 }
1713
1714 sub _get_charts {
1715   $main::lxdebug->enter_sub();
1716
1717   my ($self, $dbh, $params) = @_;
1718
1719   $key = $params->{key};
1720   $key = "all_charts" unless ($key);
1721
1722   my $transdate = quote_db_date($params->{transdate});
1723
1724   my $query =
1725     qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
1726     qq|FROM chart c | .
1727     qq|LEFT JOIN taxkeys tk ON | .
1728     qq|(tk.id = (SELECT id FROM taxkeys | .
1729     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
1730     qq|          ORDER BY startdate DESC LIMIT 1)) | .
1731     qq|ORDER BY c.accno|;
1732
1733   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1734
1735   $main::lxdebug->leave_sub();
1736 }
1737
1738 sub _get_taxcharts {
1739   $main::lxdebug->enter_sub();
1740
1741   my ($self, $dbh, $key) = @_;
1742
1743   $key = "all_taxcharts" unless ($key);
1744
1745   my $query = qq|SELECT * FROM tax ORDER BY taxkey|;
1746
1747   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1748
1749   $main::lxdebug->leave_sub();
1750 }
1751
1752 sub _get_taxzones {
1753   $main::lxdebug->enter_sub();
1754
1755   my ($self, $dbh, $key) = @_;
1756
1757   $key = "all_taxzones" unless ($key);
1758
1759   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
1760
1761   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1762
1763   $main::lxdebug->leave_sub();
1764 }
1765
1766 sub _get_employees {
1767   $main::lxdebug->enter_sub();
1768
1769   my ($self, $dbh, $default_key, $key) = @_;
1770
1771   $key = $default_key unless ($key);
1772   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY name|);
1773
1774   $main::lxdebug->leave_sub();
1775 }
1776
1777 sub _get_business_types {
1778   $main::lxdebug->enter_sub();
1779
1780   my ($self, $dbh, $key) = @_;
1781
1782   $key = "all_business_types" unless ($key);
1783   $self->{$key} =
1784     selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
1785
1786   $main::lxdebug->leave_sub();
1787 }
1788
1789 sub _get_languages {
1790   $main::lxdebug->enter_sub();
1791
1792   my ($self, $dbh, $key) = @_;
1793
1794   $key = "all_languages" unless ($key);
1795
1796   my $query = qq|SELECT * FROM language ORDER BY id|;
1797
1798   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1799
1800   $main::lxdebug->leave_sub();
1801 }
1802
1803 sub _get_dunning_configs {
1804   $main::lxdebug->enter_sub();
1805
1806   my ($self, $dbh, $key) = @_;
1807
1808   $key = "all_dunning_configs" unless ($key);
1809
1810   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
1811
1812   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1813
1814   $main::lxdebug->leave_sub();
1815 }
1816
1817 sub _get_currencies {
1818 $main::lxdebug->enter_sub();
1819
1820   my ($self, $dbh, $key) = @_;
1821
1822   $key = "all_currencies" unless ($key);
1823
1824   my $query = qq|SELECT curr AS currency FROM defaults|;
1825  
1826   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
1827
1828   $main::lxdebug->leave_sub();
1829 }
1830
1831 sub _get_payments {
1832 $main::lxdebug->enter_sub();
1833
1834   my ($self, $dbh, $key) = @_;
1835
1836   $key = "all_payments" unless ($key);
1837
1838   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
1839  
1840   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1841
1842   $main::lxdebug->leave_sub();
1843 }
1844
1845 sub _get_customers {
1846   $main::lxdebug->enter_sub();
1847
1848   my ($self, $dbh, $key, $limit) = @_;
1849
1850   $key = "all_customers" unless ($key);
1851   $limit_clause = "LIMIT $limit" if $limit;
1852
1853   my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name $limit_clause|;
1854
1855   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1856
1857   $main::lxdebug->leave_sub();
1858 }
1859
1860 sub _get_vendors {
1861   $main::lxdebug->enter_sub();
1862
1863   my ($self, $dbh, $key) = @_;
1864
1865   $key = "all_vendors" unless ($key);
1866
1867   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
1868
1869   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1870
1871   $main::lxdebug->leave_sub();
1872 }
1873
1874 sub _get_departments {
1875   $main::lxdebug->enter_sub();
1876
1877   my ($self, $dbh, $key) = @_;
1878
1879   $key = "all_departments" unless ($key);
1880
1881   my $query = qq|SELECT * FROM department ORDER BY description|;
1882
1883   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1884
1885   $main::lxdebug->leave_sub();
1886 }
1887
1888 sub _get_price_factors {
1889   $main::lxdebug->enter_sub();
1890
1891   my ($self, $dbh, $key) = @_;
1892
1893   $key ||= "all_price_factors";
1894
1895   my $query = qq|SELECT * FROM price_factors ORDER BY sortkey|;
1896
1897   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1898
1899   $main::lxdebug->leave_sub();
1900 }
1901
1902 sub get_lists {
1903   $main::lxdebug->enter_sub();
1904
1905   my $self = shift;
1906   my %params = @_;
1907
1908   my $dbh = $self->get_standard_dbh(\%main::myconfig);
1909   my ($sth, $query, $ref);
1910
1911   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
1912   my $vc_id = $self->{"${vc}_id"};
1913
1914   if ($params{"contacts"}) {
1915     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
1916   }
1917
1918   if ($params{"shipto"}) {
1919     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
1920   }
1921
1922   if ($params{"projects"} || $params{"all_projects"}) {
1923     $self->_get_projects($dbh, $params{"all_projects"} ?
1924                          $params{"all_projects"} : $params{"projects"},
1925                          $params{"all_projects"} ? 1 : 0);
1926   }
1927
1928   if ($params{"printers"}) {
1929     $self->_get_printers($dbh, $params{"printers"});
1930   }
1931
1932   if ($params{"languages"}) {
1933     $self->_get_languages($dbh, $params{"languages"});
1934   }
1935
1936   if ($params{"charts"}) {
1937     $self->_get_charts($dbh, $params{"charts"});
1938   }
1939
1940   if ($params{"taxcharts"}) {
1941     $self->_get_taxcharts($dbh, $params{"taxcharts"});
1942   }
1943
1944   if ($params{"taxzones"}) {
1945     $self->_get_taxzones($dbh, $params{"taxzones"});
1946   }
1947
1948   if ($params{"employees"}) {
1949     $self->_get_employees($dbh, "all_employees", $params{"employees"});
1950   }
1951   
1952   if ($params{"salesmen"}) {
1953     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
1954   }
1955
1956   if ($params{"business_types"}) {
1957     $self->_get_business_types($dbh, $params{"business_types"});
1958   }
1959
1960   if ($params{"dunning_configs"}) {
1961     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
1962   }
1963   
1964   if($params{"currencies"}) {
1965     $self->_get_currencies($dbh, $params{"currencies"});
1966   }
1967   
1968   if($params{"customers"}) {
1969     if (ref $params{"customers"} eq 'HASH') {
1970       $self->_get_customers($dbh, $params{"customers"}{key}, $params{"customers"}{limit});
1971     } else {
1972       $self->_get_customers($dbh, $params{"customers"});
1973     }
1974   }
1975   
1976   if($params{"vendors"}) {
1977     if (ref $params{"vendors"} eq 'HASH') {
1978       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
1979     } else {
1980       $self->_get_vendors($dbh, $params{"vendors"});
1981     }
1982   }
1983   
1984   if($params{"payments"}) {
1985     $self->_get_payments($dbh, $params{"payments"});
1986   }
1987
1988   if($params{"departments"}) {
1989     $self->_get_departments($dbh, $params{"departments"});
1990   }
1991
1992   if ($params{price_factors}) {
1993     $self->_get_price_factors($dbh, $params{price_factors});
1994   }
1995
1996   $main::lxdebug->leave_sub();
1997 }
1998
1999 # this sub gets the id and name from $table
2000 sub get_name {
2001   $main::lxdebug->enter_sub();
2002
2003   my ($self, $myconfig, $table) = @_;
2004
2005   # connect to database
2006   my $dbh = $self->get_standard_dbh($myconfig);
2007
2008   $table = $table eq "customer" ? "customer" : "vendor";
2009   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2010
2011   my ($query, @values);
2012
2013   if (!$self->{openinvoices}) {
2014     my $where;
2015     if ($self->{customernumber} ne "") {
2016       $where = qq|(vc.customernumber ILIKE ?)|;
2017       push(@values, '%' . $self->{customernumber} . '%');
2018     } else {
2019       $where = qq|(vc.name ILIKE ?)|;
2020       push(@values, '%' . $self->{$table} . '%');
2021     }
2022
2023     $query =
2024       qq~SELECT vc.id, vc.name,
2025            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2026          FROM $table vc
2027          WHERE $where AND (NOT vc.obsolete)
2028          ORDER BY vc.name~;
2029   } else {
2030     $query =
2031       qq~SELECT DISTINCT vc.id, vc.name,
2032            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2033          FROM $arap a
2034          JOIN $table vc ON (a.${table}_id = vc.id)
2035          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2036          ORDER BY vc.name~;
2037     push(@values, '%' . $self->{$table} . '%');
2038   }
2039
2040   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2041
2042   $main::lxdebug->leave_sub();
2043
2044   return scalar(@{ $self->{name_list} });
2045 }
2046
2047 # the selection sub is used in the AR, AP, IS, IR and OE module
2048 #
2049 sub all_vc {
2050   $main::lxdebug->enter_sub();
2051
2052   my ($self, $myconfig, $table, $module) = @_;
2053
2054   my $ref;
2055   my $dbh = $self->get_standard_dbh($myconfig);
2056
2057   $table = $table eq "customer" ? "customer" : "vendor";
2058
2059   my $query = qq|SELECT count(*) FROM $table|;
2060   my ($count) = selectrow_query($self, $dbh, $query);
2061
2062   # build selection list
2063   if ($count < $myconfig->{vclimit}) {
2064     $query = qq|SELECT id, name, salesman_id
2065                 FROM $table WHERE NOT obsolete
2066                 ORDER BY name|;
2067     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2068   }
2069
2070   # get self
2071   $self->get_employee($dbh);
2072
2073   # setup sales contacts
2074   $query = qq|SELECT e.id, e.name
2075               FROM employee e
2076               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2077   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2078
2079   # this is for self
2080   push(@{ $self->{all_employees} },
2081        { id   => $self->{employee_id},
2082          name => $self->{employee} });
2083
2084   # sort the whole thing
2085   @{ $self->{all_employees} } =
2086     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2087
2088   if ($module eq 'AR') {
2089
2090     # prepare query for departments
2091     $query = qq|SELECT id, description
2092                 FROM department
2093                 WHERE role = 'P'
2094                 ORDER BY description|;
2095
2096   } else {
2097     $query = qq|SELECT id, description
2098                 FROM department
2099                 ORDER BY description|;
2100   }
2101
2102   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2103
2104   # get languages
2105   $query = qq|SELECT id, description
2106               FROM language
2107               ORDER BY id|;
2108
2109   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2110
2111   # get printer
2112   $query = qq|SELECT printer_description, id
2113               FROM printers
2114               ORDER BY printer_description|;
2115
2116   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2117
2118   # get payment terms
2119   $query = qq|SELECT id, description
2120               FROM payment_terms
2121               ORDER BY sortkey|;
2122
2123   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2124
2125   $main::lxdebug->leave_sub();
2126 }
2127
2128 sub language_payment {
2129   $main::lxdebug->enter_sub();
2130
2131   my ($self, $myconfig) = @_;
2132
2133   my $dbh = $self->get_standard_dbh($myconfig);
2134   # get languages
2135   my $query = qq|SELECT id, description
2136                  FROM language
2137                  ORDER BY id|;
2138
2139   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2140
2141   # get printer
2142   $query = qq|SELECT printer_description, id
2143               FROM printers
2144               ORDER BY printer_description|;
2145
2146   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2147
2148   # get payment terms
2149   $query = qq|SELECT id, description
2150               FROM payment_terms
2151               ORDER BY sortkey|;
2152
2153   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2154
2155   # get buchungsgruppen
2156   $query = qq|SELECT id, description
2157               FROM buchungsgruppen|;
2158
2159   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2160
2161   $main::lxdebug->leave_sub();
2162 }
2163
2164 # this is only used for reports
2165 sub all_departments {
2166   $main::lxdebug->enter_sub();
2167
2168   my ($self, $myconfig, $table) = @_;
2169
2170   my $dbh = $self->get_standard_dbh($myconfig);
2171   my $where;
2172
2173   if ($table eq 'customer') {
2174     $where = "WHERE role = 'P' ";
2175   }
2176
2177   my $query = qq|SELECT id, description
2178                  FROM department
2179                  $where
2180                  ORDER BY description|;
2181   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2182
2183   delete($self->{all_departments}) unless (@{ $self->{all_departments} });
2184
2185   $main::lxdebug->leave_sub();
2186 }
2187
2188 sub create_links {
2189   $main::lxdebug->enter_sub();
2190
2191   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2192
2193   my ($fld, $arap);
2194   if ($table eq "customer") {
2195     $fld = "buy";
2196     $arap = "ar";
2197   } else {
2198     $table = "vendor";
2199     $fld = "sell";
2200     $arap = "ap";
2201   }
2202
2203   $self->all_vc($myconfig, $table, $module);
2204
2205   # get last customers or vendors
2206   my ($query, $sth, $ref);
2207
2208   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2209   my %xkeyref = ();
2210
2211   if (!$self->{id}) {
2212
2213     my $transdate = "current_date";
2214     if ($self->{transdate}) {
2215       $transdate = $dbh->quote($self->{transdate});
2216     }
2217
2218     # now get the account numbers
2219     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2220                 FROM chart c, taxkeys tk
2221                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2222                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2223                 ORDER BY c.accno|;
2224
2225     $sth = $dbh->prepare($query);
2226
2227     do_statement($self, $sth, $query, '%' . $module . '%');
2228
2229     $self->{accounts} = "";
2230     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2231
2232       foreach my $key (split(/:/, $ref->{link})) {
2233         if ($key =~ /\Q$module\E/) {
2234
2235           # cross reference for keys
2236           $xkeyref{ $ref->{accno} } = $key;
2237
2238           push @{ $self->{"${module}_links"}{$key} },
2239             { accno       => $ref->{accno},
2240               description => $ref->{description},
2241               taxkey      => $ref->{taxkey_id},
2242               tax_id      => $ref->{tax_id} };
2243
2244           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2245         }
2246       }
2247     }
2248   }
2249
2250   # get taxkeys and description
2251   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2252   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2253
2254   if (($module eq "AP") || ($module eq "AR")) {
2255     # get tax rates and description
2256     $query = qq|SELECT * FROM tax|;
2257     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2258   }
2259
2260   if ($self->{id}) {
2261     $query =
2262       qq|SELECT
2263            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2264            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2265            a.intnotes, a.department_id, a.amount AS oldinvtotal,
2266            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2267            c.name AS $table,
2268            d.description AS department,
2269            e.name AS employee
2270          FROM $arap a
2271          JOIN $table c ON (a.${table}_id = c.id)
2272          LEFT JOIN employee e ON (e.id = a.employee_id)
2273          LEFT JOIN department d ON (d.id = a.department_id)
2274          WHERE a.id = ?|;
2275     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2276
2277     foreach $key (keys %$ref) {
2278       $self->{$key} = $ref->{$key};
2279     }
2280
2281     my $transdate = "current_date";
2282     if ($self->{transdate}) {
2283       $transdate = $dbh->quote($self->{transdate});
2284     }
2285
2286     # now get the account numbers
2287     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2288                 FROM chart c
2289                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2290                 WHERE c.link LIKE ?
2291                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2292                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2293                 ORDER BY c.accno|;
2294
2295     $sth = $dbh->prepare($query);
2296     do_statement($self, $sth, $query, "%$module%");
2297
2298     $self->{accounts} = "";
2299     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2300
2301       foreach my $key (split(/:/, $ref->{link})) {
2302         if ($key =~ /\Q$module\E/) {
2303
2304           # cross reference for keys
2305           $xkeyref{ $ref->{accno} } = $key;
2306
2307           push @{ $self->{"${module}_links"}{$key} },
2308             { accno       => $ref->{accno},
2309               description => $ref->{description},
2310               taxkey      => $ref->{taxkey_id},
2311               tax_id      => $ref->{tax_id} };
2312
2313           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2314         }
2315       }
2316     }
2317
2318
2319     # get amounts from individual entries
2320     $query =
2321       qq|SELECT
2322            c.accno, c.description,
2323            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2324            p.projectnumber,
2325            t.rate, t.id
2326          FROM acc_trans a
2327          LEFT JOIN chart c ON (c.id = a.chart_id)
2328          LEFT JOIN project p ON (p.id = a.project_id)
2329          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2330                                     WHERE (tk.taxkey_id=a.taxkey) AND
2331                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2332                                         THEN tk.chart_id = a.chart_id
2333                                         ELSE 1 = 1
2334                                         END)
2335                                        OR (c.link='%tax%')) AND
2336                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2337          WHERE a.trans_id = ?
2338          AND a.fx_transaction = '0'
2339          ORDER BY a.oid, a.transdate|;
2340     $sth = $dbh->prepare($query);
2341     do_statement($self, $sth, $query, $self->{id});
2342
2343     # get exchangerate for currency
2344     $self->{exchangerate} =
2345       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2346     my $index = 0;
2347
2348     # store amounts in {acc_trans}{$key} for multiple accounts
2349     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2350       $ref->{exchangerate} =
2351         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2352       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2353         $index++;
2354       }
2355       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2356         $ref->{amount} *= -1;
2357       }
2358       $ref->{index} = $index;
2359
2360       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2361     }
2362
2363     $sth->finish;
2364     $query =
2365       qq|SELECT
2366            d.curr AS currencies, d.closedto, d.revtrans,
2367            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2368            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2369          FROM defaults d|;
2370     $ref = selectfirst_hashref_query($self, $dbh, $query);
2371     map { $self->{$_} = $ref->{$_} } keys %$ref;
2372
2373   } else {
2374
2375     # get date
2376     $query =
2377        qq|SELECT
2378             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2379             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2380             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2381           FROM defaults d|;
2382     $ref = selectfirst_hashref_query($self, $dbh, $query);
2383     map { $self->{$_} = $ref->{$_} } keys %$ref;
2384
2385     if ($self->{"$self->{vc}_id"}) {
2386
2387       # only setup currency
2388       ($self->{currency}) = split(/:/, $self->{currencies});
2389
2390     } else {
2391
2392       $self->lastname_used($dbh, $myconfig, $table, $module);
2393
2394       # get exchangerate for currency
2395       $self->{exchangerate} =
2396         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2397
2398     }
2399
2400   }
2401
2402   $main::lxdebug->leave_sub();
2403 }
2404
2405 sub lastname_used {
2406   $main::lxdebug->enter_sub();
2407
2408   my ($self, $dbh, $myconfig, $table, $module) = @_;
2409
2410   my $arap  = ($table eq 'customer') ? "ar" : "ap";
2411   $table = $table eq "customer" ? "customer" : "vendor";
2412   my $where = "1 = 1";
2413
2414   if ($self->{type} =~ /_order/) {
2415     $arap  = 'oe';
2416     $where = "quotation = '0'";
2417   }
2418   if ($self->{type} =~ /_quotation/) {
2419     $arap  = 'oe';
2420     $where = "quotation = '1'";
2421   }
2422
2423   my $query = qq|SELECT MAX(id) FROM $arap
2424                  WHERE $where AND ${table}_id > 0|;
2425   my ($trans_id) = selectrow_query($self, $dbh, $query);
2426
2427   $trans_id *= 1;
2428   $query =
2429     qq|SELECT
2430          a.curr, a.${table}_id, a.department_id,
2431          d.description AS department,
2432          ct.name, current_date + ct.terms AS duedate
2433        FROM $arap a
2434        LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2435        LEFT JOIN department d ON (a.department_id = d.id)
2436        WHERE a.id = ?|;
2437   ($self->{currency},   $self->{"${table}_id"}, $self->{department_id},
2438    $self->{department}, $self->{$table},        $self->{duedate})
2439     = selectrow_query($self, $dbh, $query, $trans_id);
2440
2441   $main::lxdebug->leave_sub();
2442 }
2443
2444 sub current_date {
2445   $main::lxdebug->enter_sub();
2446
2447   my ($self, $myconfig, $thisdate, $days) = @_;
2448
2449   my $dbh = $self->get_standard_dbh($myconfig);
2450   my $query;
2451
2452   $days *= 1;
2453   if ($thisdate) {
2454     my $dateformat = $myconfig->{dateformat};
2455     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2456     $thisdate = $dbh->quote($thisdate);
2457     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2458   } else {
2459     $query = qq|SELECT current_date AS thisdate|;
2460   }
2461
2462   ($thisdate) = selectrow_query($self, $dbh, $query);
2463
2464   $main::lxdebug->leave_sub();
2465
2466   return $thisdate;
2467 }
2468
2469 sub like {
2470   $main::lxdebug->enter_sub();
2471
2472   my ($self, $string) = @_;
2473
2474   if ($string !~ /%/) {
2475     $string = "%$string%";
2476   }
2477
2478   $string =~ s/\'/\'\'/g;
2479
2480   $main::lxdebug->leave_sub();
2481
2482   return $string;
2483 }
2484
2485 sub redo_rows {
2486   $main::lxdebug->enter_sub();
2487
2488   my ($self, $flds, $new, $count, $numrows) = @_;
2489
2490   my @ndx = ();
2491
2492   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 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} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2534   my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "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   $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} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2590       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "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/\Q$self->{formname}\E//;
2597       $emailforms =~ s/\Q$self->{formname}\E//;
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  =~ /\Q$self->{formname}\E/) ? "1" : "0";
2612     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "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;