1 #=====================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   7 #=====================================================================
 
   8 # SQL-Ledger Accounting
 
  11 #  Author: Dieter Simader
 
  12 #   Email: dsimader@sql-ledger.org
 
  13 #     Web: http://www.sql-ledger.org
 
  17 # This program is free software; you can redistribute it and/or modify
 
  18 # it under the terms of the GNU General Public License as published by
 
  19 # the Free Software Foundation; either version 2 of the License, or
 
  20 # (at your option) any later version.
 
  22 # This program is distributed in the hope that it will be useful,
 
  23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 
  24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  25 # GNU General Public License for more details.
 
  26 # You should have received a copy of the GNU General Public License
 
  27 # along with this program; if not, write to the Free Software
 
  28 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 
  30 #======================================================================
 
  32 # Accounts Receivable module backend routines
 
  34 #======================================================================
 
  39 use SL::DATEV qw(:CONSTANTS);
 
  45 use SL::Util qw(trim);
 
  50 sub post_transaction {
 
  51   my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
 
  52   $main::lxdebug->enter_sub();
 
  54   my $rc = SL::DB->client->with_transaction(\&_post_transaction, $self, $myconfig, $form, $provided_dbh, $payments_only);
 
  56   $::lxdebug->leave_sub;
 
  60 sub _post_transaction {
 
  61   my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
 
  63   my ($query, $sth, $null, $taxrate, $amount, $tax);
 
  69   my $dbh = $provided_dbh || SL::DB->client->dbh;
 
  70   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
 
  73   $form->{exchangerate} = ($form->{currency} eq $form->{defaultcurrency}) ? 1 :
 
  74       ( $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'buy') ||
 
  75         $form->parse_amount($myconfig, $form->{exchangerate}) );
 
  77   # get the charts selected
 
  78   map { ($form->{AR_amounts}{"amount_$_"}) = split /--/, $form->{"AR_amount_$_"} } 1 .. $form->{rowcount};
 
  80   $form->{AR_amounts}{receivables} = $form->{ARselected};
 
  81   $form->{AR}{receivables}         = $form->{ARselected};
 
  83   $form->{tax}       = 0; # is this still needed?
 
  85   # main calculation of rowcount loop inside Form method, amount_$i and tax_$i get formatted
 
  86   $form->{taxincluded} = 0 unless $form->{taxincluded};
 
  87   ($form->{netamount},$form->{total_tax},$form->{amount}) = $form->calculate_arap('sell', $form->{taxincluded}, $form->{exchangerate});
 
  89   # adjust paidaccounts if there is no date in the last row
 
  90   # this does not apply to stornos, where the paid field is set manually
 
  91   unless ($form->{storno}) {
 
  92     $form->{paidaccounts}-- unless $form->{"datepaid_$form->{paidaccounts}"};
 
  96     for $i (1 .. $form->{paidaccounts}) {
 
  97       $form->{"paid_$i"} = $form->round_amount($form->parse_amount($myconfig, $form->{"paid_$i"}), 2);
 
  98       $form->{paid}     += $form->{"paid_$i"};
 
  99       $form->{datepaid}  = $form->{"datepaid_$i"};
 
 103   $form->{paid}   = $form->round_amount($form->{paid} * ($form->{exchangerate} || 1), 2);
 
 105   ($null, $form->{employee_id}) = split /--/, $form->{employee};
 
 107   $form->get_employee($dbh) unless $form->{employee_id};
 
 109   # if we have an id delete old records else make one
 
 110   if (!$payments_only) {
 
 112       # delete detail records
 
 113       $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
 
 114       do_query($form, $dbh, $query, $form->{id});
 
 117       $query = qq|SELECT nextval('glid')|;
 
 118       ($form->{id}) = selectrow_query($form, $dbh, $query);
 
 119       $query = qq|INSERT INTO ar (id, invnumber, employee_id, currency_id, taxzone_id) VALUES (?, 'dummy', ?, (SELECT id FROM currencies WHERE name=?), (SELECT taxzone_id FROM customer WHERE id = ?))|;
 
 120       do_query($form, $dbh, $query, $form->{id}, $form->{employee_id}, $form->{currency}, $form->{customer_id});
 
 121       if (!$form->{invnumber}) {
 
 122         my $trans_number   = SL::TransNumber->new(type => 'invoice', dbh => $dbh, number => $form->{partnumber}, id => $form->{id});
 
 123         $form->{invnumber} = $trans_number->create_unique;
 
 128   # amount for AR account
 
 129   $form->{receivables} = $form->round_amount($form->{amount}, 2) * -1;
 
 131   # update exchangerate
 
 132   $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate}, $form->{exchangerate}, 0)
 
 133     if ($form->{currency} ne $form->{defaultcurrency}) && !$form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'buy');
 
 135   if (!$payments_only) {
 
 138            invnumber = ?, ordnumber = ?, transdate = ?, customer_id = ?,
 
 139            taxincluded = ?, amount = ?, duedate = ?, paid = ?,
 
 140            currency_id = (SELECT id FROM currencies WHERE name = ?),
 
 141            netamount = ?, notes = ?, department_id = ?,
 
 142            employee_id = ?, storno = ?, storno_id = ?, globalproject_id = ?,
 
 145     my @values = ($form->{invnumber}, $form->{ordnumber}, conv_date($form->{transdate}), conv_i($form->{customer_id}), $form->{taxincluded} ? 't' : 'f', $form->{amount},
 
 146                   conv_date($form->{duedate}), $form->{paid},
 
 148                   $form->{netamount}, $form->{notes}, conv_i($form->{department_id}),
 
 149                   conv_i($form->{employee_id}), $form->{storno} ? 't' : 'f', $form->{storno_id},
 
 150                   conv_i($form->{globalproject_id}), $form->{direct_debit} ? 't' : 'f', conv_i($form->{id}));
 
 151     do_query($form, $dbh, $query, @values);
 
 153     # add individual transactions for AR, amount and taxes
 
 154     for $i (1 .. $form->{rowcount}) {
 
 155       if ($form->{"amount_$i"} != 0) {
 
 156         my $project_id = conv_i($form->{"project_id_$i"});
 
 158         # insert detail records in acc_trans
 
 159         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link)
 
 160                      VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), ?, ?, ?, ?, ?, (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 161         @values = (conv_i($form->{id}), $form->{AR_amounts}{"amount_$i"}, conv_i($form->{"amount_$i"}), conv_date($form->{transdate}), $project_id,
 
 162                    conv_i($form->{"taxkey_$i"}), conv_i($form->{"tax_id_$i"}), $form->{AR_amounts}{"amount_$i"});
 
 163         do_query($form, $dbh, $query, @values);
 
 165         if ($form->{"tax_$i"} != 0) {
 
 166           # insert detail records in acc_trans
 
 167           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link)
 
 168                        VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), ?, ?, ?, ?, ?, (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 169           @values = (conv_i($form->{id}), $form->{AR_amounts}{"tax_$i"}, conv_i($form->{"tax_$i"}), conv_date($form->{transdate}), $project_id,
 
 170                      conv_i($form->{"taxkey_$i"}), conv_i($form->{"tax_id_$i"}), $form->{AR_amounts}{"tax_$i"});
 
 171           do_query($form, $dbh, $query, @values);
 
 177     $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link)
 
 178                  VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, (SELECT taxkey_id FROM chart WHERE accno = ?),
 
 181                   WHERE chart_id= (SELECT id
 
 185                   ORDER BY startdate DESC LIMIT 1),
 
 186                  (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 187     @values = (conv_i($form->{id}), $form->{AR_amounts}{receivables}, conv_i($form->{receivables}), conv_date($form->{transdate}),
 
 188                 $form->{AR_amounts}{receivables}, $form->{AR_amounts}{receivables}, conv_date($form->{transdate}), $form->{AR_amounts}{receivables});
 
 189     do_query($form, $dbh, $query, @values);
 
 192     # Record paid amount.
 
 193     $query = qq|UPDATE ar SET paid = ?, datepaid = ? WHERE id = ?|;
 
 194     do_query($form, $dbh, $query,  $form->{paid}, $form->{paid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
 
 197   $form->new_lastmtime('ar');
 
 199   # add paid transactions
 
 200   for my $i (1 .. $form->{paidaccounts}) {
 
 202     if ($form->{"acc_trans_id_$i"} && $payments_only && (SL::DB::Default->get->payments_changeable == 0)) {
 
 206     if ($form->{"paid_$i"} != 0) {
 
 207       my $project_id = conv_i($form->{"paid_project_id_$i"});
 
 209       $form->{"AR_paid_$i"} =~ s/\"//g;
 
 210       ($form->{AR}{"paid_$i"}) = split(/--/, $form->{"AR_paid_$i"});
 
 211       $form->{"datepaid_$i"} = $form->{transdate}
 
 212         unless ($form->{"datepaid_$i"});
 
 214       $form->{"exchangerate_$i"} = ($form->{currency} eq $form->{defaultcurrency}) ? 1 :
 
 215         ( $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy') ||
 
 216           $form->parse_amount($myconfig, $form->{"exchangerate_$i"}) );
 
 218       # if there is no amount and invtotal is zero there is no exchangerate
 
 219       $form->{exchangerate} = $form->{"exchangerate_$i"}
 
 220         if ($form->{amount} == 0 && $form->{netamount} == 0);
 
 223       $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
 
 227         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link)
 
 228                      VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, (SELECT taxkey_id FROM chart WHERE accno = ?),
 
 231                       WHERE chart_id= (SELECT id
 
 235                       ORDER BY startdate DESC LIMIT 1),
 
 236                      (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 237         @values = (conv_i($form->{id}), $form->{AR}{receivables}, $amount, conv_date($form->{"datepaid_$i"}), $project_id, $form->{AR}{receivables}, $form->{AR}{receivables}, conv_date($form->{"datepaid_$i"}),
 
 238         $form->{AR}{receivables});
 
 240         do_query($form, $dbh, $query, @values);
 
 243       if ($form->{"paid_$i"} != 0) {
 
 245         my $project_id = conv_i($form->{"paid_project_id_$i"});
 
 246         my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
 
 247         $amount = $form->{"paid_$i"} * -1;
 
 248         $query  = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, project_id, taxkey, tax_id, chart_link)
 
 249                      VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE accno = ?),
 
 252                       WHERE chart_id= (SELECT id
 
 256                       ORDER BY startdate DESC LIMIT 1),
 
 257                      (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 258         @values = (conv_i($form->{id}), $form->{AR}{"paid_$i"}, $amount, conv_date($form->{"datepaid_$i"}), $gldate, $form->{"source_$i"}, $form->{"memo_$i"}, $project_id, $form->{AR}{"paid_$i"},
 
 259                     $form->{AR}{"paid_$i"}, conv_date($form->{"datepaid_$i"}), $form->{AR}{"paid_$i"});
 
 260         do_query($form, $dbh, $query, @values);
 
 262         # exchangerate difference for payment
 
 263         $amount = $form->round_amount( $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) * -1, 2);
 
 266           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link)
 
 267                        VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, (SELECT taxkey_id FROM chart WHERE accno = ?),
 
 270                         WHERE chart_id= (SELECT id
 
 274                         ORDER BY startdate DESC LIMIT 1),
 
 275                        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 276           @values = (conv_i($form->{id}), $form->{AR}{"paid_$i"}, $amount, conv_date($form->{"datepaid_$i"}), $project_id, $form->{AR}{"paid_$i"},
 
 277                     $form->{AR}{"paid_$i"}, conv_date($form->{"datepaid_$i"}), $form->{AR}{"paid_$i"});
 
 278           do_query($form, $dbh, $query, @values);
 
 281         # exchangerate gain/loss
 
 282         $amount = $form->round_amount( $form->{"paid_$i"} * ($form->{exchangerate} - $form->{"exchangerate_$i"}) * -1, 2);
 
 285           # fetch fxgain and fxloss chart info from defaults if charts aren't already filled in form
 
 286           if ( !$form->{fxgain_accno} && $::instance_conf->get_fxgain_accno_id ) {
 
 287             $form->{fxgain_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxgain_accno_id)->accno;
 
 289           if ( !$form->{fxloss_accno} && $::instance_conf->get_fxloss_accno_id ) {
 
 290             $form->{fxloss_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxloss_accno_id)->accno;
 
 292           die "fxloss_accno missing" if $amount < 0 and not $form->{fxloss_accno};
 
 293           die "fxgain_accno missing" if $amount > 0 and not $form->{fxgain_accno};
 
 294           my $accno = ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno};
 
 295           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link)
 
 296                        VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, (SELECT taxkey_id FROM chart WHERE accno = ?),
 
 299                         WHERE chart_id= (SELECT id
 
 303                         ORDER BY startdate DESC LIMIT 1),
 
 304                        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 305           @values = (conv_i($form->{id}), $accno, $amount, conv_date($form->{"datepaid_$i"}), $project_id, $accno, $accno, conv_date($form->{"datepaid_$i"}), $accno);
 
 306           do_query($form, $dbh, $query, @values);
 
 310       # update exchangerate record
 
 311       $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, $form->{"exchangerate_$i"}, 0)
 
 312         if ($form->{currency} ne $form->{defaultcurrency}) && !$form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
 
 316   IO->set_datepaid(table => 'ar', id => $form->{id}, dbh => $dbh);
 
 318   # safety check datev export
 
 319   if ($::instance_conf->get_datev_check_on_ar_transaction) {
 
 320     my $transdate = $::form->{transdate} ? DateTime->from_lxoffice($::form->{transdate}) : undef;
 
 321     $transdate  ||= DateTime->today;
 
 323     my $datev = SL::DATEV->new(
 
 324       exporttype => DATEV_ET_BUCHUNGEN,
 
 325       format     => DATEV_FORMAT_KNE,
 
 327       trans_id   => $form->{id},
 
 332     if ($datev->errors) {
 
 333       die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
 
 340 sub _delete_payments {
 
 341   $main::lxdebug->enter_sub();
 
 343   my ($self, $form, $dbh) = @_;
 
 345   my @delete_acc_trans_ids;
 
 347   # Delete old payment entries from acc_trans.
 
 349     qq|SELECT acc_trans_id
 
 351        WHERE (trans_id = ?) AND fx_transaction
 
 355        SELECT at.acc_trans_id
 
 357        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 358        WHERE (trans_id = ?) AND (c.link LIKE '%AR_paid%')|;
 
 359   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
 
 362     qq|SELECT at.acc_trans_id
 
 364        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 366          AND ((c.link = 'AR') OR (c.link LIKE '%:AR') OR (c.link LIKE 'AR:%'))
 
 367        ORDER BY at.acc_trans_id
 
 369   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
 
 371   if (@delete_acc_trans_ids) {
 
 372     $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
 
 373     do_query($form, $dbh, $query);
 
 376   $main::lxdebug->leave_sub();
 
 380   my ($self, $myconfig, $form, $locale) = @_;
 
 381   $main::lxdebug->enter_sub();
 
 383   my $rc = SL::DB->client->with_transaction(\&_post_payment, $self, $myconfig, $form, $locale);
 
 385   $::lxdebug->leave_sub;
 
 390   my ($self, $myconfig, $form, $locale) = @_;
 
 392   my $dbh = SL::DB->client->dbh;
 
 394   my (%payments, $old_form, $row, $item, $query, %keep_vars);
 
 396   $old_form = save_form();
 
 398   # Delete all entries in acc_trans from prior payments.
 
 399   if (SL::DB::Default->get->payments_changeable != 0) {
 
 400     $self->_delete_payments($form, $dbh);
 
 403   # Save the new payments the user made before cleaning up $form.
 
 404   my $payments_re = '^datepaid_\d+$|^gldate_\d+$|^acc_trans_id_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^paid_project_id_\d+$|^AR_paid_\d+$|^paidaccounts$';
 
 405   map { $payments{$_} = $form->{$_} } grep m/$payments_re/, keys %{ $form };
 
 407   # Clean up $form so that old content won't tamper the results.
 
 408   %keep_vars = map { $_, 1 } qw(login password id);
 
 409   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
 
 411   # Retrieve the invoice from the database.
 
 412   $form->create_links('AR', $myconfig, 'customer', $dbh);
 
 414   # Restore the payment options from the user input.
 
 415   map { $form->{$_} = $payments{$_} } keys %payments;
 
 417   # Set up the content of $form in the way that AR::post_transaction() expects.
 
 419   $self->setup_form($form, 1);
 
 421   $form->{exchangerate}    = $form->format_amount($myconfig, $form->{exchangerate});
 
 422   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
 
 424   # Get the AR accno (which is normally done by Form::create_links()).
 
 428        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 430          AND ((c.link = 'AR') OR (c.link LIKE '%:AR') OR (c.link LIKE 'AR:%'))
 
 431        ORDER BY at.acc_trans_id
 
 434   ($form->{ARselected}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
 
 436   # Post the new payments.
 
 437   $self->post_transaction($myconfig, $form, $dbh, 1);
 
 439   restore_form($old_form);
 
 444 sub delete_transaction {
 
 445   $main::lxdebug->enter_sub();
 
 447   my ($self, $myconfig, $form) = @_;
 
 449   SL::DB->client->with_transaction(sub {
 
 450     # acc_trans entries are deleted by database triggers.
 
 451     my $query = qq|DELETE FROM ar WHERE id = ?|;
 
 452     do_query($form, SL::DB->client->dbh, $query, $form->{id});
 
 454   }) or do { die SL::DB->client->error };
 
 456   $main::lxdebug->leave_sub();
 
 461 sub ar_transactions {
 
 462   $main::lxdebug->enter_sub();
 
 464   my ($self, $myconfig, $form) = @_;
 
 466   # connect to database
 
 467   my $dbh = $form->get_standard_dbh($myconfig);
 
 472     qq|SELECT DISTINCT a.id, a.invnumber, a.ordnumber, a.cusordnumber, a.transdate, | .
 
 473     qq|  a.duedate, a.netamount, a.amount, a.paid, | .
 
 474     qq|  a.invoice, a.datepaid, a.notes, a.shipvia, | .
 
 475     qq|  a.shippingpoint, a.storno, a.storno_id, a.globalproject_id, | .
 
 476     qq|  a.marge_total, a.marge_percent, | .
 
 477     qq|  a.transaction_description, a.direct_debit, | .
 
 478     qq|  pr.projectnumber AS globalprojectnumber, | .
 
 479     qq|  c.name, c.customernumber, c.country, c.ustid, b.description as customertype, | .
 
 480     qq|  c.id as customer_id, | .
 
 481     qq|  e.name AS employee, | .
 
 482     qq|  e2.name AS salesman, | .
 
 483     qq|  dc.dunning_description, | .
 
 484     qq|  tz.description AS taxzone, | .
 
 485     qq|  pt.description AS payment_terms, | .
 
 486     qq|  d.description AS department, | .
 
 487     qq{  ( SELECT ch.accno || ' -- ' || ch.description
 
 489            LEFT JOIN chart ch ON ch.id = at.chart_id
 
 490            WHERE ch.link ~ 'AR[[:>:]]'
 
 491             AND at.trans_id = a.id
 
 495     qq|JOIN customer c ON (a.customer_id = c.id) | .
 
 496     qq|LEFT JOIN contacts cp ON (a.cp_id = cp.cp_id) | .
 
 497     qq|LEFT JOIN employee e ON (a.employee_id = e.id) | .
 
 498     qq|LEFT JOIN employee e2 ON (a.salesman_id = e2.id) | .
 
 499     qq|LEFT JOIN dunning_config dc ON (a.dunning_config_id = dc.id) | .
 
 500     qq|LEFT JOIN project pr ON (a.globalproject_id = pr.id)| .
 
 501     qq|LEFT JOIN tax_zones tz ON (tz.id = a.taxzone_id)| .
 
 502     qq|LEFT JOIN payment_terms pt ON (pt.id = a.payment_id)| .
 
 503     qq|LEFT JOIN business b ON (b.id = c.business_id)| .
 
 504     qq|LEFT JOIN department d ON (d.id = a.department_id)|;
 
 508   unless ( $::auth->assert('show_ar_transactions', 1) ) {
 
 509     $where .= " AND NOT invoice = 'f' ";  # remove ar transactions from Sales -> Reports -> Invoices
 
 512   if ($form->{customernumber}) {
 
 513     $where .= " AND c.customernumber = ?";
 
 514     push(@values, trim($form->{customernumber}));
 
 516   if ($form->{customer_id}) {
 
 517     $where .= " AND a.customer_id = ?";
 
 518     push(@values, $form->{customer_id});
 
 519   } elsif ($form->{customer}) {
 
 520     $where .= " AND c.name ILIKE ?";
 
 521     push(@values, like($form->{customer}));
 
 523   if ($form->{"cp_name"}) {
 
 524     $where .= " AND (cp.cp_name ILIKE ? OR cp.cp_givenname ILIKE ?)";
 
 525     push(@values, (like($form->{"cp_name"}))x2);
 
 527   if ($form->{business_id}) {
 
 528     my $business_id = $form->{business_id};
 
 529     $where .= " AND c.business_id = ?";
 
 530     push(@values, $business_id);
 
 532   if ($form->{department_id}) {
 
 533     $where .= " AND a.department_id = ?";
 
 534     push(@values, $form->{department_id});
 
 536   foreach my $column (qw(invnumber ordnumber cusordnumber notes transaction_description)) {
 
 537     if ($form->{$column}) {
 
 538       $where .= " AND a.$column ILIKE ?";
 
 539       push(@values, like($form->{$column}));
 
 542   if ($form->{"project_id"}) {
 
 544       qq|AND ((a.globalproject_id = ?) OR EXISTS | .
 
 545       qq|  (SELECT * FROM invoice i | .
 
 546       qq|   WHERE i.project_id = ? AND i.trans_id = a.id) | .
 
 548       qq|  (SELECT * FROM acc_trans at | .
 
 549       qq|   WHERE at.project_id = ? AND at.trans_id = a.id)| .
 
 551     push(@values, $form->{project_id}, $form->{project_id}, $form->{project_id});
 
 554   if ($form->{transdatefrom}) {
 
 555     $where .= " AND a.transdate >= ?";
 
 556     push(@values, trim($form->{transdatefrom}));
 
 558   if ($form->{transdateto}) {
 
 559     $where .= " AND a.transdate <= ?";
 
 560     push(@values, trim($form->{transdateto}));
 
 562   if ($form->{duedatefrom}) {
 
 563     $where .= " AND a.duedate >= ?";
 
 564     push(@values, trim($form->{duedatefrom}));
 
 566   if ($form->{duedateto}) {
 
 567     $where .= " AND a.duedate <= ?";
 
 568     push(@values, trim($form->{duedateto}));
 
 570   if ($form->{open} || $form->{closed}) {
 
 571     unless ($form->{open} && $form->{closed}) {
 
 572       $where .= " AND a.amount <> a.paid" if ($form->{open});
 
 573       $where .= " AND a.amount = a.paid"  if ($form->{closed});
 
 577   if (!$main::auth->assert('sales_all_edit', 1)) {
 
 578     # only show own invoices
 
 579     $where .= " AND a.employee_id = (select id from employee where login= ?)";
 
 580     push (@values, $::myconfig{login});
 
 582     if ($form->{employee_id}) {
 
 583       $where .= " AND a.employee_id = ?";
 
 584       push @values, conv_i($form->{employee_id});
 
 586     if ($form->{salesman_id}) {
 
 587       $where .= " AND a.salesman_id = ?";
 
 588       push @values, conv_i($form->{salesman_id});
 
 592   if ($form->{parts_partnumber}) {
 
 595         SELECT invoice.trans_id
 
 597         LEFT JOIN parts ON (invoice.parts_id = parts.id)
 
 598         WHERE (invoice.trans_id = a.id)
 
 599           AND (parts.partnumber ILIKE ?)
 
 603     push @values, like($form->{parts_partnumber});
 
 606   if ($form->{parts_description}) {
 
 609         SELECT invoice.trans_id
 
 611         WHERE (invoice.trans_id = a.id)
 
 612           AND (invoice.description ILIKE ?)
 
 616     push @values, like($form->{parts_description});
 
 619   my ($cvar_where, @cvar_values) = CVar->build_filter_query('module'         => 'CT',
 
 620                                                             'trans_id_field' => 'c.id',
 
 624     $where .= qq| AND ($cvar_where)|;
 
 625     push @values, @cvar_values;
 
 628   my @a = qw(transdate invnumber name);
 
 629   push @a, "employee" if $form->{l_employee};
 
 630   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
 631   my $sortorder = join(', ', map { "$_ $sortdir" } @a);
 
 633   if (grep({ $_ eq $form->{sort} } qw(id transdate duedate invnumber ordnumber cusordnumber name datepaid employee shippingpoint shipvia transaction_description))) {
 
 634     $sortorder = $form->{sort} . " $sortdir";
 
 637   $query .= " WHERE $where ORDER BY $sortorder";
 
 639   my @result = selectall_hashref_query($form, $dbh, $query, @values);
 
 641   $form->{AR} = [ @result ];
 
 643   $main::lxdebug->leave_sub();
 
 647   $main::lxdebug->enter_sub();
 
 649   my ($self, $myconfig, $form) = @_;
 
 651   # connect to database
 
 652   my $dbh = SL::DB->client->dbh;
 
 656     "  (SELECT transdate FROM ar WHERE id = " .
 
 657     "    (SELECT MAX(id) FROM ar) LIMIT 1), " .
 
 659   ($form->{transdate}) = $dbh->selectrow_array($query);
 
 661   $main::lxdebug->leave_sub();
 
 665   $main::lxdebug->enter_sub();
 
 667   my ($self, $form, $for_post_payments) = @_;
 
 669   my ($exchangerate, $akey, $j, $k, $index, $taxamount, $totaltax, $taxrate, $diff, $totalwithholding, $withholdingrate,
 
 673   $form->{forex} = $form->{exchangerate};
 
 674   $exchangerate  = $form->{exchangerate} ? $form->{exchangerate} : 1;
 
 676   # expected keys: AR, AR_paid, AR_tax, AR_amount
 
 677   foreach my $key (keys %{ $form->{AR_links} }) {
 
 681     # if there is a value we have an old entry
 
 682     next unless $form->{acc_trans}{$key};
 
 684     # do not use old entries for payments. They come from the form
 
 685     # even if they are not changeable (then they are in hiddens)
 
 686     next if $for_post_payments && $key eq "AR_paid";
 
 688     for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
 
 689       if ($key eq "AR_paid") {
 
 691         $form->{"AR_paid_$j"} = $form->{acc_trans}{$key}->[$i-1]->{accno};
 
 693         $form->{"acc_trans_id_$j"}    = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
 
 695         $form->{"paid_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
 
 696         $form->{"datepaid_$j"}        = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
 
 697         $form->{"gldate_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
 
 698         $form->{"source_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{source};
 
 699         $form->{"memo_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{memo};
 
 700         $form->{"forex_$j"}           = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
 
 701         $form->{"exchangerate_$i"}    = $form->{"forex_$j"};
 
 702         $form->{"paid_project_id_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{project_id};
 
 703         $form->{paidaccounts}++;
 
 705       } else { # e.g. AR_amount, AR, AR_tax
 
 708         $akey =~ s/AR_//; # e.g. tax, amount, AR, used to store form key tax_$i, amount_$i, ...
 
 710         if ($key eq "AR_tax" || $key eq "AP_tax") { # AR_tax
 
 711           $form->{"${key}_$form->{acc_trans}{$key}->[$i-1]->{accno}"}  = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 712           # determine the rounded tax amounts for each account, e.g. tax_1776
 
 713           $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
 
 715           # check e.g. $form->{1776_rate}, does this make sense for AR_tax charts? Is this ever valid? If it was, totaltax would be calculated twice
 
 716           if ($form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"} > 0) {
 
 717             $totaltax += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
 
 718             $taxrate  += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
 
 721             $totalwithholding += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
 
 722             $withholdingrate  += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
 
 725           $index                 = $form->{acc_trans}{$key}->[$i - 1]->{index};
 
 726           $form->{"tax_$index"}  = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2); # convert the tax_$i amounts
 
 727           # currently totaltax is the sum of rounded tax amounts, is this correct?
 
 728           $totaltax             += $form->{"tax_$index"};
 
 730         } else { # e.g. AR_amount, AR
 
 732           $form->{"${akey}_$k"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
 
 734           if ($akey eq 'amount') {
 
 736             $totalamount += $form->{"${akey}_$i"};
 
 738             $form->{"oldprojectnumber_$k"} = $form->{acc_trans}{$key}->[$i-1]->{projectnumber};
 
 739             $form->{"projectnumber_$k"}    = $form->{acc_trans}{$key}->[$i-1]->{projectnumber};
 
 740             $form->{taxrate}               = $form->{acc_trans}{$key}->[$i - 1]->{rate};
 
 741             $form->{"project_id_$k"}       = $form->{acc_trans}{$key}->[$i-1]->{project_id};
 
 744           $form->{"${key}_$i"} = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 747             $form->{ARselected} = $form->{acc_trans}{$key}->[$i-1]->{accno};
 
 749           } elsif ($akey eq "amount") {
 
 750             $form->{"${key}_$k"}   = $form->{acc_trans}{$key}->[$i-1]->{accno} . "--" . $form->{acc_trans}{$key}->[$i-1]->{id};
 
 751             $form->{"taxchart_$k"} = $form->{acc_trans}{$key}->[$i-1]->{id}    . "--" . $form->{acc_trans}{$key}->[$i-1]->{rate};
 
 758   $form->{paidaccounts} = 1            if not defined $form->{paidaccounts};
 
 760   if ($form->{taxincluded} && $form->{taxrate} && $totalamount) {
 
 762     # add tax to amounts and invtotal
 
 763     for my $i (1 .. $form->{rowcount}) {
 
 764       $taxamount            = ($totaltax + $totalwithholding) * $form->{"amount_$i"} / $totalamount;
 
 765       $tax                  = $form->round_amount($taxamount, 2);
 
 766       $diff                += ($taxamount - $tax);
 
 767       $form->{"amount_$i"} += $form->{"tax_$i"};
 
 769     $form->{amount_1} += $form->round_amount($diff, 2);
 
 772   $taxamount   = $form->round_amount($taxamount, 2);
 
 773   $form->{tax} = $taxamount;
 
 775   $form->{invtotal} = $totalamount + $totaltax;
 
 777   $main::lxdebug->leave_sub();
 
 781   my ($self, $form, $myconfig, $id) = @_;
 
 782   $main::lxdebug->enter_sub();
 
 784   my $rc = SL::DB->client->with_transaction(\&_storno, $self, $form, $myconfig, $id);
 
 786   $::lxdebug->leave_sub;
 
 792   my ($self, $form, $myconfig, $id) = @_;
 
 794   my ($query, $new_id, $storno_row, $acc_trans_rows);
 
 795   my $dbh = SL::DB->client->dbh;
 
 797   $query = qq|SELECT nextval('glid')|;
 
 798   ($new_id) = selectrow_query($form, $dbh, $query);
 
 800   $query = qq|SELECT * FROM ar WHERE id = ?|;
 
 801   $storno_row = selectfirst_hashref_query($form, $dbh, $query, $id);
 
 803   $storno_row->{id}         = $new_id;
 
 804   $storno_row->{storno_id}  = $id;
 
 805   $storno_row->{storno}     = 't';
 
 806   $storno_row->{invnumber}  = 'Storno-' . $storno_row->{invnumber};
 
 807   $storno_row->{amount}    *= -1;
 
 808   $storno_row->{netamount} *= -1;
 
 809   $storno_row->{paid}       = $storno_row->{amount};
 
 811   delete @$storno_row{qw(itime mtime)};
 
 813   $query = sprintf 'INSERT INTO ar (%s) VALUES (%s)', join(', ', keys %$storno_row), join(', ', map '?', values %$storno_row);
 
 814   do_query($form, $dbh, $query, (values %$storno_row));
 
 816   $query = qq|UPDATE ar SET paid = amount + paid, storno = 't' WHERE id = ?|;
 
 817   do_query($form, $dbh, $query, $id);
 
 819   $form->new_lastmtime('ar') if $id == $form->{id};
 
 821   # now copy acc_trans entries
 
 822   $query = qq|SELECT a.*, c.link FROM acc_trans a LEFT JOIN chart c ON a.chart_id = c.id WHERE a.trans_id = ? ORDER BY a.acc_trans_id|;
 
 823   my $rowref = selectall_hashref_query($form, $dbh, $query, $id);
 
 825   # kill all entries containing payments, which are the last 2n rows, of which the last has link =~ /paid/
 
 826   while ($rowref->[-1]{link} =~ /paid/) {
 
 827     splice(@$rowref, -2);
 
 830   for my $row (@$rowref) {
 
 831     delete @$row{qw(itime mtime link acc_trans_id)};
 
 832     $query = sprintf 'INSERT INTO acc_trans (%s) VALUES (%s)', join(', ', keys %$row), join(', ', map '?', values %$row);
 
 833     $row->{trans_id}   = $new_id;
 
 834     $row->{amount}    *= -1;
 
 835     do_query($form, $dbh, $query, (values %$row));
 
 838   map { IO->set_datepaid(table => 'ar', id => $_, dbh => $dbh) } ($id, $new_id);