mirror of
https://gitlab.com/DanLegoff/mgap.git
synced 2026-11-16 14:22:37 +00:00
297 lines
11 KiB
PHP
297 lines
11 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\Area;
|
|
use App\Models\Recurso;
|
|
use App\Models\Usuario;
|
|
use App\Support\HistoricalPeriod;
|
|
use Carbon\Carbon;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Validator;
|
|
use Illuminate\Validation\Rule;
|
|
use Illuminate\Validation\ValidationException;
|
|
use Inertia\Inertia;
|
|
|
|
class AreaGestionController extends Controller
|
|
{
|
|
public function show(Area $area)
|
|
{
|
|
return Inertia::render('Areas/Gestionar', [
|
|
'area' => $area->load(['usuarios', 'recursos.tipoRecurso']),
|
|
'usuarios' => Usuario::query()->where('activo', true)->orderBy('nombre')->orderBy('apellido')->get(),
|
|
'recursos' => Recurso::query()->with('tipoRecurso')->orderBy('nombre')->get(),
|
|
]);
|
|
}
|
|
|
|
public function updateField(Request $request, Area $area)
|
|
{
|
|
$validated = $request->validate([
|
|
'field' => ['required', Rule::in([
|
|
'nombre', 'descripcion', 'correo', 'direccion', 'telefono',
|
|
'motivo_alta', 'activo', 'fecha_alta', 'fecha_baja',
|
|
])],
|
|
'value' => ['nullable'],
|
|
]);
|
|
|
|
if ($validated['field'] === 'activo') {
|
|
$validated['value'] = (int) $validated['value'];
|
|
}
|
|
|
|
$rules = [
|
|
'nombre' => ['required', 'string', 'max:35'],
|
|
'descripcion' => ['nullable', 'string', 'max:185'],
|
|
'correo' => ['nullable', 'email', 'max:35'],
|
|
'direccion' => ['nullable', 'string', 'max:35'],
|
|
'telefono' => ['nullable', 'string', 'regex:/^[0-9]*$/', 'max:35'],
|
|
'motivo_alta' => ['nullable', 'string', 'max:35'],
|
|
'activo' => ['required', 'boolean'],
|
|
];
|
|
|
|
if (isset($rules[$validated['field']])) {
|
|
validator(['value' => $validated['value']], ['value' => $rules[$validated['field']]])->validate();
|
|
}
|
|
|
|
$fechas = [
|
|
'fecha_alta' => $validated['field'] === 'fecha_alta' ? $validated['value'] : $area->fecha_alta,
|
|
'fecha_baja' => $validated['field'] === 'fecha_baja' ? $validated['value'] : $area->fecha_baja,
|
|
];
|
|
|
|
$validator = Validator::make($fechas, [
|
|
'fecha_alta' => ['nullable', 'date'],
|
|
'fecha_baja' => ['nullable', 'date', 'after_or_equal:fecha_alta'],
|
|
], [
|
|
'fecha_baja.after_or_equal' => 'La fecha de baja no puede ser anterior a la fecha de alta.',
|
|
]);
|
|
|
|
if ($validator->fails()) {
|
|
throw ValidationException::withMessages(['value' => $validator->errors()->first()]);
|
|
}
|
|
|
|
$area->update([$validated['field'] => $validated['value']]);
|
|
|
|
return back()->with('success', 'Dato actualizado correctamente.');
|
|
}
|
|
|
|
public function attachUsuario(Request $request, Area $area)
|
|
{
|
|
$validated = $request->validate([
|
|
'usuario_id' => ['required', 'exists:usuarios,id'],
|
|
'fecha_inicio' => ['required', 'date'],
|
|
'fecha_fin' => ['nullable', 'date', 'after_or_equal:fecha_inicio'],
|
|
'responsable' => ['required', 'boolean'],
|
|
], [
|
|
'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);
|
|
|
|
DB::transaction(function () use ($area, $validated) {
|
|
Area::query()->whereKey($area->id)->lockForUpdate()->firstOrFail();
|
|
$this->ensureNoOverlap(
|
|
$area,
|
|
(int) $validated['usuario_id'],
|
|
$validated['fecha_inicio'],
|
|
$validated['fecha_fin'] ?? null,
|
|
);
|
|
|
|
$area->usuarios()->attach($validated['usuario_id'], [
|
|
'fecha_inicio' => $validated['fecha_inicio'],
|
|
'fecha_fin' => $validated['fecha_fin'] ?? null,
|
|
'responsable' => $validated['responsable'],
|
|
]);
|
|
|
|
});
|
|
|
|
return back()->with('success', 'Usuario asignado al histórico correctamente.');
|
|
}
|
|
|
|
public function updateUsuarioPivot(Request $request, Area $area, int $pivotId)
|
|
{
|
|
$validated = $request->validate([
|
|
'responsable' => ['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);
|
|
|
|
$pivot = DB::table('area_usuario')
|
|
->where('area_id', $area->id)
|
|
->where('id', $pivotId)
|
|
->firstOrFail();
|
|
|
|
if ((bool) $pivot->responsable && (
|
|
! $validated['responsable']
|
|
|| Carbon::parse($pivot->fecha_inicio)->toDateString() !== Carbon::parse($validated['fecha_inicio'])->toDateString()
|
|
)) {
|
|
throw ValidationException::withMessages([
|
|
'fecha_inicio' => 'Un período de responsabilidad no puede reprogramarse. Finalícelo y cree uno nuevo.',
|
|
]);
|
|
}
|
|
|
|
DB::transaction(function () use ($area, $pivot, $pivotId, $validated) {
|
|
Area::query()->whereKey($area->id)->lockForUpdate()->firstOrFail();
|
|
$this->ensureNoOverlap(
|
|
$area,
|
|
(int) $pivot->usuario_id,
|
|
$validated['fecha_inicio'],
|
|
$validated['fecha_fin'] ?? null,
|
|
$pivotId,
|
|
);
|
|
|
|
DB::table('area_usuario')
|
|
->where('area_id', $area->id)
|
|
->where('id', $pivotId)
|
|
->update([
|
|
...$validated,
|
|
'updated_at' => now(),
|
|
]);
|
|
|
|
});
|
|
|
|
return back()->with('success', 'Asignación actualizada correctamente.');
|
|
}
|
|
|
|
public function detachUsuario(Area $area, int $pivotId)
|
|
{
|
|
DB::table('area_usuario')->where('area_id', $area->id)->where('id', $pivotId)->delete();
|
|
|
|
return back()->with('success', 'Asignación eliminada correctamente.');
|
|
}
|
|
|
|
public function attachRecurso(Request $request, Area $area)
|
|
{
|
|
$validated = $request->validate([
|
|
'recurso_id' => ['required', 'exists:recursos,id'],
|
|
'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 ($area, $validated): void {
|
|
Area::query()->whereKey($area->id)->lockForUpdate()->firstOrFail();
|
|
$this->ensureNoRecursoOverlap(
|
|
$area,
|
|
(int) $validated['recurso_id'],
|
|
$validated['fecha_inicio'],
|
|
$validated['fecha_fin'] ?? null,
|
|
);
|
|
|
|
$area->recursos()->attach($validated['recurso_id'], [
|
|
'fecha_inicio' => $validated['fecha_inicio'],
|
|
'fecha_fin' => $validated['fecha_fin'] ?? null,
|
|
]);
|
|
});
|
|
|
|
return back()->with('success', 'Recurso asociado correctamente.');
|
|
}
|
|
|
|
public function updateRecursoPivot(Request $request, Area $area, int $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);
|
|
|
|
DB::transaction(function () use ($area, $pivotId, $validated): void {
|
|
Area::query()->whereKey($area->id)->lockForUpdate()->firstOrFail();
|
|
$pivot = DB::table('area_recurso')
|
|
->where('area_id', $area->id)
|
|
->where('id', $pivotId)
|
|
->firstOrFail();
|
|
|
|
$this->ensureNoRecursoOverlap(
|
|
$area,
|
|
(int) $pivot->recurso_id,
|
|
$validated['fecha_inicio'],
|
|
$validated['fecha_fin'] ?? null,
|
|
$pivotId,
|
|
);
|
|
|
|
DB::table('area_recurso')
|
|
->where('area_id', $area->id)
|
|
->where('id', $pivotId)
|
|
->update([...$validated, 'updated_at' => now()]);
|
|
});
|
|
|
|
return back()->with('success', 'Asignación de recurso actualizada correctamente.');
|
|
}
|
|
|
|
public function detachRecurso(Area $area, int $pivotId)
|
|
{
|
|
DB::table('area_recurso')->where('area_id', $area->id)->where('id', $pivotId)->delete();
|
|
|
|
return back()->with('success', 'Asignación de recurso eliminada correctamente.');
|
|
}
|
|
|
|
private function ensureNoOverlap(
|
|
Area $area,
|
|
int $usuarioId,
|
|
string $fechaInicio,
|
|
?string $fechaFin,
|
|
?int $exceptPivotId = null,
|
|
): void {
|
|
$inicio = Carbon::parse($fechaInicio);
|
|
$fin = $fechaFin ? Carbon::parse($fechaFin) : null;
|
|
|
|
$query = DB::table('area_usuario')
|
|
->where('area_id', $area->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;
|
|
$empiezaAntesDeQueTermineElOtro = $otroFin === null || $inicio->lte($otroFin);
|
|
$terminaDespuesDeQueEmpieceElOtro = $fin === null || $fin->gte($otroInicio);
|
|
|
|
if ($empiezaAntesDeQueTermineElOtro && $terminaDespuesDeQueEmpieceElOtro) {
|
|
$textoOtroFin = $otroFin ? $otroFin->format('d/m/Y') : 'la actualidad';
|
|
|
|
throw ValidationException::withMessages([
|
|
'fecha_inicio' => "El período ingresado se superpone con un registro histórico existente (del {$otroInicio->format('d/m/Y')} al {$textoOtroFin}).",
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
|
|
private function ensureNoRecursoOverlap(
|
|
Area $area,
|
|
int $recursoId,
|
|
string $fechaInicio,
|
|
?string $fechaFin,
|
|
?int $exceptPivotId = null,
|
|
): void {
|
|
$inicio = Carbon::parse($fechaInicio);
|
|
$fin = $fechaFin ? Carbon::parse($fechaFin) : null;
|
|
$query = DB::table('area_recurso')
|
|
->where('area_id', $area->id)
|
|
->where('recurso_id', $recursoId);
|
|
|
|
if ($exceptPivotId !== null) {
|
|
$query->where('id', '!=', $exceptPivotId);
|
|
}
|
|
|
|
foreach ($query->get() as $otro) {
|
|
$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 recurso al área.',
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
}
|