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 #======================================================================
 
  59 use List::Util qw(first max min sum);
 
  60 use List::MoreUtils qw(any apply);
 
  67   disconnect_standard_dbh();
 
  70 sub disconnect_standard_dbh {
 
  71   return unless $standard_dbh;
 
  72   $standard_dbh->disconnect();
 
  77   $main::lxdebug->enter_sub(2);
 
  83   my @tokens = split /((?:\[\+?\])?(?:\.|$))/, $key;
 
  88      $curr = \ $self->{ shift @tokens };
 
  92     my $sep = shift @tokens;
 
  93     my $key = shift @tokens;
 
  95     $curr = \ $$curr->[++$#$$curr], next if $sep eq '[]';
 
  96     $curr = \ $$curr->[max 0, $#$$curr]  if $sep eq '[].';
 
  97     $curr = \ $$curr->[++$#$$curr]       if $sep eq '[+].';
 
  98     $curr = \ $$curr->{$key}
 
 103   $main::lxdebug->leave_sub(2);
 
 109   $main::lxdebug->enter_sub(2);
 
 114   my @pairs = split(/&/, $input);
 
 117     my ($key, $value) = split(/=/, $_, 2);
 
 118     $self->_store_value($self->unescape($key), $self->unescape($value)) if ($key);
 
 121   $main::lxdebug->leave_sub(2);
 
 124 sub _request_to_hash {
 
 125   $main::lxdebug->enter_sub(2);
 
 130   if (!$ENV{'CONTENT_TYPE'}
 
 131       || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
 
 133     $self->_input_to_hash($input);
 
 135     $main::lxdebug->leave_sub(2);
 
 139   my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr, $previous);
 
 141   my $boundary = '--' . $1;
 
 143   foreach my $line (split m/\n/, $input) {
 
 144     last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
 
 146     if (($line eq $boundary) || ($line eq "$boundary\r")) {
 
 147       ${ $previous } =~ s|\r?\n$|| if $previous;
 
 153       $content_type   = "text/plain";
 
 160     next unless $boundary_found;
 
 162     if (!$headers_done) {
 
 163       $line =~ s/[\r\n]*$//;
 
 170       if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
 
 171         if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
 
 173           substr $line, $-[0], $+[0] - $-[0], "";
 
 176         if ($line =~ m|name\s*=\s*"(.*?)"|i) {
 
 178           substr $line, $-[0], $+[0] - $-[0], "";
 
 181         $previous         = $self->_store_value($name, '') if ($name);
 
 182         $self->{FILENAME} = $filename if ($filename);
 
 187       if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
 
 194     next unless $previous;
 
 196     ${ $previous } .= "${line}\n";
 
 199   ${ $previous } =~ s|\r?\n$|| if $previous;
 
 201   $main::lxdebug->leave_sub(2);
 
 204 sub _recode_recursively {
 
 205   $main::lxdebug->enter_sub();
 
 206   my ($iconv, $param) = @_;
 
 208   if (any { ref $param eq $_ } qw(Form HASH)) {
 
 209     foreach my $key (keys %{ $param }) {
 
 210       if (!ref $param->{$key}) {
 
 211         # Workaround for a bug: converting $param->{$key} directly
 
 212         # leads to 'undef'. I don't know why. Converting a copy works,
 
 214         $param->{$key} = $iconv->convert("" . $param->{$key});
 
 216         _recode_recursively($iconv, $param->{$key});
 
 220   } elsif (ref $param eq 'ARRAY') {
 
 221     foreach my $idx (0 .. scalar(@{ $param }) - 1) {
 
 222       if (!ref $param->[$idx]) {
 
 223         # Workaround for a bug: converting $param->[$idx] directly
 
 224         # leads to 'undef'. I don't know why. Converting a copy works,
 
 226         $param->[$idx] = $iconv->convert("" . $param->[$idx]);
 
 228         _recode_recursively($iconv, $param->[$idx]);
 
 232   $main::lxdebug->leave_sub();
 
 236   $main::lxdebug->enter_sub();
 
 242   if ($LXDebug::watch_form) {
 
 243     require SL::Watchdog;
 
 244     tie %{ $self }, 'SL::Watchdog';
 
 249   $self->_input_to_hash($ENV{QUERY_STRING}) if $ENV{QUERY_STRING};
 
 250   $self->_input_to_hash($ARGV[0])           if @ARGV && $ARGV[0];
 
 252   if ($ENV{CONTENT_LENGTH}) {
 
 254     read STDIN, $content, $ENV{CONTENT_LENGTH};
 
 255     $self->_request_to_hash($content);
 
 258   my $db_charset   = $main::dbcharset;
 
 259   $db_charset    ||= Common::DEFAULT_CHARSET;
 
 261   my $encoding     = $self->{INPUT_ENCODING} || $db_charset;
 
 262   delete $self->{INPUT_ENCODING};
 
 264   _recode_recursively(SL::Iconv->new($encoding, $db_charset), $self);
 
 266   $self->{action}  =  lc $self->{action};
 
 267   $self->{action}  =~ s/( |-|,|\#)/_/g;
 
 269   #$self->{version} =  "2.6.1";                 # Old hardcoded but secure style
 
 270   open VERSION_FILE, "VERSION";                 # New but flexible code reads version from VERSION-file
 
 271   $self->{version} =  <VERSION_FILE>;
 
 273   $self->{version}  =~ s/[^0-9A-Za-z\.\_\-]//g; # only allow numbers, letters, points, underscores and dashes. Prevents injecting of malicious code.
 
 275   $main::lxdebug->leave_sub();
 
 280 sub _flatten_variables_rec {
 
 281   $main::lxdebug->enter_sub(2);
 
 290   if ('' eq ref $curr->{$key}) {
 
 291     @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
 
 293   } elsif ('HASH' eq ref $curr->{$key}) {
 
 294     foreach my $hash_key (sort keys %{ $curr->{$key} }) {
 
 295       push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
 
 299     foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
 
 300       my $first_array_entry = 1;
 
 302       foreach my $hash_key (sort keys %{ $curr->{$key}->[$idx] }) {
 
 303         push @result, $self->_flatten_variables_rec($curr->{$key}->[$idx], $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
 
 304         $first_array_entry = 0;
 
 309   $main::lxdebug->leave_sub(2);
 
 314 sub flatten_variables {
 
 315   $main::lxdebug->enter_sub(2);
 
 323     push @variables, $self->_flatten_variables_rec($self, '', $_);
 
 326   $main::lxdebug->leave_sub(2);
 
 331 sub flatten_standard_variables {
 
 332   $main::lxdebug->enter_sub(2);
 
 335   my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar version), @_);
 
 339   foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
 
 340     push @variables, $self->_flatten_variables_rec($self, '', $_);
 
 343   $main::lxdebug->leave_sub(2);
 
 349   $main::lxdebug->enter_sub();
 
 355   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
 
 357   $main::lxdebug->leave_sub();
 
 361   $main::lxdebug->enter_sub(2);
 
 364   my $password      = $self->{password};
 
 366   $self->{password} = 'X' x 8;
 
 368   local $Data::Dumper::Sortkeys = 1;
 
 369   my $output                    = Dumper($self);
 
 371   $self->{password} = $password;
 
 373   $main::lxdebug->leave_sub(2);
 
 379   $main::lxdebug->enter_sub(2);
 
 381   my ($self, $str) = @_;
 
 383   $str =  Encode::encode('utf-8-strict', $str) if $::locale->is_utf8;
 
 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}) {
 
 479     <p class="message_ok"><b>$msg</b></p>
 
 481     <script type="text/javascript">
 
 483     // If JavaScript is enabled, the whole thing will be reloaded.
 
 484     // The reason is: When one changes his menu setup (HTML / XUL / CSS ...)
 
 485     // it now loads the correct code into the browser instead of do nothing.
 
 486     setTimeout("top.frames.location.href='login.pl'",500);
 
 495     if ($self->{info_function}) {
 
 496       &{ $self->{info_function} }($msg);
 
 502   $main::lxdebug->leave_sub();
 
 505 # calculates the number of rows in a textarea based on the content and column number
 
 506 # can be capped with maxrows
 
 508   $main::lxdebug->enter_sub();
 
 509   my ($self, $str, $cols, $maxrows, $minrows) = @_;
 
 513   my $rows   = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
 
 516   $main::lxdebug->leave_sub();
 
 518   return max(min($rows, $maxrows), $minrows);
 
 522   $main::lxdebug->enter_sub();
 
 524   my ($self, $msg) = @_;
 
 526   $self->error("$msg\n" . $DBI::errstr);
 
 528   $main::lxdebug->leave_sub();
 
 532   $main::lxdebug->enter_sub();
 
 534   my ($self, $name, $msg) = @_;
 
 537   foreach my $part (split m/\./, $name) {
 
 538     if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
 
 541     $curr = $curr->{$part};
 
 544   $main::lxdebug->leave_sub();
 
 547 sub _get_request_uri {
 
 550   return URI->new($ENV{HTTP_REFERER})->canonical() if $ENV{HTTP_X_FORWARDED_FOR};
 
 552   my $scheme =  $ENV{HTTPS} && (lc $ENV{HTTPS} eq 'on') ? 'https' : 'http';
 
 553   my $port   =  $ENV{SERVER_PORT} || '';
 
 554   $port      =  undef if (($scheme eq 'http' ) && ($port == 80))
 
 555                       || (($scheme eq 'https') && ($port == 443));
 
 557   my $uri    =  URI->new("${scheme}://");
 
 558   $uri->scheme($scheme);
 
 560   $uri->host($ENV{HTTP_HOST} || $ENV{SERVER_ADDR});
 
 561   $uri->path_query($ENV{REQUEST_URI});
 
 567 sub _add_to_request_uri {
 
 570   my $relative_new_path = shift;
 
 571   my $request_uri       = shift || $self->_get_request_uri;
 
 572   my $relative_new_uri  = URI->new($relative_new_path);
 
 573   my @request_segments  = $request_uri->path_segments;
 
 575   my $new_uri           = $request_uri->clone;
 
 576   $new_uri->path_segments(@request_segments[0..scalar(@request_segments) - 2], $relative_new_uri->path_segments);
 
 581 sub create_http_response {
 
 582   $main::lxdebug->enter_sub();
 
 587   my $cgi      = $main::cgi;
 
 588   $cgi       ||= CGI->new('');
 
 591   if (defined $main::auth) {
 
 592     my $uri      = $self->_get_request_uri;
 
 593     my @segments = $uri->path_segments;
 
 595     $uri->path_segments(@segments);
 
 597     my $session_cookie_value   = $main::auth->get_session_id();
 
 598     $session_cookie_value    ||= 'NO_SESSION';
 
 600     $session_cookie = $cgi->cookie('-name'   => $main::auth->get_session_cookie_name(),
 
 601                                    '-value'  => $session_cookie_value,
 
 602                                    '-path'   => $uri->path,
 
 603                                    '-secure' => $ENV{HTTPS});
 
 606   my %cgi_params = ('-type' => $params{content_type});
 
 607   $cgi_params{'-charset'} = $params{charset} if ($params{charset});
 
 609   my $output = $cgi->header('-cookie' => $session_cookie,
 
 612   $main::lxdebug->leave_sub();
 
 619   $main::lxdebug->enter_sub();
 
 621   # extra code ist currently only used by menuv3 and menuv4 to set their css.
 
 622   # it is strongly deprecated, and will be changed in a future version.
 
 623   my ($self, $extra_code) = @_;
 
 625   if ($self->{header}) {
 
 626     $main::lxdebug->leave_sub();
 
 630   my ($stylesheet, $favicon, $pagelayout);
 
 632   if ($ENV{HTTP_USER_AGENT}) {
 
 635     if ($ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+\d/) {
 
 636       # Only set the DOCTYPE for Internet Explorer. Other browsers have problems displaying the menu otherwise.
 
 637       $doctype = qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n|;
 
 640     my $stylesheets = "$self->{stylesheet} $self->{stylesheets}";
 
 642     $stylesheets =~ s|^\s*||;
 
 643     $stylesheets =~ s|\s*$||;
 
 644     foreach my $file (split m/\s+/, $stylesheets) {
 
 646       next if (! -f "css/$file");
 
 648       $stylesheet .= qq|<link rel="stylesheet" href="css/$file" TYPE="text/css" TITLE="Lx-Office stylesheet">\n|;
 
 651     $self->{favicon}    = "favicon.ico" unless $self->{favicon};
 
 653     if ($self->{favicon} && (-f "$self->{favicon}")) {
 
 655         qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
 
 659     my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
 661     if ($self->{landscape}) {
 
 662       $pagelayout = qq|<style type="text/css">
 
 663                         \@page { size:landscape; }
 
 668     <script type="text/javascript">
 
 671         document.$self->{fokus}.focus();
 
 675     | if $self->{"fokus"};
 
 677   # if there is a title, we put some JavaScript in to the page, wich writes a
 
 678   # meaningful title-tag for our frameset.
 
 680     if ($self->{"title"}){
 
 682                 <script type="text/javascript">
 
 684                   // Write a meaningful title-tag for our frameset.
 
 685                   top.document.title="| . $self->{"title"} . qq| - | . $self->{"login"} . qq| - | . $::myconfig{dbname} . qq| - V| . $self->{"version"} . qq|";
 
 693     if ($self->{jsscript} == 1) {
 
 696         <script type="text/javascript" src="js/jquery.js"></script>
 
 697         <script type="text/javascript" src="js/common.js"></script>
 
 698         <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
 
 699         <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
 
 700         <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
 
 701         <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
 
 708       ? "$self->{title} - $self->{titlebar}"
 
 711     for my $item (@ { $self->{AJAX} || [] }) {
 
 712       $ajax .= $item->show_javascript();
 
 715     print $self->create_http_response('content_type' => 'text/html',
 
 716                                       'charset'      => $db_charset,);
 
 717     print qq|${doctype}<html>
 
 719   <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
 
 720   <title>$self->{titlebar}</title>
 
 729   <link rel="stylesheet" href="css/jquery.autocomplete.css" type="text/css" />
 
 731   <meta name="robots" content="noindex,nofollow" />
 
 733   <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
 
 734   <script type="text/javascript" src="js/tabcontent.js">
 
 736   /***********************************************
 
 737    * Tab Content script v2.2- Â© Dynamic Drive DHTML code library (www.dynamicdrive.com)
 
 738    * This notice MUST stay intact for legal use
 
 739    * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
 
 740    ***********************************************/
 
 751   $main::lxdebug->leave_sub();
 
 754 sub ajax_response_header {
 
 755   $main::lxdebug->enter_sub();
 
 759   my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
 760   my $cgi        = $main::cgi || CGI->new('');
 
 761   my $output     = $cgi->header('-charset' => $db_charset);
 
 763   $main::lxdebug->leave_sub();
 
 768 sub redirect_header {
 
 772   my $base_uri = $self->_get_request_uri;
 
 773   my $new_uri  = URI->new_abs($new_url, $base_uri);
 
 775   die "Headers already sent" if $::self->{header};
 
 778   my $cgi = $main::cgi || CGI->new('');
 
 779   return $cgi->redirect($new_uri);
 
 782 sub set_standard_title {
 
 783   $::lxdebug->enter_sub;
 
 786   $self->{titlebar}  = "Lx-Office " . $::locale->text('Version') . " $self->{version}";
 
 787   $self->{titlebar} .= "- $::myconfig{name}"   if $::myconfig{name};
 
 788   $self->{titlebar} .= "- $::myconfig{dbname}" if $::myconfig{name};
 
 790   $::lxdebug->leave_sub;
 
 793 sub _prepare_html_template {
 
 794   $main::lxdebug->enter_sub();
 
 796   my ($self, $file, $additional_params) = @_;
 
 799   if (!%::myconfig || !$::myconfig{"countrycode"}) {
 
 800     $language = $main::language;
 
 802     $language = $main::myconfig{"countrycode"};
 
 804   $language = "de" unless ($language);
 
 806   if (-f "templates/webpages/${file}.html") {
 
 807     if ((-f ".developer") && ((stat("templates/webpages/${file}.html"))[9] > (stat("locale/${language}/all"))[9])) {
 
 808       my $info = "Developer information: templates/webpages/${file}.html is newer than the translation file locale/${language}/all.\n" .
 
 809         "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 810       print(qq|<pre>$info</pre>|);
 
 814     $file = "templates/webpages/${file}.html";
 
 817     my $info = "Web page template '${file}' not found.\n" .
 
 818       "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 819     print(qq|<pre>$info</pre>|);
 
 823   if ($self->{"DEBUG"}) {
 
 824     $additional_params->{"DEBUG"} = $self->{"DEBUG"};
 
 827   if ($additional_params->{"DEBUG"}) {
 
 828     $additional_params->{"DEBUG"} =
 
 829       "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
 
 832   if (%main::myconfig) {
 
 833     $::myconfig{jsc_dateformat} = apply {
 
 837     } $::myconfig{"dateformat"};
 
 838     $additional_params->{"myconfig"} ||= \%::myconfig;
 
 839     map { $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys %::myconfig;
 
 842   $additional_params->{"conf_dbcharset"}              = $main::dbcharset;
 
 843   $additional_params->{"conf_webdav"}                 = $main::webdav;
 
 844   $additional_params->{"conf_lizenzen"}               = $main::lizenzen;
 
 845   $additional_params->{"conf_latex_templates"}        = $main::latex;
 
 846   $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
 
 847   $additional_params->{"conf_vertreter"}              = $main::vertreter;
 
 848   $additional_params->{"conf_show_best_before"}       = $main::show_best_before;
 
 850   if (%main::debug_options) {
 
 851     map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
 
 854   if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
 
 855     while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
 
 856       $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
 
 860   $main::lxdebug->leave_sub();
 
 865 sub parse_html_template {
 
 866   $main::lxdebug->enter_sub();
 
 868   my ($self, $file, $additional_params) = @_;
 
 870   $additional_params ||= { };
 
 872   my $real_file = $self->_prepare_html_template($file, $additional_params);
 
 873   my $template  = $self->template || $self->init_template;
 
 875   map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
 
 878   $template->process($real_file, $additional_params, \$output) || die $template->error;
 
 880   $main::lxdebug->leave_sub();
 
 888   return if $self->template;
 
 890   return $self->template(Template->new({
 
 895      'PLUGIN_BASE'  => 'SL::Template::Plugin',
 
 896      'INCLUDE_PATH' => '.:templates/webpages',
 
 897      'COMPILE_EXT'  => '.tcc',
 
 898      'COMPILE_DIR'  => $::userspath . '/templates-cache',
 
 904   $self->{template_object} = shift if @_;
 
 905   return $self->{template_object};
 
 908 sub show_generic_error {
 
 909   $main::lxdebug->enter_sub();
 
 911   my ($self, $error, %params) = @_;
 
 914     'title_error' => $params{title},
 
 915     'label_error' => $error,
 
 918   if ($params{action}) {
 
 921     map { delete($self->{$_}); } qw(action);
 
 922     map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
 
 924     $add_params->{SHOW_BUTTON}  = 1;
 
 925     $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
 
 926     $add_params->{VARIABLES}    = \@vars;
 
 928   } elsif ($params{back_button}) {
 
 929     $add_params->{SHOW_BACK_BUTTON} = 1;
 
 932   $self->{title} = $params{title} if $params{title};
 
 935   print $self->parse_html_template("generic/error", $add_params);
 
 937   print STDERR "Error: $error\n";
 
 939   $main::lxdebug->leave_sub();
 
 944 sub show_generic_information {
 
 945   $main::lxdebug->enter_sub();
 
 947   my ($self, $text, $title) = @_;
 
 950     'title_information' => $title,
 
 951     'label_information' => $text,
 
 954   $self->{title} = $title if ($title);
 
 957   print $self->parse_html_template("generic/information", $add_params);
 
 959   $main::lxdebug->leave_sub();
 
 964 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
 
 965 # changed it to accept an arbitrary number of triggers - sschoeling
 
 967   $main::lxdebug->enter_sub();
 
 970   my $myconfig = shift;
 
 973   # set dateform for jsscript
 
 976     "dd.mm.yy" => "%d.%m.%Y",
 
 977     "dd-mm-yy" => "%d-%m-%Y",
 
 978     "dd/mm/yy" => "%d/%m/%Y",
 
 979     "mm/dd/yy" => "%m/%d/%Y",
 
 980     "mm-dd-yy" => "%m-%d-%Y",
 
 981     "yyyy-mm-dd" => "%Y-%m-%d",
 
 984   my $ifFormat = defined($dateformats{$myconfig->{"dateformat"}}) ?
 
 985     $dateformats{$myconfig->{"dateformat"}} : "%d.%m.%Y";
 
 992       inputField : "| . (shift) . qq|",
 
 993       ifFormat :"$ifFormat",
 
 994       align : "| .  (shift) . qq|",
 
 995       button : "| . (shift) . qq|"
 
1001        <script type="text/javascript">
 
1002        <!--| . join("", @triggers) . qq|//-->
 
1006   $main::lxdebug->leave_sub();
 
1009 }    #end sub write_trigger
 
1012   $main::lxdebug->enter_sub();
 
1014   my ($self, $msg) = @_;
 
1016   if (!$self->{callback}) {
 
1022 #  my ($script, $argv) = split(/\?/, $self->{callback}, 2);
 
1023 #  $script =~ s|.*/||;
 
1024 #  $script =~ s|[^a-zA-Z0-9_\.]||g;
 
1025 #  exec("perl", "$script", $argv);
 
1027   print $::form->redirect_header($self->{callback});
 
1029   $main::lxdebug->leave_sub();
 
1032 # sort of columns removed - empty sub
 
1034   $main::lxdebug->enter_sub();
 
1036   my ($self, @columns) = @_;
 
1038   $main::lxdebug->leave_sub();
 
1044   $main::lxdebug->enter_sub(2);
 
1046   my ($self, $myconfig, $amount, $places, $dash) = @_;
 
1048   if ($amount eq "") {
 
1052   # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
 
1054   my $neg = ($amount =~ s/^-//);
 
1055   my $exp = ($amount =~ m/[e]/) ? 1 : 0;
 
1057   if (defined($places) && ($places ne '')) {
 
1063         my ($actual_places) = ($amount =~ /\.(\d+)/);
 
1064         $actual_places = length($actual_places);
 
1065         $places = $actual_places > $places ? $actual_places : $places;
 
1068     $amount = $self->round_amount($amount, $places);
 
1071   my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
 
1072   my @p = split(/\./, $amount); # split amount at decimal point
 
1074   $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
 
1077   $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
 
1080     ($dash =~ /-/)    ? ($neg ? "($amount)"                            : "$amount" )                              :
 
1081     ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
 
1082                         ($neg ? "-$amount"                             : "$amount" )                              ;
 
1086   $main::lxdebug->leave_sub(2);
 
1090 sub format_amount_units {
 
1091   $main::lxdebug->enter_sub();
 
1096   my $myconfig         = \%main::myconfig;
 
1097   my $amount           = $params{amount} * 1;
 
1098   my $places           = $params{places};
 
1099   my $part_unit_name   = $params{part_unit};
 
1100   my $amount_unit_name = $params{amount_unit};
 
1101   my $conv_units       = $params{conv_units};
 
1102   my $max_places       = $params{max_places};
 
1104   if (!$part_unit_name) {
 
1105     $main::lxdebug->leave_sub();
 
1109   AM->retrieve_all_units();
 
1110   my $all_units        = $main::all_units;
 
1112   if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
 
1113     $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
 
1116   if (!scalar @{ $conv_units }) {
 
1117     my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
 
1118     $main::lxdebug->leave_sub();
 
1122   my $part_unit  = $all_units->{$part_unit_name};
 
1123   my $conv_unit  = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
 
1125   $amount       *= $conv_unit->{factor};
 
1130   foreach my $unit (@$conv_units) {
 
1131     my $last = $unit->{name} eq $part_unit->{name};
 
1133       $num     = int($amount / $unit->{factor});
 
1134       $amount -= $num * $unit->{factor};
 
1137     if ($last ? $amount : $num) {
 
1138       push @values, { "unit"   => $unit->{name},
 
1139                       "amount" => $last ? $amount / $unit->{factor} : $num,
 
1140                       "places" => $last ? $places : 0 };
 
1147     push @values, { "unit"   => $part_unit_name,
 
1152   my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
 
1154   $main::lxdebug->leave_sub();
 
1160   $main::lxdebug->enter_sub(2);
 
1165   $input =~ s/(^|[^\#]) \#  (\d+)  /$1$_[$2 - 1]/gx;
 
1166   $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
 
1167   $input =~ s/\#\#/\#/g;
 
1169   $main::lxdebug->leave_sub(2);
 
1177   $main::lxdebug->enter_sub(2);
 
1179   my ($self, $myconfig, $amount) = @_;
 
1181   if (   ($myconfig->{numberformat} eq '1.000,00')
 
1182       || ($myconfig->{numberformat} eq '1000,00')) {
 
1187   if ($myconfig->{numberformat} eq "1'000.00") {
 
1193   $main::lxdebug->leave_sub(2);
 
1195   return ($amount * 1);
 
1199   $main::lxdebug->enter_sub(2);
 
1201   my ($self, $amount, $places) = @_;
 
1204   # Rounding like "Kaufmannsrunden" (see http://de.wikipedia.org/wiki/Rundung )
 
1206   # Round amounts to eight places before rounding to the requested
 
1207   # number of places. This gets rid of errors due to internal floating
 
1208   # point representation.
 
1209   $amount       = $self->round_amount($amount, 8) if $places < 8;
 
1210   $amount       = $amount * (10**($places));
 
1211   $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
 
1213   $main::lxdebug->leave_sub(2);
 
1215   return $round_amount;
 
1219 sub parse_template {
 
1220   $main::lxdebug->enter_sub();
 
1222   my ($self, $myconfig, $userspath) = @_;
 
1227   $self->{"cwd"} = getcwd();
 
1228   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
 
1233   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
 
1234     $template_type  = 'OpenDocument';
 
1235     $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
 
1237   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
 
1238     $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
 
1239     $template_type    = 'LaTeX';
 
1240     $ext_for_format   = 'pdf';
 
1242   } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
 
1243     $template_type  = 'HTML';
 
1244     $ext_for_format = 'html';
 
1246   } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
 
1247     $template_type  = 'XML';
 
1248     $ext_for_format = 'xml';
 
1250   } elsif ( $self->{"format"} =~ /elster(?:winston|taxbird)/i ) {
 
1251     $template_type = 'xml';
 
1253   } elsif ( $self->{"format"} =~ /excel/i ) {
 
1254     $template_type  = 'Excel';
 
1255     $ext_for_format = 'xls';
 
1257   } elsif ( defined $self->{'format'}) {
 
1258     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
 
1260   } elsif ( $self->{'format'} eq '' ) {
 
1261     $self->error("No Outputformat given: $self->{'format'}");
 
1263   } else { #Catch the rest
 
1264     $self->error("Outputformat not defined: $self->{'format'}");
 
1267   my $template = SL::Template::create(type      => $template_type,
 
1268                                       file_name => $self->{IN},
 
1270                                       myconfig  => $myconfig,
 
1271                                       userspath => $userspath);
 
1273   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
 
1274   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
 
1276   if (!$self->{employee_id}) {
 
1277     map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
 
1280   map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
 
1282   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
 
1284   # OUT is used for the media, screen, printer, email
 
1285   # for postscript we store a copy in a temporary file
 
1287   my $prepend_userspath;
 
1289   if (!$self->{tmpfile}) {
 
1290     $self->{tmpfile}   = "${fileid}.$self->{IN}";
 
1291     $prepend_userspath = 1;
 
1294   $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
 
1296   $self->{tmpfile} =~ s|.*/||;
 
1297   $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
 
1298   $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
 
1300   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
1301     $out = $self->{OUT};
 
1302     $self->{OUT} = ">$self->{tmpfile}";
 
1308     open OUT, "$self->{OUT}" or $self->error("$self->{OUT} : $!");
 
1309     $result = $template->parse(*OUT);
 
1314     $result = $template->parse(*STDOUT);
 
1319     $self->error("$self->{IN} : " . $template->get_error());
 
1322   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
1324     if ($self->{media} eq 'email') {
 
1326       my $mail = new Mailer;
 
1328       map { $mail->{$_} = $self->{$_} }
 
1329         qw(cc bcc subject message version format);
 
1330       $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
1331       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
 
1332       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
 
1333       $mail->{fileid} = "$fileid.";
 
1334       $myconfig->{signature} =~ s/\r//g;
 
1336       # if we send html or plain text inline
 
1337       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
 
1338         $mail->{contenttype} = "text/html";
 
1340         $mail->{message}       =~ s/\r//g;
 
1341         $mail->{message}       =~ s/\n/<br>\n/g;
 
1342         $myconfig->{signature} =~ s/\n/<br>\n/g;
 
1343         $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
 
1345         open(IN, $self->{tmpfile})
 
1346           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1348           $mail->{message} .= $_;
 
1355         if (!$self->{"do_not_attach"}) {
 
1356           my $attachment_name  =  $self->{attachment_filename} || $self->{tmpfile};
 
1357           $attachment_name     =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
 
1358           $mail->{attachments} =  [{ "filename" => $self->{tmpfile},
 
1359                                      "name"     => $attachment_name }];
 
1362         $mail->{message}  =~ s/\r//g;
 
1363         $mail->{message} .=  "\n-- \n$myconfig->{signature}";
 
1367       my $err = $mail->send();
 
1368       $self->error($self->cleanup . "$err") if ($err);
 
1372       $self->{OUT} = $out;
 
1374       my $numbytes = (-s $self->{tmpfile});
 
1375       open(IN, $self->{tmpfile})
 
1376         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1378       $self->{copies} = 1 unless $self->{media} eq 'printer';
 
1380       chdir("$self->{cwd}");
 
1381       #print(STDERR "Kopien $self->{copies}\n");
 
1382       #print(STDERR "OUT $self->{OUT}\n");
 
1383       for my $i (1 .. $self->{copies}) {
 
1385           open OUT, $self->{OUT} or $self->error($self->cleanup . "$self->{OUT} : $!");
 
1386           print OUT while <IN>;
 
1391           $self->{attachment_filename} = ($self->{attachment_filename})
 
1392                                        ? $self->{attachment_filename}
 
1393                                        : $self->generate_attachment_filename();
 
1395           # launch application
 
1396           print qq|Content-Type: | . $template->get_mime_type() . qq|
 
1397 Content-Disposition: attachment; filename="$self->{attachment_filename}"
 
1398 Content-Length: $numbytes
 
1402           $::locale->with_raw_io(\*STDOUT, sub { print while <IN> });
 
1413   chdir("$self->{cwd}");
 
1414   $main::lxdebug->leave_sub();
 
1417 sub get_formname_translation {
 
1418   $main::lxdebug->enter_sub();
 
1419   my ($self, $formname) = @_;
 
1421   $formname ||= $self->{formname};
 
1423   my %formname_translations = (
 
1424     bin_list                => $main::locale->text('Bin List'),
 
1425     credit_note             => $main::locale->text('Credit Note'),
 
1426     invoice                 => $main::locale->text('Invoice'),
 
1427     packing_list            => $main::locale->text('Packing List'),
 
1428     pick_list               => $main::locale->text('Pick List'),
 
1429     proforma                => $main::locale->text('Proforma Invoice'),
 
1430     purchase_order          => $main::locale->text('Purchase Order'),
 
1431     request_quotation       => $main::locale->text('RFQ'),
 
1432     sales_order             => $main::locale->text('Confirmation'),
 
1433     sales_quotation         => $main::locale->text('Quotation'),
 
1434     storno_invoice          => $main::locale->text('Storno Invoice'),
 
1435     storno_packing_list     => $main::locale->text('Storno Packing List'),
 
1436     sales_delivery_order    => $main::locale->text('Delivery Order'),
 
1437     purchase_delivery_order => $main::locale->text('Delivery Order'),
 
1438     dunning                 => $main::locale->text('Dunning'),
 
1441   $main::lxdebug->leave_sub();
 
1442   return $formname_translations{$formname}
 
1445 sub get_number_prefix_for_type {
 
1446   $main::lxdebug->enter_sub();
 
1450       (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
 
1451     : ($self->{type} =~ /_quotation$/)                        ? 'quo'
 
1452     : ($self->{type} =~ /_delivery_order$/)                   ? 'do'
 
1455   $main::lxdebug->leave_sub();
 
1459 sub get_extension_for_format {
 
1460   $main::lxdebug->enter_sub();
 
1463   my $extension = $self->{format} =~ /pdf/i          ? ".pdf"
 
1464                 : $self->{format} =~ /postscript/i   ? ".ps"
 
1465                 : $self->{format} =~ /opendocument/i ? ".odt"
 
1466                 : $self->{format} =~ /excel/i        ? ".xls"
 
1467                 : $self->{format} =~ /html/i         ? ".html"
 
1470   $main::lxdebug->leave_sub();
 
1474 sub generate_attachment_filename {
 
1475   $main::lxdebug->enter_sub();
 
1478   my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
 
1479   my $prefix              = $self->get_number_prefix_for_type();
 
1481   if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
 
1482     $attachment_filename .= ' (' . $main::locale->text('Preview') . ')' . $self->get_extension_for_format();
 
1484   } elsif ($attachment_filename && $self->{"${prefix}number"}) {
 
1485     $attachment_filename .=  "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
 
1488     $attachment_filename = "";
 
1491   $attachment_filename =  $main::locale->quote_special_chars('filenames', $attachment_filename);
 
1492   $attachment_filename =~ s|[\s/\\]+|_|g;
 
1494   $main::lxdebug->leave_sub();
 
1495   return $attachment_filename;
 
1498 sub generate_email_subject {
 
1499   $main::lxdebug->enter_sub();
 
1502   my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
 
1503   my $prefix  = $self->get_number_prefix_for_type();
 
1505   if ($subject && $self->{"${prefix}number"}) {
 
1506     $subject .= " " . $self->{"${prefix}number"}
 
1509   $main::lxdebug->leave_sub();
 
1514   $main::lxdebug->enter_sub();
 
1518   chdir("$self->{tmpdir}");
 
1521   if (-f "$self->{tmpfile}.err") {
 
1522     open(FH, "$self->{tmpfile}.err");
 
1527   if ($self->{tmpfile} && ! $::keep_temp_files) {
 
1528     $self->{tmpfile} =~ s|.*/||g;
 
1530     $self->{tmpfile} =~ s/\.\w+$//g;
 
1531     my $tmpfile = $self->{tmpfile};
 
1532     unlink(<$tmpfile.*>);
 
1535   chdir("$self->{cwd}");
 
1537   $main::lxdebug->leave_sub();
 
1543   $main::lxdebug->enter_sub();
 
1545   my ($self, $date, $myconfig) = @_;
 
1548   if ($date && $date =~ /\D/) {
 
1550     if ($myconfig->{dateformat} =~ /^yy/) {
 
1551       ($yy, $mm, $dd) = split /\D/, $date;
 
1553     if ($myconfig->{dateformat} =~ /^mm/) {
 
1554       ($mm, $dd, $yy) = split /\D/, $date;
 
1556     if ($myconfig->{dateformat} =~ /^dd/) {
 
1557       ($dd, $mm, $yy) = split /\D/, $date;
 
1562     $yy = ($yy < 70) ? $yy + 2000 : $yy;
 
1563     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
 
1565     $dd = "0$dd" if ($dd < 10);
 
1566     $mm = "0$mm" if ($mm < 10);
 
1568     $date = "$yy$mm$dd";
 
1571   $main::lxdebug->leave_sub();
 
1576 # Database routines used throughout
 
1578 sub _dbconnect_options {
 
1580   my $options = { pg_enable_utf8 => $::locale->is_utf8,
 
1587   $main::lxdebug->enter_sub(2);
 
1589   my ($self, $myconfig) = @_;
 
1591   # connect to database
 
1592   my $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, $self->_dbconnect_options)
 
1596   if ($myconfig->{dboptions}) {
 
1597     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1600   $main::lxdebug->leave_sub(2);
 
1605 sub dbconnect_noauto {
 
1606   $main::lxdebug->enter_sub();
 
1608   my ($self, $myconfig) = @_;
 
1610   # connect to database
 
1611   my $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, $self->_dbconnect_options(AutoCommit => 0))
 
1615   if ($myconfig->{dboptions}) {
 
1616     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1619   $main::lxdebug->leave_sub();
 
1624 sub get_standard_dbh {
 
1625   $main::lxdebug->enter_sub(2);
 
1628   my $myconfig = shift || \%::myconfig;
 
1630   if ($standard_dbh && !$standard_dbh->{Active}) {
 
1631     $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
 
1632     undef $standard_dbh;
 
1635   $standard_dbh ||= $self->dbconnect_noauto($myconfig);
 
1637   $main::lxdebug->leave_sub(2);
 
1639   return $standard_dbh;
 
1643   $main::lxdebug->enter_sub();
 
1645   my ($self, $date, $myconfig) = @_;
 
1646   my $dbh = $self->dbconnect($myconfig);
 
1648   my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
 
1649   my $sth = prepare_execute_query($self, $dbh, $query, $date);
 
1650   my ($closed) = $sth->fetchrow_array;
 
1652   $main::lxdebug->leave_sub();
 
1657 sub update_balance {
 
1658   $main::lxdebug->enter_sub();
 
1660   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
 
1662   # if we have a value, go do it
 
1665     # retrieve balance from table
 
1666     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
 
1667     my $sth = prepare_execute_query($self, $dbh, $query, @values);
 
1668     my ($balance) = $sth->fetchrow_array;
 
1674     $query = "UPDATE $table SET $field = $balance WHERE $where";
 
1675     do_query($self, $dbh, $query, @values);
 
1677   $main::lxdebug->leave_sub();
 
1680 sub update_exchangerate {
 
1681   $main::lxdebug->enter_sub();
 
1683   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
 
1685   # some sanity check for currency
 
1687     $main::lxdebug->leave_sub();
 
1690   $query = qq|SELECT curr FROM defaults|;
 
1692   my ($currency) = selectrow_query($self, $dbh, $query);
 
1693   my ($defaultcurrency) = split m/:/, $currency;
 
1696   if ($curr eq $defaultcurrency) {
 
1697     $main::lxdebug->leave_sub();
 
1701   $query = qq|SELECT e.curr FROM exchangerate e
 
1702                  WHERE e.curr = ? AND e.transdate = ?
 
1704   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
 
1713   $buy = conv_i($buy, "NULL");
 
1714   $sell = conv_i($sell, "NULL");
 
1717   if ($buy != 0 && $sell != 0) {
 
1718     $set = "buy = $buy, sell = $sell";
 
1719   } elsif ($buy != 0) {
 
1720     $set = "buy = $buy";
 
1721   } elsif ($sell != 0) {
 
1722     $set = "sell = $sell";
 
1725   if ($sth->fetchrow_array) {
 
1726     $query = qq|UPDATE exchangerate
 
1732     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
 
1733                 VALUES (?, $buy, $sell, ?)|;
 
1736   do_query($self, $dbh, $query, $curr, $transdate);
 
1738   $main::lxdebug->leave_sub();
 
1741 sub save_exchangerate {
 
1742   $main::lxdebug->enter_sub();
 
1744   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
 
1746   my $dbh = $self->dbconnect($myconfig);
 
1750   $buy  = $rate if $fld eq 'buy';
 
1751   $sell = $rate if $fld eq 'sell';
 
1754   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
 
1759   $main::lxdebug->leave_sub();
 
1762 sub get_exchangerate {
 
1763   $main::lxdebug->enter_sub();
 
1765   my ($self, $dbh, $curr, $transdate, $fld) = @_;
 
1768   unless ($transdate) {
 
1769     $main::lxdebug->leave_sub();
 
1773   $query = qq|SELECT curr FROM defaults|;
 
1775   my ($currency) = selectrow_query($self, $dbh, $query);
 
1776   my ($defaultcurrency) = split m/:/, $currency;
 
1778   if ($currency eq $defaultcurrency) {
 
1779     $main::lxdebug->leave_sub();
 
1783   $query = qq|SELECT e.$fld FROM exchangerate e
 
1784                  WHERE e.curr = ? AND e.transdate = ?|;
 
1785   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
 
1789   $main::lxdebug->leave_sub();
 
1791   return $exchangerate;
 
1794 sub check_exchangerate {
 
1795   $main::lxdebug->enter_sub();
 
1797   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
 
1799   if ($fld !~/^buy|sell$/) {
 
1800     $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
 
1803   unless ($transdate) {
 
1804     $main::lxdebug->leave_sub();
 
1808   my ($defaultcurrency) = $self->get_default_currency($myconfig);
 
1810   if ($currency eq $defaultcurrency) {
 
1811     $main::lxdebug->leave_sub();
 
1815   my $dbh   = $self->get_standard_dbh($myconfig);
 
1816   my $query = qq|SELECT e.$fld FROM exchangerate e
 
1817                  WHERE e.curr = ? AND e.transdate = ?|;
 
1819   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
 
1821   $main::lxdebug->leave_sub();
 
1823   return $exchangerate;
 
1826 sub get_all_currencies {
 
1827   $main::lxdebug->enter_sub();
 
1830   my $myconfig = shift || \%::myconfig;
 
1831   my $dbh      = $self->get_standard_dbh($myconfig);
 
1833   my $query = qq|SELECT curr FROM defaults|;
 
1835   my ($curr)     = selectrow_query($self, $dbh, $query);
 
1836   my @currencies = grep { $_ } map { s/\s//g; $_ } split m/:/, $curr;
 
1838   $main::lxdebug->leave_sub();
 
1843 sub get_default_currency {
 
1844   $main::lxdebug->enter_sub();
 
1846   my ($self, $myconfig) = @_;
 
1847   my @currencies        = $self->get_all_currencies($myconfig);
 
1849   $main::lxdebug->leave_sub();
 
1851   return $currencies[0];
 
1854 sub set_payment_options {
 
1855   $main::lxdebug->enter_sub();
 
1857   my ($self, $myconfig, $transdate) = @_;
 
1859   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
 
1861   my $dbh = $self->get_standard_dbh($myconfig);
 
1864     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
 
1865     qq|FROM payment_terms p | .
 
1868   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
 
1869    $self->{payment_terms}) =
 
1870      selectrow_query($self, $dbh, $query, $self->{payment_id});
 
1872   if ($transdate eq "") {
 
1873     if ($self->{invdate}) {
 
1874       $transdate = $self->{invdate};
 
1876       $transdate = $self->{transdate};
 
1881     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
 
1882     qq|FROM payment_terms|;
 
1883   ($self->{netto_date}, $self->{skonto_date}) =
 
1884     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
 
1886   my ($invtotal, $total);
 
1887   my (%amounts, %formatted_amounts);
 
1889   if ($self->{type} =~ /_order$/) {
 
1890     $amounts{invtotal} = $self->{ordtotal};
 
1891     $amounts{total}    = $self->{ordtotal};
 
1893   } elsif ($self->{type} =~ /_quotation$/) {
 
1894     $amounts{invtotal} = $self->{quototal};
 
1895     $amounts{total}    = $self->{quototal};
 
1898     $amounts{invtotal} = $self->{invtotal};
 
1899     $amounts{total}    = $self->{total};
 
1901   $amounts{skonto_in_percent} = 100.0 * $self->{percent_skonto};
 
1903   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
 
1905   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
 
1906   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
 
1907   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
 
1909   foreach (keys %amounts) {
 
1910     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
 
1911     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
 
1914   if ($self->{"language_id"}) {
 
1916       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
 
1917       qq|FROM translation_payment_terms t | .
 
1918       qq|LEFT JOIN language l ON t.language_id = l.id | .
 
1919       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
 
1920     my ($description_long, $output_numberformat, $output_dateformat,
 
1921       $output_longdates) =
 
1922       selectrow_query($self, $dbh, $query,
 
1923                       $self->{"language_id"}, $self->{"payment_id"});
 
1925     $self->{payment_terms} = $description_long if ($description_long);
 
1927     if ($output_dateformat) {
 
1928       foreach my $key (qw(netto_date skonto_date)) {
 
1930           $main::locale->reformat_date($myconfig, $self->{$key},
 
1936     if ($output_numberformat &&
 
1937         ($output_numberformat ne $myconfig->{"numberformat"})) {
 
1938       my $saved_numberformat = $myconfig->{"numberformat"};
 
1939       $myconfig->{"numberformat"} = $output_numberformat;
 
1940       map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
 
1941       $myconfig->{"numberformat"} = $saved_numberformat;
 
1945   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
 
1946   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
 
1947   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
 
1948   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
 
1949   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
 
1950   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
 
1951   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
 
1953   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
 
1955   $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
 
1957   $main::lxdebug->leave_sub();
 
1961 sub get_template_language {
 
1962   $main::lxdebug->enter_sub();
 
1964   my ($self, $myconfig) = @_;
 
1966   my $template_code = "";
 
1968   if ($self->{language_id}) {
 
1969     my $dbh = $self->get_standard_dbh($myconfig);
 
1970     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
 
1971     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
 
1974   $main::lxdebug->leave_sub();
 
1976   return $template_code;
 
1979 sub get_printer_code {
 
1980   $main::lxdebug->enter_sub();
 
1982   my ($self, $myconfig) = @_;
 
1984   my $template_code = "";
 
1986   if ($self->{printer_id}) {
 
1987     my $dbh = $self->get_standard_dbh($myconfig);
 
1988     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
 
1989     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
 
1992   $main::lxdebug->leave_sub();
 
1994   return $template_code;
 
1998   $main::lxdebug->enter_sub();
 
2000   my ($self, $myconfig) = @_;
 
2002   my $template_code = "";
 
2004   if ($self->{shipto_id}) {
 
2005     my $dbh = $self->get_standard_dbh($myconfig);
 
2006     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
 
2007     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
 
2008     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
 
2011   $main::lxdebug->leave_sub();
 
2015   $main::lxdebug->enter_sub();
 
2017   my ($self, $dbh, $id, $module) = @_;
 
2022   foreach my $item (qw(name department_1 department_2 street zipcode city country
 
2023                        contact cp_gender phone fax email)) {
 
2024     if ($self->{"shipto$item"}) {
 
2025       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
 
2027     push(@values, $self->{"shipto${item}"});
 
2031     if ($self->{shipto_id}) {
 
2032       my $query = qq|UPDATE shipto set
 
2034                        shiptodepartment_1 = ?,
 
2035                        shiptodepartment_2 = ?,
 
2041                        shiptocp_gender = ?,
 
2045                      WHERE shipto_id = ?|;
 
2046       do_query($self, $dbh, $query, @values, $self->{shipto_id});
 
2048       my $query = qq|SELECT * FROM shipto
 
2049                      WHERE shiptoname = ? AND
 
2050                        shiptodepartment_1 = ? AND
 
2051                        shiptodepartment_2 = ? AND
 
2052                        shiptostreet = ? AND
 
2053                        shiptozipcode = ? AND
 
2055                        shiptocountry = ? AND
 
2056                        shiptocontact = ? AND
 
2057                        shiptocp_gender = ? AND
 
2063       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
 
2066           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
 
2067                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
 
2068                                  shiptocontact, shiptocp_gender, shiptophone, shiptofax, shiptoemail, module)
 
2069              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
 
2070         do_query($self, $dbh, $query, $id, @values, $module);
 
2075   $main::lxdebug->leave_sub();
 
2079   $main::lxdebug->enter_sub();
 
2081   my ($self, $dbh) = @_;
 
2083   $dbh ||= $self->get_standard_dbh(\%main::myconfig);
 
2085   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
 
2086   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
 
2087   $self->{"employee_id"} *= 1;
 
2089   $main::lxdebug->leave_sub();
 
2092 sub get_employee_data {
 
2093   $main::lxdebug->enter_sub();
 
2098   Common::check_params(\%params, qw(prefix));
 
2099   Common::check_params_x(\%params, qw(id));
 
2102     $main::lxdebug->leave_sub();
 
2106   my $myconfig = \%main::myconfig;
 
2107   my $dbh      = $params{dbh} || $self->get_standard_dbh($myconfig);
 
2109   my ($login)  = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
 
2112     my $user = User->new($login);
 
2113     map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
 
2115     $self->{$params{prefix} . '_login'}   = $login;
 
2116     $self->{$params{prefix} . '_name'}  ||= $login;
 
2119   $main::lxdebug->leave_sub();
 
2123   $main::lxdebug->enter_sub();
 
2125   my ($self, $myconfig, $reference_date) = @_;
 
2127   $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
 
2129   my $dbh         = $self->get_standard_dbh($myconfig);
 
2130   my $query       = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
 
2131   my ($duedate)   = selectrow_query($self, $dbh, $query, $self->{payment_id});
 
2133   $main::lxdebug->leave_sub();
 
2139   $main::lxdebug->enter_sub();
 
2141   my ($self, $dbh, $id, $key) = @_;
 
2143   $key = "all_contacts" unless ($key);
 
2147     $main::lxdebug->leave_sub();
 
2152     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
 
2153     qq|FROM contacts | .
 
2154     qq|WHERE cp_cv_id = ? | .
 
2155     qq|ORDER BY lower(cp_name)|;
 
2157   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
 
2159   $main::lxdebug->leave_sub();
 
2163   $main::lxdebug->enter_sub();
 
2165   my ($self, $dbh, $key) = @_;
 
2167   my ($all, $old_id, $where, @values);
 
2169   if (ref($key) eq "HASH") {
 
2172     $key = "ALL_PROJECTS";
 
2174     foreach my $p (keys(%{$params})) {
 
2176         $all = $params->{$p};
 
2177       } elsif ($p eq "old_id") {
 
2178         $old_id = $params->{$p};
 
2179       } elsif ($p eq "key") {
 
2180         $key = $params->{$p};
 
2186     $where = "WHERE active ";
 
2188       if (ref($old_id) eq "ARRAY") {
 
2189         my @ids = grep({ $_ } @{$old_id});
 
2191           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
 
2192           push(@values, @ids);
 
2195         $where .= " OR (id = ?) ";
 
2196         push(@values, $old_id);
 
2202     qq|SELECT id, projectnumber, description, active | .
 
2205     qq|ORDER BY lower(projectnumber)|;
 
2207   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
 
2209   $main::lxdebug->leave_sub();
 
2213   $main::lxdebug->enter_sub();
 
2215   my ($self, $dbh, $vc_id, $key) = @_;
 
2217   $key = "all_shipto" unless ($key);
 
2220     # get shipping addresses
 
2221     my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
 
2223     $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
 
2229   $main::lxdebug->leave_sub();
 
2233   $main::lxdebug->enter_sub();
 
2235   my ($self, $dbh, $key) = @_;
 
2237   $key = "all_printers" unless ($key);
 
2239   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
 
2241   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2243   $main::lxdebug->leave_sub();
 
2247   $main::lxdebug->enter_sub();
 
2249   my ($self, $dbh, $params) = @_;
 
2252   $key = $params->{key};
 
2253   $key = "all_charts" unless ($key);
 
2255   my $transdate = quote_db_date($params->{transdate});
 
2258     qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
 
2260     qq|LEFT JOIN taxkeys tk ON | .
 
2261     qq|(tk.id = (SELECT id FROM taxkeys | .
 
2262     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
 
2263     qq|          ORDER BY startdate DESC LIMIT 1)) | .
 
2264     qq|ORDER BY c.accno|;
 
2266   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2268   $main::lxdebug->leave_sub();
 
2271 sub _get_taxcharts {
 
2272   $main::lxdebug->enter_sub();
 
2274   my ($self, $dbh, $params) = @_;
 
2276   my $key = "all_taxcharts";
 
2279   if (ref $params eq 'HASH') {
 
2280     $key = $params->{key} if ($params->{key});
 
2281     if ($params->{module} eq 'AR') {
 
2282       push @where, 'taxkey NOT IN (8, 9, 18, 19)';
 
2284     } elsif ($params->{module} eq 'AP') {
 
2285       push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
 
2292   my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
 
2294   my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
 
2296   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2298   $main::lxdebug->leave_sub();
 
2302   $main::lxdebug->enter_sub();
 
2304   my ($self, $dbh, $key) = @_;
 
2306   $key = "all_taxzones" unless ($key);
 
2308   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
 
2310   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2312   $main::lxdebug->leave_sub();
 
2315 sub _get_employees {
 
2316   $main::lxdebug->enter_sub();
 
2318   my ($self, $dbh, $default_key, $key) = @_;
 
2320   $key = $default_key unless ($key);
 
2321   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
 
2323   $main::lxdebug->leave_sub();
 
2326 sub _get_business_types {
 
2327   $main::lxdebug->enter_sub();
 
2329   my ($self, $dbh, $key) = @_;
 
2331   my $options       = ref $key eq 'HASH' ? $key : { key => $key };
 
2332   $options->{key} ||= "all_business_types";
 
2335   if (exists $options->{salesman}) {
 
2336     $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
 
2339   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
 
2341   $main::lxdebug->leave_sub();
 
2344 sub _get_languages {
 
2345   $main::lxdebug->enter_sub();
 
2347   my ($self, $dbh, $key) = @_;
 
2349   $key = "all_languages" unless ($key);
 
2351   my $query = qq|SELECT * FROM language ORDER BY id|;
 
2353   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2355   $main::lxdebug->leave_sub();
 
2358 sub _get_dunning_configs {
 
2359   $main::lxdebug->enter_sub();
 
2361   my ($self, $dbh, $key) = @_;
 
2363   $key = "all_dunning_configs" unless ($key);
 
2365   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
 
2367   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2369   $main::lxdebug->leave_sub();
 
2372 sub _get_currencies {
 
2373 $main::lxdebug->enter_sub();
 
2375   my ($self, $dbh, $key) = @_;
 
2377   $key = "all_currencies" unless ($key);
 
2379   my $query = qq|SELECT curr AS currency FROM defaults|;
 
2381   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
 
2383   $main::lxdebug->leave_sub();
 
2387 $main::lxdebug->enter_sub();
 
2389   my ($self, $dbh, $key) = @_;
 
2391   $key = "all_payments" unless ($key);
 
2393   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
 
2395   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2397   $main::lxdebug->leave_sub();
 
2400 sub _get_customers {
 
2401   $main::lxdebug->enter_sub();
 
2403   my ($self, $dbh, $key) = @_;
 
2405   my $options        = ref $key eq 'HASH' ? $key : { key => $key };
 
2406   $options->{key}  ||= "all_customers";
 
2407   my $limit_clause   = "LIMIT $options->{limit}" if $options->{limit};
 
2410   push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if  $options->{business_is_salesman};
 
2411   push @where, qq|NOT obsolete|                                            if !$options->{with_obsolete};
 
2412   my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : '';
 
2414   my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|;
 
2415   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
 
2417   $main::lxdebug->leave_sub();
 
2421   $main::lxdebug->enter_sub();
 
2423   my ($self, $dbh, $key) = @_;
 
2425   $key = "all_vendors" unless ($key);
 
2427   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
 
2429   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2431   $main::lxdebug->leave_sub();
 
2434 sub _get_departments {
 
2435   $main::lxdebug->enter_sub();
 
2437   my ($self, $dbh, $key) = @_;
 
2439   $key = "all_departments" unless ($key);
 
2441   my $query = qq|SELECT * FROM department ORDER BY description|;
 
2443   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2445   $main::lxdebug->leave_sub();
 
2448 sub _get_warehouses {
 
2449   $main::lxdebug->enter_sub();
 
2451   my ($self, $dbh, $param) = @_;
 
2453   my ($key, $bins_key);
 
2455   if ('' eq ref $param) {
 
2459     $key      = $param->{key};
 
2460     $bins_key = $param->{bins};
 
2463   my $query = qq|SELECT w.* FROM warehouse w
 
2464                  WHERE (NOT w.invalid) AND
 
2465                    ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
 
2466                  ORDER BY w.sortkey|;
 
2468   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2471     $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
 
2472     my $sth = prepare_query($self, $dbh, $query);
 
2474     foreach my $warehouse (@{ $self->{$key} }) {
 
2475       do_statement($self, $sth, $query, $warehouse->{id});
 
2476       $warehouse->{$bins_key} = [];
 
2478       while (my $ref = $sth->fetchrow_hashref()) {
 
2479         push @{ $warehouse->{$bins_key} }, $ref;
 
2485   $main::lxdebug->leave_sub();
 
2489   $main::lxdebug->enter_sub();
 
2491   my ($self, $dbh, $table, $key, $sortkey) = @_;
 
2493   my $query  = qq|SELECT * FROM $table|;
 
2494   $query    .= qq| ORDER BY $sortkey| if ($sortkey);
 
2496   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2498   $main::lxdebug->leave_sub();
 
2502 #  $main::lxdebug->enter_sub();
 
2504 #  my ($self, $dbh, $key) = @_;
 
2506 #  $key ||= "all_groups";
 
2508 #  my $groups = $main::auth->read_groups();
 
2510 #  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2512 #  $main::lxdebug->leave_sub();
 
2516   $main::lxdebug->enter_sub();
 
2521   my $dbh = $self->get_standard_dbh(\%main::myconfig);
 
2522   my ($sth, $query, $ref);
 
2524   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
 
2525   my $vc_id = $self->{"${vc}_id"};
 
2527   if ($params{"contacts"}) {
 
2528     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
 
2531   if ($params{"shipto"}) {
 
2532     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
 
2535   if ($params{"projects"} || $params{"all_projects"}) {
 
2536     $self->_get_projects($dbh, $params{"all_projects"} ?
 
2537                          $params{"all_projects"} : $params{"projects"},
 
2538                          $params{"all_projects"} ? 1 : 0);
 
2541   if ($params{"printers"}) {
 
2542     $self->_get_printers($dbh, $params{"printers"});
 
2545   if ($params{"languages"}) {
 
2546     $self->_get_languages($dbh, $params{"languages"});
 
2549   if ($params{"charts"}) {
 
2550     $self->_get_charts($dbh, $params{"charts"});
 
2553   if ($params{"taxcharts"}) {
 
2554     $self->_get_taxcharts($dbh, $params{"taxcharts"});
 
2557   if ($params{"taxzones"}) {
 
2558     $self->_get_taxzones($dbh, $params{"taxzones"});
 
2561   if ($params{"employees"}) {
 
2562     $self->_get_employees($dbh, "all_employees", $params{"employees"});
 
2565   if ($params{"salesmen"}) {
 
2566     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
 
2569   if ($params{"business_types"}) {
 
2570     $self->_get_business_types($dbh, $params{"business_types"});
 
2573   if ($params{"dunning_configs"}) {
 
2574     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
 
2577   if($params{"currencies"}) {
 
2578     $self->_get_currencies($dbh, $params{"currencies"});
 
2581   if($params{"customers"}) {
 
2582     $self->_get_customers($dbh, $params{"customers"});
 
2585   if($params{"vendors"}) {
 
2586     if (ref $params{"vendors"} eq 'HASH') {
 
2587       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
 
2589       $self->_get_vendors($dbh, $params{"vendors"});
 
2593   if($params{"payments"}) {
 
2594     $self->_get_payments($dbh, $params{"payments"});
 
2597   if($params{"departments"}) {
 
2598     $self->_get_departments($dbh, $params{"departments"});
 
2601   if ($params{price_factors}) {
 
2602     $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
 
2605   if ($params{warehouses}) {
 
2606     $self->_get_warehouses($dbh, $params{warehouses});
 
2609 #  if ($params{groups}) {
 
2610 #    $self->_get_groups($dbh, $params{groups});
 
2613   if ($params{partsgroup}) {
 
2614     $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
 
2617   $main::lxdebug->leave_sub();
 
2620 # this sub gets the id and name from $table
 
2622   $main::lxdebug->enter_sub();
 
2624   my ($self, $myconfig, $table) = @_;
 
2626   # connect to database
 
2627   my $dbh = $self->get_standard_dbh($myconfig);
 
2629   $table = $table eq "customer" ? "customer" : "vendor";
 
2630   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
 
2632   my ($query, @values);
 
2634   if (!$self->{openinvoices}) {
 
2636     if ($self->{customernumber} ne "") {
 
2637       $where = qq|(vc.customernumber ILIKE ?)|;
 
2638       push(@values, '%' . $self->{customernumber} . '%');
 
2640       $where = qq|(vc.name ILIKE ?)|;
 
2641       push(@values, '%' . $self->{$table} . '%');
 
2645       qq~SELECT vc.id, vc.name,
 
2646            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
2648          WHERE $where AND (NOT vc.obsolete)
 
2652       qq~SELECT DISTINCT vc.id, vc.name,
 
2653            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
2655          JOIN $table vc ON (a.${table}_id = vc.id)
 
2656          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
 
2658     push(@values, '%' . $self->{$table} . '%');
 
2661   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
 
2663   $main::lxdebug->leave_sub();
 
2665   return scalar(@{ $self->{name_list} });
 
2668 # the selection sub is used in the AR, AP, IS, IR and OE module
 
2671   $main::lxdebug->enter_sub();
 
2673   my ($self, $myconfig, $table, $module) = @_;
 
2676   my $dbh = $self->get_standard_dbh;
 
2678   $table = $table eq "customer" ? "customer" : "vendor";
 
2680   my $query = qq|SELECT count(*) FROM $table|;
 
2681   my ($count) = selectrow_query($self, $dbh, $query);
 
2683   # build selection list
 
2684   if ($count <= $myconfig->{vclimit}) {
 
2685     $query = qq|SELECT id, name, salesman_id
 
2686                 FROM $table WHERE NOT obsolete
 
2688     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
 
2692   $self->get_employee($dbh);
 
2694   # setup sales contacts
 
2695   $query = qq|SELECT e.id, e.name
 
2697               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
 
2698   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
 
2701   push(@{ $self->{all_employees} },
 
2702        { id   => $self->{employee_id},
 
2703          name => $self->{employee} });
 
2705   # sort the whole thing
 
2706   @{ $self->{all_employees} } =
 
2707     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
 
2709   if ($module eq 'AR') {
 
2711     # prepare query for departments
 
2712     $query = qq|SELECT id, description
 
2715                 ORDER BY description|;
 
2718     $query = qq|SELECT id, description
 
2720                 ORDER BY description|;
 
2723   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2726   $query = qq|SELECT id, description
 
2730   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2733   $query = qq|SELECT printer_description, id
 
2735               ORDER BY printer_description|;
 
2737   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2740   $query = qq|SELECT id, description
 
2744   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
2746   $main::lxdebug->leave_sub();
 
2749 sub language_payment {
 
2750   $main::lxdebug->enter_sub();
 
2752   my ($self, $myconfig) = @_;
 
2754   my $dbh = $self->get_standard_dbh($myconfig);
 
2756   my $query = qq|SELECT id, description
 
2760   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2763   $query = qq|SELECT printer_description, id
 
2765               ORDER BY printer_description|;
 
2767   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2770   $query = qq|SELECT id, description
 
2774   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
2776   # get buchungsgruppen
 
2777   $query = qq|SELECT id, description
 
2778               FROM buchungsgruppen|;
 
2780   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
 
2782   $main::lxdebug->leave_sub();
 
2785 # this is only used for reports
 
2786 sub all_departments {
 
2787   $main::lxdebug->enter_sub();
 
2789   my ($self, $myconfig, $table) = @_;
 
2791   my $dbh = $self->get_standard_dbh($myconfig);
 
2794   if ($table eq 'customer') {
 
2795     $where = "WHERE role = 'P' ";
 
2798   my $query = qq|SELECT id, description
 
2801                  ORDER BY description|;
 
2802   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2804   delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
 
2806   $main::lxdebug->leave_sub();
 
2810   $main::lxdebug->enter_sub();
 
2812   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
 
2815   if ($table eq "customer") {
 
2824   $self->all_vc($myconfig, $table, $module);
 
2826   # get last customers or vendors
 
2827   my ($query, $sth, $ref);
 
2829   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
 
2834     my $transdate = "current_date";
 
2835     if ($self->{transdate}) {
 
2836       $transdate = $dbh->quote($self->{transdate});
 
2839     # now get the account numbers
 
2840     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
 
2841                 FROM chart c, taxkeys tk
 
2842                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
 
2843                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
 
2846     $sth = $dbh->prepare($query);
 
2848     do_statement($self, $sth, $query, '%' . $module . '%');
 
2850     $self->{accounts} = "";
 
2851     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2853       foreach my $key (split(/:/, $ref->{link})) {
 
2854         if ($key =~ /\Q$module\E/) {
 
2856           # cross reference for keys
 
2857           $xkeyref{ $ref->{accno} } = $key;
 
2859           push @{ $self->{"${module}_links"}{$key} },
 
2860             { accno       => $ref->{accno},
 
2861               description => $ref->{description},
 
2862               taxkey      => $ref->{taxkey_id},
 
2863               tax_id      => $ref->{tax_id} };
 
2865           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2871   # get taxkeys and description
 
2872   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
 
2873   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
 
2875   if (($module eq "AP") || ($module eq "AR")) {
 
2876     # get tax rates and description
 
2877     $query = qq|SELECT * FROM tax|;
 
2878     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
 
2884            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
 
2885            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
 
2886            a.intnotes, a.department_id, a.amount AS oldinvtotal,
 
2887            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
 
2889            d.description AS department,
 
2892          JOIN $table c ON (a.${table}_id = c.id)
 
2893          LEFT JOIN employee e ON (e.id = a.employee_id)
 
2894          LEFT JOIN department d ON (d.id = a.department_id)
 
2896     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
 
2898     foreach my $key (keys %$ref) {
 
2899       $self->{$key} = $ref->{$key};
 
2902     my $transdate = "current_date";
 
2903     if ($self->{transdate}) {
 
2904       $transdate = $dbh->quote($self->{transdate});
 
2907     # now get the account numbers
 
2908     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
 
2910                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
 
2912                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
 
2913                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
 
2916     $sth = $dbh->prepare($query);
 
2917     do_statement($self, $sth, $query, "%$module%");
 
2919     $self->{accounts} = "";
 
2920     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2922       foreach my $key (split(/:/, $ref->{link})) {
 
2923         if ($key =~ /\Q$module\E/) {
 
2925           # cross reference for keys
 
2926           $xkeyref{ $ref->{accno} } = $key;
 
2928           push @{ $self->{"${module}_links"}{$key} },
 
2929             { accno       => $ref->{accno},
 
2930               description => $ref->{description},
 
2931               taxkey      => $ref->{taxkey_id},
 
2932               tax_id      => $ref->{tax_id} };
 
2934           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2940     # get amounts from individual entries
 
2943            c.accno, c.description,
 
2944            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
 
2948          LEFT JOIN chart c ON (c.id = a.chart_id)
 
2949          LEFT JOIN project p ON (p.id = a.project_id)
 
2950          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
 
2951                                     WHERE (tk.taxkey_id=a.taxkey) AND
 
2952                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
 
2953                                         THEN tk.chart_id = a.chart_id
 
2956                                        OR (c.link='%tax%')) AND
 
2957                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
 
2958          WHERE a.trans_id = ?
 
2959          AND a.fx_transaction = '0'
 
2960          ORDER BY a.acc_trans_id, a.transdate|;
 
2961     $sth = $dbh->prepare($query);
 
2962     do_statement($self, $sth, $query, $self->{id});
 
2964     # get exchangerate for currency
 
2965     $self->{exchangerate} =
 
2966       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2969     # store amounts in {acc_trans}{$key} for multiple accounts
 
2970     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2971       $ref->{exchangerate} =
 
2972         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
 
2973       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
 
2976       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
 
2977         $ref->{amount} *= -1;
 
2979       $ref->{index} = $index;
 
2981       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
 
2987            d.curr AS currencies, d.closedto, d.revtrans,
 
2988            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2989            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
2991     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2992     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2999             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
 
3000             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
3001             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
3003     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
3004     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
3006     if ($self->{"$self->{vc}_id"}) {
 
3008       # only setup currency
 
3009       ($self->{currency}) = split(/:/, $self->{currencies});
 
3013       $self->lastname_used($dbh, $myconfig, $table, $module);
 
3015       # get exchangerate for currency
 
3016       $self->{exchangerate} =
 
3017         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
3023   $main::lxdebug->leave_sub();
 
3027   $main::lxdebug->enter_sub();
 
3029   my ($self, $dbh, $myconfig, $table, $module) = @_;
 
3033   $table         = $table eq "customer" ? "customer" : "vendor";
 
3034   my %column_map = ("a.curr"                  => "currency",
 
3035                     "a.${table}_id"           => "${table}_id",
 
3036                     "a.department_id"         => "department_id",
 
3037                     "d.description"           => "department",
 
3038                     "ct.name"                 => $table,
 
3039                     "current_date + ct.terms" => "duedate",
 
3042   if ($self->{type} =~ /delivery_order/) {
 
3043     $arap  = 'delivery_orders';
 
3044     delete $column_map{"a.curr"};
 
3046   } elsif ($self->{type} =~ /_order/) {
 
3048     $where = "quotation = '0'";
 
3050   } elsif ($self->{type} =~ /_quotation/) {
 
3052     $where = "quotation = '1'";
 
3054   } elsif ($table eq 'customer') {
 
3062   $where           = "($where) AND" if ($where);
 
3063   my $query        = qq|SELECT MAX(id) FROM $arap
 
3064                         WHERE $where ${table}_id > 0|;
 
3065   my ($trans_id)   = selectrow_query($self, $dbh, $query);
 
3068   my $column_spec  = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
 
3069   $query           = qq|SELECT $column_spec
 
3071                         LEFT JOIN $table     ct ON (a.${table}_id = ct.id)
 
3072                         LEFT JOIN department d  ON (a.department_id = d.id)
 
3074   my $ref          = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
 
3076   map { $self->{$_} = $ref->{$_} } values %column_map;
 
3078   $main::lxdebug->leave_sub();
 
3082   $main::lxdebug->enter_sub();
 
3085   my $myconfig = shift || \%::myconfig;
 
3086   my ($thisdate, $days) = @_;
 
3088   my $dbh = $self->get_standard_dbh($myconfig);
 
3093     my $dateformat = $myconfig->{dateformat};
 
3094     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
 
3095     $thisdate = $dbh->quote($thisdate);
 
3096     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
 
3098     $query = qq|SELECT current_date AS thisdate|;
 
3101   ($thisdate) = selectrow_query($self, $dbh, $query);
 
3103   $main::lxdebug->leave_sub();
 
3109   $main::lxdebug->enter_sub();
 
3111   my ($self, $string) = @_;
 
3113   if ($string !~ /%/) {
 
3114     $string = "%$string%";
 
3117   $string =~ s/\'/\'\'/g;
 
3119   $main::lxdebug->leave_sub();
 
3125   $main::lxdebug->enter_sub();
 
3127   my ($self, $flds, $new, $count, $numrows) = @_;
 
3131   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
 
3136   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
 
3138     my $j = $item->{ndx} - 1;
 
3139     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
 
3143   for $i ($count + 1 .. $numrows) {
 
3144     map { delete $self->{"${_}_$i"} } @{$flds};
 
3147   $main::lxdebug->leave_sub();
 
3151   $main::lxdebug->enter_sub();
 
3153   my ($self, $myconfig) = @_;
 
3157   my $dbh = $self->dbconnect_noauto($myconfig);
 
3159   my $query = qq|DELETE FROM status
 
3160                  WHERE (formname = ?) AND (trans_id = ?)|;
 
3161   my $sth = prepare_query($self, $dbh, $query);
 
3163   if ($self->{formname} =~ /(check|receipt)/) {
 
3164     for $i (1 .. $self->{rowcount}) {
 
3165       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
 
3168     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
 
3172   my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3173   my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3175   my %queued = split / /, $self->{queued};
 
3178   if ($self->{formname} =~ /(check|receipt)/) {
 
3180     # this is a check or receipt, add one entry for each lineitem
 
3181     my ($accno) = split /--/, $self->{account};
 
3182     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
 
3183                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
 
3184     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
 
3185     $sth = prepare_query($self, $dbh, $query);
 
3187     for $i (1 .. $self->{rowcount}) {
 
3188       if ($self->{"checked_$i"}) {
 
3189         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
 
3195     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
3196                 VALUES (?, ?, ?, ?, ?)|;
 
3197     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
 
3198              $queued{$self->{formname}}, $self->{formname});
 
3204   $main::lxdebug->leave_sub();
 
3208   $main::lxdebug->enter_sub();
 
3210   my ($self, $dbh) = @_;
 
3212   my ($query, $printed, $emailed);
 
3214   my $formnames  = $self->{printed};
 
3215   my $emailforms = $self->{emailed};
 
3217   $query = qq|DELETE FROM status
 
3218                  WHERE (formname = ?) AND (trans_id = ?)|;
 
3219   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
 
3221   # this only applies to the forms
 
3222   # checks and receipts are posted when printed or queued
 
3224   if ($self->{queued}) {
 
3225     my %queued = split / /, $self->{queued};
 
3227     foreach my $formname (keys %queued) {
 
3228       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3229       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3231       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
3232                   VALUES (?, ?, ?, ?, ?)|;
 
3233       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
 
3235       $formnames  =~ s/\Q$self->{formname}\E//;
 
3236       $emailforms =~ s/\Q$self->{formname}\E//;
 
3241   # save printed, emailed info
 
3242   $formnames  =~ s/^ +//g;
 
3243   $emailforms =~ s/^ +//g;
 
3246   map { $status{$_}{printed} = 1 } split / +/, $formnames;
 
3247   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
 
3249   foreach my $formname (keys %status) {
 
3250     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3251     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3253     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
 
3254                 VALUES (?, ?, ?, ?)|;
 
3255     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
 
3258   $main::lxdebug->leave_sub();
 
3262 # $main::locale->text('SAVED')
 
3263 # $main::locale->text('DELETED')
 
3264 # $main::locale->text('ADDED')
 
3265 # $main::locale->text('PAYMENT POSTED')
 
3266 # $main::locale->text('POSTED')
 
3267 # $main::locale->text('POSTED AS NEW')
 
3268 # $main::locale->text('ELSE')
 
3269 # $main::locale->text('SAVED FOR DUNNING')
 
3270 # $main::locale->text('DUNNING STARTED')
 
3271 # $main::locale->text('PRINTED')
 
3272 # $main::locale->text('MAILED')
 
3273 # $main::locale->text('SCREENED')
 
3274 # $main::locale->text('CANCELED')
 
3275 # $main::locale->text('invoice')
 
3276 # $main::locale->text('proforma')
 
3277 # $main::locale->text('sales_order')
 
3278 # $main::locale->text('packing_list')
 
3279 # $main::locale->text('pick_list')
 
3280 # $main::locale->text('purchase_order')
 
3281 # $main::locale->text('bin_list')
 
3282 # $main::locale->text('sales_quotation')
 
3283 # $main::locale->text('request_quotation')
 
3286   $main::lxdebug->enter_sub();
 
3289   my $dbh  = shift || $self->get_standard_dbh;
 
3291   if(!exists $self->{employee_id}) {
 
3292     &get_employee($self, $dbh);
 
3296    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
 
3297    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
 
3298   my @values = (conv_i($self->{id}), $self->{login},
 
3299                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
 
3300   do_query($self, $dbh, $query, @values);
 
3304   $main::lxdebug->leave_sub();
 
3308   $main::lxdebug->enter_sub();
 
3310   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
 
3311   my ($orderBy, $desc) = split(/\-\-/, $order);
 
3312   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
 
3315   if ($trans_id ne "") {
 
3317       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 | .
 
3318       qq|FROM history_erp h | .
 
3319       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
 
3320       qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
 
3323     my $sth = $dbh->prepare($query) || $self->dberror($query);
 
3325     $sth->execute() || $self->dberror("$query");
 
3327     while(my $hash_ref = $sth->fetchrow_hashref()) {
 
3328       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
 
3329       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
 
3330       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
 
3331       $tempArray[$i++] = $hash_ref;
 
3333     $main::lxdebug->leave_sub() and return \@tempArray
 
3334       if ($i > 0 && $tempArray[0] ne "");
 
3336   $main::lxdebug->leave_sub();
 
3340 sub update_defaults {
 
3341   $main::lxdebug->enter_sub();
 
3343   my ($self, $myconfig, $fld, $provided_dbh) = @_;
 
3346   if ($provided_dbh) {
 
3347     $dbh = $provided_dbh;
 
3349     $dbh = $self->dbconnect_noauto($myconfig);
 
3351   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
 
3352   my $sth   = $dbh->prepare($query);
 
3354   $sth->execute || $self->dberror($query);
 
3355   my ($var) = $sth->fetchrow_array;
 
3358   if ($var =~ m/\d+$/) {
 
3359     my $new_var  = (substr $var, $-[0]) * 1 + 1;
 
3360     my $len_diff = length($var) - $-[0] - length($new_var);
 
3361     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
 
3367   $query = qq|UPDATE defaults SET $fld = ?|;
 
3368   do_query($self, $dbh, $query, $var);
 
3370   if (!$provided_dbh) {
 
3375   $main::lxdebug->leave_sub();
 
3380 sub update_business {
 
3381   $main::lxdebug->enter_sub();
 
3383   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
 
3386   if ($provided_dbh) {
 
3387     $dbh = $provided_dbh;
 
3389     $dbh = $self->dbconnect_noauto($myconfig);
 
3392     qq|SELECT customernumberinit FROM business
 
3393        WHERE id = ? FOR UPDATE|;
 
3394   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
 
3396   return undef unless $var;
 
3398   if ($var =~ m/\d+$/) {
 
3399     my $new_var  = (substr $var, $-[0]) * 1 + 1;
 
3400     my $len_diff = length($var) - $-[0] - length($new_var);
 
3401     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
 
3407   $query = qq|UPDATE business
 
3408               SET customernumberinit = ?
 
3410   do_query($self, $dbh, $query, $var, $business_id);
 
3412   if (!$provided_dbh) {
 
3417   $main::lxdebug->leave_sub();
 
3422 sub get_partsgroup {
 
3423   $main::lxdebug->enter_sub();
 
3425   my ($self, $myconfig, $p) = @_;
 
3426   my $target = $p->{target} || 'all_partsgroup';
 
3428   my $dbh = $self->get_standard_dbh($myconfig);
 
3430   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
 
3432                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
 
3435   if ($p->{searchitems} eq 'part') {
 
3436     $query .= qq|WHERE p.inventory_accno_id > 0|;
 
3438   if ($p->{searchitems} eq 'service') {
 
3439     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
 
3441   if ($p->{searchitems} eq 'assembly') {
 
3442     $query .= qq|WHERE p.assembly = '1'|;
 
3444   if ($p->{searchitems} eq 'labor') {
 
3445     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
 
3448   $query .= qq|ORDER BY partsgroup|;
 
3451     $query = qq|SELECT id, partsgroup FROM partsgroup
 
3452                 ORDER BY partsgroup|;
 
3455   if ($p->{language_code}) {
 
3456     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
 
3457                   t.description AS translation
 
3459                 JOIN parts p ON (p.partsgroup_id = pg.id)
 
3460                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
 
3461                 ORDER BY translation|;
 
3462     @values = ($p->{language_code});
 
3465   $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
 
3467   $main::lxdebug->leave_sub();
 
3470 sub get_pricegroup {
 
3471   $main::lxdebug->enter_sub();
 
3473   my ($self, $myconfig, $p) = @_;
 
3475   my $dbh = $self->get_standard_dbh($myconfig);
 
3477   my $query = qq|SELECT p.id, p.pricegroup
 
3480   $query .= qq| ORDER BY pricegroup|;
 
3483     $query = qq|SELECT id, pricegroup FROM pricegroup
 
3484                 ORDER BY pricegroup|;
 
3487   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
 
3489   $main::lxdebug->leave_sub();
 
3493 # usage $form->all_years($myconfig, [$dbh])
 
3494 # return list of all years where bookings found
 
3497   $main::lxdebug->enter_sub();
 
3499   my ($self, $myconfig, $dbh) = @_;
 
3501   $dbh ||= $self->get_standard_dbh($myconfig);
 
3504   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
 
3505                    (SELECT MAX(transdate) FROM acc_trans)|;
 
3506   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
 
3508   if ($myconfig->{dateformat} =~ /^yy/) {
 
3509     ($startdate) = split /\W/, $startdate;
 
3510     ($enddate) = split /\W/, $enddate;
 
3512     (@_) = split /\W/, $startdate;
 
3514     (@_) = split /\W/, $enddate;
 
3519   $startdate = substr($startdate,0,4);
 
3520   $enddate = substr($enddate,0,4);
 
3522   while ($enddate >= $startdate) {
 
3523     push @all_years, $enddate--;
 
3528   $main::lxdebug->leave_sub();
 
3532   $main::lxdebug->enter_sub();
 
3536   map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
 
3538   $main::lxdebug->leave_sub();
 
3542   $main::lxdebug->enter_sub();
 
3547   map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
 
3549   $main::lxdebug->leave_sub();
 
3558 SL::Form.pm - main data object.
 
3562 This is the main data object of Lx-Office.
 
3563 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
 
3564 Points of interest for a beginner are:
 
3566  - $form->error            - renders a generic error in html. accepts an error message
 
3567  - $form->get_standard_dbh - returns a database connection for the
 
3569 =head1 SPECIAL FUNCTIONS
 
3573 =item _store_value()
 
3575 parses a complex var name, and stores it in the form.
 
3578   $form->_store_value($key, $value);
 
3580 keys must start with a string, and can contain various tokens.
 
3581 supported key structures are:
 
3584   simple key strings work as expected
 
3589   separating two keys by a dot (.) will result in a hash lookup for the inner value
 
3590   this is similar to the behaviour of java and templating mechanisms.
 
3592   filter.description => $form->{filter}->{description}
 
3594 3. array+hashref access
 
3596   adding brackets ([]) before the dot will cause the next hash to be put into an array.
 
3597   using [+] instead of [] will force a new array index. this is useful for recurring
 
3598   data structures like part lists. put a [+] into the first varname, and use [] on the
 
3601   repeating these names in your template:
 
3604     invoice.items[].parts_id
 
3608     $form->{invoice}->{items}->[
 
3622   using brackets at the end of a name will result in a pure array to be created.
 
3623   note that you mustn't use [+], which is reserved for array+hash access and will
 
3624   result in undefined behaviour in array context.
 
3626   filter.status[]  => $form->{status}->[ val1, val2, ... ]
 
3628 =item update_business PARAMS
 
3631  \%config,     - config hashref
 
3632  $business_id, - business id
 
3633  $dbh          - optional database handle
 
3635 handles business (thats customer/vendor types) sequences.
 
3637 special behaviour for empty strings in customerinitnumber field:
 
3638 will in this case not increase the value, and return undef.
 
3640 =item redirect_header $url
 
3642 Generates a HTTP redirection header for the new C<$url>. Constructs an
 
3643 absolute URL including scheme, host name and port. If C<$url> is a
 
3644 relative URL then it is considered relative to Lx-Office base URL.
 
3646 This function C<die>s if headers have already been created with
 
3647 C<$::form-E<gt>header>.
 
3651   print $::form->redirect_header('oe.pl?action=edit&id=1234');
 
3652   print $::form->redirect_header('http://www.lx-office.org/');