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| - V| . $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" />
 
 731   <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
 
 732   <script type="text/javascript" src="js/tabcontent.js">
 
 734   /***********************************************
 
 735    * Tab Content script v2.2- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
 
 736    * This notice MUST stay intact for legal use
 
 737    * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
 
 738    ***********************************************/
 
 749   $main::lxdebug->leave_sub();
 
 752 sub ajax_response_header {
 
 753   $main::lxdebug->enter_sub();
 
 757   my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
 758   my $cgi        = $main::cgi || CGI->new('');
 
 759   my $output     = $cgi->header('-charset' => $db_charset);
 
 761   $main::lxdebug->leave_sub();
 
 766 sub redirect_header {
 
 770   my $base_uri = $self->_get_request_uri;
 
 771   my $new_uri  = URI->new_abs($new_url, $base_uri);
 
 773   die "Headers already sent" if $::self->{header};
 
 776   my $cgi = $main::cgi || CGI->new('');
 
 777   return $cgi->redirect($new_uri);
 
 780 sub set_standard_title {
 
 781   $::lxdebug->enter_sub;
 
 784   $self->{titlebar}  = "Lx-Office " . $::locale->text('Version') . " $self->{version}";
 
 785   $self->{titlebar} .= "- $::myconfig{name}"   if $::myconfig{name};
 
 786   $self->{titlebar} .= "- $::myconfig{dbname}" if $::myconfig{name};
 
 788   $::lxdebug->leave_sub;
 
 791 sub _prepare_html_template {
 
 792   $main::lxdebug->enter_sub();
 
 794   my ($self, $file, $additional_params) = @_;
 
 797   if (!%::myconfig || !$::myconfig{"countrycode"}) {
 
 798     $language = $main::language;
 
 800     $language = $main::myconfig{"countrycode"};
 
 802   $language = "de" unless ($language);
 
 804   if (-f "templates/webpages/${file}.html") {
 
 805     if ((-f ".developer") && ((stat("templates/webpages/${file}.html"))[9] > (stat("locale/${language}/all"))[9])) {
 
 806       my $info = "Developer information: templates/webpages/${file}.html is newer than the translation file locale/${language}/all.\n" .
 
 807         "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 808       print(qq|<pre>$info</pre>|);
 
 812     $file = "templates/webpages/${file}.html";
 
 815     my $info = "Web page template '${file}' not found.\n" .
 
 816       "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 817     print(qq|<pre>$info</pre>|);
 
 821   if ($self->{"DEBUG"}) {
 
 822     $additional_params->{"DEBUG"} = $self->{"DEBUG"};
 
 825   if ($additional_params->{"DEBUG"}) {
 
 826     $additional_params->{"DEBUG"} =
 
 827       "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
 
 830   if (%main::myconfig) {
 
 831     map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
 
 832     my $jsc_dateformat = $main::myconfig{"dateformat"};
 
 833     $jsc_dateformat =~ s/d+/\%d/gi;
 
 834     $jsc_dateformat =~ s/m+/\%m/gi;
 
 835     $jsc_dateformat =~ s/y+/\%Y/gi;
 
 836     $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
 
 837     $additional_params->{"myconfig"} ||= \%::myconfig;
 
 840   $additional_params->{"conf_dbcharset"}              = $main::dbcharset;
 
 841   $additional_params->{"conf_webdav"}                 = $main::webdav;
 
 842   $additional_params->{"conf_lizenzen"}               = $main::lizenzen;
 
 843   $additional_params->{"conf_latex_templates"}        = $main::latex;
 
 844   $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
 
 845   $additional_params->{"conf_vertreter"}              = $main::vertreter;
 
 846   $additional_params->{"conf_show_best_before"}       = $main::show_best_before;
 
 848   if (%main::debug_options) {
 
 849     map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
 
 852   if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
 
 853     while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
 
 854       $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
 
 858   $main::lxdebug->leave_sub();
 
 863 sub parse_html_template {
 
 864   $main::lxdebug->enter_sub();
 
 866   my ($self, $file, $additional_params) = @_;
 
 868   $additional_params ||= { };
 
 870   my $real_file = $self->_prepare_html_template($file, $additional_params);
 
 871   my $template  = $self->template || $self->init_template;
 
 873   map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
 
 876   $template->process($real_file, $additional_params, \$output) || die $template->error;
 
 878   $main::lxdebug->leave_sub();
 
 886   return if $self->template;
 
 888   return $self->template(Template->new({
 
 893      'PLUGIN_BASE'  => 'SL::Template::Plugin',
 
 894      'INCLUDE_PATH' => '.:templates/webpages',
 
 895      'COMPILE_EXT'  => '.tcc',
 
 896      'COMPILE_DIR'  => $::userspath . '/templates-cache',
 
 902   $self->{template_object} = shift if @_;
 
 903   return $self->{template_object};
 
 906 sub show_generic_error {
 
 907   $main::lxdebug->enter_sub();
 
 909   my ($self, $error, %params) = @_;
 
 912     'title_error' => $params{title},
 
 913     'label_error' => $error,
 
 916   if ($params{action}) {
 
 919     map { delete($self->{$_}); } qw(action);
 
 920     map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
 
 922     $add_params->{SHOW_BUTTON}  = 1;
 
 923     $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
 
 924     $add_params->{VARIABLES}    = \@vars;
 
 926   } elsif ($params{back_button}) {
 
 927     $add_params->{SHOW_BACK_BUTTON} = 1;
 
 930   $self->{title} = $params{title} if $params{title};
 
 933   print $self->parse_html_template("generic/error", $add_params);
 
 935   print STDERR "Error: $error\n";
 
 937   $main::lxdebug->leave_sub();
 
 942 sub show_generic_information {
 
 943   $main::lxdebug->enter_sub();
 
 945   my ($self, $text, $title) = @_;
 
 948     'title_information' => $title,
 
 949     'label_information' => $text,
 
 952   $self->{title} = $title if ($title);
 
 955   print $self->parse_html_template("generic/information", $add_params);
 
 957   $main::lxdebug->leave_sub();
 
 962 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
 
 963 # changed it to accept an arbitrary number of triggers - sschoeling
 
 965   $main::lxdebug->enter_sub();
 
 968   my $myconfig = shift;
 
 971   # set dateform for jsscript
 
 974     "dd.mm.yy" => "%d.%m.%Y",
 
 975     "dd-mm-yy" => "%d-%m-%Y",
 
 976     "dd/mm/yy" => "%d/%m/%Y",
 
 977     "mm/dd/yy" => "%m/%d/%Y",
 
 978     "mm-dd-yy" => "%m-%d-%Y",
 
 979     "yyyy-mm-dd" => "%Y-%m-%d",
 
 982   my $ifFormat = defined($dateformats{$myconfig->{"dateformat"}}) ?
 
 983     $dateformats{$myconfig->{"dateformat"}} : "%d.%m.%Y";
 
 990       inputField : "| . (shift) . qq|",
 
 991       ifFormat :"$ifFormat",
 
 992       align : "| .  (shift) . qq|",
 
 993       button : "| . (shift) . qq|"
 
 999        <script type="text/javascript">
 
1000        <!--| . join("", @triggers) . qq|//-->
 
1004   $main::lxdebug->leave_sub();
 
1007 }    #end sub write_trigger
 
1010   $main::lxdebug->enter_sub();
 
1012   my ($self, $msg) = @_;
 
1014   if (!$self->{callback}) {
 
1020 #  my ($script, $argv) = split(/\?/, $self->{callback}, 2);
 
1021 #  $script =~ s|.*/||;
 
1022 #  $script =~ s|[^a-zA-Z0-9_\.]||g;
 
1023 #  exec("perl", "$script", $argv);
 
1025   print $::form->redirect_header($self->{callback});
 
1027   $main::lxdebug->leave_sub();
 
1030 # sort of columns removed - empty sub
 
1032   $main::lxdebug->enter_sub();
 
1034   my ($self, @columns) = @_;
 
1036   $main::lxdebug->leave_sub();
 
1042   $main::lxdebug->enter_sub(2);
 
1044   my ($self, $myconfig, $amount, $places, $dash) = @_;
 
1046   if ($amount eq "") {
 
1050   # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
 
1052   my $neg = ($amount =~ s/^-//);
 
1053   my $exp = ($amount =~ m/[e]/) ? 1 : 0;
 
1055   if (defined($places) && ($places ne '')) {
 
1061         my ($actual_places) = ($amount =~ /\.(\d+)/);
 
1062         $actual_places = length($actual_places);
 
1063         $places = $actual_places > $places ? $actual_places : $places;
 
1066     $amount = $self->round_amount($amount, $places);
 
1069   my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
 
1070   my @p = split(/\./, $amount); # split amount at decimal point
 
1072   $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
 
1075   $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
 
1078     ($dash =~ /-/)    ? ($neg ? "($amount)"                            : "$amount" )                              :
 
1079     ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
 
1080                         ($neg ? "-$amount"                             : "$amount" )                              ;
 
1084   $main::lxdebug->leave_sub(2);
 
1088 sub format_amount_units {
 
1089   $main::lxdebug->enter_sub();
 
1094   my $myconfig         = \%main::myconfig;
 
1095   my $amount           = $params{amount} * 1;
 
1096   my $places           = $params{places};
 
1097   my $part_unit_name   = $params{part_unit};
 
1098   my $amount_unit_name = $params{amount_unit};
 
1099   my $conv_units       = $params{conv_units};
 
1100   my $max_places       = $params{max_places};
 
1102   if (!$part_unit_name) {
 
1103     $main::lxdebug->leave_sub();
 
1107   AM->retrieve_all_units();
 
1108   my $all_units        = $main::all_units;
 
1110   if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
 
1111     $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
 
1114   if (!scalar @{ $conv_units }) {
 
1115     my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
 
1116     $main::lxdebug->leave_sub();
 
1120   my $part_unit  = $all_units->{$part_unit_name};
 
1121   my $conv_unit  = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
 
1123   $amount       *= $conv_unit->{factor};
 
1128   foreach my $unit (@$conv_units) {
 
1129     my $last = $unit->{name} eq $part_unit->{name};
 
1131       $num     = int($amount / $unit->{factor});
 
1132       $amount -= $num * $unit->{factor};
 
1135     if ($last ? $amount : $num) {
 
1136       push @values, { "unit"   => $unit->{name},
 
1137                       "amount" => $last ? $amount / $unit->{factor} : $num,
 
1138                       "places" => $last ? $places : 0 };
 
1145     push @values, { "unit"   => $part_unit_name,
 
1150   my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
 
1152   $main::lxdebug->leave_sub();
 
1158   $main::lxdebug->enter_sub(2);
 
1163   $input =~ s/(^|[^\#]) \#  (\d+)  /$1$_[$2 - 1]/gx;
 
1164   $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
 
1165   $input =~ s/\#\#/\#/g;
 
1167   $main::lxdebug->leave_sub(2);
 
1175   $main::lxdebug->enter_sub(2);
 
1177   my ($self, $myconfig, $amount) = @_;
 
1179   if (   ($myconfig->{numberformat} eq '1.000,00')
 
1180       || ($myconfig->{numberformat} eq '1000,00')) {
 
1185   if ($myconfig->{numberformat} eq "1'000.00") {
 
1191   $main::lxdebug->leave_sub(2);
 
1193   return ($amount * 1);
 
1197   $main::lxdebug->enter_sub(2);
 
1199   my ($self, $amount, $places) = @_;
 
1202   # Rounding like "Kaufmannsrunden" (see http://de.wikipedia.org/wiki/Rundung )
 
1204   # Round amounts to eight places before rounding to the requested
 
1205   # number of places. This gets rid of errors due to internal floating
 
1206   # point representation.
 
1207   $amount       = $self->round_amount($amount, 8) if $places < 8;
 
1208   $amount       = $amount * (10**($places));
 
1209   $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
 
1211   $main::lxdebug->leave_sub(2);
 
1213   return $round_amount;
 
1217 sub parse_template {
 
1218   $main::lxdebug->enter_sub();
 
1220   my ($self, $myconfig, $userspath) = @_;
 
1225   $self->{"cwd"} = getcwd();
 
1226   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
 
1231   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
 
1232     $template_type  = 'OpenDocument';
 
1233     $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
 
1235   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
 
1236     $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
 
1237     $template_type    = 'LaTeX';
 
1238     $ext_for_format   = 'pdf';
 
1240   } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
 
1241     $template_type  = 'HTML';
 
1242     $ext_for_format = 'html';
 
1244   } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
 
1245     $template_type  = 'XML';
 
1246     $ext_for_format = 'xml';
 
1248   } elsif ( $self->{"format"} =~ /elster(?:winston|taxbird)/i ) {
 
1249     $template_type = 'xml';
 
1251   } elsif ( $self->{"format"} =~ /excel/i ) {
 
1252     $template_type  = 'Excel';
 
1253     $ext_for_format = 'xls';
 
1255   } elsif ( defined $self->{'format'}) {
 
1256     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
 
1258   } elsif ( $self->{'format'} eq '' ) {
 
1259     $self->error("No Outputformat given: $self->{'format'}");
 
1261   } else { #Catch the rest
 
1262     $self->error("Outputformat not defined: $self->{'format'}");
 
1265   my $template = SL::Template::create(type      => $template_type,
 
1266                                       file_name => $self->{IN},
 
1268                                       myconfig  => $myconfig,
 
1269                                       userspath => $userspath);
 
1271   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
 
1272   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
 
1274   if (!$self->{employee_id}) {
 
1275     map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
 
1278   map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
 
1280   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
 
1282   # OUT is used for the media, screen, printer, email
 
1283   # for postscript we store a copy in a temporary file
 
1285   my $prepend_userspath;
 
1287   if (!$self->{tmpfile}) {
 
1288     $self->{tmpfile}   = "${fileid}.$self->{IN}";
 
1289     $prepend_userspath = 1;
 
1292   $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
 
1294   $self->{tmpfile} =~ s|.*/||;
 
1295   $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
 
1296   $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
 
1298   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
1299     $out = $self->{OUT};
 
1300     $self->{OUT} = ">$self->{tmpfile}";
 
1306     open OUT, "$self->{OUT}" or $self->error("$self->{OUT} : $!");
 
1307     $result = $template->parse(*OUT);
 
1312     $result = $template->parse(*STDOUT);
 
1317     $self->error("$self->{IN} : " . $template->get_error());
 
1320   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
1322     if ($self->{media} eq 'email') {
 
1324       my $mail = new Mailer;
 
1326       map { $mail->{$_} = $self->{$_} }
 
1327         qw(cc bcc subject message version format);
 
1328       $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
1329       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
 
1330       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
 
1331       $mail->{fileid} = "$fileid.";
 
1332       $myconfig->{signature} =~ s/\r//g;
 
1334       # if we send html or plain text inline
 
1335       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
 
1336         $mail->{contenttype} = "text/html";
 
1338         $mail->{message}       =~ s/\r//g;
 
1339         $mail->{message}       =~ s/\n/<br>\n/g;
 
1340         $myconfig->{signature} =~ s/\n/<br>\n/g;
 
1341         $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
 
1343         open(IN, $self->{tmpfile})
 
1344           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1346           $mail->{message} .= $_;
 
1353         if (!$self->{"do_not_attach"}) {
 
1354           my $attachment_name  =  $self->{attachment_filename} || $self->{tmpfile};
 
1355           $attachment_name     =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
 
1356           $mail->{attachments} =  [{ "filename" => $self->{tmpfile},
 
1357                                      "name"     => $attachment_name }];
 
1360         $mail->{message}  =~ s/\r//g;
 
1361         $mail->{message} .=  "\n-- \n$myconfig->{signature}";
 
1365       my $err = $mail->send();
 
1366       $self->error($self->cleanup . "$err") if ($err);
 
1370       $self->{OUT} = $out;
 
1372       my $numbytes = (-s $self->{tmpfile});
 
1373       open(IN, $self->{tmpfile})
 
1374         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1376       $self->{copies} = 1 unless $self->{media} eq 'printer';
 
1378       chdir("$self->{cwd}");
 
1379       #print(STDERR "Kopien $self->{copies}\n");
 
1380       #print(STDERR "OUT $self->{OUT}\n");
 
1381       for my $i (1 .. $self->{copies}) {
 
1383           open OUT, $self->{OUT} or $self->error($self->cleanup . "$self->{OUT} : $!");
 
1384           print OUT while <IN>;
 
1389           $self->{attachment_filename} = ($self->{attachment_filename})
 
1390                                        ? $self->{attachment_filename}
 
1391                                        : $self->generate_attachment_filename();
 
1393           # launch application
 
1394           print qq|Content-Type: | . $template->get_mime_type() . qq|
 
1395 Content-Disposition: attachment; filename="$self->{attachment_filename}"
 
1396 Content-Length: $numbytes
 
1400           $::locale->with_raw_io(\*STDOUT, sub { print while <IN> });
 
1411   chdir("$self->{cwd}");
 
1412   $main::lxdebug->leave_sub();
 
1415 sub get_formname_translation {
 
1416   $main::lxdebug->enter_sub();
 
1417   my ($self, $formname) = @_;
 
1419   $formname ||= $self->{formname};
 
1421   my %formname_translations = (
 
1422     bin_list                => $main::locale->text('Bin List'),
 
1423     credit_note             => $main::locale->text('Credit Note'),
 
1424     invoice                 => $main::locale->text('Invoice'),
 
1425     packing_list            => $main::locale->text('Packing List'),
 
1426     pick_list               => $main::locale->text('Pick List'),
 
1427     proforma                => $main::locale->text('Proforma Invoice'),
 
1428     purchase_order          => $main::locale->text('Purchase Order'),
 
1429     request_quotation       => $main::locale->text('RFQ'),
 
1430     sales_order             => $main::locale->text('Confirmation'),
 
1431     sales_quotation         => $main::locale->text('Quotation'),
 
1432     storno_invoice          => $main::locale->text('Storno Invoice'),
 
1433     storno_packing_list     => $main::locale->text('Storno Packing List'),
 
1434     sales_delivery_order    => $main::locale->text('Delivery Order'),
 
1435     purchase_delivery_order => $main::locale->text('Delivery Order'),
 
1436     dunning                 => $main::locale->text('Dunning'),
 
1439   $main::lxdebug->leave_sub();
 
1440   return $formname_translations{$formname}
 
1443 sub get_number_prefix_for_type {
 
1444   $main::lxdebug->enter_sub();
 
1448       (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
 
1449     : ($self->{type} =~ /_quotation$/)                        ? 'quo'
 
1450     : ($self->{type} =~ /_delivery_order$/)                   ? 'do'
 
1453   $main::lxdebug->leave_sub();
 
1457 sub get_extension_for_format {
 
1458   $main::lxdebug->enter_sub();
 
1461   my $extension = $self->{format} =~ /pdf/i          ? ".pdf"
 
1462                 : $self->{format} =~ /postscript/i   ? ".ps"
 
1463                 : $self->{format} =~ /opendocument/i ? ".odt"
 
1464                 : $self->{format} =~ /excel/i        ? ".xls"
 
1465                 : $self->{format} =~ /html/i         ? ".html"
 
1468   $main::lxdebug->leave_sub();
 
1472 sub generate_attachment_filename {
 
1473   $main::lxdebug->enter_sub();
 
1476   my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
 
1477   my $prefix              = $self->get_number_prefix_for_type();
 
1479   if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
 
1480     $attachment_filename .= ' (' . $main::locale->text('Preview') . ')' . $self->get_extension_for_format();
 
1482   } elsif ($attachment_filename && $self->{"${prefix}number"}) {
 
1483     $attachment_filename .=  "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
 
1486     $attachment_filename = "";
 
1489   $attachment_filename =  $main::locale->quote_special_chars('filenames', $attachment_filename);
 
1490   $attachment_filename =~ s|[\s/\\]+|_|g;
 
1492   $main::lxdebug->leave_sub();
 
1493   return $attachment_filename;
 
1496 sub generate_email_subject {
 
1497   $main::lxdebug->enter_sub();
 
1500   my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
 
1501   my $prefix  = $self->get_number_prefix_for_type();
 
1503   if ($subject && $self->{"${prefix}number"}) {
 
1504     $subject .= " " . $self->{"${prefix}number"}
 
1507   $main::lxdebug->leave_sub();
 
1512   $main::lxdebug->enter_sub();
 
1516   chdir("$self->{tmpdir}");
 
1519   if (-f "$self->{tmpfile}.err") {
 
1520     open(FH, "$self->{tmpfile}.err");
 
1525   if ($self->{tmpfile} && ! $::keep_temp_files) {
 
1526     $self->{tmpfile} =~ s|.*/||g;
 
1528     $self->{tmpfile} =~ s/\.\w+$//g;
 
1529     my $tmpfile = $self->{tmpfile};
 
1530     unlink(<$tmpfile.*>);
 
1533   chdir("$self->{cwd}");
 
1535   $main::lxdebug->leave_sub();
 
1541   $main::lxdebug->enter_sub();
 
1543   my ($self, $date, $myconfig) = @_;
 
1546   if ($date && $date =~ /\D/) {
 
1548     if ($myconfig->{dateformat} =~ /^yy/) {
 
1549       ($yy, $mm, $dd) = split /\D/, $date;
 
1551     if ($myconfig->{dateformat} =~ /^mm/) {
 
1552       ($mm, $dd, $yy) = split /\D/, $date;
 
1554     if ($myconfig->{dateformat} =~ /^dd/) {
 
1555       ($dd, $mm, $yy) = split /\D/, $date;
 
1560     $yy = ($yy < 70) ? $yy + 2000 : $yy;
 
1561     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
 
1563     $dd = "0$dd" if ($dd < 10);
 
1564     $mm = "0$mm" if ($mm < 10);
 
1566     $date = "$yy$mm$dd";
 
1569   $main::lxdebug->leave_sub();
 
1574 # Database routines used throughout
 
1576 sub _dbconnect_options {
 
1578   my $options = { pg_enable_utf8 => $::locale->is_utf8,
 
1585   $main::lxdebug->enter_sub(2);
 
1587   my ($self, $myconfig) = @_;
 
1589   # connect to database
 
1590   my $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, $self->_dbconnect_options)
 
1594   if ($myconfig->{dboptions}) {
 
1595     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1598   $main::lxdebug->leave_sub(2);
 
1603 sub dbconnect_noauto {
 
1604   $main::lxdebug->enter_sub();
 
1606   my ($self, $myconfig) = @_;
 
1608   # connect to database
 
1609   my $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, $self->_dbconnect_options(AutoCommit => 0))
 
1613   if ($myconfig->{dboptions}) {
 
1614     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1617   $main::lxdebug->leave_sub();
 
1622 sub get_standard_dbh {
 
1623   $main::lxdebug->enter_sub(2);
 
1626   my $myconfig = shift || \%::myconfig;
 
1628   if ($standard_dbh && !$standard_dbh->{Active}) {
 
1629     $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
 
1630     undef $standard_dbh;
 
1633   $standard_dbh ||= $self->dbconnect_noauto($myconfig);
 
1635   $main::lxdebug->leave_sub(2);
 
1637   return $standard_dbh;
 
1641   $main::lxdebug->enter_sub();
 
1643   my ($self, $date, $myconfig) = @_;
 
1644   my $dbh = $self->dbconnect($myconfig);
 
1646   my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
 
1647   my $sth = prepare_execute_query($self, $dbh, $query, $date);
 
1648   my ($closed) = $sth->fetchrow_array;
 
1650   $main::lxdebug->leave_sub();
 
1655 sub update_balance {
 
1656   $main::lxdebug->enter_sub();
 
1658   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
 
1660   # if we have a value, go do it
 
1663     # retrieve balance from table
 
1664     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
 
1665     my $sth = prepare_execute_query($self, $dbh, $query, @values);
 
1666     my ($balance) = $sth->fetchrow_array;
 
1672     $query = "UPDATE $table SET $field = $balance WHERE $where";
 
1673     do_query($self, $dbh, $query, @values);
 
1675   $main::lxdebug->leave_sub();
 
1678 sub update_exchangerate {
 
1679   $main::lxdebug->enter_sub();
 
1681   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
 
1683   # some sanity check for currency
 
1685     $main::lxdebug->leave_sub();
 
1688   $query = qq|SELECT curr FROM defaults|;
 
1690   my ($currency) = selectrow_query($self, $dbh, $query);
 
1691   my ($defaultcurrency) = split m/:/, $currency;
 
1694   if ($curr eq $defaultcurrency) {
 
1695     $main::lxdebug->leave_sub();
 
1699   $query = qq|SELECT e.curr FROM exchangerate e
 
1700                  WHERE e.curr = ? AND e.transdate = ?
 
1702   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
 
1711   $buy = conv_i($buy, "NULL");
 
1712   $sell = conv_i($sell, "NULL");
 
1715   if ($buy != 0 && $sell != 0) {
 
1716     $set = "buy = $buy, sell = $sell";
 
1717   } elsif ($buy != 0) {
 
1718     $set = "buy = $buy";
 
1719   } elsif ($sell != 0) {
 
1720     $set = "sell = $sell";
 
1723   if ($sth->fetchrow_array) {
 
1724     $query = qq|UPDATE exchangerate
 
1730     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
 
1731                 VALUES (?, $buy, $sell, ?)|;
 
1734   do_query($self, $dbh, $query, $curr, $transdate);
 
1736   $main::lxdebug->leave_sub();
 
1739 sub save_exchangerate {
 
1740   $main::lxdebug->enter_sub();
 
1742   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
 
1744   my $dbh = $self->dbconnect($myconfig);
 
1748   $buy  = $rate if $fld eq 'buy';
 
1749   $sell = $rate if $fld eq 'sell';
 
1752   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
 
1757   $main::lxdebug->leave_sub();
 
1760 sub get_exchangerate {
 
1761   $main::lxdebug->enter_sub();
 
1763   my ($self, $dbh, $curr, $transdate, $fld) = @_;
 
1766   unless ($transdate) {
 
1767     $main::lxdebug->leave_sub();
 
1771   $query = qq|SELECT curr FROM defaults|;
 
1773   my ($currency) = selectrow_query($self, $dbh, $query);
 
1774   my ($defaultcurrency) = split m/:/, $currency;
 
1776   if ($currency eq $defaultcurrency) {
 
1777     $main::lxdebug->leave_sub();
 
1781   $query = qq|SELECT e.$fld FROM exchangerate e
 
1782                  WHERE e.curr = ? AND e.transdate = ?|;
 
1783   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
 
1787   $main::lxdebug->leave_sub();
 
1789   return $exchangerate;
 
1792 sub check_exchangerate {
 
1793   $main::lxdebug->enter_sub();
 
1795   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
 
1797   if ($fld !~/^buy|sell$/) {
 
1798     $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
 
1801   unless ($transdate) {
 
1802     $main::lxdebug->leave_sub();
 
1806   my ($defaultcurrency) = $self->get_default_currency($myconfig);
 
1808   if ($currency eq $defaultcurrency) {
 
1809     $main::lxdebug->leave_sub();
 
1813   my $dbh   = $self->get_standard_dbh($myconfig);
 
1814   my $query = qq|SELECT e.$fld FROM exchangerate e
 
1815                  WHERE e.curr = ? AND e.transdate = ?|;
 
1817   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
 
1819   $main::lxdebug->leave_sub();
 
1821   return $exchangerate;
 
1824 sub get_all_currencies {
 
1825   $main::lxdebug->enter_sub();
 
1828   my $myconfig = shift || \%::myconfig;
 
1829   my $dbh      = $self->get_standard_dbh($myconfig);
 
1831   my $query = qq|SELECT curr FROM defaults|;
 
1833   my ($curr)     = selectrow_query($self, $dbh, $query);
 
1834   my @currencies = grep { $_ } map { s/\s//g; $_ } split m/:/, $curr;
 
1836   $main::lxdebug->leave_sub();
 
1841 sub get_default_currency {
 
1842   $main::lxdebug->enter_sub();
 
1844   my ($self, $myconfig) = @_;
 
1845   my @currencies        = $self->get_all_currencies($myconfig);
 
1847   $main::lxdebug->leave_sub();
 
1849   return $currencies[0];
 
1852 sub set_payment_options {
 
1853   $main::lxdebug->enter_sub();
 
1855   my ($self, $myconfig, $transdate) = @_;
 
1857   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
 
1859   my $dbh = $self->get_standard_dbh($myconfig);
 
1862     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
 
1863     qq|FROM payment_terms p | .
 
1866   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
 
1867    $self->{payment_terms}) =
 
1868      selectrow_query($self, $dbh, $query, $self->{payment_id});
 
1870   if ($transdate eq "") {
 
1871     if ($self->{invdate}) {
 
1872       $transdate = $self->{invdate};
 
1874       $transdate = $self->{transdate};
 
1879     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
 
1880     qq|FROM payment_terms|;
 
1881   ($self->{netto_date}, $self->{skonto_date}) =
 
1882     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
 
1884   my ($invtotal, $total);
 
1885   my (%amounts, %formatted_amounts);
 
1887   if ($self->{type} =~ /_order$/) {
 
1888     $amounts{invtotal} = $self->{ordtotal};
 
1889     $amounts{total}    = $self->{ordtotal};
 
1891   } elsif ($self->{type} =~ /_quotation$/) {
 
1892     $amounts{invtotal} = $self->{quototal};
 
1893     $amounts{total}    = $self->{quototal};
 
1896     $amounts{invtotal} = $self->{invtotal};
 
1897     $amounts{total}    = $self->{total};
 
1899   $amounts{skonto_in_percent} = 100.0 * $self->{percent_skonto};
 
1901   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
 
1903   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
 
1904   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
 
1905   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
 
1907   foreach (keys %amounts) {
 
1908     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
 
1909     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
 
1912   if ($self->{"language_id"}) {
 
1914       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
 
1915       qq|FROM translation_payment_terms t | .
 
1916       qq|LEFT JOIN language l ON t.language_id = l.id | .
 
1917       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
 
1918     my ($description_long, $output_numberformat, $output_dateformat,
 
1919       $output_longdates) =
 
1920       selectrow_query($self, $dbh, $query,
 
1921                       $self->{"language_id"}, $self->{"payment_id"});
 
1923     $self->{payment_terms} = $description_long if ($description_long);
 
1925     if ($output_dateformat) {
 
1926       foreach my $key (qw(netto_date skonto_date)) {
 
1928           $main::locale->reformat_date($myconfig, $self->{$key},
 
1934     if ($output_numberformat &&
 
1935         ($output_numberformat ne $myconfig->{"numberformat"})) {
 
1936       my $saved_numberformat = $myconfig->{"numberformat"};
 
1937       $myconfig->{"numberformat"} = $output_numberformat;
 
1938       map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
 
1939       $myconfig->{"numberformat"} = $saved_numberformat;
 
1943   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
 
1944   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
 
1945   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
 
1946   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
 
1947   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
 
1948   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
 
1949   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
 
1951   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
 
1953   $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
 
1955   $main::lxdebug->leave_sub();
 
1959 sub get_template_language {
 
1960   $main::lxdebug->enter_sub();
 
1962   my ($self, $myconfig) = @_;
 
1964   my $template_code = "";
 
1966   if ($self->{language_id}) {
 
1967     my $dbh = $self->get_standard_dbh($myconfig);
 
1968     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
 
1969     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
 
1972   $main::lxdebug->leave_sub();
 
1974   return $template_code;
 
1977 sub get_printer_code {
 
1978   $main::lxdebug->enter_sub();
 
1980   my ($self, $myconfig) = @_;
 
1982   my $template_code = "";
 
1984   if ($self->{printer_id}) {
 
1985     my $dbh = $self->get_standard_dbh($myconfig);
 
1986     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
 
1987     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
 
1990   $main::lxdebug->leave_sub();
 
1992   return $template_code;
 
1996   $main::lxdebug->enter_sub();
 
1998   my ($self, $myconfig) = @_;
 
2000   my $template_code = "";
 
2002   if ($self->{shipto_id}) {
 
2003     my $dbh = $self->get_standard_dbh($myconfig);
 
2004     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
 
2005     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
 
2006     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
 
2009   $main::lxdebug->leave_sub();
 
2013   $main::lxdebug->enter_sub();
 
2015   my ($self, $dbh, $id, $module) = @_;
 
2020   foreach my $item (qw(name department_1 department_2 street zipcode city country
 
2021                        contact phone fax email)) {
 
2022     if ($self->{"shipto$item"}) {
 
2023       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
 
2025     push(@values, $self->{"shipto${item}"});
 
2029     if ($self->{shipto_id}) {
 
2030       my $query = qq|UPDATE shipto set
 
2032                        shiptodepartment_1 = ?,
 
2033                        shiptodepartment_2 = ?,
 
2042                      WHERE shipto_id = ?|;
 
2043       do_query($self, $dbh, $query, @values, $self->{shipto_id});
 
2045       my $query = qq|SELECT * FROM shipto
 
2046                      WHERE shiptoname = ? AND
 
2047                        shiptodepartment_1 = ? AND
 
2048                        shiptodepartment_2 = ? AND
 
2049                        shiptostreet = ? AND
 
2050                        shiptozipcode = ? AND
 
2052                        shiptocountry = ? AND
 
2053                        shiptocontact = ? AND
 
2059       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
 
2062           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
 
2063                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
 
2064                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
 
2065              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
 
2066         do_query($self, $dbh, $query, $id, @values, $module);
 
2071   $main::lxdebug->leave_sub();
 
2075   $main::lxdebug->enter_sub();
 
2077   my ($self, $dbh) = @_;
 
2079   $dbh ||= $self->get_standard_dbh(\%main::myconfig);
 
2081   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
 
2082   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
 
2083   $self->{"employee_id"} *= 1;
 
2085   $main::lxdebug->leave_sub();
 
2088 sub get_employee_data {
 
2089   $main::lxdebug->enter_sub();
 
2094   Common::check_params(\%params, qw(prefix));
 
2095   Common::check_params_x(\%params, qw(id));
 
2098     $main::lxdebug->leave_sub();
 
2102   my $myconfig = \%main::myconfig;
 
2103   my $dbh      = $params{dbh} || $self->get_standard_dbh($myconfig);
 
2105   my ($login)  = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
 
2108     my $user = User->new($login);
 
2109     map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
 
2111     $self->{$params{prefix} . '_login'}   = $login;
 
2112     $self->{$params{prefix} . '_name'}  ||= $login;
 
2115   $main::lxdebug->leave_sub();
 
2119   $main::lxdebug->enter_sub();
 
2121   my ($self, $myconfig, $reference_date) = @_;
 
2123   $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
 
2125   my $dbh         = $self->get_standard_dbh($myconfig);
 
2126   my $query       = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
 
2127   my ($duedate)   = selectrow_query($self, $dbh, $query, $self->{payment_id});
 
2129   $main::lxdebug->leave_sub();
 
2135   $main::lxdebug->enter_sub();
 
2137   my ($self, $dbh, $id, $key) = @_;
 
2139   $key = "all_contacts" unless ($key);
 
2143     $main::lxdebug->leave_sub();
 
2148     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
 
2149     qq|FROM contacts | .
 
2150     qq|WHERE cp_cv_id = ? | .
 
2151     qq|ORDER BY lower(cp_name)|;
 
2153   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
 
2155   $main::lxdebug->leave_sub();
 
2159   $main::lxdebug->enter_sub();
 
2161   my ($self, $dbh, $key) = @_;
 
2163   my ($all, $old_id, $where, @values);
 
2165   if (ref($key) eq "HASH") {
 
2168     $key = "ALL_PROJECTS";
 
2170     foreach my $p (keys(%{$params})) {
 
2172         $all = $params->{$p};
 
2173       } elsif ($p eq "old_id") {
 
2174         $old_id = $params->{$p};
 
2175       } elsif ($p eq "key") {
 
2176         $key = $params->{$p};
 
2182     $where = "WHERE active ";
 
2184       if (ref($old_id) eq "ARRAY") {
 
2185         my @ids = grep({ $_ } @{$old_id});
 
2187           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
 
2188           push(@values, @ids);
 
2191         $where .= " OR (id = ?) ";
 
2192         push(@values, $old_id);
 
2198     qq|SELECT id, projectnumber, description, active | .
 
2201     qq|ORDER BY lower(projectnumber)|;
 
2203   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
 
2205   $main::lxdebug->leave_sub();
 
2209   $main::lxdebug->enter_sub();
 
2211   my ($self, $dbh, $vc_id, $key) = @_;
 
2213   $key = "all_shipto" unless ($key);
 
2216     # get shipping addresses
 
2217     my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
 
2219     $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
 
2225   $main::lxdebug->leave_sub();
 
2229   $main::lxdebug->enter_sub();
 
2231   my ($self, $dbh, $key) = @_;
 
2233   $key = "all_printers" unless ($key);
 
2235   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
 
2237   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2239   $main::lxdebug->leave_sub();
 
2243   $main::lxdebug->enter_sub();
 
2245   my ($self, $dbh, $params) = @_;
 
2248   $key = $params->{key};
 
2249   $key = "all_charts" unless ($key);
 
2251   my $transdate = quote_db_date($params->{transdate});
 
2254     qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
 
2256     qq|LEFT JOIN taxkeys tk ON | .
 
2257     qq|(tk.id = (SELECT id FROM taxkeys | .
 
2258     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
 
2259     qq|          ORDER BY startdate DESC LIMIT 1)) | .
 
2260     qq|ORDER BY c.accno|;
 
2262   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2264   $main::lxdebug->leave_sub();
 
2267 sub _get_taxcharts {
 
2268   $main::lxdebug->enter_sub();
 
2270   my ($self, $dbh, $params) = @_;
 
2272   my $key = "all_taxcharts";
 
2275   if (ref $params eq 'HASH') {
 
2276     $key = $params->{key} if ($params->{key});
 
2277     if ($params->{module} eq 'AR') {
 
2278       push @where, 'taxkey NOT IN (8, 9, 18, 19)';
 
2280     } elsif ($params->{module} eq 'AP') {
 
2281       push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
 
2288   my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
 
2290   my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
 
2292   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2294   $main::lxdebug->leave_sub();
 
2298   $main::lxdebug->enter_sub();
 
2300   my ($self, $dbh, $key) = @_;
 
2302   $key = "all_taxzones" unless ($key);
 
2304   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
 
2306   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2308   $main::lxdebug->leave_sub();
 
2311 sub _get_employees {
 
2312   $main::lxdebug->enter_sub();
 
2314   my ($self, $dbh, $default_key, $key) = @_;
 
2316   $key = $default_key unless ($key);
 
2317   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
 
2319   $main::lxdebug->leave_sub();
 
2322 sub _get_business_types {
 
2323   $main::lxdebug->enter_sub();
 
2325   my ($self, $dbh, $key) = @_;
 
2327   my $options       = ref $key eq 'HASH' ? $key : { key => $key };
 
2328   $options->{key} ||= "all_business_types";
 
2331   if (exists $options->{salesman}) {
 
2332     $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
 
2335   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
 
2337   $main::lxdebug->leave_sub();
 
2340 sub _get_languages {
 
2341   $main::lxdebug->enter_sub();
 
2343   my ($self, $dbh, $key) = @_;
 
2345   $key = "all_languages" unless ($key);
 
2347   my $query = qq|SELECT * FROM language ORDER BY id|;
 
2349   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2351   $main::lxdebug->leave_sub();
 
2354 sub _get_dunning_configs {
 
2355   $main::lxdebug->enter_sub();
 
2357   my ($self, $dbh, $key) = @_;
 
2359   $key = "all_dunning_configs" unless ($key);
 
2361   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
 
2363   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2365   $main::lxdebug->leave_sub();
 
2368 sub _get_currencies {
 
2369 $main::lxdebug->enter_sub();
 
2371   my ($self, $dbh, $key) = @_;
 
2373   $key = "all_currencies" unless ($key);
 
2375   my $query = qq|SELECT curr AS currency FROM defaults|;
 
2377   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
 
2379   $main::lxdebug->leave_sub();
 
2383 $main::lxdebug->enter_sub();
 
2385   my ($self, $dbh, $key) = @_;
 
2387   $key = "all_payments" unless ($key);
 
2389   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
 
2391   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2393   $main::lxdebug->leave_sub();
 
2396 sub _get_customers {
 
2397   $main::lxdebug->enter_sub();
 
2399   my ($self, $dbh, $key) = @_;
 
2401   my $options        = ref $key eq 'HASH' ? $key : { key => $key };
 
2402   $options->{key}  ||= "all_customers";
 
2403   my $limit_clause   = "LIMIT $options->{limit}" if $options->{limit};
 
2406   push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if  $options->{business_is_salesman};
 
2407   push @where, qq|NOT obsolete|                                            if !$options->{with_obsolete};
 
2408   my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : '';
 
2410   my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|;
 
2411   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
 
2413   $main::lxdebug->leave_sub();
 
2417   $main::lxdebug->enter_sub();
 
2419   my ($self, $dbh, $key) = @_;
 
2421   $key = "all_vendors" unless ($key);
 
2423   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
 
2425   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2427   $main::lxdebug->leave_sub();
 
2430 sub _get_departments {
 
2431   $main::lxdebug->enter_sub();
 
2433   my ($self, $dbh, $key) = @_;
 
2435   $key = "all_departments" unless ($key);
 
2437   my $query = qq|SELECT * FROM department ORDER BY description|;
 
2439   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2441   $main::lxdebug->leave_sub();
 
2444 sub _get_warehouses {
 
2445   $main::lxdebug->enter_sub();
 
2447   my ($self, $dbh, $param) = @_;
 
2449   my ($key, $bins_key);
 
2451   if ('' eq ref $param) {
 
2455     $key      = $param->{key};
 
2456     $bins_key = $param->{bins};
 
2459   my $query = qq|SELECT w.* FROM warehouse w
 
2460                  WHERE (NOT w.invalid) AND
 
2461                    ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
 
2462                  ORDER BY w.sortkey|;
 
2464   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2467     $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
 
2468     my $sth = prepare_query($self, $dbh, $query);
 
2470     foreach my $warehouse (@{ $self->{$key} }) {
 
2471       do_statement($self, $sth, $query, $warehouse->{id});
 
2472       $warehouse->{$bins_key} = [];
 
2474       while (my $ref = $sth->fetchrow_hashref()) {
 
2475         push @{ $warehouse->{$bins_key} }, $ref;
 
2481   $main::lxdebug->leave_sub();
 
2485   $main::lxdebug->enter_sub();
 
2487   my ($self, $dbh, $table, $key, $sortkey) = @_;
 
2489   my $query  = qq|SELECT * FROM $table|;
 
2490   $query    .= qq| ORDER BY $sortkey| if ($sortkey);
 
2492   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2494   $main::lxdebug->leave_sub();
 
2498 #  $main::lxdebug->enter_sub();
 
2500 #  my ($self, $dbh, $key) = @_;
 
2502 #  $key ||= "all_groups";
 
2504 #  my $groups = $main::auth->read_groups();
 
2506 #  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2508 #  $main::lxdebug->leave_sub();
 
2512   $main::lxdebug->enter_sub();
 
2517   my $dbh = $self->get_standard_dbh(\%main::myconfig);
 
2518   my ($sth, $query, $ref);
 
2520   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
 
2521   my $vc_id = $self->{"${vc}_id"};
 
2523   if ($params{"contacts"}) {
 
2524     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
 
2527   if ($params{"shipto"}) {
 
2528     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
 
2531   if ($params{"projects"} || $params{"all_projects"}) {
 
2532     $self->_get_projects($dbh, $params{"all_projects"} ?
 
2533                          $params{"all_projects"} : $params{"projects"},
 
2534                          $params{"all_projects"} ? 1 : 0);
 
2537   if ($params{"printers"}) {
 
2538     $self->_get_printers($dbh, $params{"printers"});
 
2541   if ($params{"languages"}) {
 
2542     $self->_get_languages($dbh, $params{"languages"});
 
2545   if ($params{"charts"}) {
 
2546     $self->_get_charts($dbh, $params{"charts"});
 
2549   if ($params{"taxcharts"}) {
 
2550     $self->_get_taxcharts($dbh, $params{"taxcharts"});
 
2553   if ($params{"taxzones"}) {
 
2554     $self->_get_taxzones($dbh, $params{"taxzones"});
 
2557   if ($params{"employees"}) {
 
2558     $self->_get_employees($dbh, "all_employees", $params{"employees"});
 
2561   if ($params{"salesmen"}) {
 
2562     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
 
2565   if ($params{"business_types"}) {
 
2566     $self->_get_business_types($dbh, $params{"business_types"});
 
2569   if ($params{"dunning_configs"}) {
 
2570     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
 
2573   if($params{"currencies"}) {
 
2574     $self->_get_currencies($dbh, $params{"currencies"});
 
2577   if($params{"customers"}) {
 
2578     $self->_get_customers($dbh, $params{"customers"});
 
2581   if($params{"vendors"}) {
 
2582     if (ref $params{"vendors"} eq 'HASH') {
 
2583       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
 
2585       $self->_get_vendors($dbh, $params{"vendors"});
 
2589   if($params{"payments"}) {
 
2590     $self->_get_payments($dbh, $params{"payments"});
 
2593   if($params{"departments"}) {
 
2594     $self->_get_departments($dbh, $params{"departments"});
 
2597   if ($params{price_factors}) {
 
2598     $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
 
2601   if ($params{warehouses}) {
 
2602     $self->_get_warehouses($dbh, $params{warehouses});
 
2605 #  if ($params{groups}) {
 
2606 #    $self->_get_groups($dbh, $params{groups});
 
2609   if ($params{partsgroup}) {
 
2610     $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
 
2613   $main::lxdebug->leave_sub();
 
2616 # this sub gets the id and name from $table
 
2618   $main::lxdebug->enter_sub();
 
2620   my ($self, $myconfig, $table) = @_;
 
2622   # connect to database
 
2623   my $dbh = $self->get_standard_dbh($myconfig);
 
2625   $table = $table eq "customer" ? "customer" : "vendor";
 
2626   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
 
2628   my ($query, @values);
 
2630   if (!$self->{openinvoices}) {
 
2632     if ($self->{customernumber} ne "") {
 
2633       $where = qq|(vc.customernumber ILIKE ?)|;
 
2634       push(@values, '%' . $self->{customernumber} . '%');
 
2636       $where = qq|(vc.name ILIKE ?)|;
 
2637       push(@values, '%' . $self->{$table} . '%');
 
2641       qq~SELECT vc.id, vc.name,
 
2642            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
2644          WHERE $where AND (NOT vc.obsolete)
 
2648       qq~SELECT DISTINCT vc.id, vc.name,
 
2649            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
2651          JOIN $table vc ON (a.${table}_id = vc.id)
 
2652          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
 
2654     push(@values, '%' . $self->{$table} . '%');
 
2657   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
 
2659   $main::lxdebug->leave_sub();
 
2661   return scalar(@{ $self->{name_list} });
 
2664 # the selection sub is used in the AR, AP, IS, IR and OE module
 
2667   $main::lxdebug->enter_sub();
 
2669   my ($self, $myconfig, $table, $module) = @_;
 
2672   my $dbh = $self->get_standard_dbh;
 
2674   $table = $table eq "customer" ? "customer" : "vendor";
 
2676   my $query = qq|SELECT count(*) FROM $table|;
 
2677   my ($count) = selectrow_query($self, $dbh, $query);
 
2679   # build selection list
 
2680   if ($count <= $myconfig->{vclimit}) {
 
2681     $query = qq|SELECT id, name, salesman_id
 
2682                 FROM $table WHERE NOT obsolete
 
2684     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
 
2688   $self->get_employee($dbh);
 
2690   # setup sales contacts
 
2691   $query = qq|SELECT e.id, e.name
 
2693               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
 
2694   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
 
2697   push(@{ $self->{all_employees} },
 
2698        { id   => $self->{employee_id},
 
2699          name => $self->{employee} });
 
2701   # sort the whole thing
 
2702   @{ $self->{all_employees} } =
 
2703     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
 
2705   if ($module eq 'AR') {
 
2707     # prepare query for departments
 
2708     $query = qq|SELECT id, description
 
2711                 ORDER BY description|;
 
2714     $query = qq|SELECT id, description
 
2716                 ORDER BY description|;
 
2719   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2722   $query = qq|SELECT id, description
 
2726   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2729   $query = qq|SELECT printer_description, id
 
2731               ORDER BY printer_description|;
 
2733   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2736   $query = qq|SELECT id, description
 
2740   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
2742   $main::lxdebug->leave_sub();
 
2745 sub language_payment {
 
2746   $main::lxdebug->enter_sub();
 
2748   my ($self, $myconfig) = @_;
 
2750   my $dbh = $self->get_standard_dbh($myconfig);
 
2752   my $query = qq|SELECT id, description
 
2756   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2759   $query = qq|SELECT printer_description, id
 
2761               ORDER BY printer_description|;
 
2763   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2766   $query = qq|SELECT id, description
 
2770   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
2772   # get buchungsgruppen
 
2773   $query = qq|SELECT id, description
 
2774               FROM buchungsgruppen|;
 
2776   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
 
2778   $main::lxdebug->leave_sub();
 
2781 # this is only used for reports
 
2782 sub all_departments {
 
2783   $main::lxdebug->enter_sub();
 
2785   my ($self, $myconfig, $table) = @_;
 
2787   my $dbh = $self->get_standard_dbh($myconfig);
 
2790   if ($table eq 'customer') {
 
2791     $where = "WHERE role = 'P' ";
 
2794   my $query = qq|SELECT id, description
 
2797                  ORDER BY description|;
 
2798   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2800   delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
 
2802   $main::lxdebug->leave_sub();
 
2806   $main::lxdebug->enter_sub();
 
2808   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
 
2811   if ($table eq "customer") {
 
2820   $self->all_vc($myconfig, $table, $module);
 
2822   # get last customers or vendors
 
2823   my ($query, $sth, $ref);
 
2825   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
 
2830     my $transdate = "current_date";
 
2831     if ($self->{transdate}) {
 
2832       $transdate = $dbh->quote($self->{transdate});
 
2835     # now get the account numbers
 
2836     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
 
2837                 FROM chart c, taxkeys tk
 
2838                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
 
2839                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
 
2842     $sth = $dbh->prepare($query);
 
2844     do_statement($self, $sth, $query, '%' . $module . '%');
 
2846     $self->{accounts} = "";
 
2847     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2849       foreach my $key (split(/:/, $ref->{link})) {
 
2850         if ($key =~ /\Q$module\E/) {
 
2852           # cross reference for keys
 
2853           $xkeyref{ $ref->{accno} } = $key;
 
2855           push @{ $self->{"${module}_links"}{$key} },
 
2856             { accno       => $ref->{accno},
 
2857               description => $ref->{description},
 
2858               taxkey      => $ref->{taxkey_id},
 
2859               tax_id      => $ref->{tax_id} };
 
2861           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2867   # get taxkeys and description
 
2868   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
 
2869   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
 
2871   if (($module eq "AP") || ($module eq "AR")) {
 
2872     # get tax rates and description
 
2873     $query = qq|SELECT * FROM tax|;
 
2874     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
 
2880            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
 
2881            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
 
2882            a.intnotes, a.department_id, a.amount AS oldinvtotal,
 
2883            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
 
2885            d.description AS department,
 
2888          JOIN $table c ON (a.${table}_id = c.id)
 
2889          LEFT JOIN employee e ON (e.id = a.employee_id)
 
2890          LEFT JOIN department d ON (d.id = a.department_id)
 
2892     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
 
2894     foreach my $key (keys %$ref) {
 
2895       $self->{$key} = $ref->{$key};
 
2898     my $transdate = "current_date";
 
2899     if ($self->{transdate}) {
 
2900       $transdate = $dbh->quote($self->{transdate});
 
2903     # now get the account numbers
 
2904     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
 
2906                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
 
2908                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
 
2909                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
 
2912     $sth = $dbh->prepare($query);
 
2913     do_statement($self, $sth, $query, "%$module%");
 
2915     $self->{accounts} = "";
 
2916     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2918       foreach my $key (split(/:/, $ref->{link})) {
 
2919         if ($key =~ /\Q$module\E/) {
 
2921           # cross reference for keys
 
2922           $xkeyref{ $ref->{accno} } = $key;
 
2924           push @{ $self->{"${module}_links"}{$key} },
 
2925             { accno       => $ref->{accno},
 
2926               description => $ref->{description},
 
2927               taxkey      => $ref->{taxkey_id},
 
2928               tax_id      => $ref->{tax_id} };
 
2930           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2936     # get amounts from individual entries
 
2939            c.accno, c.description,
 
2940            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
 
2944          LEFT JOIN chart c ON (c.id = a.chart_id)
 
2945          LEFT JOIN project p ON (p.id = a.project_id)
 
2946          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
 
2947                                     WHERE (tk.taxkey_id=a.taxkey) AND
 
2948                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
 
2949                                         THEN tk.chart_id = a.chart_id
 
2952                                        OR (c.link='%tax%')) AND
 
2953                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
 
2954          WHERE a.trans_id = ?
 
2955          AND a.fx_transaction = '0'
 
2956          ORDER BY a.acc_trans_id, a.transdate|;
 
2957     $sth = $dbh->prepare($query);
 
2958     do_statement($self, $sth, $query, $self->{id});
 
2960     # get exchangerate for currency
 
2961     $self->{exchangerate} =
 
2962       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2965     # store amounts in {acc_trans}{$key} for multiple accounts
 
2966     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2967       $ref->{exchangerate} =
 
2968         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
 
2969       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
 
2972       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
 
2973         $ref->{amount} *= -1;
 
2975       $ref->{index} = $index;
 
2977       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
 
2983            d.curr AS currencies, d.closedto, d.revtrans,
 
2984            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2985            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
2987     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2988     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2995             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
 
2996             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2997             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
2999     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
3000     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
3002     if ($self->{"$self->{vc}_id"}) {
 
3004       # only setup currency
 
3005       ($self->{currency}) = split(/:/, $self->{currencies});
 
3009       $self->lastname_used($dbh, $myconfig, $table, $module);
 
3011       # get exchangerate for currency
 
3012       $self->{exchangerate} =
 
3013         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
3019   $main::lxdebug->leave_sub();
 
3023   $main::lxdebug->enter_sub();
 
3025   my ($self, $dbh, $myconfig, $table, $module) = @_;
 
3029   $table         = $table eq "customer" ? "customer" : "vendor";
 
3030   my %column_map = ("a.curr"                  => "currency",
 
3031                     "a.${table}_id"           => "${table}_id",
 
3032                     "a.department_id"         => "department_id",
 
3033                     "d.description"           => "department",
 
3034                     "ct.name"                 => $table,
 
3035                     "current_date + ct.terms" => "duedate",
 
3038   if ($self->{type} =~ /delivery_order/) {
 
3039     $arap  = 'delivery_orders';
 
3040     delete $column_map{"a.curr"};
 
3042   } elsif ($self->{type} =~ /_order/) {
 
3044     $where = "quotation = '0'";
 
3046   } elsif ($self->{type} =~ /_quotation/) {
 
3048     $where = "quotation = '1'";
 
3050   } elsif ($table eq 'customer') {
 
3058   $where           = "($where) AND" if ($where);
 
3059   my $query        = qq|SELECT MAX(id) FROM $arap
 
3060                         WHERE $where ${table}_id > 0|;
 
3061   my ($trans_id)   = selectrow_query($self, $dbh, $query);
 
3064   my $column_spec  = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
 
3065   $query           = qq|SELECT $column_spec
 
3067                         LEFT JOIN $table     ct ON (a.${table}_id = ct.id)
 
3068                         LEFT JOIN department d  ON (a.department_id = d.id)
 
3070   my $ref          = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
 
3072   map { $self->{$_} = $ref->{$_} } values %column_map;
 
3074   $main::lxdebug->leave_sub();
 
3078   $main::lxdebug->enter_sub();
 
3081   my $myconfig = shift || \%::myconfig;
 
3082   my ($thisdate, $days) = @_;
 
3084   my $dbh = $self->get_standard_dbh($myconfig);
 
3089     my $dateformat = $myconfig->{dateformat};
 
3090     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
 
3091     $thisdate = $dbh->quote($thisdate);
 
3092     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
 
3094     $query = qq|SELECT current_date AS thisdate|;
 
3097   ($thisdate) = selectrow_query($self, $dbh, $query);
 
3099   $main::lxdebug->leave_sub();
 
3105   $main::lxdebug->enter_sub();
 
3107   my ($self, $string) = @_;
 
3109   if ($string !~ /%/) {
 
3110     $string = "%$string%";
 
3113   $string =~ s/\'/\'\'/g;
 
3115   $main::lxdebug->leave_sub();
 
3121   $main::lxdebug->enter_sub();
 
3123   my ($self, $flds, $new, $count, $numrows) = @_;
 
3127   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
 
3132   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
 
3134     my $j = $item->{ndx} - 1;
 
3135     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
 
3139   for $i ($count + 1 .. $numrows) {
 
3140     map { delete $self->{"${_}_$i"} } @{$flds};
 
3143   $main::lxdebug->leave_sub();
 
3147   $main::lxdebug->enter_sub();
 
3149   my ($self, $myconfig) = @_;
 
3153   my $dbh = $self->dbconnect_noauto($myconfig);
 
3155   my $query = qq|DELETE FROM status
 
3156                  WHERE (formname = ?) AND (trans_id = ?)|;
 
3157   my $sth = prepare_query($self, $dbh, $query);
 
3159   if ($self->{formname} =~ /(check|receipt)/) {
 
3160     for $i (1 .. $self->{rowcount}) {
 
3161       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
 
3164     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
 
3168   my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3169   my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3171   my %queued = split / /, $self->{queued};
 
3174   if ($self->{formname} =~ /(check|receipt)/) {
 
3176     # this is a check or receipt, add one entry for each lineitem
 
3177     my ($accno) = split /--/, $self->{account};
 
3178     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
 
3179                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
 
3180     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
 
3181     $sth = prepare_query($self, $dbh, $query);
 
3183     for $i (1 .. $self->{rowcount}) {
 
3184       if ($self->{"checked_$i"}) {
 
3185         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
 
3191     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
3192                 VALUES (?, ?, ?, ?, ?)|;
 
3193     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
 
3194              $queued{$self->{formname}}, $self->{formname});
 
3200   $main::lxdebug->leave_sub();
 
3204   $main::lxdebug->enter_sub();
 
3206   my ($self, $dbh) = @_;
 
3208   my ($query, $printed, $emailed);
 
3210   my $formnames  = $self->{printed};
 
3211   my $emailforms = $self->{emailed};
 
3213   $query = qq|DELETE FROM status
 
3214                  WHERE (formname = ?) AND (trans_id = ?)|;
 
3215   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
 
3217   # this only applies to the forms
 
3218   # checks and receipts are posted when printed or queued
 
3220   if ($self->{queued}) {
 
3221     my %queued = split / /, $self->{queued};
 
3223     foreach my $formname (keys %queued) {
 
3224       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3225       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3227       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
3228                   VALUES (?, ?, ?, ?, ?)|;
 
3229       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
 
3231       $formnames  =~ s/\Q$self->{formname}\E//;
 
3232       $emailforms =~ s/\Q$self->{formname}\E//;
 
3237   # save printed, emailed info
 
3238   $formnames  =~ s/^ +//g;
 
3239   $emailforms =~ s/^ +//g;
 
3242   map { $status{$_}{printed} = 1 } split / +/, $formnames;
 
3243   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
 
3245   foreach my $formname (keys %status) {
 
3246     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3247     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3249     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
 
3250                 VALUES (?, ?, ?, ?)|;
 
3251     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
 
3254   $main::lxdebug->leave_sub();
 
3258 # $main::locale->text('SAVED')
 
3259 # $main::locale->text('DELETED')
 
3260 # $main::locale->text('ADDED')
 
3261 # $main::locale->text('PAYMENT POSTED')
 
3262 # $main::locale->text('POSTED')
 
3263 # $main::locale->text('POSTED AS NEW')
 
3264 # $main::locale->text('ELSE')
 
3265 # $main::locale->text('SAVED FOR DUNNING')
 
3266 # $main::locale->text('DUNNING STARTED')
 
3267 # $main::locale->text('PRINTED')
 
3268 # $main::locale->text('MAILED')
 
3269 # $main::locale->text('SCREENED')
 
3270 # $main::locale->text('CANCELED')
 
3271 # $main::locale->text('invoice')
 
3272 # $main::locale->text('proforma')
 
3273 # $main::locale->text('sales_order')
 
3274 # $main::locale->text('packing_list')
 
3275 # $main::locale->text('pick_list')
 
3276 # $main::locale->text('purchase_order')
 
3277 # $main::locale->text('bin_list')
 
3278 # $main::locale->text('sales_quotation')
 
3279 # $main::locale->text('request_quotation')
 
3282   $main::lxdebug->enter_sub();
 
3285   my $dbh  = shift || $self->get_standard_dbh;
 
3287   if(!exists $self->{employee_id}) {
 
3288     &get_employee($self, $dbh);
 
3292    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
 
3293    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
 
3294   my @values = (conv_i($self->{id}), $self->{login},
 
3295                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
 
3296   do_query($self, $dbh, $query, @values);
 
3300   $main::lxdebug->leave_sub();
 
3304   $main::lxdebug->enter_sub();
 
3306   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
 
3307   my ($orderBy, $desc) = split(/\-\-/, $order);
 
3308   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
 
3311   if ($trans_id ne "") {
 
3313       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 | .
 
3314       qq|FROM history_erp h | .
 
3315       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
 
3316       qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
 
3319     my $sth = $dbh->prepare($query) || $self->dberror($query);
 
3321     $sth->execute() || $self->dberror("$query");
 
3323     while(my $hash_ref = $sth->fetchrow_hashref()) {
 
3324       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
 
3325       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
 
3326       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
 
3327       $tempArray[$i++] = $hash_ref;
 
3329     $main::lxdebug->leave_sub() and return \@tempArray
 
3330       if ($i > 0 && $tempArray[0] ne "");
 
3332   $main::lxdebug->leave_sub();
 
3336 sub update_defaults {
 
3337   $main::lxdebug->enter_sub();
 
3339   my ($self, $myconfig, $fld, $provided_dbh) = @_;
 
3342   if ($provided_dbh) {
 
3343     $dbh = $provided_dbh;
 
3345     $dbh = $self->dbconnect_noauto($myconfig);
 
3347   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
 
3348   my $sth   = $dbh->prepare($query);
 
3350   $sth->execute || $self->dberror($query);
 
3351   my ($var) = $sth->fetchrow_array;
 
3354   if ($var =~ m/\d+$/) {
 
3355     my $new_var  = (substr $var, $-[0]) * 1 + 1;
 
3356     my $len_diff = length($var) - $-[0] - length($new_var);
 
3357     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
 
3363   $query = qq|UPDATE defaults SET $fld = ?|;
 
3364   do_query($self, $dbh, $query, $var);
 
3366   if (!$provided_dbh) {
 
3371   $main::lxdebug->leave_sub();
 
3376 sub update_business {
 
3377   $main::lxdebug->enter_sub();
 
3379   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
 
3382   if ($provided_dbh) {
 
3383     $dbh = $provided_dbh;
 
3385     $dbh = $self->dbconnect_noauto($myconfig);
 
3388     qq|SELECT customernumberinit FROM business
 
3389        WHERE id = ? FOR UPDATE|;
 
3390   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
 
3392   return undef unless $var;
 
3394   if ($var =~ m/\d+$/) {
 
3395     my $new_var  = (substr $var, $-[0]) * 1 + 1;
 
3396     my $len_diff = length($var) - $-[0] - length($new_var);
 
3397     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
 
3403   $query = qq|UPDATE business
 
3404               SET customernumberinit = ?
 
3406   do_query($self, $dbh, $query, $var, $business_id);
 
3408   if (!$provided_dbh) {
 
3413   $main::lxdebug->leave_sub();
 
3418 sub get_partsgroup {
 
3419   $main::lxdebug->enter_sub();
 
3421   my ($self, $myconfig, $p) = @_;
 
3422   my $target = $p->{target} || 'all_partsgroup';
 
3424   my $dbh = $self->get_standard_dbh($myconfig);
 
3426   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
 
3428                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
 
3431   if ($p->{searchitems} eq 'part') {
 
3432     $query .= qq|WHERE p.inventory_accno_id > 0|;
 
3434   if ($p->{searchitems} eq 'service') {
 
3435     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
 
3437   if ($p->{searchitems} eq 'assembly') {
 
3438     $query .= qq|WHERE p.assembly = '1'|;
 
3440   if ($p->{searchitems} eq 'labor') {
 
3441     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
 
3444   $query .= qq|ORDER BY partsgroup|;
 
3447     $query = qq|SELECT id, partsgroup FROM partsgroup
 
3448                 ORDER BY partsgroup|;
 
3451   if ($p->{language_code}) {
 
3452     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
 
3453                   t.description AS translation
 
3455                 JOIN parts p ON (p.partsgroup_id = pg.id)
 
3456                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
 
3457                 ORDER BY translation|;
 
3458     @values = ($p->{language_code});
 
3461   $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
 
3463   $main::lxdebug->leave_sub();
 
3466 sub get_pricegroup {
 
3467   $main::lxdebug->enter_sub();
 
3469   my ($self, $myconfig, $p) = @_;
 
3471   my $dbh = $self->get_standard_dbh($myconfig);
 
3473   my $query = qq|SELECT p.id, p.pricegroup
 
3476   $query .= qq| ORDER BY pricegroup|;
 
3479     $query = qq|SELECT id, pricegroup FROM pricegroup
 
3480                 ORDER BY pricegroup|;
 
3483   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
 
3485   $main::lxdebug->leave_sub();
 
3489 # usage $form->all_years($myconfig, [$dbh])
 
3490 # return list of all years where bookings found
 
3493   $main::lxdebug->enter_sub();
 
3495   my ($self, $myconfig, $dbh) = @_;
 
3497   $dbh ||= $self->get_standard_dbh($myconfig);
 
3500   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
 
3501                    (SELECT MAX(transdate) FROM acc_trans)|;
 
3502   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
 
3504   if ($myconfig->{dateformat} =~ /^yy/) {
 
3505     ($startdate) = split /\W/, $startdate;
 
3506     ($enddate) = split /\W/, $enddate;
 
3508     (@_) = split /\W/, $startdate;
 
3510     (@_) = split /\W/, $enddate;
 
3515   $startdate = substr($startdate,0,4);
 
3516   $enddate = substr($enddate,0,4);
 
3518   while ($enddate >= $startdate) {
 
3519     push @all_years, $enddate--;
 
3524   $main::lxdebug->leave_sub();
 
3528   $main::lxdebug->enter_sub();
 
3532   map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
 
3534   $main::lxdebug->leave_sub();
 
3538   $main::lxdebug->enter_sub();
 
3543   map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
 
3545   $main::lxdebug->leave_sub();
 
3554 SL::Form.pm - main data object.
 
3558 This is the main data object of Lx-Office.
 
3559 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
 
3560 Points of interest for a beginner are:
 
3562  - $form->error            - renders a generic error in html. accepts an error message
 
3563  - $form->get_standard_dbh - returns a database connection for the
 
3565 =head1 SPECIAL FUNCTIONS
 
3569 =item _store_value()
 
3571 parses a complex var name, and stores it in the form.
 
3574   $form->_store_value($key, $value);
 
3576 keys must start with a string, and can contain various tokens.
 
3577 supported key structures are:
 
3580   simple key strings work as expected
 
3585   separating two keys by a dot (.) will result in a hash lookup for the inner value
 
3586   this is similar to the behaviour of java and templating mechanisms.
 
3588   filter.description => $form->{filter}->{description}
 
3590 3. array+hashref access
 
3592   adding brackets ([]) before the dot will cause the next hash to be put into an array.
 
3593   using [+] instead of [] will force a new array index. this is useful for recurring
 
3594   data structures like part lists. put a [+] into the first varname, and use [] on the
 
3597   repeating these names in your template:
 
3600     invoice.items[].parts_id
 
3604     $form->{invoice}->{items}->[
 
3618   using brackets at the end of a name will result in a pure array to be created.
 
3619   note that you mustn't use [+], which is reserved for array+hash access and will
 
3620   result in undefined behaviour in array context.
 
3622   filter.status[]  => $form->{status}->[ val1, val2, ... ]
 
3624 =item update_business PARAMS
 
3627  \%config,     - config hashref
 
3628  $business_id, - business id
 
3629  $dbh          - optional database handle
 
3631 handles business (thats customer/vendor types) sequences.
 
3633 special behaviour for empty strings in customerinitnumber field:
 
3634 will in this case not increase the value, and return undef.
 
3636 =item redirect_header $url
 
3638 Generates a HTTP redirection header for the new C<$url>. Constructs an
 
3639 absolute URL including scheme, host name and port. If C<$url> is a
 
3640 relative URL then it is considered relative to Lx-Office base URL.
 
3642 This function C<die>s if headers have already been created with
 
3643 C<$::form-E<gt>header>.
 
3647   print $::form->redirect_header('oe.pl?action=edit&id=1234');
 
3648   print $::form->redirect_header('http://www.lx-office.org/');