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