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