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., 675 Mass Ave, Cambridge, MA 02139, USA.
 
  31 #======================================================================
 
  32 # Utilities for parsing forms
 
  33 # and supporting routines for linking account numbers
 
  34 # used in AR, AP and IS, IR modules
 
  36 #======================================================================
 
  68 use List::Util qw(first max min sum);
 
  69 use List::MoreUtils qw(all any apply);
 
  76   disconnect_standard_dbh();
 
  79 sub disconnect_standard_dbh {
 
  80   return unless $standard_dbh;
 
  81   $standard_dbh->disconnect();
 
  86   $main::lxdebug->enter_sub(2);
 
  92   my @tokens = split /((?:\[\+?\])?(?:\.|$))/, $key;
 
  97      $curr = \ $self->{ shift @tokens };
 
 101     my $sep = shift @tokens;
 
 102     my $key = shift @tokens;
 
 104     $curr = \ $$curr->[++$#$$curr], next if $sep eq '[]';
 
 105     $curr = \ $$curr->[max 0, $#$$curr]  if $sep eq '[].';
 
 106     $curr = \ $$curr->[++$#$$curr]       if $sep eq '[+].';
 
 107     $curr = \ $$curr->{$key}
 
 112   $main::lxdebug->leave_sub(2);
 
 118   $main::lxdebug->enter_sub(2);
 
 123   my @pairs = split(/&/, $input);
 
 126     my ($key, $value) = split(/=/, $_, 2);
 
 127     $self->_store_value($self->unescape($key), $self->unescape($value)) if ($key);
 
 130   $main::lxdebug->leave_sub(2);
 
 133 sub _request_to_hash {
 
 134   $main::lxdebug->enter_sub(2);
 
 140   if (!$ENV{'CONTENT_TYPE'}
 
 141       || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
 
 143     $self->_input_to_hash($input);
 
 145     $main::lxdebug->leave_sub(2);
 
 149   my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr, $previous);
 
 151   my $boundary = '--' . $1;
 
 153   foreach my $line (split m/\n/, $input) {
 
 154     last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
 
 156     if (($line eq $boundary) || ($line eq "$boundary\r")) {
 
 157       ${ $previous } =~ s|\r?\n$|| if $previous;
 
 163       $content_type   = "text/plain";
 
 170     next unless $boundary_found;
 
 172     if (!$headers_done) {
 
 173       $line =~ s/[\r\n]*$//;
 
 180       if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
 
 181         if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
 
 183           substr $line, $-[0], $+[0] - $-[0], "";
 
 186         if ($line =~ m|name\s*=\s*"(.*?)"|i) {
 
 188           substr $line, $-[0], $+[0] - $-[0], "";
 
 191         $previous         = _store_value($uploads, $name, '') if ($name);
 
 192         $self->{FILENAME} = $filename if ($filename);
 
 197       if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
 
 204     next unless $previous;
 
 206     ${ $previous } .= "${line}\n";
 
 209   ${ $previous } =~ s|\r?\n$|| if $previous;
 
 211   $main::lxdebug->leave_sub(2);
 
 216 sub _recode_recursively {
 
 217   $main::lxdebug->enter_sub();
 
 218   my ($iconv, $param) = @_;
 
 220   if (any { ref $param eq $_ } qw(Form HASH)) {
 
 221     foreach my $key (keys %{ $param }) {
 
 222       if (!ref $param->{$key}) {
 
 223         # Workaround for a bug: converting $param->{$key} directly
 
 224         # leads to 'undef'. I don't know why. Converting a copy works,
 
 226         $param->{$key} = $iconv->convert("" . $param->{$key});
 
 228         _recode_recursively($iconv, $param->{$key});
 
 232   } elsif (ref $param eq 'ARRAY') {
 
 233     foreach my $idx (0 .. scalar(@{ $param }) - 1) {
 
 234       if (!ref $param->[$idx]) {
 
 235         # Workaround for a bug: converting $param->[$idx] directly
 
 236         # leads to 'undef'. I don't know why. Converting a copy works,
 
 238         $param->[$idx] = $iconv->convert("" . $param->[$idx]);
 
 240         _recode_recursively($iconv, $param->[$idx]);
 
 244   $main::lxdebug->leave_sub();
 
 248   $main::lxdebug->enter_sub();
 
 255   if ($LXDebug::watch_form) {
 
 256     require SL::Watchdog;
 
 257     tie %{ $self }, 'SL::Watchdog';
 
 262   $main::lxdebug->leave_sub();
 
 268   $main::lxdebug->enter_sub();
 
 272   $self->_input_to_hash($ENV{QUERY_STRING}) if $ENV{QUERY_STRING};
 
 273   $self->_input_to_hash($ARGV[0])           if @ARGV && $ARGV[0];
 
 276   if ($ENV{CONTENT_LENGTH}) {
 
 278     read STDIN, $content, $ENV{CONTENT_LENGTH};
 
 279     $uploads = $self->_request_to_hash($content);
 
 282   if ($self->{RESTORE_FORM_FROM_SESSION_ID}) {
 
 284     $::auth->restore_form_from_session(delete $self->{RESTORE_FORM_FROM_SESSION_ID}, form => \%temp_form);
 
 285     $self->_input_to_hash(join '&', map { $self->escape($_) . '=' . $self->escape($temp_form{$_}) } keys %temp_form);
 
 288   my $db_charset   = $::lx_office_conf{system}->{dbcharset};
 
 289   $db_charset    ||= Common::DEFAULT_CHARSET;
 
 291   my $encoding     = $self->{INPUT_ENCODING} || $db_charset;
 
 292   delete $self->{INPUT_ENCODING};
 
 294   _recode_recursively(SL::Iconv->new($encoding, $db_charset), $self);
 
 296   map { $self->{$_} = $uploads->{$_} } keys %{ $uploads } if $uploads;
 
 298   #$self->{version} =  "2.6.1";                 # Old hardcoded but secure style
 
 299   open VERSION_FILE, "VERSION";                 # New but flexible code reads version from VERSION-file
 
 300   $self->{version} =  <VERSION_FILE>;
 
 302   $self->{version}  =~ s/[^0-9A-Za-z\.\_\-]//g; # only allow numbers, letters, points, underscores and dashes. Prevents injecting of malicious code.
 
 304   $main::lxdebug->leave_sub();
 
 309 sub _flatten_variables_rec {
 
 310   $main::lxdebug->enter_sub(2);
 
 319   if ('' eq ref $curr->{$key}) {
 
 320     @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
 
 322   } elsif ('HASH' eq ref $curr->{$key}) {
 
 323     foreach my $hash_key (sort keys %{ $curr->{$key} }) {
 
 324       push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
 
 328     foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
 
 329       my $first_array_entry = 1;
 
 331       foreach my $hash_key (sort keys %{ $curr->{$key}->[$idx] }) {
 
 332         push @result, $self->_flatten_variables_rec($curr->{$key}->[$idx], $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
 
 333         $first_array_entry = 0;
 
 338   $main::lxdebug->leave_sub(2);
 
 343 sub flatten_variables {
 
 344   $main::lxdebug->enter_sub(2);
 
 352     push @variables, $self->_flatten_variables_rec($self, '', $_);
 
 355   $main::lxdebug->leave_sub(2);
 
 360 sub flatten_standard_variables {
 
 361   $main::lxdebug->enter_sub(2);
 
 364   my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar version), @_);
 
 368   foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
 
 369     push @variables, $self->_flatten_variables_rec($self, '', $_);
 
 372   $main::lxdebug->leave_sub(2);
 
 378   $main::lxdebug->enter_sub();
 
 384   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
 
 386   $main::lxdebug->leave_sub();
 
 390   $main::lxdebug->enter_sub(2);
 
 393   my $password      = $self->{password};
 
 395   $self->{password} = 'X' x 8;
 
 397   local $Data::Dumper::Sortkeys = 1;
 
 398   my $output                    = Dumper($self);
 
 400   $self->{password} = $password;
 
 402   $main::lxdebug->leave_sub(2);
 
 408   $main::lxdebug->enter_sub(2);
 
 410   my ($self, $str) = @_;
 
 412   $str =  Encode::encode('utf-8-strict', $str) if $::locale->is_utf8;
 
 413   $str =~ s/([^a-zA-Z0-9_.:-])/sprintf("%%%02x", ord($1))/ge;
 
 415   $main::lxdebug->leave_sub(2);
 
 421   $main::lxdebug->enter_sub(2);
 
 423   my ($self, $str) = @_;
 
 428   $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
 
 429   $str =  Encode::decode('utf-8-strict', $str) if $::locale->is_utf8;
 
 431   $main::lxdebug->leave_sub(2);
 
 437   $main::lxdebug->enter_sub();
 
 438   my ($self, $str) = @_;
 
 440   if ($str && !ref($str)) {
 
 441     $str =~ s/\"/"/g;
 
 444   $main::lxdebug->leave_sub();
 
 450   $main::lxdebug->enter_sub();
 
 451   my ($self, $str) = @_;
 
 453   if ($str && !ref($str)) {
 
 454     $str =~ s/"/\"/g;
 
 457   $main::lxdebug->leave_sub();
 
 463   $main::lxdebug->enter_sub();
 
 467     map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
 
 469     for (sort keys %$self) {
 
 470       next if (($_ eq "header") || (ref($self->{$_}) ne ""));
 
 471       print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
 
 474   $main::lxdebug->leave_sub();
 
 478   my ($self, $code) = @_;
 
 479   local $self->{__ERROR_HANDLER} = sub { die SL::X::FormError->new($_[0]) };
 
 484   $main::lxdebug->enter_sub();
 
 486   $main::lxdebug->show_backtrace();
 
 488   my ($self, $msg) = @_;
 
 490   if ($self->{__ERROR_HANDLER}) {
 
 491     $self->{__ERROR_HANDLER}->($msg);
 
 493   } elsif ($ENV{HTTP_USER_AGENT}) {
 
 495     $self->show_generic_error($msg);
 
 498     print STDERR "Error: $msg\n";
 
 502   $main::lxdebug->leave_sub();
 
 506   $main::lxdebug->enter_sub();
 
 508   my ($self, $msg) = @_;
 
 510   if ($ENV{HTTP_USER_AGENT}) {
 
 513     if (!$self->{header}) {
 
 519     <p class="message_ok"><b>$msg</b></p>
 
 521     <script type="text/javascript">
 
 523     // If JavaScript is enabled, the whole thing will be reloaded.
 
 524     // The reason is: When one changes his menu setup (HTML / XUL / CSS ...)
 
 525     // it now loads the correct code into the browser instead of do nothing.
 
 526     setTimeout("top.frames.location.href='login.pl'",500);
 
 535     if ($self->{info_function}) {
 
 536       &{ $self->{info_function} }($msg);
 
 542   $main::lxdebug->leave_sub();
 
 545 # calculates the number of rows in a textarea based on the content and column number
 
 546 # can be capped with maxrows
 
 548   $main::lxdebug->enter_sub();
 
 549   my ($self, $str, $cols, $maxrows, $minrows) = @_;
 
 553   my $rows   = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
 
 556   $main::lxdebug->leave_sub();
 
 558   return max(min($rows, $maxrows), $minrows);
 
 562   $main::lxdebug->enter_sub();
 
 564   my ($self, $msg) = @_;
 
 566   $self->error("$msg\n" . $DBI::errstr);
 
 568   $main::lxdebug->leave_sub();
 
 572   $main::lxdebug->enter_sub();
 
 574   my ($self, $name, $msg) = @_;
 
 577   foreach my $part (split m/\./, $name) {
 
 578     if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
 
 581     $curr = $curr->{$part};
 
 584   $main::lxdebug->leave_sub();
 
 587 sub _get_request_uri {
 
 590   return URI->new($ENV{HTTP_REFERER})->canonical() if $ENV{HTTP_X_FORWARDED_FOR};
 
 592   my $scheme =  $ENV{HTTPS} && (lc $ENV{HTTPS} eq 'on') ? 'https' : 'http';
 
 593   my $port   =  $ENV{SERVER_PORT} || '';
 
 594   $port      =  undef if (($scheme eq 'http' ) && ($port == 80))
 
 595                       || (($scheme eq 'https') && ($port == 443));
 
 597   my $uri    =  URI->new("${scheme}://");
 
 598   $uri->scheme($scheme);
 
 600   $uri->host($ENV{HTTP_HOST} || $ENV{SERVER_ADDR});
 
 601   $uri->path_query($ENV{REQUEST_URI});
 
 607 sub _add_to_request_uri {
 
 610   my $relative_new_path = shift;
 
 611   my $request_uri       = shift || $self->_get_request_uri;
 
 612   my $relative_new_uri  = URI->new($relative_new_path);
 
 613   my @request_segments  = $request_uri->path_segments;
 
 615   my $new_uri           = $request_uri->clone;
 
 616   $new_uri->path_segments(@request_segments[0..scalar(@request_segments) - 2], $relative_new_uri->path_segments);
 
 621 sub create_http_response {
 
 622   $main::lxdebug->enter_sub();
 
 627   my $cgi      = $main::cgi;
 
 628   $cgi       ||= CGI->new('');
 
 631   if (defined $main::auth) {
 
 632     my $uri      = $self->_get_request_uri;
 
 633     my @segments = $uri->path_segments;
 
 635     $uri->path_segments(@segments);
 
 637     my $session_cookie_value = $main::auth->get_session_id();
 
 639     if ($session_cookie_value) {
 
 640       $session_cookie = $cgi->cookie('-name'   => $main::auth->get_session_cookie_name(),
 
 641                                      '-value'  => $session_cookie_value,
 
 642                                      '-path'   => $uri->path,
 
 643                                      '-secure' => $ENV{HTTPS});
 
 647   my %cgi_params = ('-type' => $params{content_type});
 
 648   $cgi_params{'-charset'} = $params{charset} if ($params{charset});
 
 649   $cgi_params{'-cookie'}  = $session_cookie  if ($session_cookie);
 
 651   map { $cgi_params{'-' . $_} = $params{$_} if exists $params{$_} } qw(content_disposition content_length);
 
 653   my $output = $cgi->header(%cgi_params);
 
 655   $main::lxdebug->leave_sub();
 
 663   $self->{stylesheet} = [ $self->{stylesheet} ] unless ref $self->{stylesheet} eq 'ARRAY';
 
 664   $self->{stylesheet} = [ grep { -f                       }
 
 665                           map  { m:^css/: ? $_ : "css/$_" }
 
 667                                (@{ $self->{stylesheet} }, @_)
 
 670   return @{ $self->{stylesheet} };
 
 674   $::lxdebug->enter_sub;
 
 676   # extra code is currently only used by menuv3 and menuv4 to set their css.
 
 677   # it is strongly deprecated, and will be changed in a future version.
 
 678   my ($self, $extra_code) = @_;
 
 679   my $db_charset = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
 
 682   $::lxdebug->leave_sub and return if !$ENV{HTTP_USER_AGENT} || $self->{header}++;
 
 684   $self->{favicon} ||= "favicon.ico";
 
 685   $self->{titlebar}  = "$self->{title} - $self->{titlebar}" if $self->{title};
 
 688   if ($self->{refresh_url} || $self->{refresh_time}) {
 
 689     my $refresh_time = $self->{refresh_time} || 3;
 
 690     my $refresh_url  = $self->{refresh_url}  || $ENV{REFERER};
 
 691     push @header, "<meta http-equiv='refresh' content='$refresh_time;$refresh_url'>";
 
 694   push @header, map { qq|<link rel="stylesheet" href="$_" type="text/css" title="Lx-Office stylesheet">| } $self->use_stylesheet;
 
 696   push @header, "<style type='text/css'>\@page { size:landscape; }</style>" if $self->{landscape};
 
 697   push @header, "<link rel='shortcut icon' href='$self->{favicon}' type='image/x-icon'>" if -f $self->{favicon};
 
 698   push @header, '<script type="text/javascript" src="js/jquery.js"></script>',
 
 699                 '<script type="text/javascript" src="js/common.js"></script>',
 
 700                 '<link rel="stylesheet" type="text/css" href="js/jscalendar/calendar-win2k-1.css">',
 
 701                 '<script type="text/javascript" src="js/jscalendar/calendar.js"></script>',
 
 702                 '<script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>',
 
 703                 '<script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>',
 
 704                 '<script type="text/javascript" src="js/part_selection.js"></script>',
 
 705                 '<script type="text/javascript" src="js/jquery-ui.js"></script>',
 
 706                 '<link rel="stylesheet" type="text/css" href="css/ui-lightness/jquery-ui-1.8.12.custom.css">';
 
 707   push @header, $self->{javascript} if $self->{javascript};
 
 708   push @header, map { $_->show_javascript } @{ $self->{AJAX} || [] };
 
 709   push @header, "<script type='text/javascript'>function fokus(){ document.$self->{fokus}.focus(); }</script>" if $self->{fokus};
 
 710   push @header, sprintf "<script type='text/javascript'>top.document.title='%s';</script>",
 
 711     join ' - ', grep $_, $self->{title}, $self->{login}, $::myconfig{dbname}, $self->{version} if $self->{title};
 
 713   # if there is a title, we put some JavaScript in to the page, wich writes a
 
 714   # meaningful title-tag for our frameset.
 
 716   if ($self->{title}) {
 
 718     <script type="text/javascript">
 
 720       // Write a meaningful title-tag for our frameset.
 
 721       top.document.title="| . $self->{"title"} . qq| - | . $self->{"login"} . qq| - | . $::myconfig{dbname} . qq| - V| . $self->{"version"} . qq|";
 
 727   print $self->create_http_response(content_type => 'text/html', charset => $db_charset);
 
 728   print "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01//EN' 'http://www.w3.org/TR/html4/strict.dtd'>\n"
 
 729     if  $ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+\d/; # Other browsers may choke on menu scripts with DOCTYPE.
 
 733   <meta http-equiv="Content-Type" content="text/html; charset=$db_charset">
 
 734   <title>$self->{titlebar}</title>
 
 736   print "  $_\n" for @header;
 
 738   <link rel="stylesheet" href="css/jquery.autocomplete.css" type="text/css" />
 
 739   <meta name="robots" content="noindex,nofollow" />
 
 740   <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
 
 741   <script type="text/javascript" src="js/tabcontent.js">
 
 743   /***********************************************
 
 744    * Tab Content script v2.2- Â© Dynamic Drive DHTML code library (www.dynamicdrive.com)
 
 745    * This notice MUST stay intact for legal use
 
 746    * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
 
 747    ***********************************************/
 
 756   $::lxdebug->leave_sub;
 
 759 sub ajax_response_header {
 
 760   $main::lxdebug->enter_sub();
 
 764   my $db_charset = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
 
 765   my $cgi        = $main::cgi || CGI->new('');
 
 766   my $output     = $cgi->header('-charset' => $db_charset);
 
 768   $main::lxdebug->leave_sub();
 
 773 sub redirect_header {
 
 777   my $base_uri = $self->_get_request_uri;
 
 778   my $new_uri  = URI->new_abs($new_url, $base_uri);
 
 780   die "Headers already sent" if $self->{header};
 
 783   my $cgi = $main::cgi || CGI->new('');
 
 784   return $cgi->redirect($new_uri);
 
 787 sub set_standard_title {
 
 788   $::lxdebug->enter_sub;
 
 791   $self->{titlebar}  = "Lx-Office " . $::locale->text('Version') . " $self->{version}";
 
 792   $self->{titlebar} .= "- $::myconfig{name}"   if $::myconfig{name};
 
 793   $self->{titlebar} .= "- $::myconfig{dbname}" if $::myconfig{name};
 
 795   $::lxdebug->leave_sub;
 
 798 sub _prepare_html_template {
 
 799   $main::lxdebug->enter_sub();
 
 801   my ($self, $file, $additional_params) = @_;
 
 804   if (!%::myconfig || !$::myconfig{"countrycode"}) {
 
 805     $language = $::lx_office_conf{system}->{language};
 
 807     $language = $main::myconfig{"countrycode"};
 
 809   $language = "de" unless ($language);
 
 811   if (-f "templates/webpages/${file}.html") {
 
 812     $file = "templates/webpages/${file}.html";
 
 815     my $info = "Web page template '${file}' not found.\n";
 
 816     print qq|<pre>$info</pre>|;
 
 820   if ($self->{"DEBUG"}) {
 
 821     $additional_params->{"DEBUG"} = $self->{"DEBUG"};
 
 824   if ($additional_params->{"DEBUG"}) {
 
 825     $additional_params->{"DEBUG"} =
 
 826       "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
 
 829   if (%main::myconfig) {
 
 830     $::myconfig{jsc_dateformat} = apply {
 
 834     } $::myconfig{"dateformat"};
 
 835     $additional_params->{"myconfig"} ||= \%::myconfig;
 
 836     map { $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys %::myconfig;
 
 839   $additional_params->{"conf_dbcharset"}              = $::lx_office_conf{system}->{dbcharset};
 
 840   $additional_params->{"conf_webdav"}                 = $::lx_office_conf{features}->{webdav};
 
 841   $additional_params->{"conf_latex_templates"}        = $::lx_office_conf{print_templates}->{latex};
 
 842   $additional_params->{"conf_opendocument_templates"} = $::lx_office_conf{print_templates}->{opendocument};
 
 843   $additional_params->{"conf_vertreter"}              = $::lx_office_conf{features}->{vertreter};
 
 844   $additional_params->{"conf_show_best_before"}       = $::lx_office_conf{features}->{show_best_before};
 
 845   $additional_params->{"conf_parts_image_css"}        = $::lx_office_conf{features}->{parts_image_css};
 
 846   $additional_params->{"conf_parts_listing_images"}   = $::lx_office_conf{features}->{parts_listing_images};
 
 847   $additional_params->{"conf_parts_show_image"}       = $::lx_office_conf{features}->{parts_show_image};
 
 848   $additional_params->{"conf_payments_changeable"}    = $::lx_office_conf{features}->{payments_changeable};
 
 849   $additional_params->{"INSTANCE_CONF"}               = $::instance_conf;
 
 851   if (my $debug_options = $::lx_office_conf{debug}{options}) {
 
 852     map { $additional_params->{'DEBUG_' . uc($_)} = $debug_options->{$_} } keys %$debug_options;
 
 855   if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
 
 856     while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
 
 857       $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
 
 861   $main::lxdebug->leave_sub();
 
 866 sub parse_html_template {
 
 867   $main::lxdebug->enter_sub();
 
 869   my ($self, $file, $additional_params) = @_;
 
 871   $additional_params ||= { };
 
 873   my $real_file = $self->_prepare_html_template($file, $additional_params);
 
 874   my $template  = $self->template || $self->init_template;
 
 876   map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
 
 879   $template->process($real_file, $additional_params, \$output) || die $template->error;
 
 881   $main::lxdebug->leave_sub();
 
 889   return $self->template if $self->template;
 
 891   return $self->template(Template->new({
 
 896      'PLUGIN_BASE'  => 'SL::Template::Plugin',
 
 897      'INCLUDE_PATH' => '.:templates/webpages',
 
 898      'COMPILE_EXT'  => '.tcc',
 
 899      'COMPILE_DIR'  => $::lx_office_conf{paths}->{userspath} . '/templates-cache',
 
 905   $self->{template_object} = shift if @_;
 
 906   return $self->{template_object};
 
 909 sub show_generic_error {
 
 910   $main::lxdebug->enter_sub();
 
 912   my ($self, $error, %params) = @_;
 
 914   if ($self->{__ERROR_HANDLER}) {
 
 915     $self->{__ERROR_HANDLER}->($error);
 
 916     $main::lxdebug->leave_sub();
 
 921     'title_error' => $params{title},
 
 922     'label_error' => $error,
 
 925   if ($params{action}) {
 
 928     map { delete($self->{$_}); } qw(action);
 
 929     map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
 
 931     $add_params->{SHOW_BUTTON}  = 1;
 
 932     $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
 
 933     $add_params->{VARIABLES}    = \@vars;
 
 935   } elsif ($params{back_button}) {
 
 936     $add_params->{SHOW_BACK_BUTTON} = 1;
 
 939   $self->{title} = $params{title} if $params{title};
 
 942   print $self->parse_html_template("generic/error", $add_params);
 
 944   print STDERR "Error: $error\n";
 
 946   $main::lxdebug->leave_sub();
 
 951 sub show_generic_information {
 
 952   $main::lxdebug->enter_sub();
 
 954   my ($self, $text, $title) = @_;
 
 957     'title_information' => $title,
 
 958     'label_information' => $text,
 
 961   $self->{title} = $title if ($title);
 
 964   print $self->parse_html_template("generic/information", $add_params);
 
 966   $main::lxdebug->leave_sub();
 
 971 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
 
 972 # changed it to accept an arbitrary number of triggers - sschoeling
 
 974   $main::lxdebug->enter_sub();
 
 977   my $myconfig = shift;
 
 980   # set dateform for jsscript
 
 983     "dd.mm.yy" => "%d.%m.%Y",
 
 984     "dd-mm-yy" => "%d-%m-%Y",
 
 985     "dd/mm/yy" => "%d/%m/%Y",
 
 986     "mm/dd/yy" => "%m/%d/%Y",
 
 987     "mm-dd-yy" => "%m-%d-%Y",
 
 988     "yyyy-mm-dd" => "%Y-%m-%d",
 
 991   my $ifFormat = defined($dateformats{$myconfig->{"dateformat"}}) ?
 
 992     $dateformats{$myconfig->{"dateformat"}} : "%d.%m.%Y";
 
 999       inputField : "| . (shift) . qq|",
 
1000       ifFormat :"$ifFormat",
 
1001       align : "| .  (shift) . qq|",
 
1002       button : "| . (shift) . qq|"
 
1008        <script type="text/javascript">
 
1009        <!--| . join("", @triggers) . qq|//-->
 
1013   $main::lxdebug->leave_sub();
 
1016 }    #end sub write_trigger
 
1018 sub _store_redirect_info_in_session {
 
1021   return unless $self->{callback} =~ m:^ ( [^\?/]+ \.pl ) \? (.+) :x;
 
1023   my ($controller, $params) = ($1, $2);
 
1024   my $form                  = { map { map { $self->unescape($_) } split /=/, $_, 2 } split m/\&/, $params };
 
1025   $self->{callback}         = "${controller}?RESTORE_FORM_FROM_SESSION_ID=" . $::auth->save_form_in_session(form => $form);
 
1029   $main::lxdebug->enter_sub();
 
1031   my ($self, $msg) = @_;
 
1033   if (!$self->{callback}) {
 
1037     $self->_store_redirect_info_in_session;
 
1038     print $::form->redirect_header($self->{callback});
 
1043   $main::lxdebug->leave_sub();
 
1046 # sort of columns removed - empty sub
 
1048   $main::lxdebug->enter_sub();
 
1050   my ($self, @columns) = @_;
 
1052   $main::lxdebug->leave_sub();
 
1058   $main::lxdebug->enter_sub(2);
 
1060   my ($self, $myconfig, $amount, $places, $dash) = @_;
 
1062   if ($amount eq "") {
 
1066   # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
 
1068   my $neg = ($amount =~ s/^-//);
 
1069   my $exp = ($amount =~ m/[e]/) ? 1 : 0;
 
1071   if (defined($places) && ($places ne '')) {
 
1077         my ($actual_places) = ($amount =~ /\.(\d+)/);
 
1078         $actual_places = length($actual_places);
 
1079         $places = $actual_places > $places ? $actual_places : $places;
 
1082     $amount = $self->round_amount($amount, $places);
 
1085   my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
 
1086   my @p = split(/\./, $amount); # split amount at decimal point
 
1088   $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
 
1091   $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
 
1094     ($dash =~ /-/)    ? ($neg ? "($amount)"                            : "$amount" )                              :
 
1095     ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
 
1096                         ($neg ? "-$amount"                             : "$amount" )                              ;
 
1100   $main::lxdebug->leave_sub(2);
 
1104 sub format_amount_units {
 
1105   $main::lxdebug->enter_sub();
 
1110   my $myconfig         = \%main::myconfig;
 
1111   my $amount           = $params{amount} * 1;
 
1112   my $places           = $params{places};
 
1113   my $part_unit_name   = $params{part_unit};
 
1114   my $amount_unit_name = $params{amount_unit};
 
1115   my $conv_units       = $params{conv_units};
 
1116   my $max_places       = $params{max_places};
 
1118   if (!$part_unit_name) {
 
1119     $main::lxdebug->leave_sub();
 
1123   my $all_units        = AM->retrieve_all_units;
 
1125   if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
 
1126     $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
 
1129   if (!scalar @{ $conv_units }) {
 
1130     my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
 
1131     $main::lxdebug->leave_sub();
 
1135   my $part_unit  = $all_units->{$part_unit_name};
 
1136   my $conv_unit  = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
 
1138   $amount       *= $conv_unit->{factor};
 
1143   foreach my $unit (@$conv_units) {
 
1144     my $last = $unit->{name} eq $part_unit->{name};
 
1146       $num     = int($amount / $unit->{factor});
 
1147       $amount -= $num * $unit->{factor};
 
1150     if ($last ? $amount : $num) {
 
1151       push @values, { "unit"   => $unit->{name},
 
1152                       "amount" => $last ? $amount / $unit->{factor} : $num,
 
1153                       "places" => $last ? $places : 0 };
 
1160     push @values, { "unit"   => $part_unit_name,
 
1165   my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
 
1167   $main::lxdebug->leave_sub();
 
1173   $main::lxdebug->enter_sub(2);
 
1178   $input =~ s/(^|[^\#]) \#  (\d+)  /$1$_[$2 - 1]/gx;
 
1179   $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
 
1180   $input =~ s/\#\#/\#/g;
 
1182   $main::lxdebug->leave_sub(2);
 
1190   $main::lxdebug->enter_sub(2);
 
1192   my ($self, $myconfig, $amount) = @_;
 
1194   if (   ($myconfig->{numberformat} eq '1.000,00')
 
1195       || ($myconfig->{numberformat} eq '1000,00')) {
 
1197     $amount =~ s/,/\./g;
 
1200   if ($myconfig->{numberformat} eq "1'000.00") {
 
1206   $main::lxdebug->leave_sub(2);
 
1208   # Make sure no code wich is not a math expression ends up in eval().
 
1209   return 0 unless $amount =~ /^ [\s \d \( \) \- \+ \* \/ \. ]* $/x;
 
1210   return scalar(eval($amount)) * 1 ;
 
1214   $main::lxdebug->enter_sub(2);
 
1216   my ($self, $amount, $places) = @_;
 
1219   # Rounding like "Kaufmannsrunden" (see http://de.wikipedia.org/wiki/Rundung )
 
1221   # Round amounts to eight places before rounding to the requested
 
1222   # number of places. This gets rid of errors due to internal floating
 
1223   # point representation.
 
1224   $amount       = $self->round_amount($amount, 8) if $places < 8;
 
1225   $amount       = $amount * (10**($places));
 
1226   $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
 
1228   $main::lxdebug->leave_sub(2);
 
1230   return $round_amount;
 
1234 sub parse_template {
 
1235   $main::lxdebug->enter_sub();
 
1237   my ($self, $myconfig) = @_;
 
1242   my $userspath = $::lx_office_conf{paths}->{userspath};
 
1244   $self->{"cwd"} = getcwd();
 
1245   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
 
1250   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
 
1251     $template_type  = 'OpenDocument';
 
1252     $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
 
1254   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
 
1255     $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
 
1256     $template_type    = 'LaTeX';
 
1257     $ext_for_format   = 'pdf';
 
1259   } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
 
1260     $template_type  = 'HTML';
 
1261     $ext_for_format = 'html';
 
1263   } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
 
1264     $template_type  = 'XML';
 
1265     $ext_for_format = 'xml';
 
1267   } elsif ( $self->{"format"} =~ /elster(?:winston|taxbird)/i ) {
 
1268     $template_type = 'XML';
 
1270   } elsif ( $self->{"format"} =~ /excel/i ) {
 
1271     $template_type  = 'Excel';
 
1272     $ext_for_format = 'xls';
 
1274   } elsif ( defined $self->{'format'}) {
 
1275     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
 
1277   } elsif ( $self->{'format'} eq '' ) {
 
1278     $self->error("No Outputformat given: $self->{'format'}");
 
1280   } else { #Catch the rest
 
1281     $self->error("Outputformat not defined: $self->{'format'}");
 
1284   my $template = SL::Template::create(type      => $template_type,
 
1285                                       file_name => $self->{IN},
 
1287                                       myconfig  => $myconfig,
 
1288                                       userspath => $userspath);
 
1290   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
 
1291   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
 
1293   if (!$self->{employee_id}) {
 
1294     map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
 
1297   map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
 
1298   map { $self->{"myconfig_${_}"} = $myconfig->{$_} } grep { $_ ne 'dbpasswd' } keys %{ $myconfig };
 
1300   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
 
1302   # OUT is used for the media, screen, printer, email
 
1303   # for postscript we store a copy in a temporary file
 
1305   my $prepend_userspath;
 
1307   if (!$self->{tmpfile}) {
 
1308     $self->{tmpfile}   = "${fileid}.$self->{IN}";
 
1309     $prepend_userspath = 1;
 
1312   $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
 
1314   $self->{tmpfile} =~ s|.*/||;
 
1315   $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
 
1316   $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
 
1318   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
1319     $out = $self->{OUT};
 
1320     $self->{OUT} = "$self->{tmpfile}";
 
1326     open(OUT, ">", $self->{OUT}) or $self->error("$self->{OUT} : $!");
 
1328     *OUT = ($::dispatcher->get_standard_filehandles)[1];
 
1332   if (!$template->parse(*OUT)) {
 
1334     $self->error("$self->{IN} : " . $template->get_error());
 
1337   close OUT if $self->{OUT};
 
1339   if ($self->{media} eq 'file') {
 
1340     copy(join('/', $self->{cwd}, $userspath, $self->{tmpfile}), $out =~ m|^/| ? $out : join('/', $self->{cwd}, $out)) if $template->uses_temp_file;
 
1342     chdir("$self->{cwd}");
 
1344     $::lxdebug->leave_sub();
 
1349   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
1351     if ($self->{media} eq 'email') {
 
1353       my $mail = new Mailer;
 
1355       map { $mail->{$_} = $self->{$_} }
 
1356         qw(cc bcc subject message version format);
 
1357       $mail->{charset} = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
 
1358       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
 
1359       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
 
1360       $mail->{fileid} = "$fileid.";
 
1361       $myconfig->{signature} =~ s/\r//g;
 
1363       # if we send html or plain text inline
 
1364       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
 
1365         $mail->{contenttype} = "text/html";
 
1367         $mail->{message}       =~ s/\r//g;
 
1368         $mail->{message}       =~ s/\n/<br>\n/g;
 
1369         $myconfig->{signature} =~ s/\n/<br>\n/g;
 
1370         $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
 
1372         open(IN, "<", $self->{tmpfile})
 
1373           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1375           $mail->{message} .= $_;
 
1382         if (!$self->{"do_not_attach"}) {
 
1383           my $attachment_name  =  $self->{attachment_filename} || $self->{tmpfile};
 
1384           $attachment_name     =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
 
1385           $mail->{attachments} =  [{ "filename" => $self->{tmpfile},
 
1386                                      "name"     => $attachment_name }];
 
1389         $mail->{message}  =~ s/\r//g;
 
1390         $mail->{message} .=  "\n-- \n$myconfig->{signature}";
 
1394       my $err = $mail->send();
 
1395       $self->error($self->cleanup . "$err") if ($err);
 
1399       $self->{OUT} = $out;
 
1401       my $numbytes = (-s $self->{tmpfile});
 
1402       open(IN, "<", $self->{tmpfile})
 
1403         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1406       $self->{copies} = 1 unless $self->{media} eq 'printer';
 
1408       chdir("$self->{cwd}");
 
1409       #print(STDERR "Kopien $self->{copies}\n");
 
1410       #print(STDERR "OUT $self->{OUT}\n");
 
1411       for my $i (1 .. $self->{copies}) {
 
1413           open OUT, '>', $self->{OUT} or $self->error($self->cleanup . "$self->{OUT} : $!");
 
1414           print OUT while <IN>;
 
1419           $self->{attachment_filename} = ($self->{attachment_filename})
 
1420                                        ? $self->{attachment_filename}
 
1421                                        : $self->generate_attachment_filename();
 
1423           # launch application
 
1424           print qq|Content-Type: | . $template->get_mime_type() . qq|
 
1425 Content-Disposition: attachment; filename="$self->{attachment_filename}"
 
1426 Content-Length: $numbytes
 
1430           $::locale->with_raw_io(\*STDOUT, sub { print while <IN> });
 
1441   chdir("$self->{cwd}");
 
1442   $main::lxdebug->leave_sub();
 
1445 sub get_formname_translation {
 
1446   $main::lxdebug->enter_sub();
 
1447   my ($self, $formname) = @_;
 
1449   $formname ||= $self->{formname};
 
1451   my %formname_translations = (
 
1452     bin_list                => $main::locale->text('Bin List'),
 
1453     credit_note             => $main::locale->text('Credit Note'),
 
1454     invoice                 => $main::locale->text('Invoice'),
 
1455     pick_list               => $main::locale->text('Pick List'),
 
1456     proforma                => $main::locale->text('Proforma Invoice'),
 
1457     purchase_order          => $main::locale->text('Purchase Order'),
 
1458     request_quotation       => $main::locale->text('RFQ'),
 
1459     sales_order             => $main::locale->text('Confirmation'),
 
1460     sales_quotation         => $main::locale->text('Quotation'),
 
1461     storno_invoice          => $main::locale->text('Storno Invoice'),
 
1462     sales_delivery_order    => $main::locale->text('Delivery Order'),
 
1463     purchase_delivery_order => $main::locale->text('Delivery Order'),
 
1464     dunning                 => $main::locale->text('Dunning'),
 
1467   $main::lxdebug->leave_sub();
 
1468   return $formname_translations{$formname}
 
1471 sub get_number_prefix_for_type {
 
1472   $main::lxdebug->enter_sub();
 
1476       (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
 
1477     : ($self->{type} =~ /_quotation$/)                        ? 'quo'
 
1478     : ($self->{type} =~ /_delivery_order$/)                   ? 'do'
 
1481   $main::lxdebug->leave_sub();
 
1485 sub get_extension_for_format {
 
1486   $main::lxdebug->enter_sub();
 
1489   my $extension = $self->{format} =~ /pdf/i          ? ".pdf"
 
1490                 : $self->{format} =~ /postscript/i   ? ".ps"
 
1491                 : $self->{format} =~ /opendocument/i ? ".odt"
 
1492                 : $self->{format} =~ /excel/i        ? ".xls"
 
1493                 : $self->{format} =~ /html/i         ? ".html"
 
1496   $main::lxdebug->leave_sub();
 
1500 sub generate_attachment_filename {
 
1501   $main::lxdebug->enter_sub();
 
1504   my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
 
1505   my $prefix              = $self->get_number_prefix_for_type();
 
1507   if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
 
1508     $attachment_filename .= ' (' . $main::locale->text('Preview') . ')' . $self->get_extension_for_format();
 
1510   } elsif ($attachment_filename && $self->{"${prefix}number"}) {
 
1511     $attachment_filename .=  "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
 
1514     $attachment_filename = "";
 
1517   $attachment_filename =  $main::locale->quote_special_chars('filenames', $attachment_filename);
 
1518   $attachment_filename =~ s|[\s/\\]+|_|g;
 
1520   $main::lxdebug->leave_sub();
 
1521   return $attachment_filename;
 
1524 sub generate_email_subject {
 
1525   $main::lxdebug->enter_sub();
 
1528   my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
 
1529   my $prefix  = $self->get_number_prefix_for_type();
 
1531   if ($subject && $self->{"${prefix}number"}) {
 
1532     $subject .= " " . $self->{"${prefix}number"}
 
1535   $main::lxdebug->leave_sub();
 
1540   $main::lxdebug->enter_sub();
 
1542   my ($self, $application) = @_;
 
1544   my $error_code = $?;
 
1546   chdir("$self->{tmpdir}");
 
1549   if ((-1 == $error_code) || (127 == (($error_code) >> 8))) {
 
1550     push @err, $::locale->text('The application "#1" was not found on the system.', $application || 'pdflatex') . ' ' . $::locale->text('Please contact your administrator.');
 
1552   } elsif (-f "$self->{tmpfile}.err") {
 
1553     open(FH, "$self->{tmpfile}.err");
 
1558   if ($self->{tmpfile} && !($::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files})) {
 
1559     $self->{tmpfile} =~ s|.*/||g;
 
1561     $self->{tmpfile} =~ s/\.\w+$//g;
 
1562     my $tmpfile = $self->{tmpfile};
 
1563     unlink(<$tmpfile.*>);
 
1566   chdir("$self->{cwd}");
 
1568   $main::lxdebug->leave_sub();
 
1574   $main::lxdebug->enter_sub();
 
1576   my ($self, $date, $myconfig) = @_;
 
1579   if ($date && $date =~ /\D/) {
 
1581     if ($myconfig->{dateformat} =~ /^yy/) {
 
1582       ($yy, $mm, $dd) = split /\D/, $date;
 
1584     if ($myconfig->{dateformat} =~ /^mm/) {
 
1585       ($mm, $dd, $yy) = split /\D/, $date;
 
1587     if ($myconfig->{dateformat} =~ /^dd/) {
 
1588       ($dd, $mm, $yy) = split /\D/, $date;
 
1593     $yy = ($yy < 70) ? $yy + 2000 : $yy;
 
1594     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
 
1596     $dd = "0$dd" if ($dd < 10);
 
1597     $mm = "0$mm" if ($mm < 10);
 
1599     $date = "$yy$mm$dd";
 
1602   $main::lxdebug->leave_sub();
 
1607 # Database routines used throughout
 
1609 sub _dbconnect_options {
 
1611   my $options = { pg_enable_utf8 => $::locale->is_utf8,
 
1618   $main::lxdebug->enter_sub(2);
 
1620   my ($self, $myconfig) = @_;
 
1622   # connect to database
 
1623   my $dbh = SL::DBConnect->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, $self->_dbconnect_options)
 
1627   if ($myconfig->{dboptions}) {
 
1628     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1631   $main::lxdebug->leave_sub(2);
 
1636 sub dbconnect_noauto {
 
1637   $main::lxdebug->enter_sub();
 
1639   my ($self, $myconfig) = @_;
 
1641   # connect to database
 
1642   my $dbh = SL::DBConnect->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, $self->_dbconnect_options(AutoCommit => 0))
 
1646   if ($myconfig->{dboptions}) {
 
1647     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1650   $main::lxdebug->leave_sub();
 
1655 sub get_standard_dbh {
 
1656   $main::lxdebug->enter_sub(2);
 
1659   my $myconfig = shift || \%::myconfig;
 
1661   if ($standard_dbh && !$standard_dbh->{Active}) {
 
1662     $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
 
1663     undef $standard_dbh;
 
1666   $standard_dbh ||= $self->dbconnect_noauto($myconfig);
 
1668   $main::lxdebug->leave_sub(2);
 
1670   return $standard_dbh;
 
1674   $main::lxdebug->enter_sub();
 
1676   my ($self, $date, $myconfig) = @_;
 
1677   my $dbh = $self->dbconnect($myconfig);
 
1679   my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
 
1680   my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
 
1682   # Falls $date = '' - Fehlermeldung aus der Datenbank. Ich denke,
 
1683   # es ist sicher ein conv_date vorher IMMER auszuführen.
 
1684   # Testfälle ohne definiertes closedto:
 
1685   #   Leere Datumseingabe i.O.
 
1686   #     SELECT 1 FROM defaults WHERE '' < closedto
 
1687   #   normale Zahlungsbuchung Ã¼ber Rechnungsmaske i.O.
 
1688   #     SELECT 1 FROM defaults WHERE '10.05.2011' < closedto
 
1689   # Testfälle mit definiertem closedto (30.04.2011):
 
1690   #  Leere Datumseingabe i.O.
 
1691   #   SELECT 1 FROM defaults WHERE '' < closedto
 
1692   # normale Buchung im geschloßenem Zeitraum i.O.
 
1693   #   SELECT 1 FROM defaults WHERE '21.04.2011' < closedto
 
1694   #     Fehlermeldung: Es können keine Zahlungen für abgeschlossene Bücher gebucht werden!
 
1695   # normale Buchung in aktiver Buchungsperiode i.O.
 
1696   #   SELECT 1 FROM defaults WHERE '01.05.2011' < closedto
 
1698   my ($closed) = $sth->fetchrow_array;
 
1700   $main::lxdebug->leave_sub();
 
1705 sub update_balance {
 
1706   $main::lxdebug->enter_sub();
 
1708   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
 
1710   # if we have a value, go do it
 
1713     # retrieve balance from table
 
1714     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
 
1715     my $sth = prepare_execute_query($self, $dbh, $query, @values);
 
1716     my ($balance) = $sth->fetchrow_array;
 
1722     $query = "UPDATE $table SET $field = $balance WHERE $where";
 
1723     do_query($self, $dbh, $query, @values);
 
1725   $main::lxdebug->leave_sub();
 
1728 sub update_exchangerate {
 
1729   $main::lxdebug->enter_sub();
 
1731   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
 
1733   # some sanity check for currency
 
1735     $main::lxdebug->leave_sub();
 
1738   $query = qq|SELECT curr FROM defaults|;
 
1740   my ($currency) = selectrow_query($self, $dbh, $query);
 
1741   my ($defaultcurrency) = split m/:/, $currency;
 
1744   if ($curr eq $defaultcurrency) {
 
1745     $main::lxdebug->leave_sub();
 
1749   $query = qq|SELECT e.curr FROM exchangerate e
 
1750                  WHERE e.curr = ? AND e.transdate = ?
 
1752   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
 
1761   $buy = conv_i($buy, "NULL");
 
1762   $sell = conv_i($sell, "NULL");
 
1765   if ($buy != 0 && $sell != 0) {
 
1766     $set = "buy = $buy, sell = $sell";
 
1767   } elsif ($buy != 0) {
 
1768     $set = "buy = $buy";
 
1769   } elsif ($sell != 0) {
 
1770     $set = "sell = $sell";
 
1773   if ($sth->fetchrow_array) {
 
1774     $query = qq|UPDATE exchangerate
 
1780     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
 
1781                 VALUES (?, $buy, $sell, ?)|;
 
1784   do_query($self, $dbh, $query, $curr, $transdate);
 
1786   $main::lxdebug->leave_sub();
 
1789 sub save_exchangerate {
 
1790   $main::lxdebug->enter_sub();
 
1792   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
 
1794   my $dbh = $self->dbconnect($myconfig);
 
1798   $buy  = $rate if $fld eq 'buy';
 
1799   $sell = $rate if $fld eq 'sell';
 
1802   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
 
1807   $main::lxdebug->leave_sub();
 
1810 sub get_exchangerate {
 
1811   $main::lxdebug->enter_sub();
 
1813   my ($self, $dbh, $curr, $transdate, $fld) = @_;
 
1816   unless ($transdate) {
 
1817     $main::lxdebug->leave_sub();
 
1821   $query = qq|SELECT curr FROM defaults|;
 
1823   my ($currency) = selectrow_query($self, $dbh, $query);
 
1824   my ($defaultcurrency) = split m/:/, $currency;
 
1826   if ($currency eq $defaultcurrency) {
 
1827     $main::lxdebug->leave_sub();
 
1831   $query = qq|SELECT e.$fld FROM exchangerate e
 
1832                  WHERE e.curr = ? AND e.transdate = ?|;
 
1833   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
 
1837   $main::lxdebug->leave_sub();
 
1839   return $exchangerate;
 
1842 sub check_exchangerate {
 
1843   $main::lxdebug->enter_sub();
 
1845   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
 
1847   if ($fld !~/^buy|sell$/) {
 
1848     $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
 
1851   unless ($transdate) {
 
1852     $main::lxdebug->leave_sub();
 
1856   my ($defaultcurrency) = $self->get_default_currency($myconfig);
 
1858   if ($currency eq $defaultcurrency) {
 
1859     $main::lxdebug->leave_sub();
 
1863   my $dbh   = $self->get_standard_dbh($myconfig);
 
1864   my $query = qq|SELECT e.$fld FROM exchangerate e
 
1865                  WHERE e.curr = ? AND e.transdate = ?|;
 
1867   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
 
1869   $main::lxdebug->leave_sub();
 
1871   return $exchangerate;
 
1874 sub get_all_currencies {
 
1875   $main::lxdebug->enter_sub();
 
1878   my $myconfig = shift || \%::myconfig;
 
1879   my $dbh      = $self->get_standard_dbh($myconfig);
 
1881   my $query = qq|SELECT curr FROM defaults|;
 
1883   my ($curr)     = selectrow_query($self, $dbh, $query);
 
1884   my @currencies = grep { $_ } map { s/\s//g; $_ } split m/:/, $curr;
 
1886   $main::lxdebug->leave_sub();
 
1891 sub get_default_currency {
 
1892   $main::lxdebug->enter_sub();
 
1894   my ($self, $myconfig) = @_;
 
1895   my @currencies        = $self->get_all_currencies($myconfig);
 
1897   $main::lxdebug->leave_sub();
 
1899   return $currencies[0];
 
1902 sub set_payment_options {
 
1903   $main::lxdebug->enter_sub();
 
1905   my ($self, $myconfig, $transdate) = @_;
 
1907   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
 
1909   my $dbh = $self->get_standard_dbh($myconfig);
 
1912     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long , p.description | .
 
1913     qq|FROM payment_terms p | .
 
1916   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
 
1917    $self->{payment_terms}, $self->{payment_description}) =
 
1918      selectrow_query($self, $dbh, $query, $self->{payment_id});
 
1920   if ($transdate eq "") {
 
1921     if ($self->{invdate}) {
 
1922       $transdate = $self->{invdate};
 
1924       $transdate = $self->{transdate};
 
1929     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
 
1930     qq|FROM payment_terms|;
 
1931   ($self->{netto_date}, $self->{skonto_date}) =
 
1932     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
 
1934   my ($invtotal, $total);
 
1935   my (%amounts, %formatted_amounts);
 
1937   if ($self->{type} =~ /_order$/) {
 
1938     $amounts{invtotal} = $self->{ordtotal};
 
1939     $amounts{total}    = $self->{ordtotal};
 
1941   } elsif ($self->{type} =~ /_quotation$/) {
 
1942     $amounts{invtotal} = $self->{quototal};
 
1943     $amounts{total}    = $self->{quototal};
 
1946     $amounts{invtotal} = $self->{invtotal};
 
1947     $amounts{total}    = $self->{total};
 
1949   $amounts{skonto_in_percent} = 100.0 * $self->{percent_skonto};
 
1951   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
 
1953   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
 
1954   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
 
1955   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
 
1957   foreach (keys %amounts) {
 
1958     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
 
1959     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
 
1962   if ($self->{"language_id"}) {
 
1964       qq|SELECT t.translation, l.output_numberformat, l.output_dateformat, l.output_longdates | .
 
1965       qq|FROM generic_translations t | .
 
1966       qq|LEFT JOIN language l ON t.language_id = l.id | .
 
1967       qq|WHERE (t.language_id = ?)
 
1968            AND (t.translation_id = ?)
 
1969            AND (t.translation_type = 'SL::DB::PaymentTerm/description_long')|;
 
1970     my ($description_long, $output_numberformat, $output_dateformat,
 
1971       $output_longdates) =
 
1972       selectrow_query($self, $dbh, $query,
 
1973                       $self->{"language_id"}, $self->{"payment_id"});
 
1975     $self->{payment_terms} = $description_long if ($description_long);
 
1977     if ($output_dateformat) {
 
1978       foreach my $key (qw(netto_date skonto_date)) {
 
1980           $main::locale->reformat_date($myconfig, $self->{$key},
 
1986     if ($output_numberformat &&
 
1987         ($output_numberformat ne $myconfig->{"numberformat"})) {
 
1988       my $saved_numberformat = $myconfig->{"numberformat"};
 
1989       $myconfig->{"numberformat"} = $output_numberformat;
 
1990       map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
 
1991       $myconfig->{"numberformat"} = $saved_numberformat;
 
1995   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
 
1996   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
 
1997   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
 
1998   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
 
1999   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
 
2000   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
 
2001   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
 
2003   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
 
2005   $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
 
2007   $main::lxdebug->leave_sub();
 
2011 sub get_template_language {
 
2012   $main::lxdebug->enter_sub();
 
2014   my ($self, $myconfig) = @_;
 
2016   my $template_code = "";
 
2018   if ($self->{language_id}) {
 
2019     my $dbh = $self->get_standard_dbh($myconfig);
 
2020     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
 
2021     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
 
2024   $main::lxdebug->leave_sub();
 
2026   return $template_code;
 
2029 sub get_printer_code {
 
2030   $main::lxdebug->enter_sub();
 
2032   my ($self, $myconfig) = @_;
 
2034   my $template_code = "";
 
2036   if ($self->{printer_id}) {
 
2037     my $dbh = $self->get_standard_dbh($myconfig);
 
2038     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
 
2039     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
 
2042   $main::lxdebug->leave_sub();
 
2044   return $template_code;
 
2048   $main::lxdebug->enter_sub();
 
2050   my ($self, $myconfig) = @_;
 
2052   my $template_code = "";
 
2054   if ($self->{shipto_id}) {
 
2055     my $dbh = $self->get_standard_dbh($myconfig);
 
2056     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
 
2057     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
 
2058     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
 
2061   $main::lxdebug->leave_sub();
 
2065   $main::lxdebug->enter_sub();
 
2067   my ($self, $dbh, $id, $module) = @_;
 
2072   foreach my $item (qw(name department_1 department_2 street zipcode city country
 
2073                        contact cp_gender phone fax email)) {
 
2074     if ($self->{"shipto$item"}) {
 
2075       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
 
2077     push(@values, $self->{"shipto${item}"});
 
2081     if ($self->{shipto_id}) {
 
2082       my $query = qq|UPDATE shipto set
 
2084                        shiptodepartment_1 = ?,
 
2085                        shiptodepartment_2 = ?,
 
2091                        shiptocp_gender = ?,
 
2095                      WHERE shipto_id = ?|;
 
2096       do_query($self, $dbh, $query, @values, $self->{shipto_id});
 
2098       my $query = qq|SELECT * FROM shipto
 
2099                      WHERE shiptoname = ? AND
 
2100                        shiptodepartment_1 = ? AND
 
2101                        shiptodepartment_2 = ? AND
 
2102                        shiptostreet = ? AND
 
2103                        shiptozipcode = ? AND
 
2105                        shiptocountry = ? AND
 
2106                        shiptocontact = ? AND
 
2107                        shiptocp_gender = ? AND
 
2113       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
 
2116           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
 
2117                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
 
2118                                  shiptocontact, shiptocp_gender, shiptophone, shiptofax, shiptoemail, module)
 
2119              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
 
2120         do_query($self, $dbh, $query, $id, @values, $module);
 
2125   $main::lxdebug->leave_sub();
 
2129   $main::lxdebug->enter_sub();
 
2131   my ($self, $dbh) = @_;
 
2133   $dbh ||= $self->get_standard_dbh(\%main::myconfig);
 
2135   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
 
2136   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
 
2137   $self->{"employee_id"} *= 1;
 
2139   $main::lxdebug->leave_sub();
 
2142 sub get_employee_data {
 
2143   $main::lxdebug->enter_sub();
 
2148   Common::check_params(\%params, qw(prefix));
 
2149   Common::check_params_x(\%params, qw(id));
 
2152     $main::lxdebug->leave_sub();
 
2156   my $myconfig = \%main::myconfig;
 
2157   my $dbh      = $params{dbh} || $self->get_standard_dbh($myconfig);
 
2159   my ($login)  = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
 
2162     my $user = User->new($login);
 
2163     map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
 
2165     $self->{$params{prefix} . '_login'}   = $login;
 
2166     $self->{$params{prefix} . '_name'}  ||= $login;
 
2169   $main::lxdebug->leave_sub();
 
2173   $main::lxdebug->enter_sub();
 
2175   my ($self, $myconfig, $reference_date) = @_;
 
2177   $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
 
2179   my $dbh         = $self->get_standard_dbh($myconfig);
 
2180   my $query       = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
 
2181   my ($duedate)   = selectrow_query($self, $dbh, $query, $self->{payment_id});
 
2183   $main::lxdebug->leave_sub();
 
2189   $main::lxdebug->enter_sub();
 
2191   my ($self, $dbh, $id, $key) = @_;
 
2193   $key = "all_contacts" unless ($key);
 
2197     $main::lxdebug->leave_sub();
 
2202     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
 
2203     qq|FROM contacts | .
 
2204     qq|WHERE cp_cv_id = ? | .
 
2205     qq|ORDER BY lower(cp_name)|;
 
2207   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
 
2209   $main::lxdebug->leave_sub();
 
2213   $main::lxdebug->enter_sub();
 
2215   my ($self, $dbh, $key) = @_;
 
2217   my ($all, $old_id, $where, @values);
 
2219   if (ref($key) eq "HASH") {
 
2222     $key = "ALL_PROJECTS";
 
2224     foreach my $p (keys(%{$params})) {
 
2226         $all = $params->{$p};
 
2227       } elsif ($p eq "old_id") {
 
2228         $old_id = $params->{$p};
 
2229       } elsif ($p eq "key") {
 
2230         $key = $params->{$p};
 
2236     $where = "WHERE active ";
 
2238       if (ref($old_id) eq "ARRAY") {
 
2239         my @ids = grep({ $_ } @{$old_id});
 
2241           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
 
2242           push(@values, @ids);
 
2245         $where .= " OR (id = ?) ";
 
2246         push(@values, $old_id);
 
2252     qq|SELECT id, projectnumber, description, active | .
 
2255     qq|ORDER BY lower(projectnumber)|;
 
2257   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
 
2259   $main::lxdebug->leave_sub();
 
2263   $main::lxdebug->enter_sub();
 
2265   my ($self, $dbh, $vc_id, $key) = @_;
 
2267   $key = "all_shipto" unless ($key);
 
2270     # get shipping addresses
 
2271     my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
 
2273     $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
 
2279   $main::lxdebug->leave_sub();
 
2283   $main::lxdebug->enter_sub();
 
2285   my ($self, $dbh, $key) = @_;
 
2287   $key = "all_printers" unless ($key);
 
2289   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
 
2291   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2293   $main::lxdebug->leave_sub();
 
2297   $main::lxdebug->enter_sub();
 
2299   my ($self, $dbh, $params) = @_;
 
2302   $key = $params->{key};
 
2303   $key = "all_charts" unless ($key);
 
2305   my $transdate = quote_db_date($params->{transdate});
 
2308     qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
 
2310     qq|LEFT JOIN taxkeys tk ON | .
 
2311     qq|(tk.id = (SELECT id FROM taxkeys | .
 
2312     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
 
2313     qq|          ORDER BY startdate DESC LIMIT 1)) | .
 
2314     qq|ORDER BY c.accno|;
 
2316   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2318   $main::lxdebug->leave_sub();
 
2321 sub _get_taxcharts {
 
2322   $main::lxdebug->enter_sub();
 
2324   my ($self, $dbh, $params) = @_;
 
2326   my $key = "all_taxcharts";
 
2329   if (ref $params eq 'HASH') {
 
2330     $key = $params->{key} if ($params->{key});
 
2331     if ($params->{module} eq 'AR') {
 
2332       push @where, 'taxkey NOT IN (8, 9, 18, 19)';
 
2334     } elsif ($params->{module} eq 'AP') {
 
2335       push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
 
2342   my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
 
2344   my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
 
2346   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2348   $main::lxdebug->leave_sub();
 
2352   $main::lxdebug->enter_sub();
 
2354   my ($self, $dbh, $key) = @_;
 
2356   $key = "all_taxzones" unless ($key);
 
2358   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
 
2360   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2362   $main::lxdebug->leave_sub();
 
2365 sub _get_employees {
 
2366   $main::lxdebug->enter_sub();
 
2368   my ($self, $dbh, $default_key, $key) = @_;
 
2370   $key = $default_key unless ($key);
 
2371   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
 
2373   $main::lxdebug->leave_sub();
 
2376 sub _get_business_types {
 
2377   $main::lxdebug->enter_sub();
 
2379   my ($self, $dbh, $key) = @_;
 
2381   my $options       = ref $key eq 'HASH' ? $key : { key => $key };
 
2382   $options->{key} ||= "all_business_types";
 
2385   if (exists $options->{salesman}) {
 
2386     $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
 
2389   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
 
2391   $main::lxdebug->leave_sub();
 
2394 sub _get_languages {
 
2395   $main::lxdebug->enter_sub();
 
2397   my ($self, $dbh, $key) = @_;
 
2399   $key = "all_languages" unless ($key);
 
2401   my $query = qq|SELECT * FROM language ORDER BY id|;
 
2403   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2405   $main::lxdebug->leave_sub();
 
2408 sub _get_dunning_configs {
 
2409   $main::lxdebug->enter_sub();
 
2411   my ($self, $dbh, $key) = @_;
 
2413   $key = "all_dunning_configs" unless ($key);
 
2415   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
 
2417   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2419   $main::lxdebug->leave_sub();
 
2422 sub _get_currencies {
 
2423 $main::lxdebug->enter_sub();
 
2425   my ($self, $dbh, $key) = @_;
 
2427   $key = "all_currencies" unless ($key);
 
2429   my $query = qq|SELECT curr AS currency FROM defaults|;
 
2431   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
 
2433   $main::lxdebug->leave_sub();
 
2437 $main::lxdebug->enter_sub();
 
2439   my ($self, $dbh, $key) = @_;
 
2441   $key = "all_payments" unless ($key);
 
2443   my $query = qq|SELECT * FROM payment_terms ORDER BY sortkey|;
 
2445   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2447   $main::lxdebug->leave_sub();
 
2450 sub _get_customers {
 
2451   $main::lxdebug->enter_sub();
 
2453   my ($self, $dbh, $key) = @_;
 
2455   my $options        = ref $key eq 'HASH' ? $key : { key => $key };
 
2456   $options->{key}  ||= "all_customers";
 
2457   my $limit_clause   = "LIMIT $options->{limit}" if $options->{limit};
 
2460   push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if  $options->{business_is_salesman};
 
2461   push @where, qq|NOT obsolete|                                            if !$options->{with_obsolete};
 
2462   my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : '';
 
2464   my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|;
 
2465   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
 
2467   $main::lxdebug->leave_sub();
 
2471   $main::lxdebug->enter_sub();
 
2473   my ($self, $dbh, $key) = @_;
 
2475   $key = "all_vendors" unless ($key);
 
2477   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
 
2479   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2481   $main::lxdebug->leave_sub();
 
2484 sub _get_departments {
 
2485   $main::lxdebug->enter_sub();
 
2487   my ($self, $dbh, $key) = @_;
 
2489   $key = "all_departments" unless ($key);
 
2491   my $query = qq|SELECT * FROM department ORDER BY description|;
 
2493   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2495   $main::lxdebug->leave_sub();
 
2498 sub _get_warehouses {
 
2499   $main::lxdebug->enter_sub();
 
2501   my ($self, $dbh, $param) = @_;
 
2503   my ($key, $bins_key);
 
2505   if ('' eq ref $param) {
 
2509     $key      = $param->{key};
 
2510     $bins_key = $param->{bins};
 
2513   my $query = qq|SELECT w.* FROM warehouse w
 
2514                  WHERE (NOT w.invalid) AND
 
2515                    ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
 
2516                  ORDER BY w.sortkey|;
 
2518   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2521     $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?
 
2522                 ORDER BY description|;
 
2523     my $sth = prepare_query($self, $dbh, $query);
 
2525     foreach my $warehouse (@{ $self->{$key} }) {
 
2526       do_statement($self, $sth, $query, $warehouse->{id});
 
2527       $warehouse->{$bins_key} = [];
 
2529       while (my $ref = $sth->fetchrow_hashref()) {
 
2530         push @{ $warehouse->{$bins_key} }, $ref;
 
2536   $main::lxdebug->leave_sub();
 
2540   $main::lxdebug->enter_sub();
 
2542   my ($self, $dbh, $table, $key, $sortkey) = @_;
 
2544   my $query  = qq|SELECT * FROM $table|;
 
2545   $query    .= qq| ORDER BY $sortkey| if ($sortkey);
 
2547   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2549   $main::lxdebug->leave_sub();
 
2553 #  $main::lxdebug->enter_sub();
 
2555 #  my ($self, $dbh, $key) = @_;
 
2557 #  $key ||= "all_groups";
 
2559 #  my $groups = $main::auth->read_groups();
 
2561 #  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2563 #  $main::lxdebug->leave_sub();
 
2567   $main::lxdebug->enter_sub();
 
2572   my $dbh = $self->get_standard_dbh(\%main::myconfig);
 
2573   my ($sth, $query, $ref);
 
2575   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
 
2576   my $vc_id = $self->{"${vc}_id"};
 
2578   if ($params{"contacts"}) {
 
2579     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
 
2582   if ($params{"shipto"}) {
 
2583     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
 
2586   if ($params{"projects"} || $params{"all_projects"}) {
 
2587     $self->_get_projects($dbh, $params{"all_projects"} ?
 
2588                          $params{"all_projects"} : $params{"projects"},
 
2589                          $params{"all_projects"} ? 1 : 0);
 
2592   if ($params{"printers"}) {
 
2593     $self->_get_printers($dbh, $params{"printers"});
 
2596   if ($params{"languages"}) {
 
2597     $self->_get_languages($dbh, $params{"languages"});
 
2600   if ($params{"charts"}) {
 
2601     $self->_get_charts($dbh, $params{"charts"});
 
2604   if ($params{"taxcharts"}) {
 
2605     $self->_get_taxcharts($dbh, $params{"taxcharts"});
 
2608   if ($params{"taxzones"}) {
 
2609     $self->_get_taxzones($dbh, $params{"taxzones"});
 
2612   if ($params{"employees"}) {
 
2613     $self->_get_employees($dbh, "all_employees", $params{"employees"});
 
2616   if ($params{"salesmen"}) {
 
2617     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
 
2620   if ($params{"business_types"}) {
 
2621     $self->_get_business_types($dbh, $params{"business_types"});
 
2624   if ($params{"dunning_configs"}) {
 
2625     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
 
2628   if($params{"currencies"}) {
 
2629     $self->_get_currencies($dbh, $params{"currencies"});
 
2632   if($params{"customers"}) {
 
2633     $self->_get_customers($dbh, $params{"customers"});
 
2636   if($params{"vendors"}) {
 
2637     if (ref $params{"vendors"} eq 'HASH') {
 
2638       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
 
2640       $self->_get_vendors($dbh, $params{"vendors"});
 
2644   if($params{"payments"}) {
 
2645     $self->_get_payments($dbh, $params{"payments"});
 
2648   if($params{"departments"}) {
 
2649     $self->_get_departments($dbh, $params{"departments"});
 
2652   if ($params{price_factors}) {
 
2653     $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
 
2656   if ($params{warehouses}) {
 
2657     $self->_get_warehouses($dbh, $params{warehouses});
 
2660 #  if ($params{groups}) {
 
2661 #    $self->_get_groups($dbh, $params{groups});
 
2664   if ($params{partsgroup}) {
 
2665     $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
 
2668   $main::lxdebug->leave_sub();
 
2671 # this sub gets the id and name from $table
 
2673   $main::lxdebug->enter_sub();
 
2675   my ($self, $myconfig, $table) = @_;
 
2677   # connect to database
 
2678   my $dbh = $self->get_standard_dbh($myconfig);
 
2680   $table = $table eq "customer" ? "customer" : "vendor";
 
2681   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
 
2683   my ($query, @values);
 
2685   if (!$self->{openinvoices}) {
 
2687     if ($self->{customernumber} ne "") {
 
2688       $where = qq|(vc.customernumber ILIKE ?)|;
 
2689       push(@values, '%' . $self->{customernumber} . '%');
 
2691       $where = qq|(vc.name ILIKE ?)|;
 
2692       push(@values, '%' . $self->{$table} . '%');
 
2696       qq~SELECT vc.id, vc.name,
 
2697            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
2699          WHERE $where AND (NOT vc.obsolete)
 
2703       qq~SELECT DISTINCT vc.id, vc.name,
 
2704            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
2706          JOIN $table vc ON (a.${table}_id = vc.id)
 
2707          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
 
2709     push(@values, '%' . $self->{$table} . '%');
 
2712   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
 
2714   $main::lxdebug->leave_sub();
 
2716   return scalar(@{ $self->{name_list} });
 
2719 # the selection sub is used in the AR, AP, IS, IR and OE module
 
2722   $main::lxdebug->enter_sub();
 
2724   my ($self, $myconfig, $table, $module) = @_;
 
2727   my $dbh = $self->get_standard_dbh;
 
2729   $table = $table eq "customer" ? "customer" : "vendor";
 
2731   my $query = qq|SELECT count(*) FROM $table|;
 
2732   my ($count) = selectrow_query($self, $dbh, $query);
 
2734   # build selection list
 
2735   if ($count <= $myconfig->{vclimit}) {
 
2736     $query = qq|SELECT id, name, salesman_id
 
2737                 FROM $table WHERE NOT obsolete
 
2739     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
 
2743   $self->get_employee($dbh);
 
2745   # setup sales contacts
 
2746   $query = qq|SELECT e.id, e.name
 
2748               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
 
2749   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
 
2752   push(@{ $self->{all_employees} },
 
2753        { id   => $self->{employee_id},
 
2754          name => $self->{employee} });
 
2756   # sort the whole thing
 
2757   @{ $self->{all_employees} } =
 
2758     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
 
2761     # prepare query for departments
 
2762     $query = qq|SELECT id, description
 
2764                 ORDER BY description|;
 
2766   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2769   $query = qq|SELECT id, description
 
2773   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2776   $query = qq|SELECT printer_description, id
 
2778               ORDER BY printer_description|;
 
2780   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2783   $query = qq|SELECT id, description
 
2787   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
2789   $main::lxdebug->leave_sub();
 
2792 sub language_payment {
 
2793   $main::lxdebug->enter_sub();
 
2795   my ($self, $myconfig) = @_;
 
2797   my $dbh = $self->get_standard_dbh($myconfig);
 
2799   my $query = qq|SELECT id, description
 
2803   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2806   $query = qq|SELECT printer_description, id
 
2808               ORDER BY printer_description|;
 
2810   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2813   $query = qq|SELECT id, description
 
2817   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
2819   # get buchungsgruppen
 
2820   $query = qq|SELECT id, description
 
2821               FROM buchungsgruppen|;
 
2823   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
 
2825   $main::lxdebug->leave_sub();
 
2828 # this is only used for reports
 
2829 sub all_departments {
 
2830   $main::lxdebug->enter_sub();
 
2832   my ($self, $myconfig, $table) = @_;
 
2834   my $dbh = $self->get_standard_dbh($myconfig);
 
2836   my $query = qq|SELECT id, description
 
2838                  ORDER BY description|;
 
2839   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2841   delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
 
2843   $main::lxdebug->leave_sub();
 
2847   $main::lxdebug->enter_sub();
 
2849   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
 
2852   if ($table eq "customer") {
 
2861   $self->all_vc($myconfig, $table, $module);
 
2863   # get last customers or vendors
 
2864   my ($query, $sth, $ref);
 
2866   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
 
2871     my $transdate = "current_date";
 
2872     if ($self->{transdate}) {
 
2873       $transdate = $dbh->quote($self->{transdate});
 
2876     # now get the account numbers
 
2877 #    $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
 
2878 #                FROM chart c, taxkeys tk
 
2879 #                WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
 
2880 #                  (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
 
2881 #                ORDER BY c.accno|;
 
2883 #  same query as above, but without expensive subquery for each row. about 80% faster
 
2885       SELECT c.accno, c.description, c.link, c.taxkey_id, tk2.tax_id
 
2887         -- find newest entries in taxkeys
 
2889           SELECT chart_id, MAX(startdate) AS startdate
 
2891           WHERE (startdate <= $transdate)
 
2893         ) tk ON (c.id = tk.chart_id)
 
2894         -- and load all of those entries
 
2895         INNER JOIN taxkeys tk2
 
2896            ON (tk.chart_id = tk2.chart_id AND tk.startdate = tk2.startdate)
 
2897        WHERE (c.link LIKE ?)
 
2900     $sth = $dbh->prepare($query);
 
2902     do_statement($self, $sth, $query, '%' . $module . '%');
 
2904     $self->{accounts} = "";
 
2905     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2907       foreach my $key (split(/:/, $ref->{link})) {
 
2908         if ($key =~ /\Q$module\E/) {
 
2910           # cross reference for keys
 
2911           $xkeyref{ $ref->{accno} } = $key;
 
2913           push @{ $self->{"${module}_links"}{$key} },
 
2914             { accno       => $ref->{accno},
 
2915               description => $ref->{description},
 
2916               taxkey      => $ref->{taxkey_id},
 
2917               tax_id      => $ref->{tax_id} };
 
2919           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2925   # get taxkeys and description
 
2926   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
 
2927   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
 
2929   if (($module eq "AP") || ($module eq "AR")) {
 
2930     # get tax rates and description
 
2931     $query = qq|SELECT * FROM tax|;
 
2932     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
 
2938            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
 
2939            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
 
2940            a.intnotes, a.department_id, a.amount AS oldinvtotal,
 
2941            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
 
2944            d.description AS department,
 
2947          JOIN $table c ON (a.${table}_id = c.id)
 
2948          LEFT JOIN employee e ON (e.id = a.employee_id)
 
2949          LEFT JOIN department d ON (d.id = a.department_id)
 
2951     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
 
2953     foreach my $key (keys %$ref) {
 
2954       $self->{$key} = $ref->{$key};
 
2957     # remove any trailing whitespace
 
2958     $self->{currency} =~ s/\s*$//;
 
2960     my $transdate = "current_date";
 
2961     if ($self->{transdate}) {
 
2962       $transdate = $dbh->quote($self->{transdate});
 
2965     # now get the account numbers
 
2966     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
 
2968                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
 
2970                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
 
2971                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
 
2974     $sth = $dbh->prepare($query);
 
2975     do_statement($self, $sth, $query, "%$module%");
 
2977     $self->{accounts} = "";
 
2978     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2980       foreach my $key (split(/:/, $ref->{link})) {
 
2981         if ($key =~ /\Q$module\E/) {
 
2983           # cross reference for keys
 
2984           $xkeyref{ $ref->{accno} } = $key;
 
2986           push @{ $self->{"${module}_links"}{$key} },
 
2987             { accno       => $ref->{accno},
 
2988               description => $ref->{description},
 
2989               taxkey      => $ref->{taxkey_id},
 
2990               tax_id      => $ref->{tax_id} };
 
2992           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2998     # get amounts from individual entries
 
3001            c.accno, c.description,
 
3002            a.acc_trans_id, a.source, a.amount, a.memo, a.transdate, a.gldate, a.cleared, a.project_id, a.taxkey,
 
3006          LEFT JOIN chart c ON (c.id = a.chart_id)
 
3007          LEFT JOIN project p ON (p.id = a.project_id)
 
3008          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
 
3009                                     WHERE (tk.taxkey_id=a.taxkey) AND
 
3010                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
 
3011                                         THEN tk.chart_id = a.chart_id
 
3014                                        OR (c.link='%tax%')) AND
 
3015                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
 
3016          WHERE a.trans_id = ?
 
3017          AND a.fx_transaction = '0'
 
3018          ORDER BY a.acc_trans_id, a.transdate|;
 
3019     $sth = $dbh->prepare($query);
 
3020     do_statement($self, $sth, $query, $self->{id});
 
3022     # get exchangerate for currency
 
3023     $self->{exchangerate} =
 
3024       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
3027     # store amounts in {acc_trans}{$key} for multiple accounts
 
3028     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
3029       $ref->{exchangerate} =
 
3030         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
 
3031       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
 
3034       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
 
3035         $ref->{amount} *= -1;
 
3037       $ref->{index} = $index;
 
3039       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
 
3045            d.curr AS currencies, d.closedto, d.revtrans,
 
3046            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
3047            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
3049     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
3050     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
3057             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
 
3058             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
3059             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
3061     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
3062     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
3064     if ($self->{"$self->{vc}_id"}) {
 
3066       # only setup currency
 
3067       ($self->{currency}) = split(/:/, $self->{currencies});
 
3071       $self->lastname_used($dbh, $myconfig, $table, $module);
 
3073       # get exchangerate for currency
 
3074       $self->{exchangerate} =
 
3075         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
3081   $main::lxdebug->leave_sub();
 
3085   $main::lxdebug->enter_sub();
 
3087   my ($self, $dbh, $myconfig, $table, $module) = @_;
 
3091   $table         = $table eq "customer" ? "customer" : "vendor";
 
3092   my %column_map = ("a.curr"                  => "currency",
 
3093                     "a.${table}_id"           => "${table}_id",
 
3094                     "a.department_id"         => "department_id",
 
3095                     "d.description"           => "department",
 
3096                     "ct.name"                 => $table,
 
3097                     "current_date + ct.terms" => "duedate",
 
3100   if ($self->{type} =~ /delivery_order/) {
 
3101     $arap  = 'delivery_orders';
 
3102     delete $column_map{"a.curr"};
 
3104   } elsif ($self->{type} =~ /_order/) {
 
3106     $where = "quotation = '0'";
 
3108   } elsif ($self->{type} =~ /_quotation/) {
 
3110     $where = "quotation = '1'";
 
3112   } elsif ($table eq 'customer') {
 
3120   $where           = "($where) AND" if ($where);
 
3121   my $query        = qq|SELECT MAX(id) FROM $arap
 
3122                         WHERE $where ${table}_id > 0|;
 
3123   my ($trans_id)   = selectrow_query($self, $dbh, $query);
 
3126   my $column_spec  = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
 
3127   $query           = qq|SELECT $column_spec
 
3129                         LEFT JOIN $table     ct ON (a.${table}_id = ct.id)
 
3130                         LEFT JOIN department d  ON (a.department_id = d.id)
 
3132   my $ref          = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
 
3134   map { $self->{$_} = $ref->{$_} } values %column_map;
 
3136   # remove any trailing whitespace
 
3137   $self->{currency} =~ s/\s*$// if $self->{currency};
 
3139   $main::lxdebug->leave_sub();
 
3143   $main::lxdebug->enter_sub();
 
3146   my $myconfig = shift || \%::myconfig;
 
3147   my ($thisdate, $days) = @_;
 
3149   my $dbh = $self->get_standard_dbh($myconfig);
 
3154     my $dateformat = $myconfig->{dateformat};
 
3155     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
 
3156     $thisdate = $dbh->quote($thisdate);
 
3157     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
 
3159     $query = qq|SELECT current_date AS thisdate|;
 
3162   ($thisdate) = selectrow_query($self, $dbh, $query);
 
3164   $main::lxdebug->leave_sub();
 
3170   $main::lxdebug->enter_sub();
 
3172   my ($self, $string) = @_;
 
3174   if ($string !~ /%/) {
 
3175     $string = "%$string%";
 
3178   $string =~ s/\'/\'\'/g;
 
3180   $main::lxdebug->leave_sub();
 
3186   $main::lxdebug->enter_sub();
 
3188   my ($self, $flds, $new, $count, $numrows) = @_;
 
3192   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
 
3197   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
 
3199     my $j = $item->{ndx} - 1;
 
3200     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
 
3204   for $i ($count + 1 .. $numrows) {
 
3205     map { delete $self->{"${_}_$i"} } @{$flds};
 
3208   $main::lxdebug->leave_sub();
 
3212   $main::lxdebug->enter_sub();
 
3214   my ($self, $myconfig) = @_;
 
3218   my $dbh = $self->dbconnect_noauto($myconfig);
 
3220   my $query = qq|DELETE FROM status
 
3221                  WHERE (formname = ?) AND (trans_id = ?)|;
 
3222   my $sth = prepare_query($self, $dbh, $query);
 
3224   if ($self->{formname} =~ /(check|receipt)/) {
 
3225     for $i (1 .. $self->{rowcount}) {
 
3226       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
 
3229     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
 
3233   my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3234   my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3236   my %queued = split / /, $self->{queued};
 
3239   if ($self->{formname} =~ /(check|receipt)/) {
 
3241     # this is a check or receipt, add one entry for each lineitem
 
3242     my ($accno) = split /--/, $self->{account};
 
3243     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
 
3244                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
 
3245     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
 
3246     $sth = prepare_query($self, $dbh, $query);
 
3248     for $i (1 .. $self->{rowcount}) {
 
3249       if ($self->{"checked_$i"}) {
 
3250         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
 
3256     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
3257                 VALUES (?, ?, ?, ?, ?)|;
 
3258     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
 
3259              $queued{$self->{formname}}, $self->{formname});
 
3265   $main::lxdebug->leave_sub();
 
3269   $main::lxdebug->enter_sub();
 
3271   my ($self, $dbh) = @_;
 
3273   my ($query, $printed, $emailed);
 
3275   my $formnames  = $self->{printed};
 
3276   my $emailforms = $self->{emailed};
 
3278   $query = qq|DELETE FROM status
 
3279                  WHERE (formname = ?) AND (trans_id = ?)|;
 
3280   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
 
3282   # this only applies to the forms
 
3283   # checks and receipts are posted when printed or queued
 
3285   if ($self->{queued}) {
 
3286     my %queued = split / /, $self->{queued};
 
3288     foreach my $formname (keys %queued) {
 
3289       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3290       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3292       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
3293                   VALUES (?, ?, ?, ?, ?)|;
 
3294       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
 
3296       $formnames  =~ s/\Q$self->{formname}\E//;
 
3297       $emailforms =~ s/\Q$self->{formname}\E//;
 
3302   # save printed, emailed info
 
3303   $formnames  =~ s/^ +//g;
 
3304   $emailforms =~ s/^ +//g;
 
3307   map { $status{$_}{printed} = 1 } split / +/, $formnames;
 
3308   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
 
3310   foreach my $formname (keys %status) {
 
3311     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3312     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3314     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
 
3315                 VALUES (?, ?, ?, ?)|;
 
3316     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
 
3319   $main::lxdebug->leave_sub();
 
3323 # $main::locale->text('SAVED')
 
3324 # $main::locale->text('DELETED')
 
3325 # $main::locale->text('ADDED')
 
3326 # $main::locale->text('PAYMENT POSTED')
 
3327 # $main::locale->text('POSTED')
 
3328 # $main::locale->text('POSTED AS NEW')
 
3329 # $main::locale->text('ELSE')
 
3330 # $main::locale->text('SAVED FOR DUNNING')
 
3331 # $main::locale->text('DUNNING STARTED')
 
3332 # $main::locale->text('PRINTED')
 
3333 # $main::locale->text('MAILED')
 
3334 # $main::locale->text('SCREENED')
 
3335 # $main::locale->text('CANCELED')
 
3336 # $main::locale->text('invoice')
 
3337 # $main::locale->text('proforma')
 
3338 # $main::locale->text('sales_order')
 
3339 # $main::locale->text('pick_list')
 
3340 # $main::locale->text('purchase_order')
 
3341 # $main::locale->text('bin_list')
 
3342 # $main::locale->text('sales_quotation')
 
3343 # $main::locale->text('request_quotation')
 
3346   $main::lxdebug->enter_sub();
 
3349   my $dbh  = shift || $self->get_standard_dbh;
 
3351   if(!exists $self->{employee_id}) {
 
3352     &get_employee($self, $dbh);
 
3356    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
 
3357    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
 
3358   my @values = (conv_i($self->{id}), $self->{login},
 
3359                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
 
3360   do_query($self, $dbh, $query, @values);
 
3364   $main::lxdebug->leave_sub();
 
3368   $main::lxdebug->enter_sub();
 
3370   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
 
3371   my ($orderBy, $desc) = split(/\-\-/, $order);
 
3372   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
 
3375   if ($trans_id ne "") {
 
3377       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 | .
 
3378       qq|FROM history_erp h | .
 
3379       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
 
3380       qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
 
3383     my $sth = $dbh->prepare($query) || $self->dberror($query);
 
3385     $sth->execute() || $self->dberror("$query");
 
3387     while(my $hash_ref = $sth->fetchrow_hashref()) {
 
3388       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
 
3389       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
 
3390       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
 
3391       $tempArray[$i++] = $hash_ref;
 
3393     $main::lxdebug->leave_sub() and return \@tempArray
 
3394       if ($i > 0 && $tempArray[0] ne "");
 
3396   $main::lxdebug->leave_sub();
 
3400 sub update_defaults {
 
3401   $main::lxdebug->enter_sub();
 
3403   my ($self, $myconfig, $fld, $provided_dbh) = @_;
 
3406   if ($provided_dbh) {
 
3407     $dbh = $provided_dbh;
 
3409     $dbh = $self->dbconnect_noauto($myconfig);
 
3411   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
 
3412   my $sth   = $dbh->prepare($query);
 
3414   $sth->execute || $self->dberror($query);
 
3415   my ($var) = $sth->fetchrow_array;
 
3418   if ($var =~ m/\d+$/) {
 
3419     my $new_var  = (substr $var, $-[0]) * 1 + 1;
 
3420     my $len_diff = length($var) - $-[0] - length($new_var);
 
3421     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
 
3427   $query = qq|UPDATE defaults SET $fld = ?|;
 
3428   do_query($self, $dbh, $query, $var);
 
3430   if (!$provided_dbh) {
 
3435   $main::lxdebug->leave_sub();
 
3440 sub update_business {
 
3441   $main::lxdebug->enter_sub();
 
3443   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
 
3446   if ($provided_dbh) {
 
3447     $dbh = $provided_dbh;
 
3449     $dbh = $self->dbconnect_noauto($myconfig);
 
3452     qq|SELECT customernumberinit FROM business
 
3453        WHERE id = ? FOR UPDATE|;
 
3454   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
 
3456   return undef unless $var;
 
3458   if ($var =~ m/\d+$/) {
 
3459     my $new_var  = (substr $var, $-[0]) * 1 + 1;
 
3460     my $len_diff = length($var) - $-[0] - length($new_var);
 
3461     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
 
3467   $query = qq|UPDATE business
 
3468               SET customernumberinit = ?
 
3470   do_query($self, $dbh, $query, $var, $business_id);
 
3472   if (!$provided_dbh) {
 
3477   $main::lxdebug->leave_sub();
 
3482 sub get_partsgroup {
 
3483   $main::lxdebug->enter_sub();
 
3485   my ($self, $myconfig, $p) = @_;
 
3486   my $target = $p->{target} || 'all_partsgroup';
 
3488   my $dbh = $self->get_standard_dbh($myconfig);
 
3490   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
 
3492                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
 
3495   if ($p->{searchitems} eq 'part') {
 
3496     $query .= qq|WHERE p.inventory_accno_id > 0|;
 
3498   if ($p->{searchitems} eq 'service') {
 
3499     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
 
3501   if ($p->{searchitems} eq 'assembly') {
 
3502     $query .= qq|WHERE p.assembly = '1'|;
 
3504   if ($p->{searchitems} eq 'labor') {
 
3505     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
 
3508   $query .= qq|ORDER BY partsgroup|;
 
3511     $query = qq|SELECT id, partsgroup FROM partsgroup
 
3512                 ORDER BY partsgroup|;
 
3515   if ($p->{language_code}) {
 
3516     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
 
3517                   t.description AS translation
 
3519                 JOIN parts p ON (p.partsgroup_id = pg.id)
 
3520                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
 
3521                 ORDER BY translation|;
 
3522     @values = ($p->{language_code});
 
3525   $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
 
3527   $main::lxdebug->leave_sub();
 
3530 sub get_pricegroup {
 
3531   $main::lxdebug->enter_sub();
 
3533   my ($self, $myconfig, $p) = @_;
 
3535   my $dbh = $self->get_standard_dbh($myconfig);
 
3537   my $query = qq|SELECT p.id, p.pricegroup
 
3540   $query .= qq| ORDER BY pricegroup|;
 
3543     $query = qq|SELECT id, pricegroup FROM pricegroup
 
3544                 ORDER BY pricegroup|;
 
3547   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
 
3549   $main::lxdebug->leave_sub();
 
3553 # usage $form->all_years($myconfig, [$dbh])
 
3554 # return list of all years where bookings found
 
3557   $main::lxdebug->enter_sub();
 
3559   my ($self, $myconfig, $dbh) = @_;
 
3561   $dbh ||= $self->get_standard_dbh($myconfig);
 
3564   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
 
3565                    (SELECT MAX(transdate) FROM acc_trans)|;
 
3566   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
 
3568   if ($myconfig->{dateformat} =~ /^yy/) {
 
3569     ($startdate) = split /\W/, $startdate;
 
3570     ($enddate) = split /\W/, $enddate;
 
3572     (@_) = split /\W/, $startdate;
 
3574     (@_) = split /\W/, $enddate;
 
3579   $startdate = substr($startdate,0,4);
 
3580   $enddate = substr($enddate,0,4);
 
3582   while ($enddate >= $startdate) {
 
3583     push @all_years, $enddate--;
 
3588   $main::lxdebug->leave_sub();
 
3592   $main::lxdebug->enter_sub();
 
3596   map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
 
3598   $main::lxdebug->leave_sub();
 
3602   $main::lxdebug->enter_sub();
 
3607   map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
 
3609   $main::lxdebug->leave_sub();
 
3612 sub prepare_for_printing {
 
3615   $self->{templates} ||= $::myconfig{templates};
 
3616   $self->{formname}  ||= $self->{type};
 
3617   $self->{media}     ||= 'email';
 
3619   die "'media' other than 'email', 'file', 'printer' is not supported yet" unless $self->{media} =~ m/^(?:email|file|printer)$/;
 
3621   # set shipto from billto unless set
 
3622   my $has_shipto = any { $self->{"shipto$_"} } qw(name street zipcode city country contact);
 
3623   if (!$has_shipto && ($self->{type} =~ m/^(?:purchase_order|request_quotation)$/)) {
 
3624     $self->{shiptoname}   = $::myconfig{company};
 
3625     $self->{shiptostreet} = $::myconfig{address};
 
3628   my $language = $self->{language} ? '_' . $self->{language} : '';
 
3630   my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
 
3631   if ($self->{language_id}) {
 
3632     ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) = AM->get_language_details(\%::myconfig, $self, $self->{language_id});
 
3634     $output_dateformat   = $::myconfig{dateformat};
 
3635     $output_numberformat = $::myconfig{numberformat};
 
3636     $output_longdates    = 1;
 
3639   # Retrieve accounts for tax calculation.
 
3640   IC->retrieve_accounts(\%::myconfig, $self, map { $_ => $self->{"id_$_"} } 1 .. $self->{rowcount});
 
3642   if ($self->{type} =~ /_delivery_order$/) {
 
3643     DO->order_details();
 
3644   } elsif ($self->{type} =~ /sales_order|sales_quotation|request_quotation|purchase_order/) {
 
3645     OE->order_details(\%::myconfig, $self);
 
3647     IS->invoice_details(\%::myconfig, $self, $::locale);
 
3650   # Chose extension & set source file name
 
3651   my $extension = 'html';
 
3652   if ($self->{format} eq 'postscript') {
 
3653     $self->{postscript}   = 1;
 
3655   } elsif ($self->{"format"} =~ /pdf/) {
 
3657     $extension            = $self->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
 
3658   } elsif ($self->{"format"} =~ /opendocument/) {
 
3659     $self->{opendocument} = 1;
 
3661   } elsif ($self->{"format"} =~ /excel/) {
 
3666   my $printer_code    = '_' . $self->{printer_code} if $self->{printer_code};
 
3667   my $email_extension = '_email' if -f "$self->{templates}/$self->{formname}_email${language}${printer_code}.${extension}";
 
3668   $self->{IN}         = "$self->{formname}${email_extension}${language}${printer_code}.${extension}";
 
3671   $self->format_dates($output_dateformat, $output_longdates,
 
3672                       qw(invdate orddate quodate pldate duedate reqdate transdate shippingdate deliverydate validitydate paymentdate datepaid
 
3673                          transdate_oe deliverydate_oe employee_startdate employee_enddate),
 
3674                       grep({ /^(?:datepaid|transdate_oe|reqdate|deliverydate|deliverydate_oe|transdate)_\d+$/ } keys(%{$self})));
 
3676   $self->reformat_numbers($output_numberformat, 2,
 
3677                           qw(invtotal ordtotal quototal subtotal linetotal listprice sellprice netprice discount tax taxbase total paid),
 
3678                           grep({ /^(?:linetotal|listprice|sellprice|netprice|taxbase|discount|paid|subtotal|total|tax)_\d+$/ } keys(%{$self})));
 
3680   $self->reformat_numbers($output_numberformat, undef, qw(qty price_factor), grep({ /^qty_\d+$/} keys(%{$self})));
 
3682   my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
 
3684   if (scalar @{ $cvar_date_fields }) {
 
3685     $self->format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
 
3688   while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
 
3689     $self->reformat_numbers($output_numberformat, $precision, @{ $field_list });
 
3696   my ($self, $dateformat, $longformat, @indices) = @_;
 
3698   $dateformat ||= $::myconfig{dateformat};
 
3700   foreach my $idx (@indices) {
 
3701     if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
 
3702       for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
 
3703         $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $dateformat, $longformat);
 
3707     next unless defined $self->{$idx};
 
3709     if (!ref($self->{$idx})) {
 
3710       $self->{$idx} = $::locale->reformat_date(\%::myconfig, $self->{$idx}, $dateformat, $longformat);
 
3712     } elsif (ref($self->{$idx}) eq "ARRAY") {
 
3713       for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
 
3714         $self->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{$idx}->[$i], $dateformat, $longformat);
 
3720 sub reformat_numbers {
 
3721   my ($self, $numberformat, $places, @indices) = @_;
 
3723   return if !$numberformat || ($numberformat eq $::myconfig{numberformat});
 
3725   foreach my $idx (@indices) {
 
3726     if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
 
3727       for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
 
3728         $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i]);
 
3732     next unless defined $self->{$idx};
 
3734     if (!ref($self->{$idx})) {
 
3735       $self->{$idx} = $self->parse_amount(\%::myconfig, $self->{$idx});
 
3737     } elsif (ref($self->{$idx}) eq "ARRAY") {
 
3738       for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
 
3739         $self->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{$idx}->[$i]);
 
3744   my $saved_numberformat    = $::myconfig{numberformat};
 
3745   $::myconfig{numberformat} = $numberformat;
 
3747   foreach my $idx (@indices) {
 
3748     if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
 
3749       for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
 
3750         $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $places);
 
3754     next unless defined $self->{$idx};
 
3756     if (!ref($self->{$idx})) {
 
3757       $self->{$idx} = $self->format_amount(\%::myconfig, $self->{$idx}, $places);
 
3759     } elsif (ref($self->{$idx}) eq "ARRAY") {
 
3760       for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
 
3761         $self->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{$idx}->[$i], $places);
 
3766   $::myconfig{numberformat} = $saved_numberformat;
 
3775 SL::Form.pm - main data object.
 
3779 This is the main data object of Lx-Office.
 
3780 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
 
3781 Points of interest for a beginner are:
 
3783  - $form->error            - renders a generic error in html. accepts an error message
 
3784  - $form->get_standard_dbh - returns a database connection for the
 
3786 =head1 SPECIAL FUNCTIONS
 
3788 =head2 C<_store_value()>
 
3790 parses a complex var name, and stores it in the form.
 
3793   $form->_store_value($key, $value);
 
3795 keys must start with a string, and can contain various tokens.
 
3796 supported key structures are:
 
3799   simple key strings work as expected
 
3804   separating two keys by a dot (.) will result in a hash lookup for the inner value
 
3805   this is similar to the behaviour of java and templating mechanisms.
 
3807   filter.description => $form->{filter}->{description}
 
3809 3. array+hashref access
 
3811   adding brackets ([]) before the dot will cause the next hash to be put into an array.
 
3812   using [+] instead of [] will force a new array index. this is useful for recurring
 
3813   data structures like part lists. put a [+] into the first varname, and use [] on the
 
3816   repeating these names in your template:
 
3819     invoice.items[].parts_id
 
3823     $form->{invoice}->{items}->[
 
3837   using brackets at the end of a name will result in a pure array to be created.
 
3838   note that you mustn't use [+], which is reserved for array+hash access and will
 
3839   result in undefined behaviour in array context.
 
3841   filter.status[]  => $form->{status}->[ val1, val2, ... ]
 
3843 =head2 C<update_business> PARAMS
 
3846  \%config,     - config hashref
 
3847  $business_id, - business id
 
3848  $dbh          - optional database handle
 
3850 handles business (thats customer/vendor types) sequences.
 
3852 special behaviour for empty strings in customerinitnumber field:
 
3853 will in this case not increase the value, and return undef.
 
3855 =head2 C<redirect_header> $url
 
3857 Generates a HTTP redirection header for the new C<$url>. Constructs an
 
3858 absolute URL including scheme, host name and port. If C<$url> is a
 
3859 relative URL then it is considered relative to Lx-Office base URL.
 
3861 This function C<die>s if headers have already been created with
 
3862 C<$::form-E<gt>header>.
 
3866   print $::form->redirect_header('oe.pl?action=edit&id=1234');
 
3867   print $::form->redirect_header('http://www.lx-office.org/');
 
3871 Generates a general purpose http/html header and includes most of the scripts
 
3872 and stylesheets needed. Stylesheets can be added with L<use_stylesheet>.
 
3874 Only one header will be generated. If the method was already called in this
 
3875 request it will not output anything and return undef. Also if no
 
3876 HTTP_USER_AGENT is found, no header is generated.
 
3878 Although header does not accept parameters itself, it will honor special
 
3879 hashkeys of its Form instance:
 
3887 If one of these is set, a http-equiv refresh is generated. Missing parameters
 
3888 default to 3 seconds and the refering url.
 
3892 Either a scalar or an array ref. Will be inlined into the header. Add
 
3893 stylesheets with the L<use_stylesheet> function.
 
3897 If true, a css snippet will be generated that sets the page in landscape mode.
 
3901 Used to override the default favicon.
 
3905 A html page title will be generated from this