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