diff --git a/app/Console/Commands/validacionCompra.php b/app/Console/Commands/validacionCompra.php new file mode 100644 index 0000000..fda3283 --- /dev/null +++ b/app/Console/Commands/validacionCompra.php @@ -0,0 +1,168 @@ +format('Y-m-d H:i:s'); // Fecha y hora actual + $hora_antes = Carbon::now()->subHours(100)->format('Y-m-d H:i:s'); // 24 horas antes + + $resultados = Historiale::select('vendedor_id') + ->selectRaw('COUNT(*) as total') + ->where('estado', 'activo') + ->whereBetween('created_at', [$hora_antes, $fecha_ahora]) + ->groupBy('vendedor_id') + ->havingRaw('COUNT(*) > 1') + ->get(); + + foreach ($resultados as $resultado) { + $registro_vendedores_duplicados = Historiale::where('vendedor_id', $resultado->vendedor_id) + ->where('estado', 'activo') + ->whereBetween('created_at', [$hora_antes, $fecha_ahora]) + ->orderBy('created_at', 'asc') // Ordenar por fecha ascendente para comparar correctamente + ->get(); + + + foreach ($registro_vendedores_duplicados as $index => $registro) { + if ($index > 0) { + $anterior = $registro_vendedores_duplicados[$index - 1]; + $diferencia = Carbon::parse($anterior->created_at)->diffInSeconds(Carbon::parse($registro->created_at)); + + if ($diferencia < 20) { + //echo "Diferencia: {$diferencia} segundos
Vendedor ID: {$anterior->nombre_cliente}- {$anterior->created_at} - {$registro->created_at}

"; + $validar_actual = Log_general::where('historial_id', $registro->id) + ->where('tipo', 'compra') + ->exists(); // Corregido + + $validar_anterior = Log_general::where('historial_id', $anterior->id) + ->where('tipo', 'compra') + ->exists(); // Corregido + + if ($validar_actual && $validar_anterior) { + $vendedor = User::find($resultado->vendedor_id); + $email = $vendedor->email; + $mensaje = "⚠️ Compra Duplicada ⚠️\nUsuario: {$email}\nFechas:\n- Anterior: {$anterior->created_at}\n- Actual: {$registro->created_at}\nDiferencia: {$diferencia} segundos"; + $this->enviarTelegram($mensaje); + $corregido = $this->corregir($anterior->id, $registro->id); + + if ($corregido === true) { // Aseguramos que la corrección fue exitosa + $mensaje = "📌 Corregido 📌\n" . + "🆔 Historial ID inactivo: " . addslashes($registro->id) . "\n" . + "👤 Usuario: " . addslashes($email) . "\n" . + "📅 Fechas:\n" . + " ➤ Anterior: " . addslashes(Carbon::parse($anterior->created_at)->format('d M Y h:i:s A')) . "\n" . + " ➤ Actual: " . addslashes(Carbon::parse($registro->created_at)->format('d M Y h:i:s A')) . ""; + + + + $this->enviarTelegram($mensaje); + + /* Log_general::create([ + 'user_id' => $resultado->vendedor_id, + 'historial_id' => $registro->id, + 'tipo' => 'corregido', + 'detalle' => 'Se ha corregido la compra duplicada, usuario: ' . $email . ' - ' . + Carbon::parse($registro->created_at)->format('d M Y h:i A') . ' - ' . + Carbon::parse($anterior->created_at)->format('d M Y h:i A'), + ]); */ + } + + } + + } + } + } + } + } + + public function enviarTelegram($mensaje) + { + $token = '8163118229:AAENDu4PQGruSx1EHSfMH6BecunxAGyhixY'; + $chat_id = '7583714074'; + $mensaje = 'Sirpremium:' . "\n" . $mensaje; + + $response = Http::get("https://api.telegram.org/bot{$token}/sendMessage", [ + 'chat_id' => $chat_id, + 'text' => $mensaje, + ]); + + if ($response->successful()) { + echo "Mensaje enviado correctamente."; + } else { + echo "Error al enviar el mensaje."; + } + } + + public function corregir($anterior, $actual) + { + try { + DB::beginTransaction(); // Iniciar una transacción + + $historial_anterior = Historiale::find($anterior); + $historial_actual = Historiale::find($actual); + + if (!$historial_anterior || !$historial_actual) { + return response()->json(['error' => 'Historial no encontrado'], 404); + } + + $usuario_anterior = $historial_anterior->vendedor_id; + $actualizar_saldo = User::find($usuario_anterior); + + if (!$actualizar_saldo) { + return response()->json(['error' => 'Usuario no encontrado'], 404); + } + + // Devolver saldo + $actualizar_saldo->saldo->valor -= $historial_actual->valor; + $actualizar_saldo->save(); + + // Cancelar historial actual + //$historial_actual->estado = 'cancelado'; + $historial_actual->save(); + + // Eliminar cuentas asociadas + if ($historial_actual->cuentas) { + foreach ($historial_actual->cuentas as $cuenta) { + //$cuenta->delete(); + } + } + + DB::commit(); // Confirmar la transacción + + return true; // + } catch (\Exception $e) { + DB::rollBack(); // Revertir si hay un error + return response()->json(['error' => 'Error al corregir: ' . $e->getMessage()], 500); + } + } +}