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