2024-08-31 22:05:47 -05:00
|
|
|
<?php
|
|
|
|
|
|
2025-01-28 17:33:54 -06:00
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
2024-08-31 22:05:47 -05:00
|
|
|
namespace App\Rules;
|
|
|
|
|
|
|
|
|
|
use App\Models\Portfolio;
|
2025-04-09 19:25:15 -05:00
|
|
|
use App\Models\Transaction;
|
|
|
|
|
use Illuminate\Contracts\Validation\ValidationRule;
|
2025-08-29 15:47:18 -05:00
|
|
|
use Illuminate\Support\Carbon;
|
2024-08-31 22:05:47 -05:00
|
|
|
|
|
|
|
|
class QuantityValidationRule implements ValidationRule
|
|
|
|
|
{
|
|
|
|
|
/**
|
|
|
|
|
* Create a new rule instance.
|
|
|
|
|
*
|
|
|
|
|
* @return void
|
|
|
|
|
*/
|
|
|
|
|
public function __construct(
|
2025-01-28 17:14:49 -06:00
|
|
|
protected ?Portfolio $portfolio,
|
|
|
|
|
protected ?string $symbol,
|
2025-01-27 20:04:03 -06:00
|
|
|
protected ?string $transactionType,
|
2025-08-29 15:47:18 -05:00
|
|
|
protected string|Carbon|null $date,
|
|
|
|
|
protected ?Transaction $transaction
|
|
|
|
|
) {}
|
2024-08-31 22:05:47 -05:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Validate the attribute.
|
|
|
|
|
*/
|
|
|
|
|
public function validate(string $attribute, mixed $value, \Closure $fail): void
|
|
|
|
|
{
|
2025-01-27 20:04:03 -06:00
|
|
|
if (is_null($this->portfolio) || is_null($this->symbol) || is_null($this->transactionType) || is_null($this->date)) {
|
|
|
|
|
//
|
|
|
|
|
$fail(__('The quantity must not be greater than the available quantity.'));
|
|
|
|
|
}
|
|
|
|
|
|
2024-08-31 22:05:47 -05:00
|
|
|
if ($this->transactionType == 'SELL') {
|
2024-09-06 23:15:52 -05:00
|
|
|
|
2025-04-09 19:25:15 -05:00
|
|
|
$purchase_qty = (float) $this->portfolio->transactions()
|
2025-01-28 17:14:49 -06:00
|
|
|
->symbol($this->symbol)
|
|
|
|
|
->buy()
|
2025-04-09 19:25:15 -05:00
|
|
|
->whereDate('date', '<', $this->date)
|
2025-01-28 17:14:49 -06:00
|
|
|
->sum('quantity');
|
2024-09-06 23:15:52 -05:00
|
|
|
|
2025-04-09 19:25:15 -05:00
|
|
|
$sales_qty = (float) $this->portfolio->transactions()
|
2025-08-29 15:47:18 -05:00
|
|
|
->where('id', '!=', $this->transaction?->id)
|
2025-01-28 17:14:49 -06:00
|
|
|
->symbol($this->symbol)
|
|
|
|
|
->sell()
|
2025-04-09 19:25:15 -05:00
|
|
|
->whereDate('date', '<', $this->date)
|
2025-01-28 17:14:49 -06:00
|
|
|
->sum('quantity');
|
|
|
|
|
|
2024-09-06 23:15:52 -05:00
|
|
|
$maxQuantity = $purchase_qty - $sales_qty;
|
|
|
|
|
|
2025-04-09 19:25:15 -05:00
|
|
|
if (round($value, 4) > round($maxQuantity, 4)) {
|
2024-08-31 22:05:47 -05:00
|
|
|
$fail(__('The quantity must not be greater than the available quantity.'));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|