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