Beim Dialogbuchen die Kontensalden zu den jeweils ausgewählten Konten anzeigen. Fix...
[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 " . $main::locale->text('DR') : "$amount " . $main::locale->text('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   my $ext_for_format;
1133
1134   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
1135     $template       = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1136     $ext_for_format = 'odt';
1137
1138   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
1139     $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
1140     $template         = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1141     $ext_for_format   = 'pdf';
1142
1143   } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
1144     $template       = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1145     $ext_for_format = 'html';
1146
1147   } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
1148     $template       = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1149     $ext_for_format = 'xml';
1150
1151   } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
1152     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1153
1154   } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
1155     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1156
1157   } elsif ( defined $self->{'format'}) {
1158     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
1159
1160   } elsif ( $self->{'format'} eq '' ) {
1161     $self->error("No Outputformat given: $self->{'format'}");
1162
1163   } else { #Catch the rest
1164     $self->error("Outputformat not defined: $self->{'format'}");
1165   }
1166
1167   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
1168   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
1169
1170   if (!$self->{employee_id}) {
1171     map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
1172   }
1173
1174   map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
1175
1176   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
1177
1178   # OUT is used for the media, screen, printer, email
1179   # for postscript we store a copy in a temporary file
1180   my $fileid = time;
1181   my $prepend_userspath;
1182
1183   if (!$self->{tmpfile}) {
1184     $self->{tmpfile}   = "${fileid}.$self->{IN}";
1185     $prepend_userspath = 1;
1186   }
1187
1188   $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
1189
1190   $self->{tmpfile} =~ s|.*/||;
1191   $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
1192   $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
1193
1194   if ($template->uses_temp_file() || $self->{media} eq 'email') {
1195     $out = $self->{OUT};
1196     $self->{OUT} = ">$self->{tmpfile}";
1197   }
1198
1199   if ($self->{OUT}) {
1200     open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
1201   } else {
1202     open(OUT, ">-") or $self->error("STDOUT : $!");
1203     $self->header;
1204   }
1205
1206   if (!$template->parse(*OUT)) {
1207     $self->cleanup();
1208     $self->error("$self->{IN} : " . $template->get_error());
1209   }
1210
1211   close(OUT);
1212
1213   if ($template->uses_temp_file() || $self->{media} eq 'email') {
1214
1215     if ($self->{media} eq 'email') {
1216
1217       my $mail = new Mailer;
1218
1219       map { $mail->{$_} = $self->{$_} }
1220         qw(cc bcc subject message version format);
1221       $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
1222       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1223       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1224       $mail->{fileid} = "$fileid.";
1225       $myconfig->{signature} =~ s/\r//g;
1226
1227       # if we send html or plain text inline
1228       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1229         $mail->{contenttype} = "text/html";
1230
1231         $mail->{message}       =~ s/\r//g;
1232         $mail->{message}       =~ s/\n/<br>\n/g;
1233         $myconfig->{signature} =~ s/\n/<br>\n/g;
1234         $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
1235
1236         open(IN, $self->{tmpfile})
1237           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1238         while (<IN>) {
1239           $mail->{message} .= $_;
1240         }
1241
1242         close(IN);
1243
1244       } else {
1245
1246         if (!$self->{"do_not_attach"}) {
1247           my $attachment_name  =  $self->{attachment_filename} || $self->{tmpfile};
1248           $attachment_name     =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
1249           $mail->{attachments} =  [{ "filename" => $self->{tmpfile},
1250                                      "name"     => $attachment_name }];
1251         }
1252
1253         $mail->{message}  =~ s/\r//g;
1254         $mail->{message} .=  "\n-- \n$myconfig->{signature}";
1255
1256       }
1257
1258       my $err = $mail->send();
1259       $self->error($self->cleanup . "$err") if ($err);
1260
1261     } else {
1262
1263       $self->{OUT} = $out;
1264
1265       my $numbytes = (-s $self->{tmpfile});
1266       open(IN, $self->{tmpfile})
1267         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1268
1269       $self->{copies} = 1 unless $self->{media} eq 'printer';
1270
1271       chdir("$self->{cwd}");
1272       #print(STDERR "Kopien $self->{copies}\n");
1273       #print(STDERR "OUT $self->{OUT}\n");
1274       for my $i (1 .. $self->{copies}) {
1275         if ($self->{OUT}) {
1276           open(OUT, $self->{OUT})
1277             or $self->error($self->cleanup . "$self->{OUT} : $!");
1278         } else {
1279           $self->{attachment_filename} = ($self->{attachment_filename})
1280                                        ? $self->{attachment_filename}
1281                                        : $self->generate_attachment_filename();
1282
1283           # launch application
1284           print qq|Content-Type: | . $template->get_mime_type() . qq|
1285 Content-Disposition: attachment; filename="$self->{attachment_filename}"
1286 Content-Length: $numbytes
1287
1288 |;
1289
1290           open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
1291
1292         }
1293
1294         while (<IN>) {
1295           print OUT $_;
1296         }
1297
1298         close(OUT);
1299
1300         seek IN, 0, 0;
1301       }
1302
1303       close(IN);
1304     }
1305
1306   }
1307
1308   $self->cleanup;
1309
1310   chdir("$self->{cwd}");
1311   $main::lxdebug->leave_sub();
1312 }
1313
1314 sub get_formname_translation {
1315   my ($self, $formname) = @_;
1316
1317   $formname ||= $self->{formname};
1318
1319   my %formname_translations = (
1320     bin_list                => $main::locale->text('Bin List'),
1321     credit_note             => $main::locale->text('Credit Note'),
1322     invoice                 => $main::locale->text('Invoice'),
1323     packing_list            => $main::locale->text('Packing List'),
1324     pick_list               => $main::locale->text('Pick List'),
1325     proforma                => $main::locale->text('Proforma Invoice'),
1326     purchase_order          => $main::locale->text('Purchase Order'),
1327     request_quotation       => $main::locale->text('RFQ'),
1328     sales_order             => $main::locale->text('Confirmation'),
1329     sales_quotation         => $main::locale->text('Quotation'),
1330     storno_invoice          => $main::locale->text('Storno Invoice'),
1331     storno_packing_list     => $main::locale->text('Storno Packing List'),
1332     sales_delivery_order    => $main::locale->text('Delivery Order'),
1333     purchase_delivery_order => $main::locale->text('Delivery Order'),
1334   );
1335
1336   return $formname_translations{$formname}
1337 }
1338
1339 sub get_number_prefix_for_type {
1340   my ($self) = @_;
1341
1342   my $prefix =
1343       (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1344     : ($self->{type} =~ /_quotation$/)                        ? 'quo'
1345     : ($self->{type} =~ /_delivery_order$/)                   ? 'do'
1346     :                                                           'ord';
1347
1348   return $prefix;
1349 }
1350
1351 sub get_extension_for_format {
1352   my ($self)    = @_;
1353
1354   my $extension = $self->{format} =~ /pdf/i          ? ".pdf"
1355                 : $self->{format} =~ /postscript/i   ? ".ps"
1356                 : $self->{format} =~ /opendocument/i ? ".odt"
1357                 : $self->{format} =~ /html/i         ? ".html"
1358                 :                                      "";
1359
1360   return $extension;
1361 }
1362
1363 sub generate_attachment_filename {
1364   my ($self) = @_;
1365
1366   my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1367   my $prefix              = $self->get_number_prefix_for_type();
1368
1369   if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1370     $attachment_filename .= ' (' . $main::locale->text('Preview') . ')' . $self->get_extension_for_format();
1371
1372   } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1373     $attachment_filename .=  "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1374
1375   } else {
1376     $attachment_filename = "";
1377   }
1378
1379   $attachment_filename =  $main::locale->quote_special_chars('filenames', $attachment_filename);
1380   $attachment_filename =~ s|[\s/\\]+|_|g;
1381
1382   return $attachment_filename;
1383 }
1384
1385 sub generate_email_subject {
1386   my ($self) = @_;
1387
1388   my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1389   my $prefix  = $self->get_number_prefix_for_type();
1390
1391   if ($subject && $self->{"${prefix}number"}) {
1392     $subject .= " " . $self->{"${prefix}number"}
1393   }
1394
1395   return $subject;
1396 }
1397
1398 sub cleanup {
1399   $main::lxdebug->enter_sub();
1400
1401   my $self = shift;
1402
1403   chdir("$self->{tmpdir}");
1404
1405   my @err = ();
1406   if (-f "$self->{tmpfile}.err") {
1407     open(FH, "$self->{tmpfile}.err");
1408     @err = <FH>;
1409     close(FH);
1410   }
1411
1412   if ($self->{tmpfile}) {
1413     $self->{tmpfile} =~ s|.*/||g;
1414     # strip extension
1415     $self->{tmpfile} =~ s/\.\w+$//g;
1416     my $tmpfile = $self->{tmpfile};
1417     unlink(<$tmpfile.*>);
1418   }
1419
1420   chdir("$self->{cwd}");
1421
1422   $main::lxdebug->leave_sub();
1423
1424   return "@err";
1425 }
1426
1427 sub datetonum {
1428   $main::lxdebug->enter_sub();
1429
1430   my ($self, $date, $myconfig) = @_;
1431   my ($yy, $mm, $dd);
1432
1433   if ($date && $date =~ /\D/) {
1434
1435     if ($myconfig->{dateformat} =~ /^yy/) {
1436       ($yy, $mm, $dd) = split /\D/, $date;
1437     }
1438     if ($myconfig->{dateformat} =~ /^mm/) {
1439       ($mm, $dd, $yy) = split /\D/, $date;
1440     }
1441     if ($myconfig->{dateformat} =~ /^dd/) {
1442       ($dd, $mm, $yy) = split /\D/, $date;
1443     }
1444
1445     $dd *= 1;
1446     $mm *= 1;
1447     $yy = ($yy < 70) ? $yy + 2000 : $yy;
1448     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1449
1450     $dd = "0$dd" if ($dd < 10);
1451     $mm = "0$mm" if ($mm < 10);
1452
1453     $date = "$yy$mm$dd";
1454   }
1455
1456   $main::lxdebug->leave_sub();
1457
1458   return $date;
1459 }
1460
1461 # Database routines used throughout
1462
1463 sub dbconnect {
1464   $main::lxdebug->enter_sub(2);
1465
1466   my ($self, $myconfig) = @_;
1467
1468   # connect to database
1469   my $dbh =
1470     DBI->connect($myconfig->{dbconnect},
1471                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
1472     or $self->dberror;
1473
1474   # set db options
1475   if ($myconfig->{dboptions}) {
1476     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1477   }
1478
1479   $main::lxdebug->leave_sub(2);
1480
1481   return $dbh;
1482 }
1483
1484 sub dbconnect_noauto {
1485   $main::lxdebug->enter_sub();
1486
1487   my ($self, $myconfig) = @_;
1488
1489   # connect to database
1490   my $dbh =
1491     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1492                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
1493     or $self->dberror;
1494
1495   # set db options
1496   if ($myconfig->{dboptions}) {
1497     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1498   }
1499
1500   $main::lxdebug->leave_sub();
1501
1502   return $dbh;
1503 }
1504
1505 sub get_standard_dbh {
1506   $main::lxdebug->enter_sub(2);
1507
1508   my ($self, $myconfig) = @_;
1509
1510   if ($standard_dbh && !$standard_dbh->{Active}) {
1511     $main::lxdebug->message(LXDebug::INFO, "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
1512     undef $standard_dbh;
1513   }
1514
1515   $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1516
1517   $main::lxdebug->leave_sub(2);
1518
1519   return $standard_dbh;
1520 }
1521
1522 sub date_closed {
1523   $main::lxdebug->enter_sub();
1524
1525   my ($self, $date, $myconfig) = @_;
1526   my $dbh = $self->dbconnect($myconfig);
1527
1528   my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1529   my $sth = prepare_execute_query($self, $dbh, $query, $date);
1530   my ($closed) = $sth->fetchrow_array;
1531
1532   $main::lxdebug->leave_sub();
1533
1534   return $closed;
1535 }
1536
1537 sub update_balance {
1538   $main::lxdebug->enter_sub();
1539
1540   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1541
1542   # if we have a value, go do it
1543   if ($value != 0) {
1544
1545     # retrieve balance from table
1546     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1547     my $sth = prepare_execute_query($self, $dbh, $query, @values);
1548     my ($balance) = $sth->fetchrow_array;
1549     $sth->finish;
1550
1551     $balance += $value;
1552
1553     # update balance
1554     $query = "UPDATE $table SET $field = $balance WHERE $where";
1555     do_query($self, $dbh, $query, @values);
1556   }
1557   $main::lxdebug->leave_sub();
1558 }
1559
1560 sub update_exchangerate {
1561   $main::lxdebug->enter_sub();
1562
1563   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1564   my ($query);
1565   # some sanity check for currency
1566   if ($curr eq '') {
1567     $main::lxdebug->leave_sub();
1568     return;
1569   }
1570   $query = qq|SELECT curr FROM defaults|;
1571
1572   my ($currency) = selectrow_query($self, $dbh, $query);
1573   my ($defaultcurrency) = split m/:/, $currency;
1574
1575
1576   if ($curr eq $defaultcurrency) {
1577     $main::lxdebug->leave_sub();
1578     return;
1579   }
1580
1581   $query = qq|SELECT e.curr FROM exchangerate e
1582                  WHERE e.curr = ? AND e.transdate = ?
1583                  FOR UPDATE|;
1584   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1585
1586   if ($buy == 0) {
1587     $buy = "";
1588   }
1589   if ($sell == 0) {
1590     $sell = "";
1591   }
1592
1593   $buy = conv_i($buy, "NULL");
1594   $sell = conv_i($sell, "NULL");
1595
1596   my $set;
1597   if ($buy != 0 && $sell != 0) {
1598     $set = "buy = $buy, sell = $sell";
1599   } elsif ($buy != 0) {
1600     $set = "buy = $buy";
1601   } elsif ($sell != 0) {
1602     $set = "sell = $sell";
1603   }
1604
1605   if ($sth->fetchrow_array) {
1606     $query = qq|UPDATE exchangerate
1607                 SET $set
1608                 WHERE curr = ?
1609                 AND transdate = ?|;
1610
1611   } else {
1612     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1613                 VALUES (?, $buy, $sell, ?)|;
1614   }
1615   $sth->finish;
1616   do_query($self, $dbh, $query, $curr, $transdate);
1617
1618   $main::lxdebug->leave_sub();
1619 }
1620
1621 sub save_exchangerate {
1622   $main::lxdebug->enter_sub();
1623
1624   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1625
1626   my $dbh = $self->dbconnect($myconfig);
1627
1628   my ($buy, $sell);
1629
1630   $buy  = $rate if $fld eq 'buy';
1631   $sell = $rate if $fld eq 'sell';
1632
1633
1634   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1635
1636
1637   $dbh->disconnect;
1638
1639   $main::lxdebug->leave_sub();
1640 }
1641
1642 sub get_exchangerate {
1643   $main::lxdebug->enter_sub();
1644
1645   my ($self, $dbh, $curr, $transdate, $fld) = @_;
1646   my ($query);
1647
1648   unless ($transdate) {
1649     $main::lxdebug->leave_sub();
1650     return 1;
1651   }
1652
1653   $query = qq|SELECT curr FROM defaults|;
1654
1655   my ($currency) = selectrow_query($self, $dbh, $query);
1656   my ($defaultcurrency) = split m/:/, $currency;
1657
1658   if ($currency eq $defaultcurrency) {
1659     $main::lxdebug->leave_sub();
1660     return 1;
1661   }
1662
1663   $query = qq|SELECT e.$fld FROM exchangerate e
1664                  WHERE e.curr = ? AND e.transdate = ?|;
1665   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1666
1667
1668
1669   $main::lxdebug->leave_sub();
1670
1671   return $exchangerate;
1672 }
1673
1674 sub check_exchangerate {
1675   $main::lxdebug->enter_sub();
1676
1677   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1678
1679   if ($fld !~/^buy|sell$/) {
1680     $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1681   }
1682
1683   unless ($transdate) {
1684     $main::lxdebug->leave_sub();
1685     return "";
1686   }
1687
1688   my ($defaultcurrency) = $self->get_default_currency($myconfig);
1689
1690   if ($currency eq $defaultcurrency) {
1691     $main::lxdebug->leave_sub();
1692     return 1;
1693   }
1694
1695   my $dbh   = $self->get_standard_dbh($myconfig);
1696   my $query = qq|SELECT e.$fld FROM exchangerate e
1697                  WHERE e.curr = ? AND e.transdate = ?|;
1698
1699   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1700
1701   $main::lxdebug->leave_sub();
1702
1703   return $exchangerate;
1704 }
1705
1706 sub get_default_currency {
1707   $main::lxdebug->enter_sub();
1708
1709   my ($self, $myconfig) = @_;
1710   my $dbh = $self->get_standard_dbh($myconfig);
1711
1712   my $query = qq|SELECT curr FROM defaults|;
1713
1714   my ($curr)            = selectrow_query($self, $dbh, $query);
1715   my ($defaultcurrency) = split m/:/, $curr;
1716
1717   $main::lxdebug->leave_sub();
1718
1719   return $defaultcurrency;
1720 }
1721
1722
1723 sub set_payment_options {
1724   $main::lxdebug->enter_sub();
1725
1726   my ($self, $myconfig, $transdate) = @_;
1727
1728   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1729
1730   my $dbh = $self->get_standard_dbh($myconfig);
1731
1732   my $query =
1733     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1734     qq|FROM payment_terms p | .
1735     qq|WHERE p.id = ?|;
1736
1737   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1738    $self->{payment_terms}) =
1739      selectrow_query($self, $dbh, $query, $self->{payment_id});
1740
1741   if ($transdate eq "") {
1742     if ($self->{invdate}) {
1743       $transdate = $self->{invdate};
1744     } else {
1745       $transdate = $self->{transdate};
1746     }
1747   }
1748
1749   $query =
1750     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1751     qq|FROM payment_terms|;
1752   ($self->{netto_date}, $self->{skonto_date}) =
1753     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1754
1755   my ($invtotal, $total);
1756   my (%amounts, %formatted_amounts);
1757
1758   if ($self->{type} =~ /_order$/) {
1759     $amounts{invtotal} = $self->{ordtotal};
1760     $amounts{total}    = $self->{ordtotal};
1761
1762   } elsif ($self->{type} =~ /_quotation$/) {
1763     $amounts{invtotal} = $self->{quototal};
1764     $amounts{total}    = $self->{quototal};
1765
1766   } else {
1767     $amounts{invtotal} = $self->{invtotal};
1768     $amounts{total}    = $self->{total};
1769   }
1770
1771   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1772
1773   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
1774   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1775   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
1776
1777   foreach (keys %amounts) {
1778     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
1779     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1780   }
1781
1782   if ($self->{"language_id"}) {
1783     $query =
1784       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1785       qq|FROM translation_payment_terms t | .
1786       qq|LEFT JOIN language l ON t.language_id = l.id | .
1787       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1788     my ($description_long, $output_numberformat, $output_dateformat,
1789       $output_longdates) =
1790       selectrow_query($self, $dbh, $query,
1791                       $self->{"language_id"}, $self->{"payment_id"});
1792
1793     $self->{payment_terms} = $description_long if ($description_long);
1794
1795     if ($output_dateformat) {
1796       foreach my $key (qw(netto_date skonto_date)) {
1797         $self->{$key} =
1798           $main::locale->reformat_date($myconfig, $self->{$key},
1799                                        $output_dateformat,
1800                                        $output_longdates);
1801       }
1802     }
1803
1804     if ($output_numberformat &&
1805         ($output_numberformat ne $myconfig->{"numberformat"})) {
1806       my $saved_numberformat = $myconfig->{"numberformat"};
1807       $myconfig->{"numberformat"} = $output_numberformat;
1808       map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1809       $myconfig->{"numberformat"} = $saved_numberformat;
1810     }
1811   }
1812
1813   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1814   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1815   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1816   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1817   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1818   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1819   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1820
1821   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1822
1823   $main::lxdebug->leave_sub();
1824
1825 }
1826
1827 sub get_template_language {
1828   $main::lxdebug->enter_sub();
1829
1830   my ($self, $myconfig) = @_;
1831
1832   my $template_code = "";
1833
1834   if ($self->{language_id}) {
1835     my $dbh = $self->get_standard_dbh($myconfig);
1836     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1837     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1838   }
1839
1840   $main::lxdebug->leave_sub();
1841
1842   return $template_code;
1843 }
1844
1845 sub get_printer_code {
1846   $main::lxdebug->enter_sub();
1847
1848   my ($self, $myconfig) = @_;
1849
1850   my $template_code = "";
1851
1852   if ($self->{printer_id}) {
1853     my $dbh = $self->get_standard_dbh($myconfig);
1854     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1855     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1856   }
1857
1858   $main::lxdebug->leave_sub();
1859
1860   return $template_code;
1861 }
1862
1863 sub get_shipto {
1864   $main::lxdebug->enter_sub();
1865
1866   my ($self, $myconfig) = @_;
1867
1868   my $template_code = "";
1869
1870   if ($self->{shipto_id}) {
1871     my $dbh = $self->get_standard_dbh($myconfig);
1872     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1873     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1874     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1875   }
1876
1877   $main::lxdebug->leave_sub();
1878 }
1879
1880 sub add_shipto {
1881   $main::lxdebug->enter_sub();
1882
1883   my ($self, $dbh, $id, $module) = @_;
1884
1885   my $shipto;
1886   my @values;
1887
1888   foreach my $item (qw(name department_1 department_2 street zipcode city country
1889                        contact phone fax email)) {
1890     if ($self->{"shipto$item"}) {
1891       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1892     }
1893     push(@values, $self->{"shipto${item}"});
1894   }
1895
1896   if ($shipto) {
1897     if ($self->{shipto_id}) {
1898       my $query = qq|UPDATE shipto set
1899                        shiptoname = ?,
1900                        shiptodepartment_1 = ?,
1901                        shiptodepartment_2 = ?,
1902                        shiptostreet = ?,
1903                        shiptozipcode = ?,
1904                        shiptocity = ?,
1905                        shiptocountry = ?,
1906                        shiptocontact = ?,
1907                        shiptophone = ?,
1908                        shiptofax = ?,
1909                        shiptoemail = ?
1910                      WHERE shipto_id = ?|;
1911       do_query($self, $dbh, $query, @values, $self->{shipto_id});
1912     } else {
1913       my $query = qq|SELECT * FROM shipto
1914                      WHERE shiptoname = ? AND
1915                        shiptodepartment_1 = ? AND
1916                        shiptodepartment_2 = ? AND
1917                        shiptostreet = ? AND
1918                        shiptozipcode = ? AND
1919                        shiptocity = ? AND
1920                        shiptocountry = ? AND
1921                        shiptocontact = ? AND
1922                        shiptophone = ? AND
1923                        shiptofax = ? AND
1924                        shiptoemail = ? AND
1925                        module = ? AND
1926                        trans_id = ?|;
1927       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1928       if(!$insert_check){
1929         $query =
1930           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1931                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
1932                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
1933              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1934         do_query($self, $dbh, $query, $id, @values, $module);
1935       }
1936     }
1937   }
1938
1939   $main::lxdebug->leave_sub();
1940 }
1941
1942 sub get_employee {
1943   $main::lxdebug->enter_sub();
1944
1945   my ($self, $dbh) = @_;
1946
1947   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1948   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1949   $self->{"employee_id"} *= 1;
1950
1951   $main::lxdebug->leave_sub();
1952 }
1953
1954 sub get_employee_data {
1955   $main::lxdebug->enter_sub();
1956
1957   my $self     = shift;
1958   my %params   = @_;
1959
1960   Common::check_params(\%params, qw(prefix));
1961   Common::check_params_x(\%params, qw(id));
1962
1963   if (!$params{id}) {
1964     $main::lxdebug->leave_sub();
1965     return;
1966   }
1967
1968   my $myconfig = \%main::myconfig;
1969   my $dbh      = $params{dbh} || $self->get_standard_dbh($myconfig);
1970
1971   my ($login)  = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
1972
1973   if ($login) {
1974     my $user = User->new($login);
1975     map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
1976
1977     $self->{$params{prefix} . '_login'}   = $login;
1978     $self->{$params{prefix} . '_name'}  ||= $login;
1979   }
1980
1981   $main::lxdebug->leave_sub();
1982 }
1983
1984 sub get_duedate {
1985   $main::lxdebug->enter_sub();
1986
1987   my ($self, $myconfig, $reference_date) = @_;
1988
1989   my $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
1990
1991   my $dbh            = $self->get_standard_dbh($myconfig);
1992   my $query          = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
1993   my ($duedate)      = selectrow_query($self, $dbh, $query, $self->{payment_id});
1994
1995   $main::lxdebug->leave_sub();
1996
1997   return $duedate;
1998 }
1999
2000 sub _get_contacts {
2001   $main::lxdebug->enter_sub();
2002
2003   my ($self, $dbh, $id, $key) = @_;
2004
2005   $key = "all_contacts" unless ($key);
2006
2007   if (!$id) {
2008     $self->{$key} = [];
2009     $main::lxdebug->leave_sub();
2010     return;
2011   }
2012
2013   my $query =
2014     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
2015     qq|FROM contacts | .
2016     qq|WHERE cp_cv_id = ? | .
2017     qq|ORDER BY lower(cp_name)|;
2018
2019   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
2020
2021   $main::lxdebug->leave_sub();
2022 }
2023
2024 sub _get_projects {
2025   $main::lxdebug->enter_sub();
2026
2027   my ($self, $dbh, $key) = @_;
2028
2029   my ($all, $old_id, $where, @values);
2030
2031   if (ref($key) eq "HASH") {
2032     my $params = $key;
2033
2034     $key = "ALL_PROJECTS";
2035
2036     foreach my $p (keys(%{$params})) {
2037       if ($p eq "all") {
2038         $all = $params->{$p};
2039       } elsif ($p eq "old_id") {
2040         $old_id = $params->{$p};
2041       } elsif ($p eq "key") {
2042         $key = $params->{$p};
2043       }
2044     }
2045   }
2046
2047   if (!$all) {
2048     $where = "WHERE active ";
2049     if ($old_id) {
2050       if (ref($old_id) eq "ARRAY") {
2051         my @ids = grep({ $_ } @{$old_id});
2052         if (@ids) {
2053           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
2054           push(@values, @ids);
2055         }
2056       } else {
2057         $where .= " OR (id = ?) ";
2058         push(@values, $old_id);
2059       }
2060     }
2061   }
2062
2063   my $query =
2064     qq|SELECT id, projectnumber, description, active | .
2065     qq|FROM project | .
2066     $where .
2067     qq|ORDER BY lower(projectnumber)|;
2068
2069   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2070
2071   $main::lxdebug->leave_sub();
2072 }
2073
2074 sub _get_shipto {
2075   $main::lxdebug->enter_sub();
2076
2077   my ($self, $dbh, $vc_id, $key) = @_;
2078
2079   $key = "all_shipto" unless ($key);
2080
2081   if ($vc_id) {
2082     # get shipping addresses
2083     my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2084
2085     $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2086
2087   } else {
2088     $self->{$key} = [];
2089   }
2090
2091   $main::lxdebug->leave_sub();
2092 }
2093
2094 sub _get_printers {
2095   $main::lxdebug->enter_sub();
2096
2097   my ($self, $dbh, $key) = @_;
2098
2099   $key = "all_printers" unless ($key);
2100
2101   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2102
2103   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2104
2105   $main::lxdebug->leave_sub();
2106 }
2107
2108 sub _get_charts {
2109   $main::lxdebug->enter_sub();
2110
2111   my ($self, $dbh, $params) = @_;
2112   my ($key);
2113
2114   $key = $params->{key};
2115   $key = "all_charts" unless ($key);
2116
2117   my $transdate = quote_db_date($params->{transdate});
2118
2119   my $query =
2120     qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
2121     qq|FROM chart c | .
2122     qq|LEFT JOIN taxkeys tk ON | .
2123     qq|(tk.id = (SELECT id FROM taxkeys | .
2124     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2125     qq|          ORDER BY startdate DESC LIMIT 1)) | .
2126     qq|ORDER BY c.accno|;
2127
2128   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2129
2130   $main::lxdebug->leave_sub();
2131 }
2132
2133 sub _get_taxcharts {
2134   $main::lxdebug->enter_sub();
2135
2136   my ($self, $dbh, $params) = @_;
2137
2138   my $key = "all_taxcharts";
2139   my @where;
2140
2141   if (ref $params eq 'HASH') {
2142     $key = $params->{key} if ($params->{key});
2143     if ($params->{module} eq 'AR') {
2144       push @where, 'taxkey NOT IN (8, 9, 18, 19)';
2145
2146     } elsif ($params->{module} eq 'AP') {
2147       push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
2148     }
2149
2150   } elsif ($params) {
2151     $key = $params;
2152   }
2153
2154   my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
2155
2156   my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
2157
2158   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2159
2160   $main::lxdebug->leave_sub();
2161 }
2162
2163 sub _get_taxzones {
2164   $main::lxdebug->enter_sub();
2165
2166   my ($self, $dbh, $key) = @_;
2167
2168   $key = "all_taxzones" unless ($key);
2169
2170   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
2171
2172   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2173
2174   $main::lxdebug->leave_sub();
2175 }
2176
2177 sub _get_employees {
2178   $main::lxdebug->enter_sub();
2179
2180   my ($self, $dbh, $default_key, $key) = @_;
2181
2182   $key = $default_key unless ($key);
2183   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
2184
2185   $main::lxdebug->leave_sub();
2186 }
2187
2188 sub _get_business_types {
2189   $main::lxdebug->enter_sub();
2190
2191   my ($self, $dbh, $key) = @_;
2192
2193   $key = "all_business_types" unless ($key);
2194   $self->{$key} =
2195     selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
2196
2197   $main::lxdebug->leave_sub();
2198 }
2199
2200 sub _get_languages {
2201   $main::lxdebug->enter_sub();
2202
2203   my ($self, $dbh, $key) = @_;
2204
2205   $key = "all_languages" unless ($key);
2206
2207   my $query = qq|SELECT * FROM language ORDER BY id|;
2208
2209   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2210
2211   $main::lxdebug->leave_sub();
2212 }
2213
2214 sub _get_dunning_configs {
2215   $main::lxdebug->enter_sub();
2216
2217   my ($self, $dbh, $key) = @_;
2218
2219   $key = "all_dunning_configs" unless ($key);
2220
2221   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2222
2223   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2224
2225   $main::lxdebug->leave_sub();
2226 }
2227
2228 sub _get_currencies {
2229 $main::lxdebug->enter_sub();
2230
2231   my ($self, $dbh, $key) = @_;
2232
2233   $key = "all_currencies" unless ($key);
2234
2235   my $query = qq|SELECT curr AS currency FROM defaults|;
2236
2237   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2238
2239   $main::lxdebug->leave_sub();
2240 }
2241
2242 sub _get_payments {
2243 $main::lxdebug->enter_sub();
2244
2245   my ($self, $dbh, $key) = @_;
2246
2247   $key = "all_payments" unless ($key);
2248
2249   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
2250
2251   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2252
2253   $main::lxdebug->leave_sub();
2254 }
2255
2256 sub _get_customers {
2257   $main::lxdebug->enter_sub();
2258
2259   my ($self, $dbh, $key, $limit) = @_;
2260
2261   $key = "all_customers" unless ($key);
2262   my $limit_clause = "LIMIT $limit" if $limit;
2263
2264   my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name $limit_clause|;
2265
2266   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2267
2268   $main::lxdebug->leave_sub();
2269 }
2270
2271 sub _get_vendors {
2272   $main::lxdebug->enter_sub();
2273
2274   my ($self, $dbh, $key) = @_;
2275
2276   $key = "all_vendors" unless ($key);
2277
2278   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2279
2280   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2281
2282   $main::lxdebug->leave_sub();
2283 }
2284
2285 sub _get_departments {
2286   $main::lxdebug->enter_sub();
2287
2288   my ($self, $dbh, $key) = @_;
2289
2290   $key = "all_departments" unless ($key);
2291
2292   my $query = qq|SELECT * FROM department ORDER BY description|;
2293
2294   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2295
2296   $main::lxdebug->leave_sub();
2297 }
2298
2299 sub _get_warehouses {
2300   $main::lxdebug->enter_sub();
2301
2302   my ($self, $dbh, $param) = @_;
2303
2304   my ($key, $bins_key);
2305
2306   if ('' eq ref $param) {
2307     $key = $param;
2308
2309   } else {
2310     $key      = $param->{key};
2311     $bins_key = $param->{bins};
2312   }
2313
2314   my $query = qq|SELECT w.* FROM warehouse w
2315                  WHERE (NOT w.invalid) AND
2316                    ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2317                  ORDER BY w.sortkey|;
2318
2319   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2320
2321   if ($bins_key) {
2322     $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
2323     my $sth = prepare_query($self, $dbh, $query);
2324
2325     foreach my $warehouse (@{ $self->{$key} }) {
2326       do_statement($self, $sth, $query, $warehouse->{id});
2327       $warehouse->{$bins_key} = [];
2328
2329       while (my $ref = $sth->fetchrow_hashref()) {
2330         push @{ $warehouse->{$bins_key} }, $ref;
2331       }
2332     }
2333     $sth->finish();
2334   }
2335
2336   $main::lxdebug->leave_sub();
2337 }
2338
2339 sub _get_simple {
2340   $main::lxdebug->enter_sub();
2341
2342   my ($self, $dbh, $table, $key, $sortkey) = @_;
2343
2344   my $query  = qq|SELECT * FROM $table|;
2345   $query    .= qq| ORDER BY $sortkey| if ($sortkey);
2346
2347   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2348
2349   $main::lxdebug->leave_sub();
2350 }
2351
2352 #sub _get_groups {
2353 #  $main::lxdebug->enter_sub();
2354 #
2355 #  my ($self, $dbh, $key) = @_;
2356 #
2357 #  $key ||= "all_groups";
2358 #
2359 #  my $groups = $main::auth->read_groups();
2360 #
2361 #  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2362 #
2363 #  $main::lxdebug->leave_sub();
2364 #}
2365
2366 sub get_lists {
2367   $main::lxdebug->enter_sub();
2368
2369   my $self = shift;
2370   my %params = @_;
2371
2372   my $dbh = $self->get_standard_dbh(\%main::myconfig);
2373   my ($sth, $query, $ref);
2374
2375   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2376   my $vc_id = $self->{"${vc}_id"};
2377
2378   if ($params{"contacts"}) {
2379     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2380   }
2381
2382   if ($params{"shipto"}) {
2383     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2384   }
2385
2386   if ($params{"projects"} || $params{"all_projects"}) {
2387     $self->_get_projects($dbh, $params{"all_projects"} ?
2388                          $params{"all_projects"} : $params{"projects"},
2389                          $params{"all_projects"} ? 1 : 0);
2390   }
2391
2392   if ($params{"printers"}) {
2393     $self->_get_printers($dbh, $params{"printers"});
2394   }
2395
2396   if ($params{"languages"}) {
2397     $self->_get_languages($dbh, $params{"languages"});
2398   }
2399
2400   if ($params{"charts"}) {
2401     $self->_get_charts($dbh, $params{"charts"});
2402   }
2403
2404   if ($params{"taxcharts"}) {
2405     $self->_get_taxcharts($dbh, $params{"taxcharts"});
2406   }
2407
2408   if ($params{"taxzones"}) {
2409     $self->_get_taxzones($dbh, $params{"taxzones"});
2410   }
2411
2412   if ($params{"employees"}) {
2413     $self->_get_employees($dbh, "all_employees", $params{"employees"});
2414   }
2415
2416   if ($params{"salesmen"}) {
2417     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2418   }
2419
2420   if ($params{"business_types"}) {
2421     $self->_get_business_types($dbh, $params{"business_types"});
2422   }
2423
2424   if ($params{"dunning_configs"}) {
2425     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2426   }
2427
2428   if($params{"currencies"}) {
2429     $self->_get_currencies($dbh, $params{"currencies"});
2430   }
2431
2432   if($params{"customers"}) {
2433     if (ref $params{"customers"} eq 'HASH') {
2434       $self->_get_customers($dbh, $params{"customers"}{key}, $params{"customers"}{limit});
2435     } else {
2436       $self->_get_customers($dbh, $params{"customers"});
2437     }
2438   }
2439
2440   if($params{"vendors"}) {
2441     if (ref $params{"vendors"} eq 'HASH') {
2442       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2443     } else {
2444       $self->_get_vendors($dbh, $params{"vendors"});
2445     }
2446   }
2447
2448   if($params{"payments"}) {
2449     $self->_get_payments($dbh, $params{"payments"});
2450   }
2451
2452   if($params{"departments"}) {
2453     $self->_get_departments($dbh, $params{"departments"});
2454   }
2455
2456   if ($params{price_factors}) {
2457     $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2458   }
2459
2460   if ($params{warehouses}) {
2461     $self->_get_warehouses($dbh, $params{warehouses});
2462   }
2463
2464 #  if ($params{groups}) {
2465 #    $self->_get_groups($dbh, $params{groups});
2466 #  }
2467
2468   if ($params{partsgroup}) {
2469     $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2470   }
2471
2472   $main::lxdebug->leave_sub();
2473 }
2474
2475 # this sub gets the id and name from $table
2476 sub get_name {
2477   $main::lxdebug->enter_sub();
2478
2479   my ($self, $myconfig, $table) = @_;
2480
2481   # connect to database
2482   my $dbh = $self->get_standard_dbh($myconfig);
2483
2484   $table = $table eq "customer" ? "customer" : "vendor";
2485   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2486
2487   my ($query, @values);
2488
2489   if (!$self->{openinvoices}) {
2490     my $where;
2491     if ($self->{customernumber} ne "") {
2492       $where = qq|(vc.customernumber ILIKE ?)|;
2493       push(@values, '%' . $self->{customernumber} . '%');
2494     } else {
2495       $where = qq|(vc.name ILIKE ?)|;
2496       push(@values, '%' . $self->{$table} . '%');
2497     }
2498
2499     $query =
2500       qq~SELECT vc.id, vc.name,
2501            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2502          FROM $table vc
2503          WHERE $where AND (NOT vc.obsolete)
2504          ORDER BY vc.name~;
2505   } else {
2506     $query =
2507       qq~SELECT DISTINCT vc.id, vc.name,
2508            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2509          FROM $arap a
2510          JOIN $table vc ON (a.${table}_id = vc.id)
2511          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2512          ORDER BY vc.name~;
2513     push(@values, '%' . $self->{$table} . '%');
2514   }
2515
2516   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2517
2518   $main::lxdebug->leave_sub();
2519
2520   return scalar(@{ $self->{name_list} });
2521 }
2522
2523 # the selection sub is used in the AR, AP, IS, IR and OE module
2524 #
2525 sub all_vc {
2526   $main::lxdebug->enter_sub();
2527
2528   my ($self, $myconfig, $table, $module) = @_;
2529
2530   my $ref;
2531   my $dbh = $self->get_standard_dbh($myconfig);
2532
2533   $table = $table eq "customer" ? "customer" : "vendor";
2534
2535   my $query = qq|SELECT count(*) FROM $table|;
2536   my ($count) = selectrow_query($self, $dbh, $query);
2537
2538   # build selection list
2539   if ($count < $myconfig->{vclimit}) {
2540     $query = qq|SELECT id, name, salesman_id
2541                 FROM $table WHERE NOT obsolete
2542                 ORDER BY name|;
2543     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2544   }
2545
2546   # get self
2547   $self->get_employee($dbh);
2548
2549   # setup sales contacts
2550   $query = qq|SELECT e.id, e.name
2551               FROM employee e
2552               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2553   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2554
2555   # this is for self
2556   push(@{ $self->{all_employees} },
2557        { id   => $self->{employee_id},
2558          name => $self->{employee} });
2559
2560   # sort the whole thing
2561   @{ $self->{all_employees} } =
2562     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2563
2564   if ($module eq 'AR') {
2565
2566     # prepare query for departments
2567     $query = qq|SELECT id, description
2568                 FROM department
2569                 WHERE role = 'P'
2570                 ORDER BY description|;
2571
2572   } else {
2573     $query = qq|SELECT id, description
2574                 FROM department
2575                 ORDER BY description|;
2576   }
2577
2578   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2579
2580   # get languages
2581   $query = qq|SELECT id, description
2582               FROM language
2583               ORDER BY id|;
2584
2585   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2586
2587   # get printer
2588   $query = qq|SELECT printer_description, id
2589               FROM printers
2590               ORDER BY printer_description|;
2591
2592   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2593
2594   # get payment terms
2595   $query = qq|SELECT id, description
2596               FROM payment_terms
2597               ORDER BY sortkey|;
2598
2599   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2600
2601   $main::lxdebug->leave_sub();
2602 }
2603
2604 sub language_payment {
2605   $main::lxdebug->enter_sub();
2606
2607   my ($self, $myconfig) = @_;
2608
2609   my $dbh = $self->get_standard_dbh($myconfig);
2610   # get languages
2611   my $query = qq|SELECT id, description
2612                  FROM language
2613                  ORDER BY id|;
2614
2615   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2616
2617   # get printer
2618   $query = qq|SELECT printer_description, id
2619               FROM printers
2620               ORDER BY printer_description|;
2621
2622   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2623
2624   # get payment terms
2625   $query = qq|SELECT id, description
2626               FROM payment_terms
2627               ORDER BY sortkey|;
2628
2629   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2630
2631   # get buchungsgruppen
2632   $query = qq|SELECT id, description
2633               FROM buchungsgruppen|;
2634
2635   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2636
2637   $main::lxdebug->leave_sub();
2638 }
2639
2640 # this is only used for reports
2641 sub all_departments {
2642   $main::lxdebug->enter_sub();
2643
2644   my ($self, $myconfig, $table) = @_;
2645
2646   my $dbh = $self->get_standard_dbh($myconfig);
2647   my $where;
2648
2649   if ($table eq 'customer') {
2650     $where = "WHERE role = 'P' ";
2651   }
2652
2653   my $query = qq|SELECT id, description
2654                  FROM department
2655                  $where
2656                  ORDER BY description|;
2657   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2658
2659   delete($self->{all_departments}) unless (@{ $self->{all_departments} });
2660
2661   $main::lxdebug->leave_sub();
2662 }
2663
2664 sub create_links {
2665   $main::lxdebug->enter_sub();
2666
2667   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2668
2669   my ($fld, $arap);
2670   if ($table eq "customer") {
2671     $fld = "buy";
2672     $arap = "ar";
2673   } else {
2674     $table = "vendor";
2675     $fld = "sell";
2676     $arap = "ap";
2677   }
2678
2679   $self->all_vc($myconfig, $table, $module);
2680
2681   # get last customers or vendors
2682   my ($query, $sth, $ref);
2683
2684   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2685   my %xkeyref = ();
2686
2687   if (!$self->{id}) {
2688
2689     my $transdate = "current_date";
2690     if ($self->{transdate}) {
2691       $transdate = $dbh->quote($self->{transdate});
2692     }
2693
2694     # now get the account numbers
2695     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2696                 FROM chart c, taxkeys tk
2697                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2698                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2699                 ORDER BY c.accno|;
2700
2701     $sth = $dbh->prepare($query);
2702
2703     do_statement($self, $sth, $query, '%' . $module . '%');
2704
2705     $self->{accounts} = "";
2706     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2707
2708       foreach my $key (split(/:/, $ref->{link})) {
2709         if ($key =~ /\Q$module\E/) {
2710
2711           # cross reference for keys
2712           $xkeyref{ $ref->{accno} } = $key;
2713
2714           push @{ $self->{"${module}_links"}{$key} },
2715             { accno       => $ref->{accno},
2716               description => $ref->{description},
2717               taxkey      => $ref->{taxkey_id},
2718               tax_id      => $ref->{tax_id} };
2719
2720           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2721         }
2722       }
2723     }
2724   }
2725
2726   # get taxkeys and description
2727   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2728   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2729
2730   if (($module eq "AP") || ($module eq "AR")) {
2731     # get tax rates and description
2732     $query = qq|SELECT * FROM tax|;
2733     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2734   }
2735
2736   if ($self->{id}) {
2737     $query =
2738       qq|SELECT
2739            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2740            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2741            a.intnotes, a.department_id, a.amount AS oldinvtotal,
2742            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2743            c.name AS $table,
2744            d.description AS department,
2745            e.name AS employee
2746          FROM $arap a
2747          JOIN $table c ON (a.${table}_id = c.id)
2748          LEFT JOIN employee e ON (e.id = a.employee_id)
2749          LEFT JOIN department d ON (d.id = a.department_id)
2750          WHERE a.id = ?|;
2751     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2752
2753     foreach my $key (keys %$ref) {
2754       $self->{$key} = $ref->{$key};
2755     }
2756
2757     my $transdate = "current_date";
2758     if ($self->{transdate}) {
2759       $transdate = $dbh->quote($self->{transdate});
2760     }
2761
2762     # now get the account numbers
2763     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2764                 FROM chart c
2765                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2766                 WHERE c.link LIKE ?
2767                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2768                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2769                 ORDER BY c.accno|;
2770
2771     $sth = $dbh->prepare($query);
2772     do_statement($self, $sth, $query, "%$module%");
2773
2774     $self->{accounts} = "";
2775     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2776
2777       foreach my $key (split(/:/, $ref->{link})) {
2778         if ($key =~ /\Q$module\E/) {
2779
2780           # cross reference for keys
2781           $xkeyref{ $ref->{accno} } = $key;
2782
2783           push @{ $self->{"${module}_links"}{$key} },
2784             { accno       => $ref->{accno},
2785               description => $ref->{description},
2786               taxkey      => $ref->{taxkey_id},
2787               tax_id      => $ref->{tax_id} };
2788
2789           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2790         }
2791       }
2792     }
2793
2794
2795     # get amounts from individual entries
2796     $query =
2797       qq|SELECT
2798            c.accno, c.description,
2799            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2800            p.projectnumber,
2801            t.rate, t.id
2802          FROM acc_trans a
2803          LEFT JOIN chart c ON (c.id = a.chart_id)
2804          LEFT JOIN project p ON (p.id = a.project_id)
2805          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2806                                     WHERE (tk.taxkey_id=a.taxkey) AND
2807                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2808                                         THEN tk.chart_id = a.chart_id
2809                                         ELSE 1 = 1
2810                                         END)
2811                                        OR (c.link='%tax%')) AND
2812                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2813          WHERE a.trans_id = ?
2814          AND a.fx_transaction = '0'
2815          ORDER BY a.oid, a.transdate|;
2816     $sth = $dbh->prepare($query);
2817     do_statement($self, $sth, $query, $self->{id});
2818
2819     # get exchangerate for currency
2820     $self->{exchangerate} =
2821       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2822     my $index = 0;
2823
2824     # store amounts in {acc_trans}{$key} for multiple accounts
2825     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2826       $ref->{exchangerate} =
2827         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2828       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2829         $index++;
2830       }
2831       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2832         $ref->{amount} *= -1;
2833       }
2834       $ref->{index} = $index;
2835
2836       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2837     }
2838
2839     $sth->finish;
2840     $query =
2841       qq|SELECT
2842            d.curr AS currencies, d.closedto, d.revtrans,
2843            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2844            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2845          FROM defaults d|;
2846     $ref = selectfirst_hashref_query($self, $dbh, $query);
2847     map { $self->{$_} = $ref->{$_} } keys %$ref;
2848
2849   } else {
2850
2851     # get date
2852     $query =
2853        qq|SELECT
2854             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2855             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2856             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2857           FROM defaults d|;
2858     $ref = selectfirst_hashref_query($self, $dbh, $query);
2859     map { $self->{$_} = $ref->{$_} } keys %$ref;
2860
2861     if ($self->{"$self->{vc}_id"}) {
2862
2863       # only setup currency
2864       ($self->{currency}) = split(/:/, $self->{currencies});
2865
2866     } else {
2867
2868       $self->lastname_used($dbh, $myconfig, $table, $module);
2869
2870       # get exchangerate for currency
2871       $self->{exchangerate} =
2872         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2873
2874     }
2875
2876   }
2877
2878   $main::lxdebug->leave_sub();
2879 }
2880
2881 sub lastname_used {
2882   $main::lxdebug->enter_sub();
2883
2884   my ($self, $dbh, $myconfig, $table, $module) = @_;
2885
2886   my ($arap, $where);
2887
2888   $table         = $table eq "customer" ? "customer" : "vendor";
2889   my %column_map = ("a.curr"                  => "currency",
2890                     "a.${table}_id"           => "${table}_id",
2891                     "a.department_id"         => "department_id",
2892                     "d.description"           => "department",
2893                     "ct.name"                 => $table,
2894                     "current_date + ct.terms" => "duedate",
2895     );
2896
2897   if ($self->{type} =~ /delivery_order/) {
2898     $arap  = 'delivery_orders';
2899     delete $column_map{"a.curr"};
2900
2901   } elsif ($self->{type} =~ /_order/) {
2902     $arap  = 'oe';
2903     $where = "quotation = '0'";
2904
2905   } elsif ($self->{type} =~ /_quotation/) {
2906     $arap  = 'oe';
2907     $where = "quotation = '1'";
2908
2909   } elsif ($table eq 'customer') {
2910     $arap  = 'ar';
2911
2912   } else {
2913     $arap  = 'ap';
2914
2915   }
2916
2917   $where           = "($where) AND" if ($where);
2918   my $query        = qq|SELECT MAX(id) FROM $arap
2919                         WHERE $where ${table}_id > 0|;
2920   my ($trans_id)   = selectrow_query($self, $dbh, $query);
2921   $trans_id       *= 1;
2922
2923   my $column_spec  = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2924   $query           = qq|SELECT $column_spec
2925                         FROM $arap a
2926                         LEFT JOIN $table     ct ON (a.${table}_id = ct.id)
2927                         LEFT JOIN department d  ON (a.department_id = d.id)
2928                         WHERE a.id = ?|;
2929   my $ref          = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
2930
2931   map { $self->{$_} = $ref->{$_} } values %column_map;
2932
2933   $main::lxdebug->leave_sub();
2934 }
2935
2936 sub current_date {
2937   $main::lxdebug->enter_sub();
2938
2939   my ($self, $myconfig, $thisdate, $days) = @_;
2940
2941   my $dbh = $self->get_standard_dbh($myconfig);
2942   my $query;
2943
2944   $days *= 1;
2945   if ($thisdate) {
2946     my $dateformat = $myconfig->{dateformat};
2947     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2948     $thisdate = $dbh->quote($thisdate);
2949     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2950   } else {
2951     $query = qq|SELECT current_date AS thisdate|;
2952   }
2953
2954   ($thisdate) = selectrow_query($self, $dbh, $query);
2955
2956   $main::lxdebug->leave_sub();
2957
2958   return $thisdate;
2959 }
2960
2961 sub like {
2962   $main::lxdebug->enter_sub();
2963
2964   my ($self, $string) = @_;
2965
2966   if ($string !~ /%/) {
2967     $string = "%$string%";
2968   }
2969
2970   $string =~ s/\'/\'\'/g;
2971
2972   $main::lxdebug->leave_sub();
2973
2974   return $string;
2975 }
2976
2977 sub redo_rows {
2978   $main::lxdebug->enter_sub();
2979
2980   my ($self, $flds, $new, $count, $numrows) = @_;
2981
2982   my @ndx = ();
2983
2984   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
2985
2986   my $i = 0;
2987
2988   # fill rows
2989   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2990     $i++;
2991     my $j = $item->{ndx} - 1;
2992     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2993   }
2994
2995   # delete empty rows
2996   for $i ($count + 1 .. $numrows) {
2997     map { delete $self->{"${_}_$i"} } @{$flds};
2998   }
2999
3000   $main::lxdebug->leave_sub();
3001 }
3002
3003 sub update_status {
3004   $main::lxdebug->enter_sub();
3005
3006   my ($self, $myconfig) = @_;
3007
3008   my ($i, $id);
3009
3010   my $dbh = $self->dbconnect_noauto($myconfig);
3011
3012   my $query = qq|DELETE FROM status
3013                  WHERE (formname = ?) AND (trans_id = ?)|;
3014   my $sth = prepare_query($self, $dbh, $query);
3015
3016   if ($self->{formname} =~ /(check|receipt)/) {
3017     for $i (1 .. $self->{rowcount}) {
3018       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
3019     }
3020   } else {
3021     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
3022   }
3023   $sth->finish();
3024
3025   my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3026   my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3027
3028   my %queued = split / /, $self->{queued};
3029   my @values;
3030
3031   if ($self->{formname} =~ /(check|receipt)/) {
3032
3033     # this is a check or receipt, add one entry for each lineitem
3034     my ($accno) = split /--/, $self->{account};
3035     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3036                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3037     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3038     $sth = prepare_query($self, $dbh, $query);
3039
3040     for $i (1 .. $self->{rowcount}) {
3041       if ($self->{"checked_$i"}) {
3042         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3043       }
3044     }
3045     $sth->finish();
3046
3047   } else {
3048     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3049                 VALUES (?, ?, ?, ?, ?)|;
3050     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3051              $queued{$self->{formname}}, $self->{formname});
3052   }
3053
3054   $dbh->commit;
3055   $dbh->disconnect;
3056
3057   $main::lxdebug->leave_sub();
3058 }
3059
3060 sub save_status {
3061   $main::lxdebug->enter_sub();
3062
3063   my ($self, $dbh) = @_;
3064
3065   my ($query, $printed, $emailed);
3066
3067   my $formnames  = $self->{printed};
3068   my $emailforms = $self->{emailed};
3069
3070   $query = qq|DELETE FROM status
3071                  WHERE (formname = ?) AND (trans_id = ?)|;
3072   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3073
3074   # this only applies to the forms
3075   # checks and receipts are posted when printed or queued
3076
3077   if ($self->{queued}) {
3078     my %queued = split / /, $self->{queued};
3079
3080     foreach my $formname (keys %queued) {
3081       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3082       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3083
3084       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3085                   VALUES (?, ?, ?, ?, ?)|;
3086       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3087
3088       $formnames  =~ s/\Q$self->{formname}\E//;
3089       $emailforms =~ s/\Q$self->{formname}\E//;
3090
3091     }
3092   }
3093
3094   # save printed, emailed info
3095   $formnames  =~ s/^ +//g;
3096   $emailforms =~ s/^ +//g;
3097
3098   my %status = ();
3099   map { $status{$_}{printed} = 1 } split / +/, $formnames;
3100   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3101
3102   foreach my $formname (keys %status) {
3103     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
3104     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3105
3106     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3107                 VALUES (?, ?, ?, ?)|;
3108     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3109   }
3110
3111   $main::lxdebug->leave_sub();
3112 }
3113
3114 #--- 4 locale ---#
3115 # $main::locale->text('SAVED')
3116 # $main::locale->text('DELETED')
3117 # $main::locale->text('ADDED')
3118 # $main::locale->text('PAYMENT POSTED')
3119 # $main::locale->text('POSTED')
3120 # $main::locale->text('POSTED AS NEW')
3121 # $main::locale->text('ELSE')
3122 # $main::locale->text('SAVED FOR DUNNING')
3123 # $main::locale->text('DUNNING STARTED')
3124 # $main::locale->text('PRINTED')
3125 # $main::locale->text('MAILED')
3126 # $main::locale->text('SCREENED')
3127 # $main::locale->text('CANCELED')
3128 # $main::locale->text('invoice')
3129 # $main::locale->text('proforma')
3130 # $main::locale->text('sales_order')
3131 # $main::locale->text('packing_list')
3132 # $main::locale->text('pick_list')
3133 # $main::locale->text('purchase_order')
3134 # $main::locale->text('bin_list')
3135 # $main::locale->text('sales_quotation')
3136 # $main::locale->text('request_quotation')
3137
3138 sub save_history {
3139   $main::lxdebug->enter_sub();
3140
3141   my $self = shift();
3142   my $dbh = shift();
3143
3144   if(!exists $self->{employee_id}) {
3145     &get_employee($self, $dbh);
3146   }
3147
3148   my $query =
3149    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3150    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3151   my @values = (conv_i($self->{id}), $self->{login},
3152                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3153   do_query($self, $dbh, $query, @values);
3154
3155   $main::lxdebug->leave_sub();
3156 }
3157
3158 sub get_history {
3159   $main::lxdebug->enter_sub();
3160
3161   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3162   my ($orderBy, $desc) = split(/\-\-/, $order);
3163   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3164   my @tempArray;
3165   my $i = 0;
3166   if ($trans_id ne "") {
3167     my $query =
3168       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 | .
3169       qq|FROM history_erp h | .
3170       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3171       qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3172       $order;
3173
3174     my $sth = $dbh->prepare($query) || $self->dberror($query);
3175
3176     $sth->execute() || $self->dberror("$query");
3177
3178     while(my $hash_ref = $sth->fetchrow_hashref()) {
3179       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3180       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3181       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3182       $tempArray[$i++] = $hash_ref;
3183     }
3184     $main::lxdebug->leave_sub() and return \@tempArray
3185       if ($i > 0 && $tempArray[0] ne "");
3186   }
3187   $main::lxdebug->leave_sub();
3188   return 0;
3189 }
3190
3191 sub update_defaults {
3192   $main::lxdebug->enter_sub();
3193
3194   my ($self, $myconfig, $fld, $provided_dbh) = @_;
3195
3196   my $dbh;
3197   if ($provided_dbh) {
3198     $dbh = $provided_dbh;
3199   } else {
3200     $dbh = $self->dbconnect_noauto($myconfig);
3201   }
3202   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3203   my $sth   = $dbh->prepare($query);
3204
3205   $sth->execute || $self->dberror($query);
3206   my ($var) = $sth->fetchrow_array;
3207   $sth->finish;
3208
3209   if ($var =~ m/\d+$/) {
3210     my $new_var  = (substr $var, $-[0]) * 1 + 1;
3211     my $len_diff = length($var) - $-[0] - length($new_var);
3212     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3213
3214   } else {
3215     $var = $var . '1';
3216   }
3217
3218   $query = qq|UPDATE defaults SET $fld = ?|;
3219   do_query($self, $dbh, $query, $var);
3220
3221   if (!$provided_dbh) {
3222     $dbh->commit;
3223     $dbh->disconnect;
3224   }
3225
3226   $main::lxdebug->leave_sub();
3227
3228   return $var;
3229 }
3230
3231 sub update_business {
3232   $main::lxdebug->enter_sub();
3233
3234   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3235
3236   my $dbh;
3237   if ($provided_dbh) {
3238     $dbh = $provided_dbh;
3239   } else {
3240     $dbh = $self->dbconnect_noauto($myconfig);
3241   }
3242   my $query =
3243     qq|SELECT customernumberinit FROM business
3244        WHERE id = ? FOR UPDATE|;
3245   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3246
3247   if ($var =~ m/\d+$/) {
3248     my $new_var  = (substr $var, $-[0]) * 1 + 1;
3249     my $len_diff = length($var) - $-[0] - length($new_var);
3250     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3251
3252   } else {
3253     $var = $var . '1';
3254   }
3255
3256   $query = qq|UPDATE business
3257               SET customernumberinit = ?
3258               WHERE id = ?|;
3259   do_query($self, $dbh, $query, $var, $business_id);
3260
3261   if (!$provided_dbh) {
3262     $dbh->commit;
3263     $dbh->disconnect;
3264   }
3265
3266   $main::lxdebug->leave_sub();
3267
3268   return $var;
3269 }
3270
3271 sub get_partsgroup {
3272   $main::lxdebug->enter_sub();
3273
3274   my ($self, $myconfig, $p) = @_;
3275   my $target = $p->{target} || 'all_partsgroup';
3276
3277   my $dbh = $self->get_standard_dbh($myconfig);
3278
3279   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3280                  FROM partsgroup pg
3281                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
3282   my @values;
3283
3284   if ($p->{searchitems} eq 'part') {
3285     $query .= qq|WHERE p.inventory_accno_id > 0|;
3286   }
3287   if ($p->{searchitems} eq 'service') {
3288     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3289   }
3290   if ($p->{searchitems} eq 'assembly') {
3291     $query .= qq|WHERE p.assembly = '1'|;
3292   }
3293   if ($p->{searchitems} eq 'labor') {
3294     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3295   }
3296
3297   $query .= qq|ORDER BY partsgroup|;
3298
3299   if ($p->{all}) {
3300     $query = qq|SELECT id, partsgroup FROM partsgroup
3301                 ORDER BY partsgroup|;
3302   }
3303
3304   if ($p->{language_code}) {
3305     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3306                   t.description AS translation
3307                 FROM partsgroup pg
3308                 JOIN parts p ON (p.partsgroup_id = pg.id)
3309                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3310                 ORDER BY translation|;
3311     @values = ($p->{language_code});
3312   }
3313
3314   $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3315
3316   $main::lxdebug->leave_sub();
3317 }
3318
3319 sub get_pricegroup {
3320   $main::lxdebug->enter_sub();
3321
3322   my ($self, $myconfig, $p) = @_;
3323
3324   my $dbh = $self->get_standard_dbh($myconfig);
3325
3326   my $query = qq|SELECT p.id, p.pricegroup
3327                  FROM pricegroup p|;
3328
3329   $query .= qq| ORDER BY pricegroup|;
3330
3331   if ($p->{all}) {
3332     $query = qq|SELECT id, pricegroup FROM pricegroup
3333                 ORDER BY pricegroup|;
3334   }
3335
3336   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3337
3338   $main::lxdebug->leave_sub();
3339 }
3340
3341 sub all_years {
3342 # usage $form->all_years($myconfig, [$dbh])
3343 # return list of all years where bookings found
3344 # (@all_years)
3345
3346   $main::lxdebug->enter_sub();
3347
3348   my ($self, $myconfig, $dbh) = @_;
3349
3350   $dbh ||= $self->get_standard_dbh($myconfig);
3351
3352   # get years
3353   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3354                    (SELECT MAX(transdate) FROM acc_trans)|;
3355   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3356
3357   if ($myconfig->{dateformat} =~ /^yy/) {
3358     ($startdate) = split /\W/, $startdate;
3359     ($enddate) = split /\W/, $enddate;
3360   } else {
3361     (@_) = split /\W/, $startdate;
3362     $startdate = $_[2];
3363     (@_) = split /\W/, $enddate;
3364     $enddate = $_[2];
3365   }
3366
3367   my @all_years;
3368   $startdate = substr($startdate,0,4);
3369   $enddate = substr($enddate,0,4);
3370
3371   while ($enddate >= $startdate) {
3372     push @all_years, $enddate--;
3373   }
3374
3375   return @all_years;
3376
3377   $main::lxdebug->leave_sub();
3378 }
3379
3380 sub backup_vars {
3381   $main::lxdebug->enter_sub();
3382   my $self = shift;
3383   my @vars = @_;
3384
3385   map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3386
3387   $main::lxdebug->leave_sub();
3388 }
3389
3390 sub restore_vars {
3391   $main::lxdebug->enter_sub();
3392
3393   my $self = shift;
3394   my @vars = @_;
3395
3396   map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3397
3398   $main::lxdebug->leave_sub();
3399 }
3400
3401 1;