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