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