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 #======================================================================
 
  53   $main::lxdebug->enter_sub(2);
 
  57   my @pairs = split(/&/, $input);
 
  60     my ($name, $value) = split(/=/, $_, 2);
 
  61     $in{$name} = unescape(undef, $value);
 
  64   $main::lxdebug->leave_sub(2);
 
  69 sub _request_to_hash {
 
  70   $main::lxdebug->enter_sub(2);
 
  74   if (!$ENV{'CONTENT_TYPE'}
 
  75       || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
 
  76     $main::lxdebug->leave_sub(2);
 
  77     return _input_to_hash($input);
 
  80   my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr);
 
  83   my $boundary = '--' . $1;
 
  85   foreach my $line (split m/\n/, $input) {
 
  86     last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
 
  88     if (($line eq $boundary) || ($line eq "$boundary\r")) {
 
  89       $params{$name} =~ s|\r?\n$|| if $name;
 
  91       undef $name, $filename;
 
  94       $content_type   = "text/plain";
 
 101     next unless $boundary_found;
 
 103     if (!$headers_done) {
 
 104       $line =~ s/[\r\n]*$//;
 
 111       if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
 
 112         if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
 
 114           substr $line, $-[0], $+[0] - $-[0], "";
 
 117         if ($line =~ m|name\s*=\s*"(.*?)"|i) {
 
 119           substr $line, $-[0], $+[0] - $-[0], "";
 
 123         $params{FILENAME} = $filename if ($filename);
 
 128       if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
 
 137     $params{$name} .= "${line}\n";
 
 140   $params{$name} =~ s|\r?\n$|| if $name;
 
 142   $main::lxdebug->leave_sub(2);
 
 147   $main::lxdebug->enter_sub();
 
 153   if ($LXDebug::watch_form) {
 
 154     require SL::Watchdog;
 
 155     tie %{ $self }, 'SL::Watchdog';
 
 158   read(STDIN, $_, $ENV{CONTENT_LENGTH});
 
 160   if ($ENV{QUERY_STRING}) {
 
 161     $_ = $ENV{QUERY_STRING};
 
 168   my %parameters = _request_to_hash($_);
 
 169   map({ $self->{$_} = $parameters{$_}; } keys(%parameters));
 
 171   $self->{action} = lc $self->{action};
 
 172   $self->{action} =~ s/( |-|,|\#)/_/g;
 
 174   $self->{version}   = "2.4.2";
 
 176   $main::lxdebug->leave_sub();
 
 182   $main::lxdebug->enter_sub();
 
 188   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
 
 190   $main::lxdebug->leave_sub();
 
 194   $main::lxdebug->enter_sub(2);
 
 196   my ($self, $str) = @_;
 
 198   $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
 
 200   $main::lxdebug->leave_sub(2);
 
 206   $main::lxdebug->enter_sub(2);
 
 208   my ($self, $str) = @_;
 
 213   $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
 
 215   $main::lxdebug->leave_sub(2);
 
 221   my ($self, $str) = @_;
 
 223   if ($str && !ref($str)) {
 
 224     $str =~ s/\"/"/g;
 
 232   my ($self, $str) = @_;
 
 234   if ($str && !ref($str)) {
 
 235     $str =~ s/"/\"/g;
 
 243   $main::lxdebug->enter_sub(2);
 
 245   my ($self, $str) = @_;
 
 248     ('order' => ['"', '<', '>'],
 
 254   map({ $str =~ s/$_/$replace{$_}/g; } @{ $replace{"order"} });
 
 256   $main::lxdebug->leave_sub(2);
 
 265     map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
 
 267     for (sort keys %$self) {
 
 268       next if (($_ eq "header") || (ref($self->{$_}) ne ""));
 
 269       print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
 
 276   $main::lxdebug->enter_sub();
 
 278   $main::lxdebug->show_backtrace();
 
 280   my ($self, $msg) = @_;
 
 281   if ($ENV{HTTP_USER_AGENT}) {
 
 283     $self->show_generic_error($msg);
 
 287     if ($self->{error_function}) {
 
 288       &{ $self->{error_function} }($msg);
 
 294   $main::lxdebug->leave_sub();
 
 298   $main::lxdebug->enter_sub();
 
 300   my ($self, $msg) = @_;
 
 302   if ($ENV{HTTP_USER_AGENT}) {
 
 305     if (!$self->{header}) {
 
 318     if ($self->{info_function}) {
 
 319       &{ $self->{info_function} }($msg);
 
 325   $main::lxdebug->leave_sub();
 
 329   $main::lxdebug->enter_sub();
 
 331   my ($self, $str, $cols, $maxrows) = @_;
 
 335   map { $rows += int(((length) - 2) / $cols) + 1 } split /\r/, $str;
 
 337   $maxrows = $rows unless defined $maxrows;
 
 339   $main::lxdebug->leave_sub();
 
 341   return ($rows > $maxrows) ? $maxrows : $rows;
 
 345   $main::lxdebug->enter_sub();
 
 347   my ($self, $msg) = @_;
 
 349   $self->error("$msg\n" . $DBI::errstr);
 
 351   $main::lxdebug->leave_sub();
 
 355   $main::lxdebug->enter_sub();
 
 357   my ($self, $name, $msg) = @_;
 
 359   if ($self->{$name} =~ /^\s*$/) {
 
 362   $main::lxdebug->leave_sub();
 
 366   $main::lxdebug->enter_sub();
 
 368   my ($self, $extra_code) = @_;
 
 370   if ($self->{header}) {
 
 371     $main::lxdebug->leave_sub();
 
 375   my ($stylesheet, $favicon);
 
 377   if ($ENV{HTTP_USER_AGENT}) {
 
 379     if ($self->{stylesheet} && (-f "css/$self->{stylesheet}")) {
 
 381         qq|<LINK REL="stylesheet" HREF="css/$self->{stylesheet}" TYPE="text/css" TITLE="Lx-Office stylesheet">
 
 385     $self->{favicon}    = "favicon.ico" unless $self->{favicon};
 
 387     if ($self->{favicon} && (-f "$self->{favicon}")) {
 
 389         qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
 
 393     my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
 395     if ($self->{landscape}) {
 
 396       $pagelayout = qq|<style type="text/css">
 
 397                         \@page { size:landscape; }
 
 401     my $fokus = qq|  document.$self->{fokus}.focus();| if ($self->{"fokus"});
 
 405     if ($self->{jsscript} == 1) {
 
 408         <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
 
 409         <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
 
 410         <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
 
 411         <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
 
 418       ? "$self->{title} - $self->{titlebar}"
 
 421     foreach $item (@ { $self->{AJAX} }) {
 
 422       $ajax .= $item->show_javascript();
 
 424     print qq|Content-Type: text/html; charset=${db_charset};
 
 428   <title>$self->{titlebar}</title>
 
 432   <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
 
 436   <script type="text/javascript">
 
 444   <meta name="robots" content="noindex,nofollow" />
 
 445   <script type="text/javascript" src="js/highlight_input.js"></script>
 
 446   <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
 
 448   <script type="text/javascript" src="js/tabcontent.js">
 
 450   /***********************************************
 
 451   * Tab Content script- Dynamic Drive DHTML code library (www.dynamicdrive.com)
 
 452   * This notice MUST stay intact for legal use
 
 453   * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
 
 454   ***********************************************/
 
 465   $main::lxdebug->leave_sub();
 
 468 sub parse_html_template {
 
 469   $main::lxdebug->enter_sub();
 
 471   my ($self, $file, $additional_params) = @_;
 
 474   if (!defined(%main::myconfig) || !defined($main::myconfig{"countrycode"})) {
 
 475     $language = $main::language;
 
 477     $language = $main::myconfig{"countrycode"};
 
 479   $language = "de" unless ($language);
 
 481   if (-f "templates/webpages/${file}_${language}.html") {
 
 482     if ((-f ".developer") &&
 
 483         (-f "templates/webpages/${file}_master.html") &&
 
 484         ((stat("templates/webpages/${file}_master.html"))[9] >
 
 485          (stat("templates/webpages/${file}_${language}.html"))[9])) {
 
 486       my $info = "Developer information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
 
 487         "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 488       print(qq|<pre>$info</pre>|);
 
 492     $file = "templates/webpages/${file}_${language}.html";
 
 493   } elsif (-f "templates/webpages/${file}.html") {
 
 494     $file = "templates/webpages/${file}.html";
 
 496     my $info = "Web page template '${file}' not found.\n" .
 
 497       "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 498     print(qq|<pre>$info</pre>|);
 
 502   my $template = HTML::Template->new("filename" => $file,
 
 503                                      "die_on_bad_params" => 0,
 
 505                                      "case_sensitive" => 1,
 
 506                                      "loop_context_vars" => 1,
 
 509   $additional_params = {} unless ($additional_params);
 
 510   if ($self->{"DEBUG"}) {
 
 511     $additional_params->{"DEBUG"} = $self->{"DEBUG"};
 
 514   if ($additional_params->{"DEBUG"}) {
 
 515     $additional_params->{"DEBUG"} =
 
 516       "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
 
 519   if (%main::myconfig) {
 
 520     map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
 
 521     my $jsc_dateformat = $main::myconfig{"dateformat"};
 
 522     $jsc_dateformat =~ s/d+/\%d/gi;
 
 523     $jsc_dateformat =~ s/m+/\%m/gi;
 
 524     $jsc_dateformat =~ s/y+/\%Y/gi;
 
 525     $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
 
 528   $additional_params->{"conf_webdav"}                 = $main::webdav;
 
 529   $additional_params->{"conf_lizenzen"}               = $main::lizenzen;
 
 530   $additional_params->{"conf_latex_templates"}        = $main::latex;
 
 531   $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
 
 533   my @additional_param_names = keys(%{$additional_params});
 
 534   foreach my $key ($template->param()) {
 
 535     my $param = $self->{$key};
 
 536     $param = $additional_params->{$key} if (grep(/^${key}$/, @additional_param_names));
 
 537     $param = [] if (($template->query("name" => $key) eq "LOOP") && (ref($param) ne "ARRAY"));
 
 538     $template->param($key => $param);
 
 541   my $output = $template->output();
 
 543   $main::lxdebug->leave_sub();
 
 548 sub show_generic_error {
 
 549   my ($self, $error, $title, $action) = @_;
 
 552   $add_params->{"title"} = $title if ($title);
 
 553   $self->{"label_error"} = $error;
 
 557     map({ delete($self->{$_}); } qw(action));
 
 558     map({ push(@vars, { "name" => $_, "value" => $self->{$_} })
 
 559             if (!ref($self->{$_})); }
 
 561     $add_params->{"SHOW_BUTTON"} = 1;
 
 562     $add_params->{"BUTTON_LABEL"} = $action;
 
 564   $add_params->{"VARIABLES"} = \@vars;
 
 567   print($self->parse_html_template("generic/error", $add_params));
 
 569   die("Error: $error\n");
 
 572 sub show_generic_information {
 
 573   my ($self, $error, $title) = @_;
 
 576   $add_params->{"title"} = $title if ($title);
 
 577   $self->{"label_information"} = $error;
 
 580   print($self->parse_html_template("generic/information", $add_params));
 
 582   die("Information: $error\n");
 
 585 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
 
 586 # changed it to accept an arbitrary number of triggers - sschoeling
 
 588   $main::lxdebug->enter_sub();
 
 591   my $myconfig = shift;
 
 594   # set dateform for jsscript
 
 597     "dd.mm.yy" => "%d.%m.%Y",
 
 598     "dd-mm-yy" => "%d-%m-%Y",
 
 599     "dd/mm/yy" => "%d/%m/%Y",
 
 600     "mm/dd/yy" => "%m/%d/%Y",
 
 601     "mm-dd-yy" => "%m-%d-%Y",
 
 602     "yyyy-mm-dd" => "%Y-%m-%d",
 
 605   my $ifFormat = defined($dateformats{$myconfig{"dateformat"}}) ?
 
 606     $dateformats{$myconfig{"dateformat"}} : "%d.%m.%Y";
 
 613       inputField : "| . (shift) . qq|",
 
 614       ifFormat :"$ifFormat",
 
 615       align : "| .  (shift) . qq|",
 
 616       button : "| . (shift) . qq|"
 
 622        <script type="text/javascript">
 
 623        <!--| . join("", @triggers) . qq|//-->
 
 627   $main::lxdebug->leave_sub();
 
 630 }    #end sub write_trigger
 
 633   $main::lxdebug->enter_sub();
 
 635   my ($self, $msg) = @_;
 
 637   if ($self->{callback}) {
 
 639     ($script, $argv) = split(/\?/, $self->{callback});
 
 640     exec("perl", "$script", $argv);
 
 648   $main::lxdebug->leave_sub();
 
 651 # sort of columns removed - empty sub
 
 653   $main::lxdebug->enter_sub();
 
 655   my ($self, @columns) = @_;
 
 657   $main::lxdebug->leave_sub();
 
 663   $main::lxdebug->enter_sub(2);
 
 665   my ($self, $myconfig, $amount, $places, $dash) = @_;
 
 670   my $neg = ($amount =~ s/-//);
 
 672   if (defined($places) && ($places ne '')) {
 
 677       my ($actual_places) = ($amount =~ /\.(\d+)/);
 
 678       $actual_places = length($actual_places);
 
 679       $places = $actual_places > $places ? $actual_places : $places;
 
 682     $amount = $self->round_amount($amount, $places);
 
 685   my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
 
 686   my @p = split(/\./, $amount); # split amount at decimal point
 
 688   $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
 
 691   $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
 
 694     ($dash =~ /-/)    ? ($neg ? "($amount)"  : "$amount" )    :
 
 695     ($dash =~ /DRCR/) ? ($neg ? "$amount DR" : "$amount CR" ) :
 
 696                         ($neg ? "-$amount"   : "$amount" )    ;
 
 700   $main::lxdebug->leave_sub(2);
 
 705   $main::lxdebug->enter_sub(2);
 
 707   my ($self, $myconfig, $amount) = @_;
 
 709   if (   ($myconfig->{numberformat} eq '1.000,00')
 
 710       || ($myconfig->{numberformat} eq '1000,00')) {
 
 715   if ($myconfig->{numberformat} eq "1'000.00") {
 
 721   $main::lxdebug->leave_sub(2);
 
 723   return ($amount * 1);
 
 727   $main::lxdebug->enter_sub(2);
 
 729   my ($self, $amount, $places) = @_;
 
 732   # Rounding like "Kaufmannsrunden"
 
 733   # Descr. http://de.wikipedia.org/wiki/Rundung
 
 735   # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
 
 738   $amount = $amount * (10**($places));
 
 739   $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
 
 741   $main::lxdebug->leave_sub(2);
 
 743   return $round_amount;
 
 748   $main::lxdebug->enter_sub();
 
 750   my ($self, $myconfig, $userspath) = @_;
 
 751   my ($template, $out);
 
 755   $self->{"cwd"} = getcwd();
 
 756   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
 
 758   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
 
 759     $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
 760   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
 
 761     $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
 
 762     $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
 763   } elsif (($self->{"format"} =~ /html/i) ||
 
 764            (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
 
 765     $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
 766   } elsif (($self->{"format"} =~ /xml/i) ||
 
 767              (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
 
 768     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
 769   } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
 
 770     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
 771   } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
 
 772     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
 773   } elsif ( defined $self->{'format'}) {
 
 774     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
 
 775   } elsif ( $self->{'format'} eq '' ) {
 
 776     $self->error("No Outputformat given: $self->{'format'}");
 
 777   } else { #Catch the rest
 
 778     $self->error("Outputformat not defined: $self->{'format'}");
 
 781   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
 
 782   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
 
 784   map({ $self->{"employee_${_}"} = $myconfig->{$_}; }
 
 785       qw(email tel fax name signature company address businessnumber
 
 786          co_ustid taxnumber duns));
 
 787   map({ $self->{"employee_${_}"} =~ s/\\n/\n/g; }
 
 788       qw(company address signature));
 
 789   map({ $self->{$_} =~ s/\\n/\n/g; } qw(company address signature));
 
 791   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
 
 793   # OUT is used for the media, screen, printer, email
 
 794   # for postscript we store a copy in a temporary file
 
 796   my $prepend_userspath;
 
 798   if (!$self->{tmpfile}) {
 
 799     $self->{tmpfile}   = "${fileid}.$self->{IN}";
 
 800     $prepend_userspath = 1;
 
 803   $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
 
 805   $self->{tmpfile} =~ s|.*/||;
 
 806   $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
 
 807   $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
 
 809   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
 811     $self->{OUT} = ">$self->{tmpfile}";
 
 815     open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
 
 817     open(OUT, ">-") or $self->error("STDOUT : $!");
 
 821   if (!$template->parse(*OUT)) {
 
 823     $self->error("$self->{IN} : " . $template->get_error());
 
 828   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
 830     if ($self->{media} eq 'email') {
 
 832       my $mail = new Mailer;
 
 834       map { $mail->{$_} = $self->{$_} }
 
 835         qw(cc bcc subject message version format);
 
 836       $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
 837       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
 
 838       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
 
 839       $mail->{fileid} = "$fileid.";
 
 840       $myconfig->{signature} =~ s/\\r\\n/\\n/g;
 
 842       # if we send html or plain text inline
 
 843       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
 
 844         $mail->{contenttype} = "text/html";
 
 846         $mail->{message}       =~ s/\r\n/<br>\n/g;
 
 847         $myconfig->{signature} =~ s/\\n/<br>\n/g;
 
 848         $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
 
 850         open(IN, $self->{tmpfile})
 
 851           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
 853           $mail->{message} .= $_;
 
 860         if (!$self->{"do_not_attach"}) {
 
 861           @{ $mail->{attachments} } =
 
 862             ({ "filename" => $self->{"tmpfile"},
 
 863                "name" => $self->{"attachment_filename"} ?
 
 864                  $self->{"attachment_filename"} : $self->{"tmpfile"} });
 
 867         $mail->{message}       =~ s/\r\n/\n/g;
 
 868         $myconfig->{signature} =~ s/\\n/\n/g;
 
 869         $mail->{message} .= "\n-- \n$myconfig->{signature}";
 
 873       my $err = $mail->send();
 
 874       $self->error($self->cleanup . "$err") if ($err);
 
 880       my $numbytes = (-s $self->{tmpfile});
 
 881       open(IN, $self->{tmpfile})
 
 882         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
 884       $self->{copies} = 1 unless $self->{media} eq 'printer';
 
 886       chdir("$self->{cwd}");
 
 887       #print(STDERR "Kopien $self->{copies}\n");
 
 888       #print(STDERR "OUT $self->{OUT}\n");
 
 889       for my $i (1 .. $self->{copies}) {
 
 891           open(OUT, $self->{OUT})
 
 892             or $self->error($self->cleanup . "$self->{OUT} : $!");
 
 894           $self->{attachment_filename} = ($self->{attachment_filename}) 
 
 895                                        ? $self->{attachment_filename}
 
 896                                        : $self->generate_attachment_filename();
 
 899           print qq|Content-Type: | . $template->get_mime_type() . qq|
 
 900 Content-Disposition: attachment; filename="$self->{attachment_filename}"
 
 901 Content-Length: $numbytes
 
 905           open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
 
 925   chdir("$self->{cwd}");
 
 926   $main::lxdebug->leave_sub();
 
 929 sub generate_attachment_filename {
 
 932   my %formname_translations = (
 
 933      bin_list            => $main::locale->text('Bin List'),
 
 934      credit_note         => $main::locale->text('Credit Note'),
 
 935      invoice             => $main::locale->text('Invoice'),
 
 936      packing_list        => $main::locale->text('Packing List'),
 
 937      pick_list           => $main::locale->text('Pick List'),
 
 938      proforma            => $main::locale->text('Proforma Invoice'),
 
 939      purchase_order      => $main::locale->text('Purchase Order'),
 
 940      request_quotation   => $main::locale->text('RFQ'),
 
 941      sales_order         => $main::locale->text('Confirmation'),
 
 942      sales_quotation     => $main::locale->text('Quotation'),
 
 943      storno_invoice      => $main::locale->text('Storno Invoice'),
 
 944      storno_packing_list => $main::locale->text('Storno Packing List'),
 
 947   my $attachment_filename = $formname_translations{$self->{"formname"}};
 
 949       (grep { $self->{"type"} eq $_ } qw(invoice credit_note)) ? "inv"
 
 950     : ($self->{"type"} =~ /_quotation$/)                       ? "quo"
 
 953   if ($attachment_filename && $self->{"${prefix}number"}) {
 
 954     $attachment_filename .= "_" . $self->{"${prefix}number"}
 
 955                             . (  $self->{format} =~ /pdf/i          ? ".pdf"
 
 956                                : $self->{format} =~ /postscript/i   ? ".ps"
 
 957                                : $self->{format} =~ /opendocument/i ? ".odt"
 
 958                                : $self->{format} =~ /html/i         ? ".html"
 
 960     $attachment_filename =~ s/ /_/g;
 
 961     my %umlaute = ( "ä" => "ae", "ö" => "oe", "ü" => "ue", 
 
 962                     "Ä" => "Ae", "Ö" => "Oe", "Ü" => "Ue", "ß" => "ss");
 
 963     map { $attachment_filename =~ s/$_/$umlaute{$_}/g } keys %umlaute;
 
 965     $attachment_filename = "";
 
 968   return $attachment_filename;
 
 972   $main::lxdebug->enter_sub();
 
 976   chdir("$self->{tmpdir}");
 
 979   if (-f "$self->{tmpfile}.err") {
 
 980     open(FH, "$self->{tmpfile}.err");
 
 985   if ($self->{tmpfile}) {
 
 986     $self->{tmpfile} =~ s|.*/||g;
 
 988     $self->{tmpfile} =~ s/\.\w+$//g;
 
 989     my $tmpfile = $self->{tmpfile};
 
 990     unlink(<$tmpfile.*>);
 
 993   chdir("$self->{cwd}");
 
 995   $main::lxdebug->leave_sub();
 
1001   $main::lxdebug->enter_sub();
 
1003   my ($self, $date, $myconfig) = @_;
 
1005   if ($date && $date =~ /\D/) {
 
1007     if ($myconfig->{dateformat} =~ /^yy/) {
 
1008       ($yy, $mm, $dd) = split /\D/, $date;
 
1010     if ($myconfig->{dateformat} =~ /^mm/) {
 
1011       ($mm, $dd, $yy) = split /\D/, $date;
 
1013     if ($myconfig->{dateformat} =~ /^dd/) {
 
1014       ($dd, $mm, $yy) = split /\D/, $date;
 
1019     $yy = ($yy < 70) ? $yy + 2000 : $yy;
 
1020     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
 
1022     $dd = "0$dd" if ($dd < 10);
 
1023     $mm = "0$mm" if ($mm < 10);
 
1025     $date = "$yy$mm$dd";
 
1028   $main::lxdebug->leave_sub();
 
1033 # Database routines used throughout
 
1036   $main::lxdebug->enter_sub(2);
 
1038   my ($self, $myconfig) = @_;
 
1040   # connect to database
 
1042     DBI->connect($myconfig->{dbconnect},
 
1043                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
 
1047   if ($myconfig->{dboptions}) {
 
1048     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1051   $main::lxdebug->leave_sub(2);
 
1056 sub dbconnect_noauto {
 
1057   $main::lxdebug->enter_sub();
 
1059   my ($self, $myconfig) = @_;
 
1061   # connect to database
 
1063     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
 
1064                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
 
1068   if ($myconfig->{dboptions}) {
 
1069     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1072   $main::lxdebug->leave_sub();
 
1077 sub update_balance {
 
1078   $main::lxdebug->enter_sub();
 
1080   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
 
1082   # if we have a value, go do it
 
1085     # retrieve balance from table
 
1086     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
 
1087     my $sth = prepare_execute_query($self, $dbh, $query, @values);
 
1088     my ($balance) = $sth->fetchrow_array;
 
1094     $query = "UPDATE $table SET $field = $balance WHERE $where";
 
1095     do_query($self, $dbh, $query, @values);
 
1097   $main::lxdebug->leave_sub();
 
1100 sub update_exchangerate {
 
1101   $main::lxdebug->enter_sub();
 
1103   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
 
1105   # some sanity check for currency
 
1107     $main::lxdebug->leave_sub();
 
1111   my $query = qq|SELECT e.curr FROM exchangerate e
 
1112                  WHERE e.curr = ? AND e.transdate = ?
 
1114   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
 
1117   if ($buy != 0 && $sell != 0) {
 
1118     $set = "buy = $buy, sell = $sell";
 
1119   } elsif ($buy != 0) {
 
1120     $set = "buy = $buy";
 
1121   } elsif ($sell != 0) {
 
1122     $set = "sell = $sell";
 
1125   if ($sth->fetchrow_array) {
 
1126     $query = qq|UPDATE exchangerate
 
1131     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
 
1132                 VALUES (?, $buy, $sell, ?)|;
 
1135   do_query($self, $dbh, $query, $curr, $transdate);
 
1137   $main::lxdebug->leave_sub();
 
1140 sub save_exchangerate {
 
1141   $main::lxdebug->enter_sub();
 
1143   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
 
1145   my $dbh = $self->dbconnect($myconfig);
 
1147   my ($buy, $sell) = (0, 0);
 
1148   $buy  = $rate if $fld eq 'buy';
 
1149   $sell = $rate if $fld eq 'sell';
 
1151   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
 
1155   $main::lxdebug->leave_sub();
 
1158 sub get_exchangerate {
 
1159   $main::lxdebug->enter_sub();
 
1161   my ($self, $dbh, $curr, $transdate, $fld) = @_;
 
1163   unless ($transdate) {
 
1164     $main::lxdebug->leave_sub();
 
1168   my $query = qq|SELECT e.$fld FROM exchangerate e
 
1169                  WHERE e.curr = ? AND e.transdate = ?|;
 
1170   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
 
1172   if (!$exchangerate) {
 
1176   $main::lxdebug->leave_sub();
 
1178   return $exchangerate;
 
1181 sub check_exchangerate {
 
1182   $main::lxdebug->enter_sub();
 
1184   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
 
1186   unless ($transdate) {
 
1187     $main::lxdebug->leave_sub();
 
1191   my $dbh = $self->dbconnect($myconfig);
 
1193   my $query = qq|SELECT e.$fld FROM exchangerate e
 
1194                  WHERE e.curr = ? AND e.transdate = ?|;
 
1195   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
 
1198   $main::lxdebug->leave_sub();
 
1200   return $exchangerate;
 
1203 sub set_payment_options {
 
1204   $main::lxdebug->enter_sub();
 
1206   my ($self, $myconfig, $transdate) = @_;
 
1208   if ($self->{payment_id}) {
 
1210     my $dbh = $self->dbconnect($myconfig);
 
1213       qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
 
1214       qq|FROM payment_terms p | .
 
1217     ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
 
1218      $self->{payment_terms}) =
 
1219        selectrow_query($self, $dbh, $query, $self->{payment_id});
 
1221     if ($transdate eq "") {
 
1222       if ($self->{invdate}) {
 
1223         $transdate = $self->{invdate};
 
1225         $transdate = $self->{transdate};
 
1230       qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
 
1231       qq|FROM payment_terms|;
 
1232     ($self->{netto_date}, $self->{skonto_date}) =
 
1233       selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
 
1235     my $total = ($self->{invtotal}) ? $self->{invtotal} : $self->{ordtotal};
 
1236     my $skonto_amount = $self->parse_amount($myconfig, $total) *
 
1237       $self->{percent_skonto};
 
1239     $self->{skonto_amount} =
 
1240       $self->format_amount($myconfig, $skonto_amount, 2);
 
1242     if ($self->{"language_id"}) {
 
1244         qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
 
1245         qq|FROM translation_payment_terms t | .
 
1246         qq|LEFT JOIN language l ON t.language_id = l.id | .
 
1247         qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
 
1248       my ($description_long, $output_numberformat, $output_dateformat,
 
1249         $output_longdates) =
 
1250         selectrow_query($self, $dbh, $query,
 
1251                         $self->{"language_id"}, $self->{"payment_id"});
 
1253       $self->{payment_terms} = $description_long if ($description_long);
 
1255       if ($output_dateformat) {
 
1256         foreach my $key (qw(netto_date skonto_date)) {
 
1258             $main::locale->reformat_date($myconfig, $self->{$key},
 
1264       if ($output_numberformat &&
 
1265           ($output_numberformat ne $myconfig->{"numberformat"})) {
 
1266         my $saved_numberformat = $myconfig->{"numberformat"};
 
1267         $myconfig->{"numberformat"} = $output_numberformat;
 
1268         $self->{skonto_amount} =
 
1269           $self->format_amount($myconfig, $skonto_amount, 2);
 
1270         $myconfig->{"numberformat"} = $saved_numberformat;
 
1274     $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
 
1275     $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
 
1276     $self->{payment_terms} =~ s/<%skonto_amount%>/$self->{skonto_amount}/g;
 
1277     $self->{payment_terms} =~ s/<%total%>/$self->{total}/g;
 
1278     $self->{payment_terms} =~ s/<%invtotal%>/$self->{invtotal}/g;
 
1279     $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
 
1280     $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
 
1281     $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
 
1282     $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
 
1283     $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
 
1288   $main::lxdebug->leave_sub();
 
1292 sub get_template_language {
 
1293   $main::lxdebug->enter_sub();
 
1295   my ($self, $myconfig) = @_;
 
1297   my $template_code = "";
 
1299   if ($self->{language_id}) {
 
1300     my $dbh = $self->dbconnect($myconfig);
 
1301     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
 
1302     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
 
1306   $main::lxdebug->leave_sub();
 
1308   return $template_code;
 
1311 sub get_printer_code {
 
1312   $main::lxdebug->enter_sub();
 
1314   my ($self, $myconfig) = @_;
 
1316   my $template_code = "";
 
1318   if ($self->{printer_id}) {
 
1319     my $dbh = $self->dbconnect($myconfig);
 
1320     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
 
1321     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
 
1325   $main::lxdebug->leave_sub();
 
1327   return $template_code;
 
1331   $main::lxdebug->enter_sub();
 
1333   my ($self, $myconfig) = @_;
 
1335   my $template_code = "";
 
1337   if ($self->{shipto_id}) {
 
1338     my $dbh = $self->dbconnect($myconfig);
 
1339     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
 
1340     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
 
1341     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
 
1345   $main::lxdebug->leave_sub();
 
1349   $main::lxdebug->enter_sub();
 
1351   my ($self, $dbh, $id, $module) = @_;
 
1355   foreach my $item (qw(name department_1 department_2 street zipcode city country
 
1356                        contact phone fax email)) {
 
1357     if ($self->{"shipto$item"}) {
 
1358       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
 
1360     push(@values, $self->{"shipto${item}"});
 
1363     if ($self->{shipto_id}) {
 
1364       my $query = qq|UPDATE shipto set
 
1366                        shiptodepartment_1 = ?,
 
1367                        shiptodepartment_2 = ?,
 
1376                      WHERE shipto_id = ?|;
 
1377       do_query($self, $dbh, $query, @values, $self->{shipto_id});
 
1379       my $query = qq|SELECT * FROM shipto
 
1380                      WHERE shiptoname = ? AND
 
1381                        shiptodepartment_1 = ? AND
 
1382                        shiptodepartment_2 = ? AND
 
1383                        shiptostreet = ? AND
 
1384                        shiptozipcode = ? AND
 
1386                        shiptocountry = ? AND
 
1387                        shiptocontact = ? AND
 
1391       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values);
 
1394           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
 
1395                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
 
1396                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
 
1397              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
 
1398         do_query($self, $dbh, $query, $id, @values, $module);
 
1403   $main::lxdebug->leave_sub();
 
1407   $main::lxdebug->enter_sub();
 
1409   my ($self, $dbh) = @_;
 
1411   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
 
1412   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
 
1413   $self->{"employee_id"} *= 1;
 
1415   $main::lxdebug->leave_sub();
 
1419   $main::lxdebug->enter_sub();
 
1421   my ($self, $myconfig, $salesman_id) = @_;
 
1423   $main::lxdebug->leave_sub() and return unless $salesman_id;
 
1425   my $dbh = $self->dbconnect($myconfig);
 
1428     selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|,
 
1432     my $user = new User($main::memberfile, $login);
 
1433     map({ $self->{"salesman_$_"} = $user->{$_}; }
 
1434         qw(address businessnumber co_ustid company duns email fax name
 
1436     $self->{salesman_login} = $login;
 
1438     $self->{salesman_name} = $login
 
1439       if ($self->{salesman_name} eq "");
 
1441     map({ $self->{"salesman_$_"} =~ s/\\n/\n/g; } qw(address company));
 
1446   $main::lxdebug->leave_sub();
 
1450   $main::lxdebug->enter_sub();
 
1452   my ($self, $myconfig) = @_;
 
1454   my $dbh = $self->dbconnect($myconfig);
 
1455   my $query = qq|SELECT current_date + terms_netto FROM payment_terms WHERE id = ?|;
 
1456   ($self->{duedate}) = selectrow_query($self, $dbh, $query, $self->{payment_id});
 
1459   $main::lxdebug->leave_sub();
 
1463   $main::lxdebug->enter_sub();
 
1465   my ($self, $dbh, $id, $key) = @_;
 
1467   $key = "all_contacts" unless ($key);
 
1470     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
 
1471     qq|FROM contacts | .
 
1472     qq|WHERE cp_cv_id = ? | .
 
1473     qq|ORDER BY lower(cp_name)|;
 
1475   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
 
1477   $main::lxdebug->leave_sub();
 
1481   $main::lxdebug->enter_sub();
 
1483   my ($self, $dbh, $key) = @_;
 
1485   my ($all, $old_id, $where, @values);
 
1487   if (ref($key) eq "HASH") {
 
1490     $key = "ALL_PROJECTS";
 
1492     foreach my $p (keys(%{$params})) {
 
1494         $all = $params->{$p};
 
1495       } elsif ($p eq "old_id") {
 
1496         $old_id = $params->{$p};
 
1497       } elsif ($p eq "key") {
 
1498         $key = $params->{$p};
 
1504     $where = "WHERE active ";
 
1506       if (ref($old_id) eq "ARRAY") {
 
1507         my @ids = grep({ $_ } @{$old_id});
 
1509           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
 
1510           push(@values, @ids);
 
1513         $where .= " OR (id = ?) ";
 
1514         push(@values, $old_id);
 
1520     qq|SELECT id, projectnumber, description, active | .
 
1523     qq|ORDER BY lower(projectnumber)|;
 
1525   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
 
1527   $main::lxdebug->leave_sub();
 
1531   $main::lxdebug->enter_sub();
 
1533   my ($self, $dbh, $vc_id, $key) = @_;
 
1535   $key = "all_shipto" unless ($key);
 
1537   # get shipping addresses
 
1538   my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
 
1540   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
 
1542   $main::lxdebug->leave_sub();
 
1546   $main::lxdebug->enter_sub();
 
1548   my ($self, $dbh, $key) = @_;
 
1550   $key = "all_printers" unless ($key);
 
1552   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
 
1554   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1556   $main::lxdebug->leave_sub();
 
1560   $main::lxdebug->enter_sub();
 
1562   my ($self, $dbh, $params) = @_;
 
1564   $key = $params->{key};
 
1565   $key = "all_charts" unless ($key);
 
1567   my $transdate = quote_db_date($params->{transdate});
 
1570     qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
 
1572     qq|LEFT JOIN taxkeys tk ON | .
 
1573     qq|(tk.id = (SELECT id FROM taxkeys | .
 
1574     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
 
1575     qq|          ORDER BY startdate DESC LIMIT 1)) | .
 
1576     qq|ORDER BY c.accno|;
 
1578   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1580   $main::lxdebug->leave_sub();
 
1583 sub _get_taxcharts {
 
1584   $main::lxdebug->enter_sub();
 
1586   my ($self, $dbh, $key) = @_;
 
1588   $key = "all_taxcharts" unless ($key);
 
1590   my $query = qq|SELECT * FROM tax ORDER BY taxkey|;
 
1592   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1594   $main::lxdebug->leave_sub();
 
1598   $main::lxdebug->enter_sub();
 
1600   my ($self, $dbh, $key) = @_;
 
1602   $key = "all_taxzones" unless ($key);
 
1604   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
 
1606   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1608   $main::lxdebug->leave_sub();
 
1611 sub _get_employees {
 
1612   $main::lxdebug->enter_sub();
 
1614   my ($self, $dbh, $default_key, $key) = @_;
 
1616   $key = $default_key unless ($key);
 
1617   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY name|);
 
1619   $main::lxdebug->leave_sub();
 
1622 sub _get_business_types {
 
1623   $main::lxdebug->enter_sub();
 
1625   my ($self, $dbh, $key) = @_;
 
1627   $key = "all_business_types" unless ($key);
 
1629     selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
 
1631   $main::lxdebug->leave_sub();
 
1634 sub _get_languages {
 
1635   $main::lxdebug->enter_sub();
 
1637   my ($self, $dbh, $key) = @_;
 
1639   $key = "all_languages" unless ($key);
 
1641   my $query = qq|SELECT * FROM language ORDER BY id|;
 
1643   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1645   $main::lxdebug->leave_sub();
 
1648 sub _get_dunning_configs {
 
1649   $main::lxdebug->enter_sub();
 
1651   my ($self, $dbh, $key) = @_;
 
1653   $key = "all_dunning_configs" unless ($key);
 
1655   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
 
1657   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1659   $main::lxdebug->leave_sub();
 
1662 sub _get_currencies {
 
1663 $main::lxdebug->enter_sub();
 
1665   my ($self, $dbh, $key) = @_;
 
1667   $key = "all_currencies" unless ($key);
 
1669   my $query = qq|SELECT curr AS currency FROM defaults|;
 
1671   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
 
1673   $main::lxdebug->leave_sub();
 
1677 $main::lxdebug->enter_sub();
 
1679   my ($self, $dbh, $key) = @_;
 
1681   $key = "all_payments" unless ($key);
 
1683   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
 
1685   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1687   $main::lxdebug->leave_sub();
 
1690 sub _get_customers {
 
1691   $main::lxdebug->enter_sub();
 
1693   my ($self, $dbh, $key) = @_;
 
1695   $key = "all_customers" unless ($key);
 
1697   my $query = qq|SELECT * FROM customer ORDER BY name|;
 
1699   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1701   $main::lxdebug->leave_sub();
 
1705   $main::lxdebug->enter_sub();
 
1707   my ($self, $dbh, $key) = @_;
 
1709   $key = "all_vendors" unless ($key);
 
1711   my $query = qq|SELECT * FROM vendor ORDER BY name|;
 
1713   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1715   $main::lxdebug->leave_sub();
 
1718 sub _get_departments {
 
1719   $main::lxdebug->enter_sub();
 
1721   my ($self, $dbh, $key) = @_;
 
1723   $key = "all_departments" unless ($key);
 
1725   my $query = qq|SELECT * FROM department ORDER BY description|;
 
1727   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1729   $main::lxdebug->leave_sub();
 
1733   $main::lxdebug->enter_sub();
 
1738   my $dbh = $self->dbconnect(\%main::myconfig);
 
1739   my ($sth, $query, $ref);
 
1741   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
 
1742   my $vc_id = $self->{"${vc}_id"};
 
1744   if ($params{"contacts"}) {
 
1745     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
 
1748   if ($params{"shipto"}) {
 
1749     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
 
1752   if ($params{"projects"} || $params{"all_projects"}) {
 
1753     $self->_get_projects($dbh, $params{"all_projects"} ?
 
1754                          $params{"all_projects"} : $params{"projects"},
 
1755                          $params{"all_projects"} ? 1 : 0);
 
1758   if ($params{"printers"}) {
 
1759     $self->_get_printers($dbh, $params{"printers"});
 
1762   if ($params{"languages"}) {
 
1763     $self->_get_languages($dbh, $params{"languages"});
 
1766   if ($params{"charts"}) {
 
1767     $self->_get_charts($dbh, $params{"charts"});
 
1770   if ($params{"taxcharts"}) {
 
1771     $self->_get_taxcharts($dbh, $params{"taxcharts"});
 
1774   if ($params{"taxzones"}) {
 
1775     $self->_get_taxzones($dbh, $params{"taxzones"});
 
1778   if ($params{"employees"}) {
 
1779     $self->_get_employees($dbh, "all_employees", $params{"employees"});
 
1782   if ($params{"salesmen"}) {
 
1783     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
 
1786   if ($params{"business_types"}) {
 
1787     $self->_get_business_types($dbh, $params{"business_types"});
 
1790   if ($params{"dunning_configs"}) {
 
1791     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
 
1794   if($params{"currencies"}) {
 
1795     $self->_get_currencies($dbh, $params{"currencies"});
 
1798   if($params{"customers"}) {
 
1799     $self->_get_customers($dbh, $params{"customers"});
 
1802   if($params{"vendors"}) {
 
1803     $self->_get_vendors($dbh, $params{"vendors"});
 
1806   if($params{"payments"}) {
 
1807     $self->_get_payments($dbh, $params{"payments"});
 
1810   if($params{"departments"}) {
 
1811     $self->_get_departments($dbh, $params{"departments"});
 
1816   $main::lxdebug->leave_sub();
 
1819 # this sub gets the id and name from $table
 
1821   $main::lxdebug->enter_sub();
 
1823   my ($self, $myconfig, $table) = @_;
 
1825   # connect to database
 
1826   my $dbh = $self->dbconnect($myconfig);
 
1828   $table = $table eq "customer" ? "customer" : "vendor";
 
1829   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
 
1831   my ($query, @values);
 
1833   if (!$self->{openinvoices}) {
 
1835     if ($self->{customernumber} ne "") {
 
1836       $where = qq|(vc.customernumber ILIKE ?)|;
 
1837       push(@values, '%' . $self->{customernumber} . '%');
 
1839       $where = qq|(vc.name ILIKE ?)|;
 
1840       push(@values, '%' . $self->{$table} . '%');
 
1844       qq~SELECT vc.id, vc.name,
 
1845            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
1847          WHERE $where AND (NOT vc.obsolete)
 
1851       qq~SELECT DISTINCT vc.id, vc.name,
 
1852            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
1854          JOIN $table vc ON (a.${table}_id = vc.id)
 
1855          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
 
1857     push(@values, '%' . $self->{$table} . '%');
 
1860   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
 
1862   $main::lxdebug->leave_sub();
 
1864   return scalar(@{ $self->{name_list} });
 
1867 # the selection sub is used in the AR, AP, IS, IR and OE module
 
1870   $main::lxdebug->enter_sub();
 
1872   my ($self, $myconfig, $table, $module) = @_;
 
1875   my $dbh = $self->dbconnect($myconfig);
 
1877   $table = $table eq "customer" ? "customer" : "vendor";
 
1879   my $query = qq|SELECT count(*) FROM $table|;
 
1880   my ($count) = selectrow_query($self, $dbh, $query);
 
1882   # build selection list
 
1883   if ($count < $myconfig->{vclimit}) {
 
1884     $query = qq|SELECT id, name, salesman_id
 
1885                 FROM $table WHERE NOT obsolete
 
1887     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
 
1891   $self->get_employee($dbh);
 
1893   # setup sales contacts
 
1894   $query = qq|SELECT e.id, e.name
 
1896               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
 
1897   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
 
1900   push(@{ $self->{all_employees} },
 
1901        { id   => $self->{employee_id},
 
1902          name => $self->{employee} });
 
1904   # sort the whole thing
 
1905   @{ $self->{all_employees} } =
 
1906     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
 
1908   if ($module eq 'AR') {
 
1910     # prepare query for departments
 
1911     $query = qq|SELECT id, description
 
1914                 ORDER BY description|;
 
1917     $query = qq|SELECT id, description
 
1919                 ORDER BY description|;
 
1922   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
1925   $query = qq|SELECT id, description
 
1929   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
1932   $query = qq|SELECT printer_description, id
 
1934               ORDER BY printer_description|;
 
1936   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
1939   $query = qq|SELECT id, description
 
1943   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
1947   $main::lxdebug->leave_sub();
 
1950 sub language_payment {
 
1951   $main::lxdebug->enter_sub();
 
1953   my ($self, $myconfig) = @_;
 
1955   my $dbh = $self->dbconnect($myconfig);
 
1957   my $query = qq|SELECT id, description
 
1961   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
1964   $query = qq|SELECT printer_description, id
 
1966               ORDER BY printer_description|;
 
1968   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
1971   $query = qq|SELECT id, description
 
1975   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
1977   # get buchungsgruppen
 
1978   $query = qq|SELECT id, description
 
1979               FROM buchungsgruppen|;
 
1981   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
 
1984   $main::lxdebug->leave_sub();
 
1987 # this is only used for reports
 
1988 sub all_departments {
 
1989   $main::lxdebug->enter_sub();
 
1991   my ($self, $myconfig, $table) = @_;
 
1993   my $dbh = $self->dbconnect($myconfig);
 
1996   if ($table eq 'customer') {
 
1997     $where = "WHERE role = 'P' ";
 
2000   my $query = qq|SELECT id, description
 
2003                  ORDER BY description|;
 
2004   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2006   delete($self->{all_departments}) unless (@{ $self->{all_departments} });
 
2010   $main::lxdebug->leave_sub();
 
2014   $main::lxdebug->enter_sub();
 
2016   my ($self, $module, $myconfig, $table) = @_;
 
2019   if ($table eq "customer") {
 
2028   $self->all_vc($myconfig, $table, $module);
 
2030   # get last customers or vendors
 
2031   my ($query, $sth, $ref);
 
2033   my $dbh = $self->dbconnect($myconfig);
 
2038     my $transdate = "current_date";
 
2039     if ($self->{transdate}) {
 
2040       $transdate = $dbh->quote($self->{transdate});
 
2043     # now get the account numbers
 
2044     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
 
2045                 FROM chart c, taxkeys tk
 
2046                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
 
2047                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
 
2050     $sth = $dbh->prepare($query);
 
2052     do_statement($self, $sth, $query, '%' . $module . '%');
 
2054     $self->{accounts} = "";
 
2055     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
2057       foreach my $key (split(/:/, $ref->{link})) {
 
2058         if ($key =~ /$module/) {
 
2060           # cross reference for keys
 
2061           $xkeyref{ $ref->{accno} } = $key;
 
2063           push @{ $self->{"${module}_links"}{$key} },
 
2064             { accno       => $ref->{accno},
 
2065               description => $ref->{description},
 
2066               taxkey      => $ref->{taxkey_id},
 
2067               tax_id      => $ref->{tax_id} };
 
2069           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2075   # get taxkeys and description
 
2076   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
 
2077   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
 
2079   if (($module eq "AP") || ($module eq "AR")) {
 
2080     # get tax rates and description
 
2081     $query = qq|SELECT * FROM tax|;
 
2082     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
 
2088            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
 
2089            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
 
2090            a.intnotes, a.department_id, a.amount AS oldinvtotal,
 
2091            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
 
2093            d.description AS department,
 
2096          JOIN $table c ON (a.${table}_id = c.id)
 
2097          LEFT JOIN employee e ON (e.id = a.employee_id)
 
2098          LEFT JOIN department d ON (d.id = a.department_id)
 
2100     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
 
2102     foreach $key (keys %$ref) {
 
2103       $self->{$key} = $ref->{$key};
 
2106     my $transdate = "current_date";
 
2107     if ($self->{transdate}) {
 
2108       $transdate = $dbh->quote($self->{transdate});
 
2111     # now get the account numbers
 
2112     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
 
2114                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
 
2116                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
 
2117                     OR c.link LIKE '%_tax%')
 
2120     $sth = $dbh->prepare($query);
 
2121     do_statement($self, $sth, $query, "%$module%");
 
2123     $self->{accounts} = "";
 
2124     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
2126       foreach my $key (split(/:/, $ref->{link})) {
 
2127         if ($key =~ /$module/) {
 
2129           # cross reference for keys
 
2130           $xkeyref{ $ref->{accno} } = $key;
 
2132           push @{ $self->{"${module}_links"}{$key} },
 
2133             { accno       => $ref->{accno},
 
2134               description => $ref->{description},
 
2135               taxkey      => $ref->{taxkey_id},
 
2136               tax_id      => $ref->{tax_id} };
 
2138           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2144     # get amounts from individual entries
 
2147            c.accno, c.description,
 
2148            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
 
2152          LEFT JOIN chart c ON (c.id = a.chart_id)
 
2153          LEFT JOIN project p ON (p.id = a.project_id)
 
2154          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
 
2155                                     WHERE (tk.taxkey_id=a.taxkey) AND
 
2156                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
 
2157                                         THEN tk.chart_id = a.chart_id
 
2160                                        OR (c.link='%tax%')) AND
 
2161                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
 
2162          WHERE a.trans_id = ?
 
2163          AND a.fx_transaction = '0'
 
2164          ORDER BY a.oid, a.transdate|;
 
2165     $sth = $dbh->prepare($query);
 
2166     do_statement($self, $sth, $query, $self->{id});
 
2168     # get exchangerate for currency
 
2169     $self->{exchangerate} =
 
2170       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2173     # store amounts in {acc_trans}{$key} for multiple accounts
 
2174     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
2175       $ref->{exchangerate} =
 
2176         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
 
2177       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
 
2180       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
 
2181         $ref->{amount} *= -1;
 
2183       $ref->{index} = $index;
 
2185       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
 
2191            d.curr AS currencies, d.closedto, d.revtrans,
 
2192            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2193            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
2195     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2196     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2203             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
 
2204             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2205             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
2207     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2208     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2210     if ($self->{"$self->{vc}_id"}) {
 
2212       # only setup currency
 
2213       ($self->{currency}) = split(/:/, $self->{currencies});
 
2217       $self->lastname_used($dbh, $myconfig, $table, $module);
 
2219       # get exchangerate for currency
 
2220       $self->{exchangerate} =
 
2221         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2229   $main::lxdebug->leave_sub();
 
2233   $main::lxdebug->enter_sub();
 
2235   my ($self, $dbh, $myconfig, $table, $module) = @_;
 
2237   my $arap  = ($table eq 'customer') ? "ar" : "ap";
 
2238   $table = $table eq "customer" ? "customer" : "vendor";
 
2239   my $where = "1 = 1";
 
2241   if ($self->{type} =~ /_order/) {
 
2243     $where = "quotation = '0'";
 
2245   if ($self->{type} =~ /_quotation/) {
 
2247     $where = "quotation = '1'";
 
2250   my $query = qq|SELECT MAX(id) FROM $arap
 
2251                  WHERE $where AND ${table}_id > 0|;
 
2252   my ($trans_id) = selectrow_query($self, $dbh, $query);
 
2257          a.curr, a.${table}_id, a.department_id,
 
2258          d.description AS department,
 
2259          ct.name, current_date + ct.terms AS duedate
 
2261        LEFT JOIN $table ct ON (a.${table}_id = ct.id)
 
2262        LEFT JOIN department d ON (a.department_id = d.id)
 
2264   ($self->{currency},   $self->{"${table}_id"}, $self->{department_id},
 
2265    $self->{department}, $self->{$table},        $self->{duedate})
 
2266     = selectrow_query($self, $dbh, $query, $trans_id);
 
2268   $main::lxdebug->leave_sub();
 
2272   $main::lxdebug->enter_sub();
 
2274   my ($self, $myconfig, $thisdate, $days) = @_;
 
2276   my $dbh = $self->dbconnect($myconfig);
 
2281     my $dateformat = $myconfig->{dateformat};
 
2282     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
 
2283     $thisdate = $dbh->quote($thisdate);
 
2284     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
 
2286     $query = qq|SELECT current_date AS thisdate|;
 
2289   ($thisdate) = selectrow_query($self, $dbh, $query);
 
2293   $main::lxdebug->leave_sub();
 
2299   $main::lxdebug->enter_sub();
 
2301   my ($self, $string) = @_;
 
2303   if ($string !~ /%/) {
 
2304     $string = "%$string%";
 
2307   $string =~ s/\'/\'\'/g;
 
2309   $main::lxdebug->leave_sub();
 
2315   $main::lxdebug->enter_sub();
 
2317   my ($self, $flds, $new, $count, $numrows) = @_;
 
2321   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } }
 
2327   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
 
2329     $j = $item->{ndx} - 1;
 
2330     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
 
2334   for $i ($count + 1 .. $numrows) {
 
2335     map { delete $self->{"${_}_$i"} } @{$flds};
 
2338   $main::lxdebug->leave_sub();
 
2342   $main::lxdebug->enter_sub();
 
2344   my ($self, $myconfig) = @_;
 
2348   my $dbh = $self->dbconnect_noauto($myconfig);
 
2350   my $query = qq|DELETE FROM status
 
2351                  WHERE (formname = ?) AND (trans_id = ?)|;
 
2352   my $sth = prepare_query($self, $dbh, $query);
 
2354   if ($self->{formname} =~ /(check|receipt)/) {
 
2355     for $i (1 .. $self->{rowcount}) {
 
2356       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
 
2359     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
 
2363   my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
 
2364   my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
 
2366   my %queued = split / /, $self->{queued};
 
2369   if ($self->{formname} =~ /(check|receipt)/) {
 
2371     # this is a check or receipt, add one entry for each lineitem
 
2372     my ($accno) = split /--/, $self->{account};
 
2373     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
 
2374                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
 
2375     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
 
2376     $sth = prepare_query($self, $dbh, $query);
 
2378     for $i (1 .. $self->{rowcount}) {
 
2379       if ($self->{"checked_$i"}) {
 
2380         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
 
2386     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
2387                 VALUES (?, ?, ?, ?, ?)|;
 
2388     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
 
2389              $queued{$self->{formname}}, $self->{formname});
 
2395   $main::lxdebug->leave_sub();
 
2399   $main::lxdebug->enter_sub();
 
2401   my ($self, $dbh) = @_;
 
2403   my ($query, $printed, $emailed);
 
2405   my $formnames  = $self->{printed};
 
2406   my $emailforms = $self->{emailed};
 
2408   my $query = qq|DELETE FROM status
 
2409                  WHERE (formname = ?) AND (trans_id = ?)|;
 
2410   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
 
2412   # this only applies to the forms
 
2413   # checks and receipts are posted when printed or queued
 
2415   if ($self->{queued}) {
 
2416     my %queued = split / /, $self->{queued};
 
2418     foreach my $formname (keys %queued) {
 
2419       $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
 
2420       $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
 
2422       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
2423                   VALUES (?, ?, ?, ?, ?)|;
 
2424       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
 
2426       $formnames  =~ s/$self->{formname}//;
 
2427       $emailforms =~ s/$self->{formname}//;
 
2432   # save printed, emailed info
 
2433   $formnames  =~ s/^ +//g;
 
2434   $emailforms =~ s/^ +//g;
 
2437   map { $status{$_}{printed} = 1 } split / +/, $formnames;
 
2438   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
 
2440   foreach my $formname (keys %status) {
 
2441     $printed = ($formnames  =~ /$self->{formname}/) ? "1" : "0";
 
2442     $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
 
2444     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
 
2445                 VALUES (?, ?, ?, ?)|;
 
2446     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
 
2449   $main::lxdebug->leave_sub();
 
2453 # $main::locale->text('SAVED')
 
2454 # $main::locale->text('DELETED')
 
2455 # $main::locale->text('ADDED')
 
2456 # $main::locale->text('PAYMENT POSTED')
 
2457 # $main::locale->text('POSTED')
 
2458 # $main::locale->text('POSTED AS NEW')
 
2459 # $main::locale->text('ELSE')
 
2460 # $main::locale->text('SAVED FOR DUNNING')
 
2461 # $main::locale->text('DUNNING STARTED')
 
2462 # $main::locale->text('PRINTED')
 
2463 # $main::locale->text('MAILED')
 
2464 # $main::locale->text('SCREENED')
 
2465 # $main::locale->text('CANCELED')
 
2466 # $main::locale->text('invoice')
 
2467 # $main::locale->text('proforma')
 
2468 # $main::locale->text('sales_order')
 
2469 # $main::locale->text('packing_list')
 
2470 # $main::locale->text('pick_list')
 
2471 # $main::locale->text('purchase_order')
 
2472 # $main::locale->text('bin_list')
 
2473 # $main::locale->text('sales_quotation')
 
2474 # $main::locale->text('request_quotation')
 
2477   $main::lxdebug->enter_sub();
 
2482   if(!exists $self->{employee_id}) {
 
2483     &get_employee($self, $dbh);
 
2487    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
 
2488    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
 
2489  my @values = (conv_i($self->{id}), $self->{login},
 
2490                $self->{addition}, $self->{what_done}, "$self->{snumbers}");
 
2491  do_query($self, $dbh, $query, @values);
 
2493   $main::lxdebug->leave_sub();
 
2497   $main::lxdebug->enter_sub();
 
2499   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
 
2500   my ($orderBy, $desc) = split(/\-\-/, $order);
 
2501   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
 
2504   if ($trans_id ne "") {
 
2506       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 | .
 
2507       qq|FROM history_erp h | .
 
2508       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
 
2509       qq|WHERE trans_id = | . $trans_id
 
2510       . $restriction . qq| |
 
2513     my $sth = $dbh->prepare($query) || $self->dberror($query);
 
2515     $sth->execute() || $self->dberror("$query");
 
2517     while(my $hash_ref = $sth->fetchrow_hashref()) {
 
2518       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
 
2519       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
 
2520       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
 
2521       $tempArray[$i++] = $hash_ref;
 
2523     $main::lxdebug->leave_sub() and return \@tempArray 
 
2524       if ($i > 0 && $tempArray[0] ne "");
 
2526   $main::lxdebug->leave_sub();
 
2530 sub update_defaults {
 
2531   $main::lxdebug->enter_sub();
 
2533   my ($self, $myconfig, $fld, $provided_dbh) = @_;
 
2536   if ($provided_dbh) {
 
2537     $dbh = $provided_dbh;
 
2539     $dbh = $self->dbconnect_noauto($myconfig);
 
2541   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
 
2542   my $sth   = $dbh->prepare($query);
 
2544   $sth->execute || $self->dberror($query);
 
2545   my ($var) = $sth->fetchrow_array;
 
2548   $var =~ s/\d+$/ sprintf '%0*d', length($&), $&+1 /e;
 
2551   $query = qq|UPDATE defaults SET $fld = ?|;
 
2552   do_query($self, $dbh, $query, $var);
 
2554   if (!$provided_dbh) {
 
2559   $main::lxdebug->leave_sub();
 
2564 sub update_business {
 
2565   $main::lxdebug->enter_sub();
 
2567   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
 
2570   if ($provided_dbh) {
 
2571     $dbh = $provided_dbh;
 
2573     $dbh = $self->dbconnect_noauto($myconfig);
 
2576     qq|SELECT customernumberinit FROM business
 
2577        WHERE id = ? FOR UPDATE|;
 
2578   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
 
2580   $var =~ s/\d+$/ sprintf '%0*d', length($&), $&+1 /e;
 
2582   $query = qq|UPDATE business
 
2583               SET customernumberinit = ?
 
2585   do_query($self, $dbh, $query, $var, $business_id);
 
2587   if (!$provided_dbh) {
 
2592   $main::lxdebug->leave_sub();
 
2597 sub get_partsgroup {
 
2598   $main::lxdebug->enter_sub();
 
2600   my ($self, $myconfig, $p) = @_;
 
2602   my $dbh = $self->dbconnect($myconfig);
 
2604   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
 
2606                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
 
2609   if ($p->{searchitems} eq 'part') {
 
2610     $query .= qq|WHERE p.inventory_accno_id > 0|;
 
2612   if ($p->{searchitems} eq 'service') {
 
2613     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
 
2615   if ($p->{searchitems} eq 'assembly') {
 
2616     $query .= qq|WHERE p.assembly = '1'|;
 
2618   if ($p->{searchitems} eq 'labor') {
 
2619     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
 
2622   $query .= qq|ORDER BY partsgroup|;
 
2625     $query = qq|SELECT id, partsgroup FROM partsgroup
 
2626                 ORDER BY partsgroup|;
 
2629   if ($p->{language_code}) {
 
2630     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
 
2631                   t.description AS translation
 
2633                 JOIN parts p ON (p.partsgroup_id = pg.id)
 
2634                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
 
2635                 ORDER BY translation|;
 
2636     @values = ($p->{language_code});
 
2639   $self->{all_partsgroup} = selectall_hashref_query($self, $dbh, $query, @values);
 
2642   $main::lxdebug->leave_sub();
 
2645 sub get_pricegroup {
 
2646   $main::lxdebug->enter_sub();
 
2648   my ($self, $myconfig, $p) = @_;
 
2650   my $dbh = $self->dbconnect($myconfig);
 
2652   my $query = qq|SELECT p.id, p.pricegroup
 
2655   $query .= qq| ORDER BY pricegroup|;
 
2658     $query = qq|SELECT id, pricegroup FROM pricegroup
 
2659                 ORDER BY pricegroup|;
 
2662   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
 
2666   $main::lxdebug->leave_sub();
 
2670 # usage $form->all_years($myconfig, [$dbh])
 
2671 # return list of all years where bookings found
 
2674   $main::lxdebug->enter_sub();
 
2676   my ($self, $myconfig, $dbh) = @_;
 
2680     $dbh = $self->dbconnect($myconfig);
 
2685   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
 
2686                    (SELECT MAX(transdate) FROM acc_trans)|;
 
2687   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
 
2689   if ($myconfig->{dateformat} =~ /^yy/) {
 
2690     ($startdate) = split /\W/, $startdate;
 
2691     ($enddate) = split /\W/, $enddate;
 
2693     (@_) = split /\W/, $startdate;
 
2695     (@_) = split /\W/, $enddate;
 
2700   $startdate = substr($startdate,0,4);
 
2701   $enddate = substr($enddate,0,4);
 
2703   while ($enddate >= $startdate) {
 
2704     push @all_years, $enddate--;
 
2707   $dbh->disconnect if $disconnect;
 
2711   $main::lxdebug->leave_sub();