1 #====================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   7 #=====================================================================
 
   8 # SQL-Ledger Accounting
 
   9 # Copyright (C) 1998-2002
 
  11 #  Author: Dieter Simader
 
  12 #   Email: dsimader@sql-ledger.org
 
  13 #     Web: http://www.sql-ledger.org
 
  15 # Contributors: Thomas Bayen <bayen@gmx.de>
 
  16 #               Antti Kaihola <akaihola@siba.fi>
 
  17 #               Moritz Bunkus (tex code)
 
  19 # This program is free software; you can redistribute it and/or modify
 
  20 # it under the terms of the GNU General Public License as published by
 
  21 # the Free Software Foundation; either version 2 of the License, or
 
  22 # (at your option) any later version.
 
  24 # This program is distributed in the hope that it will be useful,
 
  25 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 
  26 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  27 # GNU General Public License for more details.
 
  28 # You should have received a copy of the GNU General Public License
 
  29 # along with this program; if not, write to the Free Software
 
  30 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 
  31 #======================================================================
 
  32 # Utilities for parsing forms
 
  33 # and supporting routines for linking account numbers
 
  34 # used in AR, AP and IS, IR modules
 
  36 #======================================================================
 
  58 use List::Util qw(first max min sum);
 
  59 use List::MoreUtils qw(any);
 
  67     $standard_dbh->disconnect();
 
  73   $main::lxdebug->enter_sub(2);
 
  79   my @tokens = split /((?:\[\+?\])?(?:\.|$))/, $key;
 
  84      $curr = \ $self->{ shift @tokens };
 
  88     my $sep = shift @tokens;
 
  89     my $key = shift @tokens;
 
  91     $curr = \ $$curr->[++$#$$curr], next if $sep eq '[]';
 
  92     $curr = \ $$curr->[max 0, $#$$curr]  if $sep eq '[].';
 
  93     $curr = \ $$curr->[++$#$$curr]       if $sep eq '[+].';
 
  94     $curr = \ $$curr->{$key}
 
  99   $main::lxdebug->leave_sub(2);
 
 105   $main::lxdebug->enter_sub(2);
 
 110   my @pairs = split(/&/, $input);
 
 113     my ($key, $value) = split(/=/, $_, 2);
 
 114     $self->_store_value($self->unescape($key), $self->unescape($value)) if ($key);
 
 117   $main::lxdebug->leave_sub(2);
 
 120 sub _request_to_hash {
 
 121   $main::lxdebug->enter_sub(2);
 
 126   if (!$ENV{'CONTENT_TYPE'}
 
 127       || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
 
 129     $self->_input_to_hash($input);
 
 131     $main::lxdebug->leave_sub(2);
 
 135   my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr, $previous);
 
 137   my $boundary = '--' . $1;
 
 139   foreach my $line (split m/\n/, $input) {
 
 140     last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
 
 142     if (($line eq $boundary) || ($line eq "$boundary\r")) {
 
 143       ${ $previous } =~ s|\r?\n$|| if $previous;
 
 149       $content_type   = "text/plain";
 
 156     next unless $boundary_found;
 
 158     if (!$headers_done) {
 
 159       $line =~ s/[\r\n]*$//;
 
 166       if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
 
 167         if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
 
 169           substr $line, $-[0], $+[0] - $-[0], "";
 
 172         if ($line =~ m|name\s*=\s*"(.*?)"|i) {
 
 174           substr $line, $-[0], $+[0] - $-[0], "";
 
 177         $previous         = $self->_store_value($name, '') if ($name);
 
 178         $self->{FILENAME} = $filename if ($filename);
 
 183       if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
 
 190     next unless $previous;
 
 192     ${ $previous } .= "${line}\n";
 
 195   ${ $previous } =~ s|\r?\n$|| if $previous;
 
 197   $main::lxdebug->leave_sub(2);
 
 200 sub _recode_recursively {
 
 201   $main::lxdebug->enter_sub();
 
 202   my ($iconv, $param) = @_;
 
 204   if (any { ref $param eq $_ } qw(Form HASH)) {
 
 205     foreach my $key (keys %{ $param }) {
 
 206       if (!ref $param->{$key}) {
 
 207         # Workaround for a bug: converting $param->{$key} directly
 
 208         # leads to 'undef'. I don't know why. Converting a copy works,
 
 210         $param->{$key} = $iconv->convert("" . $param->{$key});
 
 212         _recode_recursively($iconv, $param->{$key});
 
 216   } elsif (ref $param eq 'ARRAY') {
 
 217     foreach my $idx (0 .. scalar(@{ $param }) - 1) {
 
 218       if (!ref $param->[$idx]) {
 
 219         # Workaround for a bug: converting $param->[$idx] directly
 
 220         # leads to 'undef'. I don't know why. Converting a copy works,
 
 222         $param->[$idx] = $iconv->convert("" . $param->[$idx]);
 
 224         _recode_recursively($iconv, $param->[$idx]);
 
 228   $main::lxdebug->leave_sub();
 
 232   $main::lxdebug->enter_sub();
 
 238   if ($LXDebug::watch_form) {
 
 239     require SL::Watchdog;
 
 240     tie %{ $self }, 'SL::Watchdog';
 
 243   read(STDIN, $_, $ENV{CONTENT_LENGTH});
 
 245   if ($ENV{QUERY_STRING}) {
 
 246     $_ = $ENV{QUERY_STRING};
 
 255   $self->_request_to_hash($_);
 
 257   my $db_charset   = $main::dbcharset;
 
 258   $db_charset    ||= Common::DEFAULT_CHARSET;
 
 260   if ($self->{INPUT_ENCODING}) {
 
 261     if (lc $self->{INPUT_ENCODING} ne lc $db_charset) {
 
 263       my $iconv = Text::Iconv->new($self->{INPUT_ENCODING}, $db_charset);
 
 265       _recode_recursively($iconv, $self);
 
 268     delete $self->{INPUT_ENCODING};
 
 271   $self->{action}  =  lc $self->{action};
 
 272   $self->{action}  =~ s/( |-|,|\#)/_/g;
 
 274   $self->{version} =  "2.6.1";
 
 276   $main::lxdebug->leave_sub();
 
 281 sub _flatten_variables_rec {
 
 282   $main::lxdebug->enter_sub(2);
 
 291   if ('' eq ref $curr->{$key}) {
 
 292     @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
 
 294   } elsif ('HASH' eq ref $curr->{$key}) {
 
 295     foreach my $hash_key (sort keys %{ $curr->{$key} }) {
 
 296       push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
 
 300     foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
 
 301       my $first_array_entry = 1;
 
 303       foreach my $hash_key (sort keys %{ $curr->{$key}->[$idx] }) {
 
 304         push @result, $self->_flatten_variables_rec($curr->{$key}->[$idx], $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
 
 305         $first_array_entry = 0;
 
 310   $main::lxdebug->leave_sub(2);
 
 315 sub flatten_variables {
 
 316   $main::lxdebug->enter_sub(2);
 
 324     push @variables, $self->_flatten_variables_rec($self, '', $_);
 
 327   $main::lxdebug->leave_sub(2);
 
 332 sub flatten_standard_variables {
 
 333   $main::lxdebug->enter_sub(2);
 
 336   my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar version), @_);
 
 340   foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
 
 341     push @variables, $self->_flatten_variables_rec($self, '', $_);
 
 344   $main::lxdebug->leave_sub(2);
 
 350   $main::lxdebug->enter_sub();
 
 356   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
 
 358   $main::lxdebug->leave_sub();
 
 362   $main::lxdebug->enter_sub(2);
 
 365   my $password      = $self->{password};
 
 367   $self->{password} = 'X' x 8;
 
 369   local $Data::Dumper::Sortkeys = 1;
 
 370   my $output                    = Dumper($self);
 
 372   $self->{password} = $password;
 
 374   $main::lxdebug->leave_sub(2);
 
 380   $main::lxdebug->enter_sub(2);
 
 382   my ($self, $str) = @_;
 
 384   $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
 
 386   $main::lxdebug->leave_sub(2);
 
 392   $main::lxdebug->enter_sub(2);
 
 394   my ($self, $str) = @_;
 
 399   $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
 
 401   $main::lxdebug->leave_sub(2);
 
 407   $main::lxdebug->enter_sub();
 
 408   my ($self, $str) = @_;
 
 410   if ($str && !ref($str)) {
 
 411     $str =~ s/\"/"/g;
 
 414   $main::lxdebug->leave_sub();
 
 420   $main::lxdebug->enter_sub();
 
 421   my ($self, $str) = @_;
 
 423   if ($str && !ref($str)) {
 
 424     $str =~ s/"/\"/g;
 
 427   $main::lxdebug->leave_sub();
 
 433   $main::lxdebug->enter_sub();
 
 437     map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
 
 439     for (sort keys %$self) {
 
 440       next if (($_ eq "header") || (ref($self->{$_}) ne ""));
 
 441       print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
 
 444   $main::lxdebug->leave_sub();
 
 448   $main::lxdebug->enter_sub();
 
 450   $main::lxdebug->show_backtrace();
 
 452   my ($self, $msg) = @_;
 
 453   if ($ENV{HTTP_USER_AGENT}) {
 
 455     $self->show_generic_error($msg);
 
 462   $main::lxdebug->leave_sub();
 
 466   $main::lxdebug->enter_sub();
 
 468   my ($self, $msg) = @_;
 
 470   if ($ENV{HTTP_USER_AGENT}) {
 
 473     if (!$self->{header}) {
 
 486     if ($self->{info_function}) {
 
 487       &{ $self->{info_function} }($msg);
 
 493   $main::lxdebug->leave_sub();
 
 496 # calculates the number of rows in a textarea based on the content and column number
 
 497 # can be capped with maxrows
 
 499   $main::lxdebug->enter_sub();
 
 500   my ($self, $str, $cols, $maxrows, $minrows) = @_;
 
 504   my $rows   = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
 
 507   $main::lxdebug->leave_sub();
 
 509   return max(min($rows, $maxrows), $minrows);
 
 513   $main::lxdebug->enter_sub();
 
 515   my ($self, $msg) = @_;
 
 517   $self->error("$msg\n" . $DBI::errstr);
 
 519   $main::lxdebug->leave_sub();
 
 523   $main::lxdebug->enter_sub();
 
 525   my ($self, $name, $msg) = @_;
 
 528   foreach my $part (split m/\./, $name) {
 
 529     if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
 
 532     $curr = $curr->{$part};
 
 535   $main::lxdebug->leave_sub();
 
 538 sub _get_request_uri {
 
 541   return URI->new($ENV{HTTP_REFERER})->canonical() if $ENV{HTTP_X_FORWARDED_FOR};
 
 543   my $scheme =  $ENV{HTTPS} && (lc $ENV{HTTPS} eq 'on') ? 'https' : 'http';
 
 544   my $port   =  $ENV{SERVER_PORT} || '';
 
 545   $port      =  undef if (($scheme eq 'http' ) && ($port == 80))
 
 546                       || (($scheme eq 'https') && ($port == 443));
 
 548   my $uri    =  URI->new("${scheme}://");
 
 549   $uri->scheme($scheme);
 
 551   $uri->host($ENV{HTTP_HOST} || $ENV{SERVER_ADDR});
 
 552   $uri->path_query($ENV{REQUEST_URI});
 
 558 sub create_http_response {
 
 559   $main::lxdebug->enter_sub();
 
 564   my $cgi      = $main::cgi;
 
 565   $cgi       ||= CGI->new('');
 
 568   if (defined $main::auth) {
 
 569     my $uri      = $self->_get_request_uri;
 
 570     my @segments = $uri->path_segments;
 
 572     $uri->path_segments(@segments);
 
 574     my $session_cookie_value   = $main::auth->get_session_id();
 
 575     $session_cookie_value    ||= 'NO_SESSION';
 
 577     $session_cookie = $cgi->cookie('-name'   => $main::auth->get_session_cookie_name(),
 
 578                                    '-value'  => $session_cookie_value,
 
 579                                    '-path'   => $uri->path,
 
 580                                    '-secure' => $ENV{HTTPS});
 
 583   my %cgi_params = ('-type' => $params{content_type});
 
 584   $cgi_params{'-charset'} = $params{charset} if ($params{charset});
 
 586   my $output = $cgi->header('-cookie' => $session_cookie,
 
 589   $main::lxdebug->leave_sub();
 
 596   $main::lxdebug->enter_sub();
 
 598   # extra code ist currently only used by menuv3 and menuv4 to set their css.
 
 599   # it is strongly deprecated, and will be changed in a future version.
 
 600   my ($self, $extra_code) = @_;
 
 602   if ($self->{header}) {
 
 603     $main::lxdebug->leave_sub();
 
 607   my ($stylesheet, $favicon, $pagelayout);
 
 609   if ($ENV{HTTP_USER_AGENT}) {
 
 612     if ($ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+\d/) {
 
 613       # Only set the DOCTYPE for Internet Explorer. Other browsers have problems displaying the menu otherwise.
 
 614       $doctype = qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n|;
 
 617     my $stylesheets = "$self->{stylesheet} $self->{stylesheets}";
 
 619     $stylesheets =~ s|^\s*||;
 
 620     $stylesheets =~ s|\s*$||;
 
 621     foreach my $file (split m/\s+/, $stylesheets) {
 
 623       next if (! -f "css/$file");
 
 625       $stylesheet .= qq|<link rel="stylesheet" href="css/$file" TYPE="text/css" TITLE="Lx-Office stylesheet">\n|;
 
 628     $self->{favicon}    = "favicon.ico" unless $self->{favicon};
 
 630     if ($self->{favicon} && (-f "$self->{favicon}")) {
 
 632         qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
 
 636     my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
 638     if ($self->{landscape}) {
 
 639       $pagelayout = qq|<style type="text/css">
 
 640                         \@page { size:landscape; }
 
 645     <script type="text/javascript">
 
 648         document.$self->{fokus}.focus();
 
 652     | if $self->{"fokus"};
 
 656     if ($self->{jsscript} == 1) {
 
 659         <script type="text/javascript" src="js/jquery.js"></script>
 
 660         <script type="text/javascript" src="js/common.js"></script>
 
 661         <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
 
 662         <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
 
 663         <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
 
 664         <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
 
 671       ? "$self->{title} - $self->{titlebar}"
 
 674     for my $item (@ { $self->{AJAX} || [] }) {
 
 675       $ajax .= $item->show_javascript();
 
 678     print $self->create_http_response('content_type' => 'text/html',
 
 679                                       'charset'      => $db_charset,);
 
 680     print qq|${doctype}<html>
 
 682   <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
 
 683   <title>$self->{titlebar}</title>
 
 692   <link rel="stylesheet" href="css/jquery.autocomplete.css" type="text/css" />
 
 694   <meta name="robots" content="noindex,nofollow" />
 
 695   <script type="text/javascript" src="js/highlight_input.js"></script>
 
 697   <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
 
 698   <script type="text/javascript" src="js/tabcontent.js">
 
 700   /***********************************************
 
 701    * Tab Content script v2.2- Â© Dynamic Drive DHTML code library (www.dynamicdrive.com)
 
 702    * This notice MUST stay intact for legal use
 
 703    * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
 
 704    ***********************************************/
 
 715   $main::lxdebug->leave_sub();
 
 718 sub ajax_response_header {
 
 719   $main::lxdebug->enter_sub();
 
 723   my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
 724   my $cgi        = $main::cgi || CGI->new('');
 
 725   my $output     = $cgi->header('-charset' => $db_charset);
 
 727   $main::lxdebug->leave_sub();
 
 732 sub redirect_header {
 
 736   my $base_uri = $self->_get_request_uri;
 
 737   my $new_uri  = URI->new_abs($new_url, $base_uri);
 
 739   die "Headers already sent" if $::self->{header};
 
 742   my $cgi = $main::cgi || CGI->new('');
 
 743   return $cgi->redirect($new_uri);
 
 746 sub _prepare_html_template {
 
 747   $main::lxdebug->enter_sub();
 
 749   my ($self, $file, $additional_params) = @_;
 
 752   if (!%::myconfig || !$::myconfig{"countrycode"}) {
 
 753     $language = $main::language;
 
 755     $language = $main::myconfig{"countrycode"};
 
 757   $language = "de" unless ($language);
 
 759   if (-f "templates/webpages/${file}.html") {
 
 760     if ((-f ".developer") && ((stat("templates/webpages/${file}.html"))[9] > (stat("locale/${language}/all"))[9])) {
 
 761       my $info = "Developer information: templates/webpages/${file}.html is newer than the translation file locale/${language}/all.\n" .
 
 762         "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 763       print(qq|<pre>$info</pre>|);
 
 767     $file = "templates/webpages/${file}.html";
 
 770     my $info = "Web page template '${file}' not found.\n" .
 
 771       "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 772     print(qq|<pre>$info</pre>|);
 
 776   if ($self->{"DEBUG"}) {
 
 777     $additional_params->{"DEBUG"} = $self->{"DEBUG"};
 
 780   if ($additional_params->{"DEBUG"}) {
 
 781     $additional_params->{"DEBUG"} =
 
 782       "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
 
 785   if (%main::myconfig) {
 
 786     map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
 
 787     my $jsc_dateformat = $main::myconfig{"dateformat"};
 
 788     $jsc_dateformat =~ s/d+/\%d/gi;
 
 789     $jsc_dateformat =~ s/m+/\%m/gi;
 
 790     $jsc_dateformat =~ s/y+/\%Y/gi;
 
 791     $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
 
 792     $additional_params->{"myconfig"} ||= \%::myconfig;
 
 795   $additional_params->{"conf_dbcharset"}              = $main::dbcharset;
 
 796   $additional_params->{"conf_webdav"}                 = $main::webdav;
 
 797   $additional_params->{"conf_lizenzen"}               = $main::lizenzen;
 
 798   $additional_params->{"conf_latex_templates"}        = $main::latex;
 
 799   $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
 
 800   $additional_params->{"conf_vertreter"}              = $main::vertreter;
 
 801   $additional_params->{"conf_show_best_before"}       = $main::show_best_before;
 
 803   if (%main::debug_options) {
 
 804     map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
 
 807   if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
 
 808     while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
 
 809       $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
 
 813   $main::lxdebug->leave_sub();
 
 818 sub parse_html_template {
 
 819   $main::lxdebug->enter_sub();
 
 821   my ($self, $file, $additional_params) = @_;
 
 823   $additional_params ||= { };
 
 825   $file = $self->_prepare_html_template($file, $additional_params);
 
 827   my $template = Template->new({ 'INTERPOLATE'  => 0,
 
 831                                  'PLUGIN_BASE'  => 'SL::Template::Plugin',
 
 832                                  'INCLUDE_PATH' => '.:templates/webpages',
 
 835   map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
 
 837   my $in = IO::File->new($file, 'r');
 
 840     print STDERR "Error opening template file: $!";
 
 841     $main::lxdebug->leave_sub();
 
 845   my $input = join('', <$in>);
 
 849   if (!$template->process(\$input, $additional_params, \$output)) {
 
 850     print STDERR $template->error();
 
 853   $main::lxdebug->leave_sub();
 
 858 sub show_generic_error {
 
 859   $main::lxdebug->enter_sub();
 
 861   my ($self, $error, %params) = @_;
 
 864     'title_error' => $params{title},
 
 865     'label_error' => $error,
 
 868   if ($params{action}) {
 
 871     map { delete($self->{$_}); } qw(action);
 
 872     map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
 
 874     $add_params->{SHOW_BUTTON}  = 1;
 
 875     $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
 
 876     $add_params->{VARIABLES}    = \@vars;
 
 878   } elsif ($params{back_button}) {
 
 879     $add_params->{SHOW_BACK_BUTTON} = 1;
 
 882   $self->{title} = $params{title} if $params{title};
 
 885   print $self->parse_html_template("generic/error", $add_params);
 
 887   $main::lxdebug->leave_sub();
 
 889   die("Error: $error\n");
 
 892 sub show_generic_information {
 
 893   $main::lxdebug->enter_sub();
 
 895   my ($self, $text, $title) = @_;
 
 898     'title_information' => $title,
 
 899     'label_information' => $text,
 
 902   $self->{title} = $title if ($title);
 
 905   print $self->parse_html_template("generic/information", $add_params);
 
 907   $main::lxdebug->leave_sub();
 
 909   die("Information: $text\n");
 
 912 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
 
 913 # changed it to accept an arbitrary number of triggers - sschoeling
 
 915   $main::lxdebug->enter_sub();
 
 918   my $myconfig = shift;
 
 921   # set dateform for jsscript
 
 924     "dd.mm.yy" => "%d.%m.%Y",
 
 925     "dd-mm-yy" => "%d-%m-%Y",
 
 926     "dd/mm/yy" => "%d/%m/%Y",
 
 927     "mm/dd/yy" => "%m/%d/%Y",
 
 928     "mm-dd-yy" => "%m-%d-%Y",
 
 929     "yyyy-mm-dd" => "%Y-%m-%d",
 
 932   my $ifFormat = defined($dateformats{$myconfig->{"dateformat"}}) ?
 
 933     $dateformats{$myconfig->{"dateformat"}} : "%d.%m.%Y";
 
 940       inputField : "| . (shift) . qq|",
 
 941       ifFormat :"$ifFormat",
 
 942       align : "| .  (shift) . qq|",
 
 943       button : "| . (shift) . qq|"
 
 949        <script type="text/javascript">
 
 950        <!--| . join("", @triggers) . qq|//-->
 
 954   $main::lxdebug->leave_sub();
 
 957 }    #end sub write_trigger
 
 960   $main::lxdebug->enter_sub();
 
 962   my ($self, $msg) = @_;
 
 964   if ($self->{callback}) {
 
 966     my ($script, $argv) = split(/\?/, $self->{callback}, 2);
 
 968     $script =~ s|[^a-zA-Z0-9_\.]||g;
 
 969     exec("perl", "$script", $argv);
 
 977   $main::lxdebug->leave_sub();
 
 980 # sort of columns removed - empty sub
 
 982   $main::lxdebug->enter_sub();
 
 984   my ($self, @columns) = @_;
 
 986   $main::lxdebug->leave_sub();
 
 992   $main::lxdebug->enter_sub(2);
 
 994   my ($self, $myconfig, $amount, $places, $dash) = @_;
 
1000   # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
 
1002   my $neg = ($amount =~ s/^-//);
 
1003   my $exp = ($amount =~ m/[e]/) ? 1 : 0;
 
1005   if (defined($places) && ($places ne '')) {
 
1011         my ($actual_places) = ($amount =~ /\.(\d+)/);
 
1012         $actual_places = length($actual_places);
 
1013         $places = $actual_places > $places ? $actual_places : $places;
 
1016     $amount = $self->round_amount($amount, $places);
 
1019   my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
 
1020   my @p = split(/\./, $amount); # split amount at decimal point
 
1022   $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
 
1025   $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
 
1028     ($dash =~ /-/)    ? ($neg ? "($amount)"                            : "$amount" )                              :
 
1029     ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
 
1030                         ($neg ? "-$amount"                             : "$amount" )                              ;
 
1034   $main::lxdebug->leave_sub(2);
 
1038 sub format_amount_units {
 
1039   $main::lxdebug->enter_sub();
 
1044   my $myconfig         = \%main::myconfig;
 
1045   my $amount           = $params{amount} * 1;
 
1046   my $places           = $params{places};
 
1047   my $part_unit_name   = $params{part_unit};
 
1048   my $amount_unit_name = $params{amount_unit};
 
1049   my $conv_units       = $params{conv_units};
 
1050   my $max_places       = $params{max_places};
 
1052   if (!$part_unit_name) {
 
1053     $main::lxdebug->leave_sub();
 
1057   AM->retrieve_all_units();
 
1058   my $all_units        = $main::all_units;
 
1060   if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
 
1061     $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
 
1064   if (!scalar @{ $conv_units }) {
 
1065     my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
 
1066     $main::lxdebug->leave_sub();
 
1070   my $part_unit  = $all_units->{$part_unit_name};
 
1071   my $conv_unit  = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
 
1073   $amount       *= $conv_unit->{factor};
 
1078   foreach my $unit (@$conv_units) {
 
1079     my $last = $unit->{name} eq $part_unit->{name};
 
1081       $num     = int($amount / $unit->{factor});
 
1082       $amount -= $num * $unit->{factor};
 
1085     if ($last ? $amount : $num) {
 
1086       push @values, { "unit"   => $unit->{name},
 
1087                       "amount" => $last ? $amount / $unit->{factor} : $num,
 
1088                       "places" => $last ? $places : 0 };
 
1095     push @values, { "unit"   => $part_unit_name,
 
1100   my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
 
1102   $main::lxdebug->leave_sub();
 
1108   $main::lxdebug->enter_sub(2);
 
1113   $input =~ s/(^|[^\#]) \#  (\d+)  /$1$_[$2 - 1]/gx;
 
1114   $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
 
1115   $input =~ s/\#\#/\#/g;
 
1117   $main::lxdebug->leave_sub(2);
 
1125   $main::lxdebug->enter_sub(2);
 
1127   my ($self, $myconfig, $amount) = @_;
 
1129   if (   ($myconfig->{numberformat} eq '1.000,00')
 
1130       || ($myconfig->{numberformat} eq '1000,00')) {
 
1135   if ($myconfig->{numberformat} eq "1'000.00") {
 
1141   $main::lxdebug->leave_sub(2);
 
1143   return ($amount * 1);
 
1147   $main::lxdebug->enter_sub(2);
 
1149   my ($self, $amount, $places) = @_;
 
1152   # Rounding like "Kaufmannsrunden" (see http://de.wikipedia.org/wiki/Rundung )
 
1154   # Round amounts to eight places before rounding to the requested
 
1155   # number of places. This gets rid of errors due to internal floating
 
1156   # point representation.
 
1157   $amount       = $self->round_amount($amount, 8) if $places < 8;
 
1158   $amount       = $amount * (10**($places));
 
1159   $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
 
1161   $main::lxdebug->leave_sub(2);
 
1163   return $round_amount;
 
1167 sub parse_template {
 
1168   $main::lxdebug->enter_sub();
 
1170   my ($self, $myconfig, $userspath) = @_;
 
1171   my ($template, $out);
 
1175   $self->{"cwd"} = getcwd();
 
1176   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
 
1180   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
 
1181     $template       = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1182     $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
 
1184   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
 
1185     $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
 
1186     $template         = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1187     $ext_for_format   = 'pdf';
 
1189   } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
 
1190     $template       = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1191     $ext_for_format = 'html';
 
1193   } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
 
1194     $template       = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1195     $ext_for_format = 'xml';
 
1197   } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
 
1198     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1200   } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
 
1201     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1203   } elsif ( $self->{"format"} =~ /excel/i ) {
 
1204     $template = ExcelTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1205     $ext_for_format = 'xls';
 
1207   } elsif ( defined $self->{'format'}) {
 
1208     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
 
1210   } elsif ( $self->{'format'} eq '' ) {
 
1211     $self->error("No Outputformat given: $self->{'format'}");
 
1213   } else { #Catch the rest
 
1214     $self->error("Outputformat not defined: $self->{'format'}");
 
1217   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
 
1218   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
 
1220   if (!$self->{employee_id}) {
 
1221     map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
 
1224   map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
 
1226   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
 
1228   # OUT is used for the media, screen, printer, email
 
1229   # for postscript we store a copy in a temporary file
 
1231   my $prepend_userspath;
 
1233   if (!$self->{tmpfile}) {
 
1234     $self->{tmpfile}   = "${fileid}.$self->{IN}";
 
1235     $prepend_userspath = 1;
 
1238   $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
 
1240   $self->{tmpfile} =~ s|.*/||;
 
1241   $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
 
1242   $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
 
1244   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
1245     $out = $self->{OUT};
 
1246     $self->{OUT} = ">$self->{tmpfile}";
 
1250     open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
 
1252     open(OUT, ">-") or $self->error("STDOUT : $!");
 
1256   if (!$template->parse(*OUT)) {
 
1258     $self->error("$self->{IN} : " . $template->get_error());
 
1263   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
1265     if ($self->{media} eq 'email') {
 
1267       my $mail = new Mailer;
 
1269       map { $mail->{$_} = $self->{$_} }
 
1270         qw(cc bcc subject message version format);
 
1271       $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
1272       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
 
1273       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
 
1274       $mail->{fileid} = "$fileid.";
 
1275       $myconfig->{signature} =~ s/\r//g;
 
1277       # if we send html or plain text inline
 
1278       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
 
1279         $mail->{contenttype} = "text/html";
 
1281         $mail->{message}       =~ s/\r//g;
 
1282         $mail->{message}       =~ s/\n/<br>\n/g;
 
1283         $myconfig->{signature} =~ s/\n/<br>\n/g;
 
1284         $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
 
1286         open(IN, $self->{tmpfile})
 
1287           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1289           $mail->{message} .= $_;
 
1296         if (!$self->{"do_not_attach"}) {
 
1297           my $attachment_name  =  $self->{attachment_filename} || $self->{tmpfile};
 
1298           $attachment_name     =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
 
1299           $mail->{attachments} =  [{ "filename" => $self->{tmpfile},
 
1300                                      "name"     => $attachment_name }];
 
1303         $mail->{message}  =~ s/\r//g;
 
1304         $mail->{message} .=  "\n-- \n$myconfig->{signature}";
 
1308       my $err = $mail->send();
 
1309       $self->error($self->cleanup . "$err") if ($err);
 
1313       $self->{OUT} = $out;
 
1315       my $numbytes = (-s $self->{tmpfile});
 
1316       open(IN, $self->{tmpfile})
 
1317         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1319       $self->{copies} = 1 unless $self->{media} eq 'printer';
 
1321       chdir("$self->{cwd}");
 
1322       #print(STDERR "Kopien $self->{copies}\n");
 
1323       #print(STDERR "OUT $self->{OUT}\n");
 
1324       for my $i (1 .. $self->{copies}) {
 
1326           open(OUT, $self->{OUT})
 
1327             or $self->error($self->cleanup . "$self->{OUT} : $!");
 
1329           $self->{attachment_filename} = ($self->{attachment_filename})
 
1330                                        ? $self->{attachment_filename}
 
1331                                        : $self->generate_attachment_filename();
 
1333           # launch application
 
1334           print qq|Content-Type: | . $template->get_mime_type() . qq|
 
1335 Content-Disposition: attachment; filename="$self->{attachment_filename}"
 
1336 Content-Length: $numbytes
 
1340           open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
 
1361   chdir("$self->{cwd}");
 
1362   $main::lxdebug->leave_sub();
 
1365 sub get_formname_translation {
 
1366   $main::lxdebug->enter_sub();
 
1367   my ($self, $formname) = @_;
 
1369   $formname ||= $self->{formname};
 
1371   my %formname_translations = (
 
1372     bin_list                => $main::locale->text('Bin List'),
 
1373     credit_note             => $main::locale->text('Credit Note'),
 
1374     invoice                 => $main::locale->text('Invoice'),
 
1375     packing_list            => $main::locale->text('Packing List'),
 
1376     pick_list               => $main::locale->text('Pick List'),
 
1377     proforma                => $main::locale->text('Proforma Invoice'),
 
1378     purchase_order          => $main::locale->text('Purchase Order'),
 
1379     request_quotation       => $main::locale->text('RFQ'),
 
1380     sales_order             => $main::locale->text('Confirmation'),
 
1381     sales_quotation         => $main::locale->text('Quotation'),
 
1382     storno_invoice          => $main::locale->text('Storno Invoice'),
 
1383     storno_packing_list     => $main::locale->text('Storno Packing List'),
 
1384     sales_delivery_order    => $main::locale->text('Delivery Order'),
 
1385     purchase_delivery_order => $main::locale->text('Delivery Order'),
 
1386     dunning                 => $main::locale->text('Dunning'),
 
1389   $main::lxdebug->leave_sub();
 
1390   return $formname_translations{$formname}
 
1393 sub get_number_prefix_for_type {
 
1394   $main::lxdebug->enter_sub();
 
1398       (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
 
1399     : ($self->{type} =~ /_quotation$/)                        ? 'quo'
 
1400     : ($self->{type} =~ /_delivery_order$/)                   ? 'do'
 
1403   $main::lxdebug->leave_sub();
 
1407 sub get_extension_for_format {
 
1408   $main::lxdebug->enter_sub();
 
1411   my $extension = $self->{format} =~ /pdf/i          ? ".pdf"
 
1412                 : $self->{format} =~ /postscript/i   ? ".ps"
 
1413                 : $self->{format} =~ /opendocument/i ? ".odt"
 
1414                 : $self->{format} =~ /excel/i        ? ".xls"
 
1415                 : $self->{format} =~ /html/i         ? ".html"
 
1418   $main::lxdebug->leave_sub();
 
1422 sub generate_attachment_filename {
 
1423   $main::lxdebug->enter_sub();
 
1426   my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
 
1427   my $prefix              = $self->get_number_prefix_for_type();
 
1429   if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
 
1430     $attachment_filename .= ' (' . $main::locale->text('Preview') . ')' . $self->get_extension_for_format();
 
1432   } elsif ($attachment_filename && $self->{"${prefix}number"}) {
 
1433     $attachment_filename .=  "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
 
1436     $attachment_filename = "";
 
1439   $attachment_filename =  $main::locale->quote_special_chars('filenames', $attachment_filename);
 
1440   $attachment_filename =~ s|[\s/\\]+|_|g;
 
1442   $main::lxdebug->leave_sub();
 
1443   return $attachment_filename;
 
1446 sub generate_email_subject {
 
1447   $main::lxdebug->enter_sub();
 
1450   my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
 
1451   my $prefix  = $self->get_number_prefix_for_type();
 
1453   if ($subject && $self->{"${prefix}number"}) {
 
1454     $subject .= " " . $self->{"${prefix}number"}
 
1457   $main::lxdebug->leave_sub();
 
1462   $main::lxdebug->enter_sub();
 
1466   chdir("$self->{tmpdir}");
 
1469   if (-f "$self->{tmpfile}.err") {
 
1470     open(FH, "$self->{tmpfile}.err");
 
1475   if ($self->{tmpfile} && ! $::keep_temp_files) {
 
1476     $self->{tmpfile} =~ s|.*/||g;
 
1478     $self->{tmpfile} =~ s/\.\w+$//g;
 
1479     my $tmpfile = $self->{tmpfile};
 
1480     unlink(<$tmpfile.*>);
 
1483   chdir("$self->{cwd}");
 
1485   $main::lxdebug->leave_sub();
 
1491   $main::lxdebug->enter_sub();
 
1493   my ($self, $date, $myconfig) = @_;
 
1496   if ($date && $date =~ /\D/) {
 
1498     if ($myconfig->{dateformat} =~ /^yy/) {
 
1499       ($yy, $mm, $dd) = split /\D/, $date;
 
1501     if ($myconfig->{dateformat} =~ /^mm/) {
 
1502       ($mm, $dd, $yy) = split /\D/, $date;
 
1504     if ($myconfig->{dateformat} =~ /^dd/) {
 
1505       ($dd, $mm, $yy) = split /\D/, $date;
 
1510     $yy = ($yy < 70) ? $yy + 2000 : $yy;
 
1511     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
 
1513     $dd = "0$dd" if ($dd < 10);
 
1514     $mm = "0$mm" if ($mm < 10);
 
1516     $date = "$yy$mm$dd";
 
1519   $main::lxdebug->leave_sub();
 
1524 # Database routines used throughout
 
1527   $main::lxdebug->enter_sub(2);
 
1529   my ($self, $myconfig) = @_;
 
1531   # connect to database
 
1533     DBI->connect($myconfig->{dbconnect},
 
1534                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
 
1538   if ($myconfig->{dboptions}) {
 
1539     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1542   $main::lxdebug->leave_sub(2);
 
1547 sub dbconnect_noauto {
 
1548   $main::lxdebug->enter_sub();
 
1550   my ($self, $myconfig) = @_;
 
1552   # connect to database
 
1554     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
 
1555                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
 
1559   if ($myconfig->{dboptions}) {
 
1560     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1563   $main::lxdebug->leave_sub();
 
1568 sub get_standard_dbh {
 
1569   $main::lxdebug->enter_sub(2);
 
1571   my ($self, $myconfig) = @_;
 
1573   if ($standard_dbh && !$standard_dbh->{Active}) {
 
1574     $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
 
1575     undef $standard_dbh;
 
1578   $standard_dbh ||= $self->dbconnect_noauto($myconfig);
 
1580   $main::lxdebug->leave_sub(2);
 
1582   return $standard_dbh;
 
1586   $main::lxdebug->enter_sub();
 
1588   my ($self, $date, $myconfig) = @_;
 
1589   my $dbh = $self->dbconnect($myconfig);
 
1591   my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
 
1592   my $sth = prepare_execute_query($self, $dbh, $query, $date);
 
1593   my ($closed) = $sth->fetchrow_array;
 
1595   $main::lxdebug->leave_sub();
 
1600 sub update_balance {
 
1601   $main::lxdebug->enter_sub();
 
1603   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
 
1605   # if we have a value, go do it
 
1608     # retrieve balance from table
 
1609     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
 
1610     my $sth = prepare_execute_query($self, $dbh, $query, @values);
 
1611     my ($balance) = $sth->fetchrow_array;
 
1617     $query = "UPDATE $table SET $field = $balance WHERE $where";
 
1618     do_query($self, $dbh, $query, @values);
 
1620   $main::lxdebug->leave_sub();
 
1623 sub update_exchangerate {
 
1624   $main::lxdebug->enter_sub();
 
1626   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
 
1628   # some sanity check for currency
 
1630     $main::lxdebug->leave_sub();
 
1633   $query = qq|SELECT curr FROM defaults|;
 
1635   my ($currency) = selectrow_query($self, $dbh, $query);
 
1636   my ($defaultcurrency) = split m/:/, $currency;
 
1639   if ($curr eq $defaultcurrency) {
 
1640     $main::lxdebug->leave_sub();
 
1644   $query = qq|SELECT e.curr FROM exchangerate e
 
1645                  WHERE e.curr = ? AND e.transdate = ?
 
1647   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
 
1656   $buy = conv_i($buy, "NULL");
 
1657   $sell = conv_i($sell, "NULL");
 
1660   if ($buy != 0 && $sell != 0) {
 
1661     $set = "buy = $buy, sell = $sell";
 
1662   } elsif ($buy != 0) {
 
1663     $set = "buy = $buy";
 
1664   } elsif ($sell != 0) {
 
1665     $set = "sell = $sell";
 
1668   if ($sth->fetchrow_array) {
 
1669     $query = qq|UPDATE exchangerate
 
1675     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
 
1676                 VALUES (?, $buy, $sell, ?)|;
 
1679   do_query($self, $dbh, $query, $curr, $transdate);
 
1681   $main::lxdebug->leave_sub();
 
1684 sub save_exchangerate {
 
1685   $main::lxdebug->enter_sub();
 
1687   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
 
1689   my $dbh = $self->dbconnect($myconfig);
 
1693   $buy  = $rate if $fld eq 'buy';
 
1694   $sell = $rate if $fld eq 'sell';
 
1697   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
 
1702   $main::lxdebug->leave_sub();
 
1705 sub get_exchangerate {
 
1706   $main::lxdebug->enter_sub();
 
1708   my ($self, $dbh, $curr, $transdate, $fld) = @_;
 
1711   unless ($transdate) {
 
1712     $main::lxdebug->leave_sub();
 
1716   $query = qq|SELECT curr FROM defaults|;
 
1718   my ($currency) = selectrow_query($self, $dbh, $query);
 
1719   my ($defaultcurrency) = split m/:/, $currency;
 
1721   if ($currency eq $defaultcurrency) {
 
1722     $main::lxdebug->leave_sub();
 
1726   $query = qq|SELECT e.$fld FROM exchangerate e
 
1727                  WHERE e.curr = ? AND e.transdate = ?|;
 
1728   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
 
1732   $main::lxdebug->leave_sub();
 
1734   return $exchangerate;
 
1737 sub check_exchangerate {
 
1738   $main::lxdebug->enter_sub();
 
1740   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
 
1742   if ($fld !~/^buy|sell$/) {
 
1743     $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
 
1746   unless ($transdate) {
 
1747     $main::lxdebug->leave_sub();
 
1751   my ($defaultcurrency) = $self->get_default_currency($myconfig);
 
1753   if ($currency eq $defaultcurrency) {
 
1754     $main::lxdebug->leave_sub();
 
1758   my $dbh   = $self->get_standard_dbh($myconfig);
 
1759   my $query = qq|SELECT e.$fld FROM exchangerate e
 
1760                  WHERE e.curr = ? AND e.transdate = ?|;
 
1762   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
 
1764   $main::lxdebug->leave_sub();
 
1766   return $exchangerate;
 
1769 sub get_all_currencies {
 
1770   $main::lxdebug->enter_sub();
 
1772   my ($self, $myconfig) = @_;
 
1773   my $dbh = $self->get_standard_dbh($myconfig);
 
1775   my $query = qq|SELECT curr FROM defaults|;
 
1777   my ($curr)     = selectrow_query($self, $dbh, $query);
 
1778   my @currencies = grep { $_ } map { s/\s//g; $_ } split m/:/, $curr;
 
1780   $main::lxdebug->leave_sub();
 
1785 sub get_default_currency {
 
1786   $main::lxdebug->enter_sub();
 
1788   my ($self, $myconfig) = @_;
 
1789   my @currencies        = $self->get_all_currencies($myconfig);
 
1791   $main::lxdebug->leave_sub();
 
1793   return $currencies[0];
 
1796 sub set_payment_options {
 
1797   $main::lxdebug->enter_sub();
 
1799   my ($self, $myconfig, $transdate) = @_;
 
1801   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
 
1803   my $dbh = $self->get_standard_dbh($myconfig);
 
1806     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
 
1807     qq|FROM payment_terms p | .
 
1810   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
 
1811    $self->{payment_terms}) =
 
1812      selectrow_query($self, $dbh, $query, $self->{payment_id});
 
1814   if ($transdate eq "") {
 
1815     if ($self->{invdate}) {
 
1816       $transdate = $self->{invdate};
 
1818       $transdate = $self->{transdate};
 
1823     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
 
1824     qq|FROM payment_terms|;
 
1825   ($self->{netto_date}, $self->{skonto_date}) =
 
1826     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
 
1828   my ($invtotal, $total);
 
1829   my (%amounts, %formatted_amounts);
 
1831   if ($self->{type} =~ /_order$/) {
 
1832     $amounts{invtotal} = $self->{ordtotal};
 
1833     $amounts{total}    = $self->{ordtotal};
 
1835   } elsif ($self->{type} =~ /_quotation$/) {
 
1836     $amounts{invtotal} = $self->{quototal};
 
1837     $amounts{total}    = $self->{quototal};
 
1840     $amounts{invtotal} = $self->{invtotal};
 
1841     $amounts{total}    = $self->{total};
 
1843   $amounts{skonto_in_percent} = 100.0 * $self->{percent_skonto};
 
1845   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
 
1847   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
 
1848   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
 
1849   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
 
1851   foreach (keys %amounts) {
 
1852     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
 
1853     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
 
1856   if ($self->{"language_id"}) {
 
1858       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
 
1859       qq|FROM translation_payment_terms t | .
 
1860       qq|LEFT JOIN language l ON t.language_id = l.id | .
 
1861       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
 
1862     my ($description_long, $output_numberformat, $output_dateformat,
 
1863       $output_longdates) =
 
1864       selectrow_query($self, $dbh, $query,
 
1865                       $self->{"language_id"}, $self->{"payment_id"});
 
1867     $self->{payment_terms} = $description_long if ($description_long);
 
1869     if ($output_dateformat) {
 
1870       foreach my $key (qw(netto_date skonto_date)) {
 
1872           $main::locale->reformat_date($myconfig, $self->{$key},
 
1878     if ($output_numberformat &&
 
1879         ($output_numberformat ne $myconfig->{"numberformat"})) {
 
1880       my $saved_numberformat = $myconfig->{"numberformat"};
 
1881       $myconfig->{"numberformat"} = $output_numberformat;
 
1882       map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
 
1883       $myconfig->{"numberformat"} = $saved_numberformat;
 
1887   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
 
1888   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
 
1889   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
 
1890   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
 
1891   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
 
1892   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
 
1893   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
 
1895   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
 
1897   $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
 
1899   $main::lxdebug->leave_sub();
 
1903 sub get_template_language {
 
1904   $main::lxdebug->enter_sub();
 
1906   my ($self, $myconfig) = @_;
 
1908   my $template_code = "";
 
1910   if ($self->{language_id}) {
 
1911     my $dbh = $self->get_standard_dbh($myconfig);
 
1912     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
 
1913     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
 
1916   $main::lxdebug->leave_sub();
 
1918   return $template_code;
 
1921 sub get_printer_code {
 
1922   $main::lxdebug->enter_sub();
 
1924   my ($self, $myconfig) = @_;
 
1926   my $template_code = "";
 
1928   if ($self->{printer_id}) {
 
1929     my $dbh = $self->get_standard_dbh($myconfig);
 
1930     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
 
1931     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
 
1934   $main::lxdebug->leave_sub();
 
1936   return $template_code;
 
1940   $main::lxdebug->enter_sub();
 
1942   my ($self, $myconfig) = @_;
 
1944   my $template_code = "";
 
1946   if ($self->{shipto_id}) {
 
1947     my $dbh = $self->get_standard_dbh($myconfig);
 
1948     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
 
1949     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
 
1950     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
 
1953   $main::lxdebug->leave_sub();
 
1957   $main::lxdebug->enter_sub();
 
1959   my ($self, $dbh, $id, $module) = @_;
 
1964   foreach my $item (qw(name department_1 department_2 street zipcode city country
 
1965                        contact phone fax email)) {
 
1966     if ($self->{"shipto$item"}) {
 
1967       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
 
1969     push(@values, $self->{"shipto${item}"});
 
1973     if ($self->{shipto_id}) {
 
1974       my $query = qq|UPDATE shipto set
 
1976                        shiptodepartment_1 = ?,
 
1977                        shiptodepartment_2 = ?,
 
1986                      WHERE shipto_id = ?|;
 
1987       do_query($self, $dbh, $query, @values, $self->{shipto_id});
 
1989       my $query = qq|SELECT * FROM shipto
 
1990                      WHERE shiptoname = ? AND
 
1991                        shiptodepartment_1 = ? AND
 
1992                        shiptodepartment_2 = ? AND
 
1993                        shiptostreet = ? AND
 
1994                        shiptozipcode = ? AND
 
1996                        shiptocountry = ? AND
 
1997                        shiptocontact = ? AND
 
2003       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
 
2006           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
 
2007                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
 
2008                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
 
2009              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
 
2010         do_query($self, $dbh, $query, $id, @values, $module);
 
2015   $main::lxdebug->leave_sub();
 
2019   $main::lxdebug->enter_sub();
 
2021   my ($self, $dbh) = @_;
 
2023   $dbh ||= $self->get_standard_dbh(\%main::myconfig);
 
2025   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
 
2026   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
 
2027   $self->{"employee_id"} *= 1;
 
2029   $main::lxdebug->leave_sub();
 
2032 sub get_employee_data {
 
2033   $main::lxdebug->enter_sub();
 
2038   Common::check_params(\%params, qw(prefix));
 
2039   Common::check_params_x(\%params, qw(id));
 
2042     $main::lxdebug->leave_sub();
 
2046   my $myconfig = \%main::myconfig;
 
2047   my $dbh      = $params{dbh} || $self->get_standard_dbh($myconfig);
 
2049   my ($login)  = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
 
2052     my $user = User->new($login);
 
2053     map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
 
2055     $self->{$params{prefix} . '_login'}   = $login;
 
2056     $self->{$params{prefix} . '_name'}  ||= $login;
 
2059   $main::lxdebug->leave_sub();
 
2063   $main::lxdebug->enter_sub();
 
2065   my ($self, $myconfig, $reference_date) = @_;
 
2067   $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
 
2069   my $dbh         = $self->get_standard_dbh($myconfig);
 
2070   my $query       = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
 
2071   my ($duedate)   = selectrow_query($self, $dbh, $query, $self->{payment_id});
 
2073   $main::lxdebug->leave_sub();
 
2079   $main::lxdebug->enter_sub();
 
2081   my ($self, $dbh, $id, $key) = @_;
 
2083   $key = "all_contacts" unless ($key);
 
2087     $main::lxdebug->leave_sub();
 
2092     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
 
2093     qq|FROM contacts | .
 
2094     qq|WHERE cp_cv_id = ? | .
 
2095     qq|ORDER BY lower(cp_name)|;
 
2097   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
 
2099   $main::lxdebug->leave_sub();
 
2103   $main::lxdebug->enter_sub();
 
2105   my ($self, $dbh, $key) = @_;
 
2107   my ($all, $old_id, $where, @values);
 
2109   if (ref($key) eq "HASH") {
 
2112     $key = "ALL_PROJECTS";
 
2114     foreach my $p (keys(%{$params})) {
 
2116         $all = $params->{$p};
 
2117       } elsif ($p eq "old_id") {
 
2118         $old_id = $params->{$p};
 
2119       } elsif ($p eq "key") {
 
2120         $key = $params->{$p};
 
2126     $where = "WHERE active ";
 
2128       if (ref($old_id) eq "ARRAY") {
 
2129         my @ids = grep({ $_ } @{$old_id});
 
2131           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
 
2132           push(@values, @ids);
 
2135         $where .= " OR (id = ?) ";
 
2136         push(@values, $old_id);
 
2142     qq|SELECT id, projectnumber, description, active | .
 
2145     qq|ORDER BY lower(projectnumber)|;
 
2147   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
 
2149   $main::lxdebug->leave_sub();
 
2153   $main::lxdebug->enter_sub();
 
2155   my ($self, $dbh, $vc_id, $key) = @_;
 
2157   $key = "all_shipto" unless ($key);
 
2160     # get shipping addresses
 
2161     my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
 
2163     $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
 
2169   $main::lxdebug->leave_sub();
 
2173   $main::lxdebug->enter_sub();
 
2175   my ($self, $dbh, $key) = @_;
 
2177   $key = "all_printers" unless ($key);
 
2179   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
 
2181   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2183   $main::lxdebug->leave_sub();
 
2187   $main::lxdebug->enter_sub();
 
2189   my ($self, $dbh, $params) = @_;
 
2192   $key = $params->{key};
 
2193   $key = "all_charts" unless ($key);
 
2195   my $transdate = quote_db_date($params->{transdate});
 
2198     qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
 
2200     qq|LEFT JOIN taxkeys tk ON | .
 
2201     qq|(tk.id = (SELECT id FROM taxkeys | .
 
2202     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
 
2203     qq|          ORDER BY startdate DESC LIMIT 1)) | .
 
2204     qq|ORDER BY c.accno|;
 
2206   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2208   $main::lxdebug->leave_sub();
 
2211 sub _get_taxcharts {
 
2212   $main::lxdebug->enter_sub();
 
2214   my ($self, $dbh, $params) = @_;
 
2216   my $key = "all_taxcharts";
 
2219   if (ref $params eq 'HASH') {
 
2220     $key = $params->{key} if ($params->{key});
 
2221     if ($params->{module} eq 'AR') {
 
2222       push @where, 'taxkey NOT IN (8, 9, 18, 19)';
 
2224     } elsif ($params->{module} eq 'AP') {
 
2225       push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
 
2232   my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
 
2234   my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
 
2236   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2238   $main::lxdebug->leave_sub();
 
2242   $main::lxdebug->enter_sub();
 
2244   my ($self, $dbh, $key) = @_;
 
2246   $key = "all_taxzones" unless ($key);
 
2248   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
 
2250   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2252   $main::lxdebug->leave_sub();
 
2255 sub _get_employees {
 
2256   $main::lxdebug->enter_sub();
 
2258   my ($self, $dbh, $default_key, $key) = @_;
 
2260   $key = $default_key unless ($key);
 
2261   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
 
2263   $main::lxdebug->leave_sub();
 
2266 sub _get_business_types {
 
2267   $main::lxdebug->enter_sub();
 
2269   my ($self, $dbh, $key) = @_;
 
2271   my $options       = ref $key eq 'HASH' ? $key : { key => $key };
 
2272   $options->{key} ||= "all_business_types";
 
2275   if (exists $options->{salesman}) {
 
2276     $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
 
2279   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
 
2281   $main::lxdebug->leave_sub();
 
2284 sub _get_languages {
 
2285   $main::lxdebug->enter_sub();
 
2287   my ($self, $dbh, $key) = @_;
 
2289   $key = "all_languages" unless ($key);
 
2291   my $query = qq|SELECT * FROM language ORDER BY id|;
 
2293   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2295   $main::lxdebug->leave_sub();
 
2298 sub _get_dunning_configs {
 
2299   $main::lxdebug->enter_sub();
 
2301   my ($self, $dbh, $key) = @_;
 
2303   $key = "all_dunning_configs" unless ($key);
 
2305   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
 
2307   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2309   $main::lxdebug->leave_sub();
 
2312 sub _get_currencies {
 
2313 $main::lxdebug->enter_sub();
 
2315   my ($self, $dbh, $key) = @_;
 
2317   $key = "all_currencies" unless ($key);
 
2319   my $query = qq|SELECT curr AS currency FROM defaults|;
 
2321   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
 
2323   $main::lxdebug->leave_sub();
 
2327 $main::lxdebug->enter_sub();
 
2329   my ($self, $dbh, $key) = @_;
 
2331   $key = "all_payments" unless ($key);
 
2333   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
 
2335   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2337   $main::lxdebug->leave_sub();
 
2340 sub _get_customers {
 
2341   $main::lxdebug->enter_sub();
 
2343   my ($self, $dbh, $key) = @_;
 
2345   my $options        = ref $key eq 'HASH' ? $key : { key => $key };
 
2346   $options->{key}  ||= "all_customers";
 
2347   my $limit_clause   = "LIMIT $options->{limit}" if $options->{limit};
 
2348   my $where          = $options->{business_is_salesman} ? qq| AND business_id IN (SELECT id FROM business WHERE salesman)| : '';
 
2350   my $query = qq|SELECT * FROM customer WHERE NOT obsolete $where ORDER BY name $limit_clause|;
 
2351   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
 
2353   $main::lxdebug->leave_sub();
 
2357   $main::lxdebug->enter_sub();
 
2359   my ($self, $dbh, $key) = @_;
 
2361   $key = "all_vendors" unless ($key);
 
2363   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
 
2365   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2367   $main::lxdebug->leave_sub();
 
2370 sub _get_departments {
 
2371   $main::lxdebug->enter_sub();
 
2373   my ($self, $dbh, $key) = @_;
 
2375   $key = "all_departments" unless ($key);
 
2377   my $query = qq|SELECT * FROM department ORDER BY description|;
 
2379   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2381   $main::lxdebug->leave_sub();
 
2384 sub _get_warehouses {
 
2385   $main::lxdebug->enter_sub();
 
2387   my ($self, $dbh, $param) = @_;
 
2389   my ($key, $bins_key);
 
2391   if ('' eq ref $param) {
 
2395     $key      = $param->{key};
 
2396     $bins_key = $param->{bins};
 
2399   my $query = qq|SELECT w.* FROM warehouse w
 
2400                  WHERE (NOT w.invalid) AND
 
2401                    ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
 
2402                  ORDER BY w.sortkey|;
 
2404   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2407     $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
 
2408     my $sth = prepare_query($self, $dbh, $query);
 
2410     foreach my $warehouse (@{ $self->{$key} }) {
 
2411       do_statement($self, $sth, $query, $warehouse->{id});
 
2412       $warehouse->{$bins_key} = [];
 
2414       while (my $ref = $sth->fetchrow_hashref()) {
 
2415         push @{ $warehouse->{$bins_key} }, $ref;
 
2421   $main::lxdebug->leave_sub();
 
2425   $main::lxdebug->enter_sub();
 
2427   my ($self, $dbh, $table, $key, $sortkey) = @_;
 
2429   my $query  = qq|SELECT * FROM $table|;
 
2430   $query    .= qq| ORDER BY $sortkey| if ($sortkey);
 
2432   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2434   $main::lxdebug->leave_sub();
 
2438 #  $main::lxdebug->enter_sub();
 
2440 #  my ($self, $dbh, $key) = @_;
 
2442 #  $key ||= "all_groups";
 
2444 #  my $groups = $main::auth->read_groups();
 
2446 #  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2448 #  $main::lxdebug->leave_sub();
 
2452   $main::lxdebug->enter_sub();
 
2457   my $dbh = $self->get_standard_dbh(\%main::myconfig);
 
2458   my ($sth, $query, $ref);
 
2460   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
 
2461   my $vc_id = $self->{"${vc}_id"};
 
2463   if ($params{"contacts"}) {
 
2464     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
 
2467   if ($params{"shipto"}) {
 
2468     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
 
2471   if ($params{"projects"} || $params{"all_projects"}) {
 
2472     $self->_get_projects($dbh, $params{"all_projects"} ?
 
2473                          $params{"all_projects"} : $params{"projects"},
 
2474                          $params{"all_projects"} ? 1 : 0);
 
2477   if ($params{"printers"}) {
 
2478     $self->_get_printers($dbh, $params{"printers"});
 
2481   if ($params{"languages"}) {
 
2482     $self->_get_languages($dbh, $params{"languages"});
 
2485   if ($params{"charts"}) {
 
2486     $self->_get_charts($dbh, $params{"charts"});
 
2489   if ($params{"taxcharts"}) {
 
2490     $self->_get_taxcharts($dbh, $params{"taxcharts"});
 
2493   if ($params{"taxzones"}) {
 
2494     $self->_get_taxzones($dbh, $params{"taxzones"});
 
2497   if ($params{"employees"}) {
 
2498     $self->_get_employees($dbh, "all_employees", $params{"employees"});
 
2501   if ($params{"salesmen"}) {
 
2502     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
 
2505   if ($params{"business_types"}) {
 
2506     $self->_get_business_types($dbh, $params{"business_types"});
 
2509   if ($params{"dunning_configs"}) {
 
2510     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
 
2513   if($params{"currencies"}) {
 
2514     $self->_get_currencies($dbh, $params{"currencies"});
 
2517   if($params{"customers"}) {
 
2518     $self->_get_customers($dbh, $params{"customers"});
 
2521   if($params{"vendors"}) {
 
2522     if (ref $params{"vendors"} eq 'HASH') {
 
2523       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
 
2525       $self->_get_vendors($dbh, $params{"vendors"});
 
2529   if($params{"payments"}) {
 
2530     $self->_get_payments($dbh, $params{"payments"});
 
2533   if($params{"departments"}) {
 
2534     $self->_get_departments($dbh, $params{"departments"});
 
2537   if ($params{price_factors}) {
 
2538     $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
 
2541   if ($params{warehouses}) {
 
2542     $self->_get_warehouses($dbh, $params{warehouses});
 
2545 #  if ($params{groups}) {
 
2546 #    $self->_get_groups($dbh, $params{groups});
 
2549   if ($params{partsgroup}) {
 
2550     $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
 
2553   $main::lxdebug->leave_sub();
 
2556 # this sub gets the id and name from $table
 
2558   $main::lxdebug->enter_sub();
 
2560   my ($self, $myconfig, $table) = @_;
 
2562   # connect to database
 
2563   my $dbh = $self->get_standard_dbh($myconfig);
 
2565   $table = $table eq "customer" ? "customer" : "vendor";
 
2566   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
 
2568   my ($query, @values);
 
2570   if (!$self->{openinvoices}) {
 
2572     if ($self->{customernumber} ne "") {
 
2573       $where = qq|(vc.customernumber ILIKE ?)|;
 
2574       push(@values, '%' . $self->{customernumber} . '%');
 
2576       $where = qq|(vc.name ILIKE ?)|;
 
2577       push(@values, '%' . $self->{$table} . '%');
 
2581       qq~SELECT vc.id, vc.name,
 
2582            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
2584          WHERE $where AND (NOT vc.obsolete)
 
2588       qq~SELECT DISTINCT vc.id, vc.name,
 
2589            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
2591          JOIN $table vc ON (a.${table}_id = vc.id)
 
2592          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
 
2594     push(@values, '%' . $self->{$table} . '%');
 
2597   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
 
2599   $main::lxdebug->leave_sub();
 
2601   return scalar(@{ $self->{name_list} });
 
2604 # the selection sub is used in the AR, AP, IS, IR and OE module
 
2607   $main::lxdebug->enter_sub();
 
2609   my ($self, $myconfig, $table, $module) = @_;
 
2612   my $dbh = $self->get_standard_dbh($myconfig);
 
2614   $table = $table eq "customer" ? "customer" : "vendor";
 
2616   my $query = qq|SELECT count(*) FROM $table|;
 
2617   my ($count) = selectrow_query($self, $dbh, $query);
 
2619   # build selection list
 
2620   if ($count <= $myconfig->{vclimit}) {
 
2621     $query = qq|SELECT id, name, salesman_id
 
2622                 FROM $table WHERE NOT obsolete
 
2624     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
 
2628   $self->get_employee($dbh);
 
2630   # setup sales contacts
 
2631   $query = qq|SELECT e.id, e.name
 
2633               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
 
2634   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
 
2637   push(@{ $self->{all_employees} },
 
2638        { id   => $self->{employee_id},
 
2639          name => $self->{employee} });
 
2641   # sort the whole thing
 
2642   @{ $self->{all_employees} } =
 
2643     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
 
2645   if ($module eq 'AR') {
 
2647     # prepare query for departments
 
2648     $query = qq|SELECT id, description
 
2651                 ORDER BY description|;
 
2654     $query = qq|SELECT id, description
 
2656                 ORDER BY description|;
 
2659   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2662   $query = qq|SELECT id, description
 
2666   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2669   $query = qq|SELECT printer_description, id
 
2671               ORDER BY printer_description|;
 
2673   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2676   $query = qq|SELECT id, description
 
2680   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
2682   $main::lxdebug->leave_sub();
 
2685 sub language_payment {
 
2686   $main::lxdebug->enter_sub();
 
2688   my ($self, $myconfig) = @_;
 
2690   my $dbh = $self->get_standard_dbh($myconfig);
 
2692   my $query = qq|SELECT id, description
 
2696   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2699   $query = qq|SELECT printer_description, id
 
2701               ORDER BY printer_description|;
 
2703   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2706   $query = qq|SELECT id, description
 
2710   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
2712   # get buchungsgruppen
 
2713   $query = qq|SELECT id, description
 
2714               FROM buchungsgruppen|;
 
2716   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
 
2718   $main::lxdebug->leave_sub();
 
2721 # this is only used for reports
 
2722 sub all_departments {
 
2723   $main::lxdebug->enter_sub();
 
2725   my ($self, $myconfig, $table) = @_;
 
2727   my $dbh = $self->get_standard_dbh($myconfig);
 
2730   if ($table eq 'customer') {
 
2731     $where = "WHERE role = 'P' ";
 
2734   my $query = qq|SELECT id, description
 
2737                  ORDER BY description|;
 
2738   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2740   delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
 
2742   $main::lxdebug->leave_sub();
 
2746   $main::lxdebug->enter_sub();
 
2748   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
 
2751   if ($table eq "customer") {
 
2760   $self->all_vc($myconfig, $table, $module);
 
2762   # get last customers or vendors
 
2763   my ($query, $sth, $ref);
 
2765   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
 
2770     my $transdate = "current_date";
 
2771     if ($self->{transdate}) {
 
2772       $transdate = $dbh->quote($self->{transdate});
 
2775     # now get the account numbers
 
2776     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
 
2777                 FROM chart c, taxkeys tk
 
2778                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
 
2779                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
 
2782     $sth = $dbh->prepare($query);
 
2784     do_statement($self, $sth, $query, '%' . $module . '%');
 
2786     $self->{accounts} = "";
 
2787     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2789       foreach my $key (split(/:/, $ref->{link})) {
 
2790         if ($key =~ /\Q$module\E/) {
 
2792           # cross reference for keys
 
2793           $xkeyref{ $ref->{accno} } = $key;
 
2795           push @{ $self->{"${module}_links"}{$key} },
 
2796             { accno       => $ref->{accno},
 
2797               description => $ref->{description},
 
2798               taxkey      => $ref->{taxkey_id},
 
2799               tax_id      => $ref->{tax_id} };
 
2801           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2807   # get taxkeys and description
 
2808   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
 
2809   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
 
2811   if (($module eq "AP") || ($module eq "AR")) {
 
2812     # get tax rates and description
 
2813     $query = qq|SELECT * FROM tax|;
 
2814     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
 
2820            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
 
2821            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
 
2822            a.intnotes, a.department_id, a.amount AS oldinvtotal,
 
2823            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
 
2825            d.description AS department,
 
2828          JOIN $table c ON (a.${table}_id = c.id)
 
2829          LEFT JOIN employee e ON (e.id = a.employee_id)
 
2830          LEFT JOIN department d ON (d.id = a.department_id)
 
2832     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
 
2834     foreach my $key (keys %$ref) {
 
2835       $self->{$key} = $ref->{$key};
 
2838     my $transdate = "current_date";
 
2839     if ($self->{transdate}) {
 
2840       $transdate = $dbh->quote($self->{transdate});
 
2843     # now get the account numbers
 
2844     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
 
2846                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
 
2848                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
 
2849                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
 
2852     $sth = $dbh->prepare($query);
 
2853     do_statement($self, $sth, $query, "%$module%");
 
2855     $self->{accounts} = "";
 
2856     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2858       foreach my $key (split(/:/, $ref->{link})) {
 
2859         if ($key =~ /\Q$module\E/) {
 
2861           # cross reference for keys
 
2862           $xkeyref{ $ref->{accno} } = $key;
 
2864           push @{ $self->{"${module}_links"}{$key} },
 
2865             { accno       => $ref->{accno},
 
2866               description => $ref->{description},
 
2867               taxkey      => $ref->{taxkey_id},
 
2868               tax_id      => $ref->{tax_id} };
 
2870           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2876     # get amounts from individual entries
 
2879            c.accno, c.description,
 
2880            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
 
2884          LEFT JOIN chart c ON (c.id = a.chart_id)
 
2885          LEFT JOIN project p ON (p.id = a.project_id)
 
2886          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
 
2887                                     WHERE (tk.taxkey_id=a.taxkey) AND
 
2888                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
 
2889                                         THEN tk.chart_id = a.chart_id
 
2892                                        OR (c.link='%tax%')) AND
 
2893                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
 
2894          WHERE a.trans_id = ?
 
2895          AND a.fx_transaction = '0'
 
2896          ORDER BY a.acc_trans_id, a.transdate|;
 
2897     $sth = $dbh->prepare($query);
 
2898     do_statement($self, $sth, $query, $self->{id});
 
2900     # get exchangerate for currency
 
2901     $self->{exchangerate} =
 
2902       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2905     # store amounts in {acc_trans}{$key} for multiple accounts
 
2906     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2907       $ref->{exchangerate} =
 
2908         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
 
2909       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
 
2912       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
 
2913         $ref->{amount} *= -1;
 
2915       $ref->{index} = $index;
 
2917       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
 
2923            d.curr AS currencies, d.closedto, d.revtrans,
 
2924            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2925            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
2927     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2928     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2935             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
 
2936             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2937             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
2939     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2940     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2942     if ($self->{"$self->{vc}_id"}) {
 
2944       # only setup currency
 
2945       ($self->{currency}) = split(/:/, $self->{currencies});
 
2949       $self->lastname_used($dbh, $myconfig, $table, $module);
 
2951       # get exchangerate for currency
 
2952       $self->{exchangerate} =
 
2953         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2959   $main::lxdebug->leave_sub();
 
2963   $main::lxdebug->enter_sub();
 
2965   my ($self, $dbh, $myconfig, $table, $module) = @_;
 
2969   $table         = $table eq "customer" ? "customer" : "vendor";
 
2970   my %column_map = ("a.curr"                  => "currency",
 
2971                     "a.${table}_id"           => "${table}_id",
 
2972                     "a.department_id"         => "department_id",
 
2973                     "d.description"           => "department",
 
2974                     "ct.name"                 => $table,
 
2975                     "current_date + ct.terms" => "duedate",
 
2978   if ($self->{type} =~ /delivery_order/) {
 
2979     $arap  = 'delivery_orders';
 
2980     delete $column_map{"a.curr"};
 
2982   } elsif ($self->{type} =~ /_order/) {
 
2984     $where = "quotation = '0'";
 
2986   } elsif ($self->{type} =~ /_quotation/) {
 
2988     $where = "quotation = '1'";
 
2990   } elsif ($table eq 'customer') {
 
2998   $where           = "($where) AND" if ($where);
 
2999   my $query        = qq|SELECT MAX(id) FROM $arap
 
3000                         WHERE $where ${table}_id > 0|;
 
3001   my ($trans_id)   = selectrow_query($self, $dbh, $query);
 
3004   my $column_spec  = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
 
3005   $query           = qq|SELECT $column_spec
 
3007                         LEFT JOIN $table     ct ON (a.${table}_id = ct.id)
 
3008                         LEFT JOIN department d  ON (a.department_id = d.id)
 
3010   my $ref          = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
 
3012   map { $self->{$_} = $ref->{$_} } values %column_map;
 
3014   $main::lxdebug->leave_sub();
 
3018   $main::lxdebug->enter_sub();
 
3021   my $myconfig          = shift  || \%::myconfig;
 
3022   my ($thisdate, $days) = @_;
 
3024   my $dbh = $self->get_standard_dbh($myconfig);
 
3029     my $dateformat = $myconfig->{dateformat};
 
3030     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
 
3031     $thisdate = $dbh->quote($thisdate);
 
3032     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
 
3034     $query = qq|SELECT current_date AS thisdate|;
 
3037   ($thisdate) = selectrow_query($self, $dbh, $query);
 
3039   $main::lxdebug->leave_sub();
 
3045   $main::lxdebug->enter_sub();
 
3047   my ($self, $string) = @_;
 
3049   if ($string !~ /%/) {
 
3050     $string = "%$string%";
 
3053   $string =~ s/\'/\'\'/g;
 
3055   $main::lxdebug->leave_sub();
 
3061   $main::lxdebug->enter_sub();
 
3063   my ($self, $flds, $new, $count, $numrows) = @_;
 
3067   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
 
3072   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
 
3074     my $j = $item->{ndx} - 1;
 
3075     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
 
3079   for $i ($count + 1 .. $numrows) {
 
3080     map { delete $self->{"${_}_$i"} } @{$flds};
 
3083   $main::lxdebug->leave_sub();
 
3087   $main::lxdebug->enter_sub();
 
3089   my ($self, $myconfig) = @_;
 
3093   my $dbh = $self->dbconnect_noauto($myconfig);
 
3095   my $query = qq|DELETE FROM status
 
3096                  WHERE (formname = ?) AND (trans_id = ?)|;
 
3097   my $sth = prepare_query($self, $dbh, $query);
 
3099   if ($self->{formname} =~ /(check|receipt)/) {
 
3100     for $i (1 .. $self->{rowcount}) {
 
3101       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
 
3104     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
 
3108   my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3109   my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3111   my %queued = split / /, $self->{queued};
 
3114   if ($self->{formname} =~ /(check|receipt)/) {
 
3116     # this is a check or receipt, add one entry for each lineitem
 
3117     my ($accno) = split /--/, $self->{account};
 
3118     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
 
3119                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
 
3120     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
 
3121     $sth = prepare_query($self, $dbh, $query);
 
3123     for $i (1 .. $self->{rowcount}) {
 
3124       if ($self->{"checked_$i"}) {
 
3125         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
 
3131     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
3132                 VALUES (?, ?, ?, ?, ?)|;
 
3133     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
 
3134              $queued{$self->{formname}}, $self->{formname});
 
3140   $main::lxdebug->leave_sub();
 
3144   $main::lxdebug->enter_sub();
 
3146   my ($self, $dbh) = @_;
 
3148   my ($query, $printed, $emailed);
 
3150   my $formnames  = $self->{printed};
 
3151   my $emailforms = $self->{emailed};
 
3153   $query = qq|DELETE FROM status
 
3154                  WHERE (formname = ?) AND (trans_id = ?)|;
 
3155   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
 
3157   # this only applies to the forms
 
3158   # checks and receipts are posted when printed or queued
 
3160   if ($self->{queued}) {
 
3161     my %queued = split / /, $self->{queued};
 
3163     foreach my $formname (keys %queued) {
 
3164       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3165       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3167       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
3168                   VALUES (?, ?, ?, ?, ?)|;
 
3169       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
 
3171       $formnames  =~ s/\Q$self->{formname}\E//;
 
3172       $emailforms =~ s/\Q$self->{formname}\E//;
 
3177   # save printed, emailed info
 
3178   $formnames  =~ s/^ +//g;
 
3179   $emailforms =~ s/^ +//g;
 
3182   map { $status{$_}{printed} = 1 } split / +/, $formnames;
 
3183   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
 
3185   foreach my $formname (keys %status) {
 
3186     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3187     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3189     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
 
3190                 VALUES (?, ?, ?, ?)|;
 
3191     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
 
3194   $main::lxdebug->leave_sub();
 
3198 # $main::locale->text('SAVED')
 
3199 # $main::locale->text('DELETED')
 
3200 # $main::locale->text('ADDED')
 
3201 # $main::locale->text('PAYMENT POSTED')
 
3202 # $main::locale->text('POSTED')
 
3203 # $main::locale->text('POSTED AS NEW')
 
3204 # $main::locale->text('ELSE')
 
3205 # $main::locale->text('SAVED FOR DUNNING')
 
3206 # $main::locale->text('DUNNING STARTED')
 
3207 # $main::locale->text('PRINTED')
 
3208 # $main::locale->text('MAILED')
 
3209 # $main::locale->text('SCREENED')
 
3210 # $main::locale->text('CANCELED')
 
3211 # $main::locale->text('invoice')
 
3212 # $main::locale->text('proforma')
 
3213 # $main::locale->text('sales_order')
 
3214 # $main::locale->text('packing_list')
 
3215 # $main::locale->text('pick_list')
 
3216 # $main::locale->text('purchase_order')
 
3217 # $main::locale->text('bin_list')
 
3218 # $main::locale->text('sales_quotation')
 
3219 # $main::locale->text('request_quotation')
 
3222   $main::lxdebug->enter_sub();
 
3227   if(!exists $self->{employee_id}) {
 
3228     &get_employee($self, $dbh);
 
3232    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
 
3233    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
 
3234   my @values = (conv_i($self->{id}), $self->{login},
 
3235                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
 
3236   do_query($self, $dbh, $query, @values);
 
3238   $main::lxdebug->leave_sub();
 
3242   $main::lxdebug->enter_sub();
 
3244   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
 
3245   my ($orderBy, $desc) = split(/\-\-/, $order);
 
3246   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
 
3249   if ($trans_id ne "") {
 
3251       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 | .
 
3252       qq|FROM history_erp h | .
 
3253       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
 
3254       qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
 
3257     my $sth = $dbh->prepare($query) || $self->dberror($query);
 
3259     $sth->execute() || $self->dberror("$query");
 
3261     while(my $hash_ref = $sth->fetchrow_hashref()) {
 
3262       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
 
3263       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
 
3264       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
 
3265       $tempArray[$i++] = $hash_ref;
 
3267     $main::lxdebug->leave_sub() and return \@tempArray
 
3268       if ($i > 0 && $tempArray[0] ne "");
 
3270   $main::lxdebug->leave_sub();
 
3274 sub update_defaults {
 
3275   $main::lxdebug->enter_sub();
 
3277   my ($self, $myconfig, $fld, $provided_dbh) = @_;
 
3280   if ($provided_dbh) {
 
3281     $dbh = $provided_dbh;
 
3283     $dbh = $self->dbconnect_noauto($myconfig);
 
3285   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
 
3286   my $sth   = $dbh->prepare($query);
 
3288   $sth->execute || $self->dberror($query);
 
3289   my ($var) = $sth->fetchrow_array;
 
3292   if ($var =~ m/\d+$/) {
 
3293     my $new_var  = (substr $var, $-[0]) * 1 + 1;
 
3294     my $len_diff = length($var) - $-[0] - length($new_var);
 
3295     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
 
3301   $query = qq|UPDATE defaults SET $fld = ?|;
 
3302   do_query($self, $dbh, $query, $var);
 
3304   if (!$provided_dbh) {
 
3309   $main::lxdebug->leave_sub();
 
3314 sub update_business {
 
3315   $main::lxdebug->enter_sub();
 
3317   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
 
3320   if ($provided_dbh) {
 
3321     $dbh = $provided_dbh;
 
3323     $dbh = $self->dbconnect_noauto($myconfig);
 
3326     qq|SELECT customernumberinit FROM business
 
3327        WHERE id = ? FOR UPDATE|;
 
3328   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
 
3330   return undef unless $var;
 
3332   if ($var =~ m/\d+$/) {
 
3333     my $new_var  = (substr $var, $-[0]) * 1 + 1;
 
3334     my $len_diff = length($var) - $-[0] - length($new_var);
 
3335     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
 
3341   $query = qq|UPDATE business
 
3342               SET customernumberinit = ?
 
3344   do_query($self, $dbh, $query, $var, $business_id);
 
3346   if (!$provided_dbh) {
 
3351   $main::lxdebug->leave_sub();
 
3356 sub get_partsgroup {
 
3357   $main::lxdebug->enter_sub();
 
3359   my ($self, $myconfig, $p) = @_;
 
3360   my $target = $p->{target} || 'all_partsgroup';
 
3362   my $dbh = $self->get_standard_dbh($myconfig);
 
3364   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
 
3366                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
 
3369   if ($p->{searchitems} eq 'part') {
 
3370     $query .= qq|WHERE p.inventory_accno_id > 0|;
 
3372   if ($p->{searchitems} eq 'service') {
 
3373     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
 
3375   if ($p->{searchitems} eq 'assembly') {
 
3376     $query .= qq|WHERE p.assembly = '1'|;
 
3378   if ($p->{searchitems} eq 'labor') {
 
3379     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
 
3382   $query .= qq|ORDER BY partsgroup|;
 
3385     $query = qq|SELECT id, partsgroup FROM partsgroup
 
3386                 ORDER BY partsgroup|;
 
3389   if ($p->{language_code}) {
 
3390     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
 
3391                   t.description AS translation
 
3393                 JOIN parts p ON (p.partsgroup_id = pg.id)
 
3394                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
 
3395                 ORDER BY translation|;
 
3396     @values = ($p->{language_code});
 
3399   $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
 
3401   $main::lxdebug->leave_sub();
 
3404 sub get_pricegroup {
 
3405   $main::lxdebug->enter_sub();
 
3407   my ($self, $myconfig, $p) = @_;
 
3409   my $dbh = $self->get_standard_dbh($myconfig);
 
3411   my $query = qq|SELECT p.id, p.pricegroup
 
3414   $query .= qq| ORDER BY pricegroup|;
 
3417     $query = qq|SELECT id, pricegroup FROM pricegroup
 
3418                 ORDER BY pricegroup|;
 
3421   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
 
3423   $main::lxdebug->leave_sub();
 
3427 # usage $form->all_years($myconfig, [$dbh])
 
3428 # return list of all years where bookings found
 
3431   $main::lxdebug->enter_sub();
 
3433   my ($self, $myconfig, $dbh) = @_;
 
3435   $dbh ||= $self->get_standard_dbh($myconfig);
 
3438   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
 
3439                    (SELECT MAX(transdate) FROM acc_trans)|;
 
3440   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
 
3442   if ($myconfig->{dateformat} =~ /^yy/) {
 
3443     ($startdate) = split /\W/, $startdate;
 
3444     ($enddate) = split /\W/, $enddate;
 
3446     (@_) = split /\W/, $startdate;
 
3448     (@_) = split /\W/, $enddate;
 
3453   $startdate = substr($startdate,0,4);
 
3454   $enddate = substr($enddate,0,4);
 
3456   while ($enddate >= $startdate) {
 
3457     push @all_years, $enddate--;
 
3462   $main::lxdebug->leave_sub();
 
3466   $main::lxdebug->enter_sub();
 
3470   map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
 
3472   $main::lxdebug->leave_sub();
 
3476   $main::lxdebug->enter_sub();
 
3481   map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
 
3483   $main::lxdebug->leave_sub();
 
3492 SL::Form.pm - main data object.
 
3496 This is the main data object of Lx-Office.
 
3497 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
 
3498 Points of interest for a beginner are:
 
3500  - $form->error            - renders a generic error in html. accepts an error message
 
3501  - $form->get_standard_dbh - returns a database connection for the
 
3503 =head1 SPECIAL FUNCTIONS
 
3507 =item _store_value()
 
3509 parses a complex var name, and stores it in the form.
 
3512   $form->_store_value($key, $value);
 
3514 keys must start with a string, and can contain various tokens.
 
3515 supported key structures are:
 
3518   simple key strings work as expected
 
3523   separating two keys by a dot (.) will result in a hash lookup for the inner value
 
3524   this is similar to the behaviour of java and templating mechanisms.
 
3526   filter.description => $form->{filter}->{description}
 
3528 3. array+hashref access
 
3530   adding brackets ([]) before the dot will cause the next hash to be put into an array.
 
3531   using [+] instead of [] will force a new array index. this is useful for recurring
 
3532   data structures like part lists. put a [+] into the first varname, and use [] on the
 
3535   repeating these names in your template:
 
3538     invoice.items[].parts_id
 
3542     $form->{invoice}->{items}->[
 
3556   using brackets at the end of a name will result in a pure array to be created.
 
3557   note that you mustn't use [+], which is reserved for array+hash access and will
 
3558   result in undefined behaviour in array context.
 
3560   filter.status[]  => $form->{status}->[ val1, val2, ... ]
 
3562 =item update_business PARAMS
 
3565  \%config,     - config hashref
 
3566  $business_id, - business id
 
3567  $dbh          - optional database handle
 
3569 handles business (thats customer/vendor types) sequences.
 
3571 special behaviour for empty strings in customerinitnumber field:
 
3572 will in this case not increase the value, and return undef.
 
3574 =item redirect_header $url
 
3576 Generates a HTTP redirection header for the new C<$url>. Constructs an
 
3577 absolute URL including scheme, host name and port. If C<$url> is a
 
3578 relative URL then it is considered relative to Lx-Office base URL.
 
3580 This function C<die>s if headers have already been created with
 
3581 C<$::form-E<gt>header>.
 
3585   print $::form->redirect_header('oe.pl?action=edit&id=1234');
 
3586   print $::form->redirect_header('http://www.lx-office.org/');