$cantidadTerminada) { throw ValidationException::withMessages(['distribuciones' => 'La suma de las cantidades asignadas excede la cantidad terminada.']); } // Remover distribuciones del payload antes de crear el registro principal unset($data['distribuciones']); $record = parent::handleRecordCreation($data); // Procesar distribuciones y actualizar stock en bodegas foreach ($distribuciones as $d) { $cantidad = intval($d['cantidad'] ?? 0); if ($cantidad <= 0) continue; // Crear registro de distribución $created = InventarioPrendaDistribucion::create([ 'inventario_prenda_id' => $record->id, 'bodega_id' => $d['bodega_id'] ?? null, 'color_id' => $d['color_id'] ?? null, 'size_id' => $d['size_id'] ?? null, 'cantidad' => $cantidad, ]); // Actualizar stock en bodegas $bodegaId = $d['bodega_id'] ?? null; // Si tiene color y talla -> variante if (!empty($d['color_id']) && !empty($d['size_id'])) { $productoId = $record->producto_id ?? ($record->ordenProduccion->producto_id ?? null); // Si no hay producto, intentar obtener por OP if (! $productoId && $record->ordenProduccion) { $productoId = $record->ordenProduccion->producto_id; } if ($productoId) { $variant = ProductVariant::firstOrCreate( [ 'producto_id' => $productoId, 'color_id' => $d['color_id'], 'size_id' => $d['size_id'], ], [ 'stock' => 0, 'sku' => null, 'barcode' => null, ] ); $existing = DB::table('variante_bodega') ->where('variante_id', $variant->id) ->where('bodega_id', $bodegaId) ->first(); if ($existing) { DB::table('variante_bodega') ->where('variante_id', $variant->id) ->where('bodega_id', $bodegaId) ->update([ 'stock' => ($existing->stock ?? 0) + $cantidad, 'updated_at' => now(), ]); } else { DB::table('variante_bodega')->insert([ 'variante_id' => $variant->id, 'bodega_id' => $bodegaId, 'stock' => $cantidad, 'created_at' => now(), 'updated_at' => now(), ]); } // También incrementar stock total de la variante $variant->increment('stock', $cantidad); } } else { // Producto a nivel general $productoId = $record->producto_id ?? ($record->ordenProduccion->producto_id ?? null); if ($productoId) { $existing = DB::table('producto_bodega') ->where('producto_id', $productoId) ->where('bodega_id', $bodegaId) ->first(); if ($existing) { DB::table('producto_bodega') ->where('producto_id', $productoId) ->where('bodega_id', $bodegaId) ->update([ 'stock' => ($existing->stock ?? 0) + $cantidad, 'updated_at' => now(), ]); } else { DB::table('producto_bodega')->insert([ 'producto_id' => $productoId, 'bodega_id' => $bodegaId, 'stock' => $cantidad, 'created_at' => now(), 'updated_at' => now(), ]); } // Incrementar stock total del producto si no tiene variantes $prod = \App\Models\Producto::find($productoId); if ($prod && ! $prod->variants()->exists()) { $prod->increment('stock', $cantidad); } } } } return $record; } }