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   if ($self->{INPUT_ENCODING}) {
 
 261     if (lc $self->{INPUT_ENCODING} ne lc $db_charset) {
 
 263       my $iconv = Text::Iconv->new($self->{INPUT_ENCODING}, $db_charset);
 
 265       _recode_recursively($iconv, $self);
 
 268     delete $self->{INPUT_ENCODING};
 
 271   $self->{action}  =  lc $self->{action};
 
 272   $self->{action}  =~ s/( |-|,|\#)/_/g;
 
 274   $self->{version} =  "2.6.1";
 
 276   $main::lxdebug->leave_sub();
 
 281 sub _flatten_variables_rec {
 
 282   $main::lxdebug->enter_sub(2);
 
 291   if ('' eq ref $curr->{$key}) {
 
 292     @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
 
 294   } elsif ('HASH' eq ref $curr->{$key}) {
 
 295     foreach my $hash_key (sort keys %{ $curr->{$key} }) {
 
 296       push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
 
 300     foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
 
 301       my $first_array_entry = 1;
 
 303       foreach my $hash_key (sort keys %{ $curr->{$key}->[$idx] }) {
 
 304         push @result, $self->_flatten_variables_rec($curr->{$key}->[$idx], $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
 
 305         $first_array_entry = 0;
 
 310   $main::lxdebug->leave_sub(2);
 
 315 sub flatten_variables {
 
 316   $main::lxdebug->enter_sub(2);
 
 324     push @variables, $self->_flatten_variables_rec($self, '', $_);
 
 327   $main::lxdebug->leave_sub(2);
 
 332 sub flatten_standard_variables {
 
 333   $main::lxdebug->enter_sub(2);
 
 336   my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar version), @_);
 
 340   foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
 
 341     push @variables, $self->_flatten_variables_rec($self, '', $_);
 
 344   $main::lxdebug->leave_sub(2);
 
 350   $main::lxdebug->enter_sub();
 
 356   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
 
 358   $main::lxdebug->leave_sub();
 
 362   $main::lxdebug->enter_sub(2);
 
 365   my $password      = $self->{password};
 
 367   $self->{password} = 'X' x 8;
 
 369   local $Data::Dumper::Sortkeys = 1;
 
 370   my $output                    = Dumper($self);
 
 372   $self->{password} = $password;
 
 374   $main::lxdebug->leave_sub(2);
 
 380   $main::lxdebug->enter_sub(2);
 
 382   my ($self, $str) = @_;
 
 384   $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
 
 386   $main::lxdebug->leave_sub(2);
 
 392   $main::lxdebug->enter_sub(2);
 
 394   my ($self, $str) = @_;
 
 399   $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
 
 401   $main::lxdebug->leave_sub(2);
 
 407   $main::lxdebug->enter_sub();
 
 408   my ($self, $str) = @_;
 
 410   if ($str && !ref($str)) {
 
 411     $str =~ s/\"/"/g;
 
 414   $main::lxdebug->leave_sub();
 
 420   $main::lxdebug->enter_sub();
 
 421   my ($self, $str) = @_;
 
 423   if ($str && !ref($str)) {
 
 424     $str =~ s/"/\"/g;
 
 427   $main::lxdebug->leave_sub();
 
 433   $main::lxdebug->enter_sub();
 
 437     map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
 
 439     for (sort keys %$self) {
 
 440       next if (($_ eq "header") || (ref($self->{$_}) ne ""));
 
 441       print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
 
 444   $main::lxdebug->leave_sub();
 
 448   $main::lxdebug->enter_sub();
 
 450   $main::lxdebug->show_backtrace();
 
 452   my ($self, $msg) = @_;
 
 453   if ($ENV{HTTP_USER_AGENT}) {
 
 455     $self->show_generic_error($msg);
 
 458     print STDERR "Error: $msg\n";
 
 462   $main::lxdebug->leave_sub();
 
 466   $main::lxdebug->enter_sub();
 
 468   my ($self, $msg) = @_;
 
 470   if ($ENV{HTTP_USER_AGENT}) {
 
 473     if (!$self->{header}) {
 
 486     if ($self->{info_function}) {
 
 487       &{ $self->{info_function} }($msg);
 
 493   $main::lxdebug->leave_sub();
 
 496 # calculates the number of rows in a textarea based on the content and column number
 
 497 # can be capped with maxrows
 
 499   $main::lxdebug->enter_sub();
 
 500   my ($self, $str, $cols, $maxrows, $minrows) = @_;
 
 504   my $rows   = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
 
 507   $main::lxdebug->leave_sub();
 
 509   return max(min($rows, $maxrows), $minrows);
 
 513   $main::lxdebug->enter_sub();
 
 515   my ($self, $msg) = @_;
 
 517   $self->error("$msg\n" . $DBI::errstr);
 
 519   $main::lxdebug->leave_sub();
 
 523   $main::lxdebug->enter_sub();
 
 525   my ($self, $name, $msg) = @_;
 
 528   foreach my $part (split m/\./, $name) {
 
 529     if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
 
 532     $curr = $curr->{$part};
 
 535   $main::lxdebug->leave_sub();
 
 538 sub _get_request_uri {
 
 541   return URI->new($ENV{HTTP_REFERER})->canonical() if $ENV{HTTP_X_FORWARDED_FOR};
 
 543   my $scheme =  $ENV{HTTPS} && (lc $ENV{HTTPS} eq 'on') ? 'https' : 'http';
 
 544   my $port   =  $ENV{SERVER_PORT} || '';
 
 545   $port      =  undef if (($scheme eq 'http' ) && ($port == 80))
 
 546                       || (($scheme eq 'https') && ($port == 443));
 
 548   my $uri    =  URI->new("${scheme}://");
 
 549   $uri->scheme($scheme);
 
 551   $uri->host($ENV{HTTP_HOST} || $ENV{SERVER_ADDR});
 
 552   $uri->path_query($ENV{REQUEST_URI});
 
 558 sub _add_to_request_uri {
 
 561   my $relative_new_path = shift;
 
 562   my $request_uri       = shift || $self->_get_request_uri;
 
 563   my $relative_new_uri  = URI->new($relative_new_path);
 
 564   my @request_segments  = $request_uri->path_segments;
 
 566   my $new_uri           = $request_uri->clone;
 
 567   $new_uri->path_segments(@request_segments[0..scalar(@request_segments) - 2], $relative_new_uri->path_segments);
 
 572 sub create_http_response {
 
 573   $main::lxdebug->enter_sub();
 
 578   my $cgi      = $main::cgi;
 
 579   $cgi       ||= CGI->new('');
 
 582   if (defined $main::auth) {
 
 583     my $uri      = $self->_get_request_uri;
 
 584     my @segments = $uri->path_segments;
 
 586     $uri->path_segments(@segments);
 
 588     my $session_cookie_value   = $main::auth->get_session_id();
 
 589     $session_cookie_value    ||= 'NO_SESSION';
 
 591     $session_cookie = $cgi->cookie('-name'   => $main::auth->get_session_cookie_name(),
 
 592                                    '-value'  => $session_cookie_value,
 
 593                                    '-path'   => $uri->path,
 
 594                                    '-secure' => $ENV{HTTPS});
 
 597   my %cgi_params = ('-type' => $params{content_type});
 
 598   $cgi_params{'-charset'} = $params{charset} if ($params{charset});
 
 600   my $output = $cgi->header('-cookie' => $session_cookie,
 
 603   $main::lxdebug->leave_sub();
 
 610   $main::lxdebug->enter_sub();
 
 612   # extra code ist currently only used by menuv3 and menuv4 to set their css.
 
 613   # it is strongly deprecated, and will be changed in a future version.
 
 614   my ($self, $extra_code) = @_;
 
 616   if ($self->{header}) {
 
 617     $main::lxdebug->leave_sub();
 
 621   my ($stylesheet, $favicon, $pagelayout);
 
 623   if ($ENV{HTTP_USER_AGENT}) {
 
 626     if ($ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+\d/) {
 
 627       # Only set the DOCTYPE for Internet Explorer. Other browsers have problems displaying the menu otherwise.
 
 628       $doctype = qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n|;
 
 631     my $stylesheets = "$self->{stylesheet} $self->{stylesheets}";
 
 633     $stylesheets =~ s|^\s*||;
 
 634     $stylesheets =~ s|\s*$||;
 
 635     foreach my $file (split m/\s+/, $stylesheets) {
 
 637       next if (! -f "css/$file");
 
 639       $stylesheet .= qq|<link rel="stylesheet" href="css/$file" TYPE="text/css" TITLE="Lx-Office stylesheet">\n|;
 
 642     $self->{favicon}    = "favicon.ico" unless $self->{favicon};
 
 644     if ($self->{favicon} && (-f "$self->{favicon}")) {
 
 646         qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
 
 650     my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
 652     if ($self->{landscape}) {
 
 653       $pagelayout = qq|<style type="text/css">
 
 654                         \@page { size:landscape; }
 
 659     <script type="text/javascript">
 
 662         document.$self->{fokus}.focus();
 
 666     | if $self->{"fokus"};
 
 670     if ($self->{jsscript} == 1) {
 
 673         <script type="text/javascript" src="js/jquery.js"></script>
 
 674         <script type="text/javascript" src="js/common.js"></script>
 
 675         <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
 
 676         <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
 
 677         <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
 
 678         <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
 
 685       ? "$self->{title} - $self->{titlebar}"
 
 688     for my $item (@ { $self->{AJAX} || [] }) {
 
 689       $ajax .= $item->show_javascript();
 
 692     print $self->create_http_response('content_type' => 'text/html',
 
 693                                       'charset'      => $db_charset,);
 
 694     print qq|${doctype}<html>
 
 696   <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
 
 697   <title>$self->{titlebar}</title>
 
 706   <link rel="stylesheet" href="css/jquery.autocomplete.css" type="text/css" />
 
 708   <meta name="robots" content="noindex,nofollow" />
 
 709   <script type="text/javascript" src="js/highlight_input.js"></script>
 
 711   <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
 
 712   <script type="text/javascript" src="js/tabcontent.js">
 
 714   /***********************************************
 
 715    * Tab Content script v2.2- Â© Dynamic Drive DHTML code library (www.dynamicdrive.com)
 
 716    * This notice MUST stay intact for legal use
 
 717    * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
 
 718    ***********************************************/
 
 729   $main::lxdebug->leave_sub();
 
 732 sub ajax_response_header {
 
 733   $main::lxdebug->enter_sub();
 
 737   my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
 738   my $cgi        = $main::cgi || CGI->new('');
 
 739   my $output     = $cgi->header('-charset' => $db_charset);
 
 741   $main::lxdebug->leave_sub();
 
 746 sub redirect_header {
 
 750   my $base_uri = $self->_get_request_uri;
 
 751   my $new_uri  = URI->new_abs($new_url, $base_uri);
 
 753   die "Headers already sent" if $::self->{header};
 
 756   my $cgi = $main::cgi || CGI->new('');
 
 757   return $cgi->redirect($new_uri);
 
 760 sub set_standard_title {
 
 761   $::lxdebug->enter_sub;
 
 764   $self->{titlebar}  = "Lx-Office " . $::locale->text('Version') . " $self->{version}";
 
 765   $self->{titlebar} .= "- $::myconfig{name}"   if $::myconfig{name};
 
 766   $self->{titlebar} .= "- $::myconfig{dbname}" if $::myconfig{name};
 
 768   $::lxdebug->leave_sub;
 
 771 sub _prepare_html_template {
 
 772   $main::lxdebug->enter_sub();
 
 774   my ($self, $file, $additional_params) = @_;
 
 777   if (!%::myconfig || !$::myconfig{"countrycode"}) {
 
 778     $language = $main::language;
 
 780     $language = $main::myconfig{"countrycode"};
 
 782   $language = "de" unless ($language);
 
 784   if (-f "templates/webpages/${file}.html") {
 
 785     if ((-f ".developer") && ((stat("templates/webpages/${file}.html"))[9] > (stat("locale/${language}/all"))[9])) {
 
 786       my $info = "Developer information: templates/webpages/${file}.html is newer than the translation file locale/${language}/all.\n" .
 
 787         "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 788       print(qq|<pre>$info</pre>|);
 
 792     $file = "templates/webpages/${file}.html";
 
 795     my $info = "Web page template '${file}' not found.\n" .
 
 796       "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 797     print(qq|<pre>$info</pre>|);
 
 801   if ($self->{"DEBUG"}) {
 
 802     $additional_params->{"DEBUG"} = $self->{"DEBUG"};
 
 805   if ($additional_params->{"DEBUG"}) {
 
 806     $additional_params->{"DEBUG"} =
 
 807       "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
 
 810   if (%main::myconfig) {
 
 811     map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
 
 812     my $jsc_dateformat = $main::myconfig{"dateformat"};
 
 813     $jsc_dateformat =~ s/d+/\%d/gi;
 
 814     $jsc_dateformat =~ s/m+/\%m/gi;
 
 815     $jsc_dateformat =~ s/y+/\%Y/gi;
 
 816     $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
 
 817     $additional_params->{"myconfig"} ||= \%::myconfig;
 
 820   $additional_params->{"conf_dbcharset"}              = $main::dbcharset;
 
 821   $additional_params->{"conf_webdav"}                 = $main::webdav;
 
 822   $additional_params->{"conf_lizenzen"}               = $main::lizenzen;
 
 823   $additional_params->{"conf_latex_templates"}        = $main::latex;
 
 824   $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
 
 825   $additional_params->{"conf_vertreter"}              = $main::vertreter;
 
 826   $additional_params->{"conf_show_best_before"}       = $main::show_best_before;
 
 828   if (%main::debug_options) {
 
 829     map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
 
 832   if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
 
 833     while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
 
 834       $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
 
 838   $main::lxdebug->leave_sub();
 
 843 sub parse_html_template {
 
 844   $main::lxdebug->enter_sub();
 
 846   my ($self, $file, $additional_params) = @_;
 
 848   $additional_params ||= { };
 
 850   my $real_file = $self->_prepare_html_template($file, $additional_params);
 
 851   my $template  = $self->template || $self->init_template;
 
 853   map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
 
 856   $template->process($real_file, $additional_params, \$output) || die $template->error;
 
 858   $main::lxdebug->leave_sub();
 
 866   return if $self->template;
 
 868   return $self->template(Template->new({
 
 873      'PLUGIN_BASE'  => 'SL::Template::Plugin',
 
 874      'INCLUDE_PATH' => '.:templates/webpages',
 
 875      'COMPILE_EXT'  => $main::template_compile_ext,
 
 876      'COMPILE_DIR'  => $main::template_compile_dir,
 
 882   $self->{template_object} = shift if @_;
 
 883   return $self->{template_object};
 
 886 sub show_generic_error {
 
 887   $main::lxdebug->enter_sub();
 
 889   my ($self, $error, %params) = @_;
 
 892     'title_error' => $params{title},
 
 893     'label_error' => $error,
 
 896   if ($params{action}) {
 
 899     map { delete($self->{$_}); } qw(action);
 
 900     map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
 
 902     $add_params->{SHOW_BUTTON}  = 1;
 
 903     $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
 
 904     $add_params->{VARIABLES}    = \@vars;
 
 906   } elsif ($params{back_button}) {
 
 907     $add_params->{SHOW_BACK_BUTTON} = 1;
 
 910   $self->{title} = $params{title} if $params{title};
 
 913   print $self->parse_html_template("generic/error", $add_params);
 
 915   print STDERR "Error: $error\n";
 
 917   $main::lxdebug->leave_sub();
 
 922 sub show_generic_information {
 
 923   $main::lxdebug->enter_sub();
 
 925   my ($self, $text, $title) = @_;
 
 928     'title_information' => $title,
 
 929     'label_information' => $text,
 
 932   $self->{title} = $title if ($title);
 
 935   print $self->parse_html_template("generic/information", $add_params);
 
 937   $main::lxdebug->leave_sub();
 
 942 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
 
 943 # changed it to accept an arbitrary number of triggers - sschoeling
 
 945   $main::lxdebug->enter_sub();
 
 948   my $myconfig = shift;
 
 951   # set dateform for jsscript
 
 954     "dd.mm.yy" => "%d.%m.%Y",
 
 955     "dd-mm-yy" => "%d-%m-%Y",
 
 956     "dd/mm/yy" => "%d/%m/%Y",
 
 957     "mm/dd/yy" => "%m/%d/%Y",
 
 958     "mm-dd-yy" => "%m-%d-%Y",
 
 959     "yyyy-mm-dd" => "%Y-%m-%d",
 
 962   my $ifFormat = defined($dateformats{$myconfig->{"dateformat"}}) ?
 
 963     $dateformats{$myconfig->{"dateformat"}} : "%d.%m.%Y";
 
 970       inputField : "| . (shift) . qq|",
 
 971       ifFormat :"$ifFormat",
 
 972       align : "| .  (shift) . qq|",
 
 973       button : "| . (shift) . qq|"
 
 979        <script type="text/javascript">
 
 980        <!--| . join("", @triggers) . qq|//-->
 
 984   $main::lxdebug->leave_sub();
 
 987 }    #end sub write_trigger
 
 990   $main::lxdebug->enter_sub();
 
 992   my ($self, $msg) = @_;
 
 994   if (!$self->{callback}) {
 
1000 #  my ($script, $argv) = split(/\?/, $self->{callback}, 2);
 
1001 #  $script =~ s|.*/||;
 
1002 #  $script =~ s|[^a-zA-Z0-9_\.]||g;
 
1003 #  exec("perl", "$script", $argv);
 
1005   print $::form->redirect_header($self->{callback});
 
1007   $main::lxdebug->leave_sub();
 
1010 # sort of columns removed - empty sub
 
1012   $main::lxdebug->enter_sub();
 
1014   my ($self, @columns) = @_;
 
1016   $main::lxdebug->leave_sub();
 
1022   $main::lxdebug->enter_sub(2);
 
1024   my ($self, $myconfig, $amount, $places, $dash) = @_;
 
1026   if ($amount eq "") {
 
1030   # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
 
1032   my $neg = ($amount =~ s/^-//);
 
1033   my $exp = ($amount =~ m/[e]/) ? 1 : 0;
 
1035   if (defined($places) && ($places ne '')) {
 
1041         my ($actual_places) = ($amount =~ /\.(\d+)/);
 
1042         $actual_places = length($actual_places);
 
1043         $places = $actual_places > $places ? $actual_places : $places;
 
1046     $amount = $self->round_amount($amount, $places);
 
1049   my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
 
1050   my @p = split(/\./, $amount); # split amount at decimal point
 
1052   $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
 
1055   $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
 
1058     ($dash =~ /-/)    ? ($neg ? "($amount)"                            : "$amount" )                              :
 
1059     ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
 
1060                         ($neg ? "-$amount"                             : "$amount" )                              ;
 
1064   $main::lxdebug->leave_sub(2);
 
1068 sub format_amount_units {
 
1069   $main::lxdebug->enter_sub();
 
1074   my $myconfig         = \%main::myconfig;
 
1075   my $amount           = $params{amount} * 1;
 
1076   my $places           = $params{places};
 
1077   my $part_unit_name   = $params{part_unit};
 
1078   my $amount_unit_name = $params{amount_unit};
 
1079   my $conv_units       = $params{conv_units};
 
1080   my $max_places       = $params{max_places};
 
1082   if (!$part_unit_name) {
 
1083     $main::lxdebug->leave_sub();
 
1087   AM->retrieve_all_units();
 
1088   my $all_units        = $main::all_units;
 
1090   if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
 
1091     $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
 
1094   if (!scalar @{ $conv_units }) {
 
1095     my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
 
1096     $main::lxdebug->leave_sub();
 
1100   my $part_unit  = $all_units->{$part_unit_name};
 
1101   my $conv_unit  = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
 
1103   $amount       *= $conv_unit->{factor};
 
1108   foreach my $unit (@$conv_units) {
 
1109     my $last = $unit->{name} eq $part_unit->{name};
 
1111       $num     = int($amount / $unit->{factor});
 
1112       $amount -= $num * $unit->{factor};
 
1115     if ($last ? $amount : $num) {
 
1116       push @values, { "unit"   => $unit->{name},
 
1117                       "amount" => $last ? $amount / $unit->{factor} : $num,
 
1118                       "places" => $last ? $places : 0 };
 
1125     push @values, { "unit"   => $part_unit_name,
 
1130   my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
 
1132   $main::lxdebug->leave_sub();
 
1138   $main::lxdebug->enter_sub(2);
 
1143   $input =~ s/(^|[^\#]) \#  (\d+)  /$1$_[$2 - 1]/gx;
 
1144   $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
 
1145   $input =~ s/\#\#/\#/g;
 
1147   $main::lxdebug->leave_sub(2);
 
1155   $main::lxdebug->enter_sub(2);
 
1157   my ($self, $myconfig, $amount) = @_;
 
1159   if (   ($myconfig->{numberformat} eq '1.000,00')
 
1160       || ($myconfig->{numberformat} eq '1000,00')) {
 
1165   if ($myconfig->{numberformat} eq "1'000.00") {
 
1171   $main::lxdebug->leave_sub(2);
 
1173   return ($amount * 1);
 
1177   $main::lxdebug->enter_sub(2);
 
1179   my ($self, $amount, $places) = @_;
 
1182   # Rounding like "Kaufmannsrunden" (see http://de.wikipedia.org/wiki/Rundung )
 
1184   # Round amounts to eight places before rounding to the requested
 
1185   # number of places. This gets rid of errors due to internal floating
 
1186   # point representation.
 
1187   $amount       = $self->round_amount($amount, 8) if $places < 8;
 
1188   $amount       = $amount * (10**($places));
 
1189   $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
 
1191   $main::lxdebug->leave_sub(2);
 
1193   return $round_amount;
 
1197 sub parse_template {
 
1198   $main::lxdebug->enter_sub();
 
1200   my ($self, $myconfig, $userspath) = @_;
 
1201   my ($template, $out);
 
1205   $self->{"cwd"} = getcwd();
 
1206   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
 
1210   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
 
1211     $template       = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1212     $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
 
1214   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
 
1215     $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
 
1216     $template         = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1217     $ext_for_format   = 'pdf';
 
1219   } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
 
1220     $template       = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1221     $ext_for_format = 'html';
 
1223   } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
 
1224     $template       = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1225     $ext_for_format = 'xml';
 
1227   } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
 
1228     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1230   } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
 
1231     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1233   } elsif ( $self->{"format"} =~ /excel/i ) {
 
1234     $template = ExcelTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1235     $ext_for_format = 'xls';
 
1237   } elsif ( defined $self->{'format'}) {
 
1238     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
 
1240   } elsif ( $self->{'format'} eq '' ) {
 
1241     $self->error("No Outputformat given: $self->{'format'}");
 
1243   } else { #Catch the rest
 
1244     $self->error("Outputformat not defined: $self->{'format'}");
 
1247   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
 
1248   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
 
1250   if (!$self->{employee_id}) {
 
1251     map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
 
1254   map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
 
1256   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
 
1258   # OUT is used for the media, screen, printer, email
 
1259   # for postscript we store a copy in a temporary file
 
1261   my $prepend_userspath;
 
1263   if (!$self->{tmpfile}) {
 
1264     $self->{tmpfile}   = "${fileid}.$self->{IN}";
 
1265     $prepend_userspath = 1;
 
1268   $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
 
1270   $self->{tmpfile} =~ s|.*/||;
 
1271   $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
 
1272   $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
 
1274   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
1275     $out = $self->{OUT};
 
1276     $self->{OUT} = ">$self->{tmpfile}";
 
1282     open OUT, "$self->{OUT}" or $self->error("$self->{OUT} : $!");
 
1283     $result = $template->parse(*OUT);
 
1288     $result = $template->parse(*STDOUT);
 
1293     $self->error("$self->{IN} : " . $template->get_error());
 
1296   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
1298     if ($self->{media} eq 'email') {
 
1300       my $mail = new Mailer;
 
1302       map { $mail->{$_} = $self->{$_} }
 
1303         qw(cc bcc subject message version format);
 
1304       $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
1305       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
 
1306       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
 
1307       $mail->{fileid} = "$fileid.";
 
1308       $myconfig->{signature} =~ s/\r//g;
 
1310       # if we send html or plain text inline
 
1311       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
 
1312         $mail->{contenttype} = "text/html";
 
1314         $mail->{message}       =~ s/\r//g;
 
1315         $mail->{message}       =~ s/\n/<br>\n/g;
 
1316         $myconfig->{signature} =~ s/\n/<br>\n/g;
 
1317         $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
 
1319         open(IN, $self->{tmpfile})
 
1320           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1322           $mail->{message} .= $_;
 
1329         if (!$self->{"do_not_attach"}) {
 
1330           my $attachment_name  =  $self->{attachment_filename} || $self->{tmpfile};
 
1331           $attachment_name     =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
 
1332           $mail->{attachments} =  [{ "filename" => $self->{tmpfile},
 
1333                                      "name"     => $attachment_name }];
 
1336         $mail->{message}  =~ s/\r//g;
 
1337         $mail->{message} .=  "\n-- \n$myconfig->{signature}";
 
1341       my $err = $mail->send();
 
1342       $self->error($self->cleanup . "$err") if ($err);
 
1346       $self->{OUT} = $out;
 
1348       my $numbytes = (-s $self->{tmpfile});
 
1349       open(IN, $self->{tmpfile})
 
1350         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1352       $self->{copies} = 1 unless $self->{media} eq 'printer';
 
1354       chdir("$self->{cwd}");
 
1355       #print(STDERR "Kopien $self->{copies}\n");
 
1356       #print(STDERR "OUT $self->{OUT}\n");
 
1357       for my $i (1 .. $self->{copies}) {
 
1359           open OUT, $self->{OUT} or $self->error($self->cleanup . "$self->{OUT} : $!");
 
1360           print OUT while <IN>;
 
1365           $self->{attachment_filename} = ($self->{attachment_filename})
 
1366                                        ? $self->{attachment_filename}
 
1367                                        : $self->generate_attachment_filename();
 
1369           # launch application
 
1370           print qq|Content-Type: | . $template->get_mime_type() . qq|
 
1371 Content-Disposition: attachment; filename="$self->{attachment_filename}"
 
1372 Content-Length: $numbytes
 
1376           $::locale->with_raw_io(\*STDOUT, sub { print while <IN> });
 
1387   chdir("$self->{cwd}");
 
1388   $main::lxdebug->leave_sub();
 
1391 sub get_formname_translation {
 
1392   $main::lxdebug->enter_sub();
 
1393   my ($self, $formname) = @_;
 
1395   $formname ||= $self->{formname};
 
1397   my %formname_translations = (
 
1398     bin_list                => $main::locale->text('Bin List'),
 
1399     credit_note             => $main::locale->text('Credit Note'),
 
1400     invoice                 => $main::locale->text('Invoice'),
 
1401     packing_list            => $main::locale->text('Packing List'),
 
1402     pick_list               => $main::locale->text('Pick List'),
 
1403     proforma                => $main::locale->text('Proforma Invoice'),
 
1404     purchase_order          => $main::locale->text('Purchase Order'),
 
1405     request_quotation       => $main::locale->text('RFQ'),
 
1406     sales_order             => $main::locale->text('Confirmation'),
 
1407     sales_quotation         => $main::locale->text('Quotation'),
 
1408     storno_invoice          => $main::locale->text('Storno Invoice'),
 
1409     storno_packing_list     => $main::locale->text('Storno Packing List'),
 
1410     sales_delivery_order    => $main::locale->text('Delivery Order'),
 
1411     purchase_delivery_order => $main::locale->text('Delivery Order'),
 
1412     dunning                 => $main::locale->text('Dunning'),
 
1415   $main::lxdebug->leave_sub();
 
1416   return $formname_translations{$formname}
 
1419 sub get_number_prefix_for_type {
 
1420   $main::lxdebug->enter_sub();
 
1424       (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
 
1425     : ($self->{type} =~ /_quotation$/)                        ? 'quo'
 
1426     : ($self->{type} =~ /_delivery_order$/)                   ? 'do'
 
1429   $main::lxdebug->leave_sub();
 
1433 sub get_extension_for_format {
 
1434   $main::lxdebug->enter_sub();
 
1437   my $extension = $self->{format} =~ /pdf/i          ? ".pdf"
 
1438                 : $self->{format} =~ /postscript/i   ? ".ps"
 
1439                 : $self->{format} =~ /opendocument/i ? ".odt"
 
1440                 : $self->{format} =~ /excel/i        ? ".xls"
 
1441                 : $self->{format} =~ /html/i         ? ".html"
 
1444   $main::lxdebug->leave_sub();
 
1448 sub generate_attachment_filename {
 
1449   $main::lxdebug->enter_sub();
 
1452   my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
 
1453   my $prefix              = $self->get_number_prefix_for_type();
 
1455   if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
 
1456     $attachment_filename .= ' (' . $main::locale->text('Preview') . ')' . $self->get_extension_for_format();
 
1458   } elsif ($attachment_filename && $self->{"${prefix}number"}) {
 
1459     $attachment_filename .=  "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
 
1462     $attachment_filename = "";
 
1465   $attachment_filename =  $main::locale->quote_special_chars('filenames', $attachment_filename);
 
1466   $attachment_filename =~ s|[\s/\\]+|_|g;
 
1468   $main::lxdebug->leave_sub();
 
1469   return $attachment_filename;
 
1472 sub generate_email_subject {
 
1473   $main::lxdebug->enter_sub();
 
1476   my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
 
1477   my $prefix  = $self->get_number_prefix_for_type();
 
1479   if ($subject && $self->{"${prefix}number"}) {
 
1480     $subject .= " " . $self->{"${prefix}number"}
 
1483   $main::lxdebug->leave_sub();
 
1488   $main::lxdebug->enter_sub();
 
1492   chdir("$self->{tmpdir}");
 
1495   if (-f "$self->{tmpfile}.err") {
 
1496     open(FH, "$self->{tmpfile}.err");
 
1501   if ($self->{tmpfile} && ! $::keep_temp_files) {
 
1502     $self->{tmpfile} =~ s|.*/||g;
 
1504     $self->{tmpfile} =~ s/\.\w+$//g;
 
1505     my $tmpfile = $self->{tmpfile};
 
1506     unlink(<$tmpfile.*>);
 
1509   chdir("$self->{cwd}");
 
1511   $main::lxdebug->leave_sub();
 
1517   $main::lxdebug->enter_sub();
 
1519   my ($self, $date, $myconfig) = @_;
 
1522   if ($date && $date =~ /\D/) {
 
1524     if ($myconfig->{dateformat} =~ /^yy/) {
 
1525       ($yy, $mm, $dd) = split /\D/, $date;
 
1527     if ($myconfig->{dateformat} =~ /^mm/) {
 
1528       ($mm, $dd, $yy) = split /\D/, $date;
 
1530     if ($myconfig->{dateformat} =~ /^dd/) {
 
1531       ($dd, $mm, $yy) = split /\D/, $date;
 
1536     $yy = ($yy < 70) ? $yy + 2000 : $yy;
 
1537     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
 
1539     $dd = "0$dd" if ($dd < 10);
 
1540     $mm = "0$mm" if ($mm < 10);
 
1542     $date = "$yy$mm$dd";
 
1545   $main::lxdebug->leave_sub();
 
1550 # Database routines used throughout
 
1553   $main::lxdebug->enter_sub(2);
 
1555   my ($self, $myconfig) = @_;
 
1557   # connect to database
 
1559     DBI->connect($myconfig->{dbconnect},
 
1560                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
 
1564   if ($myconfig->{dboptions}) {
 
1565     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1568   $main::lxdebug->leave_sub(2);
 
1573 sub dbconnect_noauto {
 
1574   $main::lxdebug->enter_sub();
 
1576   my ($self, $myconfig) = @_;
 
1578   # connect to database
 
1580     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
 
1581                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
 
1585   if ($myconfig->{dboptions}) {
 
1586     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1589   $main::lxdebug->leave_sub();
 
1594 sub get_standard_dbh {
 
1595   $main::lxdebug->enter_sub(2);
 
1598   my $myconfig = shift || \%::myconfig;
 
1600   if ($standard_dbh && !$standard_dbh->{Active}) {
 
1601     $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
 
1602     undef $standard_dbh;
 
1605   $standard_dbh ||= $self->dbconnect_noauto($myconfig);
 
1607   $main::lxdebug->leave_sub(2);
 
1609   return $standard_dbh;
 
1613   $main::lxdebug->enter_sub();
 
1615   my ($self, $date, $myconfig) = @_;
 
1616   my $dbh = $self->dbconnect($myconfig);
 
1618   my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
 
1619   my $sth = prepare_execute_query($self, $dbh, $query, $date);
 
1620   my ($closed) = $sth->fetchrow_array;
 
1622   $main::lxdebug->leave_sub();
 
1627 sub update_balance {
 
1628   $main::lxdebug->enter_sub();
 
1630   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
 
1632   # if we have a value, go do it
 
1635     # retrieve balance from table
 
1636     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
 
1637     my $sth = prepare_execute_query($self, $dbh, $query, @values);
 
1638     my ($balance) = $sth->fetchrow_array;
 
1644     $query = "UPDATE $table SET $field = $balance WHERE $where";
 
1645     do_query($self, $dbh, $query, @values);
 
1647   $main::lxdebug->leave_sub();
 
1650 sub update_exchangerate {
 
1651   $main::lxdebug->enter_sub();
 
1653   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
 
1655   # some sanity check for currency
 
1657     $main::lxdebug->leave_sub();
 
1660   $query = qq|SELECT curr FROM defaults|;
 
1662   my ($currency) = selectrow_query($self, $dbh, $query);
 
1663   my ($defaultcurrency) = split m/:/, $currency;
 
1666   if ($curr eq $defaultcurrency) {
 
1667     $main::lxdebug->leave_sub();
 
1671   $query = qq|SELECT e.curr FROM exchangerate e
 
1672                  WHERE e.curr = ? AND e.transdate = ?
 
1674   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
 
1683   $buy = conv_i($buy, "NULL");
 
1684   $sell = conv_i($sell, "NULL");
 
1687   if ($buy != 0 && $sell != 0) {
 
1688     $set = "buy = $buy, sell = $sell";
 
1689   } elsif ($buy != 0) {
 
1690     $set = "buy = $buy";
 
1691   } elsif ($sell != 0) {
 
1692     $set = "sell = $sell";
 
1695   if ($sth->fetchrow_array) {
 
1696     $query = qq|UPDATE exchangerate
 
1702     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
 
1703                 VALUES (?, $buy, $sell, ?)|;
 
1706   do_query($self, $dbh, $query, $curr, $transdate);
 
1708   $main::lxdebug->leave_sub();
 
1711 sub save_exchangerate {
 
1712   $main::lxdebug->enter_sub();
 
1714   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
 
1716   my $dbh = $self->dbconnect($myconfig);
 
1720   $buy  = $rate if $fld eq 'buy';
 
1721   $sell = $rate if $fld eq 'sell';
 
1724   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
 
1729   $main::lxdebug->leave_sub();
 
1732 sub get_exchangerate {
 
1733   $main::lxdebug->enter_sub();
 
1735   my ($self, $dbh, $curr, $transdate, $fld) = @_;
 
1738   unless ($transdate) {
 
1739     $main::lxdebug->leave_sub();
 
1743   $query = qq|SELECT curr FROM defaults|;
 
1745   my ($currency) = selectrow_query($self, $dbh, $query);
 
1746   my ($defaultcurrency) = split m/:/, $currency;
 
1748   if ($currency eq $defaultcurrency) {
 
1749     $main::lxdebug->leave_sub();
 
1753   $query = qq|SELECT e.$fld FROM exchangerate e
 
1754                  WHERE e.curr = ? AND e.transdate = ?|;
 
1755   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
 
1759   $main::lxdebug->leave_sub();
 
1761   return $exchangerate;
 
1764 sub check_exchangerate {
 
1765   $main::lxdebug->enter_sub();
 
1767   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
 
1769   if ($fld !~/^buy|sell$/) {
 
1770     $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
 
1773   unless ($transdate) {
 
1774     $main::lxdebug->leave_sub();
 
1778   my ($defaultcurrency) = $self->get_default_currency($myconfig);
 
1780   if ($currency eq $defaultcurrency) {
 
1781     $main::lxdebug->leave_sub();
 
1785   my $dbh   = $self->get_standard_dbh($myconfig);
 
1786   my $query = qq|SELECT e.$fld FROM exchangerate e
 
1787                  WHERE e.curr = ? AND e.transdate = ?|;
 
1789   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
 
1791   $main::lxdebug->leave_sub();
 
1793   return $exchangerate;
 
1796 sub get_all_currencies {
 
1797   $main::lxdebug->enter_sub();
 
1800   my $myconfig = shift || \%::myconfig;
 
1801   my $dbh      = $self->get_standard_dbh($myconfig);
 
1803   my $query = qq|SELECT curr FROM defaults|;
 
1805   my ($curr)     = selectrow_query($self, $dbh, $query);
 
1806   my @currencies = grep { $_ } map { s/\s//g; $_ } split m/:/, $curr;
 
1808   $main::lxdebug->leave_sub();
 
1813 sub get_default_currency {
 
1814   $main::lxdebug->enter_sub();
 
1816   my ($self, $myconfig) = @_;
 
1817   my @currencies        = $self->get_all_currencies($myconfig);
 
1819   $main::lxdebug->leave_sub();
 
1821   return $currencies[0];
 
1824 sub set_payment_options {
 
1825   $main::lxdebug->enter_sub();
 
1827   my ($self, $myconfig, $transdate) = @_;
 
1829   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
 
1831   my $dbh = $self->get_standard_dbh($myconfig);
 
1834     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
 
1835     qq|FROM payment_terms p | .
 
1838   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
 
1839    $self->{payment_terms}) =
 
1840      selectrow_query($self, $dbh, $query, $self->{payment_id});
 
1842   if ($transdate eq "") {
 
1843     if ($self->{invdate}) {
 
1844       $transdate = $self->{invdate};
 
1846       $transdate = $self->{transdate};
 
1851     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
 
1852     qq|FROM payment_terms|;
 
1853   ($self->{netto_date}, $self->{skonto_date}) =
 
1854     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
 
1856   my ($invtotal, $total);
 
1857   my (%amounts, %formatted_amounts);
 
1859   if ($self->{type} =~ /_order$/) {
 
1860     $amounts{invtotal} = $self->{ordtotal};
 
1861     $amounts{total}    = $self->{ordtotal};
 
1863   } elsif ($self->{type} =~ /_quotation$/) {
 
1864     $amounts{invtotal} = $self->{quototal};
 
1865     $amounts{total}    = $self->{quototal};
 
1868     $amounts{invtotal} = $self->{invtotal};
 
1869     $amounts{total}    = $self->{total};
 
1871   $amounts{skonto_in_percent} = 100.0 * $self->{percent_skonto};
 
1873   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
 
1875   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
 
1876   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
 
1877   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
 
1879   foreach (keys %amounts) {
 
1880     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
 
1881     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
 
1884   if ($self->{"language_id"}) {
 
1886       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
 
1887       qq|FROM translation_payment_terms t | .
 
1888       qq|LEFT JOIN language l ON t.language_id = l.id | .
 
1889       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
 
1890     my ($description_long, $output_numberformat, $output_dateformat,
 
1891       $output_longdates) =
 
1892       selectrow_query($self, $dbh, $query,
 
1893                       $self->{"language_id"}, $self->{"payment_id"});
 
1895     $self->{payment_terms} = $description_long if ($description_long);
 
1897     if ($output_dateformat) {
 
1898       foreach my $key (qw(netto_date skonto_date)) {
 
1900           $main::locale->reformat_date($myconfig, $self->{$key},
 
1906     if ($output_numberformat &&
 
1907         ($output_numberformat ne $myconfig->{"numberformat"})) {
 
1908       my $saved_numberformat = $myconfig->{"numberformat"};
 
1909       $myconfig->{"numberformat"} = $output_numberformat;
 
1910       map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
 
1911       $myconfig->{"numberformat"} = $saved_numberformat;
 
1915   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
 
1916   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
 
1917   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
 
1918   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
 
1919   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
 
1920   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
 
1921   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
 
1923   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
 
1925   $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
 
1927   $main::lxdebug->leave_sub();
 
1931 sub get_template_language {
 
1932   $main::lxdebug->enter_sub();
 
1934   my ($self, $myconfig) = @_;
 
1936   my $template_code = "";
 
1938   if ($self->{language_id}) {
 
1939     my $dbh = $self->get_standard_dbh($myconfig);
 
1940     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
 
1941     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
 
1944   $main::lxdebug->leave_sub();
 
1946   return $template_code;
 
1949 sub get_printer_code {
 
1950   $main::lxdebug->enter_sub();
 
1952   my ($self, $myconfig) = @_;
 
1954   my $template_code = "";
 
1956   if ($self->{printer_id}) {
 
1957     my $dbh = $self->get_standard_dbh($myconfig);
 
1958     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
 
1959     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
 
1962   $main::lxdebug->leave_sub();
 
1964   return $template_code;
 
1968   $main::lxdebug->enter_sub();
 
1970   my ($self, $myconfig) = @_;
 
1972   my $template_code = "";
 
1974   if ($self->{shipto_id}) {
 
1975     my $dbh = $self->get_standard_dbh($myconfig);
 
1976     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
 
1977     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
 
1978     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
 
1981   $main::lxdebug->leave_sub();
 
1985   $main::lxdebug->enter_sub();
 
1987   my ($self, $dbh, $id, $module) = @_;
 
1992   foreach my $item (qw(name department_1 department_2 street zipcode city country
 
1993                        contact phone fax email)) {
 
1994     if ($self->{"shipto$item"}) {
 
1995       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
 
1997     push(@values, $self->{"shipto${item}"});
 
2001     if ($self->{shipto_id}) {
 
2002       my $query = qq|UPDATE shipto set
 
2004                        shiptodepartment_1 = ?,
 
2005                        shiptodepartment_2 = ?,
 
2014                      WHERE shipto_id = ?|;
 
2015       do_query($self, $dbh, $query, @values, $self->{shipto_id});
 
2017       my $query = qq|SELECT * FROM shipto
 
2018                      WHERE shiptoname = ? AND
 
2019                        shiptodepartment_1 = ? AND
 
2020                        shiptodepartment_2 = ? AND
 
2021                        shiptostreet = ? AND
 
2022                        shiptozipcode = ? AND
 
2024                        shiptocountry = ? AND
 
2025                        shiptocontact = ? AND
 
2031       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
 
2034           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
 
2035                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
 
2036                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
 
2037              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
 
2038         do_query($self, $dbh, $query, $id, @values, $module);
 
2043   $main::lxdebug->leave_sub();
 
2047   $main::lxdebug->enter_sub();
 
2049   my ($self, $dbh) = @_;
 
2051   $dbh ||= $self->get_standard_dbh(\%main::myconfig);
 
2053   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
 
2054   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
 
2055   $self->{"employee_id"} *= 1;
 
2057   $main::lxdebug->leave_sub();
 
2060 sub get_employee_data {
 
2061   $main::lxdebug->enter_sub();
 
2066   Common::check_params(\%params, qw(prefix));
 
2067   Common::check_params_x(\%params, qw(id));
 
2070     $main::lxdebug->leave_sub();
 
2074   my $myconfig = \%main::myconfig;
 
2075   my $dbh      = $params{dbh} || $self->get_standard_dbh($myconfig);
 
2077   my ($login)  = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
 
2080     my $user = User->new($login);
 
2081     map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
 
2083     $self->{$params{prefix} . '_login'}   = $login;
 
2084     $self->{$params{prefix} . '_name'}  ||= $login;
 
2087   $main::lxdebug->leave_sub();
 
2091   $main::lxdebug->enter_sub();
 
2093   my ($self, $myconfig, $reference_date) = @_;
 
2095   $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
 
2097   my $dbh         = $self->get_standard_dbh($myconfig);
 
2098   my $query       = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
 
2099   my ($duedate)   = selectrow_query($self, $dbh, $query, $self->{payment_id});
 
2101   $main::lxdebug->leave_sub();
 
2107   $main::lxdebug->enter_sub();
 
2109   my ($self, $dbh, $id, $key) = @_;
 
2111   $key = "all_contacts" unless ($key);
 
2115     $main::lxdebug->leave_sub();
 
2120     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
 
2121     qq|FROM contacts | .
 
2122     qq|WHERE cp_cv_id = ? | .
 
2123     qq|ORDER BY lower(cp_name)|;
 
2125   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
 
2127   $main::lxdebug->leave_sub();
 
2131   $main::lxdebug->enter_sub();
 
2133   my ($self, $dbh, $key) = @_;
 
2135   my ($all, $old_id, $where, @values);
 
2137   if (ref($key) eq "HASH") {
 
2140     $key = "ALL_PROJECTS";
 
2142     foreach my $p (keys(%{$params})) {
 
2144         $all = $params->{$p};
 
2145       } elsif ($p eq "old_id") {
 
2146         $old_id = $params->{$p};
 
2147       } elsif ($p eq "key") {
 
2148         $key = $params->{$p};
 
2154     $where = "WHERE active ";
 
2156       if (ref($old_id) eq "ARRAY") {
 
2157         my @ids = grep({ $_ } @{$old_id});
 
2159           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
 
2160           push(@values, @ids);
 
2163         $where .= " OR (id = ?) ";
 
2164         push(@values, $old_id);
 
2170     qq|SELECT id, projectnumber, description, active | .
 
2173     qq|ORDER BY lower(projectnumber)|;
 
2175   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
 
2177   $main::lxdebug->leave_sub();
 
2181   $main::lxdebug->enter_sub();
 
2183   my ($self, $dbh, $vc_id, $key) = @_;
 
2185   $key = "all_shipto" unless ($key);
 
2188     # get shipping addresses
 
2189     my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
 
2191     $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
 
2197   $main::lxdebug->leave_sub();
 
2201   $main::lxdebug->enter_sub();
 
2203   my ($self, $dbh, $key) = @_;
 
2205   $key = "all_printers" unless ($key);
 
2207   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
 
2209   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2211   $main::lxdebug->leave_sub();
 
2215   $main::lxdebug->enter_sub();
 
2217   my ($self, $dbh, $params) = @_;
 
2220   $key = $params->{key};
 
2221   $key = "all_charts" unless ($key);
 
2223   my $transdate = quote_db_date($params->{transdate});
 
2226     qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
 
2228     qq|LEFT JOIN taxkeys tk ON | .
 
2229     qq|(tk.id = (SELECT id FROM taxkeys | .
 
2230     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
 
2231     qq|          ORDER BY startdate DESC LIMIT 1)) | .
 
2232     qq|ORDER BY c.accno|;
 
2234   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2236   $main::lxdebug->leave_sub();
 
2239 sub _get_taxcharts {
 
2240   $main::lxdebug->enter_sub();
 
2242   my ($self, $dbh, $params) = @_;
 
2244   my $key = "all_taxcharts";
 
2247   if (ref $params eq 'HASH') {
 
2248     $key = $params->{key} if ($params->{key});
 
2249     if ($params->{module} eq 'AR') {
 
2250       push @where, 'taxkey NOT IN (8, 9, 18, 19)';
 
2252     } elsif ($params->{module} eq 'AP') {
 
2253       push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
 
2260   my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
 
2262   my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
 
2264   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2266   $main::lxdebug->leave_sub();
 
2270   $main::lxdebug->enter_sub();
 
2272   my ($self, $dbh, $key) = @_;
 
2274   $key = "all_taxzones" unless ($key);
 
2276   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
 
2278   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2280   $main::lxdebug->leave_sub();
 
2283 sub _get_employees {
 
2284   $main::lxdebug->enter_sub();
 
2286   my ($self, $dbh, $default_key, $key) = @_;
 
2288   $key = $default_key unless ($key);
 
2289   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
 
2291   $main::lxdebug->leave_sub();
 
2294 sub _get_business_types {
 
2295   $main::lxdebug->enter_sub();
 
2297   my ($self, $dbh, $key) = @_;
 
2299   my $options       = ref $key eq 'HASH' ? $key : { key => $key };
 
2300   $options->{key} ||= "all_business_types";
 
2303   if (exists $options->{salesman}) {
 
2304     $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
 
2307   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
 
2309   $main::lxdebug->leave_sub();
 
2312 sub _get_languages {
 
2313   $main::lxdebug->enter_sub();
 
2315   my ($self, $dbh, $key) = @_;
 
2317   $key = "all_languages" unless ($key);
 
2319   my $query = qq|SELECT * FROM language ORDER BY id|;
 
2321   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2323   $main::lxdebug->leave_sub();
 
2326 sub _get_dunning_configs {
 
2327   $main::lxdebug->enter_sub();
 
2329   my ($self, $dbh, $key) = @_;
 
2331   $key = "all_dunning_configs" unless ($key);
 
2333   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
 
2335   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2337   $main::lxdebug->leave_sub();
 
2340 sub _get_currencies {
 
2341 $main::lxdebug->enter_sub();
 
2343   my ($self, $dbh, $key) = @_;
 
2345   $key = "all_currencies" unless ($key);
 
2347   my $query = qq|SELECT curr AS currency FROM defaults|;
 
2349   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
 
2351   $main::lxdebug->leave_sub();
 
2355 $main::lxdebug->enter_sub();
 
2357   my ($self, $dbh, $key) = @_;
 
2359   $key = "all_payments" unless ($key);
 
2361   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
 
2363   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2365   $main::lxdebug->leave_sub();
 
2368 sub _get_customers {
 
2369   $main::lxdebug->enter_sub();
 
2371   my ($self, $dbh, $key) = @_;
 
2373   my $options        = ref $key eq 'HASH' ? $key : { key => $key };
 
2374   $options->{key}  ||= "all_customers";
 
2375   my $limit_clause   = "LIMIT $options->{limit}" if $options->{limit};
 
2376   my $where          = $options->{business_is_salesman} ? qq| AND business_id IN (SELECT id FROM business WHERE salesman)| : '';
 
2378   my $query = qq|SELECT * FROM customer WHERE NOT obsolete $where ORDER BY name $limit_clause|;
 
2379   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
 
2381   $main::lxdebug->leave_sub();
 
2385   $main::lxdebug->enter_sub();
 
2387   my ($self, $dbh, $key) = @_;
 
2389   $key = "all_vendors" unless ($key);
 
2391   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
 
2393   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2395   $main::lxdebug->leave_sub();
 
2398 sub _get_departments {
 
2399   $main::lxdebug->enter_sub();
 
2401   my ($self, $dbh, $key) = @_;
 
2403   $key = "all_departments" unless ($key);
 
2405   my $query = qq|SELECT * FROM department ORDER BY description|;
 
2407   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2409   $main::lxdebug->leave_sub();
 
2412 sub _get_warehouses {
 
2413   $main::lxdebug->enter_sub();
 
2415   my ($self, $dbh, $param) = @_;
 
2417   my ($key, $bins_key);
 
2419   if ('' eq ref $param) {
 
2423     $key      = $param->{key};
 
2424     $bins_key = $param->{bins};
 
2427   my $query = qq|SELECT w.* FROM warehouse w
 
2428                  WHERE (NOT w.invalid) AND
 
2429                    ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
 
2430                  ORDER BY w.sortkey|;
 
2432   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2435     $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
 
2436     my $sth = prepare_query($self, $dbh, $query);
 
2438     foreach my $warehouse (@{ $self->{$key} }) {
 
2439       do_statement($self, $sth, $query, $warehouse->{id});
 
2440       $warehouse->{$bins_key} = [];
 
2442       while (my $ref = $sth->fetchrow_hashref()) {
 
2443         push @{ $warehouse->{$bins_key} }, $ref;
 
2449   $main::lxdebug->leave_sub();
 
2453   $main::lxdebug->enter_sub();
 
2455   my ($self, $dbh, $table, $key, $sortkey) = @_;
 
2457   my $query  = qq|SELECT * FROM $table|;
 
2458   $query    .= qq| ORDER BY $sortkey| if ($sortkey);
 
2460   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2462   $main::lxdebug->leave_sub();
 
2466 #  $main::lxdebug->enter_sub();
 
2468 #  my ($self, $dbh, $key) = @_;
 
2470 #  $key ||= "all_groups";
 
2472 #  my $groups = $main::auth->read_groups();
 
2474 #  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2476 #  $main::lxdebug->leave_sub();
 
2480   $main::lxdebug->enter_sub();
 
2485   my $dbh = $self->get_standard_dbh(\%main::myconfig);
 
2486   my ($sth, $query, $ref);
 
2488   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
 
2489   my $vc_id = $self->{"${vc}_id"};
 
2491   if ($params{"contacts"}) {
 
2492     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
 
2495   if ($params{"shipto"}) {
 
2496     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
 
2499   if ($params{"projects"} || $params{"all_projects"}) {
 
2500     $self->_get_projects($dbh, $params{"all_projects"} ?
 
2501                          $params{"all_projects"} : $params{"projects"},
 
2502                          $params{"all_projects"} ? 1 : 0);
 
2505   if ($params{"printers"}) {
 
2506     $self->_get_printers($dbh, $params{"printers"});
 
2509   if ($params{"languages"}) {
 
2510     $self->_get_languages($dbh, $params{"languages"});
 
2513   if ($params{"charts"}) {
 
2514     $self->_get_charts($dbh, $params{"charts"});
 
2517   if ($params{"taxcharts"}) {
 
2518     $self->_get_taxcharts($dbh, $params{"taxcharts"});
 
2521   if ($params{"taxzones"}) {
 
2522     $self->_get_taxzones($dbh, $params{"taxzones"});
 
2525   if ($params{"employees"}) {
 
2526     $self->_get_employees($dbh, "all_employees", $params{"employees"});
 
2529   if ($params{"salesmen"}) {
 
2530     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
 
2533   if ($params{"business_types"}) {
 
2534     $self->_get_business_types($dbh, $params{"business_types"});
 
2537   if ($params{"dunning_configs"}) {
 
2538     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
 
2541   if($params{"currencies"}) {
 
2542     $self->_get_currencies($dbh, $params{"currencies"});
 
2545   if($params{"customers"}) {
 
2546     $self->_get_customers($dbh, $params{"customers"});
 
2549   if($params{"vendors"}) {
 
2550     if (ref $params{"vendors"} eq 'HASH') {
 
2551       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
 
2553       $self->_get_vendors($dbh, $params{"vendors"});
 
2557   if($params{"payments"}) {
 
2558     $self->_get_payments($dbh, $params{"payments"});
 
2561   if($params{"departments"}) {
 
2562     $self->_get_departments($dbh, $params{"departments"});
 
2565   if ($params{price_factors}) {
 
2566     $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
 
2569   if ($params{warehouses}) {
 
2570     $self->_get_warehouses($dbh, $params{warehouses});
 
2573 #  if ($params{groups}) {
 
2574 #    $self->_get_groups($dbh, $params{groups});
 
2577   if ($params{partsgroup}) {
 
2578     $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
 
2581   $main::lxdebug->leave_sub();
 
2584 # this sub gets the id and name from $table
 
2586   $main::lxdebug->enter_sub();
 
2588   my ($self, $myconfig, $table) = @_;
 
2590   # connect to database
 
2591   my $dbh = $self->get_standard_dbh($myconfig);
 
2593   $table = $table eq "customer" ? "customer" : "vendor";
 
2594   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
 
2596   my ($query, @values);
 
2598   if (!$self->{openinvoices}) {
 
2600     if ($self->{customernumber} ne "") {
 
2601       $where = qq|(vc.customernumber ILIKE ?)|;
 
2602       push(@values, '%' . $self->{customernumber} . '%');
 
2604       $where = qq|(vc.name ILIKE ?)|;
 
2605       push(@values, '%' . $self->{$table} . '%');
 
2609       qq~SELECT vc.id, vc.name,
 
2610            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
2612          WHERE $where AND (NOT vc.obsolete)
 
2616       qq~SELECT DISTINCT vc.id, vc.name,
 
2617            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
2619          JOIN $table vc ON (a.${table}_id = vc.id)
 
2620          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
 
2622     push(@values, '%' . $self->{$table} . '%');
 
2625   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
 
2627   $main::lxdebug->leave_sub();
 
2629   return scalar(@{ $self->{name_list} });
 
2632 # the selection sub is used in the AR, AP, IS, IR and OE module
 
2635   $main::lxdebug->enter_sub();
 
2637   my ($self, $myconfig, $table, $module) = @_;
 
2640   my $dbh = $self->get_standard_dbh;
 
2642   $table = $table eq "customer" ? "customer" : "vendor";
 
2644   my $query = qq|SELECT count(*) FROM $table|;
 
2645   my ($count) = selectrow_query($self, $dbh, $query);
 
2647   # build selection list
 
2648   if ($count <= $myconfig->{vclimit}) {
 
2649     $query = qq|SELECT id, name, salesman_id
 
2650                 FROM $table WHERE NOT obsolete
 
2652     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
 
2656   $self->get_employee($dbh);
 
2658   # setup sales contacts
 
2659   $query = qq|SELECT e.id, e.name
 
2661               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
 
2662   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
 
2665   push(@{ $self->{all_employees} },
 
2666        { id   => $self->{employee_id},
 
2667          name => $self->{employee} });
 
2669   # sort the whole thing
 
2670   @{ $self->{all_employees} } =
 
2671     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
 
2673   if ($module eq 'AR') {
 
2675     # prepare query for departments
 
2676     $query = qq|SELECT id, description
 
2679                 ORDER BY description|;
 
2682     $query = qq|SELECT id, description
 
2684                 ORDER BY description|;
 
2687   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2690   $query = qq|SELECT id, description
 
2694   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2697   $query = qq|SELECT printer_description, id
 
2699               ORDER BY printer_description|;
 
2701   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2704   $query = qq|SELECT id, description
 
2708   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
2710   $main::lxdebug->leave_sub();
 
2713 sub language_payment {
 
2714   $main::lxdebug->enter_sub();
 
2716   my ($self, $myconfig) = @_;
 
2718   my $dbh = $self->get_standard_dbh($myconfig);
 
2720   my $query = qq|SELECT id, description
 
2724   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2727   $query = qq|SELECT printer_description, id
 
2729               ORDER BY printer_description|;
 
2731   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2734   $query = qq|SELECT id, description
 
2738   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
2740   # get buchungsgruppen
 
2741   $query = qq|SELECT id, description
 
2742               FROM buchungsgruppen|;
 
2744   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
 
2746   $main::lxdebug->leave_sub();
 
2749 # this is only used for reports
 
2750 sub all_departments {
 
2751   $main::lxdebug->enter_sub();
 
2753   my ($self, $myconfig, $table) = @_;
 
2755   my $dbh = $self->get_standard_dbh($myconfig);
 
2758   if ($table eq 'customer') {
 
2759     $where = "WHERE role = 'P' ";
 
2762   my $query = qq|SELECT id, description
 
2765                  ORDER BY description|;
 
2766   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2768   delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
 
2770   $main::lxdebug->leave_sub();
 
2774   $main::lxdebug->enter_sub();
 
2776   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
 
2779   if ($table eq "customer") {
 
2788   $self->all_vc($myconfig, $table, $module);
 
2790   # get last customers or vendors
 
2791   my ($query, $sth, $ref);
 
2793   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
 
2798     my $transdate = "current_date";
 
2799     if ($self->{transdate}) {
 
2800       $transdate = $dbh->quote($self->{transdate});
 
2803     # now get the account numbers
 
2804     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
 
2805                 FROM chart c, taxkeys tk
 
2806                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
 
2807                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
 
2810     $sth = $dbh->prepare($query);
 
2812     do_statement($self, $sth, $query, '%' . $module . '%');
 
2814     $self->{accounts} = "";
 
2815     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2817       foreach my $key (split(/:/, $ref->{link})) {
 
2818         if ($key =~ /\Q$module\E/) {
 
2820           # cross reference for keys
 
2821           $xkeyref{ $ref->{accno} } = $key;
 
2823           push @{ $self->{"${module}_links"}{$key} },
 
2824             { accno       => $ref->{accno},
 
2825               description => $ref->{description},
 
2826               taxkey      => $ref->{taxkey_id},
 
2827               tax_id      => $ref->{tax_id} };
 
2829           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2835   # get taxkeys and description
 
2836   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
 
2837   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
 
2839   if (($module eq "AP") || ($module eq "AR")) {
 
2840     # get tax rates and description
 
2841     $query = qq|SELECT * FROM tax|;
 
2842     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
 
2848            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
 
2849            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
 
2850            a.intnotes, a.department_id, a.amount AS oldinvtotal,
 
2851            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
 
2853            d.description AS department,
 
2856          JOIN $table c ON (a.${table}_id = c.id)
 
2857          LEFT JOIN employee e ON (e.id = a.employee_id)
 
2858          LEFT JOIN department d ON (d.id = a.department_id)
 
2860     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
 
2862     foreach my $key (keys %$ref) {
 
2863       $self->{$key} = $ref->{$key};
 
2866     my $transdate = "current_date";
 
2867     if ($self->{transdate}) {
 
2868       $transdate = $dbh->quote($self->{transdate});
 
2871     # now get the account numbers
 
2872     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
 
2874                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
 
2876                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
 
2877                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
 
2880     $sth = $dbh->prepare($query);
 
2881     do_statement($self, $sth, $query, "%$module%");
 
2883     $self->{accounts} = "";
 
2884     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2886       foreach my $key (split(/:/, $ref->{link})) {
 
2887         if ($key =~ /\Q$module\E/) {
 
2889           # cross reference for keys
 
2890           $xkeyref{ $ref->{accno} } = $key;
 
2892           push @{ $self->{"${module}_links"}{$key} },
 
2893             { accno       => $ref->{accno},
 
2894               description => $ref->{description},
 
2895               taxkey      => $ref->{taxkey_id},
 
2896               tax_id      => $ref->{tax_id} };
 
2898           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2904     # get amounts from individual entries
 
2907            c.accno, c.description,
 
2908            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
 
2912          LEFT JOIN chart c ON (c.id = a.chart_id)
 
2913          LEFT JOIN project p ON (p.id = a.project_id)
 
2914          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
 
2915                                     WHERE (tk.taxkey_id=a.taxkey) AND
 
2916                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
 
2917                                         THEN tk.chart_id = a.chart_id
 
2920                                        OR (c.link='%tax%')) AND
 
2921                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
 
2922          WHERE a.trans_id = ?
 
2923          AND a.fx_transaction = '0'
 
2924          ORDER BY a.acc_trans_id, a.transdate|;
 
2925     $sth = $dbh->prepare($query);
 
2926     do_statement($self, $sth, $query, $self->{id});
 
2928     # get exchangerate for currency
 
2929     $self->{exchangerate} =
 
2930       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2933     # store amounts in {acc_trans}{$key} for multiple accounts
 
2934     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2935       $ref->{exchangerate} =
 
2936         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
 
2937       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
 
2940       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
 
2941         $ref->{amount} *= -1;
 
2943       $ref->{index} = $index;
 
2945       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
 
2951            d.curr AS currencies, d.closedto, d.revtrans,
 
2952            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2953            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
2955     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2956     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2963             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
 
2964             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2965             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
2967     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2968     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2970     if ($self->{"$self->{vc}_id"}) {
 
2972       # only setup currency
 
2973       ($self->{currency}) = split(/:/, $self->{currencies});
 
2977       $self->lastname_used($dbh, $myconfig, $table, $module);
 
2979       # get exchangerate for currency
 
2980       $self->{exchangerate} =
 
2981         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2987   $main::lxdebug->leave_sub();
 
2991   $main::lxdebug->enter_sub();
 
2993   my ($self, $dbh, $myconfig, $table, $module) = @_;
 
2997   $table         = $table eq "customer" ? "customer" : "vendor";
 
2998   my %column_map = ("a.curr"                  => "currency",
 
2999                     "a.${table}_id"           => "${table}_id",
 
3000                     "a.department_id"         => "department_id",
 
3001                     "d.description"           => "department",
 
3002                     "ct.name"                 => $table,
 
3003                     "current_date + ct.terms" => "duedate",
 
3006   if ($self->{type} =~ /delivery_order/) {
 
3007     $arap  = 'delivery_orders';
 
3008     delete $column_map{"a.curr"};
 
3010   } elsif ($self->{type} =~ /_order/) {
 
3012     $where = "quotation = '0'";
 
3014   } elsif ($self->{type} =~ /_quotation/) {
 
3016     $where = "quotation = '1'";
 
3018   } elsif ($table eq 'customer') {
 
3026   $where           = "($where) AND" if ($where);
 
3027   my $query        = qq|SELECT MAX(id) FROM $arap
 
3028                         WHERE $where ${table}_id > 0|;
 
3029   my ($trans_id)   = selectrow_query($self, $dbh, $query);
 
3032   my $column_spec  = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
 
3033   $query           = qq|SELECT $column_spec
 
3035                         LEFT JOIN $table     ct ON (a.${table}_id = ct.id)
 
3036                         LEFT JOIN department d  ON (a.department_id = d.id)
 
3038   my $ref          = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
 
3040   map { $self->{$_} = $ref->{$_} } values %column_map;
 
3042   $main::lxdebug->leave_sub();
 
3046   $main::lxdebug->enter_sub();
 
3049   my $myconfig = shift || \%::myconfig;
 
3050   my ($thisdate, $days) = @_;
 
3052   my $dbh = $self->get_standard_dbh($myconfig);
 
3057     my $dateformat = $myconfig->{dateformat};
 
3058     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
 
3059     $thisdate = $dbh->quote($thisdate);
 
3060     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
 
3062     $query = qq|SELECT current_date AS thisdate|;
 
3065   ($thisdate) = selectrow_query($self, $dbh, $query);
 
3067   $main::lxdebug->leave_sub();
 
3073   $main::lxdebug->enter_sub();
 
3075   my ($self, $string) = @_;
 
3077   if ($string !~ /%/) {
 
3078     $string = "%$string%";
 
3081   $string =~ s/\'/\'\'/g;
 
3083   $main::lxdebug->leave_sub();
 
3089   $main::lxdebug->enter_sub();
 
3091   my ($self, $flds, $new, $count, $numrows) = @_;
 
3095   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
 
3100   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
 
3102     my $j = $item->{ndx} - 1;
 
3103     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
 
3107   for $i ($count + 1 .. $numrows) {
 
3108     map { delete $self->{"${_}_$i"} } @{$flds};
 
3111   $main::lxdebug->leave_sub();
 
3115   $main::lxdebug->enter_sub();
 
3117   my ($self, $myconfig) = @_;
 
3121   my $dbh = $self->dbconnect_noauto($myconfig);
 
3123   my $query = qq|DELETE FROM status
 
3124                  WHERE (formname = ?) AND (trans_id = ?)|;
 
3125   my $sth = prepare_query($self, $dbh, $query);
 
3127   if ($self->{formname} =~ /(check|receipt)/) {
 
3128     for $i (1 .. $self->{rowcount}) {
 
3129       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
 
3132     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
 
3136   my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3137   my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3139   my %queued = split / /, $self->{queued};
 
3142   if ($self->{formname} =~ /(check|receipt)/) {
 
3144     # this is a check or receipt, add one entry for each lineitem
 
3145     my ($accno) = split /--/, $self->{account};
 
3146     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
 
3147                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
 
3148     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
 
3149     $sth = prepare_query($self, $dbh, $query);
 
3151     for $i (1 .. $self->{rowcount}) {
 
3152       if ($self->{"checked_$i"}) {
 
3153         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
 
3159     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
3160                 VALUES (?, ?, ?, ?, ?)|;
 
3161     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
 
3162              $queued{$self->{formname}}, $self->{formname});
 
3168   $main::lxdebug->leave_sub();
 
3172   $main::lxdebug->enter_sub();
 
3174   my ($self, $dbh) = @_;
 
3176   my ($query, $printed, $emailed);
 
3178   my $formnames  = $self->{printed};
 
3179   my $emailforms = $self->{emailed};
 
3181   $query = qq|DELETE FROM status
 
3182                  WHERE (formname = ?) AND (trans_id = ?)|;
 
3183   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
 
3185   # this only applies to the forms
 
3186   # checks and receipts are posted when printed or queued
 
3188   if ($self->{queued}) {
 
3189     my %queued = split / /, $self->{queued};
 
3191     foreach my $formname (keys %queued) {
 
3192       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3193       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3195       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
3196                   VALUES (?, ?, ?, ?, ?)|;
 
3197       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
 
3199       $formnames  =~ s/\Q$self->{formname}\E//;
 
3200       $emailforms =~ s/\Q$self->{formname}\E//;
 
3205   # save printed, emailed info
 
3206   $formnames  =~ s/^ +//g;
 
3207   $emailforms =~ s/^ +//g;
 
3210   map { $status{$_}{printed} = 1 } split / +/, $formnames;
 
3211   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
 
3213   foreach my $formname (keys %status) {
 
3214     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3215     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3217     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
 
3218                 VALUES (?, ?, ?, ?)|;
 
3219     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
 
3222   $main::lxdebug->leave_sub();
 
3226 # $main::locale->text('SAVED')
 
3227 # $main::locale->text('DELETED')
 
3228 # $main::locale->text('ADDED')
 
3229 # $main::locale->text('PAYMENT POSTED')
 
3230 # $main::locale->text('POSTED')
 
3231 # $main::locale->text('POSTED AS NEW')
 
3232 # $main::locale->text('ELSE')
 
3233 # $main::locale->text('SAVED FOR DUNNING')
 
3234 # $main::locale->text('DUNNING STARTED')
 
3235 # $main::locale->text('PRINTED')
 
3236 # $main::locale->text('MAILED')
 
3237 # $main::locale->text('SCREENED')
 
3238 # $main::locale->text('CANCELED')
 
3239 # $main::locale->text('invoice')
 
3240 # $main::locale->text('proforma')
 
3241 # $main::locale->text('sales_order')
 
3242 # $main::locale->text('packing_list')
 
3243 # $main::locale->text('pick_list')
 
3244 # $main::locale->text('purchase_order')
 
3245 # $main::locale->text('bin_list')
 
3246 # $main::locale->text('sales_quotation')
 
3247 # $main::locale->text('request_quotation')
 
3250   $main::lxdebug->enter_sub();
 
3253   my $dbh  = shift || $self->get_standard_dbh;
 
3255   if(!exists $self->{employee_id}) {
 
3256     &get_employee($self, $dbh);
 
3260    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
 
3261    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
 
3262   my @values = (conv_i($self->{id}), $self->{login},
 
3263                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
 
3264   do_query($self, $dbh, $query, @values);
 
3268   $main::lxdebug->leave_sub();
 
3272   $main::lxdebug->enter_sub();
 
3274   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
 
3275   my ($orderBy, $desc) = split(/\-\-/, $order);
 
3276   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
 
3279   if ($trans_id ne "") {
 
3281       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 | .
 
3282       qq|FROM history_erp h | .
 
3283       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
 
3284       qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
 
3287     my $sth = $dbh->prepare($query) || $self->dberror($query);
 
3289     $sth->execute() || $self->dberror("$query");
 
3291     while(my $hash_ref = $sth->fetchrow_hashref()) {
 
3292       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
 
3293       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
 
3294       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
 
3295       $tempArray[$i++] = $hash_ref;
 
3297     $main::lxdebug->leave_sub() and return \@tempArray
 
3298       if ($i > 0 && $tempArray[0] ne "");
 
3300   $main::lxdebug->leave_sub();
 
3304 sub update_defaults {
 
3305   $main::lxdebug->enter_sub();
 
3307   my ($self, $myconfig, $fld, $provided_dbh) = @_;
 
3310   if ($provided_dbh) {
 
3311     $dbh = $provided_dbh;
 
3313     $dbh = $self->dbconnect_noauto($myconfig);
 
3315   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
 
3316   my $sth   = $dbh->prepare($query);
 
3318   $sth->execute || $self->dberror($query);
 
3319   my ($var) = $sth->fetchrow_array;
 
3322   if ($var =~ m/\d+$/) {
 
3323     my $new_var  = (substr $var, $-[0]) * 1 + 1;
 
3324     my $len_diff = length($var) - $-[0] - length($new_var);
 
3325     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
 
3331   $query = qq|UPDATE defaults SET $fld = ?|;
 
3332   do_query($self, $dbh, $query, $var);
 
3334   if (!$provided_dbh) {
 
3339   $main::lxdebug->leave_sub();
 
3344 sub update_business {
 
3345   $main::lxdebug->enter_sub();
 
3347   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
 
3350   if ($provided_dbh) {
 
3351     $dbh = $provided_dbh;
 
3353     $dbh = $self->dbconnect_noauto($myconfig);
 
3356     qq|SELECT customernumberinit FROM business
 
3357        WHERE id = ? FOR UPDATE|;
 
3358   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
 
3360   return undef unless $var;
 
3362   if ($var =~ m/\d+$/) {
 
3363     my $new_var  = (substr $var, $-[0]) * 1 + 1;
 
3364     my $len_diff = length($var) - $-[0] - length($new_var);
 
3365     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
 
3371   $query = qq|UPDATE business
 
3372               SET customernumberinit = ?
 
3374   do_query($self, $dbh, $query, $var, $business_id);
 
3376   if (!$provided_dbh) {
 
3381   $main::lxdebug->leave_sub();
 
3386 sub get_partsgroup {
 
3387   $main::lxdebug->enter_sub();
 
3389   my ($self, $myconfig, $p) = @_;
 
3390   my $target = $p->{target} || 'all_partsgroup';
 
3392   my $dbh = $self->get_standard_dbh($myconfig);
 
3394   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
 
3396                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
 
3399   if ($p->{searchitems} eq 'part') {
 
3400     $query .= qq|WHERE p.inventory_accno_id > 0|;
 
3402   if ($p->{searchitems} eq 'service') {
 
3403     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
 
3405   if ($p->{searchitems} eq 'assembly') {
 
3406     $query .= qq|WHERE p.assembly = '1'|;
 
3408   if ($p->{searchitems} eq 'labor') {
 
3409     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
 
3412   $query .= qq|ORDER BY partsgroup|;
 
3415     $query = qq|SELECT id, partsgroup FROM partsgroup
 
3416                 ORDER BY partsgroup|;
 
3419   if ($p->{language_code}) {
 
3420     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
 
3421                   t.description AS translation
 
3423                 JOIN parts p ON (p.partsgroup_id = pg.id)
 
3424                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
 
3425                 ORDER BY translation|;
 
3426     @values = ($p->{language_code});
 
3429   $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
 
3431   $main::lxdebug->leave_sub();
 
3434 sub get_pricegroup {
 
3435   $main::lxdebug->enter_sub();
 
3437   my ($self, $myconfig, $p) = @_;
 
3439   my $dbh = $self->get_standard_dbh($myconfig);
 
3441   my $query = qq|SELECT p.id, p.pricegroup
 
3444   $query .= qq| ORDER BY pricegroup|;
 
3447     $query = qq|SELECT id, pricegroup FROM pricegroup
 
3448                 ORDER BY pricegroup|;
 
3451   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
 
3453   $main::lxdebug->leave_sub();
 
3457 # usage $form->all_years($myconfig, [$dbh])
 
3458 # return list of all years where bookings found
 
3461   $main::lxdebug->enter_sub();
 
3463   my ($self, $myconfig, $dbh) = @_;
 
3465   $dbh ||= $self->get_standard_dbh($myconfig);
 
3468   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
 
3469                    (SELECT MAX(transdate) FROM acc_trans)|;
 
3470   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
 
3472   if ($myconfig->{dateformat} =~ /^yy/) {
 
3473     ($startdate) = split /\W/, $startdate;
 
3474     ($enddate) = split /\W/, $enddate;
 
3476     (@_) = split /\W/, $startdate;
 
3478     (@_) = split /\W/, $enddate;
 
3483   $startdate = substr($startdate,0,4);
 
3484   $enddate = substr($enddate,0,4);
 
3486   while ($enddate >= $startdate) {
 
3487     push @all_years, $enddate--;
 
3492   $main::lxdebug->leave_sub();
 
3496   $main::lxdebug->enter_sub();
 
3500   map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
 
3502   $main::lxdebug->leave_sub();
 
3506   $main::lxdebug->enter_sub();
 
3511   map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
 
3513   $main::lxdebug->leave_sub();
 
3522 SL::Form.pm - main data object.
 
3526 This is the main data object of Lx-Office.
 
3527 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
 
3528 Points of interest for a beginner are:
 
3530  - $form->error            - renders a generic error in html. accepts an error message
 
3531  - $form->get_standard_dbh - returns a database connection for the
 
3533 =head1 SPECIAL FUNCTIONS
 
3537 =item _store_value()
 
3539 parses a complex var name, and stores it in the form.
 
3542   $form->_store_value($key, $value);
 
3544 keys must start with a string, and can contain various tokens.
 
3545 supported key structures are:
 
3548   simple key strings work as expected
 
3553   separating two keys by a dot (.) will result in a hash lookup for the inner value
 
3554   this is similar to the behaviour of java and templating mechanisms.
 
3556   filter.description => $form->{filter}->{description}
 
3558 3. array+hashref access
 
3560   adding brackets ([]) before the dot will cause the next hash to be put into an array.
 
3561   using [+] instead of [] will force a new array index. this is useful for recurring
 
3562   data structures like part lists. put a [+] into the first varname, and use [] on the
 
3565   repeating these names in your template:
 
3568     invoice.items[].parts_id
 
3572     $form->{invoice}->{items}->[
 
3586   using brackets at the end of a name will result in a pure array to be created.
 
3587   note that you mustn't use [+], which is reserved for array+hash access and will
 
3588   result in undefined behaviour in array context.
 
3590   filter.status[]  => $form->{status}->[ val1, val2, ... ]
 
3592 =item update_business PARAMS
 
3595  \%config,     - config hashref
 
3596  $business_id, - business id
 
3597  $dbh          - optional database handle
 
3599 handles business (thats customer/vendor types) sequences.
 
3601 special behaviour for empty strings in customerinitnumber field:
 
3602 will in this case not increase the value, and return undef.
 
3604 =item redirect_header $url
 
3606 Generates a HTTP redirection header for the new C<$url>. Constructs an
 
3607 absolute URL including scheme, host name and port. If C<$url> is a
 
3608 relative URL then it is considered relative to Lx-Office base URL.
 
3610 This function C<die>s if headers have already been created with
 
3611 C<$::form-E<gt>header>.
 
3615   print $::form->redirect_header('oe.pl?action=edit&id=1234');
 
3616   print $::form->redirect_header('http://www.lx-office.org/');