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