'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('updated_at', 'desc') ->get(); 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 $cuentas_pantallas = 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', 'activo') //->with('perfil') //->whereDoesntHave('perfil', function ($query) use ($cantidad_restante) { // $query->select('cuenta_id') // ->groupBy('cuenta_id') // ->havingRaw("COUNT(*) >= $cantidad_restante"); //}) ->withCount('historiales') ->where('estado', 'activo') ->having('historiales_count', '<=', $cantidad_restante) ->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() { $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) { $suma = $pantalla_servicio - $cantidad_solicitada; $cantidad_necesaria = $this->cantidad_tarjetaPlan; $cuenta = Cuentas::where('servicio_id', $this->servicio_id) ->whereDate('inicio', '>=', $this->fecha) ->whereDate('vencimiento', '>=', $this->fecha_final_1) ->whereDate('vencimiento', '<=', $this->fecha_final_2) // ->whereDate('vencimiento','>=', $this->fechaFinal) ->Orderby('inicio', 'ASC') ->withCount('historiales') ->where('estado', 'activo') ->having('historiales_count', '<=', $suma) //->with('perfil') //->whereDoesntHave('perfil', function ($query) use ($suma) { // $query->select('cuenta_id') // ->groupBy('cuenta_id') // ->havingRaw("COUNT(*) >= $suma"); //}) ->get(); if ($cuenta->isEmpty()) { $suma3 = $pantalla_servicio - $pantallas; $cantidad_necesaria = $this->cantidad_tarjetaPlan; $cuenta = Cuentas::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') ->having('historiales_count', '<=', $suma3) //->with('perfil') //->whereDoesntHave('perfil', function ($query) use ($suma2) { //$query->select('cuenta_id') // ->groupBy('cuenta_id') // ->havingRaw("COUNT(*) >= $suma2"); //}) ->get(); } // dd($cuenta); } 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('inicio', '>=', $this->fecha) ->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; $cuenta = Cuentas::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') ->having('historiales_count', '<=', $suma2) //->with('perfil') //->whereDoesntHave('perfil', function ($query) use ($suma2) { //$query->select('cuenta_id') // ->groupBy('cuenta_id') // ->havingRaw("COUNT(*) >= $suma2"); //}) ->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 = ''; $perfil = $cuenta[$h]->historiales_count; for ($y = 0; $y < (int) $pantallas; $y++) { $historial_cuenta = new Historial_cuenta; $historial_cuenta->cuenta_id = $cuenta[$h]->id; $historial_cuenta->historial_id = $historial->id; $historial_cuenta->perfil = (int) $perfil + (int) $y + 1; $historial_cuenta->save(); if ($cuenta[$h]->correo != $cuentasMostar) { $cuentasMostar .= $cuenta[$h]->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->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']); $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->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->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->save(); $this->alert('warning', 'No hay cuentas disponibles!', [ 'position' => 'top' ]); } $this->tarjetaPlan = false; $this->cantidad_tarjetaPlan = 1; } 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; } }