where('estado', 'activo') ->orderBy('id', 'DESC') ->when(!empty($this->fecha_desde), fn($q) => $q->whereDate('created_at', '>=', $this->fecha_desde)) ->when(!empty($this->fecha_hasta), fn($q) => $q->whereDate('created_at', '<=', $this->fecha_hasta)) ->when(!empty($this->buscar), function ($query) { $query->where(function ($q) { $q->where('id', 'ILIKE', '%' . $this->buscar . '%') ->orWhere('nombre_cliente', 'ILIKE', '%' . $this->buscar . '%') ->orWhereHas('vendedor', function ($sub) { $sub->where('name', 'ILIKE', '%' . $this->buscar . '%') ->orWhere('email', 'ILIKE', '%' . $this->buscar . '%'); }) ->orWhereHas('cliente', function ($sub) { $sub->where('name', 'ILIKE', '%' . $this->buscar . '%') ->orWhere('email', 'ILIKE', '%' . $this->buscar . '%'); }) ->orWhereHas('cuentas', function ($sub) { $sub->where('correo', 'ILIKE', '%' . $this->buscar . '%'); }); }); }) ->take(200) ->paginate(20); $consulta->setCollection($consulta->getCollection()->values()); return view('livewire.reversar-compra', ['historiales' => $consulta]); } public function confirmar($id) { $this->confirmando_id = $id; } public function cancelarConfirmacion() { $this->confirmando_id = null; } public function reversar($id) { DB::beginTransaction(); try { $historial = Historiale::with('vendedor.saldo', 'tarifa', 'promocion')->findOrFail($id); if ($historial->estado !== 'activo') { $this->alert('error', 'Solo se pueden reversar compras activas.'); DB::rollBack(); return; } $vendedor = $historial->vendedor; $total_valor = $historial->valor; $utilidad_total = $historial->utilidad ?? 0; // 1. Restaurar saldo al vendedor $nuevo_saldo = $vendedor->saldo->valor + $total_valor; Saldo::where('usuario_id', $vendedor->id)->update(['valor' => $nuevo_saldo]); // 2. Si el vendedor tiene subvendedor padre, restar la utilidad que se le había dado if ($vendedor->subvendedor_id && $utilidad_total > 0) { $subvendedorPadre = User::with('saldo')->find($vendedor->subvendedor_id); if ($subvendedorPadre && $subvendedorPadre->saldo) { $saldoPadre = $subvendedorPadre->saldo->valor - $utilidad_total; $subvendedorPadre->saldo->update(['valor' => max($saldoPadre, 0)]); } } // 3. Eliminar registros de cuentas asignadas (las libera) Historial_cuenta::where('historial_id', $historial->id)->delete(); // 4. Eliminar datos de compatibilidad DGO si existen if ($historial->compatibilidadDgo) { $historial->compatibilidadDgo->delete(); } // 5. Marcar historial como cancelado $historial->estado = 'cancelado'; $historial->save(); // 6. Actualizar logs Log_general::where('historial_id', $historial->id) ->where('tipo', 'compra') ->update(['tipo' => 'revertida']); Log_general::create([ 'user_id' => auth()->id(), 'historial_id' => $historial->id, 'tipo' => 'reversion', 'detalle' => 'Reversión manual por ' . auth()->user()->name . ' - Historial #' . $historial->id . ' - Valor: $' . $total_valor . ' - Vendedor: ' . $vendedor->name . ' - Saldo restaurado: $' . $nuevo_saldo, ]); DB::commit(); $this->confirmando_id = null; $this->alert('success', 'Compra #' . $historial->id . ' revertida correctamente. Saldo restaurado: $' . number_format($total_valor)); } catch (\Exception $e) { DB::rollBack(); $this->alert('error', 'Error al revertir: ' . $e->getMessage()); } } }