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