1 #=====================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   7 #=====================================================================
 
   8 # SQL-Ledger Accounting
 
   9 # Copyright (C) 1998-2002
 
  11 #  Author: Dieter Simader
 
  12 #   Email: dsimader@sql-ledger.org
 
  13 #     Web: http://www.sql-ledger.org
 
  15 # Contributors: Thomas Bayen <bayen@gmx.de>
 
  16 #               Antti Kaihola <akaihola@siba.fi>
 
  17 #               Moritz Bunkus (tex code)
 
  19 # This program is free software; you can redistribute it and/or modify
 
  20 # it under the terms of the GNU General Public License as published by
 
  21 # the Free Software Foundation; either version 2 of the License, or
 
  22 # (at your option) any later version.
 
  24 # This program is distributed in the hope that it will be useful,
 
  25 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 
  26 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  27 # GNU General Public License for more details.
 
  28 # You should have received a copy of the GNU General Public License
 
  29 # along with this program; if not, write to the Free Software
 
  30 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 
  32 #======================================================================
 
  33 # Utilities for parsing forms
 
  34 # and supporting routines for linking account numbers
 
  35 # used in AR, AP and IS, IR modules
 
  37 #======================================================================
 
  52 use POSIX qw(strftime);
 
  64 use SL::DB::PaymentTerm;
 
  67 use SL::Helper::Flash qw();
 
  70 use SL::Layout::Dispatcher;
 
  72 use SL::Locale::String;
 
  75 use SL::MoreCommon qw(uri_encode uri_decode);
 
  77 use SL::PrefixedNumber;
 
  86 use List::Util qw(first max min sum);
 
  87 use List::MoreUtils qw(all any apply);
 
  89 use SL::Helper::File qw(:all);
 
  90 use SL::Helper::Number;
 
  91 use SL::Helper::CreatePDF qw(merge_pdfs);
 
  96   SL::Version->get_version;
 
 100   $main::lxdebug->enter_sub();
 
 107   if ($LXDebug::watch_form) {
 
 108     require SL::Watchdog;
 
 109     tie %{ $self }, 'SL::Watchdog';
 
 114   $main::lxdebug->leave_sub();
 
 119 sub _flatten_variables_rec {
 
 120   $main::lxdebug->enter_sub(2);
 
 129   if ('' eq ref $curr->{$key}) {
 
 130     @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
 
 132   } elsif ('HASH' eq ref $curr->{$key}) {
 
 133     foreach my $hash_key (sort keys %{ $curr->{$key} }) {
 
 134       push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
 
 138     foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
 
 139       my $first_array_entry = 1;
 
 141       my $element = $curr->{$key}[$idx];
 
 143       if ('HASH' eq ref $element) {
 
 144         foreach my $hash_key (sort keys %{ $element }) {
 
 145           push @result, $self->_flatten_variables_rec($element, $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
 
 146           $first_array_entry = 0;
 
 149         push @result, { 'key' => $prefix . $key . '[]', 'value' => $element };
 
 154   $main::lxdebug->leave_sub(2);
 
 159 sub flatten_variables {
 
 160   $main::lxdebug->enter_sub(2);
 
 168     push @variables, $self->_flatten_variables_rec($self, '', $_);
 
 171   $main::lxdebug->leave_sub(2);
 
 176 sub flatten_standard_variables {
 
 177   $main::lxdebug->enter_sub(2);
 
 180   my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar), @_);
 
 184   foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
 
 185     push @variables, $self->_flatten_variables_rec($self, '', $_);
 
 188   $main::lxdebug->leave_sub(2);
 
 194   my ($self, $str) = @_;
 
 196   return uri_encode($str);
 
 200   my ($self, $str) = @_;
 
 202   return uri_decode($str);
 
 206   $main::lxdebug->enter_sub();
 
 207   my ($self, $str) = @_;
 
 209   if ($str && !ref($str)) {
 
 210     $str =~ s/\"/"/g;
 
 213   $main::lxdebug->leave_sub();
 
 219   $main::lxdebug->enter_sub();
 
 220   my ($self, $str) = @_;
 
 222   if ($str && !ref($str)) {
 
 223     $str =~ s/"/\"/g;
 
 226   $main::lxdebug->leave_sub();
 
 232   $main::lxdebug->enter_sub();
 
 236     map({ print($::request->{cgi}->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
 
 238     for (sort keys %$self) {
 
 239       next if (($_ eq "header") || (ref($self->{$_}) ne ""));
 
 240       print($::request->{cgi}->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
 
 243   $main::lxdebug->leave_sub();
 
 247   my ($self, $code) = @_;
 
 248   local $self->{__ERROR_HANDLER} = sub { SL::X::FormError->throw(error => $_[0]) };
 
 253   $main::lxdebug->enter_sub();
 
 255   $main::lxdebug->show_backtrace();
 
 257   my ($self, $msg) = @_;
 
 259   if ($self->{__ERROR_HANDLER}) {
 
 260     $self->{__ERROR_HANDLER}->($msg);
 
 262   } elsif ($ENV{HTTP_USER_AGENT}) {
 
 264     $self->show_generic_error($msg);
 
 267     confess "Error: $msg\n";
 
 270   $main::lxdebug->leave_sub();
 
 274   $main::lxdebug->enter_sub();
 
 276   my ($self, $msg) = @_;
 
 278   if ($ENV{HTTP_USER_AGENT}) {
 
 280     print $self->parse_html_template('generic/form_info', { message => $msg });
 
 282   } elsif ($self->{info_function}) {
 
 283     &{ $self->{info_function} }($msg);
 
 288   $main::lxdebug->leave_sub();
 
 291 # calculates the number of rows in a textarea based on the content and column number
 
 292 # can be capped with maxrows
 
 294   $main::lxdebug->enter_sub();
 
 295   my ($self, $str, $cols, $maxrows, $minrows) = @_;
 
 299   my $rows   = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
 
 302   $main::lxdebug->leave_sub();
 
 304   return max(min($rows, $maxrows), $minrows);
 
 308   my ($self, $msg) = @_;
 
 310   SL::X::DBError->throw(
 
 312     db_error => $DBI::errstr,
 
 317   $main::lxdebug->enter_sub();
 
 319   my ($self, $name, $msg) = @_;
 
 322   foreach my $part (split m/\./, $name) {
 
 323     if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
 
 326     $curr = $curr->{$part};
 
 329   $main::lxdebug->leave_sub();
 
 332 sub _get_request_uri {
 
 335   return URI->new($ENV{HTTP_REFERER})->canonical() if $ENV{HTTP_X_FORWARDED_FOR};
 
 336   return URI->new                                  if !$ENV{REQUEST_URI}; # for testing
 
 338   my $scheme =  $::request->is_https ? 'https' : 'http';
 
 339   my $port   =  $ENV{SERVER_PORT};
 
 340   $port      =  undef if (($scheme eq 'http' ) && ($port == 80))
 
 341                       || (($scheme eq 'https') && ($port == 443));
 
 343   my $uri    =  URI->new("${scheme}://");
 
 344   $uri->scheme($scheme);
 
 346   $uri->host($ENV{HTTP_HOST} || $ENV{SERVER_ADDR});
 
 347   $uri->path_query($ENV{REQUEST_URI});
 
 353 sub _add_to_request_uri {
 
 356   my $relative_new_path = shift;
 
 357   my $request_uri       = shift || $self->_get_request_uri;
 
 358   my $relative_new_uri  = URI->new($relative_new_path);
 
 359   my @request_segments  = $request_uri->path_segments;
 
 361   my $new_uri           = $request_uri->clone;
 
 362   $new_uri->path_segments(@request_segments[0..scalar(@request_segments) - 2], $relative_new_uri->path_segments);
 
 367 sub create_http_response {
 
 368   $main::lxdebug->enter_sub();
 
 373   my $cgi      = $::request->{cgi};
 
 376   if (defined $main::auth) {
 
 377     my $uri      = $self->_get_request_uri;
 
 378     my @segments = $uri->path_segments;
 
 380     $uri->path_segments(@segments);
 
 382     my $session_cookie_value = $main::auth->get_session_id();
 
 384     if ($session_cookie_value) {
 
 385       $session_cookie = $cgi->cookie('-name'    => $main::auth->get_session_cookie_name(),
 
 386                                      '-value'   => $session_cookie_value,
 
 387                                      '-path'    => $uri->path,
 
 388                                      '-expires' => '+' . $::auth->{session_timeout} . 'm',
 
 389                                      '-secure'  => $::request->is_https);
 
 393   my %cgi_params = ('-type' => $params{content_type});
 
 394   $cgi_params{'-charset'} = $params{charset} if ($params{charset});
 
 395   $cgi_params{'-cookie'}  = $session_cookie  if ($session_cookie);
 
 397   map { $cgi_params{'-' . $_} = $params{$_} if exists $params{$_} } qw(content_disposition content_length status);
 
 399   my $output = $cgi->header(%cgi_params);
 
 401   $main::lxdebug->leave_sub();
 
 407   $::lxdebug->enter_sub;
 
 409   my ($self, %params) = @_;
 
 412   $::lxdebug->leave_sub and return if !$ENV{HTTP_USER_AGENT} || $self->{header}++;
 
 414   if ($params{no_layout}) {
 
 415     $::request->{layout} = SL::Layout::Dispatcher->new(style => 'none');
 
 418   my $layout = $::request->{layout};
 
 420   # standard css for all
 
 421   # this should gradually move to the layouts that need it
 
 422   $layout->use_stylesheet("$_.css") for qw(
 
 423     common main menu list_accounts jquery.autocomplete
 
 424     jquery.multiselect2side
 
 425     ui-lightness/jquery-ui
 
 427     tooltipster themes/tooltipster-light
 
 430   $layout->use_javascript("$_.js") for (qw(
 
 431     jquery jquery-ui jquery.cookie jquery.checkall jquery.download
 
 432     jquery/jquery.form jquery/fixes client_js
 
 433     jquery/jquery.tooltipster.min
 
 434     common part_selection
 
 435   ), "jquery/ui/i18n/jquery.ui.datepicker-$::myconfig{countrycode}");
 
 437   $self->{favicon} ||= "favicon.ico";
 
 438   $self->{titlebar} = join ' - ', grep $_, $self->{title}, $self->{login}, $::myconfig{dbname}, $self->read_version if $self->{title} || !$self->{titlebar};
 
 441   if ($self->{refresh_url} || $self->{refresh_time}) {
 
 442     my $refresh_time = $self->{refresh_time} || 3;
 
 443     my $refresh_url  = $self->{refresh_url}  || $ENV{REFERER};
 
 444     push @header, "<meta http-equiv='refresh' content='$refresh_time;$refresh_url'>";
 
 447   my $auto_reload_resources_param = $layout->auto_reload_resources_param;
 
 449   push @header, map { qq|<link rel="stylesheet" href="${_}${auto_reload_resources_param}" type="text/css" title="Stylesheet">| } $layout->stylesheets;
 
 450   push @header, "<style type='text/css'>\@page { size:landscape; }</style> "                     if $self->{landscape};
 
 451   push @header, "<link rel='shortcut icon' href='$self->{favicon}' type='image/x-icon'>"         if -f $self->{favicon};
 
 452   push @header, map { qq|<script type="text/javascript" src="${_}${auto_reload_resources_param}"></script>| }                    $layout->javascripts;
 
 453   push @header, $self->{javascript} if $self->{javascript};
 
 454   push @header, map { $_->show_javascript } @{ $self->{AJAX} || [] };
 
 457     strict       => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">|,
 
 458     transitional => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">|,
 
 459     frameset     => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">|,
 
 460     html5        => qq|<!DOCTYPE html>|,
 
 464   print $self->create_http_response(content_type => 'text/html', charset => 'UTF-8');
 
 465   print $doctypes{$params{doctype} || 'transitional'}, $/;
 
 469   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 
 470   <title>$self->{titlebar}</title>
 
 472   print "  $_\n" for @header;
 
 474   <meta name="robots" content="noindex,nofollow">
 
 479   print $::request->{layout}->pre_content;
 
 480   print $::request->{layout}->start_content;
 
 482   $layout->header_done;
 
 484   $::lxdebug->leave_sub;
 
 488   return unless $::request->{layout}->need_footer;
 
 490   print $::request->{layout}->end_content;
 
 491   print $::request->{layout}->post_content;
 
 493   if (my @inline_scripts = $::request->{layout}->javascripts_inline) {
 
 494     print "<script type='text/javascript'>" . join("; ", @inline_scripts) . "</script>\n";
 
 503 sub ajax_response_header {
 
 504   $main::lxdebug->enter_sub();
 
 508   my $output = $::request->{cgi}->header('-charset' => 'UTF-8');
 
 510   $main::lxdebug->leave_sub();
 
 515 sub redirect_header {
 
 519   my $base_uri = $self->_get_request_uri;
 
 520   my $new_uri  = URI->new_abs($new_url, $base_uri);
 
 522   die "Headers already sent" if $self->{header};
 
 525   return $::request->{cgi}->redirect($new_uri);
 
 528 sub set_standard_title {
 
 529   $::lxdebug->enter_sub;
 
 532   $self->{titlebar}  = "kivitendo " . $::locale->text('Version') . " " . $self->read_version;
 
 533   $self->{titlebar} .= "- $::myconfig{name}"   if $::myconfig{name};
 
 534   $self->{titlebar} .= "- $::myconfig{dbname}" if $::myconfig{name};
 
 536   $::lxdebug->leave_sub;
 
 539 sub _prepare_html_template {
 
 540   $main::lxdebug->enter_sub();
 
 542   my ($self, $file, $additional_params) = @_;
 
 545   if (!%::myconfig || !$::myconfig{"countrycode"}) {
 
 546     $language = $::lx_office_conf{system}->{language};
 
 548     $language = $main::myconfig{"countrycode"};
 
 550   $language = "de" unless ($language);
 
 552   if (-f "templates/webpages/${file}.html") {
 
 553     $file = "templates/webpages/${file}.html";
 
 555   } elsif (ref $file eq 'SCALAR') {
 
 556     # file is a scalarref, use inline mode
 
 558     my $info = "Web page template '${file}' not found.\n";
 
 560     print qq|<pre>$info</pre>|;
 
 561     $::dispatcher->end_request;
 
 564   $additional_params->{AUTH}          = $::auth;
 
 565   $additional_params->{INSTANCE_CONF} = $::instance_conf;
 
 566   $additional_params->{LOCALE}        = $::locale;
 
 567   $additional_params->{LXCONFIG}      = \%::lx_office_conf;
 
 568   $additional_params->{LXDEBUG}       = $::lxdebug;
 
 569   $additional_params->{MYCONFIG}      = \%::myconfig;
 
 571   $main::lxdebug->leave_sub();
 
 576 sub parse_html_template {
 
 577   $main::lxdebug->enter_sub();
 
 579   my ($self, $file, $additional_params) = @_;
 
 581   $additional_params ||= { };
 
 583   my $real_file = $self->_prepare_html_template($file, $additional_params);
 
 584   my $template  = $self->template;
 
 586   map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
 
 589   $template->process($real_file, $additional_params, \$output) || die $template->error;
 
 591   $main::lxdebug->leave_sub();
 
 596 sub template { $::request->presenter->get_template }
 
 598 sub show_generic_error {
 
 599   $main::lxdebug->enter_sub();
 
 601   my ($self, $error, %params) = @_;
 
 603   if ($self->{__ERROR_HANDLER}) {
 
 604     $self->{__ERROR_HANDLER}->($error);
 
 605     $main::lxdebug->leave_sub();
 
 609   if ($::request->is_ajax) {
 
 612       ->render(SL::Controller::Base->new);
 
 613     $::dispatcher->end_request;
 
 617     'title_error' => $params{title},
 
 618     'label_error' => $error,
 
 621   $self->{title} = $params{title} if $params{title};
 
 623   for my $bar ($::request->layout->get('actionbar')) {
 
 627         call      => [ 'kivi.history_back' ],
 
 628         accesskey => 'enter',
 
 634   print $self->parse_html_template("generic/error", $add_params);
 
 636   print STDERR "Error: $error\n";
 
 638   $main::lxdebug->leave_sub();
 
 640   $::dispatcher->end_request;
 
 643 sub show_generic_information {
 
 644   $main::lxdebug->enter_sub();
 
 646   my ($self, $text, $title) = @_;
 
 649     'title_information' => $title,
 
 650     'label_information' => $text,
 
 653   $self->{title} = $title if ($title);
 
 656   print $self->parse_html_template("generic/information", $add_params);
 
 658   $main::lxdebug->leave_sub();
 
 660   $::dispatcher->end_request;
 
 663 sub _store_redirect_info_in_session {
 
 666   return unless $self->{callback} =~ m:^ ( [^\?/]+ \.pl ) \? (.+) :x;
 
 668   my ($controller, $params) = ($1, $2);
 
 669   my $form                  = { map { map { $self->unescape($_) } split /=/, $_, 2 } split m/\&/, $params };
 
 670   $self->{callback}         = "${controller}?RESTORE_FORM_FROM_SESSION_ID=" . $::auth->save_form_in_session(form => $form);
 
 674   $main::lxdebug->enter_sub();
 
 676   my ($self, $msg) = @_;
 
 678   if (!$self->{callback}) {
 
 682     SL::Helper::Flash::flash_later('info', $msg) if $msg;
 
 683     $self->_store_redirect_info_in_session;
 
 684     print $::form->redirect_header($self->{callback});
 
 687   $::dispatcher->end_request;
 
 689   $main::lxdebug->leave_sub();
 
 692 # sort of columns removed - empty sub
 
 694   $main::lxdebug->enter_sub();
 
 696   my ($self, @columns) = @_;
 
 698   $main::lxdebug->leave_sub();
 
 705   my ($self, $myconfig, $amount, $places, $dash) = @_;
 
 706   SL::Helper::Number::_format_number($amount, $places, %$myconfig, dash => $dash);
 
 709 sub format_amount_units {
 
 710   $main::lxdebug->enter_sub();
 
 715   my $myconfig         = \%main::myconfig;
 
 716   my $amount           = $params{amount} * 1;
 
 717   my $places           = $params{places};
 
 718   my $part_unit_name   = $params{part_unit};
 
 719   my $amount_unit_name = $params{amount_unit};
 
 720   my $conv_units       = $params{conv_units};
 
 721   my $max_places       = $params{max_places};
 
 723   if (!$part_unit_name) {
 
 724     $main::lxdebug->leave_sub();
 
 728   my $all_units        = AM->retrieve_all_units;
 
 730   if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
 
 731     $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
 
 734   if (!scalar @{ $conv_units }) {
 
 735     my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
 
 736     $main::lxdebug->leave_sub();
 
 740   my $part_unit  = $all_units->{$part_unit_name};
 
 741   my $conv_unit  = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
 
 743   $amount       *= $conv_unit->{factor};
 
 748   foreach my $unit (@$conv_units) {
 
 749     my $last = $unit->{name} eq $part_unit->{name};
 
 751       $num     = int($amount / $unit->{factor});
 
 752       $amount -= $num * $unit->{factor};
 
 755     if ($last ? $amount : $num) {
 
 756       push @values, { "unit"   => $unit->{name},
 
 757                       "amount" => $last ? $amount / $unit->{factor} : $num,
 
 758                       "places" => $last ? $places : 0 };
 
 765     push @values, { "unit"   => $part_unit_name,
 
 770   my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
 
 772   $main::lxdebug->leave_sub();
 
 778   $main::lxdebug->enter_sub(2);
 
 783   $input =~ s/(^|[^\#]) \#  (\d+)  /$1$_[$2 - 1]/gx;
 
 784   $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
 
 785   $input =~ s/\#\#/\#/g;
 
 787   $main::lxdebug->leave_sub(2);
 
 795   my ($self, $myconfig, $amount) = @_;
 
 796   SL::Helper::Number::_parse_number($amount, %$myconfig);
 
 799 sub round_amount { shift; goto &SL::Helper::Number::_round_number; }
 
 802   $main::lxdebug->enter_sub();
 
 804   my ($self, $myconfig) = @_;
 
 805   my ($out, $out_mode);
 
 809   my $defaults        = SL::DB::Default->get;
 
 811   my $keep_temp_files = $::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files};
 
 812   $self->{cwd}        = getcwd();
 
 813   my $temp_dir        = File::Temp->newdir(
 
 814     "kivitendo-print-XXXXXX",
 
 815     DIR     => $self->{cwd} . "/" . $::lx_office_conf{paths}->{userspath},
 
 816     CLEANUP => !$keep_temp_files,
 
 819   my $userspath   = File::Spec->abs2rel($temp_dir->dirname);
 
 820   $self->{tmpdir} = $temp_dir->dirname;
 
 825   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
 
 826     $template_type  = 'OpenDocument';
 
 827     $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
 
 829   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
 
 830     $template_type    = 'LaTeX';
 
 831     $ext_for_format   = 'pdf';
 
 833   } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
 
 834     $template_type  = 'HTML';
 
 835     $ext_for_format = 'html';
 
 837   } elsif ( $self->{"format"} =~ /excel/i ) {
 
 838     $template_type  = 'Excel';
 
 839     $ext_for_format = 'xls';
 
 841   } elsif ( defined $self->{'format'}) {
 
 842     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
 
 844   } elsif ( $self->{'format'} eq '' ) {
 
 845     $self->error("No Outputformat given: $self->{'format'}");
 
 847   } else { #Catch the rest
 
 848     $self->error("Outputformat not defined: $self->{'format'}");
 
 851   my $template = SL::Template::create(type      => $template_type,
 
 852                                       file_name => $self->{IN},
 
 854                                       myconfig  => $myconfig,
 
 855                                       userspath => $userspath,
 
 856                                       %{ $self->{TEMPLATE_DRIVER_OPTIONS} || {} });
 
 858   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
 
 859   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" } if exists $self->{ $self->{"formname"} . "notes" };
 
 861   if (!$self->{employee_id}) {
 
 862     $self->{"employee_${_}"} = $myconfig->{$_} for qw(email tel fax name signature);
 
 863     $self->{"employee_${_}"} = $defaults->$_   for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
 
 866   $self->{"myconfig_${_}"} = $myconfig->{$_} for grep { $_ ne 'dbpasswd' } keys %{ $myconfig };
 
 867   $self->{$_}              = $defaults->$_   for qw(co_ustid);
 
 868   $self->{"myconfig_${_}"} = $defaults->$_   for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
 
 869   $self->{AUTH}            = $::auth;
 
 870   $self->{INSTANCE_CONF}   = $::instance_conf;
 
 871   $self->{LOCALE}          = $::locale;
 
 872   $self->{LXCONFIG}        = $::lx_office_conf;
 
 873   $self->{LXDEBUG}         = $::lxdebug;
 
 874   $self->{MYCONFIG}        = \%::myconfig;
 
 876   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
 
 878   # OUT is used for the media, screen, printer, email
 
 879   # for postscript we store a copy in a temporary file
 
 881   my ($temp_fh, $suffix);
 
 882   $suffix =  $self->{IN};
 
 884   ($temp_fh, $self->{tmpfile}) = File::Temp::tempfile(
 
 885     strftime('kivitendo-print-%Y%m%d%H%M%S-XXXXXX', localtime()),
 
 886     SUFFIX => '.' . ($suffix || 'tex'),
 
 888     UNLINK => $keep_temp_files ? 0 : 1,
 
 891   chmod 0644, $self->{tmpfile} if $keep_temp_files;
 
 892   (undef, undef, $self->{template_meta}{tmpfile}) = File::Spec->splitpath( $self->{tmpfile} );
 
 895   $out_mode         = $self->{OUT_MODE} || '>';
 
 896   $self->{OUT}      = "$self->{tmpfile}";
 
 897   $self->{OUT_MODE} = '>';
 
 900   my $command_formatter = sub {
 
 901     my ($out_mode, $out) = @_;
 
 902     return $out_mode eq '|-' ? SL::Template::create(type => 'ShellCommand', form => $self)->parse($out) : $out;
 
 906     $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
 
 907     open(OUT, $self->{OUT_MODE}, $self->{OUT}) or $self->error("error on opening $self->{OUT} with mode $self->{OUT_MODE} : $!");
 
 909     *OUT = ($::dispatcher->get_standard_filehandles)[1];
 
 913   if (!$template->parse(*OUT)) {
 
 915     $self->error("$self->{IN} : " . $template->get_error());
 
 918   close OUT if $self->{OUT};
 
 919   # check only one flag (webdav_documents)
 
 920   # therefore copy to webdav, even if we do not have the webdav feature enabled (just archive)
 
 921   my $copy_to_webdav =  $::instance_conf->get_webdav_documents && !$self->{preview} && $self->{tmpdir} && $self->{tmpfile} && $self->{type}
 
 922                         && $self->{type} ne 'statement';
 
 923   if ( $ext_for_format eq 'pdf' && $self->doc_storage_enabled ) {
 
 924     $self->append_general_pdf_attachments(filepath =>  $self->{tmpdir}."/".$self->{tmpfile},
 
 925                                           type     =>  $self->{type});
 
 927   if ($self->{media} eq 'file') {
 
 928     copy(join('/', $self->{cwd}, $userspath, $self->{tmpfile}), $out =~ m|^/| ? $out : join('/', $self->{cwd}, $out)) if $template->uses_temp_file;
 
 930     if ($copy_to_webdav) {
 
 931       if (my $error = Common::copy_file_to_webdav_folder($self)) {
 
 932         chdir("$self->{cwd}");
 
 933         $self->error($error);
 
 937     if (!$self->{preview} && $self->{attachment_type} !~ m{^dunning} && $self->doc_storage_enabled)
 
 939       $self->{attachment_filename} ||= $self->generate_attachment_filename;
 
 940       $self->store_pdf($self);
 
 943     chdir("$self->{cwd}");
 
 945     $::lxdebug->leave_sub();
 
 950   if ($copy_to_webdav) {
 
 951     if (my $error = Common::copy_file_to_webdav_folder($self)) {
 
 952       chdir("$self->{cwd}");
 
 953       $self->error($error);
 
 957   if ( !$self->{preview} && $ext_for_format eq 'pdf' && $self->{attachment_type} !~ m{^dunning} && $self->doc_storage_enabled) {
 
 958     $self->{attachment_filename} ||= $self->generate_attachment_filename;
 
 959     my $file_obj = $self->store_pdf($self);
 
 960     $self->{print_file_id} = $file_obj->id if $file_obj;
 
 962   if ($self->{media} eq 'email') {
 
 963     if ( getcwd() eq $self->{"tmpdir"} ) {
 
 964       # in the case of generating pdf we are in the tmpdir, but WHY ???
 
 965       $self->{tmpfile} = $userspath."/".$self->{tmpfile};
 
 966       chdir("$self->{cwd}");
 
 968     $self->send_email(\%::myconfig,$ext_for_format);
 
 972     $self->{OUT_MODE} = $out_mode;
 
 973     $self->output_file($template->get_mime_type,$command_formatter);
 
 975   delete $self->{print_file_id};
 
 979   chdir("$self->{cwd}");
 
 980   $main::lxdebug->leave_sub();
 
 983 sub get_bcc_defaults {
 
 984   my ($self, $myconfig, $mybcc) = @_;
 
 985   if (SL::DB::Default->get->bcc_to_login) {
 
 986     $mybcc .= ", " if $mybcc;
 
 987     $mybcc .= $myconfig->{email};
 
 989   my $otherbcc = SL::DB::Default->get->global_bcc;
 
 991     $mybcc .= ", " if $mybcc;
 
 998   $main::lxdebug->enter_sub();
 
 999   my ($self, $myconfig, $ext_for_format) = @_;
 
1000   my $mail = Mailer->new;
 
1002   map { $mail->{$_} = $self->{$_} }
 
1003     qw(cc subject message format);
 
1005   if ($self->{cc_employee}) {
 
1006     my ($user, $my_emp_cc);
 
1007     $user        = SL::DB::Manager::AuthUser->find_by(login => $self->{cc_employee});
 
1008     $my_emp_cc   = $user->get_config_value('email') if ref $user eq 'SL::DB::AuthUser';
 
1009     $mail->{cc} .= ", "       if $mail->{cc};
 
1010     $mail->{cc} .= $my_emp_cc if $my_emp_cc;
 
1013   $mail->{bcc}    = $self->get_bcc_defaults($myconfig, $self->{bcc});
 
1014   $mail->{to}     = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
 
1015   $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
 
1016   $mail->{fileid} = time() . '.' . $$ . '.';
 
1017   my $full_signature     =  $self->create_email_signature();
 
1018   $full_signature        =~ s/\r//g;
 
1020   $mail->{attachments} =  [];
 
1022   # if we send html or plain text inline
 
1023   if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
 
1024     $mail->{content_type}   =  "text/html";
 
1025     $mail->{message}        =~ s/\r//g;
 
1026     $mail->{message}        =~ s{\n}{<br>\n}g;
 
1027     $full_signature         =~ s{\n}{<br>\n}g;
 
1028     $mail->{message}       .=  $full_signature;
 
1030     open(IN, "<", $self->{tmpfile})
 
1031       or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1032     $mail->{message} .= $_ while <IN>;
 
1035   } elsif (($self->{attachment_policy} // '') ne 'no_file') {
 
1036     my $attachment_name  =  $self->{attachment_filename}  || $self->{tmpfile};
 
1037     $attachment_name     =~ s{\.(.+?)$}{.${ext_for_format}} if ($ext_for_format);
 
1039     if (($self->{attachment_policy} // '') eq 'old_file') {
 
1040       my ( $attfile ) = SL::File->get_all(object_id   => $self->{id},
 
1041                                           object_type => $self->{formname},
 
1042                                           file_type   => 'document');
 
1045         $attfile->{override_file_name} = $attachment_name if $attachment_name;
 
1046         push @attfiles, $attfile;
 
1050       push @{ $mail->{attachments} }, { path => $self->{tmpfile},
 
1051                                         id   => $self->{print_file_id},
 
1052                                         type => "application/pdf",
 
1053                                         name => $attachment_name };
 
1059     map  { SL::File->get(id => $_) }
 
1060     @{ $self->{attach_file_ids} // [] };
 
1062   foreach my $attfile ( @attfiles ) {
 
1063     push @{ $mail->{attachments} }, {
 
1064       path    => $attfile->get_file,
 
1066       type    => $attfile->mime_type,
 
1067       name    => $attfile->{override_file_name} // $attfile->file_name,
 
1068       content => $attfile->get_content ? ${ $attfile->get_content } : undef,
 
1072   $mail->{message}  =~ s/\r//g;
 
1073   $mail->{message} .= $full_signature;
 
1074   $self->{emailerr} = $mail->send();
 
1076   if ($self->{emailerr}) {
 
1078     $self->error($::locale->text('The email was not sent due to the following error: #1.', $self->{emailerr}));
 
1081   $self->{email_journal_id} = $mail->{journalentry};
 
1082   $self->{snumbers}  = "emailjournal" . "_" . $self->{email_journal_id};
 
1083   $self->{what_done} = $::form->{type};
 
1084   $self->{addition}  = "MAILED";
 
1085   $self->save_history;
 
1087   #write back for message info and mail journal
 
1088   $self->{cc}  = $mail->{cc};
 
1089   $self->{bcc} = $mail->{bcc};
 
1090   $self->{email} = $mail->{to};
 
1092   $main::lxdebug->leave_sub();
 
1096   $main::lxdebug->enter_sub();
 
1098   my ($self,$mimeType,$command_formatter) = @_;
 
1099   my $numbytes = (-s $self->{tmpfile});
 
1100   open(IN, "<", $self->{tmpfile})
 
1101     or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1104   $self->{copies} = 1 unless $self->{media} eq 'printer';
 
1106   chdir("$self->{cwd}");
 
1107   for my $i (1 .. $self->{copies}) {
 
1109       $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
 
1111       open  OUT, $self->{OUT_MODE}, $self->{OUT} or $self->error($self->cleanup . "$self->{OUT} : $!");
 
1112       print OUT $_ while <IN>;
 
1117       my %headers = ('-type'       => $mimeType,
 
1118                      '-connection' => 'close',
 
1119                      '-charset'    => 'UTF-8');
 
1121       $self->{attachment_filename} ||= $self->generate_attachment_filename;
 
1123       if ($self->{attachment_filename}) {
 
1126           '-attachment'     => $self->{attachment_filename},
 
1127           '-content-length' => $numbytes,
 
1132       print $::request->cgi->header(%headers);
 
1134       $::locale->with_raw_io(\*STDOUT, sub { print while <IN> });
 
1138   $main::lxdebug->leave_sub();
 
1141 sub get_formname_translation {
 
1142   $main::lxdebug->enter_sub();
 
1143   my ($self, $formname) = @_;
 
1145   $formname ||= $self->{formname};
 
1147   $self->{recipient_locale} ||=  Locale->lang_to_locale($self->{language});
 
1148   local $::locale = Locale->new($self->{recipient_locale});
 
1150   my %formname_translations = (
 
1151     bin_list                => $main::locale->text('Bin List'),
 
1152     credit_note             => $main::locale->text('Credit Note'),
 
1153     invoice                 => $main::locale->text('Invoice'),
 
1154     pick_list               => $main::locale->text('Pick List'),
 
1155     proforma                => $main::locale->text('Proforma Invoice'),
 
1156     purchase_order          => $main::locale->text('Purchase Order'),
 
1157     request_quotation       => $main::locale->text('RFQ'),
 
1158     sales_order             => $main::locale->text('Confirmation'),
 
1159     sales_quotation         => $main::locale->text('Quotation'),
 
1160     storno_invoice          => $main::locale->text('Storno Invoice'),
 
1161     sales_delivery_order    => $main::locale->text('Delivery Order'),
 
1162     purchase_delivery_order => $main::locale->text('Delivery Order'),
 
1163     dunning                 => $main::locale->text('Dunning'),
 
1164     dunning1                => $main::locale->text('Payment Reminder'),
 
1165     dunning2                => $main::locale->text('Dunning'),
 
1166     dunning3                => $main::locale->text('Last Dunning'),
 
1167     dunning_invoice         => $main::locale->text('Dunning Invoice'),
 
1168     letter                  => $main::locale->text('Letter'),
 
1169     ic_supply               => $main::locale->text('Intra-Community supply'),
 
1170     statement               => $main::locale->text('Statement'),
 
1173   $main::lxdebug->leave_sub();
 
1174   return $formname_translations{$formname};
 
1177 sub get_cusordnumber_translation {
 
1178   $main::lxdebug->enter_sub();
 
1179   my ($self, $formname) = @_;
 
1181   $formname ||= $self->{formname};
 
1183   $self->{recipient_locale} ||=  Locale->lang_to_locale($self->{language});
 
1184   local $::locale = Locale->new($self->{recipient_locale});
 
1187   $main::lxdebug->leave_sub();
 
1188   return $main::locale->text('Your Order');
 
1191 sub get_number_prefix_for_type {
 
1192   $main::lxdebug->enter_sub();
 
1196       (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
 
1197     : ($self->{type} =~ /_quotation$/)                        ? 'quo'
 
1198     : ($self->{type} =~ /_delivery_order$/)                   ? 'do'
 
1199     : ($self->{type} =~ /letter/)                             ? 'letter'
 
1202   # better default like this?
 
1203   # : ($self->{type} =~ /(sales|purcharse)_order/           :  'ord';
 
1204   # :                                                           'prefix_undefined';
 
1206   $main::lxdebug->leave_sub();
 
1210 sub get_extension_for_format {
 
1211   $main::lxdebug->enter_sub();
 
1214   my $extension = $self->{format} =~ /pdf/i          ? ".pdf"
 
1215                 : $self->{format} =~ /postscript/i   ? ".ps"
 
1216                 : $self->{format} =~ /opendocument/i ? ".odt"
 
1217                 : $self->{format} =~ /excel/i        ? ".xls"
 
1218                 : $self->{format} =~ /html/i         ? ".html"
 
1221   $main::lxdebug->leave_sub();
 
1225 sub generate_attachment_filename {
 
1226   $main::lxdebug->enter_sub();
 
1229   $self->{recipient_locale} ||=  Locale->lang_to_locale($self->{language});
 
1230   my $recipient_locale = Locale->new($self->{recipient_locale});
 
1232   my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
 
1233   my $prefix              = $self->get_number_prefix_for_type();
 
1235   if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
 
1236     $attachment_filename .= ' (' . $recipient_locale->text('Preview') . ')' . $self->get_extension_for_format();
 
1238   } elsif ($attachment_filename && $self->{"${prefix}number"}) {
 
1239     $attachment_filename .=  "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
 
1241   } elsif ($attachment_filename) {
 
1242     $attachment_filename .=  $self->get_extension_for_format();
 
1245     $attachment_filename = "";
 
1248   $attachment_filename =  $main::locale->quote_special_chars('filenames', $attachment_filename);
 
1249   $attachment_filename =~ s|[\s/\\]+|_|g;
 
1251   $main::lxdebug->leave_sub();
 
1252   return $attachment_filename;
 
1255 sub generate_email_subject {
 
1256   $main::lxdebug->enter_sub();
 
1259   my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
 
1260   my $prefix  = $self->get_number_prefix_for_type();
 
1262   if ($subject && $self->{"${prefix}number"}) {
 
1263     $subject .= " " . $self->{"${prefix}number"}
 
1266   if ($self->{cusordnumber}) {
 
1267     $subject = $self->get_cusordnumber_translation() . ' ' . $self->{cusordnumber} . ' / ' . $subject;
 
1270   $main::lxdebug->leave_sub();
 
1274 sub generate_email_body {
 
1275   $main::lxdebug->enter_sub();
 
1276   my ($self, %params) = @_;
 
1277   # simple german and english will work grammatically (most european languages as well)
 
1278   # Dear Mr Alan Greenspan:
 
1279   # Sehr geehrte Frau Meyer,
 
1280   # A l’attention de Mme Villeroy,
 
1281   # Gentile Signora Ferrari,
 
1284   if ($self->{cp_id} && !$params{record_email}) {
 
1285     my $givenname = SL::DB::Contact->load_cached($self->{cp_id})->cp_givenname; # for qw(gender givename name);
 
1286     my $name      = SL::DB::Contact->load_cached($self->{cp_id})->cp_name; # for qw(gender givename name);
 
1287     my $gender    = SL::DB::Contact->load_cached($self->{cp_id})->cp_gender; # for qw(gender givename name);
 
1288     my $mf = $gender eq 'f' ? 'female' : 'male';
 
1289     $body  = GenericTranslations->get(translation_type => "salutation_$mf", language_id => $self->{language_id});
 
1290     $body .= ' ' . $givenname . ' ' . $name if $body;
 
1292     $body  = GenericTranslations->get(translation_type => "salutation_general", language_id => $self->{language_id});
 
1295   return undef unless $body;
 
1297   my $translation_type = $params{translation_type} // "preset_text_$self->{formname}";
 
1298   my $main_body        = GenericTranslations->get(translation_type => $translation_type,                  language_id => $self->{language_id});
 
1299   $main_body           = GenericTranslations->get(translation_type => $params{fallback_translation_type}, language_id => $self->{language_id}) if !$main_body && $params{fallback_translation_type};
 
1300   $body               .= GenericTranslations->get(translation_type => "salutation_punctuation_mark",      language_id => $self->{language_id}) . "\n\n";
 
1301   $body               .= $main_body;
 
1303   $body = $main::locale->unquote_special_chars('HTML', $body);
 
1305   $main::lxdebug->leave_sub();
 
1310   $main::lxdebug->enter_sub();
 
1312   my ($self, $application) = @_;
 
1314   my $error_code = $?;
 
1316   chdir("$self->{tmpdir}");
 
1319   if ((-1 == $error_code) || (127 == (($error_code) >> 8))) {
 
1320     push @err, $::locale->text('The application "#1" was not found on the system.', $application || 'pdflatex') . ' ' . $::locale->text('Please contact your administrator.');
 
1322   } elsif (-f "$self->{tmpfile}.err") {
 
1323     open(FH, "<:encoding(UTF-8)", "$self->{tmpfile}.err");
 
1328   if ($self->{tmpfile} && !($::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files})) {
 
1329     $self->{tmpfile} =~ s|.*/||g;
 
1331     $self->{tmpfile} =~ s/\.\w+$//g;
 
1332     my $tmpfile = $self->{tmpfile};
 
1333     unlink(<$tmpfile.*>);
 
1336   chdir("$self->{cwd}");
 
1338   $main::lxdebug->leave_sub();
 
1344   $main::lxdebug->enter_sub();
 
1346   my ($self, $date, $myconfig) = @_;
 
1349   if ($date && $date =~ /\D/) {
 
1351     if ($myconfig->{dateformat} =~ /^yy/) {
 
1352       ($yy, $mm, $dd) = split /\D/, $date;
 
1354     if ($myconfig->{dateformat} =~ /^mm/) {
 
1355       ($mm, $dd, $yy) = split /\D/, $date;
 
1357     if ($myconfig->{dateformat} =~ /^dd/) {
 
1358       ($dd, $mm, $yy) = split /\D/, $date;
 
1363     $yy = ($yy < 70) ? $yy + 2000 : $yy;
 
1364     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
 
1366     $dd = "0$dd" if ($dd < 10);
 
1367     $mm = "0$mm" if ($mm < 10);
 
1369     $date = "$yy$mm$dd";
 
1372   $main::lxdebug->leave_sub();
 
1377 # Database routines used throughout
 
1378 # DB Handling got moved to SL::DB, these are only shims for compatibility
 
1381   SL::DB->client->dbh;
 
1384 sub get_standard_dbh {
 
1385   my $dbh = SL::DB->client->dbh;
 
1387   if ($dbh && !$dbh->{Active}) {
 
1388     $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$dbh is defined but not Active anymore");
 
1389     SL::DB->client->dbh(undef);
 
1392   SL::DB->client->dbh;
 
1395 sub disconnect_standard_dbh {
 
1396   SL::DB->client->dbh->rollback;
 
1402   $main::lxdebug->enter_sub();
 
1404   my ($self, $date, $myconfig) = @_;
 
1405   my $dbh = $self->get_standard_dbh;
 
1407   my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
 
1408   my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
 
1410   # Falls $date = '' - Fehlermeldung aus der Datenbank. Ich denke,
 
1411   # es ist sicher ein conv_date vorher IMMER auszuführen.
 
1412   # Testfälle ohne definiertes closedto:
 
1413   #   Leere Datumseingabe i.O.
 
1414   #     SELECT 1 FROM defaults WHERE '' < closedto
 
1415   #   normale Zahlungsbuchung Ã¼ber Rechnungsmaske i.O.
 
1416   #     SELECT 1 FROM defaults WHERE '10.05.2011' < closedto
 
1417   # Testfälle mit definiertem closedto (30.04.2011):
 
1418   #  Leere Datumseingabe i.O.
 
1419   #   SELECT 1 FROM defaults WHERE '' < closedto
 
1420   # normale Buchung im geschloßenem Zeitraum i.O.
 
1421   #   SELECT 1 FROM defaults WHERE '21.04.2011' < closedto
 
1422   #     Fehlermeldung: Es können keine Zahlungen für abgeschlossene Bücher gebucht werden!
 
1423   # normale Buchung in aktiver Buchungsperiode i.O.
 
1424   #   SELECT 1 FROM defaults WHERE '01.05.2011' < closedto
 
1426   my ($closed) = $sth->fetchrow_array;
 
1428   $main::lxdebug->leave_sub();
 
1433 # prevents bookings to the to far away future
 
1434 sub date_max_future {
 
1435   $main::lxdebug->enter_sub();
 
1437   my ($self, $date, $myconfig) = @_;
 
1438   my $dbh = $self->get_standard_dbh;
 
1440   my $query = "SELECT 1 FROM defaults WHERE ? - current_date > max_future_booking_interval";
 
1441   my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
 
1443   my ($max_future_booking_interval) = $sth->fetchrow_array;
 
1445   $main::lxdebug->leave_sub();
 
1447   return $max_future_booking_interval;
 
1451 sub update_balance {
 
1452   $main::lxdebug->enter_sub();
 
1454   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
 
1456   # if we have a value, go do it
 
1459     # retrieve balance from table
 
1460     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
 
1461     my $sth = prepare_execute_query($self, $dbh, $query, @values);
 
1462     my ($balance) = $sth->fetchrow_array;
 
1468     $query = "UPDATE $table SET $field = $balance WHERE $where";
 
1469     do_query($self, $dbh, $query, @values);
 
1471   $main::lxdebug->leave_sub();
 
1474 sub update_exchangerate {
 
1475   $main::lxdebug->enter_sub();
 
1477   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
 
1479   # some sanity check for currency
 
1481     $main::lxdebug->leave_sub();
 
1484   $query = qq|SELECT name AS curr FROM currencies WHERE id=(SELECT currency_id FROM defaults)|;
 
1486   my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
 
1488   if ($curr eq $defaultcurrency) {
 
1489     $main::lxdebug->leave_sub();
 
1493   $query = qq|SELECT e.currency_id FROM exchangerate e
 
1494                  WHERE e.currency_id = (SELECT cu.id FROM currencies cu WHERE cu.name=?) AND e.transdate = ?
 
1496   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
 
1505   $buy = conv_i($buy, "NULL");
 
1506   $sell = conv_i($sell, "NULL");
 
1509   if ($buy != 0 && $sell != 0) {
 
1510     $set = "buy = $buy, sell = $sell";
 
1511   } elsif ($buy != 0) {
 
1512     $set = "buy = $buy";
 
1513   } elsif ($sell != 0) {
 
1514     $set = "sell = $sell";
 
1517   if ($sth->fetchrow_array) {
 
1518     $query = qq|UPDATE exchangerate
 
1520                 WHERE currency_id = (SELECT id FROM currencies WHERE name = ?)
 
1524     $query = qq|INSERT INTO exchangerate (currency_id, buy, sell, transdate)
 
1525                 VALUES ((SELECT id FROM currencies WHERE name = ?), $buy, $sell, ?)|;
 
1528   do_query($self, $dbh, $query, $curr, $transdate);
 
1530   $main::lxdebug->leave_sub();
 
1533 sub save_exchangerate {
 
1534   $main::lxdebug->enter_sub();
 
1536   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
 
1538   SL::DB->client->with_transaction(sub {
 
1539     my $dbh = SL::DB->client->dbh;
 
1543     $buy  = $rate if $fld eq 'buy';
 
1544     $sell = $rate if $fld eq 'sell';
 
1547     $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
 
1549   }) or do { die SL::DB->client->error };
 
1551   $main::lxdebug->leave_sub();
 
1554 sub get_exchangerate {
 
1555   $main::lxdebug->enter_sub();
 
1557   my ($self, $dbh, $curr, $transdate, $fld) = @_;
 
1560   unless ($transdate && $curr) {
 
1561     $main::lxdebug->leave_sub();
 
1565   $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
 
1567   my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
 
1569   if ($curr eq $defaultcurrency) {
 
1570     $main::lxdebug->leave_sub();
 
1574   $query = qq|SELECT e.$fld FROM exchangerate e
 
1575                  WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
 
1576   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
 
1580   $main::lxdebug->leave_sub();
 
1582   return $exchangerate;
 
1585 sub check_exchangerate {
 
1586   $main::lxdebug->enter_sub();
 
1588   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
 
1590   if ($fld !~/^buy|sell$/) {
 
1591     $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
 
1594   unless ($transdate) {
 
1595     $main::lxdebug->leave_sub();
 
1599   my ($defaultcurrency) = $self->get_default_currency($myconfig);
 
1601   if ($currency eq $defaultcurrency) {
 
1602     $main::lxdebug->leave_sub();
 
1606   my $dbh   = $self->get_standard_dbh($myconfig);
 
1607   my $query = qq|SELECT e.$fld FROM exchangerate e
 
1608                  WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
 
1610   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
 
1612   $main::lxdebug->leave_sub();
 
1614   return $exchangerate;
 
1617 sub get_all_currencies {
 
1618   $main::lxdebug->enter_sub();
 
1621   my $myconfig = shift || \%::myconfig;
 
1622   my $dbh      = $self->get_standard_dbh($myconfig);
 
1624   my $query = qq|SELECT name FROM currencies|;
 
1625   my @currencies = map { $_->{name} } selectall_hashref_query($self, $dbh, $query);
 
1627   $main::lxdebug->leave_sub();
 
1632 sub get_default_currency {
 
1633   $main::lxdebug->enter_sub();
 
1635   my ($self, $myconfig) = @_;
 
1636   my $dbh      = $self->get_standard_dbh($myconfig);
 
1637   my $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
 
1639   my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
 
1641   $main::lxdebug->leave_sub();
 
1643   return $defaultcurrency;
 
1646 sub set_payment_options {
 
1647   my ($self, $myconfig, $transdate, $type) = @_;
 
1649   my $terms = $self->{payment_id} ? SL::DB::PaymentTerm->new(id => $self->{payment_id})->load : undef;
 
1652   my $is_invoice                = $type =~ m{invoice}i;
 
1654   $transdate                  ||= $self->{invdate} || $self->{transdate};
 
1655   my $due_date                  = $self->{duedate} || $self->{reqdate};
 
1657   $self->{$_}                   = $terms->$_ for qw(terms_netto terms_skonto percent_skonto);
 
1658   $self->{payment_description}  = $terms->description;
 
1659   $self->{netto_date}           = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'net')->to_kivitendo;
 
1660   $self->{skonto_date}          = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'discount')->to_kivitendo;
 
1662   my ($invtotal, $total);
 
1663   my (%amounts, %formatted_amounts);
 
1665   if ($self->{type} =~ /_order$/) {
 
1666     $amounts{invtotal} = $self->{ordtotal};
 
1667     $amounts{total}    = $self->{ordtotal};
 
1669   } elsif ($self->{type} =~ /_quotation$/) {
 
1670     $amounts{invtotal} = $self->{quototal};
 
1671     $amounts{total}    = $self->{quototal};
 
1674     $amounts{invtotal} = $self->{invtotal};
 
1675     $amounts{total}    = $self->{total};
 
1677   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
 
1679   $amounts{skonto_in_percent}  = 100.0 * $self->{percent_skonto};
 
1680   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
 
1681   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
 
1682   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
 
1684   foreach (keys %amounts) {
 
1685     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
 
1686     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
 
1689   if ($self->{"language_id"}) {
 
1690     my $language             = SL::DB::Language->new(id => $self->{language_id})->load;
 
1692     $self->{payment_terms}   = $type =~ m{invoice}i ? $terms->translated_attribute('description_long_invoice', $language->id) : undef;
 
1693     $self->{payment_terms} ||= $terms->translated_attribute('description_long', $language->id);
 
1695     if ($language->output_dateformat) {
 
1696       foreach my $key (qw(netto_date skonto_date)) {
 
1697         $self->{$key} = $::locale->reformat_date($myconfig, $self->{$key}, $language->output_dateformat, $language->output_longdates);
 
1701     if ($language->output_numberformat && ($language->output_numberformat ne $myconfig->{numberformat})) {
 
1702       local $myconfig->{numberformat};
 
1703       $myconfig->{"numberformat"} = $language->output_numberformat;
 
1704       $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) for keys %amounts;
 
1708   $self->{payment_terms} =  $self->{payment_terms} || ($is_invoice ? $terms->description_long_invoice : undef) || $terms->description_long;
 
1710   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
 
1711   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
 
1712   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
 
1713   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
 
1714   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
 
1715   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
 
1716   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
 
1717   $self->{payment_terms} =~ s/<\%bic\%>/$self->{bic}/g;
 
1718   $self->{payment_terms} =~ s/<\%iban\%>/$self->{iban}/g;
 
1719   $self->{payment_terms} =~ s/<\%mandate_date_of_signature\%>/$self->{mandate_date_of_signature}/g;
 
1720   $self->{payment_terms} =~ s/<\%mandator_id\%>/$self->{mandator_id}/g;
 
1722   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
 
1724   $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
 
1728 sub get_template_language {
 
1729   $main::lxdebug->enter_sub();
 
1731   my ($self, $myconfig) = @_;
 
1733   my $template_code = "";
 
1735   if ($self->{language_id}) {
 
1736     my $dbh = $self->get_standard_dbh($myconfig);
 
1737     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
 
1738     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
 
1741   $main::lxdebug->leave_sub();
 
1743   return $template_code;
 
1746 sub get_printer_code {
 
1747   $main::lxdebug->enter_sub();
 
1749   my ($self, $myconfig) = @_;
 
1751   my $template_code = "";
 
1753   if ($self->{printer_id}) {
 
1754     my $dbh = $self->get_standard_dbh($myconfig);
 
1755     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
 
1756     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
 
1759   $main::lxdebug->leave_sub();
 
1761   return $template_code;
 
1765   $main::lxdebug->enter_sub();
 
1767   my ($self, $myconfig) = @_;
 
1769   my $template_code = "";
 
1771   if ($self->{shipto_id}) {
 
1772     my $dbh = $self->get_standard_dbh($myconfig);
 
1773     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
 
1774     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
 
1775     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
 
1777     my $cvars = CVar->get_custom_variables(
 
1780       trans_id => $self->{shipto_id},
 
1782     $self->{"shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
 
1785   $main::lxdebug->leave_sub();
 
1789   my ($self, $dbh, $id, $module) = @_;
 
1794   foreach my $item (qw(name department_1 department_2 street zipcode city country gln
 
1795                        contact phone fax email)) {
 
1796     if ($self->{"shipto$item"}) {
 
1797       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
 
1799     push(@values, $self->{"shipto${item}"});
 
1804   # shiptocp_gender only makes sense, if any other shipto attribute is set.
 
1805   # Because shiptocp_gender is set to 'm' by default in forms
 
1806   # it must not be considered above to decide if shiptos has to be added or
 
1807   # updated, but must be inserted or updated as well in case.
 
1808   push(@values, $self->{shiptocp_gender});
 
1810   my $shipto_id = $self->{shipto_id};
 
1812   if ($self->{shipto_id}) {
 
1813     my $query = qq|UPDATE shipto set
 
1815                      shiptodepartment_1 = ?,
 
1816                      shiptodepartment_2 = ?,
 
1826                      shiptocp_gender = ?,
 
1827                    WHERE shipto_id = ?|;
 
1828     do_query($self, $dbh, $query, @values, $self->{shipto_id});
 
1830     my $query = qq|SELECT * FROM shipto
 
1831                    WHERE shiptoname = ? AND
 
1832                      shiptodepartment_1 = ? AND
 
1833                      shiptodepartment_2 = ? AND
 
1834                      shiptostreet = ? AND
 
1835                      shiptozipcode = ? AND
 
1837                      shiptocountry = ? AND
 
1839                      shiptocontact = ? AND
 
1843                      shiptocp_gender = ? AND
 
1846     my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
 
1849         qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
 
1850                                shiptostreet, shiptozipcode, shiptocity, shiptocountry, shiptogln,
 
1851                                shiptocontact, shiptophone, shiptofax, shiptoemail, shiptocp_gender, module)
 
1852            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
 
1853       do_query($self, $dbh, $insert_query, $id, @values, $module);
 
1855       $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
 
1858     $shipto_id = $insert_check->{shipto_id};
 
1861   return unless $shipto_id;
 
1863   CVar->save_custom_variables(
 
1866     trans_id    => $shipto_id,
 
1868     name_prefix => 'shipto',
 
1873   $main::lxdebug->enter_sub();
 
1875   my ($self, $dbh) = @_;
 
1877   $dbh ||= $self->get_standard_dbh(\%main::myconfig);
 
1879   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
 
1880   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
 
1881   $self->{"employee_id"} *= 1;
 
1883   $main::lxdebug->leave_sub();
 
1886 sub get_employee_data {
 
1887   $main::lxdebug->enter_sub();
 
1891   my $defaults = SL::DB::Default->get;
 
1893   Common::check_params(\%params, qw(prefix));
 
1894   Common::check_params_x(\%params, qw(id));
 
1897     $main::lxdebug->leave_sub();
 
1901   my $myconfig = \%main::myconfig;
 
1902   my $dbh      = $params{dbh} || $self->get_standard_dbh($myconfig);
 
1904   my ($login, $deleted)  = selectrow_query($self, $dbh, qq|SELECT login,deleted FROM employee WHERE id = ?|, conv_i($params{id}));
 
1907     # login already fetched and still the same client (mandant) | same for both cases (delete|!delete)
 
1908     $self->{$params{prefix} . '_login'}   = $login;
 
1909     $self->{$params{prefix} . "_${_}"}    = $defaults->$_ for qw(address businessnumber co_ustid company duns taxnumber);
 
1912       # get employee data from auth.user_config
 
1913       my $user = User->new(login => $login);
 
1914       $self->{$params{prefix} . "_${_}"} = $user->{$_} for qw(email fax name signature tel);
 
1916       # get saved employee data from employee
 
1917       my $employee = SL::DB::Manager::Employee->find_by(id => conv_i($params{id}));
 
1918       $self->{$params{prefix} . "_${_}"} = $employee->{"deleted_$_"} for qw(email fax signature tel);
 
1919       $self->{$params{prefix} . "_name"} = $employee->name;
 
1922   $main::lxdebug->leave_sub();
 
1926   $main::lxdebug->enter_sub();
 
1928   my ($self, $dbh, $id, $key) = @_;
 
1930   $key = "all_contacts" unless ($key);
 
1934     $main::lxdebug->leave_sub();
 
1939     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
 
1940     qq|FROM contacts | .
 
1941     qq|WHERE cp_cv_id = ? | .
 
1942     qq|ORDER BY lower(cp_name)|;
 
1944   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
 
1946   $main::lxdebug->leave_sub();
 
1950   $main::lxdebug->enter_sub();
 
1952   my ($self, $dbh, $key) = @_;
 
1954   my ($all, $old_id, $where, @values);
 
1956   if (ref($key) eq "HASH") {
 
1959     $key = "ALL_PROJECTS";
 
1961     foreach my $p (keys(%{$params})) {
 
1963         $all = $params->{$p};
 
1964       } elsif ($p eq "old_id") {
 
1965         $old_id = $params->{$p};
 
1966       } elsif ($p eq "key") {
 
1967         $key = $params->{$p};
 
1973     $where = "WHERE active ";
 
1975       if (ref($old_id) eq "ARRAY") {
 
1976         my @ids = grep({ $_ } @{$old_id});
 
1978           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
 
1979           push(@values, @ids);
 
1982         $where .= " OR (id = ?) ";
 
1983         push(@values, $old_id);
 
1989     qq|SELECT id, projectnumber, description, active | .
 
1992     qq|ORDER BY lower(projectnumber)|;
 
1994   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
 
1996   $main::lxdebug->leave_sub();
 
2000   $main::lxdebug->enter_sub();
 
2002   my ($self, $dbh, $key) = @_;
 
2004   $key = "all_printers" unless ($key);
 
2006   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
 
2008   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2010   $main::lxdebug->leave_sub();
 
2014   $main::lxdebug->enter_sub();
 
2016   my ($self, $dbh, $params) = @_;
 
2019   $key = $params->{key};
 
2020   $key = "all_charts" unless ($key);
 
2022   my $transdate = quote_db_date($params->{transdate});
 
2025     qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
 
2027     qq|LEFT JOIN taxkeys tk ON | .
 
2028     qq|(tk.id = (SELECT id FROM taxkeys | .
 
2029     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
 
2030     qq|          ORDER BY startdate DESC LIMIT 1)) | .
 
2031     qq|ORDER BY c.accno|;
 
2033   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2035   $main::lxdebug->leave_sub();
 
2039   $main::lxdebug->enter_sub();
 
2041   my ($self, $dbh, $key) = @_;
 
2043   $key = "all_taxzones" unless ($key);
 
2045   $tzfilter = "WHERE obsolete is FALSE" if $key eq 'ALL_ACTIVE_TAXZONES';
 
2047   my $query = qq|SELECT * FROM tax_zones $tzfilter ORDER BY sortkey|;
 
2049   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2051   $main::lxdebug->leave_sub();
 
2054 sub _get_employees {
 
2055   $main::lxdebug->enter_sub();
 
2057   my ($self, $dbh, $params) = @_;
 
2062   if (ref $params eq 'HASH') {
 
2063     $key     = $params->{key};
 
2064     $deleted = $params->{deleted};
 
2070   $key     ||= "all_employees";
 
2071   my $filter = $deleted ? '' : 'WHERE NOT COALESCE(deleted, FALSE)';
 
2072   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee $filter ORDER BY lower(name)|);
 
2074   $main::lxdebug->leave_sub();
 
2077 sub _get_business_types {
 
2078   $main::lxdebug->enter_sub();
 
2080   my ($self, $dbh, $key) = @_;
 
2082   my $options       = ref $key eq 'HASH' ? $key : { key => $key };
 
2083   $options->{key} ||= "all_business_types";
 
2086   if (exists $options->{salesman}) {
 
2087     $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
 
2090   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
 
2092   $main::lxdebug->leave_sub();
 
2095 sub _get_languages {
 
2096   $main::lxdebug->enter_sub();
 
2098   my ($self, $dbh, $key) = @_;
 
2100   $key = "all_languages" unless ($key);
 
2102   my $query = qq|SELECT * FROM language ORDER BY id|;
 
2104   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2106   $main::lxdebug->leave_sub();
 
2109 sub _get_dunning_configs {
 
2110   $main::lxdebug->enter_sub();
 
2112   my ($self, $dbh, $key) = @_;
 
2114   $key = "all_dunning_configs" unless ($key);
 
2116   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
 
2118   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2120   $main::lxdebug->leave_sub();
 
2123 sub _get_currencies {
 
2124 $main::lxdebug->enter_sub();
 
2126   my ($self, $dbh, $key) = @_;
 
2128   $key = "all_currencies" unless ($key);
 
2130   $self->{$key} = [$self->get_all_currencies()];
 
2132   $main::lxdebug->leave_sub();
 
2136 $main::lxdebug->enter_sub();
 
2138   my ($self, $dbh, $key) = @_;
 
2140   $key = "all_payments" unless ($key);
 
2142   my $query = qq|SELECT * FROM payment_terms ORDER BY sortkey|;
 
2144   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2146   $main::lxdebug->leave_sub();
 
2149 sub _get_customers {
 
2150   $main::lxdebug->enter_sub();
 
2152   my ($self, $dbh, $key) = @_;
 
2154   my $options        = ref $key eq 'HASH' ? $key : { key => $key };
 
2155   $options->{key}  ||= "all_customers";
 
2156   my $limit_clause   = $options->{limit} ? "LIMIT $options->{limit}" : '';
 
2159   push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if  $options->{business_is_salesman};
 
2160   push @where, qq|NOT obsolete|                                            if !$options->{with_obsolete};
 
2161   my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : '';
 
2163   my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|;
 
2164   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
 
2166   $main::lxdebug->leave_sub();
 
2170   $main::lxdebug->enter_sub();
 
2172   my ($self, $dbh, $key) = @_;
 
2174   $key = "all_vendors" unless ($key);
 
2176   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
 
2178   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2180   $main::lxdebug->leave_sub();
 
2183 sub _get_departments {
 
2184   $main::lxdebug->enter_sub();
 
2186   my ($self, $dbh, $key) = @_;
 
2188   $key = "all_departments" unless ($key);
 
2190   my $query = qq|SELECT * FROM department ORDER BY description|;
 
2192   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2194   $main::lxdebug->leave_sub();
 
2197 sub _get_warehouses {
 
2198   $main::lxdebug->enter_sub();
 
2200   my ($self, $dbh, $param) = @_;
 
2202   my ($key, $bins_key);
 
2204   if ('' eq ref $param) {
 
2208     $key      = $param->{key};
 
2209     $bins_key = $param->{bins};
 
2212   my $query = qq|SELECT w.* FROM warehouse w
 
2213                  WHERE (NOT w.invalid) AND
 
2214                    ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
 
2215                  ORDER BY w.sortkey|;
 
2217   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2220     $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?
 
2221                 ORDER BY description|;
 
2222     my $sth = prepare_query($self, $dbh, $query);
 
2224     foreach my $warehouse (@{ $self->{$key} }) {
 
2225       do_statement($self, $sth, $query, $warehouse->{id});
 
2226       $warehouse->{$bins_key} = [];
 
2228       while (my $ref = $sth->fetchrow_hashref()) {
 
2229         push @{ $warehouse->{$bins_key} }, $ref;
 
2235   $main::lxdebug->leave_sub();
 
2239   $main::lxdebug->enter_sub();
 
2241   my ($self, $dbh, $table, $key, $sortkey) = @_;
 
2243   my $query  = qq|SELECT * FROM $table|;
 
2244   $query    .= qq| ORDER BY $sortkey| if ($sortkey);
 
2246   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2248   $main::lxdebug->leave_sub();
 
2252   $main::lxdebug->enter_sub();
 
2257   croak "get_lists: shipto is no longer supported" if $params{shipto};
 
2259   my $dbh = $self->get_standard_dbh(\%main::myconfig);
 
2260   my ($sth, $query, $ref);
 
2263   if ($params{contacts}) {
 
2264     $vc = 'customer' if $self->{"vc"} eq "customer";
 
2265     $vc = 'vendor'   if $self->{"vc"} eq "vendor";
 
2266     die "invalid use of get_lists, need 'vc'" unless $vc;
 
2267     $vc_id = $self->{"${vc}_id"};
 
2270   if ($params{"contacts"}) {
 
2271     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
 
2274   if ($params{"projects"} || $params{"all_projects"}) {
 
2275     $self->_get_projects($dbh, $params{"all_projects"} ?
 
2276                          $params{"all_projects"} : $params{"projects"},
 
2277                          $params{"all_projects"} ? 1 : 0);
 
2280   if ($params{"printers"}) {
 
2281     $self->_get_printers($dbh, $params{"printers"});
 
2284   if ($params{"languages"}) {
 
2285     $self->_get_languages($dbh, $params{"languages"});
 
2288   if ($params{"charts"}) {
 
2289     $self->_get_charts($dbh, $params{"charts"});
 
2292   if ($params{"taxzones"}) {
 
2293     $self->_get_taxzones($dbh, $params{"taxzones"});
 
2296   if ($params{"employees"}) {
 
2297     $self->_get_employees($dbh, $params{"employees"});
 
2300   if ($params{"salesmen"}) {
 
2301     $self->_get_employees($dbh, $params{"salesmen"});
 
2304   if ($params{"business_types"}) {
 
2305     $self->_get_business_types($dbh, $params{"business_types"});
 
2308   if ($params{"dunning_configs"}) {
 
2309     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
 
2312   if($params{"currencies"}) {
 
2313     $self->_get_currencies($dbh, $params{"currencies"});
 
2316   if($params{"customers"}) {
 
2317     $self->_get_customers($dbh, $params{"customers"});
 
2320   if($params{"vendors"}) {
 
2321     if (ref $params{"vendors"} eq 'HASH') {
 
2322       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
 
2324       $self->_get_vendors($dbh, $params{"vendors"});
 
2328   if($params{"payments"}) {
 
2329     $self->_get_payments($dbh, $params{"payments"});
 
2332   if($params{"departments"}) {
 
2333     $self->_get_departments($dbh, $params{"departments"});
 
2336   if ($params{price_factors}) {
 
2337     $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
 
2340   if ($params{warehouses}) {
 
2341     $self->_get_warehouses($dbh, $params{warehouses});
 
2344   if ($params{partsgroup}) {
 
2345     $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
 
2348   $main::lxdebug->leave_sub();
 
2351 # this sub gets the id and name from $table
 
2353   $main::lxdebug->enter_sub();
 
2355   my ($self, $myconfig, $table) = @_;
 
2357   # connect to database
 
2358   my $dbh = $self->get_standard_dbh($myconfig);
 
2360   $table = $table eq "customer" ? "customer" : "vendor";
 
2361   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
 
2363   my ($query, @values);
 
2365   if (!$self->{openinvoices}) {
 
2367     if ($self->{customernumber} ne "") {
 
2368       $where = qq|(vc.customernumber ILIKE ?)|;
 
2369       push(@values, like($self->{customernumber}));
 
2371       $where = qq|(vc.name ILIKE ?)|;
 
2372       push(@values, like($self->{$table}));
 
2376       qq~SELECT vc.id, vc.name,
 
2377            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
2379          WHERE $where AND (NOT vc.obsolete)
 
2383       qq~SELECT DISTINCT vc.id, vc.name,
 
2384            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
2386          JOIN $table vc ON (a.${table}_id = vc.id)
 
2387          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
 
2389     push(@values, like($self->{$table}));
 
2392   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
 
2394   $main::lxdebug->leave_sub();
 
2396   return scalar(@{ $self->{name_list} });
 
2401   my ($self, $table, $provided_dbh) = @_;
 
2403   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh;
 
2404   return                                       unless $self->{id};
 
2405   croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
 
2407   my $query       = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
 
2408   my $ref         = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
 
2409   $ref->{mtime} ||= $ref->{itime};
 
2410   $self->{lastmtime} = $ref->{mtime};
 
2414 sub mtime_ischanged {
 
2415   my ($self, $table, $option) = @_;
 
2417   return                                       unless $self->{id};
 
2418   croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
 
2420   my $query       = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
 
2421   my $ref         = selectfirst_hashref_query($self, $self->get_standard_dbh, $query, $self->{id});
 
2422   $ref->{mtime} ||= $ref->{itime};
 
2424   if ($self->{lastmtime} && $self->{lastmtime} ne $ref->{mtime} ) {
 
2425       $self->error(($option eq 'mail') ?
 
2426         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") :
 
2427         t8("The document has been changed by another user. Please reopen it in another window and copy the changes to the new window")
 
2429     $::dispatcher->end_request;
 
2433 # language_payment duplicates some of the functionality of all_vc (language,
 
2434 # printer, payment_terms), and at least in the case of sales invoices both
 
2435 # all_vc and language_payment are called when adding new invoices
 
2436 sub language_payment {
 
2437   $main::lxdebug->enter_sub();
 
2439   my ($self, $myconfig) = @_;
 
2441   my $dbh = $self->get_standard_dbh($myconfig);
 
2443   my $query = qq|SELECT id, description
 
2447   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2450   $query = qq|SELECT printer_description, id
 
2452               ORDER BY printer_description|;
 
2454   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2457   $query = qq|SELECT id, description
 
2459               WHERE ( obsolete IS FALSE OR id = ? )
 
2461   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query, $self->{payment_id} || undef);
 
2463   # get buchungsgruppen
 
2464   $query = qq|SELECT id, description
 
2465               FROM buchungsgruppen|;
 
2467   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
 
2469   $main::lxdebug->leave_sub();
 
2472 # this is only used for reports
 
2473 sub all_departments {
 
2474   $main::lxdebug->enter_sub();
 
2476   my ($self, $myconfig, $table) = @_;
 
2478   my $dbh = $self->get_standard_dbh($myconfig);
 
2480   my $query = qq|SELECT id, description
 
2482                  ORDER BY description|;
 
2483   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2485   delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
 
2487   $main::lxdebug->leave_sub();
 
2491   $main::lxdebug->enter_sub();
 
2493   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
 
2496   if ($table eq "customer") {
 
2505   # get last customers or vendors
 
2506   my ($query, $sth, $ref);
 
2508   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
 
2513     my $transdate = "current_date";
 
2514     if ($self->{transdate}) {
 
2515       $transdate = $dbh->quote($self->{transdate});
 
2518     # now get the account numbers
 
2520       SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk2.tax_id
 
2522         -- find newest entries in taxkeys
 
2524           SELECT chart_id, MAX(startdate) AS startdate
 
2526           WHERE (startdate <= $transdate)
 
2528         ) tk ON (c.id = tk.chart_id)
 
2529         -- and load all of those entries
 
2530         INNER JOIN taxkeys tk2
 
2531            ON (tk.chart_id = tk2.chart_id AND tk.startdate = tk2.startdate)
 
2532        WHERE (c.link LIKE ?)
 
2535     $sth = $dbh->prepare($query);
 
2537     do_statement($self, $sth, $query, like($module));
 
2539     $self->{accounts} = "";
 
2540     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2542       foreach my $key (split(/:/, $ref->{link})) {
 
2543         if ($key =~ /\Q$module\E/) {
 
2545           # cross reference for keys
 
2546           $xkeyref{ $ref->{accno} } = $key;
 
2548           push @{ $self->{"${module}_links"}{$key} },
 
2549             { accno       => $ref->{accno},
 
2550               chart_id    => $ref->{chart_id},
 
2551               description => $ref->{description},
 
2552               taxkey      => $ref->{taxkey_id},
 
2553               tax_id      => $ref->{tax_id} };
 
2555           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2561   # get taxkeys and description
 
2562   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
 
2563   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
 
2565   if (($module eq "AP") || ($module eq "AR")) {
 
2566     # get tax rates and description
 
2567     $query = qq|SELECT * FROM tax|;
 
2568     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
 
2571   my $extra_columns = '';
 
2572   $extra_columns   .= 'a.direct_debit, ' if ($module eq 'AR') || ($module eq 'AP');
 
2577            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid, a.deliverydate,
 
2578            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,
 
2580            a.intnotes, a.department_id, a.amount AS oldinvtotal,
 
2581            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
 
2582            a.globalproject_id, ${extra_columns}
 
2584            d.description AS department,
 
2587          JOIN $table c ON (a.${table}_id = c.id)
 
2588          LEFT JOIN employee e ON (e.id = a.employee_id)
 
2589          LEFT JOIN department d ON (d.id = a.department_id)
 
2591     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
 
2593     foreach my $key (keys %$ref) {
 
2594       $self->{$key} = $ref->{$key};
 
2596     $self->{mtime}   ||= $self->{itime};
 
2597     $self->{lastmtime} = $self->{mtime};
 
2598     my $transdate = "current_date";
 
2599     if ($self->{transdate}) {
 
2600       $transdate = $dbh->quote($self->{transdate});
 
2603     # now get the account numbers
 
2604     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk.tax_id
 
2606                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
 
2608                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
 
2609                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
 
2612     $sth = $dbh->prepare($query);
 
2613     do_statement($self, $sth, $query, like($module));
 
2615     $self->{accounts} = "";
 
2616     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2618       foreach my $key (split(/:/, $ref->{link})) {
 
2619         if ($key =~ /\Q$module\E/) {
 
2621           # cross reference for keys
 
2622           $xkeyref{ $ref->{accno} } = $key;
 
2624           push @{ $self->{"${module}_links"}{$key} },
 
2625             { accno       => $ref->{accno},
 
2626               chart_id    => $ref->{chart_id},
 
2627               description => $ref->{description},
 
2628               taxkey      => $ref->{taxkey_id},
 
2629               tax_id      => $ref->{tax_id} };
 
2631           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2637     # get amounts from individual entries
 
2640            c.accno, c.description,
 
2641            a.acc_trans_id, a.source, a.amount, a.memo, a.transdate, a.gldate, a.cleared, a.project_id, a.taxkey, a.chart_id,
 
2645          LEFT JOIN chart c ON (c.id = a.chart_id)
 
2646          LEFT JOIN project p ON (p.id = a.project_id)
 
2647          LEFT JOIN tax t ON (t.id= a.tax_id)
 
2648          WHERE a.trans_id = ?
 
2649          AND a.fx_transaction = '0'
 
2650          ORDER BY a.acc_trans_id, a.transdate|;
 
2651     $sth = $dbh->prepare($query);
 
2652     do_statement($self, $sth, $query, $self->{id});
 
2654     # get exchangerate for currency
 
2655     $self->{exchangerate} =
 
2656       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2659     # store amounts in {acc_trans}{$key} for multiple accounts
 
2660     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2661       $ref->{exchangerate} =
 
2662         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
 
2663       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
 
2666       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
 
2667         $ref->{amount} *= -1;
 
2669       $ref->{index} = $index;
 
2671       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
 
2678            d.closedto, d.revtrans,
 
2679            (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
 
2680            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2681            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
 
2682            (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
 
2683            (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
 
2685     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2686     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2693             current_date AS transdate, d.closedto, d.revtrans,
 
2694             (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
 
2695             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2696             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
 
2697             (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
 
2698             (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
 
2700     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2701     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2703     if ($self->{"$self->{vc}_id"}) {
 
2705       # only setup currency
 
2706       ($self->{currency}) = $self->{defaultcurrency} if !$self->{currency};
 
2710       $self->lastname_used($dbh, $myconfig, $table, $module);
 
2712       # get exchangerate for currency
 
2713       $self->{exchangerate} =
 
2714         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2720   $main::lxdebug->leave_sub();
 
2724   $main::lxdebug->enter_sub();
 
2726   my ($self, $dbh, $myconfig, $table, $module) = @_;
 
2730   $table         = $table eq "customer" ? "customer" : "vendor";
 
2731   my %column_map = ("a.${table}_id"           => "${table}_id",
 
2732                     "a.department_id"         => "department_id",
 
2733                     "d.description"           => "department",
 
2734                     "ct.name"                 => $table,
 
2735                     "cu.name"                 => "currency",
 
2738   if ($self->{type} =~ /delivery_order/) {
 
2739     $arap  = 'delivery_orders';
 
2740     delete $column_map{"cu.currency"};
 
2742   } elsif ($self->{type} =~ /_order/) {
 
2744     $where = "quotation = '0'";
 
2746   } elsif ($self->{type} =~ /_quotation/) {
 
2748     $where = "quotation = '1'";
 
2750   } elsif ($table eq 'customer') {
 
2758   $where           = "($where) AND" if ($where);
 
2759   my $query        = qq|SELECT MAX(id) FROM $arap
 
2760                         WHERE $where ${table}_id > 0|;
 
2761   my ($trans_id)   = selectrow_query($self, $dbh, $query);
 
2764   my $column_spec  = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
 
2765   $query           = qq|SELECT $column_spec
 
2767                         LEFT JOIN $table     ct ON (a.${table}_id = ct.id)
 
2768                         LEFT JOIN department d  ON (a.department_id = d.id)
 
2769                         LEFT JOIN currencies cu ON (cu.id=ct.currency_id)
 
2771   my $ref          = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
 
2773   map { $self->{$_} = $ref->{$_} } values %column_map;
 
2775   $main::lxdebug->leave_sub();
 
2778 sub get_variable_content_types {
 
2779   my %html_variables  = (
 
2780       longdescription => 'html',
 
2781       partnotes       => 'html',
 
2783       orignotes       => 'html',
 
2788       header_text     => 'html',
 
2789       footer_text     => 'html',
 
2791   return \%html_variables;
 
2795   $main::lxdebug->enter_sub();
 
2798   my $myconfig = shift || \%::myconfig;
 
2799   my ($thisdate, $days) = @_;
 
2801   my $dbh = $self->get_standard_dbh($myconfig);
 
2806     my $dateformat = $myconfig->{dateformat};
 
2807     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
 
2808     $thisdate = $dbh->quote($thisdate);
 
2809     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
 
2811     $query = qq|SELECT current_date AS thisdate|;
 
2814   ($thisdate) = selectrow_query($self, $dbh, $query);
 
2816   $main::lxdebug->leave_sub();
 
2822   $main::lxdebug->enter_sub();
 
2824   my ($self, $flds, $new, $count, $numrows) = @_;
 
2828   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
 
2833   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
 
2835     my $j = $item->{ndx} - 1;
 
2836     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
 
2840   for $i ($count + 1 .. $numrows) {
 
2841     map { delete $self->{"${_}_$i"} } @{$flds};
 
2844   $main::lxdebug->leave_sub();
 
2848   $main::lxdebug->enter_sub();
 
2850   my ($self, $myconfig) = @_;
 
2854   SL::DB->client->with_transaction(sub {
 
2855     my $dbh = SL::DB->client->dbh;
 
2857     my $query = qq|DELETE FROM status
 
2858                    WHERE (formname = ?) AND (trans_id = ?)|;
 
2859     my $sth = prepare_query($self, $dbh, $query);
 
2861     if ($self->{formname} =~ /(check|receipt)/) {
 
2862       for $i (1 .. $self->{rowcount}) {
 
2863         do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
 
2866       do_statement($self, $sth, $query, $self->{formname}, $self->{id});
 
2870     my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
2871     my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
2873     my %queued = split / /, $self->{queued};
 
2876     if ($self->{formname} =~ /(check|receipt)/) {
 
2878       # this is a check or receipt, add one entry for each lineitem
 
2879       my ($accno) = split /--/, $self->{account};
 
2880       $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
 
2881                   VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
 
2882       @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
 
2883       $sth = prepare_query($self, $dbh, $query);
 
2885       for $i (1 .. $self->{rowcount}) {
 
2886         if ($self->{"checked_$i"}) {
 
2887           do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
 
2893       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
2894                   VALUES (?, ?, ?, ?, ?)|;
 
2895       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
 
2896                $queued{$self->{formname}}, $self->{formname});
 
2899   }) or do { die SL::DB->client->error };
 
2901   $main::lxdebug->leave_sub();
 
2905   $main::lxdebug->enter_sub();
 
2907   my ($self, $dbh) = @_;
 
2909   my ($query, $printed, $emailed);
 
2911   my $formnames  = $self->{printed};
 
2912   my $emailforms = $self->{emailed};
 
2914   $query = qq|DELETE FROM status
 
2915                  WHERE (formname = ?) AND (trans_id = ?)|;
 
2916   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
 
2918   # this only applies to the forms
 
2919   # checks and receipts are posted when printed or queued
 
2921   if ($self->{queued}) {
 
2922     my %queued = split / /, $self->{queued};
 
2924     foreach my $formname (keys %queued) {
 
2925       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
2926       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
2928       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
2929                   VALUES (?, ?, ?, ?, ?)|;
 
2930       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
 
2932       $formnames  =~ s/\Q$self->{formname}\E//;
 
2933       $emailforms =~ s/\Q$self->{formname}\E//;
 
2938   # save printed, emailed info
 
2939   $formnames  =~ s/^ +//g;
 
2940   $emailforms =~ s/^ +//g;
 
2943   map { $status{$_}{printed} = 1 } split / +/, $formnames;
 
2944   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
 
2946   foreach my $formname (keys %status) {
 
2947     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
2948     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
2950     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
 
2951                 VALUES (?, ?, ?, ?)|;
 
2952     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
 
2955   $main::lxdebug->leave_sub();
 
2959 # $main::locale->text('SAVED')
 
2960 # $main::locale->text('SCREENED')
 
2961 # $main::locale->text('DELETED')
 
2962 # $main::locale->text('ADDED')
 
2963 # $main::locale->text('PAYMENT POSTED')
 
2964 # $main::locale->text('POSTED')
 
2965 # $main::locale->text('POSTED AS NEW')
 
2966 # $main::locale->text('ELSE')
 
2967 # $main::locale->text('SAVED FOR DUNNING')
 
2968 # $main::locale->text('DUNNING STARTED')
 
2969 # $main::locale->text('PREVIEWED')
 
2970 # $main::locale->text('PRINTED')
 
2971 # $main::locale->text('MAILED')
 
2972 # $main::locale->text('SCREENED')
 
2973 # $main::locale->text('CANCELED')
 
2974 # $main::locale->text('IMPORT')
 
2975 # $main::locale->text('UNDO TRANSFER')
 
2976 # $main::locale->text('UNIMPORT')
 
2977 # $main::locale->text('invoice')
 
2978 # $main::locale->text('proforma')
 
2979 # $main::locale->text('sales_order')
 
2980 # $main::locale->text('pick_list')
 
2981 # $main::locale->text('purchase_order')
 
2982 # $main::locale->text('bin_list')
 
2983 # $main::locale->text('sales_quotation')
 
2984 # $main::locale->text('request_quotation')
 
2987   $main::lxdebug->enter_sub();
 
2990   my $dbh  = shift || SL::DB->client->dbh;
 
2991   SL::DB->client->with_transaction(sub {
 
2993     if(!exists $self->{employee_id}) {
 
2994       &get_employee($self, $dbh);
 
2998      qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
 
2999      qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
 
3000     my @values = (conv_i($self->{id}), $self->{login},
 
3001                   $self->{addition}, $self->{what_done}, "$self->{snumbers}");
 
3002     do_query($self, $dbh, $query, @values);
 
3004   }) or do { die SL::DB->client->error };
 
3006   $main::lxdebug->leave_sub();
 
3010   $main::lxdebug->enter_sub();
 
3012   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
 
3013   my ($orderBy, $desc) = split(/\-\-/, $order);
 
3014   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
 
3017   if ($trans_id ne "") {
 
3019       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 | .
 
3020       qq|FROM history_erp h | .
 
3021       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
 
3022       qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
 
3025     my $sth = $dbh->prepare($query) || $self->dberror($query);
 
3027     $sth->execute() || $self->dberror("$query");
 
3029     while(my $hash_ref = $sth->fetchrow_hashref()) {
 
3030       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
 
3031       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
 
3032       my ( $what, $number ) = split /_/, $hash_ref->{snumbers};
 
3033       $hash_ref->{snumbers} = $number;
 
3034       $hash_ref->{haslink}  = 'controller.pl?action=EmailJournal/show&id='.$number if $what eq 'emailjournal';
 
3035       $hash_ref->{snumbers} = $main::locale->text("E-Mail").' '.$number if $what eq 'emailjournal';
 
3036       $tempArray[$i++] = $hash_ref;
 
3038     $main::lxdebug->leave_sub() and return \@tempArray
 
3039       if ($i > 0 && $tempArray[0] ne "");
 
3041   $main::lxdebug->leave_sub();
 
3045 sub get_partsgroup {
 
3046   $main::lxdebug->enter_sub();
 
3048   my ($self, $myconfig, $p) = @_;
 
3049   my $target = $p->{target} || 'all_partsgroup';
 
3051   my $dbh = $self->get_standard_dbh($myconfig);
 
3053   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
 
3055                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
 
3058   if ($p->{searchitems} eq 'part') {
 
3059     $query .= qq|WHERE p.part_type = 'part'|;
 
3061   if ($p->{searchitems} eq 'service') {
 
3062     $query .= qq|WHERE p.part_type = 'service'|;
 
3064   if ($p->{searchitems} eq 'assembly') {
 
3065     $query .= qq|WHERE p.part_type = 'assembly'|;
 
3068   $query .= qq|ORDER BY partsgroup|;
 
3071     $query = qq|SELECT id, partsgroup FROM partsgroup
 
3072                 ORDER BY partsgroup|;
 
3075   if ($p->{language_code}) {
 
3076     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
 
3077                   t.description AS translation
 
3079                 JOIN parts p ON (p.partsgroup_id = pg.id)
 
3080                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
 
3081                 ORDER BY translation|;
 
3082     @values = ($p->{language_code});
 
3085   $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
 
3087   $main::lxdebug->leave_sub();
 
3090 sub get_pricegroup {
 
3091   $main::lxdebug->enter_sub();
 
3093   my ($self, $myconfig, $p) = @_;
 
3095   my $dbh = $self->get_standard_dbh($myconfig);
 
3097   my $query = qq|SELECT p.id, p.pricegroup
 
3100   $query .= qq| ORDER BY pricegroup|;
 
3103     $query = qq|SELECT id, pricegroup FROM pricegroup
 
3104                 ORDER BY pricegroup|;
 
3107   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
 
3109   $main::lxdebug->leave_sub();
 
3113 # usage $form->all_years($myconfig, [$dbh])
 
3114 # return list of all years where bookings found
 
3117   $main::lxdebug->enter_sub();
 
3119   my ($self, $myconfig, $dbh) = @_;
 
3121   $dbh ||= $self->get_standard_dbh($myconfig);
 
3124   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
 
3125                    (SELECT MAX(transdate) FROM acc_trans)|;
 
3126   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
 
3128   if ($myconfig->{dateformat} =~ /^yy/) {
 
3129     ($startdate) = split /\W/, $startdate;
 
3130     ($enddate) = split /\W/, $enddate;
 
3132     (@_) = split /\W/, $startdate;
 
3134     (@_) = split /\W/, $enddate;
 
3139   $startdate = substr($startdate,0,4);
 
3140   $enddate = substr($enddate,0,4);
 
3142   while ($enddate >= $startdate) {
 
3143     push @all_years, $enddate--;
 
3148   $main::lxdebug->leave_sub();
 
3152   $main::lxdebug->enter_sub();
 
3156   map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
 
3158   $main::lxdebug->leave_sub();
 
3162   $main::lxdebug->enter_sub();
 
3167   map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
 
3169   $main::lxdebug->leave_sub();
 
3172 sub prepare_for_printing {
 
3175   my $defaults         = SL::DB::Default->get;
 
3177   $self->{templates} ||= $defaults->templates;
 
3178   $self->{formname}  ||= $self->{type};
 
3179   $self->{media}     ||= 'email';
 
3181   die "'media' other than 'email', 'file', 'printer' is not supported yet" unless $self->{media} =~ m/^(?:email|file|printer)$/;
 
3183   # Several fields that used to reside in %::myconfig (stored in
 
3184   # auth.user_config) are now stored in defaults. Copy them over for
 
3186   $self->{$_} = $defaults->$_ for qw(company address taxnumber co_ustid duns sepa_creditor_id);
 
3188   $self->{"myconfig_${_}"} = $::myconfig{$_} for grep { $_ ne 'dbpasswd' } keys %::myconfig;
 
3190   if (!$self->{employee_id}) {
 
3191     $self->{"employee_${_}"} = $::myconfig{$_} for qw(email tel fax name signature);
 
3192     $self->{"employee_${_}"} = $defaults->$_   for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
 
3195   my $language = $self->{language} ? '_' . $self->{language} : '';
 
3197   my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
 
3198   if ($self->{language_id}) {
 
3199     ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) = AM->get_language_details(\%::myconfig, $self, $self->{language_id});
 
3202   $output_dateformat   ||= $::myconfig{dateformat};
 
3203   $output_numberformat ||= $::myconfig{numberformat};
 
3204   $output_longdates    //= 1;
 
3206   $self->{myconfig_output_dateformat}   = $output_dateformat   // $::myconfig{dateformat};
 
3207   $self->{myconfig_output_longdates}    = $output_longdates    // 1;
 
3208   $self->{myconfig_output_numberformat} = $output_numberformat // $::myconfig{numberformat};
 
3210   # Retrieve accounts for tax calculation.
 
3211   IC->retrieve_accounts(\%::myconfig, $self, map { $_ => $self->{"id_$_"} } 1 .. $self->{rowcount});
 
3213   if ($self->{type} =~ /_delivery_order$/) {
 
3214     DO->order_details(\%::myconfig, $self);
 
3215   } elsif ($self->{type} =~ /sales_order|sales_quotation|request_quotation|purchase_order/) {
 
3216     OE->order_details(\%::myconfig, $self);
 
3218     IS->invoice_details(\%::myconfig, $self, $::locale);
 
3221   # Chose extension & set source file name
 
3222   my $extension = 'html';
 
3223   if ($self->{format} eq 'postscript') {
 
3224     $self->{postscript}   = 1;
 
3226   } elsif ($self->{"format"} =~ /pdf/) {
 
3228     $extension            = $self->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
 
3229   } elsif ($self->{"format"} =~ /opendocument/) {
 
3230     $self->{opendocument} = 1;
 
3232   } elsif ($self->{"format"} =~ /excel/) {
 
3237   my $printer_code    = $self->{printer_code} ? '_' . $self->{printer_code} : '';
 
3238   my $email_extension = $self->{media} eq 'email' && -f ($defaults->templates . "/$self->{formname}_email${language}.${extension}") ? '_email' : '';
 
3239   $self->{IN}         = "$self->{formname}${email_extension}${language}${printer_code}.${extension}";
 
3242   $self->format_dates($output_dateformat, $output_longdates,
 
3243                       qw(invdate orddate quodate pldate duedate reqdate transdate tax_point shippingdate deliverydate validitydate paymentdate datepaid
 
3244                          transdate_oe deliverydate_oe employee_startdate employee_enddate),
 
3245                       grep({ /^(?:datepaid|transdate_oe|reqdate|deliverydate|deliverydate_oe|transdate)_\d+$/ } keys(%{$self})));
 
3247   $self->reformat_numbers($output_numberformat, 2,
 
3248                           qw(invtotal ordtotal quototal subtotal linetotal listprice sellprice netprice discount tax taxbase total paid),
 
3249                           grep({ /^(?:linetotal|listprice|sellprice|netprice|taxbase|discount|paid|subtotal|total|tax)_\d+$/ } keys(%{$self})));
 
3251   $self->reformat_numbers($output_numberformat, undef, qw(qty price_factor), grep({ /^qty_\d+$/} keys(%{$self})));
 
3253   my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
 
3255   if (scalar @{ $cvar_date_fields }) {
 
3256     $self->format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
 
3259   while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
 
3260     $self->reformat_numbers($output_numberformat, $precision, @{ $field_list });
 
3264   if (($self->{language} // '') ne '') {
 
3265     my $template_arrays = $self->{TEMPLATE_ARRAYS} || $self;
 
3266     for my $idx (0..scalar(@{ $template_arrays->{unit} }) - 1) {
 
3267       $template_arrays->{unit}->[$idx] = AM->translate_units($self, $self->{language}, $template_arrays->{unit}->[$idx], $template_arrays->{qty}->[$idx])
 
3271   $self->{template_meta} = {
 
3272     formname  => $self->{formname},
 
3273     language  => SL::DB::Manager::Language->find_by_or_create(id => $self->{language_id} || undef),
 
3274     format    => $self->{format},
 
3275     media     => $self->{media},
 
3276     extension => $extension,
 
3277     printer   => SL::DB::Manager::Printer->find_by_or_create(id => $self->{printer_id} || undef),
 
3278     today     => DateTime->today,
 
3284 sub calculate_arap {
 
3285   my ($self,$buysell,$taxincluded,$exchangerate,$roundplaces) = @_;
 
3287   # this function is used to calculate netamount, total_tax and amount for AP and
 
3288   # AR transactions (Kreditoren-/Debitorenbuchungen) by going over all lines
 
3290   # Thus it needs a fully prepared $form to work on.
 
3291   # calculate_arap assumes $form->{amount_$i} entries still need to be parsed
 
3293   # The calculated total values are all rounded (default is to 2 places) and
 
3294   # returned as parameters rather than directly modifying form.  The aim is to
 
3295   # make the calculation of AP and AR behave identically.  There is a test-case
 
3296   # for this function in t/form/arap.t
 
3298   # While calculating the totals $form->{amount_$i} and $form->{tax_$i} are
 
3299   # modified and formatted and receive the correct sign for writing straight to
 
3300   # acc_trans, depending on whether they are ar or ap.
 
3303   die "taxincluded needed in Form->calculate_arap" unless defined $taxincluded;
 
3304   die "exchangerate needed in Form->calculate_arap" unless defined $exchangerate;
 
3305   die 'illegal buysell parameter, has to be \"buy\" or \"sell\" in Form->calculate_arap\n' unless $buysell =~ /^(buy|sell)$/;
 
3306   $roundplaces = 2 unless $roundplaces;
 
3308   my $sign = 1;  # adjust final results for writing amount to acc_trans
 
3309   $sign = -1 if $buysell eq 'buy';
 
3311   my ($netamount,$total_tax,$amount);
 
3315   # parse and round amounts, setting correct sign for writing to acc_trans
 
3316   for my $i (1 .. $self->{rowcount}) {
 
3317     $self->{"amount_$i"} = $self->round_amount($self->parse_amount(\%::myconfig, $self->{"amount_$i"}) * $exchangerate * $sign, $roundplaces);
 
3319     $amount += $self->{"amount_$i"} * $sign;
 
3322   for my $i (1 .. $self->{rowcount}) {
 
3323     next unless $self->{"amount_$i"};
 
3324     ($self->{"tax_id_$i"}) = split /--/, $self->{"taxchart_$i"};
 
3325     my $tax_id = $self->{"tax_id_$i"};
 
3327     my $selected_tax = SL::DB::Manager::Tax->find_by(id => "$tax_id");
 
3329     if ( $selected_tax ) {
 
3331       if ( $buysell eq 'sell' ) {
 
3332         $self->{AR_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
 
3334         $self->{AP_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
 
3337       $self->{"taxkey_$i"} = $selected_tax->taxkey;
 
3338       $self->{"taxrate_$i"} = $selected_tax->rate;
 
3341     ($self->{"amount_$i"}, $self->{"tax_$i"}) = $self->calculate_tax($self->{"amount_$i"},$self->{"taxrate_$i"},$taxincluded,$roundplaces);
 
3343     $netamount  += $self->{"amount_$i"};
 
3344     $total_tax  += $self->{"tax_$i"};
 
3347   $amount = $netamount + $total_tax;
 
3349   # due to $sign amount_$i und tax_$i already have the right sign for acc_trans
 
3350   # but reverse sign of totals for writing amounts to ar
 
3351   if ( $buysell eq 'buy' ) {
 
3357   return($netamount,$total_tax,$amount);
 
3361   my ($self, $dateformat, $longformat, @indices) = @_;
 
3363   $dateformat ||= $::myconfig{dateformat};
 
3365   foreach my $idx (@indices) {
 
3366     if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
 
3367       for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
 
3368         $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $dateformat, $longformat);
 
3372     next unless defined $self->{$idx};
 
3374     if (!ref($self->{$idx})) {
 
3375       $self->{$idx} = $::locale->reformat_date(\%::myconfig, $self->{$idx}, $dateformat, $longformat);
 
3377     } elsif (ref($self->{$idx}) eq "ARRAY") {
 
3378       for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
 
3379         $self->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{$idx}->[$i], $dateformat, $longformat);
 
3385 sub reformat_numbers {
 
3386   my ($self, $numberformat, $places, @indices) = @_;
 
3388   return if !$numberformat || ($numberformat eq $::myconfig{numberformat});
 
3390   foreach my $idx (@indices) {
 
3391     if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
 
3392       for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
 
3393         $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i]);
 
3397     next unless defined $self->{$idx};
 
3399     if (!ref($self->{$idx})) {
 
3400       $self->{$idx} = $self->parse_amount(\%::myconfig, $self->{$idx});
 
3402     } elsif (ref($self->{$idx}) eq "ARRAY") {
 
3403       for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
 
3404         $self->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{$idx}->[$i]);
 
3409   my $saved_numberformat    = $::myconfig{numberformat};
 
3410   $::myconfig{numberformat} = $numberformat;
 
3412   foreach my $idx (@indices) {
 
3413     if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
 
3414       for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
 
3415         $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $places);
 
3419     next unless defined $self->{$idx};
 
3421     if (!ref($self->{$idx})) {
 
3422       $self->{$idx} = $self->format_amount(\%::myconfig, $self->{$idx}, $places);
 
3424     } elsif (ref($self->{$idx}) eq "ARRAY") {
 
3425       for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
 
3426         $self->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{$idx}->[$i], $places);
 
3431   $::myconfig{numberformat} = $saved_numberformat;
 
3434 sub create_email_signature {
 
3436   my $client_signature = $::instance_conf->get_signature;
 
3437   my $user_signature   = $::myconfig{signature};
 
3440   if ( $client_signature or $user_signature ) {
 
3441     $signature  = "\n\n-- \n";
 
3442     $signature .= $user_signature   . "\n" if $user_signature;
 
3443     $signature .= $client_signature . "\n" if $client_signature;
 
3450   # this function calculates the net amount and tax for the lines in ar, ap and
 
3451   # gl and is used for update as well as post. When used with update the return
 
3452   # value of amount isn't needed
 
3454   # calculate_tax should always work with positive values, or rather as the user inputs them
 
3455   # calculate_tax uses db/perl numberformat, i.e. parsed numbers
 
3456   # convert to negative numbers (when necessary) only when writing to acc_trans
 
3457   # the amount from $form for ap/ar/gl is currently always rounded to 2 decimals before it reaches here
 
3458   # for post_transaction amount already contains exchangerate and correct sign and is rounded
 
3459   # calculate_tax doesn't (need to) know anything about exchangerate
 
3461   my ($self,$amount,$taxrate,$taxincluded,$roundplaces) = @_;
 
3469     # calculate tax (unrounded), subtract from amount, round amount and round tax
 
3470     $tax       = $amount - ($amount / ($taxrate + 1)); # equivalent to: taxrate * amount / (taxrate + 1)
 
3471     $amount    = $self->round_amount($amount - $tax, $roundplaces);
 
3472     $tax       = $self->round_amount($tax, $roundplaces);
 
3474     $tax       = $amount * $taxrate;
 
3475     $tax       = $self->round_amount($tax, $roundplaces);
 
3478   $tax = 0 unless $tax;
 
3480   return ($amount,$tax);
 
3489 SL::Form.pm - main data object.
 
3493 This is the main data object of kivitendo.
 
3494 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
 
3495 Points of interest for a beginner are:
 
3497  - $form->error            - renders a generic error in html. accepts an error message
 
3498  - $form->get_standard_dbh - returns a database connection for the
 
3500 =head1 SPECIAL FUNCTIONS
 
3502 =head2 C<redirect_header> $url
 
3504 Generates a HTTP redirection header for the new C<$url>. Constructs an
 
3505 absolute URL including scheme, host name and port. If C<$url> is a
 
3506 relative URL then it is considered relative to kivitendo base URL.
 
3508 This function C<die>s if headers have already been created with
 
3509 C<$::form-E<gt>header>.
 
3513   print $::form->redirect_header('oe.pl?action=edit&id=1234');
 
3514   print $::form->redirect_header('http://www.lx-office.org/');
 
3518 Generates a general purpose http/html header and includes most of the scripts
 
3519 and stylesheets needed. Stylesheets can be added with L<use_stylesheet>.
 
3521 Only one header will be generated. If the method was already called in this
 
3522 request it will not output anything and return undef. Also if no
 
3523 HTTP_USER_AGENT is found, no header is generated.
 
3525 Although header does not accept parameters itself, it will honor special
 
3526 hashkeys of its Form instance:
 
3534 If one of these is set, a http-equiv refresh is generated. Missing parameters
 
3535 default to 3 seconds and the refering url.
 
3539 Either a scalar or an array ref. Will be inlined into the header. Add
 
3540 stylesheets with the L<use_stylesheet> function.
 
3544 If true, a css snippet will be generated that sets the page in landscape mode.
 
3548 Used to override the default favicon.
 
3552 A html page title will be generated from this
 
3554 =item mtime_ischanged
 
3556 Tries to avoid concurrent write operations to records by checking the database mtime with a fetched one.
 
3558 Can be used / called with any table, that has itime and mtime attributes.
 
3559 Valid C<table> names are: oe, ar, ap, delivery_orders, parts.
 
3560 Can be called wit C<option> mail to generate a different error message.
 
3562 Returns undef if no save operation has been done yet ($self->{id} not present).
 
3563 Returns undef if no concurrent write process is detected otherwise a error message.