Weitere Konfigurationsvariablen in HTML-Formularen zur Verfügung stellen.
[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_webdav"}                 = $main::webdav;
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 = qq|SELECT * FROM shipto WHERE trans_id = ?|;
1524
1525   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
1526
1527   $main::lxdebug->leave_sub();
1528 }
1529
1530 sub _get_printers {
1531   $main::lxdebug->enter_sub();
1532
1533   my ($self, $dbh, $key) = @_;
1534
1535   $key = "all_printers" unless ($key);
1536
1537   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
1538
1539   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1540
1541   $main::lxdebug->leave_sub();
1542 }
1543
1544 sub _get_charts {
1545   $main::lxdebug->enter_sub();
1546
1547   my ($self, $dbh, $params) = @_;
1548
1549   $key = $params->{key};
1550   $key = "all_charts" unless ($key);
1551
1552   my $transdate = quote_db_date($params->{transdate});
1553
1554   my $query =
1555     qq|SELECT c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
1556     qq|FROM chart c | .
1557     qq|LEFT JOIN taxkeys tk ON | .
1558     qq|(tk.id = (SELECT id FROM taxkeys | .
1559     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
1560     qq|          ORDER BY startdate DESC LIMIT 1)) | .
1561     qq|ORDER BY c.accno|;
1562
1563   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1564
1565   $main::lxdebug->leave_sub();
1566 }
1567
1568 sub _get_taxcharts {
1569   $main::lxdebug->enter_sub();
1570
1571   my ($self, $dbh, $key) = @_;
1572
1573   $key = "all_taxcharts" unless ($key);
1574
1575   my $query = qq|SELECT * FROM tax ORDER BY taxkey|;
1576
1577   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1578
1579   $main::lxdebug->leave_sub();
1580 }
1581
1582 sub _get_taxzones {
1583   $main::lxdebug->enter_sub();
1584
1585   my ($self, $dbh, $key) = @_;
1586
1587   $key = "all_taxzones" unless ($key);
1588
1589   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
1590
1591   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1592
1593   $main::lxdebug->leave_sub();
1594 }
1595
1596 sub _get_employees {
1597   $main::lxdebug->enter_sub();
1598
1599   my ($self, $dbh, $key) = @_;
1600
1601   $key = "all_employees" unless ($key);
1602   $self->{$key} =
1603     selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee|);
1604
1605   $main::lxdebug->leave_sub();
1606 }
1607
1608 sub _get_business_types {
1609   $main::lxdebug->enter_sub();
1610
1611   my ($self, $dbh, $key) = @_;
1612
1613   $key = "all_business_types" unless ($key);
1614   $self->{$key} =
1615     selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
1616
1617   $main::lxdebug->leave_sub();
1618 }
1619
1620 sub _get_languages {
1621   $main::lxdebug->enter_sub();
1622
1623   my ($self, $dbh, $key) = @_;
1624
1625   $key = "all_languages" unless ($key);
1626
1627   my $query = qq|SELECT * FROM language ORDER BY id|;
1628
1629   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1630
1631   $main::lxdebug->leave_sub();
1632 }
1633
1634 sub _get_dunning_configs {
1635   $main::lxdebug->enter_sub();
1636
1637   my ($self, $dbh, $key) = @_;
1638
1639   $key = "all_dunning_configs" unless ($key);
1640
1641   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
1642
1643   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1644
1645   $main::lxdebug->leave_sub();
1646 }
1647
1648 sub _get_currencies {
1649 $main::lxdebug->enter_sub();
1650
1651   my ($self, $dbh, $key) = @_;
1652
1653   $key = "all_currencies" unless ($key);
1654
1655   my $query = qq|SELECT curr AS currency FROM defaults|;
1656  
1657   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
1658
1659   $main::lxdebug->leave_sub();
1660 }
1661
1662 sub _get_payments {
1663 $main::lxdebug->enter_sub();
1664
1665   my ($self, $dbh, $key) = @_;
1666
1667   $key = "all_payments" unless ($key);
1668
1669   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
1670  
1671   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1672
1673   $main::lxdebug->leave_sub();
1674 }
1675
1676 sub _get_customers {
1677   $main::lxdebug->enter_sub();
1678
1679   my ($self, $dbh, $key) = @_;
1680
1681   $key = "all_customers" unless ($key);
1682
1683   my $query = qq|SELECT * FROM customer|;
1684
1685   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1686
1687   $main::lxdebug->leave_sub();
1688 }
1689
1690 sub _get_vendors {
1691   $main::lxdebug->enter_sub();
1692
1693   my ($self, $dbh, $key) = @_;
1694
1695   $key = "all_vendors" unless ($key);
1696
1697   my $query = qq|SELECT * FROM vendor|;
1698
1699   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1700
1701   $main::lxdebug->leave_sub();
1702 }
1703
1704 sub _get_departments {
1705   $main::lxdebug->enter_sub();
1706
1707   my ($self, $dbh, $key) = @_;
1708
1709   $key = "all_departments" unless ($key);
1710
1711   my $query = qq|SELECT * FROM department|;
1712
1713   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1714
1715   $main::lxdebug->leave_sub();
1716 }
1717
1718 sub get_lists {
1719   $main::lxdebug->enter_sub();
1720
1721   my $self = shift;
1722   my %params = @_;
1723
1724   my $dbh = $self->dbconnect(\%main::myconfig);
1725   my ($sth, $query, $ref);
1726
1727   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
1728   my $vc_id = $self->{"${vc}_id"};
1729
1730   if ($params{"contacts"}) {
1731     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
1732   }
1733
1734   if ($params{"shipto"}) {
1735     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
1736   }
1737
1738   if ($params{"projects"} || $params{"all_projects"}) {
1739     $self->_get_projects($dbh, $params{"all_projects"} ?
1740                          $params{"all_projects"} : $params{"projects"},
1741                          $params{"all_projects"} ? 1 : 0);
1742   }
1743
1744   if ($params{"printers"}) {
1745     $self->_get_printers($dbh, $params{"printers"});
1746   }
1747
1748   if ($params{"languages"}) {
1749     $self->_get_languages($dbh, $params{"languages"});
1750   }
1751
1752   if ($params{"charts"}) {
1753     $self->_get_charts($dbh, $params{"charts"});
1754   }
1755
1756   if ($params{"taxcharts"}) {
1757     $self->_get_taxcharts($dbh, $params{"taxcharts"});
1758   }
1759
1760   if ($params{"taxzones"}) {
1761     $self->_get_taxzones($dbh, $params{"taxzones"});
1762   }
1763
1764   if ($params{"employees"}) {
1765     $self->_get_employees($dbh, $params{"employees"});
1766   }
1767
1768   if ($params{"business_types"}) {
1769     $self->_get_business_types($dbh, $params{"business_types"});
1770   }
1771
1772   if ($params{"dunning_configs"}) {
1773     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
1774   }
1775   
1776   if($params{"currencies"}) {
1777     $self->_get_currencies($dbh, $params{"currencies"});
1778   }
1779   
1780   if($params{"customers"}) {
1781     $self->_get_customers($dbh, $params{"customers"});
1782   }
1783   
1784   if($params{"vendors"}) {
1785     $self->_get_vendors($dbh, $params{"vendors"});
1786   }
1787   
1788   if($params{"payments"}) {
1789     $self->_get_payments($dbh, $params{"payments"});
1790   }
1791
1792   if($params{"departments"}) {
1793     $self->_get_departments($dbh, $params{"departments"});
1794   }
1795
1796   $dbh->disconnect();
1797
1798   $main::lxdebug->leave_sub();
1799 }
1800
1801 # this sub gets the id and name from $table
1802 sub get_name {
1803   $main::lxdebug->enter_sub();
1804
1805   my ($self, $myconfig, $table) = @_;
1806
1807   # connect to database
1808   my $dbh = $self->dbconnect($myconfig);
1809
1810   $table = $table eq "customer" ? "customer" : "vendor";
1811   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
1812
1813   my ($query, @values);
1814
1815   if (!$self->{openinvoices}) {
1816     my $where;
1817     if ($self->{customernumber} ne "") {
1818       $where = qq|(vc.customernumber ILIKE ?)|;
1819       push(@values, '%' . $self->{customernumber} . '%');
1820     } else {
1821       $where = qq|(vc.name ILIKE ?)|;
1822       push(@values, '%' . $self->{$table} . '%');
1823     }
1824
1825     $query =
1826       qq~SELECT vc.id, vc.name,
1827            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
1828          FROM $table vc
1829          WHERE $where AND (NOT vc.obsolete)
1830          ORDER BY vc.name~;
1831   } else {
1832     $query =
1833       qq~SELECT DISTINCT vc.id, vc.name,
1834            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
1835          FROM $arap a
1836          JOIN $table vc ON (a.${table}_id = vc.id)
1837          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
1838          ORDER BY vc.name~;
1839     push(@values, '%' . $self->{$table} . '%');
1840   }
1841
1842   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
1843
1844   $main::lxdebug->leave_sub();
1845
1846   return scalar(@{ $self->{name_list} });
1847 }
1848
1849 # the selection sub is used in the AR, AP, IS, IR and OE module
1850 #
1851 sub all_vc {
1852   $main::lxdebug->enter_sub();
1853
1854   my ($self, $myconfig, $table, $module) = @_;
1855
1856   my $ref;
1857   my $dbh = $self->dbconnect($myconfig);
1858
1859   $table = $table eq "customer" ? "customer" : "vendor";
1860
1861   my $query = qq|SELECT count(*) FROM $table|;
1862   my ($count) = selectrow_query($self, $dbh, $query);
1863
1864   # build selection list
1865   if ($count < $myconfig->{vclimit}) {
1866     $query = qq|SELECT id, name, salesman_id
1867                 FROM $table WHERE NOT obsolete
1868                 ORDER BY name|;
1869     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
1870   }
1871
1872   # get self
1873   $self->get_employee($dbh);
1874
1875   # setup sales contacts
1876   $query = qq|SELECT e.id, e.name
1877               FROM employee e
1878               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
1879   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
1880
1881   # this is for self
1882   push(@{ $self->{all_employees} },
1883        { id   => $self->{employee_id},
1884          name => $self->{employee} });
1885
1886   # sort the whole thing
1887   @{ $self->{all_employees} } =
1888     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
1889
1890   if ($module eq 'AR') {
1891
1892     # prepare query for departments
1893     $query = qq|SELECT id, description
1894                 FROM department
1895                 WHERE role = 'P'
1896                 ORDER BY description|;
1897
1898   } else {
1899     $query = qq|SELECT id, description
1900                 FROM department
1901                 ORDER BY description|;
1902   }
1903
1904   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
1905
1906   # get languages
1907   $query = qq|SELECT id, description
1908               FROM language
1909               ORDER BY id|;
1910
1911   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
1912
1913   # get printer
1914   $query = qq|SELECT printer_description, id
1915               FROM printers
1916               ORDER BY printer_description|;
1917
1918   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
1919
1920   # get payment terms
1921   $query = qq|SELECT id, description
1922               FROM payment_terms
1923               ORDER BY sortkey|;
1924
1925   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
1926
1927   $dbh->disconnect;
1928
1929   $main::lxdebug->leave_sub();
1930 }
1931
1932 sub language_payment {
1933   $main::lxdebug->enter_sub();
1934
1935   my ($self, $myconfig) = @_;
1936
1937   my $dbh = $self->dbconnect($myconfig);
1938   # get languages
1939   my $query = qq|SELECT id, description
1940                  FROM language
1941                  ORDER BY id|;
1942
1943   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
1944
1945   # get printer
1946   $query = qq|SELECT printer_description, id
1947               FROM printers
1948               ORDER BY printer_description|;
1949
1950   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
1951
1952   # get payment terms
1953   $query = qq|SELECT id, description
1954               FROM payment_terms
1955               ORDER BY sortkey|;
1956
1957   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
1958
1959   # get buchungsgruppen
1960   $query = qq|SELECT id, description
1961               FROM buchungsgruppen|;
1962
1963   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
1964
1965   $dbh->disconnect;
1966   $main::lxdebug->leave_sub();
1967 }
1968
1969 # this is only used for reports
1970 sub all_departments {
1971   $main::lxdebug->enter_sub();
1972
1973   my ($self, $myconfig, $table) = @_;
1974
1975   my $dbh = $self->dbconnect($myconfig);
1976   my $where;
1977
1978   if ($table eq 'customer') {
1979     $where = "WHERE role = 'P' ";
1980   }
1981
1982   my $query = qq|SELECT id, description
1983                  FROM department
1984                  $where
1985                  ORDER BY description|;
1986   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
1987
1988   delete($self->{all_departments}) unless (@{ $self->{all_departments} });
1989
1990   $dbh->disconnect;
1991
1992   $main::lxdebug->leave_sub();
1993 }
1994
1995 sub create_links {
1996   $main::lxdebug->enter_sub();
1997
1998   my ($self, $module, $myconfig, $table) = @_;
1999
2000   my ($fld, $arap);
2001   if ($table eq "customer") {
2002     $fld = "buy";
2003     $arap = "ar";
2004   } else {
2005     $table = "vendor";
2006     $fld = "sell";
2007     $arap = "ap";
2008   }
2009
2010   $self->all_vc($myconfig, $table, $module);
2011
2012   # get last customers or vendors
2013   my ($query, $sth, $ref);
2014
2015   my $dbh = $self->dbconnect($myconfig);
2016   my %xkeyref = ();
2017
2018   if (!$self->{id}) {
2019
2020     my $transdate = "current_date";
2021     if ($self->{transdate}) {
2022       $transdate = $dbh->quote($self->{transdate});
2023     }
2024
2025     # now get the account numbers
2026     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2027                 FROM chart c, taxkeys tk
2028                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2029                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2030                 ORDER BY c.accno|;
2031
2032     $sth = $dbh->prepare($query);
2033
2034     do_statement($self, $sth, $query, '%' . $module . '%');
2035
2036     $self->{accounts} = "";
2037     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2038
2039       foreach my $key (split(/:/, $ref->{link})) {
2040         if ($key =~ /$module/) {
2041
2042           # cross reference for keys
2043           $xkeyref{ $ref->{accno} } = $key;
2044
2045           push @{ $self->{"${module}_links"}{$key} },
2046             { accno       => $ref->{accno},
2047               description => $ref->{description},
2048               taxkey      => $ref->{taxkey_id},
2049               tax_id      => $ref->{tax_id} };
2050
2051           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2052         }
2053       }
2054     }
2055   }
2056
2057   # get taxkeys and description
2058   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2059   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2060
2061   if (($module eq "AP") || ($module eq "AR")) {
2062     # get tax rates and description
2063     $query = qq|SELECT * FROM tax|;
2064     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2065   }
2066
2067   if ($self->{id}) {
2068     $query =
2069       qq|SELECT
2070            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2071            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2072            a.intnotes, a.department_id, a.amount AS oldinvtotal,
2073            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2074            c.name AS $table,
2075            d.description AS department,
2076            e.name AS employee
2077          FROM $arap a
2078          JOIN $table c ON (a.${table}_id = c.id)
2079          LEFT JOIN employee e ON (e.id = a.employee_id)
2080          LEFT JOIN department d ON (d.id = a.department_id)
2081          WHERE a.id = ?|;
2082     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2083
2084     foreach $key (keys %$ref) {
2085       $self->{$key} = $ref->{$key};
2086     }
2087
2088     my $transdate = "current_date";
2089     if ($self->{transdate}) {
2090       $transdate = $dbh->quote($self->{transdate});
2091     }
2092
2093     # now get the account numbers
2094     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2095                 FROM chart c
2096                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2097                 WHERE c.link LIKE ?
2098                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2099                     OR c.link LIKE '%_tax%')
2100                 ORDER BY c.accno|;
2101
2102     $sth = $dbh->prepare($query);
2103     do_statement($self, $sth, $query, "%$module%");
2104
2105     $self->{accounts} = "";
2106     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2107
2108       foreach my $key (split(/:/, $ref->{link})) {
2109         if ($key =~ /$module/) {
2110
2111           # cross reference for keys
2112           $xkeyref{ $ref->{accno} } = $key;
2113
2114           push @{ $self->{"${module}_links"}{$key} },
2115             { accno       => $ref->{accno},
2116               description => $ref->{description},
2117               taxkey      => $ref->{taxkey_id},
2118               tax_id      => $ref->{tax_id} };
2119
2120           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2121         }
2122       }
2123     }
2124
2125
2126     # get amounts from individual entries
2127     $query =
2128       qq|SELECT
2129            c.accno, c.description,
2130            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2131            p.projectnumber,
2132            t.rate, t.id
2133          FROM acc_trans a
2134          LEFT JOIN chart c ON (c.id = a.chart_id)
2135          LEFT JOIN project p ON (p.id = a.project_id)
2136          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2137                                     WHERE (tk.taxkey_id=a.taxkey) AND
2138                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2139                                         THEN tk.chart_id = a.chart_id
2140                                         ELSE 1 = 1
2141                                         END)
2142                                        OR (c.link='%tax%')) AND
2143                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2144          WHERE a.trans_id = ?
2145          AND a.fx_transaction = '0'
2146          ORDER BY a.oid, a.transdate|;
2147     $sth = $dbh->prepare($query);
2148     do_statement($self, $sth, $query, $self->{id});
2149
2150     # get exchangerate for currency
2151     $self->{exchangerate} =
2152       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2153     my $index = 0;
2154
2155     # store amounts in {acc_trans}{$key} for multiple accounts
2156     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2157       $ref->{exchangerate} =
2158         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2159       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2160         $index++;
2161       }
2162       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2163         $ref->{amount} *= -1;
2164       }
2165       $ref->{index} = $index;
2166
2167       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2168     }
2169
2170     $sth->finish;
2171     $query =
2172       qq|SELECT
2173            d.curr AS currencies, d.closedto, d.revtrans,
2174            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2175            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2176          FROM defaults d|;
2177     $ref = selectfirst_hashref_query($self, $dbh, $query);
2178     map { $self->{$_} = $ref->{$_} } keys %$ref;
2179
2180   } else {
2181
2182     # get date
2183     $query =
2184        qq|SELECT
2185             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2186             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2187             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2188           FROM defaults d|;
2189     $ref = selectfirst_hashref_query($self, $dbh, $query);
2190     map { $self->{$_} = $ref->{$_} } keys %$ref;
2191
2192     if ($self->{"$self->{vc}_id"}) {
2193
2194       # only setup currency
2195       ($self->{currency}) = split(/:/, $self->{currencies});
2196
2197     } else {
2198
2199       $self->lastname_used($dbh, $myconfig, $table, $module);
2200
2201       # get exchangerate for currency
2202       $self->{exchangerate} =
2203         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2204
2205     }
2206
2207   }
2208
2209   $dbh->disconnect;
2210
2211   $main::lxdebug->leave_sub();
2212 }
2213
2214 sub lastname_used {
2215   $main::lxdebug->enter_sub();
2216
2217   my ($self, $dbh, $myconfig, $table, $module) = @_;
2218
2219   my $arap  = ($table eq 'customer') ? "ar" : "ap";
2220   $table = $table eq "customer" ? "customer" : "vendor";
2221   my $where = "1 = 1";
2222
2223   if ($self->{type} =~ /_order/) {
2224     $arap  = 'oe';
2225     $where = "quotation = '0'";
2226   }
2227   if ($self->{type} =~ /_quotation/) {
2228     $arap  = 'oe';
2229     $where = "quotation = '1'";
2230   }
2231
2232   my $query = qq|SELECT MAX(id) FROM $arap
2233                  WHERE $where AND ${table}_id > 0|;
2234   my ($trans_id) = selectrow_query($self, $dbh, $query);
2235
2236   $trans_id *= 1;
2237   $query =
2238     qq|SELECT
2239          a.curr, a.${table}_id, a.department_id,
2240          d.description AS department,
2241          ct.name, current_date + ct.terms AS duedate
2242        FROM $arap a
2243        LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2244        LEFT JOIN department d ON (a.department_id = d.id)
2245        WHERE a.id = ?|;
2246   ($self->{currency},   $self->{"${table}_id"}, $self->{department_id},
2247    $self->{department}, $self->{$table},        $self->{duedate})
2248     = selectrow_query($self, $dbh, $query, $trans_id);
2249
2250   $main::lxdebug->leave_sub();
2251 }
2252
2253 sub current_date {
2254   $main::lxdebug->enter_sub();
2255
2256   my ($self, $myconfig, $thisdate, $days) = @_;
2257
2258   my $dbh = $self->dbconnect($myconfig);
2259   my $query;
2260
2261   $days *= 1;
2262   if ($thisdate) {
2263     my $dateformat = $myconfig->{dateformat};
2264     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2265     $thisdate = $dbh->quote($thisdate);
2266     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2267   } else {
2268     $query = qq|SELECT current_date AS thisdate|;
2269   }
2270
2271   ($thisdate) = selectrow_query($self, $dbh, $query);
2272
2273   $dbh->disconnect;
2274
2275   $main::lxdebug->leave_sub();
2276
2277   return $thisdate;
2278 }
2279
2280 sub like {
2281   $main::lxdebug->enter_sub();
2282
2283   my ($self, $string) = @_;
2284
2285   if ($string !~ /%/) {
2286     $string = "%$string%";
2287   }
2288
2289   $string =~ s/\'/\'\'/g;
2290
2291   $main::lxdebug->leave_sub();
2292
2293   return $string;
2294 }
2295
2296 sub redo_rows {
2297   $main::lxdebug->enter_sub();
2298
2299   my ($self, $flds, $new, $count, $numrows) = @_;
2300
2301   my @ndx = ();
2302
2303   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } }
2304     (1 .. $count);
2305
2306   my $i = 0;
2307
2308   # fill rows
2309   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2310     $i++;
2311     $j = $item->{ndx} - 1;
2312     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2313   }
2314
2315   # delete empty rows
2316   for $i ($count + 1 .. $numrows) {
2317     map { delete $self->{"${_}_$i"} } @{$flds};
2318   }
2319
2320   $main::lxdebug->leave_sub();
2321 }
2322
2323 sub update_status {
2324   $main::lxdebug->enter_sub();
2325
2326   my ($self, $myconfig) = @_;
2327
2328   my ($i, $id);
2329
2330   my $dbh = $self->dbconnect_noauto($myconfig);
2331
2332   my $query = qq|DELETE FROM status
2333                  WHERE (formname = ?) AND (trans_id = ?)|;
2334   my $sth = prepare_query($self, $dbh, $query);
2335
2336   if ($self->{formname} =~ /(check|receipt)/) {
2337     for $i (1 .. $self->{rowcount}) {
2338       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
2339     }
2340   } else {
2341     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
2342   }
2343   $sth->finish();
2344
2345   my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
2346   my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
2347
2348   my %queued = split / /, $self->{queued};
2349   my @values;
2350
2351   if ($self->{formname} =~ /(check|receipt)/) {
2352
2353     # this is a check or receipt, add one entry for each lineitem
2354     my ($accno) = split /--/, $self->{account};
2355     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
2356                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
2357     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
2358     $sth = prepare_query($self, $dbh, $query);
2359
2360     for $i (1 .. $self->{rowcount}) {
2361       if ($self->{"checked_$i"}) {
2362         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
2363       }
2364     }
2365     $sth->finish();
2366
2367   } else {
2368     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2369                 VALUES (?, ?, ?, ?, ?)|;
2370     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
2371              $queued{$self->{formname}}, $self->{formname});
2372   }
2373
2374   $dbh->commit;
2375   $dbh->disconnect;
2376
2377   $main::lxdebug->leave_sub();
2378 }
2379
2380 sub save_status {
2381   $main::lxdebug->enter_sub();
2382
2383   my ($self, $dbh) = @_;
2384
2385   my ($query, $printed, $emailed);
2386
2387   my $formnames  = $self->{printed};
2388   my $emailforms = $self->{emailed};
2389
2390   my $query = qq|DELETE FROM status
2391                  WHERE (formname = ?) AND (trans_id = ?)|;
2392   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
2393
2394   # this only applies to the forms
2395   # checks and receipts are posted when printed or queued
2396
2397   if ($self->{queued}) {
2398     my %queued = split / /, $self->{queued};
2399
2400     foreach my $formname (keys %queued) {
2401       $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
2402       $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
2403
2404       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2405                   VALUES (?, ?, ?, ?, ?)|;
2406       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
2407
2408       $formnames  =~ s/$self->{formname}//;
2409       $emailforms =~ s/$self->{formname}//;
2410
2411     }
2412   }
2413
2414   # save printed, emailed info
2415   $formnames  =~ s/^ +//g;
2416   $emailforms =~ s/^ +//g;
2417
2418   my %status = ();
2419   map { $status{$_}{printed} = 1 } split / +/, $formnames;
2420   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
2421
2422   foreach my $formname (keys %status) {
2423     $printed = ($formnames  =~ /$self->{formname}/) ? "1" : "0";
2424     $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
2425
2426     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
2427                 VALUES (?, ?, ?, ?)|;
2428     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
2429   }
2430
2431   $main::lxdebug->leave_sub();
2432 }
2433
2434 #--- 4 locale ---#
2435 # $main::locale->text('SAVED')
2436 # $main::locale->text('DELETED')
2437 # $main::locale->text('ADDED')
2438 # $main::locale->text('PAYMENT POSTED')
2439 # $main::locale->text('POSTED')
2440 # $main::locale->text('POSTED AS NEW')
2441 # $main::locale->text('ELSE')
2442 # $main::locale->text('SAVED FOR DUNNING')
2443 # $main::locale->text('DUNNING STARTED')
2444 # $main::locale->text('PRINTED')
2445 # $main::locale->text('MAILED')
2446 # $main::locale->text('SCREENED')
2447 # $main::locale->text('CANCELED')
2448 # $main::locale->text('invoice')
2449 # $main::locale->text('proforma')
2450 # $main::locale->text('sales_order')
2451 # $main::locale->text('packing_list')
2452 # $main::locale->text('pick_list')
2453 # $main::locale->text('purchase_order')
2454 # $main::locale->text('bin_list')
2455 # $main::locale->text('sales_quotation')
2456 # $main::locale->text('request_quotation')
2457
2458 sub save_history {
2459   $main::lxdebug->enter_sub();
2460
2461   my $self = shift();
2462   my $dbh = shift();
2463
2464   if(!exists $self->{employee_id}) {
2465     &get_employee($self, $dbh);
2466   }
2467
2468   my $query =
2469     qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
2470     qq|VALUES (?, ?, ?, ?, ?)|;
2471   my @values = (conv_i($self->{id}), conv_i($self->{employee_id}),
2472                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
2473   do_query($self, $dbh, $query, @values);
2474
2475   $main::lxdebug->leave_sub();
2476 }
2477
2478 sub get_history {
2479   $main::lxdebug->enter_sub();
2480
2481   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
2482   my ($orderBy, $desc) = split(/\-\-/, $order);
2483   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
2484   my @tempArray;
2485   my $i = 0;
2486   if ($trans_id ne "") {
2487     my $query =
2488       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 | .
2489       qq|FROM history_erp h | .
2490       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
2491       qq|WHERE trans_id = ? |. $order
2492       . $restriction;
2493
2494     my $sth = $dbh->prepare($query) || $self->dberror($query);
2495
2496     $sth->execute($trans_id) || $self->dberror("$query ($trans_id)");
2497
2498     while(my $hash_ref = $sth->fetchrow_hashref()) {
2499       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
2500       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
2501       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
2502       $tempArray[$i++] = $hash_ref;
2503     }
2504     $main::lxdebug->leave_sub() and return \@tempArray 
2505       if ($i > 0 && $tempArray[0] ne "");
2506   }
2507   $main::lxdebug->leave_sub();
2508   return 0;
2509 }
2510
2511 sub update_defaults {
2512   $main::lxdebug->enter_sub();
2513
2514   my ($self, $myconfig, $fld, $provided_dbh) = @_;
2515
2516   my $dbh;
2517   if ($provided_dbh) {
2518     $dbh = $provided_dbh;
2519   } else {
2520     $dbh = $self->dbconnect_noauto($myconfig);
2521   }
2522   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
2523   my $sth   = $dbh->prepare($query);
2524
2525   $sth->execute || $self->dberror($query);
2526   my ($var) = $sth->fetchrow_array;
2527   $sth->finish;
2528
2529   $var =~ s/\d+$/ sprintf '%0*d', length($&), $&+1 /e;
2530   $var ||= 1;
2531
2532   $query = qq|UPDATE defaults SET $fld = ?|;
2533   do_query($self, $dbh, $query, $var);
2534
2535   if (!$provided_dbh) {
2536     $dbh->commit;
2537     $dbh->disconnect;
2538   }
2539
2540   $main::lxdebug->leave_sub();
2541
2542   return $var;
2543 }
2544
2545 sub update_business {
2546   $main::lxdebug->enter_sub();
2547
2548   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
2549
2550   my $dbh;
2551   if ($provided_dbh) {
2552     $dbh = $provided_dbh;
2553   } else {
2554     $dbh = $self->dbconnect_noauto($myconfig);
2555   }
2556   my $query =
2557     qq|SELECT customernumberinit FROM business
2558        WHERE id = ? FOR UPDATE|;
2559   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
2560
2561   $var =~ s/\d+$/ sprintf '%0*d', length($&), $&+1 /e;
2562   
2563   $query = qq|UPDATE business
2564               SET customernumberinit = ?
2565               WHERE id = ?|;
2566   do_query($self, $dbh, $query, $var, $business_id);
2567
2568   if (!$provided_dbh) {
2569     $dbh->commit;
2570     $dbh->disconnect;
2571   }
2572
2573   $main::lxdebug->leave_sub();
2574
2575   return $var;
2576 }
2577
2578 sub get_partsgroup {
2579   $main::lxdebug->enter_sub();
2580
2581   my ($self, $myconfig, $p) = @_;
2582
2583   my $dbh = $self->dbconnect($myconfig);
2584
2585   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
2586                  FROM partsgroup pg
2587                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
2588   my @values;
2589
2590   if ($p->{searchitems} eq 'part') {
2591     $query .= qq|WHERE p.inventory_accno_id > 0|;
2592   }
2593   if ($p->{searchitems} eq 'service') {
2594     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
2595   }
2596   if ($p->{searchitems} eq 'assembly') {
2597     $query .= qq|WHERE p.assembly = '1'|;
2598   }
2599   if ($p->{searchitems} eq 'labor') {
2600     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
2601   }
2602
2603   $query .= qq|ORDER BY partsgroup|;
2604
2605   if ($p->{all}) {
2606     $query = qq|SELECT id, partsgroup FROM partsgroup
2607                 ORDER BY partsgroup|;
2608   }
2609
2610   if ($p->{language_code}) {
2611     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
2612                   t.description AS translation
2613                 FROM partsgroup pg
2614                 JOIN parts p ON (p.partsgroup_id = pg.id)
2615                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
2616                 ORDER BY translation|;
2617     @values = ($p->{language_code});
2618   }
2619
2620   $self->{all_partsgroup} = selectall_hashref_query($self, $dbh, $query, @values);
2621
2622   $dbh->disconnect;
2623   $main::lxdebug->leave_sub();
2624 }
2625
2626 sub get_pricegroup {
2627   $main::lxdebug->enter_sub();
2628
2629   my ($self, $myconfig, $p) = @_;
2630
2631   my $dbh = $self->dbconnect($myconfig);
2632
2633   my $query = qq|SELECT p.id, p.pricegroup
2634                  FROM pricegroup p|;
2635
2636   $query .= qq| ORDER BY pricegroup|;
2637
2638   if ($p->{all}) {
2639     $query = qq|SELECT id, pricegroup FROM pricegroup
2640                 ORDER BY pricegroup|;
2641   }
2642
2643   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
2644
2645   $dbh->disconnect;
2646
2647   $main::lxdebug->leave_sub();
2648 }
2649
2650 sub all_years {
2651 # usage $form->all_years($myconfig, [$dbh])
2652 # return list of all years where bookings found
2653 # (@all_years)
2654
2655   $main::lxdebug->enter_sub();
2656
2657   my ($self, $myconfig, $dbh) = @_;
2658
2659   my $disconnect = 0;
2660   if (! $dbh) {
2661     $dbh = $self->dbconnect($myconfig);
2662     $disconnect = 1;
2663   }
2664
2665   # get years
2666   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
2667                    (SELECT MAX(transdate) FROM acc_trans)|;
2668   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
2669
2670   if ($myconfig->{dateformat} =~ /^yy/) {
2671     ($startdate) = split /\W/, $startdate;
2672     ($enddate) = split /\W/, $enddate;
2673   } else {
2674     (@_) = split /\W/, $startdate;
2675     $startdate = $_[2];
2676     (@_) = split /\W/, $enddate;
2677     $enddate = $_[2];
2678   }
2679
2680   my @all_years;
2681   $startdate = substr($startdate,0,4);
2682   $enddate = substr($enddate,0,4);
2683
2684   while ($enddate >= $startdate) {
2685     push @all_years, $enddate--;
2686   }
2687
2688   $dbh->disconnect if $disconnect;
2689
2690   return @all_years;
2691
2692   $main::lxdebug->leave_sub();
2693 }
2694
2695
2696 1;