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