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 #======================================================================
 
  44 use List::Util qw(min max);
 
  56 use List::Util qw(max min sum);
 
  62     $standard_dbh->disconnect();
 
  68   $main::lxdebug->enter_sub(2);
 
  76   while ($key =~ /\[\+?\]\.|\./) {
 
  77     substr($key, 0, $+[0]) = '';
 
  85       if (!scalar @{ $curr->{$`} } || $& eq '[+].') {
 
  86         push @{ $curr->{$`} }, { };
 
  89       $curr = $curr->{$`}->[-1];
 
  93   $curr->{$key} = $value;
 
  95   $main::lxdebug->leave_sub(2);
 
  97   return \$curr->{$key};
 
 101   $main::lxdebug->enter_sub(2);
 
 106   my @pairs = split(/&/, $input);
 
 109     my ($key, $value) = split(/=/, $_, 2);
 
 110     $self->_store_value($self->unescape($key), $self->unescape($value));
 
 113   $main::lxdebug->leave_sub(2);
 
 116 sub _request_to_hash {
 
 117   $main::lxdebug->enter_sub(2);
 
 122   if (!$ENV{'CONTENT_TYPE'}
 
 123       || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
 
 125     $self->_input_to_hash($input);
 
 127     $main::lxdebug->leave_sub(2);
 
 131   my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr, $previous);
 
 133   my $boundary = '--' . $1;
 
 135   foreach my $line (split m/\n/, $input) {
 
 136     last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
 
 138     if (($line eq $boundary) || ($line eq "$boundary\r")) {
 
 139       ${ $previous } =~ s|\r?\n$|| if $previous;
 
 145       $content_type   = "text/plain";
 
 152     next unless $boundary_found;
 
 154     if (!$headers_done) {
 
 155       $line =~ s/[\r\n]*$//;
 
 162       if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
 
 163         if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
 
 165           substr $line, $-[0], $+[0] - $-[0], "";
 
 168         if ($line =~ m|name\s*=\s*"(.*?)"|i) {
 
 170           substr $line, $-[0], $+[0] - $-[0], "";
 
 173         $previous         = $self->_store_value($name, '');
 
 174         $self->{FILENAME} = $filename if ($filename);
 
 179       if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
 
 186     next unless $previous;
 
 188     ${ $previous } .= "${line}\n";
 
 191   ${ $previous } =~ s|\r?\n$|| if $previous;
 
 193   $main::lxdebug->leave_sub(2);
 
 197   $main::lxdebug->enter_sub();
 
 203   if ($LXDebug::watch_form) {
 
 204     require SL::Watchdog;
 
 205     tie %{ $self }, 'SL::Watchdog';
 
 208   read(STDIN, $_, $ENV{CONTENT_LENGTH});
 
 210   if ($ENV{QUERY_STRING}) {
 
 211     $_ = $ENV{QUERY_STRING};
 
 220   $self->_request_to_hash($_);
 
 222   $self->{action}  =  lc $self->{action};
 
 223   $self->{action}  =~ s/( |-|,|\#)/_/g;
 
 225   $self->{version} =  "2.4.3";
 
 227   $main::lxdebug->leave_sub();
 
 232 sub _flatten_variables_rec {
 
 233   $main::lxdebug->enter_sub(2);
 
 242   if ('' eq ref $curr->{$key}) {
 
 243     @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
 
 245   } elsif ('HASH' eq ref $curr->{$key}) {
 
 246     foreach my $hash_key (sort keys %{ $curr->{$key} }) {
 
 247       push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
 
 251     foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
 
 252       my $first_array_entry = 1;
 
 254       foreach my $hash_key (sort keys %{ $curr->{$key}->[$idx] }) {
 
 255         push @result, $self->_flatten_variables_rec($curr->{$key}->[$idx], $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
 
 256         $first_array_entry = 0;
 
 261   $main::lxdebug->leave_sub(2);
 
 266 sub flatten_variables {
 
 267   $main::lxdebug->enter_sub(2);
 
 275     push @variables, $self->_flatten_variables_rec($self, '', $_);
 
 278   $main::lxdebug->leave_sub(2);
 
 283 sub flatten_standard_variables {
 
 284   $main::lxdebug->enter_sub(2);
 
 287   my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar version), @_);
 
 291   foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
 
 292     push @variables, $self->_flatten_variables_rec($self, '', $_);
 
 295   $main::lxdebug->leave_sub(2);
 
 301   $main::lxdebug->enter_sub();
 
 307   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
 
 309   $main::lxdebug->leave_sub();
 
 313   $main::lxdebug->enter_sub(2);
 
 316   my $password      = $self->{password};
 
 318   $self->{password} = 'X' x 8;
 
 320   local $Data::Dumper::Sortkeys = 1;
 
 321   my $output                    = Dumper($self);
 
 323   $self->{password} = $password;
 
 325   $main::lxdebug->leave_sub(2);
 
 331   $main::lxdebug->enter_sub(2);
 
 333   my ($self, $str) = @_;
 
 335   $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
 
 337   $main::lxdebug->leave_sub(2);
 
 343   $main::lxdebug->enter_sub(2);
 
 345   my ($self, $str) = @_;
 
 350   $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
 
 352   $main::lxdebug->leave_sub(2);
 
 358   my ($self, $str) = @_;
 
 360   if ($str && !ref($str)) {
 
 361     $str =~ s/\"/"/g;
 
 369   my ($self, $str) = @_;
 
 371   if ($str && !ref($str)) {
 
 372     $str =~ s/"/\"/g;
 
 380   $main::lxdebug->enter_sub(2);
 
 382   my ($self, $str) = @_;
 
 385     ('order' => ['&', '"', '<', '>'],
 
 392   map({ $str =~ s/$_/$replace{$_}/g; } @{ $replace{"order"} });
 
 394   $main::lxdebug->leave_sub(2);
 
 400   $main::lxdebug->enter_sub(2);
 
 402   my ($self, $str) = @_;
 
 417   map { $str =~ s/\Q$_\E/$replace{$_}/g; } keys %replace;
 
 418   $str =~ s/\&/\&/g;
 
 420   $main::lxdebug->leave_sub(2);
 
 430     map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
 
 432     for (sort keys %$self) {
 
 433       next if (($_ eq "header") || (ref($self->{$_}) ne ""));
 
 434       print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
 
 441   $main::lxdebug->enter_sub();
 
 443   $main::lxdebug->show_backtrace();
 
 445   my ($self, $msg) = @_;
 
 446   if ($ENV{HTTP_USER_AGENT}) {
 
 448     $self->show_generic_error($msg);
 
 455   $main::lxdebug->leave_sub();
 
 459   $main::lxdebug->enter_sub();
 
 461   my ($self, $msg) = @_;
 
 463   if ($ENV{HTTP_USER_AGENT}) {
 
 466     if (!$self->{header}) {
 
 479     if ($self->{info_function}) {
 
 480       &{ $self->{info_function} }($msg);
 
 486   $main::lxdebug->leave_sub();
 
 489 # calculates the number of rows in a textarea based on the content and column number
 
 490 # can be capped with maxrows
 
 492   $main::lxdebug->enter_sub();
 
 493   my ($self, $str, $cols, $maxrows, $minrows) = @_;
 
 497   my $rows   = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
 
 500   $main::lxdebug->leave_sub();
 
 502   return max(min($rows, $maxrows), $minrows);
 
 506   $main::lxdebug->enter_sub();
 
 508   my ($self, $msg) = @_;
 
 510   $self->error("$msg\n" . $DBI::errstr);
 
 512   $main::lxdebug->leave_sub();
 
 516   $main::lxdebug->enter_sub();
 
 518   my ($self, $name, $msg) = @_;
 
 521   foreach my $part (split '.', $name) {
 
 522     if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
 
 525     $curr = $curr->{$part};
 
 528   $main::lxdebug->leave_sub();
 
 532   $main::lxdebug->enter_sub();
 
 534   my ($self, $extra_code) = @_;
 
 536   if ($self->{header}) {
 
 537     $main::lxdebug->leave_sub();
 
 541   my $cgi   = $main::cgi;
 
 542   $cgi    ||= CGI->new('');
 
 544   my ($stylesheet, $favicon);
 
 546   if ($ENV{HTTP_USER_AGENT}) {
 
 549     if ($ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+\d/) {
 
 550       # Only set the DOCTYPE for Internet Explorer. Other browsers have problems displaying the menu otherwise.
 
 551       $doctype = qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n|;
 
 554     my $stylesheets = "$self->{stylesheet} $self->{stylesheets}";
 
 556     $stylesheets =~ s|^\s*||;
 
 557     $stylesheets =~ s|\s*$||;
 
 558     foreach my $file (split m/\s+/, $stylesheets) {
 
 560       next if (! -f "css/$file");
 
 562       $stylesheet .= qq|<link rel="stylesheet" href="css/$file" TYPE="text/css" TITLE="Lx-Office stylesheet">\n|;
 
 565     $self->{favicon}    = "favicon.ico" unless $self->{favicon};
 
 567     if ($self->{favicon} && (-f "$self->{favicon}")) {
 
 569         qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
 
 573     my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
 575     if ($self->{landscape}) {
 
 576       $pagelayout = qq|<style type="text/css">
 
 577                         \@page { size:landscape; }
 
 581     my $fokus = qq|  document.$self->{fokus}.focus();| if ($self->{"fokus"});
 
 585     if ($self->{jsscript} == 1) {
 
 588         <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
 
 589         <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
 
 590         <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
 
 591         <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
 
 598       ? "$self->{title} - $self->{titlebar}"
 
 601     foreach $item (@ { $self->{AJAX} }) {
 
 602       $ajax .= $item->show_javascript();
 
 607     if ($ENV{HTTP_X_FORWARDED_FOR}) {
 
 608       $base_path =  $ENV{HTTP_REFERER};
 
 609       $base_path =~ s|^.*?://.*?/|/|;
 
 611       $base_path =  $ENV{REQUEST_URI};
 
 613     $base_path =~ s|[^/]+$||;
 
 614     $base_path =~ s|/$||;
 
 617     if (defined $main::auth) {
 
 618       my $session_cookie_value   = $main::auth->get_session_id();
 
 619       $session_cookie_value    ||= 'NO_SESSION';
 
 621       $session_cookie = $cgi->cookie('-name'  => $main::auth->get_session_cookie_name(),
 
 622                                      '-value' => $session_cookie_value,
 
 623                                      '-path'  => $base_path);
 
 626     print $cgi->header('-type'    => 'text/html',
 
 627                        '-charset' => $db_charset,
 
 628                        '-cookie'  => $session_cookie);
 
 629     print qq|${doctype}<html>
 
 631   <title>$self->{titlebar}</title>
 
 635   <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
 
 639   <script type="text/javascript">
 
 647   <meta name="robots" content="noindex,nofollow" />
 
 648   <script type="text/javascript" src="js/highlight_input.js"></script>
 
 649   <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
 
 651   <script type="text/javascript" src="js/tabcontent.js">
 
 653   /***********************************************
 
 654   * Tab Content script- Dynamic Drive DHTML code library (www.dynamicdrive.com)
 
 655   * This notice MUST stay intact for legal use
 
 656   * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
 
 657   ***********************************************/
 
 668   $main::lxdebug->leave_sub();
 
 671 sub _prepare_html_template {
 
 672   $main::lxdebug->enter_sub();
 
 674   my ($self, $file, $additional_params) = @_;
 
 677   if (!defined(%main::myconfig) || !defined($main::myconfig{"countrycode"})) {
 
 678     $language = $main::language;
 
 680     $language = $main::myconfig{"countrycode"};
 
 682   $language = "de" unless ($language);
 
 684   if (-f "templates/webpages/${file}_${language}.html") {
 
 685     if ((-f ".developer") &&
 
 686         (-f "templates/webpages/${file}_master.html") &&
 
 687         ((stat("templates/webpages/${file}_master.html"))[9] >
 
 688          (stat("templates/webpages/${file}_${language}.html"))[9])) {
 
 689       my $info = "Developer information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
 
 690         "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 691       print(qq|<pre>$info</pre>|);
 
 695     $file = "templates/webpages/${file}_${language}.html";
 
 696   } elsif (-f "templates/webpages/${file}.html") {
 
 697     $file = "templates/webpages/${file}.html";
 
 699     my $info = "Web page template '${file}' not found.\n" .
 
 700       "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 701     print(qq|<pre>$info</pre>|);
 
 705   if ($self->{"DEBUG"}) {
 
 706     $additional_params->{"DEBUG"} = $self->{"DEBUG"};
 
 709   if ($additional_params->{"DEBUG"}) {
 
 710     $additional_params->{"DEBUG"} =
 
 711       "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
 
 714   if (%main::myconfig) {
 
 715     map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
 
 716     my $jsc_dateformat = $main::myconfig{"dateformat"};
 
 717     $jsc_dateformat =~ s/d+/\%d/gi;
 
 718     $jsc_dateformat =~ s/m+/\%m/gi;
 
 719     $jsc_dateformat =~ s/y+/\%Y/gi;
 
 720     $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
 
 723   $additional_params->{"conf_webdav"}                 = $main::webdav;
 
 724   $additional_params->{"conf_lizenzen"}               = $main::lizenzen;
 
 725   $additional_params->{"conf_latex_templates"}        = $main::latex;
 
 726   $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
 
 728   if (%main::debug_options) {
 
 729     map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
 
 732   if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
 
 733     while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
 
 734       $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
 
 738   $main::lxdebug->leave_sub();
 
 743 sub parse_html_template {
 
 744   $main::lxdebug->enter_sub();
 
 746   my ($self, $file, $additional_params) = @_;
 
 748   $additional_params ||= { };
 
 750   $file = $self->_prepare_html_template($file, $additional_params);
 
 752   my $template = Template->new({ 'INTERPOLATE'  => 0,
 
 756                                  'PLUGIN_BASE'  => 'SL::Template::Plugin',
 
 757                                  'INCLUDE_PATH' => '.:templates/webpages',
 
 760   map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
 
 763   if (!$template->process($file, $additional_params, \$output)) {
 
 764     print STDERR $template->error();
 
 767   $output = $main::locale->{iconv}->convert($output) if ($main::locale);
 
 769   $main::lxdebug->leave_sub();
 
 774 sub show_generic_error {
 
 775   my ($self, $error, $title, $action) = @_;
 
 778     'title_error' => $title,
 
 779     'label_error' => $error,
 
 784     map({ delete($self->{$_}); } qw(action));
 
 785     map({ push(@vars, { "name" => $_, "value" => $self->{$_} })
 
 786             if (!ref($self->{$_})); }
 
 788     $add_params->{"SHOW_BUTTON"} = 1;
 
 789     $add_params->{"BUTTON_LABEL"} = $action;
 
 791   $add_params->{"VARIABLES"} = \@vars;
 
 793   $self->{title} = $title if ($title);
 
 796   print $self->parse_html_template("generic/error", $add_params);
 
 798   die("Error: $error\n");
 
 801 sub show_generic_information {
 
 802   my ($self, $text, $title) = @_;
 
 805     'title_information' => $title,
 
 806     'label_information' => $text,
 
 809   $self->{title} = $title if ($title);
 
 812   print $self->parse_html_template("generic/information", $add_params);
 
 814   die("Information: $error\n");
 
 817 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
 
 818 # changed it to accept an arbitrary number of triggers - sschoeling
 
 820   $main::lxdebug->enter_sub();
 
 823   my $myconfig = shift;
 
 826   # set dateform for jsscript
 
 829     "dd.mm.yy" => "%d.%m.%Y",
 
 830     "dd-mm-yy" => "%d-%m-%Y",
 
 831     "dd/mm/yy" => "%d/%m/%Y",
 
 832     "mm/dd/yy" => "%m/%d/%Y",
 
 833     "mm-dd-yy" => "%m-%d-%Y",
 
 834     "yyyy-mm-dd" => "%Y-%m-%d",
 
 837   my $ifFormat = defined($dateformats{$myconfig{"dateformat"}}) ?
 
 838     $dateformats{$myconfig{"dateformat"}} : "%d.%m.%Y";
 
 845       inputField : "| . (shift) . qq|",
 
 846       ifFormat :"$ifFormat",
 
 847       align : "| .  (shift) . qq|",
 
 848       button : "| . (shift) . qq|"
 
 854        <script type="text/javascript">
 
 855        <!--| . join("", @triggers) . qq|//-->
 
 859   $main::lxdebug->leave_sub();
 
 862 }    #end sub write_trigger
 
 865   $main::lxdebug->enter_sub();
 
 867   my ($self, $msg) = @_;
 
 869   if ($self->{callback}) {
 
 871     ($script, $argv) = split(/\?/, $self->{callback}, 2);
 
 873     $script =~ s|[^a-zA-Z0-9_\.]||g;
 
 874     exec("perl", "$script", $argv);
 
 882   $main::lxdebug->leave_sub();
 
 885 # sort of columns removed - empty sub
 
 887   $main::lxdebug->enter_sub();
 
 889   my ($self, @columns) = @_;
 
 891   $main::lxdebug->leave_sub();
 
 897   $main::lxdebug->enter_sub(2);
 
 899   my ($self, $myconfig, $amount, $places, $dash) = @_;
 
 905   # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
 
 907   my $neg = ($amount =~ s/^-//);
 
 908   my $exp = ($amount =~ m/[e]/) ? 1 : 0;
 
 910   if (defined($places) && ($places ne '')) {
 
 916         my ($actual_places) = ($amount =~ /\.(\d+)/);
 
 917         $actual_places = length($actual_places);
 
 918         $places = $actual_places > $places ? $actual_places : $places;
 
 921     $amount = $self->round_amount($amount, $places);
 
 924   my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
 
 925   my @p = split(/\./, $amount); # split amount at decimal point
 
 927   $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
 
 930   $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
 
 933     ($dash =~ /-/)    ? ($neg ? "($amount)"  : "$amount" )    :
 
 934     ($dash =~ /DRCR/) ? ($neg ? "$amount DR" : "$amount CR" ) :
 
 935                         ($neg ? "-$amount"   : "$amount" )    ;
 
 939   $main::lxdebug->leave_sub(2);
 
 943 sub format_amount_units {
 
 944   $main::lxdebug->enter_sub();
 
 949   Common::check_params(\%params, qw(amount part_unit));
 
 951   my $myconfig         = \%main::myconfig;
 
 952   my $amount           = $params{amount};
 
 953   my $places           = $params{places};
 
 954   my $part_unit_name   = $params{part_unit};
 
 955   my $amount_unit_name = $params{amount_unit};
 
 956   my $conv_units       = $params{conv_units};
 
 957   my $max_places       = $params{max_places};
 
 959   AM->retrieve_all_units();
 
 960   my $all_units        = $main::all_units;
 
 962   if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
 
 963     $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
 
 966   if (!scalar @{ $conv_units }) {
 
 967     my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
 
 968     $main::lxdebug->leave_sub();
 
 972   my $part_unit  = $all_units->{$part_unit_name};
 
 973   my $conv_unit  = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
 
 975   $amount       *= $conv_unit->{factor};
 
 979   foreach my $unit (@$conv_units) {
 
 980     my $last = $unit->{name} eq $part_unit->{name};
 
 982       $num     = int($amount / $unit->{factor});
 
 983       $amount -= $num * $unit->{factor};
 
 986     if ($last ? $amount : $num) {
 
 987       push @values, { "unit"   => $unit->{name},
 
 988                       "amount" => $last ? $amount / $unit->{factor} : $num,
 
 989                       "places" => $last ? $places : 0 };
 
 996     push @values, { "unit"   => $part_unit_name,
 
1001   my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
 
1003   $main::lxdebug->leave_sub();
 
1009   $main::lxdebug->enter_sub(2);
 
1014   $input =~ s/(^|[^\#]) \#  (\d+)  /$1$_[$2 - 1]/gx;
 
1015   $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
 
1016   $input =~ s/\#\#/\#/g;
 
1018   $main::lxdebug->leave_sub(2);
 
1026   $main::lxdebug->enter_sub(2);
 
1028   my ($self, $myconfig, $amount) = @_;
 
1030   if (   ($myconfig->{numberformat} eq '1.000,00')
 
1031       || ($myconfig->{numberformat} eq '1000,00')) {
 
1036   if ($myconfig->{numberformat} eq "1'000.00") {
 
1042   $main::lxdebug->leave_sub(2);
 
1044   return ($amount * 1);
 
1048   $main::lxdebug->enter_sub(2);
 
1050   my ($self, $amount, $places) = @_;
 
1053   # Rounding like "Kaufmannsrunden"
 
1054   # Descr. http://de.wikipedia.org/wiki/Rundung
 
1056   # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
 
1059   $amount = $amount * (10**($places));
 
1060   $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
 
1062   $main::lxdebug->leave_sub(2);
 
1064   return $round_amount;
 
1068 sub parse_template {
 
1069   $main::lxdebug->enter_sub();
 
1071   my ($self, $myconfig, $userspath) = @_;
 
1072   my ($template, $out);
 
1076   $self->{"cwd"} = getcwd();
 
1077   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
 
1079   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
 
1080     $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1081   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
 
1082     $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
 
1083     $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1084   } elsif (($self->{"format"} =~ /html/i) ||
 
1085            (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
 
1086     $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1087   } elsif (($self->{"format"} =~ /xml/i) ||
 
1088              (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
 
1089     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1090   } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
 
1091     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1092   } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
 
1093     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
1094   } elsif ( defined $self->{'format'}) {
 
1095     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
 
1096   } elsif ( $self->{'format'} eq '' ) {
 
1097     $self->error("No Outputformat given: $self->{'format'}");
 
1098   } else { #Catch the rest
 
1099     $self->error("Outputformat not defined: $self->{'format'}");
 
1102   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
 
1103   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
 
1105   map({ $self->{"employee_${_}"} = $myconfig->{$_}; }
 
1106       qw(email tel fax name signature company address businessnumber
 
1107          co_ustid taxnumber duns));
 
1109   map({ $self->{"${_}"} = $myconfig->{$_}; }
 
1113   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
 
1115   # OUT is used for the media, screen, printer, email
 
1116   # for postscript we store a copy in a temporary file
 
1118   my $prepend_userspath;
 
1120   if (!$self->{tmpfile}) {
 
1121     $self->{tmpfile}   = "${fileid}.$self->{IN}";
 
1122     $prepend_userspath = 1;
 
1125   $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
 
1127   $self->{tmpfile} =~ s|.*/||;
 
1128   $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
 
1129   $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
 
1131   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
1132     $out = $self->{OUT};
 
1133     $self->{OUT} = ">$self->{tmpfile}";
 
1137     open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
 
1139     open(OUT, ">-") or $self->error("STDOUT : $!");
 
1143   if (!$template->parse(*OUT)) {
 
1145     $self->error("$self->{IN} : " . $template->get_error());
 
1150   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
1152     if ($self->{media} eq 'email') {
 
1154       my $mail = new Mailer;
 
1156       map { $mail->{$_} = $self->{$_} }
 
1157         qw(cc bcc subject message version format);
 
1158       $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
1159       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
 
1160       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
 
1161       $mail->{fileid} = "$fileid.";
 
1162       $myconfig->{signature} =~ s/\r//g;
 
1164       # if we send html or plain text inline
 
1165       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
 
1166         $mail->{contenttype} = "text/html";
 
1168         $mail->{message}       =~ s/\r//g;
 
1169         $mail->{message}       =~ s/\n/<br>\n/g;
 
1170         $myconfig->{signature} =~ s/\n/<br>\n/g;
 
1171         $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
 
1173         open(IN, $self->{tmpfile})
 
1174           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1176           $mail->{message} .= $_;
 
1183         if (!$self->{"do_not_attach"}) {
 
1184           @{ $mail->{attachments} } =
 
1185             ({ "filename" => $self->{"tmpfile"},
 
1186                "name" => $self->{"attachment_filename"} ?
 
1187                  $self->{"attachment_filename"} : $self->{"tmpfile"} });
 
1190         $mail->{message}  =~ s/\r//g;
 
1191         $mail->{message} .=  "\n-- \n$myconfig->{signature}";
 
1195       my $err = $mail->send();
 
1196       $self->error($self->cleanup . "$err") if ($err);
 
1200       $self->{OUT} = $out;
 
1202       my $numbytes = (-s $self->{tmpfile});
 
1203       open(IN, $self->{tmpfile})
 
1204         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1206       $self->{copies} = 1 unless $self->{media} eq 'printer';
 
1208       chdir("$self->{cwd}");
 
1209       #print(STDERR "Kopien $self->{copies}\n");
 
1210       #print(STDERR "OUT $self->{OUT}\n");
 
1211       for my $i (1 .. $self->{copies}) {
 
1213           open(OUT, $self->{OUT})
 
1214             or $self->error($self->cleanup . "$self->{OUT} : $!");
 
1216           $self->{attachment_filename} = ($self->{attachment_filename}) 
 
1217                                        ? $self->{attachment_filename}
 
1218                                        : $self->generate_attachment_filename();
 
1220           # launch application
 
1221           print qq|Content-Type: | . $template->get_mime_type() . qq|
 
1222 Content-Disposition: attachment; filename="$self->{attachment_filename}"
 
1223 Content-Length: $numbytes
 
1227           open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
 
1247   chdir("$self->{cwd}");
 
1248   $main::lxdebug->leave_sub();
 
1251 sub get_formname_translation {
 
1252   my ($self, $formname) = @_;
 
1254   $formname ||= $self->{formname};
 
1256   my %formname_translations = (
 
1257     bin_list            => $main::locale->text('Bin List'),
 
1258     credit_note         => $main::locale->text('Credit Note'),
 
1259     invoice             => $main::locale->text('Invoice'),
 
1260     packing_list        => $main::locale->text('Packing List'),
 
1261     pick_list           => $main::locale->text('Pick List'),
 
1262     proforma            => $main::locale->text('Proforma Invoice'),
 
1263     purchase_order      => $main::locale->text('Purchase Order'),
 
1264     request_quotation   => $main::locale->text('RFQ'),
 
1265     sales_order         => $main::locale->text('Confirmation'),
 
1266     sales_quotation     => $main::locale->text('Quotation'),
 
1267     storno_invoice      => $main::locale->text('Storno Invoice'),
 
1268     storno_packing_list => $main::locale->text('Storno Packing List'),
 
1271   return $formname_translations{$formname}
 
1274 sub generate_attachment_filename {
 
1277   my $attachment_filename = $self->unquote_html($self->get_formname_translation());
 
1279       (grep { $self->{"type"} eq $_ } qw(invoice credit_note)) ? "inv"
 
1280     : ($self->{"type"} =~ /_quotation$/)                       ? "quo"
 
1283   if ($attachment_filename && $self->{"${prefix}number"}) {
 
1284     $attachment_filename .= "_" . $self->{"${prefix}number"}
 
1285                             . (  $self->{format} =~ /pdf/i          ? ".pdf"
 
1286                                : $self->{format} =~ /postscript/i   ? ".ps"
 
1287                                : $self->{format} =~ /opendocument/i ? ".odt"
 
1288                                : $self->{format} =~ /html/i         ? ".html"
 
1290     $attachment_filename =~ s/ /_/g;
 
1291     my %umlaute = ( "ä" => "ae", "ö" => "oe", "ü" => "ue", 
 
1292                     "Ä" => "Ae", "Ö" => "Oe", "Ü" => "Ue", "ß" => "ss");
 
1293     map { $attachment_filename =~ s/$_/$umlaute{$_}/g } keys %umlaute;
 
1295     $attachment_filename = "";
 
1298   return $attachment_filename;
 
1302   $main::lxdebug->enter_sub();
 
1306   chdir("$self->{tmpdir}");
 
1309   if (-f "$self->{tmpfile}.err") {
 
1310     open(FH, "$self->{tmpfile}.err");
 
1315   if ($self->{tmpfile}) {
 
1316     $self->{tmpfile} =~ s|.*/||g;
 
1318     $self->{tmpfile} =~ s/\.\w+$//g;
 
1319     my $tmpfile = $self->{tmpfile};
 
1320     unlink(<$tmpfile.*>);
 
1323   chdir("$self->{cwd}");
 
1325   $main::lxdebug->leave_sub();
 
1331   $main::lxdebug->enter_sub();
 
1333   my ($self, $date, $myconfig) = @_;
 
1335   if ($date && $date =~ /\D/) {
 
1337     if ($myconfig->{dateformat} =~ /^yy/) {
 
1338       ($yy, $mm, $dd) = split /\D/, $date;
 
1340     if ($myconfig->{dateformat} =~ /^mm/) {
 
1341       ($mm, $dd, $yy) = split /\D/, $date;
 
1343     if ($myconfig->{dateformat} =~ /^dd/) {
 
1344       ($dd, $mm, $yy) = split /\D/, $date;
 
1349     $yy = ($yy < 70) ? $yy + 2000 : $yy;
 
1350     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
 
1352     $dd = "0$dd" if ($dd < 10);
 
1353     $mm = "0$mm" if ($mm < 10);
 
1355     $date = "$yy$mm$dd";
 
1358   $main::lxdebug->leave_sub();
 
1363 # Database routines used throughout
 
1366   $main::lxdebug->enter_sub(2);
 
1368   my ($self, $myconfig) = @_;
 
1370   # connect to database
 
1372     DBI->connect($myconfig->{dbconnect},
 
1373                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
 
1377   if ($myconfig->{dboptions}) {
 
1378     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1381   $main::lxdebug->leave_sub(2);
 
1386 sub dbconnect_noauto {
 
1387   $main::lxdebug->enter_sub();
 
1389   my ($self, $myconfig) = @_;
 
1391   # connect to database
 
1393     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
 
1394                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
 
1398   if ($myconfig->{dboptions}) {
 
1399     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1402   $main::lxdebug->leave_sub();
 
1407 sub get_standard_dbh {
 
1408   $main::lxdebug->enter_sub(2);
 
1410   my ($self, $myconfig) = @_;
 
1412   $standard_dbh ||= $self->dbconnect_noauto($myconfig);
 
1414   $main::lxdebug->leave_sub(2);
 
1416   return $standard_dbh;
 
1419 sub update_balance {
 
1420   $main::lxdebug->enter_sub();
 
1422   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
 
1424   # if we have a value, go do it
 
1427     # retrieve balance from table
 
1428     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
 
1429     my $sth = prepare_execute_query($self, $dbh, $query, @values);
 
1430     my ($balance) = $sth->fetchrow_array;
 
1436     $query = "UPDATE $table SET $field = $balance WHERE $where";
 
1437     do_query($self, $dbh, $query, @values);
 
1439   $main::lxdebug->leave_sub();
 
1442 sub update_exchangerate {
 
1443   $main::lxdebug->enter_sub();
 
1445   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
 
1447   # some sanity check for currency
 
1449     $main::lxdebug->leave_sub();
 
1452   $query = qq|SELECT curr FROM defaults|;
 
1454   my ($currency) = selectrow_query($self, $dbh, $query);
 
1455   my ($defaultcurrency) = split m/:/, $currency;
 
1458   if ($curr eq $defaultcurrency) {
 
1459     $main::lxdebug->leave_sub();
 
1463   $query = qq|SELECT e.curr FROM exchangerate e
 
1464                  WHERE e.curr = ? AND e.transdate = ?
 
1466   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
 
1475   $buy = conv_i($buy, "NULL");
 
1476   $sell = conv_i($sell, "NULL");
 
1479   if ($buy != 0 && $sell != 0) {
 
1480     $set = "buy = $buy, sell = $sell";
 
1481   } elsif ($buy != 0) {
 
1482     $set = "buy = $buy";
 
1483   } elsif ($sell != 0) {
 
1484     $set = "sell = $sell";
 
1487   if ($sth->fetchrow_array) {
 
1488     $query = qq|UPDATE exchangerate
 
1494     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
 
1495                 VALUES (?, $buy, $sell, ?)|;
 
1498   do_query($self, $dbh, $query, $curr, $transdate);
 
1500   $main::lxdebug->leave_sub();
 
1503 sub save_exchangerate {
 
1504   $main::lxdebug->enter_sub();
 
1506   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
 
1508   my $dbh = $self->dbconnect($myconfig);
 
1512   $buy  = $rate if $fld eq 'buy';
 
1513   $sell = $rate if $fld eq 'sell';
 
1516   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
 
1521   $main::lxdebug->leave_sub();
 
1524 sub get_exchangerate {
 
1525   $main::lxdebug->enter_sub();
 
1527   my ($self, $dbh, $curr, $transdate, $fld) = @_;
 
1530   unless ($transdate) {
 
1531     $main::lxdebug->leave_sub();
 
1535   $query = qq|SELECT curr FROM defaults|;
 
1537   my ($currency) = selectrow_query($self, $dbh, $query);
 
1538   my ($defaultcurrency) = split m/:/, $currency;
 
1540   if ($currency eq $defaultcurrency) {
 
1541     $main::lxdebug->leave_sub();
 
1545   $query = qq|SELECT e.$fld FROM exchangerate e
 
1546                  WHERE e.curr = ? AND e.transdate = ?|;
 
1547   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
 
1551   $main::lxdebug->leave_sub();
 
1553   return $exchangerate;
 
1556 sub check_exchangerate {
 
1557   $main::lxdebug->enter_sub();
 
1559   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
 
1561   unless ($transdate) {
 
1562     $main::lxdebug->leave_sub();
 
1566   my ($defaultcurrency) = $self->get_default_currency($myconfig);
 
1568   if ($currency eq $defaultcurrency) {
 
1569     $main::lxdebug->leave_sub();
 
1573   my $dbh   = $self->get_standard_dbh($myconfig);
 
1574   my $query = qq|SELECT e.$fld FROM exchangerate e
 
1575                  WHERE e.curr = ? AND e.transdate = ?|;
 
1577   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
 
1579   $exchangerate = 1 if ($exchangerate eq "");
 
1581   $main::lxdebug->leave_sub();
 
1583   return $exchangerate;
 
1586 sub get_default_currency {
 
1587   $main::lxdebug->enter_sub();
 
1589   my ($self, $myconfig) = @_;
 
1590   my $dbh = $self->get_standard_dbh($myconfig);
 
1592   my $query = qq|SELECT curr FROM defaults|;
 
1594   my ($curr)            = selectrow_query($self, $dbh, $query);
 
1595   my ($defaultcurrency) = split m/:/, $curr;
 
1597   $main::lxdebug->leave_sub();
 
1599   return $defaultcurrency;
 
1603 sub set_payment_options {
 
1604   $main::lxdebug->enter_sub();
 
1606   my ($self, $myconfig, $transdate) = @_;
 
1608   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
 
1610   my $dbh = $self->get_standard_dbh($myconfig);
 
1613     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
 
1614     qq|FROM payment_terms p | .
 
1617   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
 
1618    $self->{payment_terms}) =
 
1619      selectrow_query($self, $dbh, $query, $self->{payment_id});
 
1621   if ($transdate eq "") {
 
1622     if ($self->{invdate}) {
 
1623       $transdate = $self->{invdate};
 
1625       $transdate = $self->{transdate};
 
1630     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
 
1631     qq|FROM payment_terms|;
 
1632   ($self->{netto_date}, $self->{skonto_date}) =
 
1633     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
 
1635   my ($invtotal, $total);
 
1636   my (%amounts, %formatted_amounts);
 
1638   if ($self->{type} =~ /_order$/) {
 
1639     $amounts{invtotal} = $self->{ordtotal};
 
1640     $amounts{total}    = $self->{ordtotal};
 
1642   } elsif ($self->{type} =~ /_quotation$/) {
 
1643     $amounts{invtotal} = $self->{quototal};
 
1644     $amounts{total}    = $self->{quototal};
 
1647     $amounts{invtotal} = $self->{invtotal};
 
1648     $amounts{total}    = $self->{total};
 
1651   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
 
1653   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
 
1654   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
 
1655   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
 
1657   foreach (keys %amounts) {
 
1658     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
 
1659     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
 
1662   if ($self->{"language_id"}) {
 
1664       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
 
1665       qq|FROM translation_payment_terms t | .
 
1666       qq|LEFT JOIN language l ON t.language_id = l.id | .
 
1667       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
 
1668     my ($description_long, $output_numberformat, $output_dateformat,
 
1669       $output_longdates) =
 
1670       selectrow_query($self, $dbh, $query,
 
1671                       $self->{"language_id"}, $self->{"payment_id"});
 
1673     $self->{payment_terms} = $description_long if ($description_long);
 
1675     if ($output_dateformat) {
 
1676       foreach my $key (qw(netto_date skonto_date)) {
 
1678           $main::locale->reformat_date($myconfig, $self->{$key},
 
1684     if ($output_numberformat &&
 
1685         ($output_numberformat ne $myconfig->{"numberformat"})) {
 
1686       my $saved_numberformat = $myconfig->{"numberformat"};
 
1687       $myconfig->{"numberformat"} = $output_numberformat;
 
1688       map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
 
1689       $myconfig->{"numberformat"} = $saved_numberformat;
 
1693   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
 
1694   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
 
1695   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
 
1696   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
 
1697   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
 
1698   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
 
1699   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
 
1701   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
 
1703   $main::lxdebug->leave_sub();
 
1707 sub get_template_language {
 
1708   $main::lxdebug->enter_sub();
 
1710   my ($self, $myconfig) = @_;
 
1712   my $template_code = "";
 
1714   if ($self->{language_id}) {
 
1715     my $dbh = $self->get_standard_dbh($myconfig);
 
1716     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
 
1717     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
 
1720   $main::lxdebug->leave_sub();
 
1722   return $template_code;
 
1725 sub get_printer_code {
 
1726   $main::lxdebug->enter_sub();
 
1728   my ($self, $myconfig) = @_;
 
1730   my $template_code = "";
 
1732   if ($self->{printer_id}) {
 
1733     my $dbh = $self->get_standard_dbh($myconfig);
 
1734     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
 
1735     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
 
1738   $main::lxdebug->leave_sub();
 
1740   return $template_code;
 
1744   $main::lxdebug->enter_sub();
 
1746   my ($self, $myconfig) = @_;
 
1748   my $template_code = "";
 
1750   if ($self->{shipto_id}) {
 
1751     my $dbh = $self->get_standard_dbh($myconfig);
 
1752     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
 
1753     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
 
1754     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
 
1757   $main::lxdebug->leave_sub();
 
1761   $main::lxdebug->enter_sub();
 
1763   my ($self, $dbh, $id, $module) = @_;
 
1768   foreach my $item (qw(name department_1 department_2 street zipcode city country
 
1769                        contact phone fax email)) {
 
1770     if ($self->{"shipto$item"}) {
 
1771       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
 
1773     push(@values, $self->{"shipto${item}"});
 
1777     if ($self->{shipto_id}) {
 
1778       my $query = qq|UPDATE shipto set
 
1780                        shiptodepartment_1 = ?,
 
1781                        shiptodepartment_2 = ?,
 
1790                      WHERE shipto_id = ?|;
 
1791       do_query($self, $dbh, $query, @values, $self->{shipto_id});
 
1793       my $query = qq|SELECT * FROM shipto
 
1794                      WHERE shiptoname = ? AND
 
1795                        shiptodepartment_1 = ? AND
 
1796                        shiptodepartment_2 = ? AND
 
1797                        shiptostreet = ? AND
 
1798                        shiptozipcode = ? AND
 
1800                        shiptocountry = ? AND
 
1801                        shiptocontact = ? AND
 
1807       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
 
1810           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
 
1811                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
 
1812                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
 
1813              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
 
1814         do_query($self, $dbh, $query, $id, @values, $module);
 
1819   $main::lxdebug->leave_sub();
 
1823   $main::lxdebug->enter_sub();
 
1825   my ($self, $dbh) = @_;
 
1827   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
 
1828   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
 
1829   $self->{"employee_id"} *= 1;
 
1831   $main::lxdebug->leave_sub();
 
1835   $main::lxdebug->enter_sub();
 
1837   my ($self, $myconfig, $salesman_id) = @_;
 
1839   $main::lxdebug->leave_sub() and return unless $salesman_id;
 
1841   my $dbh = $self->get_standard_dbh($myconfig);
 
1844     selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|,
 
1848     my $user = new User($main::memberfile, $login);
 
1849     map({ $self->{"salesman_$_"} = $user->{$_}; }
 
1850         qw(address businessnumber co_ustid company duns email fax name
 
1852     $self->{salesman_login} = $login;
 
1854     $self->{salesman_name} = $login
 
1855       if ($self->{salesman_name} eq "");
 
1858   $main::lxdebug->leave_sub();
 
1862   $main::lxdebug->enter_sub();
 
1864   my ($self, $myconfig) = @_;
 
1866   my $dbh = $self->get_standard_dbh($myconfig);
 
1867   my $query = qq|SELECT current_date + terms_netto FROM payment_terms WHERE id = ?|;
 
1868   ($self->{duedate}) = selectrow_query($self, $dbh, $query, $self->{payment_id});
 
1870   $main::lxdebug->leave_sub();
 
1874   $main::lxdebug->enter_sub();
 
1876   my ($self, $dbh, $id, $key) = @_;
 
1878   $key = "all_contacts" unless ($key);
 
1881     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
 
1882     qq|FROM contacts | .
 
1883     qq|WHERE cp_cv_id = ? | .
 
1884     qq|ORDER BY lower(cp_name)|;
 
1886   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
 
1888   $main::lxdebug->leave_sub();
 
1892   $main::lxdebug->enter_sub();
 
1894   my ($self, $dbh, $key) = @_;
 
1896   my ($all, $old_id, $where, @values);
 
1898   if (ref($key) eq "HASH") {
 
1901     $key = "ALL_PROJECTS";
 
1903     foreach my $p (keys(%{$params})) {
 
1905         $all = $params->{$p};
 
1906       } elsif ($p eq "old_id") {
 
1907         $old_id = $params->{$p};
 
1908       } elsif ($p eq "key") {
 
1909         $key = $params->{$p};
 
1915     $where = "WHERE active ";
 
1917       if (ref($old_id) eq "ARRAY") {
 
1918         my @ids = grep({ $_ } @{$old_id});
 
1920           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
 
1921           push(@values, @ids);
 
1924         $where .= " OR (id = ?) ";
 
1925         push(@values, $old_id);
 
1931     qq|SELECT id, projectnumber, description, active | .
 
1934     qq|ORDER BY lower(projectnumber)|;
 
1936   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
 
1938   $main::lxdebug->leave_sub();
 
1942   $main::lxdebug->enter_sub();
 
1944   my ($self, $dbh, $vc_id, $key) = @_;
 
1946   $key = "all_shipto" unless ($key);
 
1948   # get shipping addresses
 
1949   my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
 
1951   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
 
1953   $main::lxdebug->leave_sub();
 
1957   $main::lxdebug->enter_sub();
 
1959   my ($self, $dbh, $key) = @_;
 
1961   $key = "all_printers" unless ($key);
 
1963   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
 
1965   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1967   $main::lxdebug->leave_sub();
 
1971   $main::lxdebug->enter_sub();
 
1973   my ($self, $dbh, $params) = @_;
 
1975   $key = $params->{key};
 
1976   $key = "all_charts" unless ($key);
 
1978   my $transdate = quote_db_date($params->{transdate});
 
1981     qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
 
1983     qq|LEFT JOIN taxkeys tk ON | .
 
1984     qq|(tk.id = (SELECT id FROM taxkeys | .
 
1985     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
 
1986     qq|          ORDER BY startdate DESC LIMIT 1)) | .
 
1987     qq|ORDER BY c.accno|;
 
1989   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1991   $main::lxdebug->leave_sub();
 
1994 sub _get_taxcharts {
 
1995   $main::lxdebug->enter_sub();
 
1997   my ($self, $dbh, $key) = @_;
 
1999   $key = "all_taxcharts" unless ($key);
 
2001   my $query = qq|SELECT * FROM tax ORDER BY taxkey|;
 
2003   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2005   $main::lxdebug->leave_sub();
 
2009   $main::lxdebug->enter_sub();
 
2011   my ($self, $dbh, $key) = @_;
 
2013   $key = "all_taxzones" unless ($key);
 
2015   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
 
2017   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2019   $main::lxdebug->leave_sub();
 
2022 sub _get_employees {
 
2023   $main::lxdebug->enter_sub();
 
2025   my ($self, $dbh, $default_key, $key) = @_;
 
2027   $key = $default_key unless ($key);
 
2028   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
 
2030   $main::lxdebug->leave_sub();
 
2033 sub _get_business_types {
 
2034   $main::lxdebug->enter_sub();
 
2036   my ($self, $dbh, $key) = @_;
 
2038   $key = "all_business_types" unless ($key);
 
2040     selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
 
2042   $main::lxdebug->leave_sub();
 
2045 sub _get_languages {
 
2046   $main::lxdebug->enter_sub();
 
2048   my ($self, $dbh, $key) = @_;
 
2050   $key = "all_languages" unless ($key);
 
2052   my $query = qq|SELECT * FROM language ORDER BY id|;
 
2054   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2056   $main::lxdebug->leave_sub();
 
2059 sub _get_dunning_configs {
 
2060   $main::lxdebug->enter_sub();
 
2062   my ($self, $dbh, $key) = @_;
 
2064   $key = "all_dunning_configs" unless ($key);
 
2066   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
 
2068   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2070   $main::lxdebug->leave_sub();
 
2073 sub _get_currencies {
 
2074 $main::lxdebug->enter_sub();
 
2076   my ($self, $dbh, $key) = @_;
 
2078   $key = "all_currencies" unless ($key);
 
2080   my $query = qq|SELECT curr AS currency FROM defaults|;
 
2082   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
 
2084   $main::lxdebug->leave_sub();
 
2088 $main::lxdebug->enter_sub();
 
2090   my ($self, $dbh, $key) = @_;
 
2092   $key = "all_payments" unless ($key);
 
2094   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
 
2096   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2098   $main::lxdebug->leave_sub();
 
2101 sub _get_customers {
 
2102   $main::lxdebug->enter_sub();
 
2104   my ($self, $dbh, $key, $limit) = @_;
 
2106   $key = "all_customers" unless ($key);
 
2107   $limit_clause = "LIMIT $limit" if $limit;
 
2109   my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name $limit_clause|;
 
2111   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2113   $main::lxdebug->leave_sub();
 
2117   $main::lxdebug->enter_sub();
 
2119   my ($self, $dbh, $key) = @_;
 
2121   $key = "all_vendors" unless ($key);
 
2123   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
 
2125   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2127   $main::lxdebug->leave_sub();
 
2130 sub _get_departments {
 
2131   $main::lxdebug->enter_sub();
 
2133   my ($self, $dbh, $key) = @_;
 
2135   $key = "all_departments" unless ($key);
 
2137   my $query = qq|SELECT * FROM department ORDER BY description|;
 
2139   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2141   $main::lxdebug->leave_sub();
 
2144 sub _get_warehouses {
 
2145   $main::lxdebug->enter_sub();
 
2147   my ($self, $dbh, $param) = @_;
 
2149   my ($key, $bins_key, $q_access, @values);
 
2151   if ('' eq ref $param) {
 
2154     $key      = $param->{key};
 
2155     $bins_key = $param->{bins};
 
2157     if ($param->{access}) {
 
2160               SELECT wa.employee_id
 
2161               FROM warehouse_access wa
 
2162               WHERE (wa.employee_id  = (SELECT id FROM employee WHERE login = ?))
 
2163                 AND (wa.warehouse_id = w.id)
 
2164                 AND (wa.access IN ('ro', 'rw')))|;
 
2165       push @values, $param->{access};
 
2168     if ($param->{no_personal}) {
 
2169       $q_access .= qq| AND (w.personal_warehouse_of IS NULL)|;
 
2171     } elsif ($param->{personal}) {
 
2172       $q_access .= qq| AND (w.personal_warehouse_of = ?)|;
 
2173       push @values, conv_i($param->{personal});
 
2177   my $query = qq|SELECT w.* FROM warehouse w
 
2178                  WHERE (NOT w.invalid) AND
 
2179                    ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
 
2181                  ORDER BY w.sortkey|;
 
2183   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
 
2186     $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
 
2187     my $sth = prepare_query($self, $dbh, $query);
 
2189     foreach my $warehouse (@{ $self->{$key} }) {
 
2190       do_statement($self, $sth, $query, $warehouse->{id});
 
2191       $warehouse->{$bins_key} = [];
 
2193       while (my $ref = $sth->fetchrow_hashref()) {
 
2194         push @{ $warehouse->{$bins_key} }, $ref;
 
2200   $main::lxdebug->leave_sub();
 
2204   $main::lxdebug->enter_sub();
 
2206   my ($self, $dbh, $table, $key, $sortkey) = @_;
 
2208   my $query  = qq|SELECT * FROM $table|;
 
2209   $query    .= qq| ORDER BY $sortkey| if ($sortkey);
 
2211   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
2213   $main::lxdebug->leave_sub();
 
2217   $main::lxdebug->enter_sub();
 
2222   my $dbh = $self->get_standard_dbh(\%main::myconfig);
 
2223   my ($sth, $query, $ref);
 
2225   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
 
2226   my $vc_id = $self->{"${vc}_id"};
 
2228   if ($params{"contacts"}) {
 
2229     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
 
2232   if ($params{"shipto"}) {
 
2233     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
 
2236   if ($params{"projects"} || $params{"all_projects"}) {
 
2237     $self->_get_projects($dbh, $params{"all_projects"} ?
 
2238                          $params{"all_projects"} : $params{"projects"},
 
2239                          $params{"all_projects"} ? 1 : 0);
 
2242   if ($params{"printers"}) {
 
2243     $self->_get_printers($dbh, $params{"printers"});
 
2246   if ($params{"languages"}) {
 
2247     $self->_get_languages($dbh, $params{"languages"});
 
2250   if ($params{"charts"}) {
 
2251     $self->_get_charts($dbh, $params{"charts"});
 
2254   if ($params{"taxcharts"}) {
 
2255     $self->_get_taxcharts($dbh, $params{"taxcharts"});
 
2258   if ($params{"taxzones"}) {
 
2259     $self->_get_taxzones($dbh, $params{"taxzones"});
 
2262   if ($params{"employees"}) {
 
2263     $self->_get_employees($dbh, "all_employees", $params{"employees"});
 
2266   if ($params{"salesmen"}) {
 
2267     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
 
2270   if ($params{"business_types"}) {
 
2271     $self->_get_business_types($dbh, $params{"business_types"});
 
2274   if ($params{"dunning_configs"}) {
 
2275     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
 
2278   if($params{"currencies"}) {
 
2279     $self->_get_currencies($dbh, $params{"currencies"});
 
2282   if($params{"customers"}) {
 
2283     if (ref $params{"customers"} eq 'HASH') {
 
2284       $self->_get_customers($dbh, $params{"customers"}{key}, $params{"customers"}{limit});
 
2286       $self->_get_customers($dbh, $params{"customers"});
 
2290   if($params{"vendors"}) {
 
2291     if (ref $params{"vendors"} eq 'HASH') {
 
2292       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
 
2294       $self->_get_vendors($dbh, $params{"vendors"});
 
2298   if($params{"payments"}) {
 
2299     $self->_get_payments($dbh, $params{"payments"});
 
2302   if($params{"departments"}) {
 
2303     $self->_get_departments($dbh, $params{"departments"});
 
2306   if ($params{price_factors}) {
 
2307     $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
 
2310   if ($params{warehouses}) {
 
2311     $self->_get_warehouses($dbh, $params{warehouses});
 
2314   $main::lxdebug->leave_sub();
 
2317 # this sub gets the id and name from $table
 
2319   $main::lxdebug->enter_sub();
 
2321   my ($self, $myconfig, $table) = @_;
 
2323   # connect to database
 
2324   my $dbh = $self->get_standard_dbh($myconfig);
 
2326   $table = $table eq "customer" ? "customer" : "vendor";
 
2327   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
 
2329   my ($query, @values);
 
2331   if (!$self->{openinvoices}) {
 
2333     if ($self->{customernumber} ne "") {
 
2334       $where = qq|(vc.customernumber ILIKE ?)|;
 
2335       push(@values, '%' . $self->{customernumber} . '%');
 
2337       $where = qq|(vc.name ILIKE ?)|;
 
2338       push(@values, '%' . $self->{$table} . '%');
 
2342       qq~SELECT vc.id, vc.name,
 
2343            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
2345          WHERE $where AND (NOT vc.obsolete)
 
2349       qq~SELECT DISTINCT vc.id, vc.name,
 
2350            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
2352          JOIN $table vc ON (a.${table}_id = vc.id)
 
2353          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
 
2355     push(@values, '%' . $self->{$table} . '%');
 
2358   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
 
2360   $main::lxdebug->leave_sub();
 
2362   return scalar(@{ $self->{name_list} });
 
2365 # the selection sub is used in the AR, AP, IS, IR and OE module
 
2368   $main::lxdebug->enter_sub();
 
2370   my ($self, $myconfig, $table, $module) = @_;
 
2373   my $dbh = $self->get_standard_dbh($myconfig);
 
2375   $table = $table eq "customer" ? "customer" : "vendor";
 
2377   my $query = qq|SELECT count(*) FROM $table|;
 
2378   my ($count) = selectrow_query($self, $dbh, $query);
 
2380   # build selection list
 
2381   if ($count < $myconfig->{vclimit}) {
 
2382     $query = qq|SELECT id, name, salesman_id
 
2383                 FROM $table WHERE NOT obsolete
 
2385     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
 
2389   $self->get_employee($dbh);
 
2391   # setup sales contacts
 
2392   $query = qq|SELECT e.id, e.name
 
2394               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
 
2395   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
 
2398   push(@{ $self->{all_employees} },
 
2399        { id   => $self->{employee_id},
 
2400          name => $self->{employee} });
 
2402   # sort the whole thing
 
2403   @{ $self->{all_employees} } =
 
2404     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
 
2406   if ($module eq 'AR') {
 
2408     # prepare query for departments
 
2409     $query = qq|SELECT id, description
 
2412                 ORDER BY description|;
 
2415     $query = qq|SELECT id, description
 
2417                 ORDER BY description|;
 
2420   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2423   $query = qq|SELECT id, description
 
2427   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2430   $query = qq|SELECT printer_description, id
 
2432               ORDER BY printer_description|;
 
2434   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2437   $query = qq|SELECT id, description
 
2441   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
2443   $main::lxdebug->leave_sub();
 
2446 sub language_payment {
 
2447   $main::lxdebug->enter_sub();
 
2449   my ($self, $myconfig) = @_;
 
2451   my $dbh = $self->get_standard_dbh($myconfig);
 
2453   my $query = qq|SELECT id, description
 
2457   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2460   $query = qq|SELECT printer_description, id
 
2462               ORDER BY printer_description|;
 
2464   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2467   $query = qq|SELECT id, description
 
2471   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
2473   # get buchungsgruppen
 
2474   $query = qq|SELECT id, description
 
2475               FROM buchungsgruppen|;
 
2477   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
 
2479   $main::lxdebug->leave_sub();
 
2482 # this is only used for reports
 
2483 sub all_departments {
 
2484   $main::lxdebug->enter_sub();
 
2486   my ($self, $myconfig, $table) = @_;
 
2488   my $dbh = $self->get_standard_dbh($myconfig);
 
2491   if ($table eq 'customer') {
 
2492     $where = "WHERE role = 'P' ";
 
2495   my $query = qq|SELECT id, description
 
2498                  ORDER BY description|;
 
2499   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2501   delete($self->{all_departments}) unless (@{ $self->{all_departments} });
 
2503   $main::lxdebug->leave_sub();
 
2507   $main::lxdebug->enter_sub();
 
2509   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
 
2512   if ($table eq "customer") {
 
2521   $self->all_vc($myconfig, $table, $module);
 
2523   # get last customers or vendors
 
2524   my ($query, $sth, $ref);
 
2526   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
 
2531     my $transdate = "current_date";
 
2532     if ($self->{transdate}) {
 
2533       $transdate = $dbh->quote($self->{transdate});
 
2536     # now get the account numbers
 
2537     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
 
2538                 FROM chart c, taxkeys tk
 
2539                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
 
2540                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
 
2543     $sth = $dbh->prepare($query);
 
2545     do_statement($self, $sth, $query, '%' . $module . '%');
 
2547     $self->{accounts} = "";
 
2548     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
2550       foreach my $key (split(/:/, $ref->{link})) {
 
2551         if ($key =~ /\Q$module\E/) {
 
2553           # cross reference for keys
 
2554           $xkeyref{ $ref->{accno} } = $key;
 
2556           push @{ $self->{"${module}_links"}{$key} },
 
2557             { accno       => $ref->{accno},
 
2558               description => $ref->{description},
 
2559               taxkey      => $ref->{taxkey_id},
 
2560               tax_id      => $ref->{tax_id} };
 
2562           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2568   # get taxkeys and description
 
2569   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
 
2570   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
 
2572   if (($module eq "AP") || ($module eq "AR")) {
 
2573     # get tax rates and description
 
2574     $query = qq|SELECT * FROM tax|;
 
2575     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
 
2581            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
 
2582            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
 
2583            a.intnotes, a.department_id, a.amount AS oldinvtotal,
 
2584            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
 
2586            d.description AS department,
 
2589          JOIN $table c ON (a.${table}_id = c.id)
 
2590          LEFT JOIN employee e ON (e.id = a.employee_id)
 
2591          LEFT JOIN department d ON (d.id = a.department_id)
 
2593     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
 
2595     foreach $key (keys %$ref) {
 
2596       $self->{$key} = $ref->{$key};
 
2599     my $transdate = "current_date";
 
2600     if ($self->{transdate}) {
 
2601       $transdate = $dbh->quote($self->{transdate});
 
2604     # now get the account numbers
 
2605     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
 
2607                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
 
2609                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
 
2610                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
 
2613     $sth = $dbh->prepare($query);
 
2614     do_statement($self, $sth, $query, "%$module%");
 
2616     $self->{accounts} = "";
 
2617     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
2619       foreach my $key (split(/:/, $ref->{link})) {
 
2620         if ($key =~ /\Q$module\E/) {
 
2622           # cross reference for keys
 
2623           $xkeyref{ $ref->{accno} } = $key;
 
2625           push @{ $self->{"${module}_links"}{$key} },
 
2626             { accno       => $ref->{accno},
 
2627               description => $ref->{description},
 
2628               taxkey      => $ref->{taxkey_id},
 
2629               tax_id      => $ref->{tax_id} };
 
2631           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2637     # get amounts from individual entries
 
2640            c.accno, c.description,
 
2641            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
 
2645          LEFT JOIN chart c ON (c.id = a.chart_id)
 
2646          LEFT JOIN project p ON (p.id = a.project_id)
 
2647          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
 
2648                                     WHERE (tk.taxkey_id=a.taxkey) AND
 
2649                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
 
2650                                         THEN tk.chart_id = a.chart_id
 
2653                                        OR (c.link='%tax%')) AND
 
2654                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
 
2655          WHERE a.trans_id = ?
 
2656          AND a.fx_transaction = '0'
 
2657          ORDER BY a.oid, a.transdate|;
 
2658     $sth = $dbh->prepare($query);
 
2659     do_statement($self, $sth, $query, $self->{id});
 
2661     # get exchangerate for currency
 
2662     $self->{exchangerate} =
 
2663       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2666     # store amounts in {acc_trans}{$key} for multiple accounts
 
2667     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
2668       $ref->{exchangerate} =
 
2669         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
 
2670       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
 
2673       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
 
2674         $ref->{amount} *= -1;
 
2676       $ref->{index} = $index;
 
2678       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
 
2684            d.curr AS currencies, d.closedto, d.revtrans,
 
2685            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2686            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
2688     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2689     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2696             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
 
2697             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2698             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
2700     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2701     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2703     if ($self->{"$self->{vc}_id"}) {
 
2705       # only setup currency
 
2706       ($self->{currency}) = split(/:/, $self->{currencies});
 
2710       $self->lastname_used($dbh, $myconfig, $table, $module);
 
2712       # get exchangerate for currency
 
2713       $self->{exchangerate} =
 
2714         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2720   $main::lxdebug->leave_sub();
 
2724   $main::lxdebug->enter_sub();
 
2726   my ($self, $dbh, $myconfig, $table, $module) = @_;
 
2728   my $arap  = ($table eq 'customer') ? "ar" : "ap";
 
2729   $table = $table eq "customer" ? "customer" : "vendor";
 
2730   my $where = "1 = 1";
 
2732   if ($self->{type} =~ /_order/) {
 
2734     $where = "quotation = '0'";
 
2736   if ($self->{type} =~ /_quotation/) {
 
2738     $where = "quotation = '1'";
 
2741   my $query = qq|SELECT MAX(id) FROM $arap
 
2742                  WHERE $where AND ${table}_id > 0|;
 
2743   my ($trans_id) = selectrow_query($self, $dbh, $query);
 
2748          a.curr, a.${table}_id, a.department_id,
 
2749          d.description AS department,
 
2750          ct.name, current_date + ct.terms AS duedate
 
2752        LEFT JOIN $table ct ON (a.${table}_id = ct.id)
 
2753        LEFT JOIN department d ON (a.department_id = d.id)
 
2755   ($self->{currency},   $self->{"${table}_id"}, $self->{department_id},
 
2756    $self->{department}, $self->{$table},        $self->{duedate})
 
2757     = selectrow_query($self, $dbh, $query, $trans_id);
 
2759   $main::lxdebug->leave_sub();
 
2763   $main::lxdebug->enter_sub();
 
2765   my ($self, $myconfig, $thisdate, $days) = @_;
 
2767   my $dbh = $self->get_standard_dbh($myconfig);
 
2772     my $dateformat = $myconfig->{dateformat};
 
2773     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
 
2774     $thisdate = $dbh->quote($thisdate);
 
2775     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
 
2777     $query = qq|SELECT current_date AS thisdate|;
 
2780   ($thisdate) = selectrow_query($self, $dbh, $query);
 
2782   $main::lxdebug->leave_sub();
 
2788   $main::lxdebug->enter_sub();
 
2790   my ($self, $string) = @_;
 
2792   if ($string !~ /%/) {
 
2793     $string = "%$string%";
 
2796   $string =~ s/\'/\'\'/g;
 
2798   $main::lxdebug->leave_sub();
 
2804   $main::lxdebug->enter_sub();
 
2806   my ($self, $flds, $new, $count, $numrows) = @_;
 
2810   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
 
2815   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
 
2817     $j = $item->{ndx} - 1;
 
2818     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
 
2822   for $i ($count + 1 .. $numrows) {
 
2823     map { delete $self->{"${_}_$i"} } @{$flds};
 
2826   $main::lxdebug->leave_sub();
 
2830   $main::lxdebug->enter_sub();
 
2832   my ($self, $myconfig) = @_;
 
2836   my $dbh = $self->dbconnect_noauto($myconfig);
 
2838   my $query = qq|DELETE FROM status
 
2839                  WHERE (formname = ?) AND (trans_id = ?)|;
 
2840   my $sth = prepare_query($self, $dbh, $query);
 
2842   if ($self->{formname} =~ /(check|receipt)/) {
 
2843     for $i (1 .. $self->{rowcount}) {
 
2844       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
 
2847     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
 
2851   my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
2852   my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
2854   my %queued = split / /, $self->{queued};
 
2857   if ($self->{formname} =~ /(check|receipt)/) {
 
2859     # this is a check or receipt, add one entry for each lineitem
 
2860     my ($accno) = split /--/, $self->{account};
 
2861     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
 
2862                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
 
2863     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
 
2864     $sth = prepare_query($self, $dbh, $query);
 
2866     for $i (1 .. $self->{rowcount}) {
 
2867       if ($self->{"checked_$i"}) {
 
2868         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
 
2874     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
2875                 VALUES (?, ?, ?, ?, ?)|;
 
2876     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
 
2877              $queued{$self->{formname}}, $self->{formname});
 
2883   $main::lxdebug->leave_sub();
 
2887   $main::lxdebug->enter_sub();
 
2889   my ($self, $dbh) = @_;
 
2891   my ($query, $printed, $emailed);
 
2893   my $formnames  = $self->{printed};
 
2894   my $emailforms = $self->{emailed};
 
2896   $query = qq|DELETE FROM status
 
2897                  WHERE (formname = ?) AND (trans_id = ?)|;
 
2898   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
 
2900   # this only applies to the forms
 
2901   # checks and receipts are posted when printed or queued
 
2903   if ($self->{queued}) {
 
2904     my %queued = split / /, $self->{queued};
 
2906     foreach my $formname (keys %queued) {
 
2907       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
2908       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
2910       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
2911                   VALUES (?, ?, ?, ?, ?)|;
 
2912       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
 
2914       $formnames  =~ s/\Q$self->{formname}\E//;
 
2915       $emailforms =~ s/\Q$self->{formname}\E//;
 
2920   # save printed, emailed info
 
2921   $formnames  =~ s/^ +//g;
 
2922   $emailforms =~ s/^ +//g;
 
2925   map { $status{$_}{printed} = 1 } split / +/, $formnames;
 
2926   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
 
2928   foreach my $formname (keys %status) {
 
2929     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
2930     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
2932     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
 
2933                 VALUES (?, ?, ?, ?)|;
 
2934     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
 
2937   $main::lxdebug->leave_sub();
 
2941 # $main::locale->text('SAVED')
 
2942 # $main::locale->text('DELETED')
 
2943 # $main::locale->text('ADDED')
 
2944 # $main::locale->text('PAYMENT POSTED')
 
2945 # $main::locale->text('POSTED')
 
2946 # $main::locale->text('POSTED AS NEW')
 
2947 # $main::locale->text('ELSE')
 
2948 # $main::locale->text('SAVED FOR DUNNING')
 
2949 # $main::locale->text('DUNNING STARTED')
 
2950 # $main::locale->text('PRINTED')
 
2951 # $main::locale->text('MAILED')
 
2952 # $main::locale->text('SCREENED')
 
2953 # $main::locale->text('CANCELED')
 
2954 # $main::locale->text('invoice')
 
2955 # $main::locale->text('proforma')
 
2956 # $main::locale->text('sales_order')
 
2957 # $main::locale->text('packing_list')
 
2958 # $main::locale->text('pick_list')
 
2959 # $main::locale->text('purchase_order')
 
2960 # $main::locale->text('bin_list')
 
2961 # $main::locale->text('sales_quotation')
 
2962 # $main::locale->text('request_quotation')
 
2965   $main::lxdebug->enter_sub();
 
2970   if(!exists $self->{employee_id}) {
 
2971     &get_employee($self, $dbh);
 
2975    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
 
2976    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
 
2977   my @values = (conv_i($self->{id}), $self->{login},
 
2978                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
 
2979   do_query($self, $dbh, $query, @values);
 
2981   $main::lxdebug->leave_sub();
 
2985   $main::lxdebug->enter_sub();
 
2987   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
 
2988   my ($orderBy, $desc) = split(/\-\-/, $order);
 
2989   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
 
2992   if ($trans_id ne "") {
 
2994       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 | .
 
2995       qq|FROM history_erp h | .
 
2996       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
 
2997       qq|WHERE trans_id = | . $trans_id
 
2998       . $restriction . qq| |
 
3001     my $sth = $dbh->prepare($query) || $self->dberror($query);
 
3003     $sth->execute() || $self->dberror("$query");
 
3005     while(my $hash_ref = $sth->fetchrow_hashref()) {
 
3006       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
 
3007       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
 
3008       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
 
3009       $tempArray[$i++] = $hash_ref;
 
3011     $main::lxdebug->leave_sub() and return \@tempArray 
 
3012       if ($i > 0 && $tempArray[0] ne "");
 
3014   $main::lxdebug->leave_sub();
 
3018 sub update_defaults {
 
3019   $main::lxdebug->enter_sub();
 
3021   my ($self, $myconfig, $fld, $provided_dbh) = @_;
 
3024   if ($provided_dbh) {
 
3025     $dbh = $provided_dbh;
 
3027     $dbh = $self->dbconnect_noauto($myconfig);
 
3029   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
 
3030   my $sth   = $dbh->prepare($query);
 
3032   $sth->execute || $self->dberror($query);
 
3033   my ($var) = $sth->fetchrow_array;
 
3036   if ($var =~ m/\d+$/) {
 
3037     my $new_var  = (substr $var, $-[0]) * 1 + 1;
 
3038     my $len_diff = length($var) - $-[0] - length($new_var);
 
3039     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
 
3045   $query = qq|UPDATE defaults SET $fld = ?|;
 
3046   do_query($self, $dbh, $query, $var);
 
3048   if (!$provided_dbh) {
 
3053   $main::lxdebug->leave_sub();
 
3058 sub update_business {
 
3059   $main::lxdebug->enter_sub();
 
3061   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
 
3064   if ($provided_dbh) {
 
3065     $dbh = $provided_dbh;
 
3067     $dbh = $self->dbconnect_noauto($myconfig);
 
3070     qq|SELECT customernumberinit FROM business
 
3071        WHERE id = ? FOR UPDATE|;
 
3072   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
 
3074   if ($var =~ m/\d+$/) {
 
3075     my $new_var  = (substr $var, $-[0]) * 1 + 1;
 
3076     my $len_diff = length($var) - $-[0] - length($new_var);
 
3077     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
 
3083   $query = qq|UPDATE business
 
3084               SET customernumberinit = ?
 
3086   do_query($self, $dbh, $query, $var, $business_id);
 
3088   if (!$provided_dbh) {
 
3093   $main::lxdebug->leave_sub();
 
3098 sub get_partsgroup {
 
3099   $main::lxdebug->enter_sub();
 
3101   my ($self, $myconfig, $p) = @_;
 
3103   my $dbh = $self->get_standard_dbh($myconfig);
 
3105   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
 
3107                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
 
3110   if ($p->{searchitems} eq 'part') {
 
3111     $query .= qq|WHERE p.inventory_accno_id > 0|;
 
3113   if ($p->{searchitems} eq 'service') {
 
3114     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
 
3116   if ($p->{searchitems} eq 'assembly') {
 
3117     $query .= qq|WHERE p.assembly = '1'|;
 
3119   if ($p->{searchitems} eq 'labor') {
 
3120     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
 
3123   $query .= qq|ORDER BY partsgroup|;
 
3126     $query = qq|SELECT id, partsgroup FROM partsgroup
 
3127                 ORDER BY partsgroup|;
 
3130   if ($p->{language_code}) {
 
3131     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
 
3132                   t.description AS translation
 
3134                 JOIN parts p ON (p.partsgroup_id = pg.id)
 
3135                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
 
3136                 ORDER BY translation|;
 
3137     @values = ($p->{language_code});
 
3140   $self->{all_partsgroup} = selectall_hashref_query($self, $dbh, $query, @values);
 
3142   $main::lxdebug->leave_sub();
 
3145 sub get_pricegroup {
 
3146   $main::lxdebug->enter_sub();
 
3148   my ($self, $myconfig, $p) = @_;
 
3150   my $dbh = $self->get_standard_dbh($myconfig);
 
3152   my $query = qq|SELECT p.id, p.pricegroup
 
3155   $query .= qq| ORDER BY pricegroup|;
 
3158     $query = qq|SELECT id, pricegroup FROM pricegroup
 
3159                 ORDER BY pricegroup|;
 
3162   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
 
3164   $main::lxdebug->leave_sub();
 
3168 # usage $form->all_years($myconfig, [$dbh])
 
3169 # return list of all years where bookings found
 
3172   $main::lxdebug->enter_sub();
 
3174   my ($self, $myconfig, $dbh) = @_;
 
3176   $dbh ||= $self->get_standard_dbh($myconfig);
 
3179   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
 
3180                    (SELECT MAX(transdate) FROM acc_trans)|;
 
3181   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
 
3183   if ($myconfig->{dateformat} =~ /^yy/) {
 
3184     ($startdate) = split /\W/, $startdate;
 
3185     ($enddate) = split /\W/, $enddate;
 
3187     (@_) = split /\W/, $startdate;
 
3189     (@_) = split /\W/, $enddate;
 
3194   $startdate = substr($startdate,0,4);
 
3195   $enddate = substr($enddate,0,4);
 
3197   while ($enddate >= $startdate) {
 
3198     push @all_years, $enddate--;
 
3203   $main::lxdebug->leave_sub();