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