d8077528f03bb12bc7bf3f324e6838e8f1edb944
[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   my $myconfig         = \%main::myconfig;
923   my $amount           = $params{amount} * 1;
924   my $places           = $params{places};
925   my $part_unit_name   = $params{part_unit};
926   my $amount_unit_name = $params{amount_unit};
927   my $conv_units       = $params{conv_units};
928   my $max_places       = $params{max_places};
929
930   if (!$part_unit_name) {
931     $main::lxdebug->leave_sub();
932     return '';
933   }
934
935   AM->retrieve_all_units();
936   my $all_units        = $main::all_units;
937
938   if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
939     $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
940   }
941
942   if (!scalar @{ $conv_units }) {
943     my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
944     $main::lxdebug->leave_sub();
945     return $result;
946   }
947
948   my $part_unit  = $all_units->{$part_unit_name};
949   my $conv_unit  = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
950
951   $amount       *= $conv_unit->{factor};
952
953   my @values;
954
955   foreach my $unit (@$conv_units) {
956     my $last = $unit->{name} eq $part_unit->{name};
957     if (!$last) {
958       $num     = int($amount / $unit->{factor});
959       $amount -= $num * $unit->{factor};
960     }
961
962     if ($last ? $amount : $num) {
963       push @values, { "unit"   => $unit->{name},
964                       "amount" => $last ? $amount / $unit->{factor} : $num,
965                       "places" => $last ? $places : 0 };
966     }
967
968     last if $last;
969   }
970
971   if (!@values) {
972     push @values, { "unit"   => $part_unit_name,
973                     "amount" => 0,
974                     "places" => 0 };
975   }
976
977   my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
978
979   $main::lxdebug->leave_sub();
980
981   return $result;
982 }
983
984 sub format_string {
985   $main::lxdebug->enter_sub(2);
986
987   my $self  = shift;
988   my $input = shift;
989
990   $input =~ s/(^|[^\#]) \#  (\d+)  /$1$_[$2 - 1]/gx;
991   $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
992   $input =~ s/\#\#/\#/g;
993
994   $main::lxdebug->leave_sub(2);
995
996   return $input;
997 }
998
999 #
1000
1001 sub parse_amount {
1002   $main::lxdebug->enter_sub(2);
1003
1004   my ($self, $myconfig, $amount) = @_;
1005
1006   if (   ($myconfig->{numberformat} eq '1.000,00')
1007       || ($myconfig->{numberformat} eq '1000,00')) {
1008     $amount =~ s/\.//g;
1009     $amount =~ s/,/\./;
1010   }
1011
1012   if ($myconfig->{numberformat} eq "1'000.00") {
1013     $amount =~ s/\'//g;
1014   }
1015
1016   $amount =~ s/,//g;
1017
1018   $main::lxdebug->leave_sub(2);
1019
1020   return ($amount * 1);
1021 }
1022
1023 sub round_amount {
1024   $main::lxdebug->enter_sub(2);
1025
1026   my ($self, $amount, $places) = @_;
1027   my $round_amount;
1028
1029   # Rounding like "Kaufmannsrunden"
1030   # Descr. http://de.wikipedia.org/wiki/Rundung
1031   # Inspired by
1032   # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
1033   # Solves Bug: 189
1034   # Udo Spallek
1035   $amount = $amount * (10**($places));
1036   $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
1037
1038   $main::lxdebug->leave_sub(2);
1039
1040   return $round_amount;
1041
1042 }
1043
1044 sub parse_template {
1045   $main::lxdebug->enter_sub();
1046
1047   my ($self, $myconfig, $userspath) = @_;
1048   my ($template, $out);
1049
1050   local (*IN, *OUT);
1051
1052   $self->{"cwd"} = getcwd();
1053   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
1054
1055   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
1056     $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1057   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
1058     $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
1059     $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1060   } elsif (($self->{"format"} =~ /html/i) ||
1061            (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
1062     $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1063   } elsif (($self->{"format"} =~ /xml/i) ||
1064              (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
1065     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1066   } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
1067     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1068   } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
1069     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1070   } elsif ( defined $self->{'format'}) {
1071     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
1072   } elsif ( $self->{'format'} eq '' ) {
1073     $self->error("No Outputformat given: $self->{'format'}");
1074   } else { #Catch the rest
1075     $self->error("Outputformat not defined: $self->{'format'}");
1076   }
1077
1078   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
1079   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
1080
1081   map({ $self->{"employee_${_}"} = $myconfig->{$_}; }
1082       qw(email tel fax name signature company address businessnumber
1083          co_ustid taxnumber duns));
1084
1085   map({ $self->{"${_}"} = $myconfig->{$_}; }
1086       qw(co_ustid));
1087               
1088
1089   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
1090
1091   # OUT is used for the media, screen, printer, email
1092   # for postscript we store a copy in a temporary file
1093   my $fileid = time;
1094   my $prepend_userspath;
1095
1096   if (!$self->{tmpfile}) {
1097     $self->{tmpfile}   = "${fileid}.$self->{IN}";
1098     $prepend_userspath = 1;
1099   }
1100
1101   $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
1102
1103   $self->{tmpfile} =~ s|.*/||;
1104   $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
1105   $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
1106
1107   if ($template->uses_temp_file() || $self->{media} eq 'email') {
1108     $out = $self->{OUT};
1109     $self->{OUT} = ">$self->{tmpfile}";
1110   }
1111
1112   if ($self->{OUT}) {
1113     open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
1114   } else {
1115     open(OUT, ">-") or $self->error("STDOUT : $!");
1116     $self->header;
1117   }
1118
1119   if (!$template->parse(*OUT)) {
1120     $self->cleanup();
1121     $self->error("$self->{IN} : " . $template->get_error());
1122   }
1123
1124   close(OUT);
1125
1126   if ($template->uses_temp_file() || $self->{media} eq 'email') {
1127
1128     if ($self->{media} eq 'email') {
1129
1130       my $mail = new Mailer;
1131
1132       map { $mail->{$_} = $self->{$_} }
1133         qw(cc bcc subject message version format);
1134       $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
1135       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1136       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1137       $mail->{fileid} = "$fileid.";
1138       $myconfig->{signature} =~ s/\r//g;
1139
1140       # if we send html or plain text inline
1141       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1142         $mail->{contenttype} = "text/html";
1143
1144         $mail->{message}       =~ s/\r//g;
1145         $mail->{message}       =~ s/\n/<br>\n/g;
1146         $myconfig->{signature} =~ s/\n/<br>\n/g;
1147         $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
1148
1149         open(IN, $self->{tmpfile})
1150           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1151         while (<IN>) {
1152           $mail->{message} .= $_;
1153         }
1154
1155         close(IN);
1156
1157       } else {
1158
1159         if (!$self->{"do_not_attach"}) {
1160           @{ $mail->{attachments} } =
1161             ({ "filename" => $self->{"tmpfile"},
1162                "name" => $self->{"attachment_filename"} ?
1163                  $self->{"attachment_filename"} : $self->{"tmpfile"} });
1164         }
1165
1166         $mail->{message}  =~ s/\r//g;
1167         $mail->{message} .=  "\n-- \n$myconfig->{signature}";
1168
1169       }
1170
1171       my $err = $mail->send();
1172       $self->error($self->cleanup . "$err") if ($err);
1173
1174     } else {
1175
1176       $self->{OUT} = $out;
1177
1178       my $numbytes = (-s $self->{tmpfile});
1179       open(IN, $self->{tmpfile})
1180         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1181
1182       $self->{copies} = 1 unless $self->{media} eq 'printer';
1183
1184       chdir("$self->{cwd}");
1185       #print(STDERR "Kopien $self->{copies}\n");
1186       #print(STDERR "OUT $self->{OUT}\n");
1187       for my $i (1 .. $self->{copies}) {
1188         if ($self->{OUT}) {
1189           open(OUT, $self->{OUT})
1190             or $self->error($self->cleanup . "$self->{OUT} : $!");
1191         } else {
1192           $self->{attachment_filename} = ($self->{attachment_filename}) 
1193                                        ? $self->{attachment_filename}
1194                                        : $self->generate_attachment_filename();
1195
1196           # launch application
1197           print qq|Content-Type: | . $template->get_mime_type() . qq|
1198 Content-Disposition: attachment; filename="$self->{attachment_filename}"
1199 Content-Length: $numbytes
1200
1201 |;
1202
1203           open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
1204
1205         }
1206
1207         while (<IN>) {
1208           print OUT $_;
1209         }
1210
1211         close(OUT);
1212
1213         seek IN, 0, 0;
1214       }
1215
1216       close(IN);
1217     }
1218
1219   }
1220
1221   $self->cleanup;
1222
1223   chdir("$self->{cwd}");
1224   $main::lxdebug->leave_sub();
1225 }
1226
1227 sub get_formname_translation {
1228   my ($self, $formname) = @_;
1229
1230   $formname ||= $self->{formname};
1231
1232   my %formname_translations = (
1233     bin_list                => $main::locale->text('Bin List'),
1234     credit_note             => $main::locale->text('Credit Note'),
1235     invoice                 => $main::locale->text('Invoice'),
1236     packing_list            => $main::locale->text('Packing List'),
1237     pick_list               => $main::locale->text('Pick List'),
1238     proforma                => $main::locale->text('Proforma Invoice'),
1239     purchase_order          => $main::locale->text('Purchase Order'),
1240     request_quotation       => $main::locale->text('RFQ'),
1241     sales_order             => $main::locale->text('Confirmation'),
1242     sales_quotation         => $main::locale->text('Quotation'),
1243     storno_invoice          => $main::locale->text('Storno Invoice'),
1244     storno_packing_list     => $main::locale->text('Storno Packing List'),
1245     sales_delivery_order    => $main::locale->text('Delivery Order'),
1246     purchase_delivery_order => $main::locale->text('Delivery Order'),
1247   );
1248
1249   return $formname_translations{$formname}
1250 }
1251
1252 sub get_number_prefix_for_type {
1253   my ($self) = @_;
1254
1255   my $prefix =
1256       (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1257     : ($self->{type} =~ /_quotation$/)                        ? 'quo'
1258     : ($self->{type} =~ /_delivery_order$/)                   ? 'do'
1259     :                                                           'ord';
1260
1261   return $prefix;
1262 }
1263
1264 sub get_extension_for_format {
1265   my ($self)    = @_;
1266
1267   my $extension = $self->{format} =~ /pdf/i          ? ".pdf"
1268                 : $self->{format} =~ /postscript/i   ? ".ps"
1269                 : $self->{format} =~ /opendocument/i ? ".odt"
1270                 : $self->{format} =~ /html/i         ? ".html"
1271                 :                                      "";
1272
1273   return $extension;
1274 }
1275
1276 sub generate_attachment_filename {
1277   my ($self) = @_;
1278
1279   my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1280   my $prefix              = $self->get_number_prefix_for_type();
1281
1282   if ($attachment_filename && $self->{"${prefix}number"}) {
1283     $attachment_filename .=  "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1284     $attachment_filename  =  $main::locale->quote_special_chars('filenames', $attachment_filename);
1285     $attachment_filename  =~ s|[\s/\\]+|_|g;
1286   } else {
1287     $attachment_filename = "";
1288   }
1289
1290   return $attachment_filename;
1291 }
1292
1293 sub generate_email_subject {
1294   my ($self) = @_;
1295
1296   my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1297   my $prefix  = $self->get_number_prefix_for_type();
1298
1299   if ($subject && $self->{"${prefix}number"}) {
1300     $subject .= " " . $self->{"${prefix}number"}
1301   }
1302
1303   return $subject;
1304 }
1305
1306 sub cleanup {
1307   $main::lxdebug->enter_sub();
1308
1309   my $self = shift;
1310
1311   chdir("$self->{tmpdir}");
1312
1313   my @err = ();
1314   if (-f "$self->{tmpfile}.err") {
1315     open(FH, "$self->{tmpfile}.err");
1316     @err = <FH>;
1317     close(FH);
1318   }
1319
1320   if ($self->{tmpfile}) {
1321     $self->{tmpfile} =~ s|.*/||g;
1322     # strip extension
1323     $self->{tmpfile} =~ s/\.\w+$//g;
1324     my $tmpfile = $self->{tmpfile};
1325     unlink(<$tmpfile.*>);
1326   }
1327
1328   chdir("$self->{cwd}");
1329
1330   $main::lxdebug->leave_sub();
1331
1332   return "@err";
1333 }
1334
1335 sub datetonum {
1336   $main::lxdebug->enter_sub();
1337
1338   my ($self, $date, $myconfig) = @_;
1339
1340   if ($date && $date =~ /\D/) {
1341
1342     if ($myconfig->{dateformat} =~ /^yy/) {
1343       ($yy, $mm, $dd) = split /\D/, $date;
1344     }
1345     if ($myconfig->{dateformat} =~ /^mm/) {
1346       ($mm, $dd, $yy) = split /\D/, $date;
1347     }
1348     if ($myconfig->{dateformat} =~ /^dd/) {
1349       ($dd, $mm, $yy) = split /\D/, $date;
1350     }
1351
1352     $dd *= 1;
1353     $mm *= 1;
1354     $yy = ($yy < 70) ? $yy + 2000 : $yy;
1355     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1356
1357     $dd = "0$dd" if ($dd < 10);
1358     $mm = "0$mm" if ($mm < 10);
1359
1360     $date = "$yy$mm$dd";
1361   }
1362
1363   $main::lxdebug->leave_sub();
1364
1365   return $date;
1366 }
1367
1368 # Database routines used throughout
1369
1370 sub dbconnect {
1371   $main::lxdebug->enter_sub(2);
1372
1373   my ($self, $myconfig) = @_;
1374
1375   # connect to database
1376   my $dbh =
1377     DBI->connect($myconfig->{dbconnect},
1378                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
1379     or $self->dberror;
1380
1381   # set db options
1382   if ($myconfig->{dboptions}) {
1383     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1384   }
1385
1386   $main::lxdebug->leave_sub(2);
1387
1388   return $dbh;
1389 }
1390
1391 sub dbconnect_noauto {
1392   $main::lxdebug->enter_sub();
1393
1394   my ($self, $myconfig) = @_;
1395   
1396   # connect to database
1397   $dbh =
1398     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1399                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
1400     or $self->dberror;
1401
1402   # set db options
1403   if ($myconfig->{dboptions}) {
1404     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1405   }
1406
1407   $main::lxdebug->leave_sub();
1408
1409   return $dbh;
1410 }
1411
1412 sub get_standard_dbh {
1413   $main::lxdebug->enter_sub(2);
1414
1415   my ($self, $myconfig) = @_;
1416
1417   if ($standard_dbh && !$standard_dbh->{Active}) {
1418     $main::lxdebug->message(LXDebug::INFO, "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
1419     undef $standard_dbh;
1420   }
1421
1422   $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1423
1424   $main::lxdebug->leave_sub(2);
1425
1426   return $standard_dbh;
1427 }
1428
1429 sub date_closed {
1430   $main::lxdebug->enter_sub();
1431
1432   my ($self, $date, $myconfig) = @_;
1433   my $dbh = $self->dbconnect($myconfig);
1434
1435   my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1436   my $sth = prepare_execute_query($self, $dbh, $query, $date);
1437   my ($closed) = $sth->fetchrow_array;
1438
1439   $main::lxdebug->leave_sub();
1440
1441   return $closed;
1442 }
1443
1444 sub update_balance {
1445   $main::lxdebug->enter_sub();
1446
1447   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1448
1449   # if we have a value, go do it
1450   if ($value != 0) {
1451
1452     # retrieve balance from table
1453     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1454     my $sth = prepare_execute_query($self, $dbh, $query, @values);
1455     my ($balance) = $sth->fetchrow_array;
1456     $sth->finish;
1457
1458     $balance += $value;
1459
1460     # update balance
1461     $query = "UPDATE $table SET $field = $balance WHERE $where";
1462     do_query($self, $dbh, $query, @values);
1463   }
1464   $main::lxdebug->leave_sub();
1465 }
1466
1467 sub update_exchangerate {
1468   $main::lxdebug->enter_sub();
1469
1470   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1471   my ($query);
1472   # some sanity check for currency
1473   if ($curr eq '') {
1474     $main::lxdebug->leave_sub();
1475     return;
1476   }  
1477   $query = qq|SELECT curr FROM defaults|;
1478
1479   my ($currency) = selectrow_query($self, $dbh, $query);
1480   my ($defaultcurrency) = split m/:/, $currency;
1481
1482
1483   if ($curr eq $defaultcurrency) {
1484     $main::lxdebug->leave_sub();
1485     return;
1486   }
1487
1488   $query = qq|SELECT e.curr FROM exchangerate e
1489                  WHERE e.curr = ? AND e.transdate = ?
1490                  FOR UPDATE|;
1491   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1492
1493   if ($buy == 0) {
1494     $buy = "";
1495   }
1496   if ($sell == 0) {
1497     $sell = "";
1498   }
1499
1500   $buy = conv_i($buy, "NULL");
1501   $sell = conv_i($sell, "NULL");
1502
1503   my $set;
1504   if ($buy != 0 && $sell != 0) {
1505     $set = "buy = $buy, sell = $sell";
1506   } elsif ($buy != 0) {
1507     $set = "buy = $buy";
1508   } elsif ($sell != 0) {
1509     $set = "sell = $sell";
1510   }
1511
1512   if ($sth->fetchrow_array) {
1513     $query = qq|UPDATE exchangerate
1514                 SET $set
1515                 WHERE curr = ?
1516                 AND transdate = ?|;
1517     
1518   } else {
1519     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1520                 VALUES (?, $buy, $sell, ?)|;
1521   }
1522   $sth->finish;
1523   do_query($self, $dbh, $query, $curr, $transdate);
1524
1525   $main::lxdebug->leave_sub();
1526 }
1527
1528 sub save_exchangerate {
1529   $main::lxdebug->enter_sub();
1530
1531   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1532
1533   my $dbh = $self->dbconnect($myconfig);
1534
1535   my ($buy, $sell);
1536
1537   $buy  = $rate if $fld eq 'buy';
1538   $sell = $rate if $fld eq 'sell';
1539
1540
1541   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1542
1543
1544   $dbh->disconnect;
1545
1546   $main::lxdebug->leave_sub();
1547 }
1548
1549 sub get_exchangerate {
1550   $main::lxdebug->enter_sub();
1551
1552   my ($self, $dbh, $curr, $transdate, $fld) = @_;
1553   my ($query);
1554
1555   unless ($transdate) {
1556     $main::lxdebug->leave_sub();
1557     return 1;
1558   }
1559
1560   $query = qq|SELECT curr FROM defaults|;
1561
1562   my ($currency) = selectrow_query($self, $dbh, $query);
1563   my ($defaultcurrency) = split m/:/, $currency;
1564
1565   if ($currency eq $defaultcurrency) {
1566     $main::lxdebug->leave_sub();
1567     return 1;
1568   }
1569
1570   $query = qq|SELECT e.$fld FROM exchangerate e
1571                  WHERE e.curr = ? AND e.transdate = ?|;
1572   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1573
1574
1575
1576   $main::lxdebug->leave_sub();
1577
1578   return $exchangerate;
1579 }
1580
1581 sub check_exchangerate {
1582   $main::lxdebug->enter_sub();
1583
1584   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1585
1586   unless ($transdate) {
1587     $main::lxdebug->leave_sub();
1588     return "";
1589   }
1590
1591   my ($defaultcurrency) = $self->get_default_currency($myconfig);
1592
1593   if ($currency eq $defaultcurrency) {
1594     $main::lxdebug->leave_sub();
1595     return 1;
1596   }
1597
1598   my $dbh   = $self->get_standard_dbh($myconfig);
1599   my $query = qq|SELECT e.$fld FROM exchangerate e
1600                  WHERE e.curr = ? AND e.transdate = ?|;
1601
1602   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1603
1604   $main::lxdebug->leave_sub();
1605
1606   return $exchangerate;
1607 }
1608
1609 sub get_default_currency {
1610   $main::lxdebug->enter_sub();
1611
1612   my ($self, $myconfig) = @_;
1613   my $dbh = $self->get_standard_dbh($myconfig);
1614
1615   my $query = qq|SELECT curr FROM defaults|;
1616
1617   my ($curr)            = selectrow_query($self, $dbh, $query);
1618   my ($defaultcurrency) = split m/:/, $curr;
1619
1620   $main::lxdebug->leave_sub();
1621
1622   return $defaultcurrency;
1623 }
1624
1625
1626 sub set_payment_options {
1627   $main::lxdebug->enter_sub();
1628
1629   my ($self, $myconfig, $transdate) = @_;
1630
1631   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1632
1633   my $dbh = $self->get_standard_dbh($myconfig);
1634
1635   my $query =
1636     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1637     qq|FROM payment_terms p | .
1638     qq|WHERE p.id = ?|;
1639
1640   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1641    $self->{payment_terms}) =
1642      selectrow_query($self, $dbh, $query, $self->{payment_id});
1643
1644   if ($transdate eq "") {
1645     if ($self->{invdate}) {
1646       $transdate = $self->{invdate};
1647     } else {
1648       $transdate = $self->{transdate};
1649     }
1650   }
1651
1652   $query =
1653     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1654     qq|FROM payment_terms|;
1655   ($self->{netto_date}, $self->{skonto_date}) =
1656     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1657
1658   my ($invtotal, $total);
1659   my (%amounts, %formatted_amounts);
1660
1661   if ($self->{type} =~ /_order$/) {
1662     $amounts{invtotal} = $self->{ordtotal};
1663     $amounts{total}    = $self->{ordtotal};
1664
1665   } elsif ($self->{type} =~ /_quotation$/) {
1666     $amounts{invtotal} = $self->{quototal};
1667     $amounts{total}    = $self->{quototal};
1668
1669   } else {
1670     $amounts{invtotal} = $self->{invtotal};
1671     $amounts{total}    = $self->{total};
1672   }
1673
1674   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1675
1676   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
1677   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1678   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
1679
1680   foreach (keys %amounts) {
1681     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
1682     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1683   }
1684
1685   if ($self->{"language_id"}) {
1686     $query =
1687       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1688       qq|FROM translation_payment_terms t | .
1689       qq|LEFT JOIN language l ON t.language_id = l.id | .
1690       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1691     my ($description_long, $output_numberformat, $output_dateformat,
1692       $output_longdates) =
1693       selectrow_query($self, $dbh, $query,
1694                       $self->{"language_id"}, $self->{"payment_id"});
1695
1696     $self->{payment_terms} = $description_long if ($description_long);
1697
1698     if ($output_dateformat) {
1699       foreach my $key (qw(netto_date skonto_date)) {
1700         $self->{$key} =
1701           $main::locale->reformat_date($myconfig, $self->{$key},
1702                                        $output_dateformat,
1703                                        $output_longdates);
1704       }
1705     }
1706
1707     if ($output_numberformat &&
1708         ($output_numberformat ne $myconfig->{"numberformat"})) {
1709       my $saved_numberformat = $myconfig->{"numberformat"};
1710       $myconfig->{"numberformat"} = $output_numberformat;
1711       map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1712       $myconfig->{"numberformat"} = $saved_numberformat;
1713     }
1714   }
1715
1716   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1717   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1718   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1719   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1720   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1721   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1722   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1723
1724   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1725
1726   $main::lxdebug->leave_sub();
1727
1728 }
1729
1730 sub get_template_language {
1731   $main::lxdebug->enter_sub();
1732
1733   my ($self, $myconfig) = @_;
1734
1735   my $template_code = "";
1736
1737   if ($self->{language_id}) {
1738     my $dbh = $self->get_standard_dbh($myconfig);
1739     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1740     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1741   }
1742
1743   $main::lxdebug->leave_sub();
1744
1745   return $template_code;
1746 }
1747
1748 sub get_printer_code {
1749   $main::lxdebug->enter_sub();
1750
1751   my ($self, $myconfig) = @_;
1752
1753   my $template_code = "";
1754
1755   if ($self->{printer_id}) {
1756     my $dbh = $self->get_standard_dbh($myconfig);
1757     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1758     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1759   }
1760
1761   $main::lxdebug->leave_sub();
1762
1763   return $template_code;
1764 }
1765
1766 sub get_shipto {
1767   $main::lxdebug->enter_sub();
1768
1769   my ($self, $myconfig) = @_;
1770
1771   my $template_code = "";
1772
1773   if ($self->{shipto_id}) {
1774     my $dbh = $self->get_standard_dbh($myconfig);
1775     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1776     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1777     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1778   }
1779
1780   $main::lxdebug->leave_sub();
1781 }
1782
1783 sub add_shipto {
1784   $main::lxdebug->enter_sub();
1785
1786   my ($self, $dbh, $id, $module) = @_;
1787
1788   my $shipto;
1789   my @values;
1790
1791   foreach my $item (qw(name department_1 department_2 street zipcode city country
1792                        contact phone fax email)) {
1793     if ($self->{"shipto$item"}) {
1794       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1795     }
1796     push(@values, $self->{"shipto${item}"});
1797   }
1798
1799   if ($shipto) {
1800     if ($self->{shipto_id}) {
1801       my $query = qq|UPDATE shipto set
1802                        shiptoname = ?,
1803                        shiptodepartment_1 = ?,
1804                        shiptodepartment_2 = ?,
1805                        shiptostreet = ?,
1806                        shiptozipcode = ?,
1807                        shiptocity = ?,
1808                        shiptocountry = ?,
1809                        shiptocontact = ?,
1810                        shiptophone = ?,
1811                        shiptofax = ?,
1812                        shiptoemail = ?
1813                      WHERE shipto_id = ?|;
1814       do_query($self, $dbh, $query, @values, $self->{shipto_id});
1815     } else {
1816       my $query = qq|SELECT * FROM shipto
1817                      WHERE shiptoname = ? AND
1818                        shiptodepartment_1 = ? AND
1819                        shiptodepartment_2 = ? AND
1820                        shiptostreet = ? AND
1821                        shiptozipcode = ? AND
1822                        shiptocity = ? AND
1823                        shiptocountry = ? AND
1824                        shiptocontact = ? AND
1825                        shiptophone = ? AND
1826                        shiptofax = ? AND
1827                        shiptoemail = ? AND
1828                        module = ? AND 
1829                        trans_id = ?|;
1830       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1831       if(!$insert_check){
1832         $query =
1833           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1834                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
1835                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
1836              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1837         do_query($self, $dbh, $query, $id, @values, $module);
1838       }
1839     }
1840   }
1841
1842   $main::lxdebug->leave_sub();
1843 }
1844
1845 sub get_employee {
1846   $main::lxdebug->enter_sub();
1847
1848   my ($self, $dbh) = @_;
1849
1850   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1851   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1852   $self->{"employee_id"} *= 1;
1853
1854   $main::lxdebug->leave_sub();
1855 }
1856
1857 sub get_salesman {
1858   $main::lxdebug->enter_sub();
1859
1860   my ($self, $myconfig, $salesman_id) = @_;
1861
1862   $main::lxdebug->leave_sub() and return unless $salesman_id;
1863
1864   my $dbh = $self->get_standard_dbh($myconfig);
1865
1866   my ($login) =
1867     selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|,
1868                     $salesman_id);
1869
1870   if ($login) {
1871     my $user = new User($main::memberfile, $login);
1872     map({ $self->{"salesman_$_"} = $user->{$_}; }
1873         qw(address businessnumber co_ustid company duns email fax name
1874            taxnumber tel));
1875     $self->{salesman_login} = $login;
1876
1877     $self->{salesman_name} = $login
1878       if ($self->{salesman_name} eq "");
1879   }
1880
1881   $main::lxdebug->leave_sub();
1882 }
1883
1884 sub get_duedate {
1885   $main::lxdebug->enter_sub();
1886
1887   my ($self, $myconfig) = @_;
1888
1889   my $dbh = $self->get_standard_dbh($myconfig);
1890   my $query = qq|SELECT current_date + terms_netto FROM payment_terms WHERE id = ?|;
1891   ($self->{duedate}) = selectrow_query($self, $dbh, $query, $self->{payment_id});
1892
1893   $main::lxdebug->leave_sub();
1894 }
1895
1896 sub _get_contacts {
1897   $main::lxdebug->enter_sub();
1898
1899   my ($self, $dbh, $id, $key) = @_;
1900
1901   $key = "all_contacts" unless ($key);
1902
1903   if (!$id) {
1904     $self->{$key} = [];
1905     $main::lxdebug->leave_sub();
1906     return;
1907   }
1908
1909   my $query =
1910     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
1911     qq|FROM contacts | .
1912     qq|WHERE cp_cv_id = ? | .
1913     qq|ORDER BY lower(cp_name)|;
1914
1915   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
1916
1917   $main::lxdebug->leave_sub();
1918 }
1919
1920 sub _get_projects {
1921   $main::lxdebug->enter_sub();
1922
1923   my ($self, $dbh, $key) = @_;
1924
1925   my ($all, $old_id, $where, @values);
1926
1927   if (ref($key) eq "HASH") {
1928     my $params = $key;
1929
1930     $key = "ALL_PROJECTS";
1931
1932     foreach my $p (keys(%{$params})) {
1933       if ($p eq "all") {
1934         $all = $params->{$p};
1935       } elsif ($p eq "old_id") {
1936         $old_id = $params->{$p};
1937       } elsif ($p eq "key") {
1938         $key = $params->{$p};
1939       }
1940     }
1941   }
1942
1943   if (!$all) {
1944     $where = "WHERE active ";
1945     if ($old_id) {
1946       if (ref($old_id) eq "ARRAY") {
1947         my @ids = grep({ $_ } @{$old_id});
1948         if (@ids) {
1949           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
1950           push(@values, @ids);
1951         }
1952       } else {
1953         $where .= " OR (id = ?) ";
1954         push(@values, $old_id);
1955       }
1956     }
1957   }
1958
1959   my $query =
1960     qq|SELECT id, projectnumber, description, active | .
1961     qq|FROM project | .
1962     $where .
1963     qq|ORDER BY lower(projectnumber)|;
1964
1965   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
1966
1967   $main::lxdebug->leave_sub();
1968 }
1969
1970 sub _get_shipto {
1971   $main::lxdebug->enter_sub();
1972
1973   my ($self, $dbh, $vc_id, $key) = @_;
1974
1975   $key = "all_shipto" unless ($key);
1976
1977   if ($vc_id) {
1978     # get shipping addresses
1979     my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
1980
1981     $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
1982
1983   } else {
1984     $self->{$key} = [];
1985   }
1986
1987   $main::lxdebug->leave_sub();
1988 }
1989
1990 sub _get_printers {
1991   $main::lxdebug->enter_sub();
1992
1993   my ($self, $dbh, $key) = @_;
1994
1995   $key = "all_printers" unless ($key);
1996
1997   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
1998
1999   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2000
2001   $main::lxdebug->leave_sub();
2002 }
2003
2004 sub _get_charts {
2005   $main::lxdebug->enter_sub();
2006
2007   my ($self, $dbh, $params) = @_;
2008
2009   $key = $params->{key};
2010   $key = "all_charts" unless ($key);
2011
2012   my $transdate = quote_db_date($params->{transdate});
2013
2014   my $query =
2015     qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
2016     qq|FROM chart c | .
2017     qq|LEFT JOIN taxkeys tk ON | .
2018     qq|(tk.id = (SELECT id FROM taxkeys | .
2019     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2020     qq|          ORDER BY startdate DESC LIMIT 1)) | .
2021     qq|ORDER BY c.accno|;
2022
2023   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2024
2025   $main::lxdebug->leave_sub();
2026 }
2027
2028 sub _get_taxcharts {
2029   $main::lxdebug->enter_sub();
2030
2031   my ($self, $dbh, $key) = @_;
2032
2033   $key = "all_taxcharts" unless ($key);
2034
2035   my $query = qq|SELECT * FROM tax ORDER BY taxkey|;
2036
2037   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2038
2039   $main::lxdebug->leave_sub();
2040 }
2041
2042 sub _get_taxzones {
2043   $main::lxdebug->enter_sub();
2044
2045   my ($self, $dbh, $key) = @_;
2046
2047   $key = "all_taxzones" unless ($key);
2048
2049   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
2050
2051   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2052
2053   $main::lxdebug->leave_sub();
2054 }
2055
2056 sub _get_employees {
2057   $main::lxdebug->enter_sub();
2058
2059   my ($self, $dbh, $default_key, $key) = @_;
2060
2061   $key = $default_key unless ($key);
2062   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
2063
2064   $main::lxdebug->leave_sub();
2065 }
2066
2067 sub _get_business_types {
2068   $main::lxdebug->enter_sub();
2069
2070   my ($self, $dbh, $key) = @_;
2071
2072   $key = "all_business_types" unless ($key);
2073   $self->{$key} =
2074     selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
2075
2076   $main::lxdebug->leave_sub();
2077 }
2078
2079 sub _get_languages {
2080   $main::lxdebug->enter_sub();
2081
2082   my ($self, $dbh, $key) = @_;
2083
2084   $key = "all_languages" unless ($key);
2085
2086   my $query = qq|SELECT * FROM language ORDER BY id|;
2087
2088   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2089
2090   $main::lxdebug->leave_sub();
2091 }
2092
2093 sub _get_dunning_configs {
2094   $main::lxdebug->enter_sub();
2095
2096   my ($self, $dbh, $key) = @_;
2097
2098   $key = "all_dunning_configs" unless ($key);
2099
2100   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2101
2102   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2103
2104   $main::lxdebug->leave_sub();
2105 }
2106
2107 sub _get_currencies {
2108 $main::lxdebug->enter_sub();
2109
2110   my ($self, $dbh, $key) = @_;
2111
2112   $key = "all_currencies" unless ($key);
2113
2114   my $query = qq|SELECT curr AS currency FROM defaults|;
2115  
2116   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2117
2118   $main::lxdebug->leave_sub();
2119 }
2120
2121 sub _get_payments {
2122 $main::lxdebug->enter_sub();
2123
2124   my ($self, $dbh, $key) = @_;
2125
2126   $key = "all_payments" unless ($key);
2127
2128   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
2129  
2130   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2131
2132   $main::lxdebug->leave_sub();
2133 }
2134
2135 sub _get_customers {
2136   $main::lxdebug->enter_sub();
2137
2138   my ($self, $dbh, $key, $limit) = @_;
2139
2140   $key = "all_customers" unless ($key);
2141   $limit_clause = "LIMIT $limit" if $limit;
2142
2143   my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name $limit_clause|;
2144
2145   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2146
2147   $main::lxdebug->leave_sub();
2148 }
2149
2150 sub _get_vendors {
2151   $main::lxdebug->enter_sub();
2152
2153   my ($self, $dbh, $key) = @_;
2154
2155   $key = "all_vendors" unless ($key);
2156
2157   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2158
2159   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2160
2161   $main::lxdebug->leave_sub();
2162 }
2163
2164 sub _get_departments {
2165   $main::lxdebug->enter_sub();
2166
2167   my ($self, $dbh, $key) = @_;
2168
2169   $key = "all_departments" unless ($key);
2170
2171   my $query = qq|SELECT * FROM department ORDER BY description|;
2172
2173   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2174
2175   $main::lxdebug->leave_sub();
2176 }
2177
2178 sub _get_warehouses {
2179   $main::lxdebug->enter_sub();
2180
2181   my ($self, $dbh, $param) = @_;
2182
2183   my ($key, $bins_key);
2184
2185   if ('' eq ref $param) {
2186     $key = $param;
2187
2188   } else {
2189     $key      = $param->{key};
2190     $bins_key = $param->{bins};
2191   }
2192
2193   my $query = qq|SELECT w.* FROM warehouse w
2194                  WHERE (NOT w.invalid) AND
2195                    ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2196                  ORDER BY w.sortkey|;
2197
2198   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2199
2200   if ($bins_key) {
2201     $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
2202     my $sth = prepare_query($self, $dbh, $query);
2203
2204     foreach my $warehouse (@{ $self->{$key} }) {
2205       do_statement($self, $sth, $query, $warehouse->{id});
2206       $warehouse->{$bins_key} = [];
2207
2208       while (my $ref = $sth->fetchrow_hashref()) {
2209         push @{ $warehouse->{$bins_key} }, $ref;
2210       }
2211     }
2212     $sth->finish();
2213   }
2214
2215   $main::lxdebug->leave_sub();
2216 }
2217
2218 sub _get_simple {
2219   $main::lxdebug->enter_sub();
2220
2221   my ($self, $dbh, $table, $key, $sortkey) = @_;
2222
2223   my $query  = qq|SELECT * FROM $table|;
2224   $query    .= qq| ORDER BY $sortkey| if ($sortkey);
2225
2226   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2227
2228   $main::lxdebug->leave_sub();
2229 }
2230
2231 sub _get_groups {
2232   $main::lxdebug->enter_sub();
2233
2234   my ($self, $dbh, $key) = @_;
2235
2236   $key ||= "all_groups";
2237
2238   my $groups = $main::auth->read_groups();
2239
2240   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2241
2242   $main::lxdebug->leave_sub();
2243 }
2244
2245 sub get_lists {
2246   $main::lxdebug->enter_sub();
2247
2248   my $self = shift;
2249   my %params = @_;
2250
2251   my $dbh = $self->get_standard_dbh(\%main::myconfig);
2252   my ($sth, $query, $ref);
2253
2254   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2255   my $vc_id = $self->{"${vc}_id"};
2256
2257   if ($params{"contacts"}) {
2258     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2259   }
2260
2261   if ($params{"shipto"}) {
2262     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2263   }
2264
2265   if ($params{"projects"} || $params{"all_projects"}) {
2266     $self->_get_projects($dbh, $params{"all_projects"} ?
2267                          $params{"all_projects"} : $params{"projects"},
2268                          $params{"all_projects"} ? 1 : 0);
2269   }
2270
2271   if ($params{"printers"}) {
2272     $self->_get_printers($dbh, $params{"printers"});
2273   }
2274
2275   if ($params{"languages"}) {
2276     $self->_get_languages($dbh, $params{"languages"});
2277   }
2278
2279   if ($params{"charts"}) {
2280     $self->_get_charts($dbh, $params{"charts"});
2281   }
2282
2283   if ($params{"taxcharts"}) {
2284     $self->_get_taxcharts($dbh, $params{"taxcharts"});
2285   }
2286
2287   if ($params{"taxzones"}) {
2288     $self->_get_taxzones($dbh, $params{"taxzones"});
2289   }
2290
2291   if ($params{"employees"}) {
2292     $self->_get_employees($dbh, "all_employees", $params{"employees"});
2293   }
2294   
2295   if ($params{"salesmen"}) {
2296     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2297   }
2298
2299   if ($params{"business_types"}) {
2300     $self->_get_business_types($dbh, $params{"business_types"});
2301   }
2302
2303   if ($params{"dunning_configs"}) {
2304     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2305   }
2306   
2307   if($params{"currencies"}) {
2308     $self->_get_currencies($dbh, $params{"currencies"});
2309   }
2310   
2311   if($params{"customers"}) {
2312     if (ref $params{"customers"} eq 'HASH') {
2313       $self->_get_customers($dbh, $params{"customers"}{key}, $params{"customers"}{limit});
2314     } else {
2315       $self->_get_customers($dbh, $params{"customers"});
2316     }
2317   }
2318   
2319   if($params{"vendors"}) {
2320     if (ref $params{"vendors"} eq 'HASH') {
2321       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2322     } else {
2323       $self->_get_vendors($dbh, $params{"vendors"});
2324     }
2325   }
2326   
2327   if($params{"payments"}) {
2328     $self->_get_payments($dbh, $params{"payments"});
2329   }
2330
2331   if($params{"departments"}) {
2332     $self->_get_departments($dbh, $params{"departments"});
2333   }
2334
2335   if ($params{price_factors}) {
2336     $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2337   }
2338
2339   if ($params{warehouses}) {
2340     $self->_get_warehouses($dbh, $params{warehouses});
2341   }
2342
2343   if ($params{groups}) {
2344     $self->_get_groups($dbh, $params{groups});
2345   }
2346   if ($params{partsgroup}) {
2347     $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2348   }
2349
2350   $main::lxdebug->leave_sub();
2351 }
2352
2353 # this sub gets the id and name from $table
2354 sub get_name {
2355   $main::lxdebug->enter_sub();
2356
2357   my ($self, $myconfig, $table) = @_;
2358
2359   # connect to database
2360   my $dbh = $self->get_standard_dbh($myconfig);
2361
2362   $table = $table eq "customer" ? "customer" : "vendor";
2363   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2364
2365   my ($query, @values);
2366
2367   if (!$self->{openinvoices}) {
2368     my $where;
2369     if ($self->{customernumber} ne "") {
2370       $where = qq|(vc.customernumber ILIKE ?)|;
2371       push(@values, '%' . $self->{customernumber} . '%');
2372     } else {
2373       $where = qq|(vc.name ILIKE ?)|;
2374       push(@values, '%' . $self->{$table} . '%');
2375     }
2376
2377     $query =
2378       qq~SELECT vc.id, vc.name,
2379            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2380          FROM $table vc
2381          WHERE $where AND (NOT vc.obsolete)
2382          ORDER BY vc.name~;
2383   } else {
2384     $query =
2385       qq~SELECT DISTINCT vc.id, vc.name,
2386            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2387          FROM $arap a
2388          JOIN $table vc ON (a.${table}_id = vc.id)
2389          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2390          ORDER BY vc.name~;
2391     push(@values, '%' . $self->{$table} . '%');
2392   }
2393
2394   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2395
2396   $main::lxdebug->leave_sub();
2397
2398   return scalar(@{ $self->{name_list} });
2399 }
2400
2401 # the selection sub is used in the AR, AP, IS, IR and OE module
2402 #
2403 sub all_vc {
2404   $main::lxdebug->enter_sub();
2405
2406   my ($self, $myconfig, $table, $module) = @_;
2407
2408   my $ref;
2409   my $dbh = $self->get_standard_dbh($myconfig);
2410
2411   $table = $table eq "customer" ? "customer" : "vendor";
2412
2413   my $query = qq|SELECT count(*) FROM $table|;
2414   my ($count) = selectrow_query($self, $dbh, $query);
2415
2416   # build selection list
2417   if ($count < $myconfig->{vclimit}) {
2418     $query = qq|SELECT id, name, salesman_id
2419                 FROM $table WHERE NOT obsolete
2420                 ORDER BY name|;
2421     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2422   }
2423
2424   # get self
2425   $self->get_employee($dbh);
2426
2427   # setup sales contacts
2428   $query = qq|SELECT e.id, e.name
2429               FROM employee e
2430               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2431   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2432
2433   # this is for self
2434   push(@{ $self->{all_employees} },
2435        { id   => $self->{employee_id},
2436          name => $self->{employee} });
2437
2438   # sort the whole thing
2439   @{ $self->{all_employees} } =
2440     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2441
2442   if ($module eq 'AR') {
2443
2444     # prepare query for departments
2445     $query = qq|SELECT id, description
2446                 FROM department
2447                 WHERE role = 'P'
2448                 ORDER BY description|;
2449
2450   } else {
2451     $query = qq|SELECT id, description
2452                 FROM department
2453                 ORDER BY description|;
2454   }
2455
2456   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2457
2458   # get languages
2459   $query = qq|SELECT id, description
2460               FROM language
2461               ORDER BY id|;
2462
2463   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2464
2465   # get printer
2466   $query = qq|SELECT printer_description, id
2467               FROM printers
2468               ORDER BY printer_description|;
2469
2470   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2471
2472   # get payment terms
2473   $query = qq|SELECT id, description
2474               FROM payment_terms
2475               ORDER BY sortkey|;
2476
2477   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2478
2479   $main::lxdebug->leave_sub();
2480 }
2481
2482 sub language_payment {
2483   $main::lxdebug->enter_sub();
2484
2485   my ($self, $myconfig) = @_;
2486
2487   my $dbh = $self->get_standard_dbh($myconfig);
2488   # get languages
2489   my $query = qq|SELECT id, description
2490                  FROM language
2491                  ORDER BY id|;
2492
2493   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2494
2495   # get printer
2496   $query = qq|SELECT printer_description, id
2497               FROM printers
2498               ORDER BY printer_description|;
2499
2500   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2501
2502   # get payment terms
2503   $query = qq|SELECT id, description
2504               FROM payment_terms
2505               ORDER BY sortkey|;
2506
2507   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2508
2509   # get buchungsgruppen
2510   $query = qq|SELECT id, description
2511               FROM buchungsgruppen|;
2512
2513   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2514
2515   $main::lxdebug->leave_sub();
2516 }
2517
2518 # this is only used for reports
2519 sub all_departments {
2520   $main::lxdebug->enter_sub();
2521
2522   my ($self, $myconfig, $table) = @_;
2523
2524   my $dbh = $self->get_standard_dbh($myconfig);
2525   my $where;
2526
2527   if ($table eq 'customer') {
2528     $where = "WHERE role = 'P' ";
2529   }
2530
2531   my $query = qq|SELECT id, description
2532                  FROM department
2533                  $where
2534                  ORDER BY description|;
2535   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2536
2537   delete($self->{all_departments}) unless (@{ $self->{all_departments} });
2538
2539   $main::lxdebug->leave_sub();
2540 }
2541
2542 sub create_links {
2543   $main::lxdebug->enter_sub();
2544
2545   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2546
2547   my ($fld, $arap);
2548   if ($table eq "customer") {
2549     $fld = "buy";
2550     $arap = "ar";
2551   } else {
2552     $table = "vendor";
2553     $fld = "sell";
2554     $arap = "ap";
2555   }
2556
2557   $self->all_vc($myconfig, $table, $module);
2558
2559   # get last customers or vendors
2560   my ($query, $sth, $ref);
2561
2562   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2563   my %xkeyref = ();
2564
2565   if (!$self->{id}) {
2566
2567     my $transdate = "current_date";
2568     if ($self->{transdate}) {
2569       $transdate = $dbh->quote($self->{transdate});
2570     }
2571
2572     # now get the account numbers
2573     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2574                 FROM chart c, taxkeys tk
2575                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2576                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2577                 ORDER BY c.accno|;
2578
2579     $sth = $dbh->prepare($query);
2580
2581     do_statement($self, $sth, $query, '%' . $module . '%');
2582
2583     $self->{accounts} = "";
2584     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2585
2586       foreach my $key (split(/:/, $ref->{link})) {
2587         if ($key =~ /\Q$module\E/) {
2588
2589           # cross reference for keys
2590           $xkeyref{ $ref->{accno} } = $key;
2591
2592           push @{ $self->{"${module}_links"}{$key} },
2593             { accno       => $ref->{accno},
2594               description => $ref->{description},
2595               taxkey      => $ref->{taxkey_id},
2596               tax_id      => $ref->{tax_id} };
2597
2598           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2599         }
2600       }
2601     }
2602   }
2603
2604   # get taxkeys and description
2605   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2606   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2607
2608   if (($module eq "AP") || ($module eq "AR")) {
2609     # get tax rates and description
2610     $query = qq|SELECT * FROM tax|;
2611     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2612   }
2613
2614   if ($self->{id}) {
2615     $query =
2616       qq|SELECT
2617            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2618            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2619            a.intnotes, a.department_id, a.amount AS oldinvtotal,
2620            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2621            c.name AS $table,
2622            d.description AS department,
2623            e.name AS employee
2624          FROM $arap a
2625          JOIN $table c ON (a.${table}_id = c.id)
2626          LEFT JOIN employee e ON (e.id = a.employee_id)
2627          LEFT JOIN department d ON (d.id = a.department_id)
2628          WHERE a.id = ?|;
2629     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2630
2631     foreach $key (keys %$ref) {
2632       $self->{$key} = $ref->{$key};
2633     }
2634
2635     my $transdate = "current_date";
2636     if ($self->{transdate}) {
2637       $transdate = $dbh->quote($self->{transdate});
2638     }
2639
2640     # now get the account numbers
2641     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2642                 FROM chart c
2643                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2644                 WHERE c.link LIKE ?
2645                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2646                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2647                 ORDER BY c.accno|;
2648
2649     $sth = $dbh->prepare($query);
2650     do_statement($self, $sth, $query, "%$module%");
2651
2652     $self->{accounts} = "";
2653     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2654
2655       foreach my $key (split(/:/, $ref->{link})) {
2656         if ($key =~ /\Q$module\E/) {
2657
2658           # cross reference for keys
2659           $xkeyref{ $ref->{accno} } = $key;
2660
2661           push @{ $self->{"${module}_links"}{$key} },
2662             { accno       => $ref->{accno},
2663               description => $ref->{description},
2664               taxkey      => $ref->{taxkey_id},
2665               tax_id      => $ref->{tax_id} };
2666
2667           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2668         }
2669       }
2670     }
2671
2672
2673     # get amounts from individual entries
2674     $query =
2675       qq|SELECT
2676            c.accno, c.description,
2677            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2678            p.projectnumber,
2679            t.rate, t.id
2680          FROM acc_trans a
2681          LEFT JOIN chart c ON (c.id = a.chart_id)
2682          LEFT JOIN project p ON (p.id = a.project_id)
2683          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2684                                     WHERE (tk.taxkey_id=a.taxkey) AND
2685                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2686                                         THEN tk.chart_id = a.chart_id
2687                                         ELSE 1 = 1
2688                                         END)
2689                                        OR (c.link='%tax%')) AND
2690                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2691          WHERE a.trans_id = ?
2692          AND a.fx_transaction = '0'
2693          ORDER BY a.oid, a.transdate|;
2694     $sth = $dbh->prepare($query);
2695     do_statement($self, $sth, $query, $self->{id});
2696
2697     # get exchangerate for currency
2698     $self->{exchangerate} =
2699       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2700     my $index = 0;
2701
2702     # store amounts in {acc_trans}{$key} for multiple accounts
2703     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2704       $ref->{exchangerate} =
2705         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2706       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2707         $index++;
2708       }
2709       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2710         $ref->{amount} *= -1;
2711       }
2712       $ref->{index} = $index;
2713
2714       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2715     }
2716
2717     $sth->finish;
2718     $query =
2719       qq|SELECT
2720            d.curr AS currencies, d.closedto, d.revtrans,
2721            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2722            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2723          FROM defaults d|;
2724     $ref = selectfirst_hashref_query($self, $dbh, $query);
2725     map { $self->{$_} = $ref->{$_} } keys %$ref;
2726
2727   } else {
2728
2729     # get date
2730     $query =
2731        qq|SELECT
2732             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2733             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2734             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2735           FROM defaults d|;
2736     $ref = selectfirst_hashref_query($self, $dbh, $query);
2737     map { $self->{$_} = $ref->{$_} } keys %$ref;
2738
2739     if ($self->{"$self->{vc}_id"}) {
2740
2741       # only setup currency
2742       ($self->{currency}) = split(/:/, $self->{currencies});
2743
2744     } else {
2745
2746       $self->lastname_used($dbh, $myconfig, $table, $module);
2747
2748       # get exchangerate for currency
2749       $self->{exchangerate} =
2750         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2751
2752     }
2753
2754   }
2755
2756   $main::lxdebug->leave_sub();
2757 }
2758
2759 sub lastname_used {
2760   $main::lxdebug->enter_sub();
2761
2762   my ($self, $dbh, $myconfig, $table, $module) = @_;
2763
2764   my ($arap, $where);
2765
2766   $table         = $table eq "customer" ? "customer" : "vendor";
2767   my %column_map = ("a.curr"                  => "currency",
2768                     "a.${table}_id"           => "${table}_id",
2769                     "a.department_id"         => "department_id",
2770                     "d.description"           => "department",
2771                     "ct.name"                 => $table,
2772                     "current_date + ct.terms" => "duedate",
2773     );
2774
2775   if ($self->{type} =~ /delivery_order/) {
2776     $arap  = 'delivery_orders';
2777     delete $column_map{"a.curr"};
2778
2779   } elsif ($self->{type} =~ /_order/) {
2780     $arap  = 'oe';
2781     $where = "quotation = '0'";
2782
2783   } elsif ($self->{type} =~ /_quotation/) {
2784     $arap  = 'oe';
2785     $where = "quotation = '1'";
2786
2787   } elsif ($table eq 'customer') {
2788     $arap  = 'ar';
2789
2790   } else {
2791     $arap  = 'ap';
2792
2793   }
2794
2795   $where           = "($where) AND" if ($where);
2796   my $query        = qq|SELECT MAX(id) FROM $arap
2797                         WHERE $where ${table}_id > 0|;
2798   my ($trans_id)   = selectrow_query($self, $dbh, $query);
2799   $trans_id       *= 1;
2800
2801   my $column_spec  = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2802   $query           = qq|SELECT $column_spec
2803                         FROM $arap a
2804                         LEFT JOIN $table     ct ON (a.${table}_id = ct.id)
2805                         LEFT JOIN department d  ON (a.department_id = d.id)
2806                         WHERE a.id = ?|;
2807   my $ref          = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
2808
2809   map { $self->{$_} = $ref->{$_} } values %column_map;
2810
2811   $main::lxdebug->leave_sub();
2812 }
2813
2814 sub current_date {
2815   $main::lxdebug->enter_sub();
2816
2817   my ($self, $myconfig, $thisdate, $days) = @_;
2818
2819   my $dbh = $self->get_standard_dbh($myconfig);
2820   my $query;
2821
2822   $days *= 1;
2823   if ($thisdate) {
2824     my $dateformat = $myconfig->{dateformat};
2825     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2826     $thisdate = $dbh->quote($thisdate);
2827     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2828   } else {
2829     $query = qq|SELECT current_date AS thisdate|;
2830   }
2831
2832   ($thisdate) = selectrow_query($self, $dbh, $query);
2833
2834   $main::lxdebug->leave_sub();
2835
2836   return $thisdate;
2837 }
2838
2839 sub like {
2840   $main::lxdebug->enter_sub();
2841
2842   my ($self, $string) = @_;
2843
2844   if ($string !~ /%/) {
2845     $string = "%$string%";
2846   }
2847
2848   $string =~ s/\'/\'\'/g;
2849
2850   $main::lxdebug->leave_sub();
2851
2852   return $string;
2853 }
2854
2855 sub redo_rows {
2856   $main::lxdebug->enter_sub();
2857
2858   my ($self, $flds, $new, $count, $numrows) = @_;
2859
2860   my @ndx = ();
2861
2862   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
2863
2864   my $i = 0;
2865
2866   # fill rows
2867   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2868     $i++;
2869     $j = $item->{ndx} - 1;
2870     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2871   }
2872
2873   # delete empty rows
2874   for $i ($count + 1 .. $numrows) {
2875     map { delete $self->{"${_}_$i"} } @{$flds};
2876   }
2877
2878   $main::lxdebug->leave_sub();
2879 }
2880
2881 sub update_status {
2882   $main::lxdebug->enter_sub();
2883
2884   my ($self, $myconfig) = @_;
2885
2886   my ($i, $id);
2887
2888   my $dbh = $self->dbconnect_noauto($myconfig);
2889
2890   my $query = qq|DELETE FROM status
2891                  WHERE (formname = ?) AND (trans_id = ?)|;
2892   my $sth = prepare_query($self, $dbh, $query);
2893
2894   if ($self->{formname} =~ /(check|receipt)/) {
2895     for $i (1 .. $self->{rowcount}) {
2896       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
2897     }
2898   } else {
2899     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
2900   }
2901   $sth->finish();
2902
2903   my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2904   my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2905
2906   my %queued = split / /, $self->{queued};
2907   my @values;
2908
2909   if ($self->{formname} =~ /(check|receipt)/) {
2910
2911     # this is a check or receipt, add one entry for each lineitem
2912     my ($accno) = split /--/, $self->{account};
2913     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
2914                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
2915     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
2916     $sth = prepare_query($self, $dbh, $query);
2917
2918     for $i (1 .. $self->{rowcount}) {
2919       if ($self->{"checked_$i"}) {
2920         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
2921       }
2922     }
2923     $sth->finish();
2924
2925   } else {
2926     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2927                 VALUES (?, ?, ?, ?, ?)|;
2928     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
2929              $queued{$self->{formname}}, $self->{formname});
2930   }
2931
2932   $dbh->commit;
2933   $dbh->disconnect;
2934
2935   $main::lxdebug->leave_sub();
2936 }
2937
2938 sub save_status {
2939   $main::lxdebug->enter_sub();
2940
2941   my ($self, $dbh) = @_;
2942
2943   my ($query, $printed, $emailed);
2944
2945   my $formnames  = $self->{printed};
2946   my $emailforms = $self->{emailed};
2947
2948   $query = qq|DELETE FROM status
2949                  WHERE (formname = ?) AND (trans_id = ?)|;
2950   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
2951
2952   # this only applies to the forms
2953   # checks and receipts are posted when printed or queued
2954
2955   if ($self->{queued}) {
2956     my %queued = split / /, $self->{queued};
2957
2958     foreach my $formname (keys %queued) {
2959       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2960       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2961
2962       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2963                   VALUES (?, ?, ?, ?, ?)|;
2964       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
2965
2966       $formnames  =~ s/\Q$self->{formname}\E//;
2967       $emailforms =~ s/\Q$self->{formname}\E//;
2968
2969     }
2970   }
2971
2972   # save printed, emailed info
2973   $formnames  =~ s/^ +//g;
2974   $emailforms =~ s/^ +//g;
2975
2976   my %status = ();
2977   map { $status{$_}{printed} = 1 } split / +/, $formnames;
2978   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
2979
2980   foreach my $formname (keys %status) {
2981     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
2982     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
2983
2984     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
2985                 VALUES (?, ?, ?, ?)|;
2986     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
2987   }
2988
2989   $main::lxdebug->leave_sub();
2990 }
2991
2992 #--- 4 locale ---#
2993 # $main::locale->text('SAVED')
2994 # $main::locale->text('DELETED')
2995 # $main::locale->text('ADDED')
2996 # $main::locale->text('PAYMENT POSTED')
2997 # $main::locale->text('POSTED')
2998 # $main::locale->text('POSTED AS NEW')
2999 # $main::locale->text('ELSE')
3000 # $main::locale->text('SAVED FOR DUNNING')
3001 # $main::locale->text('DUNNING STARTED')
3002 # $main::locale->text('PRINTED')
3003 # $main::locale->text('MAILED')
3004 # $main::locale->text('SCREENED')
3005 # $main::locale->text('CANCELED')
3006 # $main::locale->text('invoice')
3007 # $main::locale->text('proforma')
3008 # $main::locale->text('sales_order')
3009 # $main::locale->text('packing_list')
3010 # $main::locale->text('pick_list')
3011 # $main::locale->text('purchase_order')
3012 # $main::locale->text('bin_list')
3013 # $main::locale->text('sales_quotation')
3014 # $main::locale->text('request_quotation')
3015
3016 sub save_history {
3017   $main::lxdebug->enter_sub();
3018
3019   my $self = shift();
3020   my $dbh = shift();
3021
3022   if(!exists $self->{employee_id}) {
3023     &get_employee($self, $dbh);
3024   }
3025
3026   my $query =
3027    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3028    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3029   my @values = (conv_i($self->{id}), $self->{login},
3030                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3031   do_query($self, $dbh, $query, @values);
3032
3033   $main::lxdebug->leave_sub();
3034 }
3035
3036 sub get_history {
3037   $main::lxdebug->enter_sub();
3038
3039   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3040   my ($orderBy, $desc) = split(/\-\-/, $order);
3041   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3042   my @tempArray;
3043   my $i = 0;
3044   if ($trans_id ne "") {
3045     my $query =
3046       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 | .
3047       qq|FROM history_erp h | .
3048       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3049       qq|WHERE trans_id = | . $trans_id
3050       . $restriction . qq| |
3051       . $order;
3052       
3053     my $sth = $dbh->prepare($query) || $self->dberror($query);
3054
3055     $sth->execute() || $self->dberror("$query");
3056
3057     while(my $hash_ref = $sth->fetchrow_hashref()) {
3058       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3059       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3060       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3061       $tempArray[$i++] = $hash_ref;
3062     }
3063     $main::lxdebug->leave_sub() and return \@tempArray 
3064       if ($i > 0 && $tempArray[0] ne "");
3065   }
3066   $main::lxdebug->leave_sub();
3067   return 0;
3068 }
3069
3070 sub update_defaults {
3071   $main::lxdebug->enter_sub();
3072
3073   my ($self, $myconfig, $fld, $provided_dbh) = @_;
3074
3075   my $dbh;
3076   if ($provided_dbh) {
3077     $dbh = $provided_dbh;
3078   } else {
3079     $dbh = $self->dbconnect_noauto($myconfig);
3080   }
3081   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3082   my $sth   = $dbh->prepare($query);
3083
3084   $sth->execute || $self->dberror($query);
3085   my ($var) = $sth->fetchrow_array;
3086   $sth->finish;
3087
3088   if ($var =~ m/\d+$/) {
3089     my $new_var  = (substr $var, $-[0]) * 1 + 1;
3090     my $len_diff = length($var) - $-[0] - length($new_var);
3091     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3092
3093   } else {
3094     $var = $var . '1';
3095   }
3096
3097   $query = qq|UPDATE defaults SET $fld = ?|;
3098   do_query($self, $dbh, $query, $var);
3099
3100   if (!$provided_dbh) {
3101     $dbh->commit;
3102     $dbh->disconnect;
3103   }
3104
3105   $main::lxdebug->leave_sub();
3106
3107   return $var;
3108 }
3109
3110 sub update_business {
3111   $main::lxdebug->enter_sub();
3112
3113   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3114
3115   my $dbh;
3116   if ($provided_dbh) {
3117     $dbh = $provided_dbh;
3118   } else {
3119     $dbh = $self->dbconnect_noauto($myconfig);
3120   }
3121   my $query =
3122     qq|SELECT customernumberinit FROM business
3123        WHERE id = ? FOR UPDATE|;
3124   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3125
3126   if ($var =~ m/\d+$/) {
3127     my $new_var  = (substr $var, $-[0]) * 1 + 1;
3128     my $len_diff = length($var) - $-[0] - length($new_var);
3129     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3130
3131   } else {
3132     $var = $var . '1';
3133   }
3134
3135   $query = qq|UPDATE business
3136               SET customernumberinit = ?
3137               WHERE id = ?|;
3138   do_query($self, $dbh, $query, $var, $business_id);
3139
3140   if (!$provided_dbh) {
3141     $dbh->commit;
3142     $dbh->disconnect;
3143   }
3144
3145   $main::lxdebug->leave_sub();
3146
3147   return $var;
3148 }
3149
3150 sub get_partsgroup {
3151   $main::lxdebug->enter_sub();
3152
3153   my ($self, $myconfig, $p) = @_;
3154   my $target = $p->{target} || 'all_partsgroup';
3155
3156   my $dbh = $self->get_standard_dbh($myconfig);
3157
3158   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3159                  FROM partsgroup pg
3160                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
3161   my @values;
3162
3163   if ($p->{searchitems} eq 'part') {
3164     $query .= qq|WHERE p.inventory_accno_id > 0|;
3165   }
3166   if ($p->{searchitems} eq 'service') {
3167     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3168   }
3169   if ($p->{searchitems} eq 'assembly') {
3170     $query .= qq|WHERE p.assembly = '1'|;
3171   }
3172   if ($p->{searchitems} eq 'labor') {
3173     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3174   }
3175
3176   $query .= qq|ORDER BY partsgroup|;
3177
3178   if ($p->{all}) {
3179     $query = qq|SELECT id, partsgroup FROM partsgroup
3180                 ORDER BY partsgroup|;
3181   }
3182
3183   if ($p->{language_code}) {
3184     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3185                   t.description AS translation
3186                 FROM partsgroup pg
3187                 JOIN parts p ON (p.partsgroup_id = pg.id)
3188                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3189                 ORDER BY translation|;
3190     @values = ($p->{language_code});
3191   }
3192
3193   $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3194
3195   $main::lxdebug->leave_sub();
3196 }
3197
3198 sub get_pricegroup {
3199   $main::lxdebug->enter_sub();
3200
3201   my ($self, $myconfig, $p) = @_;
3202
3203   my $dbh = $self->get_standard_dbh($myconfig);
3204
3205   my $query = qq|SELECT p.id, p.pricegroup
3206                  FROM pricegroup p|;
3207
3208   $query .= qq| ORDER BY pricegroup|;
3209
3210   if ($p->{all}) {
3211     $query = qq|SELECT id, pricegroup FROM pricegroup
3212                 ORDER BY pricegroup|;
3213   }
3214
3215   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3216
3217   $main::lxdebug->leave_sub();
3218 }
3219
3220 sub all_years {
3221 # usage $form->all_years($myconfig, [$dbh])
3222 # return list of all years where bookings found
3223 # (@all_years)
3224
3225   $main::lxdebug->enter_sub();
3226
3227   my ($self, $myconfig, $dbh) = @_;
3228
3229   $dbh ||= $self->get_standard_dbh($myconfig);
3230
3231   # get years
3232   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3233                    (SELECT MAX(transdate) FROM acc_trans)|;
3234   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3235
3236   if ($myconfig->{dateformat} =~ /^yy/) {
3237     ($startdate) = split /\W/, $startdate;
3238     ($enddate) = split /\W/, $enddate;
3239   } else {
3240     (@_) = split /\W/, $startdate;
3241     $startdate = $_[2];
3242     (@_) = split /\W/, $enddate;
3243     $enddate = $_[2];
3244   }
3245
3246   my @all_years;
3247   $startdate = substr($startdate,0,4);
3248   $enddate = substr($enddate,0,4);
3249
3250   while ($enddate >= $startdate) {
3251     push @all_years, $enddate--;
3252   }
3253
3254   return @all_years;
3255
3256   $main::lxdebug->leave_sub();
3257 }
3258
3259 sub backup_vars {
3260   $main::lxdebug->enter_sub();
3261   my $self = shift;
3262   my @vars = @_;
3263
3264   map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if $self->{$_} } @vars;
3265
3266   $main::lxdebug->leave_sub();
3267 }
3268
3269 sub restore_vars {
3270   $main::lxdebug->enter_sub();
3271
3272   my $self = shift;
3273   my @vars = @_;
3274
3275   map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if $self->{_VAR_BACKUP}->{$_} } @vars;
3276
3277   $main::lxdebug->leave_sub();
3278 }
3279
3280 1;