Versión 2.8.2 Rutina de envio de mensajes con plantillas de utilidad refactorizado, además tipo de pago 'applied_to_payment' en en analisis de webhooks de Stripe

This commit is contained in:
server 2025-05-27 15:57:43 -06:00
parent e34b3ec0f8
commit e899945ca3
7 changed files with 1948 additions and 321 deletions

View File

@ -2,6 +2,21 @@
Este plugin sincroniza los clientes del sitema 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 Este plugin sincroniza los clientes del sitema 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
## REGISTRO DE CAMBIOS
# VERSIÓN 2.8.2
## 🟡 Bugs Resueltos
* 1⃣ No se enviaban las notificaciones de las tareas al instalador. Se cambió la plantilla de CallBell o WhatsApp con 3 variables en lugar de 8
* 2⃣ Se agregó un nuevo tipo de pago ("applied_to_payment") en las propiedades de los Webhooks recibidos mediante Stripe por concepto de transferencias bancarias. Ya que sólo se revisaba el tipo de pago "funded" y eso hacía que no enviara los comprobantes de pago a los clientes para todos los casos.
## REGISTRO DE CAMBIOS
# VERSIÓN 2.8.1
## 🟡 Bugs Resueltos
* 1⃣ No se enviaban las notificaciones de las tareas al instalador.
# VERSIÓN 2.8.0 # VERSIÓN 2.8.0
## 🟢 Novedades ## 🟢 Novedades

File diff suppressed because it is too large Load Diff

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.8.0", "version": "2.8.2",
"unmsVersionCompliancy": { "unmsVersionCompliancy": {
"min": "2.1.0", "min": "2.1.0",
"max": null "max": null

View File

@ -1,6 +1,6 @@
<?php <?php
declare (strict_types = 1); declare(strict_types=1);
namespace SmsNotifier\Facade; namespace SmsNotifier\Facade;
@ -47,16 +47,16 @@ abstract class AbstractMessageNotifierFacade
protected $ucrmApi; protected $ucrmApi;
const SUBJECT_OF_INSTALLER_CHANGE = ["se ha cancelado una tarea que tenías asignada con el folio ", "se te ha desasignado❌ la tarea con el folio "]; const SUBJECT_OF_INSTALLER_CHANGE = ["se ha cancelado una tarea que tenías asignada con el folio ", "se te ha desasignado❌ la tarea con el folio "];
const ADDITIONAL_CHANGE_DATA = ["Ya no es necesario realizar la visita técnica.", "En tu lugar asistirá el técnico 👷🏻‍♂️➡️ "]; const ADDITIONAL_CHANGE_DATA = ["Ya no es necesario realizar la visita técnica.", "En tu lugar asistirá el técnico 👷🏻‍♂️➡️ "];
public function __construct( public function __construct(
Logger $logger, Logger $logger,
MessageTextFactory $messageTextFactory, MessageTextFactory $messageTextFactory,
SmsNumberProvider $clientPhoneNumber, SmsNumberProvider $clientPhoneNumber,
) { ) {
$this->logger = $logger; $this->logger = $logger;
$this->messageTextFactory = $messageTextFactory; $this->messageTextFactory = $messageTextFactory;
$this->clientPhoneNumber = $clientPhoneNumber; $this->clientPhoneNumber = $clientPhoneNumber;
} }
@ -223,23 +223,23 @@ abstract class AbstractMessageNotifierFacade
{ {
$this->logger->debug('******** INCIO DE LA FUNCIÓN verifyJobActionToDo ******' . PHP_EOL); $this->logger->debug('******** INCIO DE LA FUNCIÓN verifyJobActionToDo ******' . PHP_EOL);
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create(); $configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
$config = $configManager->loadConfig(); $config = $configManager->loadConfig();
$IPServer = $config['ipserver']; $IPServer = $config['ipserver'];
$UCRMAPIToken = $config['apitoken']; $UCRMAPIToken = $config['apitoken'];
$CallBellAPIToken = $config['tokencallbell']; $CallBellAPIToken = $config['tokencallbell'];
$IPServer = $config['ipserver']; $IPServer = $config['ipserver'];
$installersData = $config['installersDataWhatsApp']; $installersData = $config['installersDataWhatsApp'];
$this->logger->debug('Valor de $jsonNotificationData en verifyJobActionToDo: ' . json_encode($jsonNotificationData) . PHP_EOL); $this->logger->debug('Valor de $jsonNotificationData en verifyJobActionToDo: ' . json_encode($jsonNotificationData) . PHP_EOL);
$this->logger->debug('Valor de $jsonNotificationData en verifyJobActionToDo: ' . json_encode($jsonNotificationData) . PHP_EOL); $this->logger->debug('Valor de $jsonNotificationData en verifyJobActionToDo: ' . json_encode($jsonNotificationData) . PHP_EOL);
$clientId = $jsonNotificationData['extraData']['entity']['clientId']; $clientId = $jsonNotificationData['extraData']['entity']['clientId'];
$installerId = $jsonNotificationData['extraData']['entity']['assignedUserId']; $installerId = $jsonNotificationData['extraData']['entity']['assignedUserId'];
$jobId = $jsonNotificationData['entityId']; $jobId = $jsonNotificationData['entityId'];
$jobDescription = $jsonNotificationData['extraData']['entity']['description'] ?? null; $jobDescription = $jsonNotificationData['extraData']['entity']['description'] ?? null;
$reprogrammingValue = var_export($reprogramming, true); $reprogrammingValue = var_export($reprogramming, true);
$changeInstallerValue = var_export($changeInstaller, true); $changeInstallerValue = var_export($changeInstaller, true);
$this->logger->debug('Valor de $reprogramming en verifyJobActionToDo: ' . $reprogrammingValue . PHP_EOL); $this->logger->debug('Valor de $reprogramming en verifyJobActionToDo: ' . $reprogrammingValue . PHP_EOL);
$this->logger->debug('Valor de $changeInstaller en verifyJobActionToDo: ' . $changeInstallerValue . PHP_EOL); $this->logger->debug('Valor de $changeInstaller en verifyJobActionToDo: ' . $changeInstallerValue . PHP_EOL);
@ -251,19 +251,64 @@ abstract class AbstractMessageNotifierFacade
// Crear un objeto DateTime a partir de la fecha // Crear un objeto DateTime a partir de la fecha
$date = new DateTime($dateString); $date = new DateTime($dateString);
// concaternar emoji de reloj de la hora que más se asemeje a la hora del evento, por ejemplo si la hora es 8:00 am o pm se concatena el emoji de reloj de las 8:00 am o pm como: 🕗
$hour = $date->format('h');
$clockEmoji = "🕐"; // Emoji por defecto
// Determinar el emoji del reloj según la hora
switch ($hour) {
case '01':
$clockEmoji = "🕐";
break;
case '02':
$clockEmoji = "🕑";
break;
case '03':
$clockEmoji = "🕒";
break;
case '04':
$clockEmoji = "🕓";
break;
case '05':
$clockEmoji = "🕔";
break;
case '06':
$clockEmoji = "🕕";
break;
case '07':
$clockEmoji = "🕖";
break;
case '08':
$clockEmoji = "🕗";
break;
case '09':
$clockEmoji = "🕘";
break;
case '10':
$clockEmoji = "🕙";
break;
case '11':
$clockEmoji = "🕚";
break;
case '12':
$clockEmoji = "🕛";
break;
}
// Formatear la fecha al formato deseado: día/mes/año a las hora:minuto am/pm aproximadamente // Formatear la fecha al formato deseado: día/mes/año a las hora:minuto am/pm aproximadamente
$formattedDate = "*" . $date->format('d/m/Y') . "* a las *" . $date->format('h:i A') . "* aproximadamente"; $formattedDate = "*" . $date->format('d/m/Y') . "* a las $clockEmoji *" . $date->format('h:i A') . "* aproximadamente";
// $this->logger->debug('Valor de $formattedDate en verifyJobActionToDo: ' . $formattedDate . PHP_EOL); // $this->logger->debug('Valor de $formattedDate en verifyJobActionToDo: ' . $formattedDate . PHP_EOL);
} else { } else {
$this->logger->error('La fecha no está disponible en el JSON' . PHP_EOL); $this->logger->error('La fecha no está disponible en el JSON' . PHP_EOL);
} }
// $this->logger->debug('Valor de $installersData en verifyJobActionToDo: ' . $installersData . PHP_EOL); $this->logger->debug('Valor de $installersData en verifyJobActionToDo: ' . $installersData . PHP_EOL);
$this->ucrmApi = UcrmApi::create(); $this->ucrmApi = UcrmApi::create();
$usersInstallers = $this->ucrmApi->get('users/admins/' . $installerId, []); $usersInstallers = $this->ucrmApi->get('users/admins/' . $installerId, []);
// $this->logger->debug('Valor de $usersInstallers en verifyJobActionToDo: ' . json_encode($usersInstallers) . PHP_EOL); $this->logger->debug('Valor de $usersInstallers en verifyJobActionToDo: ' . json_encode($usersInstallers) . PHP_EOL);
// Inicializar la variable para el nombre completo // Inicializar la variable para el nombre completo
$installerFullName = ''; $installerFullName = '';
@ -276,7 +321,7 @@ abstract class AbstractMessageNotifierFacade
} }
// Verificar si el nodo "instaladores" existe // Verificar si el nodo "instaladores" existe
if (! isset($jsonInstallersData['instaladores'])) { if (!isset($jsonInstallersData['instaladores'])) {
$this->logger->error('El nodo "instaladores" no existe en el JSON'); $this->logger->error('El nodo "instaladores" no existe en el JSON');
return; return;
} }
@ -295,31 +340,31 @@ abstract class AbstractMessageNotifierFacade
if (empty($installerWhatsApp)) { if (empty($installerWhatsApp)) {
$this->logger->warning('No se encontró un número de WhatsApp para el instalador con ID 1019'); $this->logger->warning('No se encontró un número de WhatsApp para el instalador con ID 1019');
} else { } else {
// $this->logger->debug('Número de WhatsApp del Instalador: ' . $installerWhatsApp . PHP_EOL); $this->logger->debug('Número de WhatsApp del Instalador: ' . $installerWhatsApp . PHP_EOL);
} }
$this->ucrmApi = UcrmApi::create(); $this->ucrmApi = UcrmApi::create();
$usersInstallers = $this->ucrmApi->get('users/admins/' . $installerId, []); $usersInstallers = $this->ucrmApi->get('users/admins/' . $installerId, []);
//$this->logger->debug('Valor de $usersInstallers ' . json_encode($usersInstallers) . PHP_EOL); //$this->logger->debug('Valor de $usersInstallers ' . json_encode($usersInstallers) . PHP_EOL);
$firstName = $usersInstallers['firstName'] ?? ''; $firstName = $usersInstallers['firstName'] ?? '';
$lastName = $usersInstallers['lastName'] ?? ''; $lastName = $usersInstallers['lastName'] ?? '';
$installerFullName = trim("$firstName $lastName"); $installerFullName = trim("$firstName $lastName");
// $this->logger->debug('Valor de $installerFullName: ' . $installerFullName . PHP_EOL); $this->logger->debug('Valor de $installerFullName: ' . $installerFullName . PHP_EOL);
$baseUri = 'https://' . $IPServer . '/crm/api/v1.0/'; $baseUri = 'https://' . $IPServer . '/crm/api/v1.0/';
$clientGuzzleHttp = new Client([ $clientGuzzleHttp = new Client([
'base_uri' => $baseUri, 'base_uri' => $baseUri,
'headers' => [ 'headers' => [
'X-Auth-App-Key' => $UCRMAPIToken, 'X-Auth-App-Key' => $UCRMAPIToken,
'Accept' => 'application/json', 'Accept' => 'application/json',
], ],
'verify' => false, 'verify' => false,
]); ]);
$responseClients = $clientGuzzleHttp->request('GET', "clients/" . $clientId); $responseClients = $clientGuzzleHttp->request('GET', "clients/" . $clientId);
$arrayClientCRM = json_decode($responseClients->getBody()->getContents(), true); $arrayClientCRM = json_decode($responseClients->getBody()->getContents(), true);
// $this->logger->debug('Valor de $arrayClientCRM en verifyJobActionToDo: ' . json_encode($arrayClientCRM) . PHP_EOL); // $this->logger->debug('Valor de $arrayClientCRM en verifyJobActionToDo: ' . json_encode($arrayClientCRM) . PHP_EOL);
$clientFullName = sprintf("%s %s", $arrayClientCRM['firstName'], $arrayClientCRM['lastName']); $clientFullName = sprintf("%s %s", $arrayClientCRM['firstName'], $arrayClientCRM['lastName']);
@ -356,11 +401,11 @@ abstract class AbstractMessageNotifierFacade
// Convertir el array de teléfonos en una cadena separada por comas // Convertir el array de teléfonos en una cadena separada por comas
$clientAllPhonesString = implode(',', $arrayAllPhones); $clientAllPhonesString = implode(',', $arrayAllPhones);
// $this->logger->debug('Valor de $clientAllPhonesString en verifyJobActionToDo: ' . $clientAllPhonesString . PHP_EOL); $this->logger->debug('Valor de $clientAllPhonesString en verifyJobActionToDo: ' . $clientAllPhonesString . PHP_EOL);
// Dividir los números en un array // Dividir los números en un array
$arrayNumeros = explode(',', $clientAllPhonesString); $arrayNumeros = explode(',', $clientAllPhonesString);
// $this->logger->debug('Valor de $arrayNumeros en verifyJobActionToDo: ' . json_encode($arrayNumeros) . PHP_EOL); $this->logger->debug('Valor de $arrayNumeros en verifyJobActionToDo: ' . json_encode($arrayNumeros) . PHP_EOL);
// Procesar cada número // Procesar cada número
$resultados = []; $resultados = [];
@ -378,7 +423,7 @@ abstract class AbstractMessageNotifierFacade
$resultados[] = $numeroValidado; // Mantener el número sin cambios $resultados[] = $numeroValidado; // Mantener el número sin cambios
} }
} }
// $this->logger->debug('Valor de $resultados en verifyJobActionToDo: ' . json_encode($resultados) . PHP_EOL); $this->logger->debug('Valor de $resultados en verifyJobActionToDo: ' . json_encode($resultados) . PHP_EOL);
// Convertir el array de resultados en una cadena separada por comas // Convertir el array de resultados en una cadena separada por comas
$resultadoFinalNumerosCliente = implode(', ', $resultados); $resultadoFinalNumerosCliente = implode(', ', $resultados);
@ -389,9 +434,9 @@ abstract class AbstractMessageNotifierFacade
// Construir el array asociativo con los datos de la notificación para el cliente // Construir el array asociativo con los datos de la notificación para el cliente
$jsonClientJobNotificationData = [ $jsonClientJobNotificationData = [
"clientFullName" => $clientFullName, "clientFullName" => $clientFullName,
"jobId" => $jobId, "jobId" => $jobId,
"date" => $formattedDate, "date" => $formattedDate,
"installerName" => $installerFullName, "installerName" => $installerFullName,
]; ];
$clientWhatsApp = ''; $clientWhatsApp = '';
@ -410,9 +455,9 @@ abstract class AbstractMessageNotifierFacade
// Verificar si el valor es un array de teléfonos // Verificar si el valor es un array de teléfonos
if (is_array($phones)) { if (is_array($phones)) {
$attempts = 0; $attempts = 0;
$maxAttempts = 3; $maxAttempts = 3;
$result = false; $result = false;
foreach ($phones as $phone) { foreach ($phones as $phone) {
//Aquí se enviará la notificación al cliente //Aquí se enviará la notificación al cliente
@ -439,12 +484,12 @@ abstract class AbstractMessageNotifierFacade
$this->logger->debug('Valor de $title en verifyJobActionToDo: ' . $title . PHP_EOL); $this->logger->debug('Valor de $title en verifyJobActionToDo: ' . $title . PHP_EOL);
//la variable $title contiene el título del trabajo con un prefijo "[NOTIFICACION-PENDIENTE]" aquí hay que quitarlo //la variable $title contiene el título del trabajo con un prefijo "[NOTIFICACION-PENDIENTE]" aquí hay que quitarlo
// $this->ucrmApi = UcrmApi::create(); // $this->ucrmApi = UcrmApi::create();
// $responsePatch = $this->ucrmApi->patch('scheduling/jobs/' . $jsonNotificationData['entityId'], [ // $responsePatch = $this->ucrmApi->patch('scheduling/jobs/' . $jsonNotificationData['entityId'], [
// 'title' => $title, // 'title' => $title,
// ]); // ]);
if (strpos($title, '[NOTIFICACION-PENDIENTE]') !== false) { //si el título contiene el prefijo [NOTIFICACION-PENDIENTE] entonces se quita if (strpos($title, '[NOTIFICACION-PENDIENTE]') !== false) { //si el título contiene el prefijo [NOTIFICACION-PENDIENTE] entonces se quita
$title = str_replace('[NOTIFICACION-PENDIENTE]', '', $title); // Quitar el prefijo $title = str_replace('[NOTIFICACION-PENDIENTE]', '', $title); // Quitar el prefijo
$responseClients = $clientGuzzleHttp->request('PATCH', "scheduling/jobs/" . $jsonNotificationData['entityId'], [ $responseClients = $clientGuzzleHttp->request('PATCH', "scheduling/jobs/" . $jsonNotificationData['entityId'], [
'json' => [ 'json' => [
'title' => $title, 'title' => $title,
@ -474,7 +519,7 @@ abstract class AbstractMessageNotifierFacade
} }
// --- ¡AÑADE ESTAS LÍNEAS PARA CONVERTIR A BOOLEANO REAL! --- // --- ¡AÑADE ESTAS LÍNEAS PARA CONVERTIR A BOOLEANO REAL! ---
$reprogramming = filter_var($reprogramming, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); $reprogramming = filter_var($reprogramming, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
$changeInstaller = filter_var($changeInstaller, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); $changeInstaller = filter_var($changeInstaller, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
// ----------------------------------------------------------- // -----------------------------------------------------------
@ -490,19 +535,19 @@ abstract class AbstractMessageNotifierFacade
//Enviar notificación al instalador anterior //Enviar notificación al instalador anterior
$previousinstallerInstallerId = $installerId = $jsonNotificationData['extraData']['entityBeforeEdit']['assignedUserId']; $previousinstallerInstallerId = $installerId = $jsonNotificationData['extraData']['entityBeforeEdit']['assignedUserId'];
$usersInstallers = $this->ucrmApi->get('users/admins/' . $previousinstallerInstallerId, []); $usersInstallers = $this->ucrmApi->get('users/admins/' . $previousinstallerInstallerId, []);
$firstNamePreviousInstaller = $usersInstallers['firstName'] ?? ''; //Obtener el nombre del instalador anterior $firstNamePreviousInstaller = $usersInstallers['firstName'] ?? ''; //Obtener el nombre del instalador anterior
$lastNamePreviousInstaller = $usersInstallers['lastName'] ?? ''; //Obtener el apellido del instalador anterior $lastNamePreviousInstaller = $usersInstallers['lastName'] ?? ''; //Obtener el apellido del instalador anterior
$previousInstallerFullName = trim("$firstNamePreviousInstaller $lastNamePreviousInstaller"); $previousInstallerFullName = trim("$firstNamePreviousInstaller $lastNamePreviousInstaller");
$attempts = 0; $attempts = 0;
$maxAttempts = 3; $maxAttempts = 3;
$result = false; $result = false;
$jsonPreviousInstallerJobNotificationData = [ $jsonPreviousInstallerJobNotificationData = [
"installerName" => "👷🏻‍♂️" . $previousInstallerFullName, "installerName" => "👷🏻‍♂️" . $previousInstallerFullName,
"subjectOfChange" => self::SUBJECT_OF_INSTALLER_CHANGE[1], "subjectOfChange" => self::SUBJECT_OF_INSTALLER_CHANGE[1],
"jobId" => $jobId, "jobId" => $jobId,
"clientFullName" => sprintf("[%s] %s", $arrayClientCRM['id'], $clientFullName), "clientFullName" => sprintf("[%s] %s", $arrayClientCRM['id'], $clientFullName),
"additionalChangeData" => self::ADDITIONAL_CHANGE_DATA[1] . ' *' . $installerFullName . '*', "additionalChangeData" => self::ADDITIONAL_CHANGE_DATA[1] . ' *' . $installerFullName . '*',
]; ];
@ -524,8 +569,8 @@ abstract class AbstractMessageNotifierFacade
$result = $client_callbell_api->sendJobNotificationWhatsAppToInstaller( $result = $client_callbell_api->sendJobNotificationWhatsAppToInstaller(
$this->validarNumeroTelefono((string) $previousInstallerWhatsApp), $this->validarNumeroTelefono((string) $previousInstallerWhatsApp),
$jsonPreviousInstallerJobNotificationData, $jsonPreviousInstallerJobNotificationData,
false, $reprogramming,
true, $changeInstaller,
'' ''
); );
@ -540,21 +585,21 @@ abstract class AbstractMessageNotifierFacade
// Construir el array asociativo con los datos de la notificación para el instalador nuevo // Construir el array asociativo con los datos de la notificación para el instalador nuevo
$jsonInstallerJobNotificationData = [ $jsonInstallerJobNotificationData = [
"installerName" => $installerFullName, "installerName" => $installerFullName,
"clientFullName" => sprintf("[%s] %s", $arrayClientCRM['id'], $clientFullName), "clientFullName" => sprintf("[%s] %s", $arrayClientCRM['id'], $clientFullName),
"jobId" => $jobId, "jobId" => $jobId,
"clientAddress" => $safeAddress, "clientAddress" => $safeAddress,
"clientWhatsApp" => $resultadoFinalNumerosCliente, "clientWhatsApp" => $resultadoFinalNumerosCliente,
"date" => $formattedDate, "date" => $formattedDate,
"jobDescription" => $jobDescription, "jobDescription" => $jobDescription,
"gmapsLocation" => $googleMapsUrl, "gmapsLocation" => $googleMapsUrl,
]; ];
//Enviar notificación al instalador nuevo //Enviar notificación al instalador nuevo
$attempts = 0; $attempts = 0;
$maxAttempts = 3; $maxAttempts = 3;
$result = false; $result = false;
// Reintentar hasta 3 veces si la función retorna false // Reintentar hasta 3 veces si la función retorna false
while ($attempts < $maxAttempts && $result === false) { while ($attempts < $maxAttempts && $result === false) {
@ -578,20 +623,20 @@ abstract class AbstractMessageNotifierFacade
// Construir el array asociativo con los datos de la notificación // Construir el array asociativo con los datos de la notificación
$jsonInstallerJobNotificationData = [ $jsonInstallerJobNotificationData = [
"installerName" => $installerFullName, "installerName" => $installerFullName,
"clientFullName" => sprintf("[%s] %s", $arrayClientCRM['id'], $clientFullName), "clientFullName" => sprintf("[%s] %s", $arrayClientCRM['id'], $clientFullName),
"jobId" => $jobId, "jobId" => $jobId,
"clientAddress" => $safeAddress, "clientAddress" => $safeAddress,
"clientWhatsApp" => $resultadoFinalNumerosCliente, "clientWhatsApp" => $resultadoFinalNumerosCliente,
"date" => $formattedDate, "date" => $formattedDate,
"jobDescription" => $jobDescription, "jobDescription" => $jobDescription,
"gmapsLocation" => $googleMapsUrl, "gmapsLocation" => $googleMapsUrl,
]; ];
$attempts = 0; $attempts = 0;
$maxAttempts = 3; $maxAttempts = 3;
$result = false; $result = false;
// // Reintentar hasta 3 veces si la función retorna false // // Reintentar hasta 3 veces si la función retorna false
while ($attempts < $maxAttempts && $result === false) { while ($attempts < $maxAttempts && $result === false) {
@ -599,8 +644,8 @@ abstract class AbstractMessageNotifierFacade
$result = $client_callbell_api->sendJobNotificationWhatsAppToInstaller( $result = $client_callbell_api->sendJobNotificationWhatsAppToInstaller(
$this->validarNumeroTelefono((string) $installerWhatsApp), $this->validarNumeroTelefono((string) $installerWhatsApp),
$jsonInstallerJobNotificationData, $jsonInstallerJobNotificationData,
false, $reprogramming,
false, $changeInstaller,
$this->getVaultCredentials($arrayClientCRM['id']) $this->getVaultCredentials($arrayClientCRM['id'])
); );
@ -674,16 +719,16 @@ abstract class AbstractMessageNotifierFacade
// $notification_client_data_export = json_encode($notification_client_data); // $notification_client_data_export = json_encode($notification_client_data);
// $this->logger->info("Valor de notification client data export: " . $notification_client_data_export . PHP_EOL); // $this->logger->info("Valor de notification client data export: " . $notification_client_data_export . PHP_EOL);
$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
$IPServer = $config['ipserver']; $IPServer = $config['ipserver'];
$UCRMAPIToken = $config['apitoken']; $UCRMAPIToken = $config['apitoken'];
$CallBellAPIToken = $config['tokencallbell']; $CallBellAPIToken = $config['tokencallbell'];
$notificationTypeText = $config['notificationTypeText']; $notificationTypeText = $config['notificationTypeText'];
$client_callbell_api = new ClientCallBellAPI($UCRMAPIToken, $IPServer, $CallBellAPIToken); $client_callbell_api = new ClientCallBellAPI($UCRMAPIToken, $IPServer, $CallBellAPIToken);
//$clientPhoneNumber = $this->clientPhoneNumber->getUcrmClientNumber($notificationData); //$clientPhoneNumber = $this->clientPhoneNumber->getUcrmClientNumber($notificationData);
$clientPhoneNumber = $this->validarNumeroTelefono($phoneToNotify); //Obtiene el número de celular del cliente que sea del tipo de contacto "WhatsApp" $clientPhoneNumber = $this->validarNumeroTelefono($phoneToNotify); //Obtiene el número de celular del cliente que sea del tipo de contacto "WhatsApp"
//$this->logger->debug("Numero de cel obtenido " . $clientPhoneNumber . PHP_EOL); //$this->logger->debug("Numero de cel obtenido " . $clientPhoneNumber . PHP_EOL);
@ -695,15 +740,15 @@ abstract class AbstractMessageNotifierFacade
if ($notificationTypeText) { if ($notificationTypeText) {
try { try {
$attempts = 0; $attempts = 0;
$maxAttempts = 3; $maxAttempts = 3;
$result = false; $result = false;
while ($attempts < $maxAttempts && ! $result) { while ($attempts < $maxAttempts && !$result) {
$attempts++; $attempts++;
$result = $client_callbell_api->sendTextPaymentNotificationWhatsApp($clientPhoneNumber, $notificationData); $result = $client_callbell_api->sendTextPaymentNotificationWhatsApp($clientPhoneNumber, $notificationData);
if (! $result) { if (!$result) {
$this->logger->warning("Intento $attempts fallido para enviar notificación de texto al cliente con número $clientPhoneNumber." . PHP_EOL); $this->logger->warning("Intento $attempts fallido para enviar notificación de texto al cliente con número $clientPhoneNumber." . PHP_EOL);
} }
} }
@ -719,15 +764,15 @@ abstract class AbstractMessageNotifierFacade
} else { } else {
try { try {
$attempts = 0; $attempts = 0;
$maxAttempts = 3; $maxAttempts = 3;
$result = false; $result = false;
while ($attempts < $maxAttempts && ! $result) { while ($attempts < $maxAttempts && !$result) {
$attempts++; $attempts++;
$result = $client_callbell_api->sendPaymentNotificationWhatsApp($clientPhoneNumber, $notificationData); $result = $client_callbell_api->sendPaymentNotificationWhatsApp($clientPhoneNumber, $notificationData);
if (! $result) { if (!$result) {
$this->logger->warning("Intento $attempts fallido para enviar notificación al cliente con número $clientPhoneNumber." . PHP_EOL); $this->logger->warning("Intento $attempts fallido para enviar notificación al cliente con número $clientPhoneNumber." . PHP_EOL);
} }
} }
@ -766,11 +811,11 @@ abstract class AbstractMessageNotifierFacade
// $this->logger->info("Valor de notification client data export: " . $notification_client_data_export . PHP_EOL); // $this->logger->info("Valor de notification client data export: " . $notification_client_data_export . PHP_EOL);
//$this->logger->debug("Creando instancia callbell ".PHP_EOL); //$this->logger->debug("Creando instancia callbell ".PHP_EOL);
$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
$IPServer = $config['ipserver']; $IPServer = $config['ipserver'];
$UCRMAPIToken = $config['apitoken']; $UCRMAPIToken = $config['apitoken'];
$CallBellAPIToken = $config['tokencallbell']; $CallBellAPIToken = $config['tokencallbell'];
$notificationTypeText = $config['notificationTypeText']; $notificationTypeText = $config['notificationTypeText'];
$client_callbell_api = new ClientCallBellAPI($UCRMAPIToken, $IPServer, $CallBellAPIToken); $client_callbell_api = new ClientCallBellAPI($UCRMAPIToken, $IPServer, $CallBellAPIToken);
@ -844,10 +889,10 @@ abstract class AbstractMessageNotifierFacade
// $this->logger->info("Valor de notification client data export: " . $notification_client_data_export . PHP_EOL); // $this->logger->info("Valor de notification client data export: " . $notification_client_data_export . PHP_EOL);
//$this->logger->debug("Creando instancia callbell ".PHP_EOL); //$this->logger->debug("Creando instancia callbell ".PHP_EOL);
$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
$IPServer = $config['ipserver']; $IPServer = $config['ipserver'];
$UCRMAPIToken = $config['apitoken']; $UCRMAPIToken = $config['apitoken'];
$CallBellAPIToken = $config['tokencallbell']; $CallBellAPIToken = $config['tokencallbell'];
$client_callbell_api = new ClientCallBellAPI($UCRMAPIToken, $IPServer, $CallBellAPIToken); $client_callbell_api = new ClientCallBellAPI($UCRMAPIToken, $IPServer, $CallBellAPIToken);
@ -895,15 +940,15 @@ abstract class AbstractMessageNotifierFacade
// $this->logger->info("Valor de notification client data export: " . $notification_client_data_export . PHP_EOL); // $this->logger->info("Valor de notification client data export: " . $notification_client_data_export . PHP_EOL);
$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
$IPServer = $config['ipserver']; $IPServer = $config['ipserver'];
$UCRMAPIToken = $config['apitoken']; $UCRMAPIToken = $config['apitoken'];
$CallBellAPIToken = $config['tokencallbell']; $CallBellAPIToken = $config['tokencallbell'];
$StripeToken = $config['tokenstripe']; $StripeToken = $config['tokenstripe'];
$attributes = $notificationData->clientData['attributes']; //Obtener los atributos del cliente $attributes = $notificationData->clientData['attributes']; //Obtener los atributos del cliente
// Variable para almacenar los valores de los atributos que comienzan con "clabe" // Variable para almacenar los valores de los atributos que comienzan con "clabe"
// Iterar sobre los atributoss // Iterar sobre los atributoss
foreach ($attributes as $attribute) { foreach ($attributes as $attribute) {
@ -912,7 +957,7 @@ abstract class AbstractMessageNotifierFacade
// Agregar el valor al array $clabeValues // Agregar el valor al array $clabeValues
$customerStripeID = $attribute['value']; $customerStripeID = $attribute['value'];
} else if (strpos($attribute['key'], 'clabe') === 0) { // Verificar si la "key" comienza con "clabe" } else if (strpos($attribute['key'], 'clabe') === 0) { // Verificar si la "key" comienza con "clabe"
// Agregar el valor al array $clabeValues // Agregar el valor al array $clabeValues
$clabeInterbancaria = $attribute['value']; $clabeInterbancaria = $attribute['value'];
} }
@ -957,7 +1002,7 @@ abstract class AbstractMessageNotifierFacade
//$this->sendWhatsApp($notificationData, $clientSmsNumber); //$this->sendWhatsApp($notificationData, $clientSmsNumber);
//$client_callbell_api->sendMessageWhatsApp($clientPhoneNumber, $notificationData); //$client_callbell_api->sendMessageWhatsApp($clientPhoneNumber, $notificationData);
$client_callbell_api = new ClientCallBellAPI($UCRMAPIToken, $IPServer, $CallBellAPIToken); $client_callbell_api = new ClientCallBellAPI($UCRMAPIToken, $IPServer, $CallBellAPIToken);
$response_getContactCallBell = json_decode($client_callbell_api->getContactWhatsapp($clientPhoneNumber), true); $response_getContactCallBell = json_decode($client_callbell_api->getContactWhatsapp($clientPhoneNumber), true);
//$this->logger->debug('Se hizo la petición al callbell para obtener el uuid' . PHP_EOL); //$this->logger->debug('Se hizo la petición al callbell para obtener el uuid' . PHP_EOL);
$client_callbell_api->patchWhatsapp($response_getContactCallBell, $notificationData, $clabeInterbancaria); $client_callbell_api->patchWhatsapp($response_getContactCallBell, $notificationData, $clabeInterbancaria);
@ -992,14 +1037,14 @@ abstract class AbstractMessageNotifierFacade
//$this->logger->info("client id " .$clientID. PHP_EOL); //$this->logger->info("client id " .$clientID. PHP_EOL);
$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
$IPServer = $config['ipserver']; $IPServer = $config['ipserver'];
$UCRMAPIToken = $config['apitoken']; $UCRMAPIToken = $config['apitoken'];
$CallBellAPIToken = $config['tokencallbell']; $CallBellAPIToken = $config['tokencallbell'];
$clientPhoneNumber = $this->validarNumeroTelefono($phoneToUpdate); //Obtiene el número de celular del cliente que sea del tipo de contacto "WhatsApp" $clientPhoneNumber = $this->validarNumeroTelefono($phoneToUpdate); //Obtiene el número de celular del cliente que sea del tipo de contacto "WhatsApp"
//$this->logger->info("Número de telefono obtenido para actualizar:" .$clientPhoneNumber. PHP_EOL); //$this->logger->info("Número de telefono obtenido para actualizar:" .$clientPhoneNumber. PHP_EOL);
if (empty($clientPhoneNumber)) { if (empty($clientPhoneNumber)) {
$this->logger->warning('No se encontró un teléfono celular válido para el cliente: ' . $notificationData->clientId); $this->logger->warning('No se encontró un teléfono celular válido para el cliente: ' . $notificationData->clientId);
@ -1011,7 +1056,7 @@ abstract class AbstractMessageNotifierFacade
//$this->sendMessage($notificationData, $clientSmsNumber, $messageBody); //$this->sendMessage($notificationData, $clientSmsNumber, $messageBody);
//$this->sendWhatsApp($notificationData, $clientSmsNumber); //$this->sendWhatsApp($notificationData, $clientSmsNumber);
$client_callbell_api = new ClientCallBellAPI($UCRMAPIToken, $IPServer, $CallBellAPIToken); $client_callbell_api = new ClientCallBellAPI($UCRMAPIToken, $IPServer, $CallBellAPIToken);
$response_getContactCallBell = json_decode($client_callbell_api->getContactWhatsapp($clientPhoneNumber), true); $response_getContactCallBell = json_decode($client_callbell_api->getContactWhatsapp($clientPhoneNumber), true);
$client_callbell_api->patchServiceStatusWhatsApp($response_getContactCallBell, $notificationData); $client_callbell_api->patchServiceStatusWhatsApp($response_getContactCallBell, $notificationData);
@ -1079,11 +1124,11 @@ abstract class AbstractMessageNotifierFacade
function patchClientCustomAttribute($clientId, $attributeId, $value): bool function patchClientCustomAttribute($clientId, $attributeId, $value): bool
{ {
$logger = \Ubnt\UcrmPluginSdk\Service\PluginLogManager::create(); $logger = \Ubnt\UcrmPluginSdk\Service\PluginLogManager::create();
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create(); $configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
$config = $configManager->loadConfig(); $config = $configManager->loadConfig();
$ucrmBaseUri = $config['ipserver']; $ucrmBaseUri = $config['ipserver'];
$authToken = $config['apitoken']; $authToken = $config['apitoken'];
$ucrmBaseUri = 'https://' . $ucrmBaseUri . '/crm/api/v1.0/'; $ucrmBaseUri = 'https://' . $ucrmBaseUri . '/crm/api/v1.0/';
$clientguzz = new Client(); //instancia de cliente GuzzleHttp para consumir API UISP CRM $clientguzz = new Client(); //instancia de cliente GuzzleHttp para consumir API UISP CRM
@ -1107,10 +1152,10 @@ abstract class AbstractMessageNotifierFacade
'X-Auth-Token' => $authToken, 'X-Auth-Token' => $authToken,
'Content-Type' => 'application/json', 'Content-Type' => 'application/json',
], ],
'body' => $json_data_patch, 'body' => $json_data_patch,
'verify' => false, // Deshabilitar la verificación del certificado SSL 'verify' => false, // Deshabilitar la verificación del certificado SSL
], ],
); );
//evaluar el código de respuesta HTTP y si es 200 se retorna true //evaluar el código de respuesta HTTP y si es 200 se retorna true
if ($responseCRM->getStatusCode() === 200) { if ($responseCRM->getStatusCode() === 200) {
@ -1126,15 +1171,15 @@ abstract class AbstractMessageNotifierFacade
$this->logger->info("Error al hacer el patch al CRM: " . $error->getMessage() . PHP_EOL); $this->logger->info("Error al hacer el patch al CRM: " . $error->getMessage() . PHP_EOL);
return false; // Return false if patch fails return false; // Return false if patch fails
} }
} }
function getVaultCredentials($dataToSearch): string function getVaultCredentials($dataToSearch): string
{ {
$logger = \Ubnt\UcrmPluginSdk\Service\PluginLogManager::create(); $logger = \Ubnt\UcrmPluginSdk\Service\PluginLogManager::create();
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create(); $configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
$config = $configManager->loadConfig(); $config = $configManager->loadConfig();
$ucrmBaseUri = $config['ipserver']; $ucrmBaseUri = $config['ipserver'];
$authToken = $config['apitoken']; $authToken = $config['apitoken'];
if ($ucrmBaseUri === '172.16.5.134') { //opción solo para el servidor de pruebas if ($ucrmBaseUri === '172.16.5.134') { //opción solo para el servidor de pruebas
return 'gYAIEK:Be}SK*01z5+/V'; return 'gYAIEK:Be}SK*01z5+/V';
@ -1147,19 +1192,19 @@ abstract class AbstractMessageNotifierFacade
// Crear una instancia del cliente Guzzle // Crear una instancia del cliente Guzzle
$clientUnms = new Client([ $clientUnms = new Client([
'base_uri' => $unmsBaseUri, 'base_uri' => $unmsBaseUri,
'verify' => false, // Deshabilitar la verificación del certificado SSL 'verify' => false, // Deshabilitar la verificación del certificado SSL
]); ]);
$clientUcrm = new Client([ $clientUcrm = new Client([
'base_uri' => $ucrmBaseUri, 'base_uri' => $ucrmBaseUri,
'verify' => false, // Deshabilitar la verificación del certificado SSL 'verify' => false, // Deshabilitar la verificación del certificado SSL
]); ]);
//validar si dataToSearch es una dirección IP o una dirección MAC //validar si dataToSearch es una dirección IP o una dirección MAC
if (filter_var($dataToSearch, FILTER_VALIDATE_IP)) { if (filter_var($dataToSearch, FILTER_VALIDATE_IP)) {
// La variable es una dirección IP válida // La variable es una dirección IP válida
// $logger->appendLog('Consulta por dirección IP: ' . $dataToSearch); // $logger->appendLog('Consulta por dirección IP: ' . $dataToSearch);
print('Consulta por dirección IP: ' . $dataToSearch . PHP_EOL); print ('Consulta por dirección IP: ' . $dataToSearch . PHP_EOL);
$IpAddressClientId = filter_var($dataToSearch, FILTER_VALIDATE_IP); $IpAddressClientId = filter_var($dataToSearch, FILTER_VALIDATE_IP);
@ -1172,7 +1217,7 @@ abstract class AbstractMessageNotifierFacade
if ($responseSitesByIP->getStatusCode() === 200) { if ($responseSitesByIP->getStatusCode() === 200) {
$datasSitesByIP = json_decode((string) $responseSitesByIP->getBody(), true); $datasSitesByIP = json_decode((string) $responseSitesByIP->getBody(), true);
$jsonDevicesBySite = json_encode($datasSitesByIP, JSON_PRETTY_PRINT); $jsonDevicesBySite = json_encode($datasSitesByIP, JSON_PRETTY_PRINT);
//print_r($jsonDevicesBySite . PHP_EOL); //Devices por ID del sitio //print_r($jsonDevicesBySite . PHP_EOL); //Devices por ID del sitio
@ -1263,9 +1308,9 @@ abstract class AbstractMessageNotifierFacade
} catch (RequestException $requestException) { } catch (RequestException $requestException) {
// Manejar errores de la solicitud, si hay error 404 entonces responder que no se encontró niguna IP asociada a alguna antena o dispositivo de red // Manejar errores de la solicitud, si hay error 404 entonces responder que no se encontró niguna IP asociada a alguna antena o dispositivo de red
if ($requestException->hasResponse()) { if ($requestException->hasResponse()) {
$response = $requestException->getResponse(); $response = $requestException->getResponse();
$statusCode = $response->getStatusCode(); $statusCode = $response->getStatusCode();
$reason = $response->getReasonPhrase(); $reason = $response->getReasonPhrase();
// echo "Error: {$statusCode} - {$reason}" . PHP_EOL; // echo "Error: {$statusCode} - {$reason}" . PHP_EOL;
// echo $response->getBody(); // echo $response->getBody();
if ($statusCode == 404) { if ($statusCode == 404) {
@ -1287,7 +1332,7 @@ abstract class AbstractMessageNotifierFacade
} else if (preg_match('/^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/', $dataToSearch)) { } else if (preg_match('/^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/', $dataToSearch)) {
// La variable es una dirección MAC válida // La variable es una dirección MAC válida
// $logger->appendLog('Consulta por dirección MAC: ' . $dataToSearch); // $logger->appendLog('Consulta por dirección MAC: ' . $dataToSearch);
print('Consulta por dirección MAC: ' . $dataToSearch . PHP_EOL); print ('Consulta por dirección MAC: ' . $dataToSearch . PHP_EOL);
try { try {
// //para mandarla al endpoint de dispositivos por MAC se necesita convertir la cadena de la direccion mac en un formato como el siguiente ejemplo: para la dirección mac 60:22:32:c8:b2:c3 quedaría como 60%3A22%3A32%3Ac8%3Ab2%3Ac3 // //para mandarla al endpoint de dispositivos por MAC se necesita convertir la cadena de la direccion mac en un formato como el siguiente ejemplo: para la dirección mac 60:22:32:c8:b2:c3 quedaría como 60%3A22%3A32%3Ac8%3Ab2%3Ac3
@ -1351,9 +1396,9 @@ abstract class AbstractMessageNotifierFacade
} catch (RequestException $requestException) { } catch (RequestException $requestException) {
// Manejar errores de la solicitud, si hay error 404 entonces responder que no se encontró niguna MAC asociada a alguna antena o dispositivo de red // Manejar errores de la solicitud, si hay error 404 entonces responder que no se encontró niguna MAC asociada a alguna antena o dispositivo de red
if ($requestException->hasResponse()) { if ($requestException->hasResponse()) {
$response = $requestException->getResponse(); $response = $requestException->getResponse();
$statusCode = $response->getStatusCode(); $statusCode = $response->getStatusCode();
$reason = $response->getReasonPhrase(); $reason = $response->getReasonPhrase();
// echo "Error: {$statusCode} - {$reason}" . PHP_EOL; // echo "Error: {$statusCode} - {$reason}" . PHP_EOL;
// echo $response->getBody(); // echo $response->getBody();
if ($statusCode == 404) { if ($statusCode == 404) {
@ -1389,14 +1434,14 @@ abstract class AbstractMessageNotifierFacade
} catch (RequestException $requestException) { } catch (RequestException $requestException) {
// Manejar errores de la solicitud // Manejar errores de la solicitud
if ($requestException->hasResponse()) { if ($requestException->hasResponse()) {
$response = $requestException->getResponse(); $response = $requestException->getResponse();
$statusCode = $response->getStatusCode(); $statusCode = $response->getStatusCode();
$reason = $response->getReasonPhrase(); $reason = $response->getReasonPhrase();
//si el statusCode es 404 significa que no se encontró el cliente //si el statusCode es 404 significa que no se encontró el cliente
if ($statusCode == 404) { if ($statusCode == 404) {
echo "No se encontró el cliente con el ID proporcionado." . PHP_EOL; echo "No se encontró el cliente con el ID proporcionado." . PHP_EOL;
$logger->appendLog('No se encontró el cliente con el ID proporcionado: ' . $IpAddressClientId); $logger->appendLog('No se encontró el cliente con el ID proporcionado: ' . $IpAddressClientId);
// print_r('No se encontró el cliente con el ID proporcionado: ' . $IpAddressClientId . PHP_EOL); // print_r('No se encontró el cliente con el ID proporcionado: ' . $IpAddressClientId . PHP_EOL);
return 'Error: No se encontró el cliente con el ID proporcionado: ' . $IpAddressClientId; // Return early if the client is not found return 'Error: No se encontró el cliente con el ID proporcionado: ' . $IpAddressClientId; // Return early if the client is not found
} }
return 'Error: ' . $reason; // Return early if the request fails return 'Error: ' . $reason; // Return early if the request fails
@ -1404,7 +1449,7 @@ abstract class AbstractMessageNotifierFacade
} else { } else {
// echo "Error: " . $requestException->getMessage() . PHP_EOL; // echo "Error: " . $requestException->getMessage() . PHP_EOL;
$logger->appendLog('Error: ' . $requestException->getMessage()); $logger->appendLog('Error: ' . $requestException->getMessage());
// print_r('Error: ' . $requestException->getMessage() . PHP_EOL); // print_r('Error: ' . $requestException->getMessage() . PHP_EOL);
return 'Error: ' . $requestException->getMessage(); // Return early if the request fails return 'Error: ' . $requestException->getMessage(); // Return early if the request fails
} }
@ -1420,7 +1465,7 @@ abstract class AbstractMessageNotifierFacade
} else { } else {
// echo "No se encontraron servicios para el cliente proporcionado." . PHP_EOL; // echo "No se encontraron servicios para el cliente proporcionado." . PHP_EOL;
$logger->appendLog('No se encontraron servicios para el cliente proporcionado: ' . $IpAddressClientId); $logger->appendLog('No se encontraron servicios para el cliente proporcionado: ' . $IpAddressClientId);
// print_r('No se encontraron servicios para el cliente proporcionado: ' . $IpAddressClientId . PHP_EOL); // print_r('No se encontraron servicios para el cliente proporcionado: ' . $IpAddressClientId . PHP_EOL);
return "Error: No se encontraron servicios para el cliente proporcionado: " . $IpAddressClientId; // Return early if no services are found return "Error: No se encontraron servicios para el cliente proporcionado: " . $IpAddressClientId; // Return early if no services are found
} }
@ -1440,14 +1485,14 @@ abstract class AbstractMessageNotifierFacade
} catch (RequestException $requestException) { } catch (RequestException $requestException) {
// Manejar errores de la solicitud // Manejar errores de la solicitud
if ($requestException->hasResponse()) { if ($requestException->hasResponse()) {
$response = $requestException->getResponse(); $response = $requestException->getResponse();
$statusCode = $response->getStatusCode(); $statusCode = $response->getStatusCode();
$reason = $response->getReasonPhrase(); $reason = $response->getReasonPhrase();
//si el statusCode es 404 significa que no se encontró el cliente //si el statusCode es 404 significa que no se encontró el cliente
if ($statusCode == 404) { if ($statusCode == 404) {
// echo "No se encontró el cliente con el ID proporcionado." . PHP_EOL; // echo "No se encontró el cliente con el ID proporcionado." . PHP_EOL;
$logger->appendLog('No se encontró el cliente con el ID proporcionado: ' . $IpAddressClientId); $logger->appendLog('No se encontró el cliente con el ID proporcionado: ' . $IpAddressClientId);
// print_r('No se encontró el devicie con el ID proporcionado: ' . $IpAddressClientId . PHP_EOL); // print_r('No se encontró el devicie con el ID proporcionado: ' . $IpAddressClientId . PHP_EOL);
return 'Error: No se encontró el devicie con el ID proporcionado: ' . $IpAddressClientId; // Return early if the client is not found return 'Error: No se encontró el devicie con el ID proporcionado: ' . $IpAddressClientId; // Return early if the client is not found
} }
return 'Error: ' . $reason; // Return early if the request fails return 'Error: ' . $reason; // Return early if the request fails
@ -1455,7 +1500,7 @@ abstract class AbstractMessageNotifierFacade
} else { } else {
// echo "Error: " . $requestException->getMessage() . PHP_EOL; // echo "Error: " . $requestException->getMessage() . PHP_EOL;
$logger->appendLog('Error: ' . $requestException->getMessage()); $logger->appendLog('Error: ' . $requestException->getMessage());
// print_r('Error: ' . $requestException->getMessage() . PHP_EOL); // print_r('Error: ' . $requestException->getMessage() . PHP_EOL);
return 'Error: ' . $requestException->getMessage(); // Return early if the request fails return 'Error: ' . $requestException->getMessage(); // Return early if the request fails
} }
@ -1472,18 +1517,18 @@ abstract class AbstractMessageNotifierFacade
//verificar con iiset si existe la clave 'identification' y 'apDevice' en el primer elemento del array //verificar con iiset si existe la clave 'identification' y 'apDevice' en el primer elemento del array
if (isset($dataDevicesBySite[0]['identification']) && isset($dataDevicesBySite[0]['attributes']['apDevice'])) { if (isset($dataDevicesBySite[0]['identification']) && isset($dataDevicesBySite[0]['attributes']['apDevice'])) {
$idClientDevice = $dataDevicesBySite[0]['identification']['id']; $idClientDevice = $dataDevicesBySite[0]['identification']['id'];
$deviceID = $dataDevicesBySite[0]['attributes']['apDevice']['id']; $deviceID = $dataDevicesBySite[0]['attributes']['apDevice']['id'];
} else { } else {
// echo "No se encontró la clave 'identification' o 'apDevice' en la respuesta." . PHP_EOL; // echo "No se encontró la clave 'identification' o 'apDevice' en la respuesta." . PHP_EOL;
$logger->appendLog('No se encontró la clave \'identification\' o \'apDevice\' en la respuesta.'); $logger->appendLog('No se encontró la clave \'identification\' o \'apDevice\' en la respuesta.');
// print_r('Este cliente es un repetidor.' . PHP_EOL); // print_r('Este cliente es un repetidor.' . PHP_EOL);
return "Este cliente es un repetidor."; // Return early if the key is not found return "Este cliente es un repetidor."; // Return early if the key is not found
} }
} else { } else {
// echo "No se encontraron dispositivos para el sitio proporcionado." . PHP_EOL; // echo "No se encontraron dispositivos para el sitio proporcionado." . PHP_EOL;
$logger->appendLog('No se encontraron dispositivos para el sitio proporcionado: ' . $unmsSiteID); $logger->appendLog('No se encontraron dispositivos para el sitio proporcionado: ' . $unmsSiteID);
// print_r('No se encontraron dispositivos para el sitio proporcionado: ' . $unmsSiteID . PHP_EOL); // print_r('No se encontraron dispositivos para el sitio proporcionado: ' . $unmsSiteID . PHP_EOL);
return "Error: No se encontraron dispositivos para el sitio proporcionado."; // Return early if no devices are found return "Error: No se encontraron dispositivos para el sitio proporcionado."; // Return early if no devices are found
} }
@ -1503,14 +1548,14 @@ abstract class AbstractMessageNotifierFacade
} catch (RequestException $requestException) { } catch (RequestException $requestException) {
// Manejar errores de la solicitud // Manejar errores de la solicitud
if ($requestException->hasResponse()) { if ($requestException->hasResponse()) {
$response = $requestException->getResponse(); $response = $requestException->getResponse();
$statusCode = $response->getStatusCode(); $statusCode = $response->getStatusCode();
$reason = $response->getReasonPhrase(); $reason = $response->getReasonPhrase();
//si el statusCode es 404 significa que no se encontró el cliente //si el statusCode es 404 significa que no se encontró el cliente
if ($statusCode == 404) { if ($statusCode == 404) {
// echo "No se encontró el cliente con el ID proporcionado." . PHP_EOL; // echo "No se encontró el cliente con el ID proporcionado." . PHP_EOL;
$logger->appendLog('No se encontró el cliente con el ID proporcionado: ' . $IpAddressClientId); $logger->appendLog('No se encontró el cliente con el ID proporcionado: ' . $IpAddressClientId);
// print_r('No se encontró el device con el ID proporcionado: ' . $IpAddressClientId . PHP_EOL); // print_r('No se encontró el device con el ID proporcionado: ' . $IpAddressClientId . PHP_EOL);
return 'Error: No se encontró el device con el ID proporcionado: ' . $IpAddressClientId; // Return early if the client is not found return 'Error: No se encontró el device con el ID proporcionado: ' . $IpAddressClientId; // Return early if the client is not found
} }
return 'Error: ' . $reason; // Return early if the request fails return 'Error: ' . $reason; // Return early if the request fails
@ -1518,7 +1563,7 @@ abstract class AbstractMessageNotifierFacade
} else { } else {
// echo "Error: " . $requestException->getMessage() . PHP_EOL; // echo "Error: " . $requestException->getMessage() . PHP_EOL;
$logger->appendLog('Error: ' . $requestException->getMessage()); $logger->appendLog('Error: ' . $requestException->getMessage());
// print_r('Error: ' . $requestException->getMessage() . PHP_EOL); // print_r('Error: ' . $requestException->getMessage() . PHP_EOL);
return 'Error: ' . $requestException->getMessage(); // Return early if the request fails return 'Error: ' . $requestException->getMessage(); // Return early if the request fails
} }
@ -1540,14 +1585,14 @@ abstract class AbstractMessageNotifierFacade
} catch (RequestException $requestException) { } catch (RequestException $requestException) {
// Manejar errores de la solicitud // Manejar errores de la solicitud
if ($requestException->hasResponse()) { if ($requestException->hasResponse()) {
$response = $requestException->getResponse(); $response = $requestException->getResponse();
$statusCode = $response->getStatusCode(); $statusCode = $response->getStatusCode();
$reason = $response->getReasonPhrase(); $reason = $response->getReasonPhrase();
//si el statusCode es 404 significa que no se encontró el cliente //si el statusCode es 404 significa que no se encontró el cliente
if ($statusCode == 404) { if ($statusCode == 404) {
// echo "No se encontró el cliente con el ID proporcionado." . PHP_EOL; // echo "No se encontró el cliente con el ID proporcionado." . PHP_EOL;
$logger->appendLog('No se encontró el cliente con el ID proporcionado: ' . $IpAddressClientId); $logger->appendLog('No se encontró el cliente con el ID proporcionado: ' . $IpAddressClientId);
// print_r('No se encontró el device con el ID proporcionado: ' . $IpAddressClientId . PHP_EOL); // print_r('No se encontró el device con el ID proporcionado: ' . $IpAddressClientId . PHP_EOL);
return 'Error: No se encontró el device con el ID proporcionado: ' . $IpAddressClientId; // Return early if the client is not found return 'Error: No se encontró el device con el ID proporcionado: ' . $IpAddressClientId; // Return early if the client is not found
} }
return 'Error: ' . $reason; // Return early if the request fails return 'Error: ' . $reason; // Return early if the request fails
@ -1555,7 +1600,7 @@ abstract class AbstractMessageNotifierFacade
} else { } else {
// echo "Error: " . $requestException->getMessage() . PHP_EOL; // echo "Error: " . $requestException->getMessage() . PHP_EOL;
$logger->appendLog('Error: ' . $requestException->getMessage()); $logger->appendLog('Error: ' . $requestException->getMessage());
// print_r('Error: ' . $requestException->getMessage() . PHP_EOL); // print_r('Error: ' . $requestException->getMessage() . PHP_EOL);
return 'Error: ' . $requestException->getMessage(); // Return early if the request fails return 'Error: ' . $requestException->getMessage(); // Return early if the request fails
} }
} }
@ -1569,21 +1614,21 @@ abstract class AbstractMessageNotifierFacade
} else { } else {
// echo "No se encontró la contraseña en la respuesta de la API." . PHP_EOL; // echo "No se encontró la contraseña en la respuesta de la API." . PHP_EOL;
$logger->appendLog('No se encontró una contraseña en la bóveda para la antena de este cliente, es altamente probable que conserve una contraseña conocida.'); $logger->appendLog('No se encontró una contraseña en la bóveda para la antena de este cliente, es altamente probable que conserve una contraseña conocida.');
// print_r('No se encontró una contraseña en la bóveda para la antena de este cliente, es altamente probable que conserve una contraseña conocida.' . PHP_EOL); // print_r('No se encontró una contraseña en la bóveda para la antena de este cliente, es altamente probable que conserve una contraseña conocida.' . PHP_EOL);
return "Error: No se encontró una contraseña en la bóveda para la antena de este cliente, es altamente probable que conserve una contraseña conocida."; // Return early if the password is not found return "Error: No se encontró una contraseña en la bóveda para la antena de este cliente, es altamente probable que conserve una contraseña conocida."; // Return early if the password is not found
} }
} else { } else {
// echo "Error en la solicitud. Código de estado HTTP: " . $responsePasswordVault->getStatusCode() . PHP_EOL; // echo "Error en la solicitud. Código de estado HTTP: " . $responsePasswordVault->getStatusCode() . PHP_EOL;
$logger->appendLog('Error en la solicitud. Código de estado HTTP: ' . $responsePasswordVault->getStatusCode()); $logger->appendLog('Error en la solicitud. Código de estado HTTP: ' . $responsePasswordVault->getStatusCode());
// print_r('Error en la solicitud. Código de estado HTTP: ' . $responsePasswordVault->getStatusCode() . PHP_EOL); // print_r('Error en la solicitud. Código de estado HTTP: ' . $responsePasswordVault->getStatusCode() . PHP_EOL);
return 'Error: Falla en la solicitud. Código de estado HTTP: ' . $responsePasswordVault->getStatusCode(); // Return early if the request fails return 'Error: Falla en la solicitud. Código de estado HTTP: ' . $responsePasswordVault->getStatusCode(); // Return early if the request fails
} }
} else { } else {
// echo "Error en la solicitud. Código de estado HTTP: " . $responseDevicesBySite->getStatusCode() . PHP_EOL; // echo "Error en la solicitud. Código de estado HTTP: " . $responseDevicesBySite->getStatusCode() . PHP_EOL;
$logger->appendLog('Error en la solicitud. Código de estado HTTP: ' . $responseDevicesBySite->getStatusCode()); $logger->appendLog('Error en la solicitud. Código de estado HTTP: ' . $responseDevicesBySite->getStatusCode());
// print_r('Error en la solicitud. Código de estado HTTP: ' . $responseDevicesBySite->getStatusCode() . PHP_EOL); // print_r('Error en la solicitud. Código de estado HTTP: ' . $responseDevicesBySite->getStatusCode() . PHP_EOL);
return 'Error: Falla en la solicitud. Código de estado HTTP: ' . $responseDevicesBySite->getStatusCode(); // Return early if the request fails return 'Error: Falla en la solicitud. Código de estado HTTP: ' . $responseDevicesBySite->getStatusCode(); // Return early if the request fails
} }

View File

@ -57,13 +57,14 @@ class ClientCallBellAPI
$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)
{ {
@ -118,7 +119,7 @@ class ClientCallBellAPI
// $log->appendLog("Datos de la notificación de trabajo: " . $jsonJobNotificationData . PHP_EOL); // $log->appendLog("Datos de la notificación de trabajo: " . $jsonJobNotificationData . PHP_EOL);
// --- ¡AÑADE ESTAS LÍNEAS PARA CONVERTIR A BOOLEANO REAL! --- // --- ¡AÑADE ESTAS LÍNEAS PARA CONVERTIR A BOOLEANO REAL! ---
$reprogramming = filter_var($reprogramming, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); $reprogramming = filter_var($reprogramming, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
$changeInstaller = filter_var($changeInstaller, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); $changeInstaller = filter_var($changeInstaller, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
// ----------------------------------------------------------- // -----------------------------------------------------------
@ -134,37 +135,52 @@ 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']); if ($changeInstaller && !$reprogramming) {
$campo3 = sprintf('%s', $jobNotificationData['date']); $campo2 = sprintf('se ha hecho un cambio de técnico 👷🏻‍♂️🔄 para su visita con el folio *#️⃣%s*', $jobNotificationData['jobId']);
$campo4 = sprintf('*%s*', $jobNotificationData['installerName']); } else {
$campo2 = sprintf('*#️⃣%s*', $jobNotificationData['jobId']);
}
$campo3 = '🗓️ ' . sprintf('%s', $jobNotificationData['date']);
if ($changeInstaller && $reprogramming) {
$campo4 = 'Además se ha hecho un cambio de técnico por el siguiente 👷🏻‍♂️➡️ ' . sprintf('*%s*', $jobNotificationData['installerName']);
} else {
$campo4 = '👷🏻‍♂️➡️ ' . sprintf('*%s*', $jobNotificationData['installerName']);
}
$campo5 = "asegúrese de que alguien esté presente en el domicilio 🏠 para permitir el acceso y confirme su disponibilidad.";
$log->appendLog("DEBUG: Valores antes de la estructura IF - Reprogramming: " . var_export($reprogramming, true) . ", ChangeInstaller: " . var_export($changeInstaller, true) . PHP_EOL); $log->appendLog("DEBUG: Valores antes de la estructura IF - Reprogramming: " . var_export($reprogramming, true) . ", ChangeInstaller: " . var_export($changeInstaller, true) . PHP_EOL);
if ($reprogramming && ! $changeInstaller) { if ($reprogramming && !$changeInstaller) {
//{{1}}, se ha reprogramado su visita técnica con el folio {{2}}
$campo3 = '🗓️➡️ ' . sprintf('%s', $jobNotificationData['date']);
$campo1_combinado = "Estimado cliente $campo1 se ha reprogramado su visita técnica con folio $campo2";
// Case: true, false // 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\": \"323631bf578e43fb8a0095f55978aae8\",\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_combinado\", \"$campo3\", \"$campo4\", \"$campo5\"],\n \"template_uuid\": \"715eed9d6f2d4d90853f25e296202e00\",\n \"optin_contact\": true\n }";
} else if (! $reprogramming && $changeInstaller) { } else if (!$reprogramming && $changeInstaller) {
// Case: false, true // 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\": \"c59c3ce2c9c6439b941b0d42d1435605\",\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\", \"$campo5\"],\n \"template_uuid\": \"d684e6fa2ba24593a86c98be1815831d\",\n \"optin_contact\": true\n }";
} else if (! $reprogramming && ! $changeInstaller) { // <--- Ahora este else if está correctamente encadenado } else if (!$reprogramming && !$changeInstaller) { // <--- Ahora este else if está correctamente encadenado
// Case: false, false // Case: false, false
//Enviar notificación normal de visita técnica al cliente //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\", \"$campo5\"],\n \"template_uuid\": \"07cfbc6e394044608485b530a27177d0\",\n \"optin_contact\": true\n }";
}else if ($reprogramming && $changeInstaller) { // <--- Ahora este else if está correctamente encadenado } else if ($reprogramming && $changeInstaller) { // <--- Ahora este else if está correctamente encadenado
// Case: true, true // Case: true, true
//Enviar notificación de cambio de instalador y reprogramación al cliente //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); $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 }"; $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\", \"$campo5\"],\n \"template_uuid\": \"145885d15323414f978f1e3f249c2ae1\",\n \"optin_contact\": true\n }";
} else { } else {
// Case: true, true (la única combinación restante con booleanos) // 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); $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? // Decide qué hacer aquí, ¿Quizás devolver false? ¿O manejar esta combinación?
return false; // O el manejo adecuado para true/true return false; // O el manejo adecuado para true/true
} }
@ -211,7 +227,7 @@ class ClientCallBellAPI
$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! --- // --- ¡AÑADE ESTAS LÍNEAS PARA CONVERTIR A BOOLEANO REAL! ---
$reprogramming = filter_var($reprogramming, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); $reprogramming = filter_var($reprogramming, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
$changeInstaller = filter_var($changeInstaller, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); $changeInstaller = filter_var($changeInstaller, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
// ----------------------------------------------------------- // -----------------------------------------------------------
@ -227,39 +243,60 @@ class ClientCallBellAPI
'Content-Type: application/json', 'Content-Type: application/json',
]); ]);
$campo1 = $jobInstallerNotificationData['installerName']; $campo1 = '👷🏻‍♂️ ' . $jobInstallerNotificationData['installerName'];
if ($changeInstaller) { if (!$reprogramming && $changeInstaller) {
$campo2 = $jobInstallerNotificationData['subjectOfChange']; $campo2 = $jobInstallerNotificationData['subjectOfChange'];
$campo3 = sprintf("#%s", $jobInstallerNotificationData['jobId']); $campo3 = sprintf("#️⃣%s", $jobInstallerNotificationData['jobId']);
$campo4 = $jobInstallerNotificationData['clientFullName']; $campo4 = '👤 *Cliente:* ' . $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'];
$campo5 = $jobInstallerNotificationData['date']; $campo5 = '🗓️ ' . $jobInstallerNotificationData['date'];
$campo6 = $jobInstallerNotificationData['jobDescription']; $campo6 = '🛠️ ' . $jobInstallerNotificationData['jobDescription'];
$campo7 = $jobInstallerNotificationData['gmapsLocation']; $campo7 = '📌 ' . $jobInstallerNotificationData['gmapsLocation'];
$campo8 = $passwordAntenaCliente; $campo8 = '🔐 ' . $passwordAntenaCliente;
} }
if ($reprogramming && ! $changeInstaller) { if ($reprogramming && !$changeInstaller) {
$jobId = sprintf("#️⃣ *%s*", $jobInstallerNotificationData['jobId']);
$clientFullName = sprintf("👤 *%s*", $jobInstallerNotificationData['clientFullName']);
$date = sprintf("🗓️➡️ %s", $jobInstallerNotificationData['date']);
$installerName = sprintf("👷🏻‍♂️ *%s*", $jobInstallerNotificationData['installerName']);
$campo1_combinado = "$installerName se reprogramó una tarea con el folio $jobId para el cliente $clientFullName, la nueva fecha será el $date";
$campo2 = $jobInstallerNotificationData['clientWhatsApp'];
$campo3 = $jobInstallerNotificationData['gmapsLocation'];
$campo4 = $passwordAntenaCliente;
//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_combinado\", \"$campo2\", \"$campo3\", \"$campo4\"],\n \"template_uuid\": \"88eeb6420a214fd8870dd28d741021c4\",\n \"optin_contact\": true\n }";
} else if (! $reprogramming && $changeInstaller) { } else if (!$reprogramming && $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 anterior, 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 if ($reprogramming && $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 y notificación de reprogramación al instalador, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL); $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 }"; $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 if (!$reprogramming && !$changeInstaller) {
//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); //combinar el campo3, campo4, campo5, campo6, campo7 y campo8 en un solo campo con saltos de línea
$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 }"; $jobId = sprintf("#️⃣ *%s*", $jobInstallerNotificationData['jobId']);
$clientFullName = sprintf("👤 *%s*", $jobInstallerNotificationData['clientFullName']);
$date = sprintf("🗓️ %s", $jobInstallerNotificationData['date']);
$installerName = sprintf("👷🏻‍♂️ *%s*", $jobInstallerNotificationData['installerName']);
$campo1_combinado = "$installerName se te ha asignado una tarea con folio $jobId para el cliente $clientFullName, para el $date";
$campo2 = $jobInstallerNotificationData['clientWhatsApp'];
$campo3 = $jobInstallerNotificationData['gmapsLocation'];
$campo4 = $passwordAntenaCliente;
$log->appendLog("Enviando notificación normal 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_combinado\", \"$campo2\", \"$campo3\", \"$campo4\"],\n \"template_uuid\": \"88eeb6420a214fd8870dd28d741021c4\",\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);
@ -311,23 +348,23 @@ class ClientCallBellAPI
$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"
@ -343,11 +380,11 @@ 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 {
@ -359,7 +396,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) {
@ -369,7 +406,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;
} }
@ -402,8 +439,8 @@ class ClientCallBellAPI
} }
$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);
@ -463,18 +500,18 @@ 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 = '';
$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']) {
@ -525,11 +562,11 @@ class ClientCallBellAPI
$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',
] ]
@ -549,7 +586,7 @@ class ClientCallBellAPI
$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"
@ -565,7 +602,7 @@ 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'])) {
@ -585,22 +622,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);
@ -615,9 +652,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);
@ -629,7 +666,7 @@ 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);
@ -640,14 +677,14 @@ class ClientCallBellAPI
} }
} 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 }";
} }
@ -739,7 +776,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
@ -826,13 +863,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
@ -849,11 +886,11 @@ 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',
] ]
@ -867,7 +904,7 @@ class ClientCallBellAPI
// $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, [
@ -890,7 +927,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':
@ -953,7 +990,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"
@ -967,11 +1004,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": "' .
@ -985,22 +1022,22 @@ class ClientCallBellAPI
$data_CRM = [ $data_CRM = [
//"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" => [ "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,
], ],
]; ];
@ -1080,7 +1117,7 @@ class ClientCallBellAPI
$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, [
@ -1098,9 +1135,9 @@ class ClientCallBellAPI
$fecha_actual_ajustada = $fecha_actual->format("d/m/Y H:i"); $fecha_actual_ajustada = $fecha_actual->format("d/m/Y H:i");
$data_CRM = [ $data_CRM = [
"name" => $nombre_cliente, "name" => $nombre_cliente,
"custom_fields" => [ "custom_fields" => [
"Estado" => ( "Estado" => (
isset($notificationData->serviceData['status']) isset($notificationData->serviceData['status'])
&& $notificationData->serviceData['status'] == 3 && $notificationData->serviceData['status'] == 3
) ? '🟠 Suspendido' : ( ) ? '🟠 Suspendido' : (
@ -1126,14 +1163,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);
@ -1141,15 +1178,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) {
@ -1161,7 +1198,7 @@ class ClientCallBellAPI
$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
@ -1269,10 +1306,10 @@ class ClientCallBellAPI
*/ */
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.");
} }

View File

@ -129,7 +129,7 @@ class Plugin
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' || $jsonData['data']['object']['type'] === 'applied_to_payment') {
$this->pluginNotifierFacade->createPaymentIntent($jsonData); $this->pluginNotifierFacade->createPaymentIntent($jsonData);
} }
break; break;

View File

@ -5,7 +5,7 @@
'type' => 'library', 'type' => 'library',
'install_path' => __DIR__ . '/../../', 'install_path' => __DIR__ . '/../../',
'aliases' => array(), 'aliases' => array(),
'reference' => '7cb26fe7358fc5b3d7671f2db68235f6bb07ef3f', 'reference' => 'e34b3ec0f84e1274c6c6bbed67f8aacd933f0807',
'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' => '7cb26fe7358fc5b3d7671f2db68235f6bb07ef3f', 'reference' => 'e34b3ec0f84e1274c6c6bbed67f8aacd933f0807',
'dev_requirement' => false, 'dev_requirement' => false,
), ),
), ),