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);
 
  62 use SL::DB::AdditionalBillingAddress;
 
  64 use SL::DB::CustomVariableConfig;
 
  66 use SL::DB::PaymentTerm;
 
  69 use SL::Helper::Flash qw();
 
  72 use SL::Layout::Dispatcher;
 
  74 use SL::Locale::String;
 
  77 use SL::MoreCommon qw(uri_encode uri_decode);
 
  79 use SL::PrefixedNumber;
 
  88 use List::Util qw(first max min sum);
 
  89 use List::MoreUtils qw(all any apply);
 
  91 use SL::Helper::File qw(:all);
 
  92 use SL::Helper::Number;
 
  93 use SL::Helper::CreatePDF qw(merge_pdfs);
 
  98   SL::Version->get_version;
 
 102   $main::lxdebug->enter_sub();
 
 109   if ($LXDebug::watch_form) {
 
 110     require SL::Watchdog;
 
 111     tie %{ $self }, 'SL::Watchdog';
 
 116   $main::lxdebug->leave_sub();
 
 121 sub _flatten_variables_rec {
 
 122   $main::lxdebug->enter_sub(2);
 
 131   if ('' eq ref $curr->{$key}) {
 
 132     @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
 
 134   } elsif ('HASH' eq ref $curr->{$key}) {
 
 135     foreach my $hash_key (sort keys %{ $curr->{$key} }) {
 
 136       push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
 
 140     foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
 
 141       my $first_array_entry = 1;
 
 143       my $element = $curr->{$key}[$idx];
 
 145       if ('HASH' eq ref $element) {
 
 146         foreach my $hash_key (sort keys %{ $element }) {
 
 147           push @result, $self->_flatten_variables_rec($element, $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
 
 148           $first_array_entry = 0;
 
 151         push @result, { 'key' => $prefix . $key . '[]', 'value' => $element };
 
 156   $main::lxdebug->leave_sub(2);
 
 161 sub flatten_variables {
 
 162   $main::lxdebug->enter_sub(2);
 
 170     push @variables, $self->_flatten_variables_rec($self, '', $_);
 
 173   $main::lxdebug->leave_sub(2);
 
 178 sub flatten_standard_variables {
 
 179   $main::lxdebug->enter_sub(2);
 
 182   my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar), @_);
 
 186   foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
 
 187     push @variables, $self->_flatten_variables_rec($self, '', $_);
 
 190   $main::lxdebug->leave_sub(2);
 
 196   my ($self, $str) = @_;
 
 198   return uri_encode($str);
 
 202   my ($self, $str) = @_;
 
 204   return uri_decode($str);
 
 208   $main::lxdebug->enter_sub();
 
 209   my ($self, $str) = @_;
 
 211   if ($str && !ref($str)) {
 
 212     $str =~ s/\"/"/g;
 
 215   $main::lxdebug->leave_sub();
 
 221   $main::lxdebug->enter_sub();
 
 222   my ($self, $str) = @_;
 
 224   if ($str && !ref($str)) {
 
 225     $str =~ s/"/\"/g;
 
 228   $main::lxdebug->leave_sub();
 
 234   $main::lxdebug->enter_sub();
 
 238     map({ print($::request->{cgi}->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
 
 240     for (sort keys %$self) {
 
 241       next if (($_ eq "header") || (ref($self->{$_}) ne ""));
 
 242       print($::request->{cgi}->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
 
 245   $main::lxdebug->leave_sub();
 
 249   my ($self, $code) = @_;
 
 250   local $self->{__ERROR_HANDLER} = sub { SL::X::FormError->throw(error => $_[0]) };
 
 255   $main::lxdebug->enter_sub();
 
 257   $main::lxdebug->show_backtrace();
 
 259   my ($self, $msg) = @_;
 
 261   if ($self->{__ERROR_HANDLER}) {
 
 262     $self->{__ERROR_HANDLER}->($msg);
 
 264   } elsif ($ENV{HTTP_USER_AGENT}) {
 
 266     $self->show_generic_error($msg);
 
 269     confess "Error: $msg\n";
 
 272   $main::lxdebug->leave_sub();
 
 276   $main::lxdebug->enter_sub();
 
 278   my ($self, $msg) = @_;
 
 280   if ($ENV{HTTP_USER_AGENT}) {
 
 282     print $self->parse_html_template('generic/form_info', { message => $msg });
 
 284   } elsif ($self->{info_function}) {
 
 285     &{ $self->{info_function} }($msg);
 
 290   $main::lxdebug->leave_sub();
 
 293 # calculates the number of rows in a textarea based on the content and column number
 
 294 # can be capped with maxrows
 
 296   $main::lxdebug->enter_sub();
 
 297   my ($self, $str, $cols, $maxrows, $minrows) = @_;
 
 301   my $rows   = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
 
 304   $main::lxdebug->leave_sub();
 
 306   return max(min($rows, $maxrows), $minrows);
 
 310   my ($self, $msg) = @_;
 
 312   SL::X::DBError->throw(
 
 314     db_error => $DBI::errstr,
 
 319   $main::lxdebug->enter_sub();
 
 321   my ($self, $name, $msg) = @_;
 
 324   foreach my $part (split m/\./, $name) {
 
 325     if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
 
 328     $curr = $curr->{$part};
 
 331   $main::lxdebug->leave_sub();
 
 334 sub _get_request_uri {
 
 337   return URI->new($ENV{HTTP_REFERER})->canonical() if $ENV{HTTP_X_FORWARDED_FOR};
 
 338   return URI->new                                  if !$ENV{REQUEST_URI}; # for testing
 
 340   my $scheme =  $::request->is_https ? 'https' : 'http';
 
 341   my $port   =  $ENV{SERVER_PORT};
 
 342   $port      =  undef if (($scheme eq 'http' ) && ($port == 80))
 
 343                       || (($scheme eq 'https') && ($port == 443));
 
 345   my $uri    =  URI->new("${scheme}://");
 
 346   $uri->scheme($scheme);
 
 348   $uri->host($ENV{HTTP_HOST} || $ENV{SERVER_ADDR});
 
 349   $uri->path_query($ENV{REQUEST_URI});
 
 355 sub _add_to_request_uri {
 
 358   my $relative_new_path = shift;
 
 359   my $request_uri       = shift || $self->_get_request_uri;
 
 360   my $relative_new_uri  = URI->new($relative_new_path);
 
 361   my @request_segments  = $request_uri->path_segments;
 
 363   my $new_uri           = $request_uri->clone;
 
 364   $new_uri->path_segments(@request_segments[0..scalar(@request_segments) - 2], $relative_new_uri->path_segments);
 
 369 sub create_http_response {
 
 370   $main::lxdebug->enter_sub();
 
 375   my $cgi      = $::request->{cgi};
 
 378   if (defined $main::auth) {
 
 379     my $uri      = $self->_get_request_uri;
 
 380     my @segments = $uri->path_segments;
 
 382     $uri->path_segments(@segments);
 
 384     my $session_cookie_value = $main::auth->get_session_id();
 
 386     if ($session_cookie_value) {
 
 387       $session_cookie = $cgi->cookie('-name'    => $main::auth->get_session_cookie_name(),
 
 388                                      '-value'   => $session_cookie_value,
 
 389                                      '-path'    => $uri->path,
 
 390                                      '-expires' => '+' . $::auth->{session_timeout} . 'm',
 
 391                                      '-secure'  => $::request->is_https);
 
 395   my %cgi_params = ('-type' => $params{content_type});
 
 396   $cgi_params{'-charset'} = $params{charset} if ($params{charset});
 
 397   $cgi_params{'-cookie'}  = $session_cookie  if ($session_cookie);
 
 399   map { $cgi_params{'-' . $_} = $params{$_} if exists $params{$_} } qw(content_disposition content_length status);
 
 401   my $output = $cgi->header(%cgi_params);
 
 403   $main::lxdebug->leave_sub();
 
 409   $::lxdebug->enter_sub;
 
 411   my ($self, %params) = @_;
 
 414   $::lxdebug->leave_sub and return if !$ENV{HTTP_USER_AGENT} || $self->{header}++;
 
 416   if ($params{no_layout}) {
 
 417     $::request->{layout} = SL::Layout::Dispatcher->new(style => 'none');
 
 420   my $layout = $::request->{layout};
 
 422   # standard css for all
 
 423   # this should gradually move to the layouts that need it
 
 424   $layout->use_stylesheet("$_.css") for qw(
 
 425     common main menu list_accounts jquery.autocomplete
 
 426     jquery.multiselect2side
 
 427     ui-lightness/jquery-ui
 
 429     tooltipster themes/tooltipster-light
 
 432   $layout->use_javascript("$_.js") for (qw(
 
 433     jquery jquery-ui jquery.cookie jquery.checkall jquery.download
 
 434     jquery/jquery.form jquery/fixes client_js
 
 435     jquery/jquery.tooltipster.min
 
 436     common part_selection
 
 437   ), "jquery/ui/i18n/jquery.ui.datepicker-$::myconfig{countrycode}");
 
 439   $self->{favicon} ||= "favicon.ico";
 
 440   $self->{titlebar} = join ' - ', grep $_, $self->{title}, $self->{login}, $::myconfig{dbname}, $self->read_version if $self->{title} || !$self->{titlebar};
 
 443   if ($self->{refresh_url} || $self->{refresh_time}) {
 
 444     my $refresh_time = $self->{refresh_time} || 3;
 
 445     my $refresh_url  = $self->{refresh_url}  || $ENV{REFERER};
 
 446     push @header, "<meta http-equiv='refresh' content='$refresh_time;$refresh_url'>";
 
 449   my $auto_reload_resources_param = $layout->auto_reload_resources_param;
 
 451   push @header, map { qq|<link rel="stylesheet" href="${_}${auto_reload_resources_param}" type="text/css" title="Stylesheet">| } $layout->stylesheets;
 
 452   push @header, "<style type='text/css'>\@page { size:landscape; }</style> "                     if $self->{landscape};
 
 453   push @header, "<link rel='shortcut icon' href='$self->{favicon}' type='image/x-icon'>"         if -f $self->{favicon};
 
 454   push @header, map { qq|<script type="text/javascript" src="${_}${auto_reload_resources_param}"></script>| }                    $layout->javascripts;
 
 455   push @header, '<meta name="viewport" content="width=device-width, initial-scale=1">';
 
 456   push @header, $self->{javascript} if $self->{javascript};
 
 457   push @header, map { $_->show_javascript } @{ $self->{AJAX} || [] };
 
 460     strict       => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">|,
 
 461     transitional => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">|,
 
 462     frameset     => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">|,
 
 463     html5        => qq|<!DOCTYPE html>|,
 
 467   print $self->create_http_response(content_type => 'text/html', charset => 'UTF-8');
 
 468   print $doctypes{$params{doctype} || 'transitional'}, $/;
 
 472   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 
 473   <title>$self->{titlebar}</title>
 
 475   print "  $_\n" for @header;
 
 477   <meta name="robots" content="noindex,nofollow">
 
 482   print $::request->{layout}->pre_content;
 
 483   print $::request->{layout}->start_content;
 
 485   $layout->header_done;
 
 487   $::lxdebug->leave_sub;
 
 491   return unless $::request->{layout}->need_footer;
 
 493   print $::request->{layout}->end_content;
 
 494   print $::request->{layout}->post_content;
 
 496   if (my @inline_scripts = $::request->{layout}->javascripts_inline) {
 
 497     print "<script type='text/javascript'>" . join("; ", @inline_scripts) . "</script>\n";
 
 506 sub ajax_response_header {
 
 507   $main::lxdebug->enter_sub();
 
 511   my $output = $::request->{cgi}->header('-charset' => 'UTF-8');
 
 513   $main::lxdebug->leave_sub();
 
 518 sub redirect_header {
 
 522   my $base_uri = $self->_get_request_uri;
 
 523   my $new_uri  = URI->new_abs($new_url, $base_uri);
 
 525   die "Headers already sent" if $self->{header};
 
 528   return $::request->{cgi}->redirect($new_uri);
 
 531 sub set_standard_title {
 
 532   $::lxdebug->enter_sub;
 
 535   $self->{titlebar}  = "kivitendo " . $::locale->text('Version') . " " . $self->read_version;
 
 536   $self->{titlebar} .= "- $::myconfig{name}"   if $::myconfig{name};
 
 537   $self->{titlebar} .= "- $::myconfig{dbname}" if $::myconfig{name};
 
 539   $::lxdebug->leave_sub;
 
 542 sub _prepare_html_template {
 
 543   $main::lxdebug->enter_sub();
 
 545   my ($self, $file, $additional_params) = @_;
 
 548   if (!%::myconfig || !$::myconfig{"countrycode"}) {
 
 549     $language = $::lx_office_conf{system}->{language};
 
 551     $language = $main::myconfig{"countrycode"};
 
 553   $language = "de" unless ($language);
 
 555   my $webpages_path = $::request->layout->webpages_path;
 
 557   if (-f "${webpages_path}/${file}.html") {
 
 558     $file = "${webpages_path}/${file}.html";
 
 560   } elsif (ref $file eq 'SCALAR') {
 
 561     # file is a scalarref, use inline mode
 
 563     my $info = "Web page template '${file}' not found.\n";
 
 565     print qq|<pre>$info</pre>|;
 
 566     $::dispatcher->end_request;
 
 569   $additional_params->{AUTH}          = $::auth;
 
 570   $additional_params->{INSTANCE_CONF} = $::instance_conf;
 
 571   $additional_params->{LOCALE}        = $::locale;
 
 572   $additional_params->{LXCONFIG}      = \%::lx_office_conf;
 
 573   $additional_params->{LXDEBUG}       = $::lxdebug;
 
 574   $additional_params->{MYCONFIG}      = \%::myconfig;
 
 576   $main::lxdebug->leave_sub();
 
 581 sub parse_html_template {
 
 582   $main::lxdebug->enter_sub();
 
 584   my ($self, $file, $additional_params) = @_;
 
 586   $additional_params ||= { };
 
 588   my $real_file = $self->_prepare_html_template($file, $additional_params);
 
 589   my $template  = $self->template;
 
 591   map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
 
 594   $template->process($real_file, $additional_params, \$output) || die $template->error;
 
 596   $main::lxdebug->leave_sub();
 
 601 sub template { $::request->presenter->get_template }
 
 603 sub show_generic_error {
 
 604   $main::lxdebug->enter_sub();
 
 606   my ($self, $error, %params) = @_;
 
 608   if ($self->{__ERROR_HANDLER}) {
 
 609     $self->{__ERROR_HANDLER}->($error);
 
 610     $main::lxdebug->leave_sub();
 
 614   if ($::request->is_ajax) {
 
 617       ->render(SL::Controller::Base->new);
 
 618     $::dispatcher->end_request;
 
 622     'title_error' => $params{title},
 
 623     'label_error' => $error,
 
 626   $self->{title} = $params{title} if $params{title};
 
 628   for my $bar ($::request->layout->get('actionbar')) {
 
 632         call      => [ 'kivi.history_back' ],
 
 633         accesskey => 'enter',
 
 639   print $self->parse_html_template("generic/error", $add_params);
 
 641   print STDERR "Error: $error\n";
 
 643   $main::lxdebug->leave_sub();
 
 645   $::dispatcher->end_request;
 
 648 sub show_generic_information {
 
 649   $main::lxdebug->enter_sub();
 
 651   my ($self, $text, $title) = @_;
 
 654     'title_information' => $title,
 
 655     'label_information' => $text,
 
 658   $self->{title} = $title if ($title);
 
 661   print $self->parse_html_template("generic/information", $add_params);
 
 663   $main::lxdebug->leave_sub();
 
 665   $::dispatcher->end_request;
 
 668 sub _store_redirect_info_in_session {
 
 671   return unless $self->{callback} =~ m:^ ( [^\?/]+ \.pl ) \? (.+) :x;
 
 673   my ($controller, $params) = ($1, $2);
 
 674   my $form                  = { map { map { $self->unescape($_) } split /=/, $_, 2 } split m/\&/, $params };
 
 675   $self->{callback}         = "${controller}?RESTORE_FORM_FROM_SESSION_ID=" . $::auth->save_form_in_session(form => $form);
 
 679   $main::lxdebug->enter_sub();
 
 681   my ($self, $msg) = @_;
 
 683   if (!$self->{callback}) {
 
 687     SL::Helper::Flash::flash_later('info', $msg) if $msg;
 
 688     $self->_store_redirect_info_in_session;
 
 689     print $::form->redirect_header($self->{callback});
 
 692   $::dispatcher->end_request;
 
 694   $main::lxdebug->leave_sub();
 
 697 # sort of columns removed - empty sub
 
 699   $main::lxdebug->enter_sub();
 
 701   my ($self, @columns) = @_;
 
 703   $main::lxdebug->leave_sub();
 
 710   my ($self, $myconfig, $amount, $places, $dash) = @_;
 
 711   SL::Helper::Number::_format_number($amount, $places, %$myconfig, dash => $dash);
 
 715   $main::lxdebug->enter_sub(2);
 
 720   $input =~ s/(^|[^\#]) \#  (\d+)  /$1$_[$2 - 1]/gx;
 
 721   $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
 
 722   $input =~ s/\#\#/\#/g;
 
 724   $main::lxdebug->leave_sub(2);
 
 732   my ($self, $myconfig, $amount) = @_;
 
 733   SL::Helper::Number::_parse_number($amount, %$myconfig);
 
 736 sub round_amount { shift; goto &SL::Helper::Number::_round_number; }
 
 739   $main::lxdebug->enter_sub();
 
 741   my ($self, $myconfig) = @_;
 
 742   my ($out, $out_mode);
 
 746   my $defaults        = SL::DB::Default->get;
 
 748   my $keep_temp_files = $::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files};
 
 749   $self->{cwd}        = getcwd();
 
 750   my $temp_dir        = File::Temp->newdir(
 
 751     "kivitendo-print-XXXXXX",
 
 752     DIR     => $self->{cwd} . "/" . $::lx_office_conf{paths}->{userspath},
 
 753     CLEANUP => !$keep_temp_files,
 
 756   my $userspath   = File::Spec->abs2rel($temp_dir->dirname);
 
 757   $self->{tmpdir} = $temp_dir->dirname;
 
 762   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
 
 763     $template_type  = 'OpenDocument';
 
 764     $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
 
 766   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
 
 767     $template_type    = 'LaTeX';
 
 768     $ext_for_format   = 'pdf';
 
 770   } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
 
 771     $template_type  = 'HTML';
 
 772     $ext_for_format = 'html';
 
 774   } elsif ( $self->{"format"} =~ /excel/i ) {
 
 775     $template_type  = 'Excel';
 
 776     $ext_for_format = 'xls';
 
 778   } elsif ( defined $self->{'format'}) {
 
 779     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
 
 781   } elsif ( $self->{'format'} eq '' ) {
 
 782     $self->error("No Outputformat given: $self->{'format'}");
 
 784   } else { #Catch the rest
 
 785     $self->error("Outputformat not defined: $self->{'format'}");
 
 788   my $template = SL::Template::create(type      => $template_type,
 
 789                                       file_name => $self->{IN},
 
 791                                       myconfig  => $myconfig,
 
 792                                       userspath => $userspath,
 
 793                                       %{ $self->{TEMPLATE_DRIVER_OPTIONS} || {} });
 
 795   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
 
 796   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" } if exists $self->{ $self->{"formname"} . "notes" };
 
 798   if (!$self->{employee_id}) {
 
 799     $self->{"employee_${_}"} = $myconfig->{$_} for qw(email tel fax name signature);
 
 800     $self->{"employee_${_}"} = $defaults->$_   for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
 
 803   $self->{"myconfig_${_}"} = $myconfig->{$_} for grep { $_ ne 'dbpasswd' } keys %{ $myconfig };
 
 804   $self->{$_}              = $defaults->$_   for qw(co_ustid);
 
 805   $self->{"myconfig_${_}"} = $defaults->$_   for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
 
 806   $self->{AUTH}            = $::auth;
 
 807   $self->{INSTANCE_CONF}   = $::instance_conf;
 
 808   $self->{LOCALE}          = $::locale;
 
 809   $self->{LXCONFIG}        = $::lx_office_conf;
 
 810   $self->{LXDEBUG}         = $::lxdebug;
 
 811   $self->{MYCONFIG}        = \%::myconfig;
 
 813   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
 
 815   # OUT is used for the media, screen, printer, email
 
 816   # for postscript we store a copy in a temporary file
 
 818   my ($temp_fh, $suffix);
 
 819   $suffix =  $self->{IN};
 
 821   ($temp_fh, $self->{tmpfile}) = File::Temp::tempfile(
 
 822     strftime('kivitendo-print-%Y%m%d%H%M%S-XXXXXX', localtime()),
 
 823     SUFFIX => '.' . ($suffix || 'tex'),
 
 825     UNLINK => $keep_temp_files ? 0 : 1,
 
 828   chmod 0644, $self->{tmpfile} if $keep_temp_files;
 
 829   (undef, undef, $self->{template_meta}{tmpfile}) = File::Spec->splitpath( $self->{tmpfile} );
 
 832   $out_mode         = $self->{OUT_MODE} || '>';
 
 833   $self->{OUT}      = "$self->{tmpfile}";
 
 834   $self->{OUT_MODE} = '>';
 
 837   my $command_formatter = sub {
 
 838     my ($out_mode, $out) = @_;
 
 839     return $out_mode eq '|-' ? SL::Template::create(type => 'ShellCommand', form => $self)->parse($out) : $out;
 
 843     $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
 
 844     open(OUT, $self->{OUT_MODE}, $self->{OUT}) or $self->error("error on opening $self->{OUT} with mode $self->{OUT_MODE} : $!");
 
 846     *OUT = ($::dispatcher->get_standard_filehandles)[1];
 
 850   if (!$template->parse(*OUT)) {
 
 852     $self->error("$self->{IN} : " . $template->get_error());
 
 855   close OUT if $self->{OUT};
 
 856   # check only one flag (webdav_documents)
 
 857   # therefore copy to webdav, even if we do not have the webdav feature enabled (just archive)
 
 858   my $copy_to_webdav =  $::instance_conf->get_webdav_documents && !$self->{preview} && $self->{tmpdir} && $self->{tmpfile} && $self->{type}
 
 859                         && $self->{type} ne 'statement';
 
 861   $self->{attachment_filename} ||= $self->generate_attachment_filename;
 
 863   if ( $ext_for_format eq 'pdf' && $self->doc_storage_enabled ) {
 
 864     $self->append_general_pdf_attachments(filepath =>  $self->{tmpdir}."/".$self->{tmpfile},
 
 865                                           type     =>  $self->{type});
 
 867   if ($self->{media} eq 'file') {
 
 868     copy(join('/', $self->{cwd}, $userspath, $self->{tmpfile}), $out =~ m|^/| ? $out : join('/', $self->{cwd}, $out)) if $template->uses_temp_file;
 
 870     if ($copy_to_webdav) {
 
 871       if (my $error = Common::copy_file_to_webdav_folder($self)) {
 
 872         chdir("$self->{cwd}");
 
 873         $self->error($error);
 
 877     if (!$self->{preview} && $self->{attachment_type} !~ m{^dunning} && $self->doc_storage_enabled)
 
 879       $self->store_pdf($self);
 
 882     chdir("$self->{cwd}");
 
 884     $::lxdebug->leave_sub();
 
 889   if ($copy_to_webdav) {
 
 890     if (my $error = Common::copy_file_to_webdav_folder($self)) {
 
 891       chdir("$self->{cwd}");
 
 892       $self->error($error);
 
 896   if ( !$self->{preview} && $ext_for_format eq 'pdf' && $self->{attachment_type} !~ m{^dunning} && $self->doc_storage_enabled) {
 
 897     my $file_obj = $self->store_pdf($self);
 
 898     $self->{print_file_id} = $file_obj->id if $file_obj;
 
 900   if ($self->{media} eq 'email') {
 
 901     if ( getcwd() eq $self->{"tmpdir"} ) {
 
 902       # in the case of generating pdf we are in the tmpdir, but WHY ???
 
 903       $self->{tmpfile} = $userspath."/".$self->{tmpfile};
 
 904       chdir("$self->{cwd}");
 
 906     $self->send_email(\%::myconfig,$ext_for_format);
 
 910     $self->{OUT_MODE} = $out_mode;
 
 911     $self->output_file($template->get_mime_type,$command_formatter);
 
 913   delete $self->{print_file_id};
 
 917   chdir("$self->{cwd}");
 
 918   $main::lxdebug->leave_sub();
 
 921 sub get_bcc_defaults {
 
 922   my ($self, $myconfig, $mybcc) = @_;
 
 923   if (SL::DB::Default->get->bcc_to_login) {
 
 924     $mybcc .= ", " if $mybcc;
 
 925     $mybcc .= $myconfig->{email};
 
 927   my $otherbcc = SL::DB::Default->get->global_bcc;
 
 929     $mybcc .= ", " if $mybcc;
 
 936   $main::lxdebug->enter_sub();
 
 937   my ($self, $myconfig, $ext_for_format) = @_;
 
 938   my $mail = Mailer->new;
 
 940   map { $mail->{$_} = $self->{$_} }
 
 941     qw(cc subject message format);
 
 943   if ($self->{cc_employee}) {
 
 944     my ($user, $my_emp_cc);
 
 945     $user        = SL::DB::Manager::AuthUser->find_by(login => $self->{cc_employee});
 
 946     $my_emp_cc   = $user->get_config_value('email') if ref $user eq 'SL::DB::AuthUser';
 
 947     $mail->{cc} .= ", "       if $mail->{cc};
 
 948     $mail->{cc} .= $my_emp_cc if $my_emp_cc;
 
 951   $mail->{bcc}    = $self->get_bcc_defaults($myconfig, $self->{bcc});
 
 952   $mail->{to}     = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
 
 953   $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
 
 954   $mail->{fileid} = time() . '.' . $$ . '.';
 
 955   $mail->{content_type}  =  "text/html";
 
 956   my $full_signature     =  $self->create_email_signature();
 
 958   $mail->{attachments} =  [];
 
 960   # if we send html or plain text inline
 
 961   if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
 
 962     $mail->{message}        =~ s/\r//g;
 
 963     $mail->{message}        =~ s{\n}{<br>\n}g;
 
 964     $mail->{message}       .=  $full_signature;
 
 966     open(IN, "<", $self->{tmpfile})
 
 967       or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
 968     $mail->{message} .= $_ while <IN>;
 
 971   } elsif (($self->{attachment_policy} // '') ne 'no_file') {
 
 972     my $attachment_name  =  $self->{attachment_filename}  || $self->{tmpfile};
 
 973     $attachment_name     =~ s{\.(.+?)$}{.${ext_for_format}} if ($ext_for_format);
 
 975     if (($self->{attachment_policy} // '') eq 'old_file') {
 
 976       my ( $attfile ) = SL::File->get_all(object_id     => $self->{id},
 
 977                                           object_type   => $self->{type},
 
 978                                           file_type     => 'document',
 
 979                                           print_variant => $self->{formname},);
 
 982         $attfile->{override_file_name} = $attachment_name if $attachment_name;
 
 983         push @attfiles, $attfile;
 
 987       push @{ $mail->{attachments} }, { path => $self->{tmpfile},
 
 988                                         id   => $self->{print_file_id},
 
 989                                         type => "application/pdf",
 
 990                                         name => $attachment_name };
 
 996     map  { SL::File->get(id => $_) }
 
 997     @{ $self->{attach_file_ids} // [] };
 
 999   foreach my $attfile ( @attfiles ) {
 
1000     push @{ $mail->{attachments} }, {
 
1001       path    => $attfile->get_file,
 
1003       type    => $attfile->mime_type,
 
1004       name    => $attfile->{override_file_name} // $attfile->file_name,
 
1005       content => $attfile->get_content ? ${ $attfile->get_content } : undef,
 
1009   $mail->{message}  =~ s/\r//g;
 
1010   $mail->{message} .= $full_signature;
 
1011   $self->{emailerr} = $mail->send();
 
1013   if ($self->{emailerr}) {
 
1015     $self->error($::locale->text('The email was not sent due to the following error: #1.', $self->{emailerr}));
 
1018   $self->{email_journal_id} = $mail->{journalentry};
 
1019   $self->{snumbers}  = "emailjournal" . "_" . $self->{email_journal_id};
 
1020   $self->{what_done} = $::form->{type};
 
1021   $self->{addition}  = "MAILED";
 
1022   $self->save_history;
 
1024   #write back for message info and mail journal
 
1025   $self->{cc}  = $mail->{cc};
 
1026   $self->{bcc} = $mail->{bcc};
 
1027   $self->{email} = $mail->{to};
 
1029   $main::lxdebug->leave_sub();
 
1033   $main::lxdebug->enter_sub();
 
1035   my ($self,$mimeType,$command_formatter) = @_;
 
1036   my $numbytes = (-s $self->{tmpfile});
 
1037   open(IN, "<", $self->{tmpfile})
 
1038     or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1041   $self->{copies} = 1 unless $self->{media} eq 'printer';
 
1043   chdir("$self->{cwd}");
 
1044   for my $i (1 .. $self->{copies}) {
 
1046       $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
 
1048       open  OUT, $self->{OUT_MODE}, $self->{OUT} or $self->error($self->cleanup . "$self->{OUT} : $!");
 
1049       print OUT $_ while <IN>;
 
1054       my %headers = ('-type'       => $mimeType,
 
1055                      '-connection' => 'close',
 
1056                      '-charset'    => 'UTF-8');
 
1058       $self->{attachment_filename} ||= $self->generate_attachment_filename;
 
1060       if ($self->{attachment_filename}) {
 
1063           '-attachment'     => $self->{attachment_filename},
 
1064           '-content-length' => $numbytes,
 
1069       print $::request->cgi->header(%headers);
 
1071       $::locale->with_raw_io(\*STDOUT, sub { print while <IN> });
 
1075   $main::lxdebug->leave_sub();
 
1078 sub get_formname_translation {
 
1079   $main::lxdebug->enter_sub();
 
1080   my ($self, $formname) = @_;
 
1082   $formname ||= $self->{formname};
 
1084   $self->{recipient_locale} ||=  Locale->lang_to_locale($self->{language});
 
1085   local $::locale = Locale->new($self->{recipient_locale});
 
1087   my %formname_translations = (
 
1088     bin_list                => $main::locale->text('Bin List'),
 
1089     credit_note             => $main::locale->text('Credit Note'),
 
1090     invoice                 => $main::locale->text('Invoice'),
 
1091     invoice_copy            => $main::locale->text('Invoice Copy'),
 
1092     invoice_for_advance_payment => $main::locale->text('Invoice for Advance Payment'),
 
1093     final_invoice           => $main::locale->text('Final Invoice'),
 
1094     pick_list               => $main::locale->text('Pick List'),
 
1095     proforma                => $main::locale->text('Proforma Invoice'),
 
1096     purchase_order          => $main::locale->text('Purchase Order'),
 
1097     request_quotation       => $main::locale->text('RFQ'),
 
1098     sales_order             => $main::locale->text('Confirmation'),
 
1099     sales_quotation         => $main::locale->text('Quotation'),
 
1100     storno_invoice          => $main::locale->text('Storno Invoice'),
 
1101     sales_delivery_order    => $main::locale->text('Delivery Order'),
 
1102     purchase_delivery_order => $main::locale->text('Delivery Order'),
 
1103     dunning                 => $main::locale->text('Dunning'),
 
1104     dunning1                => $main::locale->text('Payment Reminder'),
 
1105     dunning2                => $main::locale->text('Dunning'),
 
1106     dunning3                => $main::locale->text('Last Dunning'),
 
1107     dunning_invoice         => $main::locale->text('Dunning Invoice'),
 
1108     letter                  => $main::locale->text('Letter'),
 
1109     ic_supply               => $main::locale->text('Intra-Community supply'),
 
1110     statement               => $main::locale->text('Statement'),
 
1113   $main::lxdebug->leave_sub();
 
1114   return $formname_translations{$formname};
 
1117 sub get_cusordnumber_translation {
 
1118   $main::lxdebug->enter_sub();
 
1119   my ($self, $formname) = @_;
 
1121   $formname ||= $self->{formname};
 
1123   $self->{recipient_locale} ||=  Locale->lang_to_locale($self->{language});
 
1124   local $::locale = Locale->new($self->{recipient_locale});
 
1127   $main::lxdebug->leave_sub();
 
1128   return $main::locale->text('Your Order');
 
1131 sub get_number_prefix_for_type {
 
1132   $main::lxdebug->enter_sub();
 
1136       (first { $self->{type} eq $_ } qw(invoice invoice_for_advance_payment final_invoice credit_note)) ? 'inv'
 
1137     : ($self->{type} =~ /_quotation$/)                        ? 'quo'
 
1138     : ($self->{type} =~ /_delivery_order$/)                   ? 'do'
 
1139     : ($self->{type} =~ /letter/)                             ? 'letter'
 
1142   # better default like this?
 
1143   # : ($self->{type} =~ /(sales|purcharse)_order/           :  'ord';
 
1144   # :                                                           'prefix_undefined';
 
1146   $main::lxdebug->leave_sub();
 
1150 sub get_extension_for_format {
 
1151   $main::lxdebug->enter_sub();
 
1154   my $extension = $self->{format} =~ /pdf/i          ? ".pdf"
 
1155                 : $self->{format} =~ /postscript/i   ? ".ps"
 
1156                 : $self->{format} =~ /opendocument/i ? ".odt"
 
1157                 : $self->{format} =~ /excel/i        ? ".xls"
 
1158                 : $self->{format} =~ /html/i         ? ".html"
 
1161   $main::lxdebug->leave_sub();
 
1165 sub generate_attachment_filename {
 
1166   $main::lxdebug->enter_sub();
 
1169   $self->{recipient_locale} ||=  Locale->lang_to_locale($self->{language});
 
1170   my $recipient_locale = Locale->new($self->{recipient_locale});
 
1172   my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
 
1173   my $prefix              = $self->get_number_prefix_for_type();
 
1175   if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice invoice_for_advance_payment final_invoice credit_note))) {
 
1176     $attachment_filename .= ' (' . $recipient_locale->text('Preview') . ')' . $self->get_extension_for_format();
 
1178   } elsif ($attachment_filename && $self->{"${prefix}number"}) {
 
1179     $attachment_filename .=  "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
 
1181   } elsif ($attachment_filename) {
 
1182     $attachment_filename .=  $self->get_extension_for_format();
 
1185     $attachment_filename = "";
 
1188   $attachment_filename =  $main::locale->quote_special_chars('filenames', $attachment_filename);
 
1189   $attachment_filename =~ s|[\s/\\]+|_|g;
 
1191   $main::lxdebug->leave_sub();
 
1192   return $attachment_filename;
 
1195 sub generate_email_subject {
 
1196   $main::lxdebug->enter_sub();
 
1199   my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
 
1200   my $prefix  = $self->get_number_prefix_for_type();
 
1202   if ($subject && $self->{"${prefix}number"}) {
 
1203     $subject .= " " . $self->{"${prefix}number"}
 
1206   if ($self->{cusordnumber}) {
 
1207     $subject = $self->get_cusordnumber_translation() . ' ' . $self->{cusordnumber} . ' / ' . $subject;
 
1210   $main::lxdebug->leave_sub();
 
1214 sub generate_email_body {
 
1215   $main::lxdebug->enter_sub();
 
1216   my ($self, %params) = @_;
 
1217   # simple german and english will work grammatically (most european languages as well)
 
1218   # Dear Mr Alan Greenspan:
 
1219   # Sehr geehrte Frau Meyer,
 
1220   # A l’attention de Mme Villeroy,
 
1221   # Gentile Signora Ferrari,
 
1224   if ($self->{cp_id} && !$params{record_email}) {
 
1225     my $givenname = SL::DB::Contact->load_cached($self->{cp_id})->cp_givenname; # for qw(gender givename name);
 
1226     my $name      = SL::DB::Contact->load_cached($self->{cp_id})->cp_name; # for qw(gender givename name);
 
1227     my $gender    = SL::DB::Contact->load_cached($self->{cp_id})->cp_gender; # for qw(gender givename name);
 
1228     my $mf = $gender eq 'f' ? 'female' : 'male';
 
1229     $body  = GenericTranslations->get(translation_type => "salutation_$mf", language_id => $self->{language_id});
 
1230     $body .= ' ' . $givenname . ' ' . $name if $body;
 
1232     $body  = GenericTranslations->get(translation_type => "salutation_general", language_id => $self->{language_id});
 
1235   return undef unless $body;
 
1237   $body .= GenericTranslations->get(translation_type => "salutation_punctuation_mark", language_id => $self->{language_id});
 
1238   $body  = '<p>' . $::locale->quote_special_chars('HTML', $body) . '</p>';
 
1240   my $translation_type = $params{translation_type} // "preset_text_$self->{formname}";
 
1241   my $main_body        = GenericTranslations->get(translation_type => $translation_type,                  language_id => $self->{language_id});
 
1242   $main_body           = GenericTranslations->get(translation_type => $params{fallback_translation_type}, language_id => $self->{language_id}) if !$main_body && $params{fallback_translation_type};
 
1243   $body               .= $main_body;
 
1245   $body = $main::locale->unquote_special_chars('HTML', $body);
 
1247   $main::lxdebug->leave_sub();
 
1252   $main::lxdebug->enter_sub();
 
1254   my ($self, $application) = @_;
 
1256   my $error_code = $?;
 
1258   chdir("$self->{tmpdir}");
 
1261   if ((-1 == $error_code) || (127 == (($error_code) >> 8))) {
 
1262     push @err, $::locale->text('The application "#1" was not found on the system.', $application || 'pdflatex') . ' ' . $::locale->text('Please contact your administrator.');
 
1264   } elsif (-f "$self->{tmpfile}.err") {
 
1265     open(FH, "<:encoding(UTF-8)", "$self->{tmpfile}.err");
 
1270   if ($self->{tmpfile} && !($::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files})) {
 
1271     $self->{tmpfile} =~ s|.*/||g;
 
1273     $self->{tmpfile} =~ s/\.\w+$//g;
 
1274     my $tmpfile = $self->{tmpfile};
 
1275     unlink(<$tmpfile.*>);
 
1278   chdir("$self->{cwd}");
 
1280   $main::lxdebug->leave_sub();
 
1286   $main::lxdebug->enter_sub();
 
1288   my ($self, $date, $myconfig) = @_;
 
1291   if ($date && $date =~ /\D/) {
 
1293     if ($myconfig->{dateformat} =~ /^yy/) {
 
1294       ($yy, $mm, $dd) = split /\D/, $date;
 
1296     if ($myconfig->{dateformat} =~ /^mm/) {
 
1297       ($mm, $dd, $yy) = split /\D/, $date;
 
1299     if ($myconfig->{dateformat} =~ /^dd/) {
 
1300       ($dd, $mm, $yy) = split /\D/, $date;
 
1305     $yy = ($yy < 70) ? $yy + 2000 : $yy;
 
1306     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
 
1308     $dd = "0$dd" if ($dd < 10);
 
1309     $mm = "0$mm" if ($mm < 10);
 
1311     $date = "$yy$mm$dd";
 
1314   $main::lxdebug->leave_sub();
 
1319 # Database routines used throughout
 
1320 # DB Handling got moved to SL::DB, these are only shims for compatibility
 
1323   SL::DB->client->dbh;
 
1326 sub get_standard_dbh {
 
1327   my $dbh = SL::DB->client->dbh;
 
1329   if ($dbh && !$dbh->{Active}) {
 
1330     $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$dbh is defined but not Active anymore");
 
1331     SL::DB->client->dbh(undef);
 
1334   SL::DB->client->dbh;
 
1337 sub disconnect_standard_dbh {
 
1338   SL::DB->client->dbh->rollback;
 
1344   $main::lxdebug->enter_sub();
 
1346   my ($self, $date, $myconfig) = @_;
 
1347   my $dbh = $self->get_standard_dbh;
 
1349   my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
 
1350   my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
 
1352   # Falls $date = '' - Fehlermeldung aus der Datenbank. Ich denke,
 
1353   # es ist sicher ein conv_date vorher IMMER auszuführen.
 
1354   # Testfälle ohne definiertes closedto:
 
1355   #   Leere Datumseingabe i.O.
 
1356   #     SELECT 1 FROM defaults WHERE '' < closedto
 
1357   #   normale Zahlungsbuchung Ã¼ber Rechnungsmaske i.O.
 
1358   #     SELECT 1 FROM defaults WHERE '10.05.2011' < closedto
 
1359   # Testfälle mit definiertem closedto (30.04.2011):
 
1360   #  Leere Datumseingabe i.O.
 
1361   #   SELECT 1 FROM defaults WHERE '' < closedto
 
1362   # normale Buchung im geschloßenem Zeitraum i.O.
 
1363   #   SELECT 1 FROM defaults WHERE '21.04.2011' < closedto
 
1364   #     Fehlermeldung: Es können keine Zahlungen für abgeschlossene Bücher gebucht werden!
 
1365   # normale Buchung in aktiver Buchungsperiode i.O.
 
1366   #   SELECT 1 FROM defaults WHERE '01.05.2011' < closedto
 
1368   my ($closed) = $sth->fetchrow_array;
 
1370   $main::lxdebug->leave_sub();
 
1375 # prevents bookings to the to far away future
 
1376 sub date_max_future {
 
1377   $main::lxdebug->enter_sub();
 
1379   my ($self, $date, $myconfig) = @_;
 
1380   my $dbh = $self->get_standard_dbh;
 
1382   my $query = "SELECT 1 FROM defaults WHERE ? - current_date > max_future_booking_interval";
 
1383   my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
 
1385   my ($max_future_booking_interval) = $sth->fetchrow_array;
 
1387   $main::lxdebug->leave_sub();
 
1389   return $max_future_booking_interval;
 
1393 sub update_balance {
 
1394   $main::lxdebug->enter_sub();
 
1396   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
 
1398   # if we have a value, go do it
 
1401     # retrieve balance from table
 
1402     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
 
1403     my $sth = prepare_execute_query($self, $dbh, $query, @values);
 
1404     my ($balance) = $sth->fetchrow_array;
 
1410     $query = "UPDATE $table SET $field = $balance WHERE $where";
 
1411     do_query($self, $dbh, $query, @values);
 
1413   $main::lxdebug->leave_sub();
 
1416 sub update_exchangerate {
 
1417   $main::lxdebug->enter_sub();
 
1419   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
 
1421   # some sanity check for currency
 
1423     $main::lxdebug->leave_sub();
 
1426   $query = qq|SELECT name AS curr FROM currencies WHERE id=(SELECT currency_id FROM defaults)|;
 
1428   my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
 
1430   if ($curr eq $defaultcurrency) {
 
1431     $main::lxdebug->leave_sub();
 
1435   $query = qq|SELECT e.currency_id FROM exchangerate e
 
1436                  WHERE e.currency_id = (SELECT cu.id FROM currencies cu WHERE cu.name=?) AND e.transdate = ?
 
1438   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
 
1447   $buy = conv_i($buy, "NULL");
 
1448   $sell = conv_i($sell, "NULL");
 
1451   if ($buy != 0 && $sell != 0) {
 
1452     $set = "buy = $buy, sell = $sell";
 
1453   } elsif ($buy != 0) {
 
1454     $set = "buy = $buy";
 
1455   } elsif ($sell != 0) {
 
1456     $set = "sell = $sell";
 
1459   if ($sth->fetchrow_array) {
 
1460     $query = qq|UPDATE exchangerate
 
1462                 WHERE currency_id = (SELECT id FROM currencies WHERE name = ?)
 
1466     $query = qq|INSERT INTO exchangerate (currency_id, buy, sell, transdate)
 
1467                 VALUES ((SELECT id FROM currencies WHERE name = ?), $buy, $sell, ?)|;
 
1470   do_query($self, $dbh, $query, $curr, $transdate);
 
1472   $main::lxdebug->leave_sub();
 
1475 sub save_exchangerate {
 
1476   $main::lxdebug->enter_sub();
 
1478   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
 
1480   SL::DB->client->with_transaction(sub {
 
1481     my $dbh = SL::DB->client->dbh;
 
1485     $buy  = $rate if $fld eq 'buy';
 
1486     $sell = $rate if $fld eq 'sell';
 
1489     $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
 
1491   }) or do { die SL::DB->client->error };
 
1493   $main::lxdebug->leave_sub();
 
1496 sub get_exchangerate {
 
1497   $main::lxdebug->enter_sub();
 
1499   my ($self, $dbh, $curr, $transdate, $fld) = @_;
 
1502   unless ($transdate && $curr) {
 
1503     $main::lxdebug->leave_sub();
 
1507   $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
 
1509   my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
 
1511   if ($curr eq $defaultcurrency) {
 
1512     $main::lxdebug->leave_sub();
 
1516   $query = qq|SELECT e.$fld FROM exchangerate e
 
1517                  WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
 
1518   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
 
1522   $main::lxdebug->leave_sub();
 
1524   return $exchangerate;
 
1527 sub check_exchangerate {
 
1528   $main::lxdebug->enter_sub();
 
1530   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
 
1532   if ($fld !~/^buy|sell$/) {
 
1533     $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
 
1536   unless ($transdate) {
 
1537     $main::lxdebug->leave_sub();
 
1541   my ($defaultcurrency) = $self->get_default_currency($myconfig);
 
1543   if ($currency eq $defaultcurrency) {
 
1544     $main::lxdebug->leave_sub();
 
1548   my $dbh   = $self->get_standard_dbh($myconfig);
 
1549   my $query = qq|SELECT e.$fld FROM exchangerate e
 
1550                  WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
 
1552   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
 
1554   $main::lxdebug->leave_sub();
 
1556   return $exchangerate;
 
1559 sub get_all_currencies {
 
1560   $main::lxdebug->enter_sub();
 
1563   my $myconfig = shift || \%::myconfig;
 
1564   my $dbh      = $self->get_standard_dbh($myconfig);
 
1566   my $query = qq|SELECT name FROM currencies|;
 
1567   my @currencies = map { $_->{name} } selectall_hashref_query($self, $dbh, $query);
 
1569   $main::lxdebug->leave_sub();
 
1574 sub get_default_currency {
 
1575   $main::lxdebug->enter_sub();
 
1577   my ($self, $myconfig) = @_;
 
1578   my $dbh      = $self->get_standard_dbh($myconfig);
 
1579   my $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
 
1581   my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
 
1583   $main::lxdebug->leave_sub();
 
1585   return $defaultcurrency;
 
1588 sub set_payment_options {
 
1589   my ($self, $myconfig, $transdate, $type) = @_;
 
1591   my $terms = $self->{payment_id} ? SL::DB::PaymentTerm->new(id => $self->{payment_id})->load : undef;
 
1594   my $is_invoice                = $type =~ m{invoice}i;
 
1596   $transdate                  ||= $self->{invdate} || $self->{transdate};
 
1597   my $due_date                  = $self->{duedate} || $self->{reqdate};
 
1599   $self->{$_}                   = $terms->$_ for qw(terms_netto terms_skonto percent_skonto);
 
1600   $self->{payment_description}  = $terms->description;
 
1601   $self->{netto_date}           = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'net')->to_kivitendo;
 
1602   $self->{skonto_date}          = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'discount')->to_kivitendo;
 
1604   my ($invtotal, $total);
 
1605   my (%amounts, %formatted_amounts);
 
1607   if ($self->{type} =~ /_order$/) {
 
1608     $amounts{invtotal} = $self->{ordtotal};
 
1609     $amounts{total}    = $self->{ordtotal};
 
1611   } elsif ($self->{type} =~ /_quotation$/) {
 
1612     $amounts{invtotal} = $self->{quototal};
 
1613     $amounts{total}    = $self->{quototal};
 
1616     $amounts{invtotal} = $self->{invtotal};
 
1617     $amounts{total}    = $self->{total};
 
1619   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
 
1621   $amounts{skonto_in_percent}  = 100.0 * $self->{percent_skonto};
 
1622   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
 
1623   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
 
1624   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
 
1626   foreach (keys %amounts) {
 
1627     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
 
1628     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
 
1631   if ($self->{"language_id"}) {
 
1632     my $language             = SL::DB::Language->new(id => $self->{language_id})->load;
 
1634     $self->{payment_terms}   = $type =~ m{invoice}i ? $terms->translated_attribute('description_long_invoice', $language->id) : undef;
 
1635     $self->{payment_terms} ||= $terms->translated_attribute('description_long', $language->id);
 
1637     if ($language->output_dateformat) {
 
1638       foreach my $key (qw(netto_date skonto_date)) {
 
1639         $self->{$key} = $::locale->reformat_date($myconfig, $self->{$key}, $language->output_dateformat, $language->output_longdates);
 
1643     if ($language->output_numberformat && ($language->output_numberformat ne $myconfig->{numberformat})) {
 
1644       local $myconfig->{numberformat};
 
1645       $myconfig->{"numberformat"} = $language->output_numberformat;
 
1646       $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) for keys %amounts;
 
1650   $self->{payment_terms} =  $self->{payment_terms} || ($is_invoice ? $terms->description_long_invoice : undef) || $terms->description_long;
 
1652   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
 
1653   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
 
1654   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
 
1655   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
 
1656   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
 
1657   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
 
1658   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
 
1659   $self->{payment_terms} =~ s/<\%bic\%>/$self->{bic}/g;
 
1660   $self->{payment_terms} =~ s/<\%iban\%>/$self->{iban}/g;
 
1661   $self->{payment_terms} =~ s/<\%mandate_date_of_signature\%>/$self->{mandate_date_of_signature}/g;
 
1662   $self->{payment_terms} =~ s/<\%mandator_id\%>/$self->{mandator_id}/g;
 
1664   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
 
1666   $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
 
1670 sub get_template_language {
 
1671   $main::lxdebug->enter_sub();
 
1673   my ($self, $myconfig) = @_;
 
1675   my $template_code = "";
 
1677   if ($self->{language_id}) {
 
1678     my $dbh = $self->get_standard_dbh($myconfig);
 
1679     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
 
1680     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
 
1683   $main::lxdebug->leave_sub();
 
1685   return $template_code;
 
1688 sub get_printer_code {
 
1689   $main::lxdebug->enter_sub();
 
1691   my ($self, $myconfig) = @_;
 
1693   my $template_code = "";
 
1695   if ($self->{printer_id}) {
 
1696     my $dbh = $self->get_standard_dbh($myconfig);
 
1697     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
 
1698     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
 
1701   $main::lxdebug->leave_sub();
 
1703   return $template_code;
 
1707   $main::lxdebug->enter_sub();
 
1709   my ($self, $myconfig) = @_;
 
1711   my $template_code = "";
 
1713   if ($self->{shipto_id}) {
 
1714     my $dbh = $self->get_standard_dbh($myconfig);
 
1715     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
 
1716     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
 
1717     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
 
1719     my $cvars = CVar->get_custom_variables(
 
1722       trans_id => $self->{shipto_id},
 
1724     $self->{"shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
 
1727   $main::lxdebug->leave_sub();
 
1731   my ($self, $dbh, $id, $module) = @_;
 
1736   foreach my $item (qw(name department_1 department_2 street zipcode city country gln
 
1737                        contact phone fax email)) {
 
1738     if ($self->{"shipto$item"}) {
 
1739       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
 
1741     push(@values, $self->{"shipto${item}"});
 
1746   # shiptocp_gender only makes sense, if any other shipto attribute is set.
 
1747   # Because shiptocp_gender is set to 'm' by default in forms
 
1748   # it must not be considered above to decide if shiptos has to be added or
 
1749   # updated, but must be inserted or updated as well in case.
 
1750   push(@values, $self->{shiptocp_gender});
 
1752   my $shipto_id = $self->{shipto_id};
 
1754   if ($self->{shipto_id}) {
 
1755     my $query = qq|UPDATE shipto set
 
1757                      shiptodepartment_1 = ?,
 
1758                      shiptodepartment_2 = ?,
 
1768                      shiptocp_gender = ?,
 
1769                    WHERE shipto_id = ?|;
 
1770     do_query($self, $dbh, $query, @values, $self->{shipto_id});
 
1772     my $query = qq|SELECT * FROM shipto
 
1773                    WHERE shiptoname = ? AND
 
1774                      shiptodepartment_1 = ? AND
 
1775                      shiptodepartment_2 = ? AND
 
1776                      shiptostreet = ? AND
 
1777                      shiptozipcode = ? AND
 
1779                      shiptocountry = ? AND
 
1781                      shiptocontact = ? AND
 
1785                      shiptocp_gender = ? AND
 
1788     my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
 
1791         qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
 
1792                                shiptostreet, shiptozipcode, shiptocity, shiptocountry, shiptogln,
 
1793                                shiptocontact, shiptophone, shiptofax, shiptoemail, shiptocp_gender, module)
 
1794            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
 
1795       do_query($self, $dbh, $insert_query, $id, @values, $module);
 
1797       $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
 
1800     $shipto_id = $insert_check->{shipto_id};
 
1803   return unless $shipto_id;
 
1805   CVar->save_custom_variables(
 
1808     trans_id    => $shipto_id,
 
1810     name_prefix => 'shipto',
 
1815   $main::lxdebug->enter_sub();
 
1817   my ($self, $dbh) = @_;
 
1819   $dbh ||= $self->get_standard_dbh(\%main::myconfig);
 
1821   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
 
1822   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
 
1823   $self->{"employee_id"} *= 1;
 
1825   $main::lxdebug->leave_sub();
 
1828 sub get_employee_data {
 
1829   $main::lxdebug->enter_sub();
 
1833   my $defaults = SL::DB::Default->get;
 
1835   Common::check_params(\%params, qw(prefix));
 
1836   Common::check_params_x(\%params, qw(id));
 
1839     $main::lxdebug->leave_sub();
 
1843   my $myconfig = \%main::myconfig;
 
1844   my $dbh      = $params{dbh} || $self->get_standard_dbh($myconfig);
 
1846   my ($login, $deleted)  = selectrow_query($self, $dbh, qq|SELECT login,deleted FROM employee WHERE id = ?|, conv_i($params{id}));
 
1849     # login already fetched and still the same client (mandant) | same for both cases (delete|!delete)
 
1850     $self->{$params{prefix} . '_login'}   = $login;
 
1851     $self->{$params{prefix} . "_${_}"}    = $defaults->$_ for qw(address businessnumber co_ustid company duns taxnumber);
 
1854       # get employee data from auth.user_config
 
1855       my $user = User->new(login => $login);
 
1856       $self->{$params{prefix} . "_${_}"} = $user->{$_} for qw(email fax name signature tel);
 
1858       # get saved employee data from employee
 
1859       my $employee = SL::DB::Manager::Employee->find_by(id => conv_i($params{id}));
 
1860       $self->{$params{prefix} . "_${_}"} = $employee->{"deleted_$_"} for qw(email fax signature tel);
 
1861       $self->{$params{prefix} . "_name"} = $employee->name;
 
1864   $main::lxdebug->leave_sub();
 
1868   $main::lxdebug->enter_sub();
 
1870   my ($self, $dbh, $id, $key) = @_;
 
1872   $key = "all_contacts" unless ($key);
 
1876     $main::lxdebug->leave_sub();
 
1881     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
 
1882     qq|FROM contacts | .
 
1883     qq|WHERE cp_cv_id = ? | .
 
1884     qq|ORDER BY lower(cp_name)|;
 
1886   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
 
1888   $main::lxdebug->leave_sub();
 
1892   $main::lxdebug->enter_sub();
 
1894   my ($self, $dbh, $key) = @_;
 
1896   my ($all, $old_id, $where, @values);
 
1898   if (ref($key) eq "HASH") {
 
1901     $key = "ALL_PROJECTS";
 
1903     foreach my $p (keys(%{$params})) {
 
1905         $all = $params->{$p};
 
1906       } elsif ($p eq "old_id") {
 
1907         $old_id = $params->{$p};
 
1908       } elsif ($p eq "key") {
 
1909         $key = $params->{$p};
 
1915     $where = "WHERE active ";
 
1917       if (ref($old_id) eq "ARRAY") {
 
1918         my @ids = grep({ $_ } @{$old_id});
 
1920           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
 
1921           push(@values, @ids);
 
1924         $where .= " OR (id = ?) ";
 
1925         push(@values, $old_id);
 
1931     qq|SELECT id, projectnumber, description, active | .
 
1934     qq|ORDER BY lower(projectnumber)|;
 
1936   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
 
1938   $main::lxdebug->leave_sub();
 
1942   $main::lxdebug->enter_sub();
 
1944   my ($self, $dbh, $key) = @_;
 
1946   $key = "all_printers" unless ($key);
 
1948   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
 
1950   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1952   $main::lxdebug->leave_sub();
 
1956   $main::lxdebug->enter_sub();
 
1958   my ($self, $dbh, $params) = @_;
 
1961   $key = $params->{key};
 
1962   $key = "all_charts" unless ($key);
 
1964   my $transdate = quote_db_date($params->{transdate});
 
1967     qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
 
1969     qq|LEFT JOIN taxkeys tk ON | .
 
1970     qq|(tk.id = (SELECT id FROM taxkeys | .
 
1971     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
 
1972     qq|          ORDER BY startdate DESC LIMIT 1)) | .
 
1973     qq|ORDER BY c.accno|;
 
1975   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1977   $main::lxdebug->leave_sub();
 
1981   $main::lxdebug->enter_sub();
 
1983   my ($self, $dbh, $key) = @_;
 
1985   $key = "all_taxzones" unless ($key);
 
1987   $tzfilter = "WHERE obsolete is FALSE" if $key eq 'ALL_ACTIVE_TAXZONES';
 
1989   my $query = qq|SELECT * FROM tax_zones $tzfilter ORDER BY sortkey|;
 
1991   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1993   $main::lxdebug->leave_sub();
 
1996 sub _get_employees {
 
1997   $main::lxdebug->enter_sub();
 
1999   my ($self, $dbh, $params) = @_;
 
2004   if (ref $params eq 'HASH') {
 
2005     $key     = $params->{key};
 
2006     $deleted = $params->{deleted};
 
2012   $key     ||= "all_employees";
 
2013   my $filter = $deleted ? '' : 'WHERE NOT COALESCE(deleted, FALSE)';
 
2014   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee $filter ORDER BY lower(name)|);
 
2016   $main::lxdebug->leave_sub();
 
2019 sub _get_business_types {
 
2020   $main::lxdebug->enter_sub();
 
2022   my ($self, $dbh, $key) = @_;
 
2024   my $options       = ref $key eq 'HASH' ? $key : { key => $key };
 
2025   $options->{key} ||= "all_business_types";
 
2028   if (exists $options->{salesman}) {
 
2029     $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
 
2032   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
 
2034   $main::lxdebug->leave_sub();
 
2037 sub _get_languages {
 
2038   $main::lxdebug->enter_sub();
 
2040   my ($self, $dbh, $key) = @_;
 
2042   $key = "all_languages" unless ($key);
 
2044   my $query = qq|SELECT * FROM language ORDER BY id|;
 
2046   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2048   $main::lxdebug->leave_sub();
 
2051 sub _get_dunning_configs {
 
2052   $main::lxdebug->enter_sub();
 
2054   my ($self, $dbh, $key) = @_;
 
2056   $key = "all_dunning_configs" unless ($key);
 
2058   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
 
2060   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2062   $main::lxdebug->leave_sub();
 
2065 sub _get_currencies {
 
2066 $main::lxdebug->enter_sub();
 
2068   my ($self, $dbh, $key) = @_;
 
2070   $key = "all_currencies" unless ($key);
 
2072   $self->{$key} = [$self->get_all_currencies()];
 
2074   $main::lxdebug->leave_sub();
 
2078 $main::lxdebug->enter_sub();
 
2080   my ($self, $dbh, $key) = @_;
 
2082   $key = "all_payments" unless ($key);
 
2084   my $query = qq|SELECT * FROM payment_terms ORDER BY sortkey|;
 
2086   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2088   $main::lxdebug->leave_sub();
 
2091 sub _get_customers {
 
2092   $main::lxdebug->enter_sub();
 
2094   my ($self, $dbh, $key) = @_;
 
2096   my $options        = ref $key eq 'HASH' ? $key : { key => $key };
 
2097   $options->{key}  ||= "all_customers";
 
2098   my $limit_clause   = $options->{limit} ? "LIMIT $options->{limit}" : '';
 
2101   push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if  $options->{business_is_salesman};
 
2102   push @where, qq|NOT obsolete|                                            if !$options->{with_obsolete};
 
2103   my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : '';
 
2105   my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|;
 
2106   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
 
2108   $main::lxdebug->leave_sub();
 
2112   $main::lxdebug->enter_sub();
 
2114   my ($self, $dbh, $key) = @_;
 
2116   $key = "all_vendors" unless ($key);
 
2118   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
 
2120   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2122   $main::lxdebug->leave_sub();
 
2125 sub _get_departments {
 
2126   $main::lxdebug->enter_sub();
 
2128   my ($self, $dbh, $key) = @_;
 
2130   $key = "all_departments" unless ($key);
 
2132   my $query = qq|SELECT * FROM department ORDER BY description|;
 
2134   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2136   $main::lxdebug->leave_sub();
 
2139 sub _get_warehouses {
 
2140   $main::lxdebug->enter_sub();
 
2142   my ($self, $dbh, $param) = @_;
 
2144   my ($key, $bins_key);
 
2146   if ('' eq ref $param) {
 
2150     $key      = $param->{key};
 
2151     $bins_key = $param->{bins};
 
2154   my $query = qq|SELECT w.* FROM warehouse w
 
2155                  WHERE (NOT w.invalid) AND
 
2156                    ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
 
2157                  ORDER BY w.sortkey|;
 
2159   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2162     $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?
 
2163                 ORDER BY description|;
 
2164     my $sth = prepare_query($self, $dbh, $query);
 
2166     foreach my $warehouse (@{ $self->{$key} }) {
 
2167       do_statement($self, $sth, $query, $warehouse->{id});
 
2168       $warehouse->{$bins_key} = [];
 
2170       while (my $ref = $sth->fetchrow_hashref()) {
 
2171         push @{ $warehouse->{$bins_key} }, $ref;
 
2177   $main::lxdebug->leave_sub();
 
2181   $main::lxdebug->enter_sub();
 
2183   my ($self, $dbh, $table, $key, $sortkey) = @_;
 
2185   my $query  = qq|SELECT * FROM $table|;
 
2186   $query    .= qq| ORDER BY $sortkey| if ($sortkey);
 
2188   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2190   $main::lxdebug->leave_sub();
 
2194   $main::lxdebug->enter_sub();
 
2199   croak "get_lists: shipto is no longer supported" if $params{shipto};
 
2201   my $dbh = $self->get_standard_dbh(\%main::myconfig);
 
2202   my ($sth, $query, $ref);
 
2205   if ($params{contacts}) {
 
2206     $vc = 'customer' if $self->{"vc"} eq "customer";
 
2207     $vc = 'vendor'   if $self->{"vc"} eq "vendor";
 
2208     die "invalid use of get_lists, need 'vc'" unless $vc;
 
2209     $vc_id = $self->{"${vc}_id"};
 
2212   if ($params{"contacts"}) {
 
2213     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
 
2216   if ($params{"projects"} || $params{"all_projects"}) {
 
2217     $self->_get_projects($dbh, $params{"all_projects"} ?
 
2218                          $params{"all_projects"} : $params{"projects"},
 
2219                          $params{"all_projects"} ? 1 : 0);
 
2222   if ($params{"printers"}) {
 
2223     $self->_get_printers($dbh, $params{"printers"});
 
2226   if ($params{"languages"}) {
 
2227     $self->_get_languages($dbh, $params{"languages"});
 
2230   if ($params{"charts"}) {
 
2231     $self->_get_charts($dbh, $params{"charts"});
 
2234   if ($params{"taxzones"}) {
 
2235     $self->_get_taxzones($dbh, $params{"taxzones"});
 
2238   if ($params{"employees"}) {
 
2239     $self->_get_employees($dbh, $params{"employees"});
 
2242   if ($params{"salesmen"}) {
 
2243     $self->_get_employees($dbh, $params{"salesmen"});
 
2246   if ($params{"business_types"}) {
 
2247     $self->_get_business_types($dbh, $params{"business_types"});
 
2250   if ($params{"dunning_configs"}) {
 
2251     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
 
2254   if($params{"currencies"}) {
 
2255     $self->_get_currencies($dbh, $params{"currencies"});
 
2258   if($params{"customers"}) {
 
2259     $self->_get_customers($dbh, $params{"customers"});
 
2262   if($params{"vendors"}) {
 
2263     if (ref $params{"vendors"} eq 'HASH') {
 
2264       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
 
2266       $self->_get_vendors($dbh, $params{"vendors"});
 
2270   if($params{"payments"}) {
 
2271     $self->_get_payments($dbh, $params{"payments"});
 
2274   if($params{"departments"}) {
 
2275     $self->_get_departments($dbh, $params{"departments"});
 
2278   if ($params{price_factors}) {
 
2279     $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
 
2282   if ($params{warehouses}) {
 
2283     $self->_get_warehouses($dbh, $params{warehouses});
 
2286   if ($params{partsgroup}) {
 
2287     $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
 
2290   $main::lxdebug->leave_sub();
 
2293 # this sub gets the id and name from $table
 
2295   $main::lxdebug->enter_sub();
 
2297   my ($self, $myconfig, $table) = @_;
 
2299   # connect to database
 
2300   my $dbh = $self->get_standard_dbh($myconfig);
 
2302   $table = $table eq "customer" ? "customer" : "vendor";
 
2303   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
 
2305   my ($query, @values);
 
2307   if (!$self->{openinvoices}) {
 
2309     if ($self->{customernumber} ne "") {
 
2310       $where = qq|(vc.customernumber ILIKE ?)|;
 
2311       push(@values, like($self->{customernumber}));
 
2313       $where = qq|(vc.name ILIKE ?)|;
 
2314       push(@values, like($self->{$table}));
 
2318       qq~SELECT vc.id, vc.name,
 
2319            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
2321          WHERE $where AND (NOT vc.obsolete)
 
2325       qq~SELECT DISTINCT vc.id, vc.name,
 
2326            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
2328          JOIN $table vc ON (a.${table}_id = vc.id)
 
2329          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
 
2331     push(@values, like($self->{$table}));
 
2334   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
 
2336   $main::lxdebug->leave_sub();
 
2338   return scalar(@{ $self->{name_list} });
 
2343   my ($self, $table, $provided_dbh) = @_;
 
2345   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh;
 
2346   return                                       unless $self->{id};
 
2347   croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
 
2349   my $query       = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
 
2350   my $ref         = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
 
2351   $ref->{mtime} ||= $ref->{itime};
 
2352   $self->{lastmtime} = $ref->{mtime};
 
2356 sub mtime_ischanged {
 
2357   my ($self, $table, $option) = @_;
 
2359   return                                       unless $self->{id};
 
2360   croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
 
2362   my $query       = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
 
2363   my $ref         = selectfirst_hashref_query($self, $self->get_standard_dbh, $query, $self->{id});
 
2364   $ref->{mtime} ||= $ref->{itime};
 
2366   if ($self->{lastmtime} && $self->{lastmtime} ne $ref->{mtime} ) {
 
2367       $self->error(($option eq 'mail') ?
 
2368         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") :
 
2369         t8("The document has been changed by another user. Please reopen it in another window and copy the changes to the new window")
 
2371     $::dispatcher->end_request;
 
2375 # language_payment duplicates some of the functionality of all_vc (language,
 
2376 # printer, payment_terms), and at least in the case of sales invoices both
 
2377 # all_vc and language_payment are called when adding new invoices
 
2378 sub language_payment {
 
2379   $main::lxdebug->enter_sub();
 
2381   my ($self, $myconfig) = @_;
 
2383   my $dbh = $self->get_standard_dbh($myconfig);
 
2385   my $query = qq|SELECT id, description
 
2389   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2392   $query = qq|SELECT printer_description, id
 
2394               ORDER BY printer_description|;
 
2396   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2399   $query = qq|SELECT id, description
 
2401               WHERE ( obsolete IS FALSE OR id = ? )
 
2403   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query, $self->{payment_id} || undef);
 
2405   # get buchungsgruppen
 
2406   $query = qq|SELECT id, description
 
2407               FROM buchungsgruppen|;
 
2409   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
 
2411   $main::lxdebug->leave_sub();
 
2414 # this is only used for reports
 
2415 sub all_departments {
 
2416   $main::lxdebug->enter_sub();
 
2418   my ($self, $myconfig, $table) = @_;
 
2420   my $dbh = $self->get_standard_dbh($myconfig);
 
2422   my $query = qq|SELECT id, description
 
2424                  ORDER BY description|;
 
2425   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2427   delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
 
2429   $main::lxdebug->leave_sub();
 
2433   $main::lxdebug->enter_sub();
 
2435   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
 
2438   if ($table eq "customer") {
 
2447   # get last customers or vendors
 
2448   my ($query, $sth, $ref);
 
2450   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
 
2455     my $transdate = "current_date";
 
2456     if ($self->{transdate}) {
 
2457       $transdate = $dbh->quote($self->{transdate});
 
2460     # now get the account numbers
 
2462       SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk2.tax_id
 
2464         -- find newest entries in taxkeys
 
2466           SELECT chart_id, MAX(startdate) AS startdate
 
2468           WHERE (startdate <= $transdate)
 
2470         ) tk ON (c.id = tk.chart_id)
 
2471         -- and load all of those entries
 
2472         INNER JOIN taxkeys tk2
 
2473            ON (tk.chart_id = tk2.chart_id AND tk.startdate = tk2.startdate)
 
2474        WHERE (c.link LIKE ?)
 
2477     $sth = $dbh->prepare($query);
 
2479     do_statement($self, $sth, $query, like($module));
 
2481     $self->{accounts} = "";
 
2482     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2484       foreach my $key (split(/:/, $ref->{link})) {
 
2485         if ($key =~ /\Q$module\E/) {
 
2487           # cross reference for keys
 
2488           $xkeyref{ $ref->{accno} } = $key;
 
2490           push @{ $self->{"${module}_links"}{$key} },
 
2491             { accno       => $ref->{accno},
 
2492               chart_id    => $ref->{chart_id},
 
2493               description => $ref->{description},
 
2494               taxkey      => $ref->{taxkey_id},
 
2495               tax_id      => $ref->{tax_id} };
 
2497           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2503   # get taxkeys and description
 
2504   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
 
2505   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
 
2507   if (($module eq "AP") || ($module eq "AR")) {
 
2508     # get tax rates and description
 
2509     $query = qq|SELECT * FROM tax|;
 
2510     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
 
2513   my $extra_columns = '';
 
2514   $extra_columns   .= 'a.direct_debit, ' if ($module eq 'AR') || ($module eq 'AP');
 
2519            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid, a.deliverydate,
 
2520            a.duedate, a.tax_point, a.ordnumber, a.taxincluded, (SELECT cu.name FROM currencies cu WHERE cu.id=a.currency_id) AS currency, a.notes,
 
2522            a.intnotes, a.department_id, a.amount AS oldinvtotal,
 
2523            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
 
2524            a.globalproject_id, ${extra_columns}
 
2526            d.description AS department,
 
2529          JOIN $table c ON (a.${table}_id = c.id)
 
2530          LEFT JOIN employee e ON (e.id = a.employee_id)
 
2531          LEFT JOIN department d ON (d.id = a.department_id)
 
2533     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
 
2535     foreach my $key (keys %$ref) {
 
2536       $self->{$key} = $ref->{$key};
 
2538     $self->{mtime}   ||= $self->{itime};
 
2539     $self->{lastmtime} = $self->{mtime};
 
2540     my $transdate = "current_date";
 
2541     if ($self->{transdate}) {
 
2542       $transdate = $dbh->quote($self->{transdate});
 
2545     # now get the account numbers
 
2546     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk.tax_id
 
2548                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
 
2550                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
 
2551                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
 
2554     $sth = $dbh->prepare($query);
 
2555     do_statement($self, $sth, $query, like($module));
 
2557     $self->{accounts} = "";
 
2558     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2560       foreach my $key (split(/:/, $ref->{link})) {
 
2561         if ($key =~ /\Q$module\E/) {
 
2563           # cross reference for keys
 
2564           $xkeyref{ $ref->{accno} } = $key;
 
2566           push @{ $self->{"${module}_links"}{$key} },
 
2567             { accno       => $ref->{accno},
 
2568               chart_id    => $ref->{chart_id},
 
2569               description => $ref->{description},
 
2570               taxkey      => $ref->{taxkey_id},
 
2571               tax_id      => $ref->{tax_id} };
 
2573           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2579     # get amounts from individual entries
 
2582            c.accno, c.description,
 
2583            a.acc_trans_id, a.source, a.amount, a.memo, a.transdate, a.gldate, a.cleared, a.project_id, a.taxkey, a.chart_id,
 
2587          LEFT JOIN chart c ON (c.id = a.chart_id)
 
2588          LEFT JOIN project p ON (p.id = a.project_id)
 
2589          LEFT JOIN tax t ON (t.id= a.tax_id)
 
2590          WHERE a.trans_id = ?
 
2591          AND a.fx_transaction = '0'
 
2592          ORDER BY a.acc_trans_id, a.transdate|;
 
2593     $sth = $dbh->prepare($query);
 
2594     do_statement($self, $sth, $query, $self->{id});
 
2596     # get exchangerate for currency
 
2597     $self->{exchangerate} =
 
2598       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2601     # store amounts in {acc_trans}{$key} for multiple accounts
 
2602     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2603       $ref->{exchangerate} =
 
2604         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
 
2605       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
 
2608       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
 
2609         $ref->{amount} *= -1;
 
2611       $ref->{index} = $index;
 
2613       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
 
2620            d.closedto, d.revtrans,
 
2621            (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
 
2622            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2623            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
 
2624            (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
 
2625            (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
 
2627     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2628     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2635             current_date AS transdate, d.closedto, d.revtrans,
 
2636             (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
 
2637             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2638             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
 
2639             (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
 
2640             (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
 
2642     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2643     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2645     if ($self->{"$self->{vc}_id"}) {
 
2647       # only setup currency
 
2648       ($self->{currency}) = $self->{defaultcurrency} if !$self->{currency};
 
2652       $self->lastname_used($dbh, $myconfig, $table, $module);
 
2654       # get exchangerate for currency
 
2655       $self->{exchangerate} =
 
2656         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2662   $main::lxdebug->leave_sub();
 
2666   $main::lxdebug->enter_sub();
 
2668   my ($self, $dbh, $myconfig, $table, $module) = @_;
 
2672   $table         = $table eq "customer" ? "customer" : "vendor";
 
2673   my %column_map = ("a.${table}_id"           => "${table}_id",
 
2674                     "a.department_id"         => "department_id",
 
2675                     "d.description"           => "department",
 
2676                     "ct.name"                 => $table,
 
2677                     "cu.name"                 => "currency",
 
2680   if ($self->{type} =~ /delivery_order/) {
 
2681     $arap  = 'delivery_orders';
 
2682     delete $column_map{"cu.currency"};
 
2684   } elsif ($self->{type} =~ /_order/) {
 
2686     $where = "quotation = '0'";
 
2688   } elsif ($self->{type} =~ /_quotation/) {
 
2690     $where = "quotation = '1'";
 
2692   } elsif ($table eq 'customer') {
 
2700   $where           = "($where) AND" if ($where);
 
2701   my $query        = qq|SELECT MAX(id) FROM $arap
 
2702                         WHERE $where ${table}_id > 0|;
 
2703   my ($trans_id)   = selectrow_query($self, $dbh, $query);
 
2706   my $column_spec  = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
 
2707   $query           = qq|SELECT $column_spec
 
2709                         LEFT JOIN $table     ct ON (a.${table}_id = ct.id)
 
2710                         LEFT JOIN department d  ON (a.department_id = d.id)
 
2711                         LEFT JOIN currencies cu ON (cu.id=ct.currency_id)
 
2713   my $ref          = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
 
2715   map { $self->{$_} = $ref->{$_} } values %column_map;
 
2717   $main::lxdebug->leave_sub();
 
2720 sub get_variable_content_types {
 
2723   my %html_variables = (
 
2724     longdescription  => 'html',
 
2725     partnotes        => 'html',
 
2727     orignotes        => 'html',
 
2732     header_text      => 'html',
 
2733     footer_text      => 'html',
 
2738     $self->get_variable_content_types_for_cvars,
 
2742 sub get_variable_content_types_for_cvars {
 
2744   my $html_configs = SL::DB::Manager::CustomVariableConfig->get_all(where => [ type => 'htmlfield' ]);
 
2747   if (@{ $html_configs }) {
 
2748     my %prefix_by_module = (
 
2749       Contacts => 'cp_cvar_',
 
2752       Projects => 'project_cvar_',
 
2753       ShipTo   => 'shiptocvar_',
 
2756     foreach my $cfg (@{ $html_configs }) {
 
2757       my $prefix = $prefix_by_module{$cfg->module};
 
2758       $types{$prefix . $cfg->name} = 'html' if $prefix;
 
2766   $main::lxdebug->enter_sub();
 
2769   my $myconfig = shift || \%::myconfig;
 
2770   my ($thisdate, $days) = @_;
 
2772   my $dbh = $self->get_standard_dbh($myconfig);
 
2777     my $dateformat = $myconfig->{dateformat};
 
2778     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
 
2779     $thisdate = $dbh->quote($thisdate);
 
2780     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
 
2782     $query = qq|SELECT current_date AS thisdate|;
 
2785   ($thisdate) = selectrow_query($self, $dbh, $query);
 
2787   $main::lxdebug->leave_sub();
 
2793   $main::lxdebug->enter_sub();
 
2795   my ($self, $flds, $new, $count, $numrows) = @_;
 
2799   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
 
2804   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
 
2806     my $j = $item->{ndx} - 1;
 
2807     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
 
2811   for $i ($count + 1 .. $numrows) {
 
2812     map { delete $self->{"${_}_$i"} } @{$flds};
 
2815   $main::lxdebug->leave_sub();
 
2819   $main::lxdebug->enter_sub();
 
2821   my ($self, $myconfig) = @_;
 
2825   SL::DB->client->with_transaction(sub {
 
2826     my $dbh = SL::DB->client->dbh;
 
2828     my $query = qq|DELETE FROM status
 
2829                    WHERE (formname = ?) AND (trans_id = ?)|;
 
2830     my $sth = prepare_query($self, $dbh, $query);
 
2832     if ($self->{formname} =~ /(check|receipt)/) {
 
2833       for $i (1 .. $self->{rowcount}) {
 
2834         do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
 
2837       do_statement($self, $sth, $query, $self->{formname}, $self->{id});
 
2841     my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
2842     my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
2844     my %queued = split / /, $self->{queued};
 
2847     if ($self->{formname} =~ /(check|receipt)/) {
 
2849       # this is a check or receipt, add one entry for each lineitem
 
2850       my ($accno) = split /--/, $self->{account};
 
2851       $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
 
2852                   VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
 
2853       @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
 
2854       $sth = prepare_query($self, $dbh, $query);
 
2856       for $i (1 .. $self->{rowcount}) {
 
2857         if ($self->{"checked_$i"}) {
 
2858           do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
 
2864       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
2865                   VALUES (?, ?, ?, ?, ?)|;
 
2866       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
 
2867                $queued{$self->{formname}}, $self->{formname});
 
2870   }) or do { die SL::DB->client->error };
 
2872   $main::lxdebug->leave_sub();
 
2876   $main::lxdebug->enter_sub();
 
2878   my ($self, $dbh) = @_;
 
2880   my ($query, $printed, $emailed);
 
2882   my $formnames  = $self->{printed};
 
2883   my $emailforms = $self->{emailed};
 
2885   $query = qq|DELETE FROM status
 
2886                  WHERE (formname = ?) AND (trans_id = ?)|;
 
2887   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
 
2889   # this only applies to the forms
 
2890   # checks and receipts are posted when printed or queued
 
2892   if ($self->{queued}) {
 
2893     my %queued = split / /, $self->{queued};
 
2895     foreach my $formname (keys %queued) {
 
2896       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
2897       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
2899       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
2900                   VALUES (?, ?, ?, ?, ?)|;
 
2901       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
 
2903       $formnames  =~ s/\Q$self->{formname}\E//;
 
2904       $emailforms =~ s/\Q$self->{formname}\E//;
 
2909   # save printed, emailed info
 
2910   $formnames  =~ s/^ +//g;
 
2911   $emailforms =~ s/^ +//g;
 
2914   map { $status{$_}{printed} = 1 } split / +/, $formnames;
 
2915   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
 
2917   foreach my $formname (keys %status) {
 
2918     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
2919     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
2921     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
 
2922                 VALUES (?, ?, ?, ?)|;
 
2923     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
 
2926   $main::lxdebug->leave_sub();
 
2930 # $main::locale->text('SAVED')
 
2931 # $main::locale->text('SCREENED')
 
2932 # $main::locale->text('DELETED')
 
2933 # $main::locale->text('ADDED')
 
2934 # $main::locale->text('PAYMENT POSTED')
 
2935 # $main::locale->text('POSTED')
 
2936 # $main::locale->text('POSTED AS NEW')
 
2937 # $main::locale->text('ELSE')
 
2938 # $main::locale->text('SAVED FOR DUNNING')
 
2939 # $main::locale->text('DUNNING STARTED')
 
2940 # $main::locale->text('PREVIEWED')
 
2941 # $main::locale->text('PRINTED')
 
2942 # $main::locale->text('MAILED')
 
2943 # $main::locale->text('SCREENED')
 
2944 # $main::locale->text('CANCELED')
 
2945 # $main::locale->text('IMPORT')
 
2946 # $main::locale->text('UNDO TRANSFER')
 
2947 # $main::locale->text('UNIMPORT')
 
2948 # $main::locale->text('invoice')
 
2949 # $main::locale->text('invoice_for_advance_payment')
 
2950 # $main::locale->text('final_invoice')
 
2951 # $main::locale->text('proforma')
 
2952 # $main::locale->text('sales_order')
 
2953 # $main::locale->text('pick_list')
 
2954 # $main::locale->text('purchase_order')
 
2955 # $main::locale->text('bin_list')
 
2956 # $main::locale->text('sales_quotation')
 
2957 # $main::locale->text('request_quotation')
 
2960   $main::lxdebug->enter_sub();
 
2963   my $dbh  = shift || SL::DB->client->dbh;
 
2964   SL::DB->client->with_transaction(sub {
 
2966     if(!exists $self->{employee_id}) {
 
2967       &get_employee($self, $dbh);
 
2971      qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
 
2972      qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
 
2973     my @values = (conv_i($self->{id}), $self->{login},
 
2974                   $self->{addition}, $self->{what_done}, "$self->{snumbers}");
 
2975     do_query($self, $dbh, $query, @values);
 
2977   }) or do { die SL::DB->client->error };
 
2979   $main::lxdebug->leave_sub();
 
2983   $main::lxdebug->enter_sub();
 
2985   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
 
2986   my ($orderBy, $desc) = split(/\-\-/, $order);
 
2987   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
 
2990   if ($trans_id ne "") {
 
2992       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 | .
 
2993       qq|FROM history_erp h | .
 
2994       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
 
2995       qq|WHERE (trans_id = | . $dbh->quote($trans_id) . qq|) $restriction | .
 
2998     my $sth = $dbh->prepare($query) || $self->dberror($query);
 
3000     $sth->execute() || $self->dberror("$query");
 
3002     while(my $hash_ref = $sth->fetchrow_hashref()) {
 
3003       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
 
3004       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
 
3005       my ( $what, $number ) = split /_/, $hash_ref->{snumbers};
 
3006       $hash_ref->{snumbers} = $number;
 
3007       $hash_ref->{haslink}  = 'controller.pl?action=EmailJournal/show&id='.$number if $what eq 'emailjournal';
 
3008       $hash_ref->{snumbers} = $main::locale->text("E-Mail").' '.$number if $what eq 'emailjournal';
 
3009       $tempArray[$i++] = $hash_ref;
 
3011     $main::lxdebug->leave_sub() and return \@tempArray
 
3012       if ($i > 0 && $tempArray[0] ne "");
 
3014   $main::lxdebug->leave_sub();
 
3018 sub get_partsgroup {
 
3019   $main::lxdebug->enter_sub();
 
3021   my ($self, $myconfig, $p) = @_;
 
3022   my $target = $p->{target} || 'all_partsgroup';
 
3024   my $dbh = $self->get_standard_dbh($myconfig);
 
3026   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
 
3028                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
 
3031   if ($p->{searchitems} eq 'part') {
 
3032     $query .= qq|WHERE p.part_type = 'part'|;
 
3034   if ($p->{searchitems} eq 'service') {
 
3035     $query .= qq|WHERE p.part_type = 'service'|;
 
3037   if ($p->{searchitems} eq 'assembly') {
 
3038     $query .= qq|WHERE p.part_type = 'assembly'|;
 
3041   $query .= qq|ORDER BY partsgroup|;
 
3044     $query = qq|SELECT id, partsgroup FROM partsgroup
 
3045                 ORDER BY partsgroup|;
 
3048   if ($p->{language_code}) {
 
3049     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
 
3050                   t.description AS translation
 
3052                 JOIN parts p ON (p.partsgroup_id = pg.id)
 
3053                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
 
3054                 ORDER BY translation|;
 
3055     @values = ($p->{language_code});
 
3058   $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
 
3060   $main::lxdebug->leave_sub();
 
3063 sub get_pricegroup {
 
3064   $main::lxdebug->enter_sub();
 
3066   my ($self, $myconfig, $p) = @_;
 
3068   my $dbh = $self->get_standard_dbh($myconfig);
 
3070   my $query = qq|SELECT p.id, p.pricegroup
 
3073   $query .= qq| ORDER BY pricegroup|;
 
3076     $query = qq|SELECT id, pricegroup FROM pricegroup
 
3077                 ORDER BY pricegroup|;
 
3080   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
 
3082   $main::lxdebug->leave_sub();
 
3086 # usage $form->all_years($myconfig, [$dbh])
 
3087 # return list of all years where bookings found
 
3090   $main::lxdebug->enter_sub();
 
3092   my ($self, $myconfig, $dbh) = @_;
 
3094   $dbh ||= $self->get_standard_dbh($myconfig);
 
3097   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
 
3098                    (SELECT MAX(transdate) FROM acc_trans)|;
 
3099   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
 
3101   if ($myconfig->{dateformat} =~ /^yy/) {
 
3102     ($startdate) = split /\W/, $startdate;
 
3103     ($enddate) = split /\W/, $enddate;
 
3105     (@_) = split /\W/, $startdate;
 
3107     (@_) = split /\W/, $enddate;
 
3112   $startdate = substr($startdate,0,4);
 
3113   $enddate = substr($enddate,0,4);
 
3115   while ($enddate >= $startdate) {
 
3116     push @all_years, $enddate--;
 
3121   $main::lxdebug->leave_sub();
 
3125   $main::lxdebug->enter_sub();
 
3129   map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
 
3131   $main::lxdebug->leave_sub();
 
3135   $main::lxdebug->enter_sub();
 
3140   map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
 
3142   $main::lxdebug->leave_sub();
 
3145 sub prepare_for_printing {
 
3148   my $defaults         = SL::DB::Default->get;
 
3150   $self->{templates} ||= $defaults->templates;
 
3151   $self->{formname}  ||= $self->{type};
 
3152   $self->{media}     ||= 'email';
 
3154   die "'media' other than 'email', 'file', 'printer' is not supported yet" unless $self->{media} =~ m/^(?:email|file|printer)$/;
 
3156   # Several fields that used to reside in %::myconfig (stored in
 
3157   # auth.user_config) are now stored in defaults. Copy them over for
 
3159   $self->{$_} = $defaults->$_ for qw(company address taxnumber co_ustid duns sepa_creditor_id);
 
3161   $self->{"myconfig_${_}"} = $::myconfig{$_} for grep { $_ ne 'dbpasswd' } keys %::myconfig;
 
3163   if (!$self->{employee_id}) {
 
3164     $self->{"employee_${_}"} = $::myconfig{$_} for qw(email tel fax name signature);
 
3165     $self->{"employee_${_}"} = $defaults->$_   for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
 
3168   my $language = $self->{language} ? '_' . $self->{language} : '';
 
3170   my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
 
3171   if ($self->{language_id}) {
 
3172     ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) = AM->get_language_details(\%::myconfig, $self, $self->{language_id});
 
3175   $output_dateformat   ||= $::myconfig{dateformat};
 
3176   $output_numberformat ||= $::myconfig{numberformat};
 
3177   $output_longdates    //= 1;
 
3179   $self->{myconfig_output_dateformat}   = $output_dateformat   // $::myconfig{dateformat};
 
3180   $self->{myconfig_output_longdates}    = $output_longdates    // 1;
 
3181   $self->{myconfig_output_numberformat} = $output_numberformat // $::myconfig{numberformat};
 
3183   # Retrieve accounts for tax calculation.
 
3184   IC->retrieve_accounts(\%::myconfig, $self, map { $_ => $self->{"id_$_"} } 1 .. $self->{rowcount});
 
3186   if ($self->{type} =~ /_delivery_order$/) {
 
3187     DO->order_details(\%::myconfig, $self);
 
3188   } elsif ($self->{type} =~ /sales_order|sales_quotation|request_quotation|purchase_order/) {
 
3189     OE->order_details(\%::myconfig, $self);
 
3191     IS->invoice_details(\%::myconfig, $self, $::locale);
 
3194   $self->set_addition_billing_address_print_variables;
 
3196   # Chose extension & set source file name
 
3197   my $extension = 'html';
 
3198   if ($self->{format} eq 'postscript') {
 
3199     $self->{postscript}   = 1;
 
3201   } elsif ($self->{"format"} =~ /pdf/) {
 
3203     $extension            = $self->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
 
3204   } elsif ($self->{"format"} =~ /opendocument/) {
 
3205     $self->{opendocument} = 1;
 
3207   } elsif ($self->{"format"} =~ /excel/) {
 
3212   my $printer_code    = $self->{printer_code} ? '_' . $self->{printer_code} : '';
 
3213   my $email_extension = $self->{media} eq 'email' && -f ($defaults->templates . "/$self->{formname}_email${language}.${extension}") ? '_email' : '';
 
3214   $self->{IN}         = "$self->{formname}${email_extension}${language}${printer_code}.${extension}";
 
3217   $self->format_dates($output_dateformat, $output_longdates,
 
3218                       qw(invdate orddate quodate pldate duedate reqdate transdate tax_point shippingdate deliverydate validitydate paymentdate datepaid
 
3219                          transdate_oe deliverydate_oe employee_startdate employee_enddate),
 
3220                       grep({ /^(?:datepaid|transdate_oe|reqdate|deliverydate|deliverydate_oe|transdate)_\d+$/ } keys(%{$self})));
 
3222   $self->reformat_numbers($output_numberformat, 2,
 
3223                           qw(invtotal ordtotal quototal subtotal linetotal listprice sellprice netprice discount tax taxbase total paid),
 
3224                           grep({ /^(?:linetotal|listprice|sellprice|netprice|taxbase|discount|paid|subtotal|total|tax)_\d+$/ } keys(%{$self})));
 
3226   $self->reformat_numbers($output_numberformat, undef, qw(qty price_factor), grep({ /^qty_\d+$/} keys(%{$self})));
 
3228   my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
 
3230   if (scalar @{ $cvar_date_fields }) {
 
3231     $self->format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
 
3234   while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
 
3235     $self->reformat_numbers($output_numberformat, $precision, @{ $field_list });
 
3239   if (($self->{language} // '') ne '') {
 
3240     my $template_arrays = $self->{TEMPLATE_ARRAYS} || $self;
 
3241     for my $idx (0..scalar(@{ $template_arrays->{unit} }) - 1) {
 
3242       $template_arrays->{unit}->[$idx] = AM->translate_units($self, $self->{language}, $template_arrays->{unit}->[$idx], $template_arrays->{qty}->[$idx])
 
3246   $self->{template_meta} = {
 
3247     formname  => $self->{formname},
 
3248     language  => SL::DB::Manager::Language->find_by_or_create(id => $self->{language_id} || undef),
 
3249     format    => $self->{format},
 
3250     media     => $self->{media},
 
3251     extension => $extension,
 
3252     printer   => SL::DB::Manager::Printer->find_by_or_create(id => $self->{printer_id} || undef),
 
3253     today     => DateTime->today,
 
3256   if ($defaults->print_interpolate_variables_in_positions) {
 
3257     $self->substitute_placeholders_in_template_arrays({ field => 'description', type => 'text' }, { field => 'longdescription', type => 'html' });
 
3263 sub set_addition_billing_address_print_variables {
 
3266   return if !$self->{billing_address_id};
 
3268   my $address = SL::DB::Manager::AdditionalBillingAddress->find_by(id => $self->{billing_address_id});
 
3269   return if !$address;
 
3271   $self->{"billing_address_${_}"} = $address->$_ for map { $_->name } @{ $address->meta->columns };
 
3274 sub substitute_placeholders_in_template_arrays {
 
3275   my ($self, @fields) = @_;
 
3277   foreach my $spec (@fields) {
 
3278     $spec     = { field => $spec, type => 'text' } if !ref($spec);
 
3279     my $field = $spec->{field};
 
3281     next unless exists $self->{TEMPLATE_ARRAYS} && exists $self->{TEMPLATE_ARRAYS}->{$field};
 
3283     my $tag_start = $spec->{type} eq 'html' ? '<%' : '<%';
 
3284     my $tag_end   = $spec->{type} eq 'html' ? '%>' : '%>';
 
3285     my $formatter = $spec->{type} eq 'html' ? sub { $::locale->quote_special_chars('html', $_[0] // '') } : sub { $_[0] };
 
3287     $self->{TEMPLATE_ARRAYS}->{$field} = [
 
3288       apply { s{${tag_start}(.+?)${tag_end}}{ $formatter->($self->{$1}) }eg }
 
3289         @{ $self->{TEMPLATE_ARRAYS}->{$field} }
 
3296 sub calculate_arap {
 
3297   my ($self,$buysell,$taxincluded,$exchangerate,$roundplaces) = @_;
 
3299   # this function is used to calculate netamount, total_tax and amount for AP and
 
3300   # AR transactions (Kreditoren-/Debitorenbuchungen) by going over all lines
 
3302   # Thus it needs a fully prepared $form to work on.
 
3303   # calculate_arap assumes $form->{amount_$i} entries still need to be parsed
 
3305   # The calculated total values are all rounded (default is to 2 places) and
 
3306   # returned as parameters rather than directly modifying form.  The aim is to
 
3307   # make the calculation of AP and AR behave identically.  There is a test-case
 
3308   # for this function in t/form/arap.t
 
3310   # While calculating the totals $form->{amount_$i} and $form->{tax_$i} are
 
3311   # modified and formatted and receive the correct sign for writing straight to
 
3312   # acc_trans, depending on whether they are ar or ap.
 
3315   die "taxincluded needed in Form->calculate_arap" unless defined $taxincluded;
 
3316   die "exchangerate needed in Form->calculate_arap" unless defined $exchangerate;
 
3317   die 'illegal buysell parameter, has to be \"buy\" or \"sell\" in Form->calculate_arap\n' unless $buysell =~ /^(buy|sell)$/;
 
3318   $roundplaces = 2 unless $roundplaces;
 
3320   my $sign = 1;  # adjust final results for writing amount to acc_trans
 
3321   $sign = -1 if $buysell eq 'buy';
 
3323   my ($netamount,$total_tax,$amount);
 
3327   # parse and round amounts, setting correct sign for writing to acc_trans
 
3328   for my $i (1 .. $self->{rowcount}) {
 
3329     $self->{"amount_$i"} = $self->round_amount($self->parse_amount(\%::myconfig, $self->{"amount_$i"}) * $exchangerate * $sign, $roundplaces);
 
3331     $amount += $self->{"amount_$i"} * $sign;
 
3334   for my $i (1 .. $self->{rowcount}) {
 
3335     next unless $self->{"amount_$i"};
 
3336     ($self->{"tax_id_$i"}) = split /--/, $self->{"taxchart_$i"};
 
3337     my $tax_id = $self->{"tax_id_$i"};
 
3339     my $selected_tax = SL::DB::Manager::Tax->find_by(id => "$tax_id");
 
3341     if ( $selected_tax ) {
 
3343       if ( $buysell eq 'sell' ) {
 
3344         $self->{AR_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
 
3346         $self->{AP_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
 
3349       $self->{"taxkey_$i"} = $selected_tax->taxkey;
 
3350       $self->{"taxrate_$i"} = $selected_tax->rate;
 
3353     ($self->{"amount_$i"}, $self->{"tax_$i"}) = $self->calculate_tax($self->{"amount_$i"},$self->{"taxrate_$i"},$taxincluded,$roundplaces);
 
3355     $netamount  += $self->{"amount_$i"};
 
3356     $total_tax  += $self->{"tax_$i"};
 
3359   $amount = $netamount + $total_tax;
 
3361   # due to $sign amount_$i und tax_$i already have the right sign for acc_trans
 
3362   # but reverse sign of totals for writing amounts to ar
 
3363   if ( $buysell eq 'buy' ) {
 
3369   return($netamount,$total_tax,$amount);
 
3373   my ($self, $dateformat, $longformat, @indices) = @_;
 
3375   $dateformat ||= $::myconfig{dateformat};
 
3377   foreach my $idx (@indices) {
 
3378     if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
 
3379       for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
 
3380         $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $dateformat, $longformat);
 
3384     next unless defined $self->{$idx};
 
3386     if (!ref($self->{$idx})) {
 
3387       $self->{$idx} = $::locale->reformat_date(\%::myconfig, $self->{$idx}, $dateformat, $longformat);
 
3389     } elsif (ref($self->{$idx}) eq "ARRAY") {
 
3390       for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
 
3391         $self->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{$idx}->[$i], $dateformat, $longformat);
 
3397 sub reformat_numbers {
 
3398   my ($self, $numberformat, $places, @indices) = @_;
 
3400   return if !$numberformat || ($numberformat eq $::myconfig{numberformat});
 
3402   foreach my $idx (@indices) {
 
3403     if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
 
3404       for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
 
3405         $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i]);
 
3409     next unless defined $self->{$idx};
 
3411     if (!ref($self->{$idx})) {
 
3412       $self->{$idx} = $self->parse_amount(\%::myconfig, $self->{$idx});
 
3414     } elsif (ref($self->{$idx}) eq "ARRAY") {
 
3415       for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
 
3416         $self->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{$idx}->[$i]);
 
3421   my $saved_numberformat    = $::myconfig{numberformat};
 
3422   $::myconfig{numberformat} = $numberformat;
 
3424   foreach my $idx (@indices) {
 
3425     if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
 
3426       for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
 
3427         $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $places);
 
3431     next unless defined $self->{$idx};
 
3433     if (!ref($self->{$idx})) {
 
3434       $self->{$idx} = $self->format_amount(\%::myconfig, $self->{$idx}, $places);
 
3436     } elsif (ref($self->{$idx}) eq "ARRAY") {
 
3437       for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
 
3438         $self->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{$idx}->[$i], $places);
 
3443   $::myconfig{numberformat} = $saved_numberformat;
 
3446 sub create_email_signature {
 
3447   my $client_signature = $::instance_conf->get_signature;
 
3448   my $user_signature   = $::myconfig{signature};
 
3450   return join '', grep { $_ } ($user_signature, $client_signature);
 
3454   # this function calculates the net amount and tax for the lines in ar, ap and
 
3455   # gl and is used for update as well as post. When used with update the return
 
3456   # value of amount isn't needed
 
3458   # calculate_tax should always work with positive values, or rather as the user inputs them
 
3459   # calculate_tax uses db/perl numberformat, i.e. parsed numbers
 
3460   # convert to negative numbers (when necessary) only when writing to acc_trans
 
3461   # the amount from $form for ap/ar/gl is currently always rounded to 2 decimals before it reaches here
 
3462   # for post_transaction amount already contains exchangerate and correct sign and is rounded
 
3463   # calculate_tax doesn't (need to) know anything about exchangerate
 
3465   my ($self,$amount,$taxrate,$taxincluded,$roundplaces) = @_;
 
3473     # calculate tax (unrounded), subtract from amount, round amount and round tax
 
3474     $tax       = $amount - ($amount / ($taxrate + 1)); # equivalent to: taxrate * amount / (taxrate + 1)
 
3475     $amount    = $self->round_amount($amount - $tax, $roundplaces);
 
3476     $tax       = $self->round_amount($tax, $roundplaces);
 
3478     $tax       = $amount * $taxrate;
 
3479     $tax       = $self->round_amount($tax, $roundplaces);
 
3482   $tax = 0 unless $tax;
 
3484   return ($amount,$tax);
 
3493 SL::Form.pm - main data object.
 
3497 This is the main data object of kivitendo.
 
3498 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
 
3499 Points of interest for a beginner are:
 
3501  - $form->error            - renders a generic error in html. accepts an error message
 
3502  - $form->get_standard_dbh - returns a database connection for the
 
3504 =head1 SPECIAL FUNCTIONS
 
3506 =head2 C<redirect_header> $url
 
3508 Generates a HTTP redirection header for the new C<$url>. Constructs an
 
3509 absolute URL including scheme, host name and port. If C<$url> is a
 
3510 relative URL then it is considered relative to kivitendo base URL.
 
3512 This function C<die>s if headers have already been created with
 
3513 C<$::form-E<gt>header>.
 
3517   print $::form->redirect_header('oe.pl?action=edit&id=1234');
 
3518   print $::form->redirect_header('http://www.lx-office.org/');
 
3522 Generates a general purpose http/html header and includes most of the scripts
 
3523 and stylesheets needed. Stylesheets can be added with L<use_stylesheet>.
 
3525 Only one header will be generated. If the method was already called in this
 
3526 request it will not output anything and return undef. Also if no
 
3527 HTTP_USER_AGENT is found, no header is generated.
 
3529 Although header does not accept parameters itself, it will honor special
 
3530 hashkeys of its Form instance:
 
3538 If one of these is set, a http-equiv refresh is generated. Missing parameters
 
3539 default to 3 seconds and the refering url.
 
3543 Either a scalar or an array ref. Will be inlined into the header. Add
 
3544 stylesheets with the L<use_stylesheet> function.
 
3548 If true, a css snippet will be generated that sets the page in landscape mode.
 
3552 Used to override the default favicon.
 
3556 A html page title will be generated from this
 
3558 =item mtime_ischanged
 
3560 Tries to avoid concurrent write operations to records by checking the database mtime with a fetched one.
 
3562 Can be used / called with any table, that has itime and mtime attributes.
 
3563 Valid C<table> names are: oe, ar, ap, delivery_orders, parts.
 
3564 Can be called wit C<option> mail to generate a different error message.
 
3566 Returns undef if no save operation has been done yet ($self->{id} not present).
 
3567 Returns undef if no concurrent write process is detected otherwise a error message.