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