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 #======================================================================
 
  58 use List::Util qw(first max min sum);
 
  59 use List::MoreUtils qw(any);
 
  66   disconnect_standard_dbh();
 
  69 sub disconnect_standard_dbh {
 
  70   return unless $standard_dbh;
 
  71   $standard_dbh->disconnect();
 
  76   $main::lxdebug->enter_sub(2);
 
  82   my @tokens = split /((?:\[\+?\])?(?:\.|$))/, $key;
 
  87      $curr = \ $self->{ shift @tokens };
 
  91     my $sep = shift @tokens;
 
  92     my $key = shift @tokens;
 
  94     $curr = \ $$curr->[++$#$$curr], next if $sep eq '[]';
 
  95     $curr = \ $$curr->[max 0, $#$$curr]  if $sep eq '[].';
 
  96     $curr = \ $$curr->[++$#$$curr]       if $sep eq '[+].';
 
  97     $curr = \ $$curr->{$key}
 
 102   $main::lxdebug->leave_sub(2);
 
 108   $main::lxdebug->enter_sub(2);
 
 113   my @pairs = split(/&/, $input);
 
 116     my ($key, $value) = split(/=/, $_, 2);
 
 117     $self->_store_value($self->unescape($key), $self->unescape($value)) if ($key);
 
 120   $main::lxdebug->leave_sub(2);
 
 123 sub _request_to_hash {
 
 124   $main::lxdebug->enter_sub(2);
 
 129   if (!$ENV{'CONTENT_TYPE'}
 
 130       || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
 
 132     $self->_input_to_hash($input);
 
 134     $main::lxdebug->leave_sub(2);
 
 138   my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr, $previous);
 
 140   my $boundary = '--' . $1;
 
 142   foreach my $line (split m/\n/, $input) {
 
 143     last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
 
 145     if (($line eq $boundary) || ($line eq "$boundary\r")) {
 
 146       ${ $previous } =~ s|\r?\n$|| if $previous;
 
 152       $content_type   = "text/plain";
 
 159     next unless $boundary_found;
 
 161     if (!$headers_done) {
 
 162       $line =~ s/[\r\n]*$//;
 
 169       if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
 
 170         if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
 
 172           substr $line, $-[0], $+[0] - $-[0], "";
 
 175         if ($line =~ m|name\s*=\s*"(.*?)"|i) {
 
 177           substr $line, $-[0], $+[0] - $-[0], "";
 
 180         $previous         = $self->_store_value($name, '') if ($name);
 
 181         $self->{FILENAME} = $filename if ($filename);
 
 186       if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
 
 193     next unless $previous;
 
 195     ${ $previous } .= "${line}\n";
 
 198   ${ $previous } =~ s|\r?\n$|| if $previous;
 
 200   $main::lxdebug->leave_sub(2);
 
 203 sub _recode_recursively {
 
 204   $main::lxdebug->enter_sub();
 
 205   my ($iconv, $param) = @_;
 
 207   if (any { ref $param eq $_ } qw(Form HASH)) {
 
 208     foreach my $key (keys %{ $param }) {
 
 209       if (!ref $param->{$key}) {
 
 210         # Workaround for a bug: converting $param->{$key} directly
 
 211         # leads to 'undef'. I don't know why. Converting a copy works,
 
 213         $param->{$key} = $iconv->convert("" . $param->{$key});
 
 215         _recode_recursively($iconv, $param->{$key});
 
 219   } elsif (ref $param eq 'ARRAY') {
 
 220     foreach my $idx (0 .. scalar(@{ $param }) - 1) {
 
 221       if (!ref $param->[$idx]) {
 
 222         # Workaround for a bug: converting $param->[$idx] directly
 
 223         # leads to 'undef'. I don't know why. Converting a copy works,
 
 225         $param->[$idx] = $iconv->convert("" . $param->[$idx]);
 
 227         _recode_recursively($iconv, $param->[$idx]);
 
 231   $main::lxdebug->leave_sub();
 
 235   $main::lxdebug->enter_sub();
 
 241   if ($LXDebug::watch_form) {
 
 242     require SL::Watchdog;
 
 243     tie %{ $self }, 'SL::Watchdog';
 
 248   $self->_input_to_hash($ENV{QUERY_STRING}) if $ENV{QUERY_STRING};
 
 249   $self->_input_to_hash($ARGV[0])           if @ARGV && $ARGV[0];
 
 251   if ($ENV{CONTENT_LENGTH}) {
 
 253     read STDIN, $content, $ENV{CONTENT_LENGTH};
 
 254     $self->_request_to_hash($content);
 
 257   my $db_charset   = $main::dbcharset;
 
 258   $db_charset    ||= Common::DEFAULT_CHARSET;
 
 260   my $encoding     = $self->{INPUT_ENCODING} || $db_charset;
 
 261   delete $self->{INPUT_ENCODING};
 
 263   _recode_recursively(SL::Iconv->new($encoding, $db_charset), $self);
 
 265   $self->{action}  =  lc $self->{action};
 
 266   $self->{action}  =~ s/( |-|,|\#)/_/g;
 
 268   #$self->{version} =  "2.6.1";                 # Old hardcoded but secure style
 
 269   open VERSION_FILE, "VERSION";                 # New but flexible code reads version from VERSION-file
 
 270   $self->{version} =  <VERSION_FILE>;
 
 272   $self->{version}  =~ s/[^0-9A-Za-z\.\_\-]//g; # only allow numbers, letters, points, underscores and dashes. Prevents injecting of malicious code.
 
 274   $main::lxdebug->leave_sub();
 
 279 sub _flatten_variables_rec {
 
 280   $main::lxdebug->enter_sub(2);
 
 289   if ('' eq ref $curr->{$key}) {
 
 290     @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
 
 292   } elsif ('HASH' eq ref $curr->{$key}) {
 
 293     foreach my $hash_key (sort keys %{ $curr->{$key} }) {
 
 294       push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
 
 298     foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
 
 299       my $first_array_entry = 1;
 
 301       foreach my $hash_key (sort keys %{ $curr->{$key}->[$idx] }) {
 
 302         push @result, $self->_flatten_variables_rec($curr->{$key}->[$idx], $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
 
 303         $first_array_entry = 0;
 
 308   $main::lxdebug->leave_sub(2);
 
 313 sub flatten_variables {
 
 314   $main::lxdebug->enter_sub(2);
 
 322     push @variables, $self->_flatten_variables_rec($self, '', $_);
 
 325   $main::lxdebug->leave_sub(2);
 
 330 sub flatten_standard_variables {
 
 331   $main::lxdebug->enter_sub(2);
 
 334   my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar version), @_);
 
 338   foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
 
 339     push @variables, $self->_flatten_variables_rec($self, '', $_);
 
 342   $main::lxdebug->leave_sub(2);
 
 348   $main::lxdebug->enter_sub();
 
 354   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
 
 356   $main::lxdebug->leave_sub();
 
 360   $main::lxdebug->enter_sub(2);
 
 363   my $password      = $self->{password};
 
 365   $self->{password} = 'X' x 8;
 
 367   local $Data::Dumper::Sortkeys = 1;
 
 368   my $output                    = Dumper($self);
 
 370   $self->{password} = $password;
 
 372   $main::lxdebug->leave_sub(2);
 
 378   $main::lxdebug->enter_sub(2);
 
 380   my ($self, $str) = @_;
 
 382   $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
 
 384   $main::lxdebug->leave_sub(2);
 
 390   $main::lxdebug->enter_sub(2);
 
 392   my ($self, $str) = @_;
 
 397   $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
 
 399   $main::lxdebug->leave_sub(2);
 
 405   $main::lxdebug->enter_sub();
 
 406   my ($self, $str) = @_;
 
 408   if ($str && !ref($str)) {
 
 409     $str =~ s/\"/"/g;
 
 412   $main::lxdebug->leave_sub();
 
 418   $main::lxdebug->enter_sub();
 
 419   my ($self, $str) = @_;
 
 421   if ($str && !ref($str)) {
 
 422     $str =~ s/"/\"/g;
 
 425   $main::lxdebug->leave_sub();
 
 431   $main::lxdebug->enter_sub();
 
 435     map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
 
 437     for (sort keys %$self) {
 
 438       next if (($_ eq "header") || (ref($self->{$_}) ne ""));
 
 439       print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
 
 442   $main::lxdebug->leave_sub();
 
 446   $main::lxdebug->enter_sub();
 
 448   $main::lxdebug->show_backtrace();
 
 450   my ($self, $msg) = @_;
 
 451   if ($ENV{HTTP_USER_AGENT}) {
 
 453     $self->show_generic_error($msg);
 
 456     print STDERR "Error: $msg\n";
 
 460   $main::lxdebug->leave_sub();
 
 464   $main::lxdebug->enter_sub();
 
 466   my ($self, $msg) = @_;
 
 468   if ($ENV{HTTP_USER_AGENT}) {
 
 471     if (!$self->{header}) {
 
 477     <p class="message_ok"><b>$msg</b></p>
 
 479     <script type="text/javascript">
 
 481     // If JavaScript is enabled, the whole thing will be reloaded.
 
 482     // The reason is: When one changes his menu setup (HTML / XUL / CSS ...)
 
 483     // it now loads the correct code into the browser instead of do nothing.
 
 484     setTimeout("top.frames.location.href='login.pl'",500);
 
 493     if ($self->{info_function}) {
 
 494       &{ $self->{info_function} }($msg);
 
 500   $main::lxdebug->leave_sub();
 
 503 # calculates the number of rows in a textarea based on the content and column number
 
 504 # can be capped with maxrows
 
 506   $main::lxdebug->enter_sub();
 
 507   my ($self, $str, $cols, $maxrows, $minrows) = @_;
 
 511   my $rows   = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
 
 514   $main::lxdebug->leave_sub();
 
 516   return max(min($rows, $maxrows), $minrows);
 
 520   $main::lxdebug->enter_sub();
 
 522   my ($self, $msg) = @_;
 
 524   $self->error("$msg\n" . $DBI::errstr);
 
 526   $main::lxdebug->leave_sub();
 
 530   $main::lxdebug->enter_sub();
 
 532   my ($self, $name, $msg) = @_;
 
 535   foreach my $part (split m/\./, $name) {
 
 536     if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
 
 539     $curr = $curr->{$part};
 
 542   $main::lxdebug->leave_sub();
 
 545 sub _get_request_uri {
 
 548   return URI->new($ENV{HTTP_REFERER})->canonical() if $ENV{HTTP_X_FORWARDED_FOR};
 
 550   my $scheme =  $ENV{HTTPS} && (lc $ENV{HTTPS} eq 'on') ? 'https' : 'http';
 
 551   my $port   =  $ENV{SERVER_PORT} || '';
 
 552   $port      =  undef if (($scheme eq 'http' ) && ($port == 80))
 
 553                       || (($scheme eq 'https') && ($port == 443));
 
 555   my $uri    =  URI->new("${scheme}://");
 
 556   $uri->scheme($scheme);
 
 558   $uri->host($ENV{HTTP_HOST} || $ENV{SERVER_ADDR});
 
 559   $uri->path_query($ENV{REQUEST_URI});
 
 565 sub _add_to_request_uri {
 
 568   my $relative_new_path = shift;
 
 569   my $request_uri       = shift || $self->_get_request_uri;
 
 570   my $relative_new_uri  = URI->new($relative_new_path);
 
 571   my @request_segments  = $request_uri->path_segments;
 
 573   my $new_uri           = $request_uri->clone;
 
 574   $new_uri->path_segments(@request_segments[0..scalar(@request_segments) - 2], $relative_new_uri->path_segments);
 
 579 sub create_http_response {
 
 580   $main::lxdebug->enter_sub();
 
 585   my $cgi      = $main::cgi;
 
 586   $cgi       ||= CGI->new('');
 
 589   if (defined $main::auth) {
 
 590     my $uri      = $self->_get_request_uri;
 
 591     my @segments = $uri->path_segments;
 
 593     $uri->path_segments(@segments);
 
 595     my $session_cookie_value   = $main::auth->get_session_id();
 
 596     $session_cookie_value    ||= 'NO_SESSION';
 
 598     $session_cookie = $cgi->cookie('-name'   => $main::auth->get_session_cookie_name(),
 
 599                                    '-value'  => $session_cookie_value,
 
 600                                    '-path'   => $uri->path,
 
 601                                    '-secure' => $ENV{HTTPS});
 
 604   my %cgi_params = ('-type' => $params{content_type});
 
 605   $cgi_params{'-charset'} = $params{charset} if ($params{charset});
 
 607   my $output = $cgi->header('-cookie' => $session_cookie,
 
 610   $main::lxdebug->leave_sub();
 
 617   $main::lxdebug->enter_sub();
 
 619   # extra code ist currently only used by menuv3 and menuv4 to set their css.
 
 620   # it is strongly deprecated, and will be changed in a future version.
 
 621   my ($self, $extra_code) = @_;
 
 623   if ($self->{header}) {
 
 624     $main::lxdebug->leave_sub();
 
 628   my ($stylesheet, $favicon, $pagelayout);
 
 630   if ($ENV{HTTP_USER_AGENT}) {
 
 633     if ($ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+\d/) {
 
 634       # Only set the DOCTYPE for Internet Explorer. Other browsers have problems displaying the menu otherwise.
 
 635       $doctype = qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n|;
 
 638     my $stylesheets = "$self->{stylesheet} $self->{stylesheets}";
 
 640     $stylesheets =~ s|^\s*||;
 
 641     $stylesheets =~ s|\s*$||;
 
 642     foreach my $file (split m/\s+/, $stylesheets) {
 
 644       next if (! -f "css/$file");
 
 646       $stylesheet .= qq|<link rel="stylesheet" href="css/$file" TYPE="text/css" TITLE="Lx-Office stylesheet">\n|;
 
 649     $self->{favicon}    = "favicon.ico" unless $self->{favicon};
 
 651     if ($self->{favicon} && (-f "$self->{favicon}")) {
 
 653         qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
 
 657     my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
 659     if ($self->{landscape}) {
 
 660       $pagelayout = qq|<style type="text/css">
 
 661                         \@page { size:landscape; }
 
 666     <script type="text/javascript">
 
 669         document.$self->{fokus}.focus();
 
 673     | if $self->{"fokus"};
 
 675   # if there is a title, we put some JavaScript in to the page, wich writes a 
 
 676   # meaningful title-tag for our frameset.
 
 678     if ($self->{"title"}){
 
 680                 <script type="text/javascript">
 
 682                   // Write a meaningful title-tag for our frameset.
 
 683                   top.document.title="| . $self->{"title"} . qq| - | . $self->{"login"} . qq| - | . $::myconfig{dbname} . qq| - Ver. | . $self->{"version"} . qq|";
 
 691     if ($self->{jsscript} == 1) {
 
 694         <script type="text/javascript" src="js/jquery.js"></script>
 
 695         <script type="text/javascript" src="js/common.js"></script>
 
 696         <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
 
 697         <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
 
 698         <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
 
 699         <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
 
 706       ? "$self->{title} - $self->{titlebar}"
 
 709     for my $item (@ { $self->{AJAX} || [] }) {
 
 710       $ajax .= $item->show_javascript();
 
 713     print $self->create_http_response('content_type' => 'text/html',
 
 714                                       'charset'      => $db_charset,);
 
 715     print qq|${doctype}<html>
 
 717   <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
 
 718   <title>$self->{titlebar}</title>
 
 727   <link rel="stylesheet" href="css/jquery.autocomplete.css" type="text/css" />
 
 729   <meta name="robots" content="noindex,nofollow" />
 
 730   <script type="text/javascript" src="js/highlight_input.js"></script>
 
 732   <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
 
 733   <script type="text/javascript" src="js/tabcontent.js">
 
 735   /***********************************************
 
 736    * Tab Content script v2.2- Â© Dynamic Drive DHTML code library (www.dynamicdrive.com)
 
 737    * This notice MUST stay intact for legal use
 
 738    * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
 
 739    ***********************************************/
 
 750   $main::lxdebug->leave_sub();
 
 753 sub ajax_response_header {
 
 754   $main::lxdebug->enter_sub();
 
 758   my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
 759   my $cgi        = $main::cgi || CGI->new('');
 
 760   my $output     = $cgi->header('-charset' => $db_charset);
 
 762   $main::lxdebug->leave_sub();
 
 767 sub redirect_header {
 
 771   my $base_uri = $self->_get_request_uri;
 
 772   my $new_uri  = URI->new_abs($new_url, $base_uri);
 
 774   die "Headers already sent" if $::self->{header};
 
 777   my $cgi = $main::cgi || CGI->new('');
 
 778   return $cgi->redirect($new_uri);
 
 781 sub set_standard_title {
 
 782   $::lxdebug->enter_sub;
 
 785   $self->{titlebar}  = "Lx-Office " . $::locale->text('Version') . " $self->{version}";
 
 786   $self->{titlebar} .= "- $::myconfig{name}"   if $::myconfig{name};
 
 787   $self->{titlebar} .= "- $::myconfig{dbname}" if $::myconfig{name};
 
 789   $::lxdebug->leave_sub;
 
 792 sub _prepare_html_template {
 
 793   $main::lxdebug->enter_sub();
 
 795   my ($self, $file, $additional_params) = @_;
 
 798   if (!%::myconfig || !$::myconfig{"countrycode"}) {
 
 799     $language = $main::language;
 
 801     $language = $main::myconfig{"countrycode"};
 
 803   $language = "de" unless ($language);
 
 805   if (-f "templates/webpages/${file}.html") {
 
 806     if ((-f ".developer") && ((stat("templates/webpages/${file}.html"))[9] > (stat("locale/${language}/all"))[9])) {
 
 807       my $info = "Developer information: templates/webpages/${file}.html is newer than the translation file locale/${language}/all.\n" .
 
 808         "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 809       print(qq|<pre>$info</pre>|);
 
 813     $file = "templates/webpages/${file}.html";
 
 816     my $info = "Web page template '${file}' not found.\n" .
 
 817       "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 818     print(qq|<pre>$info</pre>|);
 
 822   if ($self->{"DEBUG"}) {
 
 823     $additional_params->{"DEBUG"} = $self->{"DEBUG"};
 
 826   if ($additional_params->{"DEBUG"}) {
 
 827     $additional_params->{"DEBUG"} =
 
 828       "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
 
 831   if (%main::myconfig) {
 
 832     map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
 
 833     my $jsc_dateformat = $main::myconfig{"dateformat"};
 
 834     $jsc_dateformat =~ s/d+/\%d/gi;
 
 835     $jsc_dateformat =~ s/m+/\%m/gi;
 
 836     $jsc_dateformat =~ s/y+/\%Y/gi;
 
 837     $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
 
 838     $additional_params->{"myconfig"} ||= \%::myconfig;
 
 841   $additional_params->{"conf_dbcharset"}              = $main::dbcharset;
 
 842   $additional_params->{"conf_webdav"}                 = $main::webdav;
 
 843   $additional_params->{"conf_lizenzen"}               = $main::lizenzen;
 
 844   $additional_params->{"conf_latex_templates"}        = $main::latex;
 
 845   $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
 
 846   $additional_params->{"conf_vertreter"}              = $main::vertreter;
 
 847   $additional_params->{"conf_show_best_before"}       = $main::show_best_before;
 
 849   if (%main::debug_options) {
 
 850     map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
 
 853   if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
 
 854     while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
 
 855       $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
 
 859   $main::lxdebug->leave_sub();
 
 864 sub parse_html_template {
 
 865   $main::lxdebug->enter_sub();
 
 867   my ($self, $file, $additional_params) = @_;
 
 869   $additional_params ||= { };
 
 871   my $real_file = $self->_prepare_html_template($file, $additional_params);
 
 872   my $template  = $self->template || $self->init_template;
 
 874   map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
 
 877   $template->process($real_file, $additional_params, \$output) || die $template->error;
 
 879   $main::lxdebug->leave_sub();
 
 887   return if $self->template;
 
 889   return $self->template(Template->new({
 
 894      'PLUGIN_BASE'  => 'SL::Template::Plugin',
 
 895      'INCLUDE_PATH' => '.:templates/webpages',
 
 896      'COMPILE_EXT'  => '.tcc',
 
 897      'COMPILE_DIR'  => $::userspath . '/templates-cache',
 
 903   $self->{template_object} = shift if @_;
 
 904   return $self->{template_object};
 
 907 sub show_generic_error {
 
 908   $main::lxdebug->enter_sub();
 
 910   my ($self, $error, %params) = @_;
 
 913     'title_error' => $params{title},
 
 914     'label_error' => $error,
 
 917   if ($params{action}) {
 
 920     map { delete($self->{$_}); } qw(action);
 
 921     map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
 
 923     $add_params->{SHOW_BUTTON}  = 1;
 
 924     $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
 
 925     $add_params->{VARIABLES}    = \@vars;
 
 927   } elsif ($params{back_button}) {
 
 928     $add_params->{SHOW_BACK_BUTTON} = 1;
 
 931   $self->{title} = $params{title} if $params{title};
 
 934   print $self->parse_html_template("generic/error", $add_params);
 
 936   print STDERR "Error: $error\n";
 
 938   $main::lxdebug->leave_sub();
 
 943 sub show_generic_information {
 
 944   $main::lxdebug->enter_sub();
 
 946   my ($self, $text, $title) = @_;
 
 949     'title_information' => $title,
 
 950     'label_information' => $text,
 
 953   $self->{title} = $title if ($title);
 
 956   print $self->parse_html_template("generic/information", $add_params);
 
 958   $main::lxdebug->leave_sub();
 
 963 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
 
 964 # changed it to accept an arbitrary number of triggers - sschoeling
 
 966   $main::lxdebug->enter_sub();
 
 969   my $myconfig = shift;
 
 972   # set dateform for jsscript
 
 975     "dd.mm.yy" => "%d.%m.%Y",
 
 976     "dd-mm-yy" => "%d-%m-%Y",
 
 977     "dd/mm/yy" => "%d/%m/%Y",
 
 978     "mm/dd/yy" => "%m/%d/%Y",
 
 979     "mm-dd-yy" => "%m-%d-%Y",
 
 980     "yyyy-mm-dd" => "%Y-%m-%d",
 
 983   my $ifFormat = defined($dateformats{$myconfig->{"dateformat"}}) ?
 
 984     $dateformats{$myconfig->{"dateformat"}} : "%d.%m.%Y";
 
 991       inputField : "| . (shift) . qq|",
 
 992       ifFormat :"$ifFormat",
 
 993       align : "| .  (shift) . qq|",
 
 994       button : "| . (shift) . qq|"
 
1000        <script type="text/javascript">
 
1001        <!--| . join("", @triggers) . qq|//-->
 
1005   $main::lxdebug->leave_sub();
 
1008 }    #end sub write_trigger
 
1011   $main::lxdebug->enter_sub();
 
1013   my ($self, $msg) = @_;
 
1015   if (!$self->{callback}) {
 
1021 #  my ($script, $argv) = split(/\?/, $self->{callback}, 2);
 
1022 #  $script =~ s|.*/||;
 
1023 #  $script =~ s|[^a-zA-Z0-9_\.]||g;
 
1024 #  exec("perl", "$script", $argv);
 
1026   print $::form->redirect_header($self->{callback});
 
1028   $main::lxdebug->leave_sub();
 
1031 # sort of columns removed - empty sub
 
1033   $main::lxdebug->enter_sub();
 
1035   my ($self, @columns) = @_;
 
1037   $main::lxdebug->leave_sub();
 
1043   $main::lxdebug->enter_sub(2);
 
1045   my ($self, $myconfig, $amount, $places, $dash) = @_;
 
1047   if ($amount eq "") {
 
1051   # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
 
1053   my $neg = ($amount =~ s/^-//);
 
1054   my $exp = ($amount =~ m/[e]/) ? 1 : 0;
 
1056   if (defined($places) && ($places ne '')) {
 
1062         my ($actual_places) = ($amount =~ /\.(\d+)/);
 
1063         $actual_places = length($actual_places);
 
1064         $places = $actual_places > $places ? $actual_places : $places;
 
1067     $amount = $self->round_amount($amount, $places);
 
1070   my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
 
1071   my @p = split(/\./, $amount); # split amount at decimal point
 
1073   $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
 
1076   $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
 
1079     ($dash =~ /-/)    ? ($neg ? "($amount)"                            : "$amount" )                              :
 
1080     ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
 
1081                         ($neg ? "-$amount"                             : "$amount" )                              ;
 
1085   $main::lxdebug->leave_sub(2);
 
1089 sub format_amount_units {
 
1090   $main::lxdebug->enter_sub();
 
1095   my $myconfig         = \%main::myconfig;
 
1096   my $amount           = $params{amount} * 1;
 
1097   my $places           = $params{places};
 
1098   my $part_unit_name   = $params{part_unit};
 
1099   my $amount_unit_name = $params{amount_unit};
 
1100   my $conv_units       = $params{conv_units};
 
1101   my $max_places       = $params{max_places};
 
1103   if (!$part_unit_name) {
 
1104     $main::lxdebug->leave_sub();
 
1108   AM->retrieve_all_units();
 
1109   my $all_units        = $main::all_units;
 
1111   if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
 
1112     $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
 
1115   if (!scalar @{ $conv_units }) {
 
1116     my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
 
1117     $main::lxdebug->leave_sub();
 
1121   my $part_unit  = $all_units->{$part_unit_name};
 
1122   my $conv_unit  = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
 
1124   $amount       *= $conv_unit->{factor};
 
1129   foreach my $unit (@$conv_units) {
 
1130     my $last = $unit->{name} eq $part_unit->{name};
 
1132       $num     = int($amount / $unit->{factor});
 
1133       $amount -= $num * $unit->{factor};
 
1136     if ($last ? $amount : $num) {
 
1137       push @values, { "unit"   => $unit->{name},
 
1138                       "amount" => $last ? $amount / $unit->{factor} : $num,
 
1139                       "places" => $last ? $places : 0 };
 
1146     push @values, { "unit"   => $part_unit_name,
 
1151   my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
 
1153   $main::lxdebug->leave_sub();
 
1159   $main::lxdebug->enter_sub(2);
 
1164   $input =~ s/(^|[^\#]) \#  (\d+)  /$1$_[$2 - 1]/gx;
 
1165   $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
 
1166   $input =~ s/\#\#/\#/g;
 
1168   $main::lxdebug->leave_sub(2);
 
1176   $main::lxdebug->enter_sub(2);
 
1178   my ($self, $myconfig, $amount) = @_;
 
1180   if (   ($myconfig->{numberformat} eq '1.000,00')
 
1181       || ($myconfig->{numberformat} eq '1000,00')) {
 
1186   if ($myconfig->{numberformat} eq "1'000.00") {
 
1192   $main::lxdebug->leave_sub(2);
 
1194   return ($amount * 1);
 
1198   $main::lxdebug->enter_sub(2);
 
1200   my ($self, $amount, $places) = @_;
 
1203   # Rounding like "Kaufmannsrunden" (see http://de.wikipedia.org/wiki/Rundung )
 
1205   # Round amounts to eight places before rounding to the requested
 
1206   # number of places. This gets rid of errors due to internal floating
 
1207   # point representation.
 
1208   $amount       = $self->round_amount($amount, 8) if $places < 8;
 
1209   $amount       = $amount * (10**($places));
 
1210   $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
 
1212   $main::lxdebug->leave_sub(2);
 
1214   return $round_amount;
 
1218 sub parse_template {
 
1219   $main::lxdebug->enter_sub();
 
1221   my ($self, $myconfig, $userspath) = @_;
 
1226   $self->{"cwd"} = getcwd();
 
1227   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
 
1232   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
 
1233     $template_type  = 'OpenDocument';
 
1234     $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
 
1236   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
 
1237     $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
 
1238     $template_type    = 'LaTeX';
 
1239     $ext_for_format   = 'pdf';
 
1241   } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
 
1242     $template_type  = 'HTML';
 
1243     $ext_for_format = 'html';
 
1245   } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
 
1246     $template_type  = 'XML';
 
1247     $ext_for_format = 'xml';
 
1249   } elsif ( $self->{"format"} =~ /elster(?:winston|taxbird)/i ) {
 
1250     $template_type = 'xml';
 
1252   } elsif ( $self->{"format"} =~ /excel/i ) {
 
1253     $template_type  = 'Excel';
 
1254     $ext_for_format = 'xls';
 
1256   } elsif ( defined $self->{'format'}) {
 
1257     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
 
1259   } elsif ( $self->{'format'} eq '' ) {
 
1260     $self->error("No Outputformat given: $self->{'format'}");
 
1262   } else { #Catch the rest
 
1263     $self->error("Outputformat not defined: $self->{'format'}");
 
1266   my $template = SL::Template::create(type      => $template_type,
 
1267                                       file_name => $self->{IN},
 
1269                                       myconfig  => $myconfig,
 
1270                                       userspath => $userspath);
 
1272   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
 
1273   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
 
1275   if (!$self->{employee_id}) {
 
1276     map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
 
1279   map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
 
1281   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
 
1283   # OUT is used for the media, screen, printer, email
 
1284   # for postscript we store a copy in a temporary file
 
1286   my $prepend_userspath;
 
1288   if (!$self->{tmpfile}) {
 
1289     $self->{tmpfile}   = "${fileid}.$self->{IN}";
 
1290     $prepend_userspath = 1;
 
1293   $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
 
1295   $self->{tmpfile} =~ s|.*/||;
 
1296   $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
 
1297   $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
 
1299   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
1300     $out = $self->{OUT};
 
1301     $self->{OUT} = ">$self->{tmpfile}";
 
1307     open OUT, "$self->{OUT}" or $self->error("$self->{OUT} : $!");
 
1308     $result = $template->parse(*OUT);
 
1313     $result = $template->parse(*STDOUT);
 
1318     $self->error("$self->{IN} : " . $template->get_error());
 
1321   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
1323     if ($self->{media} eq 'email') {
 
1325       my $mail = new Mailer;
 
1327       map { $mail->{$_} = $self->{$_} }
 
1328         qw(cc bcc subject message version format);
 
1329       $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
1330       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
 
1331       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
 
1332       $mail->{fileid} = "$fileid.";
 
1333       $myconfig->{signature} =~ s/\r//g;
 
1335       # if we send html or plain text inline
 
1336       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
 
1337         $mail->{contenttype} = "text/html";
 
1339         $mail->{message}       =~ s/\r//g;
 
1340         $mail->{message}       =~ s/\n/<br>\n/g;
 
1341         $myconfig->{signature} =~ s/\n/<br>\n/g;
 
1342         $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
 
1344         open(IN, $self->{tmpfile})
 
1345           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1347           $mail->{message} .= $_;
 
1354         if (!$self->{"do_not_attach"}) {
 
1355           my $attachment_name  =  $self->{attachment_filename} || $self->{tmpfile};
 
1356           $attachment_name     =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
 
1357           $mail->{attachments} =  [{ "filename" => $self->{tmpfile},
 
1358                                      "name"     => $attachment_name }];
 
1361         $mail->{message}  =~ s/\r//g;
 
1362         $mail->{message} .=  "\n-- \n$myconfig->{signature}";
 
1366       my $err = $mail->send();
 
1367       $self->error($self->cleanup . "$err") if ($err);
 
1371       $self->{OUT} = $out;
 
1373       my $numbytes = (-s $self->{tmpfile});
 
1374       open(IN, $self->{tmpfile})
 
1375         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1377       $self->{copies} = 1 unless $self->{media} eq 'printer';
 
1379       chdir("$self->{cwd}");
 
1380       #print(STDERR "Kopien $self->{copies}\n");
 
1381       #print(STDERR "OUT $self->{OUT}\n");
 
1382       for my $i (1 .. $self->{copies}) {
 
1384           open OUT, $self->{OUT} or $self->error($self->cleanup . "$self->{OUT} : $!");
 
1385           print OUT while <IN>;
 
1390           $self->{attachment_filename} = ($self->{attachment_filename})
 
1391                                        ? $self->{attachment_filename}
 
1392                                        : $self->generate_attachment_filename();
 
1394           # launch application
 
1395           print qq|Content-Type: | . $template->get_mime_type() . qq|
 
1396 Content-Disposition: attachment; filename="$self->{attachment_filename}"
 
1397 Content-Length: $numbytes
 
1401           $::locale->with_raw_io(\*STDOUT, sub { print while <IN> });
 
1412   chdir("$self->{cwd}");
 
1413   $main::lxdebug->leave_sub();
 
1416 sub get_formname_translation {
 
1417   $main::lxdebug->enter_sub();
 
1418   my ($self, $formname) = @_;
 
1420   $formname ||= $self->{formname};
 
1422   my %formname_translations = (
 
1423     bin_list                => $main::locale->text('Bin List'),
 
1424     credit_note             => $main::locale->text('Credit Note'),
 
1425     invoice                 => $main::locale->text('Invoice'),
 
1426     packing_list            => $main::locale->text('Packing List'),
 
1427     pick_list               => $main::locale->text('Pick List'),
 
1428     proforma                => $main::locale->text('Proforma Invoice'),
 
1429     purchase_order          => $main::locale->text('Purchase Order'),
 
1430     request_quotation       => $main::locale->text('RFQ'),
 
1431     sales_order             => $main::locale->text('Confirmation'),
 
1432     sales_quotation         => $main::locale->text('Quotation'),
 
1433     storno_invoice          => $main::locale->text('Storno Invoice'),
 
1434     storno_packing_list     => $main::locale->text('Storno Packing List'),
 
1435     sales_delivery_order    => $main::locale->text('Delivery Order'),
 
1436     purchase_delivery_order => $main::locale->text('Delivery Order'),
 
1437     dunning                 => $main::locale->text('Dunning'),
 
1440   $main::lxdebug->leave_sub();
 
1441   return $formname_translations{$formname}
 
1444 sub get_number_prefix_for_type {
 
1445   $main::lxdebug->enter_sub();
 
1449       (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
 
1450     : ($self->{type} =~ /_quotation$/)                        ? 'quo'
 
1451     : ($self->{type} =~ /_delivery_order$/)                   ? 'do'
 
1454   $main::lxdebug->leave_sub();
 
1458 sub get_extension_for_format {
 
1459   $main::lxdebug->enter_sub();
 
1462   my $extension = $self->{format} =~ /pdf/i          ? ".pdf"
 
1463                 : $self->{format} =~ /postscript/i   ? ".ps"
 
1464                 : $self->{format} =~ /opendocument/i ? ".odt"
 
1465                 : $self->{format} =~ /excel/i        ? ".xls"
 
1466                 : $self->{format} =~ /html/i         ? ".html"
 
1469   $main::lxdebug->leave_sub();
 
1473 sub generate_attachment_filename {
 
1474   $main::lxdebug->enter_sub();
 
1477   my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
 
1478   my $prefix              = $self->get_number_prefix_for_type();
 
1480   if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
 
1481     $attachment_filename .= ' (' . $main::locale->text('Preview') . ')' . $self->get_extension_for_format();
 
1483   } elsif ($attachment_filename && $self->{"${prefix}number"}) {
 
1484     $attachment_filename .=  "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
 
1487     $attachment_filename = "";
 
1490   $attachment_filename =  $main::locale->quote_special_chars('filenames', $attachment_filename);
 
1491   $attachment_filename =~ s|[\s/\\]+|_|g;
 
1493   $main::lxdebug->leave_sub();
 
1494   return $attachment_filename;
 
1497 sub generate_email_subject {
 
1498   $main::lxdebug->enter_sub();
 
1501   my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
 
1502   my $prefix  = $self->get_number_prefix_for_type();
 
1504   if ($subject && $self->{"${prefix}number"}) {
 
1505     $subject .= " " . $self->{"${prefix}number"}
 
1508   $main::lxdebug->leave_sub();
 
1513   $main::lxdebug->enter_sub();
 
1517   chdir("$self->{tmpdir}");
 
1520   if (-f "$self->{tmpfile}.err") {
 
1521     open(FH, "$self->{tmpfile}.err");
 
1526   if ($self->{tmpfile} && ! $::keep_temp_files) {
 
1527     $self->{tmpfile} =~ s|.*/||g;
 
1529     $self->{tmpfile} =~ s/\.\w+$//g;
 
1530     my $tmpfile = $self->{tmpfile};
 
1531     unlink(<$tmpfile.*>);
 
1534   chdir("$self->{cwd}");
 
1536   $main::lxdebug->leave_sub();
 
1542   $main::lxdebug->enter_sub();
 
1544   my ($self, $date, $myconfig) = @_;
 
1547   if ($date && $date =~ /\D/) {
 
1549     if ($myconfig->{dateformat} =~ /^yy/) {
 
1550       ($yy, $mm, $dd) = split /\D/, $date;
 
1552     if ($myconfig->{dateformat} =~ /^mm/) {
 
1553       ($mm, $dd, $yy) = split /\D/, $date;
 
1555     if ($myconfig->{dateformat} =~ /^dd/) {
 
1556       ($dd, $mm, $yy) = split /\D/, $date;
 
1561     $yy = ($yy < 70) ? $yy + 2000 : $yy;
 
1562     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
 
1564     $dd = "0$dd" if ($dd < 10);
 
1565     $mm = "0$mm" if ($mm < 10);
 
1567     $date = "$yy$mm$dd";
 
1570   $main::lxdebug->leave_sub();
 
1575 # Database routines used throughout
 
1577 sub _dbconnect_options {
 
1579   my $options = { pg_enable_utf8 => $::locale->is_utf8,
 
1586   $main::lxdebug->enter_sub(2);
 
1588   my ($self, $myconfig) = @_;
 
1590   # connect to database
 
1591   my $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, $self->_dbconnect_options)
 
1595   if ($myconfig->{dboptions}) {
 
1596     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1599   $main::lxdebug->leave_sub(2);
 
1604 sub dbconnect_noauto {
 
1605   $main::lxdebug->enter_sub();
 
1607   my ($self, $myconfig) = @_;
 
1609   # connect to database
 
1610   my $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, $self->_dbconnect_options(AutoCommit => 0))
 
1614   if ($myconfig->{dboptions}) {
 
1615     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1618   $main::lxdebug->leave_sub();
 
1623 sub get_standard_dbh {
 
1624   $main::lxdebug->enter_sub(2);
 
1627   my $myconfig = shift || \%::myconfig;
 
1629   if ($standard_dbh && !$standard_dbh->{Active}) {
 
1630     $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
 
1631     undef $standard_dbh;
 
1634   $standard_dbh ||= $self->dbconnect_noauto($myconfig);
 
1636   $main::lxdebug->leave_sub(2);
 
1638   return $standard_dbh;
 
1642   $main::lxdebug->enter_sub();
 
1644   my ($self, $date, $myconfig) = @_;
 
1645   my $dbh = $self->dbconnect($myconfig);
 
1647   my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
 
1648   my $sth = prepare_execute_query($self, $dbh, $query, $date);
 
1649   my ($closed) = $sth->fetchrow_array;
 
1651   $main::lxdebug->leave_sub();
 
1656 sub update_balance {
 
1657   $main::lxdebug->enter_sub();
 
1659   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
 
1661   # if we have a value, go do it
 
1664     # retrieve balance from table
 
1665     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
 
1666     my $sth = prepare_execute_query($self, $dbh, $query, @values);
 
1667     my ($balance) = $sth->fetchrow_array;
 
1673     $query = "UPDATE $table SET $field = $balance WHERE $where";
 
1674     do_query($self, $dbh, $query, @values);
 
1676   $main::lxdebug->leave_sub();
 
1679 sub update_exchangerate {
 
1680   $main::lxdebug->enter_sub();
 
1682   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
 
1684   # some sanity check for currency
 
1686     $main::lxdebug->leave_sub();
 
1689   $query = qq|SELECT curr FROM defaults|;
 
1691   my ($currency) = selectrow_query($self, $dbh, $query);
 
1692   my ($defaultcurrency) = split m/:/, $currency;
 
1695   if ($curr eq $defaultcurrency) {
 
1696     $main::lxdebug->leave_sub();
 
1700   $query = qq|SELECT e.curr FROM exchangerate e
 
1701                  WHERE e.curr = ? AND e.transdate = ?
 
1703   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
 
1712   $buy = conv_i($buy, "NULL");
 
1713   $sell = conv_i($sell, "NULL");
 
1716   if ($buy != 0 && $sell != 0) {
 
1717     $set = "buy = $buy, sell = $sell";
 
1718   } elsif ($buy != 0) {
 
1719     $set = "buy = $buy";
 
1720   } elsif ($sell != 0) {
 
1721     $set = "sell = $sell";
 
1724   if ($sth->fetchrow_array) {
 
1725     $query = qq|UPDATE exchangerate
 
1731     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
 
1732                 VALUES (?, $buy, $sell, ?)|;
 
1735   do_query($self, $dbh, $query, $curr, $transdate);
 
1737   $main::lxdebug->leave_sub();
 
1740 sub save_exchangerate {
 
1741   $main::lxdebug->enter_sub();
 
1743   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
 
1745   my $dbh = $self->dbconnect($myconfig);
 
1749   $buy  = $rate if $fld eq 'buy';
 
1750   $sell = $rate if $fld eq 'sell';
 
1753   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
 
1758   $main::lxdebug->leave_sub();
 
1761 sub get_exchangerate {
 
1762   $main::lxdebug->enter_sub();
 
1764   my ($self, $dbh, $curr, $transdate, $fld) = @_;
 
1767   unless ($transdate) {
 
1768     $main::lxdebug->leave_sub();
 
1772   $query = qq|SELECT curr FROM defaults|;
 
1774   my ($currency) = selectrow_query($self, $dbh, $query);
 
1775   my ($defaultcurrency) = split m/:/, $currency;
 
1777   if ($currency eq $defaultcurrency) {
 
1778     $main::lxdebug->leave_sub();
 
1782   $query = qq|SELECT e.$fld FROM exchangerate e
 
1783                  WHERE e.curr = ? AND e.transdate = ?|;
 
1784   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
 
1788   $main::lxdebug->leave_sub();
 
1790   return $exchangerate;
 
1793 sub check_exchangerate {
 
1794   $main::lxdebug->enter_sub();
 
1796   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
 
1798   if ($fld !~/^buy|sell$/) {
 
1799     $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
 
1802   unless ($transdate) {
 
1803     $main::lxdebug->leave_sub();
 
1807   my ($defaultcurrency) = $self->get_default_currency($myconfig);
 
1809   if ($currency eq $defaultcurrency) {
 
1810     $main::lxdebug->leave_sub();
 
1814   my $dbh   = $self->get_standard_dbh($myconfig);
 
1815   my $query = qq|SELECT e.$fld FROM exchangerate e
 
1816                  WHERE e.curr = ? AND e.transdate = ?|;
 
1818   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
 
1820   $main::lxdebug->leave_sub();
 
1822   return $exchangerate;
 
1825 sub get_all_currencies {
 
1826   $main::lxdebug->enter_sub();
 
1829   my $myconfig = shift || \%::myconfig;
 
1830   my $dbh      = $self->get_standard_dbh($myconfig);
 
1832   my $query = qq|SELECT curr FROM defaults|;
 
1834   my ($curr)     = selectrow_query($self, $dbh, $query);
 
1835   my @currencies = grep { $_ } map { s/\s//g; $_ } split m/:/, $curr;
 
1837   $main::lxdebug->leave_sub();
 
1842 sub get_default_currency {
 
1843   $main::lxdebug->enter_sub();
 
1845   my ($self, $myconfig) = @_;
 
1846   my @currencies        = $self->get_all_currencies($myconfig);
 
1848   $main::lxdebug->leave_sub();
 
1850   return $currencies[0];
 
1853 sub set_payment_options {
 
1854   $main::lxdebug->enter_sub();
 
1856   my ($self, $myconfig, $transdate) = @_;
 
1858   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
 
1860   my $dbh = $self->get_standard_dbh($myconfig);
 
1863     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
 
1864     qq|FROM payment_terms p | .
 
1867   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
 
1868    $self->{payment_terms}) =
 
1869      selectrow_query($self, $dbh, $query, $self->{payment_id});
 
1871   if ($transdate eq "") {
 
1872     if ($self->{invdate}) {
 
1873       $transdate = $self->{invdate};
 
1875       $transdate = $self->{transdate};
 
1880     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
 
1881     qq|FROM payment_terms|;
 
1882   ($self->{netto_date}, $self->{skonto_date}) =
 
1883     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
 
1885   my ($invtotal, $total);
 
1886   my (%amounts, %formatted_amounts);
 
1888   if ($self->{type} =~ /_order$/) {
 
1889     $amounts{invtotal} = $self->{ordtotal};
 
1890     $amounts{total}    = $self->{ordtotal};
 
1892   } elsif ($self->{type} =~ /_quotation$/) {
 
1893     $amounts{invtotal} = $self->{quototal};
 
1894     $amounts{total}    = $self->{quototal};
 
1897     $amounts{invtotal} = $self->{invtotal};
 
1898     $amounts{total}    = $self->{total};
 
1900   $amounts{skonto_in_percent} = 100.0 * $self->{percent_skonto};
 
1902   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
 
1904   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
 
1905   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
 
1906   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
 
1908   foreach (keys %amounts) {
 
1909     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
 
1910     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
 
1913   if ($self->{"language_id"}) {
 
1915       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
 
1916       qq|FROM translation_payment_terms t | .
 
1917       qq|LEFT JOIN language l ON t.language_id = l.id | .
 
1918       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
 
1919     my ($description_long, $output_numberformat, $output_dateformat,
 
1920       $output_longdates) =
 
1921       selectrow_query($self, $dbh, $query,
 
1922                       $self->{"language_id"}, $self->{"payment_id"});
 
1924     $self->{payment_terms} = $description_long if ($description_long);
 
1926     if ($output_dateformat) {
 
1927       foreach my $key (qw(netto_date skonto_date)) {
 
1929           $main::locale->reformat_date($myconfig, $self->{$key},
 
1935     if ($output_numberformat &&
 
1936         ($output_numberformat ne $myconfig->{"numberformat"})) {
 
1937       my $saved_numberformat = $myconfig->{"numberformat"};
 
1938       $myconfig->{"numberformat"} = $output_numberformat;
 
1939       map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
 
1940       $myconfig->{"numberformat"} = $saved_numberformat;
 
1944   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
 
1945   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
 
1946   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
 
1947   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
 
1948   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
 
1949   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
 
1950   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
 
1952   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
 
1954   $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
 
1956   $main::lxdebug->leave_sub();
 
1960 sub get_template_language {
 
1961   $main::lxdebug->enter_sub();
 
1963   my ($self, $myconfig) = @_;
 
1965   my $template_code = "";
 
1967   if ($self->{language_id}) {
 
1968     my $dbh = $self->get_standard_dbh($myconfig);
 
1969     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
 
1970     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
 
1973   $main::lxdebug->leave_sub();
 
1975   return $template_code;
 
1978 sub get_printer_code {
 
1979   $main::lxdebug->enter_sub();
 
1981   my ($self, $myconfig) = @_;
 
1983   my $template_code = "";
 
1985   if ($self->{printer_id}) {
 
1986     my $dbh = $self->get_standard_dbh($myconfig);
 
1987     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
 
1988     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
 
1991   $main::lxdebug->leave_sub();
 
1993   return $template_code;
 
1997   $main::lxdebug->enter_sub();
 
1999   my ($self, $myconfig) = @_;
 
2001   my $template_code = "";
 
2003   if ($self->{shipto_id}) {
 
2004     my $dbh = $self->get_standard_dbh($myconfig);
 
2005     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
 
2006     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
 
2007     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
 
2010   $main::lxdebug->leave_sub();
 
2014   $main::lxdebug->enter_sub();
 
2016   my ($self, $dbh, $id, $module) = @_;
 
2021   foreach my $item (qw(name department_1 department_2 street zipcode city country
 
2022                        contact phone fax email)) {
 
2023     if ($self->{"shipto$item"}) {
 
2024       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
 
2026     push(@values, $self->{"shipto${item}"});
 
2030     if ($self->{shipto_id}) {
 
2031       my $query = qq|UPDATE shipto set
 
2033                        shiptodepartment_1 = ?,
 
2034                        shiptodepartment_2 = ?,
 
2043                      WHERE shipto_id = ?|;
 
2044       do_query($self, $dbh, $query, @values, $self->{shipto_id});
 
2046       my $query = qq|SELECT * FROM shipto
 
2047                      WHERE shiptoname = ? AND
 
2048                        shiptodepartment_1 = ? AND
 
2049                        shiptodepartment_2 = ? AND
 
2050                        shiptostreet = ? AND
 
2051                        shiptozipcode = ? AND
 
2053                        shiptocountry = ? AND
 
2054                        shiptocontact = ? AND
 
2060       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
 
2063           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
 
2064                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
 
2065                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
 
2066              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
 
2067         do_query($self, $dbh, $query, $id, @values, $module);
 
2072   $main::lxdebug->leave_sub();
 
2076   $main::lxdebug->enter_sub();
 
2078   my ($self, $dbh) = @_;
 
2080   $dbh ||= $self->get_standard_dbh(\%main::myconfig);
 
2082   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
 
2083   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
 
2084   $self->{"employee_id"} *= 1;
 
2086   $main::lxdebug->leave_sub();
 
2089 sub get_employee_data {
 
2090   $main::lxdebug->enter_sub();
 
2095   Common::check_params(\%params, qw(prefix));
 
2096   Common::check_params_x(\%params, qw(id));
 
2099     $main::lxdebug->leave_sub();
 
2103   my $myconfig = \%main::myconfig;
 
2104   my $dbh      = $params{dbh} || $self->get_standard_dbh($myconfig);
 
2106   my ($login)  = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
 
2109     my $user = User->new($login);
 
2110     map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
 
2112     $self->{$params{prefix} . '_login'}   = $login;
 
2113     $self->{$params{prefix} . '_name'}  ||= $login;
 
2116   $main::lxdebug->leave_sub();
 
2120   $main::lxdebug->enter_sub();
 
2122   my ($self, $myconfig, $reference_date) = @_;
 
2124   $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
 
2126   my $dbh         = $self->get_standard_dbh($myconfig);
 
2127   my $query       = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
 
2128   my ($duedate)   = selectrow_query($self, $dbh, $query, $self->{payment_id});
 
2130   $main::lxdebug->leave_sub();
 
2136   $main::lxdebug->enter_sub();
 
2138   my ($self, $dbh, $id, $key) = @_;
 
2140   $key = "all_contacts" unless ($key);
 
2144     $main::lxdebug->leave_sub();
 
2149     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
 
2150     qq|FROM contacts | .
 
2151     qq|WHERE cp_cv_id = ? | .
 
2152     qq|ORDER BY lower(cp_name)|;
 
2154   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
 
2156   $main::lxdebug->leave_sub();
 
2160   $main::lxdebug->enter_sub();
 
2162   my ($self, $dbh, $key) = @_;
 
2164   my ($all, $old_id, $where, @values);
 
2166   if (ref($key) eq "HASH") {
 
2169     $key = "ALL_PROJECTS";
 
2171     foreach my $p (keys(%{$params})) {
 
2173         $all = $params->{$p};
 
2174       } elsif ($p eq "old_id") {
 
2175         $old_id = $params->{$p};
 
2176       } elsif ($p eq "key") {
 
2177         $key = $params->{$p};
 
2183     $where = "WHERE active ";
 
2185       if (ref($old_id) eq "ARRAY") {
 
2186         my @ids = grep({ $_ } @{$old_id});
 
2188           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
 
2189           push(@values, @ids);
 
2192         $where .= " OR (id = ?) ";
 
2193         push(@values, $old_id);
 
2199     qq|SELECT id, projectnumber, description, active | .
 
2202     qq|ORDER BY lower(projectnumber)|;
 
2204   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
 
2206   $main::lxdebug->leave_sub();
 
2210   $main::lxdebug->enter_sub();
 
2212   my ($self, $dbh, $vc_id, $key) = @_;
 
2214   $key = "all_shipto" unless ($key);
 
2217     # get shipping addresses
 
2218     my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
 
2220     $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
 
2226   $main::lxdebug->leave_sub();
 
2230   $main::lxdebug->enter_sub();
 
2232   my ($self, $dbh, $key) = @_;
 
2234   $key = "all_printers" unless ($key);
 
2236   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
 
2238   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2240   $main::lxdebug->leave_sub();
 
2244   $main::lxdebug->enter_sub();
 
2246   my ($self, $dbh, $params) = @_;
 
2249   $key = $params->{key};
 
2250   $key = "all_charts" unless ($key);
 
2252   my $transdate = quote_db_date($params->{transdate});
 
2255     qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
 
2257     qq|LEFT JOIN taxkeys tk ON | .
 
2258     qq|(tk.id = (SELECT id FROM taxkeys | .
 
2259     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
 
2260     qq|          ORDER BY startdate DESC LIMIT 1)) | .
 
2261     qq|ORDER BY c.accno|;
 
2263   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2265   $main::lxdebug->leave_sub();
 
2268 sub _get_taxcharts {
 
2269   $main::lxdebug->enter_sub();
 
2271   my ($self, $dbh, $params) = @_;
 
2273   my $key = "all_taxcharts";
 
2276   if (ref $params eq 'HASH') {
 
2277     $key = $params->{key} if ($params->{key});
 
2278     if ($params->{module} eq 'AR') {
 
2279       push @where, 'taxkey NOT IN (8, 9, 18, 19)';
 
2281     } elsif ($params->{module} eq 'AP') {
 
2282       push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
 
2289   my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
 
2291   my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
 
2293   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2295   $main::lxdebug->leave_sub();
 
2299   $main::lxdebug->enter_sub();
 
2301   my ($self, $dbh, $key) = @_;
 
2303   $key = "all_taxzones" unless ($key);
 
2305   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
 
2307   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2309   $main::lxdebug->leave_sub();
 
2312 sub _get_employees {
 
2313   $main::lxdebug->enter_sub();
 
2315   my ($self, $dbh, $default_key, $key) = @_;
 
2317   $key = $default_key unless ($key);
 
2318   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
 
2320   $main::lxdebug->leave_sub();
 
2323 sub _get_business_types {
 
2324   $main::lxdebug->enter_sub();
 
2326   my ($self, $dbh, $key) = @_;
 
2328   my $options       = ref $key eq 'HASH' ? $key : { key => $key };
 
2329   $options->{key} ||= "all_business_types";
 
2332   if (exists $options->{salesman}) {
 
2333     $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
 
2336   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
 
2338   $main::lxdebug->leave_sub();
 
2341 sub _get_languages {
 
2342   $main::lxdebug->enter_sub();
 
2344   my ($self, $dbh, $key) = @_;
 
2346   $key = "all_languages" unless ($key);
 
2348   my $query = qq|SELECT * FROM language ORDER BY id|;
 
2350   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2352   $main::lxdebug->leave_sub();
 
2355 sub _get_dunning_configs {
 
2356   $main::lxdebug->enter_sub();
 
2358   my ($self, $dbh, $key) = @_;
 
2360   $key = "all_dunning_configs" unless ($key);
 
2362   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
 
2364   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2366   $main::lxdebug->leave_sub();
 
2369 sub _get_currencies {
 
2370 $main::lxdebug->enter_sub();
 
2372   my ($self, $dbh, $key) = @_;
 
2374   $key = "all_currencies" unless ($key);
 
2376   my $query = qq|SELECT curr AS currency FROM defaults|;
 
2378   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
 
2380   $main::lxdebug->leave_sub();
 
2384 $main::lxdebug->enter_sub();
 
2386   my ($self, $dbh, $key) = @_;
 
2388   $key = "all_payments" unless ($key);
 
2390   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
 
2392   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2394   $main::lxdebug->leave_sub();
 
2397 sub _get_customers {
 
2398   $main::lxdebug->enter_sub();
 
2400   my ($self, $dbh, $key) = @_;
 
2402   my $options        = ref $key eq 'HASH' ? $key : { key => $key };
 
2403   $options->{key}  ||= "all_customers";
 
2404   my $limit_clause   = "LIMIT $options->{limit}" if $options->{limit};
 
2407   push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if  $options->{business_is_salesman};
 
2408   push @where, qq|NOT obsolete|                                            if !$options->{with_obsolete};
 
2409   my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : '';
 
2411   my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|;
 
2412   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
 
2414   $main::lxdebug->leave_sub();
 
2418   $main::lxdebug->enter_sub();
 
2420   my ($self, $dbh, $key) = @_;
 
2422   $key = "all_vendors" unless ($key);
 
2424   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
 
2426   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2428   $main::lxdebug->leave_sub();
 
2431 sub _get_departments {
 
2432   $main::lxdebug->enter_sub();
 
2434   my ($self, $dbh, $key) = @_;
 
2436   $key = "all_departments" unless ($key);
 
2438   my $query = qq|SELECT * FROM department ORDER BY description|;
 
2440   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2442   $main::lxdebug->leave_sub();
 
2445 sub _get_warehouses {
 
2446   $main::lxdebug->enter_sub();
 
2448   my ($self, $dbh, $param) = @_;
 
2450   my ($key, $bins_key);
 
2452   if ('' eq ref $param) {
 
2456     $key      = $param->{key};
 
2457     $bins_key = $param->{bins};
 
2460   my $query = qq|SELECT w.* FROM warehouse w
 
2461                  WHERE (NOT w.invalid) AND
 
2462                    ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
 
2463                  ORDER BY w.sortkey|;
 
2465   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2468     $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
 
2469     my $sth = prepare_query($self, $dbh, $query);
 
2471     foreach my $warehouse (@{ $self->{$key} }) {
 
2472       do_statement($self, $sth, $query, $warehouse->{id});
 
2473       $warehouse->{$bins_key} = [];
 
2475       while (my $ref = $sth->fetchrow_hashref()) {
 
2476         push @{ $warehouse->{$bins_key} }, $ref;
 
2482   $main::lxdebug->leave_sub();
 
2486   $main::lxdebug->enter_sub();
 
2488   my ($self, $dbh, $table, $key, $sortkey) = @_;
 
2490   my $query  = qq|SELECT * FROM $table|;
 
2491   $query    .= qq| ORDER BY $sortkey| if ($sortkey);
 
2493   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2495   $main::lxdebug->leave_sub();
 
2499 #  $main::lxdebug->enter_sub();
 
2501 #  my ($self, $dbh, $key) = @_;
 
2503 #  $key ||= "all_groups";
 
2505 #  my $groups = $main::auth->read_groups();
 
2507 #  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2509 #  $main::lxdebug->leave_sub();
 
2513   $main::lxdebug->enter_sub();
 
2518   my $dbh = $self->get_standard_dbh(\%main::myconfig);
 
2519   my ($sth, $query, $ref);
 
2521   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
 
2522   my $vc_id = $self->{"${vc}_id"};
 
2524   if ($params{"contacts"}) {
 
2525     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
 
2528   if ($params{"shipto"}) {
 
2529     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
 
2532   if ($params{"projects"} || $params{"all_projects"}) {
 
2533     $self->_get_projects($dbh, $params{"all_projects"} ?
 
2534                          $params{"all_projects"} : $params{"projects"},
 
2535                          $params{"all_projects"} ? 1 : 0);
 
2538   if ($params{"printers"}) {
 
2539     $self->_get_printers($dbh, $params{"printers"});
 
2542   if ($params{"languages"}) {
 
2543     $self->_get_languages($dbh, $params{"languages"});
 
2546   if ($params{"charts"}) {
 
2547     $self->_get_charts($dbh, $params{"charts"});
 
2550   if ($params{"taxcharts"}) {
 
2551     $self->_get_taxcharts($dbh, $params{"taxcharts"});
 
2554   if ($params{"taxzones"}) {
 
2555     $self->_get_taxzones($dbh, $params{"taxzones"});
 
2558   if ($params{"employees"}) {
 
2559     $self->_get_employees($dbh, "all_employees", $params{"employees"});
 
2562   if ($params{"salesmen"}) {
 
2563     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
 
2566   if ($params{"business_types"}) {
 
2567     $self->_get_business_types($dbh, $params{"business_types"});
 
2570   if ($params{"dunning_configs"}) {
 
2571     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
 
2574   if($params{"currencies"}) {
 
2575     $self->_get_currencies($dbh, $params{"currencies"});
 
2578   if($params{"customers"}) {
 
2579     $self->_get_customers($dbh, $params{"customers"});
 
2582   if($params{"vendors"}) {
 
2583     if (ref $params{"vendors"} eq 'HASH') {
 
2584       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
 
2586       $self->_get_vendors($dbh, $params{"vendors"});
 
2590   if($params{"payments"}) {
 
2591     $self->_get_payments($dbh, $params{"payments"});
 
2594   if($params{"departments"}) {
 
2595     $self->_get_departments($dbh, $params{"departments"});
 
2598   if ($params{price_factors}) {
 
2599     $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
 
2602   if ($params{warehouses}) {
 
2603     $self->_get_warehouses($dbh, $params{warehouses});
 
2606 #  if ($params{groups}) {
 
2607 #    $self->_get_groups($dbh, $params{groups});
 
2610   if ($params{partsgroup}) {
 
2611     $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
 
2614   $main::lxdebug->leave_sub();
 
2617 # this sub gets the id and name from $table
 
2619   $main::lxdebug->enter_sub();
 
2621   my ($self, $myconfig, $table) = @_;
 
2623   # connect to database
 
2624   my $dbh = $self->get_standard_dbh($myconfig);
 
2626   $table = $table eq "customer" ? "customer" : "vendor";
 
2627   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
 
2629   my ($query, @values);
 
2631   if (!$self->{openinvoices}) {
 
2633     if ($self->{customernumber} ne "") {
 
2634       $where = qq|(vc.customernumber ILIKE ?)|;
 
2635       push(@values, '%' . $self->{customernumber} . '%');
 
2637       $where = qq|(vc.name ILIKE ?)|;
 
2638       push(@values, '%' . $self->{$table} . '%');
 
2642       qq~SELECT vc.id, vc.name,
 
2643            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
2645          WHERE $where AND (NOT vc.obsolete)
 
2649       qq~SELECT DISTINCT vc.id, vc.name,
 
2650            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
2652          JOIN $table vc ON (a.${table}_id = vc.id)
 
2653          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
 
2655     push(@values, '%' . $self->{$table} . '%');
 
2658   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
 
2660   $main::lxdebug->leave_sub();
 
2662   return scalar(@{ $self->{name_list} });
 
2665 # the selection sub is used in the AR, AP, IS, IR and OE module
 
2668   $main::lxdebug->enter_sub();
 
2670   my ($self, $myconfig, $table, $module) = @_;
 
2673   my $dbh = $self->get_standard_dbh;
 
2675   $table = $table eq "customer" ? "customer" : "vendor";
 
2677   my $query = qq|SELECT count(*) FROM $table|;
 
2678   my ($count) = selectrow_query($self, $dbh, $query);
 
2680   # build selection list
 
2681   if ($count <= $myconfig->{vclimit}) {
 
2682     $query = qq|SELECT id, name, salesman_id
 
2683                 FROM $table WHERE NOT obsolete
 
2685     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
 
2689   $self->get_employee($dbh);
 
2691   # setup sales contacts
 
2692   $query = qq|SELECT e.id, e.name
 
2694               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
 
2695   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
 
2698   push(@{ $self->{all_employees} },
 
2699        { id   => $self->{employee_id},
 
2700          name => $self->{employee} });
 
2702   # sort the whole thing
 
2703   @{ $self->{all_employees} } =
 
2704     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
 
2706   if ($module eq 'AR') {
 
2708     # prepare query for departments
 
2709     $query = qq|SELECT id, description
 
2712                 ORDER BY description|;
 
2715     $query = qq|SELECT id, description
 
2717                 ORDER BY description|;
 
2720   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2723   $query = qq|SELECT id, description
 
2727   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2730   $query = qq|SELECT printer_description, id
 
2732               ORDER BY printer_description|;
 
2734   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2737   $query = qq|SELECT id, description
 
2741   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
2743   $main::lxdebug->leave_sub();
 
2746 sub language_payment {
 
2747   $main::lxdebug->enter_sub();
 
2749   my ($self, $myconfig) = @_;
 
2751   my $dbh = $self->get_standard_dbh($myconfig);
 
2753   my $query = qq|SELECT id, description
 
2757   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2760   $query = qq|SELECT printer_description, id
 
2762               ORDER BY printer_description|;
 
2764   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2767   $query = qq|SELECT id, description
 
2771   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
2773   # get buchungsgruppen
 
2774   $query = qq|SELECT id, description
 
2775               FROM buchungsgruppen|;
 
2777   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
 
2779   $main::lxdebug->leave_sub();
 
2782 # this is only used for reports
 
2783 sub all_departments {
 
2784   $main::lxdebug->enter_sub();
 
2786   my ($self, $myconfig, $table) = @_;
 
2788   my $dbh = $self->get_standard_dbh($myconfig);
 
2791   if ($table eq 'customer') {
 
2792     $where = "WHERE role = 'P' ";
 
2795   my $query = qq|SELECT id, description
 
2798                  ORDER BY description|;
 
2799   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2801   delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
 
2803   $main::lxdebug->leave_sub();
 
2807   $main::lxdebug->enter_sub();
 
2809   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
 
2812   if ($table eq "customer") {
 
2821   $self->all_vc($myconfig, $table, $module);
 
2823   # get last customers or vendors
 
2824   my ($query, $sth, $ref);
 
2826   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
 
2831     my $transdate = "current_date";
 
2832     if ($self->{transdate}) {
 
2833       $transdate = $dbh->quote($self->{transdate});
 
2836     # now get the account numbers
 
2837     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
 
2838                 FROM chart c, taxkeys tk
 
2839                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
 
2840                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
 
2843     $sth = $dbh->prepare($query);
 
2845     do_statement($self, $sth, $query, '%' . $module . '%');
 
2847     $self->{accounts} = "";
 
2848     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2850       foreach my $key (split(/:/, $ref->{link})) {
 
2851         if ($key =~ /\Q$module\E/) {
 
2853           # cross reference for keys
 
2854           $xkeyref{ $ref->{accno} } = $key;
 
2856           push @{ $self->{"${module}_links"}{$key} },
 
2857             { accno       => $ref->{accno},
 
2858               description => $ref->{description},
 
2859               taxkey      => $ref->{taxkey_id},
 
2860               tax_id      => $ref->{tax_id} };
 
2862           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2868   # get taxkeys and description
 
2869   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
 
2870   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
 
2872   if (($module eq "AP") || ($module eq "AR")) {
 
2873     # get tax rates and description
 
2874     $query = qq|SELECT * FROM tax|;
 
2875     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
 
2881            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
 
2882            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
 
2883            a.intnotes, a.department_id, a.amount AS oldinvtotal,
 
2884            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
 
2886            d.description AS department,
 
2889          JOIN $table c ON (a.${table}_id = c.id)
 
2890          LEFT JOIN employee e ON (e.id = a.employee_id)
 
2891          LEFT JOIN department d ON (d.id = a.department_id)
 
2893     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
 
2895     foreach my $key (keys %$ref) {
 
2896       $self->{$key} = $ref->{$key};
 
2899     my $transdate = "current_date";
 
2900     if ($self->{transdate}) {
 
2901       $transdate = $dbh->quote($self->{transdate});
 
2904     # now get the account numbers
 
2905     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
 
2907                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
 
2909                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
 
2910                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
 
2913     $sth = $dbh->prepare($query);
 
2914     do_statement($self, $sth, $query, "%$module%");
 
2916     $self->{accounts} = "";
 
2917     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2919       foreach my $key (split(/:/, $ref->{link})) {
 
2920         if ($key =~ /\Q$module\E/) {
 
2922           # cross reference for keys
 
2923           $xkeyref{ $ref->{accno} } = $key;
 
2925           push @{ $self->{"${module}_links"}{$key} },
 
2926             { accno       => $ref->{accno},
 
2927               description => $ref->{description},
 
2928               taxkey      => $ref->{taxkey_id},
 
2929               tax_id      => $ref->{tax_id} };
 
2931           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2937     # get amounts from individual entries
 
2940            c.accno, c.description,
 
2941            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
 
2945          LEFT JOIN chart c ON (c.id = a.chart_id)
 
2946          LEFT JOIN project p ON (p.id = a.project_id)
 
2947          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
 
2948                                     WHERE (tk.taxkey_id=a.taxkey) AND
 
2949                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
 
2950                                         THEN tk.chart_id = a.chart_id
 
2953                                        OR (c.link='%tax%')) AND
 
2954                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
 
2955          WHERE a.trans_id = ?
 
2956          AND a.fx_transaction = '0'
 
2957          ORDER BY a.acc_trans_id, a.transdate|;
 
2958     $sth = $dbh->prepare($query);
 
2959     do_statement($self, $sth, $query, $self->{id});
 
2961     # get exchangerate for currency
 
2962     $self->{exchangerate} =
 
2963       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2966     # store amounts in {acc_trans}{$key} for multiple accounts
 
2967     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2968       $ref->{exchangerate} =
 
2969         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
 
2970       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
 
2973       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
 
2974         $ref->{amount} *= -1;
 
2976       $ref->{index} = $index;
 
2978       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
 
2984            d.curr AS currencies, d.closedto, d.revtrans,
 
2985            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2986            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
2988     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2989     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2996             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
 
2997             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2998             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
3000     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
3001     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
3003     if ($self->{"$self->{vc}_id"}) {
 
3005       # only setup currency
 
3006       ($self->{currency}) = split(/:/, $self->{currencies});
 
3010       $self->lastname_used($dbh, $myconfig, $table, $module);
 
3012       # get exchangerate for currency
 
3013       $self->{exchangerate} =
 
3014         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
3020   $main::lxdebug->leave_sub();
 
3024   $main::lxdebug->enter_sub();
 
3026   my ($self, $dbh, $myconfig, $table, $module) = @_;
 
3030   $table         = $table eq "customer" ? "customer" : "vendor";
 
3031   my %column_map = ("a.curr"                  => "currency",
 
3032                     "a.${table}_id"           => "${table}_id",
 
3033                     "a.department_id"         => "department_id",
 
3034                     "d.description"           => "department",
 
3035                     "ct.name"                 => $table,
 
3036                     "current_date + ct.terms" => "duedate",
 
3039   if ($self->{type} =~ /delivery_order/) {
 
3040     $arap  = 'delivery_orders';
 
3041     delete $column_map{"a.curr"};
 
3043   } elsif ($self->{type} =~ /_order/) {
 
3045     $where = "quotation = '0'";
 
3047   } elsif ($self->{type} =~ /_quotation/) {
 
3049     $where = "quotation = '1'";
 
3051   } elsif ($table eq 'customer') {
 
3059   $where           = "($where) AND" if ($where);
 
3060   my $query        = qq|SELECT MAX(id) FROM $arap
 
3061                         WHERE $where ${table}_id > 0|;
 
3062   my ($trans_id)   = selectrow_query($self, $dbh, $query);
 
3065   my $column_spec  = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
 
3066   $query           = qq|SELECT $column_spec
 
3068                         LEFT JOIN $table     ct ON (a.${table}_id = ct.id)
 
3069                         LEFT JOIN department d  ON (a.department_id = d.id)
 
3071   my $ref          = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
 
3073   map { $self->{$_} = $ref->{$_} } values %column_map;
 
3075   $main::lxdebug->leave_sub();
 
3079   $main::lxdebug->enter_sub();
 
3082   my $myconfig = shift || \%::myconfig;
 
3083   my ($thisdate, $days) = @_;
 
3085   my $dbh = $self->get_standard_dbh($myconfig);
 
3090     my $dateformat = $myconfig->{dateformat};
 
3091     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
 
3092     $thisdate = $dbh->quote($thisdate);
 
3093     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
 
3095     $query = qq|SELECT current_date AS thisdate|;
 
3098   ($thisdate) = selectrow_query($self, $dbh, $query);
 
3100   $main::lxdebug->leave_sub();
 
3106   $main::lxdebug->enter_sub();
 
3108   my ($self, $string) = @_;
 
3110   if ($string !~ /%/) {
 
3111     $string = "%$string%";
 
3114   $string =~ s/\'/\'\'/g;
 
3116   $main::lxdebug->leave_sub();
 
3122   $main::lxdebug->enter_sub();
 
3124   my ($self, $flds, $new, $count, $numrows) = @_;
 
3128   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
 
3133   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
 
3135     my $j = $item->{ndx} - 1;
 
3136     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
 
3140   for $i ($count + 1 .. $numrows) {
 
3141     map { delete $self->{"${_}_$i"} } @{$flds};
 
3144   $main::lxdebug->leave_sub();
 
3148   $main::lxdebug->enter_sub();
 
3150   my ($self, $myconfig) = @_;
 
3154   my $dbh = $self->dbconnect_noauto($myconfig);
 
3156   my $query = qq|DELETE FROM status
 
3157                  WHERE (formname = ?) AND (trans_id = ?)|;
 
3158   my $sth = prepare_query($self, $dbh, $query);
 
3160   if ($self->{formname} =~ /(check|receipt)/) {
 
3161     for $i (1 .. $self->{rowcount}) {
 
3162       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
 
3165     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
 
3169   my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3170   my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3172   my %queued = split / /, $self->{queued};
 
3175   if ($self->{formname} =~ /(check|receipt)/) {
 
3177     # this is a check or receipt, add one entry for each lineitem
 
3178     my ($accno) = split /--/, $self->{account};
 
3179     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
 
3180                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
 
3181     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
 
3182     $sth = prepare_query($self, $dbh, $query);
 
3184     for $i (1 .. $self->{rowcount}) {
 
3185       if ($self->{"checked_$i"}) {
 
3186         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
 
3192     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
3193                 VALUES (?, ?, ?, ?, ?)|;
 
3194     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
 
3195              $queued{$self->{formname}}, $self->{formname});
 
3201   $main::lxdebug->leave_sub();
 
3205   $main::lxdebug->enter_sub();
 
3207   my ($self, $dbh) = @_;
 
3209   my ($query, $printed, $emailed);
 
3211   my $formnames  = $self->{printed};
 
3212   my $emailforms = $self->{emailed};
 
3214   $query = qq|DELETE FROM status
 
3215                  WHERE (formname = ?) AND (trans_id = ?)|;
 
3216   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
 
3218   # this only applies to the forms
 
3219   # checks and receipts are posted when printed or queued
 
3221   if ($self->{queued}) {
 
3222     my %queued = split / /, $self->{queued};
 
3224     foreach my $formname (keys %queued) {
 
3225       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3226       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3228       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
3229                   VALUES (?, ?, ?, ?, ?)|;
 
3230       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
 
3232       $formnames  =~ s/\Q$self->{formname}\E//;
 
3233       $emailforms =~ s/\Q$self->{formname}\E//;
 
3238   # save printed, emailed info
 
3239   $formnames  =~ s/^ +//g;
 
3240   $emailforms =~ s/^ +//g;
 
3243   map { $status{$_}{printed} = 1 } split / +/, $formnames;
 
3244   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
 
3246   foreach my $formname (keys %status) {
 
3247     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3248     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3250     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
 
3251                 VALUES (?, ?, ?, ?)|;
 
3252     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
 
3255   $main::lxdebug->leave_sub();
 
3259 # $main::locale->text('SAVED')
 
3260 # $main::locale->text('DELETED')
 
3261 # $main::locale->text('ADDED')
 
3262 # $main::locale->text('PAYMENT POSTED')
 
3263 # $main::locale->text('POSTED')
 
3264 # $main::locale->text('POSTED AS NEW')
 
3265 # $main::locale->text('ELSE')
 
3266 # $main::locale->text('SAVED FOR DUNNING')
 
3267 # $main::locale->text('DUNNING STARTED')
 
3268 # $main::locale->text('PRINTED')
 
3269 # $main::locale->text('MAILED')
 
3270 # $main::locale->text('SCREENED')
 
3271 # $main::locale->text('CANCELED')
 
3272 # $main::locale->text('invoice')
 
3273 # $main::locale->text('proforma')
 
3274 # $main::locale->text('sales_order')
 
3275 # $main::locale->text('packing_list')
 
3276 # $main::locale->text('pick_list')
 
3277 # $main::locale->text('purchase_order')
 
3278 # $main::locale->text('bin_list')
 
3279 # $main::locale->text('sales_quotation')
 
3280 # $main::locale->text('request_quotation')
 
3283   $main::lxdebug->enter_sub();
 
3286   my $dbh  = shift || $self->get_standard_dbh;
 
3288   if(!exists $self->{employee_id}) {
 
3289     &get_employee($self, $dbh);
 
3293    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
 
3294    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
 
3295   my @values = (conv_i($self->{id}), $self->{login},
 
3296                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
 
3297   do_query($self, $dbh, $query, @values);
 
3301   $main::lxdebug->leave_sub();
 
3305   $main::lxdebug->enter_sub();
 
3307   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
 
3308   my ($orderBy, $desc) = split(/\-\-/, $order);
 
3309   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
 
3312   if ($trans_id ne "") {
 
3314       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 | .
 
3315       qq|FROM history_erp h | .
 
3316       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
 
3317       qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
 
3320     my $sth = $dbh->prepare($query) || $self->dberror($query);
 
3322     $sth->execute() || $self->dberror("$query");
 
3324     while(my $hash_ref = $sth->fetchrow_hashref()) {
 
3325       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
 
3326       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
 
3327       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
 
3328       $tempArray[$i++] = $hash_ref;
 
3330     $main::lxdebug->leave_sub() and return \@tempArray
 
3331       if ($i > 0 && $tempArray[0] ne "");
 
3333   $main::lxdebug->leave_sub();
 
3337 sub update_defaults {
 
3338   $main::lxdebug->enter_sub();
 
3340   my ($self, $myconfig, $fld, $provided_dbh) = @_;
 
3343   if ($provided_dbh) {
 
3344     $dbh = $provided_dbh;
 
3346     $dbh = $self->dbconnect_noauto($myconfig);
 
3348   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
 
3349   my $sth   = $dbh->prepare($query);
 
3351   $sth->execute || $self->dberror($query);
 
3352   my ($var) = $sth->fetchrow_array;
 
3355   if ($var =~ m/\d+$/) {
 
3356     my $new_var  = (substr $var, $-[0]) * 1 + 1;
 
3357     my $len_diff = length($var) - $-[0] - length($new_var);
 
3358     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
 
3364   $query = qq|UPDATE defaults SET $fld = ?|;
 
3365   do_query($self, $dbh, $query, $var);
 
3367   if (!$provided_dbh) {
 
3372   $main::lxdebug->leave_sub();
 
3377 sub update_business {
 
3378   $main::lxdebug->enter_sub();
 
3380   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
 
3383   if ($provided_dbh) {
 
3384     $dbh = $provided_dbh;
 
3386     $dbh = $self->dbconnect_noauto($myconfig);
 
3389     qq|SELECT customernumberinit FROM business
 
3390        WHERE id = ? FOR UPDATE|;
 
3391   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
 
3393   return undef unless $var;
 
3395   if ($var =~ m/\d+$/) {
 
3396     my $new_var  = (substr $var, $-[0]) * 1 + 1;
 
3397     my $len_diff = length($var) - $-[0] - length($new_var);
 
3398     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
 
3404   $query = qq|UPDATE business
 
3405               SET customernumberinit = ?
 
3407   do_query($self, $dbh, $query, $var, $business_id);
 
3409   if (!$provided_dbh) {
 
3414   $main::lxdebug->leave_sub();
 
3419 sub get_partsgroup {
 
3420   $main::lxdebug->enter_sub();
 
3422   my ($self, $myconfig, $p) = @_;
 
3423   my $target = $p->{target} || 'all_partsgroup';
 
3425   my $dbh = $self->get_standard_dbh($myconfig);
 
3427   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
 
3429                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
 
3432   if ($p->{searchitems} eq 'part') {
 
3433     $query .= qq|WHERE p.inventory_accno_id > 0|;
 
3435   if ($p->{searchitems} eq 'service') {
 
3436     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
 
3438   if ($p->{searchitems} eq 'assembly') {
 
3439     $query .= qq|WHERE p.assembly = '1'|;
 
3441   if ($p->{searchitems} eq 'labor') {
 
3442     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
 
3445   $query .= qq|ORDER BY partsgroup|;
 
3448     $query = qq|SELECT id, partsgroup FROM partsgroup
 
3449                 ORDER BY partsgroup|;
 
3452   if ($p->{language_code}) {
 
3453     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
 
3454                   t.description AS translation
 
3456                 JOIN parts p ON (p.partsgroup_id = pg.id)
 
3457                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
 
3458                 ORDER BY translation|;
 
3459     @values = ($p->{language_code});
 
3462   $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
 
3464   $main::lxdebug->leave_sub();
 
3467 sub get_pricegroup {
 
3468   $main::lxdebug->enter_sub();
 
3470   my ($self, $myconfig, $p) = @_;
 
3472   my $dbh = $self->get_standard_dbh($myconfig);
 
3474   my $query = qq|SELECT p.id, p.pricegroup
 
3477   $query .= qq| ORDER BY pricegroup|;
 
3480     $query = qq|SELECT id, pricegroup FROM pricegroup
 
3481                 ORDER BY pricegroup|;
 
3484   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
 
3486   $main::lxdebug->leave_sub();
 
3490 # usage $form->all_years($myconfig, [$dbh])
 
3491 # return list of all years where bookings found
 
3494   $main::lxdebug->enter_sub();
 
3496   my ($self, $myconfig, $dbh) = @_;
 
3498   $dbh ||= $self->get_standard_dbh($myconfig);
 
3501   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
 
3502                    (SELECT MAX(transdate) FROM acc_trans)|;
 
3503   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
 
3505   if ($myconfig->{dateformat} =~ /^yy/) {
 
3506     ($startdate) = split /\W/, $startdate;
 
3507     ($enddate) = split /\W/, $enddate;
 
3509     (@_) = split /\W/, $startdate;
 
3511     (@_) = split /\W/, $enddate;
 
3516   $startdate = substr($startdate,0,4);
 
3517   $enddate = substr($enddate,0,4);
 
3519   while ($enddate >= $startdate) {
 
3520     push @all_years, $enddate--;
 
3525   $main::lxdebug->leave_sub();
 
3529   $main::lxdebug->enter_sub();
 
3533   map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
 
3535   $main::lxdebug->leave_sub();
 
3539   $main::lxdebug->enter_sub();
 
3544   map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
 
3546   $main::lxdebug->leave_sub();
 
3555 SL::Form.pm - main data object.
 
3559 This is the main data object of Lx-Office.
 
3560 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
 
3561 Points of interest for a beginner are:
 
3563  - $form->error            - renders a generic error in html. accepts an error message
 
3564  - $form->get_standard_dbh - returns a database connection for the
 
3566 =head1 SPECIAL FUNCTIONS
 
3570 =item _store_value()
 
3572 parses a complex var name, and stores it in the form.
 
3575   $form->_store_value($key, $value);
 
3577 keys must start with a string, and can contain various tokens.
 
3578 supported key structures are:
 
3581   simple key strings work as expected
 
3586   separating two keys by a dot (.) will result in a hash lookup for the inner value
 
3587   this is similar to the behaviour of java and templating mechanisms.
 
3589   filter.description => $form->{filter}->{description}
 
3591 3. array+hashref access
 
3593   adding brackets ([]) before the dot will cause the next hash to be put into an array.
 
3594   using [+] instead of [] will force a new array index. this is useful for recurring
 
3595   data structures like part lists. put a [+] into the first varname, and use [] on the
 
3598   repeating these names in your template:
 
3601     invoice.items[].parts_id
 
3605     $form->{invoice}->{items}->[
 
3619   using brackets at the end of a name will result in a pure array to be created.
 
3620   note that you mustn't use [+], which is reserved for array+hash access and will
 
3621   result in undefined behaviour in array context.
 
3623   filter.status[]  => $form->{status}->[ val1, val2, ... ]
 
3625 =item update_business PARAMS
 
3628  \%config,     - config hashref
 
3629  $business_id, - business id
 
3630  $dbh          - optional database handle
 
3632 handles business (thats customer/vendor types) sequences.
 
3634 special behaviour for empty strings in customerinitnumber field:
 
3635 will in this case not increase the value, and return undef.
 
3637 =item redirect_header $url
 
3639 Generates a HTTP redirection header for the new C<$url>. Constructs an
 
3640 absolute URL including scheme, host name and port. If C<$url> is a
 
3641 relative URL then it is considered relative to Lx-Office base URL.
 
3643 This function C<die>s if headers have already been created with
 
3644 C<$::form-E<gt>header>.
 
3648   print $::form->redirect_header('oe.pl?action=edit&id=1234');
 
3649   print $::form->redirect_header('http://www.lx-office.org/');