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