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