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