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