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, %params) = @_;
 
  52   $main::lxdebug->enter_sub();
 
  54   my $rc = SL::DB->client->with_transaction(\&_post_transaction, $self, $myconfig, $form, $provided_dbh, %params);
 
  56   $::lxdebug->leave_sub;
 
  60 sub _post_transaction {
 
  61   my ($self, $myconfig, $form, $provided_dbh, %params) = @_;
 
  63   my $payments_only = $params{payments_only};
 
  64   my $dbh = $provided_dbh || SL::DB->client->dbh;
 
  66   my ($null, $taxrate, $amount);
 
  69   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
 
  70   $form->{taxincluded} = 0 unless $form->{taxincluded};
 
  72   if ($form->{currency} eq $form->{defaultcurrency}) {
 
  73     $form->{exchangerate} = 1;
 
  75     $exchangerate         = $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'sell');
 
  76     $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
 
  79   # get the charts selected
 
  80   $form->{AP_amounts}{"amount_$_"} = $form->{"AP_amount_chart_id_$_"} for (1 .. $form->{rowcount});
 
  82   # calculate the totals while calculating and reformatting the $amount_$i and $tax_$i
 
  83   ($form->{netamount},$form->{total_tax},$form->{invtotal}) = $form->calculate_arap('buy',$form->{taxincluded}, $form->{exchangerate});
 
  85   # adjust paidaccounts if there is no date in the last row
 
  86   $form->{paidaccounts}-- unless ($form->{"datepaid_$form->{paidaccounts}"});
 
  91   for my $i (1 .. $form->{paidaccounts}) {
 
  93       $form->round_amount($form->parse_amount($myconfig, $form->{"paid_$i"}),
 
  96     $form->{invpaid} += $form->{"paid_$i"};
 
  97     $form->{datepaid} = $form->{"datepaid_$i"};
 
 102     $form->round_amount($form->{invpaid} * $form->{exchangerate}, 2);
 
 104   # # store invoice total, this goes into ap table
 
 105   # $form->{invtotal} = $form->{netamount} + $form->{total_tax};
 
 107   # amount for total AP
 
 108   $form->{payables} = $form->{invtotal};
 
 110   # update exchangerate
 
 111   if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
 
 112     $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate}, 0,
 
 113                                $form->{exchangerate});
 
 116   my ($query, $sth, @values);
 
 118   if (!$payments_only) {
 
 119     # if we have an id delete old records
 
 122       # delete detail records
 
 123       $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
 
 124       do_query($form, $dbh, $query, $form->{id});
 
 128       ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
 
 131         qq|INSERT INTO ap (id, invnumber, employee_id,currency_id, taxzone_id) | .
 
 132         qq|VALUES (?, ?, (SELECT e.id FROM employee e WHERE e.login = ?),
 
 133                       (SELECT id FROM currencies WHERE name = ?), (SELECT taxzone_id FROM vendor WHERE id = ?) )|;
 
 134       do_query($form, $dbh, $query, $form->{id}, $form->{invnumber}, $::myconfig{login}, $form->{currency}, $form->{vendor_id});
 
 138     $query = qq|UPDATE ap SET invnumber = ?,
 
 139                 transdate = ?, ordnumber = ?, vendor_id = ?, taxincluded = ?,
 
 140                 amount = ?, duedate = ?, paid = ?, netamount = ?,
 
 141                 currency_id = (SELECT id FROM currencies WHERE name = ?), notes = ?, department_id = ?, storno = ?, storno_id = ?,
 
 142                 globalproject_id = ?, direct_debit = ?
 
 144     @values = ($form->{invnumber}, conv_date($form->{transdate}),
 
 145                   $form->{ordnumber}, conv_i($form->{vendor_id}),
 
 146                   $form->{taxincluded} ? 't' : 'f', $form->{invtotal},
 
 147                   conv_date($form->{duedate}), $form->{invpaid},
 
 149                   $form->{currency}, $form->{notes},
 
 150                   conv_i($form->{department_id}), $form->{storno},
 
 151                   $form->{storno_id}, conv_i($form->{globalproject_id}),
 
 152                   $form->{direct_debit} ? 't' : 'f',
 
 154     do_query($form, $dbh, $query, @values);
 
 156     $form->new_lastmtime('ap');
 
 158     # add individual transactions
 
 159     for my $i (1 .. $form->{rowcount}) {
 
 160       if ($form->{"amount_$i"} != 0) {
 
 162         $project_id = conv_i($form->{"project_id_$i"});
 
 164         # insert detail records in acc_trans
 
 166           qq|INSERT INTO acc_trans | .
 
 167           qq|  (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link)| .
 
 168           qq|VALUES (?, ?,   ?, ?, ?, ?, ?, (SELECT c.link FROM chart c WHERE c.id = ?))|;
 
 169         @values = ($form->{id}, $form->{"AP_amount_chart_id_$i"},
 
 170                    $form->{"amount_$i"}, conv_date($form->{transdate}),
 
 171                    $project_id, $form->{"taxkey_$i"}, conv_i($form->{"tax_id_$i"}),
 
 172                    $form->{"AP_amount_chart_id_$i"});
 
 173         do_query($form, $dbh, $query, @values);
 
 175         if ($form->{"tax_$i"} != 0) {
 
 176           # insert detail records in acc_trans
 
 178             qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, | .
 
 179             qq|  project_id, taxkey, tax_id, chart_link) | .
 
 180             qq|VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), | .
 
 181             qq|  ?, ?, ?, ?, ?,| .
 
 182             qq| (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 183           @values = ($form->{id}, $form->{AP_amounts}{"tax_$i"},
 
 184                      $form->{"tax_$i"}, conv_date($form->{transdate}),
 
 185                      $project_id, $form->{"taxkey_$i"}, conv_i($form->{"tax_id_$i"}),
 
 186                      $form->{AP_amounts}{"tax_$i"});
 
 187           do_query($form, $dbh, $query, @values);
 
 195       qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) | .
 
 196       qq|VALUES (?, ?, ?, ?, | .
 
 197       qq|        (SELECT taxkey_id FROM chart WHERE id = ?),| .
 
 198       qq|        (SELECT tax_id| .
 
 200       qq|         WHERE chart_id = ?| .
 
 201       qq|         AND startdate <= ?| .
 
 202       qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 203       qq|        (SELECT c.link FROM chart c WHERE c.id = ?))|;
 
 204     @values = ($form->{id}, $form->{AP_chart_id}, $form->{payables},
 
 205                conv_date($form->{transdate}), $form->{AP_chart_id}, $form->{AP_chart_id}, conv_date($form->{transdate}),
 
 206                $form->{AP_chart_id});
 
 207     do_query($form, $dbh, $query, @values);
 
 210   # if there is no amount but a payment record a payable
 
 211   if ($form->{amount} == 0 && $form->{invtotal} == 0) {
 
 212     $form->{payables} = $form->{invpaid};
 
 215   my %already_cleared = %{ $params{already_cleared} // {} };
 
 217   # add paid transactions
 
 218   for my $i (1 .. $form->{paidaccounts}) {
 
 220     if ($form->{"acc_trans_id_$i"} && $payments_only && (SL::DB::Default->get->payments_changeable == 0)) {
 
 224     if ($form->{"paid_$i"} != 0) {
 
 225       my $project_id = conv_i($form->{"paid_project_id_$i"});
 
 228       if ($form->{currency} eq $form->{defaultcurrency}) {
 
 229         $form->{"exchangerate_$i"} = 1;
 
 231         $exchangerate              = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
 
 232         $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
 
 234       $form->{"AP_paid_$i"} =~ s/\"//g;
 
 238       ($form->{"AP_paid_account_$i"}) = split(/--/, $form->{"AP_paid_$i"});
 
 239       $form->{"datepaid_$i"} = $form->{transdate}
 
 240         unless ($form->{"datepaid_$i"});
 
 242       # if there is no amount and invtotal is zero there is no exchangerate
 
 243       if ($form->{amount} == 0 && $form->{invtotal} == 0) {
 
 244         $form->{exchangerate} = $form->{"exchangerate_$i"};
 
 248         $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} * -1,
 
 251       my $new_cleared = !$form->{"acc_trans_id_$i"}                                                             ? 'f'
 
 252                       : !$already_cleared{$form->{"acc_trans_id_$i"}}                                           ? 'f'
 
 253                       : $already_cleared{$form->{"acc_trans_id_$i"}}->{amount} != $amount * -1                  ? 'f'
 
 254                       : $already_cleared{$form->{"acc_trans_id_$i"}}->{accno}  != $form->{"AP_paid_account_$i"} ? 'f'
 
 255                       : $already_cleared{$form->{"acc_trans_id_$i"}}->{cleared}                                 ? 't'
 
 258       if ($form->{payables}) {
 
 260           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, cleared, taxkey, tax_id, chart_link) | .
 
 261           qq|VALUES (?, ?, ?, ?, ?, ?, | .
 
 262           qq|        (SELECT taxkey_id FROM chart WHERE id = ?),| .
 
 263           qq|        (SELECT tax_id| .
 
 265           qq|         WHERE chart_id = ?| .
 
 266           qq|         AND startdate <= ?| .
 
 267           qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 268           qq|        (SELECT c.link FROM chart c WHERE c.id = ?))|;
 
 269         @values = ($form->{id}, $form->{AP_chart_id}, $amount,
 
 270                    conv_date($form->{"datepaid_$i"}), $project_id, $new_cleared,
 
 271                    $form->{AP_chart_id}, $form->{AP_chart_id}, conv_date($form->{"datepaid_$i"}),
 
 272                    $form->{AP_chart_id});
 
 273         do_query($form, $dbh, $query, @values);
 
 275       $form->{payables} = $amount;
 
 278       my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
 
 280         qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, project_id, cleared, taxkey, tax_id, chart_link) | .
 
 281         qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?, ?, ?, | .
 
 282         qq|        (SELECT taxkey_id FROM chart WHERE accno = ?), | .
 
 283         qq|        (SELECT tax_id| .
 
 285         qq|         WHERE chart_id= (SELECT id | .
 
 287         qq|                          WHERE accno = ?)| .
 
 288         qq|         AND startdate <= ?| .
 
 289         qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 290         qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 291       @values = ($form->{id}, $form->{"AP_paid_account_$i"}, $form->{"paid_$i"},
 
 292                  conv_date($form->{"datepaid_$i"}), $gldate, $form->{"source_$i"},
 
 293                  $form->{"memo_$i"}, $project_id, $new_cleared, $form->{"AP_paid_account_$i"},
 
 294                  $form->{"AP_paid_account_$i"}, conv_date($form->{"datepaid_$i"}),
 
 295                  $form->{"AP_paid_account_$i"});
 
 296       do_query($form, $dbh, $query, @values);
 
 298       # add exchange rate difference
 
 300         $form->round_amount($form->{"paid_$i"} *
 
 301                             ($form->{"exchangerate_$i"} - 1), 2);
 
 304           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link) | .
 
 305           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, | .
 
 306           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?), | .
 
 307           qq|        (SELECT tax_id| .
 
 309           qq|         WHERE chart_id= (SELECT id | .
 
 311           qq|                          WHERE accno = ?)| .
 
 312           qq|         AND startdate <= ?| .
 
 313           qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 314           qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 315         @values = ($form->{id}, $form->{"AP_paid_account_$i"}, $amount,
 
 316                    conv_date($form->{"datepaid_$i"}), $project_id,
 
 317                    $form->{"AP_paid_account_$i"},
 
 318                    $form->{"AP_paid_account_$i"}, conv_date($form->{"datepaid_$i"}),
 
 319                    $form->{"AP_paid_account_$i"});
 
 320         do_query($form, $dbh, $query, @values);
 
 323       # exchangerate gain/loss
 
 325         $form->round_amount($form->{"paid_$i"} *
 
 326                             ($form->{exchangerate} -
 
 327                              $form->{"exchangerate_$i"}), 2);
 
 330         # fetch fxgain and fxloss chart info from defaults if charts aren't already filled in form
 
 331         if ( !$form->{fxgain_accno} && $::instance_conf->get_fxgain_accno_id ) {
 
 332           $form->{fxgain_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxgain_accno_id)->accno;
 
 334         if ( !$form->{fxloss_accno} && $::instance_conf->get_fxloss_accno_id ) {
 
 335           $form->{fxloss_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxloss_accno_id)->accno;
 
 337         die "fxloss_accno missing" if $amount < 0 and not $form->{fxloss_accno};
 
 338         die "fxgain_accno missing" if $amount > 0 and not $form->{fxgain_accno};
 
 340           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link) | .
 
 341           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, | .
 
 342           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?),| .
 
 343           qq|        (SELECT tax_id| .
 
 345           qq|         WHERE chart_id= (SELECT id | .
 
 347           qq|                          WHERE accno = ?)| .
 
 348           qq|         AND startdate <= ?| .
 
 349           qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 350           qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 351         @values = ($form->{id},
 
 352                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno},
 
 353                    $amount, conv_date($form->{"datepaid_$i"}), $project_id,
 
 354                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno},
 
 355                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno}, conv_date($form->{"datepaid_$i"}),
 
 356                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno});
 
 357         do_query($form, $dbh, $query, @values);
 
 360       # update exchange rate record
 
 361       if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
 
 362         $form->update_exchangerate($dbh, $form->{currency},
 
 363                                    $form->{"datepaid_$i"},
 
 364                                    0, $form->{"exchangerate_$i"});
 
 369   if ($payments_only) {
 
 370     $query = qq|UPDATE ap SET paid = ?, datepaid = ? WHERE id = ?|;
 
 371     do_query($form, $dbh, $query,  $form->{invpaid}, $form->{invpaid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
 
 372     $form->new_lastmtime('ap');
 
 375   IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
 
 377   if ($form->{draft_id}) {
 
 378     SL::DB::Manager::Draft->delete_all(where => [ id => delete($form->{draft_id}) ]);
 
 381   # safety check datev export
 
 382   if ($::instance_conf->get_datev_check_on_ap_transaction) {
 
 383     my $datev = SL::DATEV->new(
 
 385       trans_id   => $form->{id},
 
 387     $datev->generate_datev_data;
 
 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}) {
 
 454     $where .= " AND v.name ILIKE ?";
 
 455     push(@values, like($form->{vendor}));
 
 457   if ($form->{"cp_name"}) {
 
 458     $where .= " AND (cp.cp_name ILIKE ? OR cp.cp_givenname ILIKE ?)";
 
 459     push(@values, (like($form->{"cp_name"}))x2);
 
 461   if ($form->{department_id}) {
 
 462     $where .= " AND a.department_id = ?";
 
 463     push(@values, $form->{department_id});
 
 465   if ($form->{invnumber}) {
 
 466     $where .= " AND a.invnumber ILIKE ?";
 
 467     push(@values, like($form->{invnumber}));
 
 469   if ($form->{ordnumber}) {
 
 470     $where .= " AND a.ordnumber ILIKE ?";
 
 471     push(@values, like($form->{ordnumber}));
 
 473   if ($form->{notes}) {
 
 474     $where .= " AND lower(a.notes) LIKE ?";
 
 475     push(@values, like($form->{notes}));
 
 477   if ($form->{project_id}) {
 
 479       qq| AND ((a.globalproject_id = ?) OR EXISTS | .
 
 480       qq|  (SELECT * FROM invoice i | .
 
 481       qq|   WHERE i.project_id = ? AND i.trans_id = a.id) | .
 
 483       qq|  (SELECT * FROM acc_trans at | .
 
 484       qq|   WHERE at.project_id = ? AND at.trans_id = a.id)| .
 
 486     push(@values, $form->{project_id}, $form->{project_id}, $form->{project_id});
 
 489   if ($form->{transdatefrom}) {
 
 490     $where .= " AND a.transdate >= ?";
 
 491     push(@values, trim($form->{transdatefrom}));
 
 493   if ($form->{transdateto}) {
 
 494     $where .= " AND a.transdate <= ?";
 
 495     push(@values, trim($form->{transdateto}));
 
 497   if ($form->{open} || $form->{closed}) {
 
 498     unless ($form->{open} && $form->{closed}) {
 
 499       $where .= " AND a.amount <> a.paid" if ($form->{open});
 
 500       $where .= " AND a.amount = a.paid"  if ($form->{closed});
 
 504   if ($form->{parts_partnumber}) {
 
 507         SELECT invoice.trans_id
 
 509         LEFT JOIN parts ON (invoice.parts_id = parts.id)
 
 510         WHERE (invoice.trans_id = a.id)
 
 511           AND (parts.partnumber ILIKE ?)
 
 515     push @values, like($form->{parts_partnumber});
 
 518   if ($form->{parts_description}) {
 
 521         SELECT invoice.trans_id
 
 523         WHERE (invoice.trans_id = a.id)
 
 524           AND (invoice.description ILIKE ?)
 
 528     push @values, like($form->{parts_description});
 
 532     substr($where, 0, 4, " WHERE ");
 
 536   my @a = qw(transdate invnumber name);
 
 537   push @a, "employee" if $form->{l_employee};
 
 538   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
 539   my $sortorder = join(', ', map { "$_ $sortdir" } @a);
 
 541   if (grep({ $_ eq $form->{sort} } qw(transdate id invnumber ordnumber name netamount tax amount paid datepaid due duedate notes employee transaction_description direct_debit))) {
 
 542     $sortorder = $form->{sort} . " $sortdir";
 
 545   $query .= " ORDER BY $sortorder";
 
 547   my @result = selectall_hashref_query($form, $dbh, $query, @values);
 
 549   $form->{AP} = [ @result ];
 
 551   $main::lxdebug->leave_sub();
 
 555   $main::lxdebug->enter_sub();
 
 557   my ($self, $myconfig, $form) = @_;
 
 559   # connect to database
 
 560   my $dbh = SL::DB->client->dbh;
 
 564     "  (SELECT transdate FROM ap WHERE id = " .
 
 565     "    (SELECT MAX(id) FROM ap) LIMIT 1), " .
 
 567   ($form->{transdate}) = $dbh->selectrow_array($query);
 
 569   $main::lxdebug->leave_sub();
 
 572 sub _delete_payments {
 
 573   $main::lxdebug->enter_sub();
 
 575   my ($self, $form, $dbh) = @_;
 
 577   my @delete_acc_trans_ids;
 
 579   # Delete old payment entries from acc_trans.
 
 581     qq|SELECT acc_trans_id
 
 583        WHERE (trans_id = ?) AND fx_transaction
 
 587        SELECT at.acc_trans_id
 
 589        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 590        WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
 
 591   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
 
 594     qq|SELECT at.acc_trans_id
 
 596        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 598          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
 
 599        ORDER BY at.acc_trans_id
 
 601   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
 
 603   if (@delete_acc_trans_ids) {
 
 604     $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
 
 605     do_query($form, $dbh, $query);
 
 608   $main::lxdebug->leave_sub();
 
 612   my ($self, $myconfig, $form, $locale) = @_;
 
 613   $main::lxdebug->enter_sub();
 
 615   my $rc = SL::DB->client->with_transaction(\&_post_payment, $self, $myconfig, $form, $locale);
 
 617   $::lxdebug->leave_sub;
 
 622   my ($self, $myconfig, $form, $locale) = @_;
 
 624   my $dbh = SL::DB->client->dbh;
 
 626   my (%payments, $old_form, $row, $item, $query, %keep_vars);
 
 628   $old_form = save_form();
 
 631     SELECT at.acc_trans_id, at.amount, at.cleared, c.accno
 
 633     LEFT JOIN chart c ON (at.chart_id = c.id)
 
 634     WHERE (at.trans_id = ?)
 
 637   my %already_cleared = selectall_as_map($form, $dbh, $query, 'acc_trans_id', [ qw(amount cleared accno) ], $form->{id});
 
 639   # Delete all entries in acc_trans from prior payments.
 
 640   if (SL::DB::Default->get->payments_changeable != 0) {
 
 641     $self->_delete_payments($form, $dbh);
 
 644   # Save the new payments the user made before cleaning up $form.
 
 645   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$';
 
 646   map { $payments{$_} = $form->{$_} } grep m/$payments_re/, keys %{ $form };
 
 648   # Clean up $form so that old content won't tamper the results.
 
 649   %keep_vars = map { $_, 1 } qw(login password id);
 
 650   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
 
 652   # Retrieve the invoice from the database.
 
 653   $form->create_links('AP', $myconfig, 'vendor', $dbh);
 
 655   # Restore the payment options from the user input.
 
 656   map { $form->{$_} = $payments{$_} } keys %payments;
 
 658   # Set up the content of $form in the way that AR::post_transaction() expects.
 
 660   $self->setup_form($form, 1);
 
 662   $form->{exchangerate}    = $form->format_amount($myconfig, $form->{exchangerate});
 
 663   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
 
 669        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 671          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
 
 672        ORDER BY at.acc_trans_id
 
 675   ($form->{AP_chart_id}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
 
 677   # Post the new payments.
 
 678   $self->post_transaction($myconfig, $form, $dbh, payments_only => 1, already_cleared => \%already_cleared);
 
 680   restore_form($old_form);
 
 686   $main::lxdebug->enter_sub();
 
 688   my ($self, $form, $for_post_payments) = @_;
 
 690   my ($exchangerate, $i, $j, $k, $key, $akey, $ref, $index, $taxamount, $totalamount, $totaltax, $totalwithholding, $withholdingrate,
 
 694   $form->{forex} = $form->{exchangerate};
 
 695   $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
 
 697   foreach $key (keys %{ $form->{AP_links} }) {
 
 698     foreach $ref (@{ $form->{AP_links}{$key} }) {
 
 699       if ($key eq "AP_paid") {
 
 700         $form->{"select$key"} .= "<option value=\"$ref->{accno}\">$ref->{accno}--$ref->{description}</option>\n";
 
 702         $form->{"select$key"} .= "<option value=\"$ref->{accno}--$ref->{tax_id}\">$ref->{accno}--$ref->{description}</option>\n";
 
 706     $form->{$key} = $form->{"select$key"};
 
 711     # if there is a value we have an old entry
 
 712     next unless $form->{acc_trans}{$key};
 
 714     # do not use old entries for payments. They come from the form
 
 715     # even if they are not changeable (then they are in hiddens)
 
 716     next if $for_post_payments && $key eq "AP_paid";
 
 718     for $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
 
 720       if ($key eq "AP_paid") {
 
 722         $form->{"AP_paid_$j"}         = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 723         $form->{"acc_trans_id_$j"}    = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
 
 724         $form->{"paid_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{amount};
 
 725         $form->{"datepaid_$j"}        = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
 
 726         $form->{"gldate_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
 
 727         $form->{"source_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{source};
 
 728         $form->{"memo_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{memo};
 
 730         $form->{"exchangerate_$i"}    = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
 
 731         $form->{"forex_$j"}           = $form->{"exchangerate_$i"};
 
 732         $form->{"AP_paid_$j"}         = $form->{acc_trans}{$key}->[$i-1]->{accno};
 
 733         $form->{"paid_project_id_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{project_id};
 
 734         $form->{paidaccounts}++;
 
 740         if (($key eq "AP_tax") || ($key eq "AR_tax")) {
 
 741           $form->{"${key}_$form->{acc_trans}{$key}->[$i-1]->{accno}"}  = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 742           $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
 
 744           if ($form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"} > 0) {
 
 745             $totaltax += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
 
 747             $totalwithholding += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
 
 748             $withholdingrate  += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
 
 751           $index                 = $form->{acc_trans}{$key}->[$i - 1]->{index};
 
 752           $form->{"tax_$index"}  = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} * -1 / $exchangerate, 2);
 
 753           $totaltax             += $form->{"tax_$index"};
 
 757           $form->{"${akey}_$k"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
 
 759           if ($akey eq 'amount') {
 
 761             $form->{"${akey}_$i"} *= -1;
 
 762             $totalamount          += $form->{"${akey}_$i"};
 
 763             $form->{taxrate}       = $form->{acc_trans}{$key}->[$i - 1]->{rate};
 
 765             $form->{"projectnumber_$k"}    = "$form->{acc_trans}{$key}->[$i-1]->{projectnumber}";
 
 766             $form->{"oldprojectnumber_$k"} = $form->{"projectnumber_$k"};
 
 767             $form->{"project_id_$k"}       = "$form->{acc_trans}{$key}->[$i-1]->{project_id}";
 
 768             $form->{"${key}_chart_id_$k"}  = $form->{acc_trans}{$key}->[$i-1]->{chart_id};
 
 769             $form->{"taxchart_$k"} = $form->{acc_trans}{$key}->[$i-1]->{id}    . "--" . $form->{acc_trans}{$key}->[$i-1]->{rate};
 
 776   $form->{paidaccounts} = 1            if not defined $form->{paidaccounts};
 
 778   if ($form->{taxincluded} && $form->{taxrate} && $totalamount) {
 
 779     # add tax to amounts and invtotal
 
 780     for $i (1 .. $form->{rowcount}) {
 
 781       $taxamount            = ($totaltax + $totalwithholding) * $form->{"amount_$i"} / $totalamount;
 
 782       $tax                  = $form->round_amount($taxamount, 2);
 
 783       $diff                += ($taxamount - $tax);
 
 784       $form->{"amount_$i"} += $form->{"tax_$i"};
 
 787     $form->{amount_1} += $form->round_amount($diff, 2);
 
 790   $taxamount        = $form->round_amount($taxamount, 2);
 
 791   $form->{invtotal} = $totalamount + $totaltax;
 
 793   $main::lxdebug->leave_sub();
 
 797   my ($self, $form, $myconfig, $id) = @_;
 
 798   $main::lxdebug->enter_sub();
 
 800   my $rc = SL::DB->client->with_transaction(\&_storno, $self, $form, $myconfig, $id);
 
 802   $::lxdebug->leave_sub;
 
 807   my ($self, $form, $myconfig, $id) = @_;
 
 809   my ($query, $new_id, $storno_row, $acc_trans_rows);
 
 810   my $dbh = SL::DB->client->dbh;
 
 812   $query = qq|SELECT nextval('glid')|;
 
 813   ($new_id) = selectrow_query($form, $dbh, $query);
 
 815   $query = qq|SELECT * FROM ap WHERE id = ?|;
 
 816   $storno_row = selectfirst_hashref_query($form, $dbh, $query, $id);
 
 818   $storno_row->{id}         = $new_id;
 
 819   $storno_row->{storno_id}  = $id;
 
 820   $storno_row->{storno}     = 't';
 
 821   $storno_row->{invnumber}  = 'Storno-' . $storno_row->{invnumber};
 
 822   $storno_row->{amount}    *= -1;
 
 823   $storno_row->{netamount} *= -1;
 
 824   $storno_row->{paid}       = $storno_row->{amount};
 
 826   delete @$storno_row{qw(itime mtime)};
 
 828   $query = sprintf 'INSERT INTO ap (%s) VALUES (%s)', join(', ', keys %$storno_row), join(', ', map '?', values %$storno_row);
 
 829   do_query($form, $dbh, $query, (values %$storno_row));
 
 831   $query = qq|UPDATE ap SET paid = amount + paid, storno = 't' WHERE id = ?|;
 
 832   do_query($form, $dbh, $query, $id);
 
 834   $form->new_lastmtime('ap') if $id == $form->{id};
 
 836   # now copy acc_trans entries
 
 837   $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|;
 
 838   my $rowref = selectall_hashref_query($form, $dbh, $query, $id);
 
 840   # kill all entries containing payments, which are the last 2n rows, of which the last has link =~ /paid/
 
 841   while ($rowref->[-1]{link} =~ /paid/) {
 
 842     splice(@$rowref, -2);
 
 845   for my $row (@$rowref) {
 
 846     delete @$row{qw(itime mtime link acc_trans_id)};
 
 847     $query = sprintf 'INSERT INTO acc_trans (%s) VALUES (%s)', join(', ', keys %$row), join(', ', map '?', values %$row);
 
 848     $row->{trans_id}   = $new_id;
 
 849     $row->{amount}    *= -1;
 
 850     do_query($form, $dbh, $query, (values %$row));
 
 853   map { IO->set_datepaid(table => 'ap', id => $_, dbh => $dbh) } ($id, $new_id);