diff --git a/app/Rules/QuantityValidationRule.php b/app/Rules/QuantityValidationRule.php index ffee127..91bebe2 100644 --- a/app/Rules/QuantityValidationRule.php +++ b/app/Rules/QuantityValidationRule.php @@ -15,11 +15,13 @@ class QuantityValidationRule implements ValidationRule public function __construct( protected Portfolio $portfolio, protected string $symbol, - protected string $transactionType + protected string $transactionType, + protected string $date ) { $this->portfolio = $portfolio; - $this->symbol = $symbol; + $this->symbol = $symbol; $this->transactionType = $transactionType; + $this->date = $date; } /** @@ -33,9 +35,21 @@ class QuantityValidationRule implements ValidationRule public function validate(string $attribute, mixed $value, \Closure $fail): void { if ($this->transactionType == 'SELL') { - $holding = $this->portfolio->holdings()->symbol($this->symbol)->first(); - $maxQuantity = $holding ? $holding->quantity : 0; - + + $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; + if ($value > $maxQuantity) { $fail(__('The quantity must not be greater than the available quantity.')); } diff --git a/resources/views/livewire/manage-transaction-form.blade.php b/resources/views/livewire/manage-transaction-form.blade.php index 8493ee3..95586bd 100644 --- a/resources/views/livewire/manage-transaction-form.blade.php +++ b/resources/views/livewire/manage-transaction-form.blade.php @@ -40,7 +40,7 @@ new class extends Component { 'required', 'numeric', 'min:0', - new QuantityValidationRule($this->portfolio, $this->symbol, $this->transaction_type) + new QuantityValidationRule($this->portfolio, $this->symbol, $this->transaction_type, $this->date) ], 'cost_basis' => 'exclude_if:transaction_type,SELL|min:0|numeric', 'sale_price' => 'exclude_if:transaction_type,BUY|min:0|numeric',