Initial commit

This commit is contained in:
lizandrogd
2023-07-26 08:28:13 -05:00
commit 8ce210f27c
1207 changed files with 36066 additions and 0 deletions
+144
View File
@@ -0,0 +1,144 @@
<?php
namespace App\Console;
use App\Models\Historiale;
use App\Models\Servicio;
use App\Models\User;
use App\Models\Cuentas;
use App\Models\log;
use App\Models\Configuracione;
use App\Models\Historial_cuenta;
use App\Notifications\Vencimiento;
use Carbon\Carbon;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Exception;
use Illuminate\Support\Facades\Notification;
use Twilio\Rest\Client;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->exec('nohup php /home/u111286300/domains/sirpremium.com.co/public_html/app/artisan queue:work --sleep=3 --tries=3 > /dev/null 2>&1 &')->everyMinute();
$schedule->call(function () {
$fechaHoy = Carbon::now();
$fechaManana = $fechaHoy->copy()->addDay(); // Obtenemos la fecha de mañana sumando un día a la fecha actual
$consulta_historial = Historiale::whereDate('fecha_final', $fechaManana)->with('cliente')->get();
foreach ($consulta_historial as $item) {
$user = User::find($item->cliente->id);
if (!empty($item->promocion_id)) {
$nombre= $item->promocion->nombre;
}
if (!empty($item->tarifa_id)) {
$nombre = $item->tarifa->servicio->nombre . '-' . $item->tarifa->pantallas . 'P';
}
$notificacion = [
//'valor' => $value['precio'],
'fecha_final' => $item->fecha_final,
'cliente' => $item->cliente->name,
'servicio' => $nombre,
'tipo' => 'vencimiento',
'vendedor' =>$item->vendedor->name,
];
Notification::sendNow($user, new Vencimiento($notificacion));
//$fecha=Carbon::parse($item->fecha_final)->format('d/m/Y');
//$message = 'Su '.$nombre.', Vence Hoy, '.$fecha.'. Renueva ahora!!' ;
//$recipients= '+57'.$item->cliente->celular;
//$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);
//return $response;
// if ($err) {
//
//} else {
//
//}
}
$fechaHoy1 = Carbon::now();
$fechaHoy1 = Carbon::parse($fechaHoy1)->subDay(1);
$consulta_historial1= Historiale::whereDate('fecha_final','<',$fechaHoy1)->with('cliente','cuentas')->get();
foreach ($consulta_historial1 as $item1) {
foreach($item1->cuentas->unique() as $item2){
//dd($item2);
$logs = new log;
$logs->historial_id = $item1->id;
$logs->cuenta_id = $item2->id;
$logs->save();
}
//$eliminar_cuentas = Historial_cuenta::where('historial_id',$item1->id)->truncate();
//dd('termine');
}
})->dailyAt(Configuracione::orderby('id','desc')->first()->hora);
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of exception types with their corresponding custom log levels.
*
* @var array<class-string<\Throwable>, \Psr\Log\LogLevel::*>
*/
protected $levels = [
//
];
/**
* A list of the exception types that are not reported.
*
* @var array<int, class-string<\Throwable>>
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed to the session on validation exceptions.
*
* @var array<int, string>
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->reportable(function (Throwable $e) {
//
});
}
}
@@ -0,0 +1,54 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthenticatedSessionController extends Controller
{
/**
* Display the login view.
*
* @return \Illuminate\View\View
*/
public function create()
{
return view('auth.login');
}
/**
* Handle an incoming authentication request.
*
* @param \App\Http\Requests\Auth\LoginRequest $request
* @return \Illuminate\Http\RedirectResponse
*/
public function store(LoginRequest $request)
{
$request->authenticate();
$request->session()->regenerate();
return redirect()->intended(RouteServiceProvider::HOME);
}
/**
* Destroy an authenticated session.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy(Request $request)
{
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}
@@ -0,0 +1,44 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
class ConfirmablePasswordController extends Controller
{
/**
* Show the confirm password view.
*
* @return \Illuminate\View\View
*/
public function show()
{
return view('auth.confirm-password');
}
/**
* Confirm the user's password.
*
* @param \Illuminate\Http\Request $request
* @return mixed
*/
public function store(Request $request)
{
if (! Auth::guard('web')->validate([
'email' => $request->user()->email,
'password' => $request->password,
])) {
throw ValidationException::withMessages([
'password' => __('auth.password'),
]);
}
$request->session()->put('auth.password_confirmed_at', time());
return redirect()->intended(RouteServiceProvider::HOME);
}
}
@@ -0,0 +1,27 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
class EmailVerificationNotificationController extends Controller
{
/**
* Send a new email verification notification.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse
*/
public function store(Request $request)
{
if ($request->user()->hasVerifiedEmail()) {
return redirect()->intended(RouteServiceProvider::HOME);
}
$request->user()->sendEmailVerificationNotification();
return back()->with('status', 'verification-link-sent');
}
}
@@ -0,0 +1,23 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
class EmailVerificationPromptController extends Controller
{
/**
* Display the email verification prompt.
*
* @param \Illuminate\Http\Request $request
* @return mixed
*/
public function __invoke(Request $request)
{
return $request->user()->hasVerifiedEmail()
? redirect()->intended(RouteServiceProvider::HOME)
: view('auth.verify-email');
}
}
@@ -0,0 +1,65 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules;
class NewPasswordController extends Controller
{
/**
* Display the password reset view.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\View\View
*/
public function create(Request $request)
{
return view('auth.reset-password', ['request' => $request]);
}
/**
* Handle an incoming new password request.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse
*
* @throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request)
{
$request->validate([
'token' => ['required'],
'email' => ['required', 'email'],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$status = Password::reset(
$request->only('email', 'password', 'password_confirmation', 'token'),
function ($user) use ($request) {
$user->forceFill([
'password' => Hash::make($request->password),
'remember_token' => Str::random(60),
])->save();
event(new PasswordReset($user));
}
);
// If the password was successfully reset, we will redirect the user back to
// the application's home authenticated view. If there is an error we can
// redirect them back to where they came from with their error message.
return $status == Password::PASSWORD_RESET
? redirect()->route('login')->with('status', __($status))
: back()->withInput($request->only('email'))
->withErrors(['email' => __($status)]);
}
}
@@ -0,0 +1,47 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;
class PasswordResetLinkController extends Controller
{
/**
* Display the password reset link request view.
*
* @return \Illuminate\View\View
*/
public function create()
{
return view('auth.forgot-password');
}
/**
* Handle an incoming password reset link request.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse
*
* @throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request)
{
$request->validate([
'email' => ['required', 'email'],
]);
// We will send the password reset link to this user. Once we have attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$status = Password::sendResetLink(
$request->only('email')
);
return $status == Password::RESET_LINK_SENT
? back()->with('status', __($status))
: back()->withInput($request->only('email'))
->withErrors(['email' => __($status)]);
}
}
@@ -0,0 +1,54 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
class RegisteredUserController extends Controller
{
/**
* Display the registration view.
*
* @return \Illuminate\View\View
*/
public function create()
{
return view('auth.register');
}
/**
* Handle an incoming registration request.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse
*
* @throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request)
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
event(new Registered($user));
Auth::login($user);
return redirect(RouteServiceProvider::HOME);
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Auth\Events\Verified;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
class VerifyEmailController extends Controller
{
/**
* Mark the authenticated user's email address as verified.
*
* @param \Illuminate\Foundation\Auth\EmailVerificationRequest $request
* @return \Illuminate\Http\RedirectResponse
*/
public function __invoke(EmailVerificationRequest $request)
{
if ($request->user()->hasVerifiedEmail()) {
return redirect()->intended(RouteServiceProvider::HOME.'?verified=1');
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
}
return redirect()->intended(RouteServiceProvider::HOME.'?verified=1');
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
+683
View File
@@ -0,0 +1,683 @@
<?php
namespace App\Http\Controllers;
use App\Models\Configuracione;
use App\Models\Cuentas;
use App\Models\Historial_cuenta;
use App\Models\Historiale;
use App\Notifications\Vencimiento;
use Illuminate\Support\Facades\Crypt;
use App\Models\Promociones;
use App\Models\recarga;
use App\Models\Role;
use App\Models\Saldo;
use App\Models\slider;
use App\Models\Tarifas;
use App\Models\User;
use App\Notifications\compra;
use Carbon\Carbon;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Log;
use Exception;
use Twilio\Rest\Client;
use AshAllenDesign\ShortURL\Facades\ShortURL;
class MenuController extends Controller
{
public function showwelcome(){
$consulta_promociones = slider::get();
return view('welcome',[
'promociones' => $consulta_promociones,
]);
}
public function showclientes(){
return view('menu/clientes');
}
public function showservicios(){
return view('menu/servicios');
}
public function showtop(){
return view('menu/top');
}
public function showreportes(){
return view('menu/reportes');
}
public function showperfil(){
return view('menu/perfil');
}
public function showconfiguracion(){
return view('menu/configuracion');
}
public function showplanes(){
return view('menu/planes');
}
public function showusuarios(){
return view('menu/usuarios');
}
public function showadmin(){
return view('menu/admin');
}
public function showrecarga(){
return view('menu/recarga');
}
public function showcomprar(){
return view('menu/comprar');
}
public function showLogRecargas(){
return view('menu/logs_recargas');
}
public function showroles(){
return view('menu/roles');
}
public function pay($estado){
return view('menu/order',[
'estado' => $estado,
]);
}
public function showcredenciales(Request $request){
$credencial = Crypt::decryptString($request->id);
$consulta_historiales = Historiale::where('id',$credencial)->with('cuentas')->first();
$msj = Configuracione::orderby('id','desc')->select('msj_compra','msj_wp','clave_1','clave_2','clave_3','clave_4','clave_5','clave_6','iptv')->first();
return view('menu/credenciales',[
'consulta' =>$consulta_historiales,
'msj' => $msj,
]);
}
public function order( Request $request ){
$payment_id= $request->get('payment_id');
$response = Http::get("https://api.mercadopago.com/v1/payments/$payment_id" . "?access_token=APP_USR-7353579040069171-102716-58fdd1f52a604a1febd18a638227f603-260361439");
$response = json_decode($response);
$status = $response->status;
if ($status == 'approved') {
$metodo_pago = $response->payment_method_id;
$referencia = $response->external_reference;
$consulta = recarga::where('reference',$referencia)->where('status',$status)->exists();
if ($consulta == false){
$update_recargas = recarga::where('reference',$referencia)->update(['status' => $status,'payment_method_id'=> $metodo_pago]);
$recarga = recarga::where('reference',$referencia)->with('usuario')->first();
$usuario= $recarga->usuario;
$saldo = $usuario->saldo;
$saldo_anterior = $saldo->valor;
$rol = $usuario->rol->nombre;
$monto = $recarga->valor_recarga;
if (!empty($saldo_anterior)) {
$valor= (float)$saldo_anterior + (float)$monto ;
$nuevo_saldo = $saldo->update(['valor'=>$valor]);
}else{
$nuevo_saldo = $saldo->update(['valor'=>$monto]);
}
}
$estado= 'aprobado';
}elseif($status == 'pending'){
$metodo_pago = $response->payment_method_id;
$referencia = $response->external_reference;
$update_recargas = recarga::where('reference',$referencia)->update(['status' => $status,'payment_method_id'=> $metodo_pago]);
$usuario = recarga::where('reference',$referencia)->with('usuario')->first()->usuario;
$estado= 'pendiente';
}else{
$metodo_pago = $response->payment_method_id;
$referencia = $response->external_reference;
$update_recargas = recarga::where('reference',$referencia)->update(['status' => $status,'payment_method_id'=> $metodo_pago]);
$usuario = recarga::where('reference',$referencia)->with('usuario')->first()->usuario;
$estado ='rechazado';
};
return redirect()->route('pay',$estado);
}
public function showwebhooks(Request $request){
}
public function recargas(){
return view('menu/recargas');
}
public function showutilidad(){
return view('menu/utilidades');
}
public function showwompi($monto){
return view('menu/wompi',[
'monto' => $monto,
]);
}
public function showoferta(){
return view('portadaservicio');
}
public function showsingle(){
return view('menu/single');
}
public function showpromo(){
return view('menu/promo');
}
public function showlogs(){
return view('menu/logs');
}
public function showpromociones(){
return view('menu/promociones');
}
public function showimport(){
return view('menu/importar');
}
public function showcategoria(){
return view('menu/categoria');
}
public function showcategorias(){
return view('menu/ver');
}
public function showservicio(){
return view('menu/servicio');
}
public function compras( Request $request ){
$payment_id= $request->get('payment_id');
$response = Http::get("https://api.mercadopago.com/v1/payments/$payment_id" . "?access_token=APP_USR-7353579040069171-102716-58fdd1f52a604a1febd18a638227f603-260361439");
$response = json_decode($response);
$status = $response->status;
if ($status == 'approved') {
foreach($response->additional_info->items as $item){
$consulta = Historiale::where('id', $item->id)->first();
$tarifa_id=$consulta->tarifa_id;
}
$date = Carbon::now()->subDay(30);
$fecha= $date->format('Y-m-d');
//SERVICIO//
if (!empty($consulta->tarifa_id)) {
$pantallas = Tarifas::where('id', $tarifa_id)->with('servicio')->first();
$servicio_id= $pantallas->servicio_id;
$pantalla_servicio = $pantallas->servicio->pantallas;
$pantalla_servicio_completa = $pantallas->servicio->completa;
$pantallas= $pantallas ->pantallas ?? null;
$cantidad_tarjetaPlan = $consulta->cantidad;
$cantidad_solicitada = (int)$cantidad_tarjetaPlan*(int)$pantallas;
//dd($cantidad_tarjetaPlan);
if((int)$pantalla_servicio_completa >= (int)$cantidad_solicitada ){
$suma = $pantalla_servicio-$cantidad_solicitada;
$cuenta = Cuentas::where('servicio_id',$servicio_id)->whereDate('inicio','>=',$fecha)->Orderby('created_at', 'ASC')->withCount('historiales')->where('estado','activo')->having('historiales_count', '<=', $suma)->first();
}elseif((int)$pantalla_servicio_completa == (int)$cantidad_solicitada){
$this->fecha_final_1 = $today = Carbon::now()->addDays($pantallas->dias-15);
$this->fecha_final_2 = $today = Carbon::now()->addDays($pantallas->dias+15);
//completas
$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('created_at', 'ASC')->withCount('historiales')->where('estado','pendiente')->having('historiales_count', '==', 0)->first();
}else{
$cuenta=null;
}
if (!empty($cuenta) ) {
$perfil = $cuenta->historiales_count;
for ($n=1; $n <= $cantidad_solicitada ; $n++) {
$historial_cuenta = new Historial_cuenta();
$historial_cuenta->cuenta_id = $cuenta->id;
$historial_cuenta->historial_id = $item->id;
$historial_cuenta->perfil = (int)$perfil + (int)$n;
$historial_cuenta->save();
//dd($historial_cuenta->id);
}
if (($n-1) == $cantidad_solicitada) {
$consulta->update(['estado'=>'activo']);
$this->cred($consulta);
$encryptado = Crypt::encryptString($consulta->id);
//dd('llegue');
return redirect('/credenciales?id='.$encryptado);
}else{
return 'Error en la asignacion de cuentas, comuniquese con soporte!';
}
}else{
//dd($cuenta);
$suma2= $pantalla_servicio - $pantallas;
for ($h=0; $h < (int)$cantidad_tarjetaPlan ; $h++) {
//dd($n);
$cuenta = Cuentas::where('servicio_id',$servicio_id)->whereDate('inicio','>=',$fecha)->Orderby('created_at', 'ASC')->with('historiales')->withCount('historiales')->where('estado','activo')->having('historiales_count', '<=', (int)$suma2)->first();
//dd($cuenta);
if (!empty($cuenta)) {
$perfil = $cuenta->historiales_count;
for ($y=0; $y < (int)$pantallas ; $y++) {
//dd($pantallas);
$historial_cuenta = new Historial_cuenta;
$historial_cuenta->cuenta_id = $cuenta->id;
$historial_cuenta->historial_id = $item->id;
$historial_cuenta->perfil = (int)$perfil + (int)$y+1;
$historial_cuenta->save();
}
}else{
return 'No hay cuentas disponibles, comuniquese con soporte!';
}
}
$consulta->update(['estado'=>'activo']);
$this->cred($consulta);
$encryptado = Crypt::encryptString($consulta->id);
return redirect('/credenciales?id='.$encryptado);
}
}
//PROMOCION
if (!empty($consulta->promocion_id)){
for ($p = 0; $p < (int)$consulta->cantidad; $p++) {
//dd($this->cantidad_comprarPromo);
foreach ($consulta->promocion->tarifas as $tarifa) {
$pantallas_tarifa = $tarifa->pantallas;
$servicio_id = $tarifa->servicio_id;
$pantalla_servicio = $tarifa->servicio->pantallas;
$pantalla_servicio_completa = $tarifa->servicio->completa;
$faltante = $pantalla_servicio - $pantallas_tarifa;
if ($pantalla_servicio_completa == $pantallas_tarifa) {
$this->fecha_final_1 = $today = Carbon::now()->addDays($tarifa->dias-15);
$this->fecha_final_2 = $today = Carbon::now()->addDays($tarifa->dias+15);
$cuenta = Cuentas::where('servicio_id',$servicio_id)->whereDate('inicio','>=',$fecha)->whereDate('vencimiento','>=',$this->fecha_final_1)->whereDate('vencimiento','<=',$this->fecha_final_2)->Orderby('created_at', 'ASC')->with('historiales')->withCount('historiales')->where('estado','pendiente')->having('historiales_count', '==', 0)->first();
}else{
$cuenta = Cuentas::where('servicio_id', $servicio_id)->whereDate('inicio','>=',$fecha)->Orderby('created_at', 'ASC')->with('historiales')->withCount('historiales')->where('estado', 'activo')->having('historiales_count', '<=', (int)$faltante)->first();
}
//dd($tarifa);
if (!empty($cuenta)) {
$perfil = $cuenta->historiales_count;
for ($y = 0; $y < (int)$pantallas_tarifa; $y++) {
$historial_cuenta = new Historial_cuenta();
$historial_cuenta->cuenta_id = $cuenta->id;
$historial_cuenta->historial_id = $item->id;
$historial_cuenta->perfil = (int)$perfil + (int)$y+1;
$historial_cuenta->save();
}
} else {
return 'No hay cuentas disponibles, comuniquese con soporte!';
}
}
}
if (!empty($y)) {
$consulta->update(['estado'=>'activo']);
$this->cred($consulta);
$encryptado = Crypt::encryptString($consulta->id);
//dd('llegue');
return redirect('/credenciales?id='.$encryptado);
}else{
return 'No hay cuentas disponibles, comuniquese con soporte!';
}
}
}
}
//wompi
public function wompi_pagos(Request $request){
$response = Http::get("https://sandbox.wompi.co/v1/transactions/136099-1677473887-65588");
$response = json_decode($response);
//dd($response);
}
public function wompi_hook(Request $request){
//return json_encode('hola');
if (!empty($request)) {
foreach($request->data as $item ){
//return $item;
$status = $item['status'];
$user_id = $item['reference'];
$monto = substr($item['amount_in_cents'], 0, -2);
$metodo_pago = $item['payment_method_type'];
}
$update_recargas = recarga::where('reference',$referencia)->update(['status' => $status,'payment_method_id'=> $metodo_pago]);
if ($status == 'APPROVED') {
$usuario = recarga::where('reference',$referencia)->with('usuario')->first()->usuario;
$saldo = $usuario->saldo;
$saldo_anterior = $saldo->valor;
$rol = $usuario->rol->nombre;
//return $rol;
$monto_adicional = 0;
if ($rol == "super" || $rol == "administrador" || $rol == "distribuidor") {
$monto_adicional = 500;
}
if (!empty($saldo_anterior)) {
$valor= (float)$saldo_anterior + (float)$monto - (float)$monto_adicional;
$nuevo_saldo = $saldo->update(['valor'=>$valor]);
// return $nuevo_saldo;
}
}
}
}
public function cred($consulta){
$encryptado = Crypt::encryptString($consulta->id);
$enlace = '/credenciales?id='.$encryptado;
$user=User::find($consulta->cliente);
if (!empty($consulta->promocion_id)){ {
$shortURLObject = ShortURL::destinationUrl('https://app.sirpremium.com.co'.$enlace)->make();
$shortURL = $shortURLObject->default_short_url;
$message = $consulta->promocion->nombre.'. Ver credenciales: '.$shortURL ;
$recipients= '+57'.$consulta->cliente->celular;
$this->sendMessage($message, $recipients);
$notificacion = [
'enlace' => $enlace,
'fecha_final' => $consulta->fecha_final,
'cliente' => $consulta->cliente->name,
'servicio' => $consulta->promocion->nombre,
'tipo' => 'compra',
'vendedor' => Role::where('nombre','super')->first()->usuarios->first()->name,
];
}
if (!empty($consulta->tarifa_id)){
$shortURLObject = ShortURL::destinationUrl('https://app.sirpremium.com.co'.$enlace)->make();
$shortURL = $shortURLObject->default_short_url;
$message = $consulta->tarifa->servicio->nombre.'-'.$consulta->tarifa->pantallas. 'P. Ver credenciales: '.$shortURL ;
$recipients= '+57'.$consulta->cliente->celular;
$this->sendMessage($message, $recipients);
$notificacion = [
'enlace' => $enlace,
'fecha_final' => $consulta->fecha_final,
'cliente' => $consulta->cliente->name,
'servicio' => $consulta->tarifa->servicio->nombre.'-'.$consulta->tarifa->pantallas. 'pantallas',
'tipo' => 'compra',
'vendedor' => Role::where('nombre','super')->first()->usuarios->first()->name,
];
}
Notification::send($user, new compra($notificacion));
}
}
public function sendMessage($message, $recipients)
{
$auth_basic = base64_encode(getenv("USER_LABSMOBILE").':'.getenv("PASS_LABSMOBILE"));
$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) {
} else {
}
}
public function showmp(Request $request){
Log::info('MercadoPago webhook received', $request->all());
// Aquí puedes agregar la lógica para manejar las notificaciones de MercadoPago
$data = json_decode($request->getContent(), true);
$paymentId = $data['data']['id'];
$response = Http::get("https://api.mercadopago.com/v1/payments/$paymentId" . "?access_token=APP_USR-7353579040069171-102716-58fdd1f52a604a1febd18a638227f603-260361439");
//return $response;
$response = json_decode($response);
$status = $response->status;
if ($status == 'approved') {
$metodo_pago = $response->payment_method_id;
$referencia = $response->external_reference;
$consulta = recarga::where('reference',$referencia)->where('status',$status)->exists();
if ($consulta == false){
$update_recargas = recarga::where('reference',$referencia)->update(['status' => $status,'payment_method_id'=> $metodo_pago]);
$recarga = recarga::where('reference',$referencia)->with('usuario')->first();
$usuario= $recarga->usuario;
$saldo = $usuario->saldo;
$saldo_anterior = $saldo->valor;
$monto = $recarga->valor_recarga;
$valor= (float)$saldo_anterior + (float)$monto ;
$nuevo_saldo = $saldo->update(['valor'=>$valor]);
}
}
return response()->json(['status' => 'ok']);
}
public function pruebas (){
$fechaHoy = Carbon::now()->format('Y-m-d');
$consulta_historial = Historiale::whereDate('fecha_final', $fechaHoy)->with('cliente')->get();
foreach ($consulta_historial as $item) {
$user = User::find($item->cliente->id);
if (!empty($item->promocion_id)) {
$nombre= $item->promocion->nombre;
}
if (!empty($item->tarifa_id)) {
$nombre = $item->tarifa->servicio->nombre . '-' . $item->tarifa->pantallas . 'P';
}
$notificacion = [
//'valor' => $value['precio'],
'fecha_final' => $item->fecha_final,
'cliente' => $item->cliente->name,
'servicio' => $nombre,
'tipo' => 'vencimiento',
'vendedor' =>$item->vendedor->name,
];
Notification::sendNow($user, new Vencimiento($notificacion));
// $fecha=Carbon::parse($item->fecha_final)->format('d/m/Y');
//$message = 'Su '.$nombre.', Vence Hoy, '.$fecha.'. Renueva ahora!!' ;
//$recipients= '+57'.$item->cliente->celular;
//$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);
//return $response;
//if ($err) {
//} else {
//}
}
$fechaHoy1 = Carbon::now();
$fechaHoy1 = Carbon::parse($fechaHoy1)->subDay(1);
$consulta_historial1= Historiale::whereDate('fecha_final','<',$fechaHoy1)->with('cliente','cuentas')->get();
foreach ($consulta_historial1 as $item1) {
foreach($item1->cuentas->unique() as $item2){
//dd($item2);
$logs = new log;
$logs->historial_id = $item1->id;
$logs->cuenta_id = $item2->id;
$logs->save();
}
//$eliminar_cuentas = Historial_cuenta::where('historial_id',$item1->id)->truncate();
//dd('termine');
}
}
}
@@ -0,0 +1,217 @@
<?php
namespace App\Http\Controllers;
use DateInterval;
use DateTime;
use Exception;
use WpOrg\Requests\Requests;
use Illuminate\Support\Facades\Route;
use Twilio\Jwt\AccessToken;
use Twilio\Rest\Client;
class TwilioSMSController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
//auth2.0
$client_id=getenv("NEQUI_CLIENT_ID");
$client_secret=getenv("NEQUI_CLIENT_SECRET");
$api_key=getenv("NEQUI_API_KEY");
$endpoint=getenv("NEQUI_ENDPOINT");
//push
$RestEndpoint = '/payments/v2/-services-paymentservice-unregisteredpayment';
try{
$authorization = 'Basic ' . base64_encode($client_id . ':' . $client_secret);
$headers = array(
'Content-Type' => 'application/x-www-form-urlencoded',
'Accept' => 'application/json',
'Authorization' => $authorization
);
$request = Requests::post($endpoint, $headers);
if (
isset($request->status_code) && $request->status_code == 200
&& isset($request->body) && !empty($request->body)
) {
$response = json_decode($request->body);
$tokenExpiresAt = new DateTime();
$tokenExpiresAt->add(new DateInterval('PT' . $response->expires_in . 'S'));
$token = $response->access_token;
$tokenType = $response->token_type;
} else {
throw new Exception('Unable to connect to Nequi, please check the information sent.');
}
}catch(Exception $e){
throw $e;
}
// pago
$headers1 = array(
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'Authorization' => $token,
'x-api-key' => $api_key
);
$options = array(
'timeout' => 30
);
$endpoint1 = 'https://api.sandbox.nequi.com' . $RestEndpoint;
$body1 = json_encode(array(
'RequestMessage' => array(
'RequestHeader' => array(
'Channel' => 'PNP04-C001',
'RequestDate' => '2020-01-14T10:26:12.654Z',
'MessageID' => '1234567890',
'ClientID' => '12345',
'Destination' => array(
'ServiceName' => 'PaymentsService',
'ServiceOperation' => 'unregisteredPayment',
'ServiceRegion' => 'C001',
'ServiceVersion' => '1.2.0'
)
),
'RequestBody' => array(
'any' => array(
'unregisteredPaymentRQ' => array(
'phoneNumber'=> '3193590918',
'code' => 'NIT_1',
'value' => '1000',
'reference1' => 'Referencia numero 1',
'reference2' => 'Referencia numero 2',
'reference3' => 'Referencia numero 3'
)
)
)
)
));
$request1 = Requests::post($endpoint1, $headers1, $body1, $options);
if (
isset($request1->status_code) && $request1->status_code == 200
&& isset($request1->body) && !empty($request1->body)
) {
dd($request1);
try {
$response1 = json_decode($request->body);
$status = $response1->ResponseMessage->ResponseHeader->Status;
$statusCode = isset($status) ? $status->StatusCode : '';
$statusDesc = isset($status) ? $status->StatusDesc : '';
if ($statusCode == Constan::NEQUI_STATUS_CODE_SUCCESS) {
$payment = $response1->ResponseMessage->ResponseBody->any->unregisteredPaymentRS;
$trnId = isset($payment) ? trim($payment->transactionId) : '';
} else {
throw new Exception('Error ' . $statusCode . ' = ' . $statusDesc);
}
} catch (Exception $e) {
throw $e;
}
} else {
throw new Exception('Unable to connect to Nequi, please check the information sent.');
}
// $auth_basic = base64_encode("5ml5b35ijjk13f4q99utnsm97e:1b3703aq0o6t1rrfti13q7uf7f42glik3gsf81s0d783shblmt8l");
// $curl = curl_init();
// curl_setopt_array($curl, array(
// CURLOPT_URL => "https://oauth.sandbox.nequi.com/oauth2/token?grant_type=client_credentials",
// 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":"Text of the SMS message", "tpoa":"Sender","recipient":[{"msisdn":"573168950803"},{"msisdn":"573022548060"}]}',
// CURLOPT_HTTPHEADER => array(
// "Authorization: Basic ".$auth_basic,
// "Cache-Control: no-cache",
// "Content-Type: application/x-www-form-urlencoded"
// ),
// ));
// $response = curl_exec($curl);
// $err = curl_error($curl);
// curl_close($curl);
// if ($err) {
// echo "cURL Error #:" . $err;
// } else {
// echo $response;
// $AccessToken=json_decode($response)->access_token;
// //dd($AccessToken);
// $receiverNumber = "RECEIVER_NUMBER";
// $message = "All About Laravel";
// try {
// $auth_basic = base64_encode(getenv("USER_LABSMOBILE").':'.getenv("PASS_LABSMOBILE"));
// $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":"Text of the SMS message", "tpoa":"Sender","recipient":[{"msisdn":"573168950803"},{"msisdn":"573022548060"}]}',
// 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) {
// echo "cURL Error #:" . $err;
// } else {
// echo $response;
// }
//$account_sid = getenv("TWILIO_SID");
//$auth_token = getenv("TWILIO_TOKEN");
//$twilio_number = getenv("TWILIO_FROM");
//$client = new Client($account_sid, $auth_token);
//$client->messages->create('+573168950803', [
// 'from' => $twilio_number,
// 'body' => $message]);
//dd('SMS Sent Successfully.');
// } catch (Exception $e) {
// dd("Error: ". $e->getMessage());
// }
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
use App\Http\Middleware\SoloUsuarioAdministrador;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array<int, class-string|string>
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array<string, class-string|string>
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \App\Http\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'solo_usuario_administrador' => SoloUsuarioAdministrador::class,
];
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace App\Http\Livewire;
use Livewire\WithFileUploads;
use Livewire\Component;
use App\Imports\UsersImport;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\Controller;
class Import extends Component
{
use WithFileUploads;
public $photo;
public $importado;
public function render()
{
return view('livewire.import');
}
public function import()
{
$data=Excel::import(new UsersImport, $this->photo);
$this->photo=null;
$this->importado = 'true';
// aquí se puede procesar los datos obtenidos
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Http\Livewire;
use App\Models\recarga;
use Livewire\Component;
use Livewire\WithPagination;
class LogsRecargas extends Component
{
public $aprobado;
public $buscar;
use WithPagination;
public function render()
{
$consulta_historial = Recarga::orderBy('id', 'DESC');
if (!empty($this->aprobado)) {
$consulta_historial->where('status', 'approved');
}
if (!empty($this->buscar)) {
$consulta_historial->whereHas('usuario', function ($query) {
$query->where('email', 'like', '%' . $this->buscar . '%');
});
}
// Limitar resultados a un máximo de 200
$resultados = $consulta_historial->take(200)->paginate(30);
// Restablecer la paginación después de limitar los resultados
$resultados->setCollection($resultados->getCollection()->values());
return view('livewire.logs-recargas',[
'historial_recargas' => $resultados
]);
}
}
+19
View File
@@ -0,0 +1,19 @@
<?php
namespace App\Http\Livewire;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Livewire\Component;
class Portada extends Component
{
public $promociones;
public function render()
{
return view('livewire.portada');
}
}
+224
View File
@@ -0,0 +1,224 @@
<?php
namespace App\Http\Livewire;
use App\Models\Categoria;
use App\Models\Cuentas;
use App\Models\Historial_cuenta;
use App\Models\Historiale;
use App\Models\Promocion_tarifa;
use App\Models\Promociones;
use App\Models\Role;
use App\Models\Saldo;
use App\Models\Servicio;
use App\Models\Tarifas;
use App\Models\User;
use App\Notifications\compra;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Notification;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\Component;
class PortadaServicio extends Component
{
use LivewireAlert;
public $categoria_id;
public $nombre_promocion;
public $descripcion_promocion;
public $valor_promocion;
public $estado_promocion;
public $fecha_limite_promocion;
public $categoria_id_promocion;
public $fechaFinal;
public $tarifa_id_promocion;
public $dias_comprarPromo;
public $valor_comprarPromo;
public $nombre_comprarPromo;
public $celular_comprarPromo;
public $email_comprarPromo;
public $cantidad_comprarPromo = 1;
public $newCategoria = false;
public $nombre_categoria;
public $descripcion_categoria;
public $modalComprarPromo = false;
public $verPromo = false;
public $precioAntes;
public $precioAhora;
public $fechaLimite;
public $nombrePromo;
public $descripcionPromo;
public $editarPromo = false;
public $nombre_editarPromo;
public $descripcion_editarPromo;
public $valor_editarPromo;
public $estado_editarPromo;
public $fecha_limite_editarPromo;
public $categoria_id_editarPromo;
public $editar_promo_id;
public $imagen;
public $dias;
public $total;
public $consulta;
public $fechaHoy;
public $fechafinal;
public $fecha;
public $credenciales;
public $cuentas;
protected $rules = [
'nombre_comprarPromo' => 'required',
'celular_comprarPromo' => 'required',
'email_comprarPromo' => 'required',
'cantidad_comprarPromo' => 'required',
];
public function render()
{
$date = Carbon::now()->subDay(8);
$this->fecha= $date->format('Y-m-d');
$this->fechaActual = Carbon::now();
$this->fechaActual = Carbon::parse($this->fechaActual);
$this->fechaHoy = Carbon::now();
$this->fechaHoy = $this->fechaHoy->format('d/m/Y');
$consulta_promociones = Promociones::with('tarifas')->where('visible', 'true');
if (!is_null($this->categoria_id)) {
$consulta_promociones = $consulta_promociones->where('categoria_id', 'LIKE', '%' . $this->categoria_id . '%');
}
//dd($consulta_promociones->get());
$consulta_promociones = $consulta_promociones->get();
return view('livewire.portada-servicio',[
'promociones' => $consulta_promociones,
'categorias' => Categoria::get(),
'tarifas' => Tarifas::with('servicio')->get(),
]);
}
public function verPromocion($id)
{
$consulta_verpromocion = Promociones::with('tarifas')->where('id', $id)->first();
$this->consulta = $consulta_verpromocion;
$this->precioAntes = $consulta_verpromocion->tarifas->first()->valor;
$this->precioAhora = $consulta_verpromocion->precio;
$this->imagen = $consulta_verpromocion->img_publicidad;
$this->fechaLimite = $consulta_verpromocion->fecha_limite;
$this->nombrePromo = $consulta_verpromocion->nombre;
$this->dias = $consulta_verpromocion->dias;
$this->descripcionPromo = $consulta_verpromocion->descripcion;
$this->fechaFinal = $this->fechaActual->addDay($this->dias);
$this->verPromo = true;
}
public function comprarPromo($id)
{
$consulta_verpromocion = Promociones::with('tarifas')->where('id', $id)->first();
$this->consulta = $consulta_verpromocion;
$this->precioAntes = $consulta_verpromocion->tarifas->first()->valor;
$this->precioAhora = $consulta_verpromocion->precio;
$this->imagen = $consulta_verpromocion->img_publicidad;
$this->fechaLimite = $consulta_verpromocion->fecha_limite;
$this->nombrePromo = $consulta_verpromocion->nombre;
$this->dias = $consulta_verpromocion->dias;
$this->descripcionPromo = $consulta_verpromocion->descripcion;
$this->fechaFinal = $this->fechaActual->addDay($this->dias);
$this->modalComprarPromo = true;
}
/* ---------------- Btn Comprar ---------------- */
public function pagar()
{
$this->validate();
$usuario_existe = User::firstWhere('email', $this->email_comprarPromo)->id ?? null;
if (is_null($usuario_existe)) {
$usuario = new User;
$usuario->name = $this->nombre_tarjetaPlan;
$usuario->email = $this->email_tarjetaPlan;
$usuario->password = '123';
$usuario->celular = $this->celular_tarjetaPlan;
$usuario->save();
$usuario_id = $usuario->id;
} else {
$usuario_id = $usuario_existe;
}
if (empty(Auth::user())) {
$historial = new Historiale();
$historial->fecha_inicio = $this->fechaHoy;
$historial->fecha_final = $this->fechaFinal;
$historial->valor = $this->precioAhora *$this->cantidad_comprarPromo;
$historial->tipo_pago = 'manual';
$historial->estado = 'pendiente';
$historial->vendedor_id = Role::where('nombre','super')->first()->usuarios->first()->id;
$historial->promocion_id = $this->consulta->id;
$historial->cliente_id = $usuario_id;
$historial->cantidad = $this->cantidad_comprarPromo;
$historial->save();
}else{
$historial = new Historiale();
$historial->fecha_inicio = $this->fechaHoy;
$historial->fecha_final = $this->fechaFinal;
$historial->valor = $this->precioAhora *$this->cantidad_comprarPromo;
$historial->tipo_pago = 'manual';
$historial->estado = 'pendiente';
$historial->vendedor_id = Auth::user()->id;
$historial->promocion_id = $this->consulta->id;
$historial->cliente_id = $usuario_id;
$historial->cantidad = $this->cantidad_comprarPromo;
$historial->save();
}
return redirect('/comprar?monto='.$historial->valor.'&id='.$historial->id);
}
public function limpiarInputPromocion()
{
$this->nombre_promocion = '';
$this->descripcion_promocion = '';
$this->valor_promocion = '';
$this->estado_promocion = null;
$this->fecha_limite_promocion = null;
$this->categoria_id_promocion = null;
$this->newCategoria = false;
$this->newPromocion = false;
$this->list = null;
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use Jantinnerezo\LivewireAlert\LivewireAlert;
class ShowAdmin extends Component
{
use LivewireAlert;
public function render()
{
return view('livewire.show-admin');
}
}
+139
View File
@@ -0,0 +1,139 @@
<?php
namespace App\Http\Livewire;
use App\Models\Categoria;
use Livewire\Component;
use Livewire\WithFileUploads;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Intervention\Image\ImageManagerStatic as Img;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
class ShowCategoria extends Component
{
use LivewireAlert;
use WithFileUploads;
public $categoria_id;
public $photo;
public $img;
public $nombre;
public $descripcion;
public $editarCategoria=false;
public $nuevaCategoria=false;
protected $rules = [
'photo' =>'required',
'nombre' => 'required',
];
public function render()
{
$consulta_categoria = Categoria::get();
return view('livewire.show-categoria',[
'categorias' => $consulta_categoria,
]);
}
public function create()
{
$this->validate();
if (!empty($this->photo)) {
$nombre=Str::random(10);
$img = img::make($this->photo)->orientate()->resize(1000, null, function($constraint){
$constraint->aspectRatio();
$constraint->upsize();
})->encode('webp');
$location = "photos/".$nombre.".webp";
Storage::disk('local')->put($location, $img);
$url_foto = $location;
} else {
$url_foto = '';
}
$guardar_categoria = new Categoria;
$guardar_categoria->nombre = $this->nombre;
$guardar_categoria->imagen = $url_foto;
$guardar_categoria->descripcion = $this->descripcion;
$guardar_categoria->save();
$this->alert('success', 'Categoria creada correctamente!', [
'position' => 'top'
]);
$this->nuevaCategoria=false;
}
public function editar($id)
{
$consulta_categorias = Categoria::FindOrFail($id);
$this->categoria_id = $consulta_categorias->id;
$this->nombre = $consulta_categorias->nombre;
$this->descripcion = $consulta_categorias->descripcion;
$this->img = $consulta_categorias->imagen;
}
public function update()
{
if (!empty($this->photo)) {
$nombre=Str::random(10);
$img = img::make($this->photo)->orientate()->resize(1000, null, function($constraint){
$constraint->aspectRatio();
$constraint->upsize();
})->encode('webp');
$location = "photos/".$nombre.".webp";
Storage::disk('local')->put($location, $img);
$url_foto = $location;
} else {
$url_foto = $this->img;
}
Categoria::where('id', $this->categoria_id)->update([
'nombre' => $this->nombre,
'descripcion' => $this->descripcion,
'imagen' => $url_foto
]);
$this->alert('success', 'Categoria actualizada correctamente!', [
'position' => 'top'
]);
$this->limpiarInputCategoria();
$this->editarCategoria=false;
}
public function delete($id)
{
Categoria::where('id',$id)->delete();
$this->alert('success', 'Categoria eliminada correctamente!', [
'position' => 'top'
]);
}
public function limpiarInputCategoria()
{
$this->photo = null;
$this->nombre = '';
$this->descripcion = '';
}
}
+278
View File
@@ -0,0 +1,278 @@
<?php
namespace App\Http\Livewire;
use App\Models\Historial_cuenta;
use App\Models\Historiale;
use App\Models\User;
use App\Notifications\Vencimiento;
use Carbon\Carbon;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Exception;
use Illuminate\Support\Facades\Crypt;
use App\Models\Configuracione;
use Livewire\WithPagination;
use Twilio\Rest\Client;
use Jantinnerezo\LivewireAlert\LivewireAlert;
class ShowClientes extends Component
{
use LivewireAlert;
use WithPagination;
public $date;
public $buscar;
public $fechaActual;
public $verCliente = false;
public $ver_nombre;
public $ver_email;
public $ver_fecha_inicio;
public $ver_fecha_vencimiento;
public $ver_paquete;
public $precio_paquete;
public $dias_paquete;
public $consulta_historial;
public $venceHoy;
public $vencidosHoy =false;
public $visto = false;
public $vencidHoy;
public $configuracion;
public $msj;
public function render()
{ $fechaHoy = Carbon::now();
$this->fechaActual = date('d/m/Y');
$fechaVencimiento = Carbon::now()->subDay(30);
$consulta_clientes = Historiale::where('vendedor_id', Auth()->user()->id)->whereDate('fecha_final','>', $fechaVencimiento);
$this->configuracion = User::where('id',Auth::user()->id)->whereDate('updated_at','!=', $fechaHoy)->first();
if($this->configuracion){
$this->vencidosHoy = true;
$this->vencidHoy= $consulta_clientes->whereDate('fecha_final', $fechaHoy)->get();
$this->configuracion = User::where('id',Auth::user()->id)->update(['visto' => true]);
}
$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();
if (!empty($this->buscar)) {
$consulta_clientes = $consulta_clientes->where(function ($query) {
$query->whereHas('cuentas', function ($subQuery) {
$subQuery->where('correo', 'LIKE', '%' . $this->buscar . '%');
})->orWhereHas('cliente', function ($subQuery) {
$subQuery->where('email', 'LIKE', '%' . $this->buscar . '%');
});
});
}
if ($this->venceHoy) {
$fecha5 = Carbon::parse($fechaHoy)->subDay(5);
$consulta_clientes = $consulta_clientes->whereDate('fecha_final', '<=', $fechaHoy)
->whereDate('fecha_final', '>=', $fecha5);
}
$consulta_clientes = $consulta_clientes->with('tarifa', 'promocion', 'cliente')
->orderBy('id', 'DESC')
->paginate(15);
// dd($consulta_clientes);
return view('livewire.show-clientes', [
'clientes' => $consulta_clientes
]);
}
public function verCliente($id)
{
$this->consulta_historial = Historiale::with('promocion', 'tarifa', 'cliente','cuentas')->where('id', $id)->first();
// dd($this->consulta_historial );
$this->verCliente = true;
}
public function enviarNotificacion($id)
{
$consulta_historial = Historiale::where('id', $id)->with('tarifa', 'cliente')->first();
$user = User::find($consulta_historial->cliente);
$notificacion = [
//'valor' => $value['precio'],
'fecha_final' => $consulta_historial->fecha_final,
'cliente' => $consulta_historial->cliente->name,
'servicio' => $consulta_historial->tarifa->servicio->nombre . '-' . $consulta_historial->tarifa->pantallas . 'pantallas',
'tipo' => 'vencimiento',
'vendedor' => auth()->user()->username,
];
Notification::send($user, new Vencimiento($notificacion));
$this->alert('success', 'Notificación enviada', [
'position' => 'top'
]);
}
public function enviarNotificacionPromo($id)
{
$consulta_historial = Historiale::where('id', $id)->with('promocion', 'cliente')->first();
$user = User::find($consulta_historial->cliente);
$nombre = $consulta_historial->promocion->nombre;
$descripcion = $consulta_historial->promocion->descripcion;
$notificacion = [
//'valor' => $value['precio'],
'fecha_final' => $consulta_historial->fecha_final,
'cliente' => $consulta_historial->cliente->name,
'servicio' => 'PROMO ' . $nombre . '-' . $descripcion,
'tipo' => 'vencimiento',
'vendedor' => auth()->user()->username,
];
Notification::send($user, new Vencimiento($notificacion));
$this->alert('success', 'Notificación enviada', [
'position' => 'top'
]);
}
public function notSMSpromo($id){
$consulta_historial = Historiale::where('id', $id)->with('promocion', 'cliente')->first();
$user = User::find($consulta_historial->cliente);
$nombre = $consulta_historial->promocion->nombre;
$fecha=Carbon::parse($consulta_historial->fecha_final)->format('Y/m/d');
$fecha_humana= Carbon::parse($consulta_historial->fecha_final)->diffForHumans();
//dd($fecha_humana);
//$descripcion = $consulta_historial->promocion->descripcion;
$message = 'Su '.$nombre.', Vence '.$fecha_humana.', '.$fecha.'. Renueva ahora!!' ;
$recipients= '+57'.$consulta_historial->cliente->celular;
$this->sendMessage($message, $recipients);
}
public function notSMS($id){
$consulta_historial = Historiale::where('id', $id)->with('tarifa', 'cliente')->first();
$user = User::find($consulta_historial->cliente);
$nombre = $consulta_historial->tarifa->servicio->nombre . '-' . $consulta_historial->tarifa->pantallas . 'P';
$fecha=Carbon::parse($consulta_historial->fecha_final)->format('Y/m/d');
$fecha_humana= Carbon::parse($consulta_historial->fecha_final)->diffForHumans();
$message = 'Su '.$nombre.', Vence '.$fecha_humana.', '.$fecha.'. Renueva ahora!!' ;
$recipients= '+57'.$consulta_historial->cliente->celular;
$this->sendMessage($message, $recipients);
}
public function sendMessage($message, $recipients)
{
// try {
// $account_sid = getenv("TWILIO_SID");
// $auth_token = getenv("TWILIO_TOKEN");
// $twilio_number = getenv("TWILIO_FROM");
// $client = new Client($account_sid, $auth_token);
// $client->messages->create($recipients,
// ['from' => $twilio_number, 'body' => $message] );
// $this->alert('success', 'Notificación enviada por SMS! ', [
// 'position' => 'top'
// ]);
// }catch(Exception $e){
// $this->alert('warning', 'Error enviando SMS!'.$e->getMessage(), [
// 'position' => 'top'
// ]);
// }
$auth_basic = base64_encode('admin@jaguarws.ga:9u3xxXhHt8maeiOexg07pFKI0rpYazI0');
//dd(getenv('USER_LABSMOBILE'));
$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.'","nofilter":"1, "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 {
//dd($response);
if (!empty(json_decode($response)->subid)) {
$this->alert('success', 'Notificación enviada por SMS! '.json_decode($response)->subid, [
'position' => 'top'
]);
}else{
$this->alert('warning', 'Servicio de SMS en mantenimiento!'.json_decode($response)->code, [
'position' => 'top'
]);
}
}
}
public function cerrar(){
$this->configuracion = User::where('id',Auth::user()->id)->update(['visto' => true]);
//dd($this->configuracion);
$this->visto=true;
$this->vencidosHoy = false;
}
public function renovar(){
}
}
+451
View File
@@ -0,0 +1,451 @@
<?php
namespace App\Http\Livewire;
use App\Models\Configuracione;
use App\Models\slider;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\WithFileUploads;
use App\Models\Cuentas;
use App\Models\Historial_cuenta;
use App\Models\Historiale;
use Intervention\Image\ImageManagerStatic as Img;
use Illuminate\Support\Str;
use Artisan;
use Illuminate\Support\Facades\Storage;
class ShowConfiguracion extends Component
{
use LivewireAlert;
use WithFileUploads;
public $nombre;
public $slogan;
public $photo;
public $color_boton;
public $color_barra;
public $color_menu;
public $url_logo;
public $slider;
public $delete_slider;
public $photo_top;
public $imgP1;
public $imgP2;
public $imgP3;
public $imgP4;
public $imgP5;
public $imgP6;
public $imgP7;
public $imgP8;
public $imgP9;
public $imgP10;
public $premio_1;
public $premio_2;
public $premio_3;
public $premio_4;
public $premio_5;
public $premio_6;
public $premio_7;
public $premio_8;
public $premio_9;
public $premio_10;
public $mensaje_top;
public $img_top;
public $mensaje_msj_compra;
public $mensaje_msj_wp;
public $clave_1;
public $clave_2;
public $clave_3;
public $clave_4;
public $clave_5;
public $clave_6;
public $iptv;
public $notificacion;
public $consulta_configuracion;
public function render()
{
//$consulta = Configuracione::with('usuario')->orderby('id','desc');
$consulta_configuracion= Configuracione::with('usuario')->orderby('id','desc')->first();
$this->consulta_configuracion = $consulta_configuracion;
//dd($consulta_configuraciones);
if (empty($this->nombre) && empty($this->slogan) && empty($this->color_boton) ) {
$this->nombre = $consulta_configuracion->nombre;
$this->slogan = $consulta_configuracion->slogan;
$this->color_boton = $consulta_configuracion->color_boton;
$this->url_logo = $consulta_configuracion->url_logo;
$this->color_barra = $consulta_configuracion->color_barra;
$this->color_menu = $consulta_configuracion->color_menu;
//top
$this->top_1 = $consulta_configuracion->top_1;
$this->top_2 = $consulta_configuracion->top_2;
$this->top_3 = $consulta_configuracion->top_3;
$this->top_4 = $consulta_configuracion->top_4;
$this->top_5 = $consulta_configuracion->top_5;
$this->top_6 = $consulta_configuracion->top_6;
$this->top_7 = $consulta_configuracion->top_7;
$this->top_8 = $consulta_configuracion->top_8;
$this->top_9 = $consulta_configuracion->top_9;
$this->top_10 = $consulta_configuracion->top_10;
$this->premio_1 = $consulta_configuracion->premio_1;
$this->premio_2 = $consulta_configuracion->premio_2;
$this->premio_3 = $consulta_configuracion->premio_3;
$this->premio_4 = $consulta_configuracion->premio_4;
$this->premio_5 = $consulta_configuracion->premio_5;
$this->premio_6 = $consulta_configuracion->premio_6;
$this->premio_7 = $consulta_configuracion->premio_7;
$this->premio_8 = $consulta_configuracion->premio_8;
$this->premio_9 = $consulta_configuracion->premio_9;
$this->premio_10 = $consulta_configuracion->premio_10;
$this->img_top = $consulta_configuracion->img_top;
$this->mensaje_top = $consulta_configuracion->mensaje_top;
//msj
$this->mensaje_msj_compra= $consulta_configuracion->msj_compra;
$this->mensaje_msj_wp= $consulta_configuracion->msj_wp;
$this->clave_1 = $consulta_configuracion->clave_1;
$this->clave_2 = $consulta_configuracion->clave_2;
$this->clave_3 = $consulta_configuracion->clave_3;
$this->clave_4 = $consulta_configuracion->clave_4;
$this->clave_5 = $consulta_configuracion->clave_5;
$this->clave_6 = $consulta_configuracion->clave_6;
$this->iptv = $consulta_configuracion->iptv;
$this->notificacion = $consulta_configuracion->hora;
}
return view('livewire.show-configuracion',[
'sliders' => slider::get(),
]);
}
public function guardarclaves(){
$claves=$this->consulta_configuracion->update([
'clave_1' => $this->clave_1,
'clave_2' => $this->clave_2,
'clave_3' => $this->clave_3,
'clave_4' => $this->clave_4,
'clave_5' => $this->clave_5,
'clave_6' => $this->clave_6,
]);
if ($claves) {
$this->alert('success', 'claves actualizado', [
'position' => 'top'
]);
}
}
public function guardar(){
if (!empty($this->photo)) {
$nombre=Str::random(10);
$img = img::make($this->photo)->orientate()->resize(1000, null, function($constraint){
$constraint->aspectRatio();
$constraint->upsize();
})->encode('webp');
$location = "photos/".$nombre.".webp";
Storage::disk('local')->put($location, $img);
$url_logo = $location;
}else{
$url_logo = $this->url_logo ;
}
$configuracion=$this->consulta_configuracion->update([
'nombre' => $this->nombre,
'slogan' => $this->slogan,
'color_boton' => $this->color_boton,
'url_logo' => $url_logo,
'color_barra' => $this->color_barra,
'color_menu'=> $this->color_menu,
'usermodifico_id'=>Auth::user()->id,
]);
if ($configuracion) {
$this->alert('success', 'Configuración actualizada', [
'position' => 'top'
]);
}
}
public function guardarSlider(){
if (!empty($this->slider)) {
$nombre=Str::random(12);
$img = img::make($this->slider)->orientate()->resize(1000, null, function($constraint){
$constraint->aspectRatio();
$constraint->upsize();
})->encode('webp');
$location = "photos/".$nombre.".webp";
Storage::disk('local')->put($location, $img);
$url_slider = $location;
}else{
$url_slider = '' ;
}
$guardar = new slider;
$guardar->slider = $url_slider;
$guardar->save();
$this->slider = '';
}
public function cancelarSlider()
{
$this->slider = '';
}
public function deleteSlider($id)
{
$this->delete_slider = $id;
$this->alert('warning', '¿Eliminar slider?', [
'position' => 'center',
'timer' => '10000',
'toast' => false,
'text' => 'Esta seguro',
'showConfirmButton' => true,
'onConfirmed' => 'confirmed',
'showDenyButton' => false,
'onDenied' => '',
'showCancelButton' => true,
'onDismissed' => '',
'cancelButtonText' => 'Salir',
'confirmButtonText' => 'Si',
]);
}
public function getListeners()
{
return [
'confirmed'
];
}
public function confirmed(){
slider::where('id',$this->delete_slider)->delete();
$this->alert('success', 'Imagen eliminada correctamente!', [
'position' => 'top'
]);
}
public function guardarTop(){
if (!empty($this->photo_top)) {
$nombre=Str::random(10);
$img = img::make($this->photo_top)->orientate()->resize(1000, null, function($constraint){
$constraint->aspectRatio();
$constraint->upsize();
})->encode('webp');
$location = "photos/".$nombre.".webp";
Storage::disk('local')->put($location, $img);
$photo_top = $location;
}else{
$photo_top = $this->img_top ;
}
if (!empty($this->imgP1)) {
$imgP1=$this->imgP1->store('photos');
}else{
$imgP1 = $this->top_1 ;
}
if (!empty($this->imgP2)) {
$imgP2=$this->imgP2->store('photos');
}else{
$imgP2 = $this->top_2 ;
}
if (!empty($this->imgP3)) {
$imgP3=$this->imgP3->store('photos');
}else{
$imgP3 = $this->top_3 ;
}
if (!empty($this->imgP4)) {
$imgP4=$this->imgP4->store('photos');
}else{
$imgP4 = $this->top_4 ;
}
if (!empty($this->imgP5)) {
$imgP5=$this->imgP5->store('photos');
}else{
$imgP5 = $this->top_5 ;
}
if (!empty($this->imgP6)) {
$imgP6=$this->imgP6->store('photos');
}else{
$imgP6 = $this->top_6 ;
}
if (!empty($this->imgP7)) {
$imgP7=$this->imgP7->store('photos');
}else{
$imgP7 = $this->top_7 ;
}
if (!empty($this->imgP8)) {
$imgP8=$this->imgP8->store('photos');
}else{
$imgP8 = $this->top_8 ;
}
if (!empty($this->imgP9)) {
$imgP9=$this->imgP9->store('photos');
}else{
$imgP9 = $this->top_9 ;
}
if (!empty($this->imgP10)) {
$imgP10=$this->imgP10->store('photos');
}else{
$imgP10 = $this->top_10 ;
}
$top = $this->consulta_configuracion->update([
'top_1' => $imgP1,
'top_2' => $imgP2,
'top_3' => $imgP3,
'top_4' => $imgP4,
'top_5' => $imgP5,
'top_6' => $imgP6,
'top_7' => $imgP7,
'top_8' => $imgP8,
'top_9' => $imgP9,
'top_10' => $imgP10,
'img_top' => $photo_top,
'mensaje_top' => $this->mensaje_top,
'premio_1' => $this->premio_1,
'premio_2' => $this->premio_2,
'premio_3' => $this->premio_3,
'premio_4' => $this->premio_4,
'premio_5' => $this->premio_5,
'premio_6' => $this->premio_6,
'premio_7' => $this->premio_7,
'premio_8' => $this->premio_8,
'premio_9' => $this->premio_9,
'premio_10' => $this->premio_10,
]);
if($top){
$this->alert('success', 'Top distribuidores actualizado', [
'position' => 'top'
]);
}
}
public function guardarMsjCompra(){
$msj = $this->consulta_configuracion->update([
'msj_compra' => $this->mensaje_msj_compra,
'msj_wp' => $this->mensaje_msj_wp,
]);
if ($msj) {
$this->alert('success', 'Mensaje actualizado', [
'position' => 'top'
]);
}
}
public function guardariptv(){
// dd($this->iptv);
$iptv = $this->consulta_configuracion->update([
'iptv' => $this->iptv,
]);
if ($iptv) {
$this->alert('success', 'iptv actualizado', [
'position' => 'top'
]);
}
}
public function eliminarC(){
//$eliminar_cuentas = Cuentas::truncate();
$this->alert('warning', 'Funcion deshabilitada ', [
'position' => 'top'
]);
}
public function eliminarR(){
// $eliminar_cuentas = Historial_cuenta::truncate();
$this->alert('warning', 'Funcion deshabilitada ', [
'position' => 'top'
]);
}
public function eliminarH(){
//$desasociar_cuentas = Historiale::truncate();
$this->alert('warning', 'Funcion deshabilitada ', [
'position' => 'top'
]);
}
public function guardarnot(){
$notificacion = $this->consulta_configuracion->update([
'hora' => $this->notificacion,
]);
$this->alert('success', 'La hora de notificación ha sido actualizada.', [
'position' => 'top'
]);
}
public function eliminarCache(){
Artisan::call('cache:clear');
Artisan::call('config:clear');
Artisan::call('view:clear');
Artisan::call('route:cache');
$this->alert('success', 'Cache removido correctamente', [
'position' => 'top'
]);
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace App\Http\Livewire;
use App\Models\Promociones;
use App\Models\Role;
use App\Models\Servicio;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
class ShowIndex extends Component
{
public function render()
{
$promociones = Promociones::where('visible','true')->limit(4)->get();
$this->rol_id = Role::where('nombre','cliente')->value('id');
$planes = Servicio::where('estado','activo')->withMax(['tarifas' => function ($query) {
$query->where('rol_id', $this->rol_id);
}],'valor')->withMin(['tarifas' => function ($query) {
$query->where('rol_id', $this->rol_id);
}],'valor')->get();
return view('livewire.show-index',[
'planes' => $planes,
'promociones' => $promociones,
]);
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Http\Livewire;
use App\Models\Categoria;
use Livewire\Component;
class ShowIndexCategoria extends Component
{
public $verPro=false;
public $categorian;
public $imagen;
public function render()
{
$consulta_categoria = Categoria::get();
return view('livewire.show-index-categoria',[
'categorias' => $consulta_categoria
]);
}
}
+106
View File
@@ -0,0 +1,106 @@
<?php
namespace App\Http\Livewire;
use App\Models\Cuentas;
use App\Models\Historial_cuenta;
use App\Models\Historiale;
use App\Models\Promociones;
use App\Models\Role;
use App\Models\Saldo;
use App\Models\User;
use Carbon\Carbon;
use Livewire\Component;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ShowIndexPromo extends Component
{
public $nombre_comprarPromo;
public $celular_comprarPromo;
public $email_comprarPromo;
public $cantidad_comprarPromo = 1;
public $fechaHoy;
public $fechaFinal;
public $promo_id;
protected $rules = [
'nombre_comprarPromo' => 'required',
'celular_comprarPromo' => 'required',
'email_comprarPromo' => 'required',
'cantidad_comprarPromo' => 'required',
];
public function render(Request $request)
{
if (empty($this->promo_id)) {
$this->promo_id = $request->promo;
}
$consulta_promo = Promociones::find($this->promo_id);
$this->consulta= $consulta_promo;
$promociones= Promociones::where('visible','true')->get();
$fechaActual = Carbon::now();
$this->fechaHoy = $fechaActual;
//dd($consulta_promo);
$this->fechaFinal = $fechaActual->addDay($consulta_promo->dias);
return view('livewire.show-index-promo',[
'promo' => $consulta_promo,
'promociones'=>$promociones
]);
}
public function comprar()
{
$this->validate();
$usuario_existe = User::firstWhere('email', $this->email_comprarPromo)->id ?? null;
if (is_null($usuario_existe)) {
$usuario = new User;
$usuario->name = $this->nombre_tarjetaPlan;
$usuario->email = $this->email_tarjetaPlan;
$usuario->password = '123';
$usuario->celular = $this->celular_tarjetaPlan;
$usuario->save();
$usuario_id = $usuario->id;
} else {
$usuario_id = $usuario_existe;
}
if (empty(Auth::user())) {
$historial = new Historiale();
$historial->fecha_inicio = $this->fechaHoy;
$historial->fecha_final = $this->fechaFinal;
$historial->valor = $this->consulta->precio *$this->cantidad_comprarPromo;
$historial->tipo_pago = 'manual';
$historial->estado = 'pendiente';
$historial->vendedor_id = Role::where('nombre','super')->first()->usuarios->first()->id;
$historial->promocion_id = $this->consulta->id;
$historial->cliente_id = $usuario_id;
$historial->cantidad = $this->cantidad_comprarPromo;
$historial->save();
}else{
$historial = new Historiale;
$historial->fecha_inicio = $this->fechaHoy;
$historial->fecha_final = $this->fechaFinal;
$historial->valor = $this->consulta->precio *$this->cantidad_comprarPromo ;
$historial->tipo_pago = 'manual';
$historial->estado = 'pendiente';
$historial->vendedor_id = Auth::user()->id;
$historial->promocion_id = $this->consulta->id;
$historial->cliente_id = $usuario_id;
$historial->cantidad = $this->cantidad_comprarPromo;
$historial->save();
}
return redirect('/comprar?monto='.$historial->valor.'&id='.$historial->id);
}
}
+153
View File
@@ -0,0 +1,153 @@
<?php
namespace App\Http\Livewire;
use App\Models\Cuentas;
use App\Models\Historial_cuenta;
use App\Models\Historiale;
use App\Models\Role;
use App\Models\Servicio;
use App\Models\Tarifas;
use App\Models\User;
use Carbon\Carbon;
use Livewire\Component;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ShowIndexServicio extends Component
{
public $tarifa_id;
public $fechaFinal;
public $disponibles;
public $fechaActual;
public $valor;
public $servicio_id;
public $celular_tarjetaPlan;
public $nombre_tarjetaPlan;
public $email_tarjetaPlan;
public $cantidad_tarjetaPlan = 1;
public $total;
public $rol_id;
protected $rules = [
'nombre_tarjetaPlan' => 'required',
'cantidad_tarjetaPlan' => 'required',
'email_tarjetaPlan' => 'required',
'celular_tarjetaPlan' => 'required',
];
public function render(Request $request)
{
if (empty($this->servicio_id)) {
$this->servicio_id = $request->servicio;
}
$this->total = (int) $this->valor * (int)$this->cantidad_tarjetaPlan;
$this->fechaHoy = Carbon::now();
$this->fechaHoy = $this->fechaHoy->format('d/m/Y');
$fechaActual = Carbon::now();
$this->fechaActual = Carbon::parse($this->fechaActual);
$date = $fechaActual ->subDay(8);
$this->fecha= $date->format('Y-m-d');
if (!empty($this->tarifa_id)) {
$this->fecha_final_1 = $today = Carbon::now()->addDays($tarifas->dias-15);
$this->fecha_final_2 = $today = Carbon::now()->addDays($tarifas->dias+15);
$tarifas = Tarifas::with('servicio')->where('id', $this->tarifa_id)->first();
$cuentas_creadas = Cuentas::whereDate('inicio','>=',$this->fecha)->where('servicio_id',$this->servicio_id)->where('estado','activo')->get();
$cuentas_tomadas = Historial_cuenta::whereIn('cuenta_id', $cuentas_creadas->pluck('id'))->count();
$cuentas_completas = Cuentas::whereDate('inicio','>=',$this->fecha)->whereDate('vencimiento','>=',$this->fecha_final_1)->whereDate('vencimiento','<=',$this->fecha_final_2)->where('servicio_id',$tarifas->servicio->id)->where('estado','pendiente')->get();
$cuentas_completas_tomadas = Historial_cuenta::whereIn('cuenta_id', $cuentas_completas->pluck('id'))
->count();
$this->fechaFinal = $this->fechaActual->addDay($tarifas->dias);
$this->fechaFinal = $this->fechaFinal->format('d/m/Y');
if ($tarifas->pantallas == $tarifas->servicio->completa) {
$this->disponibles = (($cuentas_completas->count()*$tarifas->servicio->completa) - $cuentas_completas_tomadas)/ $tarifas->pantallas;
}else{
$this->disponibles = (($cuentas_creadas->count()*$tarifas->servicio->pantallas) - $cuentas_tomadas)/ $tarifas->pantallas;
}
$this->valor= $tarifas->valor;
}
$this->rol_id = Role::where('nombre','cliente')->value('id');
$planes = Servicio::where('estado','activo')->withMax(['tarifas' => function ($query) {
$query->where('rol_id', $this->rol_id);
}],'valor')->withMin(['tarifas' => function ($query) {
$query->where('rol_id', $this->rol_id);
}],'valor')->with(['tarifas' => function ($query) {
$query->where('rol_id', $this->rol_id);
}])->get();
foreach ($planes as $plan ) {
if($plan->id == $this->servicio_id){
$servicio = $plan;
}
}
return view('livewire.show-index-servicio',[
'servicio' =>$servicio,
'planes' =>$planes
]);
}
/* ---------------- Btn Comprar ---------------- */
public function comprar()
{
$this->validate();
$total_valor = (int) $this->valor * (int)$this->cantidad_tarjetaPlan;
$usuario_existe = User::firstWhere('email', $this->email_tarjetaPlan)->id ?? null;
if (is_null($usuario_existe)) {
$usuario = new User;
$usuario->name = $this->nombre_tarjetaPlan;
$usuario->email = $this->email_tarjetaPlan;
$usuario->password = '123';
$usuario->celular = $this->celular_tarjetaPlan;
$usuario->save();
$usuario_id = $usuario->id;
}else{
$usuario_id = $usuario_existe;
}
$historial = new Historiale;
$historial->fecha_inicio = $this->fechaActual;
$historial->fecha_final = $this->fechaFinal;
$historial->valor = $total_valor ;
$historial->tipo_pago = 'manual';
$historial->estado = 'pendiente';
if (empty(Auth::user())) { // SI esta logueado o no
$historial->vendedor_id = Role::where('nombre','super')->first()->usuarios->first()->id;
}else{
$historial->vendedor_id = Auth::user()->id;
}
$historial->tarifa_id = $this->tarifa_id;
$historial->cliente_id = $usuario_id;
$historial->cantidad = $this->cantidad_tarjetaPlan;
$historial->save();
return redirect('/comprar?monto='.$historial->valor.'&id='.$historial->id);
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace App\Http\Livewire;
use App\Models\Configuracione;
use App\Models\Promociones;
use App\Models\slider;
use Livewire\Component;
use Jantinnerezo\LivewireAlert\LivewireAlert;
class ShowInicio extends Component
{
use LivewireAlert;
public function render()
{
$consulta_promociones = slider::get();
//dd($consulta_promociones);
return view('livewire.show-inicio',[
'promociones' => $consulta_promociones,
]);
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Http\Livewire;
use App\Models\Historiale;
use Livewire\Component;
use Livewire\WithPagination;
use Carbon\Carbon;
class ShowLogs extends Component
{
Use WithPagination;
public $buscar;
public function render()
{
$fechaVencimiento = Carbon::now()->subDay(30);
//dd($fechaVencimiento);
$consulta_historial = Historiale::with('promocion', 'tarifa', 'vendedor','cuentas','cuentas_obsoletas')->whereDate('fecha_final','>', $fechaVencimiento)->orderBy('id', 'DESC')
->when(!empty($this->buscar), function ($query) {
$query->whereHas('cuentas', function ($subquery) {
$subquery->where('correo', 'LIKE', '%' . $this->buscar . '%');
})->orWhereHas('vendedor', function ($subquery) {
$subquery->where('email', 'LIKE', '%' . $this->buscar . '%');
});
});
// Limitar resultados a un máximo de 200
$resultados= $consulta_historial->take(200)->paginate(20);
// Restablecer la paginación después de limitar los resultados
$resultados->setCollection($resultados->getCollection()->values());
//dd($consulta_historial);
return view('livewire.show-logs',['logs'=>$resultados]);
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace App\Http\Livewire;
use Illuminate\Http\Request;
use Livewire\Component;
use App\Models\recarga;
use App\Models\Saldo;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Auth;
use Jantinnerezo\LivewireAlert\LivewireAlert;
class ShowOrder extends Component
{
use LivewireAlert;
public $estado;
public function render()
{
return view('livewire.show-order');
}
}
+108
View File
@@ -0,0 +1,108 @@
<?php
namespace App\Http\Livewire;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Livewire\Component;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\WithFileUploads;
class ShowPerfil extends Component
{
use LivewireAlert;
use WithFileUploads;
public $nombre;
public $email;
public $celular;
public $cedula;
public $rol;
public $url_imagen;
public $url_imagen_d;
public $url;
public $modalPassword = false;
public $newPassword;
public function render()
{
if (empty($this->nombre)) {
$consulta_perfil = User::with('rol')->where('id', Auth()->user()->id)->first();
$this->nombre = $consulta_perfil->name;
$this->email = $consulta_perfil->email;
$this->celular = $consulta_perfil->celular;
$this->cedula = $consulta_perfil->cedula;
$this->rol = $consulta_perfil->rol->nombre;
$this->url_imagen_d = $consulta_perfil->img_perfil;
}
return view('livewire.show-perfil');
}
public function update()
{
if ($this->url_imagen) {
$this->url = $this->url_imagen->store('photos');
} else {
$this->url = null;
}
if (!empty($this->nombre) && !empty($this->email) && !empty($this->celular) && !empty($this->cedula)) {
User::where('id', Auth()->user()->id)->update([
'name' => $this->nombre,
'email' => $this->email,
'celular' => $this->celular,
'cedula' => $this->cedula,
'img_perfil' => $this->url
]);
$this->alert('success', 'La informacion se actualizo correctamente!', [
'position' => 'top'
]);
} else {
$this->alert('warning', 'Llene todos los campos!', [
'position' => 'top'
]);
}
}
public function cambiar_password()
{
$this->modalPassword = true;
}
public function confirmar()
{
$validatedData = $this->validate([
'newPassword' => 'required'
]);
User::where('id', Auth()->user()->id)->update([
'password' => Hash::make($this->newPassword),
]);
$this->alert('success', 'Contraseña actualizada correctamente!', [
'position' => 'top'
]);
$this->limpiarContra();
}
public function limpiarContra()
{
$this->newPassword = '';
$this->modalPassword = false;
}
}
+543
View File
@@ -0,0 +1,543 @@
<?php
namespace App\Http\Livewire;
use App\Models\Cuentas;
use App\Models\Historiale;
use App\Models\Historial_cuenta;
use App\Models\Role;
use App\Models\Servicio;
use App\Models\Tarifas;
use App\Models\user;
use Carbon\Carbon;
use Livewire\Component;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\WithFileUploads;
use Livewire\WithPagination;
class ShowPlanes extends Component
{
use LivewireAlert;
use WithFileUploads;
use WithPagination;
public $delete_cuenta;
public $informacionTarifaRol;
public $newCuenta = false;
public $renovar = false;
public $serviciosModal = false;
public $modTarifas = false;
public $roles_modTarifas;
public $pantallas_modTarifas;
public $precio_modTarifas = 0;
public $estadoTarifa = true;
public $diasTarifa = '30';
public $servicio_modTarifas;
public $buscar;
public $servicios_id;
public $fechaActual;
public $id_cuentaVer;
public $consulta_verUsuarios;
public $nombre_servicios = '';
public $nombre_servicio;
public $descripcion_servicio;
public $estado_servicio;
public $color_servicio;
public $servicio_newCuenta;
public $usuario_newCuenta;
public $password_newCuenta;
public $fecha_inicial;
public $fecha_final;
public $observacionesm = false;
public $observaciones;
public $id_observacion;
public $observacionesm1 = false;
public $observaciones1;
public $id_observacion1;
public $usuario_renovar;
public $password_renovar;
public $fecha_inicial_renovar;
public $fecha_final_renovar;
public $servicio;
public $photo;
public $photo_inicio;
public $estado='activo';
public $completa;
public $pantallas;
public $venceHoy;
public $activoHoy;
public $libres = null;
public $delete_1=['1'];
public $tarifas;
public $addUser;
public $usuarios;
public $selectedOption;
public $searchTerm = '';
public $tarifa;
public $perfil;
public $repetidas;
public $editarTarifaRol = false;
public function render()
{
$this->fechaActual = date('Y-m-d');
$consulta_tarifas = Tarifas::take(1);
if(empty($this->fecha_inicial)){
$this->fecha_inicial=Carbon::now()->format('Y-m-d');
$this->fecha_final=Carbon::now()->addDay(30)->format('Y-m-d');
}
if ($this->servicio_modTarifas) {
$this->tarifas = Tarifas::with('rol')
->where('servicio_id', $this->servicio_modTarifas)
->where('estado', 'activo')
->get();
}
// Empezamos definiendo la consulta básica
$consulta_cuentas = Cuentas::where('correo', 'LIKE', '%'.$this->buscar.'%')
->withCount('historiales')
->with('historiales')
->orderBy('id','DESC');
$consulta_cuentas = $consulta_cuentas->when(!empty($this->servicios_id), function ($query) {
return $query->where('servicio_id', $this->servicios_id);
})
->when(!empty($this->completa), function ($query) {
return $query->where('estado', 'pendiente');
})
->when(!empty($this->pantallas), function ($query) {
return $query->where('estado', 'activo');
})
->when(!empty($this->activoHoy), function ($query) {
$fechaHoy = Carbon::now()->subDay(1);
return $query->whereDate('vencimiento', '>', $fechaHoy);
})
->when($this->venceHoy, function ($query) {
$fechaHoy = Carbon::now()->addDay(1);
return $query->whereDate('vencimiento', '<', $fechaHoy);
})
->when($this->libres, function ($query) {
return $query->whereDoesntHave('historiales');
});
if (!empty($this->repetidas)) {
$consulta_cuentas = $consulta_cuentas->whereIn('correo', function ($subquery) {
$subquery->select('correo')
->from('cuentas')
->groupBy('correo')
->havingRaw('COUNT(*) > 1');
});
}
$consulta_cuentas = $consulta_cuentas->paginate(30);
if ( $this->searchTerm) {
$this->usuarios = User::where('email', 'LIKE', '%' . $this->searchTerm . '%')->get();
if ($this->selectedOption) {
$this->searchTerm = $this->selectedOption;
}
}else{
$this->selectedOption = null;
}
return view('livewire.show-planes', [
'cuentas' => $consulta_cuentas,
'servicios' => Servicio::where('estado','activo')->get(),
'roles' => Role::get()
]);
}
//modal Ver
public function ver($id, $nom)
{
$this->id_cuentaVer = $id;
$this->consulta_verUsuarios = Cuentas::with('historiales','servicio')->where('id', $id)->first();
//dd($this->consulta_verUsuarios);
$this->nombre_servicios = $nom;
}
public function openRenovar()
{
$this->renovar = true;
$id = $this->id_cuentaVer;
$renovarCuenta = Cuentas::findOrFail($id);
$this->usuario_renovar = $renovarCuenta->correo;
$this->password_renovar = $renovarCuenta->password;
$this->fecha_inicial_renovar = $renovarCuenta->inicio;
$this->fecha_final_renovar = $renovarCuenta->vencimiento;
$this->estado = $renovarCuenta->estado;
}
public function saveRenovar()
{
$id = $this->id_cuentaVer;
Cuentas::where('id', $id)->update([
'correo' => $this->usuario_renovar,
'password' => $this->password_renovar,
'inicio' => date('Y-m-d', strtotime(strval($this->fecha_inicial_renovar))),
'vencimiento' => date('Y-m-d', strtotime(strval($this->fecha_final_renovar))),
'estado' => $this->estado,
]);
$this->alert('success', 'Cuenta renovada correctamente!', [
'position' => 'top'
]);
$this->renovar = false;
}
/* ------------- CREAR ------------- */
public function createNewCuenta()
{
$this->validate([
'servicio_newCuenta' => 'required',
'usuario_newCuenta' => 'required',
'password_newCuenta' => 'required',
'fecha_inicial' => 'required',
'fecha_final' => 'required',
'estado' => 'required',
]);
if($consulta_cuenta = Cuentas::where('correo',$this->usuario_newCuenta)->exists()){
$this->alert('warning', 'La cuenta ya existe', [
'position' => 'top'
]);
}else{
$cuenta = new Cuentas;
$cuenta->servicio_id = $this->servicio_newCuenta;
$cuenta->correo = $this->usuario_newCuenta;
$cuenta->password = $this->password_newCuenta;
$cuenta->inicio = date('Y-m-d', strtotime(strval($this->fecha_inicial)));
$cuenta->vencimiento = date('Y-m-d', strtotime(strval($this->fecha_final)));
$cuenta->estado = $this->estado;
$cuenta->save();
$this->alert('success', 'Cuenta creada correctamente!', [
'position' => 'top'
]);
$this->limpiarInputNewCuenta();
$this->newCuenta = false;
}
}
public function createServicio()
{
$url_foto = $this->photo->store('photos');
$url_foto_inicio = $this->photo_inicio->store('photos');
$servicio = new Servicio;
$servicio->nombre = $this->nombre_servicio;
$servicio->descripcion = $this->descripcion_servicio;
$servicio->estado = $this->estado_servicio;
$servicio->color_fondo = $this->color_servicio;
$servicio->pantallas = '6';
$servicio->img = $url_foto;
$servicio->img_inicio = $url_foto_inicio;
$servicio->save();
$this->alert('success', 'Servicio creado correctamente!', [
'position' => 'top'
]);
$this->serviciosModal = false;
}
public function verObservacion($id)
{
$verObservacion = Historiale::findOrFail($id);
$this->id_observacion = $id;
$this->observaciones = $verObservacion->observaciones;
}
public function update()
{
Historiale::where('id', $this->id_observacion)->update(['observaciones' => $this->observaciones,]);
$this->alert('success', 'Observacion añadida correctamente!', [
'position' => 'top'
]);
$this->observacionesm = false;
}
public function verObservacion1($id)
{
$verObservacion = Cuentas::findOrFail($id);
$this->id_observacion1 = $id;
$this->observaciones1 = $verObservacion->observaciones;
}
public function update_observaciones1()
{
Cuentas::where('id', $this->id_observacion1)->update(['observaciones' => $this->observaciones1,]);
$this->alert('success', 'Observacion añadida correctamente!', [
'position' => 'top'
]);
$this->observacionesm1 = false;
}
public function delete_cuenta($id)
{
$this->delete_cuenta = $id;
$this->alert('warning', '¿Eliminar cuenta?', [
'position' => 'center',
'timer' => '10000',
'toast' => false,
'text' => 'Esta seguro',
'showConfirmButton' => true,
'onConfirmed' => 'confirmed',
'showDenyButton' => false,
'onDenied' => '',
'showCancelButton' => true,
'onDismissed' => '',
'cancelButtonText' => 'Salir',
'confirmButtonText' => 'Si',
]);
}
public function getListeners()
{
return [
'confirmed'
];
}
public function confirmed()
{
Cuentas::where('id', $this->delete_cuenta)->delete();
$this->alert('success', 'Cuenta eliminada correctamente!', [
'position' => 'top'
]);
}
/* ------------- ACTUALIZAR ------------- */
public function updateTarifas()
{
$consulta_existe = Tarifas::where('pantallas', $this->pantallas_modTarifas)
->where('servicio_id', $this->servicio_modTarifas)
->where('rol_id', $this->roles_modTarifas)
->where('dias', $this->diasTarifa)
->exists();
if ($consulta_existe) {
$this->alert('warning', '¡Esta tarifa ya existe!', [
'position' => 'top'
]);
} elseif (empty($this->servicio_modTarifas)) {
$this->alert('warning', '¡Seleccione un servicio!', [
'position' => 'top'
]);
} elseif (empty($this->precio_modTarifas)) {
$this->alert('warning', '¡Coloque un precio!', [
'position' => 'top'
]);
} else {
$tarifa = new Tarifas;
$tarifa->pantallas = $this->pantallas_modTarifas;
$tarifa->dias = $this->diasTarifa;
$tarifa->valor = $this->precio_modTarifas;
$tarifa->estado = $this->estadoTarifa ? 'activo' : 'inactivo';
$tarifa->servicio_id = $this->servicio_modTarifas;
$tarifa->rol_id = $this->roles_modTarifas;
$tarifa->save();
$this->alert('success', '¡Tarifas actualizadas correctamente!', [
'position' => 'top'
]);
}
}
/* ------------- ELIMINAR ------------- */
public function eliminarModTarifa($id)
{
Tarifas::where('id',$id)->delete();
$this->alert('success', 'Tarifas eliminada correctamente!', [
'position' => 'top'
]);
}
/* ------------- LIMPIAR CAMPOS ------------- */
public function limpiarInputObservaciones()
{
$this->observaciones = '';
}
public function limpiarInputObservaciones1()
{
$this->observaciones1 = '';
$this->observacionesm1 = false;
}
public function limpiarInputNewCuenta()
{
$this->servicio_newCuenta = null;
$this->usuario_newCuenta = '';
$this->password_newCuenta = '';
$this->fecha_inicial = null;
$this->fecha_final = null;
$this->newCuenta = false;
}
public function limpiarInputServiciosModal()
{
$this->nombre_servicio = '';
$this->descripcion_servicio = '';
$this->estado_servicio = null;
$this->color_servicio = null;
}
public function eliminarCuentas(){
$consulta_cuentas = Cuentas::whereIn('id',$this->delete_1)->delete();
}
public function openAdd(){
$this->addUser = true;
}
public function saveUser(){
$this->validate([
'tarifa' => 'required',
]);
$tarifa = json_decode($this->tarifa, true);
//dd($this->tarifa['dias']);
$usuario_existe = User::firstWhere('email', $this->searchTerm)->id ?? null;
$usuario_id = $usuario_existe;
if (is_null($usuario_existe)) {
$rol_id=Role::where('nombre','cliente')->value('id');
$usuario = new User;
$usuario->name = 'AssignedUser';
$usuario->email = $this->searchTerm;
$usuario->password = '123456';
$usuario->celular = '+57';
$usuario->rol_id = $rol_id;
$usuario->save();
$usuario_id = $usuario->id;
}
$historial = new Historiale;
$historial->fecha_inicio = Carbon::now();
$historial->fecha_final = Carbon::now()->addDay($tarifa['dias']);
$historial->valor = '0';
$historial->tipo_pago = 'manual';
$historial->estado = 'activo';
$historial->vendedor_id = Auth()->user()->id;
$historial->tarifa_id = $tarifa['id'];
$historial->cliente_id = $usuario_id;
$historial->cantidad = $tarifa['pantallas'];
$historial->save();
$consultaHC = Historial_cuenta::where('cuenta_id',$this->consulta_verUsuarios->id)->where('perfil',$this->perfil)->exists();
if (!$consultaHC) {
$historial_cuenta = new Historial_cuenta;
$historial_cuenta->cuenta_id = $this->consulta_verUsuarios->id;
$historial_cuenta->historial_id = $historial->id;
$historial_cuenta->perfil = $this->perfil;
$historial_cuenta->save();
$this->alert('success', 'Usuario añadido correctamente!', [
'position' => 'top'
]);
$this->addUser = false;
$this->consulta_verUsuarios = Cuentas::with('historiales','servicio')->where('id', $this->id_cuentaVer)->first();
}else{
$historial->delete();
$this->alert('warning', 'El perfil ya se encuentra en uso!', [
'position' => 'top'
]);
}
}
public function editar($tarifa){
//dd($tarifa);
$this->editarTarifaRol=true;
$this->informacionTarifaRol = $tarifa;
$this->roles_modTarifas = $tarifa['rol_id'];
$this->pantallas_modTarifas = $tarifa['pantallas'];
$this->precio_modTarifas = $tarifa['valor'];
$this->diasTarifa = $tarifa['dias'];
$this->estadoTarifa = $tarifa['estado'];
$this->servicio_modTarifas = $tarifa['servicio_id'];
}
public function actualizarTarifaRol($id){
//dd($id);
$validateData = $this->validate([
'roles_modTarifas'=> 'required',
'pantallas_modTarifas' => 'required',
'precio_modTarifas'=> 'required',
'diasTarifa' => 'required',
'estadoTarifa'=> 'required'
]);
$consulta = Tarifas::find($id)->update([
'pantallas' => $this->pantallas_modTarifas,
'dias' => $this->diasTarifa,
'valor'=> $this->precio_modTarifas,
'estado'=> $this->estadoTarifa,
'rol_id' => $this->roles_modTarifas,
'servicio_id' => $this->servicio_modTarifas
]);
$this->alert('success', 'Tarifa actualizada correctamente!', [
'position' => 'top'
]);
$this->editarTarifaRol = false;
}
}
+674
View File
@@ -0,0 +1,674 @@
<?php
namespace App\Http\Livewire;
use App\Models\Categoria;
use App\Models\Configuracione;
use App\Models\Cuentas;
use App\Models\Historial_cuenta;
use App\Models\Historiale;
use App\Models\Promocion_tarifa;
use App\Models\Promociones;
use App\Models\Saldo;
use App\Models\Tarifas;
use App\Models\User;
use App\Notifications\compra;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Notification;
use Livewire\Component;
use Livewire\WithFileUploads;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Intervention\Image\ImageManagerStatic as Img;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
use Exception;
use Twilio\Rest\Client;
use AshAllenDesign\ShortURL\Facades\ShortURL;
class ShowPromociones extends Component
{
use WithFileUploads;
use LivewireAlert;
public $categoria_id;
public $eliminar_id;
public $list;
public $list2;
public $categorian;
public $photo;
public $newPromocion = false;
public $nombre_promocion;
public $descripcion_promocion;
public $valor_promocion;
public $estado_promocion;
public $fecha_limite_promocion;
public $categoria_id_promocion;
public $fechaFinal;
public $tarifa_id_promocion;
public $dias_comprarPromo;
public $valor_comprarPromo;
public $nombre_comprarPromo;
public $celular_comprarPromo;
public $email_comprarPromo;
public $cantidad_comprarPromo = 1;
public $newCategoria = false;
public $nombre_categoria;
public $descripcion_categoria;
public $modalComprarPromo = false;
public $verPromo = false;
public $precioAntes;
public $precioAhora;
public $fechaLimite;
public $nombrePromo;
public $descripcionPromo;
public $editarPromo = false;
public $nombre_editarPromo;
public $descripcion_editarPromo;
public $valor_editarPromo;
public $estado_editarPromo;
public $fecha_limite_editarPromo;
public $categoria_id_editarPromo;
public $editar_promo_id;
public $imagen;
public $dias;
public $total;
public $consulta;
public $fechaHoy;
public $fechafinal;
public $fecha;
public $credenciales;
public $cuentas;
public $img_ver;
public $fecha_editarPromo;
public $mensaje_servicio;
public $categoria_photo;
protected $rules = [
'nombre_comprarPromo' => 'required',
'celular_comprarPromo' => 'required',
'email_comprarPromo' => 'required',
'cantidad_comprarPromo' => 'required',
];
public function render()
{
$date = Carbon::now()->subDay(30);
$this->fecha= $date->format('Y-m-d');
$this->fechaActual = Carbon::now();
$this->fechaActual = Carbon::parse($this->fechaActual);
$this->fechaHoy = Carbon::now();
$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();
//$this->fechaHoy = $this->fechaHoy->format('d/m/Y');
if (empty($this->nombre_comprarPromo) && empty($this->email_comprarPromo)) {
$usuario_actual = Auth::user();
$this-> nombre_comprarPromo = $usuario_actual->name;
$this-> email_comprarPromo = $usuario_actual->email;
$this-> celular_comprarPromo = $usuario_actual->celular;
//dd($this-> nombre_tarjetaPlan);
}
return view('livewire.show-promociones', [
'categorias' => Categoria::get(),
'tarifas' => Tarifas::with('servicio')->get(),
]);
}
public function verPromocion($id)
{
$consulta_verpromocion = Promociones::with('tarifas')->where('id', $id)->with([
'usuario_promos' => function ($query) {
$query->where('usuario_id', Auth::user()->id);
},
'tarifaPromo' => function ($query) {
$query->where('rol_id', Auth::user()->rol->id);
}
])->first();
//dd($consulta_verpromocion);
//$cuentas_creadas = Cuentas::whereDate('inicio','>=',$this->fecha)->where('servicio_id',$tarifas->servicio->id)->where('estado','!=','inactivo')->where('estado','!=','delete')->get();
$this->consulta = $consulta_verpromocion;
// $this->precioAntes = $consulta_verpromocion->tarifas->first()->valor;
if (!empty($precio= $consulta_verpromocion->usuario_promos->first())) {
$this->precioAhora = $precio->precio;
}else if(!empty($precio= $consulta_verpromocion->tarifaPromo->first())){
$this->precioAhora = $precio->precio;
}else{
$this->precioAhora = $consulta_verpromocion->precio;
}
$this->imagen = $consulta_verpromocion->img_publicidad;
$this->fechaLimite = $consulta_verpromocion->fecha_limite;
$this->nombrePromo = $consulta_verpromocion->nombre;
$this->dias = $consulta_verpromocion->dias;
$this->descripcionPromo = $consulta_verpromocion->descripcion;
$this->fechaFinal = $this->fechaActual->addDay($this->dias);
$this->mensaje_servicio = $consulta_verpromocion->mensaje;
$this->verPromo = true;
}
public function comprarPromo($id)
{
$consulta_verpromocion = Promociones::with('tarifas')->where('id', $id)->first();
$this->consulta = $consulta_verpromocion;
//$this->precioAntes = $consulta_verpromocion->tarifas->first()->valor;
$this->precioAhora = $consulta_verpromocion->precio;
$this->imagen = $consulta_verpromocion->img_publicidad;
$this->fechaLimite = $consulta_verpromocion->fecha_limite;
$this->nombrePromo = $consulta_verpromocion->nombre;
$this->dias = $consulta_verpromocion->dias;
$this->descripcionPromo = $consulta_verpromocion->descripcion;
$this->fechaFinal = $this->fechaActual->addDay($this->dias);
$this->mensaje_servicio = $consulta_verpromocion->mensaje;
$this->modalComprarPromo = true;
}
/* ---------------- Btn Comprar ---------------- */
public function pagar()
{
$this->validate();
$usuario_existe = User::firstWhere('email', $this->email_comprarPromo)->id ?? null;
if (is_null($usuario_existe)) {
$usuario = new User;
$usuario->name = $this->nombre_comprarPromo;
$usuario->email = $this->email_comprarPromo;
$usuario->password = '123';
$usuario->celular = $this->celular_comprarPromo;
$usuario->save();
$usuario_id = $usuario->id;
} else {
$usuario_id = $usuario_existe;
}
$historial = new Historiale();
$historial->fecha_inicio = $this->fechaHoy;
$historial->fecha_final = $this->fechaFinal;
$historial->valor = $this->precioAhora *$this->cantidad_comprarPromo;
$historial->tipo_pago = 'manual';
$historial->estado = 'pendiente';
$historial->vendedor_id = Auth()->user()->id;
$historial->promocion_id = $this->consulta->id;
$historial->cliente_id = $usuario_id;
$historial->cantidad = $this->cantidad_comprarPromo;
$historial->nombre_cliente = $this->nombre_comprarPromo;
$historial->save();
for ($p = 0; $p < (int)$this->cantidad_comprarPromo; $p++) {
//dd($this->cantidad_comprarPromo);
$n=[];
$r=0;
foreach ($this->consulta->tarifas as $tarifa) {
$r=$r+$tarifa->pantallas;
//dd($this->consulta->tarifas->count());
$pantallas_tarifa = $tarifa->pantallas;
$servicio_id = $tarifa->servicio_id;
$pantalla_servicio = $tarifa->servicio->pantallas;
$pantalla_servicio_completa = $tarifa->servicio->completa;
$faltante = $pantalla_servicio - $pantallas_tarifa;
//dd($tarifa);
if ($pantalla_servicio_completa == $pantallas_tarifa) {
$this->fecha_final_1 = $today = Carbon::now()->addDays($tarifa->dias-20);
$this->fecha_final_2 = $today = Carbon::now()->addDays($tarifa->dias+20);
$cuenta = Cuentas::where('servicio_id',$servicio_id)->whereDate('inicio','>=',$this->fecha)->whereDate('vencimiento','>=',$this->fecha_final_1)
->whereDate('vencimiento','<=',$this->fecha_final_2)
->Orderby('created_at', 'ASC')->with('historiales')->withCount('historiales')->where('estado','pendiente')->having('historiales_count', '==', 0)->first();
}else{
$cuenta = Cuentas::where('servicio_id', $servicio_id)->whereDate('inicio','>=',$this->fecha)->Orderby('created_at', 'ASC')->with('historiales')->withCount('historiales')->where('estado', 'activo')->having('historiales_count', '<=', (int)$faltante)->first();
}
if (!is_null($cuenta)) {
$perfil = $cuenta->historiales_count;
for ($y = 0; $y < (int)$pantallas_tarifa; $y++) {
$historial_cuenta = new Historial_cuenta();
$historial_cuenta->cuenta_id = $cuenta->id;
$historial_cuenta->historial_id = $historial->id;
$historial_cuenta->perfil = (int)$perfil + (int)$y+1;
$historial_cuenta->save();
if (!empty($historial_cuenta->id)) {
array_push($n,$historial_cuenta->id);
}
}
} else {
$this->alert('warning', 'No hay cuentas disponibles de '.$tarifa->servicio->nombre, [
'position' => 'top'
]);
}
$cuenta=null;
}
}
//dump($r, count($n));
if ($r == count($n) ) {
$descuento = Saldo::where('usuario_id', Auth::user()->id)->first();
$saldo_anterior = $descuento->valor;
$nuevo_saldo = $saldo_anterior - ($this->precioAhora *$this->cantidad_comprarPromo);
$cobro = $descuento->update(['valor' => $nuevo_saldo]);
//dd($cobro);
if ($cobro) {
$historial->update(['estado' => 'activo']);
$this->modalComprarPromo = false;
$this->credenciales($historial);
} else {
$eliminar = Historial_cuenta::whereIn('id',$n)->delete();
//dd($eliminar);
$this->alert('warning', 'Error en el cobro, comuniquese con soporte!', [
'position' => 'top'
]);
}
$n=null;
}else{
$eliminar = Historial_cuenta::whereIn('id',$n)->delete();
//dump($eliminar);
$this->alert('warning', 'No hay promociones disponibles, comuniquese con soporte!', [
'position' => 'top'
]);
$n=null;
}
}
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->promocion->nombre,
'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->promocion->nombre.'. Ver credenciales: '.$shortURL ;
$recipients= '+57'.$this->celular_comprarPromo;
$this->sendMessage($message, $recipients);
$this->cantidad_comprarPromo = 1;
}
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 create_newCategoria()
{
if (!empty($this->categoria_photo)) {
$url_foto = $this->categoria_photo->store('photos');
}else{
$url_foto = '';
}
$categoria = new Categoria;
$categoria->nombre = $this->nombre_categoria;
$categoria->descripcion = $this->descripcion_categoria;
$categoria->imagen = $url_foto;
$categoria->save();
$this->newCategoria = false;
}
public function add_tarifa()
{
$consulta= Tarifas::find($this->tarifa_id_promocion);
$promocion_tarifa = new Promocion_tarifa;
$promocion_tarifa->tarifa_id = $this->tarifa_id_promocion;
$promocion_tarifa->nombre = $consulta->servicio->nombre;
$promocion_tarifa->cantidad = $consulta->pantallas;
$promocion_tarifa->dias = $consulta->dias;
if (is_null($this->list)) {
$this->list = collect();
}
$this->list->add($promocion_tarifa);
}
public function del_item($id)
{
$this->list->pull($id);
}
public function guardar()
{
$this->validate([
'nombre_promocion' => 'required',
'descripcion_promocion' => 'required',
'valor_promocion' => 'required',
'estado_promocion' => 'required',
'fecha_limite_promocion' => 'required',
'categoria_id_promocion' => 'required',
'photo' => 'required',
'list'=>'required',
]);
if (!empty($this->photo)) {
$nombre=Str::random(10);
$img = img::make($this->photo)->orientate()->resize(1000, null, function($constraint){
$constraint->aspectRatio();
$constraint->upsize();
})->encode('webp');
$location = "photos/".$nombre.".webp";
Storage::disk('local')->put($location, $img);
$url_foto = $location;
} else {
$url_foto = null;
}
$nueva_promocion = new Promociones;
$nueva_promocion->nombre = $this->nombre_promocion;
$nueva_promocion->descripcion = $this->descripcion_promocion;
$nueva_promocion->precio = $this->valor_promocion;
$nueva_promocion->visible = $this->estado_promocion;
$nueva_promocion->fecha_limite = $this->fecha_limite_promocion;
$nueva_promocion->categoria_id = $this->categoria_id_promocion;
$nueva_promocion->img_publicidad = $url_foto;
$nueva_promocion->dias = 30;
$nueva_promocion->mensaje = $this->mensaje_servicio;
$nueva_promocion->save();
foreach ($this->list as $item) {
$guardar_promotarifa = new Promocion_tarifa;
$guardar_promotarifa->promocion_id = $nueva_promocion->id;
$guardar_promotarifa->tarifa_id = $item['tarifa_id']; //falta
$guardar_promotarifa->save();
}
$this->newPromocion = false;
$this->alert('success', 'Promocion creada correctamente!', [
'position' => 'top'
]);
$this->limpiarInputPromocion();
}
public function eliminar($id)
{
$this->eliminar_id = $id;
$this->alert('warning', '¿Eliminar promocion?', [
'position' => 'center',
'timer' => '10000',
'toast' => false,
'text' => 'Esta seguro',
'showConfirmButton' => true,
'onConfirmed' => 'confirmed',
'showDenyButton' => false,
'onDenied' => '',
'showCancelButton' => true,
'onDismissed' => '',
'cancelButtonText' => 'Salir',
'confirmButtonText' => 'Si',
]);
}
public function getListeners()
{
return [
'confirmed'
];
}
public function confirmed()
{
$consulta_promociones = Promociones::findOrFail($this->eliminar_id);
$nombre = $consulta_promociones->nombre;
Promociones::where('id', $this->eliminar_id)->update([
'nombre' => $nombre . '-Delete',
'visible' => 'false',
]);
}
/* ---------------- Editar Promocion ---------------- */
public function editarPromo($id)
{
$promocion = Promociones::where('id', $id)->first();
// $this->imagen_editarPromo= $promocion->img_publicidad;
$this->editar_promo_id = $promocion->id;
$this->valor_editarPromo = $promocion->precio;
$this->fecha_editarPromo = $promocion->fecha_limite;
$this->nombre_editarPromo = $promocion->nombre;
$this->descripcion_editarPromo = $promocion->descripcion;
$this->estado_editarPromo = $promocion->visible;
$this->categoria_id_editarPromo = $promocion->categoria_id;
$this->img_ver = $promocion->img_publicidad;
$this->mensaje_servicio = $promocion->mensaje;
$consultas = Promocion_tarifa::selectRaw('promocion_tarifas.id as id, servicios.nombre as nombre, tarifas.pantallas as pantallas ')
->join('tarifas', 'tarifas.id', '=', 'promocion_tarifas.tarifa_id')
->join('servicios', 'servicios.id', '=', 'tarifas.servicio_id')
->where('promocion_tarifas.promocion_id',$this->editar_promo_id)
->get();
$this->list2 = collect();
foreach ($consultas as $consulta) {
$promocionTarifa = new Promocion_tarifa;
$promocionTarifa->tarifa_id = $this->tarifa_id_promocion;
$promocionTarifa->nombre = $consulta->nombre ;
$promocionTarifa->cantidad = $consulta->pantallas;
$promocionTarifa->identificador = $consulta->id;
$promocionTarifa->dias = $consulta->dias;
$this->list2->add($promocionTarifa);
}
$this->editarPromo = true;
}
public function editarPromoUpdate()
{
if (!empty($this->photo)) {
$nombre=Str::random(10);
$img = img::make($this->photo)->orientate()->resize(1000, null, function($constraint){
$constraint->aspectRatio();
$constraint->upsize();
})->encode('webp');
$location = "photos/".$nombre.".webp";
Storage::disk('local')->put($location, $img);
$url_foto = $location;
} else {
$url_foto = $this->img_ver;
}
Promociones::where('id', $this->editar_promo_id)->update([
'precio' => $this->valor_editarPromo,
'fecha_limite' => $this->fecha_editarPromo,
'visible' => $this->estado_editarPromo,
'categoria_id' => $this->categoria_id_editarPromo,
'nombre' => $this->nombre_editarPromo,
'descripcion' => $this->descripcion_editarPromo,
'img_publicidad' => $url_foto,
'mensaje' => $this->mensaje_servicio,
]);
$this->editarPromo = false;
$this->list2 = null;
$this->limpiarInputPromocion();
}
public function add_tarifa_list2()
{
$add = new Promocion_tarifa;
$add->promocion_id = $this->editar_promo_id;
$add->tarifa_id = $this->tarifa_id_promocion;
$add->save();
$consultas = Promocion_tarifa::selectRaw('promocion_tarifas.id as id, servicios.nombre as nombre, tarifas.pantallas as pantallas ')
->join('tarifas', 'tarifas.id', '=', 'promocion_tarifas.tarifa_id')
->join('servicios', 'servicios.id', '=', 'tarifas.servicio_id')
->where('promocion_tarifas.promocion_id',$this->editar_promo_id)
->get();
$this->list2 = collect();
foreach ($consultas as $consulta) {
$promocionTarifa = new Promocion_tarifa;
$promocionTarifa->tarifa_id = $this->tarifa_id_promocion;
$promocionTarifa->nombre = $consulta->nombre ;
$promocionTarifa->cantidad = $consulta->pantallas;
$promocionTarifa->identificador = $consulta->id;
$this->list2->add($promocionTarifa);
}
}
public function del_item_list2($id,$n)
{
Promocion_tarifa::where('id',$id)->delete();
$this->list2->pull($n);
$this->alert('success', 'Tarifa de usuario eliminada correctamente!', [
'position' => 'top'
]);
}
public function limpiarInputPromocion()
{
$this->nombre_promocion = '';
$this->descripcion_promocion = '';
$this->valor_promocion = '';
$this->estado_promocion = null;
$this->fecha_limite_promocion = null;
$this->categoria_id_promocion = null;
$this->newCategoria = false;
$this->newPromocion = false;
$this->photo = null;
$this->mensaje_servicio=null;
$this->list = null;
}
}
+199
View File
@@ -0,0 +1,199 @@
<?php
namespace App\Http\Livewire;
use DateInterval;
use DateTime;
use Exception;
use constants;
use App\Models\recarga;
use App\Models\Saldo;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use WpOrg\Requests\Requests;
class ShowRecarga extends Component
{
use LivewireAlert;
public $numero_nequi;
public $valor_recarga;
public $nequi =false;
public $cobrar = false;
public $monto = 0;
public function render()
{
// $this->fechaActual = date('d/m/Y');
if (auth()->user()->rol->nombre == "super" || auth()->user()->rol->nombre == "administrador" || auth()->user()->rol->nombre == "distribuidor") {
$this->cobrar = true;
$this->monto = "500";
}
$consulta_historial = recarga::where('usuario_id',Auth::user()->id)->orderBy('id','DESC')->limit(20)->get();
$consulta_saldo = User::where('id',Auth::user()->id)->with('saldo')->first();
return view('livewire.show-recarga',[
'user' => $consulta_saldo,
'historial_recargas' => $consulta_historial
]);
}
public function pagar(){
//auth2.0
$client_id='5ml5b35ijjk13f4q99utnsm97e';
$client_secret='1b3703aq0o6t1rrfti13q7uf7f42glik3gsf81s0d783shblmt8l';
$api_key='aHLdWJTpuM9YYnV9ruq4V6bH5esa8wUN69E1qmrM';
$endpoint="https://oauth.sandbox.nequi.com/oauth2/token?grant_type=client_credentials";
$date= Carbon::now()->format('Y-m-d\TH:i:s.z\Z');
//dd($date);
//dd($this->numero_nequi);
//push
$RestEndpoint = '/payments/v2/-services-paymentservice-unregisteredpayment';
try{
$authorization = 'Basic ' . base64_encode($client_id . ':' . $client_secret);
$headers = array(
'Content-Type' => 'application/x-www-form-urlencoded',
'Accept' => 'application/json',
'Authorization' => $authorization
);
//Solicitud
$request = Requests::post($endpoint, $headers);
if (isset($request->status_code) && $request->status_code == 200 && isset($request->body) && !empty($request->body))
{
$response = json_decode($request->body);
$tokenExpiresAt = new DateTime();
$tokenExpiresAt->add(new DateInterval('PT' . $response->expires_in . 'S'));
$token = $response->access_token;
$tokenType = $response->token_type;
} else {
throw new Exception('Unable to connect to Nequi, please check the information sent.');
}
}catch(Exception $e){
throw $e;
}
// pago
$headers1 = array(
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'Authorization' => $token,
'x-api-key' => $api_key
);
$options1 = array(
'timeout' => 30
);
$endpoint1 = 'https://api.sandbox.nequi.com' . $RestEndpoint;
$body1 = json_encode(array(
'RequestMessage' => array(
'RequestHeader' => array(
'Channel' => 'PNP04-C001',
'RequestDate' => $date,
'MessageID' => '1234567890',
'ClientID' => $client_id,
'Destination' => array(
'ServiceName' => 'PaymentsService',
'ServiceOperation' => 'unregisteredPayment',
'ServiceRegion' => 'C001',
'ServiceVersion' => '1.2.0'
)
),
'RequestBody' => array(
'any' => array(
'unregisteredPaymentRQ' => array(
'phoneNumber'=> $this->numero_nequi,
'code' => 'NIT_1',
'value' => $this->valor_recarga,
'reference1' => 'Recarga SirPremium',
)
)
)
)
));
$request1 = Requests::post($endpoint1, $headers1, $body1, $options1);
if (isset($request1->status_code) && $request1->status_code == 200 && isset($request1->body) && !empty($request1->body)
) {
try {
$response1 = json_decode($request1->body);
//dd($response1 = json_decode($request1->body));
$status = $response1->ResponseMessage->ResponseHeader->Status;
$statusCode = isset($status) ? $status->StatusCode : '';
$statusDesc = isset($status) ? $status->StatusDesc : '';
if ($statusCode == 0) {
$this->alert('success', 'Solicitud de pago enviada', [
'position' => 'top'
]);
$payment = $response1->ResponseMessage->ResponseBody->any->unregisteredPaymentRS;
$trnId = isset($payment) ? trim($payment->transactionId) : '';
if ( !empty($trnId)) {
$recarga = new recarga;
$recarga-> payment_type_id= '';
$recarga-> payment_method_id= '';
$recarga-> status= $statusCode;
$recarga-> usuario_id= Auth::user()->id;
$recarga-> saldo_id= Auth::user()->saldo->id;
$recarga-> monto= $this->valor_recarga;
$recarga->save();
$consulta_saldo = Saldo::where('usuario_id',Auth::user()->id)->first();
$nuevo_saldo = $consulta_saldo->valor + $this->valor_recarga ;
$consulta_saldo->update(['valor'=> $nuevo_saldo]);
$this->alert('success', 'Saldo actualizado', [
'position' => 'top'
]);
$this->nequi = false;
}
$this->alert('success', $trnId, [
'position' => 'top'
]);
} else {
$this->alert('warning', $statusCode . ' = ' . $statusDesc, [
'position' => 'top'
]);
}
} catch (Exception $e) {
throw $e;
}
} else {
$this->alert('wanrning','Unable to connect to Nequi, please check the information sent', [
'position' => 'top'
]);
}
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Models\recarga;
class ShowRecargas extends Component
{
public $monto;
public $referencia;
public function render(Request $request)
{
if (empty($this->referencia)){
$this->referencia = Str::random(20);
$this->monto = (((($request->recharge)*0.03) + '700' )* 0.19)+ ((($request->recharge)*0.03) + '700' ) + $request->recharge;
$recargas = new recarga;
$recargas->monto = $this->monto;
$recargas->reference = $this->referencia;
$recargas-> status = 'Procesando MP';
$recargas-> usuario_id = auth()->user()->id;
$recargas-> saldo_id= auth()->user()->saldo->id;
$recargas-> valor_recarga = $request->recharge;
$recargas->save();
}
return view('livewire.show-recargas');
}
}
+74
View File
@@ -0,0 +1,74 @@
<?php
namespace App\Http\Livewire;
use App\Models\Historiale;
use App\Models\Role;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\WithPagination;
class ShowReportes extends Component
{
use LivewireAlert;
use WithPagination;
public $fecha;
public $mes;
public $usuario;
public function render()
{
// $this->fechaActual = Carbon::now();
// $this->fechaActual = Carbon::parse($this->fechaActual);
if(!empty($this->usuario)){
$id_user = $this->usuario;
$consulta_suma = Historiale::where('vendedor_id', $id_user)->sum('valor');
$consulta_cantidad = Historiale::where('vendedor_id', $id_user)->count();
if (!empty($this->mes)) {
$consulta_suma = Historiale::where('vendedor_id', $id_user)->whereMonth('created_at',$this->mes)->sum('valor');
$consulta_cantidad = Historiale::where('vendedor_id', $id_user)->whereMonth('created_at',$this->mes)->count();
}
}elseif(empty($this->usuario)){
if(auth()->user()->rol->nombre == "super" || auth()->user()->rol->nombre == "administrador"){
$consulta_suma = Historiale::sum('valor');
$consulta_cantidad = Historiale::count();
}else{
$consulta_suma = Historiale::where('vendedor_id', auth()->user()->id)->whereMonth('created_at',$this->mes)->sum('valor');
$consulta_cantidad = Historiale::where('vendedor_id', auth()->user()->id)->whereMonth('created_at',$this->mes)->count();
}
if (!empty($this->mes)) {
$consulta_suma = Historiale::whereMonth('created_at',$this->mes)->sum('valor');
$consulta_cantidad = Historiale::whereMonth('created_at',$this->mes)->count();
}
}
$distribuidores = Role::where('nombre','distribuidor')->with('usuarios')->first();
$historial = Historiale::where('cliente_id', auth()->user()->id)->orderBy('id','DESC')->paginate(10);
//dd($historial);
return view('livewire.show-reportes',[
'suma' => $consulta_suma,
'cantidad' => $consulta_cantidad,
'roles' => $distribuidores,
'historiales' => $historial,
]);
}
}
+102
View File
@@ -0,0 +1,102 @@
<?php
namespace App\Http\Livewire;
use App\Models\Role;
use Livewire\Component;
use Jantinnerezo\LivewireAlert\LivewireAlert;
class ShowRoles extends Component
{
use LivewireAlert;
public $editar= false;
public $nombre;
public $add;
public $ro;
public function render()
{
$consulta_roles = Role::withCount('usuarios')->get();
//dd($consulta_roles);
return view('livewire.show-roles',['roles'=>$consulta_roles]);
}
public function editar($id){
$this->nombre = Role::find($id)->nombre;
$this->ro = $id;
$this->editar = true;
}
public function crear(){
if (!empty($this->nombre)) {
$crear_rol = new Role;
$crear_rol->nombre = $this->nombre;
$crear_rol->save();
$this->alert('success', 'Rol creado correctamente!', [
'position' => 'top'
]);
$this->add = false;
}else{
$this->alert('warning', 'Campo Nombre sin diligenciar!', [
'position' => 'top'
]);
}
}
public function eliminar($id)
{
$this->ro = $id;
$this->alert('warning', '¿Eliminar rol?', [
'position' => 'center',
'timer' => '10000',
'toast' => false,
'text' => 'Esta seguro',
'showConfirmButton' => true,
'onConfirmed' => 'confirmed',
'showDenyButton' => false,
'onDenied' => '',
'showCancelButton' => true,
'onDismissed' => '',
'cancelButtonText' => 'Salir',
'confirmButtonText' => 'Si',
]);
}
public function getListeners()
{
return [
'confirmed'
];
}
public function confirmed()
{
$eliminar= Role::find($this->ro)->delete();
$this->alert('success', 'Rol eliminado!', [
'position' => 'top'
]);
}
public function limpiarInputAdd(){
$this->editar= false;
$this->add = false;
}
public function actualizar(){
$eliminar= Role::find($this->ro);
//dd($eliminar);
$eliminar->update(['nombre'=>$this->nombre]);
$this->alert('success', 'Rol actualizado!', [
'position' => 'top'
]);
$this->editar=false;
}
}
+265
View File
@@ -0,0 +1,265 @@
<?php
namespace App\Http\Livewire;
use App\Models\Servicio;
use Livewire\Component;
use Livewire\WithFileUploads;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Intervention\Image\ImageManagerStatic as Img;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
class ShowServicio extends Component
{
use LivewireAlert;
use WithFileUploads;
public $serviciosModal = false;
public $serviciosEditar = false;
public $servicio_id;
public $nombre_servicio;
public $descripcion_servicio;
public $estado_servicio;
public $color_servicio;
public $img;
public $img_inicio;
public $pantallas;
public $mensaje_servicio;
public $photo;
public $photo_inicio;
public $tiempo = false;
public $perfiles;
public $password;
public $completa;
public $ver_url;
public $url;
public $renovacion = false;
protected $rules = [
'nombre_servicio' => 'required',
'estado_servicio' => 'required',
'pantallas' => 'required',
'completa' => 'required',
];
public function render()
{
if ($this->tiempo) {
$this->pantallas = 1;
$this->completa = 1;
}
$consulta = Servicio::Orderby('estado')->get();
return view('livewire.show-servicio', [
'servicios' => $consulta,
]);
}
public function createServicio()
{
$this->validate();
if (!empty($this->photo)) {
$nombre = Str::random(10);
$img = img::make($this->photo)->orientate()->resize(1000, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
})->encode('webp');
$location = "photos/" . $nombre . ".webp";
Storage::disk('local')->put($location, $img);
$url_foto = $location;
} else {
$url_foto = $this->img;
}
if (!empty($this->photo_inicio)) {
$nombre_inicio = Str::random(10);
$img_inicio = img::make($this->photo_inicio)->orientate()->resize(1000, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
})->encode('webp');
$location_inicio = "photos/" . $nombre_inicio . ".webp";
Storage::disk('local')->put($location_inicio, $img_inicio);
$url_foto_inicio = $location_inicio;
} else {
$url_foto_inicio = null;
}
$servicio = new Servicio;
$servicio->nombre = $this->nombre_servicio;
$servicio->descripcion = $this->descripcion_servicio;
$servicio->estado = $this->estado_servicio;
$servicio->color_fondo = $this->color_servicio;
$servicio->pantallas = $this->pantallas;
$servicio->img = $url_foto;
$servicio->img_inicio = $url_foto_inicio;
$servicio->mensaje = $this->mensaje_servicio;
$servicio->completa = $this->completa;
$servicio->por_tiempo = $this->tiempo;
$servicio->ver_perfiles = $this->perfiles;
$servicio->perfiles = $this->password;
$servicio->ver_url = $this->ver_url;
$servicio->url = $this->url;
$servicio->renovacion = $this->renovacion;
$servicio->save();
$this->alert('success', 'Servicio creado correctamente!', [
'position' => 'top'
]);
$this->serviciosModal = false;
}
public function editar($id)
{
$consulta_servicios = Servicio::FindOrFail($id);
$this->servicio_id = $consulta_servicios->id;
$this->nombre_servicio = $consulta_servicios->nombre;
$this->descripcion_servicio = $consulta_servicios->descripcion;
$this->estado_servicio = $consulta_servicios->estado;
$this->color_servicio = $consulta_servicios->color_fondo;
$this->pantallas = $consulta_servicios->pantallas;
$this->img = $consulta_servicios->img;
$this->img_inicio = $consulta_servicios->img_inicio;
$this->mensaje_servicio = $consulta_servicios->mensaje;
$this->completa = $consulta_servicios->completa;
$this->tiempo = $consulta_servicios->por_tiempo == 1 ? true : false;
$this->perfiles = $consulta_servicios->ver_perfiles;
$this->ver_url = $consulta_servicios->ver_url;
$this->url = $consulta_servicios->url;
$this->renovacion = $consulta_servicios->renovacion == 1 ? true : false;
}
public function guardar()
{
if (!empty($this->photo)) {
$nombre = Str::random(10);
$img = img::make($this->photo)->orientate()->resize(1000, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
})->encode('webp');
$location = "photos/" . $nombre . ".webp";
Storage::disk('local')->put($location, $img);
$url_foto = $location;
} else {
$url_foto = $this->img;
}
if (!empty($this->photo_inicio)) {
$nombre_inicio = Str::random(10);
$img_inicio = img::make($this->photo_inicio)->orientate()->resize(1000, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
})->encode('webp');
$location_inicio = "photos/" . $nombre_inicio . ".webp";
Storage::disk('local')->put($location_inicio, $img_inicio);
$url_foto_inicio = $location_inicio;
} else {
$url_foto_inicio = $this->img_inicio;
}
Servicio::where('id', $this->servicio_id)->update([
'nombre' => $this->nombre_servicio,
'descripcion' => $this->descripcion_servicio,
'estado' => $this->estado_servicio,
'color_fondo' => $this->color_servicio,
'pantallas' => $this->pantallas,
'img' => $url_foto,
'img_inicio' => $url_foto_inicio,
'mensaje' => $this->mensaje_servicio,
'completa' => $this->completa,
'por_tiempo' => $this->tiempo == 1 ? true : false,
'ver_perfiles' => $this->perfiles,
'perfiles' => $this->password,
'ver_url' => $this->ver_url,
'url' => $this->url,
'renovacion' => $this->renovacion == 1 ? true : false,
]);
$this->serviciosEditar = false;
$this->limpiarInputServiciosModal();
}
public function desactivar($id)
{
Servicio::where('id', $id)->update([
'estado' => 'inactivo',
]);
}
public function activar($id)
{
Servicio::where('id', $id)->update([
'estado' => 'activo',
]);
}
public function eliminar($id)
{
$this->delete_servicio = $id;
$this->alert('warning', '¿Eliminar servicio?', [
'position' => 'center',
'timer' => '10000',
'toast' => false,
'text' => 'Esta seguro',
'showConfirmButton' => true,
'onConfirmed' => 'confirmed',
'showDenyButton' => false,
'onDenied' => '',
'showCancelButton' => true,
'onDismissed' => '',
'cancelButtonText' => 'Salir',
'confirmButtonText' => 'Si',
]);
}
public function getListeners()
{
return [
'confirmed'
];
}
public function confirmed()
{
Servicio::where('id', $this->delete_servicio)->delete();
}
public function limpiarInputServiciosModal()
{
$this->nombre_servicio = '';
$this->descripcion_servicio = '';
$this->estado_servicio = null;
$this->color_servicio = null;
$this->pantallas = null;
$this->photo = null;
$this->photo_inicio = null;
$this->mensaje_servicio = null;
$this->completa = null;
$this->tiempo = null;
$this->renovacion = null;
}
}
+434
View File
@@ -0,0 +1,434 @@
<?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\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;
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 $tarifas;
public $servicio_t;
public $cuentas_completas;
public $cuentas_completas_tomadas;
public $cuentas_creadas;
public $cuentas_tomadas;
public $tiempo_tarjetaPlan;
public $verServ;
public $fecha_final_1;
public $fecha_final_2;
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(30);
$this->fecha = $date->format('Y-m-d');
$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 (!empty($this->tarifa_id)) {
$this->paquetesDisponibles();
}
$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);
}
]);
}
])
->get();
return view('livewire.show-servicios', [
'servicios' => $consulta_servicios,
]);
}
public function cargartarjetaPlan($id)
{
$this->tarifas = Tarifas::with('servicio')
->where('id', $id)
->first();
$this->servicio_t = $this->tarifas->servicio;
//Servicio por pantallas
$this->cuentas_creadas = Cuentas::whereDate('inicio', '>=', $this->fecha)
->where('servicio_id', $this->servicio_t->id)
->where('estado', 'activo')
->get();
$this->cuentas_tomadas = Historial_cuenta::whereIn('cuenta_id', $this->cuentas_creadas
->pluck('id'))
->count();
//$prueba1 = $this->cuentas_creadas->count() * $this->servicio_t->pantallas ;
//$prueba2 = $this->cuentas_tomadas ;
//dd($prueba1, $prueba2 , $prueba1-$prueba2);
$this->servicio_id = $this->servicio_t->id;
$this->tarifa_id = $id;
$this->servicio_tarjetaPlan = $this->servicio_t->nombre;
$this->tiempo_tarjetaPlan = $this->servicio_t->por_tiempo;
$this->pantallas_tarjetaPlan = $this->tarifas->pantallas;
$this->dias_tarjetaPlan = $this->tarifas->dias;
$this->fecha_final_1 = $today = Carbon::now();
$this->fecha_final_2 = $today = Carbon::now();
$this->mensaje = $this->servicio_t->mensaje;
//Servicio por cuenta completa
$this->cuentas_completas = Cuentas::whereDate('inicio', '>=', $this->fecha)
->whereDate('vencimiento', '>=', $this->fecha_final_1->addDays($this->tarifas->dias - 20))
->whereDate('vencimiento', '<=', $this->fecha_final_2->addDays($this->tarifas->dias + 20))
->where('servicio_id', $this->tarifas->servicio->id)
->where('estado', 'pendiente')
->get();
$this->cuentas_completas_tomadas = Historial_cuenta::whereIn('cuenta_id', $this->cuentas_completas->pluck('id'))
->count();
$usuario_tarifa = Usuario_tarifa::where('usuario_id', auth()->user()->id)
->where('tarifa_id', $id)
->first();
$this->valor_tarjetaPlan = ($usuario_tarifa) ? $usuario_tarifa->precio : $this->tarifas->valor;
$this->colorFondo_tarjetaPlan = $this->servicio_t->color_fondo;
$this->fechaFinal = $this->fechaActual->addDay($this->tarifas->dias);
//Cantidad de paquetes disponibles
$this->paquetesDisponibles();
$this->tarjetaPlan = true;
}
public function paquetesDisponibles()
{
if ($this->tarifas->pantallas == $this->servicio_t->completa) {
$this->disponibles = (($this->cuentas_completas->count() * $this->servicio_t->completa) - $this->cuentas_completas_tomadas) / $this->tarifas->pantallas;
$restantes_completas = $this->cuentas_completas->count() - ($this->cuentas_completas_tomadas / $this->servicio_t->completa);
if ($restantes_completas <= 10) {
//$this->notificacionPocas($this->servicio_t,$restantes_completas);
}
} else {
$cantidad_solicitada = (int) $this->cantidad_tarjetaPlan * (int) $this->pantallas_tarjetaPlan;
if ($this->servicio_t->pantallas >= $cantidad_solicitada) {
$this->disponibles = (($this->cuentas_creadas->count() * $this->servicio_t->pantallas) - $this->cuentas_tomadas) / $this->tarifas->pantallas;
$restantes = $this->cuentas_creadas->count() - ($this->cuentas_tomadas / $this->servicio_t->pantallas);
} else {
$this->disponibles = ($this->cuentas_creadas->count() - $this->cuentas_tomadas);
$restantes = $this->cuentas_creadas->count() - ($this->cuentas_tomadas);
}
if ($restantes <= 10) {
//$this->notificacionPocas($this->servicio_t,$restantes);
}
}
}
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_solicitada = (int) $this->cantidad_tarjetaPlan * (int) $this->pantallas_tarjetaPlan;
$total_valor = (int) $this->valor_tarjetaPlan * (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->save();
$pantallas = Tarifas::where('id', $this->tarifa_id)->with('servicio')->first();
$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 = 1;
$cuenta = Cuentas::where('servicio_id', $this->servicio_id)->whereDate('inicio', '>=', $this->fecha)->Orderby('created_at', 'ASC')->withCount('historiales')->where('estado', 'activo')->having('historiales_count', '<=', $suma)->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('inicio', '>=', $this->fecha)->whereDate('vencimiento', '>=', $this->fecha_final_1)
->whereDate('vencimiento', '<=', $this->fecha_final_2)
->Orderby('created_at', 'ASC')->withCount('historiales')->where('estado', 'pendiente')->having('historiales_count', '==', 0)->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)->Orderby('created_at', 'ASC')->withCount('historiales')->where('estado', 'activo')->having('historiales_count', '<=', $suma2)->get();
} else {
$cuenta = null;
$cantidad_necesaria = null;
}
for ($h = 0; $h < (int) $cantidad_necesaria; $h++) {
if (!empty($cuenta)) {
$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();
}
} else {
$this->alert('warning', 'No hay cuentas disponibles!', [
'position' => 'top'
]);
}
}
$descuento = Saldo::where('usuario_id', Auth::user()->id)->first();
$saldo_anterior = $descuento->valor;
//dd($saldo_anterior);
$nuevo_saldo = $saldo_anterior - $total_valor;
$cobro = $descuento->update(['valor' => $nuevo_saldo]);
if ($cobro) {
$historial->update(['estado' => 'activo']);
$this->credenciales($historial);
} else {
$this->alert('warning', 'Error en el cobro, comuniquese con soporte!', [
'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;
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class ShowSlider extends Component
{
public function render()
{
return view('livewire.show-slider');
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace App\Http\Livewire;
use App\Models\Configuracione;
use App\Models\User;
use Livewire\Component;
use Jantinnerezo\LivewireAlert\LivewireAlert;
class ShowTop extends Component
{ public $configuracion;
use LivewireAlert;
public function render()
{
$this->configuracion = Configuracione::orderby('id','desc')->first();
$consulta_ventas = User::with(['historiales_venta' => function ($query) {
$query->whereMonth('fecha_inicio', date('m'));
}])
->withCount(['historiales_venta' => function ($query) {
$query->whereMonth('fecha_inicio', date('m'));
}])
->orderBy('historiales_venta_count', 'desc')
->limit(10)
->get();
//dd($consulta_ventas);
return view('livewire.show-top',[
'usuarios' => $consulta_ventas,
]);
}
}
+505
View File
@@ -0,0 +1,505 @@
<?php
namespace App\Http\Livewire;
use App\Models\Historiale;
use App\Models\Promociones;
use App\Models\recarga;
use App\Models\Role;
use App\Models\Saldo;
use App\Models\Tarifas;
use App\Models\User;
use App\Models\Usuario_promo;
use App\Models\Usuario_tarifa;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Livewire\Component;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use App\Models\Servicio;
use App\Models\TarifaPromo;
use Livewire\WithPagination;
class ShowUsuarios extends Component
{
use LivewireAlert;
use WithPagination;
public $roles;
public $nombre;
public $email;
public $password;
public $rol;
public $buscar;
public $newPassword;
public $pass_id;
public $modalPassword = false;
public $id_edit;
public $nombre_edit;
public $email_edit;
public $password_edit;
public $rol_edit;
public $editar = false;
public $add = false;
public $gestion = false;
public $gestionPromo = false;
public $delete_user;
public $modalSaldo = false;
public $saldo_actual;
public $nuevo_saldo;
public $valor_recargar;
public $user_saldo;
public $consulta_tarifas;
public $consulta_usuarioTarifas;
public $usuario_nombre;
public $precioTarifa;
public $tarifasGestion;
public $estadoTarifa;
public $usuarioGestion_id;
public $precioTarifasGestion;
public $buscar_servicio;
public $rol_usuario;
public $consulta_promociones;
public $consulta_usuarioPromo;
public $precioPromoGestion;
public $promoGestion;
public $estadoPromo;
public $buscar_promo;
public $servicio_modTarifas;
public $roles_modTarifas;
public $precio_modTarifas = 0;
public $consulta_saldo;
public $modTarifas;
protected $rules = [
'nombre' => 'required',
'email' => 'required',
'password' => 'required',
'rol' => 'required',
];
public function render()
{
$consulta_tarifas = TarifaPromo::take(1);
$consulta_usuarios = User::where('name', 'LIKE', '%' . $this->buscar . '%')->orWhere('email', 'LIKE', '%' . $this->buscar . '%')->with('rol', 'saldo')->orderBy('id','DESC')->withCount('historiales_venta')->paginate(15);
if (!empty($this->buscar_servicio)) {
$this->consulta_tarifas = Tarifas::where('rol_id', $this->rol_usuario)->with([
'servicio' => function ($query) {
$query->Where('nombre', 'LIKE', '%' . $this->buscar_servicio . '%'); }
])->get();
}
if (!empty($this->buscar_promo)) {
$this->consulta_promo = Promociones::where('visible', '!=', 'false')->where('nombre', 'like', '%' . $this->buscar_promo . '%')->get();
}
if ($this->gestionPromo == true) {
$this->consulta_usuarioPromo = Usuario_promo::where('usuario_id', $this->usuarioGestion_id)->with('usuario', 'promocion')->get();
}
if (!empty($this->servicio_modTarifas)) {
$consulta_tarifas = TarifaPromo::with('rol')->where('promocion_id', $this->servicio_modTarifas)->get();
}
$this->roles = Role::get();
return view('livewire.show-usuarios', [
'usuarios' => $consulta_usuarios,
'tarifas' => $consulta_tarifas,
'promo' => Promociones::where('visible', 'true')->get(),
]);
}
/// Crear usuario ///
public function crear()
{
$this->validate();
$consulta_user = User::where('email', $this->email)->exists();
if (!$consulta_user) {
$crear = new User;
$crear->name = $this->nombre;
$crear->email = $this->email;
$crear->password = Hash::make($this->password);
$crear->rol_id = $this->rol;
$crear->save();
$saldo = new saldo;
$saldo->valor = '0';
$saldo->usuario_id = $crear->id;
$saldo->save();
if ($crear) {
$this->alert('success', 'Usuario creado con èxito!', [
'position' => 'top'
]);
}
$this->add = false;
} else {
$this->alert('warning', 'Este correo ya está registrado!', [
'position' => 'top'
]);
}
}
//CONSULTAR SALDO//
public function saldo($user_saldo)
{
$this->user_saldo = $user_saldo;
$this->consulta_saldo = Saldo::where('usuario_id', $this->user_saldo)->first();
if (is_null($this->consulta_saldo)) {
$saldo = new Saldo;
$saldo->valor = 0;
$saldo->usuario_id = $this->user_saldo;
$saldo->save();
$this->consulta_saldo = $saldo;
}
$this->saldo_actual = $this->consulta_saldo->valor;
$this->modalSaldo = true;
}
public function addSaldo()
{
$recarga = new recarga;
$recarga->payment_method_id = 'manual';
$recarga->status = 'Aprovada';
$recarga->usuario_id = $this->user_saldo;
$recarga->saldo_id = $this->consulta_saldo->id;
$recarga->monto = $this->valor_recargar;
$recarga->valor_recarga = $this->valor_recargar;
$recarga->save();
$this->consulta_saldo->update([
'valor' => $this->saldo_actual + $this->valor_recargar
]);
$this->alert('success', 'Saldo actualizado con exito!', [
'position' => 'top'
]);
$this->limpiarSaldo();
}
public function editar($id)
{
$this->id_edit = $id;
$consulta = User::FindOrFail($this->id_edit);
$this->nombre_edit = $consulta->name;
$this->email_edit = $consulta->email;
$this->rol_edit = $consulta->rol_id;
$this->editar = true;
}
public function actualizar()
{
$this->validate(
[
'nombre_edit' => 'required',
'email_edit' => 'required',
'rol_edit' => 'required',
]
);
User::where('id', $this->id_edit)->update([
'name' => $this->nombre_edit,
'email' => $this->email_edit,
'rol_id' => $this->rol_edit
]);
$this->editar = false;
$this->alert('success', 'Usuario actualizado con exito!', [
'position' => 'top'
]);
}
public function gestionar($id, $rid, $usuNom)
{
$this->usuarioGestion_id = $id;
$this->rol_usuario = $rid;
$this->usuario_nombre = $usuNom;
$this->consulta_tarifas = Tarifas::where('rol_id', $rid)->with('servicio')->get();
$this->consulta_usuarioTarifas = Usuario_tarifa::where('usuario_id', $this->usuarioGestion_id)->with('tarifa')->get();
//dd($this->consulta_usuarioTarifas);
$this->gestion = true;
}
public function addtarifas()
{
$consulta_existe = Usuario_tarifa::where('tarifa_id', $this->tarifasGestion)
->where('usuario_id', $this->usuarioGestion_id)
->exists();
if ($consulta_existe) {
$this->alert('warning', '¡Este usuario ya tiene esta tarifa!', [
'position' => 'top'
]);
} elseif (empty($this->tarifasGestion)) {
$this->alert('warning', '¡Seleccione una tarifa!', [
'position' => 'top'
]);
} elseif (empty($this->precioTarifasGestion)) {
$this->alert('warning', '¡Coloque un precio!', [
'position' => 'top'
]);
} else {
$usuarioTarifa = new Usuario_tarifa;
$usuarioTarifa->precio = $this->precioTarifasGestion;
$usuarioTarifa->tarifa_id = $this->tarifasGestion;
$usuarioTarifa->usuario_id = $this->usuarioGestion_id;
$usuarioTarifa->visible = $this->estadoTarifa ? 'false' : 'true';
$usuarioTarifa->save();
$this->alert('success', '¡Tarifas del usuario actualizadas correctamente!', [
'position' => 'top'
]);
}
$this->consulta_usuarioTarifas = Usuario_tarifa::where('usuario_id', $this->usuarioGestion_id)
->with('tarifa')
->get();
$this->precioTarifasGestion = null;
}
public function eliminarUsuarioTarifa($id)
{
Usuario_tarifa::where('id', $id)->delete();
$this->alert('success', 'Tarifa de usuario eliminada correctamente!', [
'position' => 'top'
]);
$this->consulta_usuarioTarifas = Usuario_tarifa::where('usuario_id', $this->usuarioGestion_id)->with('tarifa')->get();
}
public function gestionarPromociones($id, $usuNom)
{
$this->usuarioGestion_id = $id;
$this->usuario_nombre = $usuNom;
$this->consulta_promo = Promociones::where('visible', '!=', 'false')->get();
//$this->consulta_usuarioPromo = Usuario_promo::join('promociones', 'promocion_id', '=', 'promociones.id')->where('usuario_id',$this->usuarioGestion_id)->get(['usuario_promos.id','nombre','usuario_promos.visible','usuario_promos.precio']);
$this->consulta_usuarioPromo = Usuario_promo::where('usuario_id', $this->usuarioGestion_id)->with('usuario', 'promocion')->get();
$this->gestionPromo = true;
}
public function addpromos()
{
$consulta_existe = Usuario_promo::where('promocion_id', $this->promoGestion)->where('usuario_id', $this->usuarioGestion_id)->get();
if (empty($this->promoGestion)) {
$this->alert('warning', 'Seleccione una promocion!', [
'position' => 'top'
]);
} else {
if ($consulta_existe->count() > 0) {
$this->alert('warning', 'Este usuario ya tiene esta promocion!', [
'position' => 'top'
]);
} else {
$usuarioPromo = new Usuario_promo();
$usuarioPromo->precio = $this->precioPromoGestion;
$usuarioPromo->promocion_id = $this->promoGestion;
$usuarioPromo->usuario_id = $this->usuarioGestion_id;
if ($this->estadoPromo) {
$usuarioPromo->visible = 'false';
} else {
$usuarioPromo->visible = 'true';
}
$usuarioPromo->save();
$this->alert('success', 'promociones del usuario actualizadas correctamente!', [
'position' => 'top'
]);
}
}
$this->consulta_usuarioPromo = Usuario_promo::join('promociones', 'promocion_id', '=', 'promociones.id')->where('usuario_id', $this->usuarioGestion_id)->get(['usuario_promos.id', 'nombre', 'usuario_promos.visible', 'usuario_promos.precio']);
}
public function eliminarUsuarioPromo($id)
{
Usuario_promo::where('id', $id)->delete();
$this->alert('success', 'Promocion de usuario eliminada correctamente!', [
'position' => 'top'
]);
$this->consulta_usuarioPromo = Usuario_promo::join('promociones', 'promocion_id', '=', 'promociones.id')->where('usuario_id', $this->usuarioGestion_id)->get(['usuario_promos.id', 'nombre', 'usuario_promos.visible', 'usuario_promos.precio']);
}
public function eliminar($id)
{
$this->delete_user = $id;
$this->alert('warning', '¿Eliminar usuario?', [
'position' => 'center',
'timer' => '10000',
'toast' => false,
'text' => 'Esta seguro',
'showConfirmButton' => true,
'onConfirmed' => 'confirmed',
'showDenyButton' => false,
'onDenied' => '',
'showCancelButton' => true,
'onDismissed' => '',
'cancelButtonText' => 'Salir',
'confirmButtonText' => 'Si',
]);
}
public function getListeners()
{
return [
'confirmed'
];
}
public function confirmed()
{
// Paso 1: Obtener el id del usuario eliminado
$usuarioEliminado = User::where('name', 'usuarioEliminado')->value('id');
// Paso 2: Actualizar los registros en la base de datos
$consultaHistorial=Historiale::where('vendedor_id', $this->delete_user)
->update(['vendedor_id' => $usuarioEliminado,'cliente_id'=>$usuarioEliminado]);
$user = User::find($this->delete_user);
$user->delete();
}
public function editarPassword($id)
{
$this->pass_id = $id;
$this->modalPassword = true;
}
public function confirmarNewPassword()
{
$validatedData = $this->validate([
'newPassword' => 'required'
]);
User::where('id', $this->pass_id)->update([
'password' => Hash::make($this->newPassword),
]);
$this->alert('success', 'Contraseña actualizada correctamente!', [
'position' => 'top'
]);
$this->limpiarContra();
}
public function limpiarInputAdd()
{
$this->nombre = '';
$this->email = '';
$this->rol = null;
$this->add = false;
}
public function limpiarInputEdit()
{
$this->nombre_edit = '';
$this->email_edit = '';
$this->rol_edit = null;
$this->editar = false;
}
public function limpiarContra()
{
$this->newPassword = '';
$this->modalPassword = false;
}
public function limpiarSaldo()
{
$this->valor_recargar = null;
$this->modalSaldo = false;
}
/* ------------- ACTUALIZAR ------------- */
public function updateTarifas()
{
$consulta_existe = TarifaPromo::where('promocion_id', $this->servicio_modTarifas)->where('rol_id', $this->roles_modTarifas)->get();
//dd($consulta_existe);
if (empty($this->servicio_modTarifas)) {
$this->alert('warning', 'Seleccione una promocion!', [
'position' => 'top'
]);
} else {
if ($consulta_existe->count() > 0) {
$this->alert('warning', 'Esta tarifa ya existe!', [
'position' => 'top'
]);
} else {
$tarifa = new TarifaPromo;
$tarifa->precio = $this->precio_modTarifas;
$tarifa->promocion_id = $this->servicio_modTarifas;
$tarifa->rol_id = $this->roles_modTarifas;
$tarifa->save();
$this->alert('success', 'Tarifas actualizadas correctamente!', [
'position' => 'top'
]);
}
}
}
/* ------------- ELIMINAR ------------- */
public function eliminarModTarifa($id)
{
TarifaPromo::where('id', $id)->delete();
$this->alert('success', 'Tarifas eliminada correctamente!', [
'position' => 'top'
]);
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class ShowUtilidades extends Component
{
public function render()
{
return view('livewire.show-utilidades');
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use Illuminate\Support\Str;
use App\Models\recarga;
class ShowWompi extends Component
{
public $monto;
public $referencia;
public function render()
{
if (empty($this->referencia)){
$this->referencia = Str::random(20);
$recargas = new recarga;
$recargas->monto = $this->monto;
$recargas->reference = $this->referencia;
$recargas-> status = 'pendiente_wompi';
$recargas-> usuario_id = auth()->user()->id;
$recargas-> saldo_id= auth()->user()->saldo->id;
$recargas->save();
}
return view('livewire.show-wompi');
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use Illuminate\Http\Request;
class Showcomprar extends Component
{
public $monto;
public $historial_id;
public function render(Request $request)
{ //dd($request);
$this->monto = $request->monto;
$this->historial_id = $request->id;
//dd($this->id = $request->id);
return view('livewire.showcomprar');
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array<int, string>
*/
protected $except = [
//
];
}
@@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
class PreventRequestsDuringMaintenance extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array<int, string>
*/
protected $except = [
//
];
}
@@ -0,0 +1,32 @@
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @param string|null ...$guards
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
}
return $next($request);
}
}
@@ -0,0 +1,29 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class SoloUsuarioAdministrador
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
if (Auth::user()->rol->nombre =="administrador" || Auth::user()->rol->nombre == "super" || Auth::user()->rol->nombre == "editor") {
return $next($request);
} else {
return redirect()->back()->with("mensaje", "No puedes acceder al módulo seleccionado");
}
}
}
+19
View File
@@ -0,0 +1,19 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
class TrimStrings extends Middleware
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array<int, string>
*/
protected $except = [
'current_password',
'password',
'password_confirmation',
];
}
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustHosts as Middleware;
class TrustHosts extends Middleware
{
/**
* Get the host patterns that should be trusted.
*
* @return array<int, string|null>
*/
public function hosts()
{
return [
$this->allSubdomainsOfApplicationUrl(),
];
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustProxies as Middleware;
use Illuminate\Http\Request;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array<int, string>|string|null
*/
protected $proxies;
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers =
Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_AWS_ELB;
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Routing\Middleware\ValidateSignature as Middleware;
class ValidateSignature extends Middleware
{
/**
* The names of the query string parameters that should be ignored.
*
* @var array<int, string>
*/
protected $except = [
// 'fbclid',
// 'utm_campaign',
// 'utm_content',
// 'utm_medium',
// 'utm_source',
// 'utm_term',
];
}
+19
View File
@@ -0,0 +1,19 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array<int, string>
*/
protected $except = [
'/webhooks',
'/wompi_hook',
'/mp'
];
}
+93
View File
@@ -0,0 +1,93 @@
<?php
namespace App\Http\Requests\Auth;
use Illuminate\Auth\Events\Lockout;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class LoginRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'email' => ['required', 'string', 'email'],
'password' => ['required', 'string'],
];
}
/**
* Attempt to authenticate the request's credentials.
*
* @return void
*
* @throws \Illuminate\Validation\ValidationException
*/
public function authenticate()
{
$this->ensureIsNotRateLimited();
if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.failed'),
]);
}
RateLimiter::clear($this->throttleKey());
}
/**
* Ensure the login request is not rate limited.
*
* @return void
*
* @throws \Illuminate\Validation\ValidationException
*/
public function ensureIsNotRateLimited()
{
if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
return;
}
event(new Lockout($this));
$seconds = RateLimiter::availableIn($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.throttle', [
'seconds' => $seconds,
'minutes' => ceil($seconds / 60),
]),
]);
}
/**
* Get the rate limiting throttle key for the request.
*
* @return string
*/
public function throttleKey()
{
return Str::transliterate(Str::lower($this->input('email')).'|'.$this->ip());
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
namespace App\Imports;
use Illuminate\Support\Facades\Hash;
use App\Models\Cuentas;
use Maatwebsite\Excel\Concerns\ToModel;
class UsersImport implements ToModel
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
//dd($row);
return new Cuentas([
'correo'=> $row[0],
'password'=> $row[1],
'estado'=> $row[2],
'inicio'=> \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[3]),
'vencimiento'=> \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[4]),
'servicio_id'=> $row[5],
]);
}
public function headingRow(): int
{
return 1;
}
public function batchSize(): int
{
return 1000;
}
public function chunkSize(): int
{
return 1000;
}
public function getDateFormats(): array
{
return [
'Y-m-d',
];
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Categoria extends Model
{
use HasFactory;
protected $fillable = [
'nombre',
'descripcion',
'imagen',
];
public function promociones(){
return $this ->hasMany(Promociones::class,'categoria_id');
}
}
+66
View File
@@ -0,0 +1,66 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Configuracione extends Model
{
use HasFactory;
protected $fillable = [
'color_boton',
'color_barra',
'color_menu',
'url_logo',
'nombre',
'slogan',
'usermodifico_id',
'top_1',
'top_2',
'top_3',
'top_4',
'top_5',
'top_6',
'top_7',
'top_8',
'top_9',
'top_10',
'img_top',
'mensaje_top',
'premio_1',
'premio_2',
'premio_3',
'premio_4',
'premio_5',
'premio_6',
'premio_7',
'premio_8',
'premio_9',
'premio_10',
'msj_compra',
'msj_wp',
'clave_1',
'clave_2',
'clave_3',
'clave_4',
'clave_5',
'clave_6',
'iptv',
'hora',
'visto',
];
public function usuario(){
return $this ->belongsTo(User::class);
}
public function redes(){
return $this ->hasMany(Rede::class,'configuracion_id');
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Cuentas extends Model
{
use HasFactory;
protected $fillable = [
'correo',
'password',
'vencimiento',
'estado',
'tarifa_id',
'promocion_id',
'inicio',
'servicio_id'
];
public function tarifa(){
return $this ->belongsTo(Tarifas::class);
}
public function promocion(){
return $this ->belongsTo(Promociones::class);
}
public function historiales(){
return $this ->belongsToMany(Historiale::class,'historial_cuentas','cuenta_id','historial_id');
}
public function perfil(){
return $this ->hasMany(Historial_cuenta::class,'cuenta_id');
}
public function servicio(){
return $this ->belongsTo(Servicio::class);
}
public function historiales_obsoletos(){
return $this ->belongsToMany(Historiale::class,'logs','cuenta_id','historial_id');
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Historial_cuenta extends Model
{
use HasFactory;
protected $fillable = [
'historial_id',
'cuenta_id',
];
}
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Historiale extends Model
{
use HasFactory;
protected $fillable = [
'fecha_inicio',
'fecha_final',
'valor',
'tipo_pago',
'estado',
'vendedor_id',
'tarifa_id',
'promocion_id',
'cliente_id',
'nombre_cliente'
];
public function vendedor(){
return $this ->belongsTo(User::class);
}
public function tarifa(){
return $this ->belongsTo(Tarifas::class);
}
public function promocion(){
return $this ->belongsTo(Promociones::class);
}
public function cliente(){
return $this ->belongsTo(User::class);
}
public function cuentas(){
return $this ->belongsToMany(Cuentas::class,'historial_cuentas','historial_id','cuenta_id');
}
public function cuentas_obsoletas(){
return $this ->belongsToMany(Cuentas::class,'logs','historial_id','cuenta_id');
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Permiso extends Model
{
use HasFactory;
protected $fillable = [
'vista',
'usuario_id',
'rol_id'
];
public function rol(){
return $this ->belongsTo(Role::class);
}
public function usuario(){
return $this ->belongsTo(User::class);
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Preferencial extends Model
{
use HasFactory;
protected $fillable = [
'valor',
'usuario_id',
'tarifa_id'
];
public function usuario(){
return $this ->belongsTo(User::class);
}
public function tarifa(){
return $this ->belongsTo(Tarifas::class);
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Promocion_tarifa extends Model
{
use HasFactory;
protected $fillable = [
'promocion_id',
'tarifa_id',
];
//public function promocion_tarifa(){
// return $this ->belongsTo(Promociones::class,'promocion_id');
// }
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Promociones extends Model
{
use HasFactory;
protected $fillable = [
'precio',
'img_publicidad',
'fecha_limite',
'visible',
'categoria_id'
];
public function categoria(){
return $this ->belongsTo(Categoria::class);
}
public function servicios(){
return $this ->hasMany(Servicio::class,'promocion_id');
}
public function cuentas(){
return $this ->hasMany(Cuentas::class,'promocion_id');
}
public function historiales(){
return $this ->hasMany(Historiale::class,'promocion_id');
}
public function tarifas(){
return $this ->belongsToMany(Tarifas::class,'promocion_tarifas','promocion_id','tarifa_id');
}
public function usuario_promos(){
return $this ->hasMany(Usuario_promo::class,'promocion_id');
}
public function tarifaPromo(){
return $this ->hasMany(TarifaPromo::class,'promocion_id');
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Rede extends Model
{
use HasFactory;
protected $fillable = [
'nombre',
'url',
'configuracion_id'
];
public function configuracion(){
return $this ->belongsTo(Configuracione::class);
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
use HasFactory;
protected $fillable = [
'nombre',
];
public function usuarios(){
return $this ->hasMany(User::class,'rol_id');
}
public function permisos(){
return $this ->hasMany(Permiso::class,'rol_id');
}
public function tarifas(){
return $this ->hasMany(Tarifas::class,'rol_id');
}
public function rol_promos(){
return $this ->hasMany(TarifaPromo::class,'rol_id');
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Saldo extends Model
{
use HasFactory;
protected $fillable = [
'valor',
'usuario_id'
];
public function usuario(){
return $this ->belongsTo(User::class);
}
public function recargas(){
return $this ->hasMany(recarga::class, 'saldo_id');
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Servicio extends Model
{
use HasFactory;
protected $fillable = [
'nombre',
'descripcion',
'color_fondo',
'estado',
'img',
'promocion_id',
'pantallas',
'img_inicio',
'mensaje',
'completa',
'ver_perfiles',
'perfiles',
'ver_url',
'url',
'por_tiempo',
'renovacion'
];
public function promocion(){
return $this ->belongsTo(Promociones::class);
}
public function tarifas(){
return $this ->hasMany(Tarifas::class,'servicio_id');
}
public function cuentas(){
return $this ->hasMany(Cuentas::class,'servicio_id');
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class TarifaPromo extends Model
{
use HasFactory;
protected $fillable = [
'promocion_id',
'rol_id',
'precio',
'visible',
];
public function rol(){
return $this ->belongsTo(Role::class,'rol_id');
}
public function promocion(){
return $this ->belongsTo(Promociones::class,'promocion_id');
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Tarifas extends Model
{
use HasFactory;
protected $fillable = [
'pantallas',
'dias',
'valor',
'estado',
'servicio_id',
'rol_id'
];
public function servicio(){
return $this ->belongsTo(Servicio::class);
}
public function preferenciales(){
return $this ->hasMany(Preferencial::class,'tarifa_id');
}
public function cuentas(){
return $this ->hasMany(Cuentas::class,'tarifa_id');
}
public function historiales(){
return $this ->hasMany(Historiale::class,'tarifa_id');
}
public function promociones(){
return $this ->belongsToMany(Promociones::class,'promocion_tarifas','tarifa_id','promocion_id');
}
public function rol(){
return $this ->belongsTo(Role::class);
}
public function usuario_tarifas(){
return $this ->hasMany(Usuario_tarifa::class,'tarifa_id');
}
}
+88
View File
@@ -0,0 +1,88 @@
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
'cedula',
'estado',
'img_perfil',
'rol_id'
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function rol(){
return $this ->belongsTo(Role::class);
}
public function saldo(){
return $this ->hasOne(Saldo::class,'usuario_id');
}
public function modificaciones(){
return $this ->hasOne(Configuracione::class,'usermodifico_id');
}
public function permisos(){
return $this ->hasMany(Permiso::class,'usuario_id');
}
public function preferenciales(){
return $this ->hasMany(Preferencial::class,'usuario_id');
}
public function historiales_venta(){
return $this ->hasMany(Historiale::class,'vendedor_id');
}
public function historiales_compra(){
return $this ->hasMany(Historiale::class,'cliente_id');
}
public function recargas(){
return $this ->hasMany(recarga::class,'usuario_id');
}
public function usuario_tarifas(){
return $this ->hasMany(Usuario_tarifa::class,'usuario_id');
}
public function usuario_promos(){
return $this ->hasMany(Usuario_promo::class,'usuario_id');
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Usuario_promo extends Model
{
use HasFactory;
protected $hidden = [
'usuario_id',
'promocion_id',
'precio',
'visible',
];
public function usuario(){
return $this ->belongsTo(User::class,'usuario_id');
}
public function promocion(){
return $this ->belongsTo(Promociones::class,'promocion_id');
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Usuario_tarifa extends Model
{
use HasFactory;
protected $fillable = [
'usuario_id',
'tarifa_id',
'precio',
'visible',
];
public function usuario(){
return $this ->belongsTo(User::class,'usuario_id');
}
public function tarifa(){
return $this ->belongsTo(Tarifas::class,'tarifa_id');
}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class log extends Model
{
use HasFactory;
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class recarga extends Model
{
use HasFactory;
protected $fillable = [
'payment_type_id',
'payment_method_id',
'status',
'usuario_id',
'saldo_id',
'reference',
'monto',
'valor_recarga'
];
public function usuario(){
return $this ->belongsTo(User::class);
}
public function saldo(){
return $this ->belongsTo(Saldo::class);
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class slider extends Model
{
use HasFactory;
protected $fillable = [
'slider',
];
}
+71
View File
@@ -0,0 +1,71 @@
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class Vencimiento extends Notification implements ShouldQueue
{
use Queueable;
public $notificacion;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct($notificacion)
{
$this-> notificacion = $notificacion;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['database','mail'];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Aviso de renovación')
->greeting('Hola,'.$this->notificacion['cliente'])
->line('Su servicio de '.$this->notificacion['servicio'].' esta proximo a vencer.')
->action('Renovar', url('/'))
->line('Gracias por usar SirPremium!');
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
'fecha_final' => $this->notificacion['fecha_final'],
'cliente' => $this->notificacion['cliente'],
'servicio' => $this->notificacion['servicio'],
'tipo' => $this->notificacion['tipo'],
'vendedor' =>$this->notificacion['vendedor'],
];
}
}
+74
View File
@@ -0,0 +1,74 @@
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class compra extends Notification implements ShouldQueue
{
use Queueable;
public $notificacion;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct($notificacion)
{
$this-> notificacion = $notificacion;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['database','mail'];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Credenciales '.$this->notificacion['servicio'])
->greeting('Hola,'.$this->notificacion['cliente'])
->line('Sus credenciales de acceso '.$this->notificacion['servicio'])
->action('Ver credenciales', url($this->notificacion['enlace']))
->line('Gracias por usar SirPremium!');
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
'fecha_final' => $this->notificacion['fecha_final'],
'cliente' => $this->notificacion['cliente'],
'servicio' => $this->notificacion['servicio'],
'tipo' => $this->notificacion['tipo'],
'vendedor' =>$this->notificacion['vendedor'],
'enlace' =>$this->notificacion['enlace'],
];
}
}
+66
View File
@@ -0,0 +1,66 @@
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class licencias extends Notification implements ShouldQueue
{
use Queueable;
public $notificacion;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct($notificacion)
{
$this-> notificacion = $notificacion;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['database','mail'];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Alerta cuentas de '.$this->notificacion['servicio'] )
->greeting('Hola,')
->line('De '.$this->notificacion['servicio'].' quedan '. $this->notificacion['cantidad'] .' '.$this->notificacion['tipo'].' disponibles.')
->action('Añadir cuentas', url('/planes'))
->line('Gracias por usar SirPremium!');
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
'servicio' => $this->notificacion['servicio'],
'cantidad' => $this->notificacion['cantidad'],
'tipo' => $this->notificacion['tipo'],
];
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace App\Providers;
use MercadoPago\SDK;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace App\Providers;
// use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The model to policy mappings for the application.
*
* @var array<class-string, class-string>
*/
protected $policies = [
// 'App\Models\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
@@ -0,0 +1,21 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Broadcast::routes();
require base_path('routes/channels.php');
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php
namespace App\Providers;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
/**
* The event to listener mappings for the application.
*
* @var array<class-string, array<int, class-string>>
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
'ArieTimmerman\Laravel\URLShortener\Events\URLVisit' => [
'App\Listener\YourListener',
]
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
//
}
/**
* Determine if events and listeners should be automatically discovered.
*
* @return bool
*/
public function shouldDiscoverEvents()
{
return false;
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to the "home" route for your application.
*
* Typically, users are redirected here after authentication.
*
* @var string
*/
public const HOME = '/dashboard';
/**
* Define your route model bindings, pattern filters, and other route configuration.
*
* @return void
*/
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::middleware('api')
->prefix('api')
->group(base_path('routes/api.php'));
Route::middleware('web')
->group(base_path('routes/web.php'));
});
}
/**
* Configure the rate limiters for the application.
*
* @return void
*/
protected function configureRateLimiting()
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace App\View\Components;
use Illuminate\View\Component;
class AppLayout extends Component
{
/**
* Get the view / contents that represents the component.
*
* @return \Illuminate\View\View
*/
public function render()
{
return view('layouts.app');
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace App\View\Components;
use Illuminate\View\Component;
class GuestLayout extends Component
{
/**
* Get the view / contents that represents the component.
*
* @return \Illuminate\View\View
*/
public function render()
{
return view('layouts.guest');
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace App\View\Components;
use Illuminate\View\Component;
class Slider extends Component
{
/**
* Create a new component instance.
*
* @return void
*/
public function __construct($promociones)
{
$this->promociones = $promociones;
//dd($promociones);
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\Contracts\View\View|\Closure|string
*/
public function render()
{
return view('components.slider',['promociones'=>$this->promociones]);
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\View\Components;
use Illuminate\View\Component;
class listadoPlanes extends Component
{
/**
* Create a new component instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\Contracts\View\View|\Closure|string
*/
public function render()
{
return view('components.listado-planes');
}
}