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);
 
  46 use SL::DB::PurchaseInvoice;
 
  47 use SL::Util qw(trim);
 
  50 use List::Util qw(sum0);
 
  53 sub post_transaction {
 
  54   my ($self, $myconfig, $form, $provided_dbh, %params) = @_;
 
  55   $main::lxdebug->enter_sub();
 
  57   my $rc = SL::DB->client->with_transaction(\&_post_transaction, $self, $myconfig, $form, $provided_dbh, %params);
 
  59   $::lxdebug->leave_sub;
 
  63 sub _post_transaction {
 
  64   my ($self, $myconfig, $form, $provided_dbh, %params) = @_;
 
  66   my $payments_only = $params{payments_only};
 
  67   my $dbh = $provided_dbh || SL::DB->client->dbh;
 
  69   my ($null, $taxrate, $amount);
 
  72   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
 
  73   $form->{taxincluded} = 0 unless $form->{taxincluded};
 
  75   if ($form->{currency} eq $form->{defaultcurrency}) {
 
  76     $form->{exchangerate} = 1;
 
  78     $exchangerate         = $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'sell');
 
  79     $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
 
  82   # get the charts selected
 
  83   $form->{AP_amounts}{"amount_$_"} = $form->{"AP_amount_chart_id_$_"} for (1 .. $form->{rowcount});
 
  85   # calculate the totals while calculating and reformatting the $amount_$i and $tax_$i
 
  86   ($form->{netamount},$form->{total_tax},$form->{invtotal}) = $form->calculate_arap('buy',$form->{taxincluded}, $form->{exchangerate});
 
  88   # adjust paidaccounts if there is no date in the last row
 
  89   $form->{paidaccounts}-- unless ($form->{"datepaid_$form->{paidaccounts}"});
 
  94   for my $i (1 .. $form->{paidaccounts}) {
 
  96       $form->round_amount($form->parse_amount($myconfig, $form->{"paid_$i"}),
 
  99     $form->{invpaid} += $form->{"paid_$i"};
 
 100     $form->{datepaid} = $form->{"datepaid_$i"};
 
 105     $form->round_amount($form->{invpaid} * $form->{exchangerate}, 2);
 
 107   # # store invoice total, this goes into ap table
 
 108   # $form->{invtotal} = $form->{netamount} + $form->{total_tax};
 
 110   # amount for total AP
 
 111   $form->{payables} = $form->{invtotal};
 
 113   # update exchangerate
 
 114   if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
 
 115     $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate}, 0,
 
 116                                $form->{exchangerate});
 
 119   my ($query, $sth, @values);
 
 121   if (!$payments_only) {
 
 122     # if we have an id delete old records
 
 125       # delete detail records
 
 126       $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
 
 127       do_query($form, $dbh, $query, $form->{id});
 
 131       ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
 
 134         qq|INSERT INTO ap (id, invnumber, employee_id,currency_id, taxzone_id) | .
 
 135         qq|VALUES (?, ?, (SELECT e.id FROM employee e WHERE e.login = ?),
 
 136                       (SELECT id FROM currencies WHERE name = ?), (SELECT taxzone_id FROM vendor WHERE id = ?) )|;
 
 137       do_query($form, $dbh, $query, $form->{id}, $form->{invnumber}, $::myconfig{login}, $form->{currency}, $form->{vendor_id});
 
 141     $query = qq|UPDATE ap SET invnumber = ?,
 
 142                 transdate = ?, ordnumber = ?, vendor_id = ?, taxincluded = ?,
 
 143                 amount = ?, duedate = ?, deliverydate = ?, tax_point = ?, paid = ?, netamount = ?,
 
 144                 currency_id = (SELECT id FROM currencies WHERE name = ?), notes = ?, department_id = ?, storno = ?, storno_id = ?,
 
 145                 globalproject_id = ?, direct_debit = ?, payment_id = ?, transaction_description = ?
 
 147     @values = ($form->{invnumber}, conv_date($form->{transdate}),
 
 148                   $form->{ordnumber}, conv_i($form->{vendor_id}),
 
 149                   $form->{taxincluded} ? 't' : 'f', $form->{invtotal},
 
 150                   conv_date($form->{duedate}), conv_date($form->{deliverydate}), conv_date($form->{tax_point}),
 
 151                   $form->{invpaid}, $form->{netamount},
 
 152                   $form->{currency}, $form->{notes},
 
 153                   conv_i($form->{department_id}), $form->{storno},
 
 154                   $form->{storno_id}, conv_i($form->{globalproject_id}),
 
 155                   $form->{direct_debit} ? 't' : 'f',
 
 156                   conv_i($form->{payment_id}), $form->{transaction_description},
 
 158     do_query($form, $dbh, $query, @values);
 
 160     $form->new_lastmtime('ap');
 
 162     # Link this record to the record it was created from.
 
 163     my $convert_from_oe_id = delete $form->{convert_from_oe_id};
 
 164     if (!$form->{postasnew} && $convert_from_oe_id) {
 
 165       RecordLinks->create_links('dbh'        => $dbh,
 
 167                                 'from_table' => 'oe',
 
 168                                 'from_ids'   => $convert_from_oe_id,
 
 170                                 'to_id'      => $form->{id},
 
 173       # Close the record it was created from if the amount of
 
 174       # all APs create from this record equals the records amount.
 
 175       my @links = RecordLinks->get_links('dbh'        => $dbh,
 
 176                                          'from_table' => 'oe',
 
 177                                          'from_id'    => $convert_from_oe_id,
 
 181       my $amount_sum = sum0 map { SL::DB::PurchaseInvoice->new(id => $_->{to_id})->load->amount } @links;
 
 182       my $order      = SL::DB::Order->new(id => $convert_from_oe_id)->load;
 
 184       $order->update_attributes(closed => 1) if ($amount_sum - $order->amount) == 0;
 
 187     # add individual transactions
 
 188     for my $i (1 .. $form->{rowcount}) {
 
 189       if ($form->{"amount_$i"} != 0) {
 
 191         $project_id = conv_i($form->{"project_id_$i"});
 
 193         # insert detail records in acc_trans
 
 195           qq|INSERT INTO acc_trans | .
 
 196           qq|  (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link)| .
 
 197           qq|VALUES (?, ?,   ?, ?, ?, ?, ?, (SELECT c.link FROM chart c WHERE c.id = ?))|;
 
 198         @values = ($form->{id}, $form->{"AP_amount_chart_id_$i"},
 
 199                    $form->{"amount_$i"}, conv_date($form->{transdate}),
 
 200                    $project_id, $form->{"taxkey_$i"}, conv_i($form->{"tax_id_$i"}),
 
 201                    $form->{"AP_amount_chart_id_$i"});
 
 202         do_query($form, $dbh, $query, @values);
 
 204         if ($form->{"tax_$i"} != 0) {
 
 205           # insert detail records in acc_trans
 
 207             qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, | .
 
 208             qq|  project_id, taxkey, tax_id, chart_link) | .
 
 209             qq|VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), | .
 
 210             qq|  ?, ?, ?, ?, ?,| .
 
 211             qq| (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 212           @values = ($form->{id}, $form->{AP_amounts}{"tax_$i"},
 
 213                      $form->{"tax_$i"}, conv_date($form->{transdate}),
 
 214                      $project_id, $form->{"taxkey_$i"}, conv_i($form->{"tax_id_$i"}),
 
 215                      $form->{AP_amounts}{"tax_$i"});
 
 216           do_query($form, $dbh, $query, @values);
 
 224       qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) | .
 
 225       qq|VALUES (?, ?, ?, ?, | .
 
 226       qq|        (SELECT taxkey_id FROM chart WHERE id = ?),| .
 
 227       qq|        (SELECT tax_id| .
 
 229       qq|         WHERE chart_id = ?| .
 
 230       qq|         AND startdate <= ?| .
 
 231       qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 232       qq|        (SELECT c.link FROM chart c WHERE c.id = ?))|;
 
 233     @values = ($form->{id}, $form->{AP_chart_id}, $form->{payables},
 
 234                conv_date($form->{transdate}), $form->{AP_chart_id}, $form->{AP_chart_id}, conv_date($form->{transdate}),
 
 235                $form->{AP_chart_id});
 
 236     do_query($form, $dbh, $query, @values);
 
 239   # if there is no amount but a payment record a payable
 
 240   if ($form->{amount} == 0 && $form->{invtotal} == 0) {
 
 241     $form->{payables} = $form->{invpaid};
 
 244   my %already_cleared = %{ $params{already_cleared} // {} };
 
 246   # add paid transactions
 
 247   for my $i (1 .. $form->{paidaccounts}) {
 
 249     if ($form->{"acc_trans_id_$i"} && $payments_only && (SL::DB::Default->get->payments_changeable == 0)) {
 
 253     if ($form->{"paid_$i"} != 0) {
 
 254       my $project_id = conv_i($form->{"paid_project_id_$i"});
 
 257       if ($form->{currency} eq $form->{defaultcurrency}) {
 
 258         $form->{"exchangerate_$i"} = 1;
 
 260         $exchangerate              = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
 
 261         $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
 
 263       $form->{"AP_paid_$i"} =~ s/\"//g;
 
 267       ($form->{"AP_paid_account_$i"}) = split(/--/, $form->{"AP_paid_$i"});
 
 268       $form->{"datepaid_$i"} = $form->{transdate}
 
 269         unless ($form->{"datepaid_$i"});
 
 271       # if there is no amount and invtotal is zero there is no exchangerate
 
 272       if ($form->{amount} == 0 && $form->{invtotal} == 0) {
 
 273         $form->{exchangerate} = $form->{"exchangerate_$i"};
 
 277         $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} * -1,
 
 280       my $new_cleared = !$form->{"acc_trans_id_$i"}                                                             ? 'f'
 
 281                       : !$already_cleared{$form->{"acc_trans_id_$i"}}                                           ? 'f'
 
 282                       : $already_cleared{$form->{"acc_trans_id_$i"}}->{amount} != $amount * -1                  ? 'f'
 
 283                       : $already_cleared{$form->{"acc_trans_id_$i"}}->{accno}  != $form->{"AP_paid_account_$i"} ? 'f'
 
 284                       : $already_cleared{$form->{"acc_trans_id_$i"}}->{cleared}                                 ? 't'
 
 287       if ($form->{payables}) {
 
 289           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, cleared, taxkey, tax_id, chart_link) | .
 
 290           qq|VALUES (?, ?, ?, ?, ?, ?, | .
 
 291           qq|        (SELECT taxkey_id FROM chart WHERE id = ?),| .
 
 292           qq|        (SELECT tax_id| .
 
 294           qq|         WHERE chart_id = ?| .
 
 295           qq|         AND startdate <= ?| .
 
 296           qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 297           qq|        (SELECT c.link FROM chart c WHERE c.id = ?))|;
 
 298         @values = ($form->{id}, $form->{AP_chart_id}, $amount,
 
 299                    conv_date($form->{"datepaid_$i"}), $project_id, $new_cleared,
 
 300                    $form->{AP_chart_id}, $form->{AP_chart_id}, conv_date($form->{"datepaid_$i"}),
 
 301                    $form->{AP_chart_id});
 
 302         do_query($form, $dbh, $query, @values);
 
 304       $form->{payables} = $amount;
 
 307       my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
 
 309         qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, project_id, cleared, taxkey, tax_id, chart_link) | .
 
 310         qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?, ?, ?, | .
 
 311         qq|        (SELECT taxkey_id FROM chart WHERE accno = ?), | .
 
 312         qq|        (SELECT tax_id| .
 
 314         qq|         WHERE chart_id= (SELECT id | .
 
 316         qq|                          WHERE accno = ?)| .
 
 317         qq|         AND startdate <= ?| .
 
 318         qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 319         qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 320       @values = ($form->{id}, $form->{"AP_paid_account_$i"}, $form->{"paid_$i"},
 
 321                  conv_date($form->{"datepaid_$i"}), $gldate, $form->{"source_$i"},
 
 322                  $form->{"memo_$i"}, $project_id, $new_cleared, $form->{"AP_paid_account_$i"},
 
 323                  $form->{"AP_paid_account_$i"}, conv_date($form->{"datepaid_$i"}),
 
 324                  $form->{"AP_paid_account_$i"});
 
 325       do_query($form, $dbh, $query, @values);
 
 327       # add exchange rate difference
 
 329         $form->round_amount($form->{"paid_$i"} *
 
 330                             ($form->{"exchangerate_$i"} - 1), 2);
 
 333           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link) | .
 
 334           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, | .
 
 335           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?), | .
 
 336           qq|        (SELECT tax_id| .
 
 338           qq|         WHERE chart_id= (SELECT id | .
 
 340           qq|                          WHERE accno = ?)| .
 
 341           qq|         AND startdate <= ?| .
 
 342           qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 343           qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 344         @values = ($form->{id}, $form->{"AP_paid_account_$i"}, $amount,
 
 345                    conv_date($form->{"datepaid_$i"}), $project_id,
 
 346                    $form->{"AP_paid_account_$i"},
 
 347                    $form->{"AP_paid_account_$i"}, conv_date($form->{"datepaid_$i"}),
 
 348                    $form->{"AP_paid_account_$i"});
 
 349         do_query($form, $dbh, $query, @values);
 
 352       # exchangerate gain/loss
 
 354         $form->round_amount($form->{"paid_$i"} *
 
 355                             ($form->{exchangerate} -
 
 356                              $form->{"exchangerate_$i"}), 2);
 
 359         # fetch fxgain and fxloss chart info from defaults if charts aren't already filled in form
 
 360         if ( !$form->{fxgain_accno} && $::instance_conf->get_fxgain_accno_id ) {
 
 361           $form->{fxgain_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxgain_accno_id)->accno;
 
 363         if ( !$form->{fxloss_accno} && $::instance_conf->get_fxloss_accno_id ) {
 
 364           $form->{fxloss_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxloss_accno_id)->accno;
 
 366         die "fxloss_accno missing" if $amount < 0 and not $form->{fxloss_accno};
 
 367         die "fxgain_accno missing" if $amount > 0 and not $form->{fxgain_accno};
 
 369           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link) | .
 
 370           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, | .
 
 371           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?),| .
 
 372           qq|        (SELECT tax_id| .
 
 374           qq|         WHERE chart_id= (SELECT id | .
 
 376           qq|                          WHERE accno = ?)| .
 
 377           qq|         AND startdate <= ?| .
 
 378           qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 379           qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 380         @values = ($form->{id},
 
 381                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno},
 
 382                    $amount, conv_date($form->{"datepaid_$i"}), $project_id,
 
 383                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno},
 
 384                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno}, conv_date($form->{"datepaid_$i"}),
 
 385                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno});
 
 386         do_query($form, $dbh, $query, @values);
 
 389       # update exchange rate record
 
 390       if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
 
 391         $form->update_exchangerate($dbh, $form->{currency},
 
 392                                    $form->{"datepaid_$i"},
 
 393                                    0, $form->{"exchangerate_$i"});
 
 398   if ($payments_only) {
 
 399     $query = qq|UPDATE ap SET paid = ?, datepaid = ? WHERE id = ?|;
 
 400     do_query($form, $dbh, $query,  $form->{invpaid}, $form->{invpaid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
 
 401     $form->new_lastmtime('ap');
 
 404   IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
 
 406   if ($form->{draft_id}) {
 
 407     SL::DB::Manager::Draft->delete_all(where => [ id => delete($form->{draft_id}) ]);
 
 411   $self->_reverse_charge($myconfig, $form);
 
 412   # safety check datev export
 
 413   if ($::instance_conf->get_datev_check_on_ap_transaction) {
 
 414     my $datev = SL::DATEV->new(
 
 416       trans_id   => $form->{id},
 
 418     $datev->generate_datev_data;
 
 420     if ($datev->errors) {
 
 421       die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
 
 428 sub _reverse_charge {
 
 429   my ($self, $myconfig, $form) = @_;
 
 431   # delete previous bookings, if they exists (repost)
 
 432   my $ap_gl = SL::DB::Manager::ApGl->get_first(where => [ ap_id => $form->{id} ]);
 
 433   my $gl_id = ref $ap_gl eq 'SL::DB::ApGl' ? $ap_gl->gl_id : undef;
 
 435   SL::DB::Manager::GLTransaction->delete_all(where => [ id    => $gl_id ])       if $gl_id;
 
 436   SL::DB::Manager::ApGl->         delete_all(where => [ ap_id => $form->{id} ])  if $gl_id;
 
 437   SL::DB::Manager::RecordLink->   delete_all(where => [ from_table => 'ap', to_table => 'gl', from_id => $form->{id} ]);
 
 439   my ($i, $current_transaction);
 
 441   for $i (1 .. $form->{rowcount}) {
 
 443     my $tax = SL::DB::Manager::Tax->get_first( where => [id => $form->{"tax_id_$i"}, '!reverse_charge_chart_id' => undef ]);
 
 444     next unless ref $tax eq 'SL::DB::Tax';
 
 447     my ($credit, $debit);
 
 448     $credit   = SL::DB::Manager::Chart->find_by(id => $tax->chart_id);
 
 449     $debit    = SL::DB::Manager::Chart->find_by(id => $tax->reverse_charge_chart_id);
 
 451     croak("No such Chart ID" . $tax->chart_id)          unless ref $credit eq 'SL::DB::Chart';
 
 452     croak("No such Chart ID" . $tax->reverse_chart_id)  unless ref $debit  eq 'SL::DB::Chart';
 
 454     my ($tmpnetamount, $tmptaxamount) = $form->calculate_tax($form->{"amount_$i"}, $tax->rate, $form->{taxincluded}, 2);
 
 455     $current_transaction = SL::DB::GLTransaction->new(
 
 456           employee_id    => $form->{employee_id},
 
 457           transdate      => $form->{transdate},
 
 458           description    => $form->{notes} || $form->{invnumber},
 
 459           reference      => $form->{invnumber},
 
 460           department_id  => $form->{department_id} ? $form->{department_id} : undef,
 
 461           imported       => 0, # not imported
 
 463         )->add_chart_booking(
 
 464           chart  => $tmptaxamount > 0 ? $debit : $credit,
 
 465           debit  => abs($tmptaxamount),
 
 466           source => "Reverse Charge for " . $form->{invnumber},
 
 468         )->add_chart_booking(
 
 469           chart  => $tmptaxamount > 0 ? $credit : $debit,
 
 470           credit => abs($tmptaxamount),
 
 471           source => "Reverse Charge for " . $form->{invnumber},
 
 474     # add a stable link from ap to gl
 
 476         ap_id => $form->{id},
 
 477         gl_id => $current_transaction->id,
 
 479     SL::DB::ApGl->new(%props_gl)->save;
 
 480     # Record a record link from ap to gl
 
 483         from_id    => $form->{id},
 
 485         to_id      => $current_transaction->id,
 
 487     SL::DB::RecordLink->new(%props_rl)->save;
 
 491 sub delete_transaction {
 
 492   $main::lxdebug->enter_sub();
 
 494   my ($self, $myconfig, $form) = @_;
 
 496   SL::DB->client->with_transaction(sub {
 
 498     # if tax 94 reverse charge, clear all GL bookings and links
 
 499     my $ap_gl = SL::DB::Manager::ApGl->get_first(where => [ ap_id => $form->{id} ]);
 
 500     my $gl_id = ref $ap_gl eq 'SL::DB::ApGl' ? $ap_gl->gl_id : undef;
 
 502     SL::DB::Manager::GLTransaction->delete_all(where => [ id    => $gl_id ])       if $gl_id;
 
 503     SL::DB::Manager::ApGl->         delete_all(where => [ ap_id => $form->{id} ])  if $gl_id;
 
 504     SL::DB::Manager::RecordLink->   delete_all(where => [ from_table => 'ap', to_table => 'gl', from_id => $form->{id} ]);
 
 505     # done gl delete for tax 94 case
 
 508     my $query = qq|DELETE FROM ap WHERE id = ?|;
 
 509     do_query($form, SL::DB->client->dbh, $query, $form->{id});
 
 511   }) or do { die SL::DB->client->error };
 
 513   $main::lxdebug->leave_sub();
 
 518 sub ap_transactions {
 
 519   $main::lxdebug->enter_sub();
 
 521   my ($self, $myconfig, $form) = @_;
 
 523   # connect to database
 
 524   my $dbh = $form->get_standard_dbh($myconfig);
 
 527     qq|SELECT a.id, a.invnumber, a.transdate, a.duedate, a.amount, a.paid, | .
 
 528     qq|  a.ordnumber, v.name, a.invoice, a.netamount, a.datepaid, a.notes, | .
 
 529     qq|  a.globalproject_id, a.storno, a.storno_id, a.direct_debit, | .
 
 530     qq|  a.transaction_description, a.itime::DATE AS insertdate, | .
 
 531     qq|  pr.projectnumber AS globalprojectnumber, | .
 
 532     qq|  e.name AS employee, | .
 
 533     qq|  v.vendornumber, v.country, v.ustid, | .
 
 534     qq|  tz.description AS taxzone, | .
 
 535     qq|  pt.description AS payment_terms, | .
 
 536     qq|  department.description AS department, | .
 
 537     qq{  ( SELECT ch.accno || ' -- ' || ch.description
 
 539            LEFT JOIN chart ch ON ch.id = at.chart_id
 
 540            WHERE ch.link ~ 'AP[[:>:]]'
 
 541             AND at.trans_id = a.id
 
 544     qq{  ( SELECT ch.accno || ' -- ' || ch.description
 
 546            LEFT JOIN chart ch ON ch.id = at.chart_id
 
 547            WHERE ch.link ~ 'AP_amount'
 
 548             AND at.trans_id = a.id
 
 552     qq|JOIN vendor v ON (a.vendor_id = v.id) | .
 
 553     qq|LEFT JOIN contacts cp ON (a.cp_id = cp.cp_id) | .
 
 554     qq|LEFT JOIN employee e ON (a.employee_id = e.id) | .
 
 555     qq|LEFT JOIN project pr ON (a.globalproject_id = pr.id) | .
 
 556     qq|LEFT JOIN tax_zones tz ON (tz.id = a.taxzone_id)| .
 
 557     qq|LEFT JOIN payment_terms pt ON (pt.id = a.payment_id)| .
 
 558     qq|LEFT JOIN department ON (department.id = a.department_id)|;
 
 565   # - Always return invoices & AP transactions for projects the employee has "view invoices" permissions for, no matter what the other rules say.
 
 566   # - Exclude AP transactions if no permissions for them exist.
 
 567   # - Limit to own invoices unless may edit all invoices or view invoices is allowed.
 
 568   # - If may edit all or view invoices is allowed, allow filtering by employee.
 
 569   my (@permission_where, @permission_values);
 
 571   if ($::auth->assert('vendor_invoice_edit', 1) || $::auth->assert('purchase_invoice_view', 1)) {
 
 572     if (!$::auth->assert('show_ap_transactions', 1)) {
 
 573       push @permission_where, "NOT invoice = 'f'"; # remove ap transactions from Purchase -> Reports -> Invoices
 
 576     if (!$::auth->assert('purchase_all_edit', 1) && !$::auth->assert('purchase_invoice_view', 1)) {
 
 577       # only show own invoices
 
 578       push @permission_where,  "a.employee_id = ?";
 
 579       push @permission_values, SL::DB::Manager::Employee->current->id;
 
 582       if ($form->{employee_id}) {
 
 583         push @permission_where,  "a.employee_id = ?";
 
 584         push @permission_values, conv_i($form->{employee_id});
 
 589   if (@permission_where || (!$::auth->assert('vendor_invoice_edit', 1) && !$::auth->assert('purchase_invoice_view', 1))) {
 
 590     my $permission_where_str = @permission_where ? "OR (" . join(" AND ", map { "($_)" } @permission_where) . ")" : "";
 
 592       AND (   (a.globalproject_id IN (
 
 593                SELECT epi.project_id
 
 594                FROM employee_project_invoices epi
 
 595                WHERE epi.employee_id = ?))
 
 596            $permission_where_str)
 
 598     push @values, SL::DB::Manager::Employee->current->id, @permission_values;
 
 601   if ($form->{vendor}) {
 
 602     $where .= " AND v.name ILIKE ?";
 
 603     push(@values, like($form->{vendor}));
 
 605   if ($form->{"cp_name"}) {
 
 606     $where .= " AND (cp.cp_name ILIKE ? OR cp.cp_givenname ILIKE ?)";
 
 607     push(@values, (like($form->{"cp_name"}))x2);
 
 609   if ($form->{department_id}) {
 
 610     $where .= " AND a.department_id = ?";
 
 611     push(@values, $form->{department_id});
 
 613   if ($form->{invnumber}) {
 
 614     $where .= " AND a.invnumber ILIKE ?";
 
 615     push(@values, like($form->{invnumber}));
 
 617   if ($form->{ordnumber}) {
 
 618     $where .= " AND a.ordnumber ILIKE ?";
 
 619     push(@values, like($form->{ordnumber}));
 
 621   if ($form->{taxzone_id}) {
 
 622     $where .= " AND a.taxzone_id = ?";
 
 623     push(@values, $form->{taxzone_id});
 
 625   if ($form->{transaction_description}) {
 
 626     $where .= " AND a.transaction_description ILIKE ?";
 
 627     push(@values, like($form->{transaction_description}));
 
 629   if ($form->{notes}) {
 
 630     $where .= " AND a.notes ILIKE ?";
 
 631     push(@values, like($form->{notes}));
 
 633   if ($form->{project_id}) {
 
 635       qq| AND ((a.globalproject_id = ?) OR EXISTS | .
 
 636       qq|  (SELECT * FROM invoice i | .
 
 637       qq|   WHERE i.project_id = ? AND i.trans_id = a.id) | .
 
 639       qq|  (SELECT * FROM acc_trans at | .
 
 640       qq|   WHERE at.project_id = ? AND at.trans_id = a.id)| .
 
 642     push(@values, $form->{project_id}, $form->{project_id}, $form->{project_id});
 
 645   if ($form->{transdatefrom}) {
 
 646     $where .= " AND a.transdate >= ?";
 
 647     push(@values, trim($form->{transdatefrom}));
 
 649   if ($form->{transdateto}) {
 
 650     $where .= " AND a.transdate <= ?";
 
 651     push(@values, trim($form->{transdateto}));
 
 653   if ($form->{duedatefrom}) {
 
 654     $where .= " AND a.duedate >= ?";
 
 655     push(@values, trim($form->{duedatefrom}));
 
 657   if ($form->{duedateto}) {
 
 658     $where .= " AND a.duedate <= ?";
 
 659     push(@values, trim($form->{duedateto}));
 
 661   if ($form->{open} || $form->{closed}) {
 
 662     unless ($form->{open} && $form->{closed}) {
 
 663       $where .= " AND a.amount <> a.paid" if ($form->{open});
 
 664       $where .= " AND a.amount = a.paid"  if ($form->{closed});
 
 668   if ($form->{parts_partnumber}) {
 
 671         SELECT invoice.trans_id
 
 673         LEFT JOIN parts ON (invoice.parts_id = parts.id)
 
 674         WHERE (invoice.trans_id = a.id)
 
 675           AND (parts.partnumber ILIKE ?)
 
 679     push @values, like($form->{parts_partnumber});
 
 682   if ($form->{parts_description}) {
 
 685         SELECT invoice.trans_id
 
 687         WHERE (invoice.trans_id = a.id)
 
 688           AND (invoice.description ILIKE ?)
 
 692     push @values, like($form->{parts_description});
 
 696     $where  =~ s{\s*AND\s*}{ WHERE };
 
 700   my @a = qw(transdate invnumber name);
 
 701   push @a, "employee" if $form->{l_employee};
 
 702   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
 703   my $sortorder = join(', ', map { "$_ $sortdir" } @a);
 
 705   if (grep({ $_ eq $form->{sort} } qw(transdate id invnumber ordnumber name netamount tax amount paid datepaid due duedate notes employee transaction_description direct_debit department taxzone))) {
 
 706     $sortorder = $form->{sort} . " $sortdir";
 
 709   $query .= " ORDER BY $sortorder";
 
 711   my @result = selectall_hashref_query($form, $dbh, $query, @values);
 
 713   $form->{AP} = [ @result ];
 
 715   $main::lxdebug->leave_sub();
 
 719   $main::lxdebug->enter_sub();
 
 721   my ($self, $myconfig, $form) = @_;
 
 723   # connect to database
 
 724   my $dbh = SL::DB->client->dbh;
 
 728     "  (SELECT transdate FROM ap WHERE id = " .
 
 729     "    (SELECT MAX(id) FROM ap) LIMIT 1), " .
 
 731   ($form->{transdate}) = $dbh->selectrow_array($query);
 
 733   $main::lxdebug->leave_sub();
 
 736 sub _delete_payments {
 
 737   $main::lxdebug->enter_sub();
 
 739   my ($self, $form, $dbh) = @_;
 
 741   my @delete_acc_trans_ids;
 
 743   # Delete old payment entries from acc_trans.
 
 745     qq|SELECT acc_trans_id
 
 747        WHERE (trans_id = ?) AND fx_transaction
 
 751        SELECT at.acc_trans_id
 
 753        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 754        WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
 
 755   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
 
 758     qq|SELECT at.acc_trans_id
 
 760        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 762          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
 
 763        ORDER BY at.acc_trans_id
 
 765   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
 
 767   if (@delete_acc_trans_ids) {
 
 768     $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
 
 769     do_query($form, $dbh, $query);
 
 772   $main::lxdebug->leave_sub();
 
 776   my ($self, $myconfig, $form, $locale) = @_;
 
 777   $main::lxdebug->enter_sub();
 
 779   my $rc = SL::DB->client->with_transaction(\&_post_payment, $self, $myconfig, $form, $locale);
 
 781   $::lxdebug->leave_sub;
 
 786   my ($self, $myconfig, $form, $locale) = @_;
 
 788   my $dbh = SL::DB->client->dbh;
 
 790   my (%payments, $old_form, $row, $item, $query, %keep_vars);
 
 792   $old_form = save_form();
 
 795     SELECT at.acc_trans_id, at.amount, at.cleared, c.accno
 
 797     LEFT JOIN chart c ON (at.chart_id = c.id)
 
 798     WHERE (at.trans_id = ?)
 
 801   my %already_cleared = selectall_as_map($form, $dbh, $query, 'acc_trans_id', [ qw(amount cleared accno) ], $form->{id});
 
 803   # Delete all entries in acc_trans from prior payments.
 
 804   if (SL::DB::Default->get->payments_changeable != 0) {
 
 805     $self->_delete_payments($form, $dbh);
 
 808   # Save the new payments the user made before cleaning up $form.
 
 809   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$';
 
 810   map { $payments{$_} = $form->{$_} } grep m/$payments_re/, keys %{ $form };
 
 812   # Clean up $form so that old content won't tamper the results.
 
 813   %keep_vars = map { $_, 1 } qw(login password id);
 
 814   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
 
 816   # Retrieve the invoice from the database.
 
 817   $form->create_links('AP', $myconfig, 'vendor', $dbh);
 
 819   # Restore the payment options from the user input.
 
 820   map { $form->{$_} = $payments{$_} } keys %payments;
 
 822   # Set up the content of $form in the way that AR::post_transaction() expects.
 
 824   $self->setup_form($form, 1);
 
 826   $form->{exchangerate}    = $form->format_amount($myconfig, $form->{exchangerate});
 
 827   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
 
 833        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 835          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
 
 836        ORDER BY at.acc_trans_id
 
 839   ($form->{AP_chart_id}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
 
 841   # Post the new payments.
 
 842   $self->post_transaction($myconfig, $form, $dbh, payments_only => 1, already_cleared => \%already_cleared);
 
 844   restore_form($old_form);
 
 850   $main::lxdebug->enter_sub();
 
 852   my ($self, $form, $for_post_payments) = @_;
 
 854   my ($exchangerate, $i, $j, $k, $key, $akey, $ref, $index, $taxamount, $totalamount, $totaltax, $totalwithholding, $withholdingrate,
 
 858   $form->{forex} = $form->{exchangerate};
 
 859   $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
 
 861   foreach $key (keys %{ $form->{AP_links} }) {
 
 862     foreach $ref (@{ $form->{AP_links}{$key} }) {
 
 863       if ($key eq "AP_paid") {
 
 864         $form->{"select$key"} .= "<option value=\"$ref->{accno}\">$ref->{accno}--$ref->{description}</option>\n";
 
 866         $form->{"select$key"} .= "<option value=\"$ref->{accno}--$ref->{tax_id}\">$ref->{accno}--$ref->{description}</option>\n";
 
 870     $form->{$key} = $form->{"select$key"};
 
 875     # if there is a value we have an old entry
 
 876     next unless $form->{acc_trans}{$key};
 
 878     # do not use old entries for payments. They come from the form
 
 879     # even if they are not changeable (then they are in hiddens)
 
 880     next if $for_post_payments && $key eq "AP_paid";
 
 882     for $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
 
 884       if ($key eq "AP_paid") {
 
 886         $form->{"AP_paid_$j"}         = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 887         $form->{"acc_trans_id_$j"}    = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
 
 888         $form->{"paid_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{amount};
 
 889         $form->{"datepaid_$j"}        = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
 
 890         $form->{"gldate_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
 
 891         $form->{"source_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{source};
 
 892         $form->{"memo_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{memo};
 
 894         $form->{"exchangerate_$i"}    = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
 
 895         $form->{"forex_$j"}           = $form->{"exchangerate_$i"};
 
 896         $form->{"AP_paid_$j"}         = $form->{acc_trans}{$key}->[$i-1]->{accno};
 
 897         $form->{"paid_project_id_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{project_id};
 
 898         $form->{paidaccounts}++;
 
 904         if (($key eq "AP_tax") || ($key eq "AR_tax")) {
 
 905           $form->{"${key}_$form->{acc_trans}{$key}->[$i-1]->{accno}"}  = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 906           $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
 
 908           if ($form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"} > 0) {
 
 909             $totaltax += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
 
 911             $totalwithholding += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
 
 912             $withholdingrate  += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
 
 915           $index                 = $form->{acc_trans}{$key}->[$i - 1]->{index};
 
 916           $form->{"tax_$index"}  = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} * -1 / $exchangerate, 2);
 
 917           $totaltax             += $form->{"tax_$index"};
 
 921           $form->{"${akey}_$k"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
 
 923           if ($akey eq 'amount') {
 
 925             $form->{"${akey}_$i"} *= -1;
 
 926             $totalamount          += $form->{"${akey}_$i"};
 
 927             $form->{taxrate}       = $form->{acc_trans}{$key}->[$i - 1]->{rate};
 
 929             $form->{"projectnumber_$k"}    = "$form->{acc_trans}{$key}->[$i-1]->{projectnumber}";
 
 930             $form->{"oldprojectnumber_$k"} = $form->{"projectnumber_$k"};
 
 931             $form->{"project_id_$k"}       = "$form->{acc_trans}{$key}->[$i-1]->{project_id}";
 
 932             $form->{"${key}_chart_id_$k"}  = $form->{acc_trans}{$key}->[$i-1]->{chart_id};
 
 933             $form->{"taxchart_$k"} = $form->{acc_trans}{$key}->[$i-1]->{id}    . "--" . $form->{acc_trans}{$key}->[$i-1]->{rate};
 
 940   $form->{paidaccounts} = 1            if not defined $form->{paidaccounts};
 
 942   if ($form->{taxincluded} && $form->{taxrate} && $totalamount) {
 
 943     # add tax to amounts and invtotal
 
 944     for $i (1 .. $form->{rowcount}) {
 
 945       $taxamount            = ($totaltax + $totalwithholding) * $form->{"amount_$i"} / $totalamount;
 
 946       $tax                  = $form->round_amount($taxamount, 2);
 
 947       $diff                += ($taxamount - $tax);
 
 948       $form->{"amount_$i"} += $form->{"tax_$i"};
 
 951     $form->{amount_1} += $form->round_amount($diff, 2);
 
 954   $taxamount        = $form->round_amount($taxamount, 2);
 
 955   $form->{invtotal} = $totalamount + $totaltax;
 
 957   $main::lxdebug->leave_sub();
 
 961   my ($self, $form, $myconfig, $id) = @_;
 
 962   $main::lxdebug->enter_sub();
 
 964   my $rc = SL::DB->client->with_transaction(\&_storno, $self, $form, $myconfig, $id);
 
 966   $::lxdebug->leave_sub;
 
 971   my ($self, $form, $myconfig, $id) = @_;
 
 973   my ($query, $new_id, $storno_row, $acc_trans_rows);
 
 974   my $dbh = SL::DB->client->dbh;
 
 976   $query = qq|SELECT nextval('glid')|;
 
 977   ($new_id) = selectrow_query($form, $dbh, $query);
 
 979   $query = qq|SELECT * FROM ap WHERE id = ?|;
 
 980   $storno_row = selectfirst_hashref_query($form, $dbh, $query, $id);
 
 982   $storno_row->{id}         = $new_id;
 
 983   $storno_row->{storno_id}  = $id;
 
 984   $storno_row->{storno}     = 't';
 
 985   $storno_row->{invnumber}  = 'Storno-' . $storno_row->{invnumber};
 
 986   $storno_row->{amount}    *= -1;
 
 987   $storno_row->{netamount} *= -1;
 
 988   $storno_row->{paid}       = $storno_row->{amount};
 
 990   delete @$storno_row{qw(itime mtime gldate)};
 
 992   $query = sprintf 'INSERT INTO ap (%s) VALUES (%s)', join(', ', keys %$storno_row), join(', ', map '?', values %$storno_row);
 
 993   do_query($form, $dbh, $query, (values %$storno_row));
 
 995   $query = qq|UPDATE ap SET paid = amount + paid, storno = 't' WHERE id = ?|;
 
 996   do_query($form, $dbh, $query, $id);
 
 998   $form->new_lastmtime('ap') if $id == $form->{id};
 
1000   # now copy acc_trans entries
 
1001   $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|;
 
1002   my $rowref = selectall_hashref_query($form, $dbh, $query, $id);
 
1004   # kill all entries containing payments, which are the last 2n rows, of which the last has link =~ /paid/
 
1005   while ($rowref->[-1]{link} =~ /paid/) {
 
1006     splice(@$rowref, -2);
 
1009   for my $row (@$rowref) {
 
1010     delete @$row{qw(itime mtime link acc_trans_id gldate)};
 
1011     $query = sprintf 'INSERT INTO acc_trans (%s) VALUES (%s)', join(', ', keys %$row), join(', ', map '?', values %$row);
 
1012     $row->{trans_id}   = $new_id;
 
1013     $row->{amount}    *= -1;
 
1014     do_query($form, $dbh, $query, (values %$row));
 
1017   map { IO->set_datepaid(table => 'ap', id => $_, dbh => $dbh) } ($id, $new_id);