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