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 #======================================================================
 
  52 use List::Util qw(max min sum);
 
  58     $standard_dbh->disconnect();
 
  64   $main::lxdebug->enter_sub(2);
 
  68   my @pairs = split(/&/, $input);
 
  71     my ($name, $value) = split(/=/, $_, 2);
 
  72     $in{$name} = unescape(undef, $value);
 
  75   $main::lxdebug->leave_sub(2);
 
  80 sub _request_to_hash {
 
  81   $main::lxdebug->enter_sub(2);
 
  85   if (!$ENV{'CONTENT_TYPE'}
 
  86       || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
 
  87     $main::lxdebug->leave_sub(2);
 
  88     return _input_to_hash($input);
 
  91   my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr);
 
  94   my $boundary = '--' . $1;
 
  96   foreach my $line (split m/\n/, $input) {
 
  97     last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
 
  99     if (($line eq $boundary) || ($line eq "$boundary\r")) {
 
 100       $params{$name} =~ s|\r?\n$|| if $name;
 
 106       $content_type   = "text/plain";
 
 113     next unless $boundary_found;
 
 115     if (!$headers_done) {
 
 116       $line =~ s/[\r\n]*$//;
 
 123       if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
 
 124         if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
 
 126           substr $line, $-[0], $+[0] - $-[0], "";
 
 129         if ($line =~ m|name\s*=\s*"(.*?)"|i) {
 
 131           substr $line, $-[0], $+[0] - $-[0], "";
 
 135         $params{FILENAME} = $filename if ($filename);
 
 140       if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
 
 149     $params{$name} .= "${line}\n";
 
 152   $params{$name} =~ s|\r?\n$|| if $name;
 
 154   $main::lxdebug->leave_sub(2);
 
 159   $main::lxdebug->enter_sub();
 
 165   if ($LXDebug::watch_form) {
 
 166     require SL::Watchdog;
 
 167     tie %{ $self }, 'SL::Watchdog';
 
 170   read(STDIN, $_, $ENV{CONTENT_LENGTH});
 
 172   if ($ENV{QUERY_STRING}) {
 
 173     $_ = $ENV{QUERY_STRING};
 
 180   my %parameters = _request_to_hash($_);
 
 181   map({ $self->{$_} = $parameters{$_}; } keys(%parameters));
 
 183   $self->{action} = lc $self->{action};
 
 184   $self->{action} =~ s/( |-|,|\#)/_/g;
 
 186   $self->{version}   = "2.4.3";
 
 188   $main::lxdebug->leave_sub();
 
 194   $main::lxdebug->enter_sub();
 
 200   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
 
 202   $main::lxdebug->leave_sub();
 
 206   $main::lxdebug->enter_sub(2);
 
 208   my ($self, $str) = @_;
 
 210   $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
 
 212   $main::lxdebug->leave_sub(2);
 
 218   $main::lxdebug->enter_sub(2);
 
 220   my ($self, $str) = @_;
 
 225   $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
 
 227   $main::lxdebug->leave_sub(2);
 
 233   my ($self, $str) = @_;
 
 235   if ($str && !ref($str)) {
 
 236     $str =~ s/\"/"/g;
 
 244   my ($self, $str) = @_;
 
 246   if ($str && !ref($str)) {
 
 247     $str =~ s/"/\"/g;
 
 255   $main::lxdebug->enter_sub(2);
 
 257   my ($self, $str) = @_;
 
 260     ('order' => ['"', '<', '>'],
 
 266   map({ $str =~ s/$_/$replace{$_}/g; } @{ $replace{"order"} });
 
 268   $main::lxdebug->leave_sub(2);
 
 277     map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
 
 279     for (sort keys %$self) {
 
 280       next if (($_ eq "header") || (ref($self->{$_}) ne ""));
 
 281       print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
 
 288   $main::lxdebug->enter_sub();
 
 290   $main::lxdebug->show_backtrace();
 
 292   my ($self, $msg) = @_;
 
 293   if ($ENV{HTTP_USER_AGENT}) {
 
 295     $self->show_generic_error($msg);
 
 302   $main::lxdebug->leave_sub();
 
 306   $main::lxdebug->enter_sub();
 
 308   my ($self, $msg) = @_;
 
 310   if ($ENV{HTTP_USER_AGENT}) {
 
 313     if (!$self->{header}) {
 
 326     if ($self->{info_function}) {
 
 327       &{ $self->{info_function} }($msg);
 
 333   $main::lxdebug->leave_sub();
 
 336 # calculates the number of rows in a textarea based on the content and column number
 
 337 # can be capped with maxrows
 
 339   $main::lxdebug->enter_sub();
 
 340   my ($self, $str, $cols, $maxrows) = @_;
 
 342   my $rows   = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
 
 345   $main::lxdebug->leave_sub();
 
 346   return min $rows, $maxrows;
 
 350   $main::lxdebug->enter_sub();
 
 352   my ($self, $msg) = @_;
 
 354   $self->error("$msg\n" . $DBI::errstr);
 
 356   $main::lxdebug->leave_sub();
 
 360   $main::lxdebug->enter_sub();
 
 362   my ($self, $name, $msg) = @_;
 
 364   if ($self->{$name} =~ /^\s*$/) {
 
 367   $main::lxdebug->leave_sub();
 
 371   $main::lxdebug->enter_sub();
 
 373   my ($self, $extra_code) = @_;
 
 375   if ($self->{header}) {
 
 376     $main::lxdebug->leave_sub();
 
 380   my ($stylesheet, $favicon);
 
 382   if ($ENV{HTTP_USER_AGENT}) {
 
 385     if ($ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+\d/) {
 
 386       # Only set the DOCTYPE for Internet Explorer. Other browsers have problems displaying the menu otherwise.
 
 387       $doctype = qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n|;
 
 390     my $stylesheets = "$self->{stylesheet} $self->{stylesheets}";
 
 392     $stylesheets =~ s|^\s*||;
 
 393     $stylesheets =~ s|\s*$||;
 
 394     foreach my $file (split m/\s+/, $stylesheets) {
 
 396       next if (! -f "css/$file");
 
 398       $stylesheet .= qq|<link rel="stylesheet" href="css/$file" TYPE="text/css" TITLE="Lx-Office stylesheet">\n|;
 
 401     $self->{favicon}    = "favicon.ico" unless $self->{favicon};
 
 403     if ($self->{favicon} && (-f "$self->{favicon}")) {
 
 405         qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
 
 409     my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
 411     if ($self->{landscape}) {
 
 412       $pagelayout = qq|<style type="text/css">
 
 413                         \@page { size:landscape; }
 
 417     my $fokus = qq|  document.$self->{fokus}.focus();| if ($self->{"fokus"});
 
 421     if ($self->{jsscript} == 1) {
 
 424         <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
 
 425         <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
 
 426         <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
 
 427         <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
 
 434       ? "$self->{title} - $self->{titlebar}"
 
 437     foreach $item (@ { $self->{AJAX} }) {
 
 438       $ajax .= $item->show_javascript();
 
 440     print qq|Content-Type: text/html; charset=${db_charset};
 
 444   <title>$self->{titlebar}</title>
 
 448   <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
 
 452   <script type="text/javascript">
 
 460   <meta name="robots" content="noindex,nofollow" />
 
 461   <script type="text/javascript" src="js/highlight_input.js"></script>
 
 462   <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
 
 464   <script type="text/javascript" src="js/tabcontent.js">
 
 466   /***********************************************
 
 467   * Tab Content script- Dynamic Drive DHTML code library (www.dynamicdrive.com)
 
 468   * This notice MUST stay intact for legal use
 
 469   * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
 
 470   ***********************************************/
 
 481   $main::lxdebug->leave_sub();
 
 484 sub _prepare_html_template {
 
 485   $main::lxdebug->enter_sub();
 
 487   my ($self, $file, $additional_params) = @_;
 
 490   if (!defined(%main::myconfig) || !defined($main::myconfig{"countrycode"})) {
 
 491     $language = $main::language;
 
 493     $language = $main::myconfig{"countrycode"};
 
 495   $language = "de" unless ($language);
 
 497   if (-f "templates/webpages/${file}_${language}.html") {
 
 498     if ((-f ".developer") &&
 
 499         (-f "templates/webpages/${file}_master.html") &&
 
 500         ((stat("templates/webpages/${file}_master.html"))[9] >
 
 501          (stat("templates/webpages/${file}_${language}.html"))[9])) {
 
 502       my $info = "Developer information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
 
 503         "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 504       print(qq|<pre>$info</pre>|);
 
 508     $file = "templates/webpages/${file}_${language}.html";
 
 509   } elsif (-f "templates/webpages/${file}.html") {
 
 510     $file = "templates/webpages/${file}.html";
 
 512     my $info = "Web page template '${file}' not found.\n" .
 
 513       "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 514     print(qq|<pre>$info</pre>|);
 
 518   if ($self->{"DEBUG"}) {
 
 519     $additional_params->{"DEBUG"} = $self->{"DEBUG"};
 
 522   if ($additional_params->{"DEBUG"}) {
 
 523     $additional_params->{"DEBUG"} =
 
 524       "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
 
 527   if (%main::myconfig) {
 
 528     map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
 
 529     my $jsc_dateformat = $main::myconfig{"dateformat"};
 
 530     $jsc_dateformat =~ s/d+/\%d/gi;
 
 531     $jsc_dateformat =~ s/m+/\%m/gi;
 
 532     $jsc_dateformat =~ s/y+/\%Y/gi;
 
 533     $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
 
 536   $additional_params->{"conf_webdav"}                 = $main::webdav;
 
 537   $additional_params->{"conf_lizenzen"}               = $main::lizenzen;
 
 538   $additional_params->{"conf_latex_templates"}        = $main::latex;
 
 539   $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
 
 541   if (%main::debug_options) {
 
 542     map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
 
 545   $main::lxdebug->leave_sub();
 
 550 sub parse_html_template {
 
 551   $main::lxdebug->enter_sub();
 
 553   my ($self, $file, $additional_params) = @_;
 
 555   $additional_params ||= { };
 
 557   $file = $self->_prepare_html_template($file, $additional_params);
 
 559   my $template = HTML::Template->new("filename" => $file,
 
 560                                      "die_on_bad_params" => 0,
 
 562                                      "case_sensitive" => 1,
 
 563                                      "loop_context_vars" => 1,
 
 566   foreach my $key ($template->param()) {
 
 567     my $param = $additional_params->{$key} || $self->{$key};
 
 568     $param = [] if (($template->query("name" => $key) eq "LOOP") && (ref($param) ne "ARRAY"));
 
 569     $template->param($key => $param);
 
 572   my $output = $template->output();
 
 574   $output = $main::locale->{iconv}->convert($output) if ($main::locale);
 
 576   $main::lxdebug->leave_sub();
 
 581 sub parse_html_template2 {
 
 582   $main::lxdebug->enter_sub();
 
 584   my ($self, $file, $additional_params) = @_;
 
 586   $additional_params ||= { };
 
 588   $file = $self->_prepare_html_template($file, $additional_params);
 
 590   my $template = Template->new({ 'INTERPOLATE' => 0,
 
 594                                  'PLUGIN_BASE' => 'SL::Template::Plugin',
 
 597   map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
 
 600   if (!$template->process($file, $additional_params, \$output)) {
 
 601     print STDERR $template->error();
 
 604   $output = $main::locale->{iconv}->convert($output) if ($main::locale);
 
 606   $main::lxdebug->leave_sub();
 
 611 sub show_generic_error {
 
 612   my ($self, $error, $title, $action) = @_;
 
 615   $add_params->{"title"} = $title if ($title);
 
 616   $self->{"label_error"} = $error;
 
 620     map({ delete($self->{$_}); } qw(action));
 
 621     map({ push(@vars, { "name" => $_, "value" => $self->{$_} })
 
 622             if (!ref($self->{$_})); }
 
 624     $add_params->{"SHOW_BUTTON"} = 1;
 
 625     $add_params->{"BUTTON_LABEL"} = $action;
 
 627   $add_params->{"VARIABLES"} = \@vars;
 
 630   print($self->parse_html_template("generic/error", $add_params));
 
 632   die("Error: $error\n");
 
 635 sub show_generic_information {
 
 636   my ($self, $error, $title) = @_;
 
 639   $add_params->{"title"} = $title if ($title);
 
 640   $self->{"label_information"} = $error;
 
 643   print($self->parse_html_template("generic/information", $add_params));
 
 645   die("Information: $error\n");
 
 648 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
 
 649 # changed it to accept an arbitrary number of triggers - sschoeling
 
 651   $main::lxdebug->enter_sub();
 
 654   my $myconfig = shift;
 
 657   # set dateform for jsscript
 
 660     "dd.mm.yy" => "%d.%m.%Y",
 
 661     "dd-mm-yy" => "%d-%m-%Y",
 
 662     "dd/mm/yy" => "%d/%m/%Y",
 
 663     "mm/dd/yy" => "%m/%d/%Y",
 
 664     "mm-dd-yy" => "%m-%d-%Y",
 
 665     "yyyy-mm-dd" => "%Y-%m-%d",
 
 668   my $ifFormat = defined($dateformats{$myconfig{"dateformat"}}) ?
 
 669     $dateformats{$myconfig{"dateformat"}} : "%d.%m.%Y";
 
 676       inputField : "| . (shift) . qq|",
 
 677       ifFormat :"$ifFormat",
 
 678       align : "| .  (shift) . qq|",
 
 679       button : "| . (shift) . qq|"
 
 685        <script type="text/javascript">
 
 686        <!--| . join("", @triggers) . qq|//-->
 
 690   $main::lxdebug->leave_sub();
 
 693 }    #end sub write_trigger
 
 696   $main::lxdebug->enter_sub();
 
 698   my ($self, $msg) = @_;
 
 700   if ($self->{callback}) {
 
 702     ($script, $argv) = split(/\?/, $self->{callback}, 2);
 
 704     $script =~ s|[^a-zA-Z0-9_\.]||g;
 
 705     exec("perl", "$script", $argv);
 
 713   $main::lxdebug->leave_sub();
 
 716 # sort of columns removed - empty sub
 
 718   $main::lxdebug->enter_sub();
 
 720   my ($self, @columns) = @_;
 
 722   $main::lxdebug->leave_sub();
 
 728   $main::lxdebug->enter_sub(2);
 
 730   my ($self, $myconfig, $amount, $places, $dash) = @_;
 
 736   # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
 
 738   my $neg = ($amount =~ s/^-//);
 
 739   my $exp = ($amount =~ m/[e]/) ? 1 : 0;
 
 741   if (defined($places) && ($places ne '')) {
 
 747         my ($actual_places) = ($amount =~ /\.(\d+)/);
 
 748         $actual_places = length($actual_places);
 
 749         $places = $actual_places > $places ? $actual_places : $places;
 
 752     $amount = $self->round_amount($amount, $places);
 
 755   my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
 
 756   my @p = split(/\./, $amount); # split amount at decimal point
 
 758   $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
 
 761   $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
 
 764     ($dash =~ /-/)    ? ($neg ? "($amount)"  : "$amount" )    :
 
 765     ($dash =~ /DRCR/) ? ($neg ? "$amount DR" : "$amount CR" ) :
 
 766                         ($neg ? "-$amount"   : "$amount" )    ;
 
 770   $main::lxdebug->leave_sub(2);
 
 776   $main::lxdebug->enter_sub(2);
 
 781   $input =~ s/(^|[^\#]) \#  (\d+)  /$1$_[$2 - 1]/gx;
 
 782   $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
 
 783   $input =~ s/\#\#/\#/g;
 
 785   $main::lxdebug->leave_sub(2);
 
 791   $main::lxdebug->enter_sub(2);
 
 793   my ($self, $myconfig, $amount) = @_;
 
 795   if (   ($myconfig->{numberformat} eq '1.000,00')
 
 796       || ($myconfig->{numberformat} eq '1000,00')) {
 
 801   if ($myconfig->{numberformat} eq "1'000.00") {
 
 807   $main::lxdebug->leave_sub(2);
 
 809   return ($amount * 1);
 
 813   $main::lxdebug->enter_sub(2);
 
 815   my ($self, $amount, $places) = @_;
 
 818   # Rounding like "Kaufmannsrunden"
 
 819   # Descr. http://de.wikipedia.org/wiki/Rundung
 
 821   # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
 
 824   $amount = $amount * (10**($places));
 
 825   $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
 
 827   $main::lxdebug->leave_sub(2);
 
 829   return $round_amount;
 
 834   $main::lxdebug->enter_sub();
 
 836   my ($self, $myconfig, $userspath) = @_;
 
 837   my ($template, $out);
 
 841   $self->{"cwd"} = getcwd();
 
 842   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
 
 844   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
 
 845     $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
 846   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
 
 847     $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
 
 848     $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
 849   } elsif (($self->{"format"} =~ /html/i) ||
 
 850            (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
 
 851     $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
 852   } elsif (($self->{"format"} =~ /xml/i) ||
 
 853              (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
 
 854     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
 855   } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
 
 856     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
 857   } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
 
 858     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
 859   } elsif ( defined $self->{'format'}) {
 
 860     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
 
 861   } elsif ( $self->{'format'} eq '' ) {
 
 862     $self->error("No Outputformat given: $self->{'format'}");
 
 863   } else { #Catch the rest
 
 864     $self->error("Outputformat not defined: $self->{'format'}");
 
 867   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
 
 868   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
 
 870   map({ $self->{"employee_${_}"} = $myconfig->{$_}; }
 
 871       qw(email tel fax name signature company address businessnumber
 
 872          co_ustid taxnumber duns));
 
 873   map({ $self->{"employee_${_}"} =~ s/\\n/\n/g; }
 
 874       qw(company address signature));
 
 875   map({ $self->{$_} =~ s/\\n/\n/g; } qw(company address signature));
 
 877   map({ $self->{"${_}"} = $myconfig->{$_}; }
 
 881   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
 
 883   # OUT is used for the media, screen, printer, email
 
 884   # for postscript we store a copy in a temporary file
 
 886   my $prepend_userspath;
 
 888   if (!$self->{tmpfile}) {
 
 889     $self->{tmpfile}   = "${fileid}.$self->{IN}";
 
 890     $prepend_userspath = 1;
 
 893   $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
 
 895   $self->{tmpfile} =~ s|.*/||;
 
 896   $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
 
 897   $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
 
 899   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
 901     $self->{OUT} = ">$self->{tmpfile}";
 
 905     open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
 
 907     open(OUT, ">-") or $self->error("STDOUT : $!");
 
 911   if (!$template->parse(*OUT)) {
 
 913     $self->error("$self->{IN} : " . $template->get_error());
 
 918   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
 920     if ($self->{media} eq 'email') {
 
 922       my $mail = new Mailer;
 
 924       map { $mail->{$_} = $self->{$_} }
 
 925         qw(cc bcc subject message version format);
 
 926       $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
 927       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
 
 928       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
 
 929       $mail->{fileid} = "$fileid.";
 
 930       $myconfig->{signature} =~ s/\\r\\n/\\n/g;
 
 932       # if we send html or plain text inline
 
 933       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
 
 934         $mail->{contenttype} = "text/html";
 
 936         $mail->{message}       =~ s/\r\n/<br>\n/g;
 
 937         $myconfig->{signature} =~ s/\\n/<br>\n/g;
 
 938         $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
 
 940         open(IN, $self->{tmpfile})
 
 941           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
 943           $mail->{message} .= $_;
 
 950         if (!$self->{"do_not_attach"}) {
 
 951           @{ $mail->{attachments} } =
 
 952             ({ "filename" => $self->{"tmpfile"},
 
 953                "name" => $self->{"attachment_filename"} ?
 
 954                  $self->{"attachment_filename"} : $self->{"tmpfile"} });
 
 957         $mail->{message}       =~ s/\r\n/\n/g;
 
 958         $myconfig->{signature} =~ s/\\n/\n/g;
 
 959         $mail->{message} .= "\n-- \n$myconfig->{signature}";
 
 963       my $err = $mail->send();
 
 964       $self->error($self->cleanup . "$err") if ($err);
 
 970       my $numbytes = (-s $self->{tmpfile});
 
 971       open(IN, $self->{tmpfile})
 
 972         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
 974       $self->{copies} = 1 unless $self->{media} eq 'printer';
 
 976       chdir("$self->{cwd}");
 
 977       #print(STDERR "Kopien $self->{copies}\n");
 
 978       #print(STDERR "OUT $self->{OUT}\n");
 
 979       for my $i (1 .. $self->{copies}) {
 
 981           open(OUT, $self->{OUT})
 
 982             or $self->error($self->cleanup . "$self->{OUT} : $!");
 
 984           $self->{attachment_filename} = ($self->{attachment_filename}) 
 
 985                                        ? $self->{attachment_filename}
 
 986                                        : $self->generate_attachment_filename();
 
 989           print qq|Content-Type: | . $template->get_mime_type() . qq|
 
 990 Content-Disposition: attachment; filename="$self->{attachment_filename}"
 
 991 Content-Length: $numbytes
 
 995           open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
 
1015   chdir("$self->{cwd}");
 
1016   $main::lxdebug->leave_sub();
 
1019 sub get_formname_translation {
 
1020   my ($self, $formname) = @_;
 
1022   $formname ||= $self->{formname};
 
1024   my %formname_translations = (
 
1025     bin_list            => $main::locale->text('Bin List'),
 
1026     credit_note         => $main::locale->text('Credit Note'),
 
1027     invoice             => $main::locale->text('Invoice'),
 
1028     packing_list        => $main::locale->text('Packing List'),
 
1029     pick_list           => $main::locale->text('Pick List'),
 
1030     proforma            => $main::locale->text('Proforma Invoice'),
 
1031     purchase_order      => $main::locale->text('Purchase Order'),
 
1032     request_quotation   => $main::locale->text('RFQ'),
 
1033     sales_order         => $main::locale->text('Confirmation'),
 
1034     sales_quotation     => $main::locale->text('Quotation'),
 
1035     storno_invoice      => $main::locale->text('Storno Invoice'),
 
1036     storno_packing_list => $main::locale->text('Storno Packing List'),
 
1039   return $formname_translations{$formname}
 
1042 sub generate_attachment_filename {
 
1045   my $attachment_filename = $self->get_formname_translation();
 
1047       (grep { $self->{"type"} eq $_ } qw(invoice credit_note)) ? "inv"
 
1048     : ($self->{"type"} =~ /_quotation$/)                       ? "quo"
 
1051   if ($attachment_filename && $self->{"${prefix}number"}) {
 
1052     $attachment_filename .= "_" . $self->{"${prefix}number"}
 
1053                             . (  $self->{format} =~ /pdf/i          ? ".pdf"
 
1054                                : $self->{format} =~ /postscript/i   ? ".ps"
 
1055                                : $self->{format} =~ /opendocument/i ? ".odt"
 
1056                                : $self->{format} =~ /html/i         ? ".html"
 
1058     $attachment_filename =~ s/ /_/g;
 
1059     my %umlaute = ( "ä" => "ae", "ö" => "oe", "ü" => "ue", 
 
1060                     "Ä" => "Ae", "Ö" => "Oe", "Ü" => "Ue", "ß" => "ss");
 
1061     map { $attachment_filename =~ s/$_/$umlaute{$_}/g } keys %umlaute;
 
1063     $attachment_filename = "";
 
1066   return $attachment_filename;
 
1070   $main::lxdebug->enter_sub();
 
1074   chdir("$self->{tmpdir}");
 
1077   if (-f "$self->{tmpfile}.err") {
 
1078     open(FH, "$self->{tmpfile}.err");
 
1083   if ($self->{tmpfile}) {
 
1084     $self->{tmpfile} =~ s|.*/||g;
 
1086     $self->{tmpfile} =~ s/\.\w+$//g;
 
1087     my $tmpfile = $self->{tmpfile};
 
1088     unlink(<$tmpfile.*>);
 
1091   chdir("$self->{cwd}");
 
1093   $main::lxdebug->leave_sub();
 
1099   $main::lxdebug->enter_sub();
 
1101   my ($self, $date, $myconfig) = @_;
 
1103   if ($date && $date =~ /\D/) {
 
1105     if ($myconfig->{dateformat} =~ /^yy/) {
 
1106       ($yy, $mm, $dd) = split /\D/, $date;
 
1108     if ($myconfig->{dateformat} =~ /^mm/) {
 
1109       ($mm, $dd, $yy) = split /\D/, $date;
 
1111     if ($myconfig->{dateformat} =~ /^dd/) {
 
1112       ($dd, $mm, $yy) = split /\D/, $date;
 
1117     $yy = ($yy < 70) ? $yy + 2000 : $yy;
 
1118     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
 
1120     $dd = "0$dd" if ($dd < 10);
 
1121     $mm = "0$mm" if ($mm < 10);
 
1123     $date = "$yy$mm$dd";
 
1126   $main::lxdebug->leave_sub();
 
1131 # Database routines used throughout
 
1134   $main::lxdebug->enter_sub(2);
 
1136   my ($self, $myconfig) = @_;
 
1138   # connect to database
 
1140     DBI->connect($myconfig->{dbconnect},
 
1141                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
 
1145   if ($myconfig->{dboptions}) {
 
1146     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1149   $main::lxdebug->leave_sub(2);
 
1154 sub dbconnect_noauto {
 
1155   $main::lxdebug->enter_sub();
 
1157   my ($self, $myconfig) = @_;
 
1159   # connect to database
 
1161     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
 
1162                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
 
1166   if ($myconfig->{dboptions}) {
 
1167     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1170   $main::lxdebug->leave_sub();
 
1175 sub get_standard_dbh {
 
1176   $main::lxdebug->enter_sub(2);
 
1178   my ($self, $myconfig) = @_;
 
1180   $standard_dbh ||= $self->dbconnect_noauto($myconfig);
 
1182   $main::lxdebug->leave_sub(2);
 
1184   return $standard_dbh;
 
1187 sub update_balance {
 
1188   $main::lxdebug->enter_sub();
 
1190   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
 
1192   # if we have a value, go do it
 
1195     # retrieve balance from table
 
1196     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
 
1197     my $sth = prepare_execute_query($self, $dbh, $query, @values);
 
1198     my ($balance) = $sth->fetchrow_array;
 
1204     $query = "UPDATE $table SET $field = $balance WHERE $where";
 
1205     do_query($self, $dbh, $query, @values);
 
1207   $main::lxdebug->leave_sub();
 
1210 sub update_exchangerate {
 
1211   $main::lxdebug->enter_sub();
 
1213   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
 
1215   # some sanity check for currency
 
1217     $main::lxdebug->leave_sub();
 
1220   $query = qq|SELECT curr FROM defaults|;
 
1222   my ($currency) = selectrow_query($self, $dbh, $query);
 
1223   my ($defaultcurrency) = split m/:/, $currency;
 
1226   if ($curr eq $defaultcurrency) {
 
1227     $main::lxdebug->leave_sub();
 
1231   $query = qq|SELECT e.curr FROM exchangerate e
 
1232                  WHERE e.curr = ? AND e.transdate = ?
 
1234   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
 
1243   $buy = conv_i($buy, "NULL");
 
1244   $sell = conv_i($sell, "NULL");
 
1247   if ($buy != 0 && $sell != 0) {
 
1248     $set = "buy = $buy, sell = $sell";
 
1249   } elsif ($buy != 0) {
 
1250     $set = "buy = $buy";
 
1251   } elsif ($sell != 0) {
 
1252     $set = "sell = $sell";
 
1255   if ($sth->fetchrow_array) {
 
1256     $query = qq|UPDATE exchangerate
 
1262     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
 
1263                 VALUES (?, $buy, $sell, ?)|;
 
1266   do_query($self, $dbh, $query, $curr, $transdate);
 
1268   $main::lxdebug->leave_sub();
 
1271 sub save_exchangerate {
 
1272   $main::lxdebug->enter_sub();
 
1274   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
 
1276   my $dbh = $self->dbconnect($myconfig);
 
1280   $buy  = $rate if $fld eq 'buy';
 
1281   $sell = $rate if $fld eq 'sell';
 
1284   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
 
1289   $main::lxdebug->leave_sub();
 
1292 sub get_exchangerate {
 
1293   $main::lxdebug->enter_sub();
 
1295   my ($self, $dbh, $curr, $transdate, $fld) = @_;
 
1298   unless ($transdate) {
 
1299     $main::lxdebug->leave_sub();
 
1303   $query = qq|SELECT curr FROM defaults|;
 
1305   my ($currency) = selectrow_query($self, $dbh, $query);
 
1306   my ($defaultcurrency) = split m/:/, $currency;
 
1308   if ($currency eq $defaultcurrency) {
 
1309     $main::lxdebug->leave_sub();
 
1313   $query = qq|SELECT e.$fld FROM exchangerate e
 
1314                  WHERE e.curr = ? AND e.transdate = ?|;
 
1315   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
 
1319   $main::lxdebug->leave_sub();
 
1321   return $exchangerate;
 
1324 sub check_exchangerate {
 
1325   $main::lxdebug->enter_sub();
 
1327   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
 
1329   unless ($transdate) {
 
1330     $main::lxdebug->leave_sub();
 
1334   my ($defaultcurrency) = $self->get_default_currency($myconfig);
 
1336   if ($currency eq $defaultcurrency) {
 
1337     $main::lxdebug->leave_sub();
 
1341   my $dbh   = $self->get_standard_dbh($myconfig);
 
1342   my $query = qq|SELECT e.$fld FROM exchangerate e
 
1343                  WHERE e.curr = ? AND e.transdate = ?|;
 
1345   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
 
1347   $exchangerate = 1 if ($exchangerate eq "");
 
1349   $main::lxdebug->leave_sub();
 
1351   return $exchangerate;
 
1354 sub get_default_currency {
 
1355   $main::lxdebug->enter_sub();
 
1357   my ($self, $myconfig) = @_;
 
1358   my $dbh = $self->get_standard_dbh($myconfig);
 
1360   my $query = qq|SELECT curr FROM defaults|;
 
1362   my ($curr)            = selectrow_query($self, $dbh, $query);
 
1363   my ($defaultcurrency) = split m/:/, $curr;
 
1365   $main::lxdebug->leave_sub();
 
1367   return $defaultcurrency;
 
1371 sub set_payment_options {
 
1372   $main::lxdebug->enter_sub();
 
1374   my ($self, $myconfig, $transdate) = @_;
 
1376   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
 
1378   my $dbh = $self->get_standard_dbh($myconfig);
 
1381     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
 
1382     qq|FROM payment_terms p | .
 
1385   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
 
1386    $self->{payment_terms}) =
 
1387      selectrow_query($self, $dbh, $query, $self->{payment_id});
 
1389   if ($transdate eq "") {
 
1390     if ($self->{invdate}) {
 
1391       $transdate = $self->{invdate};
 
1393       $transdate = $self->{transdate};
 
1398     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
 
1399     qq|FROM payment_terms|;
 
1400   ($self->{netto_date}, $self->{skonto_date}) =
 
1401     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
 
1403   my ($invtotal, $total);
 
1404   my (%amounts, %formatted_amounts);
 
1406   if ($self->{type} =~ /_order$/) {
 
1407     $amounts{invtotal} = $self->{ordtotal};
 
1408     $amounts{total}    = $self->{ordtotal};
 
1410   } elsif ($self->{type} =~ /_quotation$/) {
 
1411     $amounts{invtotal} = $self->{quototal};
 
1412     $amounts{total}    = $self->{quototal};
 
1415     $amounts{invtotal} = $self->{invtotal};
 
1416     $amounts{total}    = $self->{total};
 
1419   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
 
1421   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
 
1422   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
 
1423   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
 
1425   foreach (keys %amounts) {
 
1426     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
 
1427     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
 
1430   if ($self->{"language_id"}) {
 
1432       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
 
1433       qq|FROM translation_payment_terms t | .
 
1434       qq|LEFT JOIN language l ON t.language_id = l.id | .
 
1435       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
 
1436     my ($description_long, $output_numberformat, $output_dateformat,
 
1437       $output_longdates) =
 
1438       selectrow_query($self, $dbh, $query,
 
1439                       $self->{"language_id"}, $self->{"payment_id"});
 
1441     $self->{payment_terms} = $description_long if ($description_long);
 
1443     if ($output_dateformat) {
 
1444       foreach my $key (qw(netto_date skonto_date)) {
 
1446           $main::locale->reformat_date($myconfig, $self->{$key},
 
1452     if ($output_numberformat &&
 
1453         ($output_numberformat ne $myconfig->{"numberformat"})) {
 
1454       my $saved_numberformat = $myconfig->{"numberformat"};
 
1455       $myconfig->{"numberformat"} = $output_numberformat;
 
1456       map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
 
1457       $myconfig->{"numberformat"} = $saved_numberformat;
 
1461   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
 
1462   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
 
1463   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
 
1464   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
 
1465   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
 
1466   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
 
1467   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
 
1469   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
 
1471   $main::lxdebug->leave_sub();
 
1475 sub get_template_language {
 
1476   $main::lxdebug->enter_sub();
 
1478   my ($self, $myconfig) = @_;
 
1480   my $template_code = "";
 
1482   if ($self->{language_id}) {
 
1483     my $dbh = $self->get_standard_dbh($myconfig);
 
1484     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
 
1485     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
 
1488   $main::lxdebug->leave_sub();
 
1490   return $template_code;
 
1493 sub get_printer_code {
 
1494   $main::lxdebug->enter_sub();
 
1496   my ($self, $myconfig) = @_;
 
1498   my $template_code = "";
 
1500   if ($self->{printer_id}) {
 
1501     my $dbh = $self->get_standard_dbh($myconfig);
 
1502     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
 
1503     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
 
1506   $main::lxdebug->leave_sub();
 
1508   return $template_code;
 
1512   $main::lxdebug->enter_sub();
 
1514   my ($self, $myconfig) = @_;
 
1516   my $template_code = "";
 
1518   if ($self->{shipto_id}) {
 
1519     my $dbh = $self->get_standard_dbh($myconfig);
 
1520     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
 
1521     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
 
1522     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
 
1525   $main::lxdebug->leave_sub();
 
1529   $main::lxdebug->enter_sub();
 
1531   my ($self, $dbh, $id, $module) = @_;
 
1536   foreach my $item (qw(name department_1 department_2 street zipcode city country
 
1537                        contact phone fax email)) {
 
1538     if ($self->{"shipto$item"}) {
 
1539       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
 
1541     push(@values, $self->{"shipto${item}"});
 
1545     if ($self->{shipto_id}) {
 
1546       my $query = qq|UPDATE shipto set
 
1548                        shiptodepartment_1 = ?,
 
1549                        shiptodepartment_2 = ?,
 
1558                      WHERE shipto_id = ?|;
 
1559       do_query($self, $dbh, $query, @values, $self->{shipto_id});
 
1561       my $query = qq|SELECT * FROM shipto
 
1562                      WHERE shiptoname = ? AND
 
1563                        shiptodepartment_1 = ? AND
 
1564                        shiptodepartment_2 = ? AND
 
1565                        shiptostreet = ? AND
 
1566                        shiptozipcode = ? AND
 
1568                        shiptocountry = ? AND
 
1569                        shiptocontact = ? AND
 
1575       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
 
1578           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
 
1579                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
 
1580                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
 
1581              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
 
1582         do_query($self, $dbh, $query, $id, @values, $module);
 
1587   $main::lxdebug->leave_sub();
 
1591   $main::lxdebug->enter_sub();
 
1593   my ($self, $dbh) = @_;
 
1595   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
 
1596   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
 
1597   $self->{"employee_id"} *= 1;
 
1599   $main::lxdebug->leave_sub();
 
1603   $main::lxdebug->enter_sub();
 
1605   my ($self, $myconfig, $salesman_id) = @_;
 
1607   $main::lxdebug->leave_sub() and return unless $salesman_id;
 
1609   my $dbh = $self->get_standard_dbh($myconfig);
 
1612     selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|,
 
1616     my $user = new User($main::memberfile, $login);
 
1617     map({ $self->{"salesman_$_"} = $user->{$_}; }
 
1618         qw(address businessnumber co_ustid company duns email fax name
 
1620     $self->{salesman_login} = $login;
 
1622     $self->{salesman_name} = $login
 
1623       if ($self->{salesman_name} eq "");
 
1625     map({ $self->{"salesman_$_"} =~ s/\\n/\n/g; } qw(address company));
 
1628   $main::lxdebug->leave_sub();
 
1632   $main::lxdebug->enter_sub();
 
1634   my ($self, $myconfig) = @_;
 
1636   my $dbh = $self->get_standard_dbh($myconfig);
 
1637   my $query = qq|SELECT current_date + terms_netto FROM payment_terms WHERE id = ?|;
 
1638   ($self->{duedate}) = selectrow_query($self, $dbh, $query, $self->{payment_id});
 
1640   $main::lxdebug->leave_sub();
 
1644   $main::lxdebug->enter_sub();
 
1646   my ($self, $dbh, $id, $key) = @_;
 
1648   $key = "all_contacts" unless ($key);
 
1651     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
 
1652     qq|FROM contacts | .
 
1653     qq|WHERE cp_cv_id = ? | .
 
1654     qq|ORDER BY lower(cp_name)|;
 
1656   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
 
1658   $main::lxdebug->leave_sub();
 
1662   $main::lxdebug->enter_sub();
 
1664   my ($self, $dbh, $key) = @_;
 
1666   my ($all, $old_id, $where, @values);
 
1668   if (ref($key) eq "HASH") {
 
1671     $key = "ALL_PROJECTS";
 
1673     foreach my $p (keys(%{$params})) {
 
1675         $all = $params->{$p};
 
1676       } elsif ($p eq "old_id") {
 
1677         $old_id = $params->{$p};
 
1678       } elsif ($p eq "key") {
 
1679         $key = $params->{$p};
 
1685     $where = "WHERE active ";
 
1687       if (ref($old_id) eq "ARRAY") {
 
1688         my @ids = grep({ $_ } @{$old_id});
 
1690           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
 
1691           push(@values, @ids);
 
1694         $where .= " OR (id = ?) ";
 
1695         push(@values, $old_id);
 
1701     qq|SELECT id, projectnumber, description, active | .
 
1704     qq|ORDER BY lower(projectnumber)|;
 
1706   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
 
1708   $main::lxdebug->leave_sub();
 
1712   $main::lxdebug->enter_sub();
 
1714   my ($self, $dbh, $vc_id, $key) = @_;
 
1716   $key = "all_shipto" unless ($key);
 
1718   # get shipping addresses
 
1719   my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
 
1721   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
 
1723   $main::lxdebug->leave_sub();
 
1727   $main::lxdebug->enter_sub();
 
1729   my ($self, $dbh, $key) = @_;
 
1731   $key = "all_printers" unless ($key);
 
1733   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
 
1735   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1737   $main::lxdebug->leave_sub();
 
1741   $main::lxdebug->enter_sub();
 
1743   my ($self, $dbh, $params) = @_;
 
1745   $key = $params->{key};
 
1746   $key = "all_charts" unless ($key);
 
1748   my $transdate = quote_db_date($params->{transdate});
 
1751     qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
 
1753     qq|LEFT JOIN taxkeys tk ON | .
 
1754     qq|(tk.id = (SELECT id FROM taxkeys | .
 
1755     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
 
1756     qq|          ORDER BY startdate DESC LIMIT 1)) | .
 
1757     qq|ORDER BY c.accno|;
 
1759   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1761   $main::lxdebug->leave_sub();
 
1764 sub _get_taxcharts {
 
1765   $main::lxdebug->enter_sub();
 
1767   my ($self, $dbh, $key) = @_;
 
1769   $key = "all_taxcharts" unless ($key);
 
1771   my $query = qq|SELECT * FROM tax ORDER BY taxkey|;
 
1773   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1775   $main::lxdebug->leave_sub();
 
1779   $main::lxdebug->enter_sub();
 
1781   my ($self, $dbh, $key) = @_;
 
1783   $key = "all_taxzones" unless ($key);
 
1785   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
 
1787   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1789   $main::lxdebug->leave_sub();
 
1792 sub _get_employees {
 
1793   $main::lxdebug->enter_sub();
 
1795   my ($self, $dbh, $default_key, $key) = @_;
 
1797   $key = $default_key unless ($key);
 
1798   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY name|);
 
1800   $main::lxdebug->leave_sub();
 
1803 sub _get_business_types {
 
1804   $main::lxdebug->enter_sub();
 
1806   my ($self, $dbh, $key) = @_;
 
1808   $key = "all_business_types" unless ($key);
 
1810     selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
 
1812   $main::lxdebug->leave_sub();
 
1815 sub _get_languages {
 
1816   $main::lxdebug->enter_sub();
 
1818   my ($self, $dbh, $key) = @_;
 
1820   $key = "all_languages" unless ($key);
 
1822   my $query = qq|SELECT * FROM language ORDER BY id|;
 
1824   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1826   $main::lxdebug->leave_sub();
 
1829 sub _get_dunning_configs {
 
1830   $main::lxdebug->enter_sub();
 
1832   my ($self, $dbh, $key) = @_;
 
1834   $key = "all_dunning_configs" unless ($key);
 
1836   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
 
1838   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1840   $main::lxdebug->leave_sub();
 
1843 sub _get_currencies {
 
1844 $main::lxdebug->enter_sub();
 
1846   my ($self, $dbh, $key) = @_;
 
1848   $key = "all_currencies" unless ($key);
 
1850   my $query = qq|SELECT curr AS currency FROM defaults|;
 
1852   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
 
1854   $main::lxdebug->leave_sub();
 
1858 $main::lxdebug->enter_sub();
 
1860   my ($self, $dbh, $key) = @_;
 
1862   $key = "all_payments" unless ($key);
 
1864   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
 
1866   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1868   $main::lxdebug->leave_sub();
 
1871 sub _get_customers {
 
1872   $main::lxdebug->enter_sub();
 
1874   my ($self, $dbh, $key, $limit) = @_;
 
1876   $key = "all_customers" unless ($key);
 
1877   $limit_clause = "LIMIT $limit" if $limit;
 
1879   my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name $limit_clause|;
 
1881   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1883   $main::lxdebug->leave_sub();
 
1887   $main::lxdebug->enter_sub();
 
1889   my ($self, $dbh, $key) = @_;
 
1891   $key = "all_vendors" unless ($key);
 
1893   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
 
1895   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1897   $main::lxdebug->leave_sub();
 
1900 sub _get_departments {
 
1901   $main::lxdebug->enter_sub();
 
1903   my ($self, $dbh, $key) = @_;
 
1905   $key = "all_departments" unless ($key);
 
1907   my $query = qq|SELECT * FROM department ORDER BY description|;
 
1909   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1911   $main::lxdebug->leave_sub();
 
1914 sub _get_price_factors {
 
1915   $main::lxdebug->enter_sub();
 
1917   my ($self, $dbh, $key) = @_;
 
1919   $key ||= "all_price_factors";
 
1921   my $query = qq|SELECT * FROM price_factors ORDER BY sortkey|;
 
1923   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1925   $main::lxdebug->leave_sub();
 
1929   $main::lxdebug->enter_sub();
 
1934   my $dbh = $self->get_standard_dbh(\%main::myconfig);
 
1935   my ($sth, $query, $ref);
 
1937   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
 
1938   my $vc_id = $self->{"${vc}_id"};
 
1940   if ($params{"contacts"}) {
 
1941     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
 
1944   if ($params{"shipto"}) {
 
1945     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
 
1948   if ($params{"projects"} || $params{"all_projects"}) {
 
1949     $self->_get_projects($dbh, $params{"all_projects"} ?
 
1950                          $params{"all_projects"} : $params{"projects"},
 
1951                          $params{"all_projects"} ? 1 : 0);
 
1954   if ($params{"printers"}) {
 
1955     $self->_get_printers($dbh, $params{"printers"});
 
1958   if ($params{"languages"}) {
 
1959     $self->_get_languages($dbh, $params{"languages"});
 
1962   if ($params{"charts"}) {
 
1963     $self->_get_charts($dbh, $params{"charts"});
 
1966   if ($params{"taxcharts"}) {
 
1967     $self->_get_taxcharts($dbh, $params{"taxcharts"});
 
1970   if ($params{"taxzones"}) {
 
1971     $self->_get_taxzones($dbh, $params{"taxzones"});
 
1974   if ($params{"employees"}) {
 
1975     $self->_get_employees($dbh, "all_employees", $params{"employees"});
 
1978   if ($params{"salesmen"}) {
 
1979     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
 
1982   if ($params{"business_types"}) {
 
1983     $self->_get_business_types($dbh, $params{"business_types"});
 
1986   if ($params{"dunning_configs"}) {
 
1987     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
 
1990   if($params{"currencies"}) {
 
1991     $self->_get_currencies($dbh, $params{"currencies"});
 
1994   if($params{"customers"}) {
 
1995     if (ref $params{"customers"} eq 'HASH') {
 
1996       $self->_get_customers($dbh, $params{"customers"}{key}, $params{"customers"}{limit});
 
1998       $self->_get_customers($dbh, $params{"customers"});
 
2002   if($params{"vendors"}) {
 
2003     if (ref $params{"vendors"} eq 'HASH') {
 
2004       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
 
2006       $self->_get_vendors($dbh, $params{"vendors"});
 
2010   if($params{"payments"}) {
 
2011     $self->_get_payments($dbh, $params{"payments"});
 
2014   if($params{"departments"}) {
 
2015     $self->_get_departments($dbh, $params{"departments"});
 
2018   if ($params{price_factors}) {
 
2019     $self->_get_price_factors($dbh, $params{price_factors});
 
2022   $main::lxdebug->leave_sub();
 
2025 # this sub gets the id and name from $table
 
2027   $main::lxdebug->enter_sub();
 
2029   my ($self, $myconfig, $table) = @_;
 
2031   # connect to database
 
2032   my $dbh = $self->get_standard_dbh($myconfig);
 
2034   $table = $table eq "customer" ? "customer" : "vendor";
 
2035   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
 
2037   my ($query, @values);
 
2039   if (!$self->{openinvoices}) {
 
2041     if ($self->{customernumber} ne "") {
 
2042       $where = qq|(vc.customernumber ILIKE ?)|;
 
2043       push(@values, '%' . $self->{customernumber} . '%');
 
2045       $where = qq|(vc.name ILIKE ?)|;
 
2046       push(@values, '%' . $self->{$table} . '%');
 
2050       qq~SELECT vc.id, vc.name,
 
2051            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
2053          WHERE $where AND (NOT vc.obsolete)
 
2057       qq~SELECT DISTINCT vc.id, vc.name,
 
2058            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
2060          JOIN $table vc ON (a.${table}_id = vc.id)
 
2061          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
 
2063     push(@values, '%' . $self->{$table} . '%');
 
2066   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
 
2068   $main::lxdebug->leave_sub();
 
2070   return scalar(@{ $self->{name_list} });
 
2073 # the selection sub is used in the AR, AP, IS, IR and OE module
 
2076   $main::lxdebug->enter_sub();
 
2078   my ($self, $myconfig, $table, $module) = @_;
 
2081   my $dbh = $self->get_standard_dbh($myconfig);
 
2083   $table = $table eq "customer" ? "customer" : "vendor";
 
2085   my $query = qq|SELECT count(*) FROM $table|;
 
2086   my ($count) = selectrow_query($self, $dbh, $query);
 
2088   # build selection list
 
2089   if ($count < $myconfig->{vclimit}) {
 
2090     $query = qq|SELECT id, name, salesman_id
 
2091                 FROM $table WHERE NOT obsolete
 
2093     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
 
2097   $self->get_employee($dbh);
 
2099   # setup sales contacts
 
2100   $query = qq|SELECT e.id, e.name
 
2102               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
 
2103   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
 
2106   push(@{ $self->{all_employees} },
 
2107        { id   => $self->{employee_id},
 
2108          name => $self->{employee} });
 
2110   # sort the whole thing
 
2111   @{ $self->{all_employees} } =
 
2112     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
 
2114   if ($module eq 'AR') {
 
2116     # prepare query for departments
 
2117     $query = qq|SELECT id, description
 
2120                 ORDER BY description|;
 
2123     $query = qq|SELECT id, description
 
2125                 ORDER BY description|;
 
2128   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2131   $query = qq|SELECT id, description
 
2135   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2138   $query = qq|SELECT printer_description, id
 
2140               ORDER BY printer_description|;
 
2142   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2145   $query = qq|SELECT id, description
 
2149   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
2151   $main::lxdebug->leave_sub();
 
2154 sub language_payment {
 
2155   $main::lxdebug->enter_sub();
 
2157   my ($self, $myconfig) = @_;
 
2159   my $dbh = $self->get_standard_dbh($myconfig);
 
2161   my $query = qq|SELECT id, description
 
2165   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2168   $query = qq|SELECT printer_description, id
 
2170               ORDER BY printer_description|;
 
2172   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2175   $query = qq|SELECT id, description
 
2179   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
2181   # get buchungsgruppen
 
2182   $query = qq|SELECT id, description
 
2183               FROM buchungsgruppen|;
 
2185   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
 
2187   $main::lxdebug->leave_sub();
 
2190 # this is only used for reports
 
2191 sub all_departments {
 
2192   $main::lxdebug->enter_sub();
 
2194   my ($self, $myconfig, $table) = @_;
 
2196   my $dbh = $self->get_standard_dbh($myconfig);
 
2199   if ($table eq 'customer') {
 
2200     $where = "WHERE role = 'P' ";
 
2203   my $query = qq|SELECT id, description
 
2206                  ORDER BY description|;
 
2207   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2209   delete($self->{all_departments}) unless (@{ $self->{all_departments} });
 
2211   $main::lxdebug->leave_sub();
 
2215   $main::lxdebug->enter_sub();
 
2217   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
 
2220   if ($table eq "customer") {
 
2229   $self->all_vc($myconfig, $table, $module);
 
2231   # get last customers or vendors
 
2232   my ($query, $sth, $ref);
 
2234   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
 
2239     my $transdate = "current_date";
 
2240     if ($self->{transdate}) {
 
2241       $transdate = $dbh->quote($self->{transdate});
 
2244     # now get the account numbers
 
2245     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
 
2246                 FROM chart c, taxkeys tk
 
2247                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
 
2248                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
 
2251     $sth = $dbh->prepare($query);
 
2253     do_statement($self, $sth, $query, '%' . $module . '%');
 
2255     $self->{accounts} = "";
 
2256     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
2258       foreach my $key (split(/:/, $ref->{link})) {
 
2259         if ($key =~ /\Q$module\E/) {
 
2261           # cross reference for keys
 
2262           $xkeyref{ $ref->{accno} } = $key;
 
2264           push @{ $self->{"${module}_links"}{$key} },
 
2265             { accno       => $ref->{accno},
 
2266               description => $ref->{description},
 
2267               taxkey      => $ref->{taxkey_id},
 
2268               tax_id      => $ref->{tax_id} };
 
2270           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2276   # get taxkeys and description
 
2277   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
 
2278   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
 
2280   if (($module eq "AP") || ($module eq "AR")) {
 
2281     # get tax rates and description
 
2282     $query = qq|SELECT * FROM tax|;
 
2283     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
 
2289            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
 
2290            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
 
2291            a.intnotes, a.department_id, a.amount AS oldinvtotal,
 
2292            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
 
2294            d.description AS department,
 
2297          JOIN $table c ON (a.${table}_id = c.id)
 
2298          LEFT JOIN employee e ON (e.id = a.employee_id)
 
2299          LEFT JOIN department d ON (d.id = a.department_id)
 
2301     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
 
2303     foreach $key (keys %$ref) {
 
2304       $self->{$key} = $ref->{$key};
 
2307     my $transdate = "current_date";
 
2308     if ($self->{transdate}) {
 
2309       $transdate = $dbh->quote($self->{transdate});
 
2312     # now get the account numbers
 
2313     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
 
2315                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
 
2317                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
 
2318                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
 
2321     $sth = $dbh->prepare($query);
 
2322     do_statement($self, $sth, $query, "%$module%");
 
2324     $self->{accounts} = "";
 
2325     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
2327       foreach my $key (split(/:/, $ref->{link})) {
 
2328         if ($key =~ /\Q$module\E/) {
 
2330           # cross reference for keys
 
2331           $xkeyref{ $ref->{accno} } = $key;
 
2333           push @{ $self->{"${module}_links"}{$key} },
 
2334             { accno       => $ref->{accno},
 
2335               description => $ref->{description},
 
2336               taxkey      => $ref->{taxkey_id},
 
2337               tax_id      => $ref->{tax_id} };
 
2339           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2345     # get amounts from individual entries
 
2348            c.accno, c.description,
 
2349            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
 
2353          LEFT JOIN chart c ON (c.id = a.chart_id)
 
2354          LEFT JOIN project p ON (p.id = a.project_id)
 
2355          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
 
2356                                     WHERE (tk.taxkey_id=a.taxkey) AND
 
2357                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
 
2358                                         THEN tk.chart_id = a.chart_id
 
2361                                        OR (c.link='%tax%')) AND
 
2362                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
 
2363          WHERE a.trans_id = ?
 
2364          AND a.fx_transaction = '0'
 
2365          ORDER BY a.oid, a.transdate|;
 
2366     $sth = $dbh->prepare($query);
 
2367     do_statement($self, $sth, $query, $self->{id});
 
2369     # get exchangerate for currency
 
2370     $self->{exchangerate} =
 
2371       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2374     # store amounts in {acc_trans}{$key} for multiple accounts
 
2375     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
2376       $ref->{exchangerate} =
 
2377         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
 
2378       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
 
2381       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
 
2382         $ref->{amount} *= -1;
 
2384       $ref->{index} = $index;
 
2386       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
 
2392            d.curr AS currencies, d.closedto, d.revtrans,
 
2393            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2394            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
2396     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2397     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2404             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
 
2405             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2406             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
2408     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2409     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2411     if ($self->{"$self->{vc}_id"}) {
 
2413       # only setup currency
 
2414       ($self->{currency}) = split(/:/, $self->{currencies});
 
2418       $self->lastname_used($dbh, $myconfig, $table, $module);
 
2420       # get exchangerate for currency
 
2421       $self->{exchangerate} =
 
2422         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2428   $main::lxdebug->leave_sub();
 
2432   $main::lxdebug->enter_sub();
 
2434   my ($self, $dbh, $myconfig, $table, $module) = @_;
 
2436   my $arap  = ($table eq 'customer') ? "ar" : "ap";
 
2437   $table = $table eq "customer" ? "customer" : "vendor";
 
2438   my $where = "1 = 1";
 
2440   if ($self->{type} =~ /_order/) {
 
2442     $where = "quotation = '0'";
 
2444   if ($self->{type} =~ /_quotation/) {
 
2446     $where = "quotation = '1'";
 
2449   my $query = qq|SELECT MAX(id) FROM $arap
 
2450                  WHERE $where AND ${table}_id > 0|;
 
2451   my ($trans_id) = selectrow_query($self, $dbh, $query);
 
2456          a.curr, a.${table}_id, a.department_id,
 
2457          d.description AS department,
 
2458          ct.name, current_date + ct.terms AS duedate
 
2460        LEFT JOIN $table ct ON (a.${table}_id = ct.id)
 
2461        LEFT JOIN department d ON (a.department_id = d.id)
 
2463   ($self->{currency},   $self->{"${table}_id"}, $self->{department_id},
 
2464    $self->{department}, $self->{$table},        $self->{duedate})
 
2465     = selectrow_query($self, $dbh, $query, $trans_id);
 
2467   $main::lxdebug->leave_sub();
 
2471   $main::lxdebug->enter_sub();
 
2473   my ($self, $myconfig, $thisdate, $days) = @_;
 
2475   my $dbh = $self->get_standard_dbh($myconfig);
 
2480     my $dateformat = $myconfig->{dateformat};
 
2481     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
 
2482     $thisdate = $dbh->quote($thisdate);
 
2483     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
 
2485     $query = qq|SELECT current_date AS thisdate|;
 
2488   ($thisdate) = selectrow_query($self, $dbh, $query);
 
2490   $main::lxdebug->leave_sub();
 
2496   $main::lxdebug->enter_sub();
 
2498   my ($self, $string) = @_;
 
2500   if ($string !~ /%/) {
 
2501     $string = "%$string%";
 
2504   $string =~ s/\'/\'\'/g;
 
2506   $main::lxdebug->leave_sub();
 
2512   $main::lxdebug->enter_sub();
 
2514   my ($self, $flds, $new, $count, $numrows) = @_;
 
2518   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
 
2523   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
 
2525     $j = $item->{ndx} - 1;
 
2526     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
 
2530   for $i ($count + 1 .. $numrows) {
 
2531     map { delete $self->{"${_}_$i"} } @{$flds};
 
2534   $main::lxdebug->leave_sub();
 
2538   $main::lxdebug->enter_sub();
 
2540   my ($self, $myconfig) = @_;
 
2544   my $dbh = $self->dbconnect_noauto($myconfig);
 
2546   my $query = qq|DELETE FROM status
 
2547                  WHERE (formname = ?) AND (trans_id = ?)|;
 
2548   my $sth = prepare_query($self, $dbh, $query);
 
2550   if ($self->{formname} =~ /(check|receipt)/) {
 
2551     for $i (1 .. $self->{rowcount}) {
 
2552       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
 
2555     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
 
2559   my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
2560   my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
2562   my %queued = split / /, $self->{queued};
 
2565   if ($self->{formname} =~ /(check|receipt)/) {
 
2567     # this is a check or receipt, add one entry for each lineitem
 
2568     my ($accno) = split /--/, $self->{account};
 
2569     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
 
2570                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
 
2571     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
 
2572     $sth = prepare_query($self, $dbh, $query);
 
2574     for $i (1 .. $self->{rowcount}) {
 
2575       if ($self->{"checked_$i"}) {
 
2576         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
 
2582     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
2583                 VALUES (?, ?, ?, ?, ?)|;
 
2584     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
 
2585              $queued{$self->{formname}}, $self->{formname});
 
2591   $main::lxdebug->leave_sub();
 
2595   $main::lxdebug->enter_sub();
 
2597   my ($self, $dbh) = @_;
 
2599   my ($query, $printed, $emailed);
 
2601   my $formnames  = $self->{printed};
 
2602   my $emailforms = $self->{emailed};
 
2604   $query = qq|DELETE FROM status
 
2605                  WHERE (formname = ?) AND (trans_id = ?)|;
 
2606   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
 
2608   # this only applies to the forms
 
2609   # checks and receipts are posted when printed or queued
 
2611   if ($self->{queued}) {
 
2612     my %queued = split / /, $self->{queued};
 
2614     foreach my $formname (keys %queued) {
 
2615       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
2616       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
2618       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
2619                   VALUES (?, ?, ?, ?, ?)|;
 
2620       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
 
2622       $formnames  =~ s/\Q$self->{formname}\E//;
 
2623       $emailforms =~ s/\Q$self->{formname}\E//;
 
2628   # save printed, emailed info
 
2629   $formnames  =~ s/^ +//g;
 
2630   $emailforms =~ s/^ +//g;
 
2633   map { $status{$_}{printed} = 1 } split / +/, $formnames;
 
2634   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
 
2636   foreach my $formname (keys %status) {
 
2637     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
2638     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
2640     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
 
2641                 VALUES (?, ?, ?, ?)|;
 
2642     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
 
2645   $main::lxdebug->leave_sub();
 
2649 # $main::locale->text('SAVED')
 
2650 # $main::locale->text('DELETED')
 
2651 # $main::locale->text('ADDED')
 
2652 # $main::locale->text('PAYMENT POSTED')
 
2653 # $main::locale->text('POSTED')
 
2654 # $main::locale->text('POSTED AS NEW')
 
2655 # $main::locale->text('ELSE')
 
2656 # $main::locale->text('SAVED FOR DUNNING')
 
2657 # $main::locale->text('DUNNING STARTED')
 
2658 # $main::locale->text('PRINTED')
 
2659 # $main::locale->text('MAILED')
 
2660 # $main::locale->text('SCREENED')
 
2661 # $main::locale->text('CANCELED')
 
2662 # $main::locale->text('invoice')
 
2663 # $main::locale->text('proforma')
 
2664 # $main::locale->text('sales_order')
 
2665 # $main::locale->text('packing_list')
 
2666 # $main::locale->text('pick_list')
 
2667 # $main::locale->text('purchase_order')
 
2668 # $main::locale->text('bin_list')
 
2669 # $main::locale->text('sales_quotation')
 
2670 # $main::locale->text('request_quotation')
 
2673   $main::lxdebug->enter_sub();
 
2678   if(!exists $self->{employee_id}) {
 
2679     &get_employee($self, $dbh);
 
2683    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
 
2684    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
 
2685   my @values = (conv_i($self->{id}), $self->{login},
 
2686                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
 
2687   do_query($self, $dbh, $query, @values);
 
2689   $main::lxdebug->leave_sub();
 
2693   $main::lxdebug->enter_sub();
 
2695   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
 
2696   my ($orderBy, $desc) = split(/\-\-/, $order);
 
2697   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
 
2700   if ($trans_id ne "") {
 
2702       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 | .
 
2703       qq|FROM history_erp h | .
 
2704       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
 
2705       qq|WHERE trans_id = | . $trans_id
 
2706       . $restriction . qq| |
 
2709     my $sth = $dbh->prepare($query) || $self->dberror($query);
 
2711     $sth->execute() || $self->dberror("$query");
 
2713     while(my $hash_ref = $sth->fetchrow_hashref()) {
 
2714       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
 
2715       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
 
2716       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
 
2717       $tempArray[$i++] = $hash_ref;
 
2719     $main::lxdebug->leave_sub() and return \@tempArray 
 
2720       if ($i > 0 && $tempArray[0] ne "");
 
2722   $main::lxdebug->leave_sub();
 
2726 sub update_defaults {
 
2727   $main::lxdebug->enter_sub();
 
2729   my ($self, $myconfig, $fld, $provided_dbh) = @_;
 
2732   if ($provided_dbh) {
 
2733     $dbh = $provided_dbh;
 
2735     $dbh = $self->dbconnect_noauto($myconfig);
 
2737   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
 
2738   my $sth   = $dbh->prepare($query);
 
2740   $sth->execute || $self->dberror($query);
 
2741   my ($var) = $sth->fetchrow_array;
 
2744   if ($var =~ m/\d+$/) {
 
2745     my $new_var  = (substr $var, $-[0]) * 1 + 1;
 
2746     my $len_diff = length($var) - $-[0] - length($new_var);
 
2747     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
 
2753   $query = qq|UPDATE defaults SET $fld = ?|;
 
2754   do_query($self, $dbh, $query, $var);
 
2756   if (!$provided_dbh) {
 
2761   $main::lxdebug->leave_sub();
 
2766 sub update_business {
 
2767   $main::lxdebug->enter_sub();
 
2769   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
 
2772   if ($provided_dbh) {
 
2773     $dbh = $provided_dbh;
 
2775     $dbh = $self->dbconnect_noauto($myconfig);
 
2778     qq|SELECT customernumberinit FROM business
 
2779        WHERE id = ? FOR UPDATE|;
 
2780   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
 
2782   if ($var =~ m/\d+$/) {
 
2783     my $new_var  = (substr $var, $-[0]) * 1 + 1;
 
2784     my $len_diff = length($var) - $-[0] - length($new_var);
 
2785     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
 
2791   $query = qq|UPDATE business
 
2792               SET customernumberinit = ?
 
2794   do_query($self, $dbh, $query, $var, $business_id);
 
2796   if (!$provided_dbh) {
 
2801   $main::lxdebug->leave_sub();
 
2806 sub get_partsgroup {
 
2807   $main::lxdebug->enter_sub();
 
2809   my ($self, $myconfig, $p) = @_;
 
2811   my $dbh = $self->get_standard_dbh($myconfig);
 
2813   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
 
2815                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
 
2818   if ($p->{searchitems} eq 'part') {
 
2819     $query .= qq|WHERE p.inventory_accno_id > 0|;
 
2821   if ($p->{searchitems} eq 'service') {
 
2822     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
 
2824   if ($p->{searchitems} eq 'assembly') {
 
2825     $query .= qq|WHERE p.assembly = '1'|;
 
2827   if ($p->{searchitems} eq 'labor') {
 
2828     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
 
2831   $query .= qq|ORDER BY partsgroup|;
 
2834     $query = qq|SELECT id, partsgroup FROM partsgroup
 
2835                 ORDER BY partsgroup|;
 
2838   if ($p->{language_code}) {
 
2839     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
 
2840                   t.description AS translation
 
2842                 JOIN parts p ON (p.partsgroup_id = pg.id)
 
2843                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
 
2844                 ORDER BY translation|;
 
2845     @values = ($p->{language_code});
 
2848   $self->{all_partsgroup} = selectall_hashref_query($self, $dbh, $query, @values);
 
2850   $main::lxdebug->leave_sub();
 
2853 sub get_pricegroup {
 
2854   $main::lxdebug->enter_sub();
 
2856   my ($self, $myconfig, $p) = @_;
 
2858   my $dbh = $self->get_standard_dbh($myconfig);
 
2860   my $query = qq|SELECT p.id, p.pricegroup
 
2863   $query .= qq| ORDER BY pricegroup|;
 
2866     $query = qq|SELECT id, pricegroup FROM pricegroup
 
2867                 ORDER BY pricegroup|;
 
2870   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
 
2872   $main::lxdebug->leave_sub();
 
2876 # usage $form->all_years($myconfig, [$dbh])
 
2877 # return list of all years where bookings found
 
2880   $main::lxdebug->enter_sub();
 
2882   my ($self, $myconfig, $dbh) = @_;
 
2884   $dbh ||= $self->get_standard_dbh($myconfig);
 
2887   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
 
2888                    (SELECT MAX(transdate) FROM acc_trans)|;
 
2889   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
 
2891   if ($myconfig->{dateformat} =~ /^yy/) {
 
2892     ($startdate) = split /\W/, $startdate;
 
2893     ($enddate) = split /\W/, $enddate;
 
2895     (@_) = split /\W/, $startdate;
 
2897     (@_) = split /\W/, $enddate;
 
2902   $startdate = substr($startdate,0,4);
 
2903   $enddate = substr($enddate,0,4);
 
2905   while ($enddate >= $startdate) {
 
2906     push @all_years, $enddate--;
 
2911   $main::lxdebug->leave_sub();