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