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   for my $i (1 .. $form->{rowcount}) {
 
  77     $form->{AP_amounts}{"amount_$i"} =
 
  78       (split(/--/, $form->{"AP_amount_$i"}))[0];
 
  81   ($form->{AP_amounts}{payables}) = split(/--/, $form->{APselected});
 
  82   ($form->{AP_payables})          = split(/--/, $form->{APselected});
 
  84   # calculate the totals while calculating and reformatting the $amount_$i and $tax_$i
 
  85   ($form->{netamount},$form->{total_tax},$form->{invtotal}) = $form->calculate_arap('buy',$form->{taxincluded}, $form->{exchangerate});
 
  87   # adjust paidaccounts if there is no date in the last row
 
  88   $form->{paidaccounts}-- unless ($form->{"datepaid_$form->{paidaccounts}"});
 
  93   for my $i (1 .. $form->{paidaccounts}) {
 
  95       $form->round_amount($form->parse_amount($myconfig, $form->{"paid_$i"}),
 
  98     $form->{invpaid} += $form->{"paid_$i"};
 
  99     $form->{datepaid} = $form->{"datepaid_$i"};
 
 104     $form->round_amount($form->{invpaid} * $form->{exchangerate}, 2);
 
 106   # # store invoice total, this goes into ap table
 
 107   # $form->{invtotal} = $form->{netamount} + $form->{total_tax};
 
 109   # amount for total AP
 
 110   $form->{payables} = $form->{invtotal};
 
 112   # update exchangerate
 
 113   if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
 
 114     $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate}, 0,
 
 115                                $form->{exchangerate});
 
 118   my ($query, $sth, @values);
 
 120   if (!$payments_only) {
 
 121     # if we have an id delete old records
 
 124       # delete detail records
 
 125       $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
 
 126       do_query($form, $dbh, $query, $form->{id});
 
 130       ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
 
 133         qq|INSERT INTO ap (id, invnumber, employee_id,currency_id, taxzone_id) | .
 
 134         qq|VALUES (?, ?, (SELECT e.id FROM employee e WHERE e.login = ?),
 
 135                       (SELECT id FROM currencies WHERE name = ?), (SELECT taxzone_id FROM vendor WHERE id = ?) )|;
 
 136       do_query($form, $dbh, $query, $form->{id}, $form->{invnumber}, $::myconfig{login}, $form->{currency}, $form->{vendor_id});
 
 140     $query = qq|UPDATE ap SET invnumber = ?,
 
 141                 transdate = ?, ordnumber = ?, vendor_id = ?, taxincluded = ?,
 
 142                 amount = ?, duedate = ?, paid = ?, netamount = ?,
 
 143                 currency_id = (SELECT id FROM currencies WHERE name = ?), notes = ?, department_id = ?, storno = ?, storno_id = ?,
 
 144                 globalproject_id = ?, direct_debit = ?
 
 146     @values = ($form->{invnumber}, conv_date($form->{transdate}),
 
 147                   $form->{ordnumber}, conv_i($form->{vendor_id}),
 
 148                   $form->{taxincluded} ? 't' : 'f', $form->{invtotal},
 
 149                   conv_date($form->{duedate}), $form->{invpaid},
 
 151                   $form->{currency}, $form->{notes},
 
 152                   conv_i($form->{department_id}), $form->{storno},
 
 153                   $form->{storno_id}, conv_i($form->{globalproject_id}),
 
 154                   $form->{direct_debit} ? 't' : 'f',
 
 156     do_query($form, $dbh, $query, @values);
 
 158     $form->new_lastmtime('ap');
 
 160     # add individual transactions
 
 161     for my $i (1 .. $form->{rowcount}) {
 
 162       if ($form->{"amount_$i"} != 0) {
 
 164         $project_id = conv_i($form->{"project_id_$i"});
 
 166         # insert detail records in acc_trans
 
 168           qq|INSERT INTO acc_trans | .
 
 169           qq|  (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link)| .
 
 170           qq|VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), | .
 
 171           qq|  ?, ?, ?, ?, ?,| .
 
 172           qq| (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 173         @values = ($form->{id}, $form->{AP_amounts}{"amount_$i"},
 
 174                    $form->{"amount_$i"}, conv_date($form->{transdate}),
 
 175                    $project_id, $form->{"taxkey_$i"}, conv_i($form->{"tax_id_$i"}),
 
 176                    $form->{AP_amounts}{"amount_$i"});
 
 177         do_query($form, $dbh, $query, @values);
 
 179         if ($form->{"tax_$i"} != 0) {
 
 180           # insert detail records in acc_trans
 
 182             qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, | .
 
 183             qq|  project_id, taxkey, tax_id, chart_link) | .
 
 184             qq|VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), | .
 
 185             qq|  ?, ?, ?, ?, ?,| .
 
 186             qq| (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 187           @values = ($form->{id}, $form->{AP_amounts}{"tax_$i"},
 
 188                      $form->{"tax_$i"}, conv_date($form->{transdate}),
 
 189                      $project_id, $form->{"taxkey_$i"}, conv_i($form->{"tax_id_$i"}),
 
 190                      $form->{AP_amounts}{"tax_$i"});
 
 191           do_query($form, $dbh, $query, @values);
 
 199       qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) | .
 
 200       qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, | .
 
 201       qq|        (SELECT taxkey_id FROM chart WHERE accno = ?),| .
 
 202       qq|        (SELECT tax_id| .
 
 204       qq|         WHERE chart_id= (SELECT id | .
 
 206       qq|                          WHERE accno = ?)| .
 
 207       qq|         AND startdate <= ?| .
 
 208       qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 209       qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 210     @values = ($form->{id}, $form->{AP_amounts}{payables}, $form->{payables},
 
 211                conv_date($form->{transdate}), $form->{AP_amounts}{payables}, $form->{AP_amounts}{payables}, conv_date($form->{transdate}),
 
 212                $form->{AP_amounts}{payables});
 
 213     do_query($form, $dbh, $query, @values);
 
 216   # if there is no amount but a payment record a payable
 
 217   if ($form->{amount} == 0 && $form->{invtotal} == 0) {
 
 218     $form->{payables} = $form->{invpaid};
 
 221   # add paid transactions
 
 222   for my $i (1 .. $form->{paidaccounts}) {
 
 224     if ($form->{"acc_trans_id_$i"} && $payments_only && (SL::DB::Default->get->payments_changeable == 0)) {
 
 228     if ($form->{"paid_$i"} != 0) {
 
 229       my $project_id = conv_i($form->{"paid_project_id_$i"});
 
 232       if ($form->{currency} eq $form->{defaultcurrency}) {
 
 233         $form->{"exchangerate_$i"} = 1;
 
 235         $exchangerate              = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
 
 236         $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
 
 238       $form->{"AP_paid_$i"} =~ s/\"//g;
 
 242       ($form->{"AP_paid_account_$i"}) = split(/--/, $form->{"AP_paid_$i"});
 
 243       $form->{"datepaid_$i"} = $form->{transdate}
 
 244         unless ($form->{"datepaid_$i"});
 
 246       # if there is no amount and invtotal is zero there is no exchangerate
 
 247       if ($form->{amount} == 0 && $form->{invtotal} == 0) {
 
 248         $form->{exchangerate} = $form->{"exchangerate_$i"};
 
 252         $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} * -1,
 
 254       if ($form->{payables}) {
 
 256           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link) | .
 
 257           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, | .
 
 258           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?),| .
 
 259           qq|        (SELECT tax_id| .
 
 261           qq|         WHERE chart_id= (SELECT id | .
 
 263           qq|                          WHERE accno = ?)| .
 
 264           qq|         AND startdate <= ?| .
 
 265           qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 266           qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 267         @values = ($form->{id}, $form->{AP_payables}, $amount,
 
 268                    conv_date($form->{"datepaid_$i"}), $project_id,
 
 269                    $form->{AP_payables}, $form->{AP_payables}, conv_date($form->{"datepaid_$i"}),
 
 270                    $form->{AP_payables});
 
 271         do_query($form, $dbh, $query, @values);
 
 273       $form->{payables} = $amount;
 
 276       my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
 
 278         qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, project_id, taxkey, tax_id, chart_link) | .
 
 279         qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?, ?, | .
 
 280         qq|        (SELECT taxkey_id FROM chart WHERE accno = ?), | .
 
 281         qq|        (SELECT tax_id| .
 
 283         qq|         WHERE chart_id= (SELECT id | .
 
 285         qq|                          WHERE accno = ?)| .
 
 286         qq|         AND startdate <= ?| .
 
 287         qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 288         qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 289       @values = ($form->{id}, $form->{"AP_paid_account_$i"}, $form->{"paid_$i"},
 
 290                  conv_date($form->{"datepaid_$i"}), $gldate, $form->{"source_$i"},
 
 291                  $form->{"memo_$i"}, $project_id, $form->{"AP_paid_account_$i"},
 
 292                  $form->{"AP_paid_account_$i"}, conv_date($form->{"datepaid_$i"}),
 
 293                  $form->{"AP_paid_account_$i"});
 
 294       do_query($form, $dbh, $query, @values);
 
 296       # add exchange rate difference
 
 298         $form->round_amount($form->{"paid_$i"} *
 
 299                             ($form->{"exchangerate_$i"} - 1), 2);
 
 302           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link) | .
 
 303           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, | .
 
 304           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?), | .
 
 305           qq|        (SELECT tax_id| .
 
 307           qq|         WHERE chart_id= (SELECT id | .
 
 309           qq|                          WHERE accno = ?)| .
 
 310           qq|         AND startdate <= ?| .
 
 311           qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 312           qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 313         @values = ($form->{id}, $form->{"AP_paid_account_$i"}, $amount,
 
 314                    conv_date($form->{"datepaid_$i"}), $project_id,
 
 315                    $form->{"AP_paid_account_$i"},
 
 316                    $form->{"AP_paid_account_$i"}, conv_date($form->{"datepaid_$i"}),
 
 317                    $form->{"AP_paid_account_$i"});
 
 318         do_query($form, $dbh, $query, @values);
 
 321       # exchangerate gain/loss
 
 323         $form->round_amount($form->{"paid_$i"} *
 
 324                             ($form->{exchangerate} -
 
 325                              $form->{"exchangerate_$i"}), 2);
 
 328         # fetch fxgain and fxloss chart info from defaults if charts aren't already filled in form
 
 329         if ( !$form->{fxgain_accno} && $::instance_conf->get_fxgain_accno_id ) {
 
 330           $form->{fxgain_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxgain_accno_id)->accno;
 
 332         if ( !$form->{fxloss_accno} && $::instance_conf->get_fxloss_accno_id ) {
 
 333           $form->{fxloss_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxloss_accno_id)->accno;
 
 335         die "fxloss_accno missing" if $amount < 0 and not $form->{fxloss_accno};
 
 336         die "fxgain_accno missing" if $amount > 0 and not $form->{fxgain_accno};
 
 338           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link) | .
 
 339           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, | .
 
 340           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?),| .
 
 341           qq|        (SELECT tax_id| .
 
 343           qq|         WHERE chart_id= (SELECT id | .
 
 345           qq|                          WHERE accno = ?)| .
 
 346           qq|         AND startdate <= ?| .
 
 347           qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 348           qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 349         @values = ($form->{id},
 
 350                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno},
 
 351                    $amount, conv_date($form->{"datepaid_$i"}), $project_id,
 
 352                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno},
 
 353                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno}, conv_date($form->{"datepaid_$i"}),
 
 354                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno});
 
 355         do_query($form, $dbh, $query, @values);
 
 358       # update exchange rate record
 
 359       if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
 
 360         $form->update_exchangerate($dbh, $form->{currency},
 
 361                                    $form->{"datepaid_$i"},
 
 362                                    0, $form->{"exchangerate_$i"});
 
 367   if ($payments_only) {
 
 368     $query = qq|UPDATE ap SET paid = ?, datepaid = ? WHERE id = ?|;
 
 369     do_query($form, $dbh, $query,  $form->{invpaid}, $form->{invpaid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
 
 370     $form->new_lastmtime('ap');
 
 373   IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
 
 375   # safety check datev export
 
 376   if ($::instance_conf->get_datev_check_on_ap_transaction) {
 
 377     my $transdate = $::form->{transdate} ? DateTime->from_lxoffice($::form->{transdate}) : undef;
 
 378     $transdate  ||= DateTime->today;
 
 380     my $datev = SL::DATEV->new(
 
 381       exporttype => DATEV_ET_BUCHUNGEN,
 
 382       format     => DATEV_FORMAT_KNE,
 
 384       trans_id   => $form->{id},
 
 389     if ($datev->errors) {
 
 390       die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
 
 397 sub delete_transaction {
 
 398   $main::lxdebug->enter_sub();
 
 400   my ($self, $myconfig, $form) = @_;
 
 402   SL::DB->client->with_transaction(sub {
 
 403     my $query = qq|DELETE FROM ap WHERE id = ?|;
 
 404     do_query($form, SL::DB->client->dbh, $query, $form->{id});
 
 406   }) or do { die SL::DB->client->error };
 
 408   $main::lxdebug->leave_sub();
 
 413 sub ap_transactions {
 
 414   $main::lxdebug->enter_sub();
 
 416   my ($self, $myconfig, $form) = @_;
 
 418   # connect to database
 
 419   my $dbh = $form->get_standard_dbh($myconfig);
 
 422     qq|SELECT a.id, a.invnumber, a.transdate, a.duedate, a.amount, a.paid, | .
 
 423     qq|  a.ordnumber, v.name, a.invoice, a.netamount, a.datepaid, a.notes, | .
 
 424     qq|  a.globalproject_id, a.storno, a.storno_id, a.direct_debit, | .
 
 425     qq|  pr.projectnumber AS globalprojectnumber, | .
 
 426     qq|  e.name AS employee, | .
 
 427     qq|  v.vendornumber, v.country, v.ustid, | .
 
 428     qq|  tz.description AS taxzone, | .
 
 429     qq|  pt.description AS payment_terms, | .
 
 430     qq{  ( SELECT ch.accno || ' -- ' || ch.description
 
 432            LEFT JOIN chart ch ON ch.id = at.chart_id
 
 433            WHERE ch.link ~ 'AP[[:>:]]'
 
 434             AND at.trans_id = a.id
 
 438     qq|JOIN vendor v ON (a.vendor_id = v.id) | .
 
 439     qq|LEFT JOIN contacts cp ON (a.cp_id = cp.cp_id) | .
 
 440     qq|LEFT JOIN employee e ON (a.employee_id = e.id) | .
 
 441     qq|LEFT JOIN project pr ON (a.globalproject_id = pr.id) | .
 
 442     qq|LEFT JOIN tax_zones tz ON (tz.id = a.taxzone_id)| .
 
 443     qq|LEFT JOIN payment_terms pt ON (pt.id = a.payment_id)|;
 
 447   unless ( $::auth->assert('show_ap_transactions', 1) ) {
 
 448     $where .= " AND NOT invoice = 'f' ";  # remove ap transactions from Sales -> Reports -> Invoices
 
 453   if ($form->{vendor_id}) {
 
 454     $where .= " AND a.vendor_id = ?";
 
 455     push(@values, $form->{vendor_id});
 
 456   } elsif ($form->{vendor}) {
 
 457     $where .= " AND v.name ILIKE ?";
 
 458     push(@values, like($form->{vendor}));
 
 460   if ($form->{"cp_name"}) {
 
 461     $where .= " AND (cp.cp_name ILIKE ? OR cp.cp_givenname ILIKE ?)";
 
 462     push(@values, (like($form->{"cp_name"}))x2);
 
 464   if ($form->{department_id}) {
 
 465     $where .= " AND a.department_id = ?";
 
 466     push(@values, $form->{department_id});
 
 468   if ($form->{invnumber}) {
 
 469     $where .= " AND a.invnumber ILIKE ?";
 
 470     push(@values, like($form->{invnumber}));
 
 472   if ($form->{ordnumber}) {
 
 473     $where .= " AND a.ordnumber ILIKE ?";
 
 474     push(@values, like($form->{ordnumber}));
 
 476   if ($form->{notes}) {
 
 477     $where .= " AND lower(a.notes) LIKE ?";
 
 478     push(@values, like($form->{notes}));
 
 480   if ($form->{project_id}) {
 
 482       qq| AND ((a.globalproject_id = ?) OR EXISTS | .
 
 483       qq|  (SELECT * FROM invoice i | .
 
 484       qq|   WHERE i.project_id = ? AND i.trans_id = a.id) | .
 
 486       qq|  (SELECT * FROM acc_trans at | .
 
 487       qq|   WHERE at.project_id = ? AND at.trans_id = a.id)| .
 
 489     push(@values, $form->{project_id}, $form->{project_id}, $form->{project_id});
 
 492   if ($form->{transdatefrom}) {
 
 493     $where .= " AND a.transdate >= ?";
 
 494     push(@values, trim($form->{transdatefrom}));
 
 496   if ($form->{transdateto}) {
 
 497     $where .= " AND a.transdate <= ?";
 
 498     push(@values, trim($form->{transdateto}));
 
 500   if ($form->{open} || $form->{closed}) {
 
 501     unless ($form->{open} && $form->{closed}) {
 
 502       $where .= " AND a.amount <> a.paid" if ($form->{open});
 
 503       $where .= " AND a.amount = a.paid"  if ($form->{closed});
 
 507   if ($form->{parts_partnumber}) {
 
 510         SELECT invoice.trans_id
 
 512         LEFT JOIN parts ON (invoice.parts_id = parts.id)
 
 513         WHERE (invoice.trans_id = a.id)
 
 514           AND (parts.partnumber ILIKE ?)
 
 518     push @values, like($form->{parts_partnumber});
 
 521   if ($form->{parts_description}) {
 
 524         SELECT invoice.trans_id
 
 526         WHERE (invoice.trans_id = a.id)
 
 527           AND (invoice.description ILIKE ?)
 
 531     push @values, like($form->{parts_description});
 
 535     substr($where, 0, 4, " WHERE ");
 
 539   my @a = qw(transdate invnumber name);
 
 540   push @a, "employee" if $form->{l_employee};
 
 541   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
 542   my $sortorder = join(', ', map { "$_ $sortdir" } @a);
 
 544   if (grep({ $_ eq $form->{sort} } qw(transdate id invnumber ordnumber name netamount tax amount paid datepaid due duedate notes employee transaction_description direct_debit))) {
 
 545     $sortorder = $form->{sort} . " $sortdir";
 
 548   $query .= " ORDER BY $sortorder";
 
 550   my @result = selectall_hashref_query($form, $dbh, $query, @values);
 
 552   $form->{AP} = [ @result ];
 
 554   $main::lxdebug->leave_sub();
 
 558   $main::lxdebug->enter_sub();
 
 560   my ($self, $myconfig, $form) = @_;
 
 562   # connect to database
 
 563   my $dbh = SL::DB->client->dbh;
 
 567     "  (SELECT transdate FROM ap WHERE id = " .
 
 568     "    (SELECT MAX(id) FROM ap) LIMIT 1), " .
 
 570   ($form->{transdate}) = $dbh->selectrow_array($query);
 
 572   $main::lxdebug->leave_sub();
 
 575 sub _delete_payments {
 
 576   $main::lxdebug->enter_sub();
 
 578   my ($self, $form, $dbh) = @_;
 
 580   my @delete_acc_trans_ids;
 
 582   # Delete old payment entries from acc_trans.
 
 584     qq|SELECT acc_trans_id
 
 586        WHERE (trans_id = ?) AND fx_transaction
 
 590        SELECT at.acc_trans_id
 
 592        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 593        WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
 
 594   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
 
 597     qq|SELECT at.acc_trans_id
 
 599        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 601          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
 
 602        ORDER BY at.acc_trans_id
 
 604   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
 
 606   if (@delete_acc_trans_ids) {
 
 607     $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
 
 608     do_query($form, $dbh, $query);
 
 611   $main::lxdebug->leave_sub();
 
 615   my ($self, $myconfig, $form, $locale) = @_;
 
 616   $main::lxdebug->enter_sub();
 
 618   my $rc = SL::DB->client->with_transaction(\&_post_payment, $self, $myconfig, $form, $locale);
 
 620   $::lxdebug->leave_sub;
 
 625   my ($self, $myconfig, $form, $locale) = @_;
 
 627   my $dbh = SL::DB->client->dbh;
 
 629   my (%payments, $old_form, $row, $item, $query, %keep_vars);
 
 631   $old_form = save_form();
 
 633   # Delete all entries in acc_trans from prior payments.
 
 634   if (SL::DB::Default->get->payments_changeable != 0) {
 
 635     $self->_delete_payments($form, $dbh);
 
 638   # Save the new payments the user made before cleaning up $form.
 
 639   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$';
 
 640   map { $payments{$_} = $form->{$_} } grep m/$payments_re/, keys %{ $form };
 
 642   # Clean up $form so that old content won't tamper the results.
 
 643   %keep_vars = map { $_, 1 } qw(login password id);
 
 644   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
 
 646   # Retrieve the invoice from the database.
 
 647   $form->create_links('AP', $myconfig, 'vendor', $dbh);
 
 649   # Restore the payment options from the user input.
 
 650   map { $form->{$_} = $payments{$_} } keys %payments;
 
 652   # Set up the content of $form in the way that AR::post_transaction() expects.
 
 654   $self->setup_form($form, 1);
 
 656   $form->{exchangerate}    = $form->format_amount($myconfig, $form->{exchangerate});
 
 657   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
 
 663        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 665          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
 
 666        ORDER BY at.acc_trans_id
 
 669   ($form->{APselected}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
 
 671   # Post the new payments.
 
 672   $self->post_transaction($myconfig, $form, $dbh, 1);
 
 674   restore_form($old_form);
 
 680   $main::lxdebug->enter_sub();
 
 682   my ($self, $form, $for_post_payments) = @_;
 
 684   my ($exchangerate, $i, $j, $k, $key, $akey, $ref, $index, $taxamount, $totalamount, $totaltax, $totalwithholding, $withholdingrate,
 
 688   $form->{forex} = $form->{exchangerate};
 
 689   $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
 
 691   foreach $key (keys %{ $form->{AP_links} }) {
 
 692     foreach $ref (@{ $form->{AP_links}{$key} }) {
 
 693       if ($key eq "AP_paid") {
 
 694         $form->{"select$key"} .= "<option value=\"$ref->{accno}\">$ref->{accno}--$ref->{description}</option>\n";
 
 696         $form->{"select$key"} .= "<option value=\"$ref->{accno}--$ref->{tax_id}\">$ref->{accno}--$ref->{description}</option>\n";
 
 700     $form->{$key} = $form->{"select$key"};
 
 705     # if there is a value we have an old entry
 
 706     next unless $form->{acc_trans}{$key};
 
 708     # do not use old entries for payments. They come from the form
 
 709     # even if they are not changeable (then they are in hiddens)
 
 710     next if $for_post_payments && $key eq "AP_paid";
 
 712     for $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
 
 714       if ($key eq "AP_paid") {
 
 716         $form->{"AP_paid_$j"}         = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 717         $form->{"acc_trans_id_$j"}    = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
 
 718         $form->{"paid_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{amount};
 
 719         $form->{"datepaid_$j"}        = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
 
 720         $form->{"gldate_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
 
 721         $form->{"source_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{source};
 
 722         $form->{"memo_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{memo};
 
 724         $form->{"exchangerate_$i"}    = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
 
 725         $form->{"forex_$j"}           = $form->{"exchangerate_$i"};
 
 726         $form->{"AP_paid_$j"}         = $form->{acc_trans}{$key}->[$i-1]->{accno};
 
 727         $form->{"paid_project_id_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{project_id};
 
 728         $form->{paidaccounts}++;
 
 734         if (($key eq "AP_tax") || ($key eq "AR_tax")) {
 
 735           $form->{"${key}_$form->{acc_trans}{$key}->[$i-1]->{accno}"}  = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 736           $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
 
 738           if ($form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"} > 0) {
 
 739             $totaltax += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
 
 741             $totalwithholding += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
 
 742             $withholdingrate  += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
 
 745           $index                 = $form->{acc_trans}{$key}->[$i - 1]->{index};
 
 746           $form->{"tax_$index"}  = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} * -1 / $exchangerate, 2);
 
 747           $totaltax             += $form->{"tax_$index"};
 
 751           $form->{"${akey}_$k"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
 
 753           if ($akey eq 'amount') {
 
 755             $form->{"${akey}_$i"} *= -1;
 
 756             $totalamount          += $form->{"${akey}_$i"};
 
 757             $form->{taxrate}       = $form->{acc_trans}{$key}->[$i - 1]->{rate};
 
 759             $form->{"projectnumber_$k"}    = "$form->{acc_trans}{$key}->[$i-1]->{projectnumber}";
 
 760             $form->{"oldprojectnumber_$k"} = $form->{"projectnumber_$k"};
 
 761             $form->{"project_id_$k"}       = "$form->{acc_trans}{$key}->[$i-1]->{project_id}";
 
 764           $form->{"${key}_$k"} = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 766           my $q_description    = quotemeta($form->{acc_trans}{$key}->[$i-1]->{description});
 
 767           $form->{"select${key}"} =~
 
 769                 ($form->{acc_trans}{$key}->[$i-1]->{accno}--[^\"]*)
 
 771               $form->{acc_trans}{$key}->[$i-1]->{accno}
 
 775           $form->{"${key}_$k"} = $1;
 
 778             $form->{APselected} = $form->{acc_trans}{$key}->[$i-1]->{accno};
 
 780           } elsif ($akey eq 'amount') {
 
 781             $form->{"${key}_$k"}   = $form->{acc_trans}{$key}->[$i-1]->{accno} . "--" . $form->{acc_trans}{$key}->[$i-1]->{id};
 
 782             $form->{"taxchart_$k"} = $form->{acc_trans}{$key}->[$i-1]->{id}    . "--" . $form->{acc_trans}{$key}->[$i-1]->{rate};
 
 789   $form->{paidaccounts} = 1            if not defined $form->{paidaccounts};
 
 791   if ($form->{taxincluded} && $form->{taxrate} && $totalamount) {
 
 792     # add tax to amounts and invtotal
 
 793     for $i (1 .. $form->{rowcount}) {
 
 794       $taxamount            = ($totaltax + $totalwithholding) * $form->{"amount_$i"} / $totalamount;
 
 795       $tax                  = $form->round_amount($taxamount, 2);
 
 796       $diff                += ($taxamount - $tax);
 
 797       $form->{"amount_$i"} += $form->{"tax_$i"};
 
 800     $form->{amount_1} += $form->round_amount($diff, 2);
 
 803   $taxamount        = $form->round_amount($taxamount, 2);
 
 804   $form->{invtotal} = $totalamount + $totaltax;
 
 806   $main::lxdebug->leave_sub();
 
 810   my ($self, $form, $myconfig, $id) = @_;
 
 811   $main::lxdebug->enter_sub();
 
 813   my $rc = SL::DB->client->with_transaction(\&_storno, $self, $form, $myconfig, $id);
 
 815   $::lxdebug->leave_sub;
 
 820   my ($self, $form, $myconfig, $id) = @_;
 
 822   my ($query, $new_id, $storno_row, $acc_trans_rows);
 
 823   my $dbh = SL::DB->client->dbh;
 
 825   $query = qq|SELECT nextval('glid')|;
 
 826   ($new_id) = selectrow_query($form, $dbh, $query);
 
 828   $query = qq|SELECT * FROM ap WHERE id = ?|;
 
 829   $storno_row = selectfirst_hashref_query($form, $dbh, $query, $id);
 
 831   $storno_row->{id}         = $new_id;
 
 832   $storno_row->{storno_id}  = $id;
 
 833   $storno_row->{storno}     = 't';
 
 834   $storno_row->{invnumber}  = 'Storno-' . $storno_row->{invnumber};
 
 835   $storno_row->{amount}    *= -1;
 
 836   $storno_row->{netamount} *= -1;
 
 837   $storno_row->{paid}       = $storno_row->{amount};
 
 839   delete @$storno_row{qw(itime mtime)};
 
 841   $query = sprintf 'INSERT INTO ap (%s) VALUES (%s)', join(', ', keys %$storno_row), join(', ', map '?', values %$storno_row);
 
 842   do_query($form, $dbh, $query, (values %$storno_row));
 
 844   $query = qq|UPDATE ap SET paid = amount + paid, storno = 't' WHERE id = ?|;
 
 845   do_query($form, $dbh, $query, $id);
 
 847   $form->new_lastmtime('ap') if $id == $form->{id};
 
 849   # now copy acc_trans entries
 
 850   $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|;
 
 851   my $rowref = selectall_hashref_query($form, $dbh, $query, $id);
 
 853   # kill all entries containing payments, which are the last 2n rows, of which the last has link =~ /paid/
 
 854   while ($rowref->[-1]{link} =~ /paid/) {
 
 855     splice(@$rowref, -2);
 
 858   for my $row (@$rowref) {
 
 859     delete @$row{qw(itime mtime link acc_trans_id)};
 
 860     $query = sprintf 'INSERT INTO acc_trans (%s) VALUES (%s)', join(', ', keys %$row), join(', ', map '?', values %$row);
 
 861     $row->{trans_id}   = $new_id;
 
 862     $row->{amount}    *= -1;
 
 863     do_query($form, $dbh, $query, (values %$row));
 
 866   map { IO->set_datepaid(table => 'ap', id => $_, dbh => $dbh) } ($id, $new_id);