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 Payables database backend routines
 
  34 #======================================================================
 
  38 use SL::DATEV qw(:CONSTANTS);
 
  44 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) = @_;
 
  62   my $dbh = $provided_dbh || SL::DB->client->dbh;
 
  64   my ($null, $taxrate, $amount);
 
  67   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
 
  68   $form->{taxincluded} = 0 unless $form->{taxincluded};
 
  70   if ($form->{currency} eq $form->{defaultcurrency}) {
 
  71     $form->{exchangerate} = 1;
 
  73     $exchangerate         = $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'sell');
 
  74     $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
 
  77   # get the charts selected
 
  78   $form->{AP_amounts}{"amount_$_"} = $form->{"AP_amount_chart_id_$_"} for (1 .. $form->{rowcount});
 
  80   # calculate the totals while calculating and reformatting the $amount_$i and $tax_$i
 
  81   ($form->{netamount},$form->{total_tax},$form->{invtotal}) = $form->calculate_arap('buy',$form->{taxincluded}, $form->{exchangerate});
 
  83   # adjust paidaccounts if there is no date in the last row
 
  84   $form->{paidaccounts}-- unless ($form->{"datepaid_$form->{paidaccounts}"});
 
  89   for my $i (1 .. $form->{paidaccounts}) {
 
  91       $form->round_amount($form->parse_amount($myconfig, $form->{"paid_$i"}),
 
  94     $form->{invpaid} += $form->{"paid_$i"};
 
  95     $form->{datepaid} = $form->{"datepaid_$i"};
 
 100     $form->round_amount($form->{invpaid} * $form->{exchangerate}, 2);
 
 102   # # store invoice total, this goes into ap table
 
 103   # $form->{invtotal} = $form->{netamount} + $form->{total_tax};
 
 105   # amount for total AP
 
 106   $form->{payables} = $form->{invtotal};
 
 108   # update exchangerate
 
 109   if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
 
 110     $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate}, 0,
 
 111                                $form->{exchangerate});
 
 114   my ($query, $sth, @values);
 
 116   if (!$payments_only) {
 
 117     # if we have an id delete old records
 
 120       # delete detail records
 
 121       $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
 
 122       do_query($form, $dbh, $query, $form->{id});
 
 126       ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
 
 129         qq|INSERT INTO ap (id, invnumber, employee_id,currency_id, taxzone_id) | .
 
 130         qq|VALUES (?, ?, (SELECT e.id FROM employee e WHERE e.login = ?),
 
 131                       (SELECT id FROM currencies WHERE name = ?), (SELECT taxzone_id FROM vendor WHERE id = ?) )|;
 
 132       do_query($form, $dbh, $query, $form->{id}, $form->{invnumber}, $::myconfig{login}, $form->{currency}, $form->{vendor_id});
 
 136     $query = qq|UPDATE ap SET invnumber = ?,
 
 137                 transdate = ?, ordnumber = ?, vendor_id = ?, taxincluded = ?,
 
 138                 amount = ?, duedate = ?, paid = ?, netamount = ?,
 
 139                 currency_id = (SELECT id FROM currencies WHERE name = ?), notes = ?, department_id = ?, storno = ?, storno_id = ?,
 
 140                 globalproject_id = ?, direct_debit = ?
 
 142     @values = ($form->{invnumber}, conv_date($form->{transdate}),
 
 143                   $form->{ordnumber}, conv_i($form->{vendor_id}),
 
 144                   $form->{taxincluded} ? 't' : 'f', $form->{invtotal},
 
 145                   conv_date($form->{duedate}), $form->{invpaid},
 
 147                   $form->{currency}, $form->{notes},
 
 148                   conv_i($form->{department_id}), $form->{storno},
 
 149                   $form->{storno_id}, conv_i($form->{globalproject_id}),
 
 150                   $form->{direct_debit} ? 't' : 'f',
 
 152     do_query($form, $dbh, $query, @values);
 
 154     $form->new_lastmtime('ap');
 
 156     # add individual transactions
 
 157     for my $i (1 .. $form->{rowcount}) {
 
 158       if ($form->{"amount_$i"} != 0) {
 
 160         $project_id = conv_i($form->{"project_id_$i"});
 
 162         # insert detail records in acc_trans
 
 164           qq|INSERT INTO acc_trans | .
 
 165           qq|  (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link)| .
 
 166           qq|VALUES (?, ?,   ?, ?, ?, ?, ?, (SELECT c.link FROM chart c WHERE c.id = ?))|;
 
 167         @values = ($form->{id}, $form->{"AP_amount_chart_id_$i"},
 
 168                    $form->{"amount_$i"}, conv_date($form->{transdate}),
 
 169                    $project_id, $form->{"taxkey_$i"}, conv_i($form->{"tax_id_$i"}),
 
 170                    $form->{"AP_amount_chart_id_$i"});
 
 171         do_query($form, $dbh, $query, @values);
 
 173         if ($form->{"tax_$i"} != 0) {
 
 174           # insert detail records in acc_trans
 
 176             qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, | .
 
 177             qq|  project_id, taxkey, tax_id, chart_link) | .
 
 178             qq|VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), | .
 
 179             qq|  ?, ?, ?, ?, ?,| .
 
 180             qq| (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 181           @values = ($form->{id}, $form->{AP_amounts}{"tax_$i"},
 
 182                      $form->{"tax_$i"}, conv_date($form->{transdate}),
 
 183                      $project_id, $form->{"taxkey_$i"}, conv_i($form->{"tax_id_$i"}),
 
 184                      $form->{AP_amounts}{"tax_$i"});
 
 185           do_query($form, $dbh, $query, @values);
 
 193       qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) | .
 
 194       qq|VALUES (?, ?, ?, ?, | .
 
 195       qq|        (SELECT taxkey_id FROM chart WHERE id = ?),| .
 
 196       qq|        (SELECT tax_id| .
 
 198       qq|         WHERE chart_id = ?| .
 
 199       qq|         AND startdate <= ?| .
 
 200       qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 201       qq|        (SELECT c.link FROM chart c WHERE c.id = ?))|;
 
 202     @values = ($form->{id}, $form->{AP_chart_id}, $form->{payables},
 
 203                conv_date($form->{transdate}), $form->{AP_chart_id}, $form->{AP_chart_id}, conv_date($form->{transdate}),
 
 204                $form->{AP_chart_id});
 
 205     do_query($form, $dbh, $query, @values);
 
 208   # if there is no amount but a payment record a payable
 
 209   if ($form->{amount} == 0 && $form->{invtotal} == 0) {
 
 210     $form->{payables} = $form->{invpaid};
 
 213   # add paid transactions
 
 214   for my $i (1 .. $form->{paidaccounts}) {
 
 216     if ($form->{"acc_trans_id_$i"} && $payments_only && (SL::DB::Default->get->payments_changeable == 0)) {
 
 220     if ($form->{"paid_$i"} != 0) {
 
 221       my $project_id = conv_i($form->{"paid_project_id_$i"});
 
 224       if ($form->{currency} eq $form->{defaultcurrency}) {
 
 225         $form->{"exchangerate_$i"} = 1;
 
 227         $exchangerate              = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
 
 228         $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
 
 230       $form->{"AP_paid_$i"} =~ s/\"//g;
 
 234       ($form->{"AP_paid_account_$i"}) = split(/--/, $form->{"AP_paid_$i"});
 
 235       $form->{"datepaid_$i"} = $form->{transdate}
 
 236         unless ($form->{"datepaid_$i"});
 
 238       # if there is no amount and invtotal is zero there is no exchangerate
 
 239       if ($form->{amount} == 0 && $form->{invtotal} == 0) {
 
 240         $form->{exchangerate} = $form->{"exchangerate_$i"};
 
 244         $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} * -1,
 
 246       if ($form->{payables}) {
 
 248           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link) | .
 
 249           qq|VALUES (?, ?, ?, ?, ?, | .
 
 250           qq|        (SELECT taxkey_id FROM chart WHERE id = ?),| .
 
 251           qq|        (SELECT tax_id| .
 
 253           qq|         WHERE chart_id = ?| .
 
 254           qq|         AND startdate <= ?| .
 
 255           qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 256           qq|        (SELECT c.link FROM chart c WHERE c.id = ?))|;
 
 257         @values = ($form->{id}, $form->{AP_chart_id}, $amount,
 
 258                    conv_date($form->{"datepaid_$i"}), $project_id,
 
 259                    $form->{AP_chart_id}, $form->{AP_chart_id}, conv_date($form->{"datepaid_$i"}),
 
 260                    $form->{AP_chart_id});
 
 261         do_query($form, $dbh, $query, @values);
 
 263       $form->{payables} = $amount;
 
 266       my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
 
 268         qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, project_id, taxkey, tax_id, chart_link) | .
 
 269         qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?, ?, | .
 
 270         qq|        (SELECT taxkey_id FROM chart WHERE accno = ?), | .
 
 271         qq|        (SELECT tax_id| .
 
 273         qq|         WHERE chart_id= (SELECT id | .
 
 275         qq|                          WHERE accno = ?)| .
 
 276         qq|         AND startdate <= ?| .
 
 277         qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 278         qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 279       @values = ($form->{id}, $form->{"AP_paid_account_$i"}, $form->{"paid_$i"},
 
 280                  conv_date($form->{"datepaid_$i"}), $gldate, $form->{"source_$i"},
 
 281                  $form->{"memo_$i"}, $project_id, $form->{"AP_paid_account_$i"},
 
 282                  $form->{"AP_paid_account_$i"}, conv_date($form->{"datepaid_$i"}),
 
 283                  $form->{"AP_paid_account_$i"});
 
 284       do_query($form, $dbh, $query, @values);
 
 286       # add exchange rate difference
 
 288         $form->round_amount($form->{"paid_$i"} *
 
 289                             ($form->{"exchangerate_$i"} - 1), 2);
 
 292           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link) | .
 
 293           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, | .
 
 294           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?), | .
 
 295           qq|        (SELECT tax_id| .
 
 297           qq|         WHERE chart_id= (SELECT id | .
 
 299           qq|                          WHERE accno = ?)| .
 
 300           qq|         AND startdate <= ?| .
 
 301           qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 302           qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 303         @values = ($form->{id}, $form->{"AP_paid_account_$i"}, $amount,
 
 304                    conv_date($form->{"datepaid_$i"}), $project_id,
 
 305                    $form->{"AP_paid_account_$i"},
 
 306                    $form->{"AP_paid_account_$i"}, conv_date($form->{"datepaid_$i"}),
 
 307                    $form->{"AP_paid_account_$i"});
 
 308         do_query($form, $dbh, $query, @values);
 
 311       # exchangerate gain/loss
 
 313         $form->round_amount($form->{"paid_$i"} *
 
 314                             ($form->{exchangerate} -
 
 315                              $form->{"exchangerate_$i"}), 2);
 
 318         # fetch fxgain and fxloss chart info from defaults if charts aren't already filled in form
 
 319         if ( !$form->{fxgain_accno} && $::instance_conf->get_fxgain_accno_id ) {
 
 320           $form->{fxgain_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxgain_accno_id)->accno;
 
 322         if ( !$form->{fxloss_accno} && $::instance_conf->get_fxloss_accno_id ) {
 
 323           $form->{fxloss_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxloss_accno_id)->accno;
 
 325         die "fxloss_accno missing" if $amount < 0 and not $form->{fxloss_accno};
 
 326         die "fxgain_accno missing" if $amount > 0 and not $form->{fxgain_accno};
 
 328           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link) | .
 
 329           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, | .
 
 330           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?),| .
 
 331           qq|        (SELECT tax_id| .
 
 333           qq|         WHERE chart_id= (SELECT id | .
 
 335           qq|                          WHERE accno = ?)| .
 
 336           qq|         AND startdate <= ?| .
 
 337           qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 338           qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 339         @values = ($form->{id},
 
 340                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno},
 
 341                    $amount, conv_date($form->{"datepaid_$i"}), $project_id,
 
 342                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno},
 
 343                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno}, conv_date($form->{"datepaid_$i"}),
 
 344                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno});
 
 345         do_query($form, $dbh, $query, @values);
 
 348       # update exchange rate record
 
 349       if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
 
 350         $form->update_exchangerate($dbh, $form->{currency},
 
 351                                    $form->{"datepaid_$i"},
 
 352                                    0, $form->{"exchangerate_$i"});
 
 357   if ($payments_only) {
 
 358     $query = qq|UPDATE ap SET paid = ?, datepaid = ? WHERE id = ?|;
 
 359     do_query($form, $dbh, $query,  $form->{invpaid}, $form->{invpaid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
 
 360     $form->new_lastmtime('ap');
 
 363   IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
 
 365   if ($form->{draft_id}) {
 
 366     SL::DB::Manager::Draft->delete_all(where => [ id => delete($form->{draft_id}) ]);
 
 369   # safety check datev export
 
 370   if ($::instance_conf->get_datev_check_on_ap_transaction) {
 
 371     my $transdate = $::form->{transdate} ? DateTime->from_lxoffice($::form->{transdate}) : undef;
 
 372     $transdate  ||= DateTime->today;
 
 374     my $datev = SL::DATEV->new(
 
 375       exporttype => DATEV_ET_BUCHUNGEN,
 
 376       format     => DATEV_FORMAT_KNE,
 
 378       trans_id   => $form->{id},
 
 383     if ($datev->errors) {
 
 384       die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
 
 391 sub delete_transaction {
 
 392   $main::lxdebug->enter_sub();
 
 394   my ($self, $myconfig, $form) = @_;
 
 396   SL::DB->client->with_transaction(sub {
 
 397     my $query = qq|DELETE FROM ap WHERE id = ?|;
 
 398     do_query($form, SL::DB->client->dbh, $query, $form->{id});
 
 400   }) or do { die SL::DB->client->error };
 
 402   $main::lxdebug->leave_sub();
 
 407 sub ap_transactions {
 
 408   $main::lxdebug->enter_sub();
 
 410   my ($self, $myconfig, $form) = @_;
 
 412   # connect to database
 
 413   my $dbh = $form->get_standard_dbh($myconfig);
 
 416     qq|SELECT a.id, a.invnumber, a.transdate, a.duedate, a.amount, a.paid, | .
 
 417     qq|  a.ordnumber, v.name, a.invoice, a.netamount, a.datepaid, a.notes, | .
 
 418     qq|  a.globalproject_id, a.storno, a.storno_id, a.direct_debit, | .
 
 419     qq|  pr.projectnumber AS globalprojectnumber, | .
 
 420     qq|  e.name AS employee, | .
 
 421     qq|  v.vendornumber, v.country, v.ustid, | .
 
 422     qq|  tz.description AS taxzone, | .
 
 423     qq|  pt.description AS payment_terms, | .
 
 424     qq{  ( SELECT ch.accno || ' -- ' || ch.description
 
 426            LEFT JOIN chart ch ON ch.id = at.chart_id
 
 427            WHERE ch.link ~ 'AP[[:>:]]'
 
 428             AND at.trans_id = a.id
 
 432     qq|JOIN vendor v ON (a.vendor_id = v.id) | .
 
 433     qq|LEFT JOIN contacts cp ON (a.cp_id = cp.cp_id) | .
 
 434     qq|LEFT JOIN employee e ON (a.employee_id = e.id) | .
 
 435     qq|LEFT JOIN project pr ON (a.globalproject_id = pr.id) | .
 
 436     qq|LEFT JOIN tax_zones tz ON (tz.id = a.taxzone_id)| .
 
 437     qq|LEFT JOIN payment_terms pt ON (pt.id = a.payment_id)|;
 
 441   unless ( $::auth->assert('show_ap_transactions', 1) ) {
 
 442     $where .= " AND NOT invoice = 'f' ";  # remove ap transactions from Sales -> Reports -> Invoices
 
 447   if ($form->{vendor}) {
 
 448     $where .= " AND v.name ILIKE ?";
 
 449     push(@values, like($form->{vendor}));
 
 451   if ($form->{"cp_name"}) {
 
 452     $where .= " AND (cp.cp_name ILIKE ? OR cp.cp_givenname ILIKE ?)";
 
 453     push(@values, (like($form->{"cp_name"}))x2);
 
 455   if ($form->{department_id}) {
 
 456     $where .= " AND a.department_id = ?";
 
 457     push(@values, $form->{department_id});
 
 459   if ($form->{invnumber}) {
 
 460     $where .= " AND a.invnumber ILIKE ?";
 
 461     push(@values, like($form->{invnumber}));
 
 463   if ($form->{ordnumber}) {
 
 464     $where .= " AND a.ordnumber ILIKE ?";
 
 465     push(@values, like($form->{ordnumber}));
 
 467   if ($form->{notes}) {
 
 468     $where .= " AND lower(a.notes) LIKE ?";
 
 469     push(@values, like($form->{notes}));
 
 471   if ($form->{project_id}) {
 
 473       qq| AND ((a.globalproject_id = ?) OR EXISTS | .
 
 474       qq|  (SELECT * FROM invoice i | .
 
 475       qq|   WHERE i.project_id = ? AND i.trans_id = a.id) | .
 
 477       qq|  (SELECT * FROM acc_trans at | .
 
 478       qq|   WHERE at.project_id = ? AND at.trans_id = a.id)| .
 
 480     push(@values, $form->{project_id}, $form->{project_id}, $form->{project_id});
 
 483   if ($form->{transdatefrom}) {
 
 484     $where .= " AND a.transdate >= ?";
 
 485     push(@values, trim($form->{transdatefrom}));
 
 487   if ($form->{transdateto}) {
 
 488     $where .= " AND a.transdate <= ?";
 
 489     push(@values, trim($form->{transdateto}));
 
 491   if ($form->{open} || $form->{closed}) {
 
 492     unless ($form->{open} && $form->{closed}) {
 
 493       $where .= " AND a.amount <> a.paid" if ($form->{open});
 
 494       $where .= " AND a.amount = a.paid"  if ($form->{closed});
 
 498   if ($form->{parts_partnumber}) {
 
 501         SELECT invoice.trans_id
 
 503         LEFT JOIN parts ON (invoice.parts_id = parts.id)
 
 504         WHERE (invoice.trans_id = a.id)
 
 505           AND (parts.partnumber ILIKE ?)
 
 509     push @values, like($form->{parts_partnumber});
 
 512   if ($form->{parts_description}) {
 
 515         SELECT invoice.trans_id
 
 517         WHERE (invoice.trans_id = a.id)
 
 518           AND (invoice.description ILIKE ?)
 
 522     push @values, like($form->{parts_description});
 
 526     substr($where, 0, 4, " WHERE ");
 
 530   my @a = qw(transdate invnumber name);
 
 531   push @a, "employee" if $form->{l_employee};
 
 532   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
 533   my $sortorder = join(', ', map { "$_ $sortdir" } @a);
 
 535   if (grep({ $_ eq $form->{sort} } qw(transdate id invnumber ordnumber name netamount tax amount paid datepaid due duedate notes employee transaction_description direct_debit))) {
 
 536     $sortorder = $form->{sort} . " $sortdir";
 
 539   $query .= " ORDER BY $sortorder";
 
 541   my @result = selectall_hashref_query($form, $dbh, $query, @values);
 
 543   $form->{AP} = [ @result ];
 
 545   $main::lxdebug->leave_sub();
 
 549   $main::lxdebug->enter_sub();
 
 551   my ($self, $myconfig, $form) = @_;
 
 553   # connect to database
 
 554   my $dbh = SL::DB->client->dbh;
 
 558     "  (SELECT transdate FROM ap WHERE id = " .
 
 559     "    (SELECT MAX(id) FROM ap) LIMIT 1), " .
 
 561   ($form->{transdate}) = $dbh->selectrow_array($query);
 
 563   $main::lxdebug->leave_sub();
 
 566 sub _delete_payments {
 
 567   $main::lxdebug->enter_sub();
 
 569   my ($self, $form, $dbh) = @_;
 
 571   my @delete_acc_trans_ids;
 
 573   # Delete old payment entries from acc_trans.
 
 575     qq|SELECT acc_trans_id
 
 577        WHERE (trans_id = ?) AND fx_transaction
 
 581        SELECT at.acc_trans_id
 
 583        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 584        WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
 
 585   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
 
 588     qq|SELECT at.acc_trans_id
 
 590        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 592          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
 
 593        ORDER BY at.acc_trans_id
 
 595   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
 
 597   if (@delete_acc_trans_ids) {
 
 598     $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
 
 599     do_query($form, $dbh, $query);
 
 602   $main::lxdebug->leave_sub();
 
 606   my ($self, $myconfig, $form, $locale) = @_;
 
 607   $main::lxdebug->enter_sub();
 
 609   my $rc = SL::DB->client->with_transaction(\&_post_payment, $self, $myconfig, $form, $locale);
 
 611   $::lxdebug->leave_sub;
 
 616   my ($self, $myconfig, $form, $locale) = @_;
 
 618   my $dbh = SL::DB->client->dbh;
 
 620   my (%payments, $old_form, $row, $item, $query, %keep_vars);
 
 622   $old_form = save_form();
 
 624   # Delete all entries in acc_trans from prior payments.
 
 625   if (SL::DB::Default->get->payments_changeable != 0) {
 
 626     $self->_delete_payments($form, $dbh);
 
 629   # Save the new payments the user made before cleaning up $form.
 
 630   my $payments_re = '^datepaid_\d+$|^gldate_\d+$|^acc_trans_id_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^paid_project_id_\d+$|^AP_paid_\d+$|^paidaccounts$';
 
 631   map { $payments{$_} = $form->{$_} } grep m/$payments_re/, keys %{ $form };
 
 633   # Clean up $form so that old content won't tamper the results.
 
 634   %keep_vars = map { $_, 1 } qw(login password id);
 
 635   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
 
 637   # Retrieve the invoice from the database.
 
 638   $form->create_links('AP', $myconfig, 'vendor', $dbh);
 
 640   # Restore the payment options from the user input.
 
 641   map { $form->{$_} = $payments{$_} } keys %payments;
 
 643   # Set up the content of $form in the way that AR::post_transaction() expects.
 
 645   $self->setup_form($form, 1);
 
 647   $form->{exchangerate}    = $form->format_amount($myconfig, $form->{exchangerate});
 
 648   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
 
 654        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 656          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
 
 657        ORDER BY at.acc_trans_id
 
 660   ($form->{AP_chart_id}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
 
 662   # Post the new payments.
 
 663   $self->post_transaction($myconfig, $form, $dbh, 1);
 
 665   restore_form($old_form);
 
 671   $main::lxdebug->enter_sub();
 
 673   my ($self, $form, $for_post_payments) = @_;
 
 675   my ($exchangerate, $i, $j, $k, $key, $akey, $ref, $index, $taxamount, $totalamount, $totaltax, $totalwithholding, $withholdingrate,
 
 679   $form->{forex} = $form->{exchangerate};
 
 680   $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
 
 682   foreach $key (keys %{ $form->{AP_links} }) {
 
 683     foreach $ref (@{ $form->{AP_links}{$key} }) {
 
 684       if ($key eq "AP_paid") {
 
 685         $form->{"select$key"} .= "<option value=\"$ref->{accno}\">$ref->{accno}--$ref->{description}</option>\n";
 
 687         $form->{"select$key"} .= "<option value=\"$ref->{accno}--$ref->{tax_id}\">$ref->{accno}--$ref->{description}</option>\n";
 
 691     $form->{$key} = $form->{"select$key"};
 
 696     # if there is a value we have an old entry
 
 697     next unless $form->{acc_trans}{$key};
 
 699     # do not use old entries for payments. They come from the form
 
 700     # even if they are not changeable (then they are in hiddens)
 
 701     next if $for_post_payments && $key eq "AP_paid";
 
 703     for $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
 
 705       if ($key eq "AP_paid") {
 
 707         $form->{"AP_paid_$j"}         = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 708         $form->{"acc_trans_id_$j"}    = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
 
 709         $form->{"paid_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{amount};
 
 710         $form->{"datepaid_$j"}        = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
 
 711         $form->{"gldate_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
 
 712         $form->{"source_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{source};
 
 713         $form->{"memo_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{memo};
 
 715         $form->{"exchangerate_$i"}    = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
 
 716         $form->{"forex_$j"}           = $form->{"exchangerate_$i"};
 
 717         $form->{"AP_paid_$j"}         = $form->{acc_trans}{$key}->[$i-1]->{accno};
 
 718         $form->{"paid_project_id_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{project_id};
 
 719         $form->{paidaccounts}++;
 
 725         if (($key eq "AP_tax") || ($key eq "AR_tax")) {
 
 726           $form->{"${key}_$form->{acc_trans}{$key}->[$i-1]->{accno}"}  = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 727           $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
 
 729           if ($form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"} > 0) {
 
 730             $totaltax += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
 
 732             $totalwithholding += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
 
 733             $withholdingrate  += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
 
 736           $index                 = $form->{acc_trans}{$key}->[$i - 1]->{index};
 
 737           $form->{"tax_$index"}  = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} * -1 / $exchangerate, 2);
 
 738           $totaltax             += $form->{"tax_$index"};
 
 742           $form->{"${akey}_$k"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
 
 744           if ($akey eq 'amount') {
 
 746             $form->{"${akey}_$i"} *= -1;
 
 747             $totalamount          += $form->{"${akey}_$i"};
 
 748             $form->{taxrate}       = $form->{acc_trans}{$key}->[$i - 1]->{rate};
 
 750             $form->{"projectnumber_$k"}    = "$form->{acc_trans}{$key}->[$i-1]->{projectnumber}";
 
 751             $form->{"oldprojectnumber_$k"} = $form->{"projectnumber_$k"};
 
 752             $form->{"project_id_$k"}       = "$form->{acc_trans}{$key}->[$i-1]->{project_id}";
 
 753             $form->{"${key}_chart_id_$k"}  = $form->{acc_trans}{$key}->[$i-1]->{chart_id};
 
 754             $form->{"taxchart_$k"} = $form->{acc_trans}{$key}->[$i-1]->{id}    . "--" . $form->{acc_trans}{$key}->[$i-1]->{rate};
 
 761   $form->{paidaccounts} = 1            if not defined $form->{paidaccounts};
 
 763   if ($form->{taxincluded} && $form->{taxrate} && $totalamount) {
 
 764     # add tax to amounts and invtotal
 
 765     for $i (1 .. $form->{rowcount}) {
 
 766       $taxamount            = ($totaltax + $totalwithholding) * $form->{"amount_$i"} / $totalamount;
 
 767       $tax                  = $form->round_amount($taxamount, 2);
 
 768       $diff                += ($taxamount - $tax);
 
 769       $form->{"amount_$i"} += $form->{"tax_$i"};
 
 772     $form->{amount_1} += $form->round_amount($diff, 2);
 
 775   $taxamount        = $form->round_amount($taxamount, 2);
 
 776   $form->{invtotal} = $totalamount + $totaltax;
 
 778   $main::lxdebug->leave_sub();
 
 782   my ($self, $form, $myconfig, $id) = @_;
 
 783   $main::lxdebug->enter_sub();
 
 785   my $rc = SL::DB->client->with_transaction(\&_storno, $self, $form, $myconfig, $id);
 
 787   $::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 ap 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 ap (%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 ap SET paid = amount + paid, storno = 't' WHERE id = ?|;
 
 817   do_query($form, $dbh, $query, $id);
 
 819   $form->new_lastmtime('ap') 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 => 'ap', id => $_, dbh => $dbh) } ($id, $new_id);