pdv.backend/app/Http/Requests/App/BundleUpdateRequest.php

74 lines
2.2 KiB
PHP

<?php
namespace App\Http\Requests\App;
use Illuminate\Foundation\Http\FormRequest;
class BundleUpdateRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*/
public function rules(): array
{
$bundleId = $this->route('bundle')?->id;
return [
'name' => ['nullable', 'string', 'max:255'],
'sku' => ['nullable', 'string', 'max:50', 'unique:bundles,sku,' . $bundleId],
'barcode' => ['nullable', 'string', 'unique:bundles,barcode,' . $bundleId],
// Componentes del kit (opcional en update)
'items' => ['nullable', 'array', 'min:2'],
'items.*.inventory_id' => ['required_with:items', 'exists:inventories,id'],
'items.*.quantity' => ['required_with:items', 'integer', 'min:1'],
// Precio
'retail_price' => ['nullable', 'numeric', 'min:0'],
'tax' => ['nullable', 'numeric', 'min:0'],
'recalculate_price' => ['nullable', 'boolean'],
];
}
/**
* Custom validation messages
*/
public function messages(): array
{
return [
'sku.unique' => 'Este SKU ya está en uso.',
'items.min' => 'Un bundle debe tener al menos 2 productos.',
'items.*.inventory_id.exists' => 'Uno de los productos no existe.',
'items.*.quantity.min' => 'La cantidad debe ser al menos 1.',
];
}
/**
* Validación adicional
*/
public function withValidator($validator)
{
$validator->after(function ($validator) {
// Validar que no haya productos duplicados (si se proporcionan items)
if ($this->has('items')) {
$inventoryIds = collect($this->items)->pluck('inventory_id')->toArray();
if (count($inventoryIds) !== count(array_unique($inventoryIds))) {
$validator->errors()->add(
'items',
'No se pueden agregar productos duplicados al bundle.'
);
}
}
});
}
}