Files
mgap/app/Http/Controllers/PerfilGestionController.php
T
2026-09-18 23:35:22 -03:00

343 lines
14 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Models\Perfil;
use App\Models\Permiso;
use App\Models\Recurso;
use App\Models\Rol;
use App\Support\HistoricalPeriod;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Inertia\Inertia;
class PerfilGestionController extends Controller
{
public function show(Perfil $perfil)
{
return Inertia::render('Perfiles/Gestionar', [
'perfil' => $perfil->load(['roles', 'permisos', 'recursos.tipoRecurso']),
'roles' => Rol::orderBy('nombre')->get(),
'permisos' => Permiso::orderBy('nombre')->get(),
'recursos' => Recurso::with('tipoRecurso')->orderBy('nombre')->get(),
]);
}
public function updateField(Request $request, Perfil $perfil)
{
$validated = $request->validate([
'field' => ['required', Rule::in(['nombre', 'descripcion', 'fecha_inicio', 'fecha_fin'])],
'value' => ['nullable'],
]);
$rules = match ($validated['field']) {
'nombre' => ['required', 'string', 'max:35'],
'descripcion' => ['nullable', 'string', 'max:185'],
'fecha_inicio', 'fecha_fin' => ['nullable', 'date'],
};
$value = validator(
['value' => $validated['value']],
['value' => $rules],
)->validate()['value'] ?? null;
if (in_array($validated['field'], ['fecha_inicio', 'fecha_fin'], true)) {
validator([
'fecha_inicio' => $validated['field'] === 'fecha_inicio' ? $value : $perfil->fecha_inicio,
'fecha_fin' => $validated['field'] === 'fecha_fin' ? $value : $perfil->fecha_fin,
], [
'fecha_inicio' => ['nullable', 'date'],
'fecha_fin' => ['nullable', 'date', 'after_or_equal:fecha_inicio'],
])->validate();
}
$perfil->update([$validated['field'] => $value]);
return back()->with('success', 'Dato actualizado correctamente.');
}
public function attachRol(Request $request, Perfil $perfil)
{
$validated = $request->validate([
'rol_id' => ['required', 'exists:roles,id'],
'fecha_inicio' => ['required', 'date'],
'fecha_fin' => ['nullable', 'date', 'after_or_equal:fecha_inicio'],
]);
$validated['fecha_fin'] = HistoricalPeriod::inclusiveEnd($validated['fecha_fin'] ?? null);
$inicio = Carbon::parse($validated['fecha_inicio']);
$fin = $validated['fecha_fin'] ? Carbon::parse($validated['fecha_fin']) : null;
$otrosRegistros = DB::table('perfil_rol')->where('perfil_id', $perfil->id)->where('rol_id', $validated['rol_id'])->get();
foreach ($otrosRegistros as $otro) {
$otroInicio = Carbon::parse($otro->fecha_inicio);
$otroFin = $otro->fecha_fin ? Carbon::parse($otro->fecha_fin) : null;
$empiezaAntes = $otroFin === null ? true : $inicio->lte($otroFin);
$terminaDespues = $fin === null ? true : $fin->gte($otroInicio);
if ($empiezaAntes && $terminaDespues) {
throw \Illuminate\Validation\ValidationException::withMessages([
'fecha_inicio' => 'Las fechas chocan con otro registro existente.',
]);
}
}
$perfil->roles()->attach($validated['rol_id'], [
'fecha_inicio' => $validated['fecha_inicio'],
'fecha_fin' => $validated['fecha_fin'] ?? null,
'created_at' => now(),
'updated_at' => now(),
]);
return back()->with('success', 'Rol asociado correctamente.');
}
public function detachRol(Perfil $perfil, $pivotId)
{
DB::table('perfil_rol')->where('perfil_id', $perfil->id)->where('id', $pivotId)->delete();
return back()->with('success', 'Asignación de rol eliminada correctamente.');
}
public function updateRolPivot(Request $request, Perfil $perfil, $pivotId)
{
$validated = $request->validate([
'fecha_inicio' => ['required', 'date'],
'fecha_fin' => ['nullable', 'date', 'after_or_equal:fecha_inicio'],
], ['fecha_fin.after_or_equal' => 'La fecha de fin no puede ser menor a la de inicio.']);
$validated['fecha_fin'] = HistoricalPeriod::inclusiveEnd($validated['fecha_fin'] ?? null);
$registroActual = DB::table('perfil_rol')
->where('perfil_id', $perfil->id)
->where('id', $pivotId)
->firstOrFail();
$inicio = Carbon::parse($validated['fecha_inicio']);
$fin = $validated['fecha_fin'] ? Carbon::parse($validated['fecha_fin']) : null;
$otrosRegistros = DB::table('perfil_rol')->where('perfil_id', $perfil->id)->where('rol_id', $registroActual->rol_id)->where('id', '!=', $pivotId)->get();
foreach ($otrosRegistros as $otro) {
$otroInicio = Carbon::parse($otro->fecha_inicio);
$otroFin = $otro->fecha_fin ? Carbon::parse($otro->fecha_fin) : null;
$empiezaAntes = $otroFin === null ? true : $inicio->lte($otroFin);
$terminaDespues = $fin === null ? true : $fin->gte($otroInicio);
if ($empiezaAntes && $terminaDespues) {
throw \Illuminate\Validation\ValidationException::withMessages([
'fecha_inicio' => 'Las fechas chocan con otro registro existente.',
]);
}
}
DB::table('perfil_rol')
->where('perfil_id', $perfil->id)
->where('id', $pivotId)
->update([
'fecha_inicio' => $validated['fecha_inicio'],
'fecha_fin' => $validated['fecha_fin'],
'updated_at' => now(),
]);
return back()->with('success', 'Asignación actualizada correctamente.');
}
public function attachPermiso(Request $request, Perfil $perfil)
{
$validated = $request->validate([
'permiso_id' => ['required', 'exists:permisos,id'],
'fecha_inicio' => ['required', 'date'],
'fecha_fin' => ['nullable', 'date', 'after_or_equal:fecha_inicio'],
]);
$inicio = Carbon::parse($validated['fecha_inicio']);
$fin = $validated['fecha_fin'] ? Carbon::parse($validated['fecha_fin']) : null;
$otrosRegistros = DB::table('permiso_perfil')->where('perfil_id', $perfil->id)->where('permiso_id', $validated['permiso_id'])->get();
foreach ($otrosRegistros as $otro) {
$otroInicio = Carbon::parse($otro->fecha_inicio);
$otroFin = $otro->fecha_fin ? Carbon::parse($otro->fecha_fin) : null;
$empiezaAntes = $otroFin === null ? true : $inicio->lte($otroFin);
$terminaDespues = $fin === null ? true : $fin->gte($otroInicio);
if ($empiezaAntes && $terminaDespues) {
throw \Illuminate\Validation\ValidationException::withMessages([
'fecha_inicio' => 'Las fechas chocan con otro registro existente.',
]);
}
}
$perfil->permisos()->attach($validated['permiso_id'], [
'fecha_inicio' => $validated['fecha_inicio'],
'fecha_fin' => $validated['fecha_fin'] ?? null,
'created_at' => now(),
'updated_at' => now(),
]);
return back()->with('success', 'Permiso asociado correctamente.');
}
public function detachPermiso(Perfil $perfil, $pivotId)
{
DB::table('permiso_perfil')->where('perfil_id', $perfil->id)->where('id', $pivotId)->delete();
return back()->with('success', 'Asignación de permiso eliminada correctamente.');
}
public function updatePermisoPivot(Request $request, Perfil $perfil, $pivotId)
{
$validated = $request->validate([
'fecha_inicio' => ['required', 'date'],
'fecha_fin' => ['nullable', 'date', 'after_or_equal:fecha_inicio'],
], ['fecha_fin.after_or_equal' => 'La fecha de fin no puede ser menor a la de inicio.']);
$registroActual = DB::table('permiso_perfil')
->where('perfil_id', $perfil->id)
->where('id', $pivotId)
->firstOrFail();
$inicio = Carbon::parse($validated['fecha_inicio']);
$fin = $validated['fecha_fin'] ? Carbon::parse($validated['fecha_fin']) : null;
$otrosRegistros = DB::table('permiso_perfil')->where('perfil_id', $perfil->id)->where('permiso_id', $registroActual->permiso_id)->where('id', '!=', $pivotId)->get();
foreach ($otrosRegistros as $otro) {
$otroInicio = Carbon::parse($otro->fecha_inicio);
$otroFin = $otro->fecha_fin ? Carbon::parse($otro->fecha_fin) : null;
$empiezaAntes = $otroFin === null ? true : $inicio->lte($otroFin);
$terminaDespues = $fin === null ? true : $fin->gte($otroInicio);
if ($empiezaAntes && $terminaDespues) {
throw \Illuminate\Validation\ValidationException::withMessages([
'fecha_inicio' => 'Las fechas chocan con otro registro existente.',
]);
}
}
DB::table('permiso_perfil')
->where('perfil_id', $perfil->id)
->where('id', $pivotId)
->update([
'fecha_inicio' => $validated['fecha_inicio'],
'fecha_fin' => $validated['fecha_fin'],
'updated_at' => now(),
]);
return back()->with('success', 'Asignación actualizada correctamente.');
}
public function attachRecurso(Request $request, Perfil $perfil)
{
$validated = $this->validateRecursoPivot($request, true);
$validated['fecha_fin'] = HistoricalPeriod::inclusiveEnd($validated['fecha_fin'] ?? null);
DB::transaction(function () use ($perfil, $validated): void {
Perfil::query()->whereKey($perfil->id)->lockForUpdate()->firstOrFail();
$this->ensureNoRecursoOverlap(
$perfil,
(int) $validated['recurso_id'],
$validated['fecha_inicio'],
$validated['fecha_fin'] ?? null,
);
$perfil->recursos()->attach($validated['recurso_id'], [
'evidencia' => $validated['evidencia'] ?? null,
'fecha_inicio' => $validated['fecha_inicio'],
'fecha_fin' => $validated['fecha_fin'] ?? null,
'fecha_revision' => $validated['fecha_revision'] ?? null,
'fecha_proxima_revision' => $validated['fecha_proxima_revision'] ?? null,
]);
});
return back()->with('success', 'Recurso asociado correctamente.');
}
public function updateRecursoPivot(Request $request, Perfil $perfil, int $pivotId)
{
$validated = $this->validateRecursoPivot($request);
$validated['fecha_fin'] = HistoricalPeriod::inclusiveEnd($validated['fecha_fin'] ?? null);
DB::transaction(function () use ($perfil, $pivotId, $validated): void {
Perfil::query()->whereKey($perfil->id)->lockForUpdate()->firstOrFail();
$pivot = DB::table('perfil_recurso')
->where('perfil_id', $perfil->id)
->where('id', $pivotId)
->firstOrFail();
$this->ensureNoRecursoOverlap(
$perfil,
(int) $pivot->recurso_id,
$validated['fecha_inicio'],
$validated['fecha_fin'] ?? null,
$pivotId,
);
DB::table('perfil_recurso')
->where('perfil_id', $perfil->id)
->where('id', $pivotId)
->update([...$validated, 'updated_at' => now()]);
});
return back()->with('success', 'Asignación de recurso actualizada correctamente.');
}
public function detachRecurso(Perfil $perfil, int $pivotId)
{
DB::table('perfil_recurso')->where('perfil_id', $perfil->id)->where('id', $pivotId)->delete();
return back()->with('success', 'Asignación de recurso eliminada correctamente.');
}
private function validateRecursoPivot(Request $request, bool $requiresResource = false): array
{
$rules = [
'evidencia' => ['nullable', 'string'],
'fecha_inicio' => ['required', 'date'],
'fecha_fin' => ['nullable', 'date', 'after_or_equal:fecha_inicio'],
'fecha_revision' => ['nullable', 'date', 'after_or_equal:fecha_inicio'],
'fecha_proxima_revision' => ['nullable', 'date', 'after_or_equal:fecha_revision'],
];
if ($requiresResource) {
$rules['recurso_id'] = ['required', 'integer', 'exists:recursos,id'];
}
return $request->validate($rules);
}
private function ensureNoRecursoOverlap(
Perfil $perfil,
int $recursoId,
string $fechaInicio,
?string $fechaFin,
?int $exceptPivotId = null,
): void {
$inicio = Carbon::parse($fechaInicio);
$fin = $fechaFin ? Carbon::parse($fechaFin) : null;
$query = DB::table('perfil_recurso')
->where('perfil_id', $perfil->id)
->where('recurso_id', $recursoId);
if ($exceptPivotId !== null) {
$query->where('id', '!=', $exceptPivotId);
}
foreach ($query->get() as $otro) {
if (! $otro->fecha_inicio) {
continue;
}
$otroInicio = Carbon::parse($otro->fecha_inicio);
$otroFin = $otro->fecha_fin ? Carbon::parse($otro->fecha_fin) : null;
if (($otroFin === null || $inicio->lte($otroFin)) && ($fin === null || $fin->gte($otroInicio))) {
throw \Illuminate\Validation\ValidationException::withMessages([
'fecha_inicio' => 'El período se superpone con otra asignación del recurso al perfil.',
]);
}
}
}
}