diff --git a/app/Rules/QuantityValidationRule.php b/app/Rules/QuantityValidationRule.php new file mode 100644 index 0000000..ffee127 --- /dev/null +++ b/app/Rules/QuantityValidationRule.php @@ -0,0 +1,44 @@ +portfolio = $portfolio; + $this->symbol = $symbol; + $this->transactionType = $transactionType; + } + + /** + * 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') { + $holding = $this->portfolio->holdings()->symbol($this->symbol)->first(); + $maxQuantity = $holding ? $holding->quantity : 0; + + if ($value > $maxQuantity) { + $fail(__('The quantity must not be greater than the available quantity.')); + } + } + } +} diff --git a/lang/en.json b/lang/en.json index f462886..2ea0f49 100644 --- a/lang/en.json +++ b/lang/en.json @@ -134,6 +134,7 @@ "Symbol": "Symbol", "Quantity": "Quantity", "Quantity Owned": "Quantity Owned", + "The quantity must not be greater than the available quantity.": "The quantity must not be greater than the available quantity.", "Average Cost Basis": "Average Cost Basis", "Market Value": "Market Value", "52 week": "52 week", diff --git a/lang/es.json b/lang/es.json index 60efdbe..a11c27d 100644 --- a/lang/es.json +++ b/lang/es.json @@ -134,6 +134,7 @@ "Symbol": "Símbolo", "Quantity": "Cantidad", "Quantity Owned": "Cantidad de propiedad", + "The quantity must not be greater than the available quantity.": "La cantidad no debe ser mayor que la cantidad disponible.", "Average Cost Basis": "Costo Promedio", "Market Value": "Valor de Mercado", "52 week": "52 semanas", diff --git a/resources/views/livewire/manage-transaction-form.blade.php b/resources/views/livewire/manage-transaction-form.blade.php index f160304..8493ee3 100644 --- a/resources/views/livewire/manage-transaction-form.blade.php +++ b/resources/views/livewire/manage-transaction-form.blade.php @@ -3,10 +3,12 @@ use App\Models\Transaction; use App\Models\Portfolio; use App\Rules\SymbolValidationRule; +use App\Rules\QuantityValidationRule; use Illuminate\Support\Collection; use Livewire\Attributes\{Computed}; use Livewire\Volt\Component; use Mary\Traits\Toast; +use Illuminate\Validation\Rule; new class extends Component { use Toast; @@ -34,7 +36,12 @@ new class extends Component { 'transaction_type' => 'required|string|in:BUY,SELL', 'portfolio_id' => 'required|exists:portfolios,id', 'date' => 'required|date_format:Y-m-d', - 'quantity' => 'required|min:0|numeric', + 'quantity' => [ + 'required', + 'numeric', + 'min:0', + new QuantityValidationRule($this->portfolio, $this->symbol, $this->transaction_type) + ], 'cost_basis' => 'exclude_if:transaction_type,SELL|min:0|numeric', 'sale_price' => 'exclude_if:transaction_type,BUY|min:0|numeric', ];