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