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 #======================================================================
 
  57     $standard_dbh->disconnect();
 
  63   $main::lxdebug->enter_sub(2);
 
  67   my @pairs = split(/&/, $input);
 
  70     my ($name, $value) = split(/=/, $_, 2);
 
  71     $in{$name} = unescape(undef, $value);
 
  74   $main::lxdebug->leave_sub(2);
 
  79 sub _request_to_hash {
 
  80   $main::lxdebug->enter_sub(2);
 
  84   if (!$ENV{'CONTENT_TYPE'}
 
  85       || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
 
  86     $main::lxdebug->leave_sub(2);
 
  87     return _input_to_hash($input);
 
  90   my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr);
 
  93   my $boundary = '--' . $1;
 
  95   foreach my $line (split m/\n/, $input) {
 
  96     last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
 
  98     if (($line eq $boundary) || ($line eq "$boundary\r")) {
 
  99       $params{$name} =~ s|\r?\n$|| if $name;
 
 101       undef $name, $filename;
 
 104       $content_type   = "text/plain";
 
 111     next unless $boundary_found;
 
 113     if (!$headers_done) {
 
 114       $line =~ s/[\r\n]*$//;
 
 121       if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
 
 122         if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
 
 124           substr $line, $-[0], $+[0] - $-[0], "";
 
 127         if ($line =~ m|name\s*=\s*"(.*?)"|i) {
 
 129           substr $line, $-[0], $+[0] - $-[0], "";
 
 133         $params{FILENAME} = $filename if ($filename);
 
 138       if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
 
 147     $params{$name} .= "${line}\n";
 
 150   $params{$name} =~ s|\r?\n$|| if $name;
 
 152   $main::lxdebug->leave_sub(2);
 
 157   $main::lxdebug->enter_sub();
 
 163   if ($LXDebug::watch_form) {
 
 164     require SL::Watchdog;
 
 165     tie %{ $self }, 'SL::Watchdog';
 
 168   read(STDIN, $_, $ENV{CONTENT_LENGTH});
 
 170   if ($ENV{QUERY_STRING}) {
 
 171     $_ = $ENV{QUERY_STRING};
 
 178   my %parameters = _request_to_hash($_);
 
 179   map({ $self->{$_} = $parameters{$_}; } keys(%parameters));
 
 181   $self->{action} = lc $self->{action};
 
 182   $self->{action} =~ s/( |-|,|\#)/_/g;
 
 184   $self->{version}   = "2.4.2";
 
 186   $main::lxdebug->leave_sub();
 
 192   $main::lxdebug->enter_sub();
 
 198   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
 
 200   $main::lxdebug->leave_sub();
 
 204   $main::lxdebug->enter_sub(2);
 
 206   my ($self, $str) = @_;
 
 208   $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
 
 210   $main::lxdebug->leave_sub(2);
 
 216   $main::lxdebug->enter_sub(2);
 
 218   my ($self, $str) = @_;
 
 223   $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
 
 225   $main::lxdebug->leave_sub(2);
 
 231   my ($self, $str) = @_;
 
 233   if ($str && !ref($str)) {
 
 234     $str =~ s/\"/"/g;
 
 242   my ($self, $str) = @_;
 
 244   if ($str && !ref($str)) {
 
 245     $str =~ s/"/\"/g;
 
 253   $main::lxdebug->enter_sub(2);
 
 255   my ($self, $str) = @_;
 
 258     ('order' => ['"', '<', '>'],
 
 264   map({ $str =~ s/$_/$replace{$_}/g; } @{ $replace{"order"} });
 
 266   $main::lxdebug->leave_sub(2);
 
 275     map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
 
 277     for (sort keys %$self) {
 
 278       next if (($_ eq "header") || (ref($self->{$_}) ne ""));
 
 279       print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
 
 286   $main::lxdebug->enter_sub();
 
 288   $main::lxdebug->show_backtrace();
 
 290   my ($self, $msg) = @_;
 
 291   if ($ENV{HTTP_USER_AGENT}) {
 
 293     $self->show_generic_error($msg);
 
 297     if ($self->{error_function}) {
 
 298       &{ $self->{error_function} }($msg);
 
 304   $main::lxdebug->leave_sub();
 
 308   $main::lxdebug->enter_sub();
 
 310   my ($self, $msg) = @_;
 
 312   if ($ENV{HTTP_USER_AGENT}) {
 
 315     if (!$self->{header}) {
 
 328     if ($self->{info_function}) {
 
 329       &{ $self->{info_function} }($msg);
 
 335   $main::lxdebug->leave_sub();
 
 339   $main::lxdebug->enter_sub();
 
 341   my ($self, $str, $cols, $maxrows) = @_;
 
 345   map { $rows += int(((length) - 2) / $cols) + 1 } split /\r/, $str;
 
 347   $maxrows = $rows unless defined $maxrows;
 
 349   $main::lxdebug->leave_sub();
 
 351   return ($rows > $maxrows) ? $maxrows : $rows;
 
 355   $main::lxdebug->enter_sub();
 
 357   my ($self, $msg) = @_;
 
 359   $self->error("$msg\n" . $DBI::errstr);
 
 361   $main::lxdebug->leave_sub();
 
 365   $main::lxdebug->enter_sub();
 
 367   my ($self, $name, $msg) = @_;
 
 369   if ($self->{$name} =~ /^\s*$/) {
 
 372   $main::lxdebug->leave_sub();
 
 376   $main::lxdebug->enter_sub();
 
 378   my ($self, $extra_code) = @_;
 
 380   if ($self->{header}) {
 
 381     $main::lxdebug->leave_sub();
 
 385   my ($stylesheet, $favicon);
 
 387   if ($ENV{HTTP_USER_AGENT}) {
 
 389     if ($self->{stylesheet} && (-f "css/$self->{stylesheet}")) {
 
 391         qq|<LINK REL="stylesheet" HREF="css/$self->{stylesheet}" TYPE="text/css" TITLE="Lx-Office stylesheet">
 
 395     $self->{favicon}    = "favicon.ico" unless $self->{favicon};
 
 397     if ($self->{favicon} && (-f "$self->{favicon}")) {
 
 399         qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
 
 403     my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
 405     if ($self->{landscape}) {
 
 406       $pagelayout = qq|<style type="text/css">
 
 407                         \@page { size:landscape; }
 
 411     my $fokus = qq|  document.$self->{fokus}.focus();| if ($self->{"fokus"});
 
 415     if ($self->{jsscript} == 1) {
 
 418         <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
 
 419         <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
 
 420         <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
 
 421         <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
 
 428       ? "$self->{title} - $self->{titlebar}"
 
 431     foreach $item (@ { $self->{AJAX} }) {
 
 432       $ajax .= $item->show_javascript();
 
 434     print qq|Content-Type: text/html; charset=${db_charset};
 
 438   <title>$self->{titlebar}</title>
 
 442   <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
 
 446   <script type="text/javascript">
 
 454   <meta name="robots" content="noindex,nofollow" />
 
 455   <script type="text/javascript" src="js/highlight_input.js"></script>
 
 456   <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
 
 458   <script type="text/javascript" src="js/tabcontent.js">
 
 460   /***********************************************
 
 461   * Tab Content script- Dynamic Drive DHTML code library (www.dynamicdrive.com)
 
 462   * This notice MUST stay intact for legal use
 
 463   * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
 
 464   ***********************************************/
 
 475   $main::lxdebug->leave_sub();
 
 478 sub _prepare_html_template {
 
 479   $main::lxdebug->enter_sub();
 
 481   my ($self, $file, $additional_params) = @_;
 
 484   if (!defined(%main::myconfig) || !defined($main::myconfig{"countrycode"})) {
 
 485     $language = $main::language;
 
 487     $language = $main::myconfig{"countrycode"};
 
 489   $language = "de" unless ($language);
 
 491   if (-f "templates/webpages/${file}_${language}.html") {
 
 492     if ((-f ".developer") &&
 
 493         (-f "templates/webpages/${file}_master.html") &&
 
 494         ((stat("templates/webpages/${file}_master.html"))[9] >
 
 495          (stat("templates/webpages/${file}_${language}.html"))[9])) {
 
 496       my $info = "Developer information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
 
 497         "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 498       print(qq|<pre>$info</pre>|);
 
 502     $file = "templates/webpages/${file}_${language}.html";
 
 503   } elsif (-f "templates/webpages/${file}.html") {
 
 504     $file = "templates/webpages/${file}.html";
 
 506     my $info = "Web page template '${file}' not found.\n" .
 
 507       "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 508     print(qq|<pre>$info</pre>|);
 
 512   if ($self->{"DEBUG"}) {
 
 513     $additional_params->{"DEBUG"} = $self->{"DEBUG"};
 
 516   if ($additional_params->{"DEBUG"}) {
 
 517     $additional_params->{"DEBUG"} =
 
 518       "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
 
 521   if (%main::myconfig) {
 
 522     map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
 
 523     my $jsc_dateformat = $main::myconfig{"dateformat"};
 
 524     $jsc_dateformat =~ s/d+/\%d/gi;
 
 525     $jsc_dateformat =~ s/m+/\%m/gi;
 
 526     $jsc_dateformat =~ s/y+/\%Y/gi;
 
 527     $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
 
 530   $additional_params->{"conf_webdav"}                 = $main::webdav;
 
 531   $additional_params->{"conf_lizenzen"}               = $main::lizenzen;
 
 532   $additional_params->{"conf_latex_templates"}        = $main::latex;
 
 533   $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
 
 535   if (%main::debug_options) {
 
 536     map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
 
 539   $main::lxdebug->leave_sub();
 
 544 sub parse_html_template {
 
 545   $main::lxdebug->enter_sub();
 
 547   my ($self, $file, $additional_params) = @_;
 
 549   $additional_params ||= { };
 
 551   $file = $self->_prepare_html_template($file, $additional_params);
 
 553   my $template = HTML::Template->new("filename" => $file,
 
 554                                      "die_on_bad_params" => 0,
 
 556                                      "case_sensitive" => 1,
 
 557                                      "loop_context_vars" => 1,
 
 560   foreach my $key ($template->param()) {
 
 561     my $param = $additional_params->{$key} || $self->{$key};
 
 562     $param = [] if (($template->query("name" => $key) eq "LOOP") && (ref($param) ne "ARRAY"));
 
 563     $template->param($key => $param);
 
 566   my $output = $template->output();
 
 568   $output = $main::locale->{iconv}->convert($output) if ($main::locale);
 
 570   $main::lxdebug->leave_sub();
 
 575 sub parse_html_template2 {
 
 576   $main::lxdebug->enter_sub();
 
 578   my ($self, $file, $additional_params) = @_;
 
 580   $additional_params ||= { };
 
 582   $file = $self->_prepare_html_template($file, $additional_params);
 
 584   my $template = Template->new({ 'INTERPOLATE' => 0,
 
 585                                  'PRE_CHOMP'   => Template::Constants::CHOMP_COLLAPSE,
 
 586                                  'POST_CHOMP'  => Template::Constants::CHOMP_COLLAPSE,
 
 592   map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
 
 595   $template->process($file, $additional_params, \$output);
 
 597   $output = $main::locale->{iconv}->convert($output) if ($main::locale);
 
 599   $main::lxdebug->leave_sub();
 
 604 sub show_generic_error {
 
 605   my ($self, $error, $title, $action) = @_;
 
 608   $add_params->{"title"} = $title if ($title);
 
 609   $self->{"label_error"} = $error;
 
 613     map({ delete($self->{$_}); } qw(action));
 
 614     map({ push(@vars, { "name" => $_, "value" => $self->{$_} })
 
 615             if (!ref($self->{$_})); }
 
 617     $add_params->{"SHOW_BUTTON"} = 1;
 
 618     $add_params->{"BUTTON_LABEL"} = $action;
 
 620   $add_params->{"VARIABLES"} = \@vars;
 
 623   print($self->parse_html_template("generic/error", $add_params));
 
 625   die("Error: $error\n");
 
 628 sub show_generic_information {
 
 629   my ($self, $error, $title) = @_;
 
 632   $add_params->{"title"} = $title if ($title);
 
 633   $self->{"label_information"} = $error;
 
 636   print($self->parse_html_template("generic/information", $add_params));
 
 638   die("Information: $error\n");
 
 641 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
 
 642 # changed it to accept an arbitrary number of triggers - sschoeling
 
 644   $main::lxdebug->enter_sub();
 
 647   my $myconfig = shift;
 
 650   # set dateform for jsscript
 
 653     "dd.mm.yy" => "%d.%m.%Y",
 
 654     "dd-mm-yy" => "%d-%m-%Y",
 
 655     "dd/mm/yy" => "%d/%m/%Y",
 
 656     "mm/dd/yy" => "%m/%d/%Y",
 
 657     "mm-dd-yy" => "%m-%d-%Y",
 
 658     "yyyy-mm-dd" => "%Y-%m-%d",
 
 661   my $ifFormat = defined($dateformats{$myconfig{"dateformat"}}) ?
 
 662     $dateformats{$myconfig{"dateformat"}} : "%d.%m.%Y";
 
 669       inputField : "| . (shift) . qq|",
 
 670       ifFormat :"$ifFormat",
 
 671       align : "| .  (shift) . qq|",
 
 672       button : "| . (shift) . qq|"
 
 678        <script type="text/javascript">
 
 679        <!--| . join("", @triggers) . qq|//-->
 
 683   $main::lxdebug->leave_sub();
 
 686 }    #end sub write_trigger
 
 689   $main::lxdebug->enter_sub();
 
 691   my ($self, $msg) = @_;
 
 693   if ($self->{callback}) {
 
 695     ($script, $argv) = split(/\?/, $self->{callback});
 
 696     exec("perl", "$script", $argv);
 
 704   $main::lxdebug->leave_sub();
 
 707 # sort of columns removed - empty sub
 
 709   $main::lxdebug->enter_sub();
 
 711   my ($self, @columns) = @_;
 
 713   $main::lxdebug->leave_sub();
 
 719   $main::lxdebug->enter_sub(2);
 
 721   my ($self, $myconfig, $amount, $places, $dash) = @_;
 
 726   my $neg = ($amount =~ s/-//);
 
 728   if (defined($places) && ($places ne '')) {
 
 733       my ($actual_places) = ($amount =~ /\.(\d+)/);
 
 734       $actual_places = length($actual_places);
 
 735       $places = $actual_places > $places ? $actual_places : $places;
 
 738     $amount = $self->round_amount($amount, $places);
 
 741   my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
 
 742   my @p = split(/\./, $amount); # split amount at decimal point
 
 744   $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
 
 747   $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
 
 750     ($dash =~ /-/)    ? ($neg ? "($amount)"  : "$amount" )    :
 
 751     ($dash =~ /DRCR/) ? ($neg ? "$amount DR" : "$amount CR" ) :
 
 752                         ($neg ? "-$amount"   : "$amount" )    ;
 
 756   $main::lxdebug->leave_sub(2);
 
 761   $main::lxdebug->enter_sub(2);
 
 763   my ($self, $myconfig, $amount) = @_;
 
 765   if (   ($myconfig->{numberformat} eq '1.000,00')
 
 766       || ($myconfig->{numberformat} eq '1000,00')) {
 
 771   if ($myconfig->{numberformat} eq "1'000.00") {
 
 777   $main::lxdebug->leave_sub(2);
 
 779   return ($amount * 1);
 
 783   $main::lxdebug->enter_sub(2);
 
 785   my ($self, $amount, $places) = @_;
 
 788   # Rounding like "Kaufmannsrunden"
 
 789   # Descr. http://de.wikipedia.org/wiki/Rundung
 
 791   # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
 
 794   $amount = $amount * (10**($places));
 
 795   $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
 
 797   $main::lxdebug->leave_sub(2);
 
 799   return $round_amount;
 
 804   $main::lxdebug->enter_sub();
 
 806   my ($self, $myconfig, $userspath) = @_;
 
 807   my ($template, $out);
 
 811   $self->{"cwd"} = getcwd();
 
 812   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
 
 814   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
 
 815     $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
 816   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
 
 817     $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
 
 818     $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
 819   } elsif (($self->{"format"} =~ /html/i) ||
 
 820            (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
 
 821     $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
 822   } elsif (($self->{"format"} =~ /xml/i) ||
 
 823              (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
 
 824     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
 825   } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
 
 826     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
 827   } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
 
 828     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
 829   } elsif ( defined $self->{'format'}) {
 
 830     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
 
 831   } elsif ( $self->{'format'} eq '' ) {
 
 832     $self->error("No Outputformat given: $self->{'format'}");
 
 833   } else { #Catch the rest
 
 834     $self->error("Outputformat not defined: $self->{'format'}");
 
 837   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
 
 838   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
 
 840   map({ $self->{"employee_${_}"} = $myconfig->{$_}; }
 
 841       qw(email tel fax name signature company address businessnumber
 
 842          co_ustid taxnumber duns));
 
 843   map({ $self->{"employee_${_}"} =~ s/\\n/\n/g; }
 
 844       qw(company address signature));
 
 845   map({ $self->{$_} =~ s/\\n/\n/g; } qw(company address signature));
 
 847   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
 
 849   # OUT is used for the media, screen, printer, email
 
 850   # for postscript we store a copy in a temporary file
 
 852   my $prepend_userspath;
 
 854   if (!$self->{tmpfile}) {
 
 855     $self->{tmpfile}   = "${fileid}.$self->{IN}";
 
 856     $prepend_userspath = 1;
 
 859   $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
 
 861   $self->{tmpfile} =~ s|.*/||;
 
 862   $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
 
 863   $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
 
 865   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
 867     $self->{OUT} = ">$self->{tmpfile}";
 
 871     open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
 
 873     open(OUT, ">-") or $self->error("STDOUT : $!");
 
 877   if (!$template->parse(*OUT)) {
 
 879     $self->error("$self->{IN} : " . $template->get_error());
 
 884   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
 886     if ($self->{media} eq 'email') {
 
 888       my $mail = new Mailer;
 
 890       map { $mail->{$_} = $self->{$_} }
 
 891         qw(cc bcc subject message version format);
 
 892       $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
 893       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
 
 894       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
 
 895       $mail->{fileid} = "$fileid.";
 
 896       $myconfig->{signature} =~ s/\\r\\n/\\n/g;
 
 898       # if we send html or plain text inline
 
 899       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
 
 900         $mail->{contenttype} = "text/html";
 
 902         $mail->{message}       =~ s/\r\n/<br>\n/g;
 
 903         $myconfig->{signature} =~ s/\\n/<br>\n/g;
 
 904         $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
 
 906         open(IN, $self->{tmpfile})
 
 907           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
 909           $mail->{message} .= $_;
 
 916         if (!$self->{"do_not_attach"}) {
 
 917           @{ $mail->{attachments} } =
 
 918             ({ "filename" => $self->{"tmpfile"},
 
 919                "name" => $self->{"attachment_filename"} ?
 
 920                  $self->{"attachment_filename"} : $self->{"tmpfile"} });
 
 923         $mail->{message}       =~ s/\r\n/\n/g;
 
 924         $myconfig->{signature} =~ s/\\n/\n/g;
 
 925         $mail->{message} .= "\n-- \n$myconfig->{signature}";
 
 929       my $err = $mail->send();
 
 930       $self->error($self->cleanup . "$err") if ($err);
 
 936       my $numbytes = (-s $self->{tmpfile});
 
 937       open(IN, $self->{tmpfile})
 
 938         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
 940       $self->{copies} = 1 unless $self->{media} eq 'printer';
 
 942       chdir("$self->{cwd}");
 
 943       #print(STDERR "Kopien $self->{copies}\n");
 
 944       #print(STDERR "OUT $self->{OUT}\n");
 
 945       for my $i (1 .. $self->{copies}) {
 
 947           open(OUT, $self->{OUT})
 
 948             or $self->error($self->cleanup . "$self->{OUT} : $!");
 
 950           $self->{attachment_filename} = ($self->{attachment_filename}) 
 
 951                                        ? $self->{attachment_filename}
 
 952                                        : $self->generate_attachment_filename();
 
 955           print qq|Content-Type: | . $template->get_mime_type() . qq|
 
 956 Content-Disposition: attachment; filename="$self->{attachment_filename}"
 
 957 Content-Length: $numbytes
 
 961           open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
 
 981   chdir("$self->{cwd}");
 
 982   $main::lxdebug->leave_sub();
 
 985 sub generate_attachment_filename {
 
 988   my %formname_translations = (
 
 989      bin_list            => $main::locale->text('Bin List'),
 
 990      credit_note         => $main::locale->text('Credit Note'),
 
 991      invoice             => $main::locale->text('Invoice'),
 
 992      packing_list        => $main::locale->text('Packing List'),
 
 993      pick_list           => $main::locale->text('Pick List'),
 
 994      proforma            => $main::locale->text('Proforma Invoice'),
 
 995      purchase_order      => $main::locale->text('Purchase Order'),
 
 996      request_quotation   => $main::locale->text('RFQ'),
 
 997      sales_order         => $main::locale->text('Confirmation'),
 
 998      sales_quotation     => $main::locale->text('Quotation'),
 
 999      storno_invoice      => $main::locale->text('Storno Invoice'),
 
1000      storno_packing_list => $main::locale->text('Storno Packing List'),
 
1003   my $attachment_filename = $formname_translations{$self->{"formname"}};
 
1005       (grep { $self->{"type"} eq $_ } qw(invoice credit_note)) ? "inv"
 
1006     : ($self->{"type"} =~ /_quotation$/)                       ? "quo"
 
1009   if ($attachment_filename && $self->{"${prefix}number"}) {
 
1010     $attachment_filename .= "_" . $self->{"${prefix}number"}
 
1011                             . (  $self->{format} =~ /pdf/i          ? ".pdf"
 
1012                                : $self->{format} =~ /postscript/i   ? ".ps"
 
1013                                : $self->{format} =~ /opendocument/i ? ".odt"
 
1014                                : $self->{format} =~ /html/i         ? ".html"
 
1016     $attachment_filename =~ s/ /_/g;
 
1017     my %umlaute = ( "ä" => "ae", "ö" => "oe", "ü" => "ue", 
 
1018                     "Ä" => "Ae", "Ö" => "Oe", "Ü" => "Ue", "ß" => "ss");
 
1019     map { $attachment_filename =~ s/$_/$umlaute{$_}/g } keys %umlaute;
 
1021     $attachment_filename = "";
 
1024   return $attachment_filename;
 
1028   $main::lxdebug->enter_sub();
 
1032   chdir("$self->{tmpdir}");
 
1035   if (-f "$self->{tmpfile}.err") {
 
1036     open(FH, "$self->{tmpfile}.err");
 
1041   if ($self->{tmpfile}) {
 
1042     $self->{tmpfile} =~ s|.*/||g;
 
1044     $self->{tmpfile} =~ s/\.\w+$//g;
 
1045     my $tmpfile = $self->{tmpfile};
 
1046     unlink(<$tmpfile.*>);
 
1049   chdir("$self->{cwd}");
 
1051   $main::lxdebug->leave_sub();
 
1057   $main::lxdebug->enter_sub();
 
1059   my ($self, $date, $myconfig) = @_;
 
1061   if ($date && $date =~ /\D/) {
 
1063     if ($myconfig->{dateformat} =~ /^yy/) {
 
1064       ($yy, $mm, $dd) = split /\D/, $date;
 
1066     if ($myconfig->{dateformat} =~ /^mm/) {
 
1067       ($mm, $dd, $yy) = split /\D/, $date;
 
1069     if ($myconfig->{dateformat} =~ /^dd/) {
 
1070       ($dd, $mm, $yy) = split /\D/, $date;
 
1075     $yy = ($yy < 70) ? $yy + 2000 : $yy;
 
1076     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
 
1078     $dd = "0$dd" if ($dd < 10);
 
1079     $mm = "0$mm" if ($mm < 10);
 
1081     $date = "$yy$mm$dd";
 
1084   $main::lxdebug->leave_sub();
 
1089 # Database routines used throughout
 
1092   $main::lxdebug->enter_sub(2);
 
1094   my ($self, $myconfig) = @_;
 
1096   # connect to database
 
1098     DBI->connect($myconfig->{dbconnect},
 
1099                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
 
1103   if ($myconfig->{dboptions}) {
 
1104     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1107   $main::lxdebug->leave_sub(2);
 
1112 sub dbconnect_noauto {
 
1113   $main::lxdebug->enter_sub();
 
1115   my ($self, $myconfig) = @_;
 
1117   # connect to database
 
1119     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
 
1120                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
 
1124   if ($myconfig->{dboptions}) {
 
1125     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1128   $main::lxdebug->leave_sub();
 
1133 sub get_standard_dbh {
 
1134   $main::lxdebug->enter_sub(2);
 
1136   my ($self, $myconfig) = @_;
 
1138   $standard_dbh ||= $self->dbconnect_noauto($myconfig);
 
1140   $main::lxdebug->leave_sub(2);
 
1142   return $standard_dbh;
 
1145 sub update_balance {
 
1146   $main::lxdebug->enter_sub();
 
1148   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
 
1150   # if we have a value, go do it
 
1153     # retrieve balance from table
 
1154     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
 
1155     my $sth = prepare_execute_query($self, $dbh, $query, @values);
 
1156     my ($balance) = $sth->fetchrow_array;
 
1162     $query = "UPDATE $table SET $field = $balance WHERE $where";
 
1163     do_query($self, $dbh, $query, @values);
 
1165   $main::lxdebug->leave_sub();
 
1168 sub update_exchangerate {
 
1169   $main::lxdebug->enter_sub();
 
1171   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
 
1173   # some sanity check for currency
 
1175     $main::lxdebug->leave_sub();
 
1178   my $query = qq|SELECT curr FROM defaults|;
 
1180   my ($currency) = selectrow_query($self, $dbh, $query);
 
1181   my ($defaultcurrency) = split m/:/, $currency;
 
1184   if ($curr eq $defaultcurrency) {
 
1185     $main::lxdebug->leave_sub();
 
1189   my $query = qq|SELECT e.curr FROM exchangerate e
 
1190                  WHERE e.curr = ? AND e.transdate = ?
 
1192   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
 
1201   $buy = conv_i($buy, "NULL");
 
1202   $sell = conv_i($sell, "NULL");
 
1205   if ($buy != 0 && $sell != 0) {
 
1206     $set = "buy = $buy, sell = $sell";
 
1207   } elsif ($buy != 0) {
 
1208     $set = "buy = $buy";
 
1209   } elsif ($sell != 0) {
 
1210     $set = "sell = $sell";
 
1213   if ($sth->fetchrow_array) {
 
1214     $query = qq|UPDATE exchangerate
 
1220     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
 
1221                 VALUES (?, $buy, $sell, ?)|;
 
1224   do_query($self, $dbh, $query, $curr, $transdate);
 
1226   $main::lxdebug->leave_sub();
 
1229 sub save_exchangerate {
 
1230   $main::lxdebug->enter_sub();
 
1232   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
 
1234   my $dbh = $self->dbconnect($myconfig);
 
1238   $buy  = $rate if $fld eq 'buy';
 
1239   $sell = $rate if $fld eq 'sell';
 
1242   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
 
1247   $main::lxdebug->leave_sub();
 
1250 sub get_exchangerate {
 
1251   $main::lxdebug->enter_sub();
 
1253   my ($self, $dbh, $curr, $transdate, $fld) = @_;
 
1255   unless ($transdate) {
 
1256     $main::lxdebug->leave_sub();
 
1260   my $query = qq|SELECT curr FROM defaults|;
 
1262   my ($currency) = selectrow_query($self, $dbh, $query);
 
1263   my ($defaultcurrency) = split m/:/, $currency;
 
1265   if ($currency eq $defaultcurrency) {
 
1266     $main::lxdebug->leave_sub();
 
1270   my $query = qq|SELECT e.$fld FROM exchangerate e
 
1271                  WHERE e.curr = ? AND e.transdate = ?|;
 
1272   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
 
1276   $main::lxdebug->leave_sub();
 
1278   return $exchangerate;
 
1281 sub check_exchangerate {
 
1282   $main::lxdebug->enter_sub();
 
1284   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
 
1286   unless ($transdate) {
 
1287     $main::lxdebug->leave_sub();
 
1291   my ($defaultcurrency) = $self->get_default_currency($myconfig);
 
1293   if ($currency eq $defaultcurrency) {
 
1294     $main::lxdebug->leave_sub();
 
1298   my $dbh   = $self->get_standard_dbh($myconfig);
 
1299   my $query = qq|SELECT e.$fld FROM exchangerate e
 
1300                  WHERE e.curr = ? AND e.transdate = ?|;
 
1302   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
 
1304   $exchangerate = 1 if ($exchangerate eq "");
 
1306   $main::lxdebug->leave_sub();
 
1308   return $exchangerate;
 
1311 sub get_default_currency {
 
1312   $main::lxdebug->enter_sub();
 
1314   my ($self, $myconfig) = @_;
 
1315   my $dbh = $self->get_standard_dbh($myconfig);
 
1317   my $query = qq|SELECT curr FROM defaults|;
 
1319   my ($curr)            = selectrow_query($self, $dbh, $query);
 
1320   my ($defaultcurrency) = split m/:/, $curr;
 
1322   $main::lxdebug->leave_sub();
 
1324   return $defaultcurrency;
 
1328 sub set_payment_options {
 
1329   $main::lxdebug->enter_sub();
 
1331   my ($self, $myconfig, $transdate) = @_;
 
1333   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
 
1335   my $dbh = $self->get_standard_dbh($myconfig);
 
1338     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
 
1339     qq|FROM payment_terms p | .
 
1342   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
 
1343    $self->{payment_terms}) =
 
1344      selectrow_query($self, $dbh, $query, $self->{payment_id});
 
1346   if ($transdate eq "") {
 
1347     if ($self->{invdate}) {
 
1348       $transdate = $self->{invdate};
 
1350       $transdate = $self->{transdate};
 
1355     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
 
1356     qq|FROM payment_terms|;
 
1357   ($self->{netto_date}, $self->{skonto_date}) =
 
1358     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
 
1360   my $total = ($self->{invtotal}) ? $self->{invtotal} : $self->{ordtotal};
 
1361   my $skonto_amount = $self->parse_amount($myconfig, $total) *
 
1362     $self->{percent_skonto};
 
1364   $self->{skonto_amount} =
 
1365     $self->format_amount($myconfig, $skonto_amount, 2);
 
1367   if ($self->{"language_id"}) {
 
1369       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
 
1370       qq|FROM translation_payment_terms t | .
 
1371       qq|LEFT JOIN language l ON t.language_id = l.id | .
 
1372       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
 
1373     my ($description_long, $output_numberformat, $output_dateformat,
 
1374       $output_longdates) =
 
1375       selectrow_query($self, $dbh, $query,
 
1376                       $self->{"language_id"}, $self->{"payment_id"});
 
1378     $self->{payment_terms} = $description_long if ($description_long);
 
1380     if ($output_dateformat) {
 
1381       foreach my $key (qw(netto_date skonto_date)) {
 
1383           $main::locale->reformat_date($myconfig, $self->{$key},
 
1389     if ($output_numberformat &&
 
1390         ($output_numberformat ne $myconfig->{"numberformat"})) {
 
1391       my $saved_numberformat = $myconfig->{"numberformat"};
 
1392       $myconfig->{"numberformat"} = $output_numberformat;
 
1393       $self->{skonto_amount} =
 
1394         $self->format_amount($myconfig, $skonto_amount, 2);
 
1395       $myconfig->{"numberformat"} = $saved_numberformat;
 
1399   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
 
1400   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
 
1401   $self->{payment_terms} =~ s/<%skonto_amount%>/$self->{skonto_amount}/g;
 
1402   $self->{payment_terms} =~ s/<%total%>/$self->{total}/g;
 
1403   $self->{payment_terms} =~ s/<%invtotal%>/$self->{invtotal}/g;
 
1404   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
 
1405   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
 
1406   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
 
1407   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
 
1408   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
 
1410   $main::lxdebug->leave_sub();
 
1414 sub get_template_language {
 
1415   $main::lxdebug->enter_sub();
 
1417   my ($self, $myconfig) = @_;
 
1419   my $template_code = "";
 
1421   if ($self->{language_id}) {
 
1422     my $dbh = $self->get_standard_dbh($myconfig);
 
1423     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
 
1424     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
 
1427   $main::lxdebug->leave_sub();
 
1429   return $template_code;
 
1432 sub get_printer_code {
 
1433   $main::lxdebug->enter_sub();
 
1435   my ($self, $myconfig) = @_;
 
1437   my $template_code = "";
 
1439   if ($self->{printer_id}) {
 
1440     my $dbh = $self->get_standard_dbh($myconfig);
 
1441     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
 
1442     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
 
1445   $main::lxdebug->leave_sub();
 
1447   return $template_code;
 
1451   $main::lxdebug->enter_sub();
 
1453   my ($self, $myconfig) = @_;
 
1455   my $template_code = "";
 
1457   if ($self->{shipto_id}) {
 
1458     my $dbh = $self->get_standard_dbh($myconfig);
 
1459     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
 
1460     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
 
1461     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
 
1464   $main::lxdebug->leave_sub();
 
1468   $main::lxdebug->enter_sub();
 
1470   my ($self, $dbh, $id, $module) = @_;
 
1474   foreach my $item (qw(name department_1 department_2 street zipcode city country
 
1475                        contact phone fax email)) {
 
1476     if ($self->{"shipto$item"}) {
 
1477       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
 
1479     push(@values, $self->{"shipto${item}"});
 
1482     if ($self->{shipto_id}) {
 
1483       my $query = qq|UPDATE shipto set
 
1485                        shiptodepartment_1 = ?,
 
1486                        shiptodepartment_2 = ?,
 
1495                      WHERE shipto_id = ?|;
 
1496       do_query($self, $dbh, $query, @values, $self->{shipto_id});
 
1498       my $query = qq|SELECT * FROM shipto
 
1499                      WHERE shiptoname = ? AND
 
1500                        shiptodepartment_1 = ? AND
 
1501                        shiptodepartment_2 = ? AND
 
1502                        shiptostreet = ? AND
 
1503                        shiptozipcode = ? AND
 
1505                        shiptocountry = ? AND
 
1506                        shiptocontact = ? AND
 
1510       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values);
 
1513           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
 
1514                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
 
1515                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
 
1516              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
 
1517         do_query($self, $dbh, $query, $id, @values, $module);
 
1522   $main::lxdebug->leave_sub();
 
1526   $main::lxdebug->enter_sub();
 
1528   my ($self, $dbh) = @_;
 
1530   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
 
1531   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
 
1532   $self->{"employee_id"} *= 1;
 
1534   $main::lxdebug->leave_sub();
 
1538   $main::lxdebug->enter_sub();
 
1540   my ($self, $myconfig, $salesman_id) = @_;
 
1542   $main::lxdebug->leave_sub() and return unless $salesman_id;
 
1544   my $dbh = $self->get_standard_dbh($myconfig);
 
1547     selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|,
 
1551     my $user = new User($main::memberfile, $login);
 
1552     map({ $self->{"salesman_$_"} = $user->{$_}; }
 
1553         qw(address businessnumber co_ustid company duns email fax name
 
1555     $self->{salesman_login} = $login;
 
1557     $self->{salesman_name} = $login
 
1558       if ($self->{salesman_name} eq "");
 
1560     map({ $self->{"salesman_$_"} =~ s/\\n/\n/g; } qw(address company));
 
1563   $main::lxdebug->leave_sub();
 
1567   $main::lxdebug->enter_sub();
 
1569   my ($self, $myconfig) = @_;
 
1571   my $dbh = $self->get_standard_dbh($myconfig);
 
1572   my $query = qq|SELECT current_date + terms_netto FROM payment_terms WHERE id = ?|;
 
1573   ($self->{duedate}) = selectrow_query($self, $dbh, $query, $self->{payment_id});
 
1575   $main::lxdebug->leave_sub();
 
1579   $main::lxdebug->enter_sub();
 
1581   my ($self, $dbh, $id, $key) = @_;
 
1583   $key = "all_contacts" unless ($key);
 
1586     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
 
1587     qq|FROM contacts | .
 
1588     qq|WHERE cp_cv_id = ? | .
 
1589     qq|ORDER BY lower(cp_name)|;
 
1591   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
 
1593   $main::lxdebug->leave_sub();
 
1597   $main::lxdebug->enter_sub();
 
1599   my ($self, $dbh, $key) = @_;
 
1601   my ($all, $old_id, $where, @values);
 
1603   if (ref($key) eq "HASH") {
 
1606     $key = "ALL_PROJECTS";
 
1608     foreach my $p (keys(%{$params})) {
 
1610         $all = $params->{$p};
 
1611       } elsif ($p eq "old_id") {
 
1612         $old_id = $params->{$p};
 
1613       } elsif ($p eq "key") {
 
1614         $key = $params->{$p};
 
1620     $where = "WHERE active ";
 
1622       if (ref($old_id) eq "ARRAY") {
 
1623         my @ids = grep({ $_ } @{$old_id});
 
1625           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
 
1626           push(@values, @ids);
 
1629         $where .= " OR (id = ?) ";
 
1630         push(@values, $old_id);
 
1636     qq|SELECT id, projectnumber, description, active | .
 
1639     qq|ORDER BY lower(projectnumber)|;
 
1641   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
 
1643   $main::lxdebug->leave_sub();
 
1647   $main::lxdebug->enter_sub();
 
1649   my ($self, $dbh, $vc_id, $key) = @_;
 
1651   $key = "all_shipto" unless ($key);
 
1653   # get shipping addresses
 
1654   my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
 
1656   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
 
1658   $main::lxdebug->leave_sub();
 
1662   $main::lxdebug->enter_sub();
 
1664   my ($self, $dbh, $key) = @_;
 
1666   $key = "all_printers" unless ($key);
 
1668   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
 
1670   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1672   $main::lxdebug->leave_sub();
 
1676   $main::lxdebug->enter_sub();
 
1678   my ($self, $dbh, $params) = @_;
 
1680   $key = $params->{key};
 
1681   $key = "all_charts" unless ($key);
 
1683   my $transdate = quote_db_date($params->{transdate});
 
1686     qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
 
1688     qq|LEFT JOIN taxkeys tk ON | .
 
1689     qq|(tk.id = (SELECT id FROM taxkeys | .
 
1690     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
 
1691     qq|          ORDER BY startdate DESC LIMIT 1)) | .
 
1692     qq|ORDER BY c.accno|;
 
1694   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1696   $main::lxdebug->leave_sub();
 
1699 sub _get_taxcharts {
 
1700   $main::lxdebug->enter_sub();
 
1702   my ($self, $dbh, $key) = @_;
 
1704   $key = "all_taxcharts" unless ($key);
 
1706   my $query = qq|SELECT * FROM tax ORDER BY taxkey|;
 
1708   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1710   $main::lxdebug->leave_sub();
 
1714   $main::lxdebug->enter_sub();
 
1716   my ($self, $dbh, $key) = @_;
 
1718   $key = "all_taxzones" unless ($key);
 
1720   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
 
1722   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1724   $main::lxdebug->leave_sub();
 
1727 sub _get_employees {
 
1728   $main::lxdebug->enter_sub();
 
1730   my ($self, $dbh, $default_key, $key) = @_;
 
1732   $key = $default_key unless ($key);
 
1733   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY name|);
 
1735   $main::lxdebug->leave_sub();
 
1738 sub _get_business_types {
 
1739   $main::lxdebug->enter_sub();
 
1741   my ($self, $dbh, $key) = @_;
 
1743   $key = "all_business_types" unless ($key);
 
1745     selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
 
1747   $main::lxdebug->leave_sub();
 
1750 sub _get_languages {
 
1751   $main::lxdebug->enter_sub();
 
1753   my ($self, $dbh, $key) = @_;
 
1755   $key = "all_languages" unless ($key);
 
1757   my $query = qq|SELECT * FROM language ORDER BY id|;
 
1759   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1761   $main::lxdebug->leave_sub();
 
1764 sub _get_dunning_configs {
 
1765   $main::lxdebug->enter_sub();
 
1767   my ($self, $dbh, $key) = @_;
 
1769   $key = "all_dunning_configs" unless ($key);
 
1771   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
 
1773   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1775   $main::lxdebug->leave_sub();
 
1778 sub _get_currencies {
 
1779 $main::lxdebug->enter_sub();
 
1781   my ($self, $dbh, $key) = @_;
 
1783   $key = "all_currencies" unless ($key);
 
1785   my $query = qq|SELECT curr AS currency FROM defaults|;
 
1787   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
 
1789   $main::lxdebug->leave_sub();
 
1793 $main::lxdebug->enter_sub();
 
1795   my ($self, $dbh, $key) = @_;
 
1797   $key = "all_payments" unless ($key);
 
1799   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
 
1801   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1803   $main::lxdebug->leave_sub();
 
1806 sub _get_customers {
 
1807   $main::lxdebug->enter_sub();
 
1809   my ($self, $dbh, $key) = @_;
 
1811   $key = "all_customers" unless ($key);
 
1813   my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name|;
 
1815   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1817   $main::lxdebug->leave_sub();
 
1821   $main::lxdebug->enter_sub();
 
1823   my ($self, $dbh, $key) = @_;
 
1825   $key = "all_vendors" unless ($key);
 
1827   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
 
1829   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1831   $main::lxdebug->leave_sub();
 
1834 sub _get_departments {
 
1835   $main::lxdebug->enter_sub();
 
1837   my ($self, $dbh, $key) = @_;
 
1839   $key = "all_departments" unless ($key);
 
1841   my $query = qq|SELECT * FROM department ORDER BY description|;
 
1843   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1845   $main::lxdebug->leave_sub();
 
1849   $main::lxdebug->enter_sub();
 
1854   my $dbh = $self->get_standard_dbh(\%main::myconfig);
 
1855   my ($sth, $query, $ref);
 
1857   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
 
1858   my $vc_id = $self->{"${vc}_id"};
 
1860   if ($params{"contacts"}) {
 
1861     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
 
1864   if ($params{"shipto"}) {
 
1865     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
 
1868   if ($params{"projects"} || $params{"all_projects"}) {
 
1869     $self->_get_projects($dbh, $params{"all_projects"} ?
 
1870                          $params{"all_projects"} : $params{"projects"},
 
1871                          $params{"all_projects"} ? 1 : 0);
 
1874   if ($params{"printers"}) {
 
1875     $self->_get_printers($dbh, $params{"printers"});
 
1878   if ($params{"languages"}) {
 
1879     $self->_get_languages($dbh, $params{"languages"});
 
1882   if ($params{"charts"}) {
 
1883     $self->_get_charts($dbh, $params{"charts"});
 
1886   if ($params{"taxcharts"}) {
 
1887     $self->_get_taxcharts($dbh, $params{"taxcharts"});
 
1890   if ($params{"taxzones"}) {
 
1891     $self->_get_taxzones($dbh, $params{"taxzones"});
 
1894   if ($params{"employees"}) {
 
1895     $self->_get_employees($dbh, "all_employees", $params{"employees"});
 
1898   if ($params{"salesmen"}) {
 
1899     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
 
1902   if ($params{"business_types"}) {
 
1903     $self->_get_business_types($dbh, $params{"business_types"});
 
1906   if ($params{"dunning_configs"}) {
 
1907     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
 
1910   if($params{"currencies"}) {
 
1911     $self->_get_currencies($dbh, $params{"currencies"});
 
1914   if($params{"customers"}) {
 
1915     $self->_get_customers($dbh, $params{"customers"});
 
1918   if($params{"vendors"}) {
 
1919     $self->_get_vendors($dbh, $params{"vendors"});
 
1922   if($params{"payments"}) {
 
1923     $self->_get_payments($dbh, $params{"payments"});
 
1926   if($params{"departments"}) {
 
1927     $self->_get_departments($dbh, $params{"departments"});
 
1930   $main::lxdebug->leave_sub();
 
1933 # this sub gets the id and name from $table
 
1935   $main::lxdebug->enter_sub();
 
1937   my ($self, $myconfig, $table) = @_;
 
1939   # connect to database
 
1940   my $dbh = $self->get_standard_dbh($myconfig);
 
1942   $table = $table eq "customer" ? "customer" : "vendor";
 
1943   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
 
1945   my ($query, @values);
 
1947   if (!$self->{openinvoices}) {
 
1949     if ($self->{customernumber} ne "") {
 
1950       $where = qq|(vc.customernumber ILIKE ?)|;
 
1951       push(@values, '%' . $self->{customernumber} . '%');
 
1953       $where = qq|(vc.name ILIKE ?)|;
 
1954       push(@values, '%' . $self->{$table} . '%');
 
1958       qq~SELECT vc.id, vc.name,
 
1959            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
1961          WHERE $where AND (NOT vc.obsolete)
 
1965       qq~SELECT DISTINCT vc.id, vc.name,
 
1966            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
1968          JOIN $table vc ON (a.${table}_id = vc.id)
 
1969          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
 
1971     push(@values, '%' . $self->{$table} . '%');
 
1974   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
 
1976   $main::lxdebug->leave_sub();
 
1978   return scalar(@{ $self->{name_list} });
 
1981 # the selection sub is used in the AR, AP, IS, IR and OE module
 
1984   $main::lxdebug->enter_sub();
 
1986   my ($self, $myconfig, $table, $module) = @_;
 
1989   my $dbh = $self->get_standard_dbh($myconfig);
 
1991   $table = $table eq "customer" ? "customer" : "vendor";
 
1993   my $query = qq|SELECT count(*) FROM $table|;
 
1994   my ($count) = selectrow_query($self, $dbh, $query);
 
1996   # build selection list
 
1997   if ($count < $myconfig->{vclimit}) {
 
1998     $query = qq|SELECT id, name, salesman_id
 
1999                 FROM $table WHERE NOT obsolete
 
2001     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
 
2005   $self->get_employee($dbh);
 
2007   # setup sales contacts
 
2008   $query = qq|SELECT e.id, e.name
 
2010               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
 
2011   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
 
2014   push(@{ $self->{all_employees} },
 
2015        { id   => $self->{employee_id},
 
2016          name => $self->{employee} });
 
2018   # sort the whole thing
 
2019   @{ $self->{all_employees} } =
 
2020     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
 
2022   if ($module eq 'AR') {
 
2024     # prepare query for departments
 
2025     $query = qq|SELECT id, description
 
2028                 ORDER BY description|;
 
2031     $query = qq|SELECT id, description
 
2033                 ORDER BY description|;
 
2036   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2039   $query = qq|SELECT id, description
 
2043   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2046   $query = qq|SELECT printer_description, id
 
2048               ORDER BY printer_description|;
 
2050   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2053   $query = qq|SELECT id, description
 
2057   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
2059   $main::lxdebug->leave_sub();
 
2062 sub language_payment {
 
2063   $main::lxdebug->enter_sub();
 
2065   my ($self, $myconfig) = @_;
 
2067   my $dbh = $self->get_standard_dbh($myconfig);
 
2069   my $query = qq|SELECT id, description
 
2073   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2076   $query = qq|SELECT printer_description, id
 
2078               ORDER BY printer_description|;
 
2080   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2083   $query = qq|SELECT id, description
 
2087   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
2089   # get buchungsgruppen
 
2090   $query = qq|SELECT id, description
 
2091               FROM buchungsgruppen|;
 
2093   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
 
2095   $main::lxdebug->leave_sub();
 
2098 # this is only used for reports
 
2099 sub all_departments {
 
2100   $main::lxdebug->enter_sub();
 
2102   my ($self, $myconfig, $table) = @_;
 
2104   my $dbh = $self->get_standard_dbh($myconfig);
 
2107   if ($table eq 'customer') {
 
2108     $where = "WHERE role = 'P' ";
 
2111   my $query = qq|SELECT id, description
 
2114                  ORDER BY description|;
 
2115   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2117   delete($self->{all_departments}) unless (@{ $self->{all_departments} });
 
2119   $main::lxdebug->leave_sub();
 
2123   $main::lxdebug->enter_sub();
 
2125   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
 
2128   if ($table eq "customer") {
 
2137   $self->all_vc($myconfig, $table, $module);
 
2139   # get last customers or vendors
 
2140   my ($query, $sth, $ref);
 
2142   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
 
2147     my $transdate = "current_date";
 
2148     if ($self->{transdate}) {
 
2149       $transdate = $dbh->quote($self->{transdate});
 
2152     # now get the account numbers
 
2153     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
 
2154                 FROM chart c, taxkeys tk
 
2155                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
 
2156                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
 
2159     $sth = $dbh->prepare($query);
 
2161     do_statement($self, $sth, $query, '%' . $module . '%');
 
2163     $self->{accounts} = "";
 
2164     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
2166       foreach my $key (split(/:/, $ref->{link})) {
 
2167         if ($key =~ /$module/) {
 
2169           # cross reference for keys
 
2170           $xkeyref{ $ref->{accno} } = $key;
 
2172           push @{ $self->{"${module}_links"}{$key} },
 
2173             { accno       => $ref->{accno},
 
2174               description => $ref->{description},
 
2175               taxkey      => $ref->{taxkey_id},
 
2176               tax_id      => $ref->{tax_id} };
 
2178           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2184   # get taxkeys and description
 
2185   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
 
2186   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
 
2188   if (($module eq "AP") || ($module eq "AR")) {
 
2189     # get tax rates and description
 
2190     $query = qq|SELECT * FROM tax|;
 
2191     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
 
2197            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
 
2198            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
 
2199            a.intnotes, a.department_id, a.amount AS oldinvtotal,
 
2200            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
 
2202            d.description AS department,
 
2205          JOIN $table c ON (a.${table}_id = c.id)
 
2206          LEFT JOIN employee e ON (e.id = a.employee_id)
 
2207          LEFT JOIN department d ON (d.id = a.department_id)
 
2209     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
 
2211     foreach $key (keys %$ref) {
 
2212       $self->{$key} = $ref->{$key};
 
2215     my $transdate = "current_date";
 
2216     if ($self->{transdate}) {
 
2217       $transdate = $dbh->quote($self->{transdate});
 
2220     # now get the account numbers
 
2221     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
 
2223                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
 
2225                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
 
2226                     OR c.link LIKE '%_tax%')
 
2229     $sth = $dbh->prepare($query);
 
2230     do_statement($self, $sth, $query, "%$module%");
 
2232     $self->{accounts} = "";
 
2233     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
2235       foreach my $key (split(/:/, $ref->{link})) {
 
2236         if ($key =~ /$module/) {
 
2238           # cross reference for keys
 
2239           $xkeyref{ $ref->{accno} } = $key;
 
2241           push @{ $self->{"${module}_links"}{$key} },
 
2242             { accno       => $ref->{accno},
 
2243               description => $ref->{description},
 
2244               taxkey      => $ref->{taxkey_id},
 
2245               tax_id      => $ref->{tax_id} };
 
2247           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2253     # get amounts from individual entries
 
2256            c.accno, c.description,
 
2257            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
 
2261          LEFT JOIN chart c ON (c.id = a.chart_id)
 
2262          LEFT JOIN project p ON (p.id = a.project_id)
 
2263          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
 
2264                                     WHERE (tk.taxkey_id=a.taxkey) AND
 
2265                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
 
2266                                         THEN tk.chart_id = a.chart_id
 
2269                                        OR (c.link='%tax%')) AND
 
2270                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
 
2271          WHERE a.trans_id = ?
 
2272          AND a.fx_transaction = '0'
 
2273          ORDER BY a.oid, a.transdate|;
 
2274     $sth = $dbh->prepare($query);
 
2275     do_statement($self, $sth, $query, $self->{id});
 
2277     # get exchangerate for currency
 
2278     $self->{exchangerate} =
 
2279       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2282     # store amounts in {acc_trans}{$key} for multiple accounts
 
2283     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
2284       $ref->{exchangerate} =
 
2285         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
 
2286       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
 
2289       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
 
2290         $ref->{amount} *= -1;
 
2292       $ref->{index} = $index;
 
2294       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
 
2300            d.curr AS currencies, d.closedto, d.revtrans,
 
2301            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2302            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
2304     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2305     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2312             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
 
2313             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2314             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
2316     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2317     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2319     if ($self->{"$self->{vc}_id"}) {
 
2321       # only setup currency
 
2322       ($self->{currency}) = split(/:/, $self->{currencies});
 
2326       $self->lastname_used($dbh, $myconfig, $table, $module);
 
2328       # get exchangerate for currency
 
2329       $self->{exchangerate} =
 
2330         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2336   $main::lxdebug->leave_sub();
 
2340   $main::lxdebug->enter_sub();
 
2342   my ($self, $dbh, $myconfig, $table, $module) = @_;
 
2344   my $arap  = ($table eq 'customer') ? "ar" : "ap";
 
2345   $table = $table eq "customer" ? "customer" : "vendor";
 
2346   my $where = "1 = 1";
 
2348   if ($self->{type} =~ /_order/) {
 
2350     $where = "quotation = '0'";
 
2352   if ($self->{type} =~ /_quotation/) {
 
2354     $where = "quotation = '1'";
 
2357   my $query = qq|SELECT MAX(id) FROM $arap
 
2358                  WHERE $where AND ${table}_id > 0|;
 
2359   my ($trans_id) = selectrow_query($self, $dbh, $query);
 
2364          a.curr, a.${table}_id, a.department_id,
 
2365          d.description AS department,
 
2366          ct.name, current_date + ct.terms AS duedate
 
2368        LEFT JOIN $table ct ON (a.${table}_id = ct.id)
 
2369        LEFT JOIN department d ON (a.department_id = d.id)
 
2371   ($self->{currency},   $self->{"${table}_id"}, $self->{department_id},
 
2372    $self->{department}, $self->{$table},        $self->{duedate})
 
2373     = selectrow_query($self, $dbh, $query, $trans_id);
 
2375   $main::lxdebug->leave_sub();
 
2379   $main::lxdebug->enter_sub();
 
2381   my ($self, $myconfig, $thisdate, $days) = @_;
 
2383   my $dbh = $self->get_standard_dbh($myconfig);
 
2388     my $dateformat = $myconfig->{dateformat};
 
2389     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
 
2390     $thisdate = $dbh->quote($thisdate);
 
2391     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
 
2393     $query = qq|SELECT current_date AS thisdate|;
 
2396   ($thisdate) = selectrow_query($self, $dbh, $query);
 
2398   $main::lxdebug->leave_sub();
 
2404   $main::lxdebug->enter_sub();
 
2406   my ($self, $string) = @_;
 
2408   if ($string !~ /%/) {
 
2409     $string = "%$string%";
 
2412   $string =~ s/\'/\'\'/g;
 
2414   $main::lxdebug->leave_sub();
 
2420   $main::lxdebug->enter_sub();
 
2422   my ($self, $flds, $new, $count, $numrows) = @_;
 
2426   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } }
 
2432   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
 
2434     $j = $item->{ndx} - 1;
 
2435     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
 
2439   for $i ($count + 1 .. $numrows) {
 
2440     map { delete $self->{"${_}_$i"} } @{$flds};
 
2443   $main::lxdebug->leave_sub();
 
2447   $main::lxdebug->enter_sub();
 
2449   my ($self, $myconfig) = @_;
 
2453   my $dbh = $self->dbconnect_noauto($myconfig);
 
2455   my $query = qq|DELETE FROM status
 
2456                  WHERE (formname = ?) AND (trans_id = ?)|;
 
2457   my $sth = prepare_query($self, $dbh, $query);
 
2459   if ($self->{formname} =~ /(check|receipt)/) {
 
2460     for $i (1 .. $self->{rowcount}) {
 
2461       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
 
2464     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
 
2468   my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
 
2469   my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
 
2471   my %queued = split / /, $self->{queued};
 
2474   if ($self->{formname} =~ /(check|receipt)/) {
 
2476     # this is a check or receipt, add one entry for each lineitem
 
2477     my ($accno) = split /--/, $self->{account};
 
2478     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
 
2479                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
 
2480     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
 
2481     $sth = prepare_query($self, $dbh, $query);
 
2483     for $i (1 .. $self->{rowcount}) {
 
2484       if ($self->{"checked_$i"}) {
 
2485         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
 
2491     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
2492                 VALUES (?, ?, ?, ?, ?)|;
 
2493     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
 
2494              $queued{$self->{formname}}, $self->{formname});
 
2500   $main::lxdebug->leave_sub();
 
2504   $main::lxdebug->enter_sub();
 
2506   my ($self, $dbh) = @_;
 
2508   my ($query, $printed, $emailed);
 
2510   my $formnames  = $self->{printed};
 
2511   my $emailforms = $self->{emailed};
 
2513   my $query = qq|DELETE FROM status
 
2514                  WHERE (formname = ?) AND (trans_id = ?)|;
 
2515   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
 
2517   # this only applies to the forms
 
2518   # checks and receipts are posted when printed or queued
 
2520   if ($self->{queued}) {
 
2521     my %queued = split / /, $self->{queued};
 
2523     foreach my $formname (keys %queued) {
 
2524       $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
 
2525       $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
 
2527       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
2528                   VALUES (?, ?, ?, ?, ?)|;
 
2529       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
 
2531       $formnames  =~ s/$self->{formname}//;
 
2532       $emailforms =~ s/$self->{formname}//;
 
2537   # save printed, emailed info
 
2538   $formnames  =~ s/^ +//g;
 
2539   $emailforms =~ s/^ +//g;
 
2542   map { $status{$_}{printed} = 1 } split / +/, $formnames;
 
2543   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
 
2545   foreach my $formname (keys %status) {
 
2546     $printed = ($formnames  =~ /$self->{formname}/) ? "1" : "0";
 
2547     $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
 
2549     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
 
2550                 VALUES (?, ?, ?, ?)|;
 
2551     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
 
2554   $main::lxdebug->leave_sub();
 
2558 # $main::locale->text('SAVED')
 
2559 # $main::locale->text('DELETED')
 
2560 # $main::locale->text('ADDED')
 
2561 # $main::locale->text('PAYMENT POSTED')
 
2562 # $main::locale->text('POSTED')
 
2563 # $main::locale->text('POSTED AS NEW')
 
2564 # $main::locale->text('ELSE')
 
2565 # $main::locale->text('SAVED FOR DUNNING')
 
2566 # $main::locale->text('DUNNING STARTED')
 
2567 # $main::locale->text('PRINTED')
 
2568 # $main::locale->text('MAILED')
 
2569 # $main::locale->text('SCREENED')
 
2570 # $main::locale->text('CANCELED')
 
2571 # $main::locale->text('invoice')
 
2572 # $main::locale->text('proforma')
 
2573 # $main::locale->text('sales_order')
 
2574 # $main::locale->text('packing_list')
 
2575 # $main::locale->text('pick_list')
 
2576 # $main::locale->text('purchase_order')
 
2577 # $main::locale->text('bin_list')
 
2578 # $main::locale->text('sales_quotation')
 
2579 # $main::locale->text('request_quotation')
 
2582   $main::lxdebug->enter_sub();
 
2587   if(!exists $self->{employee_id}) {
 
2588     &get_employee($self, $dbh);
 
2592    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
 
2593    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
 
2594   my @values = (conv_i($self->{id}), $self->{login},
 
2595                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
 
2596   do_query($self, $dbh, $query, @values);
 
2598   $main::lxdebug->leave_sub();
 
2602   $main::lxdebug->enter_sub();
 
2604   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
 
2605   my ($orderBy, $desc) = split(/\-\-/, $order);
 
2606   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
 
2609   if ($trans_id ne "") {
 
2611       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 | .
 
2612       qq|FROM history_erp h | .
 
2613       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
 
2614       qq|WHERE trans_id = | . $trans_id
 
2615       . $restriction . qq| |
 
2618     my $sth = $dbh->prepare($query) || $self->dberror($query);
 
2620     $sth->execute() || $self->dberror("$query");
 
2622     while(my $hash_ref = $sth->fetchrow_hashref()) {
 
2623       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
 
2624       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
 
2625       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
 
2626       $tempArray[$i++] = $hash_ref;
 
2628     $main::lxdebug->leave_sub() and return \@tempArray 
 
2629       if ($i > 0 && $tempArray[0] ne "");
 
2631   $main::lxdebug->leave_sub();
 
2635 sub update_defaults {
 
2636   $main::lxdebug->enter_sub();
 
2638   my ($self, $myconfig, $fld, $provided_dbh) = @_;
 
2641   if ($provided_dbh) {
 
2642     $dbh = $provided_dbh;
 
2644     $dbh = $self->dbconnect_noauto($myconfig);
 
2646   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
 
2647   my $sth   = $dbh->prepare($query);
 
2649   $sth->execute || $self->dberror($query);
 
2650   my ($var) = $sth->fetchrow_array;
 
2653   $var =~ s/\d+$/ sprintf '%0*d', length($&), $&+1 /e;
 
2656   $query = qq|UPDATE defaults SET $fld = ?|;
 
2657   do_query($self, $dbh, $query, $var);
 
2659   if (!$provided_dbh) {
 
2664   $main::lxdebug->leave_sub();
 
2669 sub update_business {
 
2670   $main::lxdebug->enter_sub();
 
2672   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
 
2675   if ($provided_dbh) {
 
2676     $dbh = $provided_dbh;
 
2678     $dbh = $self->dbconnect_noauto($myconfig);
 
2681     qq|SELECT customernumberinit FROM business
 
2682        WHERE id = ? FOR UPDATE|;
 
2683   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
 
2685   $var =~ s/\d+$/ sprintf '%0*d', length($&), $&+1 /e;
 
2687   $query = qq|UPDATE business
 
2688               SET customernumberinit = ?
 
2690   do_query($self, $dbh, $query, $var, $business_id);
 
2692   if (!$provided_dbh) {
 
2697   $main::lxdebug->leave_sub();
 
2702 sub get_partsgroup {
 
2703   $main::lxdebug->enter_sub();
 
2705   my ($self, $myconfig, $p) = @_;
 
2707   my $dbh = $self->get_standard_dbh($myconfig);
 
2709   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
 
2711                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
 
2714   if ($p->{searchitems} eq 'part') {
 
2715     $query .= qq|WHERE p.inventory_accno_id > 0|;
 
2717   if ($p->{searchitems} eq 'service') {
 
2718     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
 
2720   if ($p->{searchitems} eq 'assembly') {
 
2721     $query .= qq|WHERE p.assembly = '1'|;
 
2723   if ($p->{searchitems} eq 'labor') {
 
2724     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
 
2727   $query .= qq|ORDER BY partsgroup|;
 
2730     $query = qq|SELECT id, partsgroup FROM partsgroup
 
2731                 ORDER BY partsgroup|;
 
2734   if ($p->{language_code}) {
 
2735     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
 
2736                   t.description AS translation
 
2738                 JOIN parts p ON (p.partsgroup_id = pg.id)
 
2739                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
 
2740                 ORDER BY translation|;
 
2741     @values = ($p->{language_code});
 
2744   $self->{all_partsgroup} = selectall_hashref_query($self, $dbh, $query, @values);
 
2746   $main::lxdebug->leave_sub();
 
2749 sub get_pricegroup {
 
2750   $main::lxdebug->enter_sub();
 
2752   my ($self, $myconfig, $p) = @_;
 
2754   my $dbh = $self->get_standard_dbh($myconfig);
 
2756   my $query = qq|SELECT p.id, p.pricegroup
 
2759   $query .= qq| ORDER BY pricegroup|;
 
2762     $query = qq|SELECT id, pricegroup FROM pricegroup
 
2763                 ORDER BY pricegroup|;
 
2766   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
 
2768   $main::lxdebug->leave_sub();
 
2772 # usage $form->all_years($myconfig, [$dbh])
 
2773 # return list of all years where bookings found
 
2776   $main::lxdebug->enter_sub();
 
2778   my ($self, $myconfig, $dbh) = @_;
 
2780   $dbh ||= $self->get_standard_dbh($myconfig);
 
2783   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
 
2784                    (SELECT MAX(transdate) FROM acc_trans)|;
 
2785   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
 
2787   if ($myconfig->{dateformat} =~ /^yy/) {
 
2788     ($startdate) = split /\W/, $startdate;
 
2789     ($enddate) = split /\W/, $enddate;
 
2791     (@_) = split /\W/, $startdate;
 
2793     (@_) = split /\W/, $enddate;
 
2798   $startdate = substr($startdate,0,4);
 
2799   $enddate = substr($enddate,0,4);
 
2801   while ($enddate >= $startdate) {
 
2802     push @all_years, $enddate--;
 
2807   $main::lxdebug->leave_sub();