From e14a248f24d86e03d338164a566397c120af1a01 Mon Sep 17 00:00:00 2001 From: Darko Gjorgjijoski Date: Thu, 8 Feb 2024 03:09:56 +0100 Subject: [PATCH] Fix: Status set incorrectly after updating invoice Issue: https://github.com/crater-invoice/crater/issues/955, #23 --- app/Models/Invoice.php | 56 ++++++++++++++++++++++++++++++++---------- 1 file changed, 43 insertions(+), 13 deletions(-) diff --git a/app/Models/Invoice.php b/app/Models/Invoice.php index a06d50e3..01a788a4 100644 --- a/app/Models/Invoice.php +++ b/app/Models/Invoice.php @@ -401,7 +401,10 @@ class Invoice extends Model implements HasMedia $data['base_due_amount'] = $data['due_amount'] * $data['exchange_rate']; $data['customer_sequence_number'] = $serial->nextCustomerSequenceNumber; - $this->changeInvoiceStatus($data['due_amount']); + $statusData = $this->getInvoiceStatusByAmount($data['due_amount']); + if(!empty($statusData)) { + $data = array_merge($data, $statusData); + } $this->update($data); @@ -691,27 +694,54 @@ class Invoice extends Model implements HasMedia $this->changeInvoiceStatus($this->due_amount); } - public function changeInvoiceStatus($amount) + /** + * Set the invoice status from amount. + * @param $amount + * + * @return array + */ + public function getInvoiceStatusByAmount($amount) { if ($amount < 0) { - return [ - 'error' => 'invalid_amount', - ]; + return []; } if ($amount == 0) { - $this->status = Invoice::STATUS_COMPLETED; - $this->paid_status = Invoice::STATUS_PAID; - $this->overdue = false; + $data = [ + 'status' => Invoice::STATUS_COMPLETED, + 'paid_status' => Invoice::STATUS_PAID, + 'overdue' => false, + ]; } elseif ($amount == $this->total) { - $this->status = $this->getPreviousStatus(); - $this->paid_status = Invoice::STATUS_UNPAID; + $data = [ + 'status' => $this->getPreviousStatus(), + 'paid_status' => Invoice::STATUS_UNPAID, + ]; } else { - $this->status = $this->getPreviousStatus(); - $this->paid_status = Invoice::STATUS_PARTIALLY_PAID; + $data = [ + 'status' => $this->getPreviousStatus(), + 'paid_status' => Invoice::STATUS_PARTIALLY_PAID, + ]; } - $this->save(); + return $data; + } + + /** + * Changes the invoice status right away + * @param $amount + * + * @return string[]|void + */ + public function changeInvoiceStatus($amount) + { + $status = $this->getInvoiceStatusByAmount($amount); + if(!empty($status)) { + foreach($status as $key => $value) { + $this->setAttribute($key, $value); + } + $this->save(); + } } public static function deleteInvoices($ids)