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