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