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