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