1 #====================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   7 #=====================================================================
 
   8 # SQL-Ledger Accounting
 
   9 # Copyright (C) 1998-2002
 
  11 #  Author: Dieter Simader
 
  12 #   Email: dsimader@sql-ledger.org
 
  13 #     Web: http://www.sql-ledger.org
 
  15 # Contributors: Thomas Bayen <bayen@gmx.de>
 
  16 #               Antti Kaihola <akaihola@siba.fi>
 
  17 #               Moritz Bunkus (tex code)
 
  19 # This program is free software; you can redistribute it and/or modify
 
  20 # it under the terms of the GNU General Public License as published by
 
  21 # the Free Software Foundation; either version 2 of the License, or
 
  22 # (at your option) any later version.
 
  24 # This program is distributed in the hope that it will be useful,
 
  25 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 
  26 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  27 # GNU General Public License for more details.
 
  28 # You should have received a copy of the GNU General Public License
 
  29 # along with this program; if not, write to the Free Software
 
  30 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 
  31 #======================================================================
 
  32 # Utilities for parsing forms
 
  33 # and supporting routines for linking account numbers
 
  34 # used in AR, AP and IS, IR modules
 
  36 #======================================================================
 
  59 use List::Util qw(first max min sum);
 
  65     $standard_dbh->disconnect();
 
  71   $main::lxdebug->enter_sub(2);
 
  77   while ($key =~ /\[\+?\]\.|\./) {
 
  78     substr($key, 0, $+[0]) = '';
 
  86       if (!scalar @{ $curr->{$`} } || $& eq '[+].') {
 
  87         push @{ $curr->{$`} }, { };
 
  90       $curr = $curr->{$`}->[-1];
 
  94   $curr->{$key} = $value;
 
  96   $main::lxdebug->leave_sub(2);
 
  98   return \$curr->{$key};
 
 102   $main::lxdebug->enter_sub(2);
 
 107   my @pairs  = split(/&/, $input);
 
 110     my ($key, $value) = split(/=/, $_, 2);
 
 111     _store_value($params, unescape(undef, $key), unescape(undef, $value));
 
 114   $main::lxdebug->leave_sub(2);
 
 117 sub _request_to_hash {
 
 118   $main::lxdebug->enter_sub(2);
 
 123   if (!$ENV{'CONTENT_TYPE'}
 
 124       || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
 
 126     _input_to_hash($params, $input);
 
 128     $main::lxdebug->leave_sub(2);
 
 132   my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr, $previous);
 
 134   my $boundary = '--' . $1;
 
 136   foreach my $line (split m/\n/, $input) {
 
 137     last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
 
 139     if (($line eq $boundary) || ($line eq "$boundary\r")) {
 
 140       ${ $previous } =~ s|\r?\n$|| if $previous;
 
 146       $content_type   = "text/plain";
 
 153     next unless $boundary_found;
 
 155     if (!$headers_done) {
 
 156       $line =~ s/[\r\n]*$//;
 
 163       if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
 
 164         if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
 
 166           substr $line, $-[0], $+[0] - $-[0], "";
 
 169         if ($line =~ m|name\s*=\s*"(.*?)"|i) {
 
 171           substr $line, $-[0], $+[0] - $-[0], "";
 
 174         $previous           = _store_value($params, $name, '');
 
 175         $params->{FILENAME} = $filename if ($filename);
 
 180       if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
 
 187     next unless $previous;
 
 189     ${ $previous } .= "${line}\n";
 
 192   ${ $previous } =~ s|\r?\n$|| if $previous;
 
 194   $main::lxdebug->leave_sub(2);
 
 197 sub _recode_recursively {
 
 198   $main::lxdebug->enter_sub();
 
 199   my ($iconv, $param) = @_;
 
 201   if (ref $param eq 'HASH') {
 
 202     foreach my $key (keys %{ $param }) {
 
 203       if (!ref $param->{$key}) {
 
 204         $param->{$key} = $iconv->convert($param->{$key});
 
 206         _recode_recursively($iconv, $param->{$key});
 
 210   } elsif (ref $param eq 'ARRAY') {
 
 211     foreach my $idx (0 .. scalar(@{ $param }) - 1) {
 
 212       if (!ref $param->[$idx]) {
 
 213         $param->[$idx] = $iconv->convert($param->[$idx]);
 
 215         _recode_recursively($iconv, $param->[$idx]);
 
 219   $main::lxdebug->leave_sub();
 
 223   $main::lxdebug->enter_sub();
 
 229   if ($LXDebug::watch_form) {
 
 230     require SL::Watchdog;
 
 231     tie %{ $self }, 'SL::Watchdog';
 
 234   read(STDIN, $_, $ENV{CONTENT_LENGTH});
 
 236   if ($ENV{QUERY_STRING}) {
 
 237     $_ = $ENV{QUERY_STRING};
 
 246   my $parameters = { };
 
 247   _request_to_hash($parameters, $_);
 
 249   my $db_charset   = $main::dbcharset;
 
 250   $db_charset    ||= Common::DEFAULT_CHARSET;
 
 252   if ($parameters->{INPUT_ENCODING} && (lc $parameters->{INPUT_ENCODING} ne $db_charset)) {
 
 254     my $iconv = Text::Iconv->new($parameters->{INPUT_ENCODING}, $db_charset);
 
 256     _recode_recursively($iconv, $parameters);
 
 258     delete $parameters{INPUT_ENCODING};
 
 261   map { $self->{$_} = $parameters->{$_}; } keys %{ $parameters };
 
 263   $self->{action}  =  lc $self->{action};
 
 264   $self->{action}  =~ s/( |-|,|\#)/_/g;
 
 266   $self->{version} =  "2.6.0 beta 2";
 
 268   $main::lxdebug->leave_sub();
 
 273 sub _flatten_variables_rec {
 
 274   $main::lxdebug->enter_sub(2);
 
 283   if ('' eq ref $curr->{$key}) {
 
 284     @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
 
 286   } elsif ('HASH' eq ref $curr->{$key}) {
 
 287     foreach my $hash_key (sort keys %{ $curr->{$key} }) {
 
 288       push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
 
 292     foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
 
 293       my $first_array_entry = 1;
 
 295       foreach my $hash_key (sort keys %{ $curr->{$key}->[$idx] }) {
 
 296         push @result, $self->_flatten_variables_rec($curr->{$key}->[$idx], $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
 
 297         $first_array_entry = 0;
 
 302   $main::lxdebug->leave_sub(2);
 
 307 sub flatten_variables {
 
 308   $main::lxdebug->enter_sub(2);
 
 316     push @variables, $self->_flatten_variables_rec($self, '', $_);
 
 319   $main::lxdebug->leave_sub(2);
 
 324 sub flatten_standard_variables {
 
 325   $main::lxdebug->enter_sub(2);
 
 328   my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar version), @_);
 
 332   foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
 
 333     push @variables, $self->_flatten_variables_rec($self, '', $_);
 
 336   $main::lxdebug->leave_sub(2);
 
 342   $main::lxdebug->enter_sub();
 
 348   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
 
 350   $main::lxdebug->leave_sub();
 
 354   $main::lxdebug->enter_sub(2);
 
 357   my $password      = $self->{password};
 
 359   $self->{password} = 'X' x 8;
 
 361   local $Data::Dumper::Sortkeys = 1;
 
 362   my $output                    = Dumper($self);
 
 364   $self->{password} = $password;
 
 366   $main::lxdebug->leave_sub(2);
 
 372   $main::lxdebug->enter_sub(2);
 
 374   my ($self, $str) = @_;
 
 376   $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
 
 378   $main::lxdebug->leave_sub(2);
 
 384   $main::lxdebug->enter_sub(2);
 
 386   my ($self, $str) = @_;
 
 391   $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
 
 393   $main::lxdebug->leave_sub(2);
 
 399   $main::lxdebug->enter_sub();
 
 400   my ($self, $str) = @_;
 
 402   if ($str && !ref($str)) {
 
 403     $str =~ s/\"/"/g;
 
 406   $main::lxdebug->leave_sub();
 
 412   $main::lxdebug->enter_sub();
 
 413   my ($self, $str) = @_;
 
 415   if ($str && !ref($str)) {
 
 416     $str =~ s/"/\"/g;
 
 419   $main::lxdebug->leave_sub();
 
 425   $main::lxdebug->enter_sub();
 
 429     map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
 
 431     for (sort keys %$self) {
 
 432       next if (($_ eq "header") || (ref($self->{$_}) ne ""));
 
 433       print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
 
 436   $main::lxdebug->leave_sub();
 
 440   $main::lxdebug->enter_sub();
 
 442   $main::lxdebug->show_backtrace();
 
 444   my ($self, $msg) = @_;
 
 445   if ($ENV{HTTP_USER_AGENT}) {
 
 447     $self->show_generic_error($msg);
 
 454   $main::lxdebug->leave_sub();
 
 458   $main::lxdebug->enter_sub();
 
 460   my ($self, $msg) = @_;
 
 462   if ($ENV{HTTP_USER_AGENT}) {
 
 465     if (!$self->{header}) {
 
 478     if ($self->{info_function}) {
 
 479       &{ $self->{info_function} }($msg);
 
 485   $main::lxdebug->leave_sub();
 
 488 # calculates the number of rows in a textarea based on the content and column number
 
 489 # can be capped with maxrows
 
 491   $main::lxdebug->enter_sub();
 
 492   my ($self, $str, $cols, $maxrows, $minrows) = @_;
 
 496   my $rows   = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
 
 499   $main::lxdebug->leave_sub();
 
 501   return max(min($rows, $maxrows), $minrows);
 
 505   $main::lxdebug->enter_sub();
 
 507   my ($self, $msg) = @_;
 
 509   $self->error("$msg\n" . $DBI::errstr);
 
 511   $main::lxdebug->leave_sub();
 
 515   $main::lxdebug->enter_sub();
 
 517   my ($self, $name, $msg) = @_;
 
 520   foreach my $part (split m/\./, $name) {
 
 521     if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
 
 524     $curr = $curr->{$part};
 
 527   $main::lxdebug->leave_sub();
 
 530 sub create_http_response {
 
 531   $main::lxdebug->enter_sub();
 
 536   my $cgi      = $main::cgi;
 
 537   $cgi       ||= CGI->new('');
 
 541   if ($ENV{HTTP_X_FORWARDED_FOR}) {
 
 542     $base_path =  $ENV{HTTP_REFERER};
 
 543     $base_path =~ s|^.*?://.*?/|/|;
 
 545     $base_path =  $ENV{REQUEST_URI};
 
 547   $base_path =~ s|[^/]+$||;
 
 548   $base_path =~ s|/$||;
 
 551   if (defined $main::auth) {
 
 552     my $session_cookie_value   = $main::auth->get_session_id();
 
 553     $session_cookie_value    ||= 'NO_SESSION';
 
 555     $session_cookie = $cgi->cookie('-name'  => $main::auth->get_session_cookie_name(),
 
 556                                    '-value' => $session_cookie_value,
 
 557                                    '-path'  => $base_path);
 
 560   my %cgi_params = ('-type' => $params{content_type});
 
 561   $cgi_params{'-charset'} = $params{charset} if ($params{charset});
 
 563   my $output = $cgi->header('-cookie' => $session_cookie,
 
 566   $main::lxdebug->leave_sub();
 
 573   $main::lxdebug->enter_sub();
 
 575   my ($self, $extra_code) = @_;
 
 577   if ($self->{header}) {
 
 578     $main::lxdebug->leave_sub();
 
 582   my ($stylesheet, $favicon, $pagelayout);
 
 584   if ($ENV{HTTP_USER_AGENT}) {
 
 587     if ($ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+\d/) {
 
 588       # Only set the DOCTYPE for Internet Explorer. Other browsers have problems displaying the menu otherwise.
 
 589       $doctype = qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n|;
 
 592     my $stylesheets = "$self->{stylesheet} $self->{stylesheets}";
 
 594     $stylesheets =~ s|^\s*||;
 
 595     $stylesheets =~ s|\s*$||;
 
 596     foreach my $file (split m/\s+/, $stylesheets) {
 
 598       next if (! -f "css/$file");
 
 600       $stylesheet .= qq|<link rel="stylesheet" href="css/$file" TYPE="text/css" TITLE="Lx-Office stylesheet">\n|;
 
 603     $self->{favicon}    = "favicon.ico" unless $self->{favicon};
 
 605     if ($self->{favicon} && (-f "$self->{favicon}")) {
 
 607         qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
 
 611     my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
 613     if ($self->{landscape}) {
 
 614       $pagelayout = qq|<style type="text/css">
 
 615                         \@page { size:landscape; }
 
 619     my $fokus = qq|  document.$self->{fokus}.focus();| if ($self->{"fokus"});
 
 623     if ($self->{jsscript} == 1) {
 
 626         <script type="text/javascript" src="js/common.js"></script>
 
 627         <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
 
 628         <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
 
 629         <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
 
 630         <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
 
 637       ? "$self->{title} - $self->{titlebar}"
 
 640     foreach my $item (@ { $self->{AJAX} }) {
 
 641       $ajax .= $item->show_javascript();
 
 644     print $self->create_http_response('content_type' => 'text/html',
 
 645                                       'charset'      => $db_charset,);
 
 646     print qq|${doctype}<html>
 
 648   <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
 
 649   <title>$self->{titlebar}</title>
 
 656   <script type="text/javascript">
 
 664   <meta name="robots" content="noindex,nofollow" />
 
 665   <script type="text/javascript" src="js/highlight_input.js"></script>
 
 667   <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
 
 668   <script type="text/javascript" src="js/tabcontent.js">
 
 670   /***********************************************
 
 671    * Tab Content script v2.2- Â© Dynamic Drive DHTML code library (www.dynamicdrive.com)
 
 672    * This notice MUST stay intact for legal use
 
 673    * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
 
 674    ***********************************************/
 
 685   $main::lxdebug->leave_sub();
 
 688 sub ajax_response_header {
 
 689   $main::lxdebug->enter_sub();
 
 693   my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
 694   my $cgi        = $main::cgi || CGI->new('');
 
 695   my $output     = $cgi->header('-charset' => $db_charset);
 
 697   $main::lxdebug->leave_sub();
 
 702 sub _prepare_html_template {
 
 703   $main::lxdebug->enter_sub();
 
 705   my ($self, $file, $additional_params) = @_;
 
 708   if (!defined(%main::myconfig) || !defined($main::myconfig{"countrycode"})) {
 
 709     $language = $main::language;
 
 711     $language = $main::myconfig{"countrycode"};
 
 713   $language = "de" unless ($language);
 
 715   if (-f "templates/webpages/${file}_${language}.html") {
 
 716     if ((-f ".developer") &&
 
 717         (-f "templates/webpages/${file}_master.html") &&
 
 718         ((stat("templates/webpages/${file}_master.html"))[9] >
 
 719          (stat("templates/webpages/${file}_${language}.html"))[9])) {
 
 720       my $info = "Developer information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
 
 721         "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 722       print(qq|<pre>$info</pre>|);
 
 726     $file = "templates/webpages/${file}_${language}.html";
 
 727   } elsif (-f "templates/webpages/${file}.html") {
 
 728     $file = "templates/webpages/${file}.html";
 
 730     my $info = "Web page template '${file}' not found.\n" .
 
 731       "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 732     print(qq|<pre>$info</pre>|);
 
 736   if ($self->{"DEBUG"}) {
 
 737     $additional_params->{"DEBUG"} = $self->{"DEBUG"};
 
 740   if ($additional_params->{"DEBUG"}) {
 
 741     $additional_params->{"DEBUG"} =
 
 742       "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
 
 745   if (%main::myconfig) {
 
 746     map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
 
 747     my $jsc_dateformat = $main::myconfig{"dateformat"};
 
 748     $jsc_dateformat =~ s/d+/\%d/gi;
 
 749     $jsc_dateformat =~ s/m+/\%m/gi;
 
 750     $jsc_dateformat =~ s/y+/\%Y/gi;
 
 751     $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
 
 754   $additional_params->{"conf_dbcharset"}              = $main::dbcharset;
 
 755   $additional_params->{"conf_webdav"}                 = $main::webdav;
 
 756   $additional_params->{"conf_lizenzen"}               = $main::lizenzen;
 
 757   $additional_params->{"conf_latex_templates"}        = $main::latex;
 
 758   $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
 
 760   if (%main::debug_options) {
 
 761     map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
 
 764   if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
 
 765     while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
 
 766       $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
 
 770   $main::lxdebug->leave_sub();
 
 775 sub parse_html_template {
 
 776   $main::lxdebug->enter_sub();
 
 778   my ($self, $file, $additional_params) = @_;
 
 780   $additional_params ||= { };
 
 782   $file = $self->_prepare_html_template($file, $additional_params);
 
 784   my $template = Template->new({ 'INTERPOLATE'  => 0,
 
 788                                  'PLUGIN_BASE'  => 'SL::Template::Plugin',
 
 789                                  'INCLUDE_PATH' => '.:templates/webpages',
 
 792   map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
 
 794   my $in = IO::File->new($file, 'r');
 
 797     print STDERR "Error opening template file: $!";
 
 798     $main::lxdebug->leave_sub();
 
 802   my $input = join('', <$in>);
 
 806     $input = $main::locale->{iconv}->convert($input);
 
 810   if (!$template->process(\$input, $additional_params, \$output)) {
 
 811     print STDERR $template->error();
 
 814   $main::lxdebug->leave_sub();
 
 819 sub show_generic_error {
 
 820   $main::lxdebug->enter_sub();
 
 822   my ($self, $error, %params) = @_;
 
 825     'title_error' => $params{title},
 
 826     'label_error' => $error,
 
 829   if ($params{action}) {
 
 832     map { delete($self->{$_}); } qw(action);
 
 833     map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
 
 835     $add_params->{SHOW_BUTTON}  = 1;
 
 836     $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
 
 837     $add_params->{VARIABLES}    = \@vars;
 
 839   } elsif ($params{back_button}) {
 
 840     $add_params->{SHOW_BACK_BUTTON} = 1;
 
 843   $self->{title} = $params{title} if $params{title};
 
 846   print $self->parse_html_template("generic/error", $add_params);
 
 848   $main::lxdebug->leave_sub();
 
 850   die("Error: $error\n");
 
 853 sub show_generic_information {
 
 854   $main::lxdebug->enter_sub();
 
 856   my ($self, $text, $title) = @_;
 
 859     'title_information' => $title,
 
 860     'label_information' => $text,
 
 863   $self->{title} = $title if ($title);
 
 866   print $self->parse_html_template("generic/information", $add_params);
 
 868   $main::lxdebug->leave_sub();
 
 870   die("Information: $text\n");
 
 873 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
 
 874 # changed it to accept an arbitrary number of triggers - sschoeling
 
 876   $main::lxdebug->enter_sub();
 
 879   my $myconfig = shift;
 
 882   # set dateform for jsscript
 
 885     "dd.mm.yy" => "%d.%m.%Y",
 
 886     "dd-mm-yy" => "%d-%m-%Y",
 
 887     "dd/mm/yy" => "%d/%m/%Y",
 
 888     "mm/dd/yy" => "%m/%d/%Y",
 
 889     "mm-dd-yy" => "%m-%d-%Y",
 
 890     "yyyy-mm-dd" => "%Y-%m-%d",
 
 893   my $ifFormat = defined($dateformats{$myconfig->{"dateformat"}}) ?
 
 894     $dateformats{$myconfig->{"dateformat"}} : "%d.%m.%Y";
 
 901       inputField : "| . (shift) . qq|",
 
 902       ifFormat :"$ifFormat",
 
 903       align : "| .  (shift) . qq|",
 
 904       button : "| . (shift) . qq|"
 
 910        <script type="text/javascript">
 
 911        <!--| . join("", @triggers) . qq|//-->
 
 915   $main::lxdebug->leave_sub();
 
 918 }    #end sub write_trigger
 
 921   $main::lxdebug->enter_sub();
 
 923   my ($self, $msg) = @_;
 
 925   if ($self->{callback}) {
 
 927     my ($script, $argv) = split(/\?/, $self->{callback}, 2);
 
 929     $script =~ s|[^a-zA-Z0-9_\.]||g;
 
 930     exec("perl", "$script", $argv);
 
 938   $main::lxdebug->leave_sub();
 
 941 # sort of columns removed - empty sub
 
 943   $main::lxdebug->enter_sub();
 
 945   my ($self, @columns) = @_;
 
 947   $main::lxdebug->leave_sub();
 
 953   $main::lxdebug->enter_sub(2);
 
 955   my ($self, $myconfig, $amount, $places, $dash) = @_;
 
 961   # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
 
 963   my $neg = ($amount =~ s/^-//);
 
 964   my $exp = ($amount =~ m/[e]/) ? 1 : 0;
 
 966   if (defined($places) && ($places ne '')) {
 
 972         my ($actual_places) = ($amount =~ /\.(\d+)/);
 
 973         $actual_places = length($actual_places);
 
 974         $places = $actual_places > $places ? $actual_places : $places;
 
 977     $amount = $self->round_amount($amount, $places);
 
 980   my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
 
 981   my @p = split(/\./, $amount); # split amount at decimal point
 
 983   $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
 
 986   $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
 
 989     ($dash =~ /-/)    ? ($neg ? "($amount)"                            : "$amount" )                              :
 
 990     ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
 
 991                         ($neg ? "-$amount"                             : "$amount" )                              ;
 
 995   $main::lxdebug->leave_sub(2);
 
 999 sub format_amount_units {
 
1000   $main::lxdebug->enter_sub();
 
1005   my $myconfig         = \%main::myconfig;
 
1006   my $amount           = $params{amount} * 1;
 
1007   my $places           = $params{places};
 
1008   my $part_unit_name   = $params{part_unit};
 
1009   my $amount_unit_name = $params{amount_unit};
 
1010   my $conv_units       = $params{conv_units};
 
1011   my $max_places       = $params{max_places};
 
1013   if (!$part_unit_name) {
 
1014     $main::lxdebug->leave_sub();
 
1018   AM->retrieve_all_units();
 
1019   my $all_units        = $main::all_units;
 
1021   if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
 
1022     $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
 
1025   if (!scalar @{ $conv_units }) {
 
1026     my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
 
1027     $main::lxdebug->leave_sub();
 
1031   my $part_unit  = $all_units->{$part_unit_name};
 
1032   my $conv_unit  = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
 
1034   $amount       *= $conv_unit->{factor};
 
1039   foreach my $unit (@$conv_units) {
 
1040     my $last = $unit->{name} eq $part_unit->{name};
 
1042       $num     = int($amount / $unit->{factor});
 
1043       $amount -= $num * $unit->{factor};
 
1046     if ($last ? $amount : $num) {
 
1047       push @values, { "unit"   => $unit->{name},
 
1048                       "amount" => $last ? $amount / $unit->{factor} : $num,
 
1049                       "places" => $last ? $places : 0 };
 
1056     push @values, { "unit"   => $part_unit_name,
 
1061   my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
 
1063   $main::lxdebug->leave_sub();
 
1069   $main::lxdebug->enter_sub(2);
 
1074   $input =~ s/(^|[^\#]) \#  (\d+)  /$1$_[$2 - 1]/gx;
 
1075   $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
 
1076   $input =~ s/\#\#/\#/g;
 
1078   $main::lxdebug->leave_sub(2);
 
1086   $main::lxdebug->enter_sub(2);
 
1088   my ($self, $myconfig, $amount) = @_;
 
1090   if (   ($myconfig->{numberformat} eq '1.000,00')
 
1091       || ($myconfig->{numberformat} eq '1000,00')) {
 
1096   if ($myconfig->{numberformat} eq "1'000.00") {
 
1102   $main::lxdebug->leave_sub(2);
 
1104   return ($amount * 1);
 
1108   $main::lxdebug->enter_sub(2);
 
1110   my ($self, $amount, $places) = @_;
 
1113   # Rounding like "Kaufmannsrunden"
 
1114   # Descr. http://de.wikipedia.org/wiki/Rundung
 
1116   # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
 
1119   $amount = $amount * (10**($places));
 
1120   $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
 
1122   $main::lxdebug->leave_sub(2);
 
1124   return $round_amount;
 
1128 sub parse_template {
 
1129   $main::lxdebug->enter_sub();
 
1131   my ($self, $myconfig, $userspath) = @_;
 
1132   my ($template, $out);
 
1136   $self->{"cwd"} = getcwd();
 
1137   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
 
1141   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
 
1142     $template       = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1143     $ext_for_format = 'odt';
 
1145   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
 
1146     $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
 
1147     $template         = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1148     $ext_for_format   = 'pdf';
 
1150   } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
 
1151     $template       = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1152     $ext_for_format = 'html';
 
1154   } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
 
1155     $template       = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1156     $ext_for_format = 'xml';
 
1158   } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
 
1159     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1161   } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
 
1162     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1164   } elsif ( defined $self->{'format'}) {
 
1165     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
 
1167   } elsif ( $self->{'format'} eq '' ) {
 
1168     $self->error("No Outputformat given: $self->{'format'}");
 
1170   } else { #Catch the rest
 
1171     $self->error("Outputformat not defined: $self->{'format'}");
 
1174   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
 
1175   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
 
1177   if (!$self->{employee_id}) {
 
1178     map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
 
1181   map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
 
1183   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
 
1185   # OUT is used for the media, screen, printer, email
 
1186   # for postscript we store a copy in a temporary file
 
1188   my $prepend_userspath;
 
1190   if (!$self->{tmpfile}) {
 
1191     $self->{tmpfile}   = "${fileid}.$self->{IN}";
 
1192     $prepend_userspath = 1;
 
1195   $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
 
1197   $self->{tmpfile} =~ s|.*/||;
 
1198   $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
 
1199   $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
 
1201   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
1202     $out = $self->{OUT};
 
1203     $self->{OUT} = ">$self->{tmpfile}";
 
1207     open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
 
1209     open(OUT, ">-") or $self->error("STDOUT : $!");
 
1213   if (!$template->parse(*OUT)) {
 
1215     $self->error("$self->{IN} : " . $template->get_error());
 
1220   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
1222     if ($self->{media} eq 'email') {
 
1224       my $mail = new Mailer;
 
1226       map { $mail->{$_} = $self->{$_} }
 
1227         qw(cc bcc subject message version format);
 
1228       $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
1229       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
 
1230       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
 
1231       $mail->{fileid} = "$fileid.";
 
1232       $myconfig->{signature} =~ s/\r//g;
 
1234       # if we send html or plain text inline
 
1235       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
 
1236         $mail->{contenttype} = "text/html";
 
1238         $mail->{message}       =~ s/\r//g;
 
1239         $mail->{message}       =~ s/\n/<br>\n/g;
 
1240         $myconfig->{signature} =~ s/\n/<br>\n/g;
 
1241         $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
 
1243         open(IN, $self->{tmpfile})
 
1244           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1246           $mail->{message} .= $_;
 
1253         if (!$self->{"do_not_attach"}) {
 
1254           my $attachment_name  =  $self->{attachment_filename} || $self->{tmpfile};
 
1255           $attachment_name     =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
 
1256           $mail->{attachments} =  [{ "filename" => $self->{tmpfile},
 
1257                                      "name"     => $attachment_name }];
 
1260         $mail->{message}  =~ s/\r//g;
 
1261         $mail->{message} .=  "\n-- \n$myconfig->{signature}";
 
1265       my $err = $mail->send();
 
1266       $self->error($self->cleanup . "$err") if ($err);
 
1270       $self->{OUT} = $out;
 
1272       my $numbytes = (-s $self->{tmpfile});
 
1273       open(IN, $self->{tmpfile})
 
1274         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1276       $self->{copies} = 1 unless $self->{media} eq 'printer';
 
1278       chdir("$self->{cwd}");
 
1279       #print(STDERR "Kopien $self->{copies}\n");
 
1280       #print(STDERR "OUT $self->{OUT}\n");
 
1281       for my $i (1 .. $self->{copies}) {
 
1283           open(OUT, $self->{OUT})
 
1284             or $self->error($self->cleanup . "$self->{OUT} : $!");
 
1286           $self->{attachment_filename} = ($self->{attachment_filename})
 
1287                                        ? $self->{attachment_filename}
 
1288                                        : $self->generate_attachment_filename();
 
1290           # launch application
 
1291           print qq|Content-Type: | . $template->get_mime_type() . qq|
 
1292 Content-Disposition: attachment; filename="$self->{attachment_filename}"
 
1293 Content-Length: $numbytes
 
1297           open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
 
1317   chdir("$self->{cwd}");
 
1318   $main::lxdebug->leave_sub();
 
1321 sub get_formname_translation {
 
1322   $main::lxdebug->enter_sub();
 
1323   my ($self, $formname) = @_;
 
1325   $formname ||= $self->{formname};
 
1327   my %formname_translations = (
 
1328     bin_list                => $main::locale->text('Bin List'),
 
1329     credit_note             => $main::locale->text('Credit Note'),
 
1330     invoice                 => $main::locale->text('Invoice'),
 
1331     packing_list            => $main::locale->text('Packing List'),
 
1332     pick_list               => $main::locale->text('Pick List'),
 
1333     proforma                => $main::locale->text('Proforma Invoice'),
 
1334     purchase_order          => $main::locale->text('Purchase Order'),
 
1335     request_quotation       => $main::locale->text('RFQ'),
 
1336     sales_order             => $main::locale->text('Confirmation'),
 
1337     sales_quotation         => $main::locale->text('Quotation'),
 
1338     storno_invoice          => $main::locale->text('Storno Invoice'),
 
1339     storno_packing_list     => $main::locale->text('Storno Packing List'),
 
1340     sales_delivery_order    => $main::locale->text('Delivery Order'),
 
1341     purchase_delivery_order => $main::locale->text('Delivery Order'),
 
1344   $main::lxdebug->leave_sub();
 
1345   return $formname_translations{$formname}
 
1348 sub get_number_prefix_for_type {
 
1349   $main::lxdebug->enter_sub();
 
1353       (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
 
1354     : ($self->{type} =~ /_quotation$/)                        ? 'quo'
 
1355     : ($self->{type} =~ /_delivery_order$/)                   ? 'do'
 
1358   $main::lxdebug->leave_sub();
 
1362 sub get_extension_for_format {
 
1363   $main::lxdebug->enter_sub();
 
1366   my $extension = $self->{format} =~ /pdf/i          ? ".pdf"
 
1367                 : $self->{format} =~ /postscript/i   ? ".ps"
 
1368                 : $self->{format} =~ /opendocument/i ? ".odt"
 
1369                 : $self->{format} =~ /html/i         ? ".html"
 
1372   $main::lxdebug->leave_sub();
 
1376 sub generate_attachment_filename {
 
1377   $main::lxdebug->enter_sub();
 
1380   my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
 
1381   my $prefix              = $self->get_number_prefix_for_type();
 
1383   if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
 
1384     $attachment_filename .= ' (' . $main::locale->text('Preview') . ')' . $self->get_extension_for_format();
 
1386   } elsif ($attachment_filename && $self->{"${prefix}number"}) {
 
1387     $attachment_filename .=  "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
 
1390     $attachment_filename = "";
 
1393   $attachment_filename =  $main::locale->quote_special_chars('filenames', $attachment_filename);
 
1394   $attachment_filename =~ s|[\s/\\]+|_|g;
 
1396   $main::lxdebug->leave_sub();
 
1397   return $attachment_filename;
 
1400 sub generate_email_subject {
 
1401   $main::lxdebug->enter_sub();
 
1404   my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
 
1405   my $prefix  = $self->get_number_prefix_for_type();
 
1407   if ($subject && $self->{"${prefix}number"}) {
 
1408     $subject .= " " . $self->{"${prefix}number"}
 
1411   $main::lxdebug->leave_sub();
 
1416   $main::lxdebug->enter_sub();
 
1420   chdir("$self->{tmpdir}");
 
1423   if (-f "$self->{tmpfile}.err") {
 
1424     open(FH, "$self->{tmpfile}.err");
 
1429   if ($self->{tmpfile}) {
 
1430     $self->{tmpfile} =~ s|.*/||g;
 
1432     $self->{tmpfile} =~ s/\.\w+$//g;
 
1433     my $tmpfile = $self->{tmpfile};
 
1434     unlink(<$tmpfile.*>);
 
1437   chdir("$self->{cwd}");
 
1439   $main::lxdebug->leave_sub();
 
1445   $main::lxdebug->enter_sub();
 
1447   my ($self, $date, $myconfig) = @_;
 
1450   if ($date && $date =~ /\D/) {
 
1452     if ($myconfig->{dateformat} =~ /^yy/) {
 
1453       ($yy, $mm, $dd) = split /\D/, $date;
 
1455     if ($myconfig->{dateformat} =~ /^mm/) {
 
1456       ($mm, $dd, $yy) = split /\D/, $date;
 
1458     if ($myconfig->{dateformat} =~ /^dd/) {
 
1459       ($dd, $mm, $yy) = split /\D/, $date;
 
1464     $yy = ($yy < 70) ? $yy + 2000 : $yy;
 
1465     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
 
1467     $dd = "0$dd" if ($dd < 10);
 
1468     $mm = "0$mm" if ($mm < 10);
 
1470     $date = "$yy$mm$dd";
 
1473   $main::lxdebug->leave_sub();
 
1478 # Database routines used throughout
 
1481   $main::lxdebug->enter_sub(2);
 
1483   my ($self, $myconfig) = @_;
 
1485   # connect to database
 
1487     DBI->connect($myconfig->{dbconnect},
 
1488                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
 
1492   if ($myconfig->{dboptions}) {
 
1493     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1496   $main::lxdebug->leave_sub(2);
 
1501 sub dbconnect_noauto {
 
1502   $main::lxdebug->enter_sub();
 
1504   my ($self, $myconfig) = @_;
 
1506   # connect to database
 
1508     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
 
1509                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
 
1513   if ($myconfig->{dboptions}) {
 
1514     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1517   $main::lxdebug->leave_sub();
 
1522 sub get_standard_dbh {
 
1523   $main::lxdebug->enter_sub(2);
 
1525   my ($self, $myconfig) = @_;
 
1527   if ($standard_dbh && !$standard_dbh->{Active}) {
 
1528     $main::lxdebug->message(LXDebug::INFO, "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
 
1529     undef $standard_dbh;
 
1532   $standard_dbh ||= $self->dbconnect_noauto($myconfig);
 
1534   $main::lxdebug->leave_sub(2);
 
1536   return $standard_dbh;
 
1540   $main::lxdebug->enter_sub();
 
1542   my ($self, $date, $myconfig) = @_;
 
1543   my $dbh = $self->dbconnect($myconfig);
 
1545   my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
 
1546   my $sth = prepare_execute_query($self, $dbh, $query, $date);
 
1547   my ($closed) = $sth->fetchrow_array;
 
1549   $main::lxdebug->leave_sub();
 
1554 sub update_balance {
 
1555   $main::lxdebug->enter_sub();
 
1557   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
 
1559   # if we have a value, go do it
 
1562     # retrieve balance from table
 
1563     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
 
1564     my $sth = prepare_execute_query($self, $dbh, $query, @values);
 
1565     my ($balance) = $sth->fetchrow_array;
 
1571     $query = "UPDATE $table SET $field = $balance WHERE $where";
 
1572     do_query($self, $dbh, $query, @values);
 
1574   $main::lxdebug->leave_sub();
 
1577 sub update_exchangerate {
 
1578   $main::lxdebug->enter_sub();
 
1580   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
 
1582   # some sanity check for currency
 
1584     $main::lxdebug->leave_sub();
 
1587   $query = qq|SELECT curr FROM defaults|;
 
1589   my ($currency) = selectrow_query($self, $dbh, $query);
 
1590   my ($defaultcurrency) = split m/:/, $currency;
 
1593   if ($curr eq $defaultcurrency) {
 
1594     $main::lxdebug->leave_sub();
 
1598   $query = qq|SELECT e.curr FROM exchangerate e
 
1599                  WHERE e.curr = ? AND e.transdate = ?
 
1601   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
 
1610   $buy = conv_i($buy, "NULL");
 
1611   $sell = conv_i($sell, "NULL");
 
1614   if ($buy != 0 && $sell != 0) {
 
1615     $set = "buy = $buy, sell = $sell";
 
1616   } elsif ($buy != 0) {
 
1617     $set = "buy = $buy";
 
1618   } elsif ($sell != 0) {
 
1619     $set = "sell = $sell";
 
1622   if ($sth->fetchrow_array) {
 
1623     $query = qq|UPDATE exchangerate
 
1629     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
 
1630                 VALUES (?, $buy, $sell, ?)|;
 
1633   do_query($self, $dbh, $query, $curr, $transdate);
 
1635   $main::lxdebug->leave_sub();
 
1638 sub save_exchangerate {
 
1639   $main::lxdebug->enter_sub();
 
1641   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
 
1643   my $dbh = $self->dbconnect($myconfig);
 
1647   $buy  = $rate if $fld eq 'buy';
 
1648   $sell = $rate if $fld eq 'sell';
 
1651   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
 
1656   $main::lxdebug->leave_sub();
 
1659 sub get_exchangerate {
 
1660   $main::lxdebug->enter_sub();
 
1662   my ($self, $dbh, $curr, $transdate, $fld) = @_;
 
1665   unless ($transdate) {
 
1666     $main::lxdebug->leave_sub();
 
1670   $query = qq|SELECT curr FROM defaults|;
 
1672   my ($currency) = selectrow_query($self, $dbh, $query);
 
1673   my ($defaultcurrency) = split m/:/, $currency;
 
1675   if ($currency eq $defaultcurrency) {
 
1676     $main::lxdebug->leave_sub();
 
1680   $query = qq|SELECT e.$fld FROM exchangerate e
 
1681                  WHERE e.curr = ? AND e.transdate = ?|;
 
1682   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
 
1686   $main::lxdebug->leave_sub();
 
1688   return $exchangerate;
 
1691 sub check_exchangerate {
 
1692   $main::lxdebug->enter_sub();
 
1694   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
 
1696   if ($fld !~/^buy|sell$/) {
 
1697     $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
 
1700   unless ($transdate) {
 
1701     $main::lxdebug->leave_sub();
 
1705   my ($defaultcurrency) = $self->get_default_currency($myconfig);
 
1707   if ($currency eq $defaultcurrency) {
 
1708     $main::lxdebug->leave_sub();
 
1712   my $dbh   = $self->get_standard_dbh($myconfig);
 
1713   my $query = qq|SELECT e.$fld FROM exchangerate e
 
1714                  WHERE e.curr = ? AND e.transdate = ?|;
 
1716   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
 
1718   $main::lxdebug->leave_sub();
 
1720   return $exchangerate;
 
1723 sub get_default_currency {
 
1724   $main::lxdebug->enter_sub();
 
1726   my ($self, $myconfig) = @_;
 
1727   my $dbh = $self->get_standard_dbh($myconfig);
 
1729   my $query = qq|SELECT curr FROM defaults|;
 
1731   my ($curr)            = selectrow_query($self, $dbh, $query);
 
1732   my ($defaultcurrency) = split m/:/, $curr;
 
1734   $main::lxdebug->leave_sub();
 
1736   return $defaultcurrency;
 
1740 sub set_payment_options {
 
1741   $main::lxdebug->enter_sub();
 
1743   my ($self, $myconfig, $transdate) = @_;
 
1745   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
 
1747   my $dbh = $self->get_standard_dbh($myconfig);
 
1750     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
 
1751     qq|FROM payment_terms p | .
 
1754   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
 
1755    $self->{payment_terms}) =
 
1756      selectrow_query($self, $dbh, $query, $self->{payment_id});
 
1758   if ($transdate eq "") {
 
1759     if ($self->{invdate}) {
 
1760       $transdate = $self->{invdate};
 
1762       $transdate = $self->{transdate};
 
1767     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
 
1768     qq|FROM payment_terms|;
 
1769   ($self->{netto_date}, $self->{skonto_date}) =
 
1770     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
 
1772   my ($invtotal, $total);
 
1773   my (%amounts, %formatted_amounts);
 
1775   if ($self->{type} =~ /_order$/) {
 
1776     $amounts{invtotal} = $self->{ordtotal};
 
1777     $amounts{total}    = $self->{ordtotal};
 
1779   } elsif ($self->{type} =~ /_quotation$/) {
 
1780     $amounts{invtotal} = $self->{quototal};
 
1781     $amounts{total}    = $self->{quototal};
 
1784     $amounts{invtotal} = $self->{invtotal};
 
1785     $amounts{total}    = $self->{total};
 
1788   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
 
1790   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
 
1791   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
 
1792   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
 
1794   foreach (keys %amounts) {
 
1795     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
 
1796     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
 
1799   if ($self->{"language_id"}) {
 
1801       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
 
1802       qq|FROM translation_payment_terms t | .
 
1803       qq|LEFT JOIN language l ON t.language_id = l.id | .
 
1804       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
 
1805     my ($description_long, $output_numberformat, $output_dateformat,
 
1806       $output_longdates) =
 
1807       selectrow_query($self, $dbh, $query,
 
1808                       $self->{"language_id"}, $self->{"payment_id"});
 
1810     $self->{payment_terms} = $description_long if ($description_long);
 
1812     if ($output_dateformat) {
 
1813       foreach my $key (qw(netto_date skonto_date)) {
 
1815           $main::locale->reformat_date($myconfig, $self->{$key},
 
1821     if ($output_numberformat &&
 
1822         ($output_numberformat ne $myconfig->{"numberformat"})) {
 
1823       my $saved_numberformat = $myconfig->{"numberformat"};
 
1824       $myconfig->{"numberformat"} = $output_numberformat;
 
1825       map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
 
1826       $myconfig->{"numberformat"} = $saved_numberformat;
 
1830   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
 
1831   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
 
1832   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
 
1833   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
 
1834   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
 
1835   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
 
1836   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
 
1838   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
 
1840   $main::lxdebug->leave_sub();
 
1844 sub get_template_language {
 
1845   $main::lxdebug->enter_sub();
 
1847   my ($self, $myconfig) = @_;
 
1849   my $template_code = "";
 
1851   if ($self->{language_id}) {
 
1852     my $dbh = $self->get_standard_dbh($myconfig);
 
1853     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
 
1854     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
 
1857   $main::lxdebug->leave_sub();
 
1859   return $template_code;
 
1862 sub get_printer_code {
 
1863   $main::lxdebug->enter_sub();
 
1865   my ($self, $myconfig) = @_;
 
1867   my $template_code = "";
 
1869   if ($self->{printer_id}) {
 
1870     my $dbh = $self->get_standard_dbh($myconfig);
 
1871     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
 
1872     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
 
1875   $main::lxdebug->leave_sub();
 
1877   return $template_code;
 
1881   $main::lxdebug->enter_sub();
 
1883   my ($self, $myconfig) = @_;
 
1885   my $template_code = "";
 
1887   if ($self->{shipto_id}) {
 
1888     my $dbh = $self->get_standard_dbh($myconfig);
 
1889     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
 
1890     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
 
1891     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
 
1894   $main::lxdebug->leave_sub();
 
1898   $main::lxdebug->enter_sub();
 
1900   my ($self, $dbh, $id, $module) = @_;
 
1905   foreach my $item (qw(name department_1 department_2 street zipcode city country
 
1906                        contact phone fax email)) {
 
1907     if ($self->{"shipto$item"}) {
 
1908       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
 
1910     push(@values, $self->{"shipto${item}"});
 
1914     if ($self->{shipto_id}) {
 
1915       my $query = qq|UPDATE shipto set
 
1917                        shiptodepartment_1 = ?,
 
1918                        shiptodepartment_2 = ?,
 
1927                      WHERE shipto_id = ?|;
 
1928       do_query($self, $dbh, $query, @values, $self->{shipto_id});
 
1930       my $query = qq|SELECT * FROM shipto
 
1931                      WHERE shiptoname = ? AND
 
1932                        shiptodepartment_1 = ? AND
 
1933                        shiptodepartment_2 = ? AND
 
1934                        shiptostreet = ? AND
 
1935                        shiptozipcode = ? AND
 
1937                        shiptocountry = ? AND
 
1938                        shiptocontact = ? AND
 
1944       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
 
1947           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
 
1948                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
 
1949                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
 
1950              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
 
1951         do_query($self, $dbh, $query, $id, @values, $module);
 
1956   $main::lxdebug->leave_sub();
 
1960   $main::lxdebug->enter_sub();
 
1962   my ($self, $dbh) = @_;
 
1964   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
 
1965   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
 
1966   $self->{"employee_id"} *= 1;
 
1968   $main::lxdebug->leave_sub();
 
1971 sub get_employee_data {
 
1972   $main::lxdebug->enter_sub();
 
1977   Common::check_params(\%params, qw(prefix));
 
1978   Common::check_params_x(\%params, qw(id));
 
1981     $main::lxdebug->leave_sub();
 
1985   my $myconfig = \%main::myconfig;
 
1986   my $dbh      = $params{dbh} || $self->get_standard_dbh($myconfig);
 
1988   my ($login)  = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
 
1991     my $user = User->new($login);
 
1992     map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
 
1994     $self->{$params{prefix} . '_login'}   = $login;
 
1995     $self->{$params{prefix} . '_name'}  ||= $login;
 
1998   $main::lxdebug->leave_sub();
 
2002   $main::lxdebug->enter_sub();
 
2004   my ($self, $myconfig, $reference_date) = @_;
 
2006   my $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
 
2008   my $dbh            = $self->get_standard_dbh($myconfig);
 
2009   my $query          = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
 
2010   my ($duedate)      = selectrow_query($self, $dbh, $query, $self->{payment_id});
 
2012   $main::lxdebug->leave_sub();
 
2018   $main::lxdebug->enter_sub();
 
2020   my ($self, $dbh, $id, $key) = @_;
 
2022   $key = "all_contacts" unless ($key);
 
2026     $main::lxdebug->leave_sub();
 
2031     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
 
2032     qq|FROM contacts | .
 
2033     qq|WHERE cp_cv_id = ? | .
 
2034     qq|ORDER BY lower(cp_name)|;
 
2036   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
 
2038   $main::lxdebug->leave_sub();
 
2042   $main::lxdebug->enter_sub();
 
2044   my ($self, $dbh, $key) = @_;
 
2046   my ($all, $old_id, $where, @values);
 
2048   if (ref($key) eq "HASH") {
 
2051     $key = "ALL_PROJECTS";
 
2053     foreach my $p (keys(%{$params})) {
 
2055         $all = $params->{$p};
 
2056       } elsif ($p eq "old_id") {
 
2057         $old_id = $params->{$p};
 
2058       } elsif ($p eq "key") {
 
2059         $key = $params->{$p};
 
2065     $where = "WHERE active ";
 
2067       if (ref($old_id) eq "ARRAY") {
 
2068         my @ids = grep({ $_ } @{$old_id});
 
2070           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
 
2071           push(@values, @ids);
 
2074         $where .= " OR (id = ?) ";
 
2075         push(@values, $old_id);
 
2081     qq|SELECT id, projectnumber, description, active | .
 
2084     qq|ORDER BY lower(projectnumber)|;
 
2086   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
 
2088   $main::lxdebug->leave_sub();
 
2092   $main::lxdebug->enter_sub();
 
2094   my ($self, $dbh, $vc_id, $key) = @_;
 
2096   $key = "all_shipto" unless ($key);
 
2099     # get shipping addresses
 
2100     my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
 
2102     $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
 
2108   $main::lxdebug->leave_sub();
 
2112   $main::lxdebug->enter_sub();
 
2114   my ($self, $dbh, $key) = @_;
 
2116   $key = "all_printers" unless ($key);
 
2118   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
 
2120   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2122   $main::lxdebug->leave_sub();
 
2126   $main::lxdebug->enter_sub();
 
2128   my ($self, $dbh, $params) = @_;
 
2131   $key = $params->{key};
 
2132   $key = "all_charts" unless ($key);
 
2134   my $transdate = quote_db_date($params->{transdate});
 
2137     qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
 
2139     qq|LEFT JOIN taxkeys tk ON | .
 
2140     qq|(tk.id = (SELECT id FROM taxkeys | .
 
2141     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
 
2142     qq|          ORDER BY startdate DESC LIMIT 1)) | .
 
2143     qq|ORDER BY c.accno|;
 
2145   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2147   $main::lxdebug->leave_sub();
 
2150 sub _get_taxcharts {
 
2151   $main::lxdebug->enter_sub();
 
2153   my ($self, $dbh, $params) = @_;
 
2155   my $key = "all_taxcharts";
 
2158   if (ref $params eq 'HASH') {
 
2159     $key = $params->{key} if ($params->{key});
 
2160     if ($params->{module} eq 'AR') {
 
2161       push @where, 'taxkey NOT IN (8, 9, 18, 19)';
 
2163     } elsif ($params->{module} eq 'AP') {
 
2164       push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
 
2171   my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
 
2173   my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
 
2175   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2177   $main::lxdebug->leave_sub();
 
2181   $main::lxdebug->enter_sub();
 
2183   my ($self, $dbh, $key) = @_;
 
2185   $key = "all_taxzones" unless ($key);
 
2187   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
 
2189   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2191   $main::lxdebug->leave_sub();
 
2194 sub _get_employees {
 
2195   $main::lxdebug->enter_sub();
 
2197   my ($self, $dbh, $default_key, $key) = @_;
 
2199   $key = $default_key unless ($key);
 
2200   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
 
2202   $main::lxdebug->leave_sub();
 
2205 sub _get_business_types {
 
2206   $main::lxdebug->enter_sub();
 
2208   my ($self, $dbh, $key) = @_;
 
2210   $key = "all_business_types" unless ($key);
 
2212     selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
 
2214   $main::lxdebug->leave_sub();
 
2217 sub _get_languages {
 
2218   $main::lxdebug->enter_sub();
 
2220   my ($self, $dbh, $key) = @_;
 
2222   $key = "all_languages" unless ($key);
 
2224   my $query = qq|SELECT * FROM language ORDER BY id|;
 
2226   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2228   $main::lxdebug->leave_sub();
 
2231 sub _get_dunning_configs {
 
2232   $main::lxdebug->enter_sub();
 
2234   my ($self, $dbh, $key) = @_;
 
2236   $key = "all_dunning_configs" unless ($key);
 
2238   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
 
2240   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2242   $main::lxdebug->leave_sub();
 
2245 sub _get_currencies {
 
2246 $main::lxdebug->enter_sub();
 
2248   my ($self, $dbh, $key) = @_;
 
2250   $key = "all_currencies" unless ($key);
 
2252   my $query = qq|SELECT curr AS currency FROM defaults|;
 
2254   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
 
2256   $main::lxdebug->leave_sub();
 
2260 $main::lxdebug->enter_sub();
 
2262   my ($self, $dbh, $key) = @_;
 
2264   $key = "all_payments" unless ($key);
 
2266   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
 
2268   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2270   $main::lxdebug->leave_sub();
 
2273 sub _get_customers {
 
2274   $main::lxdebug->enter_sub();
 
2276   my ($self, $dbh, $key, $limit) = @_;
 
2278   $key = "all_customers" unless ($key);
 
2279   my $limit_clause = "LIMIT $limit" if $limit;
 
2281   my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name $limit_clause|;
 
2283   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2285   $main::lxdebug->leave_sub();
 
2289   $main::lxdebug->enter_sub();
 
2291   my ($self, $dbh, $key) = @_;
 
2293   $key = "all_vendors" unless ($key);
 
2295   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
 
2297   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2299   $main::lxdebug->leave_sub();
 
2302 sub _get_departments {
 
2303   $main::lxdebug->enter_sub();
 
2305   my ($self, $dbh, $key) = @_;
 
2307   $key = "all_departments" unless ($key);
 
2309   my $query = qq|SELECT * FROM department ORDER BY description|;
 
2311   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2313   $main::lxdebug->leave_sub();
 
2316 sub _get_warehouses {
 
2317   $main::lxdebug->enter_sub();
 
2319   my ($self, $dbh, $param) = @_;
 
2321   my ($key, $bins_key);
 
2323   if ('' eq ref $param) {
 
2327     $key      = $param->{key};
 
2328     $bins_key = $param->{bins};
 
2331   my $query = qq|SELECT w.* FROM warehouse w
 
2332                  WHERE (NOT w.invalid) AND
 
2333                    ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
 
2334                  ORDER BY w.sortkey|;
 
2336   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2339     $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
 
2340     my $sth = prepare_query($self, $dbh, $query);
 
2342     foreach my $warehouse (@{ $self->{$key} }) {
 
2343       do_statement($self, $sth, $query, $warehouse->{id});
 
2344       $warehouse->{$bins_key} = [];
 
2346       while (my $ref = $sth->fetchrow_hashref()) {
 
2347         push @{ $warehouse->{$bins_key} }, $ref;
 
2353   $main::lxdebug->leave_sub();
 
2357   $main::lxdebug->enter_sub();
 
2359   my ($self, $dbh, $table, $key, $sortkey) = @_;
 
2361   my $query  = qq|SELECT * FROM $table|;
 
2362   $query    .= qq| ORDER BY $sortkey| if ($sortkey);
 
2364   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2366   $main::lxdebug->leave_sub();
 
2370 #  $main::lxdebug->enter_sub();
 
2372 #  my ($self, $dbh, $key) = @_;
 
2374 #  $key ||= "all_groups";
 
2376 #  my $groups = $main::auth->read_groups();
 
2378 #  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2380 #  $main::lxdebug->leave_sub();
 
2384   $main::lxdebug->enter_sub();
 
2389   my $dbh = $self->get_standard_dbh(\%main::myconfig);
 
2390   my ($sth, $query, $ref);
 
2392   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
 
2393   my $vc_id = $self->{"${vc}_id"};
 
2395   if ($params{"contacts"}) {
 
2396     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
 
2399   if ($params{"shipto"}) {
 
2400     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
 
2403   if ($params{"projects"} || $params{"all_projects"}) {
 
2404     $self->_get_projects($dbh, $params{"all_projects"} ?
 
2405                          $params{"all_projects"} : $params{"projects"},
 
2406                          $params{"all_projects"} ? 1 : 0);
 
2409   if ($params{"printers"}) {
 
2410     $self->_get_printers($dbh, $params{"printers"});
 
2413   if ($params{"languages"}) {
 
2414     $self->_get_languages($dbh, $params{"languages"});
 
2417   if ($params{"charts"}) {
 
2418     $self->_get_charts($dbh, $params{"charts"});
 
2421   if ($params{"taxcharts"}) {
 
2422     $self->_get_taxcharts($dbh, $params{"taxcharts"});
 
2425   if ($params{"taxzones"}) {
 
2426     $self->_get_taxzones($dbh, $params{"taxzones"});
 
2429   if ($params{"employees"}) {
 
2430     $self->_get_employees($dbh, "all_employees", $params{"employees"});
 
2433   if ($params{"salesmen"}) {
 
2434     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
 
2437   if ($params{"business_types"}) {
 
2438     $self->_get_business_types($dbh, $params{"business_types"});
 
2441   if ($params{"dunning_configs"}) {
 
2442     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
 
2445   if($params{"currencies"}) {
 
2446     $self->_get_currencies($dbh, $params{"currencies"});
 
2449   if($params{"customers"}) {
 
2450     if (ref $params{"customers"} eq 'HASH') {
 
2451       $self->_get_customers($dbh, $params{"customers"}{key}, $params{"customers"}{limit});
 
2453       $self->_get_customers($dbh, $params{"customers"});
 
2457   if($params{"vendors"}) {
 
2458     if (ref $params{"vendors"} eq 'HASH') {
 
2459       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
 
2461       $self->_get_vendors($dbh, $params{"vendors"});
 
2465   if($params{"payments"}) {
 
2466     $self->_get_payments($dbh, $params{"payments"});
 
2469   if($params{"departments"}) {
 
2470     $self->_get_departments($dbh, $params{"departments"});
 
2473   if ($params{price_factors}) {
 
2474     $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
 
2477   if ($params{warehouses}) {
 
2478     $self->_get_warehouses($dbh, $params{warehouses});
 
2481 #  if ($params{groups}) {
 
2482 #    $self->_get_groups($dbh, $params{groups});
 
2485   if ($params{partsgroup}) {
 
2486     $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
 
2489   $main::lxdebug->leave_sub();
 
2492 # this sub gets the id and name from $table
 
2494   $main::lxdebug->enter_sub();
 
2496   my ($self, $myconfig, $table) = @_;
 
2498   # connect to database
 
2499   my $dbh = $self->get_standard_dbh($myconfig);
 
2501   $table = $table eq "customer" ? "customer" : "vendor";
 
2502   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
 
2504   my ($query, @values);
 
2506   if (!$self->{openinvoices}) {
 
2508     if ($self->{customernumber} ne "") {
 
2509       $where = qq|(vc.customernumber ILIKE ?)|;
 
2510       push(@values, '%' . $self->{customernumber} . '%');
 
2512       $where = qq|(vc.name ILIKE ?)|;
 
2513       push(@values, '%' . $self->{$table} . '%');
 
2517       qq~SELECT vc.id, vc.name,
 
2518            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
2520          WHERE $where AND (NOT vc.obsolete)
 
2524       qq~SELECT DISTINCT vc.id, vc.name,
 
2525            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
2527          JOIN $table vc ON (a.${table}_id = vc.id)
 
2528          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
 
2530     push(@values, '%' . $self->{$table} . '%');
 
2533   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
 
2535   $main::lxdebug->leave_sub();
 
2537   return scalar(@{ $self->{name_list} });
 
2540 # the selection sub is used in the AR, AP, IS, IR and OE module
 
2543   $main::lxdebug->enter_sub();
 
2545   my ($self, $myconfig, $table, $module) = @_;
 
2548   my $dbh = $self->get_standard_dbh($myconfig);
 
2550   $table = $table eq "customer" ? "customer" : "vendor";
 
2552   my $query = qq|SELECT count(*) FROM $table|;
 
2553   my ($count) = selectrow_query($self, $dbh, $query);
 
2555   # build selection list
 
2556   if ($count < $myconfig->{vclimit}) {
 
2557     $query = qq|SELECT id, name, salesman_id
 
2558                 FROM $table WHERE NOT obsolete
 
2560     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
 
2564   $self->get_employee($dbh);
 
2566   # setup sales contacts
 
2567   $query = qq|SELECT e.id, e.name
 
2569               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
 
2570   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
 
2573   push(@{ $self->{all_employees} },
 
2574        { id   => $self->{employee_id},
 
2575          name => $self->{employee} });
 
2577   # sort the whole thing
 
2578   @{ $self->{all_employees} } =
 
2579     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
 
2581   if ($module eq 'AR') {
 
2583     # prepare query for departments
 
2584     $query = qq|SELECT id, description
 
2587                 ORDER BY description|;
 
2590     $query = qq|SELECT id, description
 
2592                 ORDER BY description|;
 
2595   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2598   $query = qq|SELECT id, description
 
2602   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2605   $query = qq|SELECT printer_description, id
 
2607               ORDER BY printer_description|;
 
2609   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2612   $query = qq|SELECT id, description
 
2616   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
2618   $main::lxdebug->leave_sub();
 
2621 sub language_payment {
 
2622   $main::lxdebug->enter_sub();
 
2624   my ($self, $myconfig) = @_;
 
2626   my $dbh = $self->get_standard_dbh($myconfig);
 
2628   my $query = qq|SELECT id, description
 
2632   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2635   $query = qq|SELECT printer_description, id
 
2637               ORDER BY printer_description|;
 
2639   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2642   $query = qq|SELECT id, description
 
2646   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
2648   # get buchungsgruppen
 
2649   $query = qq|SELECT id, description
 
2650               FROM buchungsgruppen|;
 
2652   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
 
2654   $main::lxdebug->leave_sub();
 
2657 # this is only used for reports
 
2658 sub all_departments {
 
2659   $main::lxdebug->enter_sub();
 
2661   my ($self, $myconfig, $table) = @_;
 
2663   my $dbh = $self->get_standard_dbh($myconfig);
 
2666   if ($table eq 'customer') {
 
2667     $where = "WHERE role = 'P' ";
 
2670   my $query = qq|SELECT id, description
 
2673                  ORDER BY description|;
 
2674   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2676   delete($self->{all_departments}) unless (@{ $self->{all_departments} });
 
2678   $main::lxdebug->leave_sub();
 
2682   $main::lxdebug->enter_sub();
 
2684   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
 
2687   if ($table eq "customer") {
 
2696   $self->all_vc($myconfig, $table, $module);
 
2698   # get last customers or vendors
 
2699   my ($query, $sth, $ref);
 
2701   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
 
2706     my $transdate = "current_date";
 
2707     if ($self->{transdate}) {
 
2708       $transdate = $dbh->quote($self->{transdate});
 
2711     # now get the account numbers
 
2712     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
 
2713                 FROM chart c, taxkeys tk
 
2714                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
 
2715                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
 
2718     $sth = $dbh->prepare($query);
 
2720     do_statement($self, $sth, $query, '%' . $module . '%');
 
2722     $self->{accounts} = "";
 
2723     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2725       foreach my $key (split(/:/, $ref->{link})) {
 
2726         if ($key =~ /\Q$module\E/) {
 
2728           # cross reference for keys
 
2729           $xkeyref{ $ref->{accno} } = $key;
 
2731           push @{ $self->{"${module}_links"}{$key} },
 
2732             { accno       => $ref->{accno},
 
2733               description => $ref->{description},
 
2734               taxkey      => $ref->{taxkey_id},
 
2735               tax_id      => $ref->{tax_id} };
 
2737           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2743   # get taxkeys and description
 
2744   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
 
2745   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
 
2747   if (($module eq "AP") || ($module eq "AR")) {
 
2748     # get tax rates and description
 
2749     $query = qq|SELECT * FROM tax|;
 
2750     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
 
2756            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
 
2757            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
 
2758            a.intnotes, a.department_id, a.amount AS oldinvtotal,
 
2759            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
 
2761            d.description AS department,
 
2764          JOIN $table c ON (a.${table}_id = c.id)
 
2765          LEFT JOIN employee e ON (e.id = a.employee_id)
 
2766          LEFT JOIN department d ON (d.id = a.department_id)
 
2768     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
 
2770     foreach my $key (keys %$ref) {
 
2771       $self->{$key} = $ref->{$key};
 
2774     my $transdate = "current_date";
 
2775     if ($self->{transdate}) {
 
2776       $transdate = $dbh->quote($self->{transdate});
 
2779     # now get the account numbers
 
2780     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
 
2782                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
 
2784                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
 
2785                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
 
2788     $sth = $dbh->prepare($query);
 
2789     do_statement($self, $sth, $query, "%$module%");
 
2791     $self->{accounts} = "";
 
2792     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2794       foreach my $key (split(/:/, $ref->{link})) {
 
2795         if ($key =~ /\Q$module\E/) {
 
2797           # cross reference for keys
 
2798           $xkeyref{ $ref->{accno} } = $key;
 
2800           push @{ $self->{"${module}_links"}{$key} },
 
2801             { accno       => $ref->{accno},
 
2802               description => $ref->{description},
 
2803               taxkey      => $ref->{taxkey_id},
 
2804               tax_id      => $ref->{tax_id} };
 
2806           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2812     # get amounts from individual entries
 
2815            c.accno, c.description,
 
2816            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
 
2820          LEFT JOIN chart c ON (c.id = a.chart_id)
 
2821          LEFT JOIN project p ON (p.id = a.project_id)
 
2822          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
 
2823                                     WHERE (tk.taxkey_id=a.taxkey) AND
 
2824                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
 
2825                                         THEN tk.chart_id = a.chart_id
 
2828                                        OR (c.link='%tax%')) AND
 
2829                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
 
2830          WHERE a.trans_id = ?
 
2831          AND a.fx_transaction = '0'
 
2832          ORDER BY a.acc_trans_id, a.transdate|;
 
2833     $sth = $dbh->prepare($query);
 
2834     do_statement($self, $sth, $query, $self->{id});
 
2836     # get exchangerate for currency
 
2837     $self->{exchangerate} =
 
2838       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2841     # store amounts in {acc_trans}{$key} for multiple accounts
 
2842     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
2843       $ref->{exchangerate} =
 
2844         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
 
2845       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
 
2848       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
 
2849         $ref->{amount} *= -1;
 
2851       $ref->{index} = $index;
 
2853       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
 
2859            d.curr AS currencies, d.closedto, d.revtrans,
 
2860            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2861            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
2863     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2864     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2871             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
 
2872             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2873             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
2875     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2876     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2878     if ($self->{"$self->{vc}_id"}) {
 
2880       # only setup currency
 
2881       ($self->{currency}) = split(/:/, $self->{currencies});
 
2885       $self->lastname_used($dbh, $myconfig, $table, $module);
 
2887       # get exchangerate for currency
 
2888       $self->{exchangerate} =
 
2889         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2895   $main::lxdebug->leave_sub();
 
2899   $main::lxdebug->enter_sub();
 
2901   my ($self, $dbh, $myconfig, $table, $module) = @_;
 
2905   $table         = $table eq "customer" ? "customer" : "vendor";
 
2906   my %column_map = ("a.curr"                  => "currency",
 
2907                     "a.${table}_id"           => "${table}_id",
 
2908                     "a.department_id"         => "department_id",
 
2909                     "d.description"           => "department",
 
2910                     "ct.name"                 => $table,
 
2911                     "current_date + ct.terms" => "duedate",
 
2914   if ($self->{type} =~ /delivery_order/) {
 
2915     $arap  = 'delivery_orders';
 
2916     delete $column_map{"a.curr"};
 
2918   } elsif ($self->{type} =~ /_order/) {
 
2920     $where = "quotation = '0'";
 
2922   } elsif ($self->{type} =~ /_quotation/) {
 
2924     $where = "quotation = '1'";
 
2926   } elsif ($table eq 'customer') {
 
2934   $where           = "($where) AND" if ($where);
 
2935   my $query        = qq|SELECT MAX(id) FROM $arap
 
2936                         WHERE $where ${table}_id > 0|;
 
2937   my ($trans_id)   = selectrow_query($self, $dbh, $query);
 
2940   my $column_spec  = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
 
2941   $query           = qq|SELECT $column_spec
 
2943                         LEFT JOIN $table     ct ON (a.${table}_id = ct.id)
 
2944                         LEFT JOIN department d  ON (a.department_id = d.id)
 
2946   my $ref          = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
 
2948   map { $self->{$_} = $ref->{$_} } values %column_map;
 
2950   $main::lxdebug->leave_sub();
 
2954   $main::lxdebug->enter_sub();
 
2956   my ($self, $myconfig, $thisdate, $days) = @_;
 
2958   my $dbh = $self->get_standard_dbh($myconfig);
 
2963     my $dateformat = $myconfig->{dateformat};
 
2964     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
 
2965     $thisdate = $dbh->quote($thisdate);
 
2966     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
 
2968     $query = qq|SELECT current_date AS thisdate|;
 
2971   ($thisdate) = selectrow_query($self, $dbh, $query);
 
2973   $main::lxdebug->leave_sub();
 
2979   $main::lxdebug->enter_sub();
 
2981   my ($self, $string) = @_;
 
2983   if ($string !~ /%/) {
 
2984     $string = "%$string%";
 
2987   $string =~ s/\'/\'\'/g;
 
2989   $main::lxdebug->leave_sub();
 
2995   $main::lxdebug->enter_sub();
 
2997   my ($self, $flds, $new, $count, $numrows) = @_;
 
3001   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
 
3006   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
 
3008     my $j = $item->{ndx} - 1;
 
3009     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
 
3013   for $i ($count + 1 .. $numrows) {
 
3014     map { delete $self->{"${_}_$i"} } @{$flds};
 
3017   $main::lxdebug->leave_sub();
 
3021   $main::lxdebug->enter_sub();
 
3023   my ($self, $myconfig) = @_;
 
3027   my $dbh = $self->dbconnect_noauto($myconfig);
 
3029   my $query = qq|DELETE FROM status
 
3030                  WHERE (formname = ?) AND (trans_id = ?)|;
 
3031   my $sth = prepare_query($self, $dbh, $query);
 
3033   if ($self->{formname} =~ /(check|receipt)/) {
 
3034     for $i (1 .. $self->{rowcount}) {
 
3035       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
 
3038     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
 
3042   my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3043   my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3045   my %queued = split / /, $self->{queued};
 
3048   if ($self->{formname} =~ /(check|receipt)/) {
 
3050     # this is a check or receipt, add one entry for each lineitem
 
3051     my ($accno) = split /--/, $self->{account};
 
3052     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
 
3053                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
 
3054     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
 
3055     $sth = prepare_query($self, $dbh, $query);
 
3057     for $i (1 .. $self->{rowcount}) {
 
3058       if ($self->{"checked_$i"}) {
 
3059         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
 
3065     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
3066                 VALUES (?, ?, ?, ?, ?)|;
 
3067     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
 
3068              $queued{$self->{formname}}, $self->{formname});
 
3074   $main::lxdebug->leave_sub();
 
3078   $main::lxdebug->enter_sub();
 
3080   my ($self, $dbh) = @_;
 
3082   my ($query, $printed, $emailed);
 
3084   my $formnames  = $self->{printed};
 
3085   my $emailforms = $self->{emailed};
 
3087   $query = qq|DELETE FROM status
 
3088                  WHERE (formname = ?) AND (trans_id = ?)|;
 
3089   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
 
3091   # this only applies to the forms
 
3092   # checks and receipts are posted when printed or queued
 
3094   if ($self->{queued}) {
 
3095     my %queued = split / /, $self->{queued};
 
3097     foreach my $formname (keys %queued) {
 
3098       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3099       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3101       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
3102                   VALUES (?, ?, ?, ?, ?)|;
 
3103       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
 
3105       $formnames  =~ s/\Q$self->{formname}\E//;
 
3106       $emailforms =~ s/\Q$self->{formname}\E//;
 
3111   # save printed, emailed info
 
3112   $formnames  =~ s/^ +//g;
 
3113   $emailforms =~ s/^ +//g;
 
3116   map { $status{$_}{printed} = 1 } split / +/, $formnames;
 
3117   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
 
3119   foreach my $formname (keys %status) {
 
3120     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3121     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
3123     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
 
3124                 VALUES (?, ?, ?, ?)|;
 
3125     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
 
3128   $main::lxdebug->leave_sub();
 
3132 # $main::locale->text('SAVED')
 
3133 # $main::locale->text('DELETED')
 
3134 # $main::locale->text('ADDED')
 
3135 # $main::locale->text('PAYMENT POSTED')
 
3136 # $main::locale->text('POSTED')
 
3137 # $main::locale->text('POSTED AS NEW')
 
3138 # $main::locale->text('ELSE')
 
3139 # $main::locale->text('SAVED FOR DUNNING')
 
3140 # $main::locale->text('DUNNING STARTED')
 
3141 # $main::locale->text('PRINTED')
 
3142 # $main::locale->text('MAILED')
 
3143 # $main::locale->text('SCREENED')
 
3144 # $main::locale->text('CANCELED')
 
3145 # $main::locale->text('invoice')
 
3146 # $main::locale->text('proforma')
 
3147 # $main::locale->text('sales_order')
 
3148 # $main::locale->text('packing_list')
 
3149 # $main::locale->text('pick_list')
 
3150 # $main::locale->text('purchase_order')
 
3151 # $main::locale->text('bin_list')
 
3152 # $main::locale->text('sales_quotation')
 
3153 # $main::locale->text('request_quotation')
 
3156   $main::lxdebug->enter_sub();
 
3161   if(!exists $self->{employee_id}) {
 
3162     &get_employee($self, $dbh);
 
3166    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
 
3167    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
 
3168   my @values = (conv_i($self->{id}), $self->{login},
 
3169                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
 
3170   do_query($self, $dbh, $query, @values);
 
3172   $main::lxdebug->leave_sub();
 
3176   $main::lxdebug->enter_sub();
 
3178   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
 
3179   my ($orderBy, $desc) = split(/\-\-/, $order);
 
3180   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
 
3183   if ($trans_id ne "") {
 
3185       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 | .
 
3186       qq|FROM history_erp h | .
 
3187       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
 
3188       qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
 
3191     my $sth = $dbh->prepare($query) || $self->dberror($query);
 
3193     $sth->execute() || $self->dberror("$query");
 
3195     while(my $hash_ref = $sth->fetchrow_hashref()) {
 
3196       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
 
3197       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
 
3198       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
 
3199       $tempArray[$i++] = $hash_ref;
 
3201     $main::lxdebug->leave_sub() and return \@tempArray
 
3202       if ($i > 0 && $tempArray[0] ne "");
 
3204   $main::lxdebug->leave_sub();
 
3208 sub update_defaults {
 
3209   $main::lxdebug->enter_sub();
 
3211   my ($self, $myconfig, $fld, $provided_dbh) = @_;
 
3214   if ($provided_dbh) {
 
3215     $dbh = $provided_dbh;
 
3217     $dbh = $self->dbconnect_noauto($myconfig);
 
3219   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
 
3220   my $sth   = $dbh->prepare($query);
 
3222   $sth->execute || $self->dberror($query);
 
3223   my ($var) = $sth->fetchrow_array;
 
3226   if ($var =~ m/\d+$/) {
 
3227     my $new_var  = (substr $var, $-[0]) * 1 + 1;
 
3228     my $len_diff = length($var) - $-[0] - length($new_var);
 
3229     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
 
3235   $query = qq|UPDATE defaults SET $fld = ?|;
 
3236   do_query($self, $dbh, $query, $var);
 
3238   if (!$provided_dbh) {
 
3243   $main::lxdebug->leave_sub();
 
3248 =item update_business
 
3251  \%config,     - config hashref
 
3252  $business_id, - business id
 
3253  $dbh          - optional database handle
 
3255 handles business (thats customer/vendor types) sequences.
 
3257 special behaviour for empty strings in customerinitnumber field:
 
3258 will in this case not increase the value, and return undef.
 
3261 sub update_business {
 
3262   $main::lxdebug->enter_sub();
 
3264   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
 
3267   if ($provided_dbh) {
 
3268     $dbh = $provided_dbh;
 
3270     $dbh = $self->dbconnect_noauto($myconfig);
 
3273     qq|SELECT customernumberinit FROM business
 
3274        WHERE id = ? FOR UPDATE|;
 
3275   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
 
3277   return undef unless $var;
 
3279   if ($var =~ m/\d+$/) {
 
3280     my $new_var  = (substr $var, $-[0]) * 1 + 1;
 
3281     my $len_diff = length($var) - $-[0] - length($new_var);
 
3282     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
 
3288   $query = qq|UPDATE business
 
3289               SET customernumberinit = ?
 
3291   do_query($self, $dbh, $query, $var, $business_id);
 
3293   if (!$provided_dbh) {
 
3298   $main::lxdebug->leave_sub();
 
3303 sub get_partsgroup {
 
3304   $main::lxdebug->enter_sub();
 
3306   my ($self, $myconfig, $p) = @_;
 
3307   my $target = $p->{target} || 'all_partsgroup';
 
3309   my $dbh = $self->get_standard_dbh($myconfig);
 
3311   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
 
3313                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
 
3316   if ($p->{searchitems} eq 'part') {
 
3317     $query .= qq|WHERE p.inventory_accno_id > 0|;
 
3319   if ($p->{searchitems} eq 'service') {
 
3320     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
 
3322   if ($p->{searchitems} eq 'assembly') {
 
3323     $query .= qq|WHERE p.assembly = '1'|;
 
3325   if ($p->{searchitems} eq 'labor') {
 
3326     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
 
3329   $query .= qq|ORDER BY partsgroup|;
 
3332     $query = qq|SELECT id, partsgroup FROM partsgroup
 
3333                 ORDER BY partsgroup|;
 
3336   if ($p->{language_code}) {
 
3337     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
 
3338                   t.description AS translation
 
3340                 JOIN parts p ON (p.partsgroup_id = pg.id)
 
3341                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
 
3342                 ORDER BY translation|;
 
3343     @values = ($p->{language_code});
 
3346   $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
 
3348   $main::lxdebug->leave_sub();
 
3351 sub get_pricegroup {
 
3352   $main::lxdebug->enter_sub();
 
3354   my ($self, $myconfig, $p) = @_;
 
3356   my $dbh = $self->get_standard_dbh($myconfig);
 
3358   my $query = qq|SELECT p.id, p.pricegroup
 
3361   $query .= qq| ORDER BY pricegroup|;
 
3364     $query = qq|SELECT id, pricegroup FROM pricegroup
 
3365                 ORDER BY pricegroup|;
 
3368   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
 
3370   $main::lxdebug->leave_sub();
 
3374 # usage $form->all_years($myconfig, [$dbh])
 
3375 # return list of all years where bookings found
 
3378   $main::lxdebug->enter_sub();
 
3380   my ($self, $myconfig, $dbh) = @_;
 
3382   $dbh ||= $self->get_standard_dbh($myconfig);
 
3385   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
 
3386                    (SELECT MAX(transdate) FROM acc_trans)|;
 
3387   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
 
3389   if ($myconfig->{dateformat} =~ /^yy/) {
 
3390     ($startdate) = split /\W/, $startdate;
 
3391     ($enddate) = split /\W/, $enddate;
 
3393     (@_) = split /\W/, $startdate;
 
3395     (@_) = split /\W/, $enddate;
 
3400   $startdate = substr($startdate,0,4);
 
3401   $enddate = substr($enddate,0,4);
 
3403   while ($enddate >= $startdate) {
 
3404     push @all_years, $enddate--;
 
3409   $main::lxdebug->leave_sub();
 
3413   $main::lxdebug->enter_sub();
 
3417   map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
 
3419   $main::lxdebug->leave_sub();
 
3423   $main::lxdebug->enter_sub();
 
3428   map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
 
3430   $main::lxdebug->leave_sub();