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