1 #=====================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   7 #=====================================================================
 
   8 # SQL-Ledger Accounting
 
   9 # Copyright (C) 1998-2002
 
  11 #  Author: Dieter Simader
 
  12 #   Email: dsimader@sql-ledger.org
 
  13 #     Web: http://www.sql-ledger.org
 
  15 # Contributors: Thomas Bayen <bayen@gmx.de>
 
  16 #               Antti Kaihola <akaihola@siba.fi>
 
  17 #               Moritz Bunkus (tex code)
 
  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.
 
  24 # This program is distributed in the hope that it will be useful,
 
  25 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 
  26 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  27 # GNU General Public License for more details.
 
  28 # You should have received a copy of the GNU General Public License
 
  29 # along with this program; if not, write to the Free Software
 
  30 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 
  32 #======================================================================
 
  33 # Utilities for parsing forms
 
  34 # and supporting routines for linking account numbers
 
  35 # used in AR, AP and IS, IR modules
 
  37 #======================================================================
 
  52 use POSIX qw(strftime);
 
  64 use SL::DB::PaymentTerm;
 
  67 use SL::Helper::Flash qw();
 
  70 use SL::Layout::Dispatcher;
 
  72 use SL::Locale::String;
 
  75 use SL::MoreCommon qw(uri_encode uri_decode);
 
  77 use SL::PrefixedNumber;
 
  86 use List::Util qw(first max min sum);
 
  87 use List::MoreUtils qw(all any apply);
 
  89 use SL::Helper::File qw(:all);
 
  90 use SL::Helper::CreatePDF qw(merge_pdfs);
 
  95   SL::Version->get_version;
 
  99   $main::lxdebug->enter_sub();
 
 106   if ($LXDebug::watch_form) {
 
 107     require SL::Watchdog;
 
 108     tie %{ $self }, 'SL::Watchdog';
 
 113   $main::lxdebug->leave_sub();
 
 120   SL::Request::read_cgi_input($self);
 
 123 sub _flatten_variables_rec {
 
 124   $main::lxdebug->enter_sub(2);
 
 133   if ('' eq ref $curr->{$key}) {
 
 134     @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
 
 136   } elsif ('HASH' eq ref $curr->{$key}) {
 
 137     foreach my $hash_key (sort keys %{ $curr->{$key} }) {
 
 138       push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
 
 142     foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
 
 143       my $first_array_entry = 1;
 
 145       my $element = $curr->{$key}[$idx];
 
 147       if ('HASH' eq ref $element) {
 
 148         foreach my $hash_key (sort keys %{ $element }) {
 
 149           push @result, $self->_flatten_variables_rec($element, $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
 
 150           $first_array_entry = 0;
 
 153         @result = ({ 'key' => $prefix . $key . ($first_array_entry ? '[+]' : '[]'), 'value' => $element });
 
 158   $main::lxdebug->leave_sub(2);
 
 163 sub flatten_variables {
 
 164   $main::lxdebug->enter_sub(2);
 
 172     push @variables, $self->_flatten_variables_rec($self, '', $_);
 
 175   $main::lxdebug->leave_sub(2);
 
 180 sub flatten_standard_variables {
 
 181   $main::lxdebug->enter_sub(2);
 
 184   my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar), @_);
 
 188   foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
 
 189     push @variables, $self->_flatten_variables_rec($self, '', $_);
 
 192   $main::lxdebug->leave_sub(2);
 
 198   $main::lxdebug->enter_sub();
 
 204   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
 
 206   $main::lxdebug->leave_sub();
 
 210   $main::lxdebug->enter_sub(2);
 
 213   my $password      = $self->{password};
 
 215   $self->{password} = 'X' x 8;
 
 217   local $Data::Dumper::Sortkeys = 1;
 
 218   my $output                    = Dumper($self);
 
 220   $self->{password} = $password;
 
 222   $main::lxdebug->leave_sub(2);
 
 228   my ($self, $str) = @_;
 
 230   return uri_encode($str);
 
 234   my ($self, $str) = @_;
 
 236   return uri_decode($str);
 
 240   $main::lxdebug->enter_sub();
 
 241   my ($self, $str) = @_;
 
 243   if ($str && !ref($str)) {
 
 244     $str =~ s/\"/"/g;
 
 247   $main::lxdebug->leave_sub();
 
 253   $main::lxdebug->enter_sub();
 
 254   my ($self, $str) = @_;
 
 256   if ($str && !ref($str)) {
 
 257     $str =~ s/"/\"/g;
 
 260   $main::lxdebug->leave_sub();
 
 266   $main::lxdebug->enter_sub();
 
 270     map({ print($::request->{cgi}->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
 
 272     for (sort keys %$self) {
 
 273       next if (($_ eq "header") || (ref($self->{$_}) ne ""));
 
 274       print($::request->{cgi}->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
 
 277   $main::lxdebug->leave_sub();
 
 281   my ($self, $code) = @_;
 
 282   local $self->{__ERROR_HANDLER} = sub { die SL::X::FormError->new($_[0]) };
 
 287   $main::lxdebug->enter_sub();
 
 289   $main::lxdebug->show_backtrace();
 
 291   my ($self, $msg) = @_;
 
 293   if ($self->{__ERROR_HANDLER}) {
 
 294     $self->{__ERROR_HANDLER}->($msg);
 
 296   } elsif ($ENV{HTTP_USER_AGENT}) {
 
 298     $self->show_generic_error($msg);
 
 301     confess "Error: $msg\n";
 
 304   $main::lxdebug->leave_sub();
 
 308   $main::lxdebug->enter_sub();
 
 310   my ($self, $msg) = @_;
 
 312   if ($ENV{HTTP_USER_AGENT}) {
 
 314     print $self->parse_html_template('generic/form_info', { message => $msg });
 
 316   } elsif ($self->{info_function}) {
 
 317     &{ $self->{info_function} }($msg);
 
 322   $main::lxdebug->leave_sub();
 
 325 # calculates the number of rows in a textarea based on the content and column number
 
 326 # can be capped with maxrows
 
 328   $main::lxdebug->enter_sub();
 
 329   my ($self, $str, $cols, $maxrows, $minrows) = @_;
 
 333   my $rows   = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
 
 336   $main::lxdebug->leave_sub();
 
 338   return max(min($rows, $maxrows), $minrows);
 
 342   my ($self, $msg) = @_;
 
 344   die SL::X::DBError->new(
 
 346     error => $DBI::errstr,
 
 351   $main::lxdebug->enter_sub();
 
 353   my ($self, $name, $msg) = @_;
 
 356   foreach my $part (split m/\./, $name) {
 
 357     if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
 
 360     $curr = $curr->{$part};
 
 363   $main::lxdebug->leave_sub();
 
 366 sub _get_request_uri {
 
 369   return URI->new($ENV{HTTP_REFERER})->canonical() if $ENV{HTTP_X_FORWARDED_FOR};
 
 370   return URI->new                                  if !$ENV{REQUEST_URI}; # for testing
 
 372   my $scheme =  $::request->is_https ? 'https' : 'http';
 
 373   my $port   =  $ENV{SERVER_PORT};
 
 374   $port      =  undef if (($scheme eq 'http' ) && ($port == 80))
 
 375                       || (($scheme eq 'https') && ($port == 443));
 
 377   my $uri    =  URI->new("${scheme}://");
 
 378   $uri->scheme($scheme);
 
 380   $uri->host($ENV{HTTP_HOST} || $ENV{SERVER_ADDR});
 
 381   $uri->path_query($ENV{REQUEST_URI});
 
 387 sub _add_to_request_uri {
 
 390   my $relative_new_path = shift;
 
 391   my $request_uri       = shift || $self->_get_request_uri;
 
 392   my $relative_new_uri  = URI->new($relative_new_path);
 
 393   my @request_segments  = $request_uri->path_segments;
 
 395   my $new_uri           = $request_uri->clone;
 
 396   $new_uri->path_segments(@request_segments[0..scalar(@request_segments) - 2], $relative_new_uri->path_segments);
 
 401 sub create_http_response {
 
 402   $main::lxdebug->enter_sub();
 
 407   my $cgi      = $::request->{cgi};
 
 410   if (defined $main::auth) {
 
 411     my $uri      = $self->_get_request_uri;
 
 412     my @segments = $uri->path_segments;
 
 414     $uri->path_segments(@segments);
 
 416     my $session_cookie_value = $main::auth->get_session_id();
 
 418     if ($session_cookie_value) {
 
 419       $session_cookie = $cgi->cookie('-name'   => $main::auth->get_session_cookie_name(),
 
 420                                      '-value'  => $session_cookie_value,
 
 421                                      '-path'   => $uri->path,
 
 422                                      '-secure' => $::request->is_https);
 
 426   my %cgi_params = ('-type' => $params{content_type});
 
 427   $cgi_params{'-charset'} = $params{charset} if ($params{charset});
 
 428   $cgi_params{'-cookie'}  = $session_cookie  if ($session_cookie);
 
 430   map { $cgi_params{'-' . $_} = $params{$_} if exists $params{$_} } qw(content_disposition content_length);
 
 432   my $output = $cgi->header(%cgi_params);
 
 434   $main::lxdebug->leave_sub();
 
 440   $::lxdebug->enter_sub;
 
 442   my ($self, %params) = @_;
 
 445   $::lxdebug->leave_sub and return if !$ENV{HTTP_USER_AGENT} || $self->{header}++;
 
 447   if ($params{no_layout}) {
 
 448     $::request->{layout} = SL::Layout::Dispatcher->new(style => 'none');
 
 451   my $layout = $::request->{layout};
 
 453   # standard css for all
 
 454   # this should gradually move to the layouts that need it
 
 455   $layout->use_stylesheet("$_.css") for qw(
 
 456     common main menu list_accounts jquery.autocomplete
 
 457     jquery.multiselect2side
 
 458     ui-lightness/jquery-ui
 
 460     tooltipster themes/tooltipster-light
 
 463   $layout->use_javascript("$_.js") for (qw(
 
 464     jquery jquery-ui jquery.cookie jquery.checkall jquery.download
 
 465     jquery/jquery.form jquery/fixes client_js
 
 466     jquery/jquery.tooltipster.min
 
 467     common part_selection
 
 468   ), "jquery/ui/i18n/jquery.ui.datepicker-$::myconfig{countrycode}");
 
 470   $self->{favicon} ||= "favicon.ico";
 
 471   $self->{titlebar} = join ' - ', grep $_, $self->{title}, $self->{login}, $::myconfig{dbname}, $self->read_version if $self->{title} || !$self->{titlebar};
 
 474   if ($self->{refresh_url} || $self->{refresh_time}) {
 
 475     my $refresh_time = $self->{refresh_time} || 3;
 
 476     my $refresh_url  = $self->{refresh_url}  || $ENV{REFERER};
 
 477     push @header, "<meta http-equiv='refresh' content='$refresh_time;$refresh_url'>";
 
 480   my $auto_reload_resources_param = $layout->auto_reload_resources_param;
 
 482   push @header, map { qq|<link rel="stylesheet" href="${_}${auto_reload_resources_param}" type="text/css" title="Stylesheet">| } $layout->stylesheets;
 
 483   push @header, "<style type='text/css'>\@page { size:landscape; }</style> "                     if $self->{landscape};
 
 484   push @header, "<link rel='shortcut icon' href='$self->{favicon}' type='image/x-icon'>"         if -f $self->{favicon};
 
 485   push @header, map { qq|<script type="text/javascript" src="${_}${auto_reload_resources_param}"></script>| }                    $layout->javascripts;
 
 486   push @header, $self->{javascript} if $self->{javascript};
 
 487   push @header, map { $_->show_javascript } @{ $self->{AJAX} || [] };
 
 490     strict       => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">|,
 
 491     transitional => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">|,
 
 492     frameset     => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">|,
 
 493     html5        => qq|<!DOCTYPE html>|,
 
 497   print $self->create_http_response(content_type => 'text/html', charset => 'UTF-8');
 
 498   print $doctypes{$params{doctype} || 'transitional'}, $/;
 
 502   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 
 503   <title>$self->{titlebar}</title>
 
 505   print "  $_\n" for @header;
 
 507   <meta name="robots" content="noindex,nofollow">
 
 512   print $::request->{layout}->pre_content;
 
 513   print $::request->{layout}->start_content;
 
 515   $layout->header_done;
 
 517   $::lxdebug->leave_sub;
 
 521   return unless $::request->{layout}->need_footer;
 
 523   print $::request->{layout}->end_content;
 
 524   print $::request->{layout}->post_content;
 
 526   if (my @inline_scripts = $::request->{layout}->javascripts_inline) {
 
 527     print "<script type='text/javascript'>" . join("; ", @inline_scripts) . "</script>\n";
 
 536 sub ajax_response_header {
 
 537   $main::lxdebug->enter_sub();
 
 541   my $output = $::request->{cgi}->header('-charset' => 'UTF-8');
 
 543   $main::lxdebug->leave_sub();
 
 548 sub redirect_header {
 
 552   my $base_uri = $self->_get_request_uri;
 
 553   my $new_uri  = URI->new_abs($new_url, $base_uri);
 
 555   die "Headers already sent" if $self->{header};
 
 558   return $::request->{cgi}->redirect($new_uri);
 
 561 sub set_standard_title {
 
 562   $::lxdebug->enter_sub;
 
 565   $self->{titlebar}  = "kivitendo " . $::locale->text('Version') . " " . $self->read_version;
 
 566   $self->{titlebar} .= "- $::myconfig{name}"   if $::myconfig{name};
 
 567   $self->{titlebar} .= "- $::myconfig{dbname}" if $::myconfig{name};
 
 569   $::lxdebug->leave_sub;
 
 572 sub _prepare_html_template {
 
 573   $main::lxdebug->enter_sub();
 
 575   my ($self, $file, $additional_params) = @_;
 
 578   if (!%::myconfig || !$::myconfig{"countrycode"}) {
 
 579     $language = $::lx_office_conf{system}->{language};
 
 581     $language = $main::myconfig{"countrycode"};
 
 583   $language = "de" unless ($language);
 
 585   if (-f "templates/webpages/${file}.html") {
 
 586     $file = "templates/webpages/${file}.html";
 
 588   } elsif (ref $file eq 'SCALAR') {
 
 589     # file is a scalarref, use inline mode
 
 591     my $info = "Web page template '${file}' not found.\n";
 
 593     print qq|<pre>$info</pre>|;
 
 594     $::dispatcher->end_request;
 
 597   $additional_params->{AUTH}          = $::auth;
 
 598   $additional_params->{INSTANCE_CONF} = $::instance_conf;
 
 599   $additional_params->{LOCALE}        = $::locale;
 
 600   $additional_params->{LXCONFIG}      = \%::lx_office_conf;
 
 601   $additional_params->{LXDEBUG}       = $::lxdebug;
 
 602   $additional_params->{MYCONFIG}      = \%::myconfig;
 
 604   $main::lxdebug->leave_sub();
 
 609 sub parse_html_template {
 
 610   $main::lxdebug->enter_sub();
 
 612   my ($self, $file, $additional_params) = @_;
 
 614   $additional_params ||= { };
 
 616   my $real_file = $self->_prepare_html_template($file, $additional_params);
 
 617   my $template  = $self->template;
 
 619   map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
 
 622   $template->process($real_file, $additional_params, \$output) || die $template->error;
 
 624   $main::lxdebug->leave_sub();
 
 629 sub template { $::request->presenter->get_template }
 
 631 sub show_generic_error {
 
 632   $main::lxdebug->enter_sub();
 
 634   my ($self, $error, %params) = @_;
 
 636   if ($self->{__ERROR_HANDLER}) {
 
 637     $self->{__ERROR_HANDLER}->($error);
 
 638     $main::lxdebug->leave_sub();
 
 642   if ($::request->is_ajax) {
 
 645       ->render(SL::Controller::Base->new);
 
 646     $::dispatcher->end_request;
 
 650     'title_error' => $params{title},
 
 651     'label_error' => $error,
 
 654   $self->{title} = $params{title} if $params{title};
 
 656   for my $bar ($::request->layout->get('actionbar')) {
 
 660         call      => [ 'kivi.history_back' ],
 
 661         accesskey => 'enter',
 
 667   print $self->parse_html_template("generic/error", $add_params);
 
 669   print STDERR "Error: $error\n";
 
 671   $main::lxdebug->leave_sub();
 
 673   $::dispatcher->end_request;
 
 676 sub show_generic_information {
 
 677   $main::lxdebug->enter_sub();
 
 679   my ($self, $text, $title) = @_;
 
 682     'title_information' => $title,
 
 683     'label_information' => $text,
 
 686   $self->{title} = $title if ($title);
 
 689   print $self->parse_html_template("generic/information", $add_params);
 
 691   $main::lxdebug->leave_sub();
 
 693   $::dispatcher->end_request;
 
 696 sub _store_redirect_info_in_session {
 
 699   return unless $self->{callback} =~ m:^ ( [^\?/]+ \.pl ) \? (.+) :x;
 
 701   my ($controller, $params) = ($1, $2);
 
 702   my $form                  = { map { map { $self->unescape($_) } split /=/, $_, 2 } split m/\&/, $params };
 
 703   $self->{callback}         = "${controller}?RESTORE_FORM_FROM_SESSION_ID=" . $::auth->save_form_in_session(form => $form);
 
 707   $main::lxdebug->enter_sub();
 
 709   my ($self, $msg) = @_;
 
 711   if (!$self->{callback}) {
 
 715     SL::Helper::Flash::flash_later('info', $msg) if $msg;
 
 716     $self->_store_redirect_info_in_session;
 
 717     print $::form->redirect_header($self->{callback});
 
 720   $::dispatcher->end_request;
 
 722   $main::lxdebug->leave_sub();
 
 725 # sort of columns removed - empty sub
 
 727   $main::lxdebug->enter_sub();
 
 729   my ($self, @columns) = @_;
 
 731   $main::lxdebug->leave_sub();
 
 737   $main::lxdebug->enter_sub(2);
 
 739   my ($self, $myconfig, $amount, $places, $dash) = @_;
 
 742   my $neg = $amount < 0;
 
 743   my $force_places = defined $places && $places >= 0;
 
 745   $amount = $self->round_amount($amount, abs $places) if $force_places;
 
 746   $neg    = 0 if $amount == 0; # don't show negative zero
 
 747   $amount = sprintf "%.*f", ($force_places ? $places : 10), abs $amount; # 6 is default for %fa
 
 749   # before the sprintf amount was a number, afterwards it's a string. because of the dynamic nature of perl
 
 750   # this is easy to confuse, so keep in mind: before this comment no s///, m//, concat or other strong ops on
 
 751   # $amount. after this comment no +,-,*,/,abs. it will only introduce subtle bugs.
 
 753   $amount =~ s/0*$// unless defined $places && $places == 0;             # cull trailing 0s
 
 755   my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
 
 756   my @p = split(/\./, $amount);                                          # split amount at decimal point
 
 758   $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1];                             # add 1,000 delimiters
 
 760   if ($places || $p[1]) {
 
 763             .  (0 x max(abs($places || 0) - length ($p[1]||''), 0));     # pad the fraction
 
 767     ($dash =~ /-/)    ? ($neg ? "($amount)"                            : "$amount" )                              :
 
 768     ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
 
 769                         ($neg ? "-$amount"                             : "$amount" )                              ;
 
 772   $main::lxdebug->leave_sub(2);
 
 776 sub format_amount_units {
 
 777   $main::lxdebug->enter_sub();
 
 782   my $myconfig         = \%main::myconfig;
 
 783   my $amount           = $params{amount} * 1;
 
 784   my $places           = $params{places};
 
 785   my $part_unit_name   = $params{part_unit};
 
 786   my $amount_unit_name = $params{amount_unit};
 
 787   my $conv_units       = $params{conv_units};
 
 788   my $max_places       = $params{max_places};
 
 790   if (!$part_unit_name) {
 
 791     $main::lxdebug->leave_sub();
 
 795   my $all_units        = AM->retrieve_all_units;
 
 797   if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
 
 798     $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
 
 801   if (!scalar @{ $conv_units }) {
 
 802     my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
 
 803     $main::lxdebug->leave_sub();
 
 807   my $part_unit  = $all_units->{$part_unit_name};
 
 808   my $conv_unit  = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
 
 810   $amount       *= $conv_unit->{factor};
 
 815   foreach my $unit (@$conv_units) {
 
 816     my $last = $unit->{name} eq $part_unit->{name};
 
 818       $num     = int($amount / $unit->{factor});
 
 819       $amount -= $num * $unit->{factor};
 
 822     if ($last ? $amount : $num) {
 
 823       push @values, { "unit"   => $unit->{name},
 
 824                       "amount" => $last ? $amount / $unit->{factor} : $num,
 
 825                       "places" => $last ? $places : 0 };
 
 832     push @values, { "unit"   => $part_unit_name,
 
 837   my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
 
 839   $main::lxdebug->leave_sub();
 
 845   $main::lxdebug->enter_sub(2);
 
 850   $input =~ s/(^|[^\#]) \#  (\d+)  /$1$_[$2 - 1]/gx;
 
 851   $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
 
 852   $input =~ s/\#\#/\#/g;
 
 854   $main::lxdebug->leave_sub(2);
 
 862   $main::lxdebug->enter_sub(2);
 
 864   my ($self, $myconfig, $amount) = @_;
 
 866   if (!defined($amount) || ($amount eq '')) {
 
 867     $main::lxdebug->leave_sub(2);
 
 871   if (   ($myconfig->{numberformat} eq '1.000,00')
 
 872       || ($myconfig->{numberformat} eq '1000,00')) {
 
 877   if ($myconfig->{numberformat} eq "1'000.00") {
 
 883   $main::lxdebug->leave_sub(2);
 
 885   # Make sure no code wich is not a math expression ends up in eval().
 
 886   return 0 unless $amount =~ /^ [\s \d \( \) \- \+ \* \/ \. ]* $/x;
 
 888   # Prevent numbers from being parsed as octals;
 
 889   $amount =~ s{ (?<! [\d.] ) 0+ (?= [1-9] ) }{}gx;
 
 891   return scalar(eval($amount)) * 1 ;
 
 895   my ($self, $amount, $places, $adjust) = @_;
 
 897   return 0 if !defined $amount;
 
 902     my $precision = $::instance_conf->get_precision || 0.01;
 
 903     return $self->round_amount( $self->round_amount($amount / $precision, 0) * $precision, $places);
 
 906   # We use Perl's knowledge of string representation for
 
 907   # rounding. First, convert the floating point number to a string
 
 908   # with a high number of places. Then split the string on the decimal
 
 909   # sign and use integer calculation for rounding the decimal places
 
 910   # part. If an overflow occurs then apply that overflow to the part
 
 911   # before the decimal sign as well using integer arithmetic again.
 
 913   my $int_amount = int(abs $amount);
 
 914   my $str_places = max(min(10, 16 - length("$int_amount") - $places), $places);
 
 915   my $amount_str = sprintf '%.*f', $places + $str_places, abs($amount);
 
 917   return $amount unless $amount_str =~ m{^(\d+)\.(\d+)$};
 
 919   my ($pre, $post)      = ($1, $2);
 
 920   my $decimals          = '1' . substr($post, 0, $places);
 
 922   my $propagation_limit = $Config{i32size} == 4 ? 7 : 18;
 
 923   my $add_for_rounding  = substr($post, $places, 1) >= 5 ? 1 : 0;
 
 925   if ($places > $propagation_limit) {
 
 926     $decimals = Math::BigInt->new($decimals)->badd($add_for_rounding);
 
 927     $pre      = Math::BigInt->new($decimals)->badd(1) if substr($decimals, 0, 1) eq '2';
 
 930     $decimals += $add_for_rounding;
 
 931     $pre      += 1 if substr($decimals, 0, 1) eq '2';
 
 934   $amount  = ("${pre}." . substr($decimals, 1)) * ($amount <=> 0);
 
 940   $main::lxdebug->enter_sub();
 
 942   my ($self, $myconfig) = @_;
 
 943   my ($out, $out_mode);
 
 947   my $defaults  = SL::DB::Default->get;
 
 948   my $userspath = $::lx_office_conf{paths}->{userspath};
 
 950   $self->{"cwd"} = getcwd();
 
 951   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
 
 956   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
 
 957     $template_type  = 'OpenDocument';
 
 958     $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
 
 960   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
 
 961     $template_type    = 'LaTeX';
 
 962     $ext_for_format   = 'pdf';
 
 964   } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
 
 965     $template_type  = 'HTML';
 
 966     $ext_for_format = 'html';
 
 968   } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
 
 969     $template_type  = 'XML';
 
 970     $ext_for_format = 'xml';
 
 972   } elsif ( $self->{"format"} =~ /elster(?:winston|taxbird)/i ) {
 
 973     $template_type = 'XML';
 
 975   } elsif ( $self->{"format"} =~ /excel/i ) {
 
 976     $template_type  = 'Excel';
 
 977     $ext_for_format = 'xls';
 
 979   } elsif ( defined $self->{'format'}) {
 
 980     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
 
 982   } elsif ( $self->{'format'} eq '' ) {
 
 983     $self->error("No Outputformat given: $self->{'format'}");
 
 985   } else { #Catch the rest
 
 986     $self->error("Outputformat not defined: $self->{'format'}");
 
 989   my $template = SL::Template::create(type      => $template_type,
 
 990                                       file_name => $self->{IN},
 
 992                                       myconfig  => $myconfig,
 
 993                                       userspath => $userspath,
 
 994                                       %{ $self->{TEMPLATE_DRIVER_OPTIONS} || {} });
 
 996   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
 
 997   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" } if exists $self->{ $self->{"formname"} . "notes" };
 
 999   if (!$self->{employee_id}) {
 
1000     $self->{"employee_${_}"} = $myconfig->{$_} for qw(email tel fax name signature);
 
1001     $self->{"employee_${_}"} = $defaults->$_   for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
 
1004   $self->{"myconfig_${_}"} = $myconfig->{$_} for grep { $_ ne 'dbpasswd' } keys %{ $myconfig };
 
1005   $self->{$_}              = $defaults->$_   for qw(co_ustid);
 
1006   $self->{"myconfig_${_}"} = $defaults->$_   for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
 
1007   $self->{AUTH}            = $::auth;
 
1008   $self->{INSTANCE_CONF}   = $::instance_conf;
 
1009   $self->{LOCALE}          = $::locale;
 
1010   $self->{LXCONFIG}        = $::lx_office_conf;
 
1011   $self->{LXDEBUG}         = $::lxdebug;
 
1012   $self->{MYCONFIG}        = \%::myconfig;
 
1014   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
 
1016   # OUT is used for the media, screen, printer, email
 
1017   # for postscript we store a copy in a temporary file
 
1018   my $keep_temp_files = $::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files};
 
1020   my ($temp_fh, $suffix);
 
1021   $suffix =  $self->{IN};
 
1022   $suffix =~ s/.*\.//;
 
1023   ($temp_fh, $self->{tmpfile}) = File::Temp::tempfile(
 
1024     strftime('kivitendo-print-%Y%m%d%H%M%S-XXXXXX', localtime()),
 
1025     SUFFIX => '.' . ($suffix || 'tex'),
 
1027     UNLINK => $keep_temp_files ? 0 : 1,
 
1030   chmod 0644, $self->{tmpfile} if $keep_temp_files;
 
1031   (undef, undef, $self->{template_meta}{tmpfile}) = File::Spec->splitpath( $self->{tmpfile} );
 
1033   $out              = $self->{OUT};
 
1034   $out_mode         = $self->{OUT_MODE} || '>';
 
1035   $self->{OUT}      = "$self->{tmpfile}";
 
1036   $self->{OUT_MODE} = '>';
 
1039   my $command_formatter = sub {
 
1040     my ($out_mode, $out) = @_;
 
1041     return $out_mode eq '|-' ? SL::Template::create(type => 'ShellCommand', form => $self)->parse($out) : $out;
 
1045     $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
 
1046     open(OUT, $self->{OUT_MODE}, $self->{OUT}) or $self->error("error on opening $self->{OUT} with mode $self->{OUT_MODE} : $!");
 
1048     *OUT = ($::dispatcher->get_standard_filehandles)[1];
 
1052   if (!$template->parse(*OUT)) {
 
1054     $self->error("$self->{IN} : " . $template->get_error());
 
1057   close OUT if $self->{OUT};
 
1058   # check only one flag (webdav_documents)
 
1059   # therefore copy to webdav, even if we do not have the webdav feature enabled (just archive)
 
1060   my $copy_to_webdav =  $::instance_conf->get_webdav_documents && !$self->{preview} && $self->{tmpdir} && $self->{tmpfile} && $self->{type}
 
1061                         && $self->{type} ne 'statement';
 
1062   if ( $ext_for_format eq 'pdf' && $self->doc_storage_enabled ) {
 
1063     $self->append_general_pdf_attachments(filepath =>  $self->{tmpdir}."/".$self->{tmpfile},
 
1064                                           type     =>  $self->{type});
 
1066   if ($self->{media} eq 'file') {
 
1067     copy(join('/', $self->{cwd}, $userspath, $self->{tmpfile}), $out =~ m|^/| ? $out : join('/', $self->{cwd}, $out)) if $template->uses_temp_file;
 
1068     Common::copy_file_to_webdav_folder($self)                                                                         if $copy_to_webdav;
 
1069     if (!$self->{preview} && $self->doc_storage_enabled)
 
1071       $self->{attachment_filename} ||= $self->generate_attachment_filename;
 
1072       $self->store_pdf($self);
 
1075     chdir("$self->{cwd}");
 
1077     $::lxdebug->leave_sub();
 
1082   Common::copy_file_to_webdav_folder($self) if $copy_to_webdav;
 
1084   if ( !$self->{preview} && $ext_for_format eq 'pdf' && $self->doc_storage_enabled) {
 
1085     $self->{attachment_filename} ||= $self->generate_attachment_filename;
 
1086     my $file_obj = $self->store_pdf($self);
 
1087     $self->{print_file_id} = $file_obj->id if $file_obj;
 
1089   if ($self->{media} eq 'email') {
 
1090     if ( getcwd() eq $self->{"tmpdir"} ) {
 
1091       # in the case of generating pdf we are in the tmpdir, but WHY ???
 
1092       $self->{tmpfile} = $userspath."/".$self->{tmpfile};
 
1093       chdir("$self->{cwd}");
 
1095     $self->send_email(\%::myconfig,$ext_for_format);
 
1098     $self->{OUT}      = $out;
 
1099     $self->{OUT_MODE} = $out_mode;
 
1100     $self->output_file($template->get_mime_type,$command_formatter);
 
1102   delete $self->{print_file_id};
 
1106   chdir("$self->{cwd}");
 
1107   $main::lxdebug->leave_sub();
 
1110 sub get_bcc_defaults {
 
1111   my ($self, $myconfig, $mybcc) = @_;
 
1112   if (SL::DB::Default->get->bcc_to_login) {
 
1113     $mybcc .= ", " if $mybcc;
 
1114     $mybcc .= $myconfig->{email};
 
1116   my $otherbcc = SL::DB::Default->get->global_bcc;
 
1118     $mybcc .= ", " if $mybcc;
 
1119     $mybcc .= $otherbcc;
 
1125   $main::lxdebug->enter_sub();
 
1126   my ($self, $myconfig, $ext_for_format) = @_;
 
1127   my $mail = Mailer->new;
 
1129   map { $mail->{$_} = $self->{$_} }
 
1130     qw(cc subject message format);
 
1132   $mail->{bcc}    = $self->get_bcc_defaults($myconfig, $self->{bcc});
 
1133   $mail->{to}     = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
 
1134   $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
 
1135   $mail->{fileid} = time() . '.' . $$ . '.';
 
1136   my $full_signature     =  $self->create_email_signature();
 
1137   $full_signature        =~ s/\r//g;
 
1139   $mail->{attachments} =  [];
 
1141   # if we send html or plain text inline
 
1142   if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
 
1143     $mail->{contenttype}    =  "text/html";
 
1144     $mail->{message}        =~ s/\r//g;
 
1145     $mail->{message}        =~ s/\n/<br>\n/g;
 
1146     $full_signature         =~ s/\n/<br>\n/g;
 
1147     $mail->{message}       .=  $full_signature;
 
1149     open(IN, "<", $self->{tmpfile})
 
1150       or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1151     $mail->{message} .= $_ while <IN>;
 
1154   } elsif (($self->{attachment_policy} // '') ne 'no_file') {
 
1155     my $attachment_name  =  $self->{attachment_filename}  || $self->{tmpfile};
 
1156     $attachment_name     =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
 
1158     if (($self->{attachment_policy} // '') eq 'old_file') {
 
1159       my ( $attfile ) = SL::File->get_all(object_id   => $self->{id},
 
1160                                           object_type => $self->{formname},
 
1161                                           file_type   => 'document');
 
1164         $attfile->{override_file_name} = $attachment_name if $attachment_name;
 
1165         push @attfiles, $attfile;
 
1169       push @{ $mail->{attachments} }, { path => $self->{tmpfile},
 
1170                                         id   => $self->{print_file_id},
 
1171                                         type => "application/pdf",
 
1172                                         name => $attachment_name };
 
1178     map  { SL::File->get(id => $_) }
 
1179     @{ $self->{attach_file_ids} // [] };
 
1181   foreach my $attfile ( @attfiles ) {
 
1182     push @{ $mail->{attachments} }, {
 
1183       path    => $attfile->get_file,
 
1185       type    => $attfile->mime_type,
 
1186       name    => $attfile->{override_file_name} // $attfile->file_name,
 
1187       content => $attfile->get_content ? ${ $attfile->get_content } : undef,
 
1191   $mail->{message}  =~ s/\r//g;
 
1192   $mail->{message} .= $full_signature;
 
1193   $self->{emailerr} = $mail->send();
 
1195   if ($self->{emailerr}) {
 
1197     $self->error($::locale->text('The email was not sent due to the following error: #1.', $self->{emailerr}));
 
1200   $self->{email_journal_id} = $mail->{journalentry};
 
1201   $self->{snumbers}  = "emailjournal" . "_" . $self->{email_journal_id};
 
1202   $self->{what_done} = $::form->{type};
 
1203   $self->{addition}  = "MAILED";
 
1204   $self->save_history;
 
1206   #write back for message info and mail journal
 
1207   $self->{cc}  = $mail->{cc};
 
1208   $self->{bcc} = $mail->{bcc};
 
1209   $self->{email} = $mail->{to};
 
1211   $main::lxdebug->leave_sub();
 
1215   $main::lxdebug->enter_sub();
 
1217   my ($self,$mimeType,$command_formatter) = @_;
 
1218   my $numbytes = (-s $self->{tmpfile});
 
1219   open(IN, "<", $self->{tmpfile})
 
1220     or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1223   $self->{copies} = 1 unless $self->{media} eq 'printer';
 
1225   chdir("$self->{cwd}");
 
1226   for my $i (1 .. $self->{copies}) {
 
1228       $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
 
1230       open  OUT, $self->{OUT_MODE}, $self->{OUT} or $self->error($self->cleanup . "$self->{OUT} : $!");
 
1231       print OUT $_ while <IN>;
 
1236       my %headers = ('-type'       => $mimeType,
 
1237                      '-connection' => 'close',
 
1238                      '-charset'    => 'UTF-8');
 
1240       $self->{attachment_filename} ||= $self->generate_attachment_filename;
 
1242       if ($self->{attachment_filename}) {
 
1245           '-attachment'     => $self->{attachment_filename},
 
1246           '-content-length' => $numbytes,
 
1251       print $::request->cgi->header(%headers);
 
1253       $::locale->with_raw_io(\*STDOUT, sub { print while <IN> });
 
1257   $main::lxdebug->leave_sub();
 
1260 sub get_formname_translation {
 
1261   $main::lxdebug->enter_sub();
 
1262   my ($self, $formname) = @_;
 
1264   $formname ||= $self->{formname};
 
1266   $self->{recipient_locale} ||=  Locale->lang_to_locale($self->{language});
 
1267   local $::locale = Locale->new($self->{recipient_locale});
 
1269   my %formname_translations = (
 
1270     bin_list                => $main::locale->text('Bin List'),
 
1271     credit_note             => $main::locale->text('Credit Note'),
 
1272     invoice                 => $main::locale->text('Invoice'),
 
1273     pick_list               => $main::locale->text('Pick List'),
 
1274     proforma                => $main::locale->text('Proforma Invoice'),
 
1275     purchase_order          => $main::locale->text('Purchase Order'),
 
1276     request_quotation       => $main::locale->text('RFQ'),
 
1277     sales_order             => $main::locale->text('Confirmation'),
 
1278     sales_quotation         => $main::locale->text('Quotation'),
 
1279     storno_invoice          => $main::locale->text('Storno Invoice'),
 
1280     sales_delivery_order    => $main::locale->text('Delivery Order'),
 
1281     purchase_delivery_order => $main::locale->text('Delivery Order'),
 
1282     dunning                 => $main::locale->text('Dunning'),
 
1283     dunning1                => $main::locale->text('Payment Reminder'),
 
1284     dunning2                => $main::locale->text('Dunning'),
 
1285     dunning3                => $main::locale->text('Last Dunning'),
 
1286     dunning_invoice         => $main::locale->text('Dunning Invoice'),
 
1287     letter                  => $main::locale->text('Letter'),
 
1288     ic_supply               => $main::locale->text('Intra-Community supply'),
 
1289     statement               => $main::locale->text('Statement'),
 
1292   $main::lxdebug->leave_sub();
 
1293   return $formname_translations{$formname};
 
1296 sub get_number_prefix_for_type {
 
1297   $main::lxdebug->enter_sub();
 
1301       (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
 
1302     : ($self->{type} =~ /_quotation$/)                        ? 'quo'
 
1303     : ($self->{type} =~ /_delivery_order$/)                   ? 'do'
 
1304     : ($self->{type} =~ /letter/)                             ? 'letter'
 
1307   # better default like this?
 
1308   # : ($self->{type} =~ /(sales|purcharse)_order/           :  'ord';
 
1309   # :                                                           'prefix_undefined';
 
1311   $main::lxdebug->leave_sub();
 
1315 sub get_extension_for_format {
 
1316   $main::lxdebug->enter_sub();
 
1319   my $extension = $self->{format} =~ /pdf/i          ? ".pdf"
 
1320                 : $self->{format} =~ /postscript/i   ? ".ps"
 
1321                 : $self->{format} =~ /opendocument/i ? ".odt"
 
1322                 : $self->{format} =~ /excel/i        ? ".xls"
 
1323                 : $self->{format} =~ /html/i         ? ".html"
 
1326   $main::lxdebug->leave_sub();
 
1330 sub generate_attachment_filename {
 
1331   $main::lxdebug->enter_sub();
 
1334   $self->{recipient_locale} ||=  Locale->lang_to_locale($self->{language});
 
1335   my $recipient_locale = Locale->new($self->{recipient_locale});
 
1337   my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
 
1338   my $prefix              = $self->get_number_prefix_for_type();
 
1340   if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
 
1341     $attachment_filename .= ' (' . $recipient_locale->text('Preview') . ')' . $self->get_extension_for_format();
 
1343   } elsif ($attachment_filename && $self->{"${prefix}number"}) {
 
1344     $attachment_filename .=  "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
 
1346   } elsif ($attachment_filename) {
 
1347     $attachment_filename .=  $self->get_extension_for_format();
 
1350     $attachment_filename = "";
 
1353   $attachment_filename =  $main::locale->quote_special_chars('filenames', $attachment_filename);
 
1354   $attachment_filename =~ s|[\s/\\]+|_|g;
 
1356   $main::lxdebug->leave_sub();
 
1357   return $attachment_filename;
 
1360 sub generate_email_subject {
 
1361   $main::lxdebug->enter_sub();
 
1364   my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
 
1365   my $prefix  = $self->get_number_prefix_for_type();
 
1367   if ($subject && $self->{"${prefix}number"}) {
 
1368     $subject .= " " . $self->{"${prefix}number"}
 
1371   $main::lxdebug->leave_sub();
 
1375 sub generate_email_body {
 
1376   $main::lxdebug->enter_sub();
 
1378   # simple german and english will work grammatically (most european languages as well)
 
1379   # Dear Mr Alan Greenspan:
 
1380   # Sehr geehrte Frau Meyer,
 
1381   # A l’attention de Mme Villeroy,
 
1382   # Gentile Signora Ferrari,
 
1385   if ($self->{cp_id}) {
 
1386     my $givenname = SL::DB::Contact->load_cached($self->{cp_id})->cp_givenname; # for qw(gender givename name);
 
1387     my $name      = SL::DB::Contact->load_cached($self->{cp_id})->cp_name; # for qw(gender givename name);
 
1388     my $gender    = SL::DB::Contact->load_cached($self->{cp_id})->cp_gender; # for qw(gender givename name);
 
1389     my $mf = $gender eq 'f' ? 'female' : 'male';
 
1390     $body  = GenericTranslations->get(translation_type => "salutation_$mf", language_id => $self->{language_id});
 
1391     $body .= ' ' . $givenname . ' ' . $name if $body;
 
1393     $body  = GenericTranslations->get(translation_type => "salutation_general", language_id => $self->{language_id});
 
1396   return undef unless $body;
 
1398   $body   .= GenericTranslations->get(translation_type =>"salutation_punctuation_mark", language_id => $self->{language_id}) . "\n";
 
1399   $body   .= GenericTranslations->get(translation_type =>"preset_text_$self->{formname}", language_id => $self->{language_id});
 
1401   $body = $main::locale->unquote_special_chars('HTML', $body);
 
1403   $main::lxdebug->leave_sub();
 
1408   $main::lxdebug->enter_sub();
 
1410   my ($self, $application) = @_;
 
1412   my $error_code = $?;
 
1414   chdir("$self->{tmpdir}");
 
1417   if ((-1 == $error_code) || (127 == (($error_code) >> 8))) {
 
1418     push @err, $::locale->text('The application "#1" was not found on the system.', $application || 'pdflatex') . ' ' . $::locale->text('Please contact your administrator.');
 
1420   } elsif (-f "$self->{tmpfile}.err") {
 
1421     open(FH, "<:encoding(UTF-8)", "$self->{tmpfile}.err");
 
1426   if ($self->{tmpfile} && !($::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files})) {
 
1427     $self->{tmpfile} =~ s|.*/||g;
 
1429     $self->{tmpfile} =~ s/\.\w+$//g;
 
1430     my $tmpfile = $self->{tmpfile};
 
1431     unlink(<$tmpfile.*>);
 
1434   chdir("$self->{cwd}");
 
1436   $main::lxdebug->leave_sub();
 
1442   $main::lxdebug->enter_sub();
 
1444   my ($self, $date, $myconfig) = @_;
 
1447   if ($date && $date =~ /\D/) {
 
1449     if ($myconfig->{dateformat} =~ /^yy/) {
 
1450       ($yy, $mm, $dd) = split /\D/, $date;
 
1452     if ($myconfig->{dateformat} =~ /^mm/) {
 
1453       ($mm, $dd, $yy) = split /\D/, $date;
 
1455     if ($myconfig->{dateformat} =~ /^dd/) {
 
1456       ($dd, $mm, $yy) = split /\D/, $date;
 
1461     $yy = ($yy < 70) ? $yy + 2000 : $yy;
 
1462     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
 
1464     $dd = "0$dd" if ($dd < 10);
 
1465     $mm = "0$mm" if ($mm < 10);
 
1467     $date = "$yy$mm$dd";
 
1470   $main::lxdebug->leave_sub();
 
1475 # Database routines used throughout
 
1476 # DB Handling got moved to SL::DB, these are only shims for compatibility
 
1479   SL::DB->client->dbh;
 
1482 sub get_standard_dbh {
 
1483   my $dbh = SL::DB->client->dbh;
 
1485   if ($dbh && !$dbh->{Active}) {
 
1486     $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$dbh is defined but not Active anymore");
 
1487     SL::DB->client->dbh(undef);
 
1490   SL::DB->client->dbh;
 
1493 sub disconnect_standard_dbh {
 
1494   SL::DB->client->dbh->rollback;
 
1500   $main::lxdebug->enter_sub();
 
1502   my ($self, $date, $myconfig) = @_;
 
1503   my $dbh = $self->get_standard_dbh;
 
1505   my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
 
1506   my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
 
1508   # Falls $date = '' - Fehlermeldung aus der Datenbank. Ich denke,
 
1509   # es ist sicher ein conv_date vorher IMMER auszuführen.
 
1510   # Testfälle ohne definiertes closedto:
 
1511   #   Leere Datumseingabe i.O.
 
1512   #     SELECT 1 FROM defaults WHERE '' < closedto
 
1513   #   normale Zahlungsbuchung über Rechnungsmaske i.O.
 
1514   #     SELECT 1 FROM defaults WHERE '10.05.2011' < closedto
 
1515   # Testfälle mit definiertem closedto (30.04.2011):
 
1516   #  Leere Datumseingabe i.O.
 
1517   #   SELECT 1 FROM defaults WHERE '' < closedto
 
1518   # normale Buchung im geschloßenem Zeitraum i.O.
 
1519   #   SELECT 1 FROM defaults WHERE '21.04.2011' < closedto
 
1520   #     Fehlermeldung: Es können keine Zahlungen für abgeschlossene Bücher gebucht werden!
 
1521   # normale Buchung in aktiver Buchungsperiode i.O.
 
1522   #   SELECT 1 FROM defaults WHERE '01.05.2011' < closedto
 
1524   my ($closed) = $sth->fetchrow_array;
 
1526   $main::lxdebug->leave_sub();
 
1531 # prevents bookings to the to far away future
 
1532 sub date_max_future {
 
1533   $main::lxdebug->enter_sub();
 
1535   my ($self, $date, $myconfig) = @_;
 
1536   my $dbh = $self->get_standard_dbh;
 
1538   my $query = "SELECT 1 FROM defaults WHERE ? - current_date > max_future_booking_interval";
 
1539   my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
 
1541   my ($max_future_booking_interval) = $sth->fetchrow_array;
 
1543   $main::lxdebug->leave_sub();
 
1545   return $max_future_booking_interval;
 
1549 sub update_balance {
 
1550   $main::lxdebug->enter_sub();
 
1552   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
 
1554   # if we have a value, go do it
 
1557     # retrieve balance from table
 
1558     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
 
1559     my $sth = prepare_execute_query($self, $dbh, $query, @values);
 
1560     my ($balance) = $sth->fetchrow_array;
 
1566     $query = "UPDATE $table SET $field = $balance WHERE $where";
 
1567     do_query($self, $dbh, $query, @values);
 
1569   $main::lxdebug->leave_sub();
 
1572 sub update_exchangerate {
 
1573   $main::lxdebug->enter_sub();
 
1575   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
 
1577   # some sanity check for currency
 
1579     $main::lxdebug->leave_sub();
 
1582   $query = qq|SELECT name AS curr FROM currencies WHERE id=(SELECT currency_id FROM defaults)|;
 
1584   my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
 
1586   if ($curr eq $defaultcurrency) {
 
1587     $main::lxdebug->leave_sub();
 
1591   $query = qq|SELECT e.currency_id FROM exchangerate e
 
1592                  WHERE e.currency_id = (SELECT cu.id FROM currencies cu WHERE cu.name=?) AND e.transdate = ?
 
1594   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
 
1603   $buy = conv_i($buy, "NULL");
 
1604   $sell = conv_i($sell, "NULL");
 
1607   if ($buy != 0 && $sell != 0) {
 
1608     $set = "buy = $buy, sell = $sell";
 
1609   } elsif ($buy != 0) {
 
1610     $set = "buy = $buy";
 
1611   } elsif ($sell != 0) {
 
1612     $set = "sell = $sell";
 
1615   if ($sth->fetchrow_array) {
 
1616     $query = qq|UPDATE exchangerate
 
1618                 WHERE currency_id = (SELECT id FROM currencies WHERE name = ?)
 
1622     $query = qq|INSERT INTO exchangerate (currency_id, buy, sell, transdate)
 
1623                 VALUES ((SELECT id FROM currencies WHERE name = ?), $buy, $sell, ?)|;
 
1626   do_query($self, $dbh, $query, $curr, $transdate);
 
1628   $main::lxdebug->leave_sub();
 
1631 sub save_exchangerate {
 
1632   $main::lxdebug->enter_sub();
 
1634   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
 
1636   SL::DB->client->with_transaction(sub {
 
1637     my $dbh = SL::DB->client->dbh;
 
1641     $buy  = $rate if $fld eq 'buy';
 
1642     $sell = $rate if $fld eq 'sell';
 
1645     $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
 
1647   }) or do { die SL::DB->client->error };
 
1649   $main::lxdebug->leave_sub();
 
1652 sub get_exchangerate {
 
1653   $main::lxdebug->enter_sub();
 
1655   my ($self, $dbh, $curr, $transdate, $fld) = @_;
 
1658   unless ($transdate && $curr) {
 
1659     $main::lxdebug->leave_sub();
 
1663   $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
 
1665   my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
 
1667   if ($curr eq $defaultcurrency) {
 
1668     $main::lxdebug->leave_sub();
 
1672   $query = qq|SELECT e.$fld FROM exchangerate e
 
1673                  WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
 
1674   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
 
1678   $main::lxdebug->leave_sub();
 
1680   return $exchangerate;
 
1683 sub check_exchangerate {
 
1684   $main::lxdebug->enter_sub();
 
1686   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
 
1688   if ($fld !~/^buy|sell$/) {
 
1689     $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
 
1692   unless ($transdate) {
 
1693     $main::lxdebug->leave_sub();
 
1697   my ($defaultcurrency) = $self->get_default_currency($myconfig);
 
1699   if ($currency eq $defaultcurrency) {
 
1700     $main::lxdebug->leave_sub();
 
1704   my $dbh   = $self->get_standard_dbh($myconfig);
 
1705   my $query = qq|SELECT e.$fld FROM exchangerate e
 
1706                  WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
 
1708   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
 
1710   $main::lxdebug->leave_sub();
 
1712   return $exchangerate;
 
1715 sub get_all_currencies {
 
1716   $main::lxdebug->enter_sub();
 
1719   my $myconfig = shift || \%::myconfig;
 
1720   my $dbh      = $self->get_standard_dbh($myconfig);
 
1722   my $query = qq|SELECT name FROM currencies|;
 
1723   my @currencies = map { $_->{name} } selectall_hashref_query($self, $dbh, $query);
 
1725   $main::lxdebug->leave_sub();
 
1730 sub get_default_currency {
 
1731   $main::lxdebug->enter_sub();
 
1733   my ($self, $myconfig) = @_;
 
1734   my $dbh      = $self->get_standard_dbh($myconfig);
 
1735   my $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
 
1737   my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
 
1739   $main::lxdebug->leave_sub();
 
1741   return $defaultcurrency;
 
1744 sub set_payment_options {
 
1745   my ($self, $myconfig, $transdate, $type) = @_;
 
1747   my $terms = $self->{payment_id} ? SL::DB::PaymentTerm->new(id => $self->{payment_id})->load : undef;
 
1750   my $is_invoice                = $type =~ m{invoice}i;
 
1752   $transdate                  ||= $self->{invdate} || $self->{transdate};
 
1753   my $due_date                  = $self->{duedate} || $self->{reqdate};
 
1755   $self->{$_}                   = $terms->$_ for qw(terms_netto terms_skonto percent_skonto);
 
1756   $self->{payment_description}  = $terms->description;
 
1757   $self->{netto_date}           = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'net')->to_kivitendo;
 
1758   $self->{skonto_date}          = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'discount')->to_kivitendo;
 
1760   my ($invtotal, $total);
 
1761   my (%amounts, %formatted_amounts);
 
1763   if ($self->{type} =~ /_order$/) {
 
1764     $amounts{invtotal} = $self->{ordtotal};
 
1765     $amounts{total}    = $self->{ordtotal};
 
1767   } elsif ($self->{type} =~ /_quotation$/) {
 
1768     $amounts{invtotal} = $self->{quototal};
 
1769     $amounts{total}    = $self->{quototal};
 
1772     $amounts{invtotal} = $self->{invtotal};
 
1773     $amounts{total}    = $self->{total};
 
1775   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
 
1777   $amounts{skonto_in_percent}  = 100.0 * $self->{percent_skonto};
 
1778   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
 
1779   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
 
1780   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
 
1782   foreach (keys %amounts) {
 
1783     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
 
1784     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
 
1787   if ($self->{"language_id"}) {
 
1788     my $language             = SL::DB::Language->new(id => $self->{language_id})->load;
 
1790     $self->{payment_terms}   = $type =~ m{invoice}i ? $terms->translated_attribute('description_long_invoice', $language->id) : undef;
 
1791     $self->{payment_terms} ||= $terms->translated_attribute('description_long', $language->id);
 
1793     if ($language->output_dateformat) {
 
1794       foreach my $key (qw(netto_date skonto_date)) {
 
1795         $self->{$key} = $::locale->reformat_date($myconfig, $self->{$key}, $language->output_dateformat, $language->output_longdates);
 
1799     if ($language->output_numberformat && ($language->output_numberformat ne $myconfig->{numberformat})) {
 
1800       local $myconfig->{numberformat};
 
1801       $myconfig->{"numberformat"} = $language->output_numberformat;
 
1802       $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) for keys %amounts;
 
1806   $self->{payment_terms} =  $self->{payment_terms} || ($is_invoice ? $terms->description_long_invoice : undef) || $terms->description_long;
 
1808   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
 
1809   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
 
1810   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
 
1811   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
 
1812   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
 
1813   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
 
1814   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
 
1815   $self->{payment_terms} =~ s/<\%bic\%>/$self->{bic}/g;
 
1816   $self->{payment_terms} =~ s/<\%iban\%>/$self->{iban}/g;
 
1817   $self->{payment_terms} =~ s/<\%mandate_date_of_signature\%>/$self->{mandate_date_of_signature}/g;
 
1818   $self->{payment_terms} =~ s/<\%mandator_id\%>/$self->{mandator_id}/g;
 
1820   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
 
1822   $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
 
1826 sub get_template_language {
 
1827   $main::lxdebug->enter_sub();
 
1829   my ($self, $myconfig) = @_;
 
1831   my $template_code = "";
 
1833   if ($self->{language_id}) {
 
1834     my $dbh = $self->get_standard_dbh($myconfig);
 
1835     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
 
1836     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
 
1839   $main::lxdebug->leave_sub();
 
1841   return $template_code;
 
1844 sub get_printer_code {
 
1845   $main::lxdebug->enter_sub();
 
1847   my ($self, $myconfig) = @_;
 
1849   my $template_code = "";
 
1851   if ($self->{printer_id}) {
 
1852     my $dbh = $self->get_standard_dbh($myconfig);
 
1853     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
 
1854     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
 
1857   $main::lxdebug->leave_sub();
 
1859   return $template_code;
 
1863   $main::lxdebug->enter_sub();
 
1865   my ($self, $myconfig) = @_;
 
1867   my $template_code = "";
 
1869   if ($self->{shipto_id}) {
 
1870     my $dbh = $self->get_standard_dbh($myconfig);
 
1871     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
 
1872     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
 
1873     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
 
1875     my $cvars = CVar->get_custom_variables(
 
1878       trans_id => $self->{shipto_id},
 
1880     $self->{"shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
 
1883   $main::lxdebug->leave_sub();
 
1887   my ($self, $dbh, $id, $module) = @_;
 
1892   foreach my $item (qw(name department_1 department_2 street zipcode city country gln
 
1893                        contact cp_gender phone fax email)) {
 
1894     if ($self->{"shipto$item"}) {
 
1895       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
 
1897     push(@values, $self->{"shipto${item}"});
 
1902   my $shipto_id = $self->{shipto_id};
 
1904   if ($self->{shipto_id}) {
 
1905     my $query = qq|UPDATE shipto set
 
1907                      shiptodepartment_1 = ?,
 
1908                      shiptodepartment_2 = ?,
 
1915                      shiptocp_gender = ?,
 
1919                    WHERE shipto_id = ?|;
 
1920     do_query($self, $dbh, $query, @values, $self->{shipto_id});
 
1922     my $query = qq|SELECT * FROM shipto
 
1923                    WHERE shiptoname = ? AND
 
1924                      shiptodepartment_1 = ? AND
 
1925                      shiptodepartment_2 = ? AND
 
1926                      shiptostreet = ? AND
 
1927                      shiptozipcode = ? AND
 
1929                      shiptocountry = ? AND
 
1931                      shiptocontact = ? AND
 
1932                      shiptocp_gender = ? AND
 
1938     my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
 
1941         qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
 
1942                                shiptostreet, shiptozipcode, shiptocity, shiptocountry, shiptogln,
 
1943                                shiptocontact, shiptocp_gender, shiptophone, shiptofax, shiptoemail, module)
 
1944            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
 
1945       do_query($self, $dbh, $insert_query, $id, @values, $module);
 
1947       $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
 
1950     $shipto_id = $insert_check->{shipto_id};
 
1953   return unless $shipto_id;
 
1955   CVar->save_custom_variables(
 
1958     trans_id    => $shipto_id,
 
1960     name_prefix => 'shipto',
 
1965   $main::lxdebug->enter_sub();
 
1967   my ($self, $dbh) = @_;
 
1969   $dbh ||= $self->get_standard_dbh(\%main::myconfig);
 
1971   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
 
1972   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
 
1973   $self->{"employee_id"} *= 1;
 
1975   $main::lxdebug->leave_sub();
 
1978 sub get_employee_data {
 
1979   $main::lxdebug->enter_sub();
 
1983   my $defaults = SL::DB::Default->get;
 
1985   Common::check_params(\%params, qw(prefix));
 
1986   Common::check_params_x(\%params, qw(id));
 
1989     $main::lxdebug->leave_sub();
 
1993   my $myconfig = \%main::myconfig;
 
1994   my $dbh      = $params{dbh} || $self->get_standard_dbh($myconfig);
 
1996   my ($login, $deleted)  = selectrow_query($self, $dbh, qq|SELECT login,deleted FROM employee WHERE id = ?|, conv_i($params{id}));
 
1999     # login already fetched and still the same client (mandant) | same for both cases (delete|!delete)
 
2000     $self->{$params{prefix} . '_login'}   = $login;
 
2001     $self->{$params{prefix} . "_${_}"}    = $defaults->$_ for qw(address businessnumber co_ustid company duns taxnumber);
 
2004       # get employee data from auth.user_config
 
2005       my $user = User->new(login => $login);
 
2006       $self->{$params{prefix} . "_${_}"} = $user->{$_} for qw(email fax name signature tel);
 
2008       # get saved employee data from employee
 
2009       my $employee = SL::DB::Manager::Employee->find_by(id => conv_i($params{id}));
 
2010       $self->{$params{prefix} . "_${_}"} = $employee->{"deleted_$_"} for qw(email fax signature tel);
 
2011       $self->{$params{prefix} . "_name"} = $employee->name;
 
2014   $main::lxdebug->leave_sub();
 
2018   $main::lxdebug->enter_sub();
 
2020   my ($self, $dbh, $id, $key) = @_;
 
2022   $key = "all_contacts" unless ($key);
 
2026     $main::lxdebug->leave_sub();
 
2031     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
 
2032     qq|FROM contacts | .
 
2033     qq|WHERE cp_cv_id = ? | .
 
2034     qq|ORDER BY lower(cp_name)|;
 
2036   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
 
2038   $main::lxdebug->leave_sub();
 
2042   $main::lxdebug->enter_sub();
 
2044   my ($self, $dbh, $key) = @_;
 
2046   my ($all, $old_id, $where, @values);
 
2048   if (ref($key) eq "HASH") {
 
2051     $key = "ALL_PROJECTS";
 
2053     foreach my $p (keys(%{$params})) {
 
2055         $all = $params->{$p};
 
2056       } elsif ($p eq "old_id") {
 
2057         $old_id = $params->{$p};
 
2058       } elsif ($p eq "key") {
 
2059         $key = $params->{$p};
 
2065     $where = "WHERE active ";
 
2067       if (ref($old_id) eq "ARRAY") {
 
2068         my @ids = grep({ $_ } @{$old_id});
 
2070           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
 
2071           push(@values, @ids);
 
2074         $where .= " OR (id = ?) ";
 
2075         push(@values, $old_id);
 
2081     qq|SELECT id, projectnumber, description, active | .
 
2084     qq|ORDER BY lower(projectnumber)|;
 
2086   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
 
2088   $main::lxdebug->leave_sub();
 
2092   $main::lxdebug->enter_sub();
 
2094   my ($self, $dbh, $vc_id, $key) = @_;
 
2096   $key = "all_shipto" unless ($key);
 
2099     # get shipping addresses
 
2100     my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
 
2102     $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
 
2108   $main::lxdebug->leave_sub();
 
2112   $main::lxdebug->enter_sub();
 
2114   my ($self, $dbh, $key) = @_;
 
2116   $key = "all_printers" unless ($key);
 
2118   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
 
2120   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2122   $main::lxdebug->leave_sub();
 
2126   $main::lxdebug->enter_sub();
 
2128   my ($self, $dbh, $params) = @_;
 
2131   $key = $params->{key};
 
2132   $key = "all_charts" unless ($key);
 
2134   my $transdate = quote_db_date($params->{transdate});
 
2137     qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
 
2139     qq|LEFT JOIN taxkeys tk ON | .
 
2140     qq|(tk.id = (SELECT id FROM taxkeys | .
 
2141     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
 
2142     qq|          ORDER BY startdate DESC LIMIT 1)) | .
 
2143     qq|ORDER BY c.accno|;
 
2145   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2147   $main::lxdebug->leave_sub();
 
2150 sub _get_taxcharts {
 
2151   $main::lxdebug->enter_sub();
 
2153   my ($self, $dbh, $params) = @_;
 
2155   my $key = "all_taxcharts";
 
2158   if (ref $params eq 'HASH') {
 
2159     $key = $params->{key} if ($params->{key});
 
2160     if ($params->{module} eq 'AR') {
 
2161       push @where, 'chart_categories ~ \'[ACILQ]\'';
 
2163     } elsif ($params->{module} eq 'AP') {
 
2164       push @where, 'chart_categories ~ \'[ACELQ]\'';
 
2171   my $where = @where ? ' WHERE ' . join(' AND ', map { "($_)" } @where) : '';
 
2173   my $query = qq|SELECT * FROM tax $where ORDER BY taxkey, rate|;
 
2175   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2177   $main::lxdebug->leave_sub();
 
2181   $main::lxdebug->enter_sub();
 
2183   my ($self, $dbh, $key) = @_;
 
2185   $key = "all_taxzones" unless ($key);
 
2187   $tzfilter = "WHERE obsolete is FALSE" if $key eq 'ALL_ACTIVE_TAXZONES';
 
2189   my $query = qq|SELECT * FROM tax_zones $tzfilter ORDER BY sortkey|;
 
2191   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2193   $main::lxdebug->leave_sub();
 
2196 sub _get_employees {
 
2197   $main::lxdebug->enter_sub();
 
2199   my ($self, $dbh, $params) = @_;
 
2204   if (ref $params eq 'HASH') {
 
2205     $key     = $params->{key};
 
2206     $deleted = $params->{deleted};
 
2212   $key     ||= "all_employees";
 
2213   my $filter = $deleted ? '' : 'WHERE NOT COALESCE(deleted, FALSE)';
 
2214   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee $filter ORDER BY lower(name)|);
 
2216   $main::lxdebug->leave_sub();
 
2219 sub _get_business_types {
 
2220   $main::lxdebug->enter_sub();
 
2222   my ($self, $dbh, $key) = @_;
 
2224   my $options       = ref $key eq 'HASH' ? $key : { key => $key };
 
2225   $options->{key} ||= "all_business_types";
 
2228   if (exists $options->{salesman}) {
 
2229     $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
 
2232   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
 
2234   $main::lxdebug->leave_sub();
 
2237 sub _get_languages {
 
2238   $main::lxdebug->enter_sub();
 
2240   my ($self, $dbh, $key) = @_;
 
2242   $key = "all_languages" unless ($key);
 
2244   my $query = qq|SELECT * FROM language ORDER BY id|;
 
2246   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2248   $main::lxdebug->leave_sub();
 
2251 sub _get_dunning_configs {
 
2252   $main::lxdebug->enter_sub();
 
2254   my ($self, $dbh, $key) = @_;
 
2256   $key = "all_dunning_configs" unless ($key);
 
2258   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
 
2260   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2262   $main::lxdebug->leave_sub();
 
2265 sub _get_currencies {
 
2266 $main::lxdebug->enter_sub();
 
2268   my ($self, $dbh, $key) = @_;
 
2270   $key = "all_currencies" unless ($key);
 
2272   $self->{$key} = [$self->get_all_currencies()];
 
2274   $main::lxdebug->leave_sub();
 
2278 $main::lxdebug->enter_sub();
 
2280   my ($self, $dbh, $key) = @_;
 
2282   $key = "all_payments" unless ($key);
 
2284   my $query = qq|SELECT * FROM payment_terms ORDER BY sortkey|;
 
2286   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2288   $main::lxdebug->leave_sub();
 
2291 sub _get_customers {
 
2292   $main::lxdebug->enter_sub();
 
2294   my ($self, $dbh, $key) = @_;
 
2296   my $options        = ref $key eq 'HASH' ? $key : { key => $key };
 
2297   $options->{key}  ||= "all_customers";
 
2298   my $limit_clause   = $options->{limit} ? "LIMIT $options->{limit}" : '';
 
2301   push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if  $options->{business_is_salesman};
 
2302   push @where, qq|NOT obsolete|                                            if !$options->{with_obsolete};
 
2303   my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : '';
 
2305   my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|;
 
2306   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
 
2308   $main::lxdebug->leave_sub();
 
2312   $main::lxdebug->enter_sub();
 
2314   my ($self, $dbh, $key) = @_;
 
2316   $key = "all_vendors" unless ($key);
 
2318   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
 
2320   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2322   $main::lxdebug->leave_sub();
 
2325 sub _get_departments {
 
2326   $main::lxdebug->enter_sub();
 
2328   my ($self, $dbh, $key) = @_;
 
2330   $key = "all_departments" unless ($key);
 
2332   my $query = qq|SELECT * FROM department ORDER BY description|;
 
2334   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2336   $main::lxdebug->leave_sub();
 
2339 sub _get_warehouses {
 
2340   $main::lxdebug->enter_sub();
 
2342   my ($self, $dbh, $param) = @_;
 
2344   my ($key, $bins_key);
 
2346   if ('' eq ref $param) {
 
2350     $key      = $param->{key};
 
2351     $bins_key = $param->{bins};
 
2354   my $query = qq|SELECT w.* FROM warehouse w
 
2355                  WHERE (NOT w.invalid) AND
 
2356                    ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
 
2357                  ORDER BY w.sortkey|;
 
2359   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2362     $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?
 
2363                 ORDER BY description|;
 
2364     my $sth = prepare_query($self, $dbh, $query);
 
2366     foreach my $warehouse (@{ $self->{$key} }) {
 
2367       do_statement($self, $sth, $query, $warehouse->{id});
 
2368       $warehouse->{$bins_key} = [];
 
2370       while (my $ref = $sth->fetchrow_hashref()) {
 
2371         push @{ $warehouse->{$bins_key} }, $ref;
 
2377   $main::lxdebug->leave_sub();
 
2381   $main::lxdebug->enter_sub();
 
2383   my ($self, $dbh, $table, $key, $sortkey) = @_;
 
2385   my $query  = qq|SELECT * FROM $table|;
 
2386   $query    .= qq| ORDER BY $sortkey| if ($sortkey);
 
2388   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2390   $main::lxdebug->leave_sub();
 
2394 #  $main::lxdebug->enter_sub();
 
2396 #  my ($self, $dbh, $key) = @_;
 
2398 #  $key ||= "all_groups";
 
2400 #  my $groups = $main::auth->read_groups();
 
2402 #  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2404 #  $main::lxdebug->leave_sub();
 
2408   $main::lxdebug->enter_sub();
 
2413   my $dbh = $self->get_standard_dbh(\%main::myconfig);
 
2414   my ($sth, $query, $ref);
 
2417   if ($params{contacts} || $params{shipto}) {
 
2418     $vc = 'customer' if $self->{"vc"} eq "customer";
 
2419     $vc = 'vendor'   if $self->{"vc"} eq "vendor";
 
2420     die "invalid use of get_lists, need 'vc'" unless $vc;
 
2421     $vc_id = $self->{"${vc}_id"};
 
2424   if ($params{"contacts"}) {
 
2425     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
 
2428   if ($params{"shipto"}) {
 
2429     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
 
2432   if ($params{"projects"} || $params{"all_projects"}) {
 
2433     $self->_get_projects($dbh, $params{"all_projects"} ?
 
2434                          $params{"all_projects"} : $params{"projects"},
 
2435                          $params{"all_projects"} ? 1 : 0);
 
2438   if ($params{"printers"}) {
 
2439     $self->_get_printers($dbh, $params{"printers"});
 
2442   if ($params{"languages"}) {
 
2443     $self->_get_languages($dbh, $params{"languages"});
 
2446   if ($params{"charts"}) {
 
2447     $self->_get_charts($dbh, $params{"charts"});
 
2450   if ($params{"taxcharts"}) {
 
2451     $self->_get_taxcharts($dbh, $params{"taxcharts"});
 
2454   if ($params{"taxzones"}) {
 
2455     $self->_get_taxzones($dbh, $params{"taxzones"});
 
2458   if ($params{"employees"}) {
 
2459     $self->_get_employees($dbh, $params{"employees"});
 
2462   if ($params{"salesmen"}) {
 
2463     $self->_get_employees($dbh, $params{"salesmen"});
 
2466   if ($params{"business_types"}) {
 
2467     $self->_get_business_types($dbh, $params{"business_types"});
 
2470   if ($params{"dunning_configs"}) {
 
2471     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
 
2474   if($params{"currencies"}) {
 
2475     $self->_get_currencies($dbh, $params{"currencies"});
 
2478   if($params{"customers"}) {
 
2479     $self->_get_customers($dbh, $params{"customers"});
 
2482   if($params{"vendors"}) {
 
2483     if (ref $params{"vendors"} eq 'HASH') {
 
2484       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
 
2486       $self->_get_vendors($dbh, $params{"vendors"});
 
2490   if($params{"payments"}) {
 
2491     $self->_get_payments($dbh, $params{"payments"});
 
2494   if($params{"departments"}) {
 
2495     $self->_get_departments($dbh, $params{"departments"});
 
2498   if ($params{price_factors}) {
 
2499     $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
 
2502   if ($params{warehouses}) {
 
2503     $self->_get_warehouses($dbh, $params{warehouses});
 
2506 #  if ($params{groups}) {
 
2507 #    $self->_get_groups($dbh, $params{groups});
 
2510   if ($params{partsgroup}) {
 
2511     $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
 
2514   $main::lxdebug->leave_sub();
 
2517 # this sub gets the id and name from $table
 
2519   $main::lxdebug->enter_sub();
 
2521   my ($self, $myconfig, $table) = @_;
 
2523   # connect to database
 
2524   my $dbh = $self->get_standard_dbh($myconfig);
 
2526   $table = $table eq "customer" ? "customer" : "vendor";
 
2527   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
 
2529   my ($query, @values);
 
2531   if (!$self->{openinvoices}) {
 
2533     if ($self->{customernumber} ne "") {
 
2534       $where = qq|(vc.customernumber ILIKE ?)|;
 
2535       push(@values, like($self->{customernumber}));
 
2537       $where = qq|(vc.name ILIKE ?)|;
 
2538       push(@values, like($self->{$table}));
 
2542       qq~SELECT vc.id, vc.name,
 
2543            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
2545          WHERE $where AND (NOT vc.obsolete)
 
2549       qq~SELECT DISTINCT vc.id, vc.name,
 
2550            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
2552          JOIN $table vc ON (a.${table}_id = vc.id)
 
2553          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
 
2555     push(@values, like($self->{$table}));
 
2558   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
 
2560   $main::lxdebug->leave_sub();
 
2562   return scalar(@{ $self->{name_list} });
 
2567   my ($self, $table, $provided_dbh) = @_;
 
2569   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh;
 
2570   return                                       unless $self->{id};
 
2571   croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
 
2573   my $query       = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
 
2574   my $ref         = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
 
2575   $ref->{mtime} ||= $ref->{itime};
 
2576   $self->{lastmtime} = $ref->{mtime};
 
2580 sub mtime_ischanged {
 
2581   my ($self, $table, $option) = @_;
 
2583   return                                       unless $self->{id};
 
2584   croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
 
2586   my $query       = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
 
2587   my $ref         = selectfirst_hashref_query($self, $self->get_standard_dbh, $query, $self->{id});
 
2588   $ref->{mtime} ||= $ref->{itime};
 
2590   if ($self->{lastmtime} && $self->{lastmtime} ne $ref->{mtime} ) {
 
2591       $self->error(($option eq 'mail') ?
 
2592         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") :
 
2593         t8("The document has been changed by another user. Please reopen it in another window and copy the changes to the new window")
 
2595     $::dispatcher->end_request;
 
2599 # language_payment duplicates some of the functionality of all_vc (language,
 
2600 # printer, payment_terms), and at least in the case of sales invoices both
 
2601 # all_vc and language_payment are called when adding new invoices
 
2602 sub language_payment {
 
2603   $main::lxdebug->enter_sub();
 
2605   my ($self, $myconfig) = @_;
 
2607   my $dbh = $self->get_standard_dbh($myconfig);
 
2609   my $query = qq|SELECT id, description
 
2613   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2616   $query = qq|SELECT printer_description, id
 
2618               ORDER BY printer_description|;
 
2620   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2623   $query = qq|SELECT id, description
 
2625               WHERE ( obsolete IS FALSE OR id = ? )
 
2627   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query, $self->{payment_id} || undef);
 
2629   # get buchungsgruppen
 
2630   $query = qq|SELECT id, description
 
2631               FROM buchungsgruppen|;
 
2633   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
 
2635   $main::lxdebug->leave_sub();
 
2638 # this is only used for reports
 
2639 sub all_departments {
 
2640   $main::lxdebug->enter_sub();
 
2642   my ($self, $myconfig, $table) = @_;
 
2644   my $dbh = $self->get_standard_dbh($myconfig);
 
2646   my $query = qq|SELECT id, description
 
2648                  ORDER BY description|;
 
2649   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2651   delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
 
2653   $main::lxdebug->leave_sub();
 
2657   $main::lxdebug->enter_sub();
 
2659   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
 
2662   if ($table eq "customer") {
 
2671   # get last customers or vendors
 
2672   my ($query, $sth, $ref);
 
2674   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
 
2679     my $transdate = "current_date";
 
2680     if ($self->{transdate}) {
 
2681       $transdate = $dbh->quote($self->{transdate});
 
2684     # now get the account numbers
 
2686       SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk2.tax_id
 
2688         -- find newest entries in taxkeys
 
2690           SELECT chart_id, MAX(startdate) AS startdate
 
2692           WHERE (startdate <= $transdate)
 
2694         ) tk ON (c.id = tk.chart_id)
 
2695         -- and load all of those entries
 
2696         INNER JOIN taxkeys tk2
 
2697            ON (tk.chart_id = tk2.chart_id AND tk.startdate = tk2.startdate)
 
2698        WHERE (c.link LIKE ?)
 
2701     $sth = $dbh->prepare($query);
 
2703     do_statement($self, $sth, $query, like($module));
 
2705     $self->{accounts} = "";
 
2706     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2708       foreach my $key (split(/:/, $ref->{link})) {
 
2709         if ($key =~ /\Q$module\E/) {
 
2711           # cross reference for keys
 
2712           $xkeyref{ $ref->{accno} } = $key;
 
2714           push @{ $self->{"${module}_links"}{$key} },
 
2715             { accno       => $ref->{accno},
 
2716               chart_id    => $ref->{chart_id},
 
2717               description => $ref->{description},
 
2718               taxkey      => $ref->{taxkey_id},
 
2719               tax_id      => $ref->{tax_id} };
 
2721           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2727   # get taxkeys and description
 
2728   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
 
2729   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
 
2731   if (($module eq "AP") || ($module eq "AR")) {
 
2732     # get tax rates and description
 
2733     $query = qq|SELECT * FROM tax|;
 
2734     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
 
2737   my $extra_columns = '';
 
2738   $extra_columns   .= 'a.direct_debit, ' if ($module eq 'AR') || ($module eq 'AP');
 
2743            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
 
2744            a.duedate, a.ordnumber, a.taxincluded, (SELECT cu.name FROM currencies cu WHERE cu.id=a.currency_id) AS currency, a.notes,
 
2746            a.intnotes, a.department_id, a.amount AS oldinvtotal,
 
2747            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
 
2748            a.globalproject_id, ${extra_columns}
 
2750            d.description AS department,
 
2753          JOIN $table c ON (a.${table}_id = c.id)
 
2754          LEFT JOIN employee e ON (e.id = a.employee_id)
 
2755          LEFT JOIN department d ON (d.id = a.department_id)
 
2757     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
 
2759     foreach my $key (keys %$ref) {
 
2760       $self->{$key} = $ref->{$key};
 
2762     $self->{mtime}   ||= $self->{itime};
 
2763     $self->{lastmtime} = $self->{mtime};
 
2764     my $transdate = "current_date";
 
2765     if ($self->{transdate}) {
 
2766       $transdate = $dbh->quote($self->{transdate});
 
2769     # now get the account numbers
 
2770     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk.tax_id
 
2772                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
 
2774                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
 
2775                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
 
2778     $sth = $dbh->prepare($query);
 
2779     do_statement($self, $sth, $query, like($module));
 
2781     $self->{accounts} = "";
 
2782     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2784       foreach my $key (split(/:/, $ref->{link})) {
 
2785         if ($key =~ /\Q$module\E/) {
 
2787           # cross reference for keys
 
2788           $xkeyref{ $ref->{accno} } = $key;
 
2790           push @{ $self->{"${module}_links"}{$key} },
 
2791             { accno       => $ref->{accno},
 
2792               chart_id    => $ref->{chart_id},
 
2793               description => $ref->{description},
 
2794               taxkey      => $ref->{taxkey_id},
 
2795               tax_id      => $ref->{tax_id} };
 
2797           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2803     # get amounts from individual entries
 
2806            c.accno, c.description,
 
2807            a.acc_trans_id, a.source, a.amount, a.memo, a.transdate, a.gldate, a.cleared, a.project_id, a.taxkey, a.chart_id,
 
2811          LEFT JOIN chart c ON (c.id = a.chart_id)
 
2812          LEFT JOIN project p ON (p.id = a.project_id)
 
2813          LEFT JOIN tax t ON (t.id= a.tax_id)
 
2814          WHERE a.trans_id = ?
 
2815          AND a.fx_transaction = '0'
 
2816          ORDER BY a.acc_trans_id, a.transdate|;
 
2817     $sth = $dbh->prepare($query);
 
2818     do_statement($self, $sth, $query, $self->{id});
 
2820     # get exchangerate for currency
 
2821     $self->{exchangerate} =
 
2822       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2825     # store amounts in {acc_trans}{$key} for multiple accounts
 
2826     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2827       $ref->{exchangerate} =
 
2828         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
 
2829       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
 
2832       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
 
2833         $ref->{amount} *= -1;
 
2835       $ref->{index} = $index;
 
2837       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
 
2844            d.closedto, d.revtrans,
 
2845            (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
 
2846            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2847            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
 
2848            (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
 
2849            (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
 
2851     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2852     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2859             current_date AS transdate, d.closedto, d.revtrans,
 
2860             (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
 
2861             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2862             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
 
2863             (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
 
2864             (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
 
2866     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2867     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2869     if ($self->{"$self->{vc}_id"}) {
 
2871       # only setup currency
 
2872       ($self->{currency}) = $self->{defaultcurrency} if !$self->{currency};
 
2876       $self->lastname_used($dbh, $myconfig, $table, $module);
 
2878       # get exchangerate for currency
 
2879       $self->{exchangerate} =
 
2880         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2886   $main::lxdebug->leave_sub();
 
2890   $main::lxdebug->enter_sub();
 
2892   my ($self, $dbh, $myconfig, $table, $module) = @_;
 
2896   $table         = $table eq "customer" ? "customer" : "vendor";
 
2897   my %column_map = ("a.${table}_id"           => "${table}_id",
 
2898                     "a.department_id"         => "department_id",
 
2899                     "d.description"           => "department",
 
2900                     "ct.name"                 => $table,
 
2901                     "cu.name"                 => "currency",
 
2904   if ($self->{type} =~ /delivery_order/) {
 
2905     $arap  = 'delivery_orders';
 
2906     delete $column_map{"cu.currency"};
 
2908   } elsif ($self->{type} =~ /_order/) {
 
2910     $where = "quotation = '0'";
 
2912   } elsif ($self->{type} =~ /_quotation/) {
 
2914     $where = "quotation = '1'";
 
2916   } elsif ($table eq 'customer') {
 
2924   $where           = "($where) AND" if ($where);
 
2925   my $query        = qq|SELECT MAX(id) FROM $arap
 
2926                         WHERE $where ${table}_id > 0|;
 
2927   my ($trans_id)   = selectrow_query($self, $dbh, $query);
 
2930   my $column_spec  = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
 
2931   $query           = qq|SELECT $column_spec
 
2933                         LEFT JOIN $table     ct ON (a.${table}_id = ct.id)
 
2934                         LEFT JOIN department d  ON (a.department_id = d.id)
 
2935                         LEFT JOIN currencies cu ON (cu.id=ct.currency_id)
 
2937   my $ref          = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
 
2939   map { $self->{$_} = $ref->{$_} } values %column_map;
 
2941   $main::lxdebug->leave_sub();
 
2944 sub get_variable_content_types {
 
2945   my %html_variables  = (
 
2946       longdescription => 'html',
 
2947       partnotes       => 'html',
 
2949       orignotes       => 'html',
 
2954       header_text     => 'html',
 
2955       footer_text     => 'html',
 
2957   return \%html_variables;
 
2961   $main::lxdebug->enter_sub();
 
2964   my $myconfig = shift || \%::myconfig;
 
2965   my ($thisdate, $days) = @_;
 
2967   my $dbh = $self->get_standard_dbh($myconfig);
 
2972     my $dateformat = $myconfig->{dateformat};
 
2973     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
 
2974     $thisdate = $dbh->quote($thisdate);
 
2975     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
 
2977     $query = qq|SELECT current_date AS thisdate|;
 
2980   ($thisdate) = selectrow_query($self, $dbh, $query);
 
2982   $main::lxdebug->leave_sub();
 
2988   $main::lxdebug->enter_sub();
 
2990   my ($self, $flds, $new, $count, $numrows) = @_;
 
2994   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
 
2999   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
 
3001     my $j = $item->{ndx} - 1;
 
3002     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
 
3006   for $i ($count + 1 .. $numrows) {
 
3007     map { delete $self->{"${_}_$i"} } @{$flds};
 
3010   $main::lxdebug->leave_sub();
 
3014   $main::lxdebug->enter_sub();
 
3016   my ($self, $myconfig) = @_;
 
3020   SL::DB->client->with_transaction(sub {
 
3021     my $dbh = SL::DB->client->dbh;
 
3023     my $query = qq|DELETE FROM status
 
3024                    WHERE (formname = ?) AND (trans_id = ?)|;
 
3025     my $sth = prepare_query($self, $dbh, $query);
 
3027     if ($self->{formname} =~ /(check|receipt)/) {
 
3028       for $i (1 .. $self->{rowcount}) {
 
3029         do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
 
3032       do_statement($self, $sth, $query, $self->{formname}, $self->{id});
 
3036     my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3037     my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3039     my %queued = split / /, $self->{queued};
 
3042     if ($self->{formname} =~ /(check|receipt)/) {
 
3044       # this is a check or receipt, add one entry for each lineitem
 
3045       my ($accno) = split /--/, $self->{account};
 
3046       $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
 
3047                   VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
 
3048       @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
 
3049       $sth = prepare_query($self, $dbh, $query);
 
3051       for $i (1 .. $self->{rowcount}) {
 
3052         if ($self->{"checked_$i"}) {
 
3053           do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
 
3059       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
3060                   VALUES (?, ?, ?, ?, ?)|;
 
3061       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
 
3062                $queued{$self->{formname}}, $self->{formname});
 
3065   }) or do { die SL::DB->client->error };
 
3067   $main::lxdebug->leave_sub();
 
3071   $main::lxdebug->enter_sub();
 
3073   my ($self, $dbh) = @_;
 
3075   my ($query, $printed, $emailed);
 
3077   my $formnames  = $self->{printed};
 
3078   my $emailforms = $self->{emailed};
 
3080   $query = qq|DELETE FROM status
 
3081                  WHERE (formname = ?) AND (trans_id = ?)|;
 
3082   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
 
3084   # this only applies to the forms
 
3085   # checks and receipts are posted when printed or queued
 
3087   if ($self->{queued}) {
 
3088     my %queued = split / /, $self->{queued};
 
3090     foreach my $formname (keys %queued) {
 
3091       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3092       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3094       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
3095                   VALUES (?, ?, ?, ?, ?)|;
 
3096       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
 
3098       $formnames  =~ s/\Q$self->{formname}\E//;
 
3099       $emailforms =~ s/\Q$self->{formname}\E//;
 
3104   # save printed, emailed info
 
3105   $formnames  =~ s/^ +//g;
 
3106   $emailforms =~ s/^ +//g;
 
3109   map { $status{$_}{printed} = 1 } split / +/, $formnames;
 
3110   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
 
3112   foreach my $formname (keys %status) {
 
3113     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3114     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3116     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
 
3117                 VALUES (?, ?, ?, ?)|;
 
3118     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
 
3121   $main::lxdebug->leave_sub();
 
3125 # $main::locale->text('SAVED')
 
3126 # $main::locale->text('SCREENED')
 
3127 # $main::locale->text('DELETED')
 
3128 # $main::locale->text('ADDED')
 
3129 # $main::locale->text('PAYMENT POSTED')
 
3130 # $main::locale->text('POSTED')
 
3131 # $main::locale->text('POSTED AS NEW')
 
3132 # $main::locale->text('ELSE')
 
3133 # $main::locale->text('SAVED FOR DUNNING')
 
3134 # $main::locale->text('DUNNING STARTED')
 
3135 # $main::locale->text('PRINTED')
 
3136 # $main::locale->text('MAILED')
 
3137 # $main::locale->text('SCREENED')
 
3138 # $main::locale->text('CANCELED')
 
3139 # $main::locale->text('IMPORT')
 
3140 # $main::locale->text('UNIMPORT')
 
3141 # $main::locale->text('invoice')
 
3142 # $main::locale->text('proforma')
 
3143 # $main::locale->text('sales_order')
 
3144 # $main::locale->text('pick_list')
 
3145 # $main::locale->text('purchase_order')
 
3146 # $main::locale->text('bin_list')
 
3147 # $main::locale->text('sales_quotation')
 
3148 # $main::locale->text('request_quotation')
 
3151   $main::lxdebug->enter_sub();
 
3154   my $dbh  = shift || SL::DB->client->dbh;
 
3155   SL::DB->client->with_transaction(sub {
 
3157     if(!exists $self->{employee_id}) {
 
3158       &get_employee($self, $dbh);
 
3162      qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
 
3163      qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
 
3164     my @values = (conv_i($self->{id}), $self->{login},
 
3165                   $self->{addition}, $self->{what_done}, "$self->{snumbers}");
 
3166     do_query($self, $dbh, $query, @values);
 
3168   }) or do { die SL::DB->client->error };
 
3170   $main::lxdebug->leave_sub();
 
3174   $main::lxdebug->enter_sub();
 
3176   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
 
3177   my ($orderBy, $desc) = split(/\-\-/, $order);
 
3178   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
 
3181   if ($trans_id ne "") {
 
3183       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 | .
 
3184       qq|FROM history_erp h | .
 
3185       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
 
3186       qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
 
3189     my $sth = $dbh->prepare($query) || $self->dberror($query);
 
3191     $sth->execute() || $self->dberror("$query");
 
3193     while(my $hash_ref = $sth->fetchrow_hashref()) {
 
3194       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
 
3195       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
 
3196       my ( $what, $number ) = split /_/, $hash_ref->{snumbers};
 
3197       $hash_ref->{snumbers} = $number;
 
3198       $hash_ref->{haslink}  = 'controller.pl?action=EmailJournal/show&id='.$number if $what eq 'emailjournal';
 
3199       $hash_ref->{snumbers} = $main::locale->text("E-Mail").' '.$number if $what eq 'emailjournal';
 
3200       $tempArray[$i++] = $hash_ref;
 
3202     $main::lxdebug->leave_sub() and return \@tempArray
 
3203       if ($i > 0 && $tempArray[0] ne "");
 
3205   $main::lxdebug->leave_sub();
 
3209 sub get_partsgroup {
 
3210   $main::lxdebug->enter_sub();
 
3212   my ($self, $myconfig, $p) = @_;
 
3213   my $target = $p->{target} || 'all_partsgroup';
 
3215   my $dbh = $self->get_standard_dbh($myconfig);
 
3217   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
 
3219                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
 
3222   if ($p->{searchitems} eq 'part') {
 
3223     $query .= qq|WHERE p.part_type = 'part'|;
 
3225   if ($p->{searchitems} eq 'service') {
 
3226     $query .= qq|WHERE p.part_type = 'service'|;
 
3228   if ($p->{searchitems} eq 'assembly') {
 
3229     $query .= qq|WHERE p.part_type = 'assembly'|;
 
3232   $query .= qq|ORDER BY partsgroup|;
 
3235     $query = qq|SELECT id, partsgroup FROM partsgroup
 
3236                 ORDER BY partsgroup|;
 
3239   if ($p->{language_code}) {
 
3240     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
 
3241                   t.description AS translation
 
3243                 JOIN parts p ON (p.partsgroup_id = pg.id)
 
3244                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
 
3245                 ORDER BY translation|;
 
3246     @values = ($p->{language_code});
 
3249   $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
 
3251   $main::lxdebug->leave_sub();
 
3254 sub get_pricegroup {
 
3255   $main::lxdebug->enter_sub();
 
3257   my ($self, $myconfig, $p) = @_;
 
3259   my $dbh = $self->get_standard_dbh($myconfig);
 
3261   my $query = qq|SELECT p.id, p.pricegroup
 
3264   $query .= qq| ORDER BY pricegroup|;
 
3267     $query = qq|SELECT id, pricegroup FROM pricegroup
 
3268                 ORDER BY pricegroup|;
 
3271   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
 
3273   $main::lxdebug->leave_sub();
 
3277 # usage $form->all_years($myconfig, [$dbh])
 
3278 # return list of all years where bookings found
 
3281   $main::lxdebug->enter_sub();
 
3283   my ($self, $myconfig, $dbh) = @_;
 
3285   $dbh ||= $self->get_standard_dbh($myconfig);
 
3288   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
 
3289                    (SELECT MAX(transdate) FROM acc_trans)|;
 
3290   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
 
3292   if ($myconfig->{dateformat} =~ /^yy/) {
 
3293     ($startdate) = split /\W/, $startdate;
 
3294     ($enddate) = split /\W/, $enddate;
 
3296     (@_) = split /\W/, $startdate;
 
3298     (@_) = split /\W/, $enddate;
 
3303   $startdate = substr($startdate,0,4);
 
3304   $enddate = substr($enddate,0,4);
 
3306   while ($enddate >= $startdate) {
 
3307     push @all_years, $enddate--;
 
3312   $main::lxdebug->leave_sub();
 
3316   $main::lxdebug->enter_sub();
 
3320   map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
 
3322   $main::lxdebug->leave_sub();
 
3326   $main::lxdebug->enter_sub();
 
3331   map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
 
3333   $main::lxdebug->leave_sub();
 
3336 sub prepare_for_printing {
 
3339   my $defaults         = SL::DB::Default->get;
 
3341   $self->{templates} ||= $defaults->templates;
 
3342   $self->{formname}  ||= $self->{type};
 
3343   $self->{media}     ||= 'email';
 
3345   die "'media' other than 'email', 'file', 'printer' is not supported yet" unless $self->{media} =~ m/^(?:email|file|printer)$/;
 
3347   # Several fields that used to reside in %::myconfig (stored in
 
3348   # auth.user_config) are now stored in defaults. Copy them over for
 
3350   $self->{$_} = $defaults->$_ for qw(company address taxnumber co_ustid duns sepa_creditor_id);
 
3352   $self->{"myconfig_${_}"} = $::myconfig{$_} for grep { $_ ne 'dbpasswd' } keys %::myconfig;
 
3354   if (!$self->{employee_id}) {
 
3355     $self->{"employee_${_}"} = $::myconfig{$_} for qw(email tel fax name signature);
 
3356     $self->{"employee_${_}"} = $defaults->$_   for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
 
3359   # Load shipping address from database. If shipto_id is set then it's
 
3360   # one from the customer's/vendor's master data. Otherwise look an a
 
3361   # customized address linking back to the current record.
 
3362   my $shipto_module = $self->{type} =~ /_delivery_order$/                                             ? 'DO'
 
3363                     : $self->{type} =~ /sales_order|sales_quotation|request_quotation|purchase_order/ ? 'OE'
 
3365   my $shipto        = $self->{shipto_id} ? SL::DB::Shipto->new(shipto_id => $self->{shipto_id})->load
 
3366                     :                      SL::DB::Manager::Shipto->get_first(where => [ module => $shipto_module, trans_id => $self->{id} ]);
 
3368     $self->{$_} = $shipto->$_ for grep { m{^shipto} } map { $_->name } @{ $shipto->meta->columns };
 
3369     $self->{"shiptocvar_" . $_->config->name} = $_->value_as_text for @{ $shipto->cvars_by_config };
 
3372   my $language = $self->{language} ? '_' . $self->{language} : '';
 
3374   my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
 
3375   if ($self->{language_id}) {
 
3376     ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) = AM->get_language_details(\%::myconfig, $self, $self->{language_id});
 
3379   $output_dateformat   ||= $::myconfig{dateformat};
 
3380   $output_numberformat ||= $::myconfig{numberformat};
 
3381   $output_longdates    //= 1;
 
3383   $self->{myconfig_output_dateformat}   = $output_dateformat   // $::myconfig{dateformat};
 
3384   $self->{myconfig_output_longdates}    = $output_longdates    // 1;
 
3385   $self->{myconfig_output_numberformat} = $output_numberformat // $::myconfig{numberformat};
 
3387   # Retrieve accounts for tax calculation.
 
3388   IC->retrieve_accounts(\%::myconfig, $self, map { $_ => $self->{"id_$_"} } 1 .. $self->{rowcount});
 
3390   if ($self->{type} =~ /_delivery_order$/) {
 
3391     DO->order_details(\%::myconfig, $self);
 
3392   } elsif ($self->{type} =~ /sales_order|sales_quotation|request_quotation|purchase_order/) {
 
3393     OE->order_details(\%::myconfig, $self);
 
3395     IS->invoice_details(\%::myconfig, $self, $::locale);
 
3398   # Chose extension & set source file name
 
3399   my $extension = 'html';
 
3400   if ($self->{format} eq 'postscript') {
 
3401     $self->{postscript}   = 1;
 
3403   } elsif ($self->{"format"} =~ /pdf/) {
 
3405     $extension            = $self->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
 
3406   } elsif ($self->{"format"} =~ /opendocument/) {
 
3407     $self->{opendocument} = 1;
 
3409   } elsif ($self->{"format"} =~ /excel/) {
 
3414   my $printer_code    = $self->{printer_code} ? '_' . $self->{printer_code} : '';
 
3415   my $email_extension = $self->{media} eq 'email' && -f ($defaults->templates . "/$self->{formname}_email${language}.${extension}") ? '_email' : '';
 
3416   $self->{IN}         = "$self->{formname}${email_extension}${language}${printer_code}.${extension}";
 
3419   $self->format_dates($output_dateformat, $output_longdates,
 
3420                       qw(invdate orddate quodate pldate duedate reqdate transdate shippingdate deliverydate validitydate paymentdate datepaid
 
3421                          transdate_oe deliverydate_oe employee_startdate employee_enddate),
 
3422                       grep({ /^(?:datepaid|transdate_oe|reqdate|deliverydate|deliverydate_oe|transdate)_\d+$/ } keys(%{$self})));
 
3424   $self->reformat_numbers($output_numberformat, 2,
 
3425                           qw(invtotal ordtotal quototal subtotal linetotal listprice sellprice netprice discount tax taxbase total paid),
 
3426                           grep({ /^(?:linetotal|listprice|sellprice|netprice|taxbase|discount|paid|subtotal|total|tax)_\d+$/ } keys(%{$self})));
 
3428   $self->reformat_numbers($output_numberformat, undef, qw(qty price_factor), grep({ /^qty_\d+$/} keys(%{$self})));
 
3430   my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
 
3432   if (scalar @{ $cvar_date_fields }) {
 
3433     $self->format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
 
3436   while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
 
3437     $self->reformat_numbers($output_numberformat, $precision, @{ $field_list });
 
3440   $self->{template_meta} = {
 
3441     formname  => $self->{formname},
 
3442     language  => SL::DB::Manager::Language->find_by_or_create(id => $self->{language_id} || undef),
 
3443     format    => $self->{format},
 
3444     media     => $self->{media},
 
3445     extension => $extension,
 
3446     printer   => SL::DB::Manager::Printer->find_by_or_create(id => $self->{printer_id} || undef),
 
3447     today     => DateTime->today,
 
3453 sub calculate_arap {
 
3454   my ($self,$buysell,$taxincluded,$exchangerate,$roundplaces) = @_;
 
3456   # this function is used to calculate netamount, total_tax and amount for AP and
 
3457   # AR transactions (Kreditoren-/Debitorenbuchungen) by going over all lines
 
3459   # Thus it needs a fully prepared $form to work on.
 
3460   # calculate_arap assumes $form->{amount_$i} entries still need to be parsed
 
3462   # The calculated total values are all rounded (default is to 2 places) and
 
3463   # returned as parameters rather than directly modifying form.  The aim is to
 
3464   # make the calculation of AP and AR behave identically.  There is a test-case
 
3465   # for this function in t/form/arap.t
 
3467   # While calculating the totals $form->{amount_$i} and $form->{tax_$i} are
 
3468   # modified and formatted and receive the correct sign for writing straight to
 
3469   # acc_trans, depending on whether they are ar or ap.
 
3472   die "taxincluded needed in Form->calculate_arap" unless defined $taxincluded;
 
3473   die "exchangerate needed in Form->calculate_arap" unless defined $exchangerate;
 
3474   die 'illegal buysell parameter, has to be \"buy\" or \"sell\" in Form->calculate_arap\n' unless $buysell =~ /^(buy|sell)$/;
 
3475   $roundplaces = 2 unless $roundplaces;
 
3477   my $sign = 1;  # adjust final results for writing amount to acc_trans
 
3478   $sign = -1 if $buysell eq 'buy';
 
3480   my ($netamount,$total_tax,$amount);
 
3484   # parse and round amounts, setting correct sign for writing to acc_trans
 
3485   for my $i (1 .. $self->{rowcount}) {
 
3486     $self->{"amount_$i"} = $self->round_amount($self->parse_amount(\%::myconfig, $self->{"amount_$i"}) * $exchangerate * $sign, $roundplaces);
 
3488     $amount += $self->{"amount_$i"} * $sign;
 
3491   for my $i (1 .. $self->{rowcount}) {
 
3492     next unless $self->{"amount_$i"};
 
3493     ($self->{"tax_id_$i"}) = split /--/, $self->{"taxchart_$i"};
 
3494     my $tax_id = $self->{"tax_id_$i"};
 
3496     my $selected_tax = SL::DB::Manager::Tax->find_by(id => "$tax_id");
 
3498     if ( $selected_tax ) {
 
3500       if ( $buysell eq 'sell' ) {
 
3501         $self->{AR_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
 
3503         $self->{AP_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
 
3506       $self->{"taxkey_$i"} = $selected_tax->taxkey;
 
3507       $self->{"taxrate_$i"} = $selected_tax->rate;
 
3510     ($self->{"amount_$i"}, $self->{"tax_$i"}) = $self->calculate_tax($self->{"amount_$i"},$self->{"taxrate_$i"},$taxincluded,$roundplaces);
 
3512     $netamount  += $self->{"amount_$i"};
 
3513     $total_tax  += $self->{"tax_$i"};
 
3516   $amount = $netamount + $total_tax;
 
3518   # due to $sign amount_$i und tax_$i already have the right sign for acc_trans
 
3519   # but reverse sign of totals for writing amounts to ar
 
3520   if ( $buysell eq 'buy' ) {
 
3526   return($netamount,$total_tax,$amount);
 
3530   my ($self, $dateformat, $longformat, @indices) = @_;
 
3532   $dateformat ||= $::myconfig{dateformat};
 
3534   foreach my $idx (@indices) {
 
3535     if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
 
3536       for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
 
3537         $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $dateformat, $longformat);
 
3541     next unless defined $self->{$idx};
 
3543     if (!ref($self->{$idx})) {
 
3544       $self->{$idx} = $::locale->reformat_date(\%::myconfig, $self->{$idx}, $dateformat, $longformat);
 
3546     } elsif (ref($self->{$idx}) eq "ARRAY") {
 
3547       for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
 
3548         $self->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{$idx}->[$i], $dateformat, $longformat);
 
3554 sub reformat_numbers {
 
3555   my ($self, $numberformat, $places, @indices) = @_;
 
3557   return if !$numberformat || ($numberformat eq $::myconfig{numberformat});
 
3559   foreach my $idx (@indices) {
 
3560     if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
 
3561       for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
 
3562         $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i]);
 
3566     next unless defined $self->{$idx};
 
3568     if (!ref($self->{$idx})) {
 
3569       $self->{$idx} = $self->parse_amount(\%::myconfig, $self->{$idx});
 
3571     } elsif (ref($self->{$idx}) eq "ARRAY") {
 
3572       for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
 
3573         $self->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{$idx}->[$i]);
 
3578   my $saved_numberformat    = $::myconfig{numberformat};
 
3579   $::myconfig{numberformat} = $numberformat;
 
3581   foreach my $idx (@indices) {
 
3582     if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
 
3583       for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
 
3584         $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $places);
 
3588     next unless defined $self->{$idx};
 
3590     if (!ref($self->{$idx})) {
 
3591       $self->{$idx} = $self->format_amount(\%::myconfig, $self->{$idx}, $places);
 
3593     } elsif (ref($self->{$idx}) eq "ARRAY") {
 
3594       for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
 
3595         $self->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{$idx}->[$i], $places);
 
3600   $::myconfig{numberformat} = $saved_numberformat;
 
3603 sub create_email_signature {
 
3605   my $client_signature = $::instance_conf->get_signature;
 
3606   my $user_signature   = $::myconfig{signature};
 
3609   if ( $client_signature or $user_signature ) {
 
3610     $signature  = "\n\n-- \n";
 
3611     $signature .= $user_signature   . "\n" if $user_signature;
 
3612     $signature .= $client_signature . "\n" if $client_signature;
 
3620   $::lxdebug->enter_sub;
 
3622   my %style_to_script_map = (
 
3627   my $menu_script = $style_to_script_map{$::myconfig{menustyle}} || '';
 
3630   require "bin/mozilla/menu$menu_script.pl";
 
3632   require SL::Controller::FrameHeader;
 
3635   my $layout = SL::Controller::FrameHeader->new->action_header . ::render();
 
3637   $::lxdebug->leave_sub;
 
3642   # this function calculates the net amount and tax for the lines in ar, ap and
 
3643   # gl and is used for update as well as post. When used with update the return
 
3644   # value of amount isn't needed
 
3646   # calculate_tax should always work with positive values, or rather as the user inputs them
 
3647   # calculate_tax uses db/perl numberformat, i.e. parsed numbers
 
3648   # convert to negative numbers (when necessary) only when writing to acc_trans
 
3649   # the amount from $form for ap/ar/gl is currently always rounded to 2 decimals before it reaches here
 
3650   # for post_transaction amount already contains exchangerate and correct sign and is rounded
 
3651   # calculate_tax doesn't (need to) know anything about exchangerate
 
3653   my ($self,$amount,$taxrate,$taxincluded,$roundplaces) = @_;
 
3661     # calculate tax (unrounded), subtract from amount, round amount and round tax
 
3662     $tax       = $amount - ($amount / ($taxrate + 1)); # equivalent to: taxrate * amount / (taxrate + 1)
 
3663     $amount    = $self->round_amount($amount - $tax, $roundplaces);
 
3664     $tax       = $self->round_amount($tax, $roundplaces);
 
3666     $tax       = $amount * $taxrate;
 
3667     $tax       = $self->round_amount($tax, $roundplaces);
 
3670   $tax = 0 unless $tax;
 
3672   return ($amount,$tax);
 
3681 SL::Form.pm - main data object.
 
3685 This is the main data object of kivitendo.
 
3686 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
 
3687 Points of interest for a beginner are:
 
3689  - $form->error            - renders a generic error in html. accepts an error message
 
3690  - $form->get_standard_dbh - returns a database connection for the
 
3692 =head1 SPECIAL FUNCTIONS
 
3694 =head2 C<redirect_header> $url
 
3696 Generates a HTTP redirection header for the new C<$url>. Constructs an
 
3697 absolute URL including scheme, host name and port. If C<$url> is a
 
3698 relative URL then it is considered relative to kivitendo base URL.
 
3700 This function C<die>s if headers have already been created with
 
3701 C<$::form-E<gt>header>.
 
3705   print $::form->redirect_header('oe.pl?action=edit&id=1234');
 
3706   print $::form->redirect_header('http://www.lx-office.org/');
 
3710 Generates a general purpose http/html header and includes most of the scripts
 
3711 and stylesheets needed. Stylesheets can be added with L<use_stylesheet>.
 
3713 Only one header will be generated. If the method was already called in this
 
3714 request it will not output anything and return undef. Also if no
 
3715 HTTP_USER_AGENT is found, no header is generated.
 
3717 Although header does not accept parameters itself, it will honor special
 
3718 hashkeys of its Form instance:
 
3726 If one of these is set, a http-equiv refresh is generated. Missing parameters
 
3727 default to 3 seconds and the refering url.
 
3731 Either a scalar or an array ref. Will be inlined into the header. Add
 
3732 stylesheets with the L<use_stylesheet> function.
 
3736 If true, a css snippet will be generated that sets the page in landscape mode.
 
3740 Used to override the default favicon.
 
3744 A html page title will be generated from this
 
3746 =item mtime_ischanged
 
3748 Tries to avoid concurrent write operations to records by checking the database mtime with a fetched one.
 
3750 Can be used / called with any table, that has itime and mtime attributes.
 
3751 Valid C<table> names are: oe, ar, ap, delivery_orders, parts.
 
3752 Can be called wit C<option> mail to generate a different error message.
 
3754 Returns undef if no save operation has been done yet ($self->{id} not present).
 
3755 Returns undef if no concurrent write process is detected otherwise a error message.