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