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