Versión 2.8.0

This commit is contained in:
server 2025-05-21 21:31:09 -06:00
parent 7cb26fe735
commit 3a39a53da6
9 changed files with 1056 additions and 36329 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 104 KiB

After

Width:  |  Height:  |  Size: 80 KiB

File diff suppressed because one or more lines are too long

View File

@ -5,7 +5,7 @@
"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.7.5", "version": "2.8.0",
"unmsVersionCompliancy": { "unmsVersionCompliancy": {
"min": "2.1.0", "min": "2.1.0",
"max": null "max": null

File diff suppressed because it is too large Load Diff

View File

@ -192,12 +192,12 @@ abstract class AbstractStripeOperationsFacade
$tagsIds = $this->ucrmApi->get('client-tags', []); $tagsIds = $this->ucrmApi->get('client-tags', []);
//ejemplo de respuesta $tagsIds: [{"id":4,"name":"EQUIPO A CREDITO","colorBackground":"#fed74a","colorText":"#444"},{"id":5,"name":"CREARCLABESTRIPE","colorBackground":"#e30000","colorText":"#fff"}] //ejemplo de respuesta $tagsIds: [{"id":4,"name":"EQUIPO A CREDITO","colorBackground":"#fed74a","colorText":"#444"},{"id":5,"name":"CREARCLABESTRIPE","colorBackground":"#e30000","colorText":"#fff"}]
//obtener el ID de la etiqueta o tag llamada "CREARCLABESTRIPE" y asiganarla a una variable $tagCrearClabeStripe basandose en el ejemplo de respuesta anterior //obtener el ID de la etiqueta o tag llamada "CREAR CLABE STRIPE" y asiganarla a una variable $tagCrearClabeStripe basandose en el ejemplo de respuesta anterior
$tagCrearClabeStripe = null; $tagCrearClabeStripe = null;
foreach ($tagsIds as $tag) { foreach ($tagsIds as $tag) {
if ($tag['name'] === 'CREAR CLABE STRIPE') { if ($tag['name'] === 'CREAR CLABE STRIPE') {
$tagCrearClabeStripe = $tag['id']; $tagCrearClabeStripe = $tag['id'];
$this->logger->info("ID de la etiqueta 'CREAR CLABE STRIPE': " . $tagCrearClabeStripe . PHP_EOL); // $this->logger->info("ID de la etiqueta 'CREAR CLABE STRIPE': " . $tagCrearClabeStripe . PHP_EOL);
break; break;
} }
} }
@ -224,19 +224,19 @@ abstract class AbstractStripeOperationsFacade
//obtener el ID de la etiqueta o tag llamada "CREARCLABESTRIPE" y asiganarla a una variable $tagCrearClabeStripe basandose en el ejemplo de respuesta anterior //obtener el ID de la etiqueta o tag llamada "CREARCLABESTRIPE" y asiganarla a una variable $tagCrearClabeStripe basandose en el ejemplo de respuesta anterior
$tagCrearClabeStripe = null; $tagCrearClabeStripe = null;
foreach ($tagsIds as $tag) { //revisamos los tags del cliente y si encuentra el tag de "CREARCLABESTRIPE" entonces lo asigna a la variable $tagCrearClabeStripe el valor de id foreach ($tagsIds as $tag) { //revisamos los tags del cliente y si encuentra el tag de "CREARCLABESTRIPE" entonces lo asigna a la variable $tagCrearClabeStripe el valor de id
if ($tag['name'] === 'CREARCLABESTRIPE') { if ($tag['name'] === 'CREAR CLABE STRIPE') {
$tagCrearClabeStripe = $tag['id']; $tagCrearClabeStripe = $tag['id'];
$this->logger->info("ID de la etiqueta 'CREARCLABESTRIPE': " . $tagCrearClabeStripe . PHP_EOL); // $this->logger->info("ID de la etiqueta 'CREAR CLABE STRIPE': " . $tagCrearClabeStripe . PHP_EOL);
break; break;
} }
} }
if (!$tagCrearClabeStripe) { if (!$tagCrearClabeStripe) {
$this->logger->info("No se encontró la etiqueta 'CREARCLABESTRIPE'." . PHP_EOL); $this->logger->info("No se encontró la etiqueta 'CREAR CLABE STRIPE'." . PHP_EOL);
return; return;
} }
$this->createCustomerStripe($notificationData, $stripe, $baseUri, $UCRMAPIToken); $this->createCustomerStripe($notificationData, $stripe, $baseUri, $UCRMAPIToken);
$this->ucrmApi->patch("clients/$clientId/remove-tag/" . $tagCrearClabeStripe); $this->ucrmApi->patch("clients/$clientId/remove-tag/" . $tagCrearClabeStripe);
$this->logger->info("Se eliminó la etiqueta 'CREARCLABESTRIPE' del cliente." . PHP_EOL); $this->logger->info("Se eliminó la etiqueta 'CREAR CLABE STRIPE' del cliente." . PHP_EOL);
return; return;
} }

View File

@ -1,17 +1,13 @@
<?php <?php
namespace SmsNotifier\Facade; namespace SmsNotifier\Facade;
use CURLFile;
use DateTime; use DateTime;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Imagick; use Imagick;
use Ubnt\UcrmPluginSdk\Service\PluginLogManager;
use ImagickException; use ImagickException;
use Ubnt\UcrmPluginSdk\Service\UcrmApi;
use Ubnt\UcrmPluginSdk\Service\PluginConfigManager; use Ubnt\UcrmPluginSdk\Service\PluginConfigManager;
use Ubnt\UcrmPluginSdk\Service\UcrmOptionsManager; use Ubnt\UcrmPluginSdk\Service\PluginLogManager;
use Ubnt\UcrmPluginSdk\Service\UcrmApi;
//use SmsNotifier\Service\Logger; //use SmsNotifier\Service\Logger;
@ -56,20 +52,18 @@ class ClientCallBellAPI
public $ucrmVersion; public $ucrmVersion;
public function __construct( public function __construct(
$UCRMAPIToken, $UCRMAPIToken,
$IPServer, $IPServer,
$CallBellAPIToken $CallBellAPIToken
) { ) {
$this->UCRMAPIToken = $UCRMAPIToken; $this->UCRMAPIToken = $UCRMAPIToken;
$this->IPServer = $IPServer; $this->IPServer = $IPServer;
$this->CallBellAPIToken = $CallBellAPIToken; $this->CallBellAPIToken = $CallBellAPIToken;
} }
public function updateContact($client_uuid) public function updateContact($client_uuid)
{ {}
}
public function printPrueba($clientWhatsAppNumber, $notificationData) public function printPrueba($clientWhatsAppNumber, $notificationData)
{ {
@ -105,9 +99,6 @@ class ClientCallBellAPI
$campo2 = sprintf("📡 Su servicio está: %s 📍Su dirección es: *%s* ", $estado_service, $domicilio); $campo2 = sprintf("📡 Su servicio está: %s 📍Su dirección es: *%s* ", $estado_service, $domicilio);
$log->appendLog("Valor del campo2 " . $campo2); $log->appendLog("Valor del campo2 " . $campo2);
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\"],\n \"template_uuid\": \"55705f1fe4e24bab80104dc2643fe11c\",\n \"optin_contact\": true\n }"; $curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\"],\n \"template_uuid\": \"55705f1fe4e24bab80104dc2643fe11c\",\n \"optin_contact\": true\n }";
$log->appendLog("La cadena CURL que se envia es: " . $curl_string); $log->appendLog("La cadena CURL que se envia es: " . $curl_string);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curl_string); curl_setopt($ch, CURLOPT_POSTFIELDS, $curl_string);
@ -118,15 +109,21 @@ class ClientCallBellAPI
curl_close($ch); curl_close($ch);
} }
public function sendJobNotificationWhatsAppToClient($clientWhatsAppNumber, $jobNotificationData, $passwordVault, $reprogramming = false, $changeInstaller = false): bool public function sendJobNotificationWhatsAppToClient($clientWhatsAppNumber, $jobNotificationData, $reprogramming, $changeInstaller): bool
{ {
$log = PluginLogManager::create(); //Initialize Logger $log = PluginLogManager::create(); //Initialize Logger
$log->appendLog("Enviando mensaje de trabajo para el cliente" . PHP_EOL); $log->appendLog("Enviando mensaje de trabajo para el cliente" . PHP_EOL);
$jsonJobNotificationData = json_encode($jobNotificationData, true); $jsonJobNotificationData = json_encode($jobNotificationData, true);
$log->appendLog("Datos de la notificación de trabajo: " . $jsonJobNotificationData . PHP_EOL); // $log->appendLog("Datos de la notificación de trabajo: " . $jsonJobNotificationData . PHP_EOL);
$log->appendLog("Debugging: reprogramming = " . var_export($reprogramming, true) . ", changeInstaller = " . var_export($changeInstaller, true) . PHP_EOL);
// --- ¡AÑADE ESTAS LÍNEAS PARA CONVERTIR A BOOLEANO REAL! ---
$reprogramming = filter_var($reprogramming, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
$changeInstaller = filter_var($changeInstaller, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
// -----------------------------------------------------------
// Puedes volver a loggear los valores para confirmar la conversión (opcional)
$log->appendLog("DEBUG: Valores después de conversión - Reprogramming: " . var_export($reprogramming, true) . ", ChangeInstaller: " . var_export($changeInstaller, true) . PHP_EOL);
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.callbell.eu/v1/messages/send'); curl_setopt($ch, CURLOPT_URL, 'https://api.callbell.eu/v1/messages/send');
@ -137,24 +134,38 @@ class ClientCallBellAPI
'Content-Type: application/json', 'Content-Type: application/json',
]); ]);
$campo1 = sprintf('*%s*', $jobNotificationData['clientFullName']); $campo1 = sprintf(' *%s*', $jobNotificationData['clientFullName']);
$campo2 = sprintf('*#%s*', $jobNotificationData['jobId']); $campo2 = sprintf('*#%s*', $jobNotificationData['jobId']);
$campo3 = sprintf('*%s*', $jobNotificationData['date']); $campo3 = sprintf('%s', $jobNotificationData['date']);
$campo4 = sprintf('*%s*', $jobNotificationData['installerName']); $campo4 = sprintf('*%s*', $jobNotificationData['installerName']);
if ($reprogramming && $changeInstaller === false) { $log->appendLog("DEBUG: Valores antes de la estructura IF - Reprogramming: " . var_export($reprogramming, true) . ", ChangeInstaller: " . var_export($changeInstaller, true) . PHP_EOL);
if ($reprogramming && ! $changeInstaller) {
// Case: true, false
//Enviar notificación de reprogramación al cliente //Enviar notificación de reprogramación al cliente
$log->appendLog("Enviando notificación de reprogramación al cliente, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL); $log->appendLog("Enviando notificación de reprogramación al cliente, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL);
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\"],\n \"template_uuid\": \"70579353773f4de1836d4f9b6bf6074d\",\n \"optin_contact\": true\n }"; $curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\"],\n \"template_uuid\": \"323631bf578e43fb8a0095f55978aae8\",\n \"optin_contact\": true\n }";
} } else if (! $reprogramming && $changeInstaller) {
if ($changeInstaller) { // Case: false, true
//Enviar notificación de cambio de instalador //Enviar notificación de cambio de instalador
$log->appendLog("Enviando notificación de cambio de instalador al cliente, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL); $log->appendLog("Enviando notificación de cambio de instalador al cliente, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL);
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\"],\n \"template_uuid\": \"0d57fd210595422caf2f5999642882a3\",\n \"optin_contact\": true\n }"; $curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\"],\n \"template_uuid\": \"c59c3ce2c9c6439b941b0d42d1435605\",\n \"optin_contact\": true\n }";
} else { } else if (! $reprogramming && ! $changeInstaller) { // <--- Ahora este else if está correctamente encadenado
//Enviar notificación normal de visita técnica al cliente // Case: false, false
//Enviar notificación normal de visita técnica al cliente
$log->appendLog("Enviando notificación normal de visita técnica al cliente, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL); $log->appendLog("Enviando notificación normal de visita técnica al cliente, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL);
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\"],\n \"template_uuid\": \"c0ef8228b50a4d9690a2e87bc11e9ab3\",\n \"optin_contact\": true\n }"; $curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\"],\n \"template_uuid\": \"c0ef8228b50a4d9690a2e87bc11e9ab3\",\n \"optin_contact\": true\n }";
}else if ($reprogramming && $changeInstaller) { // <--- Ahora este else if está correctamente encadenado
// Case: true, true
//Enviar notificación de cambio de instalador y reprogramación al cliente
$log->appendLog("Enviando notificación de cambio de instalador y reprogramación al cliente, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL);
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\"],\n \"template_uuid\": \"99e2629a3be2421687037c001222bfe4\",\n \"optin_contact\": true\n }";
} else {
// Case: true, true (la única combinación restante con booleanos)
$log->appendLog("No se encontró una opción válida para enviar la notificación (reprogramming y changeInstaller son true)." . PHP_EOL);
// Decide qué hacer aquí, ¿Quizás devolver false? ¿O manejar esta combinación?
return false; // O el manejo adecuado para true/true
} }
$log->appendLog("La cadena CURL que se envia es: " . $curl_string); $log->appendLog("La cadena CURL que se envia es: " . $curl_string);
@ -190,7 +201,8 @@ class ClientCallBellAPI
$log->appendLog("Ruta no prevista en la función." . PHP_EOL); $log->appendLog("Ruta no prevista en la función." . PHP_EOL);
return false; return false;
} }
public function sendJobNotificationWhatsAppToInstaller($installerWhatsAppNumber, $jobInstallerNotificationData, $reprogramming = false, $changeInstaller = false, $passwordAntenaCliente): bool
public function sendJobNotificationWhatsAppToInstaller($installerWhatsAppNumber, $jobInstallerNotificationData, $reprogramming, $changeInstaller, $passwordAntenaCliente): bool
{ {
$log = PluginLogManager::create(); //Initialize Logger $log = PluginLogManager::create(); //Initialize Logger
@ -198,6 +210,14 @@ class ClientCallBellAPI
$jsonJobNotificationData = json_encode($jobInstallerNotificationData, true); $jsonJobNotificationData = json_encode($jobInstallerNotificationData, true);
$log->appendLog("Datos de la notificación de tarea: " . $jsonJobNotificationData . PHP_EOL); $log->appendLog("Datos de la notificación de tarea: " . $jsonJobNotificationData . PHP_EOL);
// --- ¡AÑADE ESTAS LÍNEAS PARA CONVERTIR A BOOLEANO REAL! ---
$reprogramming = filter_var($reprogramming, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
$changeInstaller = filter_var($changeInstaller, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
// -----------------------------------------------------------
// Puedes volver a loggear los valores para confirmar la conversión (opcional)
$log->appendLog("DEBUG: Valores después de conversión - Reprogramming: " . var_export($reprogramming, true) . ", ChangeInstaller: " . var_export($changeInstaller, true) . PHP_EOL);
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.callbell.eu/v1/messages/send'); curl_setopt($ch, CURLOPT_URL, 'https://api.callbell.eu/v1/messages/send');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
@ -207,7 +227,6 @@ class ClientCallBellAPI
'Content-Type: application/json', 'Content-Type: application/json',
]); ]);
$campo1 = $jobInstallerNotificationData['installerName']; $campo1 = $jobInstallerNotificationData['installerName'];
if ($changeInstaller) { if ($changeInstaller) {
$campo2 = $jobInstallerNotificationData['subjectOfChange']; $campo2 = $jobInstallerNotificationData['subjectOfChange'];
@ -215,7 +234,7 @@ class ClientCallBellAPI
$campo4 = $jobInstallerNotificationData['clientFullName']; $campo4 = $jobInstallerNotificationData['clientFullName'];
$campo5 = $jobInstallerNotificationData['additionalChangeData']; $campo5 = $jobInstallerNotificationData['additionalChangeData'];
} else { } else {
$campo2 = sprintf("*#%s*", $jobInstallerNotificationData['jobId']); $campo2 = sprintf("#%s", $jobInstallerNotificationData['jobId']);
$campo3 = $jobInstallerNotificationData['clientFullName']; $campo3 = $jobInstallerNotificationData['clientFullName'];
// $campo4 = $jobInstallerNotificationData['clientAddress']; // $campo4 = $jobInstallerNotificationData['clientAddress'];
$campo4 = $jobInstallerNotificationData['clientWhatsApp']; $campo4 = $jobInstallerNotificationData['clientWhatsApp'];
@ -223,25 +242,24 @@ class ClientCallBellAPI
$campo6 = $jobInstallerNotificationData['jobDescription']; $campo6 = $jobInstallerNotificationData['jobDescription'];
$campo7 = $jobInstallerNotificationData['gmapsLocation']; $campo7 = $jobInstallerNotificationData['gmapsLocation'];
$campo8 = $passwordAntenaCliente; $campo8 = $passwordAntenaCliente;
} }
if ($reprogramming && ! $changeInstaller) {
if ($reprogramming && $changeInstaller === false) {
//Enviar notificación de reprogramación //Enviar notificación de reprogramación
$log->appendLog("Enviando notificación de reprogramación al instalador, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL); $log->appendLog("Enviando notificación de reprogramación al instalador, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL);
$curl_string = "{\n \"to\": \"$installerWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\", \"$campo5\", \"$campo6\", \"$campo7\", \"$campo8\"],\n \"template_uuid\": \"7eb4d8e27cf740779dd6777fad7ffaf4\",\n \"optin_contact\": true\n }"; $curl_string = "{\n \"to\": \"$installerWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\", \"$campo5\", \"$campo6\", \"$campo7\", \"$campo8\"],\n \"template_uuid\": \"7eb4d8e27cf740779dd6777fad7ffaf4\",\n \"optin_contact\": true\n }";
} else if (! $reprogramming && $changeInstaller) {
} else if ($changeInstaller) {
//Enviar notificación de cambio de instalador //Enviar notificación de cambio de instalador
$log->appendLog("Enviando notificación de cambio de instalador al instalador, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL); $log->appendLog("Enviando notificación de cambio de instalador al instalador anterior, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL);
$curl_string = "{\n \"to\": \"$installerWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\", \"$campo5\"],\n \"template_uuid\": \"e1aa2b0fd3884595918f4ac2676acd29\",\n \"optin_contact\": true\n }"; $curl_string = "{\n \"to\": \"$installerWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\", \"$campo5\"],\n \"template_uuid\": \"e1aa2b0fd3884595918f4ac2676acd29\",\n \"optin_contact\": true\n }";
}else if ($reprogramming && $changeInstaller) {
} else { //Enviar notificación de cambio de instalador
$log->appendLog("Enviando notificación de cambio de instalador al instalador y notificación de reprogramación al instalador, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL);
$curl_string = "{\n \"to\": \"$installerWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\", \"$campo5\"],\n \"template_uuid\": \"e1aa2b0fd3884595918f4ac2676acd29\",\n \"optin_contact\": true\n }";
} else if (! $reprogramming && ! $changeInstaller) {
//Enviar notificación normal de asignación de tarea //Enviar notificación normal de asignación de tarea
$log->appendLog("Enviando notificación normal de asignación de tarea al instalador, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL); $log->appendLog("Enviando notificación normal de asignación de tarea al instalador, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL);
$curl_string = "{\n \"to\": \"$installerWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\", \"$campo5\", \"$campo6\", \"$campo7\", \"$campo8\"],\n \"template_uuid\": \"fa7f3f8e25934e159a9203eb1cd7f7a6\",\n \"optin_contact\": true\n }"; $curl_string = "{\n \"to\": \"$installerWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\", \"$campo5\", \"$campo6\", \"$campo7\", \"$campo8\"],\n \"template_uuid\": \"670bedde35b3416f8c1a27f995ebe350\",\n \"optin_contact\": true\n }";
} }
$log->appendLog("La cadena CURL que se envia es: " . $curl_string); $log->appendLog("La cadena CURL que se envia es: " . $curl_string);
@ -276,7 +294,6 @@ class ClientCallBellAPI
// Valor de retorno predeterminado en caso de que ninguna condición se cumpla // Valor de retorno predeterminado en caso de que ninguna condición se cumpla
$log->appendLog("Ruta no prevista en la función." . PHP_EOL); $log->appendLog("Ruta no prevista en la función." . PHP_EOL);
return false; return false;
} }
public function sendPaymentNotificationWhatsApp($clientWhatsAppNumber, $notificationData): bool public function sendPaymentNotificationWhatsApp($clientWhatsAppNumber, $notificationData): bool
@ -293,27 +310,24 @@ class ClientCallBellAPI
//Path base del comprobante de pago //Path base del comprobante de pago
$pdf_payment_path = ''; $pdf_payment_path = '';
$this->ucrmApi = UcrmApi::create(); $this->ucrmApi = UcrmApi::create();
$payments = $this->ucrmApi->get( $payments = $this->ucrmApi->get(
'payments/', 'payments/',
[ [
'clientId' => $notificationData->clientData['id'], 'clientId' => $notificationData->clientData['id'],
'limit' => 1, 'limit' => 1,
'direction' => 'DESC' 'direction' => 'DESC',
] ]
); );
$payment_id = $payments[0]['id'];
$payment_id = $payments[0]['id'];
$payment_amount = '$' . $payments[0]['amount']; $payment_amount = '$' . $payments[0]['amount'];
//$saldo = '$' . $notificationData->clientData['accountBalance']; //$saldo = '$' . $notificationData->clientData['accountBalance'];
$nombre_cliente = sprintf("%s %s", $notificationData->clientData['firstName'], $notificationData->clientData['lastName']); $nombre_cliente = sprintf("%s %s", $notificationData->clientData['firstName'], $notificationData->clientData['lastName']);
$accountBalance = $notificationData->clientData['accountBalance']; $accountBalance = $notificationData->clientData['accountBalance'];
$saldoTexto = ''; $saldoTexto = '';
if ($accountBalance < 0) { if ($accountBalance < 0) {
// Si el saldo es negativo, quitar el signo y poner "Pendientes" // Si el saldo es negativo, quitar el signo y poner "Pendientes"
@ -329,15 +343,13 @@ class ClientCallBellAPI
// Configuración del cliente GuzzleHttp // Configuración del cliente GuzzleHttp
$clientGuzzleHttp = new Client([ $clientGuzzleHttp = new Client([
'base_uri' => $baseUri, 'base_uri' => $baseUri,
'headers' => [ 'headers' => [
'X-Auth-App-Key' => $token, // Cambia el nombre de la cabecera de autorización 'X-Auth-App-Key' => $token, // Cambia el nombre de la cabecera de autorización
'Accept' => 'application/pdf', // Indica que esperamos una respuesta en formato JSON 'Accept' => 'application/pdf', // Indica que esperamos una respuesta en formato JSON
], ],
'verify' => false, 'verify' => false,
]); ]);
try { try {
// Hacer la solicitud GET para obtener el PDF // Hacer la solicitud GET para obtener el PDF
$response = $clientGuzzleHttp->request('GET', "payments/$payment_id/pdf"); $response = $clientGuzzleHttp->request('GET', "payments/$payment_id/pdf");
@ -347,7 +359,7 @@ class ClientCallBellAPI
// Construir el nombre del archivo PDF basado en el cliente // Construir el nombre del archivo PDF basado en el cliente
$fileNameComprobante = 'Comprobante_' . str_replace(' ', '_', $nombre_cliente) . '.pdf'; $fileNameComprobante = 'Comprobante_' . str_replace(' ', '_', $nombre_cliente) . '.pdf';
$rutaArchivo = __DIR__ . '/../../comprobantes/' . $fileNameComprobante; $rutaArchivo = __DIR__ . '/../../comprobantes/' . $fileNameComprobante;
// Guardar el contenido del PDF en un archivo local // Guardar el contenido del PDF en un archivo local
if (file_put_contents($rutaArchivo, $contenidoArchivo) !== false) { if (file_put_contents($rutaArchivo, $contenidoArchivo) !== false) {
@ -357,7 +369,7 @@ class ClientCallBellAPI
return false; return false;
} }
if (!file_exists($rutaArchivo)) { if (! file_exists($rutaArchivo)) {
$log->appendLog("El archivo PDF no existe: $rutaArchivo" . PHP_EOL); $log->appendLog("El archivo PDF no existe: $rutaArchivo" . PHP_EOL);
return false; return false;
} }
@ -369,20 +381,11 @@ class ClientCallBellAPI
$log->appendLog("El archivo PDF es válido y tiene contenido: $rutaArchivo" . PHP_EOL); $log->appendLog("El archivo PDF es válido y tiene contenido: $rutaArchivo" . PHP_EOL);
$rutaImagen = __DIR__ . '/../../comprobantes/' . str_replace('.pdf', '.png', $fileNameComprobante); $rutaImagen = __DIR__ . '/../../comprobantes/' . str_replace('.pdf', '.png', $fileNameComprobante);
} catch (\Exception $e) { } catch (\Exception $e) {
$log->appendLog("Error al manejar el comprobante de pago: " . $e->getMessage() . PHP_EOL); $log->appendLog("Error al manejar el comprobante de pago: " . $e->getMessage() . PHP_EOL);
return false; return false;
} }
try { try {
$image = new Imagick(); $image = new Imagick();
$image->setResolution(300, 300); $image->setResolution(300, 300);
@ -398,16 +401,12 @@ class ClientCallBellAPI
return false; return false;
} }
$fileNameComprobanteImage = str_replace('.pdf', '.png', $fileNameComprobante); $fileNameComprobanteImage = str_replace('.pdf', '.png', $fileNameComprobante);
$url_file = $this->UploadReceiptToWordpressByImageFileName($fileNameComprobanteImage);//Carga del comprobante PDF a Wordpress para su posterior envío $url_file = $this->UploadReceiptToWordpressByImageFileName($fileNameComprobanteImage); //Carga del comprobante PDF a Wordpress para su posterior envío
// $url_file = $this->UploadReceiptToWordpressByImageFileName($fileNameComprobante);//Carga del comprobante PDF a Wordpress para su posterior envío // $url_file = $this->UploadReceiptToWordpressByImageFileName($fileNameComprobante);//Carga del comprobante PDF a Wordpress para su posterior envío
$log->appendLog("Se terminó de subir comprobante a wordpress " . PHP_EOL); $log->appendLog("Se terminó de subir comprobante a wordpress " . PHP_EOL);
//$log->appendLog("Entrando al metodo sendPaymentNotificationWhatsAp" . PHP_EOL); //$log->appendLog("Entrando al metodo sendPaymentNotificationWhatsAp" . PHP_EOL);
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.callbell.eu/v1/messages/send'); curl_setopt($ch, CURLOPT_URL, 'https://api.callbell.eu/v1/messages/send');
@ -418,8 +417,6 @@ class ClientCallBellAPI
'Content-Type: application/json', 'Content-Type: application/json',
]); ]);
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"document\",\n \"content\": {\n \"text\": \"S/M\",\n \"url\": \"$url_file\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$payment_amount\", \"$saldoTexto\"],\n \"template_uuid\": \"57ead79cebd14902921477922403093b\",\n \"optin_contact\": true\n }"; $curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"document\",\n \"content\": {\n \"text\": \"S/M\",\n \"url\": \"$url_file\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$payment_amount\", \"$saldoTexto\"],\n \"template_uuid\": \"57ead79cebd14902921477922403093b\",\n \"optin_contact\": true\n }";
$log->appendLog("La cadena CURL que se envia es: " . $curl_string); $log->appendLog("La cadena CURL que se envia es: " . $curl_string);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curl_string); curl_setopt($ch, CURLOPT_POSTFIELDS, $curl_string);
@ -466,24 +463,20 @@ class ClientCallBellAPI
public function sendTextPaymentNotificationWhatsApp($clientWhatsAppNumber, $notificationData): bool public function sendTextPaymentNotificationWhatsApp($clientWhatsAppNumber, $notificationData): bool
{ {
$nombre_cliente = sprintf("%s %s", $notificationData->clientData['firstName'], $notificationData->clientData['lastName']);
$nombre_cliente = sprintf("%s %s", $notificationData->clientData['firstName'], $notificationData->clientData['lastName']); $folio = $notificationData->paymentData['id'];
$folio = $notificationData->paymentData['id']; $client_id = $notificationData->clientData['id'];
$client_id = $notificationData->clientData['id']; $fecha_pago = '';
$fecha_pago = null;
$cantidad_pagada = $notificationData->paymentData['amount']; $cantidad_pagada = $notificationData->paymentData['amount'];
$metodo_pago = ''; $metodo_pago = '';
//$invoice_id= null; //$invoice_id= null;
$total_factura = null; $total_factura = null;
$pago_factura = $notificationData->paymentData['amount']; $pago_factura = $notificationData->paymentData['amount'];
// $saldoTexto= null; // $saldoTexto= null;
$creditoPorPago = $notificationData->paymentData['creditAmount']; $creditoPorPago = $notificationData->paymentData['creditAmount'];
$texto_credito = null; $texto_credito = null;
$creditoClienteBase = $notificationData->clientData['accountCredit']; $creditoClienteBase = $notificationData->clientData['accountCredit'];
switch ($notificationData->paymentData['methodId']) { switch ($notificationData->paymentData['methodId']) {
case '11721cdf-a498-48be-903e-daa67552e4f6': case '11721cdf-a498-48be-903e-daa67552e4f6':
$metodo_pago = 'Cheque 📄'; $metodo_pago = 'Cheque 📄';
@ -518,11 +511,8 @@ class ClientCallBellAPI
default: default:
$metodo_pago = 'Desconocido, revisar metodos de pago no contemplados'; $metodo_pago = 'Desconocido, revisar metodos de pago no contemplados';
break; break;
} }
$log = PluginLogManager::create(); //Initialize Logger $log = PluginLogManager::create(); //Initialize Logger
$log->appendLog("Eviando comprobante de pago al cliente: " . $notificationData->clientData['id'] . ' con número: ' . $clientWhatsAppNumber . PHP_EOL); $log->appendLog("Eviando comprobante de pago al cliente: " . $notificationData->clientData['id'] . ' con número: ' . $clientWhatsAppNumber . PHP_EOL);
@ -534,14 +524,13 @@ class ClientCallBellAPI
//Path base del comprobante de pago //Path base del comprobante de pago
$pdf_payment_path = ''; $pdf_payment_path = '';
$this->ucrmApi = UcrmApi::create(); $this->ucrmApi = UcrmApi::create();
$payments = $this->ucrmApi->get( $payments = $this->ucrmApi->get(
'payments/', 'payments/',
[ [
'clientId' => $notificationData->clientData['id'], 'clientId' => $notificationData->clientData['id'],
'limit' => 1, 'limit' => 1,
'direction' => 'DESC' 'direction' => 'DESC',
] ]
); );
@ -550,7 +539,6 @@ class ClientCallBellAPI
$datos_paymentJsonText = json_encode($payments, true); $datos_paymentJsonText = json_encode($payments, true);
$log->appendLog("Datos traidos con payment api: " . $datos_paymentJsonText . PHP_EOL); $log->appendLog("Datos traidos con payment api: " . $datos_paymentJsonText . PHP_EOL);
// $log->appendLog("Check 1" . PHP_EOL); // $log->appendLog("Check 1" . PHP_EOL);
$paymentDate = new DateTime($fecha_pago); $paymentDate = new DateTime($fecha_pago);
@ -560,9 +548,8 @@ class ClientCallBellAPI
// Formatear la fecha como "d/m/Y g:ia" (día/mes/año hora:minutos am/pm) // Formatear la fecha como "d/m/Y g:ia" (día/mes/año hora:minutos am/pm)
$fecha_pago = $paymentDate->format('d/m/Y g:ia'); $fecha_pago = $paymentDate->format('d/m/Y g:ia');
$accountBalance = $notificationData->clientData['accountBalance']; $accountBalance = $notificationData->clientData['accountBalance'];
$saldoTexto = ''; $saldoTexto = '';
if ($accountBalance < 0) { if ($accountBalance < 0) {
// Si el saldo es negativo, quitar el signo y poner "Pendientes" // Si el saldo es negativo, quitar el signo y poner "Pendientes"
@ -578,25 +565,19 @@ class ClientCallBellAPI
$log->appendLog("Datos client data credit amount: " . $notificationData->paymentData['creditAmount'] . PHP_EOL); $log->appendLog("Datos client data credit amount: " . $notificationData->paymentData['creditAmount'] . PHP_EOL);
$cantidad_pagadaFormateada = '$' . number_format($cantidad_pagada, 2, ',', '.') . ' MXN'; $cantidad_pagadaFormateada = '$' . number_format($cantidad_pagada, 2, ',', '.') . ' MXN';
$creditoPorPagoFormateado = '$' . number_format($creditoPorPago, 2, ',', '.') . ' MXN'; $creditoPorPagoFormateado = '$' . number_format($creditoPorPago, 2, ',', '.') . ' MXN';
if ($creditoClienteBase > 0 && empty($notificationData->paymentData['paymentCovers'])) { if ($creditoClienteBase > 0 && empty($notificationData->paymentData['paymentCovers'])) {
$texto_credito = "La cantidad que sobra de $creditoPorPagoFormateado se ha convertido a crédito"; $texto_credito = "La cantidad que sobra de $creditoPorPagoFormateado se ha convertido a crédito";
$log->appendLog("La cantidad que sobra de $creditoPorPagoFormateado se ha convertido a crédito" . PHP_EOL); $log->appendLog("La cantidad que sobra de $creditoPorPagoFormateado se ha convertido a crédito" . PHP_EOL);
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"John Doe\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$folio\", \"$client_id\", \"$fecha_pago\", \"$cantidad_pagadaFormateada\", \"$metodo_pago\", \"$saldoTexto\", \"$texto_credito\"],\n \"template_uuid\": \"4ac9dc060cf746b6ad7f2e8acad355e0\",\n \"optin_contact\": true\n }"; $curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"John Doe\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$folio\", \"$client_id\", \"$fecha_pago\", \"$cantidad_pagadaFormateada\", \"$metodo_pago\", \"$saldoTexto\", \"$texto_credito\"],\n \"template_uuid\": \"4ac9dc060cf746b6ad7f2e8acad355e0\",\n \"optin_contact\": true\n }";
} else { } else {
if ($creditoPorPago > 0) { if ($creditoPorPago > 0) {
$texto_credito = "La cantidad que sobra de $creditoPorPagoFormateado se ha convertido a crédito"; $texto_credito = "La cantidad que sobra de $creditoPorPagoFormateado se ha convertido a crédito";
$log->appendLog("La cantidad que sobra de $creditoPorPagoFormateado se ha convertido a crédito" . PHP_EOL); $log->appendLog("La cantidad que sobra de $creditoPorPagoFormateado se ha convertido a crédito" . PHP_EOL);
} else { } else {
$texto_credito = '_________________________'; $texto_credito = '_________________________';
} }
@ -604,24 +585,22 @@ class ClientCallBellAPI
// Configuración del cliente GuzzleHttp // Configuración del cliente GuzzleHttp
$clientGuzzleHttp = new Client([ $clientGuzzleHttp = new Client([
'base_uri' => $baseUri, 'base_uri' => $baseUri,
'headers' => [ 'headers' => [
'X-Auth-App-Key' => $token, // Cambia el nombre de la cabecera de autorización 'X-Auth-App-Key' => $token, // Cambia el nombre de la cabecera de autorización
'Accept' => 'application/pdf', // Indica que esperamos una respuesta en formato JSON 'Accept' => 'application/pdf', // Indica que esperamos una respuesta en formato JSON
], ],
'verify' => false, 'verify' => false,
]); ]);
$log->appendLog("Verificar paymentCovers " . PHP_EOL); $log->appendLog("Verificar paymentCovers " . PHP_EOL);
$log->appendLog("payment covers" . json_encode($notificationData->paymentData['paymentCovers']) . PHP_EOL); $log->appendLog("payment covers" . json_encode($notificationData->paymentData['paymentCovers']) . PHP_EOL);
if (! empty($notificationData->paymentData['paymentCovers'])) {
if (!empty($notificationData->paymentData['paymentCovers'])) {
$log->appendLog('Datos del payment covers:' . PHP_EOL); $log->appendLog('Datos del payment covers:' . PHP_EOL);
$invoiceIds = ''; // Variable para almacenar los invoiceId $invoiceIds = ''; // Variable para almacenar los invoiceId
$amounts = ''; // Variable para almacenar los amounts formateados $amounts = ''; // Variable para almacenar los amounts formateados
foreach ($notificationData->paymentData['paymentCovers'] as $paymentCover) { foreach ($notificationData->paymentData['paymentCovers'] as $paymentCover) {
$log->appendLog('Invoice ID pagado: ' . $paymentCover['invoiceId'] . ' de esta cantidad: ' . $paymentCover['amount'] . PHP_EOL); $log->appendLog('Invoice ID pagado: ' . $paymentCover['invoiceId'] . ' de esta cantidad: ' . $paymentCover['amount'] . PHP_EOL);
@ -636,9 +615,9 @@ class ClientCallBellAPI
$amounts .= $formattedAmount . ', '; $amounts .= $formattedAmount . ', ';
} }
// Eliminar la última coma y el espacio extra usando substr // Eliminar la última coma y el espacio extra usando substr
$invoiceIds = substr($invoiceIds, 0, -2); // Elimina los últimos dos caracteres (coma y espacio) $invoiceIds = substr($invoiceIds, 0, -2); // Elimina los últimos dos caracteres (coma y espacio)
$amounts = substr($amounts, 0, -2); // Elimina los últimos dos caracteres (coma y espacio) $amounts = substr($amounts, 0, -2); // Elimina los últimos dos caracteres (coma y espacio)
// Mostrar las cadenas finales // Mostrar las cadenas finales
$log->appendLog('Todos los Invoice IDs: ' . $invoiceIds . PHP_EOL); $log->appendLog('Todos los Invoice IDs: ' . $invoiceIds . PHP_EOL);
@ -650,38 +629,29 @@ class ClientCallBellAPI
$response = $clientGuzzleHttp->request('GET', "invoices/$invoiceIds"); $response = $clientGuzzleHttp->request('GET', "invoices/$invoiceIds");
// Realizar la solicitud a la API y guardar el contenido en un archivo local // Realizar la solicitud a la API y guardar el contenido en un archivo local
$responseInvoices = $response->getBody()->getContents(); $responseInvoices = $response->getBody()->getContents();
$responseInvoicesJSON = json_decode($responseInvoices, true); $responseInvoicesJSON = json_decode($responseInvoices, true);
$log->appendLog('Numero de factura: ' . $responseInvoicesJSON['number'] . PHP_EOL); $log->appendLog('Numero de factura: ' . $responseInvoicesJSON['number'] . PHP_EOL);
$log->appendLog('TOTAL de factura: ' . $responseInvoicesJSON['total'] . PHP_EOL); $log->appendLog('TOTAL de factura: ' . $responseInvoicesJSON['total'] . PHP_EOL);
$total_factura = $responseInvoicesJSON['total']; $total_factura = $responseInvoicesJSON['total'];
} catch (\Exception $e) { } catch (\Exception $e) {
$log->appendLog("Error con un problema al obtener alguna factura del cliente: " . $e->getMessage() . PHP_EOL); $log->appendLog("Error con un problema al obtener alguna factura del cliente: " . $e->getMessage() . PHP_EOL);
return false; return false;
} }
} else { } else {
$log->appendLog("no hay datos en payment covers" . PHP_EOL); $log->appendLog("no hay datos en payment covers" . PHP_EOL);
$invoiceIds = $notificationData->paymentData['id']; $invoiceIds = $notificationData->paymentData['id'];
$amounts = $notificationData->paymentData['amount']; $amounts = $notificationData->paymentData['amount'];
$total_factura = 0; $total_factura = 0;
} }
//$cantidad_pagadaFormateada = '$' . number_format($cantidad_pagada, 2, ',', '.') . ' MXN'; //$cantidad_pagadaFormateada = '$' . number_format($cantidad_pagada, 2, ',', '.') . ' MXN';
$log->appendLog("Se terminó de verificar payment covers" . PHP_EOL); $log->appendLog("Se terminó de verificar payment covers" . PHP_EOL);
$total_facturaFormateada = '$' . number_format($total_factura, 2, ',', '.') . ' MXN'; $total_facturaFormateada = '$' . number_format($total_factura, 2, ',', '.') . ' MXN';
$pagoFacturaFormateado = '$' . $amounts . ' MXN'; $pagoFacturaFormateado = '$' . $amounts . ' MXN';
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"John Doe\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$folio\", \"$client_id\", \"$fecha_pago\", \"$cantidad_pagadaFormateada\", \"$metodo_pago\", \"$invoiceIds\", \"$total_facturaFormateada\", \"$pagoFacturaFormateado\", \"$saldoTexto\", \"$texto_credito\"],\n \"template_uuid\": \"c1396a6ad3cb4192916d4ac2bfb782a5\",\n \"optin_contact\": true\n }"; $curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"John Doe\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$folio\", \"$client_id\", \"$fecha_pago\", \"$cantidad_pagadaFormateada\", \"$metodo_pago\", \"$invoiceIds\", \"$total_facturaFormateada\", \"$pagoFacturaFormateado\", \"$saldoTexto\", \"$texto_credito\"],\n \"template_uuid\": \"c1396a6ad3cb4192916d4ac2bfb782a5\",\n \"optin_contact\": true\n }";
} }
//$log->appendLog("Entrando al metodo sendPaymentNotificationWhatsAp" . PHP_EOL); //$log->appendLog("Entrando al metodo sendPaymentNotificationWhatsAp" . PHP_EOL);
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.callbell.eu/v1/messages/send'); curl_setopt($ch, CURLOPT_URL, 'https://api.callbell.eu/v1/messages/send');
@ -692,9 +662,6 @@ class ClientCallBellAPI
'Content-Type: application/json', 'Content-Type: application/json',
]); ]);
//$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"document\",\n \"content\": {\n \"text\": \"S/M\",\n \"url\": \"$url_file\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$payment_amount\", \"$saldo\"],\n \"template_uuid\": \"6c0df98317b44f7b8666375a6cc8454c\",\n \"optin_contact\": true\n }"; //$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"document\",\n \"content\": {\n \"text\": \"S/M\",\n \"url\": \"$url_file\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$payment_amount\", \"$saldo\"],\n \"template_uuid\": \"6c0df98317b44f7b8666375a6cc8454c\",\n \"optin_contact\": true\n }";
// $curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\"],\n \"template_uuid\": \"55705f1fe4e24bab80104dc2643fe11c\",\n \"optin_contact\": true\n }"; // $curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\"],\n \"template_uuid\": \"55705f1fe4e24bab80104dc2643fe11c\",\n \"optin_contact\": true\n }";
@ -743,7 +710,6 @@ class ClientCallBellAPI
public function sendOverdueNotificationWhatsApp($clientWhatsAppNumber, $notificationData): void public function sendOverdueNotificationWhatsApp($clientWhatsAppNumber, $notificationData): void
{ {
$log = PluginLogManager::create(); //Initialize Logger $log = PluginLogManager::create(); //Initialize Logger
// URL base de la API // URL base de la API
@ -753,7 +719,6 @@ class ClientCallBellAPI
//Path base del comprobante de pago //Path base del comprobante de pago
//$pdf_payment_path = ''; //$pdf_payment_path = '';
// $this->ucrmApi = UcrmApi::create(); // $this->ucrmApi = UcrmApi::create();
// $invoices = $this->ucrmApi->get( // $invoices = $this->ucrmApi->get(
// 'invoices/', // 'invoices/',
@ -774,7 +739,7 @@ class ClientCallBellAPI
// $invoice_id = $invoices[0]['id']; // $invoice_id = $invoices[0]['id'];
// $invoices_amount = '$' . $invoices[0]['amount']; // $invoices_amount = '$' . $invoices[0]['amount'];
$saldo = '$' . $notificationData->clientData['accountBalance']; $saldo = '$' . $notificationData->clientData['accountBalance'];
$nombre_cliente = sprintf("%s %s", $notificationData->clientData['firstName'], $notificationData->clientData['lastName']); $nombre_cliente = sprintf("%s %s", $notificationData->clientData['firstName'], $notificationData->clientData['lastName']);
// Configuración del cliente GuzzleHttp // Configuración del cliente GuzzleHttp
@ -787,8 +752,6 @@ class ClientCallBellAPI
// 'verify' => false, // 'verify' => false,
// ]); // ]);
// if (empty($notificationData->clientData['contacts'][0]['email'])) { // if (empty($notificationData->clientData['contacts'][0]['email'])) {
// $log->appendLog("El cliente no tiene correo" . PHP_EOL); // $log->appendLog("El cliente no tiene correo" . PHP_EOL);
// } else { // } else {
@ -816,9 +779,6 @@ class ClientCallBellAPI
// $log->appendLog("La ruta no es válida o no existe" . PHP_EOL); // $log->appendLog("La ruta no es válida o no existe" . PHP_EOL);
// } // }
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"SIIP INTERNET\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\",\n },\n \"template_values\": [\"$nombre_cliente\", \"$saldo\"],\n \"template_uuid\": \"9e7024c0a61a4c49b382150d26888dc2\",\n \"optin_contact\": true\n }"; $curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"SIIP INTERNET\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\",\n },\n \"template_values\": [\"$nombre_cliente\", \"$saldo\"],\n \"template_uuid\": \"9e7024c0a61a4c49b382150d26888dc2\",\n \"optin_contact\": true\n }";
//$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"document\",\n \"content\": {\n \"text\": \"S/M\",\n \"url\": \"$url_file\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$payment_amount\", \"$saldo\"],\n \"template_uuid\": \"57ead79cebd14902921477922403093b\",\n \"optin_contact\": true\n }"; //$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"document\",\n \"content\": {\n \"text\": \"S/M\",\n \"url\": \"$url_file\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$payment_amount\", \"$saldo\"],\n \"template_uuid\": \"57ead79cebd14902921477922403093b\",\n \"optin_contact\": true\n }";
//$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"document\",\n \"content\": {\n \"text\": \"S/M\",\n \"url\": \"$url_file\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$payment_amount\", \"$saldo\"],\n \"template_uuid\": \"6c0df98317b44f7b8666375a6cc8454c\",\n \"optin_contact\": true\n }"; //$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"document\",\n \"content\": {\n \"text\": \"S/M\",\n \"url\": \"$url_file\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$payment_amount\", \"$saldo\"],\n \"template_uuid\": \"6c0df98317b44f7b8666375a6cc8454c\",\n \"optin_contact\": true\n }";
@ -831,10 +791,8 @@ class ClientCallBellAPI
$log->appendLog("Response del CallBell: " . $response); $log->appendLog("Response del CallBell: " . $response);
curl_close($ch); curl_close($ch);
} }
public function getContactWhatsapp($cellphone_number): string public function getContactWhatsapp($cellphone_number): string
{ {
// URL de la API REST // URL de la API REST
@ -848,7 +806,7 @@ class ClientCallBellAPI
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [ curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $this->CallBellAPIToken, 'Authorization: Bearer ' . $this->CallBellAPIToken,
'Content-Type: application/json' 'Content-Type: application/json',
]); ]);
// Ejecutar la solicitud y obtener la respuesta // Ejecutar la solicitud y obtener la respuesta
@ -868,13 +826,13 @@ class ClientCallBellAPI
{ {
$log = PluginLogManager::create(); //Initialize Logger $log = PluginLogManager::create(); //Initialize Logger
//imprimir notificacionData //imprimir notificacionData
$log->appendLog("Notificacion data: " . json_encode($notificationData) . PHP_EOL); $log->appendLog("Notificacion data: " . json_encode($notificationData) . PHP_EOL);
//ejemplo de $notificationData: {"uuid":"cad4fa25-176e-4823-9f4c-1421d05d2a31","changeType":"edit","entity":"client","entityId":2,"message":null,"clientId":2,"eventName":"client.edit","clientData":{"id":2,"userIdent":null,"previousIsp":null,"isLead":false,"clientType":1,"companyName":null,"companyRegistrationNumber":null,"companyTaxId":null,"companyWebsite":null,"street1":"31 Chiapas","street2":null,"city":"Dolores Hidalgo Cuna de la Independencia Nacional","countryId":173,"stateId":null,"zipCode":"37800","fullAddress":"Chiapas 31, Centro, Dolores Hidalgo Cuna de la Independencia Nacional, Gto., M\u00e9xico","invoiceStreet1":null,"invoiceStreet2":null,"invoiceCity":null,"invoiceStateId":null,"invoiceCountryId":null,"invoiceZipCode":null,"invoiceAddressSameAsContact":true,"note":"Cliente espacial, el m\u00e1s chido","sendInvoiceByPost":null,"invoiceMaturityDays":null,"stopServiceDue":null,"stopServiceDueDays":null,"organizationId":1,"tax1Id":null,"tax2Id":null,"tax3Id":null,"registrationDate":"2024-01-25T00:00:00-0600","leadConvertedAt":null,"companyContactFirstName":null,"companyContactLastName":null,"isActive":true,"firstName":"Daniel Humberto","lastName":"Soto Villegas Pollerias2","username":"danydhsv","contacts":[{"id":2,"clientId":2,"email":"dhsv.141089@gmail.com","phone":"5214181878106","name":"Personal","isBilling":false,"isContact":false,"types":[{"id":1000,"name":"WhatsApp"}]},{"id":170,"clientId":2,"email":null,"phone":"5214181817609","name":"Bussiness","isBilling":false,"isContact":false,"types":[]}],"attributes":[{"id":112,"clientId":2,"customAttributeId":10,"name":"Stripe Customer ID","key":"stripeCustomerId","value":"cus_PetN1dhr4rx0kX","clientZoneVisible":true},{"id":113,"clientId":2,"customAttributeId":11,"name":"Clabe Interbancaria","key":"clabeInterbancaria","value":"0021804341999569810","clientZoneVisible":true},{"id":178,"clientId":2,"customAttributeId":15,"name":"Site","key":"site","value":"0LOCS","clientZoneVisible":false},{"id":179,"clientId":2,"customAttributeId":16,"name":"Antena\/Sectorial","key":"antenaSectorial","value":"Sectorial-4b 172.16.13.16\/24","clientZoneVisible":false}],"accountBalance":1553.33,"accountCredit":1553.33,"accountOutstanding":0,"currencyCode":"MXN","organizationName":"SIIP Pruebas","bankAccounts":[],"tags":[{"id":2,"name":"NS EXENTO","colorBackground":"#42a3df","colorText":"#fff"}],"invitationEmailSentDate":null,"avatarColor":"#f1df43","addressGpsLat":21.1564209,"addressGpsLon":-100.9384185,"isArchived":false,"generateProformaInvoices":null,"usesProforma":false,"hasOverdueInvoice":false,"hasOutage":true,"hasSuspendedService":false,"hasServiceWithoutDevices":false,"referral":null,"hasPaymentSubscription":false,"hasAutopayCreditCard":false},"serviceData":null,"invoiceData":null,"paymentData":null} //ejemplo de $notificationData: {"uuid":"cad4fa25-176e-4823-9f4c-1421d05d2a31","changeType":"edit","entity":"client","entityId":2,"message":null,"clientId":2,"eventName":"client.edit","clientData":{"id":2,"userIdent":null,"previousIsp":null,"isLead":false,"clientType":1,"companyName":null,"companyRegistrationNumber":null,"companyTaxId":null,"companyWebsite":null,"street1":"31 Chiapas","street2":null,"city":"Dolores Hidalgo Cuna de la Independencia Nacional","countryId":173,"stateId":null,"zipCode":"37800","fullAddress":"Chiapas 31, Centro, Dolores Hidalgo Cuna de la Independencia Nacional, Gto., M\u00e9xico","invoiceStreet1":null,"invoiceStreet2":null,"invoiceCity":null,"invoiceStateId":null,"invoiceCountryId":null,"invoiceZipCode":null,"invoiceAddressSameAsContact":true,"note":"Cliente espacial, el m\u00e1s chido","sendInvoiceByPost":null,"invoiceMaturityDays":null,"stopServiceDue":null,"stopServiceDueDays":null,"organizationId":1,"tax1Id":null,"tax2Id":null,"tax3Id":null,"registrationDate":"2024-01-25T00:00:00-0600","leadConvertedAt":null,"companyContactFirstName":null,"companyContactLastName":null,"isActive":true,"firstName":"Daniel Humberto","lastName":"Soto Villegas Pollerias2","username":"danydhsv","contacts":[{"id":2,"clientId":2,"email":"dhsv.141089@gmail.com","phone":"5214181878106","name":"Personal","isBilling":false,"isContact":false,"types":[{"id":1000,"name":"WhatsApp"}]},{"id":170,"clientId":2,"email":null,"phone":"5214181817609","name":"Bussiness","isBilling":false,"isContact":false,"types":[]}],"attributes":[{"id":112,"clientId":2,"customAttributeId":10,"name":"Stripe Customer ID","key":"stripeCustomerId","value":"cus_PetN1dhr4rx0kX","clientZoneVisible":true},{"id":113,"clientId":2,"customAttributeId":11,"name":"Clabe Interbancaria","key":"clabeInterbancaria","value":"0021804341999569810","clientZoneVisible":true},{"id":178,"clientId":2,"customAttributeId":15,"name":"Site","key":"site","value":"0LOCS","clientZoneVisible":false},{"id":179,"clientId":2,"customAttributeId":16,"name":"Antena\/Sectorial","key":"antenaSectorial","value":"Sectorial-4b 172.16.13.16\/24","clientZoneVisible":false}],"accountBalance":1553.33,"accountCredit":1553.33,"accountOutstanding":0,"currencyCode":"MXN","organizationName":"SIIP Pruebas","bankAccounts":[],"tags":[{"id":2,"name":"NS EXENTO","colorBackground":"#42a3df","colorText":"#fff"}],"invitationEmailSentDate":null,"avatarColor":"#f1df43","addressGpsLat":21.1564209,"addressGpsLon":-100.9384185,"isArchived":false,"generateProformaInvoices":null,"usesProforma":false,"hasOverdueInvoice":false,"hasOutage":true,"hasSuspendedService":false,"hasServiceWithoutDevices":false,"referral":null,"hasPaymentSubscription":false,"hasAutopayCreditCard":false},"serviceData":null,"invoiceData":null,"paymentData":null}
//buscar el attribute con el key site y antenaSectorial //buscar el attribute con el key site y antenaSectorial
$attributes = $notificationData->clientData['attributes']; //Obtener los atributos del cliente $attributes = $notificationData->clientData['attributes']; //Obtener los atributos del cliente
$site = ''; $site = '';
$antenaSectorial = ''; $antenaSectorial = '';
// Iterar sobre los atributos // Iterar sobre los atributos
@ -889,16 +847,14 @@ class ClientCallBellAPI
} }
} }
$log->appendLog("Dentro del proceso del patch: " . PHP_EOL); $log->appendLog("Dentro del proceso del patch: " . PHP_EOL);
$this->ucrmApi = UcrmApi::create(); $this->ucrmApi = UcrmApi::create();
$payments = $this->ucrmApi->get( $payments = $this->ucrmApi->get(
'payments/', 'payments/',
[ [
'clientId' => $notificationData->clientData['id'], 'clientId' => $notificationData->clientData['id'],
'limit' => 1, 'limit' => 1,
'direction' => 'DESC' 'direction' => 'DESC',
] ]
); );
@ -910,12 +866,8 @@ class ClientCallBellAPI
//$log->appendLog("Esto es lo que trae la fecha mas reciente de los pagos: " . $notificationData->paymentData[0]['createdDate']. PHP_EOL); //$log->appendLog("Esto es lo que trae la fecha mas reciente de los pagos: " . $notificationData->paymentData[0]['createdDate']. PHP_EOL);
// $log->appendLog("Esto es lo que trae la fecha mas reciente de los pagos opcion 2: " . $payments[0]['createdDate'] . PHP_EOL); // $log->appendLog("Esto es lo que trae la fecha mas reciente de los pagos opcion 2: " . $payments[0]['createdDate'] . PHP_EOL);
$uuid = $response_getContactCallBell['contact']['uuid']; $uuid = $response_getContactCallBell['contact']['uuid'];
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
curl_setopt($ch, CURLOPT_HTTPHEADER, [ curl_setopt($ch, CURLOPT_HTTPHEADER, [
@ -938,7 +890,7 @@ class ClientCallBellAPI
$log->appendLog("UUID: " . $uuid . PHP_EOL); $log->appendLog("UUID: " . $uuid . PHP_EOL);
$payment_method_id = $payments[0]['methodId']; $payment_method_id = $payments[0]['methodId'];
$payment_method = ''; $payment_method = '';
switch ($payment_method_id) { switch ($payment_method_id) {
case '11721cdf-a498-48be-903e-daa67552e4f6': case '11721cdf-a498-48be-903e-daa67552e4f6':
@ -974,11 +926,8 @@ class ClientCallBellAPI
default: default:
$payment_method = 'Desconocido, revisar metodos de pago no contemplados'; $payment_method = 'Desconocido, revisar metodos de pago no contemplados';
break; break;
} }
$fecha_actual = new DateTime(); $fecha_actual = new DateTime();
$fecha_actual->modify('-6 hours'); $fecha_actual->modify('-6 hours');
$fecha_actual_ajustada = $fecha_actual->format("d/m/Y H:i"); $fecha_actual_ajustada = $fecha_actual->format("d/m/Y H:i");
@ -1004,7 +953,7 @@ class ClientCallBellAPI
// } // }
$accountBalance = $notificationData->clientData['accountBalance']; $accountBalance = $notificationData->clientData['accountBalance'];
$saldoTexto = ''; $saldoTexto = '';
if ($accountBalance < 0) { if ($accountBalance < 0) {
// Si el saldo es negativo, quitar el signo y poner "Pendientes" // Si el saldo es negativo, quitar el signo y poner "Pendientes"
@ -1018,11 +967,11 @@ class ClientCallBellAPI
} }
$resumenClienteJSON = '{' . $resumenClienteJSON = '{' .
'"Cliente": "' . $notificationData->clientData['id'] . '",' . '"Cliente": "' . $notificationData->clientData['id'] . '",' .
'"Domicilio": "' . '"Domicilio": "' .
//(($notificationData->clientData['fullAddress'] == null) ? 'Sin domicilio' : '' . $notificationData->clientData['fullAddress']) . '",' . //(($notificationData->clientData['fullAddress'] == null) ? 'Sin domicilio' : '' . $notificationData->clientData['fullAddress']) . '",' .
'"Nombre": "' . sprintf("%s %s", $notificationData->clientData['firstName'], $notificationData->clientData['lastName']) . '",' . '"Nombre": "' . sprintf("%s %s", $notificationData->clientData['firstName'], $notificationData->clientData['lastName']) . '",' .
'"URL": "https://sistema.siip.mx/crm/client/' . $notificationData->clientId . '",' . '"URL": "https://sistema.siip.mx/crm/client/' . $notificationData->clientId . '",' .
'"Saldo Actual": "' . $saldoTexto . '",' . '"Saldo Actual": "' . $saldoTexto . '",' .
'"Monto Ultimo Pago": "$ ' . $payments[0]['amount'] . '",' . '"Monto Ultimo Pago": "$ ' . $payments[0]['amount'] . '",' .
'"Estado": "' . '"Estado": "' .
@ -1034,39 +983,34 @@ class ClientCallBellAPI
'"Antena/Sectorial": "' . $antenaSectorial . '"' . '"Antena/Sectorial": "' . $antenaSectorial . '"' .
'}'; '}';
$data_CRM = [
$data_CRM = array(
//"uuid" => $json_responseAPI->contact->uuid, //"uuid" => $json_responseAPI->contact->uuid,
"name" => sprintf("%s %s", $notificationData->clientData['firstName'], $notificationData->clientData['lastName']), "name" => sprintf("%s %s", $notificationData->clientData['firstName'], $notificationData->clientData['lastName']),
"custom_fields" => array( "custom_fields" => [
"Cliente" => $notificationData->clientData['id'], "Cliente" => $notificationData->clientData['id'],
"Domicilio" => ($notificationData->clientData['fullAddress'] == null) ? '📍❌ Sin domicilio' : '📍 ' . $notificationData->clientData['fullAddress'], "Domicilio" => ($notificationData->clientData['fullAddress'] == null) ? '📍❌ Sin domicilio' : '📍 ' . $notificationData->clientData['fullAddress'],
"Nombre" => sprintf("👤 %s %s", $notificationData->clientData['firstName'], $notificationData->clientData['lastName']), "Nombre" => sprintf("👤 %s %s", $notificationData->clientData['firstName'], $notificationData->clientData['lastName']),
"URL" => '🌐 https://sistema.siip.mx/crm/client/' . $notificationData->clientId, "URL" => '🌐 https://sistema.siip.mx/crm/client/' . $notificationData->clientId,
"Saldo Actual" => $saldoTexto, "Saldo Actual" => $saldoTexto,
"Monto Ultimo Pago" => '💲 ' . $payments[0]['amount'], "Monto Ultimo Pago" => '💲 ' . $payments[0]['amount'],
"Estado" => ($notificationData->clientData['hasSuspendedService']) ? '🔴 Suspendido' : '🟢 Activo ', "Estado" => ($notificationData->clientData['hasSuspendedService']) ? '🔴 Suspendido' : '🟢 Activo ',
"Resumen" => $resumenClienteJSON, "Resumen" => $resumenClienteJSON,
"Fecha Ultimo Pago" => '📆💸 ' . $fecha_ultimoPago_ajustada . ' con ' . $payment_method, "Fecha Ultimo Pago" => '📆💸 ' . $fecha_ultimoPago_ajustada . ' con ' . $payment_method,
"Fecha Ultima Actualizacion" => '📆🔄️ ' . $fecha_actual_ajustada, "Fecha Ultima Actualizacion" => '📆🔄️ ' . $fecha_actual_ajustada,
"Clabe Interbancaria" => $clabeInterbancaria, "Clabe Interbancaria" => $clabeInterbancaria,
"Site" => $site, "Site" => $site,
"Antena/Sectorial" => $antenaSectorial "Antena/Sectorial" => $antenaSectorial,
) ],
); ];
$log->appendLog("JSON con los datos a actualizar: " . json_encode($data_CRM) . PHP_EOL); $log->appendLog("JSON con los datos a actualizar: " . json_encode($data_CRM) . PHP_EOL);
$data_CRM2 = [
$data_CRM2 = array( "custom_fields" => [
"custom_fields" => array(
"Resumen" => $resumenClienteJSON, "Resumen" => $resumenClienteJSON,
) ],
); ];
$log->appendLog("JSON con los datos a actualizar del resumen: " . $resumenClienteJSON . PHP_EOL); $log->appendLog("JSON con los datos a actualizar del resumen: " . $resumenClienteJSON . PHP_EOL);
@ -1096,7 +1040,6 @@ class ClientCallBellAPI
// $this->deleteFileWordPressAndLocal($fileNameComprobante); // $this->deleteFileWordPressAndLocal($fileNameComprobante);
// } // }
// $json_data_patch = '{ // $json_data_patch = '{
// "attributes": [ // "attributes": [
// { // {
@ -1118,7 +1061,6 @@ class ClientCallBellAPI
// 'verify' => false, // 'verify' => false,
// ]); //aquí se contruye la petición para hacer patch hacia el cliente en sus custom fields con la API del UISP UCRM // ]); //aquí se contruye la petición para hacer patch hacia el cliente en sus custom fields con la API del UISP UCRM
// } catch (GuzzleException $error) { // } catch (GuzzleException $error) {
// echo "Error al hacer el patch al CRM: " . $error->getMessage() . PHP_EOL; // echo "Error al hacer el patch al CRM: " . $error->getMessage() . PHP_EOL;
// //exit(); // //exit();
@ -1130,19 +1072,15 @@ class ClientCallBellAPI
} }
} }
public function patchServiceStatusWhatsApp($response_getContactCallBell, $notificationData) public function patchServiceStatusWhatsApp($response_getContactCallBell, $notificationData)
{ {
$log = PluginLogManager::create(); //Initialize Logger $log = PluginLogManager::create(); //Initialize Logger
$log->appendLog("Actualizando estado del servicio " . PHP_EOL); $log->appendLog("Actualizando estado del servicio " . PHP_EOL);
$uuid = $response_getContactCallBell['contact']['uuid']; $uuid = $response_getContactCallBell['contact']['uuid'];
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
curl_setopt($ch, CURLOPT_HTTPHEADER, [ curl_setopt($ch, CURLOPT_HTTPHEADER, [
@ -1155,30 +1093,23 @@ class ClientCallBellAPI
$log->appendLog("Nombre del cliente al que se va a actualizar el estado del servicio: " . $nombre_cliente . PHP_EOL); $log->appendLog("Nombre del cliente al que se va a actualizar el estado del servicio: " . $nombre_cliente . PHP_EOL);
$log->appendLog("UUID: " . $uuid . PHP_EOL); $log->appendLog("UUID: " . $uuid . PHP_EOL);
$fecha_actual = new DateTime(); $fecha_actual = new DateTime();
$fecha_actual->modify('-6 hours'); $fecha_actual->modify('-6 hours');
$fecha_actual_ajustada = $fecha_actual->format("d/m/Y H:i"); $fecha_actual_ajustada = $fecha_actual->format("d/m/Y H:i");
$data_CRM = [
"name" => $nombre_cliente,
$data_CRM = array( "custom_fields" => [
"name" => $nombre_cliente, "Estado" => (
"custom_fields" => array(
"Estado" => (
isset($notificationData->serviceData['status']) isset($notificationData->serviceData['status'])
&& $notificationData->serviceData['status'] == 3 && $notificationData->serviceData['status'] == 3
) ? '🟠 Suspendido' : ( ) ? '🟠 Suspendido' : (
(isset($notificationData->serviceData['status']) (isset($notificationData->serviceData['status'])
&& $notificationData->serviceData['status'] == 1) && $notificationData->serviceData['status'] == 1)
? '🟢 Activo' : '🚫 Finalizado'), ? '🟢 Activo' : '🚫 Finalizado'),
"Fecha Ultima Actualizacion" => '📆🔄️ ' . $fecha_actual_ajustada "Fecha Ultima Actualizacion" => '📆🔄️ ' . $fecha_actual_ajustada,
) ],
); ];
$log->appendLog("JSON con los datos a actualizar: " . json_encode($data_CRM) . PHP_EOL); $log->appendLog("JSON con los datos a actualizar: " . json_encode($data_CRM) . PHP_EOL);
@ -1187,8 +1118,6 @@ class ClientCallBellAPI
$response = curl_exec($ch); $response = curl_exec($ch);
$log->appendLog("Response Patch CallBell: " . $response . PHP_EOL); $log->appendLog("Response Patch CallBell: " . $response . PHP_EOL);
curl_close($ch); curl_close($ch);
} else { } else {
$log->appendLog("No hay cambios en el estado del servicio que actualizar " . PHP_EOL); $log->appendLog("No hay cambios en el estado del servicio que actualizar " . PHP_EOL);
} }
@ -1197,14 +1126,14 @@ class ClientCallBellAPI
function UploadReceiptToWordpressByImageFileName($imageFileName): string function UploadReceiptToWordpressByImageFileName($imageFileName): string
{ {
$log = PluginLogManager::create(); //Initialize Logger $log = PluginLogManager::create(); //Initialize Logger
$configManager = PluginConfigManager::create(); $configManager = PluginConfigManager::create();
$config = $configManager->loadConfig(); $config = $configManager->loadConfig();
// Configuración de conexión FTP // Configuración de conexión FTP
$ftp_server = $config['hostServerFTP']; $ftp_server = $config['hostServerFTP'];
$ftp_username = $config['usernameServerFTP']; $ftp_username = $config['usernameServerFTP'];
$ftp_password = $config['passServerFTP']; $ftp_password = $config['passServerFTP'];
$remote_folder = "/public_html/wp/wp-content/uploads/img/"; $remote_folder = "/public_html/wp/wp-content/uploads/img/";
$log->appendLog("Subiendo comprobante a worpdpress " . PHP_EOL); $log->appendLog("Subiendo comprobante a worpdpress " . PHP_EOL);
@ -1212,16 +1141,15 @@ class ClientCallBellAPI
// $ftp_server = "siip.mx"; // $ftp_server = "siip.mx";
// $ftp_username = "siip0001"; // $ftp_username = "siip0001";
// $ftp_password = '$spGiT,[wa)n'; // $ftp_password = '$spGiT,[wa)n';
$remote_file = "/public_html/wp/wp-content/uploads/img/" . $imageFileName; $remote_file = "/public_html/wp/wp-content/uploads/img/" . $imageFileName;
$file_to_upload = __DIR__ . '/../../comprobantes/' . $imageFileName; $file_to_upload = __DIR__ . '/../../comprobantes/' . $imageFileName;
$url = 'https://siip.mx/wp/wp-content/uploads/img/' . $imageFileName; $url = 'https://siip.mx/wp/wp-content/uploads/img/' . $imageFileName;
$log->appendLog("file_to_upload: " . $file_to_upload . PHP_EOL); $log->appendLog("file_to_upload: " . $file_to_upload . PHP_EOL);
// Conexión FTP // Conexión FTP
$ftp_conn = ftp_connect($ftp_server) or die("No se pudo conectar al servidor FTP"); $ftp_conn = ftp_connect($ftp_server) or die("No se pudo conectar al servidor FTP");
$login = ftp_login($ftp_conn, $ftp_username, $ftp_password); $login = ftp_login($ftp_conn, $ftp_username, $ftp_password);
ftp_pasv($ftp_conn, true); ftp_pasv($ftp_conn, true);
// Verificar conexión y login // Verificar conexión y login
if ($ftp_conn && $login) { if ($ftp_conn && $login) {
@ -1232,10 +1160,10 @@ class ClientCallBellAPI
$log->appendLog("El archivo ha sido cargado exitosamente." . PHP_EOL); $log->appendLog("El archivo ha sido cargado exitosamente." . PHP_EOL);
$log->appendLog("La URL es: " . $url . PHP_EOL); $log->appendLog("La URL es: " . $url . PHP_EOL);
$this->deleteFilesWordpressExceptLastHundred($log,$ftp_conn,$remote_file); $this->deleteFilesWordpressExceptLastHundred($log, $ftp_conn, $remote_file);
// Cerrar conexión FTP // Cerrar conexión FTP
ftp_close($ftp_conn);//COMENTAR AQUÍ SI SE BORRAN LOS ARCHIVOS DE WORDPRESS DESCOMENTANDO EL CÓDIGO DE MÁS ABAJO ftp_close($ftp_conn); //COMENTAR AQUÍ SI SE BORRAN LOS ARCHIVOS DE WORDPRESS DESCOMENTANDO EL CÓDIGO DE MÁS ABAJO
return $url;//COMENTAR AQUÍ SI SE BORRAN LOS ARCHIVOS DE WORDPRESS DESCOMENTANDO EL CÓDIGO DE MÁS ABAJO return $url; //COMENTAR AQUÍ SI SE BORRAN LOS ARCHIVOS DE WORDPRESS DESCOMENTANDO EL CÓDIGO DE MÁS ABAJO
} else { } else {
$log->appendLog("Error al cargar el archivo " . PHP_EOL); $log->appendLog("Error al cargar el archivo " . PHP_EOL);
@ -1285,15 +1213,12 @@ class ClientCallBellAPI
// return $url; // return $url;
// } // }
} else { } else {
$log->appendLog("No se pudo conectar o iniciar sesión en el servidor FTP." . PHP_EOL); $log->appendLog("No se pudo conectar o iniciar sesión en el servidor FTP." . PHP_EOL);
return ''; return '';
} }
} }
function deleteFilesWordpressExceptLastHundred($log, $ftp_conn, $remote_folder): bool function deleteFilesWordpressExceptLastHundred($log, $ftp_conn, $remote_folder): bool
{ {
@ -1336,23 +1261,20 @@ class ClientCallBellAPI
ftp_close($ftp_conn); ftp_close($ftp_conn);
return false; return false;
} }
} }
/** /**
* /Elimina los archivos del directorio de comprobantes de pago a excepción de los últimos 100 para evitar errores de envío * /Elimina los archivos del directorio de comprobantes de pago a excepción de los últimos 100 para evitar errores de envío
* @return void * @return void
*/ */
function deleteFilesExceptLastHundred() function deleteFilesExceptLastHundred()
{ {
$log = PluginLogManager::create(); //Initialize Logger $log = PluginLogManager::create(); //Initialize Logger
$directory = __DIR__ . '/../../comprobantes/'; $directory = __DIR__ . '/../../comprobantes/';
// Verificar si el directorio existe // Verificar si el directorio existe
if (!is_dir($directory)) { if (! is_dir($directory)) {
$log->appendLog('El directorio no existe.'); $log->appendLog('El directorio no existe.');
die("El directorio no existe."); die("El directorio no existe.");
} }
// Obtener la lista de archivos en el directorio // Obtener la lista de archivos en el directorio
@ -1379,5 +1301,4 @@ class ClientCallBellAPI
$log->appendLog("Hay menos de 100 archivos en el directorio. No se eliminarán archivos." . PHP_EOL); $log->appendLog("Hay menos de 100 archivos en el directorio. No se eliminarán archivos." . PHP_EOL);
} }
} }
} }

View File

@ -1,14 +1,13 @@
<?php <?php
declare(strict_types=1); declare (strict_types = 1);
namespace SmsNotifier; namespace SmsNotifier;
use Psr\Log\LogLevel; use Psr\Log\LogLevel;
use SmsNotifier\Facade\TwilioNotifierFacade;
use SmsNotifier\Facade\PluginNotifierFacade; use SmsNotifier\Facade\PluginNotifierFacade;
use SmsNotifier\Facade\PluginOxxoNotifierFacade; use SmsNotifier\Facade\PluginOxxoNotifierFacade;
use SmsNotifier\Facade\TwilioNotifierFacade;
use SmsNotifier\Factory\NotificationDataFactory; use SmsNotifier\Factory\NotificationDataFactory;
use SmsNotifier\Service\Logger; use SmsNotifier\Service\Logger;
use SmsNotifier\Service\OptionsManager; use SmsNotifier\Service\OptionsManager;
@ -56,7 +55,6 @@ class Plugin
*/ */
protected $ucrmApi; protected $ucrmApi;
public function __construct( public function __construct(
Logger $logger, Logger $logger,
OptionsManager $optionsManager, OptionsManager $optionsManager,
@ -66,13 +64,13 @@ class Plugin
PluginOxxoNotifierFacade $pluginOxxoNotifierFacade, PluginOxxoNotifierFacade $pluginOxxoNotifierFacade,
NotificationDataFactory $notificationDataFactory NotificationDataFactory $notificationDataFactory
) { ) {
$this->logger = $logger; $this->logger = $logger;
$this->optionsManager = $optionsManager; $this->optionsManager = $optionsManager;
$this->pluginDataValidator = $pluginDataValidator; $this->pluginDataValidator = $pluginDataValidator;
$this->notifierFacade = $notifierFacade; $this->notifierFacade = $notifierFacade;
$this->pluginNotifierFacade = $pluginNotifierFacade; $this->pluginNotifierFacade = $pluginNotifierFacade;
$this->pluginOxxoNotifierFacade = $pluginOxxoNotifierFacade; $this->pluginOxxoNotifierFacade = $pluginOxxoNotifierFacade;
$this->notificationDataFactory = $notificationDataFactory; $this->notificationDataFactory = $notificationDataFactory;
} }
public function run(): void public function run(): void
@ -108,23 +106,19 @@ class Plugin
$this->logger->setLogLevelThreshold(LogLevel::DEBUG); $this->logger->setLogLevelThreshold(LogLevel::DEBUG);
} }
$userInput = file_get_contents('php://input'); //se recibe el json del webhook $userInput = file_get_contents('php://input'); //se recibe el json del webhook
//imprimir el json del webhook //imprimir el json del webhook
$this->logger->debug('valor del webhook: ' . $userInput . PHP_EOL); $this->logger->debug('valor del webhook: ' . $userInput . PHP_EOL);
if (! $userInput) {
if (!$userInput) {
$this->logger->warning('no input'); $this->logger->warning('no input');
return; return;
} }
$jsonData = @json_decode($userInput, true, 50); $jsonData = @json_decode($userInput, true, 50);
if (!isset($jsonData['uuid'])) { if (! isset($jsonData['uuid'])) {
$this->logger->info('No UUID found in the webhook data'); $this->logger->info('No UUID found in the webhook data');
//$this->logger->error('JSON error: ' . json_last_error_msg()); //$this->logger->error('JSON error: ' . json_last_error_msg());
@ -134,20 +128,20 @@ class Plugin
if ($jsonData) { if ($jsonData) {
switch ($jsonData['type']) { switch ($jsonData['type']) {
case 'customer_cash_balance_transaction.created': case 'customer_cash_balance_transaction.created':
$this->logger->info('Evento de transfencia al cliente encontrado: '. json_encode($jsonData) . PHP_EOL); $this->logger->info('Evento de transfencia al cliente encontrado: ' . json_encode($jsonData) . PHP_EOL);
if ($jsonData['data']['object']['type'] === 'funded') { if ($jsonData['data']['object']['type'] === 'funded') {
$this->pluginNotifierFacade->createPaymentIntent($jsonData); $this->pluginNotifierFacade->createPaymentIntent($jsonData);
} }
break; break;
case 'payout.failed': case 'payout.failed':
$this->logger->info('Evento de transferencia fallida encontrado: '. json_encode($jsonData) . PHP_EOL); $this->logger->info('Evento de transferencia fallida encontrado: ' . json_encode($jsonData) . PHP_EOL);
//imprimir detalles del fallo //imprimir detalles del fallo
$this->logger->info('Detalles del fallo: ' . json_encode($jsonData )); $this->logger->info('Detalles del fallo: ' . json_encode($jsonData));
break; break;
case 'payment_intent.partially_funded': case 'payment_intent.partially_funded':
$this->logger->info('Evento de pago parcialmente financiado encontrado: '. json_encode($jsonData) . PHP_EOL); $this->logger->info('Evento de pago parcialmente financiado encontrado: ' . json_encode($jsonData) . PHP_EOL);
//imprimir detalles del evento o pago //imprimir detalles del evento o pago
$this->logger->info('Detalles del evento: ' . json_encode($jsonData )); $this->logger->info('Detalles del evento: ' . json_encode($jsonData));
break; break;
case 'inbound_payment.payment_attempt': case 'inbound_payment.payment_attempt':
//$this->logger->info('Evento de Pago de OXXO recibido: '. json_encode($jsonData) . PHP_EOL); //$this->logger->info('Evento de Pago de OXXO recibido: '. json_encode($jsonData) . PHP_EOL);
@ -158,10 +152,9 @@ class Plugin
case 'oxxo.request': case 'oxxo.request':
$this->logger->info('Evento de solicitud de referencia de oxxo recibido' . PHP_EOL); $this->logger->info('Evento de solicitud de referencia de oxxo recibido' . PHP_EOL);
// Construir la URL basada en el "client_id" // Construir la URL basada en el "client_id"
// $url = "https://siip.mx/wp/wp-content/uploads/img/voucher.png"; // $url = "https://siip.mx/wp/wp-content/uploads/img/voucher.png";
if (!empty($jsonData['amount'])) { if (! empty($jsonData['amount'])) {
$this->logger->info('Referencia persnoalizada, Valor del monto: ' . $jsonData['amount'] . PHP_EOL); $this->logger->info('Referencia persnoalizada, Valor del monto: ' . $jsonData['amount'] . PHP_EOL);
$intentos = 0; $intentos = 0;
do { do {
@ -236,11 +229,6 @@ class Plugin
// $webhook_string = json_encode($event_json); // $webhook_string = json_encode($event_json);
// $this->logger->debug("El valor de webhook_string: " . $webhook_string . PHP_EOL); // $this->logger->debug("El valor de webhook_string: " . $webhook_string . PHP_EOL);
$notification = $this->notificationDataFactory->getObject($jsonData); $notification = $this->notificationDataFactory->getObject($jsonData);
$this->logger->debug('valor el evento recibido por webhook: ' . $notification->eventName . PHP_EOL); $this->logger->debug('valor el evento recibido por webhook: ' . $notification->eventName . PHP_EOL);
$this->logger->debug('Valor de JSON: ' . json_encode($jsonData) . PHP_EOL); $this->logger->debug('Valor de JSON: ' . json_encode($jsonData) . PHP_EOL);
@ -248,14 +236,14 @@ class Plugin
if ($notification->changeType === 'test') { if ($notification->changeType === 'test') {
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create(); $configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
$config = $configManager->loadConfig(); $config = $configManager->loadConfig();
$this->logger->info('Webhook test successful.'); $this->logger->info('Webhook test successful.');
return; return;
} else if($notification->changeType === 'paperless.update') { } else if ($notification->changeType === 'paperless.update') {
//imprimir el webhook json //imprimir el webhook json
$this->logger->info( 'Webhook de paperless update: ' . json_encode($jsonData) . PHP_EOL); $this->logger->info('Webhook de paperless update: ' . json_encode($jsonData) . PHP_EOL);
} }
// if (!$notification->clientId) { // if (!$notification->clientId) {
// $this->logger->warning('No client specified, cannot notify them.'); // $this->logger->warning('No client specified, cannot notify them.');
@ -264,7 +252,7 @@ class Plugin
// } // }
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create(); $configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
$config = $configManager->loadConfig(); $config = $configManager->loadConfig();
// the "exportFormat" key must be defined in plugin's manifest file, see the link above // the "exportFormat" key must be defined in plugin's manifest file, see the link above
try { try {
@ -279,11 +267,8 @@ class Plugin
$payment_method_id = $notification->paymentData['methodId']; $payment_method_id = $notification->paymentData['methodId'];
//$this->logger->debug('Metodo de pago: ' . $notification->paymentData['methodId'] . PHP_EOL); //$this->logger->debug('Metodo de pago: ' . $notification->paymentData['methodId'] . PHP_EOL);
$payment_method = ''; $payment_method = '';
switch ($payment_method_id) { switch ($payment_method_id) {
case '11721cdf-a498-48be-903e-daa67552e4f6': case '11721cdf-a498-48be-903e-daa67552e4f6':
@ -356,23 +341,71 @@ class Plugin
$payment_method = 'Desconocido, revisar metodos de pago no contemplados'; $payment_method = 'Desconocido, revisar metodos de pago no contemplados';
break; break;
} }
} else if ($notification->eventName === 'client.edit') { } else if ($notification->eventName === 'client.edit') {
$this->logger->debug('Se actualiza a un cliente'); $this->logger->debug('Se actualiza a un cliente');
$this->logger->debug('Valor de json_data: ' . json_encode($jsonData)); $this->logger->debug('Valor de json_data: ' . json_encode($jsonData));
//ejemplo de json_data: {"uuid":"17e043a7-03b5-4312-ab81-a7818124a77e","changeType":"edit","entity":"client","entityId":"158","eventName":"client.edit","extraData":{"entity":{"id":158,"userIdent":null,"previousIsp":null,"isLead":false,"clientType":1,"companyName":null,"companyRegistrationNumber":null,"companyTaxId":null,"companyWebsite":null,"street1":"23 San Luis","street2":null,"city":"Dolores Hidalgo Cuna de la Independencia Nacional","countryId":173,"stateId":null,"zipCode":"37804","fullAddress":"San Luis 23, Guadalupe, Dolores Hidalgo Cuna de la Independencia Nacional, Gto., M\u00e9xico","invoiceStreet1":null,"invoiceStreet2":null,"invoiceCity":null,"invoiceStateId":null,"invoiceCountryId":null,"invoiceZipCode":null,"invoiceAddressSameAsContact":true,"note":null,"sendInvoiceByPost":null,"invoiceMaturityDays":null,"stopServiceDue":null,"stopServiceDueDays":null,"organizationId":1,"tax1Id":null,"tax2Id":null,"tax3Id":null,"registrationDate":"2025-01-06T00:00:00-0600","leadConvertedAt":"2025-02-09T03:15:49-0600","companyContactFirstName":null,"companyContactLastName":null,"isActive":false,"firstName":"Luis","lastName":"Guti\u00e9rrez","username":null,"contacts":[{"id":162,"clientId":158,"email":null,"phone":null,"name":null,"isBilling":true,"isContact":true,"types":[{"id":1,"name":"Billing"},{"id":2,"name":"General"}]}],"attributes":[],"accountBalance":0,"accountCredit":0,"accountOutstanding":0,"currencyCode":"MXN","organizationName":"SIIP Pruebas","bankAccounts":[],"tags":[],"invitationEmailSentDate":null,"avatarColor":"#2196f3","addressGpsLat":21.153272,"addressGpsLon":-100.9134508,"isArchived":false,"generateProformaInvoices":null,"usesProforma":false,"hasOverdueInvoice":false,"hasOutage":false,"hasSuspendedService":false,"hasServiceWithoutDevices":false,"referral":null,"hasPaymentSubscription":false,"hasAutopayCreditCard":false},"entityBeforeEdit":{"id":158,"userIdent":null,"previousIsp":null,"isLead":true,"clientType":1,"companyName":null,"companyRegistrationNumber":null,"companyTaxId":null,"companyWebsite":null,"street1":"23 San Luis","street2":null,"city":"Dolores Hidalgo Cuna de la Independencia Nacional","countryId":173,"stateId":null,"zipCode":"37804","fullAddress":"San Luis 23, Guadalupe, Dolores Hidalgo Cuna de la Independencia Nacional, Gto., M\u00e9xico","invoiceStreet1":null,"invoiceStreet2":null,"invoiceCity":null,"invoiceStateId":null,"invoiceCountryId":null,"invoiceZipCode":null,"invoiceAddressSameAsContact":true,"note":null,"sendInvoiceByPost":null,"invoiceMaturityDays":null,"stopServiceDue":null,"stopServiceDueDays":null,"organizationId":1,"tax1Id":null,"tax2Id":null,"tax3Id":null,"registrationDate":"2025-01-06T00:00:00-0600","leadConvertedAt":null,"companyContactFirstName":null,"companyContactLastName":null,"isActive":false,"firstName":"Luis","lastName":"Guti\u00e9rrez","username":null,"contacts":[{"id":162,"clientId":158,"email":null,"phone":null,"name":null,"isBilling":true,"isContact":true,"types":[{"id":1,"name":"Billing"},{"id":2,"name":"General"}]}],"attributes":[],"accountBalance":0,"accountCredit":0,"accountOutstanding":0,"currencyCode":"MXN","organizationName":"SIIP Pruebas","bankAccounts":[],"tags":[],"invitationEmailSentDate":null,"avatarColor":"#2196f3","addressGpsLat":21.153272,"addressGpsLon":-100.9134508,"isArchived":false,"generateProformaInvoices":null,"usesProforma":false,"hasOverdueInvoice":false,"hasOutage":false,"hasSuspendedService":false,"hasServiceWithoutDevices":false,"referral":null,"hasPaymentSubscription":false,"hasAutopayCreditCard":false}}} //ejemplo de json_data: {"uuid":"aacaf5c5-2bf4-44ea-864f-a24121b453bb","changeType":"edit","entity":"client","entityId":"171","eventName":"client.edit","extraData":{"entity":{"id":171,"userIdent":null,"previousIsp":null,"isLead":false,"clientType":1,"companyName":null,"companyRegistrationNumber":null,"companyTaxId":null,"companyWebsite":null,"street1":"Campeche 56","street2":null,"city":"Dolores Hidalgo","countryId":173,"stateId":null,"zipCode":"37800","fullAddress":"Campeche 56, Dolores Hidalgo, 37800","invoiceStreet1":null,"invoiceStreet2":null,"invoiceCity":null,"invoiceStateId":null,"invoiceCountryId":null,"invoiceZipCode":null,"invoiceAddressSameAsContact":true,"note":null,"sendInvoiceByPost":null,"invoiceMaturityDays":null,"stopServiceDue":null,"stopServiceDueDays":null,"organizationId":1,"tax1Id":null,"tax2Id":null,"tax3Id":null,"registrationDate":"2025-05-21T00:00:00-0600","leadConvertedAt":null,"companyContactFirstName":null,"companyContactLastName":null,"isActive":false,"firstName":"Archi","lastName":"Isalas","username":"mainstreamm2@gmail.com","contacts":[{"id":177,"clientId":171,"email":"mainstreamm2@gmail.com","phone":"4181878106","name":null,"isBilling":false,"isContact":false,"types":[]}],"attributes":[{"id":198,"clientId":171,"customAttributeId":10,"name":"Stripe Customer ID","key":"stripeCustomerId","value":"cus_SM2zH6IsjTz6ol","clientZoneVisible":true},{"id":199,"clientId":171,"customAttributeId":11,"name":"Clabe Interbancaria","key":"clabeInterbancaria","value":"124180950530868794","clientZoneVisible":true}],"accountBalance":0,"accountCredit":0,"accountOutstanding":0,"currencyCode":"MXN","organizationName":"SIIP Pruebas","bankAccounts":[],"tags":[],"invitationEmailSentDate":null,"avatarColor":"#f1df43","addressGpsLat":21.1572461,"addressGpsLon":-100.9377137,"isArchived":false,"generateProformaInvoices":null,"usesProforma":false,"hasOverdueInvoice":false,"hasOutage":false,"hasSuspendedService":false,"hasServiceWithoutDevices":true,"referral":null,"hasPaymentSubscription":false,"hasAutopayCreditCard":false},"entityBeforeEdit":{"id":171,"userIdent":null,"previousIsp":null,"isLead":false,"clientType":1,"companyName":null,"companyRegistrationNumber":null,"companyTaxId":null,"companyWebsite":null,"street1":"Campeche 56","street2":null,"city":"Dolores Hidalgo","countryId":173,"stateId":null,"zipCode":"37800","fullAddress":"Campeche 56, Dolores Hidalgo, 37800","invoiceStreet1":null,"invoiceStreet2":null,"invoiceCity":null,"invoiceStateId":null,"invoiceCountryId":null,"invoiceZipCode":null,"invoiceAddressSameAsContact":true,"note":null,"sendInvoiceByPost":null,"invoiceMaturityDays":null,"stopServiceDue":null,"stopServiceDueDays":null,"organizationId":1,"tax1Id":null,"tax2Id":null,"tax3Id":null,"registrationDate":"2025-05-21T00:00:00-0600","leadConvertedAt":null,"companyContactFirstName":null,"companyContactLastName":null,"isActive":false,"firstName":"Archi","lastName":"Isalas","username":"mainstreamm2@gmail.com","contacts":[{"id":177,"clientId":171,"email":"mainstreamm2@gmail.com","phone":"4181878106","name":null,"isBilling":false,"isContact":false,"types":[{"id":1003,"name":"WhatsNotifica"}]}],"attributes":[{"id":198,"clientId":171,"customAttributeId":10,"name":"Stripe Customer ID","key":"stripeCustomerId","value":"cus_SM2zH6IsjTz6ol","clientZoneVisible":true},{"id":199,"clientId":171,"customAttributeId":11,"name":"Clabe Interbancaria","key":"clabeInterbancaria","value":"124180950530868794","clientZoneVisible":true}],"accountBalance":0,"accountCredit":0,"accountOutstanding":0,"currencyCode":"MXN","organizationName":"SIIP Pruebas","bankAccounts":[],"tags":[],"invitationEmailSentDate":null,"avatarColor":"#f1df43","addressGpsLat":21.1572461,"addressGpsLon":-100.9377137,"isArchived":false,"generateProformaInvoices":null,"usesProforma":false,"hasOverdueInvoice":false,"hasOutage":false,"hasSuspendedService":false,"hasServiceWithoutDevices":true,"referral":null,"hasPaymentSubscription":false,"hasAutopayCreditCard":false}}}
$clientID = $jsonData['entityId'];
$this->ucrmApi = UcrmApi::create();
$customAttributes = $this->ucrmApi->get('custom-attributes/', ['attributeType' => 'client']); //Obtener los atributos del sistema que estén vinculados a la entidad "cliente"
//$this->logger->info("result del custom Attributes: " . json_encode($customAttributes) . PHP_EOL);
$idPasswordAntenaCliente = null;
$passwordAntenaValue = null;
//ejemplo de $customAttributes: [{"id":1,"name":"ip","key":"ip","attributeType":"client","type":"string","clientZoneVisible":false},{"id":2,"name":"ubntpass","key":"ubntpass","attributeType":"client","type":"string","clientZoneVisible":false},{"id":3,"name":"adminpass","key":"adminpass","attributeType":"client","type":"string","clientZoneVisible":true},{"id":4,"name":"ssid","key":"ssid","attributeType":"client","type":"string","clientZoneVisible":true},{"id":5,"name":"clavessid","key":"clavessid","attributeType":"client","type":"string","clientZoneVisible":true},{"id":6,"name":"clave","key":"clave","attributeType":"client","type":"string","clientZoneVisible":true},{"id":11,"name":"latitud","key":"latitud","attributeType":"client","type":"string","clientZoneVisible":true},{"id":12,"name":"longitud","key":"longitud","attributeType":"client","type":"string","clientZoneVisible":true},{"id":16,"name":"instalador","key":"instalador","attributeType":"client","type":"string","clientZoneVisible":true},{"id":17,"name":"creado por","key":"creadoPor","attributeType":"client","type":"string","clientZoneVisible":true},{"id":21,"name":"Chat de CallBell","key":"chatDeCallbell","attributeType":"client","type":"string","clientZoneVisible":false},{"id":22,"name":"uuid","key":"uuid","attributeType":"client","type":"string","clientZoneVisible":false},{"id":23,"name":"zona","key":"zona","attributeType":"client","type":"enum","clientZoneVisible":true},{"id":29,"name":"Stripe Customer ID","key":"stripeCustomerId","attributeType":"client","type":"string","clientZoneVisible":true},{"id":30,"name":"Clabe Interbancaria","key":"clabeInterbancaria","attributeType":"client","type":"string","clientZoneVisible":true},{"id":31,"name":"RUTA DE COBRANZA","key":"rutaDeCobranza","attributeType":"client","type":"enum","clientZoneVisible":true},{"id":35,"name":"Site","key":"site","attributeType":"client","type":"string","clientZoneVisible":true},{"id":36,"name":"Antena/Sectorial","key":"antenaSectorial","attributeType":"client","type":"string","clientZoneVisible":true},{"id":37,"name":"Password Antena Cliente","key":"passwordAntenaCliente","attributeType":"client","type":"string","clientZoneVisible":false}]
// Verificar si se obtuvieron los atributos
if ($customAttributes && is_array($customAttributes)) {
foreach ($customAttributes as $attribute) {
// Verificar si 'name' contiene la palabra 'passwordAntenaCliente' sin distinguir mayúsculas y minúsculas
if (isset($attribute['key']) && stripos($attribute['key'], 'passwordAntenaCliente') !== false) {
$this->logger->info("ID correspondiente a 'passwordAntenaCliente': " . $attribute['id'] . PHP_EOL);
$idPasswordAntenaCliente = $attribute['id'];
}
}
} else {
$this->logger->info("Error al obtener los atributos personalizados." . PHP_EOL);
}
//buscar en los attributes ($jsonData) del cliente el id del atributo personalizado 'passwordAntenaCliente' si no está o si está pero está en blanco se manda llamar la función $this->notifierFacade->getVaultCredentials($clientID);
foreach ($jsonData['extraData']['entity']['attributes'] as $attribute) {
if ($attribute['customAttributeId'] === $idPasswordAntenaCliente) {
$this->logger->info("El valor de passwordAntenaValue es: " . $attribute['value'] . PHP_EOL);
$passwordAntenaValue = $attribute['value'];
}
}
//si el value de passwordAntenaValue es igual a null o cadena vacía se manda llamar la función $this->notifierFacade->getVaultCredentials($clientID);
if ($passwordAntenaValue === null || $passwordAntenaValue === '') {
$password = $this->notifierFacade->getVaultCredentials($clientID);
$this->logger->info("El valor de passwordAntenaValue es null o cadena vacía, se manda llamar la función getVaultCredentials" . PHP_EOL);
$this->logger->info("El valor de password es: " . $password . PHP_EOL);
if ($this->notifierFacade->patchClientCustomAttribute($clientID, $idPasswordAntenaCliente, $password)) {
$this->logger->info("Se actualizó el atributo personalizado passwordAntenaCliente con el valor: " . $password . PHP_EOL);
} else {
$this->logger->info("No se pudo actualizar el atributo personalizado passwordAntenaCliente" . PHP_EOL);
}
} else {
$this->logger->info("Ya existe un valor de passwordAntenaValue: " . $passwordAntenaValue . PHP_EOL);
}
//ejemplo de json_data: {"uuid":"17e043a7-03b5-4312-ab81-a7818124a77e","changeType":"edit","entity":"client","entityId":"158","eventName":"client.edit","extraData":{"entity":{"id":158,"userIdent":null,"previousIsp":null,"isLead":false,"clientType":1,"companyName":null,"companyRegistrationNumber":null,"companyTaxId":null,"companyWebsite":null,"street1":"23 San Luis","street2":null,"city":"Dolores Hidalgo Cuna de la Independencia Nacional","countryId":173,"stateId":null,"zipCode":"37804","fullAddress":"San Luis 23, Guadalupe, Dolores Hidalgo Cuna de la Independencia Nacional, Gto., M\u00e9xico","invoiceStreet1":null,"invoiceStreet2":null,"invoiceCity":null,"invoiceStateId":null,"invoiceCountryId":null,"invoiceZipCode":null,"invoiceAddressSameAsContact":true,"note":null,"sendInvoiceByPost":null,"invoiceMaturityDays":null,"stopServiceDue":null,"stopServiceDueDays":null,"organizationId":1,"tax1Id":null,"tax2Id":null,"tax3Id":null,"registrationDate":"2025-01-06T00:00:00-0600","leadConvertedAt":"2025-02-09T03:15:49-0600","companyContactFirstName":null,"companyContactLastName":null,"isActive":false,"firstName":"Luis","lastName":"Guti\u00e9rrez","username":null,"contacts":[{"id":162,"clientId":158,"email":null,"phone":null,"name":null,"isBilling":true,"isContact":true,"types":[{"id":1,"name":"Billing"},{"id":2,"name":"General"}]}],"attributes":[],"accountBalance":0,"accountCredit":0,"accountOutstanding":0,"currencyCode":"MXN","organizationName":"SIIP Pruebas","bankAccounts":[],"tags":[],"invitationEmailSentDate":null,"avatarColor":"#2196f3","addressGpsLat":21.153272,"addressGpsLon":-100.9134508,"isArchived":false,"generateProformaInvoices":null,"usesProforma":false,"hasOverdueInvoice":false,"hasOutage":false,"hasSuspendedService":false,"hasServiceWithoutDevices":false,"referral":null,"hasPaymentSubscription":false,"hasAutopayCreditCard":false},"entityBeforeEdit":{"id":158,"userIdent":null,"previousIsp":null,"isLead":true,"clientType":1,"companyName":null,"companyRegistrationNumber":null,"companyTaxId":null,"companyWebsite":null,"street1":"23 San Luis","street2":null,"city":"Dolores Hidalgo Cuna de la Independencia Nacional","countryId":173,"stateId":null,"zipCode":"37804","fullAddress":"San Luis 23, Guadalupe, Dolores Hidalgo Cuna de la Independencia Nacional, Gto., M\u00e9xico","invoiceStreet1":null,"invoiceStreet2":null,"invoiceCity":null,"invoiceStateId":null,"invoiceCountryId":null,"invoiceZipCode":null,"invoiceAddressSameAsContact":true,"note":null,"sendInvoiceByPost":null,"invoiceMaturityDays":null,"stopServiceDue":null,"stopServiceDueDays":null,"organizationId":1,"tax1Id":null,"tax2Id":null,"tax3Id":null,"registrationDate":"2025-01-06T00:00:00-0600","leadConvertedAt":null,"companyContactFirstName":null,"companyContactLastName":null,"isActive":false,"firstName":"Luis","lastName":"Guti\u00e9rrez","username":null,"contacts":[{"id":162,"clientId":158,"email":null,"phone":null,"name":null,"isBilling":true,"isContact":true,"types":[{"id":1,"name":"Billing"},{"id":2,"name":"General"}]}],"attributes":[],"accountBalance":0,"accountCredit":0,"accountOutstanding":0,"currencyCode":"MXN","organizationName":"SIIP Pruebas","bankAccounts":[],"tags":[],"invitationEmailSentDate":null,"avatarColor":"#2196f3","addressGpsLat":21.153272,"addressGpsLon":-100.9134508,"isArchived":false,"generateProformaInvoices":null,"usesProforma":false,"hasOverdueInvoice":false,"hasOutage":false,"hasSuspendedService":false,"hasServiceWithoutDevices":false,"referral":null,"hasPaymentSubscription":false,"hasAutopayCreditCard":false}}}
// Validar que 'extraData' existe y contiene las claves necesarias // Validar que 'extraData' existe y contiene las claves necesarias
if ( if (
isset($jsonData['extraData']['entityBeforeEdit']) && isset($jsonData['extraData']['entityBeforeEdit']) &&
isset($jsonData['extraData']['entity']) isset($jsonData['extraData']['entity'])
) { ) {
$entityBeforeEdit = $jsonData['extraData']['entityBeforeEdit']; $entityBeforeEdit = $jsonData['extraData']['entityBeforeEdit'];
$entity = $jsonData['extraData']['entity']; $entity = $jsonData['extraData']['entity'];
//$this->logger->debug('Validando claves dentro de entityBeforeEdit y entity'); //$this->logger->debug('Validando claves dentro de entityBeforeEdit y entity');
@ -381,7 +414,7 @@ class Plugin
//$this->logger->debug('Los datos entityBeforeEdit y entity contienen el campo isLead'); //$this->logger->debug('Los datos entityBeforeEdit y entity contienen el campo isLead');
$isLeadBefore = $entityBeforeEdit['isLead']; $isLeadBefore = $entityBeforeEdit['isLead'];
$isLeadAfter = $entity['isLead']; $isLeadAfter = $entity['isLead'];
// Comprobar si 'isLead' cambió de true a false // Comprobar si 'isLead' cambió de true a false
if ($isLeadBefore === true && $isLeadAfter === false) { if ($isLeadBefore === true && $isLeadAfter === false) {
@ -394,9 +427,8 @@ class Plugin
$this->logger->warning('El campo isLead no existe en entityBeforeEdit o entity'); $this->logger->warning('El campo isLead no existe en entityBeforeEdit o entity');
} }
// buscar si existe la etiqueta 'STRIPE' en entity pero no en entityBeforeEdit // buscar si existe la etiqueta 'STRIPE' en entity pero no en entityBeforeEdit
$tags = $jsonData['extraData']['entity']['tags']; $tags = $jsonData['extraData']['entity']['tags'];
$tagsBefore = $jsonData['extraData']['entityBeforeEdit']['tags']; $tagsBefore = $jsonData['extraData']['entityBeforeEdit']['tags'];
$this->logger->debug('Validando claves dentro de entity y entityBeforeEdit'); $this->logger->debug('Validando claves dentro de entity y entityBeforeEdit');
@ -405,13 +437,13 @@ class Plugin
if (array_key_exists('tags', $jsonData['extraData']['entity']) && array_key_exists('tags', $jsonData['extraData']['entityBeforeEdit'])) { if (array_key_exists('tags', $jsonData['extraData']['entity']) && array_key_exists('tags', $jsonData['extraData']['entityBeforeEdit'])) {
$this->logger->debug('Los datos entity y entityBeforeEdit contienen el campo tags'); $this->logger->debug('Los datos entity y entityBeforeEdit contienen el campo tags');
$tags = $jsonData['extraData']['entity']['tags']; $tags = $jsonData['extraData']['entity']['tags'];
$tagsBefore = $jsonData['extraData']['entityBeforeEdit']['tags']; $tagsBefore = $jsonData['extraData']['entityBeforeEdit']['tags'];
$this->logger->debug('Validando si la etiqueta STRIPE existe en entity pero no en entityBeforeEdit'); $this->logger->debug('Validando si la etiqueta STRIPE existe en entity pero no en entityBeforeEdit');
// Comprobar si la etiqueta 'CREAR CLABE STRIPE' existe en 'tags' pero no en 'tagsBefore' // Comprobar si la etiqueta 'CREAR CLABE STRIPE' existe en 'tags' pero no en 'tagsBefore'
$stripeTagExists = false; $stripeTagExists = false;
$stripeTagExistsBefore = false; $stripeTagExistsBefore = false;
foreach ($tags as $tag) { foreach ($tags as $tag) {
if ($tag['name'] === 'CREAR CLABE STRIPE') { if ($tag['name'] === 'CREAR CLABE STRIPE') {
@ -427,7 +459,7 @@ class Plugin
} }
// Comprobar si la etiqueta 'STRIPE' existe en 'tags' pero no en 'tagsBefore' // Comprobar si la etiqueta 'STRIPE' existe en 'tags' pero no en 'tagsBefore'
if ($stripeTagExists && !$stripeTagExistsBefore) { if ($stripeTagExists && ! $stripeTagExistsBefore) {
$this->logger->debug('La etiqueta CREAR CLABE STRIPE se agregará al cliente'); $this->logger->debug('La etiqueta CREAR CLABE STRIPE se agregará al cliente');
$this->pluginNotifierFacade->createStripeClient($notification, true); $this->pluginNotifierFacade->createStripeClient($notification, true);
} }
@ -439,10 +471,8 @@ class Plugin
$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');
} }
$this->notifierFacade->verifyClientActionToDo($notification); $this->notifierFacade->verifyClientActionToDo($notification);
} else if ($notification->eventName === 'client.add') { } else if ($notification->eventName === 'client.add') {
$this->logger->debug('Se agregó un nuevo cliente' . PHP_EOL); $this->logger->debug('Se agregó un nuevo cliente' . PHP_EOL);
$this->logger->debug('Valor de json_data: ' . json_encode($jsonData)); $this->logger->debug('Valor de json_data: ' . json_encode($jsonData));
@ -467,6 +497,56 @@ class Plugin
} else if ($notification->eventName === 'service.edit') { } else if ($notification->eventName === 'service.edit') {
$this->logger->debug('Se editó el servicio a un cliente' . PHP_EOL); $this->logger->debug('Se editó el servicio a un cliente' . PHP_EOL);
$this->notifierFacade->verifyServiceActionToDo($notification); $this->notifierFacade->verifyServiceActionToDo($notification);
//ejemplo de json_data: {"uuid":"06d281ca-d78e-4f0a-a282-3a6b77d25da0","changeType":"edit","entity":"service","entityId":"155","eventName":"service.edit","extraData":{"entity":{"id":155,"prepaid":false,"clientId":171,"status":1,"name":"Basico 300","fullAddress":"Campeche 56, Dolores Hidalgo, 37800","street1":"Campeche 56","street2":null,"city":"Dolores Hidalgo","countryId":173,"stateId":null,"zipCode":"37800","note":null,"addressGpsLat":21.1572461,"addressGpsLon":-100.9377137,"servicePlanId":6,"servicePlanPeriodId":26,"price":300,"hasIndividualPrice":false,"totalPrice":300,"currencyCode":"MXN","invoiceLabel":null,"contractId":null,"contractLengthType":1,"minimumContractLengthMonths":null,"activeFrom":"2025-05-21T00:00:00-0600","activeTo":null,"contractEndDate":null,"discountType":0,"discountValue":null,"discountInvoiceLabel":"Descuento","discountFrom":null,"discountTo":null,"tax1Id":null,"tax2Id":null,"tax3Id":null,"invoicingStart":"2025-05-21T00:00:00-0600","invoicingPeriodType":1,"invoicingPeriodStartDay":1,"nextInvoicingDayAdjustment":10,"invoicingProratedSeparately":true,"invoicingSeparately":false,"sendEmailsAutomatically":null,"useCreditAutomatically":true,"servicePlanName":"Basico 300","servicePlanPrice":300,"servicePlanPeriod":1,"servicePlanType":"Internet","downloadSpeed":8,"uploadSpeed":8,"hasOutage":false,"unmsClientSiteStatus":null,"fccBlockId":null,"lastInvoicedDate":null,"unmsClientSiteId":"359cb58d-e64f-453a-890e-23d5abb4f116","attributes":[],"addressData":null,"suspensionReasonId":null,"serviceChangeRequestId":null,"setupFeePrice":null,"earlyTerminationFeePrice":null,"downloadSpeedOverride":null,"uploadSpeedOverride":null,"trafficShapingOverrideEnd":null,"trafficShapingOverrideEnabled":false,"servicePlanGroupId":null,"suspensionPeriods":[],"surcharges":[]},"entityBeforeEdit":{"id":155,"prepaid":false,"clientId":171,"status":1,"name":"Basico 300","fullAddress":"Campeche 56, Dolores Hidalgo, 37800","street1":"Campeche 56","street2":null,"city":"Dolores Hidalgo","countryId":173,"stateId":null,"zipCode":"37800","note":null,"addressGpsLat":21.1572461,"addressGpsLon":-100.9377137,"servicePlanId":6,"servicePlanPeriodId":26,"price":300,"hasIndividualPrice":false,"totalPrice":300,"currencyCode":"MXN","invoiceLabel":null,"contractId":null,"contractLengthType":1,"minimumContractLengthMonths":null,"activeFrom":"2025-05-21T00:00:00-0600","activeTo":null,"contractEndDate":null,"discountType":0,"discountValue":null,"discountInvoiceLabel":"Descuento","discountFrom":null,"discountTo":null,"tax1Id":null,"tax2Id":null,"tax3Id":null,"invoicingStart":"2025-05-21T00:00:00-0600","invoicingPeriodType":1,"invoicingPeriodStartDay":1,"nextInvoicingDayAdjustment":10,"invoicingProratedSeparately":true,"invoicingSeparately":false,"sendEmailsAutomatically":null,"useCreditAutomatically":true,"servicePlanName":"Basico 300","servicePlanPrice":300,"servicePlanPeriod":1,"servicePlanType":"Internet","downloadSpeed":8,"uploadSpeed":8,"hasOutage":false,"unmsClientSiteStatus":null,"fccBlockId":null,"lastInvoicedDate":null,"unmsClientSiteId":"359cb58d-e64f-453a-890e-23d5abb4f116","attributes":[],"addressData":null,"suspensionReasonId":null,"serviceChangeRequestId":null,"setupFeePrice":null,"earlyTerminationFeePrice":null,"downloadSpeedOverride":null,"uploadSpeedOverride":null,"trafficShapingOverrideEnd":null,"trafficShapingOverrideEnabled":false,"servicePlanGroupId":null,"suspensionPeriods":[],"surcharges":[]}}}
//obtener el clientID y asginarlo a la variable $clientID
$clientID = $jsonData['extraData']['entity']['clientId'];
$this->ucrmApi = UcrmApi::create();
$customAttributes = $this->ucrmApi->get('custom-attributes/', ['attributeType' => 'client']); //Obtener los atributos del sistema que estén vinculados a la entidad "cliente"
//$this->logger->info("result del custom Attributes: " . json_encode($customAttributes) . PHP_EOL);
$idPasswordAntenaCliente = null;
$passwordAntenaValue = null;
//ejemplo de $customAttributes: [{"id":1,"name":"ip","key":"ip","attributeType":"client","type":"string","clientZoneVisible":false},{"id":2,"name":"ubntpass","key":"ubntpass","attributeType":"client","type":"string","clientZoneVisible":false},{"id":3,"name":"adminpass","key":"adminpass","attributeType":"client","type":"string","clientZoneVisible":true},{"id":4,"name":"ssid","key":"ssid","attributeType":"client","type":"string","clientZoneVisible":true},{"id":5,"name":"clavessid","key":"clavessid","attributeType":"client","type":"string","clientZoneVisible":true},{"id":6,"name":"clave","key":"clave","attributeType":"client","type":"string","clientZoneVisible":true},{"id":11,"name":"latitud","key":"latitud","attributeType":"client","type":"string","clientZoneVisible":true},{"id":12,"name":"longitud","key":"longitud","attributeType":"client","type":"string","clientZoneVisible":true},{"id":16,"name":"instalador","key":"instalador","attributeType":"client","type":"string","clientZoneVisible":true},{"id":17,"name":"creado por","key":"creadoPor","attributeType":"client","type":"string","clientZoneVisible":true},{"id":21,"name":"Chat de CallBell","key":"chatDeCallbell","attributeType":"client","type":"string","clientZoneVisible":false},{"id":22,"name":"uuid","key":"uuid","attributeType":"client","type":"string","clientZoneVisible":false},{"id":23,"name":"zona","key":"zona","attributeType":"client","type":"enum","clientZoneVisible":true},{"id":29,"name":"Stripe Customer ID","key":"stripeCustomerId","attributeType":"client","type":"string","clientZoneVisible":true},{"id":30,"name":"Clabe Interbancaria","key":"clabeInterbancaria","attributeType":"client","type":"string","clientZoneVisible":true},{"id":31,"name":"RUTA DE COBRANZA","key":"rutaDeCobranza","attributeType":"client","type":"enum","clientZoneVisible":true},{"id":35,"name":"Site","key":"site","attributeType":"client","type":"string","clientZoneVisible":true},{"id":36,"name":"Antena/Sectorial","key":"antenaSectorial","attributeType":"client","type":"string","clientZoneVisible":true},{"id":37,"name":"Password Antena Cliente","key":"passwordAntenaCliente","attributeType":"client","type":"string","clientZoneVisible":false}]
// Verificar si se obtuvieron los atributos
if ($customAttributes && is_array($customAttributes)) {
foreach ($customAttributes as $attribute) {
// Verificar si 'name' contiene la palabra 'passwordAntenaCliente' sin distinguir mayúsculas y minúsculas
if (isset($attribute['key']) && stripos($attribute['key'], 'passwordAntenaCliente') !== false) {
$this->logger->info("ID correspondiente a 'passwordAntenaCliente': " . $attribute['id'] . PHP_EOL);
$idPasswordAntenaCliente = $attribute['id'];
}
}
} else {
$this->logger->info("Error al obtener los atributos personalizados." . PHP_EOL);
}
//buscar en los attributes ($jsonData) del cliente el id del atributo personalizado 'passwordAntenaCliente' si no está o si está pero está en blanco se manda llamar la función $this->notifierFacade->getVaultCredentials($clientID);
foreach ($jsonData['extraData']['entity']['attributes'] as $attribute) {
if ($attribute['customAttributeId'] === $idPasswordAntenaCliente) {
$this->logger->info("El valor de passwordAntenaValue es: " . $attribute['value'] . PHP_EOL);
$passwordAntenaValue = $attribute['value'];
}
}
//si el value de passwordAntenaValue es igual a null o cadena vacía se manda llamar la función $this->notifierFacade->getVaultCredentials($clientID);
if ($passwordAntenaValue === null || $passwordAntenaValue === '') {
$password = $this->notifierFacade->getVaultCredentials($clientID);
$this->logger->info("El valor de passwordAntenaValue es null o cadena vacía, se manda llamar la función getVaultCredentials" . PHP_EOL);
$this->logger->info("El valor de password es: " . $password . PHP_EOL);
if ($this->notifierFacade->patchClientCustomAttribute($clientID, $idPasswordAntenaCliente, $password)) {
$this->logger->info("Se actualizó el atributo personalizado passwordAntenaCliente con el valor: " . $password . PHP_EOL);
} else {
$this->logger->info("No se pudo actualizar el atributo personalizado passwordAntenaCliente" . PHP_EOL);
}
} else {
$this->logger->info("Ya existe un valor de passwordAntenaValue: " . $passwordAntenaValue . PHP_EOL);
}
} else if ($notification->eventName === 'service.suspend') { } else if ($notification->eventName === 'service.suspend') {
$this->logger->debug('Se suspendió el servicio a un cliente' . PHP_EOL); $this->logger->debug('Se suspendió el servicio a un cliente' . PHP_EOL);
$this->notifierFacade->verifyServiceActionToDo($notification); $this->notifierFacade->verifyServiceActionToDo($notification);
@ -508,28 +588,21 @@ class Plugin
$this->notifierFacade->verifyInvoiceActionToDo($notification); $this->notifierFacade->verifyInvoiceActionToDo($notification);
} else if ($notification->eventName === 'job.add') { } else if ($notification->eventName === 'job.add') {
$this->logger->debug('Se ha agregado un nuevo trabajo' . PHP_EOL); $this->logger->debug('Se ha agregado un nuevo trabajo' . PHP_EOL);
$this->logger->debug('Valor de json_data: ' . json_encode($jsonData));
//Ejemplo de json_data: {"uuid":"434b3da0-984a-4358-a1b6-2a4418bacc49","changeType":"insert","entity":"job","entityId":"38","eventName":"job.add","extraData":{"entity":{"id":38,"title":"Servicio","description":"Revisar Router","assignedUserId":null,"clientId":2,"date":null,"duration":60,"status":0,"address":"31 Chiapas, Dolores Hidalgo Cuna de la Independencia Nacional, 37800, Mexico","gpsLat":null,"gpsLon":null,"attachments":[],"tasks":[]},"entityBeforeEdit":null}}
//Extraer el valor de title en una variable y concatenarle como prefijo la cadena "[SINENVIONOTIFICACION]" por ejemplo: "[NOTIFICACION-PENDIENTE]Servicio"
$title = $jsonData['extraData']['entity']['title'];
$title = '[NOTIFICACION-PENDIENTE]' . $title;
$this->ucrmApi = UcrmApi::create();
$responsePatch = $this->ucrmApi->patch('scheduling/jobs/' . $jsonData['entityId'], [
'title' => $title,
]);
$this->logger->debug('Respuesta de la API al agregar el trabajo: ' . json_encode($responsePatch) . PHP_EOL);
// Verificar que existen tanto 'assignedUserId' como 'entity'
if (isset($jsonData['extraData']['entity']['assignedUserId'])) {
$this->logger->debug('El campo assignedUserId existe en los datos del evento');
$assignedUserId = $jsonData['extraData']['entity']['assignedUserId'];
// Comprobar si 'isLead' es null
if ($assignedUserId === null) {
$this->logger->debug('El campo assignedUserId es null');
$this->pluginNotifierFacade->createStripeClient($notification);
} else {
$this->logger->debug('El campo assignedUserId no es null');
$this->notifierFacade->verifyJobActionToDo($notification);
}
} else {
$this->logger->warning('El campo assignedUserId no existe en los datos del evento');
}
} else if ($notification->eventName === 'job.edit') { } else if ($notification->eventName === 'job.edit') {
$this->logger->debug('Se actualiza un trabajo' . PHP_EOL); $this->logger->debug('Se actualiza un trabajo' . PHP_EOL);
$this->logger->debug('Valor de json_data: ' . json_encode($jsonData)); // $this->logger->debug('Valor de json_data: ' . json_encode($jsonData));
// Validar que 'extraData' existe y contiene las claves necesarias // Validar que 'extraData' existe y contiene las claves necesarias
if ( if (
@ -537,39 +610,54 @@ class Plugin
isset($jsonData['extraData']['entity']) isset($jsonData['extraData']['entity'])
) { ) {
$entityBeforeEdit = $jsonData['extraData']['entityBeforeEdit']; $entityBeforeEdit = $jsonData['extraData']['entityBeforeEdit'];
$entity = $jsonData['extraData']['entity']; $entity = $jsonData['extraData']['entity'];
$this->logger->debug('Validando claves dentro de entityBeforeEdit y entity'); $this->logger->debug('Validando claves dentro de entityBeforeEdit y entity');
// Validar que 'assignedUserId' existe en ambas entidades // Validar que 'assignedUserId' existe en ambas entidades
if (array_key_exists('assignedUserId', $entityBeforeEdit) && array_key_exists('assignedUserId', $entity)) { if (array_key_exists('assignedUserId', $entityBeforeEdit) && array_key_exists('assignedUserId', $entity)) {
$this->logger->debug('Los datos entityBeforeEdit y entity contienen el campo assignedUserId'); // $this->logger->debug('Los datos entityBeforeEdit y entity contienen el campo assignedUserId');
$assignedUserIdBefore = $entityBeforeEdit['assignedUserId']; $assignedUserIdBefore = $entityBeforeEdit['assignedUserId'];
$assignedUserIdAfter = $entity['assignedUserId']; $assignedUserIdAfter = $entity['assignedUserId'];
$dateBefore = $entityBeforeEdit['date']; $dateBefore = $entityBeforeEdit['date'];
$dateAfter = $entity['date']; $dateAfter = $entity['date'];
$statusBefore = $entityBeforeEdit['status']; $statusBefore = $entityBeforeEdit['status'];
$statusAfter = $entity['status']; $statusAfter = $entity['status'];
$title = $entityBeforeEdit['title'];
$pendingPrefix = '[NOTIFICACION-PENDIENTE]'; // Prefijo para trabajos pendientes de notificación
$currentTitle = $entity['title'] ?? ''; // Obtener el título actual
// Comprobar si 'assignedUserId' cambió //Valores de status y su significado: 0 = abierto, 1= En curso, 2 = Cerrado
if ($assignedUserIdBefore === null && $assignedUserIdAfter != null) { //Si el campo "assignedUserId" cambió de null a un valor
$this->logger->debug('El instalador cambió de null a un valor'); if ($statusAfter == 1) {
$this->notifierFacade->verifyJobActionToDo($jsonData); // Se envía notificación de trabajo asignado // Comprobar si 'assignedUserId' cambió
} else if (($assignedUserIdBefore != null && $assignedUserIdAfter != $assignedUserIdBefore) && ($dateBefore === $dateAfter)) {//Si el campo "assignedUserId" cambió de un valor a otro y la fecha no cambió // if (($assignedUserIdBefore === null && $assignedUserIdAfter != null) || ($statusBefore == 0 && $statusAfter == 1)) { //Si el campo "assignedUserId" cambió de null a un valor
$this->logger->debug('El instalador cambió y la fecha no cambió'); // $this->logger->debug('El instalador cambió de null a un valor');
$this->notifierFacade->verifyJobActionToDo($jsonData, false, true); // Se envía notificación de trabajo reasignado
} else if (($assignedUserIdBefore != null && $assignedUserIdBefore === $assignedUserIdAfter) && ($dateBefore != $dateAfter)) {//Si el campo "assignedUserId" no cambió y la fecha cambió // $this->notifierFacade->verifyJobActionToDo($jsonData); // Se envía notificación de trabajo asignado
$this->logger->debug('El instalador no cambió y la fecha sí cambió'); // }
$this->notifierFacade->verifyJobActionToDo($jsonData, true, false); // Se envía notificación de reprogramación de trabajo
} else if (($assignedUserIdBefore != null && $assignedUserIdAfter != $assignedUserIdBefore) && ($dateBefore != $dateAfter)) { //Si el campo status cambió de 0 a 1 y title comienza con el prefijo [NOTIFICACION-PENDIENTE]
$this->logger->debug('El instalador cambió y la fecha sí cambió'); if (($statusBefore == 0 && $statusAfter == 1) && strpos($currentTitle, $pendingPrefix) !== false) { // Se envía notificación de trabajo asignado
$this->notifierFacade->verifyJobActionToDo($jsonData, true, true); // Se envía notificación de trabajo reasignado $this->logger->debug('El instalador cambió de null a un valor');
} else if ($assignedUserIdBefore != null && $assignedUserIdAfter === null) { //Si el campo "assignedUserId" cambió de un valor a null $this->notifierFacade->verifyJobActionToDo($jsonData, false, false);
$this->logger->debug('El instalador cambió de un valor a null'); } else if (($assignedUserIdBefore != null && $assignedUserIdAfter != $assignedUserIdBefore) && ($dateBefore === $dateAfter)) { //Si el campo "assignedUserId" cambió de un valor a otro y la fecha no cambió
$this->notifierFacade->verifyJobActionToDo($jsonData, null, true); // Se envía notificación de trabajo desasignado $this->logger->debug('No hay reprogramación de trabajo pero si hay cambio de instalador');
} else { $this->notifierFacade->verifyJobActionToDo($jsonData, false, true); // Se envía notificación de trabajo reasignado
$this->logger->debug('No hubo cambio en el instalador ni en la fecha'); } else if (($assignedUserIdBefore != null && $assignedUserIdBefore === $assignedUserIdAfter) && ($dateBefore != $dateAfter)) { //Si el campo "assignedUserId" no cambió y la fecha cambió
$this->logger->debug('Se reprogramó el trabajo pero no hubo cambio de instalador');
$this->notifierFacade->verifyJobActionToDo($jsonData, true, false); // Se envía notificación de reprogramación de trabajo
} else if (($assignedUserIdBefore != null && $assignedUserIdAfter != $assignedUserIdBefore) && ($dateBefore != $dateAfter)) {
$this->logger->debug('Se reprogramó el trabajo y hubo cambio de instalador');
$this->notifierFacade->verifyJobActionToDo($jsonData, true, true); // Se envía notificación de trabajo reasignado
} else if ($assignedUserIdBefore != null && $assignedUserIdAfter === null) { //Si el campo "assignedUserId" cambió de un valor a null
$this->logger->debug('El instalador cambió de un valor a null');
$this->notifierFacade->verifyJobActionToDo($jsonData, null, true); // Se envía notificación de trabajo desasignado
} else {
$this->logger->debug('No hubo cambio en el instalador ni en la fecha');
//$this->notifierFacade->verifyJobActionToDo($jsonData); // Se envía notificación de trabajo asignado
}
} }
} else { } else {
@ -581,8 +669,6 @@ class Plugin
} }
//$this->notifierFacade->update($notification); //$this->notifierFacade->update($notification);
} catch (TwilioException $exception) { } catch (TwilioException $exception) {
$this->logger->error($exception->getMessage()); $this->logger->error($exception->getMessage());

View File

@ -5,7 +5,7 @@
'type' => 'library', 'type' => 'library',
'install_path' => __DIR__ . '/../../', 'install_path' => __DIR__ . '/../../',
'aliases' => array(), 'aliases' => array(),
'reference' => '9a3af1f3d453e226100a2c8ff4c62b4929373492', 'reference' => '7cb26fe7358fc5b3d7671f2db68235f6bb07ef3f',
'name' => 'ucrm-plugins/sms-twilio', 'name' => 'ucrm-plugins/sms-twilio',
'dev' => false, 'dev' => false,
), ),
@ -307,7 +307,7 @@
'type' => 'library', 'type' => 'library',
'install_path' => __DIR__ . '/../../', 'install_path' => __DIR__ . '/../../',
'aliases' => array(), 'aliases' => array(),
'reference' => '9a3af1f3d453e226100a2c8ff4c62b4929373492', 'reference' => '7cb26fe7358fc5b3d7671f2db68235f6bb07ef3f',
'dev_requirement' => false, 'dev_requirement' => false,
), ),
), ),