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