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 #======================================================================
 
  43   $main::lxdebug->enter_sub();
 
  47   my @pairs = split(/&/, $input);
 
  50     my ($name, $value) = split(/=/, $_, 2);
 
  51     $in{$name} = unescape(undef, $value);
 
  54   $main::lxdebug->leave_sub();
 
  59 sub _request_to_hash {
 
  60   $main::lxdebug->enter_sub();
 
  63   my ($i,        $loc,  $key,    $val);
 
  64   my (%ATTACH,   $f,    $header, $header_body, $len, $buf);
 
  65   my ($boundary, @list, $size,   $body, $x, $blah, $name);
 
  67   if ($ENV{'CONTENT_TYPE'}
 
  68       && ($ENV{'CONTENT_TYPE'} =~ /multipart\/form-data; boundary=(.+)$/)) {
 
  69     $boundary = quotemeta('--' . $1);
 
  70     @list     = split(/$boundary/, $input);
 
  72     # For some reason there are always 2 extra, that are empty
 
  75     for ($x = 1; $x <= $size; $x++) {
 
  76       $header_body = $list[$x];
 
  77       $header_body =~ /\r\n\r\n|\n\n/;
 
  79       # Here we split the header and body
 
  84       # Now we try to get the file name
 
  86       $name =~ /name=\"(.+)\"/;
 
  87       ($name, $blah) = split(/\"/, $1);
 
  89       # If the form name is not attach, then we need to parse this like
 
  91       if ($name ne "attach") {
 
  92         $body =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
 
  93         $ATTACH{$name} = $body;
 
  95         # Otherwise it is an attachment and we need to finish it up
 
  96       } elsif ($name eq "attach") {
 
  97         $header =~ /filename=\"(.+)\"/;
 
  98         $ATTACH{'FILE_NAME'} = $1;
 
  99         $ATTACH{'FILE_NAME'} =~ s/\"//g;
 
 100         $ATTACH{'FILE_NAME'} =~ s/\s//g;
 
 101         $ATTACH{'FILE_CONTENT'} = $body;
 
 103         for ($i = $x; $list[$i]; $i++) {
 
 104           $list[$i] =~ s/^.+name=$//;
 
 105           $list[$i] =~ /\"(\w+)\"/;
 
 111     $main::lxdebug->leave_sub();
 
 115     $main::lxdebug->leave_sub();
 
 116     return _input_to_hash($input);
 
 121   $main::lxdebug->enter_sub();
 
 127   read(STDIN, $_, $ENV{CONTENT_LENGTH});
 
 129   if ($ENV{QUERY_STRING}) {
 
 130     $_ = $ENV{QUERY_STRING};
 
 137   my %parameters = _request_to_hash($_);
 
 138   map({ $self->{$_} = $parameters{$_}; } keys(%parameters));
 
 140   $self->{menubar} = 1 if $self->{path} =~ /lynx/i;
 
 142   $self->{action} = lc $self->{action};
 
 143   $self->{action} =~ s/( |-|,|#)/_/g;
 
 145   $self->{version}   = "2.2.0";
 
 147   $main::lxdebug->leave_sub();
 
 153   $main::lxdebug->enter_sub();
 
 159   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
 
 161   $main::lxdebug->leave_sub();
 
 165   $main::lxdebug->enter_sub();
 
 167   my ($self, $str, $beenthere) = @_;
 
 169   # for Apache 2 we escape strings twice
 
 170   #if (($ENV{SERVER_SOFTWARE} =~ /Apache\/2/) && !$beenthere) {
 
 171   #  $str = $self->escape($str, 1);
 
 174   $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
 
 176   $main::lxdebug->leave_sub();
 
 182   $main::lxdebug->enter_sub();
 
 184   my ($self, $str) = @_;
 
 189   $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
 
 191   $main::lxdebug->leave_sub();
 
 197   my ($self, $str) = @_;
 
 199   if ($str && !ref($str)) {
 
 200     $str =~ s/\"/"/g;
 
 208   my ($self, $str) = @_;
 
 210   if ($str && !ref($str)) {
 
 211     $str =~ s/"/\"/g;
 
 223       print qq|<input type=hidden name="$_" value="|
 
 224         . $self->quote($self->{$_})
 
 228     delete $self->{header};
 
 229     for (sort keys %$self) {
 
 230       print qq|<input type=hidden name="$_" value="|
 
 231         . $self->quote($self->{$_})
 
 239   $main::lxdebug->enter_sub();
 
 241   my ($self, $msg) = @_;
 
 243   if ($ENV{HTTP_USER_AGENT}) {
 
 247     $self->show_generic_error($msg);
 
 253     if ($self->{error_function}) {
 
 254       &{ $self->{error_function} }($msg);
 
 260   $main::lxdebug->leave_sub();
 
 264   $main::lxdebug->enter_sub();
 
 266   my ($self, $msg) = @_;
 
 268   if ($ENV{HTTP_USER_AGENT}) {
 
 271     if (!$self->{header}) {
 
 284     if ($self->{info_function}) {
 
 285       &{ $self->{info_function} }($msg);
 
 291   $main::lxdebug->leave_sub();
 
 295   $main::lxdebug->enter_sub();
 
 297   my ($self, $str, $cols, $maxrows) = @_;
 
 301   map { $rows += int(((length) - 2) / $cols) + 1 } split /\r/, $str;
 
 303   $maxrows = $rows unless defined $maxrows;
 
 305   $main::lxdebug->leave_sub();
 
 307   return ($rows > $maxrows) ? $maxrows : $rows;
 
 311   $main::lxdebug->enter_sub();
 
 313   my ($self, $msg) = @_;
 
 315   $self->error("$msg\n" . $DBI::errstr);
 
 317   $main::lxdebug->leave_sub();
 
 321   $main::lxdebug->enter_sub();
 
 323   my ($self, $name, $msg) = @_;
 
 325   if ($self->{$name} =~ /^\s*$/) {
 
 328   $main::lxdebug->leave_sub();
 
 332   $main::lxdebug->enter_sub();
 
 336   if ($self->{header}) {
 
 337     $main::lxdebug->leave_sub();
 
 341   my ($stylesheet, $favicon, $charset);
 
 343   if ($ENV{HTTP_USER_AGENT}) {
 
 345     if ($self->{stylesheet} && (-f "css/$self->{stylesheet}")) {
 
 347         qq|<LINK REL="stylesheet" HREF="css/$self->{stylesheet}" TYPE="text/css" TITLE="Lx-Office stylesheet">
 
 351     if ($self->{favicon} && (-f "$self->{favicon}")) {
 
 353         qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
 
 357     if ($self->{charset}) {
 
 359         qq|<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=$self->{charset}">
 
 362     if ($self->{landscape}) {
 
 363       $pagelayout = qq|<style type="text/css">
 
 364                         \@page { size:landscape; }
 
 367     if ($self->{fokus}) {
 
 368       $fokus = qq|<script type="text/javascript">
 
 370 function fokus(){document.$self->{fokus}.focus();}
 
 377     if ($self->{jsscript} == 1) {
 
 380         <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
 
 381         <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
 
 382         <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
 
 383         <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
 
 390       ? "$self->{title} - $self->{titlebar}"
 
 393     print qq|Content-Type: text/html
 
 397   <title>$self->{titlebar}</title>
 
 410   $main::lxdebug->leave_sub();
 
 414 sub parse_html_template {
 
 415   $main::lxdebug->enter_sub();
 
 417   my ($self, $file, $additional_params) = @_;
 
 420   if (!defined($main::myconfig) || !defined($main::myconfig{"countrycode"})) {
 
 421     $language = $main::language;
 
 423     $language = $main::myconfig{"countrycode"};
 
 426   if (-f "templates/webpages/${file}_${language}.html") {
 
 427     if ((-f ".developer") &&
 
 428         (-f "templates/webpages/${file}_master.html") &&
 
 429         ((stat("templates/webpages/${file}_master.html"))[9] >
 
 430          (stat("templates/webpages/${file}_${language}.html"))[9])) {
 
 431       my $info = "Developper information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
 
 432         "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 433       print(qq|<pre>$info</pre>|);
 
 437     $file = "templates/webpages/${file}_${language}.html";
 
 438   } elsif (-f "templates/webpages/${file}.html") {
 
 439     $file = "templates/webpages/${file}.html";
 
 441     my $info = "Web page template '${file}' not found.\n" .
 
 442       "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 443     print(qq|<pre>$info</pre>|);
 
 447   my $template = HTML::Template->new("filename" => $file,
 
 448                                      "die_on_bad_params" => 0,
 
 450                                      "case_sensitive" => 1,
 
 451                                      "loop_context_vars" => 1,
 
 454   $additional_params = {} unless ($additional_params);
 
 455   if ($self->{"DEBUG"}) {
 
 456     $additional_params->{"DEBUG"} = $self->{"DEBUG"};
 
 459   if ($additional_params->{"DEBUG"}) {
 
 460     $additional_params->{"DEBUG"} =
 
 461       "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
 
 464   my @additional_param_names = keys(%{$additional_params});
 
 466   foreach my $key ($template->param()) {
 
 467     if (grep(/^${key}$/, @additional_param_names)) {
 
 468       $template->param($key => $additional_params->{$key});
 
 470       $template->param($key => $self->{$key});
 
 474   my $output = $template->output();
 
 476   $main::lxdebug->leave_sub();
 
 481 sub show_generic_error {
 
 482   my ($self, $error, $title) = @_;
 
 485   $add_params->{"title"} = $title if ($title);
 
 486   $self->{"label_error"} = $error;
 
 488   print($self->parse_html_template("generic/error", $add_params));
 
 491 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
 
 492 # changed it to accept an arbitrary number of triggers - sschoeling
 
 494   $main::lxdebug->enter_sub();
 
 497   my $myconfig = shift;
 
 500   # set dateform for jsscript
 
 502   $ifFormat = "%d.%m.%Y";
 
 503   if ($myconfig->{dateformat} eq "dd.mm.yy") {
 
 504     $ifFormat = "%d.%m.%Y";
 
 506     if ($myconfig->{dateformat} eq "dd-mm-yy") {
 
 507       $ifFormat = "%d-%m-%Y";
 
 509       if ($myconfig->{dateformat} eq "dd/mm/yy") {
 
 510         $ifFormat = "%d/%m/%Y";
 
 512         if ($myconfig->{dateformat} eq "mm/dd/yy") {
 
 513           $ifFormat = "%m/%d/%Y";
 
 515           if ($myconfig->{dateformat} eq "mm-dd-yy") {
 
 516             $ifFormat = "%m-%d-%Y";
 
 518             if ($myconfig->{dateformat} eq "yyyy-mm-dd") {
 
 519               $ifFormat = "%Y-%m-%d";
 
 531       inputField : "| . (shift) . qq|",
 
 532       ifFormat :"$ifFormat",
 
 533       align : "| .  (shift) . qq|", 
 
 534       button : "| . (shift) . qq|"
 
 540        <script type="text/javascript">
 
 541        <!--| . join("", @triggers) . qq|//-->
 
 545   $main::lxdebug->leave_sub();
 
 548 }    #end sub write_trigger
 
 551   $main::lxdebug->enter_sub();
 
 553   my ($self, $msg) = @_;
 
 555   if ($self->{callback}) {
 
 557     ($script, $argv) = split(/\?/, $self->{callback});
 
 558     exec("perl", "$script", $argv);
 
 566   $main::lxdebug->leave_sub();
 
 569 # sort of columns removed - empty sub
 
 571   $main::lxdebug->enter_sub();
 
 573   my ($self, @columns) = @_;
 
 575   $main::lxdebug->leave_sub();
 
 581   $main::lxdebug->enter_sub();
 
 583   my ($self, $myconfig, $amount, $places, $dash) = @_;
 
 585   #Workaround for $format_amount calls without $places
 
 586   if (!defined $places) {
 
 587     (my $dec) = ($amount =~ /\.(\d+)/);
 
 588     $places = length $dec;
 
 591   if ($places =~ /\d/) {
 
 592     $amount = $self->round_amount($amount, $places);
 
 595   # is the amount negative
 
 596   my $negative = ($amount < 0);
 
 600     if ($myconfig->{numberformat} && ($myconfig->{numberformat} ne '1000.00'))
 
 602       my ($whole, $dec) = split /\./, "$amount";
 
 604       $amount = join '', reverse split //, $whole;
 
 605       $fillup = "0" x ($places - length($dec));
 
 607       if ($myconfig->{numberformat} eq '1,000.00') {
 
 608         $amount =~ s/\d{3,}?/$&,/g;
 
 610         $amount = join '', reverse split //, $amount;
 
 611         $amount .= "\.$dec" . $fillup if ($places ne '' && $places * 1 != 0);
 
 614       if ($myconfig->{numberformat} eq '1.000,00') {
 
 615         $amount =~ s/\d{3,}?/$&./g;
 
 617         $amount = join '', reverse split //, $amount;
 
 618         $amount .= ",$dec" . $fillup if ($places ne '' && $places * 1 != 0);
 
 621       if ($myconfig->{numberformat} eq '1000,00') {
 
 623         $amount .= ",$dec" . $fillup if ($places ne '' && $places * 1 != 0);
 
 627         $amount = ($negative) ? "($amount)" : "$amount";
 
 628       } elsif ($dash =~ /DRCR/) {
 
 629         $amount = ($negative) ? "$amount DR" : "$amount CR";
 
 631         $amount = ($negative) ? "-$amount" : "$amount";
 
 635     if ($dash eq "0" && $places) {
 
 636       if ($myconfig->{numberformat} eq '1.000,00') {
 
 637         $amount = "0" . "," . "0" x $places;
 
 639         $amount = "0" . "." . "0" x $places;
 
 642       $amount = ($dash ne "") ? "$dash" : "0";
 
 646   $main::lxdebug->leave_sub();
 
 652   $main::lxdebug->enter_sub();
 
 654   my ($self, $myconfig, $amount) = @_;
 
 655   $main::lxdebug->message(LXDebug::DEBUG2, "Start amount: $amount");
 
 657   if ($myconfig->{in_numberformat} == 1) {
 
 659     # Extra input number format 1000.00 or 1000,00
 
 660     $main::lxdebug->message(LXDebug::DEBUG2,
 
 661               "in_numberformat: " . $main::locale->text('1000,00 or 1000.00'));
 
 664     #$main::lxdebug->message(LXDebug::DEBUG2, "1.Parsed Number: $amount") if ($amount);
 
 665     $amount = scalar reverse $amount;
 
 667     #$main::lxdebug->message(LXDebug::DEBUG2, "2.Parsed Number: $amount") if ($amount);
 
 668     $amount =~ s/\./DOT/;
 
 670     #$main::lxdebug->message(LXDebug::DEBUG2, "3.Parsed Number: $amount") if ($amount);
 
 673     #$main::lxdebug->message(LXDebug::DEBUG2, "4.Parsed Number: $amount") if ($amount);
 
 674     $amount =~ s/DOT/\./;
 
 676     #$main::lxdebug->message(LXDebug::DEBUG2, "5.Parsed Number:" . $amount) if ($amount);
 
 677     $amount = scalar reverse $amount;
 
 678     $main::lxdebug->message(LXDebug::DEBUG2,
 
 679                             "Parsed amount:" . $amount . "\n");
 
 681     return ($amount * 1);
 
 684   $main::lxdebug->message(LXDebug::DEBUG2,
 
 685               "in_numberformat: " . $main::locale->text('equal Outputformat'));
 
 686   $main::lxdebug->message(LXDebug::DEBUG2,
 
 687                           " = numberformat: $myconfig->{numberformat}");
 
 688   if (   ($myconfig->{numberformat} eq '1.000,00')
 
 689       || ($myconfig->{numberformat} eq '1000,00')) {
 
 694   if ($myconfig->{numberformat} eq "1'000.00") {
 
 700   $main::lxdebug->message(LXDebug::DEBUG2, "Parsed amount:" . $amount . "\n")
 
 702   $main::lxdebug->leave_sub();
 
 704   return ($amount * 1);
 
 708   $main::lxdebug->enter_sub();
 
 710   my ($self, $amount, $places) = @_;
 
 713   # Rounding like "Kaufmannsrunden"
 
 714   # Descr. http://de.wikipedia.org/wiki/Rundung
 
 716   # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
 
 719   $amount = $amount * (10**($places));
 
 720   $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
 
 722   $main::lxdebug->leave_sub();
 
 724   return $round_amount;
 
 729   $main::lxdebug->enter_sub();
 
 731   my ($self, $myconfig, $userspath) = @_;
 
 734   # Some variables used for page breaks
 
 735   my ($chars_per_line, $lines_on_first_page, $lines_on_second_page) =
 
 737   my ($current_page, $current_line, $current_row) = (1, 1, 0);
 
 743   # Make sure that all *notes* (intnotes, partnotes_*, notes etc) are converted to markup correctly.
 
 744   $self->format_string(grep(/notes/, keys(%{$self})));
 
 746   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
 
 747   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
 
 749   map({ $self->{"employee_${_}"} = $myconfig->{$_}; }
 
 750       qw(email tel fax name signature));
 
 752   open(IN, "$self->{templates}/$self->{IN}")
 
 753     or $self->error("$self->{IN} : $!");
 
 758   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
 
 760   # OUT is used for the media, screen, printer, email
 
 761   # for postscript we store a copy in a temporary file
 
 763   $self->{tmpfile} = "$userspath/${fileid}.$self->{IN}";
 
 764   if ($self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email') {
 
 766     $self->{OUT} = ">$self->{tmpfile}";
 
 770     open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
 
 772     open(OUT, ">-") or $self->error("STDOUT : $!");
 
 776   # Do we have to run LaTeX two times? This is needed if
 
 777   # the template contains page references.
 
 780   # first we generate a tmpfile
 
 781   # read file and replace <%variable%>
 
 787     $two_passes = 1 if (/\\pageref/);
 
 790     # detect pagebreak block and its parameters
 
 791     if (/\s*<%pagebreak ([0-9]+) ([0-9]+) ([0-9]+)%>/) {
 
 792       $chars_per_line       = $1;
 
 793       $lines_on_first_page  = $2;
 
 794       $lines_on_second_page = $3;
 
 797         last if (/\s*<%end pagebreak%>/);
 
 804     if (/\s*<%foreach /) {
 
 806       # this one we need for the count
 
 808       $var =~ s/\s*<%foreach (.+?)%>/$1/;
 
 810         last if (/\s*<%end /);
 
 816       # display contents of $self->{number}[] array
 
 817       for $i (0 .. $#{ $self->{$var} }) {
 
 820         # Try to detect whether a manual page break is necessary
 
 821         # but only if there was a <%pagebreak ...%> block before
 
 823         if ($chars_per_line) {
 
 825             int(length($self->{"description"}[$i]) / $chars_per_line + 0.95);
 
 828           my $_description = $self->{"description"}[$i];
 
 829           while ($_description =~ /\\newline/) {
 
 831             $_description =~ s/\\newline//;
 
 833           $self->{"description"}[$i] =~ s/(\\newline\s?)*$//;
 
 835           if ($current_page == 1) {
 
 836             $lpp = $lines_on_first_page;
 
 838             $lpp = $lines_on_second_page;
 
 841           # Yes we need a manual page break -- or the user has forced one
 
 843              (($current_line + $lines) > $lpp)
 
 844              || ($self->{"_forced_pagebreaks"}
 
 845                && grep(/^${current_row}$/, @{ $self->{"_forced_pagebreaks"} }))
 
 849             # replace the special variables <%sumcarriedforward%>
 
 852             my $psum = $self->format_amount($myconfig, $sum, 2);
 
 853             $pb =~ s/<%sumcarriedforward%>/$psum/g;
 
 854             $pb =~ s/<%lastpage%>/$current_page/g;
 
 856             # only "normal" variables are supported here
 
 857             # (no <%if, no <%foreach, no <%include)
 
 859             $pb =~ s/<%(.+?)%>/$self->{$1}/g;
 
 861             # page break block is ready to rock
 
 866           $current_line += $lines;
 
 869         $sum += $self->parse_amount($myconfig, $self->{"linetotal"}[$i]);
 
 873         # don't parse par, we need it for each line
 
 875         s/<%(.+?)%>/$self->{$1}[$i]/mg;
 
 881     # if not comes before if!
 
 882     if (/\s*<%if not /) {
 
 884       # check if it is not set and display
 
 886       s/\s*<%if not (.+?)%>/$1/;
 
 888       unless ($self->{$_}) {
 
 890           last if (/\s*<%end /);
 
 900           last if (/\s*<%end /);
 
 908       # check if it is set and display
 
 910       s/\s*<%if (.+?)%>/$1/;
 
 914           last if (/\s*<%end /);
 
 924           last if (/\s*<%end /);
 
 930     # check for <%include filename%>
 
 931     if (/\s*<%include /) {
 
 935       $var =~ s/\s*<%include (.+?)%>/$1/;
 
 938       $var =~ s/(\/|\.\.)//g;
 
 940       # prevent the infinite loop!
 
 941       next if ($self->{"$var"});
 
 943       open(INC, "$self->{templates}/$var")
 
 944         or $self->error($self->cleanup . "$self->{templates}/$var : $!");
 
 953     s/<%(.+?)%>/$self->{$1}/g;
 
 954     s/<nobr><\/nobr>/ /g;
 
 961   # Convert the tex file to postscript
 
 962   if ($self->{format} =~ /(postscript|pdf)/) {
 
 965     $self->{cwd}    = cwd();
 
 966     $self->{tmpdir} = "$self->{cwd}/$userspath";
 
 968     chdir("$userspath") or $self->error($self->cleanup . "chdir : $!");
 
 970     $self->{tmpfile} =~ s/$userspath\///g;
 
 972     if ($self->{format} eq 'postscript') {
 
 974         "latex --interaction=nonstopmode $self->{tmpfile} > $self->{tmpfile}.err"
 
 976       $self->error($self->cleanup) if ($?);
 
 979           "latex --interaction=nonstopmode $self->{tmpfile} > $self->{tmpfile}.err"
 
 981         $self->error($self->cleanup) if ($?);
 
 984       $self->{tmpfile} =~ s/tex$/dvi/;
 
 986       system("dvips $self->{tmpfile} -o -q > /dev/null");
 
 987       $self->error($self->cleanup . "dvips : $!") if ($?);
 
 988       $self->{tmpfile} =~ s/dvi$/ps/;
 
 990     if ($self->{format} eq 'pdf') {
 
 992         "pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{tmpfile}.err"
 
 994       $self->error($self->cleanup) if ($?);
 
 997           "pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{tmpfile}.err"
 
 999         $self->error($self->cleanup) if ($?);
 
1001       $self->{tmpfile} =~ s/tex$/pdf/;
 
1006   if ($self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email') {
 
1008     if ($self->{media} eq 'email') {
 
1012       my $mail = new Mailer;
 
1014       map { $mail->{$_} = $self->{$_} }
 
1015         qw(cc bcc subject message version format charset);
 
1016       $mail->{to}     = qq|$self->{email}|;
 
1017       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
 
1018       $mail->{fileid} = "$fileid.";
 
1020       # if we send html or plain text inline
 
1021       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
 
1022         $mail->{contenttype} = "text/html";
 
1024         $mail->{message}       =~ s/\r\n/<br>\n/g;
 
1025         $myconfig->{signature} =~ s/\\n/<br>\n/g;
 
1026         $mail->{message} .= "<br>\n--<br>\n$myconfig->{signature}\n<br>";
 
1028         open(IN, $self->{tmpfile})
 
1029           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1031           $mail->{message} .= $_;
 
1038         @{ $mail->{attachments} } = ($self->{tmpfile});
 
1040         $myconfig->{signature} =~ s/\\n/\r\n/g;
 
1041         $mail->{message} .= "\r\n--\r\n$myconfig->{signature}";
 
1045       my $err = $mail->send($out);
 
1046       $self->error($self->cleanup . "$err") if ($err);
 
1050       $self->{OUT} = $out;
 
1052       my $numbytes = (-s $self->{tmpfile});
 
1053       open(IN, $self->{tmpfile})
 
1054         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1056       $self->{copies} = 1 unless $self->{media} eq 'printer';
 
1058       chdir("$self->{cwd}");
 
1060       for my $i (1 .. $self->{copies}) {
 
1062           open(OUT, $self->{OUT})
 
1063             or $self->error($self->cleanup . "$self->{OUT} : $!");
 
1066           # launch application
 
1067           print qq|Content-Type: application/$self->{format}
 
1068 Content-Disposition: attachment; filename="$self->{tmpfile}"
 
1069 Content-Length: $numbytes
 
1073           open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
 
1093   chdir("$self->{cwd}");
 
1094   $main::lxdebug->leave_sub();
 
1098   $main::lxdebug->enter_sub();
 
1102   chdir("$self->{tmpdir}");
 
1105   if (-f "$self->{tmpfile}.err") {
 
1106     open(FH, "$self->{tmpfile}.err");
 
1111   if ($self->{tmpfile}) {
 
1114     $self->{tmpfile} =~ s/\.\w+$//g;
 
1115     my $tmpfile = $self->{tmpfile};
 
1116     unlink(<$tmpfile.*>);
 
1119   chdir("$self->{cwd}");
 
1121   $main::lxdebug->leave_sub();
 
1127   $main::lxdebug->enter_sub();
 
1129   my ($self, @fields) = @_;
 
1132   %unique_fields = map({ $_ => 1 } @fields);
 
1133   @fields        = keys(%unique_fields);
 
1135   foreach my $field (@fields) {
 
1136     next unless ($self->{$field} =~ /\<pagebreak\>/);
 
1137     $self->{$field} =~ s/\<pagebreak\>//g;
 
1138     if ($field =~ /.*_(\d+)$/) {
 
1139       if (!$self->{"_forced_pagebreaks"}) {
 
1140         $self->{"_forced_pagebreaks"} = [];
 
1142       push(@{ $self->{"_forced_pagebreaks"} }, "$1");
 
1146   my $format = $self->{format};
 
1147   if ($self->{format} =~ /(postscript|pdf)/) {
 
1154         '<', '>', quotemeta('\n'), '
 
1158         '&', quotemeta('\n'), '
 
1160         '"', '\$', '%', '_', '#', quotemeta('^'),
 
1161         '{', '}',  '<', '>', '£', "\r"
 
1167       quotemeta('\n') => '<br>',
 
1178       quotemeta('^')  => '\^\\',
 
1183       quotemeta('\n') => '\newline ',
 
1190   foreach my $key (@{ $replace{order}{$format} }) {
 
1191     map { $self->{$_} =~ s/$key/$replace{$format}{$key}/g; } @fields;
 
1194   # Allow some HTML markup to be converted into the output format's
 
1195   # corresponding markup code, e.g. bold or italic.
 
1196   if ('html' eq $format) {
 
1197     my @markup_replace = ('b', 'i', 's', 'u');
 
1199     foreach my $key (@markup_replace) {
 
1200       map({ $self->{$_} =~ s/\<(\/?)${key}\>/<$1${key}>/g } @fields);
 
1203   } elsif ('tex' eq $format) {
 
1204     my %markup_replace = ('b' => 'textbf',
 
1206                           'u' => 'underline');
 
1208     foreach my $field (@fields) {
 
1209       foreach my $key (keys(%markup_replace)) {
 
1210         my $new = $markup_replace{$key};
 
1212           s/\$\<\$${key}\$\>\$(.*?)\$<\$\/${key}\$>\$/\\${new}\{$1\}/gi;
 
1217   $main::lxdebug->leave_sub();
 
1221   $main::lxdebug->enter_sub();
 
1223   my ($self, $date, $myconfig) = @_;
 
1225   if ($date && $date =~ /\D/) {
 
1227     if ($myconfig->{dateformat} =~ /^yy/) {
 
1228       ($yy, $mm, $dd) = split /\D/, $date;
 
1230     if ($myconfig->{dateformat} =~ /^mm/) {
 
1231       ($mm, $dd, $yy) = split /\D/, $date;
 
1233     if ($myconfig->{dateformat} =~ /^dd/) {
 
1234       ($dd, $mm, $yy) = split /\D/, $date;
 
1239     $yy = ($yy < 70) ? $yy + 2000 : $yy;
 
1240     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
 
1242     $dd = "0$dd" if ($dd < 10);
 
1243     $mm = "0$mm" if ($mm < 10);
 
1245     $date = "$yy$mm$dd";
 
1248   $main::lxdebug->leave_sub();
 
1253 # Database routines used throughout
 
1256   $main::lxdebug->enter_sub();
 
1258   my ($self, $myconfig) = @_;
 
1260   # connect to database
 
1262     DBI->connect($myconfig->{dbconnect},
 
1263                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
 
1267   if ($myconfig->{dboptions}) {
 
1268     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1271   $main::lxdebug->leave_sub();
 
1276 sub dbconnect_noauto {
 
1277   $main::lxdebug->enter_sub();
 
1279   my ($self, $myconfig) = @_;
 
1281   # connect to database
 
1283     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
 
1284                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
 
1288   if ($myconfig->{dboptions}) {
 
1289     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1292   $main::lxdebug->leave_sub();
 
1297 sub update_balance {
 
1298   $main::lxdebug->enter_sub();
 
1300   my ($self, $dbh, $table, $field, $where, $value) = @_;
 
1302   # if we have a value, go do it
 
1305     # retrieve balance from table
 
1306     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
 
1307     my $sth   = $dbh->prepare($query);
 
1309     $sth->execute || $self->dberror($query);
 
1310     my ($balance) = $sth->fetchrow_array;
 
1316     $query = "UPDATE $table SET $field = $balance WHERE $where";
 
1317     $dbh->do($query) || $self->dberror($query);
 
1319   $main::lxdebug->leave_sub();
 
1322 sub update_exchangerate {
 
1323   $main::lxdebug->enter_sub();
 
1325   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
 
1327   # some sanity check for currency
 
1329     $main::lxdebug->leave_sub();
 
1333   my $query = qq|SELECT e.curr FROM exchangerate e
 
1334                  WHERE e.curr = '$curr'
 
1335                  AND e.transdate = '$transdate'
 
1337   my $sth = $dbh->prepare($query);
 
1338   $sth->execute || $self->dberror($query);
 
1341   if ($buy != 0 && $sell != 0) {
 
1342     $set = "buy = $buy, sell = $sell";
 
1343   } elsif ($buy != 0) {
 
1344     $set = "buy = $buy";
 
1345   } elsif ($sell != 0) {
 
1346     $set = "sell = $sell";
 
1349   if ($sth->fetchrow_array) {
 
1350     $query = qq|UPDATE exchangerate
 
1352                 WHERE curr = '$curr'
 
1353                 AND transdate = '$transdate'|;
 
1355     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
 
1356                 VALUES ('$curr', $buy, $sell, '$transdate')|;
 
1359   $dbh->do($query) || $self->dberror($query);
 
1361   $main::lxdebug->leave_sub();
 
1364 sub save_exchangerate {
 
1365   $main::lxdebug->enter_sub();
 
1367   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
 
1369   my $dbh = $self->dbconnect($myconfig);
 
1371   my ($buy, $sell) = (0, 0);
 
1372   $buy  = $rate if $fld eq 'buy';
 
1373   $sell = $rate if $fld eq 'sell';
 
1375   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
 
1379   $main::lxdebug->leave_sub();
 
1382 sub get_exchangerate {
 
1383   $main::lxdebug->enter_sub();
 
1385   my ($self, $dbh, $curr, $transdate, $fld) = @_;
 
1387   unless ($transdate) {
 
1388     $main::lxdebug->leave_sub();
 
1392   my $query = qq|SELECT e.$fld FROM exchangerate e
 
1393                  WHERE e.curr = '$curr'
 
1394                  AND e.transdate = '$transdate'|;
 
1395   my $sth = $dbh->prepare($query);
 
1396   $sth->execute || $self->dberror($query);
 
1398   my ($exchangerate) = $sth->fetchrow_array;
 
1401   $main::lxdebug->leave_sub();
 
1403   return $exchangerate;
 
1406 sub check_exchangerate {
 
1407   $main::lxdebug->enter_sub();
 
1409   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
 
1411   unless ($transdate) {
 
1412     $main::lxdebug->leave_sub();
 
1416   my $dbh = $self->dbconnect($myconfig);
 
1418   my $query = qq|SELECT e.$fld FROM exchangerate e
 
1419                  WHERE e.curr = '$currency'
 
1420                  AND e.transdate = '$transdate'|;
 
1421   my $sth = $dbh->prepare($query);
 
1422   $sth->execute || $self->dberror($query);
 
1424   my ($exchangerate) = $sth->fetchrow_array;
 
1428   $main::lxdebug->leave_sub();
 
1430   return $exchangerate;
 
1434   $main::lxdebug->enter_sub();
 
1436   my ($self, $dbh, $id) = @_;
 
1440     qw(name department_1 department_2 street zipcode city country contact phone fax email)
 
1442     if ($self->{"shipto$item"}) {
 
1443       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
 
1445     $self->{"shipto$item"} =~ s/\'/\'\'/g;
 
1450       qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2, shiptostreet,
 
1451                    shiptozipcode, shiptocity, shiptocountry, shiptocontact,
 
1452                    shiptophone, shiptofax, shiptoemail) VALUES ($id,
 
1453                    '$self->{shiptoname}', '$self->{shiptodepartment_1}', '$self->{shiptodepartment_2}', '$self->{shiptostreet}',
 
1454                    '$self->{shiptozipcode}', '$self->{shiptocity}',
 
1455                    '$self->{shiptocountry}', '$self->{shiptocontact}',
 
1456                    '$self->{shiptophone}', '$self->{shiptofax}',
 
1457                    '$self->{shiptoemail}')|;
 
1458     $dbh->do($query) || $self->dberror($query);
 
1461   $main::lxdebug->leave_sub();
 
1465   $main::lxdebug->enter_sub();
 
1467   my ($self, $dbh) = @_;
 
1469   my $query = qq|SELECT e.id, e.name FROM employee e
 
1470                  WHERE e.login = '$self->{login}'|;
 
1471   my $sth = $dbh->prepare($query);
 
1472   $sth->execute || $self->dberror($query);
 
1474   ($self->{employee_id}, $self->{employee}) = $sth->fetchrow_array;
 
1475   $self->{employee_id} *= 1;
 
1479   $main::lxdebug->leave_sub();
 
1482 # get other contact for transaction and form - html/tex
 
1484   $main::lxdebug->enter_sub();
 
1486   my ($self, $dbh, $id) = @_;
 
1488   my $query = qq|SELECT c.*
 
1491   $sth = $dbh->prepare($query);
 
1492   $sth->execute || $self->dberror($query);
 
1494   $ref = $sth->fetchrow_hashref(NAME_lc);
 
1496   push @{ $self->{$_} }, $ref;
 
1499   $main::lxdebug->leave_sub();
 
1502 # get contacts for id, if no contact return {"","","","",""}
 
1504   $main::lxdebug->enter_sub();
 
1506   my ($self, $dbh, $id) = @_;
 
1508   my $query = qq|SELECT c.cp_id, c.cp_cv_id, c.cp_name, c.cp_givenname
 
1510               WHERE cp_cv_id=$id|;
 
1511   my $sth = $dbh->prepare($query);
 
1512   $sth->execute || $self->dberror($query);
 
1515   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1516     push @{ $self->{all_contacts} }, $ref;
 
1521     push @{ $self->{all_contacts} }, { { "", "", "", "", "" } };
 
1524   $main::lxdebug->leave_sub();
 
1527 # this sub gets the id and name from $table
 
1529   $main::lxdebug->enter_sub();
 
1531   my ($self, $myconfig, $table) = @_;
 
1533   # connect to database
 
1534   my $dbh = $self->dbconnect($myconfig);
 
1536   my $name           = $self->like(lc $self->{$table});
 
1537   my $customernumber = $self->like(lc $self->{customernumber});
 
1539   if ($self->{customernumber} ne "") {
 
1540     $query = qq~SELECT c.id, c.name,
 
1541                   c.street || ' ' || c.zipcode || ' ' || c.city || ' ' || c.country AS address
 
1543                   WHERE (lower(c.customernumber) LIKE '$customernumber') AND (not c.obsolete)
 
1546     $query = qq~SELECT c.id, c.name,
 
1547                  c.street || ' ' || c.zipcode || ' ' || c.city || ' ' || c.country AS address
 
1549                  WHERE (lower(c.name) LIKE '$name') AND (not c.obsolete)
 
1553   if ($self->{openinvoices}) {
 
1554     $query = qq~SELECT DISTINCT c.id, c.name,
 
1555                 c.street || ' ' || c.zipcode || ' ' || c.city || ' ' || c.country AS address
 
1556                 FROM $self->{arap} a
 
1557                 JOIN $table c ON (a.${table}_id = c.id)
 
1558                 WHERE NOT a.amount = a.paid
 
1559                 AND lower(c.name) LIKE '$name'
 
1562   my $sth = $dbh->prepare($query);
 
1564   $sth->execute || $self->dberror($query);
 
1567   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1568     push(@{ $self->{name_list} }, $ref);
 
1574   $main::lxdebug->leave_sub();
 
1579 # the selection sub is used in the AR, AP, IS, IR and OE module
 
1582   $main::lxdebug->enter_sub();
 
1584   my ($self, $myconfig, $table, $module) = @_;
 
1587   my $dbh = $self->dbconnect($myconfig);
 
1589   my $query = qq|SELECT count(*) FROM $table|;
 
1590   my $sth   = $dbh->prepare($query);
 
1591   $sth->execute || $self->dberror($query);
 
1592   my ($count) = $sth->fetchrow_array;
 
1595   # build selection list
 
1596   if ($count < $myconfig->{vclimit}) {
 
1597     $query = qq|SELECT id, name
 
1598                 FROM $table WHERE not obsolete
 
1600     $sth = $dbh->prepare($query);
 
1601     $sth->execute || $self->dberror($query);
 
1603     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1604       push @{ $self->{"all_$table"} }, $ref;
 
1612   $self->get_employee($dbh);
 
1614   # setup sales contacts
 
1615   $query = qq|SELECT e.id, e.name
 
1618               AND NOT e.id = $self->{employee_id}|;
 
1619   $sth = $dbh->prepare($query);
 
1620   $sth->execute || $self->dberror($query);
 
1622   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1623     push @{ $self->{all_employees} }, $ref;
 
1628   push @{ $self->{all_employees} },
 
1629     { id   => $self->{employee_id},
 
1630       name => $self->{employee} };
 
1632   # sort the whole thing
 
1633   @{ $self->{all_employees} } =
 
1634     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
 
1636   if ($module eq 'AR') {
 
1638     # prepare query for departments
 
1639     $query = qq|SELECT d.id, d.description
 
1645     $query = qq|SELECT d.id, d.description
 
1650   $sth = $dbh->prepare($query);
 
1651   $sth->execute || $self->dberror($query);
 
1653   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1654     push @{ $self->{all_departments} }, $ref;
 
1659   $main::lxdebug->leave_sub();
 
1662 # this is only used for reports
 
1663 sub all_departments {
 
1664   $main::lxdebug->enter_sub();
 
1666   my ($self, $myconfig, $table) = @_;
 
1668   my $dbh   = $self->dbconnect($myconfig);
 
1669   my $where = "1 = 1";
 
1671   if (defined $table) {
 
1672     if ($table eq 'customer') {
 
1673       $where = " d.role = 'P'";
 
1677   my $query = qq|SELECT d.id, d.description
 
1681   my $sth = $dbh->prepare($query);
 
1682   $sth->execute || $self->dberror($query);
 
1684   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1685     push @{ $self->{all_departments} }, $ref;
 
1691   $main::lxdebug->leave_sub();
 
1695   $main::lxdebug->enter_sub();
 
1697   my ($self, $module, $myconfig, $table) = @_;
 
1699   $self->all_vc($myconfig, $table, $module);
 
1701   # get last customers or vendors
 
1704   my $dbh = $self->dbconnect($myconfig);
 
1708   # now get the account numbers
 
1709   $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id
 
1711               WHERE c.link LIKE '%$module%'
 
1714   $sth = $dbh->prepare($query);
 
1715   $sth->execute || $self->dberror($query);
 
1717   $self->{accounts} = "";
 
1718   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1720     foreach my $key (split /:/, $ref->{link}) {
 
1721       if ($key =~ /$module/) {
 
1723         # cross reference for keys
 
1724         $xkeyref{ $ref->{accno} } = $key;
 
1726         push @{ $self->{"${module}_links"}{$key} },
 
1727           { accno       => $ref->{accno},
 
1728             description => $ref->{description},
 
1729             taxkey      => $ref->{taxkey_id} };
 
1731         $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
1737   if (($module eq "AP") || ($module eq "AR")) {
 
1739     # get tax rates and description
 
1740     $query = qq| SELECT * FROM tax t|;
 
1741     $sth   = $dbh->prepare($query);
 
1742     $sth->execute || $self->dberror($query);
 
1744     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1745       push @{ $self->{TAX} }, $ref;
 
1751     my $arap = ($table eq 'customer') ? 'ar' : 'ap';
 
1753     $query = qq|SELECT a.cp_id, a.invnumber, a.transdate,
 
1754                 a.${table}_id, a.datepaid, a.duedate, a.ordnumber,
 
1755                 a.taxincluded, a.curr AS currency, a.notes, a.intnotes,
 
1756                 c.name AS $table, a.department_id, d.description AS department,
 
1757                 a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
 
1758                 a.employee_id, e.name AS employee, a.gldate
 
1760                 JOIN $table c ON (a.${table}_id = c.id)
 
1761                 LEFT JOIN employee e ON (e.id = a.employee_id)
 
1762                 LEFT JOIN department d ON (d.id = a.department_id)
 
1763                 WHERE a.id = $self->{id}|;
 
1764     $sth = $dbh->prepare($query);
 
1765     $sth->execute || $self->dberror($query);
 
1767     $ref = $sth->fetchrow_hashref(NAME_lc);
 
1768     foreach $key (keys %$ref) {
 
1769       $self->{$key} = $ref->{$key};
 
1773     # get amounts from individual entries
 
1774     $query = qq|SELECT c.accno, c.description, a.source, a.amount, a.memo,
 
1775                 a.transdate, a.cleared, a.project_id, p.projectnumber, a.taxkey, t.rate
 
1777                 JOIN chart c ON (c.id = a.chart_id)
 
1778                 LEFT JOIN project p ON (p.id = a.project_id)
 
1779                 LEFT Join tax t ON (a.taxkey = t.taxkey)
 
1780                 WHERE a.trans_id = $self->{id}
 
1781                 AND a.fx_transaction = '0'
 
1782                 ORDER BY a.oid,a.transdate|;
 
1783     $sth = $dbh->prepare($query);
 
1784     $sth->execute || $self->dberror($query);
 
1786     my $fld = ($table eq 'customer') ? 'buy' : 'sell';
 
1788     # get exchangerate for currency
 
1789     $self->{exchangerate} =
 
1790       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate},
 
1794     # store amounts in {acc_trans}{$key} for multiple accounts
 
1795     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1796       $ref->{exchangerate} =
 
1797         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate},
 
1799       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
 
1802       $ref->{index} = $index;
 
1804       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
 
1808     $query = qq|SELECT d.curr AS currencies, d.closedto, d.revtrans,
 
1809                   (SELECT c.accno FROM chart c
 
1810                    WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
1811                   (SELECT c.accno FROM chart c
 
1812                    WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
1814     $sth = $dbh->prepare($query);
 
1815     $sth->execute || $self->dberror($query);
 
1817     $ref = $sth->fetchrow_hashref(NAME_lc);
 
1818     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
1824     $query = qq|SELECT current_date AS transdate,
 
1825                 d.curr AS currencies, d.closedto, d.revtrans,
 
1826                   (SELECT c.accno FROM chart c
 
1827                    WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
1828                   (SELECT c.accno FROM chart c
 
1829                    WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
1831     $sth = $dbh->prepare($query);
 
1832     $sth->execute || $self->dberror($query);
 
1834     $ref = $sth->fetchrow_hashref(NAME_lc);
 
1835     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
1838     if ($self->{"$self->{vc}_id"}) {
 
1840       # only setup currency
 
1841       ($self->{currency}) = split /:/, $self->{currencies};
 
1845       $self->lastname_used($dbh, $myconfig, $table, $module);
 
1847       my $fld = ($table eq 'customer') ? 'buy' : 'sell';
 
1849       # get exchangerate for currency
 
1850       $self->{exchangerate} =
 
1851         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate},
 
1860   $main::lxdebug->leave_sub();
 
1864   $main::lxdebug->enter_sub();
 
1866   my ($self, $dbh, $myconfig, $table, $module) = @_;
 
1868   my $arap  = ($table eq 'customer') ? "ar" : "ap";
 
1869   my $where = "1 = 1";
 
1871   if ($self->{type} =~ /_order/) {
 
1873     $where = "quotation = '0'";
 
1875   if ($self->{type} =~ /_quotation/) {
 
1877     $where = "quotation = '1'";
 
1880   my $query = qq|SELECT MAX(id) FROM $arap
 
1882                               AND ${table}_id > 0|;
 
1883   my $sth = $dbh->prepare($query);
 
1884   $sth->execute || $self->dberror($query);
 
1886   my ($trans_id) = $sth->fetchrow_array;
 
1890   $query = qq|SELECT ct.name, a.curr, a.${table}_id,
 
1891               current_date + ct.terms AS duedate, a.department_id,
 
1892               d.description AS department
 
1894               JOIN $table ct ON (a.${table}_id = ct.id)
 
1895               LEFT JOIN department d ON (a.department_id = d.id)
 
1896               WHERE a.id = $trans_id|;
 
1897   $sth = $dbh->prepare($query);
 
1898   $sth->execute || $self->dberror($query);
 
1900   ($self->{$table},  $self->{currency},      $self->{"${table}_id"},
 
1901    $self->{duedate}, $self->{department_id}, $self->{department})
 
1902     = $sth->fetchrow_array;
 
1905   $main::lxdebug->leave_sub();
 
1909   $main::lxdebug->enter_sub();
 
1911   my ($self, $myconfig, $thisdate, $days) = @_;
 
1913   my $dbh = $self->dbconnect($myconfig);
 
1918     my $dateformat = $myconfig->{dateformat};
 
1919     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
 
1921     $query = qq|SELECT to_date('$thisdate', '$dateformat') + $days AS thisdate
 
1923     $sth = $dbh->prepare($query);
 
1924     $sth->execute || $self->dberror($query);
 
1926     $query = qq|SELECT current_date AS thisdate
 
1928     $sth = $dbh->prepare($query);
 
1929     $sth->execute || $self->dberror($query);
 
1932   ($thisdate) = $sth->fetchrow_array;
 
1937   $main::lxdebug->leave_sub();
 
1943   $main::lxdebug->enter_sub();
 
1945   my ($self, $string) = @_;
 
1947   if ($string !~ /%/) {
 
1948     $string = "%$string%";
 
1951   $string =~ s/\'/\'\'/g;
 
1953   $main::lxdebug->leave_sub();
 
1959   $main::lxdebug->enter_sub();
 
1961   my ($self, $flds, $new, $count, $numrows) = @_;
 
1965   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } }
 
1971   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
 
1973     $j = $item->{ndx} - 1;
 
1974     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
 
1978   for $i ($count + 1 .. $numrows) {
 
1979     map { delete $self->{"${_}_$i"} } @{$flds};
 
1982   $main::lxdebug->leave_sub();
 
1986   $main::lxdebug->enter_sub();
 
1988   my ($self, $myconfig) = @_;
 
1992   my $dbh = $self->dbconnect_noauto($myconfig);
 
1994   my $query = qq|DELETE FROM status
 
1995                  WHERE formname = '$self->{formname}'
 
1997   my $sth = $dbh->prepare($query) || $self->dberror($query);
 
1999   if ($self->{formname} =~ /(check|receipt)/) {
 
2000     for $i (1 .. $self->{rowcount}) {
 
2001       $sth->execute($self->{"id_$i"} * 1) || $self->dberror($query);
 
2005     $sth->execute($self->{id}) || $self->dberror($query);
 
2009   my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
 
2010   my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
 
2012   my %queued = split / /, $self->{queued};
 
2014   if ($self->{formname} =~ /(check|receipt)/) {
 
2016     # this is a check or receipt, add one entry for each lineitem
 
2017     my ($accno) = split /--/, $self->{account};
 
2018     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname,
 
2019                 chart_id) VALUES (?, '$printed',
 
2020                 '$queued{$self->{formname}}', '$self->{prinform}',
 
2021                 (SELECT c.id FROM chart c WHERE c.accno = '$accno'))|;
 
2022     $sth = $dbh->prepare($query) || $self->dberror($query);
 
2024     for $i (1 .. $self->{rowcount}) {
 
2025       if ($self->{"checked_$i"}) {
 
2026         $sth->execute($self->{"id_$i"}) || $self->dberror($query);
 
2031     $query = qq|INSERT INTO status (trans_id, printed, emailed,
 
2032                 spoolfile, formname)
 
2033                 VALUES ($self->{id}, '$printed', '$emailed',
 
2034                 '$queued{$self->{formname}}', '$self->{formname}')|;
 
2035     $dbh->do($query) || $self->dberror($query);
 
2041   $main::lxdebug->leave_sub();
 
2045   $main::lxdebug->enter_sub();
 
2047   my ($self, $dbh) = @_;
 
2049   my ($query, $printed, $emailed);
 
2051   my $formnames  = $self->{printed};
 
2052   my $emailforms = $self->{emailed};
 
2054   my $query = qq|DELETE FROM status
 
2055                  WHERE formname = '$self->{formname}'
 
2056                  AND trans_id = $self->{id}|;
 
2057   $dbh->do($query) || $self->dberror($query);
 
2059   # this only applies to the forms
 
2060   # checks and receipts are posted when printed or queued
 
2062   if ($self->{queued}) {
 
2063     my %queued = split / /, $self->{queued};
 
2065     foreach my $formname (keys %queued) {
 
2066       $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
 
2067       $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
 
2069       $query = qq|INSERT INTO status (trans_id, printed, emailed,
 
2070                   spoolfile, formname)
 
2071                   VALUES ($self->{id}, '$printed', '$emailed',
 
2072                   '$queued{$formname}', '$formname')|;
 
2073       $dbh->do($query) || $self->dberror($query);
 
2075       $formnames  =~ s/$self->{formname}//;
 
2076       $emailforms =~ s/$self->{formname}//;
 
2081   # save printed, emailed info
 
2082   $formnames  =~ s/^ +//g;
 
2083   $emailforms =~ s/^ +//g;
 
2086   map { $status{$_}{printed} = 1 } split / +/, $formnames;
 
2087   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
 
2089   foreach my $formname (keys %status) {
 
2090     $printed = ($formnames  =~ /$self->{formname}/) ? "1" : "0";
 
2091     $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
 
2093     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
 
2094                 VALUES ($self->{id}, '$printed', '$emailed', '$formname')|;
 
2095     $dbh->do($query) || $self->dberror($query);
 
2098   $main::lxdebug->leave_sub();
 
2101 sub update_defaults {
 
2102   $main::lxdebug->enter_sub();
 
2104   my ($self, $myconfig, $fld) = @_;
 
2106   my $dbh   = $self->dbconnect_noauto($myconfig);
 
2107   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
 
2108   my $sth   = $dbh->prepare($query);
 
2110   $sth->execute || $self->dberror($query);
 
2111   my ($var) = $sth->fetchrow_array;
 
2116   $query = qq|UPDATE defaults
 
2118   $dbh->do($query) || $form->dberror($query);
 
2123   $main::lxdebug->leave_sub();
 
2128 sub update_business {
 
2129   $main::lxdebug->enter_sub();
 
2131   my ($self, $myconfig, $business_id) = @_;
 
2133   my $dbh   = $self->dbconnect_noauto($myconfig);
 
2135     qq|SELECT customernumberinit FROM business  WHERE id=$business_id FOR UPDATE|;
 
2136   my $sth = $dbh->prepare($query);
 
2138   $sth->execute || $self->dberror($query);
 
2139   my ($var) = $sth->fetchrow_array;
 
2144   $query = qq|UPDATE business
 
2145               SET customernumberinit = '$var' WHERE id=$business_id|;
 
2146   $dbh->do($query) || $form->dberror($query);
 
2151   $main::lxdebug->leave_sub();
 
2157   $main::lxdebug->enter_sub();
 
2159   my ($self, $myconfig, $salesman) = @_;
 
2161   my $dbh   = $self->dbconnect($myconfig);
 
2163     qq|SELECT id, name FROM customer  WHERE (customernumber ilike '%$salesman%' OR name ilike '%$salesman%') AND business_id in (SELECT id from business WHERE salesman)|;
 
2164   my $sth = $dbh->prepare($query);
 
2165   $sth->execute || $self->dberror($query);
 
2168   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
2169     push(@{ $self->{salesman_list} }, $ref);
 
2173   $main::lxdebug->leave_sub();
 
2178 sub get_partsgroup {
 
2179   $main::lxdebug->enter_sub();
 
2181   my ($self, $myconfig, $p) = @_;
 
2183   my $dbh = $self->dbconnect($myconfig);
 
2185   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
 
2187                  JOIN parts p ON (p.partsgroup_id = pg.id)|;
 
2189   if ($p->{searchitems} eq 'part') {
 
2191                  WHERE p.inventory_accno_id > 0|;
 
2193   if ($p->{searchitems} eq 'service') {
 
2195                  WHERE p.inventory_accno_id IS NULL|;
 
2197   if ($p->{searchitems} eq 'assembly') {
 
2199                  WHERE p.assembly = '1'|;
 
2201   if ($p->{searchitems} eq 'labor') {
 
2203                  WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
 
2207                  ORDER BY partsgroup|;
 
2210     $query = qq|SELECT id, partsgroup FROM partsgroup
 
2211                 ORDER BY partsgroup|;
 
2214   if ($p->{language_code}) {
 
2215     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
 
2216                 t.description AS translation
 
2218                 JOIN parts p ON (p.partsgroup_id = pg.id)
 
2219                 LEFT JOIN translation t ON (t.trans_id = pg.id AND t.language_code = '$p->{language_code}')
 
2220                 ORDER BY translation|;
 
2223   my $sth = $dbh->prepare($query);
 
2224   $sth->execute || $self->dberror($query);
 
2226   $self->{all_partsgroup} = ();
 
2227   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
2228     push @{ $self->{all_partsgroup} }, $ref;
 
2232   $main::lxdebug->leave_sub();
 
2235 sub get_pricegroup {
 
2236   $main::lxdebug->enter_sub();
 
2238   my ($self, $myconfig, $p) = @_;
 
2240   my $dbh = $self->dbconnect($myconfig);
 
2242   my $query = qq|SELECT p.id, p.pricegroup
 
2246                  ORDER BY pricegroup|;
 
2249     $query = qq|SELECT id, pricegroup FROM pricegroup
 
2250                 ORDER BY pricegroup|;
 
2253   my $sth = $dbh->prepare($query);
 
2254   $sth->execute || $self->dberror($query);
 
2256   $self->{all_pricegroup} = ();
 
2257   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
2258     push @{ $self->{all_pricegroup} }, $ref;
 
2263   $main::lxdebug->leave_sub();
 
2267   my ($self, $dbh, $myconfig, $audittrail) = @_;
 
2269   # table, $reference, $formname, $action, $id, $transdate) = @_;
 
2276     $dbh        = $self->dbconnect($myconfig);
 
2280   # if we have an id add audittrail, otherwise get a new timestamp
 
2282   if ($audittrail->{id}) {
 
2284     $query = qq|SELECT audittrail FROM defaults|;
 
2286     if ($dbh->selectrow_array($query)) {
 
2287       my ($null, $employee_id) = $self->get_employee($dbh);
 
2289       if ($self->{audittrail} && !$myconfig) {
 
2290         chop $self->{audittrail};
 
2292         my @a = split /\|/, $self->{audittrail};
 
2296         my @flds = qw(tablename reference formname action transdate);
 
2298         # put into hash and remove dups
 
2300           $key = "$a[2]$a[3]";
 
2302           $newtrail{$key} = { map { $_ => $a[$i++] } @flds };
 
2306         $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
 
2307                     formname, action, employee_id, transdate)
 
2308                     VALUES ($audittrail->{id}, ?, ?,
 
2309                     ?, ?, $employee_id, ?)|;
 
2310         my $sth = $dbh->prepare($query) || $self->dberror($query);
 
2314             $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate}
 
2318           for (@flds) { $sth->bind_param($i++, $newtrail{$key}{$_}) }
 
2320           $sth->execute || $self->dberror;
 
2325       if ($audittrail->{transdate}) {
 
2326         $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
 
2327                     formname, action, employee_id, transdate) VALUES (
 
2328                     $audittrail->{id}, '$audittrail->{tablename}', |
 
2329           . $dbh->quote($audittrail->{reference}) . qq|,
 
2330                     '$audittrail->{formname}', '$audittrail->{action}',
 
2331                     $employee_id, '$audittrail->{transdate}')|;
 
2333         $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
 
2334                     formname, action, employee_id) VALUES ($audittrail->{id},
 
2335                     '$audittrail->{tablename}', |
 
2336           . $dbh->quote($audittrail->{reference}) . qq|,
 
2337                     '$audittrail->{formname}', '$audittrail->{action}',
 
2344     $query = qq|SELECT current_timestamp FROM defaults|;
 
2345     my ($timestamp) = $dbh->selectrow_array($query);
 
2348       "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
 
2351   $dbh->disconnect if $disconnect;
 
2360   $main::lxdebug->enter_sub();
 
2362   my ($type, $country, $NLS_file) = @_;
 
2366   if ($country && -d "locale/$country") {
 
2367     $self->{countrycode} = $country;
 
2368     eval { require "locale/$country/$NLS_file"; };
 
2371   $self->{NLS_file} = $NLS_file;
 
2373   push @{ $self->{LONG_MONTH} },
 
2374     ("January",   "February", "March",    "April",
 
2375      "May ",      "June",     "July",     "August",
 
2376      "September", "October",  "November", "December");
 
2377   push @{ $self->{SHORT_MONTH} },
 
2378     (qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec));
 
2380   $main::lxdebug->leave_sub();
 
2386   my ($self, $text) = @_;
 
2388   return (exists $self{texts}{$text}) ? $self{texts}{$text} : $text;
 
2392   $main::lxdebug->enter_sub();
 
2394   my ($self, $text) = @_;
 
2396   if (exists $self{subs}{$text}) {
 
2397     $text = $self{subs}{$text};
 
2399     if ($self->{countrycode} && $self->{NLS_file}) {
 
2401          "$text not defined in locale/$self->{countrycode}/$self->{NLS_file}");
 
2405   $main::lxdebug->leave_sub();
 
2411   $main::lxdebug->enter_sub();
 
2413   my ($self, $myconfig, $date, $longformat) = @_;
 
2416   my $longmonth = ($longformat) ? 'LONG_MONTH' : 'SHORT_MONTH';
 
2421     $spc = $myconfig->{dateformat};
 
2423     $spc = substr($spc, 1, 1);
 
2425     if ($date =~ /\D/) {
 
2426       if ($myconfig->{dateformat} =~ /^yy/) {
 
2427         ($yy, $mm, $dd) = split /\D/, $date;
 
2429       if ($myconfig->{dateformat} =~ /^mm/) {
 
2430         ($mm, $dd, $yy) = split /\D/, $date;
 
2432       if ($myconfig->{dateformat} =~ /^dd/) {
 
2433         ($dd, $mm, $yy) = split /\D/, $date;
 
2436       $date = substr($date, 2);
 
2437       ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
 
2442     $yy = ($yy < 70) ? $yy + 2000 : $yy;
 
2443     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
 
2445     if ($myconfig->{dateformat} =~ /^dd/) {
 
2446       if (defined $longformat && $longformat == 0) {
 
2448         $dd = "0$dd" if ($dd < 10);
 
2449         $mm = "0$mm" if ($mm < 10);
 
2450         $longdate = "$dd$spc$mm$spc$yy";
 
2453         $longdate .= ($spc eq '.') ? ". " : " ";
 
2454         $longdate .= &text($self, $self->{$longmonth}[$mm]) . " $yy";
 
2456     } elsif ($myconfig->{dateformat} eq "yyyy-mm-dd") {
 
2458       # Use German syntax with the ISO date style "yyyy-mm-dd" because
 
2459       # Lx-Office is mainly used in Germany or German speaking countries.
 
2460       if (defined $longformat && $longformat == 0) {
 
2462         $dd = "0$dd" if ($dd < 10);
 
2463         $mm = "0$mm" if ($mm < 10);
 
2464         $longdate = "$yy-$mm-$dd";
 
2466         $longdate = "$dd. ";
 
2467         $longdate .= &text($self, $self->{$longmonth}[$mm]) . " $yy";
 
2470       if (defined $longformat && $longformat == 0) {
 
2472         $dd = "0$dd" if ($dd < 10);
 
2473         $mm = "0$mm" if ($mm < 10);
 
2474         $longdate = "$mm$spc$dd$spc$yy";
 
2476         $longdate = &text($self, $self->{$longmonth}[$mm]) . " $dd, $yy";
 
2482   $main::lxdebug->leave_sub();
 
2488   $main::lxdebug->enter_sub();
 
2490   my ($self, $myconfig, $date, $longformat) = @_;
 
2493     $main::lxdebug->leave_sub();
 
2498   $spc = $myconfig->{dateformat};
 
2500   $spc = substr($spc, 1, 1);
 
2502   if ($date =~ /\D/) {
 
2503     if ($myconfig->{dateformat} =~ /^yy/) {
 
2504       ($yy, $mm, $dd) = split /\D/, $date;
 
2505     } elsif ($myconfig->{dateformat} =~ /^mm/) {
 
2506       ($mm, $dd, $yy) = split /\D/, $date;
 
2507     } elsif ($myconfig->{dateformat} =~ /^dd/) {
 
2508       ($dd, $mm, $yy) = split /\D/, $date;
 
2511     $date = substr($date, 2);
 
2512     ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
 
2517   $yy = ($yy < 70) ? $yy + 2000 : $yy;
 
2518   $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
 
2520   $main::lxdebug->leave_sub();
 
2521   return ($yy, $mm, $dd);