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);
 
  43 use SL::Util qw(trim);
 
  49 sub post_transaction {
 
  50   my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
 
  51   $main::lxdebug->enter_sub();
 
  53   my $rc = SL::DB->client->with_transaction(\&_post_transaction, $self, $myconfig, $form, $provided_dbh, $payments_only);
 
  55   $::lxdebug->leave_sub;
 
  59 sub _post_transaction {
 
  60   my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
 
  61   my $dbh = $provided_dbh || SL::DB->client->dbh;
 
  63   my ($null, $taxrate, $amount);
 
  66   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
 
  67   $form->{taxincluded} = 0 unless $form->{taxincluded};
 
  69   if ($form->{currency} eq $form->{defaultcurrency}) {
 
  70     $form->{exchangerate} = 1;
 
  72     $exchangerate         = $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'sell');
 
  73     $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
 
  76   # get the charts selected
 
  77   $form->{AP_amounts}{"amount_$_"} = $form->{"AP_amount_chart_id_$_"} for (1 .. $form->{rowcount});
 
  79   # calculate the totals while calculating and reformatting the $amount_$i and $tax_$i
 
  80   ($form->{netamount},$form->{total_tax},$form->{invtotal}) = $form->calculate_arap('buy',$form->{taxincluded}, $form->{exchangerate});
 
  82   # adjust paidaccounts if there is no date in the last row
 
  83   $form->{paidaccounts}-- unless ($form->{"datepaid_$form->{paidaccounts}"});
 
  88   for my $i (1 .. $form->{paidaccounts}) {
 
  90       $form->round_amount($form->parse_amount($myconfig, $form->{"paid_$i"}),
 
  93     $form->{invpaid} += $form->{"paid_$i"};
 
  94     $form->{datepaid} = $form->{"datepaid_$i"};
 
  99     $form->round_amount($form->{invpaid} * $form->{exchangerate}, 2);
 
 101   # # store invoice total, this goes into ap table
 
 102   # $form->{invtotal} = $form->{netamount} + $form->{total_tax};
 
 104   # amount for total AP
 
 105   $form->{payables} = $form->{invtotal};
 
 107   # update exchangerate
 
 108   if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
 
 109     $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate}, 0,
 
 110                                $form->{exchangerate});
 
 113   my ($query, $sth, @values);
 
 115   if (!$payments_only) {
 
 116     # if we have an id delete old records
 
 119       # delete detail records
 
 120       $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
 
 121       do_query($form, $dbh, $query, $form->{id});
 
 125       ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
 
 128         qq|INSERT INTO ap (id, invnumber, employee_id,currency_id, taxzone_id) | .
 
 129         qq|VALUES (?, ?, (SELECT e.id FROM employee e WHERE e.login = ?),
 
 130                       (SELECT id FROM currencies WHERE name = ?), (SELECT taxzone_id FROM vendor WHERE id = ?) )|;
 
 131       do_query($form, $dbh, $query, $form->{id}, $form->{invnumber}, $::myconfig{login}, $form->{currency}, $form->{vendor_id});
 
 135     $query = qq|UPDATE ap SET invnumber = ?,
 
 136                 transdate = ?, ordnumber = ?, vendor_id = ?, taxincluded = ?,
 
 137                 amount = ?, duedate = ?, paid = ?, netamount = ?,
 
 138                 currency_id = (SELECT id FROM currencies WHERE name = ?), notes = ?, department_id = ?, storno = ?, storno_id = ?,
 
 139                 globalproject_id = ?, direct_debit = ?
 
 141     @values = ($form->{invnumber}, conv_date($form->{transdate}),
 
 142                   $form->{ordnumber}, conv_i($form->{vendor_id}),
 
 143                   $form->{taxincluded} ? 't' : 'f', $form->{invtotal},
 
 144                   conv_date($form->{duedate}), $form->{invpaid},
 
 146                   $form->{currency}, $form->{notes},
 
 147                   conv_i($form->{department_id}), $form->{storno},
 
 148                   $form->{storno_id}, conv_i($form->{globalproject_id}),
 
 149                   $form->{direct_debit} ? 't' : 'f',
 
 151     do_query($form, $dbh, $query, @values);
 
 153     $form->new_lastmtime('ap');
 
 155     # add individual transactions
 
 156     for my $i (1 .. $form->{rowcount}) {
 
 157       if ($form->{"amount_$i"} != 0) {
 
 159         $project_id = conv_i($form->{"project_id_$i"});
 
 161         # insert detail records in acc_trans
 
 163           qq|INSERT INTO acc_trans | .
 
 164           qq|  (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link)| .
 
 165           qq|VALUES (?, ?,   ?, ?, ?, ?, ?, (SELECT c.link FROM chart c WHERE c.id = ?))|;
 
 166         @values = ($form->{id}, $form->{"AP_amount_chart_id_$i"},
 
 167                    $form->{"amount_$i"}, conv_date($form->{transdate}),
 
 168                    $project_id, $form->{"taxkey_$i"}, conv_i($form->{"tax_id_$i"}),
 
 169                    $form->{"AP_amount_chart_id_$i"});
 
 170         do_query($form, $dbh, $query, @values);
 
 172         if ($form->{"tax_$i"} != 0) {
 
 173           # insert detail records in acc_trans
 
 175             qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, | .
 
 176             qq|  project_id, taxkey, tax_id, chart_link) | .
 
 177             qq|VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), | .
 
 178             qq|  ?, ?, ?, ?, ?,| .
 
 179             qq| (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 180           @values = ($form->{id}, $form->{AP_amounts}{"tax_$i"},
 
 181                      $form->{"tax_$i"}, conv_date($form->{transdate}),
 
 182                      $project_id, $form->{"taxkey_$i"}, conv_i($form->{"tax_id_$i"}),
 
 183                      $form->{AP_amounts}{"tax_$i"});
 
 184           do_query($form, $dbh, $query, @values);
 
 192       qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) | .
 
 193       qq|VALUES (?, ?, ?, ?, | .
 
 194       qq|        (SELECT taxkey_id FROM chart WHERE id = ?),| .
 
 195       qq|        (SELECT tax_id| .
 
 197       qq|         WHERE chart_id = ?| .
 
 198       qq|         AND startdate <= ?| .
 
 199       qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 200       qq|        (SELECT c.link FROM chart c WHERE c.id = ?))|;
 
 201     @values = ($form->{id}, $form->{AP_chart_id}, $form->{payables},
 
 202                conv_date($form->{transdate}), $form->{AP_chart_id}, $form->{AP_chart_id}, conv_date($form->{transdate}),
 
 203                $form->{AP_chart_id});
 
 204     do_query($form, $dbh, $query, @values);
 
 207   # if there is no amount but a payment record a payable
 
 208   if ($form->{amount} == 0 && $form->{invtotal} == 0) {
 
 209     $form->{payables} = $form->{invpaid};
 
 212   # add paid transactions
 
 213   for my $i (1 .. $form->{paidaccounts}) {
 
 215     if ($form->{"acc_trans_id_$i"} && $payments_only && (SL::DB::Default->get->payments_changeable == 0)) {
 
 219     if ($form->{"paid_$i"} != 0) {
 
 220       my $project_id = conv_i($form->{"paid_project_id_$i"});
 
 223       if ($form->{currency} eq $form->{defaultcurrency}) {
 
 224         $form->{"exchangerate_$i"} = 1;
 
 226         $exchangerate              = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
 
 227         $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
 
 229       $form->{"AP_paid_$i"} =~ s/\"//g;
 
 233       ($form->{"AP_paid_account_$i"}) = split(/--/, $form->{"AP_paid_$i"});
 
 234       $form->{"datepaid_$i"} = $form->{transdate}
 
 235         unless ($form->{"datepaid_$i"});
 
 237       # if there is no amount and invtotal is zero there is no exchangerate
 
 238       if ($form->{amount} == 0 && $form->{invtotal} == 0) {
 
 239         $form->{exchangerate} = $form->{"exchangerate_$i"};
 
 243         $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} * -1,
 
 245       if ($form->{payables}) {
 
 247           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link) | .
 
 248           qq|VALUES (?, ?, ?, ?, ?, | .
 
 249           qq|        (SELECT taxkey_id FROM chart WHERE id = ?),| .
 
 250           qq|        (SELECT tax_id| .
 
 252           qq|         WHERE chart_id = ?| .
 
 253           qq|         AND startdate <= ?| .
 
 254           qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 255           qq|        (SELECT c.link FROM chart c WHERE c.id = ?))|;
 
 256         @values = ($form->{id}, $form->{AP_chart_id}, $amount,
 
 257                    conv_date($form->{"datepaid_$i"}), $project_id,
 
 258                    $form->{AP_chart_id}, $form->{AP_chart_id}, conv_date($form->{"datepaid_$i"}),
 
 259                    $form->{AP_chart_id});
 
 260         do_query($form, $dbh, $query, @values);
 
 262       $form->{payables} = $amount;
 
 265       my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
 
 267         qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, project_id, taxkey, tax_id, chart_link) | .
 
 268         qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?, ?, | .
 
 269         qq|        (SELECT taxkey_id FROM chart WHERE accno = ?), | .
 
 270         qq|        (SELECT tax_id| .
 
 272         qq|         WHERE chart_id= (SELECT id | .
 
 274         qq|                          WHERE accno = ?)| .
 
 275         qq|         AND startdate <= ?| .
 
 276         qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 277         qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 278       @values = ($form->{id}, $form->{"AP_paid_account_$i"}, $form->{"paid_$i"},
 
 279                  conv_date($form->{"datepaid_$i"}), $gldate, $form->{"source_$i"},
 
 280                  $form->{"memo_$i"}, $project_id, $form->{"AP_paid_account_$i"},
 
 281                  $form->{"AP_paid_account_$i"}, conv_date($form->{"datepaid_$i"}),
 
 282                  $form->{"AP_paid_account_$i"});
 
 283       do_query($form, $dbh, $query, @values);
 
 285       # add exchange rate difference
 
 287         $form->round_amount($form->{"paid_$i"} *
 
 288                             ($form->{"exchangerate_$i"} - 1), 2);
 
 291           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link) | .
 
 292           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, | .
 
 293           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?), | .
 
 294           qq|        (SELECT tax_id| .
 
 296           qq|         WHERE chart_id= (SELECT id | .
 
 298           qq|                          WHERE accno = ?)| .
 
 299           qq|         AND startdate <= ?| .
 
 300           qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 301           qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 302         @values = ($form->{id}, $form->{"AP_paid_account_$i"}, $amount,
 
 303                    conv_date($form->{"datepaid_$i"}), $project_id,
 
 304                    $form->{"AP_paid_account_$i"},
 
 305                    $form->{"AP_paid_account_$i"}, conv_date($form->{"datepaid_$i"}),
 
 306                    $form->{"AP_paid_account_$i"});
 
 307         do_query($form, $dbh, $query, @values);
 
 310       # exchangerate gain/loss
 
 312         $form->round_amount($form->{"paid_$i"} *
 
 313                             ($form->{exchangerate} -
 
 314                              $form->{"exchangerate_$i"}), 2);
 
 317         # fetch fxgain and fxloss chart info from defaults if charts aren't already filled in form
 
 318         if ( !$form->{fxgain_accno} && $::instance_conf->get_fxgain_accno_id ) {
 
 319           $form->{fxgain_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxgain_accno_id)->accno;
 
 321         if ( !$form->{fxloss_accno} && $::instance_conf->get_fxloss_accno_id ) {
 
 322           $form->{fxloss_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxloss_accno_id)->accno;
 
 324         die "fxloss_accno missing" if $amount < 0 and not $form->{fxloss_accno};
 
 325         die "fxgain_accno missing" if $amount > 0 and not $form->{fxgain_accno};
 
 327           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link) | .
 
 328           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, | .
 
 329           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?),| .
 
 330           qq|        (SELECT tax_id| .
 
 332           qq|         WHERE chart_id= (SELECT id | .
 
 334           qq|                          WHERE accno = ?)| .
 
 335           qq|         AND startdate <= ?| .
 
 336           qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 337           qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 338         @values = ($form->{id},
 
 339                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno},
 
 340                    $amount, conv_date($form->{"datepaid_$i"}), $project_id,
 
 341                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno},
 
 342                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno}, conv_date($form->{"datepaid_$i"}),
 
 343                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno});
 
 344         do_query($form, $dbh, $query, @values);
 
 347       # update exchange rate record
 
 348       if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
 
 349         $form->update_exchangerate($dbh, $form->{currency},
 
 350                                    $form->{"datepaid_$i"},
 
 351                                    0, $form->{"exchangerate_$i"});
 
 356   if ($payments_only) {
 
 357     $query = qq|UPDATE ap SET paid = ?, datepaid = ? WHERE id = ?|;
 
 358     do_query($form, $dbh, $query,  $form->{invpaid}, $form->{invpaid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
 
 359     $form->new_lastmtime('ap');
 
 362   IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
 
 364   # safety check datev export
 
 365   if ($::instance_conf->get_datev_check_on_ap_transaction) {
 
 366     my $transdate = $::form->{transdate} ? DateTime->from_lxoffice($::form->{transdate}) : undef;
 
 367     $transdate  ||= DateTime->today;
 
 369     my $datev = SL::DATEV->new(
 
 370       exporttype => DATEV_ET_BUCHUNGEN,
 
 371       format     => DATEV_FORMAT_KNE,
 
 373       trans_id   => $form->{id},
 
 378     if ($datev->errors) {
 
 379       die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
 
 386 sub delete_transaction {
 
 387   $main::lxdebug->enter_sub();
 
 389   my ($self, $myconfig, $form) = @_;
 
 391   SL::DB->client->with_transaction(sub {
 
 392     my $query = qq|DELETE FROM ap WHERE id = ?|;
 
 393     do_query($form, SL::DB->client->dbh, $query, $form->{id});
 
 395   }) or do { die SL::DB->client->error };
 
 397   $main::lxdebug->leave_sub();
 
 402 sub ap_transactions {
 
 403   $main::lxdebug->enter_sub();
 
 405   my ($self, $myconfig, $form) = @_;
 
 407   # connect to database
 
 408   my $dbh = $form->get_standard_dbh($myconfig);
 
 411     qq|SELECT a.id, a.invnumber, a.transdate, a.duedate, a.amount, a.paid, | .
 
 412     qq|  a.ordnumber, v.name, a.invoice, a.netamount, a.datepaid, a.notes, | .
 
 413     qq|  a.globalproject_id, a.storno, a.storno_id, a.direct_debit, | .
 
 414     qq|  pr.projectnumber AS globalprojectnumber, | .
 
 415     qq|  e.name AS employee, | .
 
 416     qq|  v.vendornumber, v.country, v.ustid, | .
 
 417     qq|  tz.description AS taxzone, | .
 
 418     qq|  pt.description AS payment_terms, | .
 
 419     qq{  ( SELECT ch.accno || ' -- ' || ch.description
 
 421            LEFT JOIN chart ch ON ch.id = at.chart_id
 
 422            WHERE ch.link ~ 'AP[[:>:]]'
 
 423             AND at.trans_id = a.id
 
 427     qq|JOIN vendor v ON (a.vendor_id = v.id) | .
 
 428     qq|LEFT JOIN contacts cp ON (a.cp_id = cp.cp_id) | .
 
 429     qq|LEFT JOIN employee e ON (a.employee_id = e.id) | .
 
 430     qq|LEFT JOIN project pr ON (a.globalproject_id = pr.id) | .
 
 431     qq|LEFT JOIN tax_zones tz ON (tz.id = a.taxzone_id)| .
 
 432     qq|LEFT JOIN payment_terms pt ON (pt.id = a.payment_id)|;
 
 436   unless ( $::auth->assert('show_ap_transactions', 1) ) {
 
 437     $where .= " AND NOT invoice = 'f' ";  # remove ap transactions from Sales -> Reports -> Invoices
 
 442   if ($form->{vendor}) {
 
 443     $where .= " AND v.name ILIKE ?";
 
 444     push(@values, like($form->{vendor}));
 
 446   if ($form->{"cp_name"}) {
 
 447     $where .= " AND (cp.cp_name ILIKE ? OR cp.cp_givenname ILIKE ?)";
 
 448     push(@values, (like($form->{"cp_name"}))x2);
 
 450   if ($form->{department_id}) {
 
 451     $where .= " AND a.department_id = ?";
 
 452     push(@values, $form->{department_id});
 
 454   if ($form->{invnumber}) {
 
 455     $where .= " AND a.invnumber ILIKE ?";
 
 456     push(@values, like($form->{invnumber}));
 
 458   if ($form->{ordnumber}) {
 
 459     $where .= " AND a.ordnumber ILIKE ?";
 
 460     push(@values, like($form->{ordnumber}));
 
 462   if ($form->{notes}) {
 
 463     $where .= " AND lower(a.notes) LIKE ?";
 
 464     push(@values, like($form->{notes}));
 
 466   if ($form->{project_id}) {
 
 468       qq| AND ((a.globalproject_id = ?) OR EXISTS | .
 
 469       qq|  (SELECT * FROM invoice i | .
 
 470       qq|   WHERE i.project_id = ? AND i.trans_id = a.id) | .
 
 472       qq|  (SELECT * FROM acc_trans at | .
 
 473       qq|   WHERE at.project_id = ? AND at.trans_id = a.id)| .
 
 475     push(@values, $form->{project_id}, $form->{project_id}, $form->{project_id});
 
 478   if ($form->{transdatefrom}) {
 
 479     $where .= " AND a.transdate >= ?";
 
 480     push(@values, trim($form->{transdatefrom}));
 
 482   if ($form->{transdateto}) {
 
 483     $where .= " AND a.transdate <= ?";
 
 484     push(@values, trim($form->{transdateto}));
 
 486   if ($form->{open} || $form->{closed}) {
 
 487     unless ($form->{open} && $form->{closed}) {
 
 488       $where .= " AND a.amount <> a.paid" if ($form->{open});
 
 489       $where .= " AND a.amount = a.paid"  if ($form->{closed});
 
 493   if ($form->{parts_partnumber}) {
 
 496         SELECT invoice.trans_id
 
 498         LEFT JOIN parts ON (invoice.parts_id = parts.id)
 
 499         WHERE (invoice.trans_id = a.id)
 
 500           AND (parts.partnumber ILIKE ?)
 
 504     push @values, like($form->{parts_partnumber});
 
 507   if ($form->{parts_description}) {
 
 510         SELECT invoice.trans_id
 
 512         WHERE (invoice.trans_id = a.id)
 
 513           AND (invoice.description ILIKE ?)
 
 517     push @values, like($form->{parts_description});
 
 521     substr($where, 0, 4, " WHERE ");
 
 525   my @a = qw(transdate invnumber name);
 
 526   push @a, "employee" if $form->{l_employee};
 
 527   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
 528   my $sortorder = join(', ', map { "$_ $sortdir" } @a);
 
 530   if (grep({ $_ eq $form->{sort} } qw(transdate id invnumber ordnumber name netamount tax amount paid datepaid due duedate notes employee transaction_description direct_debit))) {
 
 531     $sortorder = $form->{sort} . " $sortdir";
 
 534   $query .= " ORDER BY $sortorder";
 
 536   my @result = selectall_hashref_query($form, $dbh, $query, @values);
 
 538   $form->{AP} = [ @result ];
 
 540   $main::lxdebug->leave_sub();
 
 544   $main::lxdebug->enter_sub();
 
 546   my ($self, $myconfig, $form) = @_;
 
 548   # connect to database
 
 549   my $dbh = SL::DB->client->dbh;
 
 553     "  (SELECT transdate FROM ap WHERE id = " .
 
 554     "    (SELECT MAX(id) FROM ap) LIMIT 1), " .
 
 556   ($form->{transdate}) = $dbh->selectrow_array($query);
 
 558   $main::lxdebug->leave_sub();
 
 561 sub _delete_payments {
 
 562   $main::lxdebug->enter_sub();
 
 564   my ($self, $form, $dbh) = @_;
 
 566   my @delete_acc_trans_ids;
 
 568   # Delete old payment entries from acc_trans.
 
 570     qq|SELECT acc_trans_id
 
 572        WHERE (trans_id = ?) AND fx_transaction
 
 576        SELECT at.acc_trans_id
 
 578        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 579        WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
 
 580   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
 
 583     qq|SELECT at.acc_trans_id
 
 585        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 587          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
 
 588        ORDER BY at.acc_trans_id
 
 590   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
 
 592   if (@delete_acc_trans_ids) {
 
 593     $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
 
 594     do_query($form, $dbh, $query);
 
 597   $main::lxdebug->leave_sub();
 
 601   my ($self, $myconfig, $form, $locale) = @_;
 
 602   $main::lxdebug->enter_sub();
 
 604   my $rc = SL::DB->client->with_transaction(\&_post_payment, $self, $myconfig, $form, $locale);
 
 606   $::lxdebug->leave_sub;
 
 611   my ($self, $myconfig, $form, $locale) = @_;
 
 613   my $dbh = SL::DB->client->dbh;
 
 615   my (%payments, $old_form, $row, $item, $query, %keep_vars);
 
 617   $old_form = save_form();
 
 619   # Delete all entries in acc_trans from prior payments.
 
 620   if (SL::DB::Default->get->payments_changeable != 0) {
 
 621     $self->_delete_payments($form, $dbh);
 
 624   # Save the new payments the user made before cleaning up $form.
 
 625   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$';
 
 626   map { $payments{$_} = $form->{$_} } grep m/$payments_re/, keys %{ $form };
 
 628   # Clean up $form so that old content won't tamper the results.
 
 629   %keep_vars = map { $_, 1 } qw(login password id);
 
 630   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
 
 632   # Retrieve the invoice from the database.
 
 633   $form->create_links('AP', $myconfig, 'vendor', $dbh);
 
 635   # Restore the payment options from the user input.
 
 636   map { $form->{$_} = $payments{$_} } keys %payments;
 
 638   # Set up the content of $form in the way that AR::post_transaction() expects.
 
 640   $self->setup_form($form, 1);
 
 642   $form->{exchangerate}    = $form->format_amount($myconfig, $form->{exchangerate});
 
 643   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
 
 649        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 651          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
 
 652        ORDER BY at.acc_trans_id
 
 655   ($form->{APselected}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
 
 657   # Post the new payments.
 
 658   $self->post_transaction($myconfig, $form, $dbh, 1);
 
 660   restore_form($old_form);
 
 666   $main::lxdebug->enter_sub();
 
 668   my ($self, $form, $for_post_payments) = @_;
 
 670   my ($exchangerate, $i, $j, $k, $key, $akey, $ref, $index, $taxamount, $totalamount, $totaltax, $totalwithholding, $withholdingrate,
 
 674   $form->{forex} = $form->{exchangerate};
 
 675   $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
 
 677   foreach $key (keys %{ $form->{AP_links} }) {
 
 678     foreach $ref (@{ $form->{AP_links}{$key} }) {
 
 679       if ($key eq "AP_paid") {
 
 680         $form->{"select$key"} .= "<option value=\"$ref->{accno}\">$ref->{accno}--$ref->{description}</option>\n";
 
 682         $form->{"select$key"} .= "<option value=\"$ref->{accno}--$ref->{tax_id}\">$ref->{accno}--$ref->{description}</option>\n";
 
 686     $form->{$key} = $form->{"select$key"};
 
 691     # if there is a value we have an old entry
 
 692     next unless $form->{acc_trans}{$key};
 
 694     # do not use old entries for payments. They come from the form
 
 695     # even if they are not changeable (then they are in hiddens)
 
 696     next if $for_post_payments && $key eq "AP_paid";
 
 698     for $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
 
 700       if ($key eq "AP_paid") {
 
 702         $form->{"AP_paid_$j"}         = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 703         $form->{"acc_trans_id_$j"}    = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
 
 704         $form->{"paid_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{amount};
 
 705         $form->{"datepaid_$j"}        = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
 
 706         $form->{"gldate_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
 
 707         $form->{"source_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{source};
 
 708         $form->{"memo_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{memo};
 
 710         $form->{"exchangerate_$i"}    = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
 
 711         $form->{"forex_$j"}           = $form->{"exchangerate_$i"};
 
 712         $form->{"AP_paid_$j"}         = $form->{acc_trans}{$key}->[$i-1]->{accno};
 
 713         $form->{"paid_project_id_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{project_id};
 
 714         $form->{paidaccounts}++;
 
 720         if (($key eq "AP_tax") || ($key eq "AR_tax")) {
 
 721           $form->{"${key}_$form->{acc_trans}{$key}->[$i-1]->{accno}"}  = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 722           $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
 
 724           if ($form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"} > 0) {
 
 725             $totaltax += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
 
 727             $totalwithholding += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
 
 728             $withholdingrate  += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
 
 731           $index                 = $form->{acc_trans}{$key}->[$i - 1]->{index};
 
 732           $form->{"tax_$index"}  = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} * -1 / $exchangerate, 2);
 
 733           $totaltax             += $form->{"tax_$index"};
 
 737           $form->{"${akey}_$k"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
 
 739           if ($akey eq 'amount') {
 
 741             $form->{"${akey}_$i"} *= -1;
 
 742             $totalamount          += $form->{"${akey}_$i"};
 
 743             $form->{taxrate}       = $form->{acc_trans}{$key}->[$i - 1]->{rate};
 
 745             $form->{"projectnumber_$k"}    = "$form->{acc_trans}{$key}->[$i-1]->{projectnumber}";
 
 746             $form->{"oldprojectnumber_$k"} = $form->{"projectnumber_$k"};
 
 747             $form->{"project_id_$k"}       = "$form->{acc_trans}{$key}->[$i-1]->{project_id}";
 
 748             $form->{"${key}_chart_id_$k"}  = $form->{acc_trans}{$key}->[$i-1]->{chart_id};
 
 749             $form->{"taxchart_$k"} = $form->{acc_trans}{$key}->[$i-1]->{id}    . "--" . $form->{acc_trans}{$key}->[$i-1]->{rate};
 
 756   $form->{paidaccounts} = 1            if not defined $form->{paidaccounts};
 
 758   if ($form->{taxincluded} && $form->{taxrate} && $totalamount) {
 
 759     # add tax to amounts and invtotal
 
 760     for $i (1 .. $form->{rowcount}) {
 
 761       $taxamount            = ($totaltax + $totalwithholding) * $form->{"amount_$i"} / $totalamount;
 
 762       $tax                  = $form->round_amount($taxamount, 2);
 
 763       $diff                += ($taxamount - $tax);
 
 764       $form->{"amount_$i"} += $form->{"tax_$i"};
 
 767     $form->{amount_1} += $form->round_amount($diff, 2);
 
 770   $taxamount        = $form->round_amount($taxamount, 2);
 
 771   $form->{invtotal} = $totalamount + $totaltax;
 
 773   $main::lxdebug->leave_sub();
 
 777   my ($self, $form, $myconfig, $id) = @_;
 
 778   $main::lxdebug->enter_sub();
 
 780   my $rc = SL::DB->client->with_transaction(\&_storno, $self, $form, $myconfig, $id);
 
 782   $::lxdebug->leave_sub;
 
 787   my ($self, $form, $myconfig, $id) = @_;
 
 789   my ($query, $new_id, $storno_row, $acc_trans_rows);
 
 790   my $dbh = SL::DB->client->dbh;
 
 792   $query = qq|SELECT nextval('glid')|;
 
 793   ($new_id) = selectrow_query($form, $dbh, $query);
 
 795   $query = qq|SELECT * FROM ap WHERE id = ?|;
 
 796   $storno_row = selectfirst_hashref_query($form, $dbh, $query, $id);
 
 798   $storno_row->{id}         = $new_id;
 
 799   $storno_row->{storno_id}  = $id;
 
 800   $storno_row->{storno}     = 't';
 
 801   $storno_row->{invnumber}  = 'Storno-' . $storno_row->{invnumber};
 
 802   $storno_row->{amount}    *= -1;
 
 803   $storno_row->{netamount} *= -1;
 
 804   $storno_row->{paid}       = $storno_row->{amount};
 
 806   delete @$storno_row{qw(itime mtime)};
 
 808   $query = sprintf 'INSERT INTO ap (%s) VALUES (%s)', join(', ', keys %$storno_row), join(', ', map '?', values %$storno_row);
 
 809   do_query($form, $dbh, $query, (values %$storno_row));
 
 811   $query = qq|UPDATE ap SET paid = amount + paid, storno = 't' WHERE id = ?|;
 
 812   do_query($form, $dbh, $query, $id);
 
 814   $form->new_lastmtime('ap') if $id == $form->{id};
 
 816   # now copy acc_trans entries
 
 817   $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|;
 
 818   my $rowref = selectall_hashref_query($form, $dbh, $query, $id);
 
 820   # kill all entries containing payments, which are the last 2n rows, of which the last has link =~ /paid/
 
 821   while ($rowref->[-1]{link} =~ /paid/) {
 
 822     splice(@$rowref, -2);
 
 825   for my $row (@$rowref) {
 
 826     delete @$row{qw(itime mtime link acc_trans_id)};
 
 827     $query = sprintf 'INSERT INTO acc_trans (%s) VALUES (%s)', join(', ', keys %$row), join(', ', map '?', values %$row);
 
 828     $row->{trans_id}   = $new_id;
 
 829     $row->{amount}    *= -1;
 
 830     do_query($form, $dbh, $query, (values %$row));
 
 833   map { IO->set_datepaid(table => 'ap', id => $_, dbh => $dbh) } ($id, $new_id);