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