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