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