feat: integrate Stripe payments and UI refinements into WhatsApp Dashboard

- Migrated PaymentIntentService with plugin-specific namespacing.
- Added AJAX endpoints for client searching and SPEI reference generation.
- Implemented global premium header with SIIP Blue gradient.
- Optimized sidebar UI: increased logo size to 180px and nav icons/text.
- Improved Dark Mode accessibility with high-contrast primary colors.
- Added "View in CRM" functionality and automated Stripe admin logic.
- Fixed layout nesting issues and polished CSS layering.
This commit is contained in:
DANYDHSV 2026-01-08 15:30:07 -06:00
parent f851ea6d7d
commit e1937f9ac3
15 changed files with 2995 additions and 63852 deletions

View File

@ -1,5 +1,10 @@
# CHANGELOG - siip-whatsapp-notifications # CHANGELOG - siip-whatsapp-notifications
## VERSIÓN 3.1.0 - 07-01-2026
### 🟢 Novedades
1**Re-envío Manual de Notificaciones de Pago**: Se añadió un nuevo apartado en el Dashboard que permite buscar clientes y re-disparar notificaciones de WhatsApp para pagos específicos de forma manual.
2**Buscador de Clientes en Dashboard**: Integración de buscador dinámico para localizar clientes y visualizar su historial de los últimos 10 pagos.
## VERSIÓN 3.0.0 - 02-01-2026 ## VERSIÓN 3.0.0 - 02-01-2026
### 🟢 Novedades ### 🟢 Novedades
1**Soporte Multi-Servicio para Antenas**: Ahora el plugin gestiona múltiples servicios por cliente, mostrando cada contraseña con el formato `Servicio 1: <pass> Servicio 2: <pass> ...`. 1**Soporte Multi-Servicio para Antenas**: Ahora el plugin gestiona múltiples servicios por cliente, mostrando cada contraseña con el formato `Servicio 1: <pass> Servicio 2: <pass> ...`.

File diff suppressed because one or more lines are too long

35
list_attributes.php Normal file
View File

@ -0,0 +1,35 @@
<?php
require_once __DIR__ . '/vendor/autoload.php';
use SmsNotifier\Service\Logger;
use SmsNotifier\Service\OptionsManager;
use SmsNotifier\Service\PluginDataValidator;
use SmsNotifier\Factory\NotificationDataFactory;
use SmsNotifier\Facade\PluginNotifierFacade;
use Ubnt\UcrmPluginSdk\Service\UcrmApi;
use Ubnt\UcrmPluginSdk\Service\PluginConfigManager;
use GuzzleHttp\Client;
$config = PluginConfigManager::create()->loadConfig();
$ipServer = $config['ipserver'] ?? 'localhost';
$apiUrl = "https://$ipServer/crm/api/v1.0/";
$token = $config['apitoken'] ?? '';
$client = new Client([
'base_uri' => $apiUrl,
'verify' => false,
]);
$ucrmApi = new UcrmApi($client, $token);
try {
echo "Fecthing custom attributes from $apiUrl\n";
$attributes = $ucrmApi->get('custom-attributes', ['attributeType' => 'client']);
echo "Total attributes: " . count($attributes) . "\n";
foreach ($attributes as $attr) {
echo sprintf("ID: %s | Name: %s | Key: %s\n", $attr['id'], $attr['name'], $attr['key']);
}
} catch (\Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}

View File

@ -5,12 +5,24 @@
"displayName": "SIIP - Procesador de Pagos en línea con Stripe, Oxxo y Transferencia, Sincronizador de CallBell y Envío de Notificaciones y comprobantes vía WhatsApp", "displayName": "SIIP - Procesador de Pagos en línea con Stripe, Oxxo y Transferencia, Sincronizador de CallBell y Envío de Notificaciones y comprobantes vía WhatsApp",
"description": "Este plugin sincroniza los clientes del sistema UISP CRM con los contactos de WhatsApp en CallBell, además procesa pagos de Stripe como las trasferencias bancarias y genera referencias de pago vía OXXO, además envía comprobantes de pago en formato imagen PNG o texto vía Whatsapp a los clientes", "description": "Este plugin sincroniza los clientes del sistema UISP CRM con los contactos de WhatsApp en CallBell, además procesa pagos de Stripe como las trasferencias bancarias y genera referencias de pago vía OXXO, además envía comprobantes de pago en formato imagen PNG o texto vía Whatsapp a los clientes",
"url": "https://siip.mx/", "url": "https://siip.mx/",
"version": "2.9.2", "version": "3.1.0",
"unmsVersionCompliancy": { "unmsVersionCompliancy": {
"min": "2.1.0", "min": "2.1.0",
"max": null "max": null
}, },
"author": "SIIP INTERNET" "author": "SIIP INTERNET",
"changelog": [
{
"version": "3.1.0",
"date": "2026-01-07",
"changes": "Añadida funcionalidad de re-envío manual de notificaciones de pago."
},
{
"version": "3.0.0",
"date": "2026-01-02",
"changes": "Soporte multi-servicio y optimizaciones de rendimiento."
}
]
}, },
"configuration": [ "configuration": [
{ {
@ -199,7 +211,7 @@
"menu": [ "menu": [
{ {
"key": "Reports", "key": "Reports",
"label": "Borrar comprobantes Wordpress", "label": "Administrar Notificaciones por WhatsApp",
"type": "admin", "type": "admin",
"target": "iframe" "target": "iframe"
} }

View File

@ -5,6 +5,10 @@ require_once __DIR__ . '/vendor/autoload.php';
use Ubnt\UcrmPluginSdk\Service\PluginLogManager; use Ubnt\UcrmPluginSdk\Service\PluginLogManager;
use Ubnt\UcrmPluginSdk\Service\PluginConfigManager; use Ubnt\UcrmPluginSdk\Service\PluginConfigManager;
use Ubnt\UcrmPluginSdk\Service\UcrmApi; use Ubnt\UcrmPluginSdk\Service\UcrmApi;
use SmsNotifier\Service\PaymentIntentService;
// Carga manual del servicio para asegurar compatibilidad si el autoloader falla
require_once __DIR__ . '/src/Service/PaymentIntentService.php';
// Solo permitir acceso si estamos en un entorno UCRM válido // Solo permitir acceso si estamos en un entorno UCRM válido
if (!file_exists(__DIR__ . '/data/config.json')) { if (!file_exists(__DIR__ . '/data/config.json')) {
@ -38,22 +42,45 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
} }
$ucrmApi = UcrmApi::create(); $ucrmApi = UcrmApi::create();
// Inicializar servicio de Stripe
$ipServer = $config['ipserver'] ?? '';
$ucrmApiUrl = 'https://' . $ipServer . '/crm';
$stripeService = new PaymentIntentService(
$ucrmApiUrl,
$config['apitoken'] ?? '',
$config['tokenstripe'] ?? '',
$logger
);
// Obtener administradores de UCRM para el selector // Obtener administradores de UCRM para el selector
$admins = []; $admins = [];
$defaultStripeAdminId = null;
try { try {
$adminsRaw = $ucrmApi->get('users/admins'); $adminsRaw = $ucrmApi->get('users/admins');
foreach ($adminsRaw as $admin) { foreach ($adminsRaw as $admin) {
$nombre = trim(($admin['firstName'] ?? '') . ' ' . ($admin['lastName'] ?? ''));
$admins[] = [ $admins[] = [
'id' => $admin['id'], 'id' => $admin['id'],
'nombre' => trim(($admin['firstName'] ?? '') . ' ' . ($admin['lastName'] ?? '')) 'nombre' => $nombre
]; ];
// Identificar al usuario "stripe" para el modo automático
if (strtolower($nombre) === 'stripe' || strtolower($admin['username'] ?? '') === 'stripe') {
$defaultStripeAdminId = $admin['id'];
}
}
// Si no se encontró el usuario "stripe", usar el primero de la lista como fallback
if ($defaultStripeAdminId === null && !empty($admins)) {
$defaultStripeAdminId = $admins[0]['id'];
} }
} catch (\Exception $e) { } catch (\Exception $e) {
$logger->error('Error al obtener administradores de UCRM: ' . $e->getMessage()); $logger->error('Error al obtener administradores de UCRM: ' . $e->getMessage());
} }
// Manejar actualizaciones del JSON de instaladores // Manejar actualizaciones del JSON de instaladores
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_installers') { if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
if ($_POST['action'] === 'save_installers') {
$installersJson = $_POST['installers_data'] ?? ''; $installersJson = $_POST['installers_data'] ?? '';
// Validar que sea un JSON válido // Validar que sea un JSON válido
@ -72,6 +99,144 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['
header('Content-Type: application/json'); header('Content-Type: application/json');
echo json_encode(['success' => false, 'message' => 'Error al guardar los datos.']); echo json_encode(['success' => false, 'message' => 'Error al guardar los datos.']);
exit; exit;
}
if ($_POST['action'] === 'resend_payment') {
$paymentId = $_POST['paymentId'] ?? null;
if (!$paymentId) {
echo json_encode(['success' => false, 'message' => 'Falta el ID del pago.']);
exit;
}
try {
// Obtener datos del pago
$payment = $ucrmApi->get("payments/$paymentId");
// Obtener datos del cliente
$client = $ucrmApi->get("clients/{$payment['clientId']}");
// Simular PayLoad de Webhook
$payload = [
'uuid' => 'manual-trigger',
'changeType' => 'insert',
'entity' => 'payment',
'entityId' => (int)$paymentId,
'eventName' => 'payment.add',
'clientData' => $client,
'paymentData' => $payment
];
// Realizar una petición interna a este mismo script para disparar el flujo de notificación
// Usamos curl local o simplemente instanciamos el plugin si lo preparamos
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$selfUrl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$ch = curl_init($selfUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
$res = curl_exec($ch);
curl_close($ch);
header('Content-Type: application/json');
echo json_encode(['success' => true, 'message' => 'Notificación disparada correctamente.']);
exit;
} catch (\Exception $e) {
header('Content-Type: application/json');
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
exit;
}
}
}
// Búsqueda de clientes (GET)
if (isset($_GET['action']) && $_GET['action'] === 'search_clients') {
$q = $_GET['q'] ?? '';
try {
$clients = $ucrmApi->get('clients', ['query' => $q, 'limit' => 10]);
header('Content-Type: application/json');
echo json_encode($clients);
} catch (\Exception $e) {
echo json_encode(['error' => $e->getMessage()]);
}
exit;
}
// Obtener pagos de un cliente (GET)
if (isset($_GET['action']) && $_GET['action'] === 'get_payments') {
$clientId = $_GET['clientId'] ?? null;
try {
$payments = $ucrmApi->get('payments', ['clientId' => $clientId, 'limit' => 20, 'order' => 'createdDate', 'direction' => 'DESC']);
$methods = $ucrmApi->get('payment-methods');
$methodMap = [];
foreach ($methods as $m) {
$methodMap[$m['id']] = $m['name'];
}
$formattedPayments = array_slice($payments, 0, 10);
foreach ($formattedPayments as &$p) {
$p['methodName'] = $methodMap[$p['methodId']] ?? 'N/A';
}
header('Content-Type: application/json');
echo json_encode($formattedPayments); // Top 10
} catch (\Exception $e) {
echo json_encode(['error' => $e->getMessage()]);
}
exit;
}
// Búsqueda de clientes para Stripe (AJAX)
if (isset($_GET['action']) && $_GET['action'] === 'search_stripe') {
$q = $_GET['q'] ?? '';
header('Content-Type: application/json');
echo json_encode($stripeService->searchClients($q));
exit;
}
// Detalles de cliente para Stripe (AJAX)
if (isset($_GET['action']) && $_GET['action'] === 'get_stripe_details') {
$clientId = $_GET['id'] ?? null;
header('Content-Type: application/json');
echo json_encode($stripeService->getClientDetails($clientId));
exit;
}
// Crear intención de pago Stripe (POST AJAX)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'create_intent') {
$clientId = $_POST['clientId'] ?? null;
$amount = $_POST['amount'] ?? 0;
$stripeCustomerId = $_POST['stripeCustomerId'] ?? null;
$adminId = $_POST['adminId'] ?? null;
try {
$result = $stripeService->createPaymentIntent($clientId, $amount, $stripeCustomerId, $adminId);
header('Content-Type: application/json');
echo json_encode($result);
} catch (\Exception $e) {
header('Content-Type: application/json');
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
exit;
}
// Cargar imágenes (GET)
if (isset($_GET['action']) && $_GET['action'] === 'image') {
$filename = basename($_GET['file'] ?? '');
$path = __DIR__ . '/img/' . $filename;
if ($filename && file_exists($path)) {
$mime = mime_content_type($path);
header("Content-Type: $mime");
readfile($path);
} else {
http_response_code(404);
echo "Image not found";
}
exit;
} }
// Cargar instaladores actuales // Cargar instaladores actuales
@ -95,18 +260,22 @@ $installersData = json_decode($config['installersDataWhatsApp'] ?? '{"instalador
--text-main: #1e293b; --text-main: #1e293b;
--text-muted: #64748b; --text-muted: #64748b;
--border: #e2e8f0; --border: #e2e8f0;
--sidebar-width: 260px; --sidebar-width: 300px;
--danger: #ef4444; --danger: #ef4444;
--success: #22c55e; --success: #22c55e;
--transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
--primary-surface: rgba(37, 99, 235, 0.08);
} }
[data-theme="dark"] { [data-theme="dark"] {
--primary: #60a5fa;
--primary-hover: #93c5fd;
--bg-body: #0f172a; --bg-body: #0f172a;
--bg-card: #1e293b; --bg-card: #1e293b;
--text-main: #f1f5f9; --text-main: #f1f5f9;
--text-muted: #94a3b8; --text-muted: #94a3b8;
--border: #334155; --border: #334155;
--primary-surface: rgba(96, 165, 250, 0.15);
} }
* { * {
@ -150,18 +319,19 @@ $installersData = json_decode($config['installersDataWhatsApp'] ?? '{"instalador
.nav-link { .nav-link {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 12px; gap: 15px;
padding: 12px 16px; padding: 14px 20px;
border-radius: 12px; border-radius: 12px;
color: var(--text-muted); color: var(--text-muted);
text-decoration: none; text-decoration: none;
margin-bottom: 8px; margin-bottom: 10px;
transition: var(--transition); transition: var(--transition);
font-weight: 500; font-weight: 600;
font-size: 1.05rem;
} }
.nav-link.active, .nav-link:hover { .nav-link.active, .nav-link:hover {
background: rgba(37, 99, 235, 0.1); background: var(--primary-surface);
color: var(--primary); color: var(--primary);
} }
@ -169,7 +339,35 @@ $installersData = json_decode($config['installersDataWhatsApp'] ?? '{"instalador
.main-content { .main-content {
margin-left: var(--sidebar-width); margin-left: var(--sidebar-width);
flex: 1; flex: 1;
padding: 2rem 3rem; padding: 0; /* Changed to 0 to allow full-width header */
display: flex;
flex-direction: column;
}
.global-header {
background: linear-gradient(90deg, #1e3a8a 0%, #2563eb 100%);
border-bottom: 4px solid rgba(255, 255, 255, 0.2);
color: #ffffff;
padding: 1.8rem 2rem;
text-align: center;
margin-bottom: 2.5rem;
box-shadow: 0 10px 15px -3px rgba(37, 99, 235, 0.2);
position: sticky;
top: 0;
z-index: 1000;
}
.global-header h2 {
font-size: 1.15rem;
font-weight: 700;
letter-spacing: 1.5px;
text-transform: uppercase;
text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.main-container {
padding: 0 3rem 2rem 3rem;
flex: 1;
} }
.header { .header {
@ -214,8 +412,31 @@ $installersData = json_decode($config['installersDataWhatsApp'] ?? '{"instalador
.btn-primary:hover { .btn-primary:hover {
background: var(--primary-hover); background: var(--primary-hover);
transform: translateY(-1px);
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}
.btn-secondary {
background: var(--bg-card);
color: var(--text-main);
border: 1px solid var(--border);
}
.btn-secondary:hover {
background: rgba(37, 99, 235, 0.05);
border-color: var(--primary);
color: var(--primary);
}
.btn-whatsapp {
background-color: #25D366;
color: white !important;
}
.btn-whatsapp:hover {
background-color: #128C7E;
transform: translateY(-2px); transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(37, 99, 235, 0.2); box-shadow: 0 10px 15px -3px rgba(37, 211, 102, 0.2);
} }
.theme-toggle { .theme-toggle {
@ -276,7 +497,7 @@ $installersData = json_decode($config['installersDataWhatsApp'] ?? '{"instalador
border-radius: 100px; border-radius: 100px;
font-size: 0.875rem; font-size: 0.875rem;
font-weight: 600; font-weight: 600;
background: rgba(37, 99, 235, 0.1); background: var(--primary-surface);
color: var(--primary); color: var(--primary);
} }
@ -373,29 +594,82 @@ $installersData = json_decode($config['installersDataWhatsApp'] ?? '{"instalador
} }
#toast.show { transform: translate(-50%, 0); } #toast.show { transform: translate(-50%, 0); }
/* Search Results in Notifications */
.search-results {
position: absolute;
top: 100%;
left: 0;
right: 0;
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 12px;
margin-top: 5px;
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
z-index: 2000; /* Always above header */
display: none;
max-height: 300px;
overflow-y: auto;
}
.search-item {
padding: 12px 16px;
cursor: pointer;
transition: var(--transition);
}
.search-item:hover {
background: rgba(37, 99, 235, 0.05);
}
.search-item .name {
display: block;
font-weight: 600;
}
.search-item .details {
font-size: 12px;
color: var(--text-muted);
}
.section-view { display: none; }
.section-view.active { display: block; }
</style> </style>
</head> </head>
<body> <body>
<aside class="sidebar"> <aside class="sidebar">
<div class="logo"> <div class="logo" style="flex-direction: column; align-items: center; gap: 15px; margin-bottom: 3.5rem;">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="m3 21 1.9-1.9a8.5 8.5 0 1 0-3.4-3.4z"/><path d="M9 13h1"/></svg> <img src="?action=image&file=logo-empresa.png" alt="Logo Empresa" style="width: 180px; height: 180px; object-fit: contain; border-radius: 16px; background: #fff; padding: 10px; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);">
<span>SIIP CRM</span>
</div> </div>
<nav> <nav>
<a href="#" class="nav-link active"> <a href="#" class="nav-link active" onclick="switchSection('installers', this)">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="7" height="9" x="3" y="3" rx="1"/><rect width="7" height="5" x="14" y="3" rx="1"/><rect width="7" height="9" x="14" y="12" rx="1"/><rect width="7" height="5" x="3" y="16" rx="1"/></svg> <img src="?action=image&file=instalador.png" alt="" style="width: 28px; height: 28px; object-fit: contain; flex-shrink: 0;">
<span>Instaladores</span> <span>Instaladores</span>
</a> </a>
<a href="#" class="nav-link" onclick="switchSection('notifications', this)">
<img src="?action=image&file=whatsapp-logo.png" alt="" style="width: 28px; height: 28px; object-fit: contain; flex-shrink: 0;">
<span>Notificaciones</span>
</a>
<a href="#" class="nav-link" onclick="switchSection('stripe', this)">
<img src="?action=image&file=stripe-logo.png" alt="" style="width: 28px; height: 28px; object-fit: contain; flex-shrink: 0;">
<span>Pagos Stripe</span>
</a>
</nav> </nav>
</aside> </aside>
<main class="main-content"> <main class="main-content">
<header class="global-header">
<h2>Portal Administrativo de Pagos de STRIPE y Notificaciones WhatsApp</h2>
</header>
<div class="main-container">
<header class="header"> <header class="header">
<div class="title-section"> <div class="title-section">
<h1>Gestión de Equipo</h1> <h1 id="headerTitle">Gestión de Equipo</h1>
<p>Administra los técnicos registrados en el sistema</p> <p id="headerDesc">Administra los técnicos registrados en el sistema</p>
</div> </div>
</header>
<div class="actions"> <div class="actions">
<button class="btn theme-toggle" id="themeBtn" title="Cambiar tema"> <button class="btn theme-toggle" id="themeBtn" title="Cambiar tema">
<svg class="sun-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/></svg> <svg class="sun-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/></svg>
@ -408,7 +682,8 @@ $installersData = json_decode($config['installersDataWhatsApp'] ?? '{"instalador
</div> </div>
</header> </header>
<section class="card"> <section id="section-installers" class="section-view active">
<div class="card">
<div class="table-container"> <div class="table-container">
<table id="installersTable"> <table id="installersTable">
<thead> <thead>
@ -422,7 +697,111 @@ $installersData = json_decode($config['installersDataWhatsApp'] ?? '{"instalador
<tbody></tbody> <tbody></tbody>
</table> </table>
</div> </div>
</div>
</section> </section>
<section id="section-notifications" class="section-view">
<div class="card" style="margin-bottom: 2rem;">
<div class="form-group" style="position: relative;">
<label>Buscar Cliente (Nombre, Email o ID)</label>
<input type="text" id="clientSearch" class="form-control" placeholder="Escribe para buscar..." autocomplete="off">
<div id="searchResults" class="search-results"></div>
</div>
</div>
<div id="paymentsContainer" class="card" style="display: none;">
<h3 id="selectedClientName" style="margin-bottom: 1.5rem;">Pagos de Cliente</h3>
<div class="table-container">
<table id="paymentsTable">
<thead>
<tr>
<th>ID Pago</th>
<th>Fecha</th>
<th>Monto</th>
<th>Método</th>
<th>Acción</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</section>
<section id="section-stripe" class="section-view">
<div class="card" style="margin-bottom: 2rem;">
<div class="form-group" style="position: relative;">
<label>Buscar Cliente para Stripe (Nombre, Email o ID)</label>
<input type="text" id="stripeSearch" class="form-control" placeholder="Escribe para buscar..." autocomplete="off">
<div id="stripeResults" class="search-results"></div>
</div>
</div>
<div id="stripeDetailContainer" class="card" style="display: none;">
<div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 1.5rem;">
<div>
<h3 id="stripeClientName">Nombre del Cliente</h3>
<p id="stripeClientIdDisplay" style="color: var(--text-muted); font-size: 0.9rem;">ID: #0</p>
</div>
<div style="text-align: right;">
<span class="badge" id="stripeBalanceBadge">Saldo Pendiente: $0.00</span>
</div>
</div>
<div style="background: rgba(37, 99, 235, 0.05); padding: 1.5rem; border-radius: 12px; margin-bottom: 2rem; border-left: 4px solid var(--primary);">
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
<div>
<label style="font-size: 0.8rem; color: var(--text-muted); display: block;">Stripe Customer ID</label>
<strong id="stripeCustomerIdDisplay">No disponible</strong>
</div>
<div>
<label style="font-size: 0.8rem; color: var(--text-muted); display: block;">Clabe Interbancaria (Personalizada)</label>
<strong id="stripeClabeDisplay">No disponible</strong>
</div>
</div>
</div>
<div style="max-width: 400px;">
<div class="form-group">
<label>Monto a Cobrar (MXN)</label>
<div style="position: relative;">
<span style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); font-weight: 600;">$</span>
<input type="number" id="stripeAmount" class="form-control" style="padding-left: 2rem;" placeholder="0.00" step="0.01">
</div>
</div>
<div class="form-group">
<label>Administrador que registra</label>
<select id="stripeAdminSelect" class="form-control">
<option value="">-- Automático (Usuario de Stripe) --</option>
<?php foreach ($admins as $admin): ?>
<option value="<?= $admin['id'] ?>"><?= $admin['nombre'] ?></option>
<?php endforeach; ?>
</select>
</div>
<a id="btnVerEnCrm" href="#" target="_blank" class="btn btn-secondary" style="width: 100%; justify-content: center; margin-bottom: 1rem; text-decoration: none;">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 8px;"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" x2="21" y1="14" y2="3"/></svg>
Ver en CRM
</a>
<button id="btnCreateIntent" class="btn btn-primary" style="width: 100%; justify-content: center; margin-top: 1rem;">
Generar Referencia de Pago
</button>
</div>
</div>
<!-- Modal Stripe Result -->
<div id="stripeResultModal" class="modal-overlay" style="display: none; z-index: 1100;">
<div class="modal card" style="max-width: 500px;">
<h2 style="margin-bottom: 1rem;">Referencia Generada</h2>
<div id="stripeResultContent" style="margin-bottom: 1.5rem;"></div>
<div class="modal-footer">
<button class="btn btn-primary" onclick="document.getElementById('stripeResultModal').style.display='none'">Cerrar</button>
</div>
</div>
</div>
</section>
</div>
</main> </main>
<!-- Modal Form --> <!-- Modal Form -->
@ -470,11 +849,310 @@ $installersData = json_decode($config['installersDataWhatsApp'] ?? '{"instalador
<script> <script>
const store = { const store = {
installers: <?php echo json_encode($installersData['instaladores']); ?>, installers: <?php echo json_encode($installersData['instaladores']); ?>,
theme: localStorage.getItem('theme') || 'light' theme: localStorage.getItem('theme') || 'light',
crmUrl: '<?php echo $ucrmApiUrl; ?>',
defaultStripeAdminId: '<?php echo $defaultStripeAdminId; ?>'
}; };
document.documentElement.setAttribute('data-theme', store.theme); document.documentElement.setAttribute('data-theme', store.theme);
function switchSection(sectionId, element) {
// Update Sidebar
document.querySelectorAll('.nav-link').forEach(link => link.classList.remove('active'));
element.classList.add('active');
// Update Views
document.querySelectorAll('.section-view').forEach(view => view.classList.remove('active'));
document.getElementById(`section-${sectionId}`).classList.add('active');
// Update Header Buttons
document.getElementById('addBtn').style.display = sectionId === 'installers' ? 'flex' : 'none';
// Update Titles
const title = document.getElementById('headerTitle');
const desc = document.getElementById('headerDesc');
if (sectionId === 'installers') {
title.textContent = 'Gestión de Equipo';
desc.textContent = 'Administra los técnicos registrados en el sistema';
} else if (sectionId === 'notifications') {
title.textContent = 'Centro de Notificaciones';
desc.textContent = 'Re-envía manualmente notificaciones de WhatsApp a tus clientes';
} else if (sectionId === 'stripe') {
title.textContent = 'Pagos Stripe (SPEI)';
desc.textContent = 'Genera referencias de transferencia bancaria personalizadas para tus clientes';
}
}
// --- Notifications Search Logic ---
const clientSearch = document.getElementById('clientSearch');
const searchResults = document.getElementById('searchResults');
let searchTimeout;
clientSearch.addEventListener('input', (e) => {
const query = e.target.value.trim();
clearTimeout(searchTimeout);
if (query.length < 2) {
searchResults.style.display = 'none';
return;
}
searchTimeout = setTimeout(async () => {
try {
const res = await fetch(`?action=search_clients&q=${encodeURIComponent(query)}`);
const clients = await res.json();
renderSearchResults(clients);
} catch (e) { console.error('Error searching clients', e); }
}, 300);
});
function renderSearchResults(clients) {
searchResults.innerHTML = '';
if (clients.length === 0) {
searchResults.innerHTML = '<div class="search-item">No se encontraron clientes</div>';
} else {
clients.forEach(client => {
const div = document.createElement('div');
div.className = 'search-item';
const name = client.clientType === 2 ? client.companyName : `${client.firstName} ${client.lastName}`;
div.innerHTML = `
<span class="name">${name}</span>
<span class="details">ID: ${client.id} | ${client.userIdent || 'Sin Identificador'}</span>
`;
div.onclick = () => selectClient(client.id, name);
searchResults.appendChild(div);
});
}
searchResults.style.display = 'block';
}
async function selectClient(clientId, name) {
searchResults.style.display = 'none';
clientSearch.value = '';
document.getElementById('selectedClientName').textContent = `Pagos de ${name}`;
document.getElementById('paymentsContainer').style.display = 'block';
const tbody = document.querySelector('#paymentsTable tbody');
tbody.innerHTML = '<tr><td colspan="5" style="text-align:center;">Cargando pagos...</td></tr>';
try {
const res = await fetch(`?action=get_payments&clientId=${clientId}`);
const payments = await res.json();
renderPayments(payments);
} catch (e) {
tbody.innerHTML = '<tr><td colspan="5" style="text-align:center; color:var(--danger);">Error al cargar pagos</td></tr>';
}
}
function renderPayments(payments) {
const tbody = document.querySelector('#paymentsTable tbody');
if (payments.length === 0) {
tbody.innerHTML = '<tr><td colspan="5" style="text-align:center;">No se encontraron pagos recientes</td></tr>';
return;
}
tbody.innerHTML = payments.map(p => `
<tr>
<td><span class="badge">#${p.id}</span></td>
<td>${new Date(p.createdDate).toLocaleString()}</td>
<td><strong>$${p.amount} ${p.currencyCode}</strong></td>
<td>${p.methodName || 'N/A'}</td>
<td>
<button class="btn btn-whatsapp" style="padding: 8px 16px; font-size: 13px; border-radius: 50px;" onclick="resendNotification(${p.id}, this)">
<img src="?action=image&file=whatsapp-logo-button.png" alt="" style="width: 18px; height: 18px; object-fit: contain; vertical-align: middle; margin-right: 6px;">
<span style="font-weight: 700;">Re-enviar</span>
</button>
</td>
</tr>
`).join('');
}
async function resendNotification(paymentId, btn) {
if (!confirm('¿Seguro que deseas re-enviar la notificación de este pago?')) return;
const originalHtml = btn.innerHTML;
btn.disabled = true;
btn.innerHTML = 'Enviando...';
const formData = new FormData();
formData.append('action', 'resend_payment');
formData.append('paymentId', paymentId);
try {
const res = await fetch(window.location.href, { method: 'POST', body: formData });
const data = await res.json();
if (data.success) {
showToast('✅ ' + data.message);
} else {
showToast('❌ Error: ' + data.message, true);
}
} catch (e) {
showToast('❌ Fallo de conexión', true);
} finally {
btn.disabled = false;
btn.innerHTML = originalHtml;
}
}
// Close search results on click outside
document.addEventListener('click', (e) => {
if (!clientSearch.contains(e.target) && !searchResults.contains(e.target)) {
searchResults.style.display = 'none';
}
if (!stripeSearch.contains(e.target) && !stripeResults.contains(e.target)) {
stripeResults.style.display = 'none';
}
});
// --- Stripe Logic ---
const stripeSearch = document.getElementById('stripeSearch');
const stripeResults = document.getElementById('stripeResults');
let selectedStripeClient = null;
stripeSearch.addEventListener('input', (e) => {
const query = e.target.value.trim();
clearTimeout(searchTimeout);
if (query.length < 2) {
stripeResults.style.display = 'none';
return;
}
searchTimeout = setTimeout(async () => {
try {
const res = await fetch(`?action=search_stripe&q=${encodeURIComponent(query)}`);
const clients = await res.json();
renderStripeResults(clients);
} catch (e) { console.error('Error searching stripe clients', e); }
}, 300);
});
function renderStripeResults(clients) {
stripeResults.innerHTML = '';
if (clients.length === 0) {
stripeResults.innerHTML = '<div class="search-item">No se encontraron clientes</div>';
} else {
clients.forEach(client => {
const div = document.createElement('div');
div.className = 'search-item';
const name = client.clientType === 2 ? client.companyName : `${client.firstName} ${client.lastName}`;
div.innerHTML = `
<span class="name">${name}</span>
<span class="details">ID: ${client.id} | ${client.username}</span>
`;
div.onclick = () => selectStripeClient(client.id, name);
stripeResults.appendChild(div);
});
}
stripeResults.style.display = 'block';
}
async function selectStripeClient(clientId, name) {
stripeResults.style.display = 'none';
stripeSearch.value = '';
try {
const res = await fetch(`?action=get_stripe_details&id=${clientId}`);
const data = await res.json();
selectedStripeClient = data;
document.getElementById('stripeClientName').textContent = data.fullName;
document.getElementById('stripeClientIdDisplay').textContent = `ID: #${data.id}`;
document.getElementById('stripeBalanceBadge').textContent = `Saldo Pendiente: $${data.accountOutstanding.toFixed(2)}`;
document.getElementById('stripeCustomerIdDisplay').textContent = data.stripeCustomerId || 'No disponible';
document.getElementById('stripeClabeDisplay').textContent = data.clabeInterbancaria || 'No disponible';
document.getElementById('stripeAmount').value = data.accountOutstanding > 0 ? data.accountOutstanding : '';
// Actualizar botón Ver en CRM
const btnVerCrm = document.getElementById('btnVerEnCrm');
btnVerCrm.href = `${store.crmUrl}/client/${data.id}`;
document.getElementById('stripeDetailContainer').style.display = 'block';
} catch (e) {
showToast('Error al cargar detalles del cliente', true);
}
}
document.getElementById('btnCreateIntent').onclick = async () => {
if (!selectedStripeClient || !selectedStripeClient.stripeCustomerId) {
showToast('El cliente no tiene un ID de Stripe válido', true);
return;
}
const amount = parseFloat(document.getElementById('stripeAmount').value);
if (!amount || amount < 10) {
showToast('El monto debe ser al menos 10 MXN', true);
return;
}
const btn = document.getElementById('btnCreateIntent');
btn.disabled = true;
btn.textContent = 'Procesando...';
const formData = new FormData();
formData.append('action', 'create_intent');
formData.append('clientId', selectedStripeClient.id);
formData.append('amount', amount);
formData.append('stripeCustomerId', selectedStripeClient.stripeCustomerId);
// Si el selector está vacío (Automático), enviamos el ID por defecto calculado en PHP
const selectedAdmin = document.getElementById('stripeAdminSelect').value;
formData.append('adminId', selectedAdmin || store.defaultStripeAdminId);
try {
const res = await fetch(window.location.href, { method: 'POST', body: formData });
const data = await res.json();
if (data.success) {
showStripeResult(data);
} else {
showToast('Error: ' + (data.error || 'Fallo desconocido'), true);
}
} catch (e) {
showToast('Fallo de conexión con el servidor', true);
} finally {
btn.disabled = false;
btn.textContent = 'Generar Referencia de Pago';
}
};
function showStripeResult(data) {
const container = document.getElementById('stripeResultContent');
const action = data.next_action;
let html = `
<div style="text-align: center; margin-bottom: 1.5rem;">
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="var(--success)" stroke-width="2" style="margin-bottom: 1rem;"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
<h3 style="color: var(--success); font-weight: 700;">¡Referencia Creada!</h3>
<p style="color: var(--text-muted);">Monto: <strong>$${data.amount.toFixed(2)} MXN</strong></p>
</div>
`;
if (data.status === 'requires_action' && action && action.type === 'display_bank_transfer_instructions') {
const instr = action.display_bank_transfer_instructions;
html += `
<div style="background: #f1f5f9; padding: 1rem; border-radius: 8px; font-family: monospace; font-size: 0.9rem;">
<p style="margin-bottom: 0.5rem; color: #1e293b; font-weight: 700;">DATOS PARA TRANSFERENCIA SPEI:</p>
<div style="display: flex; justify-content: space-between; margin-bottom: 0.3rem;">
<span>Banco:</span> <strong>${instr.financial_addresses[0].spei.bank_name}</strong>
</div>
<div style="display: flex; justify-content: space-between; margin-bottom: 0.3rem;">
<span>CLABE:</span> <strong>${instr.financial_addresses[0].spei.clabe}</strong>
</div>
<div style="display: flex; justify-content: space-between;">
<span>Beneficiario:</span> <strong>${instr.financial_addresses[0].supported_networks[0].toUpperCase()}</strong>
</div>
</div>
<p style="font-size: 0.8rem; color: var(--text-muted); margin-top: 1rem; text-align: center;">
Una vez realizada la transferencia, el pago se registrará automáticamente en UISP.
</p>
`;
} else {
html += `<div class="badge" style="width: 100%; text-align: center;">Estado: ${data.status}</div>`;
}
container.innerHTML = html;
document.getElementById('stripeResultModal').style.display = 'flex';
}
function renderTable() { function renderTable() {
const tbody = document.querySelector('#installersTable tbody'); const tbody = document.querySelector('#installersTable tbody');
tbody.innerHTML = store.installers.map((inst, index) => ` tbody.innerHTML = store.installers.map((inst, index) => `

View File

@ -28,7 +28,17 @@ abstract class AbstractMessageNotifierFacade
$this->logger = $logger; $this->logger = $logger;
$this->messageTextFactory = $messageTextFactory; $this->messageTextFactory = $messageTextFactory;
$this->clientPhoneNumber = $clientPhoneNumber; $this->clientPhoneNumber = $clientPhoneNumber;
$this->ucrmApi = UcrmApi::create();
$config = PluginConfigManager::create()->loadConfig();
$ipServer = $config['ipserver'] ?? 'localhost';
$apiUrl = "https://$ipServer/crm/api/v1.0/";
$client = new Client([
'base_uri' => $apiUrl,
'verify' => false,
]);
$this->ucrmApi = new UcrmApi($client, $config['apitoken'] ?? '');
} }
public function verifyPaymentActionToDo(NotificationData $notificationData): void { public function verifyPaymentActionToDo(NotificationData $notificationData): void {

View File

@ -51,6 +51,17 @@ abstract class AbstractOxxoOperationsFacade
$this->logger = $logger; $this->logger = $logger;
$this->messageTextFactory = $messageTextFactory; $this->messageTextFactory = $messageTextFactory;
$this->clientPhoneNumber = $clientPhoneNumber; $this->clientPhoneNumber = $clientPhoneNumber;
$config = PluginConfigManager::create()->loadConfig();
$ipServer = $config['ipserver'] ?? 'localhost';
$apiUrl = "https://$ipServer/crm/api/v1.0/";
$client = new Client([
'base_uri' => $apiUrl,
'verify' => false,
]);
$this->ucrmApi = new UcrmApi($client, $config['apitoken'] ?? '');
} }
/* /*
@ -78,7 +89,6 @@ abstract class AbstractOxxoOperationsFacade
$portPuppeteer = $config['portPuppeteer']; $portPuppeteer = $config['portPuppeteer'];
$baseUri = 'https://' . $IPServer . '/crm/api/v1.0/'; $baseUri = 'https://' . $IPServer . '/crm/api/v1.0/';
$this->ucrmApi = UcrmApi::create();
$currentUserAdmin = $this->ucrmApi->get('users/admins', []); $currentUserAdmin = $this->ucrmApi->get('users/admins', []);
$clientID = $event_json['client_id']; $clientID = $event_json['client_id'];

View File

@ -19,12 +19,23 @@ abstract class AbstractStripeOperationsFacade
protected $messageTextFactory; protected $messageTextFactory;
protected $clientPhoneNumber; protected $clientPhoneNumber;
protected $ucrmApi; protected $ucrmApi;
private $systemAttributesCache = null;
public function __construct(Logger $logger, MessageTextFactory $messageTextFactory, SmsNumberProvider $clientPhoneNumber) { public function __construct(Logger $logger, MessageTextFactory $messageTextFactory, SmsNumberProvider $clientPhoneNumber) {
$this->logger = $logger; $this->logger = $logger;
$this->messageTextFactory = $messageTextFactory; $this->messageTextFactory = $messageTextFactory;
$this->clientPhoneNumber = $clientPhoneNumber; $this->clientPhoneNumber = $clientPhoneNumber;
$this->ucrmApi = UcrmApi::create();
$config = PluginConfigManager::create()->loadConfig();
$ipServer = $config['ipserver'] ?? 'localhost';
$apiUrl = "https://$ipServer/crm/api/v1.0/";
$client = new Client([
'base_uri' => $apiUrl,
'verify' => false,
]);
$this->ucrmApi = new UcrmApi($client, $config['apitoken'] ?? '');
} }
public function createPaymentIntent(array $eventJson): void { public function createPaymentIntent(array $eventJson): void {
@ -111,20 +122,58 @@ abstract class AbstractStripeOperationsFacade
try { try {
$clientCRM = $this->ucrmApi->get("clients/$clientId", []); $clientCRM = $this->ucrmApi->get("clients/$clientId", []);
// Si intenta crear CLABE pero NO tiene stripeCustomerId, cancelamos
if ($tagName === 'CREAR CLABE STRIPE') {
$hasStripeId = false;
foreach ($clientCRM['attributes'] as $attr) {
if ($attr['key'] === 'stripeCustomerId' && !empty($attr['value'])) {
$hasStripeId = true;
break;
}
}
if (!$hasStripeId) {
$this->logger->warning("Cliente $clientId no tiene stripeCustomerId. No se puede crear CLABE.");
return;
}
}
$customer = $this->createCustomerStripe($stripe, $clientCRM, $generateSpei); $customer = $this->createCustomerStripe($stripe, $clientCRM, $generateSpei);
if ($customer) { if ($customer) {
$this->logger->info("Cliente Stripe creado/actualizado para ID: $clientId (SPEI: " . ($generateSpei ? 'SI' : 'NO') . ")"); $this->logger->info("Cliente Stripe procesado para ID: $clientId (Tag: $tagName, SPEI: " . ($generateSpei ? 'SI' : 'NO') . ")");
} }
} catch (\Exception $e) { } catch (\Exception $e) {
$this->logger->error("Error en createStripeClient para cliente $clientId: " . $e->getMessage()); $this->logger->error("Error en createStripeClient para cliente $clientId: " . $e->getMessage());
} finally {
// Garantizamos quitar la etiqueta siempre para evitar re-ejecuciones accidentales
$this->removeTagFromClient($clientId, $tagName);
} }
} }
protected function createCustomerStripe(StripeClient $stripe, array $clientCRM, bool $generateSpei): ?\Stripe\Customer { protected function createCustomerStripe(StripeClient $stripe, array $clientCRM, bool $generateSpei): ?\Stripe\Customer {
$clientId = $clientCRM['id']; $clientId = $clientCRM['id'];
// Extraer email de contactos (prioridad) o username
$email = $clientCRM['username'] ?? null; $email = $clientCRM['username'] ?? null;
foreach ($clientCRM['contacts'] ?? [] as $contact) {
if ($contact['isBilling'] || $contact['isContact']) {
$email = $contact['email'] ?? $email;
if ($email) break;
}
}
$name = trim(($clientCRM['firstName'] ?? '') . ' ' . ($clientCRM['lastName'] ?? '')); $name = trim(($clientCRM['firstName'] ?? '') . ' ' . ($clientCRM['lastName'] ?? ''));
if (empty($name) && !empty($clientCRM['companyName'])) {
$name = $clientCRM['companyName'];
}
// Obtener IDs de atributos dinámicamente desde el sistema
$cidAttrId = $this->resolveAttributeId('stripeCustomerId');
$clabeAttrId = $this->resolveAttributeId('clabeInterbancaria');
$this->logger->debug("IDs de atributos resueltos: Stripe=$cidAttrId, CLABE=$clabeAttrId");
// Buscar cliente existente por metadata // Buscar cliente existente por metadata
$customers = $stripe->customers->search([ $customers = $stripe->customers->search([
@ -133,6 +182,12 @@ abstract class AbstractStripeOperationsFacade
if ($customers->count() > 0) { if ($customers->count() > 0) {
$customer = $customers->data[0]; $customer = $customers->data[0];
// Sincronizar datos básicos
$stripe->customers->update($customer->id, [
'email' => $email,
'name' => $name,
]);
$this->logger->info("Datos básicos de Cliente Stripe sincronizados para ID: $clientId");
} else { } else {
$params = [ $params = [
'email' => $email, 'email' => $email,
@ -140,16 +195,36 @@ abstract class AbstractStripeOperationsFacade
'metadata' => ['ucrm_client_id' => $clientId] 'metadata' => ['ucrm_client_id' => $clientId]
]; ];
if ($generateSpei) { $customer = $stripe->customers->create($params);
$params['payment_method_options'] = [ $this->logger->info("Nuevo Cliente Stripe creado para ID: $clientId. CID: {$customer->id}");
'customer_balance' => [ // Guardar CID en UCRM
'funding_type' => 'bank_transfer', $this->patchClientCustomAttribute($clientId, (int)$cidAttrId, $customer->id);
'bank_transfer' => ['type' => 'mx_bank_transfer']
]
];
} }
$customer = $stripe->customers->create($params); // Si se requiere SPEI, generamos las instrucciones de fondeo para obtener la CLABE
if ($generateSpei) {
try {
$this->logger->info("Solicitando instrucciones de fondeo (CLABE) para cliente: {$customer->id}");
$fundingInstructions = $stripe->customers->createFundingInstructions(
$customer->id,
[
'currency' => 'mxn',
'funding_type' => 'bank_transfer',
'bank_transfer' => ['type' => 'mx_bank_transfer'],
]
);
$clabe = $fundingInstructions['bank_transfer']['financial_addresses'][0]['spei']['clabe'] ?? null;
if ($clabe) {
$this->logger->info("CLABE obtenida via Funding Instructions para cliente $clientId: $clabe");
$this->patchClientCustomAttribute($clientId, (int)$clabeAttrId, $clabe);
} else {
$this->logger->warning("Stripe no devolvió una CLABE en las instrucciones de fondeo para el cliente $clientId.");
}
} catch (\Exception $e) {
$this->logger->error("Error al crear instrucciones de fondeo para cliente $clientId: " . $e->getMessage());
}
} }
return $customer; return $customer;
@ -158,12 +233,10 @@ abstract class AbstractStripeOperationsFacade
protected function getVaultCredentialsByClientId($clientId): string { protected function getVaultCredentialsByClientId($clientId): string {
$config = PluginConfigManager::create()->loadConfig(); $config = PluginConfigManager::create()->loadConfig();
$ipServer = $config['ipserver'] ?? ''; $ipServer = $config['ipserver'] ?? '';
$crm = new Client(['base_uri' => "https://{$ipServer}/crm/api/v1.0/", 'verify' => false]);
try { try {
// OPT: Lazy Check - Si ya tiene pass válido en CRM, no hace falta procesar nada // OPT: Lazy Check - Si ya tiene pass válido en CRM, no hace falta procesar nada
$respClient = $crm->get("clients/$clientId", ['headers' => ['X-Auth-Token' => $config['apitoken']]]); $clientData = $this->ucrmApi->get("clients/$clientId");
$clientData = json_decode($respClient->getBody()->getContents(), true);
$passCRM = ''; $passCRM = '';
if (isset($clientData['attributes'])) { if (isset($clientData['attributes'])) {
foreach ($clientData['attributes'] as $attr) { foreach ($clientData['attributes'] as $attr) {
@ -180,10 +253,7 @@ abstract class AbstractStripeOperationsFacade
} }
// 1. Obtener los servicios del cliente // 1. Obtener los servicios del cliente
$respSvc = $crm->get('clients/services?clientId=' . $clientId, [ $svcs = $this->ucrmApi->get('clients/services', ['clientId' => $clientId]);
'headers' => ['X-Auth-Token' => $config['apitoken']]
]);
$svcs = json_decode($respSvc->getBody()->getContents(), true);
if (empty($svcs)) { if (empty($svcs)) {
$msg = '⚠️ Cliente sin servicios/antenas'; $msg = '⚠️ Cliente sin servicios/antenas';
@ -191,7 +261,7 @@ abstract class AbstractStripeOperationsFacade
return $msg; return $msg;
} }
$unms = new Client(['base_uri' => "https://{$ipServer}/nms/api/v2.1/", 'verify' => false]); $unms = new Client(['base_uri' => "https://{$ipServer}/nms/api/v2.1/", 'verify' => false, 'headers' => ['X-Auth-Token' => $config['apitoken']]]);
$allServicePasswords = []; $allServicePasswords = [];
$isTestEnv = ($ipServer === '172.16.5.134' || $ipServer === 'pruebas.internet.mx' || $ipServer === 'venus.siip.mx'); $isTestEnv = ($ipServer === '172.16.5.134' || $ipServer === 'pruebas.internet.mx' || $ipServer === 'venus.siip.mx');
@ -295,14 +365,8 @@ abstract class AbstractStripeOperationsFacade
} }
private function syncPasswordWithCrm(int $clientId, string $passVault): void { private function syncPasswordWithCrm(int $clientId, string $passVault): void {
$config = PluginConfigManager::create()->loadConfig();
$crm = new Client(['base_uri' => "https://{$config['ipserver']}/crm/api/v1.0/", 'verify' => false]);
try { try {
$respClient = $crm->get("clients/$clientId", [ $clientData = $this->ucrmApi->get("clients/$clientId");
'headers' => ['X-Auth-Token' => $config['apitoken']]
]);
$clientData = json_decode($respClient->getBody()->getContents(), true);
$passCRM = ''; $passCRM = '';
$attributeId = 17; // ID real para 'passwordAntenaCliente' $attributeId = 17; // ID real para 'passwordAntenaCliente'
@ -358,14 +422,19 @@ abstract class AbstractStripeOperationsFacade
} }
protected function patchClientCustomAttribute(int $clientId, int $attributeId, string $value): bool { protected function patchClientCustomAttribute(int $clientId, int $attributeId, string $value): bool {
$config = PluginConfigManager::create()->loadConfig(); if ($attributeId <= 0) {
$crm = new Client(['base_uri' => "https://{$config['ipserver']}/crm/api/v1.0/", 'verify' => false]); $this->logger->error("Intento de patchAttribute con ID inválido ($attributeId) para cliente $clientId");
return false;
}
try { try {
$crm->patch("clients/$clientId", [ $this->logger->debug("Intentando PATCH en clients/$clientId para atributo ID: $attributeId con valor: $value");
'headers' => ['X-Auth-Token' => $config['apitoken']], $this->ucrmApi->patch("clients/$clientId", [
'json' => [ 'attributes' => [
"attributes" => [['value' => $value, 'customAttributeId' => $attributeId]] [
] 'customAttributeId' => $attributeId,
'value' => $value,
],
],
]); ]);
return true; return true;
} catch (\Exception $e) { } catch (\Exception $e) {
@ -374,12 +443,74 @@ abstract class AbstractStripeOperationsFacade
} }
} }
private function resolveAttributeId(string $key): int {
if ($this->systemAttributesCache === null) {
try {
$this->systemAttributesCache = $this->ucrmApi->get('custom-attributes', ['attributeType' => 'client']);
} catch (\Exception $e) {
$this->logger->error("No se pudieron cargar los atributos del sistema: " . $e->getMessage());
return 0;
}
}
foreach ($this->systemAttributesCache as $attr) {
if ($attr['key'] === $key) {
return (int)$attr['id'];
}
}
return 0;
}
protected function comparePasswords(?string $crm, ?string $vault): string { protected function comparePasswords(?string $crm, ?string $vault): string {
if ($crm && strpos($crm, 'Error') !== 0) return $crm; if ($crm && strpos($crm, 'Error') !== 0) return $crm;
if ($vault && strpos($vault, 'Error') !== 0) return $vault; if ($vault && strpos($vault, 'Error') !== 0) return $vault;
return '⚠️ Probar pass conocida.'; return '⚠️ Probar pass conocida.';
} }
public function syncStripeCustomerData(int $clientId, string $name, ?string $email): void {
$config = PluginConfigManager::create()->loadConfig();
$stripe = new StripeClient($config['tokenstripe']);
try {
$customers = $stripe->customers->search([
'query' => "metadata['ucrm_client_id']:'$clientId'",
]);
if ($customers->count() > 0) {
$customer = $customers->data[0];
$stripe->customers->update($customer->id, [
'name' => $name,
'email' => $email,
]);
$this->logger->info("Sincronización automática a Stripe exitosa para cliente $clientId.");
}
} catch (\Exception $e) {
$this->logger->error("Error sincronizando cliente $clientId a Stripe: " . $e->getMessage());
}
}
protected function removeTagFromClient(int $clientId, string $tagName): void {
try {
$client = $this->ucrmApi->get("clients/$clientId");
$targetTagId = null;
foreach ($client['tags'] as $tag) {
if ($tag['name'] === $tagName) {
$targetTagId = $tag['id'];
break;
}
}
if ($targetTagId) {
$this->ucrmApi->patch("clients/$clientId/remove-tag/$targetTagId", []);
$this->logger->info("Etiqueta '$tagName' (ID: $targetTagId) removida del cliente $clientId via endpoint especializado.");
} else {
$this->logger->debug("Etiqueta '$tagName' no encontrada en el cliente $clientId, nada que remover.");
}
} catch (\Exception $e) {
$this->logger->error("Error al remover etiqueta '$tagName' del cliente $clientId: " . $e->getMessage());
}
}
protected function validarNumeroTelefono($n): string { protected function validarNumeroTelefono($n): string {
if (!$n) return ''; if (!$n) return '';
$n = preg_replace('/\D/', '', (string)$n); $n = preg_replace('/\D/', '', (string)$n);

View File

@ -352,7 +352,9 @@ class ClientCallBellAPI
//Path base del comprobante de pago //Path base del comprobante de pago
$pdf_payment_path = ''; $pdf_payment_path = '';
$this->ucrmApi = UcrmApi::create(); $config = PluginConfigManager::create()->loadConfig();
$gClient = new Client(['base_uri' => "https://{$this->IPServer}/crm/api/v1.0/", 'verify' => false]);
$this->ucrmApi = new UcrmApi($gClient, $this->UCRMAPIToken ?? '');
$payments = $this->ucrmApi->get( $payments = $this->ucrmApi->get(
'payments/', 'payments/',
[ [
@ -566,7 +568,9 @@ class ClientCallBellAPI
//Path base del comprobante de pago //Path base del comprobante de pago
$pdf_payment_path = ''; $pdf_payment_path = '';
$this->ucrmApi = UcrmApi::create(); $config = PluginConfigManager::create()->loadConfig();
$gClient = new Client(['base_uri' => "https://{$this->IPServer}/crm/api/v1.0/", 'verify' => false]);
$this->ucrmApi = new UcrmApi($gClient, $this->UCRMAPIToken ?? '');
$payments = $this->ucrmApi->get( $payments = $this->ucrmApi->get(
'payments/', 'payments/',
[ [
@ -912,7 +916,9 @@ class ClientCallBellAPI
$passAntenaFinal = !empty($passAntenaJSON) ? json_encode($passAntenaJSON) : ""; $passAntenaFinal = !empty($passAntenaJSON) ? json_encode($passAntenaJSON) : "";
$log->appendLog("Dentro del proceso del patch: " . PHP_EOL); $log->appendLog("Dentro del proceso del patch: " . PHP_EOL);
$this->ucrmApi = UcrmApi::create(); $config = PluginConfigManager::create()->loadConfig();
$gClient = new Client(['base_uri' => "https://{$this->IPServer}/crm/api/v1.0/", 'verify' => false]);
$this->ucrmApi = new UcrmApi($gClient, $this->UCRMAPIToken ?? '');
$payments = $this->ucrmApi->get( $payments = $this->ucrmApi->get(
'payments/', 'payments/',
[ [

View File

@ -37,8 +37,10 @@ class NotificationDataFactory
$notificationData->eventName = $jsonData['eventName']; $notificationData->eventName = $jsonData['eventName'];
$notificationData->message = $jsonData['extraData']['message'] ?? null; $notificationData->message = $jsonData['extraData']['message'] ?? null;
// Check if the given webhook exists. // Check if the given webhook exists. Skip for manual triggers.
if ($notificationData->uuid !== 'manual-trigger') {
$this->ucrmApi->query('webhook-events/' . $notificationData->uuid); $this->ucrmApi->query('webhook-events/' . $notificationData->uuid);
}
$this->resolveUcrmData($notificationData); $this->resolveUcrmData($notificationData);

View File

@ -71,7 +71,14 @@ class Plugin
$this->pluginNotifierFacade = $pluginNotifierFacade; $this->pluginNotifierFacade = $pluginNotifierFacade;
$this->pluginOxxoNotifierFacade = $pluginOxxoNotifierFacade; $this->pluginOxxoNotifierFacade = $pluginOxxoNotifierFacade;
$this->notificationDataFactory = $notificationDataFactory; $this->notificationDataFactory = $notificationDataFactory;
$this->ucrmApi = UcrmApi::create(); $config = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create()->loadConfig();
$ipServer = $config['ipserver'] ?? 'localhost';
$apiUrl = "https://$ipServer/crm/api/v1.0/";
$client = new \GuzzleHttp\Client([
'base_uri' => $apiUrl,
'verify' => false,
]);
$this->ucrmApi = new UcrmApi($client, $config['apitoken'] ?? '');
} }
public function run(): void public function run(): void
@ -341,7 +348,8 @@ class Plugin
$isLeadAfter = $entity['isLead']; $isLeadAfter = $entity['isLead'];
if ($isLeadBefore === true && $isLeadAfter === false) { if ($isLeadBefore === true && $isLeadAfter === false) {
$this->logger->debug('El cliente cambió de potencial a cliente'); $this->logger->info("El cliente $clientID cambió de potencial a cliente. Iniciando creación automática en Stripe...");
$this->pluginNotifierFacade->createStripeClient($notification, 'CREAR CLIENTE STRIPE', false);
} }
} }
@ -374,6 +382,34 @@ class Plugin
$this->pluginNotifierFacade->createStripeClient($notification, 'CREAR CLIENTE STRIPE', false); $this->pluginNotifierFacade->createStripeClient($notification, 'CREAR CLIENTE STRIPE', false);
} }
} }
// Automatización: Sincronizar cambios de Nombre o Email con Stripe
$nameBefore = trim(($entityBeforeEdit['firstName'] ?? '') . ' ' . ($entityBeforeEdit['lastName'] ?? ''));
if (empty($nameBefore)) $nameBefore = $entityBeforeEdit['companyName'] ?? '';
$nameAfter = trim(($entity['firstName'] ?? '') . ' ' . ($entity['lastName'] ?? ''));
if (empty($nameAfter)) $nameAfter = $entity['companyName'] ?? '';
$emailBefore = null;
foreach ($entityBeforeEdit['contacts'] ?? [] as $contact) {
if ($contact['isBilling'] || $contact['isContact']) {
$emailBefore = $contact['email'] ?? null;
if ($emailBefore) break;
}
}
$emailAfter = null;
foreach ($entity['contacts'] ?? [] as $contact) {
if ($contact['isBilling'] || $contact['isContact']) {
$emailAfter = $contact['email'] ?? null;
if ($emailAfter) break;
}
}
if ($nameBefore !== $nameAfter || $emailBefore !== $emailAfter) {
$this->logger->info("Detectado cambio en datos básicos del cliente $clientID. Sincronizando con Stripe...");
$this->pluginNotifierFacade->syncStripeCustomerData((int)$clientID, $nameAfter, $emailAfter);
}
} else { } else {
$this->logger->warning('Los datos entityBeforeEdit o entity no están presentes en extraData'); $this->logger->warning('Los datos entityBeforeEdit o entity no están presentes en extraData');
} }

View File

@ -0,0 +1,171 @@
<?php
namespace SmsNotifier\Service;
use GuzzleHttp\Client;
use Stripe\StripeClient;
use Stripe\Exception\ApiErrorException;
class PaymentIntentService
{
private $ucrmApiUrl;
private $ucrmApiKey;
private $stripeApiKey;
private $httpClient;
private $stripeClient;
private $logger;
public function __construct($ucrmApiUrl, $ucrmApiKey, $stripeApiKey, $logger = null)
{
$this->ucrmApiUrl = rtrim($ucrmApiUrl, '/');
$this->ucrmApiKey = $ucrmApiKey;
$this->stripeApiKey = $stripeApiKey;
$this->logger = $logger;
$this->httpClient = new Client([
'base_uri' => $this->ucrmApiUrl . '/api/v1.0/',
'headers' => [
'X-Auth-App-Key' => $this->ucrmApiKey,
'Accept' => 'application/json',
],
'verify' => false,
'timeout' => 10,
]);
$this->stripeClient = new StripeClient($this->stripeApiKey);
}
public function searchClients($query)
{
try {
$response = $this->httpClient->get('clients', [
'query' => [
'query' => $query,
'limit' => 5
]
]);
$clients = json_decode($response->getBody(), true);
return array_map(function ($client) {
return [
'id' => $client['id'],
'firstName' => $client['firstName'],
'lastName' => $client['lastName'],
'username' => $client['username'],
'fullAddress' => $client['fullAddress'] ?? '',
'companyName' => $client['companyName'],
'clientType' => $client['clientType'], // 1 = residential, 2 = company
];
}, $clients);
} catch (\Exception $e) {
return ['error' => $e->getMessage()];
}
}
public function getClientDetails($clientId)
{
try {
$response = $this->httpClient->get("clients/{$clientId}");
$client = json_decode($response->getBody(), true);
$stripeCustomerId = null;
$clabeInterbancaria = null;
if (isset($client['attributes'])) {
foreach ($client['attributes'] as $attribute) {
if ($attribute['key'] === 'stripeCustomerId' || $attribute['name'] === 'Stripe Customer ID') {
$stripeCustomerId = $attribute['value'];
}
if ($attribute['key'] === 'clabeInterbancaria' || $attribute['name'] === 'Clabe Interbancaria') {
$clabeInterbancaria = $attribute['value'];
}
}
}
return [
'id' => $client['id'],
'fullName' => ($client['clientType'] == 1)
? $client['firstName'] . ' ' . $client['lastName']
: $client['companyName'],
'stripeCustomerId' => $stripeCustomerId,
'clabeInterbancaria' => $clabeInterbancaria,
'email' => $this->getClientEmail($client),
'accountOutstanding' => $client['accountOutstanding'] ?? 0
];
} catch (\Exception $e) {
return ['error' => $e->getMessage()];
}
}
private function getClientEmail($clientData)
{
if (!empty($clientData['contacts'])) {
foreach ($clientData['contacts'] as $contact) {
if (!empty($contact['email'])) {
return $contact['email'];
}
}
}
return $clientData['username'] ?? ''; // Fallback, though username might not be email
}
public function createPaymentIntent($clientId, $amount, $stripeCustomerId, $adminId = null)
{
if ($amount < 10) {
throw new \Exception("El monto debe ser mayor a 10 MXN");
}
try {
$amountCentavos = intval($amount * 100);
$paymentIntent = $this->stripeClient->paymentIntents->create([
'amount' => $amountCentavos,
'currency' => 'mxn',
'customer' => $stripeCustomerId,
'payment_method_types' => ['customer_balance'],
'payment_method_data' => ['type' => 'customer_balance'],
'confirm' => true,
'payment_method_options' => [
'customer_balance' => [
'funding_type' => 'bank_transfer',
'bank_transfer' => ['type' => 'mx_bank_transfer']
],
],
'metadata' => [
'clientId' => $clientId,
'createdBy' => 'UCRM',
'paymentType' => 'card.one_time',
'signedInAdminId' => $adminId,
'tipoPago' => 'Transferencia Bancaria'
],
]);
$this->log("PaymentIntent created: " . $paymentIntent->id . " Status: " . $paymentIntent->status);
return [
'success' => true,
'id' => $paymentIntent->id,
'status' => $paymentIntent->status,
'amount' => $paymentIntent->amount / 100,
'currency' => $paymentIntent->currency,
'next_action' => $paymentIntent->next_action
];
} catch (ApiErrorException $e) {
return ['success' => false, 'error' => $e->getMessage()];
} catch (\Exception $e) {
return ['success' => false, 'error' => $e->getMessage()];
}
}
private function log($message)
{
if ($this->logger) {
$this->logger->debug($message);
} else {
error_log($message);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -34,13 +34,22 @@ class ComposerAutoloaderInitd6442a7ec79f2f43fc97d16bdcdd18ee
call_user_func(\Composer\Autoload\ComposerStaticInitd6442a7ec79f2f43fc97d16bdcdd18ee::getInitializer($loader)); call_user_func(\Composer\Autoload\ComposerStaticInitd6442a7ec79f2f43fc97d16bdcdd18ee::getInitializer($loader));
} else { } else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php'; $classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) { if ($classMap) {
$loader->addClassMap($classMap); $loader->addClassMap($classMap);
} }
} }
$loader->setClassMapAuthoritative(true);
$loader->register(true); $loader->register(true);
if ($useStaticLoader) { if ($useStaticLoader) {

File diff suppressed because it is too large Load Diff