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