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