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