710 lines
32 KiB
PHP
Executable File
710 lines
32 KiB
PHP
Executable File
<?php
|
|
|
|
namespace App\Http\Livewire;
|
|
|
|
use App\Models\Categoria;
|
|
use App\Models\Configuracione;
|
|
use App\Models\Cuentas;
|
|
use App\Models\Role;
|
|
use App\Models\Historial_cuenta;
|
|
use App\Models\Historiale;
|
|
use App\Models\Log_general;
|
|
use App\Models\Promociones;
|
|
use App\Models\Saldo;
|
|
use App\Models\Servicio;
|
|
use App\Models\Tarifas;
|
|
use App\Models\User;
|
|
use App\Models\Usuario_tarifa;
|
|
use App\Notifications\compra;
|
|
use App\Notifications\licencias;
|
|
use Illuminate\Support\Facades\Auth;
|
|
use Livewire\Component;
|
|
use Jantinnerezo\LivewireAlert\LivewireAlert;
|
|
use Carbon\Carbon;
|
|
use Exception;
|
|
use Illuminate\Support\Facades\Crypt;
|
|
use Illuminate\Support\Facades\Notification;
|
|
use Twilio\Rest\Client;
|
|
use AshAllenDesign\ShortURL\Facades\ShortURL;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Database\QueryException;
|
|
|
|
class ShowServicios extends Component
|
|
{
|
|
public $servicio;
|
|
public $tarjetaPlan = false;
|
|
public $tarifa_id;
|
|
public $servicio_id = 2;
|
|
|
|
public $servicio_tarjetaPlan;
|
|
public $pantallas_tarjetaPlan;
|
|
public $dias_tarjetaPlan;
|
|
public $valor_tarjetaPlan;
|
|
public $colorFondo_tarjetaPlan;
|
|
public $celular_tarjetaPlan;
|
|
public $nombre_tarjetaPlan;
|
|
public $email_tarjetaPlan;
|
|
public $cantidad_tarjetaPlan = 1;
|
|
public $consulta_tarifas;
|
|
|
|
public $fechaActual;
|
|
public $fechaHoy;
|
|
public $fechaFinal;
|
|
public $cuentas;
|
|
|
|
public $disponibles;
|
|
public $credenciales = false;
|
|
public $tarifa;
|
|
public $fecha;
|
|
public $msj;
|
|
public $mensaje;
|
|
public $tiempo_tarjetaPlan;
|
|
public $verServ;
|
|
public $fecha_final_1;
|
|
public $fecha_final_2;
|
|
public $utilidad;
|
|
public $tp = false;
|
|
public $usuario_actual;
|
|
|
|
use LivewireAlert;
|
|
protected $rules = [
|
|
'nombre_tarjetaPlan' => 'required',
|
|
'cantidad_tarjetaPlan' => 'required',
|
|
'email_tarjetaPlan' => 'required',
|
|
'celular_tarjetaPlan' => 'required',
|
|
];
|
|
|
|
public function render()
|
|
{
|
|
$this->fechaHoy = Carbon::now();
|
|
$this->fechaActual = Carbon::parse($this->fechaHoy);
|
|
$date = $this->fechaHoy->subDay(20);
|
|
$this->fecha = $date->format('Y-m-d');
|
|
//dd($this->fecha);
|
|
$this->usuario_actual = Auth::user();
|
|
|
|
if (empty($this->nombre_tarjetaPlan) && empty($this->email_tarjetaPlan)) {
|
|
|
|
$this->nombre_tarjetaPlan = $this->usuario_actual->name;
|
|
$this->email_tarjetaPlan = $this->usuario_actual->email;
|
|
$this->celular_tarjetaPlan = $this->usuario_actual->celular;
|
|
}
|
|
if ($this->cantidad_tarjetaPlan > 1) {
|
|
//dd($this->tarifa_id);
|
|
$this->cargartarjetaPlan($this->tarifa_id);
|
|
}
|
|
|
|
|
|
$this->msj = Configuracione::orderby('id', 'desc')->select('msj_compra', 'msj_wp', 'clave_1', 'clave_2', 'clave_3', 'clave_4', 'clave_5', 'clave_6', 'iptv')->first();
|
|
|
|
$consulta_servicios = Servicio::where('estado', 'activo')
|
|
->with([
|
|
'tarifas' => function ($query) {
|
|
$query->where('rol_id', $this->usuario_actual->rol->id)
|
|
->with([
|
|
'usuario_tarifas' => function ($query) {
|
|
$query->where('usuario_id', $this->usuario_actual->id);
|
|
}
|
|
]);
|
|
}
|
|
])
|
|
->orderBy('ubicacion')
|
|
->get();
|
|
|
|
//dd($consulta_servicios);
|
|
|
|
|
|
return view('livewire.show-servicios', [
|
|
'servicios' => $consulta_servicios,
|
|
]);
|
|
}
|
|
|
|
//Al abrir la tarjeta del servicio
|
|
public function cargartarjetaPlan($id)
|
|
{
|
|
$this->tarifa_id = $id; //$this->tarjetaPlan=false;
|
|
//Buscar tarifas por el id
|
|
$tarifa_seleccionada = Tarifas::find($id);
|
|
//Traer el servicio relacionado con esa tarifa
|
|
$servicio_tarifa = $tarifa_seleccionada->servicio;
|
|
|
|
|
|
//INFORMACIÓN DEL SERVICIO
|
|
$this->servicio_id = $servicio_tarifa->id; //Id
|
|
$this->servicio_tarjetaPlan = $servicio_tarifa->nombre; //Nombre
|
|
$this->tiempo_tarjetaPlan = $servicio_tarifa->por_tiempo; //Si es por tiempo o por pantalla
|
|
$this->mensaje = $servicio_tarifa->mensaje; //Mensaje
|
|
$this->colorFondo_tarjetaPlan = $servicio_tarifa->color_fondo; //Color de fondo
|
|
|
|
//INFORMACIÓN DE LA TARJETA
|
|
$this->tarifa_id = $tarifa_seleccionada->id; //El id de la tarifa
|
|
$this->pantallas_tarjetaPlan = $tarifa_seleccionada->pantallas; //Numero de pantallas de la tarifa
|
|
$this->dias_tarjetaPlan = $tarifa_seleccionada->dias; // Numero de dias de la tarifa
|
|
|
|
//Se añade a hoy la cantidad de dias de la tarifa ejem: 30 - 15. Da 15 despues de hoy.
|
|
$this->fecha_final_1 = Carbon::now()->addDays($tarifa_seleccionada->dias - 20);
|
|
//Se añade a hoy la cantidad de dias de la tarifa ejem: 30 + 15. Da 45 despues de hoy.
|
|
$this->fecha_final_2 = Carbon::now()->addDays($tarifa_seleccionada->dias + 20);
|
|
|
|
//Traer la tarifa personalizada del usuario para esta tarifa.
|
|
$usuario_tarifa = Usuario_tarifa::where('usuario_id', auth()->user()->id)
|
|
->where('tarifa_id', $id)
|
|
->first();
|
|
|
|
|
|
//Si tiene tarifa personalizada toma el precio, si no tiene da el valor de la tarifa.
|
|
$this->valor_tarjetaPlan = ($usuario_tarifa) ? $usuario_tarifa->precio : $tarifa_seleccionada->valor;
|
|
//Si tiene tarifa personalizada toma la utilidad, si no tiene toma la utilidad de la tarifa.
|
|
$this->utilidad = ($usuario_tarifa) ? $usuario_tarifa->utilidad : $tarifa_seleccionada->utilidad;
|
|
//Fecha de vencimiento del servicio.
|
|
$this->fechaFinal = $this->fechaActual->addDay($tarifa_seleccionada->dias);
|
|
|
|
//Cantidad de pantallas solicitadas es igual a la completa del servicio.
|
|
if ($tarifa_seleccionada->pantallas == $servicio_tarifa->completa) {
|
|
|
|
//Traer todas las cuentas completas 'pendiente' de los ultimos 15 dias. solo disponibles
|
|
$this->disponibles = Cuentas::whereDate('inicio', '>=', $this->fecha)
|
|
->whereDate('vencimiento', '>=', $this->fecha_final_1)
|
|
->whereDate('vencimiento', '<=', $this->fecha_final_2)
|
|
->where('servicio_id', $servicio_tarifa->id)
|
|
->where('estado', 'pendiente')
|
|
->where(function ($query) {
|
|
$query->doesntHave('perfil')
|
|
->orWhereHas('perfil', function ($query) {
|
|
$query->whereNull('historial_id');
|
|
});
|
|
})
|
|
->count();
|
|
} else {
|
|
$cantidad_solicitada = (int) $this->cantidad_tarjetaPlan * (int) $this->pantallas_tarjetaPlan;
|
|
$cantidad_restante = $servicio_tarifa->pantallas - $cantidad_solicitada;
|
|
|
|
//Traer todas las cuentas por pantalla 'activo' de los ultimos 15 dias. solo disponibles
|
|
$baseQuery = Cuentas::select('*')->whereDate('inicio', '>=', $this->fecha)
|
|
->whereDate('vencimiento', '>=', $this->fecha_final_1)
|
|
->whereDate('vencimiento', '<=', $this->fecha_final_2)
|
|
->where('servicio_id', $servicio_tarifa->id)
|
|
->where('estado', 'activo')
|
|
->withCount('historiales')
|
|
->where('estado', 'activo');
|
|
|
|
$cuentas_pantallas = Cuentas::fromSub($baseQuery, 'alias')
|
|
->where('historiales_count', '<=', $cantidad_restante)
|
|
->orderBy('inicio', 'ASC')
|
|
->lockForUpdate()
|
|
->get();
|
|
|
|
|
|
|
|
//dd($cuentas_pantallas); // con count da un numero entero
|
|
|
|
$cuentas_pantallas_tomadas = Historial_cuenta::whereIn('cuenta_id', $cuentas_pantallas
|
|
->pluck('id'))->whereNotNull('historial_id')
|
|
->count();
|
|
//dd($cuentas_pantallas_tomadas);
|
|
//Validar si el numero pantallas del servicio es igual o mayor que lo solicitado
|
|
|
|
if ($servicio_tarifa->pantallas >= $cantidad_solicitada) {
|
|
//dd($servicio_tarifa->pantallas * $cuentas_pantallas->count());
|
|
//Cantidad de cuentas restantes * cantidad de pantallas del servicio / en las pantalla de la tarifa.
|
|
$this->disponibles = (($cuentas_pantallas->count() * $servicio_tarifa->pantallas) - $cuentas_pantallas_tomadas) / $tarifa_seleccionada->pantallas;
|
|
//dd($this->disponibles) ;
|
|
} else {
|
|
$this->disponibles = $cuentas_pantallas;
|
|
}
|
|
}
|
|
|
|
//dd($this->tarjetaPlan);
|
|
$this->tarjetaPlan = true;
|
|
}
|
|
|
|
public function cerrartarjetaPlan()
|
|
{
|
|
$this->cantidad_tarjetaPlan = 1;
|
|
$this->tarjetaPlan = false;
|
|
$this->tarifa_id = '';
|
|
}
|
|
|
|
public function notificacionPocas($servicio, $restantes)
|
|
{
|
|
$roles = Role::where('nombre', 'super')->with('usuarios')->first();
|
|
$user = $roles->usuarios;
|
|
|
|
$notificacion = [
|
|
'servicio' => $servicio->nombre,
|
|
'cantidad' => $restantes,
|
|
'tipo' => 'cuentas normales',
|
|
];
|
|
|
|
Notification::send($user, (new licencias($notificacion)));
|
|
}
|
|
|
|
/* ---------------- Btn Comprar ---------------- */
|
|
public function comprar()
|
|
{
|
|
$maxIntentos = 3; // cantidad de veces que se intentará
|
|
$intento = 0;
|
|
|
|
while ($intento < $maxIntentos) {
|
|
|
|
DB::beginTransaction();
|
|
try {
|
|
|
|
$intento++;
|
|
$this->validate([
|
|
'cantidad_tarjetaPlan' => 'required|numeric|min:1',
|
|
]);
|
|
|
|
if ($this->cantidad_tarjetaPlan == 0) {
|
|
$this->alert('error', 'La cantidad debe ser mayor a 0', [
|
|
'position' => 'top'
|
|
]);
|
|
return;
|
|
}
|
|
|
|
if (auth()->user()->saldo->valor < $this->valor_tarjetaPlan * $this->cantidad_tarjetaPlan) {
|
|
$this->alert('error', 'Saldo insuficiente', [
|
|
'position' => 'top'
|
|
]);
|
|
return;
|
|
}
|
|
|
|
$cantidad_solicitada = (int) $this->cantidad_tarjetaPlan * (int) $this->pantallas_tarjetaPlan;
|
|
$total_valor = (int) $this->valor_tarjetaPlan * (int) $this->cantidad_tarjetaPlan;
|
|
$utilidad_total = (int) $this->utilidad * (int) $this->cantidad_tarjetaPlan;
|
|
|
|
$usuario_existe = User::firstWhere('email', $this->email_tarjetaPlan)->id ?? null;
|
|
$usuario_id = $usuario_existe;
|
|
|
|
if (is_null($usuario_existe)) {
|
|
$usuario = new User;
|
|
$usuario->name = $this->nombre_tarjetaPlan;
|
|
$usuario->email = $this->email_tarjetaPlan;
|
|
$usuario->password = '123';
|
|
$usuario->celular = '+57' . $this->celular_tarjetaPlan;
|
|
$usuario->save();
|
|
|
|
$usuario_id = $usuario->id;
|
|
}
|
|
//dd($this->fechaFinal);
|
|
$historial = new Historiale;
|
|
$historial->fecha_inicio = Carbon::now();
|
|
$historial->fecha_final = $this->fechaFinal;
|
|
$historial->valor = $total_valor;
|
|
$historial->tipo_pago = 'manual';
|
|
$historial->estado = 'pendiente';
|
|
$historial->vendedor_id = Auth()->user()->id;
|
|
$historial->tarifa_id = $this->tarifa_id;
|
|
$historial->cliente_id = $usuario_id;
|
|
$historial->cantidad = $this->cantidad_tarjetaPlan;
|
|
$historial->nombre_cliente = $this->nombre_tarjetaPlan;
|
|
$historial->utilidad = $utilidad_total;
|
|
$historial->save();
|
|
|
|
$pantallas = Tarifas::where('id', $this->tarifa_id)->with('servicio')->first();
|
|
|
|
|
|
$servicioNombre = $pantallas->servicio->nombre;
|
|
$servicio_id = $pantallas->servicio_id;
|
|
$pantalla_servicio_completa = $pantallas->servicio->completa;
|
|
$pantalla_servicio = $pantallas->servicio->pantallas;
|
|
|
|
$pantallas = $pantallas->pantallas ?? null;
|
|
|
|
|
|
if ((int) $pantalla_servicio >= (int) $cantidad_solicitada && (int) $pantalla_servicio_completa != (int) $this->pantallas_tarjetaPlan) {
|
|
//dd('soy este');
|
|
$suma = $pantalla_servicio - $cantidad_solicitada;
|
|
$cantidad_necesaria = $this->cantidad_tarjetaPlan;
|
|
|
|
$baseQuery = Cuentas::select('*')
|
|
->where('servicio_id', $this->servicio_id)
|
|
->whereDate('inicio', '>=', $this->fecha)
|
|
->whereDate('vencimiento', '>=', $this->fecha_final_1)
|
|
->whereDate('vencimiento', '<=', $this->fecha_final_2)
|
|
->where('estado', 'activo')
|
|
->withCount('historiales')
|
|
->orderBy('inicio', 'ASC');
|
|
|
|
$cuenta = Cuentas::fromSub($baseQuery, 'alias')
|
|
->where('historiales_count', '<=', $suma)
|
|
->orderBy('inicio', 'ASC')
|
|
->lockForUpdate()
|
|
->get();
|
|
|
|
|
|
|
|
if ($cuenta->isEmpty()) {
|
|
$suma3 = $pantalla_servicio - $pantallas;
|
|
$cantidad_necesaria = $this->cantidad_tarjetaPlan;
|
|
$baseQuery = Cuentas::select('*')->where('servicio_id', $this->servicio_id)
|
|
->whereDate('inicio', '>=', $this->fecha)
|
|
->whereDate('vencimiento', '>=', $this->fecha_final_1)
|
|
->whereDate('vencimiento', '<=', $this->fecha_final_2)
|
|
->withCount('historiales')
|
|
->where('estado', 'activo')
|
|
->Orderby('inicio', 'ASC');
|
|
|
|
|
|
$cuenta = Cuentas::fromSub($baseQuery, 'alias')
|
|
->where('historiales_count', '<=', $suma3)
|
|
->orderBy('inicio', 'ASC')
|
|
->lockForUpdate()
|
|
->get();
|
|
}
|
|
} elseif ((int) $pantalla_servicio_completa == (int) $this->pantallas_tarjetaPlan) {
|
|
|
|
//Cuentas completas
|
|
$cantidad_necesaria = $this->cantidad_tarjetaPlan;
|
|
$cuenta = Cuentas::where('servicio_id', $this->servicio_id)
|
|
->whereDate('vencimiento', '>=', $this->fecha_final_1)
|
|
->whereDate('vencimiento', '<=', $this->fecha_final_2)
|
|
->Orderby('inicio', 'ASC')
|
|
->withCount('historiales')
|
|
->where('estado', 'pendiente')
|
|
->doesntHave('perfil')
|
|
->get();
|
|
} elseif ((int) $pantalla_servicio < (int) $cantidad_solicitada) {
|
|
|
|
$suma2 = $pantalla_servicio - $pantallas;
|
|
$cantidad_necesaria = $this->cantidad_tarjetaPlan;
|
|
$baseQuery = Cuentas::select('*')->where('servicio_id', $this->servicio_id)
|
|
->whereDate('inicio', '>=', $this->fecha)
|
|
->whereDate('vencimiento', '>=', $this->fecha_final_1)
|
|
->whereDate('vencimiento', '<=', $this->fecha_final_2)
|
|
->Orderby('inicio', 'ASC')
|
|
->withCount('historiales')
|
|
->where('estado', 'activo');
|
|
|
|
$cuenta = Cuentas::fromSub($baseQuery, 'alias')
|
|
->where('historiales_count', '<=', $suma2)
|
|
->orderBy('inicio', 'ASC')
|
|
->lockForUpdate()
|
|
->get();
|
|
} else {
|
|
$cuenta = null;
|
|
$cantidad_necesaria = null;
|
|
}
|
|
|
|
$cuentasMostar = '';
|
|
for ($h = 0; $h < (int) $cantidad_necesaria; $h++) {
|
|
|
|
|
|
if (!empty($cuenta) && isset($cuenta[$h])) {
|
|
$esta_error = false;
|
|
$cuentasMostar = '';
|
|
|
|
// Bloquear la fila de la cuenta para leer el conteo real dentro de la transacción
|
|
$cuentaLocked = Cuentas::where('id', $cuenta[$h]->id)->lockForUpdate()->first();
|
|
$perfil = Historial_cuenta::where('cuenta_id', $cuentaLocked->id)->max('perfil') ?? 0;
|
|
|
|
// Verificar que aún hay espacio real ANTES de insertar (protección contra race condition)
|
|
$perfilesOcupados = Historial_cuenta::where('cuenta_id', $cuentaLocked->id)
|
|
->whereHas('historial', fn($q) => $q->where('estado', 'activo'))
|
|
->count();
|
|
|
|
$maxPerfiles = ($cuentaLocked->estado === 'pendiente')
|
|
? ($cuentaLocked->servicio->completa ?? $pantallas)
|
|
: ($cuentaLocked->servicio->pantallas ?? $pantallas);
|
|
|
|
if (($perfilesOcupados + (int) $pantallas) > $maxPerfiles) {
|
|
$esta_error = true;
|
|
$historial->update(['estado' => 'cancelado']);
|
|
Historial_cuenta::where('historial_id', $historial->id)->delete();
|
|
$logsGeneral = new Log_general();
|
|
$logsGeneral->user_id = Auth::user()->id;
|
|
$logsGeneral->detalle = 'El usuario ' . Auth::user()->name . ' - ' . Auth::user()->email . ' Tuvo error de concurrencia: la cuenta ' . $cuentaLocked->correo . ' ya estaba llena al momento de insertar el perfil. Compra cancelada automáticamente. Servicio: ' . $servicioNombre;
|
|
$logsGeneral->tipo = 'compra_error';
|
|
$logsGeneral->historial_id = $historial->id;
|
|
$logsGeneral->save();
|
|
DB::rollBack();
|
|
$this->alert('warning', 'No hay perfiles disponibles, intenta nuevamente!', [
|
|
'position' => 'top'
|
|
]);
|
|
return;
|
|
}
|
|
|
|
for ($y = 0; $y < (int) $pantallas; $y++) {
|
|
|
|
$historial_cuenta = new Historial_cuenta;
|
|
$historial_cuenta->cuenta_id = $cuentaLocked->id;
|
|
$historial_cuenta->historial_id = $historial->id;
|
|
$historial_cuenta->perfil = (int) $perfil + (int) $y + 1;
|
|
$historial_cuenta->save();
|
|
|
|
if ($cuentaLocked->correo != $cuentasMostar) {
|
|
$cuentasMostar .= $cuentaLocked->correo . ' ';
|
|
}
|
|
}
|
|
} else {
|
|
$esta_error = true;
|
|
$historial->update(['estado' => 'cancelado']);
|
|
$eliminar = Historial_cuenta::where('historial_id', $historial->id)->delete();
|
|
$logsGeneral = new Log_general();
|
|
$logsGeneral->user_id = Auth::user()->id;
|
|
$logsGeneral->detalle = 'El usuario ' . Auth::user()->name . ' - ' . Auth::user()->email . ' Tuvo error de "No hay cuentas disponibles" Comprando el servicio ' . $servicioNombre . ' - ' . $cuentasMostar . ' cantidad de ' . $this->cantidad_tarjetaPlan . ' por un valor de $' . $total_valor . ' Se desligaron todas las cuentas.';
|
|
$logsGeneral->tipo = 'compra_error';
|
|
$logsGeneral->historial_id = $historial->id;
|
|
$logsGeneral->save();
|
|
$this->alert('warning', 'No hay cuentas disponibles!', [
|
|
'position' => 'top'
|
|
]);
|
|
break;
|
|
}
|
|
}
|
|
if (!$esta_error && !empty($historial->cuentas)) {
|
|
$descuento = Saldo::where('usuario_id', Auth::user()->id)->first();
|
|
|
|
$saldo_anterior = $descuento->valor ?? 0;
|
|
$nuevo_saldo = $saldo_anterior - $total_valor;
|
|
$cobro = $descuento->update(['valor' => $nuevo_saldo]);
|
|
if ($cobro) {
|
|
|
|
$historial->update(['estado' => 'activo']);
|
|
|
|
// Si el campo subvendedor tiene id entonces la utilidad va a su subvendedor padre
|
|
if (Auth::user()->subvendedor_id) {
|
|
if ($utilidad_total > 0) {
|
|
$subvendedorPadre = User::with('saldo')->find(Auth::user()->subvendedor_id);
|
|
|
|
if ($subvendedorPadre && $subvendedorPadre->saldo) {
|
|
// Sumar la utilidad al saldo actual
|
|
$nuevoSaldo = $subvendedorPadre->saldo->valor + $utilidad_total;
|
|
|
|
// Actualizar el saldo
|
|
$subvendedorPadre->saldo->update([
|
|
'valor' => $nuevoSaldo
|
|
]);
|
|
|
|
// Registrar en el log la utilidad generada
|
|
$logsGeneral = new Log_general();
|
|
$logsGeneral->user_id = Auth::user()->id;
|
|
$logsGeneral->detalle = 'El usuario ' . Auth::user()->name . ' - ' . Auth::user()->email .
|
|
' ha comprado el servicio ' . $servicioNombre . ' - ' . $cuentasMostar .
|
|
' cantidad de ' . $this->cantidad_tarjetaPlan .
|
|
' por un valor de $' . $total_valor .
|
|
', Saldo anterior: $' . $saldo_anterior .
|
|
', Nuevo saldo disponible: $' . $nuevo_saldo .
|
|
'. Esta compra generó una utilidad de $' . $utilidad_total .
|
|
' al usuario padre ' . $subvendedorPadre->name . ' - ' . $subvendedorPadre->email . '.';
|
|
$logsGeneral->historial_id = $historial->id;
|
|
$logsGeneral->tipo = 'compra';
|
|
$logsGeneral->save();
|
|
}
|
|
}
|
|
} else {
|
|
// Log sin utilidad al padre
|
|
$logsGeneral = new Log_general();
|
|
$logsGeneral->user_id = Auth::user()->id;
|
|
$logsGeneral->detalle = 'El usuario ' . Auth::user()->name . ' - ' . Auth::user()->email .
|
|
' ha comprado el servicio ' . $servicioNombre . ' - ' . $cuentasMostar .
|
|
' cantidad de ' . $this->cantidad_tarjetaPlan .
|
|
' por un valor de $' . $total_valor .
|
|
', Saldo anterior: $' . $saldo_anterior .
|
|
', Nuevo saldo disponible: $' . $nuevo_saldo . '.';
|
|
$logsGeneral->historial_id = $historial->id;
|
|
$logsGeneral->tipo = 'compra';
|
|
$logsGeneral->save();
|
|
}
|
|
|
|
$this->credenciales($historial);
|
|
} else {
|
|
$historial->update(['estado' => 'cancelado']);
|
|
$logsGeneral = new Log_general();
|
|
$logsGeneral->user_id = Auth::user()->id;
|
|
$logsGeneral->detalle = 'El usuario ' . Auth::user()->name . ' - ' . Auth::user()->email . ' Tuvo un error con el cobro del servicio ' . $servicioNombre . ' - ' . $cuentasMostar . ' cantidad de ' . $this->cantidad_tarjetaPlan . ' por un valor de $' . $total_valor;
|
|
$logsGeneral->tipo = 'compra_error';
|
|
$logsGeneral->historial_id = $historial->id;
|
|
$logsGeneral->save();
|
|
$eliminar = Historial_cuenta::where('historial_id', $historial->id)->delete();
|
|
$this->alert('warning', 'Error en el cobro, comuniquese con soporte!', [
|
|
'position' => 'top'
|
|
]);
|
|
}
|
|
} else {
|
|
|
|
$eliminar = Historial_cuenta::where('historial_id', $historial->id)->delete();
|
|
$logsGeneral = new Log_general();
|
|
$logsGeneral->user_id = Auth::user()->id;
|
|
$logsGeneral->detalle = 'El usuario ' . Auth::user()->name . ' - ' . Auth::user()->email . ' Tuvo error de "No hay cuentas disponibles" Comprando el servicio ' . $servicioNombre . ' - ' . $cuentasMostar . ' cantidad de ' . $this->cantidad_tarjetaPlan . ' por un valor de $' . $total_valor . ' No se desconto el saldo, ni se asignaron cuentas.';
|
|
$logsGeneral->tipo = 'compra_error';
|
|
$logsGeneral->historial_id = $historial->id;
|
|
$logsGeneral->save();
|
|
$this->alert('warning', 'No hay cuentas disponibles!', [
|
|
'position' => 'top'
|
|
]);
|
|
}
|
|
|
|
|
|
// Verificar si hay perfiles duplicados en historial_cuenta recién creados
|
|
$perfilesDuplicados = Historial_cuenta::select('cuenta_id', 'perfil')
|
|
->where('historial_id', $historial->id)
|
|
->groupBy('cuenta_id', 'perfil')
|
|
->havingRaw('COUNT(*) > 1')
|
|
->get();
|
|
|
|
if ($perfilesDuplicados->isNotEmpty()) {
|
|
// Eliminar historial_cuenta
|
|
Historial_cuenta::where('historial_id', $historial->id)->delete();
|
|
|
|
// Cancelar historial
|
|
$historial->update(['estado' => 'cancelado']);
|
|
|
|
// Registrar en log_general
|
|
$detalleError = 'El usuario ' . Auth::user()->name . ' - ' . Auth::user()->email
|
|
. ' tuvo un error por perfiles duplicados en la compra del servicio '
|
|
. $servicioNombre . ' - ' . $cuentasMostar
|
|
. ', cantidad de ' . $this->cantidad_tarjetaPlan
|
|
. ', valor: $' . $total_valor
|
|
. '. Se canceló la operación y se eliminaron los perfiles duplicados.';
|
|
|
|
$logsGeneral = new Log_general();
|
|
$logsGeneral->user_id = Auth::user()->id;
|
|
$logsGeneral->detalle = $detalleError;
|
|
$logsGeneral->tipo = 'compra_error';
|
|
$logsGeneral->historial_id = $historial->id;
|
|
$logsGeneral->save();
|
|
|
|
$this->alert('warning', 'Error: Se detectaron perfiles duplicados. Se canceló la compra.', [
|
|
'position' => 'top'
|
|
]);
|
|
|
|
// Salir antes de confirmar la transacción
|
|
DB::rollBack();
|
|
return;
|
|
}
|
|
|
|
|
|
DB::commit();
|
|
|
|
$this->tarjetaPlan = false;
|
|
$this->cantidad_tarjetaPlan = 1;
|
|
|
|
// si todo salió bien → salir del bucle
|
|
break;
|
|
} catch (QueryException $e) {
|
|
DB::rollBack();
|
|
|
|
// PostgreSQL/MariaDB lanza 23505 cuando hay conflicto de índice único
|
|
if ($e->getCode() == '23505') {
|
|
// ⚡ Reintentar, otra transacción tomó la misma cuenta
|
|
if ($intento >= $maxIntentos) {
|
|
$this->alert('warning', 'Error: Otra persona tomó la cuenta al mismo tiempo. Intenta nuevamente.', [
|
|
'position' => 'top'
|
|
]);
|
|
return;
|
|
}
|
|
|
|
usleep(200000); // 200ms antes de reintentar
|
|
continue;
|
|
}
|
|
|
|
// Otros errores no son de concurrencia
|
|
$this->alert('error', 'Error inesperado en la compra: ' . $e->getMessage(), [
|
|
'position' => 'top'
|
|
]);
|
|
return;
|
|
} catch (\Throwable $e) {
|
|
DB::rollBack();
|
|
|
|
$this->alert('error', 'Error inesperado: ' . $e->getMessage(), [
|
|
'position' => 'top'
|
|
]);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
public function credenciales($historial)
|
|
{
|
|
$this->cuentas = $historial;
|
|
|
|
$this->credenciales = true;
|
|
|
|
$encryptado = Crypt::encryptString($historial->id);
|
|
$enlace = '/credenciales?id=' . $encryptado;
|
|
|
|
|
|
$user = $historial->cliente;
|
|
|
|
$notificacion = [
|
|
'enlace' => $enlace,
|
|
'fecha_final' => $historial->fecha_final,
|
|
'cliente' => $historial->cliente->name,
|
|
'servicio' => $historial->tarifa->servicio->nombre . '-' . $historial->tarifa->pantallas . 'pantallas',
|
|
'tipo' => 'compra',
|
|
'vendedor' => auth()->user()->username,
|
|
|
|
];
|
|
|
|
Notification::send($user, (new compra($notificacion)));
|
|
|
|
|
|
$this->alert('success', 'Credenciales enviadas a su email!', [
|
|
'position' => 'top'
|
|
]);
|
|
|
|
$shortURLObject = ShortURL::destinationUrl('https://app.sirpremium.com.co' . $enlace)->make();
|
|
$shortURL = $shortURLObject->default_short_url;
|
|
$message = $historial->tarifa->servicio->nombre . '-' . $historial->tarifa->pantallas . 'P. Ver credenciales: ' . $shortURL;
|
|
$recipients = '+57' . $this->celular_tarjetaPlan;
|
|
|
|
//$this->sendMessage($message, $recipients);
|
|
}
|
|
|
|
public function sendMessage($message, $recipients)
|
|
{
|
|
|
|
$auth_basic = base64_encode('admin@jaguarws.ga:9u3xxXhHt8maeiOexg07pFKI0rpYazI0');
|
|
|
|
$curl = curl_init();
|
|
|
|
curl_setopt_array(
|
|
$curl,
|
|
array(
|
|
CURLOPT_URL => "https://api.labsmobile.com/json/send",
|
|
CURLOPT_RETURNTRANSFER => true,
|
|
CURLOPT_ENCODING => "",
|
|
CURLOPT_MAXREDIRS => 10,
|
|
CURLOPT_TIMEOUT => 30,
|
|
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
|
|
CURLOPT_CUSTOMREQUEST => "POST",
|
|
CURLOPT_POSTFIELDS => '{"message":"' . $message . '", "tpoa":"Sender","recipient":[{"msisdn":"' . $recipients . '"}]}',
|
|
CURLOPT_HTTPHEADER => array(
|
|
"Authorization: Basic " . $auth_basic,
|
|
"Cache-Control: no-cache",
|
|
"Content-Type: application/json"
|
|
),
|
|
)
|
|
);
|
|
|
|
$response = curl_exec($curl);
|
|
$err = curl_error($curl);
|
|
|
|
curl_close($curl);
|
|
|
|
if ($err) {
|
|
|
|
$this->alert('warning', 'Error enviando SMS!' . $err, [
|
|
'position' => 'top'
|
|
]);
|
|
} else {
|
|
if (!empty(json_decode($response)->subid)) {
|
|
$this->alert('success', 'Credenciales enviadas por Email y SMS! ' . json_decode($response)->subid, [
|
|
'position' => 'top'
|
|
]);
|
|
} else {
|
|
$this->alert('success', 'Credenciales enviadas por Email! ' . json_decode($response)->code, [
|
|
'position' => 'top'
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
|
|
public function consultaTarifa($servicio1)
|
|
{
|
|
$this->servicio = $servicio1;
|
|
$this->verServ = false;
|
|
}
|
|
}
|