Add credit to paymentables on invoice reversal

This commit is contained in:
David Bomba 2020-09-22 13:09:42 +10:00
parent 8c1174b20b
commit 8d3154a149
2 changed files with 20 additions and 35 deletions

View File

@ -56,7 +56,8 @@ class AppServiceProvider extends ServiceProvider
public function boot()
{
Relation::morphMap([
'invoices' => \App\Models\Invoice::class,
'invoices' => \App\Models\Invoice::class,
'credits' => \App\Models\Credit::class,
'proposals' => \App\Models\Proposal::class,
]);

View File

@ -55,7 +55,7 @@ class HandleReversal extends AbstractService
$total_paid = $this->invoice->amount - $this->invoice->balance;
/*Adjust payment applied and the paymentables to the correct amount */
$paymentables = Paymentable::wherePaymentableType(Invoice::class)
$paymentables = Paymentable::wherePaymentableType('invoices')
->wherePaymentableId($this->invoice->id)
->get();
@ -95,6 +95,23 @@ class HandleReversal extends AbstractService
$credit->service()->markSent()->save();
}
/*If there is a payment linked, then the credit needs to be linked back to that payment in case of refund*/
if($paymentables->count() > 0){
$payment = $paymentables->first()->payment;
$payment->credits()->save($credit);
$paymentable_credit = $payment->credits()
->wherePaymentableType('credits')
->wherePaymentableId($credit->id)
->first();
//harvest the credit record and add in the amount for the credit.
$paymentable_credit->pivot->amount = $total_paid;
$paymentable_credit->pivot->save();
}
/* Set invoice balance to 0 */
if ($this->invoice->balance != 0) {
$this->invoice->ledger()->updateInvoiceBalance($balance_remaining * -1, $notes)->save();
@ -119,37 +136,4 @@ class HandleReversal extends AbstractService
//create a ledger row for this with the resulting Credit ( also include an explanation in the notes section )
}
// public function run2()
// {
// /* Check again!! */
// if (!$this->invoice->invoiceReversable($this->invoice)) {
// return $this->invoice;
// }
// if($this->invoice->status_id == Invoice::STATUS_CANCELLED)
// $this->invoice = $this->invoice->service()->reverseCancellation()->save();
// //$balance_remaining = $this->invoice->balance;
// //$total_paid = $this->invoice->amount - $this->invoice->balance;
// /*Adjust payment applied and the paymentables to the correct amount */
// $paymentables = Paymentable::wherePaymentableType(Invoice::class)
// ->wherePaymentableId($this->invoice->id)
// ->get();
// $total_paid = 0;
// $paymentables->each(function ($paymentable) use ($total_paid) {
// $reversable_amount = $paymentable->amount - $paymentable->refunded;
// $total_paid -= $reversable_amount;
// $paymentable->amount = $paymentable->refunded;
// $paymentable->save();
// });
// //Unwinding any payments made to this invoice
// }
}