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