Files
sirpremiumv2/app/Console/Commands/validacionCompra.php
T

202 lines
8.0 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Models\Historial_cuenta;
use App\Models\Historiale;
use App\Models\Log_general;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\DB;
class validacionCompra extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'tarea:validarCompra';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Validar la compra de los usuarios';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$fecha_ahora = Carbon::now()->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
$hora_antes = Carbon::now()->subMinutes(15)->format('Y-m-d H:i:s');
$this->validarSaldosNegativos($hora_antes, $fecha_ahora);
$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<br>Vendedor ID: {$anterior->nombre_cliente}- {$anterior->created_at} - {$registro->created_at}<br><br>";
$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) {
echo "Compra duplicada: {$anterior->created_at} - {$registro->created_at}<br>";
$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);
//echo "Corregido: " . $corregido;
if ($corregido === true) { // Aseguramos que la corrección fue exitosa
$mensaje = "📌 Corregido 📌\n" .
"🆔 Historial ID inactivo: " . addslashes($registro->id) . "\n" .
"🆔 Historial ID activo: " . addslashes($anterior->id) . "\n" .
"👤 Saldo retornado: " . addslashes($registro->valor) . "\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').' - Saldo retornado:'.$registro->valor,
]);
}
}
}
}
}
}
}
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()) {
Log::info('Mensaje enviado a Telegram');
} else {
Log::error('Error al enviar mensaje a Telegram');
}
}
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();
$cuentahistorial = Historial_cuenta::where('historial_id', $historial_actual->id)->get();
// Eliminar cuentas asociadas
if (!$cuentahistorial->isEmpty()) {
foreach ($cuentahistorial as $cuenta) {
$cuenta->delete();
}
}
Log_general::where('historial_id', $actual)
->where('tipo', 'compra')
->update(['tipo' => 'revertida']);
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);
}
}
public function validarSaldosNegativos($anterior,$actual)
{
$consultaLog = Log_general::whereBetween('created_at', [$anterior, $actual])
->where('detalle', 'LIKE', '%disponible: $-%')
->get();
//dd($consultaLog);
if (!$consultaLog->isEmpty()) {
foreach ($consultaLog as $log) {
$historial = Historiale::find($log->historial_id);
$usuario = User::find($historial->vendedor_id);
$email = $usuario->email;
$mensaje = "⚠️ Saldo Negativo ⚠️\nUsuario: {$email}\nFecha: {$log->created_at}\nDetalle: {$log->detalle}";
$this->enviarTelegram($mensaje);
}
}
return;
}
}