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