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