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