date_tag
[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 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                        shiptophone = ?,
2040                        shiptofax = ?,
2041                        shiptoemail = ?
2042                      WHERE shipto_id = ?|;
2043       do_query($self, $dbh, $query, @values, $self->{shipto_id});
2044     } else {
2045       my $query = qq|SELECT * FROM shipto
2046                      WHERE shiptoname = ? AND
2047                        shiptodepartment_1 = ? AND
2048                        shiptodepartment_2 = ? AND
2049                        shiptostreet = ? AND
2050                        shiptozipcode = ? AND
2051                        shiptocity = ? AND
2052                        shiptocountry = ? AND
2053                        shiptocontact = ? AND
2054                        shiptophone = ? AND
2055                        shiptofax = ? AND
2056                        shiptoemail = ? AND
2057                        module = ? AND
2058                        trans_id = ?|;
2059       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
2060       if(!$insert_check){
2061         $query =
2062           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
2063                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
2064                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
2065              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
2066         do_query($self, $dbh, $query, $id, @values, $module);
2067       }
2068     }
2069   }
2070
2071   $main::lxdebug->leave_sub();
2072 }
2073
2074 sub get_employee {
2075   $main::lxdebug->enter_sub();
2076
2077   my ($self, $dbh) = @_;
2078
2079   $dbh ||= $self->get_standard_dbh(\%main::myconfig);
2080
2081   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
2082   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
2083   $self->{"employee_id"} *= 1;
2084
2085   $main::lxdebug->leave_sub();
2086 }
2087
2088 sub get_employee_data {
2089   $main::lxdebug->enter_sub();
2090
2091   my $self     = shift;
2092   my %params   = @_;
2093
2094   Common::check_params(\%params, qw(prefix));
2095   Common::check_params_x(\%params, qw(id));
2096
2097   if (!$params{id}) {
2098     $main::lxdebug->leave_sub();
2099     return;
2100   }
2101
2102   my $myconfig = \%main::myconfig;
2103   my $dbh      = $params{dbh} || $self->get_standard_dbh($myconfig);
2104
2105   my ($login)  = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
2106
2107   if ($login) {
2108     my $user = User->new($login);
2109     map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
2110
2111     $self->{$params{prefix} . '_login'}   = $login;
2112     $self->{$params{prefix} . '_name'}  ||= $login;
2113   }
2114
2115   $main::lxdebug->leave_sub();
2116 }
2117
2118 sub get_duedate {
2119   $main::lxdebug->enter_sub();
2120
2121   my ($self, $myconfig, $reference_date) = @_;
2122
2123   $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
2124
2125   my $dbh         = $self->get_standard_dbh($myconfig);
2126   my $query       = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
2127   my ($duedate)   = selectrow_query($self, $dbh, $query, $self->{payment_id});
2128
2129   $main::lxdebug->leave_sub();
2130
2131   return $duedate;
2132 }
2133
2134 sub _get_contacts {
2135   $main::lxdebug->enter_sub();
2136
2137   my ($self, $dbh, $id, $key) = @_;
2138
2139   $key = "all_contacts" unless ($key);
2140
2141   if (!$id) {
2142     $self->{$key} = [];
2143     $main::lxdebug->leave_sub();
2144     return;
2145   }
2146
2147   my $query =
2148     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
2149     qq|FROM contacts | .
2150     qq|WHERE cp_cv_id = ? | .
2151     qq|ORDER BY lower(cp_name)|;
2152
2153   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
2154
2155   $main::lxdebug->leave_sub();
2156 }
2157
2158 sub _get_projects {
2159   $main::lxdebug->enter_sub();
2160
2161   my ($self, $dbh, $key) = @_;
2162
2163   my ($all, $old_id, $where, @values);
2164
2165   if (ref($key) eq "HASH") {
2166     my $params = $key;
2167
2168     $key = "ALL_PROJECTS";
2169
2170     foreach my $p (keys(%{$params})) {
2171       if ($p eq "all") {
2172         $all = $params->{$p};
2173       } elsif ($p eq "old_id") {
2174         $old_id = $params->{$p};
2175       } elsif ($p eq "key") {
2176         $key = $params->{$p};
2177       }
2178     }
2179   }
2180
2181   if (!$all) {
2182     $where = "WHERE active ";
2183     if ($old_id) {
2184       if (ref($old_id) eq "ARRAY") {
2185         my @ids = grep({ $_ } @{$old_id});
2186         if (@ids) {
2187           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
2188           push(@values, @ids);
2189         }
2190       } else {
2191         $where .= " OR (id = ?) ";
2192         push(@values, $old_id);
2193       }
2194     }
2195   }
2196
2197   my $query =
2198     qq|SELECT id, projectnumber, description, active | .
2199     qq|FROM project | .
2200     $where .
2201     qq|ORDER BY lower(projectnumber)|;
2202
2203   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2204
2205   $main::lxdebug->leave_sub();
2206 }
2207
2208 sub _get_shipto {
2209   $main::lxdebug->enter_sub();
2210
2211   my ($self, $dbh, $vc_id, $key) = @_;
2212
2213   $key = "all_shipto" unless ($key);
2214
2215   if ($vc_id) {
2216     # get shipping addresses
2217     my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2218
2219     $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2220
2221   } else {
2222     $self->{$key} = [];
2223   }
2224
2225   $main::lxdebug->leave_sub();
2226 }
2227
2228 sub _get_printers {
2229   $main::lxdebug->enter_sub();
2230
2231   my ($self, $dbh, $key) = @_;
2232
2233   $key = "all_printers" unless ($key);
2234
2235   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2236
2237   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2238
2239   $main::lxdebug->leave_sub();
2240 }
2241
2242 sub _get_charts {
2243   $main::lxdebug->enter_sub();
2244
2245   my ($self, $dbh, $params) = @_;
2246   my ($key);
2247
2248   $key = $params->{key};
2249   $key = "all_charts" unless ($key);
2250
2251   my $transdate = quote_db_date($params->{transdate});
2252
2253   my $query =
2254     qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
2255     qq|FROM chart c | .
2256     qq|LEFT JOIN taxkeys tk ON | .
2257     qq|(tk.id = (SELECT id FROM taxkeys | .
2258     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2259     qq|          ORDER BY startdate DESC LIMIT 1)) | .
2260     qq|ORDER BY c.accno|;
2261
2262   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2263
2264   $main::lxdebug->leave_sub();
2265 }
2266
2267 sub _get_taxcharts {
2268   $main::lxdebug->enter_sub();
2269
2270   my ($self, $dbh, $params) = @_;
2271
2272   my $key = "all_taxcharts";
2273   my @where;
2274
2275   if (ref $params eq 'HASH') {
2276     $key = $params->{key} if ($params->{key});
2277     if ($params->{module} eq 'AR') {
2278       push @where, 'taxkey NOT IN (8, 9, 18, 19)';
2279
2280     } elsif ($params->{module} eq 'AP') {
2281       push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
2282     }
2283
2284   } elsif ($params) {
2285     $key = $params;
2286   }
2287
2288   my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
2289
2290   my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
2291
2292   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2293
2294   $main::lxdebug->leave_sub();
2295 }
2296
2297 sub _get_taxzones {
2298   $main::lxdebug->enter_sub();
2299
2300   my ($self, $dbh, $key) = @_;
2301
2302   $key = "all_taxzones" unless ($key);
2303
2304   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
2305
2306   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2307
2308   $main::lxdebug->leave_sub();
2309 }
2310
2311 sub _get_employees {
2312   $main::lxdebug->enter_sub();
2313
2314   my ($self, $dbh, $default_key, $key) = @_;
2315
2316   $key = $default_key unless ($key);
2317   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
2318
2319   $main::lxdebug->leave_sub();
2320 }
2321
2322 sub _get_business_types {
2323   $main::lxdebug->enter_sub();
2324
2325   my ($self, $dbh, $key) = @_;
2326
2327   my $options       = ref $key eq 'HASH' ? $key : { key => $key };
2328   $options->{key} ||= "all_business_types";
2329   my $where         = '';
2330
2331   if (exists $options->{salesman}) {
2332     $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
2333   }
2334
2335   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
2336
2337   $main::lxdebug->leave_sub();
2338 }
2339
2340 sub _get_languages {
2341   $main::lxdebug->enter_sub();
2342
2343   my ($self, $dbh, $key) = @_;
2344
2345   $key = "all_languages" unless ($key);
2346
2347   my $query = qq|SELECT * FROM language ORDER BY id|;
2348
2349   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2350
2351   $main::lxdebug->leave_sub();
2352 }
2353
2354 sub _get_dunning_configs {
2355   $main::lxdebug->enter_sub();
2356
2357   my ($self, $dbh, $key) = @_;
2358
2359   $key = "all_dunning_configs" unless ($key);
2360
2361   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2362
2363   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2364
2365   $main::lxdebug->leave_sub();
2366 }
2367
2368 sub _get_currencies {
2369 $main::lxdebug->enter_sub();
2370
2371   my ($self, $dbh, $key) = @_;
2372
2373   $key = "all_currencies" unless ($key);
2374
2375   my $query = qq|SELECT curr AS currency FROM defaults|;
2376
2377   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2378
2379   $main::lxdebug->leave_sub();
2380 }
2381
2382 sub _get_payments {
2383 $main::lxdebug->enter_sub();
2384
2385   my ($self, $dbh, $key) = @_;
2386
2387   $key = "all_payments" unless ($key);
2388
2389   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
2390
2391   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2392
2393   $main::lxdebug->leave_sub();
2394 }
2395
2396 sub _get_customers {
2397   $main::lxdebug->enter_sub();
2398
2399   my ($self, $dbh, $key) = @_;
2400
2401   my $options        = ref $key eq 'HASH' ? $key : { key => $key };
2402   $options->{key}  ||= "all_customers";
2403   my $limit_clause   = "LIMIT $options->{limit}" if $options->{limit};
2404
2405   my @where;
2406   push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if  $options->{business_is_salesman};
2407   push @where, qq|NOT obsolete|                                            if !$options->{with_obsolete};
2408   my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : '';
2409
2410   my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|;
2411   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
2412
2413   $main::lxdebug->leave_sub();
2414 }
2415
2416 sub _get_vendors {
2417   $main::lxdebug->enter_sub();
2418
2419   my ($self, $dbh, $key) = @_;
2420
2421   $key = "all_vendors" unless ($key);
2422
2423   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2424
2425   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2426
2427   $main::lxdebug->leave_sub();
2428 }
2429
2430 sub _get_departments {
2431   $main::lxdebug->enter_sub();
2432
2433   my ($self, $dbh, $key) = @_;
2434
2435   $key = "all_departments" unless ($key);
2436
2437   my $query = qq|SELECT * FROM department ORDER BY description|;
2438
2439   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2440
2441   $main::lxdebug->leave_sub();
2442 }
2443
2444 sub _get_warehouses {
2445   $main::lxdebug->enter_sub();
2446
2447   my ($self, $dbh, $param) = @_;
2448
2449   my ($key, $bins_key);
2450
2451   if ('' eq ref $param) {
2452     $key = $param;
2453
2454   } else {
2455     $key      = $param->{key};
2456     $bins_key = $param->{bins};
2457   }
2458
2459   my $query = qq|SELECT w.* FROM warehouse w
2460                  WHERE (NOT w.invalid) AND
2461                    ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2462                  ORDER BY w.sortkey|;
2463
2464   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2465
2466   if ($bins_key) {
2467     $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
2468     my $sth = prepare_query($self, $dbh, $query);
2469
2470     foreach my $warehouse (@{ $self->{$key} }) {
2471       do_statement($self, $sth, $query, $warehouse->{id});
2472       $warehouse->{$bins_key} = [];
2473
2474       while (my $ref = $sth->fetchrow_hashref()) {
2475         push @{ $warehouse->{$bins_key} }, $ref;
2476       }
2477     }
2478     $sth->finish();
2479   }
2480
2481   $main::lxdebug->leave_sub();
2482 }
2483
2484 sub _get_simple {
2485   $main::lxdebug->enter_sub();
2486
2487   my ($self, $dbh, $table, $key, $sortkey) = @_;
2488
2489   my $query  = qq|SELECT * FROM $table|;
2490   $query    .= qq| ORDER BY $sortkey| if ($sortkey);
2491
2492   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2493
2494   $main::lxdebug->leave_sub();
2495 }
2496
2497 #sub _get_groups {
2498 #  $main::lxdebug->enter_sub();
2499 #
2500 #  my ($self, $dbh, $key) = @_;
2501 #
2502 #  $key ||= "all_groups";
2503 #
2504 #  my $groups = $main::auth->read_groups();
2505 #
2506 #  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2507 #
2508 #  $main::lxdebug->leave_sub();
2509 #}
2510
2511 sub get_lists {
2512   $main::lxdebug->enter_sub();
2513
2514   my $self = shift;
2515   my %params = @_;
2516
2517   my $dbh = $self->get_standard_dbh(\%main::myconfig);
2518   my ($sth, $query, $ref);
2519
2520   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2521   my $vc_id = $self->{"${vc}_id"};
2522
2523   if ($params{"contacts"}) {
2524     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2525   }
2526
2527   if ($params{"shipto"}) {
2528     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2529   }
2530
2531   if ($params{"projects"} || $params{"all_projects"}) {
2532     $self->_get_projects($dbh, $params{"all_projects"} ?
2533                          $params{"all_projects"} : $params{"projects"},
2534                          $params{"all_projects"} ? 1 : 0);
2535   }
2536
2537   if ($params{"printers"}) {
2538     $self->_get_printers($dbh, $params{"printers"});
2539   }
2540
2541   if ($params{"languages"}) {
2542     $self->_get_languages($dbh, $params{"languages"});
2543   }
2544
2545   if ($params{"charts"}) {
2546     $self->_get_charts($dbh, $params{"charts"});
2547   }
2548
2549   if ($params{"taxcharts"}) {
2550     $self->_get_taxcharts($dbh, $params{"taxcharts"});
2551   }
2552
2553   if ($params{"taxzones"}) {
2554     $self->_get_taxzones($dbh, $params{"taxzones"});
2555   }
2556
2557   if ($params{"employees"}) {
2558     $self->_get_employees($dbh, "all_employees", $params{"employees"});
2559   }
2560
2561   if ($params{"salesmen"}) {
2562     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2563   }
2564
2565   if ($params{"business_types"}) {
2566     $self->_get_business_types($dbh, $params{"business_types"});
2567   }
2568
2569   if ($params{"dunning_configs"}) {
2570     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2571   }
2572
2573   if($params{"currencies"}) {
2574     $self->_get_currencies($dbh, $params{"currencies"});
2575   }
2576
2577   if($params{"customers"}) {
2578     $self->_get_customers($dbh, $params{"customers"});
2579   }
2580
2581   if($params{"vendors"}) {
2582     if (ref $params{"vendors"} eq 'HASH') {
2583       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2584     } else {
2585       $self->_get_vendors($dbh, $params{"vendors"});
2586     }
2587   }
2588
2589   if($params{"payments"}) {
2590     $self->_get_payments($dbh, $params{"payments"});
2591   }
2592
2593   if($params{"departments"}) {
2594     $self->_get_departments($dbh, $params{"departments"});
2595   }
2596
2597   if ($params{price_factors}) {
2598     $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2599   }
2600
2601   if ($params{warehouses}) {
2602     $self->_get_warehouses($dbh, $params{warehouses});
2603   }
2604
2605 #  if ($params{groups}) {
2606 #    $self->_get_groups($dbh, $params{groups});
2607 #  }
2608
2609   if ($params{partsgroup}) {
2610     $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2611   }
2612
2613   $main::lxdebug->leave_sub();
2614 }
2615
2616 # this sub gets the id and name from $table
2617 sub get_name {
2618   $main::lxdebug->enter_sub();
2619
2620   my ($self, $myconfig, $table) = @_;
2621
2622   # connect to database
2623   my $dbh = $self->get_standard_dbh($myconfig);
2624
2625   $table = $table eq "customer" ? "customer" : "vendor";
2626   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2627
2628   my ($query, @values);
2629
2630   if (!$self->{openinvoices}) {
2631     my $where;
2632     if ($self->{customernumber} ne "") {
2633       $where = qq|(vc.customernumber ILIKE ?)|;
2634       push(@values, '%' . $self->{customernumber} . '%');
2635     } else {
2636       $where = qq|(vc.name ILIKE ?)|;
2637       push(@values, '%' . $self->{$table} . '%');
2638     }
2639
2640     $query =
2641       qq~SELECT vc.id, vc.name,
2642            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2643          FROM $table vc
2644          WHERE $where AND (NOT vc.obsolete)
2645          ORDER BY vc.name~;
2646   } else {
2647     $query =
2648       qq~SELECT DISTINCT vc.id, vc.name,
2649            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2650          FROM $arap a
2651          JOIN $table vc ON (a.${table}_id = vc.id)
2652          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2653          ORDER BY vc.name~;
2654     push(@values, '%' . $self->{$table} . '%');
2655   }
2656
2657   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2658
2659   $main::lxdebug->leave_sub();
2660
2661   return scalar(@{ $self->{name_list} });
2662 }
2663
2664 # the selection sub is used in the AR, AP, IS, IR and OE module
2665 #
2666 sub all_vc {
2667   $main::lxdebug->enter_sub();
2668
2669   my ($self, $myconfig, $table, $module) = @_;
2670
2671   my $ref;
2672   my $dbh = $self->get_standard_dbh;
2673
2674   $table = $table eq "customer" ? "customer" : "vendor";
2675
2676   my $query = qq|SELECT count(*) FROM $table|;
2677   my ($count) = selectrow_query($self, $dbh, $query);
2678
2679   # build selection list
2680   if ($count <= $myconfig->{vclimit}) {
2681     $query = qq|SELECT id, name, salesman_id
2682                 FROM $table WHERE NOT obsolete
2683                 ORDER BY name|;
2684     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2685   }
2686
2687   # get self
2688   $self->get_employee($dbh);
2689
2690   # setup sales contacts
2691   $query = qq|SELECT e.id, e.name
2692               FROM employee e
2693               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2694   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2695
2696   # this is for self
2697   push(@{ $self->{all_employees} },
2698        { id   => $self->{employee_id},
2699          name => $self->{employee} });
2700
2701   # sort the whole thing
2702   @{ $self->{all_employees} } =
2703     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2704
2705   if ($module eq 'AR') {
2706
2707     # prepare query for departments
2708     $query = qq|SELECT id, description
2709                 FROM department
2710                 WHERE role = 'P'
2711                 ORDER BY description|;
2712
2713   } else {
2714     $query = qq|SELECT id, description
2715                 FROM department
2716                 ORDER BY description|;
2717   }
2718
2719   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2720
2721   # get languages
2722   $query = qq|SELECT id, description
2723               FROM language
2724               ORDER BY id|;
2725
2726   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2727
2728   # get printer
2729   $query = qq|SELECT printer_description, id
2730               FROM printers
2731               ORDER BY printer_description|;
2732
2733   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2734
2735   # get payment terms
2736   $query = qq|SELECT id, description
2737               FROM payment_terms
2738               ORDER BY sortkey|;
2739
2740   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2741
2742   $main::lxdebug->leave_sub();
2743 }
2744
2745 sub language_payment {
2746   $main::lxdebug->enter_sub();
2747
2748   my ($self, $myconfig) = @_;
2749
2750   my $dbh = $self->get_standard_dbh($myconfig);
2751   # get languages
2752   my $query = qq|SELECT id, description
2753                  FROM language
2754                  ORDER BY id|;
2755
2756   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2757
2758   # get printer
2759   $query = qq|SELECT printer_description, id
2760               FROM printers
2761               ORDER BY printer_description|;
2762
2763   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2764
2765   # get payment terms
2766   $query = qq|SELECT id, description
2767               FROM payment_terms
2768               ORDER BY sortkey|;
2769
2770   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2771
2772   # get buchungsgruppen
2773   $query = qq|SELECT id, description
2774               FROM buchungsgruppen|;
2775
2776   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2777
2778   $main::lxdebug->leave_sub();
2779 }
2780
2781 # this is only used for reports
2782 sub all_departments {
2783   $main::lxdebug->enter_sub();
2784
2785   my ($self, $myconfig, $table) = @_;
2786
2787   my $dbh = $self->get_standard_dbh($myconfig);
2788   my $where;
2789
2790   if ($table eq 'customer') {
2791     $where = "WHERE role = 'P' ";
2792   }
2793
2794   my $query = qq|SELECT id, description
2795                  FROM department
2796                  $where
2797                  ORDER BY description|;
2798   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2799
2800   delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2801
2802   $main::lxdebug->leave_sub();
2803 }
2804
2805 sub create_links {
2806   $main::lxdebug->enter_sub();
2807
2808   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2809
2810   my ($fld, $arap);
2811   if ($table eq "customer") {
2812     $fld = "buy";
2813     $arap = "ar";
2814   } else {
2815     $table = "vendor";
2816     $fld = "sell";
2817     $arap = "ap";
2818   }
2819
2820   $self->all_vc($myconfig, $table, $module);
2821
2822   # get last customers or vendors
2823   my ($query, $sth, $ref);
2824
2825   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2826   my %xkeyref = ();
2827
2828   if (!$self->{id}) {
2829
2830     my $transdate = "current_date";
2831     if ($self->{transdate}) {
2832       $transdate = $dbh->quote($self->{transdate});
2833     }
2834
2835     # now get the account numbers
2836     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2837                 FROM chart c, taxkeys tk
2838                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2839                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2840                 ORDER BY c.accno|;
2841
2842     $sth = $dbh->prepare($query);
2843
2844     do_statement($self, $sth, $query, '%' . $module . '%');
2845
2846     $self->{accounts} = "";
2847     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2848
2849       foreach my $key (split(/:/, $ref->{link})) {
2850         if ($key =~ /\Q$module\E/) {
2851
2852           # cross reference for keys
2853           $xkeyref{ $ref->{accno} } = $key;
2854
2855           push @{ $self->{"${module}_links"}{$key} },
2856             { accno       => $ref->{accno},
2857               description => $ref->{description},
2858               taxkey      => $ref->{taxkey_id},
2859               tax_id      => $ref->{tax_id} };
2860
2861           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2862         }
2863       }
2864     }
2865   }
2866
2867   # get taxkeys and description
2868   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2869   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2870
2871   if (($module eq "AP") || ($module eq "AR")) {
2872     # get tax rates and description
2873     $query = qq|SELECT * FROM tax|;
2874     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2875   }
2876
2877   if ($self->{id}) {
2878     $query =
2879       qq|SELECT
2880            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2881            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2882            a.intnotes, a.department_id, a.amount AS oldinvtotal,
2883            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2884            c.name AS $table,
2885            d.description AS department,
2886            e.name AS employee
2887          FROM $arap a
2888          JOIN $table c ON (a.${table}_id = c.id)
2889          LEFT JOIN employee e ON (e.id = a.employee_id)
2890          LEFT JOIN department d ON (d.id = a.department_id)
2891          WHERE a.id = ?|;
2892     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2893
2894     foreach my $key (keys %$ref) {
2895       $self->{$key} = $ref->{$key};
2896     }
2897
2898     my $transdate = "current_date";
2899     if ($self->{transdate}) {
2900       $transdate = $dbh->quote($self->{transdate});
2901     }
2902
2903     # now get the account numbers
2904     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2905                 FROM chart c
2906                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2907                 WHERE c.link LIKE ?
2908                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2909                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2910                 ORDER BY c.accno|;
2911
2912     $sth = $dbh->prepare($query);
2913     do_statement($self, $sth, $query, "%$module%");
2914
2915     $self->{accounts} = "";
2916     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2917
2918       foreach my $key (split(/:/, $ref->{link})) {
2919         if ($key =~ /\Q$module\E/) {
2920
2921           # cross reference for keys
2922           $xkeyref{ $ref->{accno} } = $key;
2923
2924           push @{ $self->{"${module}_links"}{$key} },
2925             { accno       => $ref->{accno},
2926               description => $ref->{description},
2927               taxkey      => $ref->{taxkey_id},
2928               tax_id      => $ref->{tax_id} };
2929
2930           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2931         }
2932       }
2933     }
2934
2935
2936     # get amounts from individual entries
2937     $query =
2938       qq|SELECT
2939            c.accno, c.description,
2940            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2941            p.projectnumber,
2942            t.rate, t.id
2943          FROM acc_trans a
2944          LEFT JOIN chart c ON (c.id = a.chart_id)
2945          LEFT JOIN project p ON (p.id = a.project_id)
2946          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2947                                     WHERE (tk.taxkey_id=a.taxkey) AND
2948                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2949                                         THEN tk.chart_id = a.chart_id
2950                                         ELSE 1 = 1
2951                                         END)
2952                                        OR (c.link='%tax%')) AND
2953                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2954          WHERE a.trans_id = ?
2955          AND a.fx_transaction = '0'
2956          ORDER BY a.acc_trans_id, a.transdate|;
2957     $sth = $dbh->prepare($query);
2958     do_statement($self, $sth, $query, $self->{id});
2959
2960     # get exchangerate for currency
2961     $self->{exchangerate} =
2962       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2963     my $index = 0;
2964
2965     # store amounts in {acc_trans}{$key} for multiple accounts
2966     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2967       $ref->{exchangerate} =
2968         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2969       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2970         $index++;
2971       }
2972       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2973         $ref->{amount} *= -1;
2974       }
2975       $ref->{index} = $index;
2976
2977       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2978     }
2979
2980     $sth->finish;
2981     $query =
2982       qq|SELECT
2983            d.curr AS currencies, d.closedto, d.revtrans,
2984            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2985            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2986          FROM defaults d|;
2987     $ref = selectfirst_hashref_query($self, $dbh, $query);
2988     map { $self->{$_} = $ref->{$_} } keys %$ref;
2989
2990   } else {
2991
2992     # get date
2993     $query =
2994        qq|SELECT
2995             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2996             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2997             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2998           FROM defaults d|;
2999     $ref = selectfirst_hashref_query($self, $dbh, $query);
3000     map { $self->{$_} = $ref->{$_} } keys %$ref;
3001
3002     if ($self->{"$self->{vc}_id"}) {
3003
3004       # only setup currency
3005       ($self->{currency}) = split(/:/, $self->{currencies});
3006
3007     } else {
3008
3009       $self->lastname_used($dbh, $myconfig, $table, $module);
3010
3011       # get exchangerate for currency
3012       $self->{exchangerate} =
3013         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
3014
3015     }
3016
3017   }
3018
3019   $main::lxdebug->leave_sub();
3020 }
3021
3022 sub lastname_used {
3023   $main::lxdebug->enter_sub();
3024
3025   my ($self, $dbh, $myconfig, $table, $module) = @_;
3026
3027   my ($arap, $where);
3028
3029   $table         = $table eq "customer" ? "customer" : "vendor";
3030   my %column_map = ("a.curr"                  => "currency",
3031                     "a.${table}_id"           => "${table}_id",
3032                     "a.department_id"         => "department_id",
3033                     "d.description"           => "department",
3034                     "ct.name"                 => $table,
3035                     "current_date + ct.terms" => "duedate",
3036     );
3037
3038   if ($self->{type} =~ /delivery_order/) {
3039     $arap  = 'delivery_orders';
3040     delete $column_map{"a.curr"};
3041
3042   } elsif ($self->{type} =~ /_order/) {
3043     $arap  = 'oe';
3044     $where = "quotation = '0'";
3045
3046   } elsif ($self->{type} =~ /_quotation/) {
3047     $arap  = 'oe';
3048     $where = "quotation = '1'";
3049
3050   } elsif ($table eq 'customer') {
3051     $arap  = 'ar';
3052
3053   } else {
3054     $arap  = 'ap';
3055
3056   }
3057
3058   $where           = "($where) AND" if ($where);
3059   my $query        = qq|SELECT MAX(id) FROM $arap
3060                         WHERE $where ${table}_id > 0|;
3061   my ($trans_id)   = selectrow_query($self, $dbh, $query);
3062   $trans_id       *= 1;
3063
3064   my $column_spec  = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
3065   $query           = qq|SELECT $column_spec
3066                         FROM $arap a
3067                         LEFT JOIN $table     ct ON (a.${table}_id = ct.id)
3068                         LEFT JOIN department d  ON (a.department_id = d.id)
3069                         WHERE a.id = ?|;
3070   my $ref          = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
3071
3072   map { $self->{$_} = $ref->{$_} } values %column_map;
3073
3074   $main::lxdebug->leave_sub();
3075 }
3076
3077 sub current_date {
3078   $main::lxdebug->enter_sub();
3079
3080   my $self     = shift;
3081   my $myconfig = shift || \%::myconfig;
3082   my ($thisdate, $days) = @_;
3083
3084   my $dbh = $self->get_standard_dbh($myconfig);
3085   my $query;
3086
3087   $days *= 1;
3088   if ($thisdate) {
3089     my $dateformat = $myconfig->{dateformat};
3090     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
3091     $thisdate = $dbh->quote($thisdate);
3092     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
3093   } else {
3094     $query = qq|SELECT current_date AS thisdate|;
3095   }
3096
3097   ($thisdate) = selectrow_query($self, $dbh, $query);
3098
3099   $main::lxdebug->leave_sub();
3100
3101   return $thisdate;
3102 }
3103
3104 sub like {
3105   $main::lxdebug->enter_sub();
3106
3107   my ($self, $string) = @_;
3108
3109   if ($string !~ /%/) {
3110     $string = "%$string%";
3111   }
3112
3113   $string =~ s/\'/\'\'/g;
3114
3115   $main::lxdebug->leave_sub();
3116
3117   return $string;
3118 }
3119
3120 sub redo_rows {
3121   $main::lxdebug->enter_sub();
3122
3123   my ($self, $flds, $new, $count, $numrows) = @_;
3124
3125   my @ndx = ();
3126
3127   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
3128
3129   my $i = 0;
3130
3131   # fill rows
3132   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
3133     $i++;
3134     my $j = $item->{ndx} - 1;
3135     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
3136   }
3137
3138   # delete empty rows
3139   for $i ($count + 1 .. $numrows) {
3140     map { delete $self->{"${_}_$i"} } @{$flds};
3141   }
3142
3143   $main::lxdebug->leave_sub();
3144 }
3145
3146 sub update_status {
3147   $main::lxdebug->enter_sub();
3148
3149   my ($self, $myconfig) = @_;
3150
3151   my ($i, $id);
3152
3153   my $dbh = $self->dbconnect_noauto($myconfig);
3154
3155   my $query = qq|DELETE FROM status
3156                  WHERE (formname = ?) AND (trans_id = ?)|;
3157   my $sth = prepare_query($self, $dbh, $query);
3158
3159   if ($self->{formname} =~ /(check|receipt)/) {
3160     for $i (1 .. $self->{rowcount}) {
3161       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
3162     }
3163   } else {
3164     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
3165   }
3166   $sth->finish();
3167
3168   my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3169   my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3170
3171   my %queued = split / /, $self->{queued};
3172   my @values;
3173
3174   if ($self->{formname} =~ /(check|receipt)/) {
3175
3176     # this is a check or receipt, add one entry for each lineitem
3177     my ($accno) = split /--/, $self->{account};
3178     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3179                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3180     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3181     $sth = prepare_query($self, $dbh, $query);
3182
3183     for $i (1 .. $self->{rowcount}) {
3184       if ($self->{"checked_$i"}) {
3185         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3186       }
3187     }
3188     $sth->finish();
3189
3190   } else {
3191     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3192                 VALUES (?, ?, ?, ?, ?)|;
3193     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3194              $queued{$self->{formname}}, $self->{formname});
3195   }
3196
3197   $dbh->commit;
3198   $dbh->disconnect;
3199
3200   $main::lxdebug->leave_sub();
3201 }
3202
3203 sub save_status {
3204   $main::lxdebug->enter_sub();
3205
3206   my ($self, $dbh) = @_;
3207
3208   my ($query, $printed, $emailed);
3209
3210   my $formnames  = $self->{printed};
3211   my $emailforms = $self->{emailed};
3212
3213   $query = qq|DELETE FROM status
3214                  WHERE (formname = ?) AND (trans_id = ?)|;
3215   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3216
3217   # this only applies to the forms
3218   # checks and receipts are posted when printed or queued
3219
3220   if ($self->{queued}) {
3221     my %queued = split / /, $self->{queued};
3222
3223     foreach my $formname (keys %queued) {
3224       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3225       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3226
3227       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3228                   VALUES (?, ?, ?, ?, ?)|;
3229       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3230
3231       $formnames  =~ s/\Q$self->{formname}\E//;
3232       $emailforms =~ s/\Q$self->{formname}\E//;
3233
3234     }
3235   }
3236
3237   # save printed, emailed info
3238   $formnames  =~ s/^ +//g;
3239   $emailforms =~ s/^ +//g;
3240
3241   my %status = ();
3242   map { $status{$_}{printed} = 1 } split / +/, $formnames;
3243   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3244
3245   foreach my $formname (keys %status) {
3246     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
3247     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3248
3249     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3250                 VALUES (?, ?, ?, ?)|;
3251     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3252   }
3253
3254   $main::lxdebug->leave_sub();
3255 }
3256
3257 #--- 4 locale ---#
3258 # $main::locale->text('SAVED')
3259 # $main::locale->text('DELETED')
3260 # $main::locale->text('ADDED')
3261 # $main::locale->text('PAYMENT POSTED')
3262 # $main::locale->text('POSTED')
3263 # $main::locale->text('POSTED AS NEW')
3264 # $main::locale->text('ELSE')
3265 # $main::locale->text('SAVED FOR DUNNING')
3266 # $main::locale->text('DUNNING STARTED')
3267 # $main::locale->text('PRINTED')
3268 # $main::locale->text('MAILED')
3269 # $main::locale->text('SCREENED')
3270 # $main::locale->text('CANCELED')
3271 # $main::locale->text('invoice')
3272 # $main::locale->text('proforma')
3273 # $main::locale->text('sales_order')
3274 # $main::locale->text('packing_list')
3275 # $main::locale->text('pick_list')
3276 # $main::locale->text('purchase_order')
3277 # $main::locale->text('bin_list')
3278 # $main::locale->text('sales_quotation')
3279 # $main::locale->text('request_quotation')
3280
3281 sub save_history {
3282   $main::lxdebug->enter_sub();
3283
3284   my $self = shift;
3285   my $dbh  = shift || $self->get_standard_dbh;
3286
3287   if(!exists $self->{employee_id}) {
3288     &get_employee($self, $dbh);
3289   }
3290
3291   my $query =
3292    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3293    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3294   my @values = (conv_i($self->{id}), $self->{login},
3295                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3296   do_query($self, $dbh, $query, @values);
3297
3298   $dbh->commit;
3299
3300   $main::lxdebug->leave_sub();
3301 }
3302
3303 sub get_history {
3304   $main::lxdebug->enter_sub();
3305
3306   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3307   my ($orderBy, $desc) = split(/\-\-/, $order);
3308   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3309   my @tempArray;
3310   my $i = 0;
3311   if ($trans_id ne "") {
3312     my $query =
3313       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 | .
3314       qq|FROM history_erp h | .
3315       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3316       qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3317       $order;
3318
3319     my $sth = $dbh->prepare($query) || $self->dberror($query);
3320
3321     $sth->execute() || $self->dberror("$query");
3322
3323     while(my $hash_ref = $sth->fetchrow_hashref()) {
3324       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3325       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3326       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3327       $tempArray[$i++] = $hash_ref;
3328     }
3329     $main::lxdebug->leave_sub() and return \@tempArray
3330       if ($i > 0 && $tempArray[0] ne "");
3331   }
3332   $main::lxdebug->leave_sub();
3333   return 0;
3334 }
3335
3336 sub update_defaults {
3337   $main::lxdebug->enter_sub();
3338
3339   my ($self, $myconfig, $fld, $provided_dbh) = @_;
3340
3341   my $dbh;
3342   if ($provided_dbh) {
3343     $dbh = $provided_dbh;
3344   } else {
3345     $dbh = $self->dbconnect_noauto($myconfig);
3346   }
3347   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3348   my $sth   = $dbh->prepare($query);
3349
3350   $sth->execute || $self->dberror($query);
3351   my ($var) = $sth->fetchrow_array;
3352   $sth->finish;
3353
3354   if ($var =~ m/\d+$/) {
3355     my $new_var  = (substr $var, $-[0]) * 1 + 1;
3356     my $len_diff = length($var) - $-[0] - length($new_var);
3357     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3358
3359   } else {
3360     $var = $var . '1';
3361   }
3362
3363   $query = qq|UPDATE defaults SET $fld = ?|;
3364   do_query($self, $dbh, $query, $var);
3365
3366   if (!$provided_dbh) {
3367     $dbh->commit;
3368     $dbh->disconnect;
3369   }
3370
3371   $main::lxdebug->leave_sub();
3372
3373   return $var;
3374 }
3375
3376 sub update_business {
3377   $main::lxdebug->enter_sub();
3378
3379   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3380
3381   my $dbh;
3382   if ($provided_dbh) {
3383     $dbh = $provided_dbh;
3384   } else {
3385     $dbh = $self->dbconnect_noauto($myconfig);
3386   }
3387   my $query =
3388     qq|SELECT customernumberinit FROM business
3389        WHERE id = ? FOR UPDATE|;
3390   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3391
3392   return undef unless $var;
3393
3394   if ($var =~ m/\d+$/) {
3395     my $new_var  = (substr $var, $-[0]) * 1 + 1;
3396     my $len_diff = length($var) - $-[0] - length($new_var);
3397     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3398
3399   } else {
3400     $var = $var . '1';
3401   }
3402
3403   $query = qq|UPDATE business
3404               SET customernumberinit = ?
3405               WHERE id = ?|;
3406   do_query($self, $dbh, $query, $var, $business_id);
3407
3408   if (!$provided_dbh) {
3409     $dbh->commit;
3410     $dbh->disconnect;
3411   }
3412
3413   $main::lxdebug->leave_sub();
3414
3415   return $var;
3416 }
3417
3418 sub get_partsgroup {
3419   $main::lxdebug->enter_sub();
3420
3421   my ($self, $myconfig, $p) = @_;
3422   my $target = $p->{target} || 'all_partsgroup';
3423
3424   my $dbh = $self->get_standard_dbh($myconfig);
3425
3426   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3427                  FROM partsgroup pg
3428                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
3429   my @values;
3430
3431   if ($p->{searchitems} eq 'part') {
3432     $query .= qq|WHERE p.inventory_accno_id > 0|;
3433   }
3434   if ($p->{searchitems} eq 'service') {
3435     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3436   }
3437   if ($p->{searchitems} eq 'assembly') {
3438     $query .= qq|WHERE p.assembly = '1'|;
3439   }
3440   if ($p->{searchitems} eq 'labor') {
3441     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3442   }
3443
3444   $query .= qq|ORDER BY partsgroup|;
3445
3446   if ($p->{all}) {
3447     $query = qq|SELECT id, partsgroup FROM partsgroup
3448                 ORDER BY partsgroup|;
3449   }
3450
3451   if ($p->{language_code}) {
3452     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3453                   t.description AS translation
3454                 FROM partsgroup pg
3455                 JOIN parts p ON (p.partsgroup_id = pg.id)
3456                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3457                 ORDER BY translation|;
3458     @values = ($p->{language_code});
3459   }
3460
3461   $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3462
3463   $main::lxdebug->leave_sub();
3464 }
3465
3466 sub get_pricegroup {
3467   $main::lxdebug->enter_sub();
3468
3469   my ($self, $myconfig, $p) = @_;
3470
3471   my $dbh = $self->get_standard_dbh($myconfig);
3472
3473   my $query = qq|SELECT p.id, p.pricegroup
3474                  FROM pricegroup p|;
3475
3476   $query .= qq| ORDER BY pricegroup|;
3477
3478   if ($p->{all}) {
3479     $query = qq|SELECT id, pricegroup FROM pricegroup
3480                 ORDER BY pricegroup|;
3481   }
3482
3483   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3484
3485   $main::lxdebug->leave_sub();
3486 }
3487
3488 sub all_years {
3489 # usage $form->all_years($myconfig, [$dbh])
3490 # return list of all years where bookings found
3491 # (@all_years)
3492
3493   $main::lxdebug->enter_sub();
3494
3495   my ($self, $myconfig, $dbh) = @_;
3496
3497   $dbh ||= $self->get_standard_dbh($myconfig);
3498
3499   # get years
3500   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3501                    (SELECT MAX(transdate) FROM acc_trans)|;
3502   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3503
3504   if ($myconfig->{dateformat} =~ /^yy/) {
3505     ($startdate) = split /\W/, $startdate;
3506     ($enddate) = split /\W/, $enddate;
3507   } else {
3508     (@_) = split /\W/, $startdate;
3509     $startdate = $_[2];
3510     (@_) = split /\W/, $enddate;
3511     $enddate = $_[2];
3512   }
3513
3514   my @all_years;
3515   $startdate = substr($startdate,0,4);
3516   $enddate = substr($enddate,0,4);
3517
3518   while ($enddate >= $startdate) {
3519     push @all_years, $enddate--;
3520   }
3521
3522   return @all_years;
3523
3524   $main::lxdebug->leave_sub();
3525 }
3526
3527 sub backup_vars {
3528   $main::lxdebug->enter_sub();
3529   my $self = shift;
3530   my @vars = @_;
3531
3532   map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3533
3534   $main::lxdebug->leave_sub();
3535 }
3536
3537 sub restore_vars {
3538   $main::lxdebug->enter_sub();
3539
3540   my $self = shift;
3541   my @vars = @_;
3542
3543   map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3544
3545   $main::lxdebug->leave_sub();
3546 }
3547
3548 1;
3549
3550 __END__
3551
3552 =head1 NAME
3553
3554 SL::Form.pm - main data object.
3555
3556 =head1 SYNOPSIS
3557
3558 This is the main data object of Lx-Office.
3559 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3560 Points of interest for a beginner are:
3561
3562  - $form->error            - renders a generic error in html. accepts an error message
3563  - $form->get_standard_dbh - returns a database connection for the
3564
3565 =head1 SPECIAL FUNCTIONS
3566
3567 =over 4
3568
3569 =item _store_value()
3570
3571 parses a complex var name, and stores it in the form.
3572
3573 syntax:
3574   $form->_store_value($key, $value);
3575
3576 keys must start with a string, and can contain various tokens.
3577 supported key structures are:
3578
3579 1. simple access
3580   simple key strings work as expected
3581
3582   id => $form->{id}
3583
3584 2. hash access.
3585   separating two keys by a dot (.) will result in a hash lookup for the inner value
3586   this is similar to the behaviour of java and templating mechanisms.
3587
3588   filter.description => $form->{filter}->{description}
3589
3590 3. array+hashref access
3591
3592   adding brackets ([]) before the dot will cause the next hash to be put into an array.
3593   using [+] instead of [] will force a new array index. this is useful for recurring
3594   data structures like part lists. put a [+] into the first varname, and use [] on the
3595   following ones.
3596
3597   repeating these names in your template:
3598
3599     invoice.items[+].id
3600     invoice.items[].parts_id
3601
3602   will result in:
3603
3604     $form->{invoice}->{items}->[
3605       {
3606         id       => ...
3607         parts_id => ...
3608       },
3609       {
3610         id       => ...
3611         parts_id => ...
3612       }
3613       ...
3614     ]
3615
3616 4. arrays
3617
3618   using brackets at the end of a name will result in a pure array to be created.
3619   note that you mustn't use [+], which is reserved for array+hash access and will
3620   result in undefined behaviour in array context.
3621
3622   filter.status[]  => $form->{status}->[ val1, val2, ... ]
3623
3624 =item update_business PARAMS
3625
3626 PARAMS (not named):
3627  \%config,     - config hashref
3628  $business_id, - business id
3629  $dbh          - optional database handle
3630
3631 handles business (thats customer/vendor types) sequences.
3632
3633 special behaviour for empty strings in customerinitnumber field:
3634 will in this case not increase the value, and return undef.
3635
3636 =item redirect_header $url
3637
3638 Generates a HTTP redirection header for the new C<$url>. Constructs an
3639 absolute URL including scheme, host name and port. If C<$url> is a
3640 relative URL then it is considered relative to Lx-Office base URL.
3641
3642 This function C<die>s if headers have already been created with
3643 C<$::form-E<gt>header>.
3644
3645 Examples:
3646
3647   print $::form->redirect_header('oe.pl?action=edit&id=1234');
3648   print $::form->redirect_header('http://www.lx-office.org/');
3649
3650 =back
3651
3652 =cut