Files
investbrain/app/Http/Requests/TransactionRequest.php
T

72 lines
2.4 KiB
PHP
Raw Normal View History

2025-01-24 22:45:28 -06:00
<?php
2025-01-28 17:33:54 -06:00
declare(strict_types=1);
2025-01-24 22:45:28 -06:00
namespace App\Http\Requests;
2025-01-27 20:04:03 -06:00
use App\Models\Portfolio;
use App\Rules\QuantityValidationRule;
2025-01-28 17:14:49 -06:00
use App\Rules\SymbolValidationRule;
2025-01-24 22:45:28 -06:00
2025-01-26 22:56:05 -06:00
class TransactionRequest extends FormRequest
2025-01-24 22:45:28 -06:00
{
protected function prepareForValidation(): void
{
$this->merge([
2025-01-28 17:14:49 -06:00
'portfolio' => Portfolio::find($this->requestOrModelValue('portfolio_id', 'transaction')),
]);
}
2025-01-24 22:45:28 -06:00
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
2025-01-28 17:14:49 -06:00
2025-01-26 22:56:05 -06:00
$rules = [
2025-01-27 23:03:33 -06:00
'portfolio_id' => ['required', 'exists:portfolios,id'],
2025-01-27 20:04:03 -06:00
'symbol' => ['required', 'string', new SymbolValidationRule],
'transaction_type' => ['required', 'string', 'in:BUY,SELL'],
2025-01-28 17:14:49 -06:00
'date' => ['required', 'date_format:Y-m-d', 'before_or_equal:'.now()->format('Y-m-d')],
2025-01-27 20:04:03 -06:00
'quantity' => [
2025-01-28 17:14:49 -06:00
'required',
'numeric',
'min:0',
2025-01-27 20:04:03 -06:00
new QuantityValidationRule(
$this->input('portfolio'),
2025-01-27 20:04:03 -06:00
$this->requestOrModelValue('symbol', 'transaction'),
$this->requestOrModelValue('transaction_type', 'transaction'),
$this->requestOrModelValue('date', 'transaction')
2025-01-28 17:14:49 -06:00
),
2025-01-27 20:04:03 -06:00
],
'cost_basis' => ['exclude_if:transaction_type,SELL', 'min:0', 'numeric'],
'sale_price' => ['exclude_if:transaction_type,BUY', 'min:0', 'numeric'],
2025-01-24 22:45:28 -06:00
];
2025-01-26 22:56:05 -06:00
2025-01-28 17:14:49 -06:00
if (! is_null($this->transaction)) {
2025-01-27 23:03:33 -06:00
$rules['portfolio_id'][0] = 'sometimes';
2025-01-27 20:04:03 -06:00
$rules['symbol'][0] = 'sometimes';
$rules['transaction_type'][0] = 'sometimes';
$rules['date'][0] = 'sometimes';
$rules['quantity'][0] = 'sometimes';
if (
$this->requestOrModelValue('transaction_type', 'transaction') == 'SELL'
&& $this->requestOrModelValue('sale_price', 'transaction') == null
) {
$rules['sale_price'][0] = 'required';
} elseif (
$this->requestOrModelValue('transaction_type', 'transaction') == 'BUY'
&& $this->requestOrModelValue('cost_basis', 'transaction') == null
) {
$rules['cost_basis'][0] = 'required';
}
2025-01-28 17:14:49 -06:00
}
2025-01-26 22:56:05 -06:00
return $rules;
2025-01-24 22:45:28 -06:00
}
}