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