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