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