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