2021-04-28 03:18:27 +02:00
|
|
|
<?php
|
|
|
|
/**
|
|
|
|
* Invoice Ninja (https://invoiceninja.com).
|
|
|
|
*
|
|
|
|
* @link https://github.com/invoiceninja/invoiceninja source repository
|
|
|
|
*
|
2023-01-28 23:21:40 +01:00
|
|
|
* @copyright Copyright (c) 2023. Invoice Ninja LLC (https://invoiceninja.com)
|
2021-04-28 03:18:27 +02:00
|
|
|
*
|
2021-06-16 08:58:16 +02:00
|
|
|
* @license https://www.elastic.co/licensing/elastic-license
|
2021-04-28 03:18:27 +02:00
|
|
|
*/
|
|
|
|
|
|
|
|
namespace App\Http\ValidationRules\Invoice;
|
|
|
|
|
|
|
|
use App\Models\Invoice;
|
|
|
|
use Illuminate\Contracts\Validation\Rule;
|
|
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Class LockedInvoiceRule.
|
|
|
|
*/
|
|
|
|
class InvoiceBalanceSanity implements Rule
|
|
|
|
{
|
|
|
|
public $invoice;
|
|
|
|
|
|
|
|
public $input;
|
|
|
|
|
|
|
|
private $message;
|
|
|
|
|
|
|
|
public function __construct(Invoice $invoice, $input)
|
|
|
|
{
|
|
|
|
$this->invoice = $invoice;
|
|
|
|
$this->input = $input;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param string $attribute
|
|
|
|
* @param mixed $value
|
|
|
|
* @return bool
|
|
|
|
*/
|
|
|
|
public function passes($attribute, $value)
|
|
|
|
{
|
|
|
|
return $this->checkIfInvoiceBalanceIsSane(); //if it exists, return false!
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @return string
|
|
|
|
*/
|
|
|
|
public function message()
|
|
|
|
{
|
|
|
|
return $this->message;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @return bool
|
|
|
|
*/
|
|
|
|
private function checkIfInvoiceBalanceIsSane() : bool
|
|
|
|
{
|
2021-05-26 09:04:29 +02:00
|
|
|
DB::connection(config('database.default'))->beginTransaction();
|
2021-04-28 03:18:27 +02:00
|
|
|
|
2021-09-16 00:43:14 +02:00
|
|
|
$this->invoice = Invoice::on(config('database.default'))->withTrashed()->find($this->invoice->id);
|
2021-05-26 09:04:29 +02:00
|
|
|
$this->invoice->line_items = $this->input['line_items'];
|
|
|
|
$temp_invoice = $this->invoice->calc()->getTempEntity();
|
2022-06-21 11:57:17 +02:00
|
|
|
|
2021-05-26 09:04:29 +02:00
|
|
|
DB::connection(config('database.default'))->rollBack();
|
2021-04-28 03:18:27 +02:00
|
|
|
|
2022-06-21 11:57:17 +02:00
|
|
|
if ($temp_invoice->balance < 0) {
|
2021-04-28 03:18:27 +02:00
|
|
|
$this->message = 'Invoice balance cannot go negative';
|
2022-06-21 11:57:17 +02:00
|
|
|
|
2021-04-28 03:18:27 +02:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2022-06-21 11:57:17 +02:00
|
|
|
return true;
|
2021-04-28 03:18:27 +02:00
|
|
|
}
|
|
|
|
}
|