2024-08-31 22:05:47 -05:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace App\Rules;
|
|
|
|
|
|
|
|
|
|
use App\Models\Portfolio;
|
|
|
|
|
use Illuminate\Contracts\Validation\ValidationRule;
|
|
|
|
|
|
|
|
|
|
class QuantityValidationRule implements ValidationRule
|
|
|
|
|
{
|
|
|
|
|
/**
|
|
|
|
|
* Create a new rule instance.
|
|
|
|
|
*
|
|
|
|
|
* @return void
|
|
|
|
|
*/
|
|
|
|
|
public function __construct(
|
|
|
|
|
protected Portfolio $portfolio,
|
|
|
|
|
protected string $symbol,
|
2024-09-06 23:15:52 -05:00
|
|
|
protected string $transactionType,
|
|
|
|
|
protected string $date
|
2024-08-31 22:05:47 -05:00
|
|
|
) {
|
|
|
|
|
$this->portfolio = $portfolio;
|
2024-09-06 23:15:52 -05: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.
|
|
|
|
|
*
|
|
|
|
|
* @param string $attribute
|
|
|
|
|
* @param mixed $value
|
|
|
|
|
* @param \Closure $fail
|
|
|
|
|
* @return void
|
|
|
|
|
*/
|
|
|
|
|
public function validate(string $attribute, mixed $value, \Closure $fail): void
|
|
|
|
|
{
|
|
|
|
|
if ($this->transactionType == 'SELL') {
|
2024-09-06 23:15:52 -05:00
|
|
|
|
|
|
|
|
$purchase_qty = $this->portfolio->transactions()
|
|
|
|
|
->symbol($this->symbol)
|
|
|
|
|
->buy()
|
|
|
|
|
->beforeDate($this->date)
|
|
|
|
|
->sum('quantity');
|
|
|
|
|
|
|
|
|
|
$sales_qty = $this->portfolio->transactions()
|
|
|
|
|
->symbol($this->symbol)
|
|
|
|
|
->sell()
|
|
|
|
|
->beforeDate($this->date)
|
|
|
|
|
->sum('quantity');
|
|
|
|
|
|
|
|
|
|
$maxQuantity = $purchase_qty - $sales_qty;
|
|
|
|
|
|
2024-08-31 22:05:47 -05:00
|
|
|
if ($value > $maxQuantity) {
|
|
|
|
|
$fail(__('The quantity must not be greater than the available quantity.'));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|