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