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

75 lines
2.5 KiB
PHP

<?php
namespace App\Http\Requests\App;
use App\Models\UnitOfMeasurement;
use Illuminate\Foundation\Http\FormRequest;
class UnitOfMeasurementUpdateRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
public function rules(): array
{
$unitId = $this->route('unit')?->id ?? $this->route('unit');
return [
'name' => ['sometimes', 'string', 'max:50', 'unique:units_of_measurement,name,' . $unitId],
'abbreviation' => ['sometimes', 'string', 'max:10', 'unique:units_of_measurement,abbreviation,' . $unitId],
'allows_decimals' => ['sometimes', 'boolean'],
'is_active' => ['sometimes', 'boolean'],
];
}
public function messages(): array
{
return [
'name.unique' => 'Ya existe una unidad con este nombre.',
'name.max' => 'El nombre no debe exceder los 50 caracteres.',
'abbreviation.unique' => 'Ya existe una unidad con esta abreviatura.',
'abbreviation.max' => 'La abreviatura no debe exceder los 10 caracteres.',
'allows_decimals.boolean' => 'El campo permite decimales debe ser verdadero o falso.',
'is_active.boolean' => 'El campo activo debe ser verdadero o falso.',
];
}
/**
* Validación adicional: no permitir cambiar allows_decimals si hay productos con seriales
*/
public function withValidator($validator)
{
$validator->after(function ($validator) {
$unit = $this->route('unit');
if ($unit && !($unit instanceof UnitOfMeasurement)) {
$unit = UnitOfMeasurement::find($unit);
}
if (!$unit) {
return;
}
// Si se intenta cambiar allows_decimals
if ($this->has('allows_decimals') && (bool) $this->allows_decimals !== (bool) $unit->allows_decimals) {
// Verificar si hay productos con track_serials usando esta unidad
$hasProductsWithSerials = $unit->inventories()
->where('track_serials', true)
->exists();
if ($hasProductsWithSerials) {
$validator->errors()->add(
'allows_decimals',
'No se puede cambiar el tipo de unidad (decimal/entero) porque hay productos con números de serie que la utilizan'
);
}
}
});
}
}