mirror of
https://gitlab.com/DanLegoff/mgap.git
synced 2026-11-16 14:22:37 +00:00
494 lines
20 KiB
PHP
494 lines
20 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\Area;
|
|
use App\Models\Perfil;
|
|
use App\Models\Recurso;
|
|
use App\Models\TipoRecurso;
|
|
use App\Models\Usuario;
|
|
use App\Models\Vulnerabilidad;
|
|
use App\Support\HistoricalPeriod;
|
|
use Carbon\Carbon;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Validation\Rule;
|
|
use Illuminate\Validation\ValidationException;
|
|
use Inertia\Inertia;
|
|
|
|
class RecursoGestionController extends Controller
|
|
{
|
|
public function show(Recurso $recurso)
|
|
{
|
|
return Inertia::render('Recursos/Gestionar', [
|
|
'recurso' => $recurso->load([
|
|
'tipoRecurso',
|
|
'usuarios',
|
|
'areas',
|
|
'perfiles',
|
|
'vulnerabilidades',
|
|
'riesgos.amenaza',
|
|
'riesgos.vulnerabilidad',
|
|
]),
|
|
'usuarios' => Usuario::query()->where('activo', true)->orderBy('nombre')->get(),
|
|
'tiposRecursos' => TipoRecurso::query()->orderBy('nombre')->get(),
|
|
'areas' => Area::query()->orderBy('nombre')->get(),
|
|
'perfiles' => Perfil::query()->orderBy('nombre')->get(),
|
|
'vulnerabilidades' => Vulnerabilidad::query()->orderBy('nombre')->get(),
|
|
]);
|
|
}
|
|
|
|
public function updateField(Request $request, Recurso $recurso)
|
|
{
|
|
$validated = $request->validate([
|
|
'field' => ['required', Rule::in(['nombre', 'descripcion', 'tipo_recurso_id', 'impacto', 'fecha_alta', 'fecha_baja'])],
|
|
'value' => ['nullable'],
|
|
]);
|
|
|
|
$rules = [
|
|
'nombre' => ['required', 'string', 'max:35'],
|
|
'descripcion' => ['nullable', 'string', 'max:185'],
|
|
'tipo_recurso_id' => ['required', 'exists:tipos_recursos,id'],
|
|
'impacto' => ['nullable', 'string', 'in:Bajo,Medio,Alto,Crítico'],
|
|
'fecha_alta' => ['nullable', 'date'],
|
|
'fecha_baja' => ['nullable', 'date'],
|
|
];
|
|
|
|
$value = validator(
|
|
['value' => $validated['value']],
|
|
['value' => $rules[$validated['field']]],
|
|
)->validate()['value'] ?? null;
|
|
|
|
$fechas = [
|
|
'fecha_alta' => $validated['field'] === 'fecha_alta' ? $value : $recurso->fecha_alta,
|
|
'fecha_baja' => $validated['field'] === 'fecha_baja' ? $value : $recurso->fecha_baja,
|
|
];
|
|
validator($fechas, [
|
|
'fecha_alta' => ['nullable', 'date'],
|
|
'fecha_baja' => ['nullable', 'date', 'after_or_equal:fecha_alta'],
|
|
])->validate();
|
|
|
|
$recurso->update([$validated['field'] => $value]);
|
|
|
|
return back()->with('success', 'Dato actualizado correctamente.');
|
|
}
|
|
|
|
public function attachUsuario(Request $request, Recurso $recurso)
|
|
{
|
|
$validated = $request->validate([
|
|
'usuario_id' => ['required', 'exists:usuarios,id'],
|
|
'duenio' => ['nullable', 'boolean'],
|
|
'fecha_inicio' => ['required', 'date'],
|
|
'fecha_fin' => ['nullable', 'date', 'after_or_equal:fecha_inicio'],
|
|
]);
|
|
$validated['fecha_fin'] = HistoricalPeriod::inclusiveEnd($validated['fecha_fin'] ?? null);
|
|
|
|
DB::transaction(function () use ($recurso, $validated, $request): void {
|
|
Recurso::query()->whereKey($recurso->id)->lockForUpdate()->firstOrFail();
|
|
$this->ensureNoOverlap(
|
|
$recurso,
|
|
(int) $validated['usuario_id'],
|
|
$validated['fecha_inicio'],
|
|
$validated['fecha_fin'] ?? null,
|
|
);
|
|
|
|
$recurso->usuarios()->attach($validated['usuario_id'], [
|
|
'activo' => true,
|
|
'duenio' => $request->boolean('duenio'),
|
|
'fecha_inicio' => $validated['fecha_inicio'],
|
|
'fecha_fin' => $validated['fecha_fin'] ?? null,
|
|
'created_at' => now(),
|
|
'updated_at' => now(),
|
|
]);
|
|
});
|
|
|
|
return back()->with('success', 'Usuario asociado correctamente.');
|
|
}
|
|
|
|
public function detachUsuario(Recurso $recurso, $pivotId)
|
|
{
|
|
DB::table('recurso_usuario')->where('recurso_id', $recurso->id)->where('id', $pivotId)->delete();
|
|
|
|
return back()->with('success', 'Asignación eliminada correctamente.');
|
|
}
|
|
|
|
public function updateUsuarioPivot(Request $request, Recurso $recurso, $pivotId)
|
|
{
|
|
$validated = $request->validate([
|
|
'duenio' => ['required', 'boolean'],
|
|
'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 fecha de inicio.',
|
|
]);
|
|
$validated['fecha_fin'] = HistoricalPeriod::inclusiveEnd($validated['fecha_fin'] ?? null);
|
|
|
|
$registroActual = DB::table('recurso_usuario')
|
|
->where('recurso_id', $recurso->id)
|
|
->where('id', $pivotId)
|
|
->firstOrFail();
|
|
|
|
$inicio = Carbon::parse($validated['fecha_inicio']);
|
|
$fin = $validated['fecha_fin'] ? Carbon::parse($validated['fecha_fin']) : null;
|
|
|
|
$otrosRegistros = DB::table('recurso_usuario')
|
|
->where('recurso_id', $recurso->id)
|
|
->where('usuario_id', $registroActual->usuario_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;
|
|
|
|
$empiezaAntesDeQueTermineElOtro = $otroFin === null ? true : $inicio->lte($otroFin);
|
|
$terminaDespuesDeQueEmpieceElOtro = $fin === null ? true : $fin->gte($otroInicio);
|
|
|
|
if ($empiezaAntesDeQueTermineElOtro && $terminaDespuesDeQueEmpieceElOtro) {
|
|
$textoOtroFin = $otroFin ? $otroFin->format('d/m/Y') : 'la actualidad';
|
|
throw \Illuminate\Validation\ValidationException::withMessages([
|
|
'fecha_inicio' => "Las fechas chocan con otro registro existente (del {$otroInicio->format('d/m/Y')} al {$textoOtroFin}).",
|
|
]);
|
|
}
|
|
}
|
|
|
|
DB::table('recurso_usuario')
|
|
->where('recurso_id', $recurso->id)
|
|
->where('id', $pivotId)
|
|
->update([
|
|
'duenio' => $validated['duenio'],
|
|
'fecha_inicio' => $validated['fecha_inicio'],
|
|
'fecha_fin' => $validated['fecha_fin'],
|
|
'updated_at' => now(),
|
|
]);
|
|
|
|
return back()->with('success', 'Asignación actualizada correctamente.');
|
|
}
|
|
|
|
private function ensureNoOverlap(
|
|
Recurso $recurso,
|
|
int $usuarioId,
|
|
string $fechaInicio,
|
|
?string $fechaFin,
|
|
?int $exceptPivotId = null,
|
|
): void {
|
|
$inicio = Carbon::parse($fechaInicio);
|
|
$fin = $fechaFin ? Carbon::parse($fechaFin) : null;
|
|
$query = DB::table('recurso_usuario')
|
|
->where('recurso_id', $recurso->id)
|
|
->where('usuario_id', $usuarioId);
|
|
|
|
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 ValidationException::withMessages([
|
|
'fecha_inicio' => 'El período se superpone con otra asignación del usuario al recurso.',
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
|
|
public function attachArea(Request $request, Recurso $recurso)
|
|
{
|
|
$validated = $request->validate([
|
|
'area_id' => ['required', 'exists:areas,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('area_recurso')
|
|
->where('recurso_id', $recurso->id)
|
|
->where('area_id', $validated['area_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 ValidationException::withMessages([
|
|
'fecha_inicio' => 'Las fechas chocan con un registro existente para esta área.',
|
|
]);
|
|
}
|
|
}
|
|
|
|
$recurso->areas()->attach($validated['area_id'], [
|
|
'fecha_inicio' => $validated['fecha_inicio'],
|
|
'fecha_fin' => $validated['fecha_fin'] ?? null,
|
|
'created_at' => now(),
|
|
'updated_at' => now(),
|
|
]);
|
|
|
|
return back()->with('success', 'Área asociada correctamente.');
|
|
}
|
|
|
|
public function updateAreaPivot(Request $request, Recurso $recurso, $pivotId)
|
|
{
|
|
$validated = $request->validate([
|
|
'fecha_inicio' => ['required', 'date'],
|
|
'fecha_fin' => ['nullable', 'date', 'after_or_equal:fecha_inicio'],
|
|
]);
|
|
$validated['fecha_fin'] = HistoricalPeriod::inclusiveEnd($validated['fecha_fin'] ?? null);
|
|
|
|
$registroActual = DB::table('area_recurso')
|
|
->where('recurso_id', $recurso->id)
|
|
->where('id', $pivotId)
|
|
->firstOrFail();
|
|
|
|
$inicio = Carbon::parse($validated['fecha_inicio']);
|
|
$fin = $validated['fecha_fin'] ? Carbon::parse($validated['fecha_fin']) : null;
|
|
|
|
$otrosRegistros = DB::table('area_recurso')
|
|
->where('recurso_id', $recurso->id)
|
|
->where('area_id', $registroActual->area_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 ValidationException::withMessages([
|
|
'fecha_inicio' => 'Las fechas chocan con un registro existente para esta área.',
|
|
]);
|
|
}
|
|
}
|
|
|
|
DB::table('area_recurso')
|
|
->where('recurso_id', $recurso->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 detachArea(Recurso $recurso, $pivotId)
|
|
{
|
|
DB::table('area_recurso')->where('recurso_id', $recurso->id)->where('id', $pivotId)->delete();
|
|
|
|
return back()->with('success', 'Asignación de área eliminada correctamente.');
|
|
}
|
|
|
|
public function attachPerfil(Request $request, Recurso $recurso)
|
|
{
|
|
$validated = $request->validate([
|
|
'perfil_id' => ['required', 'exists:perfiles,id'],
|
|
'evidencia' => ['nullable', 'string'],
|
|
'fecha_inicio' => ['required', 'date'],
|
|
'fecha_fin' => ['nullable', 'date', 'after_or_equal:fecha_inicio'],
|
|
'fecha_revision' => ['nullable', 'date'],
|
|
'fecha_proxima_revision' => ['nullable', 'date', 'after_or_equal:fecha_revision'],
|
|
]);
|
|
$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_recurso')
|
|
->where('recurso_id', $recurso->id)
|
|
->where('perfil_id', $validated['perfil_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 ValidationException::withMessages([
|
|
'fecha_inicio' => 'Las fechas chocan con un registro existente para este perfil.',
|
|
]);
|
|
}
|
|
}
|
|
|
|
$recurso->perfiles()->attach($validated['perfil_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,
|
|
'created_at' => now(),
|
|
'updated_at' => now(),
|
|
]);
|
|
|
|
return back()->with('success', 'Perfil asociado correctamente.');
|
|
}
|
|
|
|
public function updatePerfilPivot(Request $request, Recurso $recurso, $pivotId)
|
|
{
|
|
$validated = $request->validate([
|
|
'evidencia' => ['nullable', 'string'],
|
|
'fecha_inicio' => ['required', 'date'],
|
|
'fecha_fin' => ['nullable', 'date', 'after_or_equal:fecha_inicio'],
|
|
'fecha_revision' => ['nullable', 'date'],
|
|
'fecha_proxima_revision' => ['nullable', 'date', 'after_or_equal:fecha_revision'],
|
|
]);
|
|
$validated['fecha_fin'] = HistoricalPeriod::inclusiveEnd($validated['fecha_fin'] ?? null);
|
|
|
|
$registroActual = DB::table('perfil_recurso')
|
|
->where('recurso_id', $recurso->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_recurso')
|
|
->where('recurso_id', $recurso->id)
|
|
->where('perfil_id', $registroActual->perfil_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 ValidationException::withMessages([
|
|
'fecha_inicio' => 'Las fechas chocan con un registro existente para este perfil.',
|
|
]);
|
|
}
|
|
}
|
|
|
|
DB::table('perfil_recurso')
|
|
->where('recurso_id', $recurso->id)
|
|
->where('id', $pivotId)
|
|
->update([
|
|
'evidencia' => $validated['evidencia'] ?? null,
|
|
'fecha_inicio' => $validated['fecha_inicio'],
|
|
'fecha_fin' => $validated['fecha_fin'],
|
|
'fecha_revision' => $validated['fecha_revision'] ?? null,
|
|
'fecha_proxima_revision' => $validated['fecha_proxima_revision'] ?? null,
|
|
'updated_at' => now(),
|
|
]);
|
|
|
|
return back()->with('success', 'Asignación actualizada correctamente.');
|
|
}
|
|
|
|
public function detachPerfil(Recurso $recurso, $pivotId)
|
|
{
|
|
DB::table('perfil_recurso')->where('recurso_id', $recurso->id)->where('id', $pivotId)->delete();
|
|
|
|
return back()->with('success', 'Asignación de perfil eliminada correctamente.');
|
|
}
|
|
|
|
public function attachVulnerabilidad(Request $request, Recurso $recurso)
|
|
{
|
|
$validated = $request->validate([
|
|
'vulnerabilidad_id' => ['required', 'exists:vulnerabilidades,id'],
|
|
'fecha_identificacion' => ['required', 'date'],
|
|
'fecha_fin' => ['nullable', 'date', 'after_or_equal:fecha_identificacion'],
|
|
]);
|
|
$validated['fecha_fin'] = HistoricalPeriod::inclusiveEnd($validated['fecha_fin'] ?? null);
|
|
|
|
$inicio = Carbon::parse($validated['fecha_identificacion']);
|
|
$fin = $validated['fecha_fin'] ? Carbon::parse($validated['fecha_fin']) : null;
|
|
|
|
$otrosRegistros = DB::table('recursos_vulnerabilidad')
|
|
->where('recursos_id', $recurso->id)
|
|
->where('vulnerabilidad_id', $validated['vulnerabilidad_id'])
|
|
->get();
|
|
|
|
foreach ($otrosRegistros as $otro) {
|
|
$otroInicio = Carbon::parse($otro->fecha_identificacion);
|
|
$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 ValidationException::withMessages([
|
|
'fecha_inicio' => 'Las fechas chocan con un registro existente para esta vulnerabilidad.',
|
|
]);
|
|
}
|
|
}
|
|
|
|
$recurso->vulnerabilidades()->attach($validated['vulnerabilidad_id'], [
|
|
'fecha_identificacion' => $validated['fecha_identificacion'],
|
|
'fecha_fin' => $validated['fecha_fin'] ?? null,
|
|
'created_at' => now(),
|
|
'updated_at' => now(),
|
|
]);
|
|
|
|
return back()->with('success', 'Vulnerabilidad asociada correctamente.');
|
|
}
|
|
|
|
public function updateVulnerabilidadPivot(Request $request, Recurso $recurso, $pivotId)
|
|
{
|
|
$validated = $request->validate([
|
|
'fecha_identificacion' => ['required', 'date'],
|
|
'fecha_fin' => ['nullable', 'date', 'after_or_equal:fecha_identificacion'],
|
|
]);
|
|
$validated['fecha_fin'] = HistoricalPeriod::inclusiveEnd($validated['fecha_fin'] ?? null);
|
|
|
|
$registroActual = DB::table('recursos_vulnerabilidad')
|
|
->where('recursos_id', $recurso->id)
|
|
->where('id', $pivotId)
|
|
->firstOrFail();
|
|
|
|
$inicio = Carbon::parse($validated['fecha_identificacion']);
|
|
$fin = $validated['fecha_fin'] ? Carbon::parse($validated['fecha_fin']) : null;
|
|
|
|
$otrosRegistros = DB::table('recursos_vulnerabilidad')
|
|
->where('recursos_id', $recurso->id)
|
|
->where('vulnerabilidad_id', $registroActual->vulnerabilidad_id)
|
|
->where('id', '!=', $pivotId)
|
|
->get();
|
|
|
|
foreach ($otrosRegistros as $otro) {
|
|
$otroInicio = Carbon::parse($otro->fecha_identificacion);
|
|
$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 ValidationException::withMessages([
|
|
'fecha_inicio' => 'Las fechas chocan con un registro existente para esta vulnerabilidad.',
|
|
]);
|
|
}
|
|
}
|
|
|
|
DB::table('recursos_vulnerabilidad')
|
|
->where('recursos_id', $recurso->id)
|
|
->where('id', $pivotId)
|
|
->update([
|
|
'fecha_identificacion' => $validated['fecha_identificacion'],
|
|
'fecha_fin' => $validated['fecha_fin'],
|
|
'updated_at' => now(),
|
|
]);
|
|
|
|
return back()->with('success', 'Asignación actualizada correctamente.');
|
|
}
|
|
|
|
public function detachVulnerabilidad(Recurso $recurso, $pivotId)
|
|
{
|
|
DB::table('recursos_vulnerabilidad')->where('recursos_id', $recurso->id)->where('id', $pivotId)->delete();
|
|
|
|
return back()->with('success', 'Asignación de vulnerabilidad eliminada correctamente.');
|
|
}
|
|
}
|