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   $form->{AR_amounts}{"amount_$_"} = $form->{"AR_amount_chart_id_$_"} for (1 .. $form->{rowcount});
 
  80   $form->{tax}       = 0; # is this still needed?
 
  82   # main calculation of rowcount loop inside Form method, amount_$i and tax_$i get formatted
 
  83   $form->{taxincluded} = 0 unless $form->{taxincluded};
 
  84   ($form->{netamount},$form->{total_tax},$form->{amount}) = $form->calculate_arap('sell', $form->{taxincluded}, $form->{exchangerate});
 
  86   # adjust paidaccounts if there is no date in the last row
 
  87   # this does not apply to stornos, where the paid field is set manually
 
  88   unless ($form->{storno}) {
 
  89     $form->{paidaccounts}-- unless $form->{"datepaid_$form->{paidaccounts}"};
 
  93     for $i (1 .. $form->{paidaccounts}) {
 
  94       $form->{"paid_$i"} = $form->round_amount($form->parse_amount($myconfig, $form->{"paid_$i"}), 2);
 
  95       $form->{paid}     += $form->{"paid_$i"};
 
  96       $form->{datepaid}  = $form->{"datepaid_$i"};
 
 100   $form->{paid}   = $form->round_amount($form->{paid} * ($form->{exchangerate} || 1), 2);
 
 102   ($null, $form->{employee_id}) = split /--/, $form->{employee};
 
 104   $form->get_employee($dbh) unless $form->{employee_id};
 
 106   # if we have an id delete old records else make one
 
 107   if (!$payments_only) {
 
 109       # delete detail records
 
 110       $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
 
 111       do_query($form, $dbh, $query, $form->{id});
 
 114       $query = qq|SELECT nextval('glid')|;
 
 115       ($form->{id}) = selectrow_query($form, $dbh, $query);
 
 116       $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 = ?))|;
 
 117       do_query($form, $dbh, $query, $form->{id}, $form->{employee_id}, $form->{currency}, $form->{customer_id});
 
 118       if (!$form->{invnumber}) {
 
 119         my $trans_number   = SL::TransNumber->new(type => 'invoice', dbh => $dbh, number => $form->{partnumber}, id => $form->{id});
 
 120         $form->{invnumber} = $trans_number->create_unique;
 
 125   # amount for AR account
 
 126   $form->{receivables} = $form->round_amount($form->{amount}, 2) * -1;
 
 128   # update exchangerate
 
 129   $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate}, $form->{exchangerate}, 0)
 
 130     if ($form->{currency} ne $form->{defaultcurrency}) && !$form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'buy');
 
 132   if (!$payments_only) {
 
 135            invnumber = ?, ordnumber = ?, transdate = ?, customer_id = ?,
 
 136            taxincluded = ?, amount = ?, duedate = ?, paid = ?,
 
 137            currency_id = (SELECT id FROM currencies WHERE name = ?),
 
 138            netamount = ?, notes = ?, department_id = ?,
 
 139            employee_id = ?, storno = ?, storno_id = ?, globalproject_id = ?,
 
 142     my @values = ($form->{invnumber}, $form->{ordnumber}, conv_date($form->{transdate}), conv_i($form->{customer_id}), $form->{taxincluded} ? 't' : 'f', $form->{amount},
 
 143                   conv_date($form->{duedate}), $form->{paid},
 
 145                   $form->{netamount}, $form->{notes}, conv_i($form->{department_id}),
 
 146                   conv_i($form->{employee_id}), $form->{storno} ? 't' : 'f', $form->{storno_id},
 
 147                   conv_i($form->{globalproject_id}), $form->{direct_debit} ? 't' : 'f', conv_i($form->{id}));
 
 148     do_query($form, $dbh, $query, @values);
 
 150     # add individual transactions for AR, amount and taxes
 
 151     for $i (1 .. $form->{rowcount}) {
 
 152       if ($form->{"amount_$i"} != 0) {
 
 153         my $project_id = conv_i($form->{"project_id_$i"});
 
 155         # insert detail records in acc_trans
 
 156         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link)
 
 157                      VALUES (?, ?, ?, ?, ?, ?, ?, (SELECT c.link FROM chart c WHERE c.id = ?))|;
 
 158         @values = (conv_i($form->{id}), $form->{AR_amounts}{"amount_$i"}, conv_i($form->{"amount_$i"}), conv_date($form->{transdate}), $project_id,
 
 159                    conv_i($form->{"taxkey_$i"}), conv_i($form->{"tax_id_$i"}), $form->{AR_amounts}{"amount_$i"});
 
 160         do_query($form, $dbh, $query, @values);
 
 162         if ($form->{"tax_$i"} != 0) {
 
 163           # insert detail records in acc_trans
 
 164           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link)
 
 165                        VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), ?, ?, ?, ?, ?, (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 166           @values = (conv_i($form->{id}), $form->{AR_amounts}{"tax_$i"}, conv_i($form->{"tax_$i"}), conv_date($form->{transdate}), $project_id,
 
 167                      conv_i($form->{"taxkey_$i"}), conv_i($form->{"tax_id_$i"}), $form->{AR_amounts}{"tax_$i"});
 
 168           do_query($form, $dbh, $query, @values);
 
 174     $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link)
 
 175                  VALUES (?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE id = ?),
 
 180                   ORDER BY startdate DESC LIMIT 1),
 
 181                  (SELECT c.link FROM chart c WHERE c.id = ?))|;
 
 182     @values = (conv_i($form->{id}), $form->{AR_chart_id}, conv_i($form->{receivables}), conv_date($form->{transdate}),
 
 183                 $form->{AR_chart_id}, $form->{AR_chart_id}, conv_date($form->{transdate}), $form->{AR_chart_id});
 
 184     do_query($form, $dbh, $query, @values);
 
 187     # Record paid amount.
 
 188     $query = qq|UPDATE ar SET paid = ?, datepaid = ? WHERE id = ?|;
 
 189     do_query($form, $dbh, $query,  $form->{paid}, $form->{paid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
 
 192   $form->new_lastmtime('ar');
 
 194   # add paid transactions
 
 195   for my $i (1 .. $form->{paidaccounts}) {
 
 197     if ($form->{"acc_trans_id_$i"} && $payments_only && (SL::DB::Default->get->payments_changeable == 0)) {
 
 201     if ($form->{"paid_$i"} != 0) {
 
 202       my $project_id = conv_i($form->{"paid_project_id_$i"});
 
 204       $form->{"AR_paid_$i"} =~ s/\"//g;
 
 205       ($form->{AR}{"paid_$i"}) = split(/--/, $form->{"AR_paid_$i"});
 
 206       $form->{"datepaid_$i"} = $form->{transdate}
 
 207         unless ($form->{"datepaid_$i"});
 
 209       $form->{"exchangerate_$i"} = ($form->{currency} eq $form->{defaultcurrency}) ? 1 :
 
 210         ( $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy') ||
 
 211           $form->parse_amount($myconfig, $form->{"exchangerate_$i"}) );
 
 213       # if there is no amount and invtotal is zero there is no exchangerate
 
 214       $form->{exchangerate} = $form->{"exchangerate_$i"}
 
 215         if ($form->{amount} == 0 && $form->{netamount} == 0);
 
 218       $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
 
 222         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link)
 
 223                      VALUES (?, ?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE id = ?),
 
 228                       ORDER BY startdate DESC LIMIT 1),
 
 229                      (SELECT c.link FROM chart c WHERE c.id = ?))|;
 
 230         @values = (conv_i($form->{id}), $form->{AR_chart_id}, $amount, conv_date($form->{"datepaid_$i"}), $project_id, $form->{AR_chart_id}, $form->{AR_chart_id}, conv_date($form->{"datepaid_$i"}), $form->{AR_chart_id});
 
 232         do_query($form, $dbh, $query, @values);
 
 235       if ($form->{"paid_$i"} != 0) {
 
 237         my $project_id = conv_i($form->{"paid_project_id_$i"});
 
 238         my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
 
 239         $amount = $form->{"paid_$i"} * -1;
 
 240         $query  = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, project_id, taxkey, tax_id, chart_link)
 
 241                      VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE accno = ?),
 
 244                       WHERE chart_id= (SELECT id
 
 248                       ORDER BY startdate DESC LIMIT 1),
 
 249                      (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 250         @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"},
 
 251                     $form->{AR}{"paid_$i"}, conv_date($form->{"datepaid_$i"}), $form->{AR}{"paid_$i"});
 
 252         do_query($form, $dbh, $query, @values);
 
 254         # exchangerate difference for payment
 
 255         $amount = $form->round_amount( $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) * -1, 2);
 
 258           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link)
 
 259                        VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, (SELECT taxkey_id FROM chart WHERE accno = ?),
 
 262                         WHERE chart_id= (SELECT id
 
 266                         ORDER BY startdate DESC LIMIT 1),
 
 267                        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 268           @values = (conv_i($form->{id}), $form->{AR}{"paid_$i"}, $amount, conv_date($form->{"datepaid_$i"}), $project_id, $form->{AR}{"paid_$i"},
 
 269                     $form->{AR}{"paid_$i"}, conv_date($form->{"datepaid_$i"}), $form->{AR}{"paid_$i"});
 
 270           do_query($form, $dbh, $query, @values);
 
 273         # exchangerate gain/loss
 
 274         $amount = $form->round_amount( $form->{"paid_$i"} * ($form->{exchangerate} - $form->{"exchangerate_$i"}) * -1, 2);
 
 277           # fetch fxgain and fxloss chart info from defaults if charts aren't already filled in form
 
 278           if ( !$form->{fxgain_accno} && $::instance_conf->get_fxgain_accno_id ) {
 
 279             $form->{fxgain_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxgain_accno_id)->accno;
 
 281           if ( !$form->{fxloss_accno} && $::instance_conf->get_fxloss_accno_id ) {
 
 282             $form->{fxloss_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxloss_accno_id)->accno;
 
 284           die "fxloss_accno missing" if $amount < 0 and not $form->{fxloss_accno};
 
 285           die "fxgain_accno missing" if $amount > 0 and not $form->{fxgain_accno};
 
 286           my $accno = ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno};
 
 287           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link)
 
 288                        VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, (SELECT taxkey_id FROM chart WHERE accno = ?),
 
 291                         WHERE chart_id= (SELECT id
 
 295                         ORDER BY startdate DESC LIMIT 1),
 
 296                        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 297           @values = (conv_i($form->{id}), $accno, $amount, conv_date($form->{"datepaid_$i"}), $project_id, $accno, $accno, conv_date($form->{"datepaid_$i"}), $accno);
 
 298           do_query($form, $dbh, $query, @values);
 
 302       # update exchangerate record
 
 303       $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, $form->{"exchangerate_$i"}, 0)
 
 304         if ($form->{currency} ne $form->{defaultcurrency}) && !$form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
 
 308   IO->set_datepaid(table => 'ar', id => $form->{id}, dbh => $dbh);
 
 310   # safety check datev export
 
 311   if ($::instance_conf->get_datev_check_on_ar_transaction) {
 
 312     my $transdate = $::form->{transdate} ? DateTime->from_lxoffice($::form->{transdate}) : undef;
 
 313     $transdate  ||= DateTime->today;
 
 315     my $datev = SL::DATEV->new(
 
 316       exporttype => DATEV_ET_BUCHUNGEN,
 
 317       format     => DATEV_FORMAT_KNE,
 
 319       trans_id   => $form->{id},
 
 324     if ($datev->errors) {
 
 325       die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
 
 332 sub _delete_payments {
 
 333   $main::lxdebug->enter_sub();
 
 335   my ($self, $form, $dbh) = @_;
 
 337   my @delete_acc_trans_ids;
 
 339   # Delete old payment entries from acc_trans.
 
 341     qq|SELECT acc_trans_id
 
 343        WHERE (trans_id = ?) AND fx_transaction
 
 347        SELECT at.acc_trans_id
 
 349        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 350        WHERE (trans_id = ?) AND (c.link LIKE '%AR_paid%')|;
 
 351   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
 
 354     qq|SELECT at.acc_trans_id
 
 356        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 358          AND ((c.link = 'AR') OR (c.link LIKE '%:AR') OR (c.link LIKE 'AR:%'))
 
 359        ORDER BY at.acc_trans_id
 
 361   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
 
 363   if (@delete_acc_trans_ids) {
 
 364     $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
 
 365     do_query($form, $dbh, $query);
 
 368   $main::lxdebug->leave_sub();
 
 372   my ($self, $myconfig, $form, $locale) = @_;
 
 373   $main::lxdebug->enter_sub();
 
 375   my $rc = SL::DB->client->with_transaction(\&_post_payment, $self, $myconfig, $form, $locale);
 
 377   $::lxdebug->leave_sub;
 
 382   my ($self, $myconfig, $form, $locale) = @_;
 
 384   my $dbh = SL::DB->client->dbh;
 
 386   my (%payments, $old_form, $row, $item, $query, %keep_vars);
 
 388   $old_form = save_form();
 
 390   # Delete all entries in acc_trans from prior payments.
 
 391   if (SL::DB::Default->get->payments_changeable != 0) {
 
 392     $self->_delete_payments($form, $dbh);
 
 395   # Save the new payments the user made before cleaning up $form.
 
 396   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$';
 
 397   map { $payments{$_} = $form->{$_} } grep m/$payments_re/, keys %{ $form };
 
 399   # Clean up $form so that old content won't tamper the results.
 
 400   %keep_vars = map { $_, 1 } qw(login password id);
 
 401   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
 
 403   # Retrieve the invoice from the database.
 
 404   $form->create_links('AR', $myconfig, 'customer', $dbh);
 
 406   # Restore the payment options from the user input.
 
 407   map { $form->{$_} = $payments{$_} } keys %payments;
 
 409   # Set up the content of $form in the way that AR::post_transaction() expects.
 
 411   $self->setup_form($form, 1);
 
 413   $form->{exchangerate}    = $form->format_amount($myconfig, $form->{exchangerate});
 
 414   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
 
 416   # Get the AR chart ID (which is normally done by Form::create_links()).
 
 420        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 422          AND ((c.link = 'AR') OR (c.link LIKE '%:AR') OR (c.link LIKE 'AR:%'))
 
 423        ORDER BY at.acc_trans_id
 
 426   ($form->{AR_chart_id}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
 
 428   # Post the new payments.
 
 429   $self->post_transaction($myconfig, $form, $dbh, 1);
 
 431   restore_form($old_form);
 
 436 sub delete_transaction {
 
 437   $main::lxdebug->enter_sub();
 
 439   my ($self, $myconfig, $form) = @_;
 
 441   SL::DB->client->with_transaction(sub {
 
 442     # acc_trans entries are deleted by database triggers.
 
 443     my $query = qq|DELETE FROM ar WHERE id = ?|;
 
 444     do_query($form, SL::DB->client->dbh, $query, $form->{id});
 
 446   }) or do { die SL::DB->client->error };
 
 448   $main::lxdebug->leave_sub();
 
 453 sub ar_transactions {
 
 454   $main::lxdebug->enter_sub();
 
 456   my ($self, $myconfig, $form) = @_;
 
 458   # connect to database
 
 459   my $dbh = $form->get_standard_dbh($myconfig);
 
 464     qq|SELECT DISTINCT a.id, a.invnumber, a.ordnumber, a.cusordnumber, a.transdate, | .
 
 465     qq|  a.duedate, a.netamount, a.amount, a.paid, | .
 
 466     qq|  a.invoice, a.datepaid, a.notes, a.shipvia, | .
 
 467     qq|  a.shippingpoint, a.storno, a.storno_id, a.globalproject_id, | .
 
 468     qq|  a.marge_total, a.marge_percent, | .
 
 469     qq|  a.transaction_description, a.direct_debit, | .
 
 470     qq|  pr.projectnumber AS globalprojectnumber, | .
 
 471     qq|  c.name, c.customernumber, c.country, c.ustid, b.description as customertype, | .
 
 472     qq|  c.id as customer_id, | .
 
 473     qq|  e.name AS employee, | .
 
 474     qq|  e2.name AS salesman, | .
 
 475     qq|  dc.dunning_description, | .
 
 476     qq|  tz.description AS taxzone, | .
 
 477     qq|  pt.description AS payment_terms, | .
 
 478     qq|  d.description AS department, | .
 
 479     qq{  ( SELECT ch.accno || ' -- ' || ch.description
 
 481            LEFT JOIN chart ch ON ch.id = at.chart_id
 
 482            WHERE ch.link ~ 'AR[[:>:]]'
 
 483             AND at.trans_id = a.id
 
 487     qq|JOIN customer c ON (a.customer_id = c.id) | .
 
 488     qq|LEFT JOIN contacts cp ON (a.cp_id = cp.cp_id) | .
 
 489     qq|LEFT JOIN employee e ON (a.employee_id = e.id) | .
 
 490     qq|LEFT JOIN employee e2 ON (a.salesman_id = e2.id) | .
 
 491     qq|LEFT JOIN dunning_config dc ON (a.dunning_config_id = dc.id) | .
 
 492     qq|LEFT JOIN project pr ON (a.globalproject_id = pr.id)| .
 
 493     qq|LEFT JOIN tax_zones tz ON (tz.id = a.taxzone_id)| .
 
 494     qq|LEFT JOIN payment_terms pt ON (pt.id = a.payment_id)| .
 
 495     qq|LEFT JOIN business b ON (b.id = c.business_id)| .
 
 496     qq|LEFT JOIN department d ON (d.id = a.department_id)|;
 
 500   unless ( $::auth->assert('show_ar_transactions', 1) ) {
 
 501     $where .= " AND NOT invoice = 'f' ";  # remove ar transactions from Sales -> Reports -> Invoices
 
 504   if ($form->{customernumber}) {
 
 505     $where .= " AND c.customernumber = ?";
 
 506     push(@values, trim($form->{customernumber}));
 
 508   if ($form->{customer_id}) {
 
 509     $where .= " AND a.customer_id = ?";
 
 510     push(@values, $form->{customer_id});
 
 511   } elsif ($form->{customer}) {
 
 512     $where .= " AND c.name ILIKE ?";
 
 513     push(@values, like($form->{customer}));
 
 515   if ($form->{"cp_name"}) {
 
 516     $where .= " AND (cp.cp_name ILIKE ? OR cp.cp_givenname ILIKE ?)";
 
 517     push(@values, (like($form->{"cp_name"}))x2);
 
 519   if ($form->{business_id}) {
 
 520     my $business_id = $form->{business_id};
 
 521     $where .= " AND c.business_id = ?";
 
 522     push(@values, $business_id);
 
 524   if ($form->{department_id}) {
 
 525     $where .= " AND a.department_id = ?";
 
 526     push(@values, $form->{department_id});
 
 528   foreach my $column (qw(invnumber ordnumber cusordnumber notes transaction_description)) {
 
 529     if ($form->{$column}) {
 
 530       $where .= " AND a.$column ILIKE ?";
 
 531       push(@values, like($form->{$column}));
 
 534   if ($form->{"project_id"}) {
 
 536       qq|AND ((a.globalproject_id = ?) OR EXISTS | .
 
 537       qq|  (SELECT * FROM invoice i | .
 
 538       qq|   WHERE i.project_id = ? AND i.trans_id = a.id) | .
 
 540       qq|  (SELECT * FROM acc_trans at | .
 
 541       qq|   WHERE at.project_id = ? AND at.trans_id = a.id)| .
 
 543     push(@values, $form->{project_id}, $form->{project_id}, $form->{project_id});
 
 546   if ($form->{transdatefrom}) {
 
 547     $where .= " AND a.transdate >= ?";
 
 548     push(@values, trim($form->{transdatefrom}));
 
 550   if ($form->{transdateto}) {
 
 551     $where .= " AND a.transdate <= ?";
 
 552     push(@values, trim($form->{transdateto}));
 
 554   if ($form->{duedatefrom}) {
 
 555     $where .= " AND a.duedate >= ?";
 
 556     push(@values, trim($form->{duedatefrom}));
 
 558   if ($form->{duedateto}) {
 
 559     $where .= " AND a.duedate <= ?";
 
 560     push(@values, trim($form->{duedateto}));
 
 562   if ($form->{open} || $form->{closed}) {
 
 563     unless ($form->{open} && $form->{closed}) {
 
 564       $where .= " AND a.amount <> a.paid" if ($form->{open});
 
 565       $where .= " AND a.amount = a.paid"  if ($form->{closed});
 
 569   if (!$main::auth->assert('sales_all_edit', 1)) {
 
 570     # only show own invoices
 
 571     $where .= " AND a.employee_id = (select id from employee where login= ?)";
 
 572     push (@values, $::myconfig{login});
 
 574     if ($form->{employee_id}) {
 
 575       $where .= " AND a.employee_id = ?";
 
 576       push @values, conv_i($form->{employee_id});
 
 578     if ($form->{salesman_id}) {
 
 579       $where .= " AND a.salesman_id = ?";
 
 580       push @values, conv_i($form->{salesman_id});
 
 584   if ($form->{parts_partnumber}) {
 
 587         SELECT invoice.trans_id
 
 589         LEFT JOIN parts ON (invoice.parts_id = parts.id)
 
 590         WHERE (invoice.trans_id = a.id)
 
 591           AND (parts.partnumber ILIKE ?)
 
 595     push @values, like($form->{parts_partnumber});
 
 598   if ($form->{parts_description}) {
 
 601         SELECT invoice.trans_id
 
 603         WHERE (invoice.trans_id = a.id)
 
 604           AND (invoice.description ILIKE ?)
 
 608     push @values, like($form->{parts_description});
 
 611   my ($cvar_where, @cvar_values) = CVar->build_filter_query('module'         => 'CT',
 
 612                                                             'trans_id_field' => 'c.id',
 
 616     $where .= qq| AND ($cvar_where)|;
 
 617     push @values, @cvar_values;
 
 620   my @a = qw(transdate invnumber name);
 
 621   push @a, "employee" if $form->{l_employee};
 
 622   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
 623   my $sortorder = join(', ', map { "$_ $sortdir" } @a);
 
 625   if (grep({ $_ eq $form->{sort} } qw(id transdate duedate invnumber ordnumber cusordnumber name datepaid employee shippingpoint shipvia transaction_description))) {
 
 626     $sortorder = $form->{sort} . " $sortdir";
 
 629   $query .= " WHERE $where ORDER BY $sortorder";
 
 631   my @result = selectall_hashref_query($form, $dbh, $query, @values);
 
 633   $form->{AR} = [ @result ];
 
 635   $main::lxdebug->leave_sub();
 
 639   $main::lxdebug->enter_sub();
 
 641   my ($self, $myconfig, $form) = @_;
 
 643   # connect to database
 
 644   my $dbh = SL::DB->client->dbh;
 
 648     "  (SELECT transdate FROM ar WHERE id = " .
 
 649     "    (SELECT MAX(id) FROM ar) LIMIT 1), " .
 
 651   ($form->{transdate}) = $dbh->selectrow_array($query);
 
 653   $main::lxdebug->leave_sub();
 
 657   $main::lxdebug->enter_sub();
 
 659   my ($self, $form, $for_post_payments) = @_;
 
 661   my ($exchangerate, $akey, $j, $k, $index, $taxamount, $totaltax, $taxrate, $diff, $totalwithholding, $withholdingrate,
 
 665   $form->{forex} = $form->{exchangerate};
 
 666   $exchangerate  = $form->{exchangerate} ? $form->{exchangerate} : 1;
 
 668   # expected keys: AR, AR_paid, AR_tax, AR_amount
 
 669   foreach my $key (keys %{ $form->{AR_links} }) {
 
 673     # if there is a value we have an old entry
 
 674     next unless $form->{acc_trans}{$key};
 
 676     # do not use old entries for payments. They come from the form
 
 677     # even if they are not changeable (then they are in hiddens)
 
 678     next if $for_post_payments && $key eq "AR_paid";
 
 680     for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
 
 681       if ($key eq "AR_paid") {
 
 683         $form->{"AR_paid_$j"} = $form->{acc_trans}{$key}->[$i-1]->{accno};
 
 685         $form->{"acc_trans_id_$j"}    = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
 
 687         $form->{"paid_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
 
 688         $form->{"datepaid_$j"}        = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
 
 689         $form->{"gldate_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
 
 690         $form->{"source_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{source};
 
 691         $form->{"memo_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{memo};
 
 692         $form->{"forex_$j"}           = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
 
 693         $form->{"exchangerate_$i"}    = $form->{"forex_$j"};
 
 694         $form->{"paid_project_id_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{project_id};
 
 695         $form->{paidaccounts}++;
 
 697       } else { # e.g. AR_amount, AR, AR_tax
 
 700         $akey =~ s/AR_//; # e.g. tax, amount, AR, used to store form key tax_$i, amount_$i, ...
 
 702         if ($key eq "AR_tax" || $key eq "AP_tax") { # AR_tax
 
 703           $form->{"${key}_$form->{acc_trans}{$key}->[$i-1]->{accno}"}  = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 704           # determine the rounded tax amounts for each account, e.g. tax_1776
 
 705           $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
 
 707           # 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
 
 708           if ($form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"} > 0) {
 
 709             $totaltax += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
 
 710             $taxrate  += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
 
 713             $totalwithholding += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
 
 714             $withholdingrate  += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
 
 717           $index                 = $form->{acc_trans}{$key}->[$i - 1]->{index};
 
 718           $form->{"tax_$index"}  = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2); # convert the tax_$i amounts
 
 719           # currently totaltax is the sum of rounded tax amounts, is this correct?
 
 720           $totaltax             += $form->{"tax_$index"};
 
 722         } else { # e.g. AR_amount, AR
 
 724           $form->{"${akey}_$k"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
 
 726           if ($akey eq 'amount') {
 
 728             $totalamount += $form->{"${akey}_$i"};
 
 730             $form->{"oldprojectnumber_$k"} = $form->{acc_trans}{$key}->[$i-1]->{projectnumber};
 
 731             $form->{"projectnumber_$k"}    = $form->{acc_trans}{$key}->[$i-1]->{projectnumber};
 
 732             $form->{taxrate}               = $form->{acc_trans}{$key}->[$i - 1]->{rate};
 
 733             $form->{"project_id_$k"}       = $form->{acc_trans}{$key}->[$i-1]->{project_id};
 
 735             $form->{"${key}_chart_id_$k"} = $form->{acc_trans}{$key}->[$i-1]->{chart_id};
 
 736             $form->{"taxchart_$k"} = $form->{acc_trans}{$key}->[$i-1]->{id}    . "--" . $form->{acc_trans}{$key}->[$i-1]->{rate};
 
 743   $form->{paidaccounts} = 1            if not defined $form->{paidaccounts};
 
 745   if ($form->{taxincluded} && $form->{taxrate} && $totalamount) {
 
 747     # add tax to amounts and invtotal
 
 748     for my $i (1 .. $form->{rowcount}) {
 
 749       $taxamount            = ($totaltax + $totalwithholding) * $form->{"amount_$i"} / $totalamount;
 
 750       $tax                  = $form->round_amount($taxamount, 2);
 
 751       $diff                += ($taxamount - $tax);
 
 752       $form->{"amount_$i"} += $form->{"tax_$i"};
 
 754     $form->{amount_1} += $form->round_amount($diff, 2);
 
 757   $taxamount   = $form->round_amount($taxamount, 2);
 
 758   $form->{tax} = $taxamount;
 
 760   $form->{invtotal} = $totalamount + $totaltax;
 
 762   $main::lxdebug->leave_sub();
 
 766   my ($self, $form, $myconfig, $id) = @_;
 
 767   $main::lxdebug->enter_sub();
 
 769   my $rc = SL::DB->client->with_transaction(\&_storno, $self, $form, $myconfig, $id);
 
 771   $::lxdebug->leave_sub;
 
 777   my ($self, $form, $myconfig, $id) = @_;
 
 779   my ($query, $new_id, $storno_row, $acc_trans_rows);
 
 780   my $dbh = SL::DB->client->dbh;
 
 782   $query = qq|SELECT nextval('glid')|;
 
 783   ($new_id) = selectrow_query($form, $dbh, $query);
 
 785   $query = qq|SELECT * FROM ar WHERE id = ?|;
 
 786   $storno_row = selectfirst_hashref_query($form, $dbh, $query, $id);
 
 788   $storno_row->{id}         = $new_id;
 
 789   $storno_row->{storno_id}  = $id;
 
 790   $storno_row->{storno}     = 't';
 
 791   $storno_row->{invnumber}  = 'Storno-' . $storno_row->{invnumber};
 
 792   $storno_row->{amount}    *= -1;
 
 793   $storno_row->{netamount} *= -1;
 
 794   $storno_row->{paid}       = $storno_row->{amount};
 
 796   delete @$storno_row{qw(itime mtime)};
 
 798   $query = sprintf 'INSERT INTO ar (%s) VALUES (%s)', join(', ', keys %$storno_row), join(', ', map '?', values %$storno_row);
 
 799   do_query($form, $dbh, $query, (values %$storno_row));
 
 801   $query = qq|UPDATE ar SET paid = amount + paid, storno = 't' WHERE id = ?|;
 
 802   do_query($form, $dbh, $query, $id);
 
 804   $form->new_lastmtime('ar') if $id == $form->{id};
 
 806   # now copy acc_trans entries
 
 807   $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|;
 
 808   my $rowref = selectall_hashref_query($form, $dbh, $query, $id);
 
 810   # kill all entries containing payments, which are the last 2n rows, of which the last has link =~ /paid/
 
 811   while ($rowref->[-1]{link} =~ /paid/) {
 
 812     splice(@$rowref, -2);
 
 815   for my $row (@$rowref) {
 
 816     delete @$row{qw(itime mtime link acc_trans_id)};
 
 817     $query = sprintf 'INSERT INTO acc_trans (%s) VALUES (%s)', join(', ', keys %$row), join(', ', map '?', values %$row);
 
 818     $row->{trans_id}   = $new_id;
 
 819     $row->{amount}    *= -1;
 
 820     do_query($form, $dbh, $query, (values %$row));
 
 823   map { IO->set_datepaid(table => 'ar', id => $_, dbh => $dbh) } ($id, $new_id);