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