From 3fa805ee1841956a5dce2d0cc955c7436cc6d562 Mon Sep 17 00:00:00 2001 From: lizandrogd <77708265+lizandrogd@users.noreply.github.com> Date: Mon, 19 Jan 2026 21:11:58 -0500 Subject: [PATCH] o --- .../Resources/InventarioPrendaResource.php | 28 ++++++++++++++++++- app/Models/InventarioPrenda.php | 17 +++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/app/Filament/Resources/InventarioPrendaResource.php b/app/Filament/Resources/InventarioPrendaResource.php index 3d7546e..cc5b163 100644 --- a/app/Filament/Resources/InventarioPrendaResource.php +++ b/app/Filament/Resources/InventarioPrendaResource.php @@ -41,7 +41,33 @@ class InventarioPrendaResource extends Resource ->relationship('ordenProduccion', 'numero_orden') ->searchable() ->preload() - ->required(), + ->reactive() + ->required() + ->afterStateUpdated(function ($state, $set) { + $remaining = 0; + + if ($state) { + // Total recibido hacia bodega desde acabados/traslados + $total = \App\Models\TrasladoPrenda::where('orden_produccion_id', $state) + ->where('destino', 'bodega') + ->sum('cantidad_recibida'); + + // Ya asignado en otros inventarios + $used = \App\Models\InventarioPrenda::where('orden_produccion_id', $state)->sum('cantidad_terminada'); + + $remaining = max(0, (int) $total - (int) $used); + + // Colocar valores en formulario + $set('cantidad_terminada', $remaining); + $set('cantidad_disponible', $remaining); + + // Si la OP tiene producto predeterminado, asignarlo como sugerencia + $op = \App\Models\OrdenProduccion::find($state); + if ($op && $op->producto_id) { + $set('producto_id', $op->producto_id); + } + } + }), TextInput::make('cantidad_terminada') ->numeric() diff --git a/app/Models/InventarioPrenda.php b/app/Models/InventarioPrenda.php index c05058d..a0779ed 100644 --- a/app/Models/InventarioPrenda.php +++ b/app/Models/InventarioPrenda.php @@ -33,6 +33,23 @@ class InventarioPrenda extends Model protected static function booted() { static::creating(function ($inventario) { + // Validación: la cantidad terminada no puede exceder lo recibido para esta OP (traslados a bodega) + if ($inventario->orden_produccion_id) { + $totalRecibido = \App\Models\TrasladoPrenda::where('orden_produccion_id', $inventario->orden_produccion_id) + ->where('destino', 'bodega') + ->sum('cantidad_recibida'); + + $assigned = \App\Models\InventarioPrenda::where('orden_produccion_id', $inventario->orden_produccion_id)->sum('cantidad_terminada'); + + $available = max(0, (int) $totalRecibido - (int) $assigned); + + if ((int) $inventario->cantidad_terminada > $available) { + throw \Illuminate\Validation\ValidationException::withMessages([ + 'cantidad_terminada' => 'No se puede registrar más cantidad terminada de la que está disponible desde acabados/traslados (' . $available . ').', + ]); + } + } + // Al ingresar al inventario, todo está disponible $inventario->cantidad_disponible = $inventario->cantidad_terminada;