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