AJAX-Antworten nicht direkt $cgi->header() ausgeben, sondern über eine Funktion,...
[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   map({ $self->{"employee_${_}"} = $myconfig->{$_}; }
1111       qw(email tel fax name signature company address businessnumber
1112          co_ustid taxnumber duns));
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_salesman {
1887   $main::lxdebug->enter_sub();
1888
1889   my ($self, $myconfig, $salesman_id) = @_;
1890
1891   $main::lxdebug->leave_sub() and return unless $salesman_id;
1892
1893   my $dbh = $self->get_standard_dbh($myconfig);
1894
1895   my ($login) =
1896     selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|,
1897                     $salesman_id);
1898
1899   if ($login) {
1900     my $user = new User($main::memberfile, $login);
1901     map({ $self->{"salesman_$_"} = $user->{$_}; }
1902         qw(address businessnumber co_ustid company duns email fax name
1903            taxnumber tel));
1904     $self->{salesman_login} = $login;
1905
1906     $self->{salesman_name} = $login
1907       if ($self->{salesman_name} eq "");
1908   }
1909
1910   $main::lxdebug->leave_sub();
1911 }
1912
1913 sub get_duedate {
1914   $main::lxdebug->enter_sub();
1915
1916   my ($self, $myconfig) = @_;
1917
1918   my $dbh = $self->get_standard_dbh($myconfig);
1919   my $query = qq|SELECT current_date + terms_netto FROM payment_terms WHERE id = ?|;
1920   ($self->{duedate}) = selectrow_query($self, $dbh, $query, $self->{payment_id});
1921
1922   $main::lxdebug->leave_sub();
1923 }
1924
1925 sub _get_contacts {
1926   $main::lxdebug->enter_sub();
1927
1928   my ($self, $dbh, $id, $key) = @_;
1929
1930   $key = "all_contacts" unless ($key);
1931
1932   if (!$id) {
1933     $self->{$key} = [];
1934     $main::lxdebug->leave_sub();
1935     return;
1936   }
1937
1938   my $query =
1939     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
1940     qq|FROM contacts | .
1941     qq|WHERE cp_cv_id = ? | .
1942     qq|ORDER BY lower(cp_name)|;
1943
1944   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
1945
1946   $main::lxdebug->leave_sub();
1947 }
1948
1949 sub _get_projects {
1950   $main::lxdebug->enter_sub();
1951
1952   my ($self, $dbh, $key) = @_;
1953
1954   my ($all, $old_id, $where, @values);
1955
1956   if (ref($key) eq "HASH") {
1957     my $params = $key;
1958
1959     $key = "ALL_PROJECTS";
1960
1961     foreach my $p (keys(%{$params})) {
1962       if ($p eq "all") {
1963         $all = $params->{$p};
1964       } elsif ($p eq "old_id") {
1965         $old_id = $params->{$p};
1966       } elsif ($p eq "key") {
1967         $key = $params->{$p};
1968       }
1969     }
1970   }
1971
1972   if (!$all) {
1973     $where = "WHERE active ";
1974     if ($old_id) {
1975       if (ref($old_id) eq "ARRAY") {
1976         my @ids = grep({ $_ } @{$old_id});
1977         if (@ids) {
1978           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
1979           push(@values, @ids);
1980         }
1981       } else {
1982         $where .= " OR (id = ?) ";
1983         push(@values, $old_id);
1984       }
1985     }
1986   }
1987
1988   my $query =
1989     qq|SELECT id, projectnumber, description, active | .
1990     qq|FROM project | .
1991     $where .
1992     qq|ORDER BY lower(projectnumber)|;
1993
1994   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
1995
1996   $main::lxdebug->leave_sub();
1997 }
1998
1999 sub _get_shipto {
2000   $main::lxdebug->enter_sub();
2001
2002   my ($self, $dbh, $vc_id, $key) = @_;
2003
2004   $key = "all_shipto" unless ($key);
2005
2006   if ($vc_id) {
2007     # get shipping addresses
2008     my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2009
2010     $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2011
2012   } else {
2013     $self->{$key} = [];
2014   }
2015
2016   $main::lxdebug->leave_sub();
2017 }
2018
2019 sub _get_printers {
2020   $main::lxdebug->enter_sub();
2021
2022   my ($self, $dbh, $key) = @_;
2023
2024   $key = "all_printers" unless ($key);
2025
2026   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2027
2028   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2029
2030   $main::lxdebug->leave_sub();
2031 }
2032
2033 sub _get_charts {
2034   $main::lxdebug->enter_sub();
2035
2036   my ($self, $dbh, $params) = @_;
2037
2038   $key = $params->{key};
2039   $key = "all_charts" unless ($key);
2040
2041   my $transdate = quote_db_date($params->{transdate});
2042
2043   my $query =
2044     qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
2045     qq|FROM chart c | .
2046     qq|LEFT JOIN taxkeys tk ON | .
2047     qq|(tk.id = (SELECT id FROM taxkeys | .
2048     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2049     qq|          ORDER BY startdate DESC LIMIT 1)) | .
2050     qq|ORDER BY c.accno|;
2051
2052   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2053
2054   $main::lxdebug->leave_sub();
2055 }
2056
2057 sub _get_taxcharts {
2058   $main::lxdebug->enter_sub();
2059
2060   my ($self, $dbh, $key) = @_;
2061
2062   $key = "all_taxcharts" unless ($key);
2063
2064   my $query = qq|SELECT * FROM tax ORDER BY taxkey|;
2065
2066   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2067
2068   $main::lxdebug->leave_sub();
2069 }
2070
2071 sub _get_taxzones {
2072   $main::lxdebug->enter_sub();
2073
2074   my ($self, $dbh, $key) = @_;
2075
2076   $key = "all_taxzones" unless ($key);
2077
2078   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
2079
2080   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2081
2082   $main::lxdebug->leave_sub();
2083 }
2084
2085 sub _get_employees {
2086   $main::lxdebug->enter_sub();
2087
2088   my ($self, $dbh, $default_key, $key) = @_;
2089
2090   $key = $default_key unless ($key);
2091   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
2092
2093   $main::lxdebug->leave_sub();
2094 }
2095
2096 sub _get_business_types {
2097   $main::lxdebug->enter_sub();
2098
2099   my ($self, $dbh, $key) = @_;
2100
2101   $key = "all_business_types" unless ($key);
2102   $self->{$key} =
2103     selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
2104
2105   $main::lxdebug->leave_sub();
2106 }
2107
2108 sub _get_languages {
2109   $main::lxdebug->enter_sub();
2110
2111   my ($self, $dbh, $key) = @_;
2112
2113   $key = "all_languages" unless ($key);
2114
2115   my $query = qq|SELECT * FROM language ORDER BY id|;
2116
2117   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2118
2119   $main::lxdebug->leave_sub();
2120 }
2121
2122 sub _get_dunning_configs {
2123   $main::lxdebug->enter_sub();
2124
2125   my ($self, $dbh, $key) = @_;
2126
2127   $key = "all_dunning_configs" unless ($key);
2128
2129   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2130
2131   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2132
2133   $main::lxdebug->leave_sub();
2134 }
2135
2136 sub _get_currencies {
2137 $main::lxdebug->enter_sub();
2138
2139   my ($self, $dbh, $key) = @_;
2140
2141   $key = "all_currencies" unless ($key);
2142
2143   my $query = qq|SELECT curr AS currency FROM defaults|;
2144  
2145   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2146
2147   $main::lxdebug->leave_sub();
2148 }
2149
2150 sub _get_payments {
2151 $main::lxdebug->enter_sub();
2152
2153   my ($self, $dbh, $key) = @_;
2154
2155   $key = "all_payments" unless ($key);
2156
2157   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
2158  
2159   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2160
2161   $main::lxdebug->leave_sub();
2162 }
2163
2164 sub _get_customers {
2165   $main::lxdebug->enter_sub();
2166
2167   my ($self, $dbh, $key, $limit) = @_;
2168
2169   $key = "all_customers" unless ($key);
2170   $limit_clause = "LIMIT $limit" if $limit;
2171
2172   my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name $limit_clause|;
2173
2174   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2175
2176   $main::lxdebug->leave_sub();
2177 }
2178
2179 sub _get_vendors {
2180   $main::lxdebug->enter_sub();
2181
2182   my ($self, $dbh, $key) = @_;
2183
2184   $key = "all_vendors" unless ($key);
2185
2186   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2187
2188   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2189
2190   $main::lxdebug->leave_sub();
2191 }
2192
2193 sub _get_departments {
2194   $main::lxdebug->enter_sub();
2195
2196   my ($self, $dbh, $key) = @_;
2197
2198   $key = "all_departments" unless ($key);
2199
2200   my $query = qq|SELECT * FROM department ORDER BY description|;
2201
2202   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2203
2204   $main::lxdebug->leave_sub();
2205 }
2206
2207 sub _get_warehouses {
2208   $main::lxdebug->enter_sub();
2209
2210   my ($self, $dbh, $param) = @_;
2211
2212   my ($key, $bins_key);
2213
2214   if ('' eq ref $param) {
2215     $key = $param;
2216
2217   } else {
2218     $key      = $param->{key};
2219     $bins_key = $param->{bins};
2220   }
2221
2222   my $query = qq|SELECT w.* FROM warehouse w
2223                  WHERE (NOT w.invalid) AND
2224                    ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2225                  ORDER BY w.sortkey|;
2226
2227   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2228
2229   if ($bins_key) {
2230     $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
2231     my $sth = prepare_query($self, $dbh, $query);
2232
2233     foreach my $warehouse (@{ $self->{$key} }) {
2234       do_statement($self, $sth, $query, $warehouse->{id});
2235       $warehouse->{$bins_key} = [];
2236
2237       while (my $ref = $sth->fetchrow_hashref()) {
2238         push @{ $warehouse->{$bins_key} }, $ref;
2239       }
2240     }
2241     $sth->finish();
2242   }
2243
2244   $main::lxdebug->leave_sub();
2245 }
2246
2247 sub _get_simple {
2248   $main::lxdebug->enter_sub();
2249
2250   my ($self, $dbh, $table, $key, $sortkey) = @_;
2251
2252   my $query  = qq|SELECT * FROM $table|;
2253   $query    .= qq| ORDER BY $sortkey| if ($sortkey);
2254
2255   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2256
2257   $main::lxdebug->leave_sub();
2258 }
2259
2260 sub _get_groups {
2261   $main::lxdebug->enter_sub();
2262
2263   my ($self, $dbh, $key) = @_;
2264
2265   $key ||= "all_groups";
2266
2267   my $groups = $main::auth->read_groups();
2268
2269   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2270
2271   $main::lxdebug->leave_sub();
2272 }
2273
2274 sub get_lists {
2275   $main::lxdebug->enter_sub();
2276
2277   my $self = shift;
2278   my %params = @_;
2279
2280   my $dbh = $self->get_standard_dbh(\%main::myconfig);
2281   my ($sth, $query, $ref);
2282
2283   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2284   my $vc_id = $self->{"${vc}_id"};
2285
2286   if ($params{"contacts"}) {
2287     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2288   }
2289
2290   if ($params{"shipto"}) {
2291     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2292   }
2293
2294   if ($params{"projects"} || $params{"all_projects"}) {
2295     $self->_get_projects($dbh, $params{"all_projects"} ?
2296                          $params{"all_projects"} : $params{"projects"},
2297                          $params{"all_projects"} ? 1 : 0);
2298   }
2299
2300   if ($params{"printers"}) {
2301     $self->_get_printers($dbh, $params{"printers"});
2302   }
2303
2304   if ($params{"languages"}) {
2305     $self->_get_languages($dbh, $params{"languages"});
2306   }
2307
2308   if ($params{"charts"}) {
2309     $self->_get_charts($dbh, $params{"charts"});
2310   }
2311
2312   if ($params{"taxcharts"}) {
2313     $self->_get_taxcharts($dbh, $params{"taxcharts"});
2314   }
2315
2316   if ($params{"taxzones"}) {
2317     $self->_get_taxzones($dbh, $params{"taxzones"});
2318   }
2319
2320   if ($params{"employees"}) {
2321     $self->_get_employees($dbh, "all_employees", $params{"employees"});
2322   }
2323   
2324   if ($params{"salesmen"}) {
2325     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2326   }
2327
2328   if ($params{"business_types"}) {
2329     $self->_get_business_types($dbh, $params{"business_types"});
2330   }
2331
2332   if ($params{"dunning_configs"}) {
2333     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2334   }
2335   
2336   if($params{"currencies"}) {
2337     $self->_get_currencies($dbh, $params{"currencies"});
2338   }
2339   
2340   if($params{"customers"}) {
2341     if (ref $params{"customers"} eq 'HASH') {
2342       $self->_get_customers($dbh, $params{"customers"}{key}, $params{"customers"}{limit});
2343     } else {
2344       $self->_get_customers($dbh, $params{"customers"});
2345     }
2346   }
2347   
2348   if($params{"vendors"}) {
2349     if (ref $params{"vendors"} eq 'HASH') {
2350       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2351     } else {
2352       $self->_get_vendors($dbh, $params{"vendors"});
2353     }
2354   }
2355   
2356   if($params{"payments"}) {
2357     $self->_get_payments($dbh, $params{"payments"});
2358   }
2359
2360   if($params{"departments"}) {
2361     $self->_get_departments($dbh, $params{"departments"});
2362   }
2363
2364   if ($params{price_factors}) {
2365     $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2366   }
2367
2368   if ($params{warehouses}) {
2369     $self->_get_warehouses($dbh, $params{warehouses});
2370   }
2371
2372   if ($params{groups}) {
2373     $self->_get_groups($dbh, $params{groups});
2374   }
2375   if ($params{partsgroup}) {
2376     $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2377   }
2378
2379   $main::lxdebug->leave_sub();
2380 }
2381
2382 # this sub gets the id and name from $table
2383 sub get_name {
2384   $main::lxdebug->enter_sub();
2385
2386   my ($self, $myconfig, $table) = @_;
2387
2388   # connect to database
2389   my $dbh = $self->get_standard_dbh($myconfig);
2390
2391   $table = $table eq "customer" ? "customer" : "vendor";
2392   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2393
2394   my ($query, @values);
2395
2396   if (!$self->{openinvoices}) {
2397     my $where;
2398     if ($self->{customernumber} ne "") {
2399       $where = qq|(vc.customernumber ILIKE ?)|;
2400       push(@values, '%' . $self->{customernumber} . '%');
2401     } else {
2402       $where = qq|(vc.name ILIKE ?)|;
2403       push(@values, '%' . $self->{$table} . '%');
2404     }
2405
2406     $query =
2407       qq~SELECT vc.id, vc.name,
2408            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2409          FROM $table vc
2410          WHERE $where AND (NOT vc.obsolete)
2411          ORDER BY vc.name~;
2412   } else {
2413     $query =
2414       qq~SELECT DISTINCT vc.id, vc.name,
2415            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2416          FROM $arap a
2417          JOIN $table vc ON (a.${table}_id = vc.id)
2418          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2419          ORDER BY vc.name~;
2420     push(@values, '%' . $self->{$table} . '%');
2421   }
2422
2423   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2424
2425   $main::lxdebug->leave_sub();
2426
2427   return scalar(@{ $self->{name_list} });
2428 }
2429
2430 # the selection sub is used in the AR, AP, IS, IR and OE module
2431 #
2432 sub all_vc {
2433   $main::lxdebug->enter_sub();
2434
2435   my ($self, $myconfig, $table, $module) = @_;
2436
2437   my $ref;
2438   my $dbh = $self->get_standard_dbh($myconfig);
2439
2440   $table = $table eq "customer" ? "customer" : "vendor";
2441
2442   my $query = qq|SELECT count(*) FROM $table|;
2443   my ($count) = selectrow_query($self, $dbh, $query);
2444
2445   # build selection list
2446   if ($count < $myconfig->{vclimit}) {
2447     $query = qq|SELECT id, name, salesman_id
2448                 FROM $table WHERE NOT obsolete
2449                 ORDER BY name|;
2450     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2451   }
2452
2453   # get self
2454   $self->get_employee($dbh);
2455
2456   # setup sales contacts
2457   $query = qq|SELECT e.id, e.name
2458               FROM employee e
2459               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2460   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2461
2462   # this is for self
2463   push(@{ $self->{all_employees} },
2464        { id   => $self->{employee_id},
2465          name => $self->{employee} });
2466
2467   # sort the whole thing
2468   @{ $self->{all_employees} } =
2469     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2470
2471   if ($module eq 'AR') {
2472
2473     # prepare query for departments
2474     $query = qq|SELECT id, description
2475                 FROM department
2476                 WHERE role = 'P'
2477                 ORDER BY description|;
2478
2479   } else {
2480     $query = qq|SELECT id, description
2481                 FROM department
2482                 ORDER BY description|;
2483   }
2484
2485   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2486
2487   # get languages
2488   $query = qq|SELECT id, description
2489               FROM language
2490               ORDER BY id|;
2491
2492   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2493
2494   # get printer
2495   $query = qq|SELECT printer_description, id
2496               FROM printers
2497               ORDER BY printer_description|;
2498
2499   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2500
2501   # get payment terms
2502   $query = qq|SELECT id, description
2503               FROM payment_terms
2504               ORDER BY sortkey|;
2505
2506   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2507
2508   $main::lxdebug->leave_sub();
2509 }
2510
2511 sub language_payment {
2512   $main::lxdebug->enter_sub();
2513
2514   my ($self, $myconfig) = @_;
2515
2516   my $dbh = $self->get_standard_dbh($myconfig);
2517   # get languages
2518   my $query = qq|SELECT id, description
2519                  FROM language
2520                  ORDER BY id|;
2521
2522   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2523
2524   # get printer
2525   $query = qq|SELECT printer_description, id
2526               FROM printers
2527               ORDER BY printer_description|;
2528
2529   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2530
2531   # get payment terms
2532   $query = qq|SELECT id, description
2533               FROM payment_terms
2534               ORDER BY sortkey|;
2535
2536   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2537
2538   # get buchungsgruppen
2539   $query = qq|SELECT id, description
2540               FROM buchungsgruppen|;
2541
2542   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2543
2544   $main::lxdebug->leave_sub();
2545 }
2546
2547 # this is only used for reports
2548 sub all_departments {
2549   $main::lxdebug->enter_sub();
2550
2551   my ($self, $myconfig, $table) = @_;
2552
2553   my $dbh = $self->get_standard_dbh($myconfig);
2554   my $where;
2555
2556   if ($table eq 'customer') {
2557     $where = "WHERE role = 'P' ";
2558   }
2559
2560   my $query = qq|SELECT id, description
2561                  FROM department
2562                  $where
2563                  ORDER BY description|;
2564   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2565
2566   delete($self->{all_departments}) unless (@{ $self->{all_departments} });
2567
2568   $main::lxdebug->leave_sub();
2569 }
2570
2571 sub create_links {
2572   $main::lxdebug->enter_sub();
2573
2574   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2575
2576   my ($fld, $arap);
2577   if ($table eq "customer") {
2578     $fld = "buy";
2579     $arap = "ar";
2580   } else {
2581     $table = "vendor";
2582     $fld = "sell";
2583     $arap = "ap";
2584   }
2585
2586   $self->all_vc($myconfig, $table, $module);
2587
2588   # get last customers or vendors
2589   my ($query, $sth, $ref);
2590
2591   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2592   my %xkeyref = ();
2593
2594   if (!$self->{id}) {
2595
2596     my $transdate = "current_date";
2597     if ($self->{transdate}) {
2598       $transdate = $dbh->quote($self->{transdate});
2599     }
2600
2601     # now get the account numbers
2602     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2603                 FROM chart c, taxkeys tk
2604                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2605                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2606                 ORDER BY c.accno|;
2607
2608     $sth = $dbh->prepare($query);
2609
2610     do_statement($self, $sth, $query, '%' . $module . '%');
2611
2612     $self->{accounts} = "";
2613     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2614
2615       foreach my $key (split(/:/, $ref->{link})) {
2616         if ($key =~ /\Q$module\E/) {
2617
2618           # cross reference for keys
2619           $xkeyref{ $ref->{accno} } = $key;
2620
2621           push @{ $self->{"${module}_links"}{$key} },
2622             { accno       => $ref->{accno},
2623               description => $ref->{description},
2624               taxkey      => $ref->{taxkey_id},
2625               tax_id      => $ref->{tax_id} };
2626
2627           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2628         }
2629       }
2630     }
2631   }
2632
2633   # get taxkeys and description
2634   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2635   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2636
2637   if (($module eq "AP") || ($module eq "AR")) {
2638     # get tax rates and description
2639     $query = qq|SELECT * FROM tax|;
2640     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2641   }
2642
2643   if ($self->{id}) {
2644     $query =
2645       qq|SELECT
2646            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2647            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2648            a.intnotes, a.department_id, a.amount AS oldinvtotal,
2649            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2650            c.name AS $table,
2651            d.description AS department,
2652            e.name AS employee
2653          FROM $arap a
2654          JOIN $table c ON (a.${table}_id = c.id)
2655          LEFT JOIN employee e ON (e.id = a.employee_id)
2656          LEFT JOIN department d ON (d.id = a.department_id)
2657          WHERE a.id = ?|;
2658     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2659
2660     foreach $key (keys %$ref) {
2661       $self->{$key} = $ref->{$key};
2662     }
2663
2664     my $transdate = "current_date";
2665     if ($self->{transdate}) {
2666       $transdate = $dbh->quote($self->{transdate});
2667     }
2668
2669     # now get the account numbers
2670     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2671                 FROM chart c
2672                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2673                 WHERE c.link LIKE ?
2674                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2675                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2676                 ORDER BY c.accno|;
2677
2678     $sth = $dbh->prepare($query);
2679     do_statement($self, $sth, $query, "%$module%");
2680
2681     $self->{accounts} = "";
2682     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2683
2684       foreach my $key (split(/:/, $ref->{link})) {
2685         if ($key =~ /\Q$module\E/) {
2686
2687           # cross reference for keys
2688           $xkeyref{ $ref->{accno} } = $key;
2689
2690           push @{ $self->{"${module}_links"}{$key} },
2691             { accno       => $ref->{accno},
2692               description => $ref->{description},
2693               taxkey      => $ref->{taxkey_id},
2694               tax_id      => $ref->{tax_id} };
2695
2696           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2697         }
2698       }
2699     }
2700
2701
2702     # get amounts from individual entries
2703     $query =
2704       qq|SELECT
2705            c.accno, c.description,
2706            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2707            p.projectnumber,
2708            t.rate, t.id
2709          FROM acc_trans a
2710          LEFT JOIN chart c ON (c.id = a.chart_id)
2711          LEFT JOIN project p ON (p.id = a.project_id)
2712          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2713                                     WHERE (tk.taxkey_id=a.taxkey) AND
2714                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2715                                         THEN tk.chart_id = a.chart_id
2716                                         ELSE 1 = 1
2717                                         END)
2718                                        OR (c.link='%tax%')) AND
2719                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2720          WHERE a.trans_id = ?
2721          AND a.fx_transaction = '0'
2722          ORDER BY a.oid, a.transdate|;
2723     $sth = $dbh->prepare($query);
2724     do_statement($self, $sth, $query, $self->{id});
2725
2726     # get exchangerate for currency
2727     $self->{exchangerate} =
2728       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2729     my $index = 0;
2730
2731     # store amounts in {acc_trans}{$key} for multiple accounts
2732     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2733       $ref->{exchangerate} =
2734         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2735       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2736         $index++;
2737       }
2738       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2739         $ref->{amount} *= -1;
2740       }
2741       $ref->{index} = $index;
2742
2743       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2744     }
2745
2746     $sth->finish;
2747     $query =
2748       qq|SELECT
2749            d.curr AS currencies, d.closedto, d.revtrans,
2750            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2751            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2752          FROM defaults d|;
2753     $ref = selectfirst_hashref_query($self, $dbh, $query);
2754     map { $self->{$_} = $ref->{$_} } keys %$ref;
2755
2756   } else {
2757
2758     # get date
2759     $query =
2760        qq|SELECT
2761             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2762             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2763             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2764           FROM defaults d|;
2765     $ref = selectfirst_hashref_query($self, $dbh, $query);
2766     map { $self->{$_} = $ref->{$_} } keys %$ref;
2767
2768     if ($self->{"$self->{vc}_id"}) {
2769
2770       # only setup currency
2771       ($self->{currency}) = split(/:/, $self->{currencies});
2772
2773     } else {
2774
2775       $self->lastname_used($dbh, $myconfig, $table, $module);
2776
2777       # get exchangerate for currency
2778       $self->{exchangerate} =
2779         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2780
2781     }
2782
2783   }
2784
2785   $main::lxdebug->leave_sub();
2786 }
2787
2788 sub lastname_used {
2789   $main::lxdebug->enter_sub();
2790
2791   my ($self, $dbh, $myconfig, $table, $module) = @_;
2792
2793   my ($arap, $where);
2794
2795   $table         = $table eq "customer" ? "customer" : "vendor";
2796   my %column_map = ("a.curr"                  => "currency",
2797                     "a.${table}_id"           => "${table}_id",
2798                     "a.department_id"         => "department_id",
2799                     "d.description"           => "department",
2800                     "ct.name"                 => $table,
2801                     "current_date + ct.terms" => "duedate",
2802     );
2803
2804   if ($self->{type} =~ /delivery_order/) {
2805     $arap  = 'delivery_orders';
2806     delete $column_map{"a.curr"};
2807
2808   } elsif ($self->{type} =~ /_order/) {
2809     $arap  = 'oe';
2810     $where = "quotation = '0'";
2811
2812   } elsif ($self->{type} =~ /_quotation/) {
2813     $arap  = 'oe';
2814     $where = "quotation = '1'";
2815
2816   } elsif ($table eq 'customer') {
2817     $arap  = 'ar';
2818
2819   } else {
2820     $arap  = 'ap';
2821
2822   }
2823
2824   $where           = "($where) AND" if ($where);
2825   my $query        = qq|SELECT MAX(id) FROM $arap
2826                         WHERE $where ${table}_id > 0|;
2827   my ($trans_id)   = selectrow_query($self, $dbh, $query);
2828   $trans_id       *= 1;
2829
2830   my $column_spec  = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2831   $query           = qq|SELECT $column_spec
2832                         FROM $arap a
2833                         LEFT JOIN $table     ct ON (a.${table}_id = ct.id)
2834                         LEFT JOIN department d  ON (a.department_id = d.id)
2835                         WHERE a.id = ?|;
2836   my $ref          = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
2837
2838   map { $self->{$_} = $ref->{$_} } values %column_map;
2839
2840   $main::lxdebug->leave_sub();
2841 }
2842
2843 sub current_date {
2844   $main::lxdebug->enter_sub();
2845
2846   my ($self, $myconfig, $thisdate, $days) = @_;
2847
2848   my $dbh = $self->get_standard_dbh($myconfig);
2849   my $query;
2850
2851   $days *= 1;
2852   if ($thisdate) {
2853     my $dateformat = $myconfig->{dateformat};
2854     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2855     $thisdate = $dbh->quote($thisdate);
2856     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2857   } else {
2858     $query = qq|SELECT current_date AS thisdate|;
2859   }
2860
2861   ($thisdate) = selectrow_query($self, $dbh, $query);
2862
2863   $main::lxdebug->leave_sub();
2864
2865   return $thisdate;
2866 }
2867
2868 sub like {
2869   $main::lxdebug->enter_sub();
2870
2871   my ($self, $string) = @_;
2872
2873   if ($string !~ /%/) {
2874     $string = "%$string%";
2875   }
2876
2877   $string =~ s/\'/\'\'/g;
2878
2879   $main::lxdebug->leave_sub();
2880
2881   return $string;
2882 }
2883
2884 sub redo_rows {
2885   $main::lxdebug->enter_sub();
2886
2887   my ($self, $flds, $new, $count, $numrows) = @_;
2888
2889   my @ndx = ();
2890
2891   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
2892
2893   my $i = 0;
2894
2895   # fill rows
2896   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2897     $i++;
2898     $j = $item->{ndx} - 1;
2899     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2900   }
2901
2902   # delete empty rows
2903   for $i ($count + 1 .. $numrows) {
2904     map { delete $self->{"${_}_$i"} } @{$flds};
2905   }
2906
2907   $main::lxdebug->leave_sub();
2908 }
2909
2910 sub update_status {
2911   $main::lxdebug->enter_sub();
2912
2913   my ($self, $myconfig) = @_;
2914
2915   my ($i, $id);
2916
2917   my $dbh = $self->dbconnect_noauto($myconfig);
2918
2919   my $query = qq|DELETE FROM status
2920                  WHERE (formname = ?) AND (trans_id = ?)|;
2921   my $sth = prepare_query($self, $dbh, $query);
2922
2923   if ($self->{formname} =~ /(check|receipt)/) {
2924     for $i (1 .. $self->{rowcount}) {
2925       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
2926     }
2927   } else {
2928     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
2929   }
2930   $sth->finish();
2931
2932   my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2933   my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2934
2935   my %queued = split / /, $self->{queued};
2936   my @values;
2937
2938   if ($self->{formname} =~ /(check|receipt)/) {
2939
2940     # this is a check or receipt, add one entry for each lineitem
2941     my ($accno) = split /--/, $self->{account};
2942     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
2943                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
2944     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
2945     $sth = prepare_query($self, $dbh, $query);
2946
2947     for $i (1 .. $self->{rowcount}) {
2948       if ($self->{"checked_$i"}) {
2949         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
2950       }
2951     }
2952     $sth->finish();
2953
2954   } else {
2955     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2956                 VALUES (?, ?, ?, ?, ?)|;
2957     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
2958              $queued{$self->{formname}}, $self->{formname});
2959   }
2960
2961   $dbh->commit;
2962   $dbh->disconnect;
2963
2964   $main::lxdebug->leave_sub();
2965 }
2966
2967 sub save_status {
2968   $main::lxdebug->enter_sub();
2969
2970   my ($self, $dbh) = @_;
2971
2972   my ($query, $printed, $emailed);
2973
2974   my $formnames  = $self->{printed};
2975   my $emailforms = $self->{emailed};
2976
2977   $query = qq|DELETE FROM status
2978                  WHERE (formname = ?) AND (trans_id = ?)|;
2979   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
2980
2981   # this only applies to the forms
2982   # checks and receipts are posted when printed or queued
2983
2984   if ($self->{queued}) {
2985     my %queued = split / /, $self->{queued};
2986
2987     foreach my $formname (keys %queued) {
2988       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2989       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2990
2991       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2992                   VALUES (?, ?, ?, ?, ?)|;
2993       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
2994
2995       $formnames  =~ s/\Q$self->{formname}\E//;
2996       $emailforms =~ s/\Q$self->{formname}\E//;
2997
2998     }
2999   }
3000
3001   # save printed, emailed info
3002   $formnames  =~ s/^ +//g;
3003   $emailforms =~ s/^ +//g;
3004
3005   my %status = ();
3006   map { $status{$_}{printed} = 1 } split / +/, $formnames;
3007   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3008
3009   foreach my $formname (keys %status) {
3010     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
3011     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3012
3013     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3014                 VALUES (?, ?, ?, ?)|;
3015     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3016   }
3017
3018   $main::lxdebug->leave_sub();
3019 }
3020
3021 #--- 4 locale ---#
3022 # $main::locale->text('SAVED')
3023 # $main::locale->text('DELETED')
3024 # $main::locale->text('ADDED')
3025 # $main::locale->text('PAYMENT POSTED')
3026 # $main::locale->text('POSTED')
3027 # $main::locale->text('POSTED AS NEW')
3028 # $main::locale->text('ELSE')
3029 # $main::locale->text('SAVED FOR DUNNING')
3030 # $main::locale->text('DUNNING STARTED')
3031 # $main::locale->text('PRINTED')
3032 # $main::locale->text('MAILED')
3033 # $main::locale->text('SCREENED')
3034 # $main::locale->text('CANCELED')
3035 # $main::locale->text('invoice')
3036 # $main::locale->text('proforma')
3037 # $main::locale->text('sales_order')
3038 # $main::locale->text('packing_list')
3039 # $main::locale->text('pick_list')
3040 # $main::locale->text('purchase_order')
3041 # $main::locale->text('bin_list')
3042 # $main::locale->text('sales_quotation')
3043 # $main::locale->text('request_quotation')
3044
3045 sub save_history {
3046   $main::lxdebug->enter_sub();
3047
3048   my $self = shift();
3049   my $dbh = shift();
3050
3051   if(!exists $self->{employee_id}) {
3052     &get_employee($self, $dbh);
3053   }
3054
3055   my $query =
3056    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3057    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3058   my @values = (conv_i($self->{id}), $self->{login},
3059                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3060   do_query($self, $dbh, $query, @values);
3061
3062   $main::lxdebug->leave_sub();
3063 }
3064
3065 sub get_history {
3066   $main::lxdebug->enter_sub();
3067
3068   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3069   my ($orderBy, $desc) = split(/\-\-/, $order);
3070   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3071   my @tempArray;
3072   my $i = 0;
3073   if ($trans_id ne "") {
3074     my $query =
3075       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 | .
3076       qq|FROM history_erp h | .
3077       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3078       qq|WHERE trans_id = | . $trans_id
3079       . $restriction . qq| |
3080       . $order;
3081       
3082     my $sth = $dbh->prepare($query) || $self->dberror($query);
3083
3084     $sth->execute() || $self->dberror("$query");
3085
3086     while(my $hash_ref = $sth->fetchrow_hashref()) {
3087       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3088       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3089       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3090       $tempArray[$i++] = $hash_ref;
3091     }
3092     $main::lxdebug->leave_sub() and return \@tempArray 
3093       if ($i > 0 && $tempArray[0] ne "");
3094   }
3095   $main::lxdebug->leave_sub();
3096   return 0;
3097 }
3098
3099 sub update_defaults {
3100   $main::lxdebug->enter_sub();
3101
3102   my ($self, $myconfig, $fld, $provided_dbh) = @_;
3103
3104   my $dbh;
3105   if ($provided_dbh) {
3106     $dbh = $provided_dbh;
3107   } else {
3108     $dbh = $self->dbconnect_noauto($myconfig);
3109   }
3110   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3111   my $sth   = $dbh->prepare($query);
3112
3113   $sth->execute || $self->dberror($query);
3114   my ($var) = $sth->fetchrow_array;
3115   $sth->finish;
3116
3117   if ($var =~ m/\d+$/) {
3118     my $new_var  = (substr $var, $-[0]) * 1 + 1;
3119     my $len_diff = length($var) - $-[0] - length($new_var);
3120     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3121
3122   } else {
3123     $var = $var . '1';
3124   }
3125
3126   $query = qq|UPDATE defaults SET $fld = ?|;
3127   do_query($self, $dbh, $query, $var);
3128
3129   if (!$provided_dbh) {
3130     $dbh->commit;
3131     $dbh->disconnect;
3132   }
3133
3134   $main::lxdebug->leave_sub();
3135
3136   return $var;
3137 }
3138
3139 sub update_business {
3140   $main::lxdebug->enter_sub();
3141
3142   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3143
3144   my $dbh;
3145   if ($provided_dbh) {
3146     $dbh = $provided_dbh;
3147   } else {
3148     $dbh = $self->dbconnect_noauto($myconfig);
3149   }
3150   my $query =
3151     qq|SELECT customernumberinit FROM business
3152        WHERE id = ? FOR UPDATE|;
3153   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3154
3155   if ($var =~ m/\d+$/) {
3156     my $new_var  = (substr $var, $-[0]) * 1 + 1;
3157     my $len_diff = length($var) - $-[0] - length($new_var);
3158     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3159
3160   } else {
3161     $var = $var . '1';
3162   }
3163
3164   $query = qq|UPDATE business
3165               SET customernumberinit = ?
3166               WHERE id = ?|;
3167   do_query($self, $dbh, $query, $var, $business_id);
3168
3169   if (!$provided_dbh) {
3170     $dbh->commit;
3171     $dbh->disconnect;
3172   }
3173
3174   $main::lxdebug->leave_sub();
3175
3176   return $var;
3177 }
3178
3179 sub get_partsgroup {
3180   $main::lxdebug->enter_sub();
3181
3182   my ($self, $myconfig, $p) = @_;
3183   my $target = $p->{target} || 'all_partsgroup';
3184
3185   my $dbh = $self->get_standard_dbh($myconfig);
3186
3187   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3188                  FROM partsgroup pg
3189                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
3190   my @values;
3191
3192   if ($p->{searchitems} eq 'part') {
3193     $query .= qq|WHERE p.inventory_accno_id > 0|;
3194   }
3195   if ($p->{searchitems} eq 'service') {
3196     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3197   }
3198   if ($p->{searchitems} eq 'assembly') {
3199     $query .= qq|WHERE p.assembly = '1'|;
3200   }
3201   if ($p->{searchitems} eq 'labor') {
3202     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3203   }
3204
3205   $query .= qq|ORDER BY partsgroup|;
3206
3207   if ($p->{all}) {
3208     $query = qq|SELECT id, partsgroup FROM partsgroup
3209                 ORDER BY partsgroup|;
3210   }
3211
3212   if ($p->{language_code}) {
3213     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3214                   t.description AS translation
3215                 FROM partsgroup pg
3216                 JOIN parts p ON (p.partsgroup_id = pg.id)
3217                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3218                 ORDER BY translation|;
3219     @values = ($p->{language_code});
3220   }
3221
3222   $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3223
3224   $main::lxdebug->leave_sub();
3225 }
3226
3227 sub get_pricegroup {
3228   $main::lxdebug->enter_sub();
3229
3230   my ($self, $myconfig, $p) = @_;
3231
3232   my $dbh = $self->get_standard_dbh($myconfig);
3233
3234   my $query = qq|SELECT p.id, p.pricegroup
3235                  FROM pricegroup p|;
3236
3237   $query .= qq| ORDER BY pricegroup|;
3238
3239   if ($p->{all}) {
3240     $query = qq|SELECT id, pricegroup FROM pricegroup
3241                 ORDER BY pricegroup|;
3242   }
3243
3244   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3245
3246   $main::lxdebug->leave_sub();
3247 }
3248
3249 sub all_years {
3250 # usage $form->all_years($myconfig, [$dbh])
3251 # return list of all years where bookings found
3252 # (@all_years)
3253
3254   $main::lxdebug->enter_sub();
3255
3256   my ($self, $myconfig, $dbh) = @_;
3257
3258   $dbh ||= $self->get_standard_dbh($myconfig);
3259
3260   # get years
3261   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3262                    (SELECT MAX(transdate) FROM acc_trans)|;
3263   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3264
3265   if ($myconfig->{dateformat} =~ /^yy/) {
3266     ($startdate) = split /\W/, $startdate;
3267     ($enddate) = split /\W/, $enddate;
3268   } else {
3269     (@_) = split /\W/, $startdate;
3270     $startdate = $_[2];
3271     (@_) = split /\W/, $enddate;
3272     $enddate = $_[2];
3273   }
3274
3275   my @all_years;
3276   $startdate = substr($startdate,0,4);
3277   $enddate = substr($enddate,0,4);
3278
3279   while ($enddate >= $startdate) {
3280     push @all_years, $enddate--;
3281   }
3282
3283   return @all_years;
3284
3285   $main::lxdebug->leave_sub();
3286 }
3287
3288 sub backup_vars {
3289   $main::lxdebug->enter_sub();
3290   my $self = shift;
3291   my @vars = @_;
3292
3293   map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if $self->{$_} } @vars;
3294
3295   $main::lxdebug->leave_sub();
3296 }
3297
3298 sub restore_vars {
3299   $main::lxdebug->enter_sub();
3300
3301   my $self = shift;
3302   my @vars = @_;
3303
3304   map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if $self->{_VAR_BACKUP}->{$_} } @vars;
3305
3306   $main::lxdebug->leave_sub();
3307 }
3308
3309 1;