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