mirror of
https://gitlab.com/DanLegoff/mgap.git
synced 2026-11-16 14:12:39 +00:00
207 lines
7.7 KiB
PHP
207 lines
7.7 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\Control;
|
|
use App\Models\Riesgo;
|
|
use App\Models\TipoControl;
|
|
use App\Support\HistoricalPeriod;
|
|
use App\Support\RiskCalculator;
|
|
use Carbon\Carbon;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Validation\Rule;
|
|
use Inertia\Inertia;
|
|
|
|
class ControlGestionController extends Controller
|
|
{
|
|
public function show(Control $control)
|
|
{
|
|
$control->load(['tiposControles', 'riesgos.recurso', 'riesgos.amenaza', 'riesgos.vulnerabilidad']);
|
|
|
|
return Inertia::render('Controles/Gestionar', [
|
|
'control' => $control,
|
|
'tiposControles' => TipoControl::orderBy('nombre')->get(),
|
|
'riesgos' => Riesgo::orderBy('nombre')->get(),
|
|
]);
|
|
}
|
|
|
|
public function updateField(Request $request, Control $control)
|
|
{
|
|
$editableFields = ['nombre', 'descripcion', 'estado', 'nivel_de_control', 'fecha_inicio', 'fecha_fin', 'tipo_control_id'];
|
|
|
|
$validated = $request->validate([
|
|
'field' => ['required', Rule::in($editableFields)],
|
|
'value' => ['nullable'],
|
|
]);
|
|
|
|
if ($validated['field'] === 'tipo_control_id') {
|
|
$tipoId = validator(
|
|
['value' => $validated['value']],
|
|
['value' => ['required', 'exists:tipos_controles,id']],
|
|
)->validate()['value'];
|
|
|
|
$asignacionActual = DB::table('control_tipos_control')
|
|
->where('control_id', $control->id)
|
|
->whereNull('fecha_fin')
|
|
->orderByDesc('id')
|
|
->first();
|
|
|
|
if ($asignacionActual && (int) $asignacionActual->tipo_control_id === (int) $tipoId) {
|
|
return back()->with('success', 'Dato actualizado correctamente.');
|
|
}
|
|
|
|
DB::transaction(function () use ($control, $tipoId, $asignacionActual) {
|
|
$now = now();
|
|
|
|
if ($asignacionActual) {
|
|
DB::table('control_tipos_control')
|
|
->where('control_id', $control->id)
|
|
->where('id', $asignacionActual->id)
|
|
->update([
|
|
'fecha_fin' => $now,
|
|
'updated_at' => $now,
|
|
]);
|
|
}
|
|
|
|
$control->tiposControles()->attach($tipoId, [
|
|
'fecha_inicio' => $now,
|
|
'fecha_fin' => null,
|
|
'created_at' => $now,
|
|
'updated_at' => $now,
|
|
]);
|
|
});
|
|
|
|
return back()->with('success', 'Dato actualizado correctamente.');
|
|
}
|
|
|
|
$rules = match ($validated['field']) {
|
|
'nombre' => ['required', 'string', 'max:35'],
|
|
'estado' => ['nullable', 'string', Rule::in(['Implementado', 'En revisión', 'Planificado'])],
|
|
'nivel_de_control' => ['nullable', 'string', 'in:fuerte,parcial,debil'],
|
|
'descripcion' => ['nullable', 'string', 'max:185'],
|
|
'fecha_inicio', 'fecha_fin' => ['nullable', 'date'],
|
|
default => ['nullable', 'string', 'max:255'],
|
|
};
|
|
|
|
$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 : $control->fecha_inicio,
|
|
'fecha_fin' => $validated['field'] === 'fecha_fin' ? $value : $control->fecha_fin,
|
|
], [
|
|
'fecha_inicio' => ['nullable', 'date'],
|
|
'fecha_fin' => ['nullable', 'date', 'after_or_equal:fecha_inicio'],
|
|
])->validate();
|
|
}
|
|
|
|
$control->update([$validated['field'] => $value]);
|
|
|
|
if (in_array($validated['field'], ['estado', 'nivel_de_control'], true)) {
|
|
$control->riesgos()->whereNull('riesgo_control.fecha_fin')->each(function (Riesgo $riesgo) {
|
|
RiskCalculator::recalculate($riesgo);
|
|
});
|
|
}
|
|
|
|
return back()->with('success', 'Dato actualizado correctamente.');
|
|
}
|
|
|
|
public function attachRiesgo(Request $request, Control $control)
|
|
{
|
|
$validated = $request->validate([
|
|
'riesgo_id' => ['required', 'integer', 'exists:riesgos,id'],
|
|
'fecha_identificacion' => ['required', 'date'],
|
|
'fecha_fin' => ['nullable', 'date', 'after_or_equal:fecha_identificacion'],
|
|
]);
|
|
$validated['fecha_fin'] = HistoricalPeriod::inclusiveEnd($validated['fecha_fin'] ?? null);
|
|
|
|
$this->ensurePeriodDoesNotOverlap(
|
|
$control->id,
|
|
(int) $validated['riesgo_id'],
|
|
$validated['fecha_identificacion'],
|
|
$validated['fecha_fin'],
|
|
);
|
|
|
|
$control->riesgos()->attach($validated['riesgo_id'], [
|
|
'fecha_identificacion' => $validated['fecha_identificacion'],
|
|
'fecha_fin' => $validated['fecha_fin'],
|
|
]);
|
|
|
|
return back()->with('success', 'Riesgo asociado correctamente.');
|
|
}
|
|
|
|
public function updateRiesgoPivot(Request $request, Control $control, int $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);
|
|
|
|
$pivot = DB::table('riesgo_control')
|
|
->where('control_id', $control->id)
|
|
->where('id', $pivotId)
|
|
->firstOrFail();
|
|
|
|
$this->ensurePeriodDoesNotOverlap(
|
|
$control->id,
|
|
(int) $pivot->riesgo_id,
|
|
$validated['fecha_identificacion'],
|
|
$validated['fecha_fin'],
|
|
$pivotId,
|
|
);
|
|
|
|
DB::table('riesgo_control')
|
|
->where('control_id', $control->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 detachRiesgo(Control $control, int $pivotId)
|
|
{
|
|
DB::table('riesgo_control')->where('control_id', $control->id)->where('id', $pivotId)->delete();
|
|
|
|
return back()->with('success', 'Asignación de riesgo eliminada correctamente.');
|
|
}
|
|
|
|
private function ensurePeriodDoesNotOverlap(
|
|
int $controlId,
|
|
int $riesgoId,
|
|
string $start,
|
|
?string $end,
|
|
?int $excludedPivotId = null,
|
|
): void {
|
|
$periods = DB::table('riesgo_control')
|
|
->where('control_id', $controlId)
|
|
->where('riesgo_id', $riesgoId)
|
|
->when($excludedPivotId, fn ($query) => $query->where('id', '!=', $excludedPivotId))
|
|
->get();
|
|
|
|
$startDate = Carbon::parse($start);
|
|
$endDate = $end ? Carbon::parse($end) : null;
|
|
|
|
foreach ($periods as $period) {
|
|
$otherStart = Carbon::parse($period->fecha_identificacion);
|
|
$otherEnd = $period->fecha_fin ? Carbon::parse($period->fecha_fin) : null;
|
|
$startsBeforeOtherEnds = $otherEnd === null || $startDate->lte($otherEnd);
|
|
$endsAfterOtherStarts = $endDate === null || $endDate->gte($otherStart);
|
|
|
|
if ($startsBeforeOtherEnds && $endsAfterOtherStarts) {
|
|
throw \Illuminate\Validation\ValidationException::withMessages([
|
|
'fecha_identificacion' => 'Las fechas chocan con una asignación existente.',
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
}
|