Files
investbrain/app/Rules/QuantityValidationRule.php
T

62 lines
1.7 KiB
PHP
Raw Normal View History

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;
use Illuminate\Contracts\Validation\ValidationRule;
2025-01-28 17:46:59 -06: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,
protected string|Carbon|null $date
2024-08-31 22:05:47 -05:00
) {
$this->portfolio = $portfolio;
2025-01-28 17:14:49 -06:00
$this->symbol = $symbol;
2024-08-31 22:05:47 -05:00
$this->transactionType = $transactionType;
2024-09-06 23:15:52 -05:00
$this->date = $date;
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
$purchase_qty = $this->portfolio->transactions()
2025-01-28 17:14:49 -06:00
->symbol($this->symbol)
->buy()
->beforeDate($this->date)
->sum('quantity');
2024-09-06 23:15:52 -05:00
$sales_qty = $this->portfolio->transactions()
2025-01-28 17:14:49 -06:00
->symbol($this->symbol)
->sell()
->beforeDate($this->date)
->sum('quantity');
2024-09-06 23:15:52 -05:00
$maxQuantity = $purchase_qty - $sales_qty;
if (round($value, 3) > round($maxQuantity, 3)) {
2024-08-31 22:05:47 -05:00
$fail(__('The quantity must not be greater than the available quantity.'));
}
}
}
}