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