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.3";
 
 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);
 
 300   $main::lxdebug->leave_sub();
 
 304   $main::lxdebug->enter_sub();
 
 306   my ($self, $msg) = @_;
 
 308   if ($ENV{HTTP_USER_AGENT}) {
 
 311     if (!$self->{header}) {
 
 324     if ($self->{info_function}) {
 
 325       &{ $self->{info_function} }($msg);
 
 331   $main::lxdebug->leave_sub();
 
 335   $main::lxdebug->enter_sub();
 
 337   my ($self, $str, $cols, $maxrows) = @_;
 
 341   map { $rows += int(((length) - 2) / $cols) + 1 } split /\r/, $str;
 
 343   $maxrows = $rows unless defined $maxrows;
 
 345   $main::lxdebug->leave_sub();
 
 347   return ($rows > $maxrows) ? $maxrows : $rows;
 
 351   $main::lxdebug->enter_sub();
 
 353   my ($self, $msg) = @_;
 
 355   $self->error("$msg\n" . $DBI::errstr);
 
 357   $main::lxdebug->leave_sub();
 
 361   $main::lxdebug->enter_sub();
 
 363   my ($self, $name, $msg) = @_;
 
 365   if ($self->{$name} =~ /^\s*$/) {
 
 368   $main::lxdebug->leave_sub();
 
 372   $main::lxdebug->enter_sub();
 
 374   my ($self, $extra_code) = @_;
 
 376   if ($self->{header}) {
 
 377     $main::lxdebug->leave_sub();
 
 381   my ($stylesheet, $favicon);
 
 383   if ($ENV{HTTP_USER_AGENT}) {
 
 385     my $stylesheets = "$self->{stylesheet} $self->{stylesheets}";
 
 387     $stylesheets =~ s|^\s*||;
 
 388     $stylesheets =~ s|\s*$||;
 
 389     foreach my $file (split m/\s+/, $stylesheets) {
 
 391       next if (! -f "css/$file");
 
 393       $stylesheet .= qq|<link rel="stylesheet" href="css/$file" TYPE="text/css" TITLE="Lx-Office stylesheet">\n|;
 
 396     $self->{favicon}    = "favicon.ico" unless $self->{favicon};
 
 398     if ($self->{favicon} && (-f "$self->{favicon}")) {
 
 400         qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
 
 404     my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
 406     if ($self->{landscape}) {
 
 407       $pagelayout = qq|<style type="text/css">
 
 408                         \@page { size:landscape; }
 
 412     my $fokus = qq|  document.$self->{fokus}.focus();| if ($self->{"fokus"});
 
 416     if ($self->{jsscript} == 1) {
 
 419         <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
 
 420         <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
 
 421         <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
 
 422         <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
 
 429       ? "$self->{title} - $self->{titlebar}"
 
 432     foreach $item (@ { $self->{AJAX} }) {
 
 433       $ajax .= $item->show_javascript();
 
 435     print qq|Content-Type: text/html; charset=${db_charset};
 
 439   <title>$self->{titlebar}</title>
 
 443   <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
 
 447   <script type="text/javascript">
 
 455   <meta name="robots" content="noindex,nofollow" />
 
 456   <script type="text/javascript" src="js/highlight_input.js"></script>
 
 457   <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
 
 459   <script type="text/javascript" src="js/tabcontent.js">
 
 461   /***********************************************
 
 462   * Tab Content script- Dynamic Drive DHTML code library (www.dynamicdrive.com)
 
 463   * This notice MUST stay intact for legal use
 
 464   * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
 
 465   ***********************************************/
 
 476   $main::lxdebug->leave_sub();
 
 479 sub _prepare_html_template {
 
 480   $main::lxdebug->enter_sub();
 
 482   my ($self, $file, $additional_params) = @_;
 
 485   if (!defined(%main::myconfig) || !defined($main::myconfig{"countrycode"})) {
 
 486     $language = $main::language;
 
 488     $language = $main::myconfig{"countrycode"};
 
 490   $language = "de" unless ($language);
 
 492   if (-f "templates/webpages/${file}_${language}.html") {
 
 493     if ((-f ".developer") &&
 
 494         (-f "templates/webpages/${file}_master.html") &&
 
 495         ((stat("templates/webpages/${file}_master.html"))[9] >
 
 496          (stat("templates/webpages/${file}_${language}.html"))[9])) {
 
 497       my $info = "Developer information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
 
 498         "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 499       print(qq|<pre>$info</pre>|);
 
 503     $file = "templates/webpages/${file}_${language}.html";
 
 504   } elsif (-f "templates/webpages/${file}.html") {
 
 505     $file = "templates/webpages/${file}.html";
 
 507     my $info = "Web page template '${file}' not found.\n" .
 
 508       "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 509     print(qq|<pre>$info</pre>|);
 
 513   if ($self->{"DEBUG"}) {
 
 514     $additional_params->{"DEBUG"} = $self->{"DEBUG"};
 
 517   if ($additional_params->{"DEBUG"}) {
 
 518     $additional_params->{"DEBUG"} =
 
 519       "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
 
 522   if (%main::myconfig) {
 
 523     map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
 
 524     my $jsc_dateformat = $main::myconfig{"dateformat"};
 
 525     $jsc_dateformat =~ s/d+/\%d/gi;
 
 526     $jsc_dateformat =~ s/m+/\%m/gi;
 
 527     $jsc_dateformat =~ s/y+/\%Y/gi;
 
 528     $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
 
 531   $additional_params->{"conf_webdav"}                 = $main::webdav;
 
 532   $additional_params->{"conf_lizenzen"}               = $main::lizenzen;
 
 533   $additional_params->{"conf_latex_templates"}        = $main::latex;
 
 534   $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
 
 536   if (%main::debug_options) {
 
 537     map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
 
 540   $main::lxdebug->leave_sub();
 
 545 sub parse_html_template {
 
 546   $main::lxdebug->enter_sub();
 
 548   my ($self, $file, $additional_params) = @_;
 
 550   $additional_params ||= { };
 
 552   $file = $self->_prepare_html_template($file, $additional_params);
 
 554   my $template = HTML::Template->new("filename" => $file,
 
 555                                      "die_on_bad_params" => 0,
 
 557                                      "case_sensitive" => 1,
 
 558                                      "loop_context_vars" => 1,
 
 561   foreach my $key ($template->param()) {
 
 562     my $param = $additional_params->{$key} || $self->{$key};
 
 563     $param = [] if (($template->query("name" => $key) eq "LOOP") && (ref($param) ne "ARRAY"));
 
 564     $template->param($key => $param);
 
 567   my $output = $template->output();
 
 569   $output = $main::locale->{iconv}->convert($output) if ($main::locale);
 
 571   $main::lxdebug->leave_sub();
 
 576 sub parse_html_template2 {
 
 577   $main::lxdebug->enter_sub();
 
 579   my ($self, $file, $additional_params) = @_;
 
 581   $additional_params ||= { };
 
 583   $file = $self->_prepare_html_template($file, $additional_params);
 
 585   my $template = Template->new({ 'INTERPOLATE' => 0,
 
 591   map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
 
 594   $template->process($file, $additional_params, \$output);
 
 596   $output = $main::locale->{iconv}->convert($output) if ($main::locale);
 
 598   $main::lxdebug->leave_sub();
 
 603 sub show_generic_error {
 
 604   my ($self, $error, $title, $action) = @_;
 
 607   $add_params->{"title"} = $title if ($title);
 
 608   $self->{"label_error"} = $error;
 
 612     map({ delete($self->{$_}); } qw(action));
 
 613     map({ push(@vars, { "name" => $_, "value" => $self->{$_} })
 
 614             if (!ref($self->{$_})); }
 
 616     $add_params->{"SHOW_BUTTON"} = 1;
 
 617     $add_params->{"BUTTON_LABEL"} = $action;
 
 619   $add_params->{"VARIABLES"} = \@vars;
 
 622   print($self->parse_html_template("generic/error", $add_params));
 
 624   die("Error: $error\n");
 
 627 sub show_generic_information {
 
 628   my ($self, $error, $title) = @_;
 
 631   $add_params->{"title"} = $title if ($title);
 
 632   $self->{"label_information"} = $error;
 
 635   print($self->parse_html_template("generic/information", $add_params));
 
 637   die("Information: $error\n");
 
 640 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
 
 641 # changed it to accept an arbitrary number of triggers - sschoeling
 
 643   $main::lxdebug->enter_sub();
 
 646   my $myconfig = shift;
 
 649   # set dateform for jsscript
 
 652     "dd.mm.yy" => "%d.%m.%Y",
 
 653     "dd-mm-yy" => "%d-%m-%Y",
 
 654     "dd/mm/yy" => "%d/%m/%Y",
 
 655     "mm/dd/yy" => "%m/%d/%Y",
 
 656     "mm-dd-yy" => "%m-%d-%Y",
 
 657     "yyyy-mm-dd" => "%Y-%m-%d",
 
 660   my $ifFormat = defined($dateformats{$myconfig{"dateformat"}}) ?
 
 661     $dateformats{$myconfig{"dateformat"}} : "%d.%m.%Y";
 
 668       inputField : "| . (shift) . qq|",
 
 669       ifFormat :"$ifFormat",
 
 670       align : "| .  (shift) . qq|",
 
 671       button : "| . (shift) . qq|"
 
 677        <script type="text/javascript">
 
 678        <!--| . join("", @triggers) . qq|//-->
 
 682   $main::lxdebug->leave_sub();
 
 685 }    #end sub write_trigger
 
 688   $main::lxdebug->enter_sub();
 
 690   my ($self, $msg) = @_;
 
 692   if ($self->{callback}) {
 
 694     ($script, $argv) = split(/\?/, $self->{callback}, 2);
 
 696     $script =~ s|[^a-zA-Z0-9_\.]||g;
 
 697     exec("perl", "$script", $argv);
 
 705   $main::lxdebug->leave_sub();
 
 708 # sort of columns removed - empty sub
 
 710   $main::lxdebug->enter_sub();
 
 712   my ($self, @columns) = @_;
 
 714   $main::lxdebug->leave_sub();
 
 720   $main::lxdebug->enter_sub(2);
 
 722   my ($self, $myconfig, $amount, $places, $dash) = @_;
 
 727   my $neg = ($amount =~ s/-//);
 
 729   if (defined($places) && ($places ne '')) {
 
 734       my ($actual_places) = ($amount =~ /\.(\d+)/);
 
 735       $actual_places = length($actual_places);
 
 736       $places = $actual_places > $places ? $actual_places : $places;
 
 739     $amount = $self->round_amount($amount, $places);
 
 742   my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
 
 743   my @p = split(/\./, $amount); # split amount at decimal point
 
 745   $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
 
 748   $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
 
 751     ($dash =~ /-/)    ? ($neg ? "($amount)"  : "$amount" )    :
 
 752     ($dash =~ /DRCR/) ? ($neg ? "$amount DR" : "$amount CR" ) :
 
 753                         ($neg ? "-$amount"   : "$amount" )    ;
 
 757   $main::lxdebug->leave_sub(2);
 
 762   $main::lxdebug->enter_sub(2);
 
 764   my ($self, $myconfig, $amount) = @_;
 
 766   if (   ($myconfig->{numberformat} eq '1.000,00')
 
 767       || ($myconfig->{numberformat} eq '1000,00')) {
 
 772   if ($myconfig->{numberformat} eq "1'000.00") {
 
 778   $main::lxdebug->leave_sub(2);
 
 780   return ($amount * 1);
 
 784   $main::lxdebug->enter_sub(2);
 
 786   my ($self, $amount, $places) = @_;
 
 789   # Rounding like "Kaufmannsrunden"
 
 790   # Descr. http://de.wikipedia.org/wiki/Rundung
 
 792   # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
 
 795   $amount = $amount * (10**($places));
 
 796   $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
 
 798   $main::lxdebug->leave_sub(2);
 
 800   return $round_amount;
 
 805   $main::lxdebug->enter_sub();
 
 807   my ($self, $myconfig, $userspath) = @_;
 
 808   my ($template, $out);
 
 812   $self->{"cwd"} = getcwd();
 
 813   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
 
 815   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
 
 816     $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
 817   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
 
 818     $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
 
 819     $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
 820   } elsif (($self->{"format"} =~ /html/i) ||
 
 821            (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
 
 822     $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
 823   } elsif (($self->{"format"} =~ /xml/i) ||
 
 824              (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
 
 825     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
 826   } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
 
 827     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
 828   } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
 
 829     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
 
 830   } elsif ( defined $self->{'format'}) {
 
 831     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
 
 832   } elsif ( $self->{'format'} eq '' ) {
 
 833     $self->error("No Outputformat given: $self->{'format'}");
 
 834   } else { #Catch the rest
 
 835     $self->error("Outputformat not defined: $self->{'format'}");
 
 838   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
 
 839   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
 
 841   map({ $self->{"employee_${_}"} = $myconfig->{$_}; }
 
 842       qw(email tel fax name signature company address businessnumber
 
 843          co_ustid taxnumber duns));
 
 844   map({ $self->{"employee_${_}"} =~ s/\\n/\n/g; }
 
 845       qw(company address signature));
 
 846   map({ $self->{$_} =~ s/\\n/\n/g; } qw(company address signature));
 
 848   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
 
 850   # OUT is used for the media, screen, printer, email
 
 851   # for postscript we store a copy in a temporary file
 
 853   my $prepend_userspath;
 
 855   if (!$self->{tmpfile}) {
 
 856     $self->{tmpfile}   = "${fileid}.$self->{IN}";
 
 857     $prepend_userspath = 1;
 
 860   $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
 
 862   $self->{tmpfile} =~ s|.*/||;
 
 863   $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
 
 864   $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
 
 866   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
 868     $self->{OUT} = ">$self->{tmpfile}";
 
 872     open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
 
 874     open(OUT, ">-") or $self->error("STDOUT : $!");
 
 878   if (!$template->parse(*OUT)) {
 
 880     $self->error("$self->{IN} : " . $template->get_error());
 
 885   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
 887     if ($self->{media} eq 'email') {
 
 889       my $mail = new Mailer;
 
 891       map { $mail->{$_} = $self->{$_} }
 
 892         qw(cc bcc subject message version format);
 
 893       $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
 894       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
 
 895       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
 
 896       $mail->{fileid} = "$fileid.";
 
 897       $myconfig->{signature} =~ s/\\r\\n/\\n/g;
 
 899       # if we send html or plain text inline
 
 900       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
 
 901         $mail->{contenttype} = "text/html";
 
 903         $mail->{message}       =~ s/\r\n/<br>\n/g;
 
 904         $myconfig->{signature} =~ s/\\n/<br>\n/g;
 
 905         $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
 
 907         open(IN, $self->{tmpfile})
 
 908           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
 910           $mail->{message} .= $_;
 
 917         if (!$self->{"do_not_attach"}) {
 
 918           @{ $mail->{attachments} } =
 
 919             ({ "filename" => $self->{"tmpfile"},
 
 920                "name" => $self->{"attachment_filename"} ?
 
 921                  $self->{"attachment_filename"} : $self->{"tmpfile"} });
 
 924         $mail->{message}       =~ s/\r\n/\n/g;
 
 925         $myconfig->{signature} =~ s/\\n/\n/g;
 
 926         $mail->{message} .= "\n-- \n$myconfig->{signature}";
 
 930       my $err = $mail->send();
 
 931       $self->error($self->cleanup . "$err") if ($err);
 
 937       my $numbytes = (-s $self->{tmpfile});
 
 938       open(IN, $self->{tmpfile})
 
 939         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
 941       $self->{copies} = 1 unless $self->{media} eq 'printer';
 
 943       chdir("$self->{cwd}");
 
 944       #print(STDERR "Kopien $self->{copies}\n");
 
 945       #print(STDERR "OUT $self->{OUT}\n");
 
 946       for my $i (1 .. $self->{copies}) {
 
 948           open(OUT, $self->{OUT})
 
 949             or $self->error($self->cleanup . "$self->{OUT} : $!");
 
 951           $self->{attachment_filename} = ($self->{attachment_filename}) 
 
 952                                        ? $self->{attachment_filename}
 
 953                                        : $self->generate_attachment_filename();
 
 956           print qq|Content-Type: | . $template->get_mime_type() . qq|
 
 957 Content-Disposition: attachment; filename="$self->{attachment_filename}"
 
 958 Content-Length: $numbytes
 
 962           open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
 
 982   chdir("$self->{cwd}");
 
 983   $main::lxdebug->leave_sub();
 
 986 sub get_formname_translation {
 
 987   my ($self, $formname) = @_;
 
 989   $formname ||= $self->{formname};
 
 991   my %formname_translations = (
 
 992      bin_list            => $main::locale->text('Bin List'),
 
 993      credit_note         => $main::locale->text('Credit Note'),
 
 994      invoice             => $main::locale->text('Invoice'),
 
 995      packing_list        => $main::locale->text('Packing List'),
 
 996      pick_list           => $main::locale->text('Pick List'),
 
 997      proforma            => $main::locale->text('Proforma Invoice'),
 
 998      purchase_order      => $main::locale->text('Purchase Order'),
 
 999      request_quotation   => $main::locale->text('RFQ'),
 
1000      sales_order         => $main::locale->text('Confirmation'),
 
1001      sales_quotation     => $main::locale->text('Quotation'),
 
1002      storno_invoice      => $main::locale->text('Storno Invoice'),
 
1003      storno_packing_list => $main::locale->text('Storno Packing List'),
 
1006   return $formname_translations{$formname}
 
1009 sub generate_attachment_filename {
 
1012   my $attachment_filename = $self->get_formname_translation();
 
1014       (grep { $self->{"type"} eq $_ } qw(invoice credit_note)) ? "inv"
 
1015     : ($self->{"type"} =~ /_quotation$/)                       ? "quo"
 
1018   if ($attachment_filename && $self->{"${prefix}number"}) {
 
1019     $attachment_filename .= "_" . $self->{"${prefix}number"}
 
1020                             . (  $self->{format} =~ /pdf/i          ? ".pdf"
 
1021                                : $self->{format} =~ /postscript/i   ? ".ps"
 
1022                                : $self->{format} =~ /opendocument/i ? ".odt"
 
1023                                : $self->{format} =~ /html/i         ? ".html"
 
1025     $attachment_filename =~ s/ /_/g;
 
1026     my %umlaute = ( "ä" => "ae", "ö" => "oe", "ü" => "ue", 
 
1027                     "Ä" => "Ae", "Ö" => "Oe", "Ü" => "Ue", "ß" => "ss");
 
1028     map { $attachment_filename =~ s/$_/$umlaute{$_}/g } keys %umlaute;
 
1030     $attachment_filename = "";
 
1033   return $attachment_filename;
 
1037   $main::lxdebug->enter_sub();
 
1041   chdir("$self->{tmpdir}");
 
1044   if (-f "$self->{tmpfile}.err") {
 
1045     open(FH, "$self->{tmpfile}.err");
 
1050   if ($self->{tmpfile}) {
 
1051     $self->{tmpfile} =~ s|.*/||g;
 
1053     $self->{tmpfile} =~ s/\.\w+$//g;
 
1054     my $tmpfile = $self->{tmpfile};
 
1055     unlink(<$tmpfile.*>);
 
1058   chdir("$self->{cwd}");
 
1060   $main::lxdebug->leave_sub();
 
1066   $main::lxdebug->enter_sub();
 
1068   my ($self, $date, $myconfig) = @_;
 
1070   if ($date && $date =~ /\D/) {
 
1072     if ($myconfig->{dateformat} =~ /^yy/) {
 
1073       ($yy, $mm, $dd) = split /\D/, $date;
 
1075     if ($myconfig->{dateformat} =~ /^mm/) {
 
1076       ($mm, $dd, $yy) = split /\D/, $date;
 
1078     if ($myconfig->{dateformat} =~ /^dd/) {
 
1079       ($dd, $mm, $yy) = split /\D/, $date;
 
1084     $yy = ($yy < 70) ? $yy + 2000 : $yy;
 
1085     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
 
1087     $dd = "0$dd" if ($dd < 10);
 
1088     $mm = "0$mm" if ($mm < 10);
 
1090     $date = "$yy$mm$dd";
 
1093   $main::lxdebug->leave_sub();
 
1098 # Database routines used throughout
 
1101   $main::lxdebug->enter_sub(2);
 
1103   my ($self, $myconfig) = @_;
 
1105   # connect to database
 
1107     DBI->connect($myconfig->{dbconnect},
 
1108                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
 
1112   if ($myconfig->{dboptions}) {
 
1113     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1116   $main::lxdebug->leave_sub(2);
 
1121 sub dbconnect_noauto {
 
1122   $main::lxdebug->enter_sub();
 
1124   my ($self, $myconfig) = @_;
 
1126   # connect to database
 
1128     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
 
1129                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
 
1133   if ($myconfig->{dboptions}) {
 
1134     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1137   $main::lxdebug->leave_sub();
 
1142 sub get_standard_dbh {
 
1143   $main::lxdebug->enter_sub(2);
 
1145   my ($self, $myconfig) = @_;
 
1147   $standard_dbh ||= $self->dbconnect_noauto($myconfig);
 
1149   $main::lxdebug->leave_sub(2);
 
1151   return $standard_dbh;
 
1154 sub update_balance {
 
1155   $main::lxdebug->enter_sub();
 
1157   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
 
1159   # if we have a value, go do it
 
1162     # retrieve balance from table
 
1163     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
 
1164     my $sth = prepare_execute_query($self, $dbh, $query, @values);
 
1165     my ($balance) = $sth->fetchrow_array;
 
1171     $query = "UPDATE $table SET $field = $balance WHERE $where";
 
1172     do_query($self, $dbh, $query, @values);
 
1174   $main::lxdebug->leave_sub();
 
1177 sub update_exchangerate {
 
1178   $main::lxdebug->enter_sub();
 
1180   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
 
1182   # some sanity check for currency
 
1184     $main::lxdebug->leave_sub();
 
1187   my $query = qq|SELECT curr FROM defaults|;
 
1189   my ($currency) = selectrow_query($self, $dbh, $query);
 
1190   my ($defaultcurrency) = split m/:/, $currency;
 
1193   if ($curr eq $defaultcurrency) {
 
1194     $main::lxdebug->leave_sub();
 
1198   my $query = qq|SELECT e.curr FROM exchangerate e
 
1199                  WHERE e.curr = ? AND e.transdate = ?
 
1201   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
 
1210   $buy = conv_i($buy, "NULL");
 
1211   $sell = conv_i($sell, "NULL");
 
1214   if ($buy != 0 && $sell != 0) {
 
1215     $set = "buy = $buy, sell = $sell";
 
1216   } elsif ($buy != 0) {
 
1217     $set = "buy = $buy";
 
1218   } elsif ($sell != 0) {
 
1219     $set = "sell = $sell";
 
1222   if ($sth->fetchrow_array) {
 
1223     $query = qq|UPDATE exchangerate
 
1229     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
 
1230                 VALUES (?, $buy, $sell, ?)|;
 
1233   do_query($self, $dbh, $query, $curr, $transdate);
 
1235   $main::lxdebug->leave_sub();
 
1238 sub save_exchangerate {
 
1239   $main::lxdebug->enter_sub();
 
1241   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
 
1243   my $dbh = $self->dbconnect($myconfig);
 
1247   $buy  = $rate if $fld eq 'buy';
 
1248   $sell = $rate if $fld eq 'sell';
 
1251   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
 
1256   $main::lxdebug->leave_sub();
 
1259 sub get_exchangerate {
 
1260   $main::lxdebug->enter_sub();
 
1262   my ($self, $dbh, $curr, $transdate, $fld) = @_;
 
1264   unless ($transdate) {
 
1265     $main::lxdebug->leave_sub();
 
1269   my $query = qq|SELECT curr FROM defaults|;
 
1271   my ($currency) = selectrow_query($self, $dbh, $query);
 
1272   my ($defaultcurrency) = split m/:/, $currency;
 
1274   if ($currency eq $defaultcurrency) {
 
1275     $main::lxdebug->leave_sub();
 
1279   my $query = qq|SELECT e.$fld FROM exchangerate e
 
1280                  WHERE e.curr = ? AND e.transdate = ?|;
 
1281   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
 
1285   $main::lxdebug->leave_sub();
 
1287   return $exchangerate;
 
1290 sub check_exchangerate {
 
1291   $main::lxdebug->enter_sub();
 
1293   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
 
1295   unless ($transdate) {
 
1296     $main::lxdebug->leave_sub();
 
1300   my ($defaultcurrency) = $self->get_default_currency($myconfig);
 
1302   if ($currency eq $defaultcurrency) {
 
1303     $main::lxdebug->leave_sub();
 
1307   my $dbh   = $self->get_standard_dbh($myconfig);
 
1308   my $query = qq|SELECT e.$fld FROM exchangerate e
 
1309                  WHERE e.curr = ? AND e.transdate = ?|;
 
1311   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
 
1313   $exchangerate = 1 if ($exchangerate eq "");
 
1315   $main::lxdebug->leave_sub();
 
1317   return $exchangerate;
 
1320 sub get_default_currency {
 
1321   $main::lxdebug->enter_sub();
 
1323   my ($self, $myconfig) = @_;
 
1324   my $dbh = $self->get_standard_dbh($myconfig);
 
1326   my $query = qq|SELECT curr FROM defaults|;
 
1328   my ($curr)            = selectrow_query($self, $dbh, $query);
 
1329   my ($defaultcurrency) = split m/:/, $curr;
 
1331   $main::lxdebug->leave_sub();
 
1333   return $defaultcurrency;
 
1337 sub set_payment_options {
 
1338   $main::lxdebug->enter_sub();
 
1340   my ($self, $myconfig, $transdate) = @_;
 
1342   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
 
1344   my $dbh = $self->get_standard_dbh($myconfig);
 
1347     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
 
1348     qq|FROM payment_terms p | .
 
1351   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
 
1352    $self->{payment_terms}) =
 
1353      selectrow_query($self, $dbh, $query, $self->{payment_id});
 
1355   if ($transdate eq "") {
 
1356     if ($self->{invdate}) {
 
1357       $transdate = $self->{invdate};
 
1359       $transdate = $self->{transdate};
 
1364     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
 
1365     qq|FROM payment_terms|;
 
1366   ($self->{netto_date}, $self->{skonto_date}) =
 
1367     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
 
1369   my ($invtotal, $total);
 
1370   my (%amounts, %formatted_amounts);
 
1372   if ($self->{type} =~ /_order$/) {
 
1373     $amounts{invtotal} = $self->{ordtotal};
 
1374     $amounts{total}    = $self->{ordtotal};
 
1376   } elsif ($self->{type} =~ /_quotation$/) {
 
1377     $amounts{invtotal} = $self->{quototal};
 
1378     $amounts{total}    = $self->{quototal};
 
1381     $amounts{invtotal} = $self->{invtotal};
 
1382     $amounts{total}    = $self->{total};
 
1385   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
 
1387   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
 
1388   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
 
1389   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
 
1391   foreach (keys %amounts) {
 
1392     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
 
1393     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
 
1396   if ($self->{"language_id"}) {
 
1398       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
 
1399       qq|FROM translation_payment_terms t | .
 
1400       qq|LEFT JOIN language l ON t.language_id = l.id | .
 
1401       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
 
1402     my ($description_long, $output_numberformat, $output_dateformat,
 
1403       $output_longdates) =
 
1404       selectrow_query($self, $dbh, $query,
 
1405                       $self->{"language_id"}, $self->{"payment_id"});
 
1407     $self->{payment_terms} = $description_long if ($description_long);
 
1409     if ($output_dateformat) {
 
1410       foreach my $key (qw(netto_date skonto_date)) {
 
1412           $main::locale->reformat_date($myconfig, $self->{$key},
 
1418     if ($output_numberformat &&
 
1419         ($output_numberformat ne $myconfig->{"numberformat"})) {
 
1420       my $saved_numberformat = $myconfig->{"numberformat"};
 
1421       $myconfig->{"numberformat"} = $output_numberformat;
 
1422       map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
 
1423       $myconfig->{"numberformat"} = $saved_numberformat;
 
1427   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
 
1428   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
 
1429   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
 
1430   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
 
1431   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
 
1432   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
 
1433   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
 
1435   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
 
1437   $main::lxdebug->leave_sub();
 
1441 sub get_template_language {
 
1442   $main::lxdebug->enter_sub();
 
1444   my ($self, $myconfig) = @_;
 
1446   my $template_code = "";
 
1448   if ($self->{language_id}) {
 
1449     my $dbh = $self->get_standard_dbh($myconfig);
 
1450     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
 
1451     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
 
1454   $main::lxdebug->leave_sub();
 
1456   return $template_code;
 
1459 sub get_printer_code {
 
1460   $main::lxdebug->enter_sub();
 
1462   my ($self, $myconfig) = @_;
 
1464   my $template_code = "";
 
1466   if ($self->{printer_id}) {
 
1467     my $dbh = $self->get_standard_dbh($myconfig);
 
1468     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
 
1469     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
 
1472   $main::lxdebug->leave_sub();
 
1474   return $template_code;
 
1478   $main::lxdebug->enter_sub();
 
1480   my ($self, $myconfig) = @_;
 
1482   my $template_code = "";
 
1484   if ($self->{shipto_id}) {
 
1485     my $dbh = $self->get_standard_dbh($myconfig);
 
1486     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
 
1487     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
 
1488     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
 
1491   $main::lxdebug->leave_sub();
 
1495   $main::lxdebug->enter_sub();
 
1497   my ($self, $dbh, $id, $module) = @_;
 
1502   foreach my $item (qw(name department_1 department_2 street zipcode city country
 
1503                        contact phone fax email)) {
 
1504     if ($self->{"shipto$item"}) {
 
1505       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
 
1507     push(@values, $self->{"shipto${item}"});
 
1511     if ($self->{shipto_id}) {
 
1512       my $query = qq|UPDATE shipto set
 
1514                        shiptodepartment_1 = ?,
 
1515                        shiptodepartment_2 = ?,
 
1524                      WHERE shipto_id = ?|;
 
1525       do_query($self, $dbh, $query, @values, $self->{shipto_id});
 
1527       my $query = qq|SELECT * FROM shipto
 
1528                      WHERE shiptoname = ? AND
 
1529                        shiptodepartment_1 = ? AND
 
1530                        shiptodepartment_2 = ? AND
 
1531                        shiptostreet = ? AND
 
1532                        shiptozipcode = ? AND
 
1534                        shiptocountry = ? AND
 
1535                        shiptocontact = ? AND
 
1541       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
 
1544           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
 
1545                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
 
1546                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
 
1547              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
 
1548         do_query($self, $dbh, $query, $id, @values, $module);
 
1553   $main::lxdebug->leave_sub();
 
1557   $main::lxdebug->enter_sub();
 
1559   my ($self, $dbh) = @_;
 
1561   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
 
1562   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
 
1563   $self->{"employee_id"} *= 1;
 
1565   $main::lxdebug->leave_sub();
 
1569   $main::lxdebug->enter_sub();
 
1571   my ($self, $myconfig, $salesman_id) = @_;
 
1573   $main::lxdebug->leave_sub() and return unless $salesman_id;
 
1575   my $dbh = $self->get_standard_dbh($myconfig);
 
1578     selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|,
 
1582     my $user = new User($main::memberfile, $login);
 
1583     map({ $self->{"salesman_$_"} = $user->{$_}; }
 
1584         qw(address businessnumber co_ustid company duns email fax name
 
1586     $self->{salesman_login} = $login;
 
1588     $self->{salesman_name} = $login
 
1589       if ($self->{salesman_name} eq "");
 
1591     map({ $self->{"salesman_$_"} =~ s/\\n/\n/g; } qw(address company));
 
1594   $main::lxdebug->leave_sub();
 
1598   $main::lxdebug->enter_sub();
 
1600   my ($self, $myconfig) = @_;
 
1602   my $dbh = $self->get_standard_dbh($myconfig);
 
1603   my $query = qq|SELECT current_date + terms_netto FROM payment_terms WHERE id = ?|;
 
1604   ($self->{duedate}) = selectrow_query($self, $dbh, $query, $self->{payment_id});
 
1606   $main::lxdebug->leave_sub();
 
1610   $main::lxdebug->enter_sub();
 
1612   my ($self, $dbh, $id, $key) = @_;
 
1614   $key = "all_contacts" unless ($key);
 
1617     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
 
1618     qq|FROM contacts | .
 
1619     qq|WHERE cp_cv_id = ? | .
 
1620     qq|ORDER BY lower(cp_name)|;
 
1622   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
 
1624   $main::lxdebug->leave_sub();
 
1628   $main::lxdebug->enter_sub();
 
1630   my ($self, $dbh, $key) = @_;
 
1632   my ($all, $old_id, $where, @values);
 
1634   if (ref($key) eq "HASH") {
 
1637     $key = "ALL_PROJECTS";
 
1639     foreach my $p (keys(%{$params})) {
 
1641         $all = $params->{$p};
 
1642       } elsif ($p eq "old_id") {
 
1643         $old_id = $params->{$p};
 
1644       } elsif ($p eq "key") {
 
1645         $key = $params->{$p};
 
1651     $where = "WHERE active ";
 
1653       if (ref($old_id) eq "ARRAY") {
 
1654         my @ids = grep({ $_ } @{$old_id});
 
1656           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
 
1657           push(@values, @ids);
 
1660         $where .= " OR (id = ?) ";
 
1661         push(@values, $old_id);
 
1667     qq|SELECT id, projectnumber, description, active | .
 
1670     qq|ORDER BY lower(projectnumber)|;
 
1672   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
 
1674   $main::lxdebug->leave_sub();
 
1678   $main::lxdebug->enter_sub();
 
1680   my ($self, $dbh, $vc_id, $key) = @_;
 
1682   $key = "all_shipto" unless ($key);
 
1684   # get shipping addresses
 
1685   my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
 
1687   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
 
1689   $main::lxdebug->leave_sub();
 
1693   $main::lxdebug->enter_sub();
 
1695   my ($self, $dbh, $key) = @_;
 
1697   $key = "all_printers" unless ($key);
 
1699   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
 
1701   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1703   $main::lxdebug->leave_sub();
 
1707   $main::lxdebug->enter_sub();
 
1709   my ($self, $dbh, $params) = @_;
 
1711   $key = $params->{key};
 
1712   $key = "all_charts" unless ($key);
 
1714   my $transdate = quote_db_date($params->{transdate});
 
1717     qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
 
1719     qq|LEFT JOIN taxkeys tk ON | .
 
1720     qq|(tk.id = (SELECT id FROM taxkeys | .
 
1721     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
 
1722     qq|          ORDER BY startdate DESC LIMIT 1)) | .
 
1723     qq|ORDER BY c.accno|;
 
1725   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1727   $main::lxdebug->leave_sub();
 
1730 sub _get_taxcharts {
 
1731   $main::lxdebug->enter_sub();
 
1733   my ($self, $dbh, $key) = @_;
 
1735   $key = "all_taxcharts" unless ($key);
 
1737   my $query = qq|SELECT * FROM tax ORDER BY taxkey|;
 
1739   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1741   $main::lxdebug->leave_sub();
 
1745   $main::lxdebug->enter_sub();
 
1747   my ($self, $dbh, $key) = @_;
 
1749   $key = "all_taxzones" unless ($key);
 
1751   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
 
1753   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1755   $main::lxdebug->leave_sub();
 
1758 sub _get_employees {
 
1759   $main::lxdebug->enter_sub();
 
1761   my ($self, $dbh, $default_key, $key) = @_;
 
1763   $key = $default_key unless ($key);
 
1764   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY name|);
 
1766   $main::lxdebug->leave_sub();
 
1769 sub _get_business_types {
 
1770   $main::lxdebug->enter_sub();
 
1772   my ($self, $dbh, $key) = @_;
 
1774   $key = "all_business_types" unless ($key);
 
1776     selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
 
1778   $main::lxdebug->leave_sub();
 
1781 sub _get_languages {
 
1782   $main::lxdebug->enter_sub();
 
1784   my ($self, $dbh, $key) = @_;
 
1786   $key = "all_languages" unless ($key);
 
1788   my $query = qq|SELECT * FROM language ORDER BY id|;
 
1790   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1792   $main::lxdebug->leave_sub();
 
1795 sub _get_dunning_configs {
 
1796   $main::lxdebug->enter_sub();
 
1798   my ($self, $dbh, $key) = @_;
 
1800   $key = "all_dunning_configs" unless ($key);
 
1802   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
 
1804   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1806   $main::lxdebug->leave_sub();
 
1809 sub _get_currencies {
 
1810 $main::lxdebug->enter_sub();
 
1812   my ($self, $dbh, $key) = @_;
 
1814   $key = "all_currencies" unless ($key);
 
1816   my $query = qq|SELECT curr AS currency FROM defaults|;
 
1818   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
 
1820   $main::lxdebug->leave_sub();
 
1824 $main::lxdebug->enter_sub();
 
1826   my ($self, $dbh, $key) = @_;
 
1828   $key = "all_payments" unless ($key);
 
1830   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
 
1832   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1834   $main::lxdebug->leave_sub();
 
1837 sub _get_customers {
 
1838   $main::lxdebug->enter_sub();
 
1840   my ($self, $dbh, $key) = @_;
 
1842   $key = "all_customers" unless ($key);
 
1844   my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name|;
 
1846   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1848   $main::lxdebug->leave_sub();
 
1852   $main::lxdebug->enter_sub();
 
1854   my ($self, $dbh, $key) = @_;
 
1856   $key = "all_vendors" unless ($key);
 
1858   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
 
1860   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1862   $main::lxdebug->leave_sub();
 
1865 sub _get_departments {
 
1866   $main::lxdebug->enter_sub();
 
1868   my ($self, $dbh, $key) = @_;
 
1870   $key = "all_departments" unless ($key);
 
1872   my $query = qq|SELECT * FROM department ORDER BY description|;
 
1874   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
 
1876   $main::lxdebug->leave_sub();
 
1880   $main::lxdebug->enter_sub();
 
1885   my $dbh = $self->get_standard_dbh(\%main::myconfig);
 
1886   my ($sth, $query, $ref);
 
1888   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
 
1889   my $vc_id = $self->{"${vc}_id"};
 
1891   if ($params{"contacts"}) {
 
1892     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
 
1895   if ($params{"shipto"}) {
 
1896     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
 
1899   if ($params{"projects"} || $params{"all_projects"}) {
 
1900     $self->_get_projects($dbh, $params{"all_projects"} ?
 
1901                          $params{"all_projects"} : $params{"projects"},
 
1902                          $params{"all_projects"} ? 1 : 0);
 
1905   if ($params{"printers"}) {
 
1906     $self->_get_printers($dbh, $params{"printers"});
 
1909   if ($params{"languages"}) {
 
1910     $self->_get_languages($dbh, $params{"languages"});
 
1913   if ($params{"charts"}) {
 
1914     $self->_get_charts($dbh, $params{"charts"});
 
1917   if ($params{"taxcharts"}) {
 
1918     $self->_get_taxcharts($dbh, $params{"taxcharts"});
 
1921   if ($params{"taxzones"}) {
 
1922     $self->_get_taxzones($dbh, $params{"taxzones"});
 
1925   if ($params{"employees"}) {
 
1926     $self->_get_employees($dbh, "all_employees", $params{"employees"});
 
1929   if ($params{"salesmen"}) {
 
1930     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
 
1933   if ($params{"business_types"}) {
 
1934     $self->_get_business_types($dbh, $params{"business_types"});
 
1937   if ($params{"dunning_configs"}) {
 
1938     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
 
1941   if($params{"currencies"}) {
 
1942     $self->_get_currencies($dbh, $params{"currencies"});
 
1945   if($params{"customers"}) {
 
1946     $self->_get_customers($dbh, $params{"customers"});
 
1949   if($params{"vendors"}) {
 
1950     $self->_get_vendors($dbh, $params{"vendors"});
 
1953   if($params{"payments"}) {
 
1954     $self->_get_payments($dbh, $params{"payments"});
 
1957   if($params{"departments"}) {
 
1958     $self->_get_departments($dbh, $params{"departments"});
 
1961   $main::lxdebug->leave_sub();
 
1964 # this sub gets the id and name from $table
 
1966   $main::lxdebug->enter_sub();
 
1968   my ($self, $myconfig, $table) = @_;
 
1970   # connect to database
 
1971   my $dbh = $self->get_standard_dbh($myconfig);
 
1973   $table = $table eq "customer" ? "customer" : "vendor";
 
1974   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
 
1976   my ($query, @values);
 
1978   if (!$self->{openinvoices}) {
 
1980     if ($self->{customernumber} ne "") {
 
1981       $where = qq|(vc.customernumber ILIKE ?)|;
 
1982       push(@values, '%' . $self->{customernumber} . '%');
 
1984       $where = qq|(vc.name ILIKE ?)|;
 
1985       push(@values, '%' . $self->{$table} . '%');
 
1989       qq~SELECT vc.id, vc.name,
 
1990            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
1992          WHERE $where AND (NOT vc.obsolete)
 
1996       qq~SELECT DISTINCT vc.id, vc.name,
 
1997            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
 
1999          JOIN $table vc ON (a.${table}_id = vc.id)
 
2000          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
 
2002     push(@values, '%' . $self->{$table} . '%');
 
2005   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
 
2007   $main::lxdebug->leave_sub();
 
2009   return scalar(@{ $self->{name_list} });
 
2012 # the selection sub is used in the AR, AP, IS, IR and OE module
 
2015   $main::lxdebug->enter_sub();
 
2017   my ($self, $myconfig, $table, $module) = @_;
 
2020   my $dbh = $self->get_standard_dbh($myconfig);
 
2022   $table = $table eq "customer" ? "customer" : "vendor";
 
2024   my $query = qq|SELECT count(*) FROM $table|;
 
2025   my ($count) = selectrow_query($self, $dbh, $query);
 
2027   # build selection list
 
2028   if ($count < $myconfig->{vclimit}) {
 
2029     $query = qq|SELECT id, name, salesman_id
 
2030                 FROM $table WHERE NOT obsolete
 
2032     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
 
2036   $self->get_employee($dbh);
 
2038   # setup sales contacts
 
2039   $query = qq|SELECT e.id, e.name
 
2041               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
 
2042   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
 
2045   push(@{ $self->{all_employees} },
 
2046        { id   => $self->{employee_id},
 
2047          name => $self->{employee} });
 
2049   # sort the whole thing
 
2050   @{ $self->{all_employees} } =
 
2051     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
 
2053   if ($module eq 'AR') {
 
2055     # prepare query for departments
 
2056     $query = qq|SELECT id, description
 
2059                 ORDER BY description|;
 
2062     $query = qq|SELECT id, description
 
2064                 ORDER BY description|;
 
2067   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2070   $query = qq|SELECT id, description
 
2074   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2077   $query = qq|SELECT printer_description, id
 
2079               ORDER BY printer_description|;
 
2081   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2084   $query = qq|SELECT id, description
 
2088   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
2090   $main::lxdebug->leave_sub();
 
2093 sub language_payment {
 
2094   $main::lxdebug->enter_sub();
 
2096   my ($self, $myconfig) = @_;
 
2098   my $dbh = $self->get_standard_dbh($myconfig);
 
2100   my $query = qq|SELECT id, description
 
2104   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
 
2107   $query = qq|SELECT printer_description, id
 
2109               ORDER BY printer_description|;
 
2111   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
 
2114   $query = qq|SELECT id, description
 
2118   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
2120   # get buchungsgruppen
 
2121   $query = qq|SELECT id, description
 
2122               FROM buchungsgruppen|;
 
2124   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
 
2126   $main::lxdebug->leave_sub();
 
2129 # this is only used for reports
 
2130 sub all_departments {
 
2131   $main::lxdebug->enter_sub();
 
2133   my ($self, $myconfig, $table) = @_;
 
2135   my $dbh = $self->get_standard_dbh($myconfig);
 
2138   if ($table eq 'customer') {
 
2139     $where = "WHERE role = 'P' ";
 
2142   my $query = qq|SELECT id, description
 
2145                  ORDER BY description|;
 
2146   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
 
2148   delete($self->{all_departments}) unless (@{ $self->{all_departments} });
 
2150   $main::lxdebug->leave_sub();
 
2154   $main::lxdebug->enter_sub();
 
2156   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
 
2159   if ($table eq "customer") {
 
2168   $self->all_vc($myconfig, $table, $module);
 
2170   # get last customers or vendors
 
2171   my ($query, $sth, $ref);
 
2173   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
 
2178     my $transdate = "current_date";
 
2179     if ($self->{transdate}) {
 
2180       $transdate = $dbh->quote($self->{transdate});
 
2183     # now get the account numbers
 
2184     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
 
2185                 FROM chart c, taxkeys tk
 
2186                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
 
2187                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
 
2190     $sth = $dbh->prepare($query);
 
2192     do_statement($self, $sth, $query, '%' . $module . '%');
 
2194     $self->{accounts} = "";
 
2195     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
2197       foreach my $key (split(/:/, $ref->{link})) {
 
2198         if ($key =~ /$module/) {
 
2200           # cross reference for keys
 
2201           $xkeyref{ $ref->{accno} } = $key;
 
2203           push @{ $self->{"${module}_links"}{$key} },
 
2204             { accno       => $ref->{accno},
 
2205               description => $ref->{description},
 
2206               taxkey      => $ref->{taxkey_id},
 
2207               tax_id      => $ref->{tax_id} };
 
2209           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2215   # get taxkeys and description
 
2216   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
 
2217   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
 
2219   if (($module eq "AP") || ($module eq "AR")) {
 
2220     # get tax rates and description
 
2221     $query = qq|SELECT * FROM tax|;
 
2222     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
 
2228            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
 
2229            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
 
2230            a.intnotes, a.department_id, a.amount AS oldinvtotal,
 
2231            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
 
2233            d.description AS department,
 
2236          JOIN $table c ON (a.${table}_id = c.id)
 
2237          LEFT JOIN employee e ON (e.id = a.employee_id)
 
2238          LEFT JOIN department d ON (d.id = a.department_id)
 
2240     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
 
2242     foreach $key (keys %$ref) {
 
2243       $self->{$key} = $ref->{$key};
 
2246     my $transdate = "current_date";
 
2247     if ($self->{transdate}) {
 
2248       $transdate = $dbh->quote($self->{transdate});
 
2251     # now get the account numbers
 
2252     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
 
2254                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
 
2256                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
 
2257                     OR c.link LIKE '%_tax%')
 
2260     $sth = $dbh->prepare($query);
 
2261     do_statement($self, $sth, $query, "%$module%");
 
2263     $self->{accounts} = "";
 
2264     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
2266       foreach my $key (split(/:/, $ref->{link})) {
 
2267         if ($key =~ /$module/) {
 
2269           # cross reference for keys
 
2270           $xkeyref{ $ref->{accno} } = $key;
 
2272           push @{ $self->{"${module}_links"}{$key} },
 
2273             { accno       => $ref->{accno},
 
2274               description => $ref->{description},
 
2275               taxkey      => $ref->{taxkey_id},
 
2276               tax_id      => $ref->{tax_id} };
 
2278           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
2284     # get amounts from individual entries
 
2287            c.accno, c.description,
 
2288            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
 
2292          LEFT JOIN chart c ON (c.id = a.chart_id)
 
2293          LEFT JOIN project p ON (p.id = a.project_id)
 
2294          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
 
2295                                     WHERE (tk.taxkey_id=a.taxkey) AND
 
2296                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
 
2297                                         THEN tk.chart_id = a.chart_id
 
2300                                        OR (c.link='%tax%')) AND
 
2301                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
 
2302          WHERE a.trans_id = ?
 
2303          AND a.fx_transaction = '0'
 
2304          ORDER BY a.oid, a.transdate|;
 
2305     $sth = $dbh->prepare($query);
 
2306     do_statement($self, $sth, $query, $self->{id});
 
2308     # get exchangerate for currency
 
2309     $self->{exchangerate} =
 
2310       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2313     # store amounts in {acc_trans}{$key} for multiple accounts
 
2314     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
2315       $ref->{exchangerate} =
 
2316         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
 
2317       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
 
2320       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
 
2321         $ref->{amount} *= -1;
 
2323       $ref->{index} = $index;
 
2325       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
 
2331            d.curr AS currencies, d.closedto, d.revtrans,
 
2332            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2333            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
2335     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2336     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2343             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
 
2344             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
2345             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
2347     $ref = selectfirst_hashref_query($self, $dbh, $query);
 
2348     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
2350     if ($self->{"$self->{vc}_id"}) {
 
2352       # only setup currency
 
2353       ($self->{currency}) = split(/:/, $self->{currencies});
 
2357       $self->lastname_used($dbh, $myconfig, $table, $module);
 
2359       # get exchangerate for currency
 
2360       $self->{exchangerate} =
 
2361         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
 
2367   $main::lxdebug->leave_sub();
 
2371   $main::lxdebug->enter_sub();
 
2373   my ($self, $dbh, $myconfig, $table, $module) = @_;
 
2375   my $arap  = ($table eq 'customer') ? "ar" : "ap";
 
2376   $table = $table eq "customer" ? "customer" : "vendor";
 
2377   my $where = "1 = 1";
 
2379   if ($self->{type} =~ /_order/) {
 
2381     $where = "quotation = '0'";
 
2383   if ($self->{type} =~ /_quotation/) {
 
2385     $where = "quotation = '1'";
 
2388   my $query = qq|SELECT MAX(id) FROM $arap
 
2389                  WHERE $where AND ${table}_id > 0|;
 
2390   my ($trans_id) = selectrow_query($self, $dbh, $query);
 
2395          a.curr, a.${table}_id, a.department_id,
 
2396          d.description AS department,
 
2397          ct.name, current_date + ct.terms AS duedate
 
2399        LEFT JOIN $table ct ON (a.${table}_id = ct.id)
 
2400        LEFT JOIN department d ON (a.department_id = d.id)
 
2402   ($self->{currency},   $self->{"${table}_id"}, $self->{department_id},
 
2403    $self->{department}, $self->{$table},        $self->{duedate})
 
2404     = selectrow_query($self, $dbh, $query, $trans_id);
 
2406   $main::lxdebug->leave_sub();
 
2410   $main::lxdebug->enter_sub();
 
2412   my ($self, $myconfig, $thisdate, $days) = @_;
 
2414   my $dbh = $self->get_standard_dbh($myconfig);
 
2419     my $dateformat = $myconfig->{dateformat};
 
2420     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
 
2421     $thisdate = $dbh->quote($thisdate);
 
2422     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
 
2424     $query = qq|SELECT current_date AS thisdate|;
 
2427   ($thisdate) = selectrow_query($self, $dbh, $query);
 
2429   $main::lxdebug->leave_sub();
 
2435   $main::lxdebug->enter_sub();
 
2437   my ($self, $string) = @_;
 
2439   if ($string !~ /%/) {
 
2440     $string = "%$string%";
 
2443   $string =~ s/\'/\'\'/g;
 
2445   $main::lxdebug->leave_sub();
 
2451   $main::lxdebug->enter_sub();
 
2453   my ($self, $flds, $new, $count, $numrows) = @_;
 
2457   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } }
 
2463   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
 
2465     $j = $item->{ndx} - 1;
 
2466     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
 
2470   for $i ($count + 1 .. $numrows) {
 
2471     map { delete $self->{"${_}_$i"} } @{$flds};
 
2474   $main::lxdebug->leave_sub();
 
2478   $main::lxdebug->enter_sub();
 
2480   my ($self, $myconfig) = @_;
 
2484   my $dbh = $self->dbconnect_noauto($myconfig);
 
2486   my $query = qq|DELETE FROM status
 
2487                  WHERE (formname = ?) AND (trans_id = ?)|;
 
2488   my $sth = prepare_query($self, $dbh, $query);
 
2490   if ($self->{formname} =~ /(check|receipt)/) {
 
2491     for $i (1 .. $self->{rowcount}) {
 
2492       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
 
2495     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
 
2499   my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
 
2500   my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
 
2502   my %queued = split / /, $self->{queued};
 
2505   if ($self->{formname} =~ /(check|receipt)/) {
 
2507     # this is a check or receipt, add one entry for each lineitem
 
2508     my ($accno) = split /--/, $self->{account};
 
2509     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
 
2510                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
 
2511     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
 
2512     $sth = prepare_query($self, $dbh, $query);
 
2514     for $i (1 .. $self->{rowcount}) {
 
2515       if ($self->{"checked_$i"}) {
 
2516         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
 
2522     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
2523                 VALUES (?, ?, ?, ?, ?)|;
 
2524     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
 
2525              $queued{$self->{formname}}, $self->{formname});
 
2531   $main::lxdebug->leave_sub();
 
2535   $main::lxdebug->enter_sub();
 
2537   my ($self, $dbh) = @_;
 
2539   my ($query, $printed, $emailed);
 
2541   my $formnames  = $self->{printed};
 
2542   my $emailforms = $self->{emailed};
 
2544   my $query = qq|DELETE FROM status
 
2545                  WHERE (formname = ?) AND (trans_id = ?)|;
 
2546   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
 
2548   # this only applies to the forms
 
2549   # checks and receipts are posted when printed or queued
 
2551   if ($self->{queued}) {
 
2552     my %queued = split / /, $self->{queued};
 
2554     foreach my $formname (keys %queued) {
 
2555       $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
 
2556       $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
 
2558       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
 
2559                   VALUES (?, ?, ?, ?, ?)|;
 
2560       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
 
2562       $formnames  =~ s/$self->{formname}//;
 
2563       $emailforms =~ s/$self->{formname}//;
 
2568   # save printed, emailed info
 
2569   $formnames  =~ s/^ +//g;
 
2570   $emailforms =~ s/^ +//g;
 
2573   map { $status{$_}{printed} = 1 } split / +/, $formnames;
 
2574   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
 
2576   foreach my $formname (keys %status) {
 
2577     $printed = ($formnames  =~ /$self->{formname}/) ? "1" : "0";
 
2578     $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
 
2580     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
 
2581                 VALUES (?, ?, ?, ?)|;
 
2582     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
 
2585   $main::lxdebug->leave_sub();
 
2589 # $main::locale->text('SAVED')
 
2590 # $main::locale->text('DELETED')
 
2591 # $main::locale->text('ADDED')
 
2592 # $main::locale->text('PAYMENT POSTED')
 
2593 # $main::locale->text('POSTED')
 
2594 # $main::locale->text('POSTED AS NEW')
 
2595 # $main::locale->text('ELSE')
 
2596 # $main::locale->text('SAVED FOR DUNNING')
 
2597 # $main::locale->text('DUNNING STARTED')
 
2598 # $main::locale->text('PRINTED')
 
2599 # $main::locale->text('MAILED')
 
2600 # $main::locale->text('SCREENED')
 
2601 # $main::locale->text('CANCELED')
 
2602 # $main::locale->text('invoice')
 
2603 # $main::locale->text('proforma')
 
2604 # $main::locale->text('sales_order')
 
2605 # $main::locale->text('packing_list')
 
2606 # $main::locale->text('pick_list')
 
2607 # $main::locale->text('purchase_order')
 
2608 # $main::locale->text('bin_list')
 
2609 # $main::locale->text('sales_quotation')
 
2610 # $main::locale->text('request_quotation')
 
2613   $main::lxdebug->enter_sub();
 
2618   if(!exists $self->{employee_id}) {
 
2619     &get_employee($self, $dbh);
 
2623    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
 
2624    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
 
2625   my @values = (conv_i($self->{id}), $self->{login},
 
2626                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
 
2627   do_query($self, $dbh, $query, @values);
 
2629   $main::lxdebug->leave_sub();
 
2633   $main::lxdebug->enter_sub();
 
2635   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
 
2636   my ($orderBy, $desc) = split(/\-\-/, $order);
 
2637   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
 
2640   if ($trans_id ne "") {
 
2642       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 | .
 
2643       qq|FROM history_erp h | .
 
2644       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
 
2645       qq|WHERE trans_id = | . $trans_id
 
2646       . $restriction . qq| |
 
2649     my $sth = $dbh->prepare($query) || $self->dberror($query);
 
2651     $sth->execute() || $self->dberror("$query");
 
2653     while(my $hash_ref = $sth->fetchrow_hashref()) {
 
2654       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
 
2655       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
 
2656       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
 
2657       $tempArray[$i++] = $hash_ref;
 
2659     $main::lxdebug->leave_sub() and return \@tempArray 
 
2660       if ($i > 0 && $tempArray[0] ne "");
 
2662   $main::lxdebug->leave_sub();
 
2666 sub update_defaults {
 
2667   $main::lxdebug->enter_sub();
 
2669   my ($self, $myconfig, $fld, $provided_dbh) = @_;
 
2672   if ($provided_dbh) {
 
2673     $dbh = $provided_dbh;
 
2675     $dbh = $self->dbconnect_noauto($myconfig);
 
2677   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
 
2678   my $sth   = $dbh->prepare($query);
 
2680   $sth->execute || $self->dberror($query);
 
2681   my ($var) = $sth->fetchrow_array;
 
2684   if ($var =~ m/\d+$/) {
 
2685     my $new_var  = (substr $var, $-[0]) * 1 + 1;
 
2686     my $len_diff = length($var) - $-[0] - length($new_var);
 
2687     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
 
2693   $query = qq|UPDATE defaults SET $fld = ?|;
 
2694   do_query($self, $dbh, $query, $var);
 
2696   if (!$provided_dbh) {
 
2701   $main::lxdebug->leave_sub();
 
2706 sub update_business {
 
2707   $main::lxdebug->enter_sub();
 
2709   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
 
2712   if ($provided_dbh) {
 
2713     $dbh = $provided_dbh;
 
2715     $dbh = $self->dbconnect_noauto($myconfig);
 
2718     qq|SELECT customernumberinit FROM business
 
2719        WHERE id = ? FOR UPDATE|;
 
2720   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
 
2722   if ($var =~ m/\d+$/) {
 
2723     my $new_var  = (substr $var, $-[0]) * 1 + 1;
 
2724     my $len_diff = length($var) - $-[0] - length($new_var);
 
2725     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
 
2731   $query = qq|UPDATE business
 
2732               SET customernumberinit = ?
 
2734   do_query($self, $dbh, $query, $var, $business_id);
 
2736   if (!$provided_dbh) {
 
2741   $main::lxdebug->leave_sub();
 
2746 sub get_partsgroup {
 
2747   $main::lxdebug->enter_sub();
 
2749   my ($self, $myconfig, $p) = @_;
 
2751   my $dbh = $self->get_standard_dbh($myconfig);
 
2753   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
 
2755                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
 
2758   if ($p->{searchitems} eq 'part') {
 
2759     $query .= qq|WHERE p.inventory_accno_id > 0|;
 
2761   if ($p->{searchitems} eq 'service') {
 
2762     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
 
2764   if ($p->{searchitems} eq 'assembly') {
 
2765     $query .= qq|WHERE p.assembly = '1'|;
 
2767   if ($p->{searchitems} eq 'labor') {
 
2768     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
 
2771   $query .= qq|ORDER BY partsgroup|;
 
2774     $query = qq|SELECT id, partsgroup FROM partsgroup
 
2775                 ORDER BY partsgroup|;
 
2778   if ($p->{language_code}) {
 
2779     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
 
2780                   t.description AS translation
 
2782                 JOIN parts p ON (p.partsgroup_id = pg.id)
 
2783                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
 
2784                 ORDER BY translation|;
 
2785     @values = ($p->{language_code});
 
2788   $self->{all_partsgroup} = selectall_hashref_query($self, $dbh, $query, @values);
 
2790   $main::lxdebug->leave_sub();
 
2793 sub get_pricegroup {
 
2794   $main::lxdebug->enter_sub();
 
2796   my ($self, $myconfig, $p) = @_;
 
2798   my $dbh = $self->get_standard_dbh($myconfig);
 
2800   my $query = qq|SELECT p.id, p.pricegroup
 
2803   $query .= qq| ORDER BY pricegroup|;
 
2806     $query = qq|SELECT id, pricegroup FROM pricegroup
 
2807                 ORDER BY pricegroup|;
 
2810   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
 
2812   $main::lxdebug->leave_sub();
 
2816 # usage $form->all_years($myconfig, [$dbh])
 
2817 # return list of all years where bookings found
 
2820   $main::lxdebug->enter_sub();
 
2822   my ($self, $myconfig, $dbh) = @_;
 
2824   $dbh ||= $self->get_standard_dbh($myconfig);
 
2827   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
 
2828                    (SELECT MAX(transdate) FROM acc_trans)|;
 
2829   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
 
2831   if ($myconfig->{dateformat} =~ /^yy/) {
 
2832     ($startdate) = split /\W/, $startdate;
 
2833     ($enddate) = split /\W/, $enddate;
 
2835     (@_) = split /\W/, $startdate;
 
2837     (@_) = split /\W/, $enddate;
 
2842   $startdate = substr($startdate,0,4);
 
2843   $enddate = substr($enddate,0,4);
 
2845   while ($enddate >= $startdate) {
 
2846     push @all_years, $enddate--;
 
2851   $main::lxdebug->leave_sub();