Versión 2.8.0
This commit is contained in:
parent
7cb26fe735
commit
3a39a53da6
Binary file not shown.
Binary file not shown.
|
Before Width: | Height: | Size: 104 KiB After Width: | Height: | Size: 80 KiB |
35399
data/plugin.log
35399
data/plugin.log
File diff suppressed because one or more lines are too long
@ -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",
|
||||
"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/",
|
||||
"version": "2.7.5",
|
||||
"version": "2.8.0",
|
||||
"unmsVersionCompliancy": {
|
||||
"min": "2.1.0",
|
||||
"max": null
|
||||
|
||||
@ -1,20 +1,19 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
declare (strict_types = 1);
|
||||
|
||||
namespace SmsNotifier\Facade;
|
||||
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\Exception\RequestException;
|
||||
use SmsNotifier\Data\NotificationData;
|
||||
use SmsNotifier\Facade\ClientCallBellAPI;
|
||||
use SmsNotifier\Factory\MessageTextFactory;
|
||||
use SmsNotifier\Service\Logger;
|
||||
use SmsNotifier\Service\SmsNumberProvider;
|
||||
use Twilio\Exceptions\HttpException;
|
||||
use SmsNotifier\Facade\ClientCallBellAPI;
|
||||
use GuzzleHttp\Client;
|
||||
use Ubnt\UcrmPluginSdk\Service\UcrmApi;
|
||||
use \DateTime;
|
||||
use GuzzleHttp\Exception\RequestException;
|
||||
|
||||
|
||||
/*
|
||||
* send message to client's number
|
||||
@ -47,9 +46,8 @@ abstract class AbstractMessageNotifierFacade
|
||||
*/
|
||||
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 ADDITIONAL_CHANGE_DATA = ["Ya no es necesario realizar la visita técnica.", "En tu lugar asistirá el técnico"];
|
||||
|
||||
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 👷🏻♂️➡️ "];
|
||||
|
||||
public function __construct(
|
||||
Logger $logger,
|
||||
@ -118,8 +116,6 @@ abstract class AbstractMessageNotifierFacade
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
/*
|
||||
@ -133,7 +129,6 @@ abstract class AbstractMessageNotifierFacade
|
||||
|
||||
$arrayPhones = $this->clientPhoneNumber->getUcrmClientNumbers($notificationData, null);
|
||||
|
||||
|
||||
// Procesar el array de teléfonos y ejecutar la función correspondiente
|
||||
foreach ($arrayPhones as $type => $phones) {
|
||||
|
||||
@ -171,7 +166,6 @@ abstract class AbstractMessageNotifierFacade
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
/*
|
||||
* Verify contact type numbers to do client's data service status at CallBell
|
||||
@ -183,7 +177,6 @@ abstract class AbstractMessageNotifierFacade
|
||||
|
||||
$arrayPhones = $this->clientPhoneNumber->getUcrmClientNumbers($notificationData, null);
|
||||
|
||||
|
||||
// Procesar el array de teléfonos y ejecutar la función correspondiente
|
||||
foreach ($arrayPhones as $type => $phones) {
|
||||
|
||||
@ -221,27 +214,35 @@ abstract class AbstractMessageNotifierFacade
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
/*
|
||||
* Verify contact type numbers to do client's
|
||||
*/
|
||||
public function verifyJobActionToDo($jsonNotificationData, $reprogramming = false, $changeInstaller = false): void
|
||||
public function verifyJobActionToDo($jsonNotificationData, $reprogramming = null, $changeInstaller = null): void
|
||||
{
|
||||
|
||||
$this->logger->debug('******** INCIO DE LA FUNCIÓN verifyJobActionToDo ******' . PHP_EOL);
|
||||
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
|
||||
$config = $configManager->loadConfig();
|
||||
$IPServer = $config['ipserver'];
|
||||
$UCRMAPIToken = $config['apitoken'];
|
||||
$CallBellAPIToken = $config['tokencallbell'];
|
||||
$IPServer = $config['ipserver'];
|
||||
$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);
|
||||
$clientId = $jsonNotificationData['extraData']['entity']['clientId'];
|
||||
$installerId = $jsonNotificationData['extraData']['entity']['assignedUserId'];
|
||||
$jobId = $jsonNotificationData['entityId'];
|
||||
$jobDescription = $jsonNotificationData['extraData']['entity']['description'] ?? null;
|
||||
|
||||
|
||||
$this->logger->debug('Valor de $clientId en verifyJobActionToDo: ' . $clientId . PHP_EOL);
|
||||
$this->logger->debug('Valor de $installerId en verifyJobActionToDo: ' . $installerId . PHP_EOL);
|
||||
$this->logger->debug('Valor de $jobId en verifyJobActionToDo: ' . $jobId . PHP_EOL);
|
||||
|
||||
|
||||
$reprogrammingValue = var_export($reprogramming, true);
|
||||
$changeInstallerValue = var_export($changeInstaller, true);
|
||||
$this->logger->debug('Valor de $reprogramming en verifyJobActionToDo: ' . $reprogrammingValue . PHP_EOL);
|
||||
$this->logger->debug('Valor de $changeInstaller en verifyJobActionToDo: ' . $changeInstallerValue . PHP_EOL);
|
||||
|
||||
// Obtener la fecha del nodo "entity"
|
||||
$dateString = $jsonNotificationData['extraData']['entity']['date'] ?? null;
|
||||
@ -251,42 +252,31 @@ abstract class AbstractMessageNotifierFacade
|
||||
$date = new DateTime($dateString);
|
||||
|
||||
// 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 *" . $date->format('h:i A') . "* aproximadamente";
|
||||
|
||||
echo $formattedDate;
|
||||
// $this->logger->debug('Valor de $formattedDate en verifyJobActionToDo: ' . $formattedDate . PHP_EOL);
|
||||
} else {
|
||||
echo "La fecha no está disponible en el JSON.\n";
|
||||
$this->logger->error('La fecha no está disponible en el JSON' . PHP_EOL);
|
||||
}
|
||||
|
||||
|
||||
|
||||
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
|
||||
$config = $configManager->loadConfig();
|
||||
$IPServer = $config['ipserver'];
|
||||
$UCRMAPIToken = $config['apitoken'];
|
||||
$CallBellAPIToken = $config['tokencallbell'];
|
||||
$IPServer = $config['ipserver'];
|
||||
$installersData = $config['installersDataWhatsApp'];
|
||||
$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();
|
||||
$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
|
||||
$installerFullName = '';
|
||||
|
||||
$jsonInstallersData = json_decode($installersData, true);
|
||||
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
$this->logger->error('Error al decodificar el JSON de instaladores: ' . json_last_error_msg());
|
||||
return;
|
||||
}
|
||||
|
||||
// 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');
|
||||
return;
|
||||
}
|
||||
@ -305,7 +295,7 @@ abstract class AbstractMessageNotifierFacade
|
||||
if (empty($installerWhatsApp)) {
|
||||
$this->logger->warning('No se encontró un número de WhatsApp para el instalador con ID 1019');
|
||||
} 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();
|
||||
@ -315,7 +305,7 @@ abstract class AbstractMessageNotifierFacade
|
||||
$firstName = $usersInstallers['firstName'] ?? '';
|
||||
$lastName = $usersInstallers['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/';
|
||||
|
||||
@ -328,9 +318,9 @@ abstract class AbstractMessageNotifierFacade
|
||||
'verify' => false,
|
||||
]);
|
||||
|
||||
$response = $clientGuzzleHttp->request('GET', "clients/" . $clientId);
|
||||
$arrayClientCRM = json_decode($response->getBody()->getContents(), true);
|
||||
$this->logger->debug('Valor de $arrayClientCRM en verifyJobActionToDo: ' . json_encode($arrayClientCRM) . PHP_EOL);
|
||||
$responseClients = $clientGuzzleHttp->request('GET', "clients/" . $clientId);
|
||||
$arrayClientCRM = json_decode($responseClients->getBody()->getContents(), true);
|
||||
// $this->logger->debug('Valor de $arrayClientCRM en verifyJobActionToDo: ' . json_encode($arrayClientCRM) . PHP_EOL);
|
||||
|
||||
$clientFullName = sprintf("%s %s", $arrayClientCRM['firstName'], $arrayClientCRM['lastName']);
|
||||
|
||||
@ -341,7 +331,7 @@ abstract class AbstractMessageNotifierFacade
|
||||
if ($fullAddress) {
|
||||
// Convertir la dirección a HTML seguro
|
||||
$safeAddress = htmlspecialchars($fullAddress, ENT_QUOTES, 'UTF-8');
|
||||
$this->logger->debug('Dirección completa: ' . $safeAddress . PHP_EOL);
|
||||
// $this->logger->debug('Dirección completa: ' . $safeAddress . PHP_EOL);
|
||||
} else {
|
||||
$this->logger->error('La dirección completa no está disponible en el JSON' . PHP_EOL);
|
||||
}
|
||||
@ -354,24 +344,23 @@ abstract class AbstractMessageNotifierFacade
|
||||
if ($gpsLat && $gpsLon) {
|
||||
// Construir la URL de Google Maps
|
||||
$googleMapsUrl = sprintf('https://www.google.com/maps?q=%s,%s', $gpsLat, $gpsLon);
|
||||
$this->logger->debug('URL de Google Maps: ' . $googleMapsUrl . PHP_EOL);
|
||||
// $this->logger->debug('URL de Google Maps: ' . $googleMapsUrl . PHP_EOL);
|
||||
} else {
|
||||
$this->logger->error('Las coordenadas no están disponibles en el JSON' . PHP_EOL);
|
||||
}
|
||||
|
||||
|
||||
$arrayPhones = $this->clientPhoneNumber->getUcrmClientNumbers(null, $arrayClientCRM);
|
||||
$this->logger->debug('Valor de $arrayPhones en verifyJobActionToDo: ' . json_encode($arrayPhones) . PHP_EOL);
|
||||
// $this->logger->debug('Valor de $arrayPhones en verifyJobActionToDo: ' . json_encode($arrayPhones) . PHP_EOL);
|
||||
|
||||
$arrayAllPhones = $this->clientPhoneNumber->getAllUcrmClientNumbers($arrayClientCRM);
|
||||
|
||||
// Convertir el array de teléfonos en una cadena separada por comas
|
||||
$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
|
||||
$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
|
||||
$resultados = [];
|
||||
@ -389,26 +378,25 @@ abstract class AbstractMessageNotifierFacade
|
||||
$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
|
||||
$resultadoFinalNumerosCliente = implode(', ', $resultados);
|
||||
$this->logger->debug('Valor de $resultadoFinalNumerosCliente en verifyJobActionToDo: ' . $resultadoFinalNumerosCliente . PHP_EOL);
|
||||
// $this->logger->debug('Valor de $resultadoFinalNumerosCliente en verifyJobActionToDo: ' . $resultadoFinalNumerosCliente . PHP_EOL);
|
||||
|
||||
$client_callbell_api = new ClientCallBellAPI($UCRMAPIToken, $IPServer, $CallBellAPIToken);
|
||||
|
||||
|
||||
// Construir el array asociativo con los datos de la notificación para el cliente
|
||||
$jsonClientJobNotificationData = [
|
||||
"clientFullName" => $clientFullName,
|
||||
"jobId" => $jobId,
|
||||
"date" => $formattedDate,
|
||||
"installerName" => $installerFullName
|
||||
"installerName" => $installerFullName,
|
||||
];
|
||||
|
||||
$clientWhatsApp = '';
|
||||
|
||||
|
||||
//Parte de la notificación al cliente
|
||||
// Procesar el array de teléfonos y ejecutar la función correspondiente
|
||||
foreach ($arrayPhones as $type => $phones) {
|
||||
|
||||
@ -422,11 +410,12 @@ abstract class AbstractMessageNotifierFacade
|
||||
|
||||
// Verificar si el valor es un array de teléfonos
|
||||
if (is_array($phones)) {
|
||||
foreach ($phones as $phone) {
|
||||
$attempts = 0;
|
||||
$maxAttempts = 3;
|
||||
$result = false;
|
||||
foreach ($phones as $phone) {
|
||||
|
||||
//Aquí se enviará la notificación al cliente
|
||||
// Reintentar hasta 3 veces si la función retorna false
|
||||
while ($attempts < $maxAttempts && $result === false) {
|
||||
$attempts++;
|
||||
@ -439,15 +428,37 @@ abstract class AbstractMessageNotifierFacade
|
||||
|
||||
if ($result === false) {
|
||||
sleep(1); // Esperar 1 segundo antes de reintentar
|
||||
$this->logger->warning("Intento $attempts fallido para enviar notificación a $phone. Reintentando..." . PHP_EOL);
|
||||
$this->logger->warning("Intento $attempts fallido en el envío de notificación a $phone. Reintentando..." . PHP_EOL);
|
||||
}
|
||||
}
|
||||
|
||||
// Verificar el resultado final
|
||||
if ($result === true) {
|
||||
$this->logger->info("Notificación enviada correctamente al contacto $phone después de $attempts intento(s)." . PHP_EOL);
|
||||
$this->logger->info("Notificación enviada correctamente al cliente con teléfono $phone después de $attempts intento(s)." . PHP_EOL);
|
||||
$title = $jsonNotificationData['extraData']['entity']['title'];
|
||||
$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
|
||||
|
||||
// $this->ucrmApi = UcrmApi::create();
|
||||
// $responsePatch = $this->ucrmApi->patch('scheduling/jobs/' . $jsonNotificationData['entityId'], [
|
||||
// 'title' => $title,
|
||||
// ]);
|
||||
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
|
||||
$responseClients = $clientGuzzleHttp->request('PATCH', "scheduling/jobs/" . $jsonNotificationData['entityId'], [
|
||||
'json' => [
|
||||
'title' => $title,
|
||||
],
|
||||
]);
|
||||
$this->logger->debug('Valor de $title después de quitar el prefijo en verifyJobActionToDo: ' . $title . PHP_EOL);
|
||||
break;
|
||||
|
||||
} else {
|
||||
$this->logger->error("No se pudo enviar la notificación al contacto $phone después de $maxAttempts intentos." . PHP_EOL);
|
||||
$this->logger->debug('El título no contiene el prefijo [NOTIFICACION-PENDIENTE] en verifyJobActionToDo: ' . $title . PHP_EOL);
|
||||
}
|
||||
|
||||
} else {
|
||||
$this->logger->error("No se pudo enviar la notificación al cliente con teléfono $phone después de $maxAttempts intentos." . PHP_EOL);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@ -462,8 +473,14 @@ abstract class AbstractMessageNotifierFacade
|
||||
}
|
||||
}
|
||||
|
||||
//$installerWhatsApp = $this->validarNumeroTelefono((string)$installerWhatsApp); //Obtiene el número de celular del cliente que sea del tipo de contacto "WhatsApp"
|
||||
$this->logger->debug('Valor de $installerWhatsApp en verifyJobActionToDo: ' . $installerWhatsApp . PHP_EOL);
|
||||
// --- ¡AÑADE ESTAS LÍNEAS PARA CONVERTIR A BOOLEANO REAL! ---
|
||||
$reprogramming = filter_var($reprogramming, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
|
||||
$changeInstaller = filter_var($changeInstaller, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
|
||||
// -----------------------------------------------------------
|
||||
|
||||
// Puedes volver a loggear los valores para confirmar la conversión (opcional)
|
||||
$this->logger->debug("DEBUG: Valores después de conversión para mensaje instalador - Reprogramming: " . var_export($reprogramming, true) . ", ChangeInstaller: " . var_export($changeInstaller, true) . PHP_EOL);
|
||||
|
||||
|
||||
if ($changeInstaller) { //Si se cambió el instalador
|
||||
$this->logger->debug('Se cambió el instalador, por lo tanto se procede a enviarle mensaje al que se le desasignó' . PHP_EOL);
|
||||
@ -482,11 +499,11 @@ abstract class AbstractMessageNotifierFacade
|
||||
$result = false;
|
||||
|
||||
$jsonPreviousInstallerJobNotificationData = [
|
||||
"installerName" => $previousInstallerFullName,
|
||||
"installerName" => "👷🏻♂️" . $previousInstallerFullName,
|
||||
"subjectOfChange" => self::SUBJECT_OF_INSTALLER_CHANGE[1],
|
||||
"jobId" => $jobId,
|
||||
"clientFullName" => sprintf("[%s] %s", $arrayClientCRM['id'], $clientFullName),
|
||||
"additionalChangeData" => self::ADDITIONAL_CHANGE_DATA[1] . ' *' . $installerFullName . '*'
|
||||
"additionalChangeData" => self::ADDITIONAL_CHANGE_DATA[1] . ' *' . $installerFullName . '*',
|
||||
|
||||
];
|
||||
|
||||
@ -500,6 +517,7 @@ abstract class AbstractMessageNotifierFacade
|
||||
}
|
||||
}
|
||||
|
||||
//Enviar mensaje al instalador anterior
|
||||
// Reintentar hasta 3 veces si la función retorna false
|
||||
while ($attempts < $maxAttempts && $result === false) {
|
||||
$attempts++;
|
||||
@ -507,11 +525,11 @@ abstract class AbstractMessageNotifierFacade
|
||||
$this->validarNumeroTelefono((string) $previousInstallerWhatsApp),
|
||||
$jsonPreviousInstallerJobNotificationData,
|
||||
false,
|
||||
true, $this->getVaultCredentials($arrayClientCRM['id'])
|
||||
true,
|
||||
''
|
||||
|
||||
);
|
||||
|
||||
|
||||
if ($result === false) {
|
||||
sleep(1);
|
||||
$this->logger->warning("Intento $attempts fallido para enviar notificación a $phone. Reintentando..." . PHP_EOL);
|
||||
@ -529,7 +547,7 @@ abstract class AbstractMessageNotifierFacade
|
||||
"clientWhatsApp" => $resultadoFinalNumerosCliente,
|
||||
"date" => $formattedDate,
|
||||
"jobDescription" => $jobDescription,
|
||||
"gmapsLocation" => $googleMapsUrl
|
||||
"gmapsLocation" => $googleMapsUrl,
|
||||
|
||||
];
|
||||
//Enviar notificación al instalador nuevo
|
||||
@ -544,23 +562,20 @@ abstract class AbstractMessageNotifierFacade
|
||||
$result = $client_callbell_api->sendJobNotificationWhatsAppToInstaller(
|
||||
$this->validarNumeroTelefono((string) $installerWhatsApp),
|
||||
$jsonInstallerJobNotificationData,
|
||||
$reprogramming,
|
||||
false
|
||||
false,
|
||||
false,
|
||||
$this->getVaultCredentials($arrayClientCRM['id'])
|
||||
);
|
||||
|
||||
|
||||
if ($result === false) {
|
||||
sleep(1);
|
||||
$this->logger->warning("Intento $attempts fallido para enviar notificación a $phone. Reintentando..." . PHP_EOL);
|
||||
}
|
||||
}
|
||||
|
||||
} else { //si el instalador no cambió
|
||||
$this->logger->debug('No se cambió el instalador' . PHP_EOL);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
} else {
|
||||
// Construir el array asociativo con los datos de la notificación
|
||||
$jsonInstallerJobNotificationData = [
|
||||
"installerName" => $installerFullName,
|
||||
@ -570,7 +585,7 @@ abstract class AbstractMessageNotifierFacade
|
||||
"clientWhatsApp" => $resultadoFinalNumerosCliente,
|
||||
"date" => $formattedDate,
|
||||
"jobDescription" => $jobDescription,
|
||||
"gmapsLocation" => $googleMapsUrl
|
||||
"gmapsLocation" => $googleMapsUrl,
|
||||
|
||||
];
|
||||
|
||||
@ -578,29 +593,25 @@ abstract class AbstractMessageNotifierFacade
|
||||
$maxAttempts = 3;
|
||||
$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) {
|
||||
$attempts++;
|
||||
$result = $client_callbell_api->sendJobNotificationWhatsAppToInstaller(
|
||||
$this->validarNumeroTelefono((string) $installerWhatsApp),
|
||||
$jsonInstallerJobNotificationData,
|
||||
$reprogramming,
|
||||
$changeInstaller
|
||||
false,
|
||||
false,
|
||||
$this->getVaultCredentials($arrayClientCRM['id'])
|
||||
);
|
||||
|
||||
|
||||
if ($result === false) {
|
||||
sleep(1);
|
||||
$this->logger->warning("Intento $attempts fallido para enviar notificación a $phone. Reintentando..." . PHP_EOL);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
/*
|
||||
@ -614,8 +625,6 @@ abstract class AbstractMessageNotifierFacade
|
||||
|
||||
$arrayPhones = $this->clientPhoneNumber->getUcrmClientNumbers($notificationData, null);
|
||||
|
||||
|
||||
|
||||
// Procesar el array de teléfonos y ejecutar la función correspondiente
|
||||
foreach ($arrayPhones as $type => $phones) {
|
||||
|
||||
@ -672,7 +681,6 @@ abstract class AbstractMessageNotifierFacade
|
||||
$CallBellAPIToken = $config['tokencallbell'];
|
||||
$notificationTypeText = $config['notificationTypeText'];
|
||||
|
||||
|
||||
$client_callbell_api = new ClientCallBellAPI($UCRMAPIToken, $IPServer, $CallBellAPIToken);
|
||||
|
||||
//$clientPhoneNumber = $this->clientPhoneNumber->getUcrmClientNumber($notificationData);
|
||||
@ -680,24 +688,22 @@ abstract class AbstractMessageNotifierFacade
|
||||
|
||||
//$this->logger->debug("Numero de cel obtenido " . $clientPhoneNumber . PHP_EOL);
|
||||
|
||||
|
||||
if (empty($clientPhoneNumber)) {
|
||||
$this->logger->warning('No se encontró un teléfono celular válido para el cliente: ' . $notificationData->clientId);
|
||||
return;
|
||||
} else {
|
||||
|
||||
|
||||
if ($notificationTypeText) {
|
||||
try {
|
||||
$attempts = 0;
|
||||
$maxAttempts = 3;
|
||||
$result = false;
|
||||
|
||||
while ($attempts < $maxAttempts && !$result) {
|
||||
while ($attempts < $maxAttempts && ! $result) {
|
||||
$attempts++;
|
||||
$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);
|
||||
}
|
||||
}
|
||||
@ -717,11 +723,11 @@ abstract class AbstractMessageNotifierFacade
|
||||
$maxAttempts = 3;
|
||||
$result = false;
|
||||
|
||||
while ($attempts < $maxAttempts && !$result) {
|
||||
while ($attempts < $maxAttempts && ! $result) {
|
||||
$attempts++;
|
||||
$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);
|
||||
}
|
||||
}
|
||||
@ -737,9 +743,6 @@ abstract class AbstractMessageNotifierFacade
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
// $messageBody = $this->messageTextFactory->createBody($notificationData);
|
||||
@ -770,7 +773,6 @@ abstract class AbstractMessageNotifierFacade
|
||||
$CallBellAPIToken = $config['tokencallbell'];
|
||||
$notificationTypeText = $config['notificationTypeText'];
|
||||
|
||||
|
||||
$client_callbell_api = new ClientCallBellAPI($UCRMAPIToken, $IPServer, $CallBellAPIToken);
|
||||
//$this->logger->debug(" instancia callbell creada".PHP_EOL);
|
||||
//$clientPhoneNumber = $this->validarNumeroTelefono($this->clientPhoneNumber->getUcrmClientNumber($notificationData));
|
||||
@ -780,13 +782,11 @@ abstract class AbstractMessageNotifierFacade
|
||||
|
||||
$clientPhoneNumber = $this->validarNumeroTelefono($phoneToNotifyAndUpdate);
|
||||
|
||||
|
||||
if (empty($clientPhoneNumber)) {
|
||||
$this->logger->warning('No se encontró un teléfono celular válido para el cliente: ' . $notificationData->clientId);
|
||||
return;
|
||||
} else {
|
||||
|
||||
|
||||
//$this->logger->debug(sprintf('llego al llamado de sendPaymentNotificationWhatsApp con client_id: %s y número de celular: %s', $notificationData->clientId, $clientPhoneNumber));
|
||||
|
||||
if ($notificationTypeText) {
|
||||
@ -821,9 +821,6 @@ abstract class AbstractMessageNotifierFacade
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
// $messageBody = $this->messageTextFactory->createBody($notificationData);
|
||||
@ -853,14 +850,12 @@ abstract class AbstractMessageNotifierFacade
|
||||
$UCRMAPIToken = $config['apitoken'];
|
||||
$CallBellAPIToken = $config['tokencallbell'];
|
||||
|
||||
|
||||
$client_callbell_api = new ClientCallBellAPI($UCRMAPIToken, $IPServer, $CallBellAPIToken);
|
||||
//$this->logger->debug(" instancia callbell creada".PHP_EOL);
|
||||
//$clientPhoneNumber = $this->validarNumeroTelefono($this->clientPhoneNumber->getUcrmClientNumber($notificationData));
|
||||
$clientPhoneNumber = $this->clientPhoneNumber->getUcrmClientNumber($notificationData);
|
||||
$this->logger->debug("Numero de cel obtenido " . $clientPhoneNumber . PHP_EOL);
|
||||
|
||||
|
||||
if (empty($clientPhoneNumber)) {
|
||||
$this->logger->warning('No se encontró un teléfono celular válido para el cliente: ' . $notificationData->clientId);
|
||||
return;
|
||||
@ -887,7 +882,6 @@ abstract class AbstractMessageNotifierFacade
|
||||
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Update the client's data at CallBell
|
||||
*/
|
||||
@ -911,20 +905,17 @@ abstract class AbstractMessageNotifierFacade
|
||||
$attributes = $notificationData->clientData['attributes']; //Obtener los atributos del cliente
|
||||
// Variable para almacenar los valores de los atributos que comienzan con "clabe"
|
||||
|
||||
|
||||
// Iterar sobre los atributoss
|
||||
foreach ($attributes as $attribute) {
|
||||
// Verificar si la "key" comienza con "stripe"
|
||||
if (strpos($attribute['key'], 'stripe') === 0) {
|
||||
// Agregar el valor al array $clabeValues
|
||||
$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
|
||||
$clabeInterbancaria = $attribute['value'];
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
if ($updateEmail) {
|
||||
@ -953,13 +944,8 @@ abstract class AbstractMessageNotifierFacade
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
$clientPhoneNumber = $this->validarNumeroTelefono($phoneToUpdate); //Obtiene el número de celular del cliente que sea del tipo de contacto "WhatsApp"
|
||||
|
||||
|
||||
|
||||
if (empty($clientPhoneNumber)) {
|
||||
$this->logger->warning('No se encontró un teléfono celular válido para el cliente: ' . $notificationData->clientId);
|
||||
return;
|
||||
@ -1005,9 +991,6 @@ abstract class AbstractMessageNotifierFacade
|
||||
|
||||
//$this->logger->info("client id " .$clientID. PHP_EOL);
|
||||
|
||||
|
||||
|
||||
|
||||
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
|
||||
$config = $configManager->loadConfig();
|
||||
// the "exportFormat" key must be defined in plugin's manifest file, see the link above
|
||||
@ -1015,7 +998,6 @@ abstract class AbstractMessageNotifierFacade
|
||||
$UCRMAPIToken = $config['apitoken'];
|
||||
$CallBellAPIToken = $config['tokencallbell'];
|
||||
|
||||
|
||||
$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);
|
||||
|
||||
@ -1039,7 +1021,6 @@ abstract class AbstractMessageNotifierFacade
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
@ -1096,14 +1077,68 @@ abstract class AbstractMessageNotifierFacade
|
||||
return '';
|
||||
}
|
||||
|
||||
function getVaultCredentials($dataToSearch): string
|
||||
{
|
||||
function patchClientCustomAttribute($clientId, $attributeId, $value): bool
|
||||
{
|
||||
$logger = \Ubnt\UcrmPluginSdk\Service\PluginLogManager::create();
|
||||
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
|
||||
$config = $configManager->loadConfig();
|
||||
$ucrmBaseUri = $config['ipserver'];
|
||||
$authToken = $config['apitoken'];
|
||||
|
||||
$ucrmBaseUri = 'https://' . $ucrmBaseUri . '/crm/api/v1.0/';
|
||||
$clientguzz = new Client(); //instancia de cliente GuzzleHttp para consumir API UISP CRM
|
||||
|
||||
$json_data_patch = '{
|
||||
"attributes": [
|
||||
{
|
||||
"value": "' . $value . '",
|
||||
"customAttributeId":' . $attributeId . '
|
||||
}
|
||||
]
|
||||
|
||||
}'; //JSON para hacer patch de los custom fields del cliente en el UISCP CRM
|
||||
|
||||
try {
|
||||
//aquí se contruye la petición para hacer patch hacia el cliente en sus custom fields con la API del UISP UCRM
|
||||
$responseCRM = $clientguzz->patch(
|
||||
$ucrmBaseUri . 'clients/' . $clientId,
|
||||
[
|
||||
'headers' => [
|
||||
'X-Auth-Token' => $authToken,
|
||||
'Content-Type' => 'application/json',
|
||||
],
|
||||
'body' => $json_data_patch,
|
||||
'verify' => false, // Deshabilitar la verificación del certificado SSL
|
||||
],
|
||||
|
||||
);
|
||||
//evaluar el código de respuesta HTTP y si es 200 se retorna true
|
||||
if ($responseCRM->getStatusCode() === 200) {
|
||||
$this->logger->info("Se actualizó el custom attribute del cliente " . $clientId . PHP_EOL);
|
||||
return true; // Return true if patch is successful
|
||||
} else {
|
||||
$this->logger->info("Error al hacer el patch al CRM: " . $responseCRM->getStatusCode() . PHP_EOL);
|
||||
return false; // Return false if patch fails
|
||||
}
|
||||
|
||||
|
||||
} catch (\GuzzleHttp\Exception\GuzzleException $error) {
|
||||
$this->logger->info("Error al hacer el patch al CRM: " . $error->getMessage() . PHP_EOL);
|
||||
return false; // Return false if patch fails
|
||||
}
|
||||
|
||||
}
|
||||
function getVaultCredentials($dataToSearch): string
|
||||
{
|
||||
$logger = \Ubnt\UcrmPluginSdk\Service\PluginLogManager::create();
|
||||
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
|
||||
$config = $configManager->loadConfig();
|
||||
$ucrmBaseUri = $config['ipserver'];
|
||||
$authToken = $config['apitoken'];
|
||||
|
||||
if ($ucrmBaseUri === '172.16.5.134') { //opción solo para el servidor de pruebas
|
||||
return 'gYAIEK:Be}SK*01z5+/V';
|
||||
}
|
||||
|
||||
$unmsBaseUri = 'https://' . $ucrmBaseUri . '/nms/api/v2.1/';
|
||||
$ucrmBaseUri = 'https://' . $ucrmBaseUri . '/crm/api/v1.0/';
|
||||
@ -1112,33 +1147,32 @@ abstract class AbstractMessageNotifierFacade
|
||||
// Crear una instancia del cliente Guzzle
|
||||
$clientUnms = new Client([
|
||||
'base_uri' => $unmsBaseUri,
|
||||
'verify' => false // Deshabilitar la verificación del certificado SSL
|
||||
'verify' => false, // Deshabilitar la verificación del certificado SSL
|
||||
]);
|
||||
|
||||
$clientUcrm = new Client([
|
||||
'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
|
||||
if (filter_var($dataToSearch, FILTER_VALIDATE_IP)) {
|
||||
// La variable es una dirección IP válida
|
||||
// $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);
|
||||
|
||||
try {
|
||||
$responseSitesByIP = $clientUnms->request('GET', 'sites/search?query=' . $dataToSearch . '&count=1&page=1', [
|
||||
'headers' => [
|
||||
'X-Auth-Token' => $authToken
|
||||
]
|
||||
'X-Auth-Token' => $authToken,
|
||||
],
|
||||
]);
|
||||
|
||||
if ($responseSitesByIP->getStatusCode() === 200) {
|
||||
|
||||
$datasSitesByIP = json_decode($responseSitesByIP->getBody(), true);
|
||||
$datasSitesByIP = json_decode((string) $responseSitesByIP->getBody(), true);
|
||||
$jsonDevicesBySite = json_encode($datasSitesByIP, JSON_PRETTY_PRINT);
|
||||
//print_r($jsonDevicesBySite . PHP_EOL); //Devices por ID del sitio
|
||||
|
||||
@ -1151,7 +1185,6 @@ abstract class AbstractMessageNotifierFacade
|
||||
return 'Error: No se encontró ningún sitio para la IP proporcionada: ' . $dataToSearch; // Return early if no site is found
|
||||
}
|
||||
|
||||
|
||||
} else {
|
||||
//echo "Error en la solicitud. Código de estado HTTP: " . $responseSitesByIP->getStatusCode() . PHP_EOL;
|
||||
// $logger->appendLog('Error en la solicitud. Código de estado HTTP: ' . $responseSitesByIP->getStatusCode());
|
||||
@ -1161,12 +1194,12 @@ abstract class AbstractMessageNotifierFacade
|
||||
|
||||
$devicesBySiteId = $clientUnms->request('GET', 'devices?siteId=' . $siteId, [
|
||||
'headers' => [
|
||||
'X-Auth-Token' => $authToken
|
||||
]
|
||||
'X-Auth-Token' => $authToken,
|
||||
],
|
||||
]);
|
||||
|
||||
if ($devicesBySiteId->getStatusCode() === 200) {
|
||||
$dataDevicesBySite = json_decode($devicesBySiteId->getBody(), true);
|
||||
$dataDevicesBySite = json_decode((string) $devicesBySiteId->getBody(), true);
|
||||
$jsonDevicesBySite = json_encode($dataDevicesBySite, JSON_PRETTY_PRINT);
|
||||
//print_r($jsonDevicesBySite . PHP_EOL); //Devices por ID del sitio
|
||||
$deviceID = null;
|
||||
@ -1201,12 +1234,12 @@ abstract class AbstractMessageNotifierFacade
|
||||
|
||||
$responsePasswordVault = $clientUnms->request('GET', 'vault/' . $deviceID . '/credentials', [
|
||||
'headers' => [
|
||||
'X-Auth-Token' => $authToken
|
||||
]
|
||||
'X-Auth-Token' => $authToken,
|
||||
],
|
||||
]);
|
||||
|
||||
if ($responsePasswordVault->getStatusCode() === 200) {
|
||||
$dataPasswordVault = json_decode($responsePasswordVault->getBody(), true);
|
||||
$dataPasswordVault = json_decode((string) $responsePasswordVault->getBody(), true);
|
||||
// $jsonPasswordVault = json_encode($dataPasswordVault, JSON_PRETTY_PRINT);
|
||||
//print_r($jsonPasswordVault . PHP_EOL); //Credenciales del dispositivo
|
||||
|
||||
@ -1227,7 +1260,6 @@ abstract class AbstractMessageNotifierFacade
|
||||
return 'Error: Falla en la solicitud. Código de estado HTTP: ' . $responsePasswordVault->getStatusCode(); // Return early if the request fails
|
||||
}
|
||||
|
||||
|
||||
} 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
|
||||
if ($requestException->hasResponse()) {
|
||||
@ -1250,15 +1282,12 @@ abstract class AbstractMessageNotifierFacade
|
||||
return 'Error: ' . $requestException->getMessage(); // Return early if the request fails
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
} 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
|
||||
// $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 {
|
||||
// //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
|
||||
@ -1266,13 +1295,13 @@ abstract class AbstractMessageNotifierFacade
|
||||
// $logger->appendLog('Consulta por dirección MAC: ' . $dataToSearch );
|
||||
$responseDeviceByMAC = $clientUnms->request('GET', 'devices/mac/' . $dataToSearch, [
|
||||
'headers' => [
|
||||
'X-Auth-Token' => $authToken
|
||||
]
|
||||
'X-Auth-Token' => $authToken,
|
||||
],
|
||||
]);
|
||||
|
||||
if ($responseDeviceByMAC->getStatusCode() === 200) {
|
||||
|
||||
$dataDeviceByMAC = json_decode($responseDeviceByMAC->getBody(), true);
|
||||
$dataDeviceByMAC = json_decode((string) $responseDeviceByMAC->getBody(), true);
|
||||
$jsonDeviceByMac = json_encode($dataDeviceByMAC, JSON_PRETTY_PRINT);
|
||||
// print_r($jsonDeviceByMac . PHP_EOL); //Devices por ID del sitio
|
||||
//$logger->appendLog($jsonDeviceByMac.PHP_EOL);
|
||||
@ -1293,12 +1322,12 @@ abstract class AbstractMessageNotifierFacade
|
||||
|
||||
$responsePasswordVault = $clientUnms->request('GET', 'vault/' . $deviceId . '/credentials', [
|
||||
'headers' => [
|
||||
'X-Auth-Token' => $authToken
|
||||
]
|
||||
'X-Auth-Token' => $authToken,
|
||||
],
|
||||
]);
|
||||
|
||||
if ($responsePasswordVault->getStatusCode() === 200) {
|
||||
$dataPasswordVault = json_decode($responsePasswordVault->getBody(), true);
|
||||
$dataPasswordVault = json_decode((string) $responsePasswordVault->getBody(), true);
|
||||
// $jsonPasswordVault = json_encode($dataPasswordVault, JSON_PRETTY_PRINT);
|
||||
//print_r($jsonPasswordVault . PHP_EOL); //Credenciales del dispositivo
|
||||
|
||||
@ -1319,7 +1348,6 @@ abstract class AbstractMessageNotifierFacade
|
||||
return 'Error: Falla en la solicitud. Código de estado HTTP: ' . $responsePasswordVault->getStatusCode(); // Return early if the request fails
|
||||
}
|
||||
|
||||
|
||||
} 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
|
||||
if ($requestException->hasResponse()) {
|
||||
@ -1342,10 +1370,8 @@ abstract class AbstractMessageNotifierFacade
|
||||
return 'Error: ' . $requestException->getMessage(); // Return early if the request fails
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
} else {
|
||||
// La variable no es una dirección IP válida, se asume que es un ID
|
||||
$IpAddressClientId = filter_var($dataToSearch, FILTER_SANITIZE_NUMBER_INT);
|
||||
@ -1356,8 +1382,8 @@ abstract class AbstractMessageNotifierFacade
|
||||
$responseServices = $clientUcrm->get('clients/services?clientId=' . $IpAddressClientId, [
|
||||
'headers' => [
|
||||
'X-Auth-Token' => $authToken,
|
||||
'Content-Type: application/json'
|
||||
]
|
||||
'Content-Type: application/json',
|
||||
],
|
||||
]);
|
||||
|
||||
} catch (RequestException $requestException) {
|
||||
@ -1386,7 +1412,7 @@ abstract class AbstractMessageNotifierFacade
|
||||
|
||||
if ($responseServices->getStatusCode() === 200) {
|
||||
|
||||
$dataServices = json_decode($responseServices->getBody(), true);
|
||||
$dataServices = json_decode($responseServices->getBody()->getContents(), true);
|
||||
// $jsonServices = json_encode($dataServices, JSON_PRETTY_PRINT);
|
||||
// print_r($jsonServices . PHP_EOL);
|
||||
if (isset($dataServices[0])) {
|
||||
@ -1408,8 +1434,8 @@ abstract class AbstractMessageNotifierFacade
|
||||
try {
|
||||
$responseDevicesBySite = $clientUnms->request('GET', 'devices?siteId=' . $unmsSiteID, [
|
||||
'headers' => [
|
||||
'X-Auth-Token' => $authToken
|
||||
]
|
||||
'X-Auth-Token' => $authToken,
|
||||
],
|
||||
]);
|
||||
} catch (RequestException $requestException) {
|
||||
// Manejar errores de la solicitud
|
||||
@ -1435,10 +1461,9 @@ abstract class AbstractMessageNotifierFacade
|
||||
|
||||
}
|
||||
|
||||
|
||||
if ($responseDevicesBySite->getStatusCode() === 200) {
|
||||
|
||||
$dataDevicesBySite = json_decode($responseDevicesBySite->getBody(), true);
|
||||
$dataDevicesBySite = json_decode($responseDevicesBySite->getBody()->getContents(), true);
|
||||
$jsonDevicesBySite = json_encode($dataDevicesBySite, JSON_PRETTY_PRINT);
|
||||
//print_r($jsonDevicesBySite . PHP_EOL); //Devices por ID del sitio
|
||||
|
||||
@ -1462,8 +1487,6 @@ abstract class AbstractMessageNotifierFacade
|
||||
return "Error: No se encontraron dispositivos para el sitio proporcionado."; // Return early if no devices are found
|
||||
}
|
||||
|
||||
|
||||
|
||||
} else {
|
||||
// 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());
|
||||
@ -1474,8 +1497,8 @@ abstract class AbstractMessageNotifierFacade
|
||||
try {
|
||||
$responseDevicesBySite = $clientUnms->request('GET', 'devices/' . $deviceID, [
|
||||
'headers' => [
|
||||
'X-Auth-Token' => $authToken
|
||||
]
|
||||
'X-Auth-Token' => $authToken,
|
||||
],
|
||||
]);
|
||||
} catch (RequestException $requestException) {
|
||||
// Manejar errores de la solicitud
|
||||
@ -1503,17 +1526,16 @@ abstract class AbstractMessageNotifierFacade
|
||||
|
||||
if ($responseDevicesBySite->getStatusCode() === 200) {
|
||||
|
||||
$dataDevices = json_decode($responseDevicesBySite->getBody(), true);
|
||||
$dataDevices = json_decode($responseDevicesBySite->getBody()->getContents(), true);
|
||||
$jsonDevices = json_encode($dataDevices, JSON_PRETTY_PRINT);
|
||||
//print_r($jsonDevices . PHP_EOL);
|
||||
|
||||
|
||||
try {
|
||||
//print_r('ID del device al que está conectado el cliente: ' . $idDevice . PHP_EOL);
|
||||
$responsePasswordVault = $clientUnms->request('GET', 'vault/' . $idClientDevice . '/credentials', [
|
||||
'headers' => [
|
||||
'X-Auth-Token' => $authToken
|
||||
]
|
||||
'X-Auth-Token' => $authToken,
|
||||
],
|
||||
]);
|
||||
} catch (RequestException $requestException) {
|
||||
// Manejar errores de la solicitud
|
||||
@ -1538,9 +1560,8 @@ abstract class AbstractMessageNotifierFacade
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if ($responsePasswordVault->getStatusCode() === 200) {
|
||||
$dataPasswordVault = json_decode($responsePasswordVault->getBody(), true);
|
||||
$dataPasswordVault = json_decode($responsePasswordVault->getBody()->getContents(), true);
|
||||
$jsonPasswordVault = json_encode($dataPasswordVault, JSON_PRETTY_PRINT);
|
||||
if (isset($dataPasswordVault['credentials']['password'])) {
|
||||
$passwordVault = $dataPasswordVault['credentials']['password'];
|
||||
@ -1559,8 +1580,6 @@ abstract class AbstractMessageNotifierFacade
|
||||
return 'Error: Falla en la solicitud. Código de estado HTTP: ' . $responsePasswordVault->getStatusCode(); // Return early if the request fails
|
||||
}
|
||||
|
||||
|
||||
|
||||
} else {
|
||||
// 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());
|
||||
@ -1569,9 +1588,7 @@ abstract class AbstractMessageNotifierFacade
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -192,12 +192,12 @@ abstract class AbstractStripeOperationsFacade
|
||||
$tagsIds = $this->ucrmApi->get('client-tags', []);
|
||||
//ejemplo de respuesta $tagsIds: [{"id":4,"name":"EQUIPO A CREDITO","colorBackground":"#fed74a","colorText":"#444"},{"id":5,"name":"CREARCLABESTRIPE","colorBackground":"#e30000","colorText":"#fff"}]
|
||||
|
||||
//obtener el ID de la etiqueta o tag llamada "CREARCLABESTRIPE" y asiganarla a una variable $tagCrearClabeStripe basandose en el ejemplo de respuesta anterior
|
||||
//obtener el ID de la etiqueta o tag llamada "CREAR CLABE STRIPE" y asiganarla a una variable $tagCrearClabeStripe basandose en el ejemplo de respuesta anterior
|
||||
$tagCrearClabeStripe = null;
|
||||
foreach ($tagsIds as $tag) {
|
||||
if ($tag['name'] === 'CREAR CLABE STRIPE') {
|
||||
$tagCrearClabeStripe = $tag['id'];
|
||||
$this->logger->info("ID de la etiqueta 'CREAR CLABE STRIPE': " . $tagCrearClabeStripe . PHP_EOL);
|
||||
// $this->logger->info("ID de la etiqueta 'CREAR CLABE STRIPE': " . $tagCrearClabeStripe . PHP_EOL);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@ -224,19 +224,19 @@ abstract class AbstractStripeOperationsFacade
|
||||
//obtener el ID de la etiqueta o tag llamada "CREARCLABESTRIPE" y asiganarla a una variable $tagCrearClabeStripe basandose en el ejemplo de respuesta anterior
|
||||
$tagCrearClabeStripe = null;
|
||||
foreach ($tagsIds as $tag) { //revisamos los tags del cliente y si encuentra el tag de "CREARCLABESTRIPE" entonces lo asigna a la variable $tagCrearClabeStripe el valor de id
|
||||
if ($tag['name'] === 'CREARCLABESTRIPE') {
|
||||
if ($tag['name'] === 'CREAR CLABE STRIPE') {
|
||||
$tagCrearClabeStripe = $tag['id'];
|
||||
$this->logger->info("ID de la etiqueta 'CREARCLABESTRIPE': " . $tagCrearClabeStripe . PHP_EOL);
|
||||
// $this->logger->info("ID de la etiqueta 'CREAR CLABE STRIPE': " . $tagCrearClabeStripe . PHP_EOL);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!$tagCrearClabeStripe) {
|
||||
$this->logger->info("No se encontró la etiqueta 'CREARCLABESTRIPE'." . PHP_EOL);
|
||||
$this->logger->info("No se encontró la etiqueta 'CREAR CLABE STRIPE'." . PHP_EOL);
|
||||
return;
|
||||
}
|
||||
$this->createCustomerStripe($notificationData, $stripe, $baseUri, $UCRMAPIToken);
|
||||
$this->ucrmApi->patch("clients/$clientId/remove-tag/" . $tagCrearClabeStripe);
|
||||
$this->logger->info("Se eliminó la etiqueta 'CREARCLABESTRIPE' del cliente." . PHP_EOL);
|
||||
$this->logger->info("Se eliminó la etiqueta 'CREAR CLABE STRIPE' del cliente." . PHP_EOL);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@ -1,17 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace SmsNotifier\Facade;
|
||||
|
||||
use CURLFile;
|
||||
use DateTime;
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\Exception\GuzzleException;
|
||||
use Imagick;
|
||||
use Ubnt\UcrmPluginSdk\Service\PluginLogManager;
|
||||
use ImagickException;
|
||||
use Ubnt\UcrmPluginSdk\Service\UcrmApi;
|
||||
use Ubnt\UcrmPluginSdk\Service\PluginConfigManager;
|
||||
use Ubnt\UcrmPluginSdk\Service\UcrmOptionsManager;
|
||||
use Ubnt\UcrmPluginSdk\Service\PluginLogManager;
|
||||
use Ubnt\UcrmPluginSdk\Service\UcrmApi;
|
||||
|
||||
//use SmsNotifier\Service\Logger;
|
||||
|
||||
@ -56,7 +52,6 @@ class ClientCallBellAPI
|
||||
|
||||
public $ucrmVersion;
|
||||
|
||||
|
||||
public function __construct(
|
||||
$UCRMAPIToken,
|
||||
$IPServer,
|
||||
@ -68,8 +63,7 @@ class ClientCallBellAPI
|
||||
}
|
||||
|
||||
public function updateContact($client_uuid)
|
||||
{
|
||||
}
|
||||
{}
|
||||
|
||||
public function printPrueba($clientWhatsAppNumber, $notificationData)
|
||||
{
|
||||
@ -105,9 +99,6 @@ class ClientCallBellAPI
|
||||
$campo2 = sprintf("📡 Su servicio está: %s 📍Su dirección es: *%s* ", $estado_service, $domicilio);
|
||||
$log->appendLog("Valor del campo2 " . $campo2);
|
||||
|
||||
|
||||
|
||||
|
||||
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\"],\n \"template_uuid\": \"55705f1fe4e24bab80104dc2643fe11c\",\n \"optin_contact\": true\n }";
|
||||
$log->appendLog("La cadena CURL que se envia es: " . $curl_string);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, $curl_string);
|
||||
@ -118,15 +109,21 @@ class ClientCallBellAPI
|
||||
curl_close($ch);
|
||||
}
|
||||
|
||||
public function sendJobNotificationWhatsAppToClient($clientWhatsAppNumber, $jobNotificationData, $passwordVault, $reprogramming = false, $changeInstaller = false): bool
|
||||
public function sendJobNotificationWhatsAppToClient($clientWhatsAppNumber, $jobNotificationData, $reprogramming, $changeInstaller): bool
|
||||
{
|
||||
|
||||
$log = PluginLogManager::create(); //Initialize Logger
|
||||
$log->appendLog("Enviando mensaje de trabajo para el cliente" . PHP_EOL);
|
||||
$jsonJobNotificationData = json_encode($jobNotificationData, true);
|
||||
$log->appendLog("Datos de la notificación de trabajo: " . $jsonJobNotificationData . PHP_EOL);
|
||||
$log->appendLog("Debugging: reprogramming = " . var_export($reprogramming, true) . ", changeInstaller = " . var_export($changeInstaller, true) . PHP_EOL);
|
||||
// $log->appendLog("Datos de la notificación de trabajo: " . $jsonJobNotificationData . PHP_EOL);
|
||||
|
||||
// --- ¡AÑADE ESTAS LÍNEAS PARA CONVERTIR A BOOLEANO REAL! ---
|
||||
$reprogramming = filter_var($reprogramming, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
|
||||
$changeInstaller = filter_var($changeInstaller, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
|
||||
// -----------------------------------------------------------
|
||||
|
||||
// Puedes volver a loggear los valores para confirmar la conversión (opcional)
|
||||
$log->appendLog("DEBUG: Valores después de conversión - Reprogramming: " . var_export($reprogramming, true) . ", ChangeInstaller: " . var_export($changeInstaller, true) . PHP_EOL);
|
||||
|
||||
$ch = curl_init();
|
||||
curl_setopt($ch, CURLOPT_URL, 'https://api.callbell.eu/v1/messages/send');
|
||||
@ -137,24 +134,38 @@ class ClientCallBellAPI
|
||||
'Content-Type: application/json',
|
||||
]);
|
||||
|
||||
$campo1 = sprintf('*%s*', $jobNotificationData['clientFullName']);
|
||||
$campo1 = sprintf(' *%s*', $jobNotificationData['clientFullName']);
|
||||
$campo2 = sprintf('*#%s*', $jobNotificationData['jobId']);
|
||||
$campo3 = sprintf('*%s*', $jobNotificationData['date']);
|
||||
$campo3 = sprintf('%s', $jobNotificationData['date']);
|
||||
$campo4 = sprintf('*%s*', $jobNotificationData['installerName']);
|
||||
|
||||
if ($reprogramming && $changeInstaller === false) {
|
||||
$log->appendLog("DEBUG: Valores antes de la estructura IF - Reprogramming: " . var_export($reprogramming, true) . ", ChangeInstaller: " . var_export($changeInstaller, true) . PHP_EOL);
|
||||
|
||||
if ($reprogramming && ! $changeInstaller) {
|
||||
// Case: true, false
|
||||
//Enviar notificación de reprogramación al cliente
|
||||
$log->appendLog("Enviando notificación de reprogramación al cliente, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL);
|
||||
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\"],\n \"template_uuid\": \"70579353773f4de1836d4f9b6bf6074d\",\n \"optin_contact\": true\n }";
|
||||
}
|
||||
if ($changeInstaller) {
|
||||
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\"],\n \"template_uuid\": \"323631bf578e43fb8a0095f55978aae8\",\n \"optin_contact\": true\n }";
|
||||
} else if (! $reprogramming && $changeInstaller) {
|
||||
// Case: false, true
|
||||
//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);
|
||||
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\"],\n \"template_uuid\": \"0d57fd210595422caf2f5999642882a3\",\n \"optin_contact\": true\n }";
|
||||
} else {
|
||||
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\"],\n \"template_uuid\": \"c59c3ce2c9c6439b941b0d42d1435605\",\n \"optin_contact\": true\n }";
|
||||
} else if (! $reprogramming && ! $changeInstaller) { // <--- Ahora este else if está correctamente encadenado
|
||||
// Case: false, false
|
||||
//Enviar notificación normal de visita técnica al cliente
|
||||
$log->appendLog("Enviando notificación normal de visita técnica al cliente, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL);
|
||||
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\"],\n \"template_uuid\": \"c0ef8228b50a4d9690a2e87bc11e9ab3\",\n \"optin_contact\": true\n }";
|
||||
}else if ($reprogramming && $changeInstaller) { // <--- Ahora este else if está correctamente encadenado
|
||||
// Case: true, true
|
||||
//Enviar notificación de cambio de instalador y reprogramación al cliente
|
||||
$log->appendLog("Enviando notificación de cambio de instalador y reprogramación al cliente, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL);
|
||||
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\"],\n \"template_uuid\": \"99e2629a3be2421687037c001222bfe4\",\n \"optin_contact\": true\n }";
|
||||
} else {
|
||||
// Case: true, true (la única combinación restante con booleanos)
|
||||
$log->appendLog("No se encontró una opción válida para enviar la notificación (reprogramming y changeInstaller son true)." . PHP_EOL);
|
||||
// Decide qué hacer aquí, ¿Quizás devolver false? ¿O manejar esta combinación?
|
||||
return false; // O el manejo adecuado para true/true
|
||||
}
|
||||
|
||||
$log->appendLog("La cadena CURL que se envia es: " . $curl_string);
|
||||
@ -190,7 +201,8 @@ class ClientCallBellAPI
|
||||
$log->appendLog("Ruta no prevista en la función." . PHP_EOL);
|
||||
return false;
|
||||
}
|
||||
public function sendJobNotificationWhatsAppToInstaller($installerWhatsAppNumber, $jobInstallerNotificationData, $reprogramming = false, $changeInstaller = false, $passwordAntenaCliente): bool
|
||||
|
||||
public function sendJobNotificationWhatsAppToInstaller($installerWhatsAppNumber, $jobInstallerNotificationData, $reprogramming, $changeInstaller, $passwordAntenaCliente): bool
|
||||
{
|
||||
|
||||
$log = PluginLogManager::create(); //Initialize Logger
|
||||
@ -198,6 +210,14 @@ class ClientCallBellAPI
|
||||
$jsonJobNotificationData = json_encode($jobInstallerNotificationData, true);
|
||||
$log->appendLog("Datos de la notificación de tarea: " . $jsonJobNotificationData . PHP_EOL);
|
||||
|
||||
// --- ¡AÑADE ESTAS LÍNEAS PARA CONVERTIR A BOOLEANO REAL! ---
|
||||
$reprogramming = filter_var($reprogramming, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
|
||||
$changeInstaller = filter_var($changeInstaller, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
|
||||
// -----------------------------------------------------------
|
||||
|
||||
// Puedes volver a loggear los valores para confirmar la conversión (opcional)
|
||||
$log->appendLog("DEBUG: Valores después de conversión - Reprogramming: " . var_export($reprogramming, true) . ", ChangeInstaller: " . var_export($changeInstaller, true) . PHP_EOL);
|
||||
|
||||
$ch = curl_init();
|
||||
curl_setopt($ch, CURLOPT_URL, 'https://api.callbell.eu/v1/messages/send');
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
@ -207,7 +227,6 @@ class ClientCallBellAPI
|
||||
'Content-Type: application/json',
|
||||
]);
|
||||
|
||||
|
||||
$campo1 = $jobInstallerNotificationData['installerName'];
|
||||
if ($changeInstaller) {
|
||||
$campo2 = $jobInstallerNotificationData['subjectOfChange'];
|
||||
@ -215,7 +234,7 @@ class ClientCallBellAPI
|
||||
$campo4 = $jobInstallerNotificationData['clientFullName'];
|
||||
$campo5 = $jobInstallerNotificationData['additionalChangeData'];
|
||||
} else {
|
||||
$campo2 = sprintf("*#%s*", $jobInstallerNotificationData['jobId']);
|
||||
$campo2 = sprintf("#%s", $jobInstallerNotificationData['jobId']);
|
||||
$campo3 = $jobInstallerNotificationData['clientFullName'];
|
||||
// $campo4 = $jobInstallerNotificationData['clientAddress'];
|
||||
$campo4 = $jobInstallerNotificationData['clientWhatsApp'];
|
||||
@ -223,25 +242,24 @@ class ClientCallBellAPI
|
||||
$campo6 = $jobInstallerNotificationData['jobDescription'];
|
||||
$campo7 = $jobInstallerNotificationData['gmapsLocation'];
|
||||
$campo8 = $passwordAntenaCliente;
|
||||
|
||||
}
|
||||
|
||||
|
||||
if ($reprogramming && $changeInstaller === false) {
|
||||
|
||||
if ($reprogramming && ! $changeInstaller) {
|
||||
//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);
|
||||
$curl_string = "{\n \"to\": \"$installerWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\", \"$campo5\", \"$campo6\", \"$campo7\", \"$campo8\"],\n \"template_uuid\": \"7eb4d8e27cf740779dd6777fad7ffaf4\",\n \"optin_contact\": true\n }";
|
||||
|
||||
} else if ($changeInstaller) {
|
||||
} else if (! $reprogramming && $changeInstaller) {
|
||||
//Enviar notificación de cambio de instalador
|
||||
$log->appendLog("Enviando notificación de cambio de instalador al instalador, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL);
|
||||
$log->appendLog("Enviando notificación de cambio de instalador al instalador anterior, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL);
|
||||
$curl_string = "{\n \"to\": \"$installerWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\", \"$campo5\"],\n \"template_uuid\": \"e1aa2b0fd3884595918f4ac2676acd29\",\n \"optin_contact\": true\n }";
|
||||
|
||||
} else {
|
||||
}else if ($reprogramming && $changeInstaller) {
|
||||
//Enviar notificación de cambio de instalador
|
||||
$log->appendLog("Enviando notificación de cambio de instalador al instalador y notificación de reprogramación al instalador, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL);
|
||||
$curl_string = "{\n \"to\": \"$installerWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\", \"$campo5\"],\n \"template_uuid\": \"e1aa2b0fd3884595918f4ac2676acd29\",\n \"optin_contact\": true\n }";
|
||||
} else if (! $reprogramming && ! $changeInstaller) {
|
||||
//Enviar notificación normal de asignación de tarea
|
||||
$log->appendLog("Enviando notificación normal de asignación de tarea al instalador, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL);
|
||||
$curl_string = "{\n \"to\": \"$installerWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\", \"$campo5\", \"$campo6\", \"$campo7\", \"$campo8\"],\n \"template_uuid\": \"fa7f3f8e25934e159a9203eb1cd7f7a6\",\n \"optin_contact\": true\n }";
|
||||
$curl_string = "{\n \"to\": \"$installerWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\", \"$campo5\", \"$campo6\", \"$campo7\", \"$campo8\"],\n \"template_uuid\": \"670bedde35b3416f8c1a27f995ebe350\",\n \"optin_contact\": true\n }";
|
||||
}
|
||||
|
||||
$log->appendLog("La cadena CURL que se envia es: " . $curl_string);
|
||||
@ -276,7 +294,6 @@ class ClientCallBellAPI
|
||||
// Valor de retorno predeterminado en caso de que ninguna condición se cumpla
|
||||
$log->appendLog("Ruta no prevista en la función." . PHP_EOL);
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
public function sendPaymentNotificationWhatsApp($clientWhatsAppNumber, $notificationData): bool
|
||||
@ -293,20 +310,17 @@ class ClientCallBellAPI
|
||||
//Path base del comprobante de pago
|
||||
$pdf_payment_path = '';
|
||||
|
||||
|
||||
$this->ucrmApi = UcrmApi::create();
|
||||
$payments = $this->ucrmApi->get(
|
||||
'payments/',
|
||||
[
|
||||
'clientId' => $notificationData->clientData['id'],
|
||||
'limit' => 1,
|
||||
'direction' => 'DESC'
|
||||
'direction' => 'DESC',
|
||||
|
||||
]
|
||||
);
|
||||
|
||||
|
||||
|
||||
$payment_id = $payments[0]['id'];
|
||||
$payment_amount = '$' . $payments[0]['amount'];
|
||||
//$saldo = '$' . $notificationData->clientData['accountBalance'];
|
||||
@ -336,8 +350,6 @@ class ClientCallBellAPI
|
||||
'verify' => false,
|
||||
]);
|
||||
|
||||
|
||||
|
||||
try {
|
||||
// Hacer la solicitud GET para obtener el PDF
|
||||
$response = $clientGuzzleHttp->request('GET', "payments/$payment_id/pdf");
|
||||
@ -357,7 +369,7 @@ class ClientCallBellAPI
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!file_exists($rutaArchivo)) {
|
||||
if (! file_exists($rutaArchivo)) {
|
||||
$log->appendLog("El archivo PDF no existe: $rutaArchivo" . PHP_EOL);
|
||||
return false;
|
||||
}
|
||||
@ -369,20 +381,11 @@ class ClientCallBellAPI
|
||||
|
||||
$log->appendLog("El archivo PDF es válido y tiene contenido: $rutaArchivo" . PHP_EOL);
|
||||
$rutaImagen = __DIR__ . '/../../comprobantes/' . str_replace('.pdf', '.png', $fileNameComprobante);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
} catch (\Exception $e) {
|
||||
$log->appendLog("Error al manejar el comprobante de pago: " . $e->getMessage() . PHP_EOL);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
try {
|
||||
$image = new Imagick();
|
||||
$image->setResolution(300, 300);
|
||||
@ -398,16 +401,12 @@ class ClientCallBellAPI
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
$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
|
||||
|
||||
$log->appendLog("Se terminó de subir comprobante a wordpress " . PHP_EOL);
|
||||
|
||||
|
||||
|
||||
|
||||
//$log->appendLog("Entrando al metodo sendPaymentNotificationWhatsAp" . PHP_EOL);
|
||||
$ch = curl_init();
|
||||
curl_setopt($ch, CURLOPT_URL, 'https://api.callbell.eu/v1/messages/send');
|
||||
@ -418,8 +417,6 @@ class ClientCallBellAPI
|
||||
'Content-Type: application/json',
|
||||
]);
|
||||
|
||||
|
||||
|
||||
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"document\",\n \"content\": {\n \"text\": \"S/M\",\n \"url\": \"$url_file\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$payment_amount\", \"$saldoTexto\"],\n \"template_uuid\": \"57ead79cebd14902921477922403093b\",\n \"optin_contact\": true\n }";
|
||||
$log->appendLog("La cadena CURL que se envia es: " . $curl_string);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, $curl_string);
|
||||
@ -466,11 +463,10 @@ class ClientCallBellAPI
|
||||
public function sendTextPaymentNotificationWhatsApp($clientWhatsAppNumber, $notificationData): bool
|
||||
{
|
||||
|
||||
|
||||
$nombre_cliente = sprintf("%s %s", $notificationData->clientData['firstName'], $notificationData->clientData['lastName']);
|
||||
$folio = $notificationData->paymentData['id'];
|
||||
$client_id = $notificationData->clientData['id'];
|
||||
$fecha_pago = null;
|
||||
$fecha_pago = '';
|
||||
$cantidad_pagada = $notificationData->paymentData['amount'];
|
||||
$metodo_pago = '';
|
||||
//$invoice_id= null;
|
||||
@ -481,9 +477,6 @@ class ClientCallBellAPI
|
||||
$texto_credito = null;
|
||||
$creditoClienteBase = $notificationData->clientData['accountCredit'];
|
||||
|
||||
|
||||
|
||||
|
||||
switch ($notificationData->paymentData['methodId']) {
|
||||
case '11721cdf-a498-48be-903e-daa67552e4f6':
|
||||
$metodo_pago = 'Cheque 📄';
|
||||
@ -518,11 +511,8 @@ class ClientCallBellAPI
|
||||
default:
|
||||
$metodo_pago = 'Desconocido, revisar metodos de pago no contemplados';
|
||||
break;
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
$log = PluginLogManager::create(); //Initialize Logger
|
||||
|
||||
$log->appendLog("Eviando comprobante de pago al cliente: " . $notificationData->clientData['id'] . ' con número: ' . $clientWhatsAppNumber . PHP_EOL);
|
||||
@ -534,14 +524,13 @@ class ClientCallBellAPI
|
||||
//Path base del comprobante de pago
|
||||
$pdf_payment_path = '';
|
||||
|
||||
|
||||
$this->ucrmApi = UcrmApi::create();
|
||||
$payments = $this->ucrmApi->get(
|
||||
'payments/',
|
||||
[
|
||||
'clientId' => $notificationData->clientData['id'],
|
||||
'limit' => 1,
|
||||
'direction' => 'DESC'
|
||||
'direction' => 'DESC',
|
||||
|
||||
]
|
||||
);
|
||||
@ -550,7 +539,6 @@ class ClientCallBellAPI
|
||||
$datos_paymentJsonText = json_encode($payments, true);
|
||||
$log->appendLog("Datos traidos con payment api: " . $datos_paymentJsonText . PHP_EOL);
|
||||
|
||||
|
||||
// $log->appendLog("Check 1" . PHP_EOL);
|
||||
$paymentDate = new DateTime($fecha_pago);
|
||||
|
||||
@ -560,7 +548,6 @@ class ClientCallBellAPI
|
||||
// Formatear la fecha como "d/m/Y g:ia" (día/mes/año hora:minutos am/pm)
|
||||
$fecha_pago = $paymentDate->format('d/m/Y g:ia');
|
||||
|
||||
|
||||
$accountBalance = $notificationData->clientData['accountBalance'];
|
||||
$saldoTexto = '';
|
||||
|
||||
@ -582,21 +569,15 @@ class ClientCallBellAPI
|
||||
|
||||
if ($creditoClienteBase > 0 && empty($notificationData->paymentData['paymentCovers'])) {
|
||||
|
||||
|
||||
$texto_credito = "La cantidad que sobra de $creditoPorPagoFormateado se ha convertido a crédito";
|
||||
$log->appendLog("La cantidad que sobra de $creditoPorPagoFormateado se ha convertido a crédito" . PHP_EOL);
|
||||
|
||||
|
||||
|
||||
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"John Doe\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$folio\", \"$client_id\", \"$fecha_pago\", \"$cantidad_pagadaFormateada\", \"$metodo_pago\", \"$saldoTexto\", \"$texto_credito\"],\n \"template_uuid\": \"4ac9dc060cf746b6ad7f2e8acad355e0\",\n \"optin_contact\": true\n }";
|
||||
|
||||
|
||||
} else {
|
||||
|
||||
if ($creditoPorPago > 0) {
|
||||
$texto_credito = "La cantidad que sobra de $creditoPorPagoFormateado se ha convertido a crédito";
|
||||
$log->appendLog("La cantidad que sobra de $creditoPorPagoFormateado se ha convertido a crédito" . PHP_EOL);
|
||||
|
||||
} else {
|
||||
$texto_credito = '_________________________';
|
||||
}
|
||||
@ -613,11 +594,9 @@ class ClientCallBellAPI
|
||||
|
||||
$log->appendLog("Verificar 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);
|
||||
|
||||
$invoiceIds = ''; // Variable para almacenar los invoiceId
|
||||
@ -655,14 +634,10 @@ class ClientCallBellAPI
|
||||
$log->appendLog('Numero de factura: ' . $responseInvoicesJSON['number'] . PHP_EOL);
|
||||
$log->appendLog('TOTAL de factura: ' . $responseInvoicesJSON['total'] . PHP_EOL);
|
||||
$total_factura = $responseInvoicesJSON['total'];
|
||||
|
||||
|
||||
|
||||
} catch (\Exception $e) {
|
||||
$log->appendLog("Error con un problema al obtener alguna factura del cliente: " . $e->getMessage() . PHP_EOL);
|
||||
return false;
|
||||
}
|
||||
|
||||
} else {
|
||||
$log->appendLog("no hay datos en payment covers" . PHP_EOL);
|
||||
$invoiceIds = $notificationData->paymentData['id'];
|
||||
@ -675,13 +650,8 @@ class ClientCallBellAPI
|
||||
$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 }";
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
//$log->appendLog("Entrando al metodo sendPaymentNotificationWhatsAp" . PHP_EOL);
|
||||
$ch = curl_init();
|
||||
curl_setopt($ch, CURLOPT_URL, 'https://api.callbell.eu/v1/messages/send');
|
||||
@ -692,9 +662,6 @@ class ClientCallBellAPI
|
||||
'Content-Type: application/json',
|
||||
]);
|
||||
|
||||
|
||||
|
||||
|
||||
//$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"document\",\n \"content\": {\n \"text\": \"S/M\",\n \"url\": \"$url_file\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$payment_amount\", \"$saldo\"],\n \"template_uuid\": \"6c0df98317b44f7b8666375a6cc8454c\",\n \"optin_contact\": true\n }";
|
||||
|
||||
// $curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\"],\n \"template_uuid\": \"55705f1fe4e24bab80104dc2643fe11c\",\n \"optin_contact\": true\n }";
|
||||
@ -743,7 +710,6 @@ class ClientCallBellAPI
|
||||
public function sendOverdueNotificationWhatsApp($clientWhatsAppNumber, $notificationData): void
|
||||
{
|
||||
|
||||
|
||||
$log = PluginLogManager::create(); //Initialize Logger
|
||||
|
||||
// URL base de la API
|
||||
@ -753,7 +719,6 @@ class ClientCallBellAPI
|
||||
//Path base del comprobante de pago
|
||||
//$pdf_payment_path = '';
|
||||
|
||||
|
||||
// $this->ucrmApi = UcrmApi::create();
|
||||
// $invoices = $this->ucrmApi->get(
|
||||
// 'invoices/',
|
||||
@ -787,8 +752,6 @@ class ClientCallBellAPI
|
||||
// 'verify' => false,
|
||||
// ]);
|
||||
|
||||
|
||||
|
||||
// if (empty($notificationData->clientData['contacts'][0]['email'])) {
|
||||
// $log->appendLog("El cliente no tiene correo" . PHP_EOL);
|
||||
// } else {
|
||||
@ -816,9 +779,6 @@ class ClientCallBellAPI
|
||||
// $log->appendLog("La ruta no es válida o no existe" . PHP_EOL);
|
||||
// }
|
||||
|
||||
|
||||
|
||||
|
||||
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"SIIP INTERNET\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\",\n },\n \"template_values\": [\"$nombre_cliente\", \"$saldo\"],\n \"template_uuid\": \"9e7024c0a61a4c49b382150d26888dc2\",\n \"optin_contact\": true\n }";
|
||||
//$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"document\",\n \"content\": {\n \"text\": \"S/M\",\n \"url\": \"$url_file\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$payment_amount\", \"$saldo\"],\n \"template_uuid\": \"57ead79cebd14902921477922403093b\",\n \"optin_contact\": true\n }";
|
||||
//$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"document\",\n \"content\": {\n \"text\": \"S/M\",\n \"url\": \"$url_file\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$payment_amount\", \"$saldo\"],\n \"template_uuid\": \"6c0df98317b44f7b8666375a6cc8454c\",\n \"optin_contact\": true\n }";
|
||||
@ -831,10 +791,8 @@ class ClientCallBellAPI
|
||||
$log->appendLog("Response del CallBell: " . $response);
|
||||
|
||||
curl_close($ch);
|
||||
|
||||
}
|
||||
|
||||
|
||||
public function getContactWhatsapp($cellphone_number): string
|
||||
{
|
||||
// URL de la API REST
|
||||
@ -848,7 +806,7 @@ class ClientCallBellAPI
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
||||
'Authorization: Bearer ' . $this->CallBellAPIToken,
|
||||
'Content-Type: application/json'
|
||||
'Content-Type: application/json',
|
||||
]);
|
||||
|
||||
// Ejecutar la solicitud y obtener la respuesta
|
||||
@ -889,8 +847,6 @@ class ClientCallBellAPI
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
$log->appendLog("Dentro del proceso del patch: " . PHP_EOL);
|
||||
$this->ucrmApi = UcrmApi::create();
|
||||
$payments = $this->ucrmApi->get(
|
||||
@ -898,7 +854,7 @@ class ClientCallBellAPI
|
||||
[
|
||||
'clientId' => $notificationData->clientData['id'],
|
||||
'limit' => 1,
|
||||
'direction' => 'DESC'
|
||||
'direction' => 'DESC',
|
||||
|
||||
]
|
||||
);
|
||||
@ -910,10 +866,6 @@ class ClientCallBellAPI
|
||||
//$log->appendLog("Esto es lo que trae la fecha mas reciente de los pagos: " . $notificationData->paymentData[0]['createdDate']. PHP_EOL);
|
||||
// $log->appendLog("Esto es lo que trae la fecha mas reciente de los pagos opcion 2: " . $payments[0]['createdDate'] . PHP_EOL);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
$uuid = $response_getContactCallBell['contact']['uuid'];
|
||||
$ch = curl_init();
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
@ -974,11 +926,8 @@ class ClientCallBellAPI
|
||||
default:
|
||||
$payment_method = 'Desconocido, revisar metodos de pago no contemplados';
|
||||
break;
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
$fecha_actual = new DateTime();
|
||||
$fecha_actual->modify('-6 hours');
|
||||
$fecha_actual_ajustada = $fecha_actual->format("d/m/Y H:i");
|
||||
@ -1034,15 +983,11 @@ class ClientCallBellAPI
|
||||
'"Antena/Sectorial": "' . $antenaSectorial . '"' .
|
||||
'}';
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
$data_CRM = array(
|
||||
$data_CRM = [
|
||||
//"uuid" => $json_responseAPI->contact->uuid,
|
||||
"name" => sprintf("%s %s", $notificationData->clientData['firstName'], $notificationData->clientData['lastName']),
|
||||
|
||||
"custom_fields" => array(
|
||||
"custom_fields" => [
|
||||
"Cliente" => $notificationData->clientData['id'],
|
||||
"Domicilio" => ($notificationData->clientData['fullAddress'] == null) ? '📍❌ Sin domicilio' : '📍 ' . $notificationData->clientData['fullAddress'],
|
||||
"Nombre" => sprintf("👤 %s %s", $notificationData->clientData['firstName'], $notificationData->clientData['lastName']),
|
||||
@ -1055,18 +1000,17 @@ class ClientCallBellAPI
|
||||
"Fecha Ultima Actualizacion" => '📆🔄️ ' . $fecha_actual_ajustada,
|
||||
"Clabe Interbancaria" => $clabeInterbancaria,
|
||||
"Site" => $site,
|
||||
"Antena/Sectorial" => $antenaSectorial
|
||||
)
|
||||
);
|
||||
"Antena/Sectorial" => $antenaSectorial,
|
||||
],
|
||||
];
|
||||
|
||||
$log->appendLog("JSON con los datos a actualizar: " . json_encode($data_CRM) . PHP_EOL);
|
||||
|
||||
|
||||
$data_CRM2 = array(
|
||||
"custom_fields" => array(
|
||||
$data_CRM2 = [
|
||||
"custom_fields" => [
|
||||
"Resumen" => $resumenClienteJSON,
|
||||
)
|
||||
);
|
||||
],
|
||||
];
|
||||
|
||||
$log->appendLog("JSON con los datos a actualizar del resumen: " . $resumenClienteJSON . PHP_EOL);
|
||||
|
||||
@ -1096,7 +1040,6 @@ class ClientCallBellAPI
|
||||
// $this->deleteFileWordPressAndLocal($fileNameComprobante);
|
||||
// }
|
||||
|
||||
|
||||
// $json_data_patch = '{
|
||||
// "attributes": [
|
||||
// {
|
||||
@ -1118,7 +1061,6 @@ class ClientCallBellAPI
|
||||
// 'verify' => false,
|
||||
// ]); //aquí se contruye la petición para hacer patch hacia el cliente en sus custom fields con la API del UISP UCRM
|
||||
|
||||
|
||||
// } catch (GuzzleException $error) {
|
||||
// echo "Error al hacer el patch al CRM: " . $error->getMessage() . PHP_EOL;
|
||||
// //exit();
|
||||
@ -1130,17 +1072,13 @@ class ClientCallBellAPI
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function patchServiceStatusWhatsApp($response_getContactCallBell, $notificationData)
|
||||
{
|
||||
|
||||
$log = PluginLogManager::create(); //Initialize Logger
|
||||
|
||||
|
||||
$log->appendLog("Actualizando estado del servicio " . PHP_EOL);
|
||||
|
||||
|
||||
$uuid = $response_getContactCallBell['contact']['uuid'];
|
||||
$ch = curl_init();
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
@ -1155,18 +1093,13 @@ class ClientCallBellAPI
|
||||
$log->appendLog("Nombre del cliente al que se va a actualizar el estado del servicio: " . $nombre_cliente . PHP_EOL);
|
||||
$log->appendLog("UUID: " . $uuid . PHP_EOL);
|
||||
|
||||
|
||||
|
||||
|
||||
$fecha_actual = new DateTime();
|
||||
$fecha_actual->modify('-6 hours');
|
||||
$fecha_actual_ajustada = $fecha_actual->format("d/m/Y H:i");
|
||||
|
||||
|
||||
|
||||
$data_CRM = array(
|
||||
$data_CRM = [
|
||||
"name" => $nombre_cliente,
|
||||
"custom_fields" => array(
|
||||
"custom_fields" => [
|
||||
"Estado" => (
|
||||
isset($notificationData->serviceData['status'])
|
||||
&& $notificationData->serviceData['status'] == 3
|
||||
@ -1174,11 +1107,9 @@ class ClientCallBellAPI
|
||||
(isset($notificationData->serviceData['status'])
|
||||
&& $notificationData->serviceData['status'] == 1)
|
||||
? '🟢 Activo' : '🚫 Finalizado'),
|
||||
"Fecha Ultima Actualizacion" => '📆🔄️ ' . $fecha_actual_ajustada
|
||||
)
|
||||
);
|
||||
|
||||
|
||||
"Fecha Ultima Actualizacion" => '📆🔄️ ' . $fecha_actual_ajustada,
|
||||
],
|
||||
];
|
||||
|
||||
$log->appendLog("JSON con los datos a actualizar: " . json_encode($data_CRM) . PHP_EOL);
|
||||
|
||||
@ -1187,8 +1118,6 @@ class ClientCallBellAPI
|
||||
$response = curl_exec($ch);
|
||||
$log->appendLog("Response Patch CallBell: " . $response . PHP_EOL);
|
||||
curl_close($ch);
|
||||
|
||||
|
||||
} else {
|
||||
$log->appendLog("No hay cambios en el estado del servicio que actualizar " . PHP_EOL);
|
||||
}
|
||||
@ -1218,7 +1147,6 @@ class ClientCallBellAPI
|
||||
|
||||
$log->appendLog("file_to_upload: " . $file_to_upload . PHP_EOL);
|
||||
|
||||
|
||||
// Conexión 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);
|
||||
@ -1232,10 +1160,10 @@ class ClientCallBellAPI
|
||||
$log->appendLog("El archivo ha sido cargado exitosamente." . 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
|
||||
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
|
||||
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
|
||||
|
||||
} else {
|
||||
$log->appendLog("Error al cargar el archivo " . PHP_EOL);
|
||||
@ -1285,15 +1213,12 @@ class ClientCallBellAPI
|
||||
// return $url;
|
||||
// }
|
||||
|
||||
|
||||
} else {
|
||||
$log->appendLog("No se pudo conectar o iniciar sesión en el servidor FTP." . PHP_EOL);
|
||||
return '';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
function deleteFilesWordpressExceptLastHundred($log, $ftp_conn, $remote_folder): bool
|
||||
{
|
||||
|
||||
@ -1336,10 +1261,8 @@ class ClientCallBellAPI
|
||||
ftp_close($ftp_conn);
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* /Elimina los archivos del directorio de comprobantes de pago a excepción de los últimos 100 para evitar errores de envío
|
||||
* @return void
|
||||
@ -1349,10 +1272,9 @@ class ClientCallBellAPI
|
||||
$log = PluginLogManager::create(); //Initialize Logger
|
||||
$directory = __DIR__ . '/../../comprobantes/';
|
||||
// Verificar si el directorio existe
|
||||
if (!is_dir($directory)) {
|
||||
if (! is_dir($directory)) {
|
||||
$log->appendLog('El directorio no existe.');
|
||||
die("El directorio no existe.");
|
||||
|
||||
}
|
||||
|
||||
// Obtener la lista de archivos en el directorio
|
||||
@ -1379,5 +1301,4 @@ class ClientCallBellAPI
|
||||
$log->appendLog("Hay menos de 100 archivos en el directorio. No se eliminarán archivos." . PHP_EOL);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
212
src/Plugin.php
212
src/Plugin.php
@ -1,14 +1,13 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
declare (strict_types = 1);
|
||||
|
||||
namespace SmsNotifier;
|
||||
|
||||
use Psr\Log\LogLevel;
|
||||
use SmsNotifier\Facade\TwilioNotifierFacade;
|
||||
use SmsNotifier\Facade\PluginNotifierFacade;
|
||||
use SmsNotifier\Facade\PluginOxxoNotifierFacade;
|
||||
use SmsNotifier\Facade\TwilioNotifierFacade;
|
||||
use SmsNotifier\Factory\NotificationDataFactory;
|
||||
use SmsNotifier\Service\Logger;
|
||||
use SmsNotifier\Service\OptionsManager;
|
||||
@ -56,7 +55,6 @@ class Plugin
|
||||
*/
|
||||
protected $ucrmApi;
|
||||
|
||||
|
||||
public function __construct(
|
||||
Logger $logger,
|
||||
OptionsManager $optionsManager,
|
||||
@ -108,23 +106,19 @@ class Plugin
|
||||
$this->logger->setLogLevelThreshold(LogLevel::DEBUG);
|
||||
}
|
||||
|
||||
|
||||
$userInput = file_get_contents('php://input'); //se recibe el json del webhook
|
||||
//imprimir el json del webhook
|
||||
$this->logger->debug('valor del webhook: ' . $userInput . PHP_EOL);
|
||||
|
||||
|
||||
|
||||
if (!$userInput) {
|
||||
if (! $userInput) {
|
||||
$this->logger->warning('no input');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
$jsonData = @json_decode($userInput, true, 50);
|
||||
|
||||
if (!isset($jsonData['uuid'])) {
|
||||
if (! isset($jsonData['uuid'])) {
|
||||
$this->logger->info('No UUID found in the webhook data');
|
||||
//$this->logger->error('JSON error: ' . json_last_error_msg());
|
||||
|
||||
@ -134,20 +128,20 @@ class Plugin
|
||||
if ($jsonData) {
|
||||
switch ($jsonData['type']) {
|
||||
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') {
|
||||
$this->pluginNotifierFacade->createPaymentIntent($jsonData);
|
||||
}
|
||||
break;
|
||||
case 'payout.failed':
|
||||
$this->logger->info('Evento de transferencia fallida encontrado: '. json_encode($jsonData) . PHP_EOL);
|
||||
$this->logger->info('Evento de transferencia fallida encontrado: ' . json_encode($jsonData) . PHP_EOL);
|
||||
//imprimir detalles del fallo
|
||||
$this->logger->info('Detalles del fallo: ' . json_encode($jsonData ));
|
||||
$this->logger->info('Detalles del fallo: ' . json_encode($jsonData));
|
||||
break;
|
||||
case 'payment_intent.partially_funded':
|
||||
$this->logger->info('Evento de pago parcialmente financiado encontrado: '. json_encode($jsonData) . PHP_EOL);
|
||||
$this->logger->info('Evento de pago parcialmente financiado encontrado: ' . json_encode($jsonData) . PHP_EOL);
|
||||
//imprimir detalles del evento o pago
|
||||
$this->logger->info('Detalles del evento: ' . json_encode($jsonData ));
|
||||
$this->logger->info('Detalles del evento: ' . json_encode($jsonData));
|
||||
break;
|
||||
case 'inbound_payment.payment_attempt':
|
||||
//$this->logger->info('Evento de Pago de OXXO recibido: '. json_encode($jsonData) . PHP_EOL);
|
||||
@ -158,10 +152,9 @@ class Plugin
|
||||
case 'oxxo.request':
|
||||
$this->logger->info('Evento de solicitud de referencia de oxxo recibido' . PHP_EOL);
|
||||
|
||||
|
||||
// Construir la URL basada en el "client_id"
|
||||
// $url = "https://siip.mx/wp/wp-content/uploads/img/voucher.png";
|
||||
if (!empty($jsonData['amount'])) {
|
||||
if (! empty($jsonData['amount'])) {
|
||||
$this->logger->info('Referencia persnoalizada, Valor del monto: ' . $jsonData['amount'] . PHP_EOL);
|
||||
$intentos = 0;
|
||||
do {
|
||||
@ -236,11 +229,6 @@ class Plugin
|
||||
// $webhook_string = json_encode($event_json);
|
||||
// $this->logger->debug("El valor de webhook_string: " . $webhook_string . PHP_EOL);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
$notification = $this->notificationDataFactory->getObject($jsonData);
|
||||
$this->logger->debug('valor el evento recibido por webhook: ' . $notification->eventName . PHP_EOL);
|
||||
$this->logger->debug('Valor de JSON: ' . json_encode($jsonData) . PHP_EOL);
|
||||
@ -253,9 +241,9 @@ class Plugin
|
||||
$this->logger->info('Webhook test successful.');
|
||||
|
||||
return;
|
||||
} else if($notification->changeType === 'paperless.update') {
|
||||
} else if ($notification->changeType === 'paperless.update') {
|
||||
//imprimir el webhook json
|
||||
$this->logger->info( 'Webhook de paperless update: ' . json_encode($jsonData) . PHP_EOL);
|
||||
$this->logger->info('Webhook de paperless update: ' . json_encode($jsonData) . PHP_EOL);
|
||||
}
|
||||
// if (!$notification->clientId) {
|
||||
// $this->logger->warning('No client specified, cannot notify them.');
|
||||
@ -279,11 +267,8 @@ class Plugin
|
||||
$payment_method_id = $notification->paymentData['methodId'];
|
||||
//$this->logger->debug('Metodo de pago: ' . $notification->paymentData['methodId'] . PHP_EOL);
|
||||
|
||||
|
||||
|
||||
$payment_method = '';
|
||||
|
||||
|
||||
switch ($payment_method_id) {
|
||||
|
||||
case '11721cdf-a498-48be-903e-daa67552e4f6':
|
||||
@ -356,16 +341,64 @@ class Plugin
|
||||
$payment_method = 'Desconocido, revisar metodos de pago no contemplados';
|
||||
break;
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
} else if ($notification->eventName === 'client.edit') {
|
||||
$this->logger->debug('Se actualiza a un cliente');
|
||||
$this->logger->debug('Valor de json_data: ' . json_encode($jsonData));
|
||||
//ejemplo de json_data: {"uuid":"17e043a7-03b5-4312-ab81-a7818124a77e","changeType":"edit","entity":"client","entityId":"158","eventName":"client.edit","extraData":{"entity":{"id":158,"userIdent":null,"previousIsp":null,"isLead":false,"clientType":1,"companyName":null,"companyRegistrationNumber":null,"companyTaxId":null,"companyWebsite":null,"street1":"23 San Luis","street2":null,"city":"Dolores Hidalgo Cuna de la Independencia Nacional","countryId":173,"stateId":null,"zipCode":"37804","fullAddress":"San Luis 23, Guadalupe, Dolores Hidalgo Cuna de la Independencia Nacional, Gto., M\u00e9xico","invoiceStreet1":null,"invoiceStreet2":null,"invoiceCity":null,"invoiceStateId":null,"invoiceCountryId":null,"invoiceZipCode":null,"invoiceAddressSameAsContact":true,"note":null,"sendInvoiceByPost":null,"invoiceMaturityDays":null,"stopServiceDue":null,"stopServiceDueDays":null,"organizationId":1,"tax1Id":null,"tax2Id":null,"tax3Id":null,"registrationDate":"2025-01-06T00:00:00-0600","leadConvertedAt":"2025-02-09T03:15:49-0600","companyContactFirstName":null,"companyContactLastName":null,"isActive":false,"firstName":"Luis","lastName":"Guti\u00e9rrez","username":null,"contacts":[{"id":162,"clientId":158,"email":null,"phone":null,"name":null,"isBilling":true,"isContact":true,"types":[{"id":1,"name":"Billing"},{"id":2,"name":"General"}]}],"attributes":[],"accountBalance":0,"accountCredit":0,"accountOutstanding":0,"currencyCode":"MXN","organizationName":"SIIP Pruebas","bankAccounts":[],"tags":[],"invitationEmailSentDate":null,"avatarColor":"#2196f3","addressGpsLat":21.153272,"addressGpsLon":-100.9134508,"isArchived":false,"generateProformaInvoices":null,"usesProforma":false,"hasOverdueInvoice":false,"hasOutage":false,"hasSuspendedService":false,"hasServiceWithoutDevices":false,"referral":null,"hasPaymentSubscription":false,"hasAutopayCreditCard":false},"entityBeforeEdit":{"id":158,"userIdent":null,"previousIsp":null,"isLead":true,"clientType":1,"companyName":null,"companyRegistrationNumber":null,"companyTaxId":null,"companyWebsite":null,"street1":"23 San Luis","street2":null,"city":"Dolores Hidalgo Cuna de la Independencia Nacional","countryId":173,"stateId":null,"zipCode":"37804","fullAddress":"San Luis 23, Guadalupe, Dolores Hidalgo Cuna de la Independencia Nacional, Gto., M\u00e9xico","invoiceStreet1":null,"invoiceStreet2":null,"invoiceCity":null,"invoiceStateId":null,"invoiceCountryId":null,"invoiceZipCode":null,"invoiceAddressSameAsContact":true,"note":null,"sendInvoiceByPost":null,"invoiceMaturityDays":null,"stopServiceDue":null,"stopServiceDueDays":null,"organizationId":1,"tax1Id":null,"tax2Id":null,"tax3Id":null,"registrationDate":"2025-01-06T00:00:00-0600","leadConvertedAt":null,"companyContactFirstName":null,"companyContactLastName":null,"isActive":false,"firstName":"Luis","lastName":"Guti\u00e9rrez","username":null,"contacts":[{"id":162,"clientId":158,"email":null,"phone":null,"name":null,"isBilling":true,"isContact":true,"types":[{"id":1,"name":"Billing"},{"id":2,"name":"General"}]}],"attributes":[],"accountBalance":0,"accountCredit":0,"accountOutstanding":0,"currencyCode":"MXN","organizationName":"SIIP Pruebas","bankAccounts":[],"tags":[],"invitationEmailSentDate":null,"avatarColor":"#2196f3","addressGpsLat":21.153272,"addressGpsLon":-100.9134508,"isArchived":false,"generateProformaInvoices":null,"usesProforma":false,"hasOverdueInvoice":false,"hasOutage":false,"hasSuspendedService":false,"hasServiceWithoutDevices":false,"referral":null,"hasPaymentSubscription":false,"hasAutopayCreditCard":false}}}
|
||||
//ejemplo de json_data: {"uuid":"aacaf5c5-2bf4-44ea-864f-a24121b453bb","changeType":"edit","entity":"client","entityId":"171","eventName":"client.edit","extraData":{"entity":{"id":171,"userIdent":null,"previousIsp":null,"isLead":false,"clientType":1,"companyName":null,"companyRegistrationNumber":null,"companyTaxId":null,"companyWebsite":null,"street1":"Campeche 56","street2":null,"city":"Dolores Hidalgo","countryId":173,"stateId":null,"zipCode":"37800","fullAddress":"Campeche 56, Dolores Hidalgo, 37800","invoiceStreet1":null,"invoiceStreet2":null,"invoiceCity":null,"invoiceStateId":null,"invoiceCountryId":null,"invoiceZipCode":null,"invoiceAddressSameAsContact":true,"note":null,"sendInvoiceByPost":null,"invoiceMaturityDays":null,"stopServiceDue":null,"stopServiceDueDays":null,"organizationId":1,"tax1Id":null,"tax2Id":null,"tax3Id":null,"registrationDate":"2025-05-21T00:00:00-0600","leadConvertedAt":null,"companyContactFirstName":null,"companyContactLastName":null,"isActive":false,"firstName":"Archi","lastName":"Isalas","username":"mainstreamm2@gmail.com","contacts":[{"id":177,"clientId":171,"email":"mainstreamm2@gmail.com","phone":"4181878106","name":null,"isBilling":false,"isContact":false,"types":[]}],"attributes":[{"id":198,"clientId":171,"customAttributeId":10,"name":"Stripe Customer ID","key":"stripeCustomerId","value":"cus_SM2zH6IsjTz6ol","clientZoneVisible":true},{"id":199,"clientId":171,"customAttributeId":11,"name":"Clabe Interbancaria","key":"clabeInterbancaria","value":"124180950530868794","clientZoneVisible":true}],"accountBalance":0,"accountCredit":0,"accountOutstanding":0,"currencyCode":"MXN","organizationName":"SIIP Pruebas","bankAccounts":[],"tags":[],"invitationEmailSentDate":null,"avatarColor":"#f1df43","addressGpsLat":21.1572461,"addressGpsLon":-100.9377137,"isArchived":false,"generateProformaInvoices":null,"usesProforma":false,"hasOverdueInvoice":false,"hasOutage":false,"hasSuspendedService":false,"hasServiceWithoutDevices":true,"referral":null,"hasPaymentSubscription":false,"hasAutopayCreditCard":false},"entityBeforeEdit":{"id":171,"userIdent":null,"previousIsp":null,"isLead":false,"clientType":1,"companyName":null,"companyRegistrationNumber":null,"companyTaxId":null,"companyWebsite":null,"street1":"Campeche 56","street2":null,"city":"Dolores Hidalgo","countryId":173,"stateId":null,"zipCode":"37800","fullAddress":"Campeche 56, Dolores Hidalgo, 37800","invoiceStreet1":null,"invoiceStreet2":null,"invoiceCity":null,"invoiceStateId":null,"invoiceCountryId":null,"invoiceZipCode":null,"invoiceAddressSameAsContact":true,"note":null,"sendInvoiceByPost":null,"invoiceMaturityDays":null,"stopServiceDue":null,"stopServiceDueDays":null,"organizationId":1,"tax1Id":null,"tax2Id":null,"tax3Id":null,"registrationDate":"2025-05-21T00:00:00-0600","leadConvertedAt":null,"companyContactFirstName":null,"companyContactLastName":null,"isActive":false,"firstName":"Archi","lastName":"Isalas","username":"mainstreamm2@gmail.com","contacts":[{"id":177,"clientId":171,"email":"mainstreamm2@gmail.com","phone":"4181878106","name":null,"isBilling":false,"isContact":false,"types":[{"id":1003,"name":"WhatsNotifica"}]}],"attributes":[{"id":198,"clientId":171,"customAttributeId":10,"name":"Stripe Customer ID","key":"stripeCustomerId","value":"cus_SM2zH6IsjTz6ol","clientZoneVisible":true},{"id":199,"clientId":171,"customAttributeId":11,"name":"Clabe Interbancaria","key":"clabeInterbancaria","value":"124180950530868794","clientZoneVisible":true}],"accountBalance":0,"accountCredit":0,"accountOutstanding":0,"currencyCode":"MXN","organizationName":"SIIP Pruebas","bankAccounts":[],"tags":[],"invitationEmailSentDate":null,"avatarColor":"#f1df43","addressGpsLat":21.1572461,"addressGpsLon":-100.9377137,"isArchived":false,"generateProformaInvoices":null,"usesProforma":false,"hasOverdueInvoice":false,"hasOutage":false,"hasSuspendedService":false,"hasServiceWithoutDevices":true,"referral":null,"hasPaymentSubscription":false,"hasAutopayCreditCard":false}}}
|
||||
|
||||
|
||||
$clientID = $jsonData['entityId'];
|
||||
$this->ucrmApi = UcrmApi::create();
|
||||
$customAttributes = $this->ucrmApi->get('custom-attributes/', ['attributeType' => 'client']); //Obtener los atributos del sistema que estén vinculados a la entidad "cliente"
|
||||
//$this->logger->info("result del custom Attributes: " . json_encode($customAttributes) . PHP_EOL);
|
||||
|
||||
$idPasswordAntenaCliente = null;
|
||||
$passwordAntenaValue = null;
|
||||
|
||||
//ejemplo de $customAttributes: [{"id":1,"name":"ip","key":"ip","attributeType":"client","type":"string","clientZoneVisible":false},{"id":2,"name":"ubntpass","key":"ubntpass","attributeType":"client","type":"string","clientZoneVisible":false},{"id":3,"name":"adminpass","key":"adminpass","attributeType":"client","type":"string","clientZoneVisible":true},{"id":4,"name":"ssid","key":"ssid","attributeType":"client","type":"string","clientZoneVisible":true},{"id":5,"name":"clavessid","key":"clavessid","attributeType":"client","type":"string","clientZoneVisible":true},{"id":6,"name":"clave","key":"clave","attributeType":"client","type":"string","clientZoneVisible":true},{"id":11,"name":"latitud","key":"latitud","attributeType":"client","type":"string","clientZoneVisible":true},{"id":12,"name":"longitud","key":"longitud","attributeType":"client","type":"string","clientZoneVisible":true},{"id":16,"name":"instalador","key":"instalador","attributeType":"client","type":"string","clientZoneVisible":true},{"id":17,"name":"creado por","key":"creadoPor","attributeType":"client","type":"string","clientZoneVisible":true},{"id":21,"name":"Chat de CallBell","key":"chatDeCallbell","attributeType":"client","type":"string","clientZoneVisible":false},{"id":22,"name":"uuid","key":"uuid","attributeType":"client","type":"string","clientZoneVisible":false},{"id":23,"name":"zona","key":"zona","attributeType":"client","type":"enum","clientZoneVisible":true},{"id":29,"name":"Stripe Customer ID","key":"stripeCustomerId","attributeType":"client","type":"string","clientZoneVisible":true},{"id":30,"name":"Clabe Interbancaria","key":"clabeInterbancaria","attributeType":"client","type":"string","clientZoneVisible":true},{"id":31,"name":"RUTA DE COBRANZA","key":"rutaDeCobranza","attributeType":"client","type":"enum","clientZoneVisible":true},{"id":35,"name":"Site","key":"site","attributeType":"client","type":"string","clientZoneVisible":true},{"id":36,"name":"Antena/Sectorial","key":"antenaSectorial","attributeType":"client","type":"string","clientZoneVisible":true},{"id":37,"name":"Password Antena Cliente","key":"passwordAntenaCliente","attributeType":"client","type":"string","clientZoneVisible":false}]
|
||||
|
||||
// Verificar si se obtuvieron los atributos
|
||||
if ($customAttributes && is_array($customAttributes)) {
|
||||
foreach ($customAttributes as $attribute) {
|
||||
// Verificar si 'name' contiene la palabra 'passwordAntenaCliente' sin distinguir mayúsculas y minúsculas
|
||||
if (isset($attribute['key']) && stripos($attribute['key'], 'passwordAntenaCliente') !== false) {
|
||||
$this->logger->info("ID correspondiente a 'passwordAntenaCliente': " . $attribute['id'] . PHP_EOL);
|
||||
$idPasswordAntenaCliente = $attribute['id'];
|
||||
}
|
||||
|
||||
}
|
||||
} else {
|
||||
$this->logger->info("Error al obtener los atributos personalizados." . PHP_EOL);
|
||||
}
|
||||
|
||||
//buscar en los attributes ($jsonData) del cliente el id del atributo personalizado 'passwordAntenaCliente' si no está o si está pero está en blanco se manda llamar la función $this->notifierFacade->getVaultCredentials($clientID);
|
||||
|
||||
foreach ($jsonData['extraData']['entity']['attributes'] as $attribute) {
|
||||
if ($attribute['customAttributeId'] === $idPasswordAntenaCliente) {
|
||||
$this->logger->info("El valor de passwordAntenaValue es: " . $attribute['value'] . PHP_EOL);
|
||||
$passwordAntenaValue = $attribute['value'];
|
||||
}
|
||||
}
|
||||
|
||||
//si el value de passwordAntenaValue es igual a null o cadena vacía se manda llamar la función $this->notifierFacade->getVaultCredentials($clientID);
|
||||
if ($passwordAntenaValue === null || $passwordAntenaValue === '') {
|
||||
$password = $this->notifierFacade->getVaultCredentials($clientID);
|
||||
$this->logger->info("El valor de passwordAntenaValue es null o cadena vacía, se manda llamar la función getVaultCredentials" . PHP_EOL);
|
||||
$this->logger->info("El valor de password es: " . $password . PHP_EOL);
|
||||
|
||||
if ($this->notifierFacade->patchClientCustomAttribute($clientID, $idPasswordAntenaCliente, $password)) {
|
||||
$this->logger->info("Se actualizó el atributo personalizado passwordAntenaCliente con el valor: " . $password . PHP_EOL);
|
||||
} else {
|
||||
$this->logger->info("No se pudo actualizar el atributo personalizado passwordAntenaCliente" . PHP_EOL);
|
||||
}
|
||||
} else {
|
||||
$this->logger->info("Ya existe un valor de passwordAntenaValue: " . $passwordAntenaValue . PHP_EOL);
|
||||
}
|
||||
|
||||
//ejemplo de json_data: {"uuid":"17e043a7-03b5-4312-ab81-a7818124a77e","changeType":"edit","entity":"client","entityId":"158","eventName":"client.edit","extraData":{"entity":{"id":158,"userIdent":null,"previousIsp":null,"isLead":false,"clientType":1,"companyName":null,"companyRegistrationNumber":null,"companyTaxId":null,"companyWebsite":null,"street1":"23 San Luis","street2":null,"city":"Dolores Hidalgo Cuna de la Independencia Nacional","countryId":173,"stateId":null,"zipCode":"37804","fullAddress":"San Luis 23, Guadalupe, Dolores Hidalgo Cuna de la Independencia Nacional, Gto., M\u00e9xico","invoiceStreet1":null,"invoiceStreet2":null,"invoiceCity":null,"invoiceStateId":null,"invoiceCountryId":null,"invoiceZipCode":null,"invoiceAddressSameAsContact":true,"note":null,"sendInvoiceByPost":null,"invoiceMaturityDays":null,"stopServiceDue":null,"stopServiceDueDays":null,"organizationId":1,"tax1Id":null,"tax2Id":null,"tax3Id":null,"registrationDate":"2025-01-06T00:00:00-0600","leadConvertedAt":"2025-02-09T03:15:49-0600","companyContactFirstName":null,"companyContactLastName":null,"isActive":false,"firstName":"Luis","lastName":"Guti\u00e9rrez","username":null,"contacts":[{"id":162,"clientId":158,"email":null,"phone":null,"name":null,"isBilling":true,"isContact":true,"types":[{"id":1,"name":"Billing"},{"id":2,"name":"General"}]}],"attributes":[],"accountBalance":0,"accountCredit":0,"accountOutstanding":0,"currencyCode":"MXN","organizationName":"SIIP Pruebas","bankAccounts":[],"tags":[],"invitationEmailSentDate":null,"avatarColor":"#2196f3","addressGpsLat":21.153272,"addressGpsLon":-100.9134508,"isArchived":false,"generateProformaInvoices":null,"usesProforma":false,"hasOverdueInvoice":false,"hasOutage":false,"hasSuspendedService":false,"hasServiceWithoutDevices":false,"referral":null,"hasPaymentSubscription":false,"hasAutopayCreditCard":false},"entityBeforeEdit":{"id":158,"userIdent":null,"previousIsp":null,"isLead":true,"clientType":1,"companyName":null,"companyRegistrationNumber":null,"companyTaxId":null,"companyWebsite":null,"street1":"23 San Luis","street2":null,"city":"Dolores Hidalgo Cuna de la Independencia Nacional","countryId":173,"stateId":null,"zipCode":"37804","fullAddress":"San Luis 23, Guadalupe, Dolores Hidalgo Cuna de la Independencia Nacional, Gto., M\u00e9xico","invoiceStreet1":null,"invoiceStreet2":null,"invoiceCity":null,"invoiceStateId":null,"invoiceCountryId":null,"invoiceZipCode":null,"invoiceAddressSameAsContact":true,"note":null,"sendInvoiceByPost":null,"invoiceMaturityDays":null,"stopServiceDue":null,"stopServiceDueDays":null,"organizationId":1,"tax1Id":null,"tax2Id":null,"tax3Id":null,"registrationDate":"2025-01-06T00:00:00-0600","leadConvertedAt":null,"companyContactFirstName":null,"companyContactLastName":null,"isActive":false,"firstName":"Luis","lastName":"Guti\u00e9rrez","username":null,"contacts":[{"id":162,"clientId":158,"email":null,"phone":null,"name":null,"isBilling":true,"isContact":true,"types":[{"id":1,"name":"Billing"},{"id":2,"name":"General"}]}],"attributes":[],"accountBalance":0,"accountCredit":0,"accountOutstanding":0,"currencyCode":"MXN","organizationName":"SIIP Pruebas","bankAccounts":[],"tags":[],"invitationEmailSentDate":null,"avatarColor":"#2196f3","addressGpsLat":21.153272,"addressGpsLon":-100.9134508,"isArchived":false,"generateProformaInvoices":null,"usesProforma":false,"hasOverdueInvoice":false,"hasOutage":false,"hasSuspendedService":false,"hasServiceWithoutDevices":false,"referral":null,"hasPaymentSubscription":false,"hasAutopayCreditCard":false}}}
|
||||
|
||||
// Validar que 'extraData' existe y contiene las claves necesarias
|
||||
if (
|
||||
isset($jsonData['extraData']['entityBeforeEdit']) &&
|
||||
@ -394,7 +427,6 @@ class Plugin
|
||||
$this->logger->warning('El campo isLead no existe en entityBeforeEdit o entity');
|
||||
}
|
||||
|
||||
|
||||
// buscar si existe la etiqueta 'STRIPE' en entity pero no en entityBeforeEdit
|
||||
$tags = $jsonData['extraData']['entity']['tags'];
|
||||
$tagsBefore = $jsonData['extraData']['entityBeforeEdit']['tags'];
|
||||
@ -427,7 +459,7 @@ class Plugin
|
||||
}
|
||||
|
||||
// Comprobar si la etiqueta 'STRIPE' existe en 'tags' pero no en 'tagsBefore'
|
||||
if ($stripeTagExists && !$stripeTagExistsBefore) {
|
||||
if ($stripeTagExists && ! $stripeTagExistsBefore) {
|
||||
$this->logger->debug('La etiqueta CREAR CLABE STRIPE se agregará al cliente');
|
||||
$this->pluginNotifierFacade->createStripeClient($notification, true);
|
||||
}
|
||||
@ -439,10 +471,8 @@ class Plugin
|
||||
$this->logger->warning('Los datos entityBeforeEdit o entity no están presentes en extraData');
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
$this->notifierFacade->verifyClientActionToDo($notification);
|
||||
|
||||
} else if ($notification->eventName === 'client.add') {
|
||||
$this->logger->debug('Se agregó un nuevo cliente' . PHP_EOL);
|
||||
$this->logger->debug('Valor de json_data: ' . json_encode($jsonData));
|
||||
@ -467,6 +497,56 @@ class Plugin
|
||||
} else if ($notification->eventName === 'service.edit') {
|
||||
$this->logger->debug('Se editó el servicio a un cliente' . PHP_EOL);
|
||||
$this->notifierFacade->verifyServiceActionToDo($notification);
|
||||
//ejemplo de json_data: {"uuid":"06d281ca-d78e-4f0a-a282-3a6b77d25da0","changeType":"edit","entity":"service","entityId":"155","eventName":"service.edit","extraData":{"entity":{"id":155,"prepaid":false,"clientId":171,"status":1,"name":"Basico 300","fullAddress":"Campeche 56, Dolores Hidalgo, 37800","street1":"Campeche 56","street2":null,"city":"Dolores Hidalgo","countryId":173,"stateId":null,"zipCode":"37800","note":null,"addressGpsLat":21.1572461,"addressGpsLon":-100.9377137,"servicePlanId":6,"servicePlanPeriodId":26,"price":300,"hasIndividualPrice":false,"totalPrice":300,"currencyCode":"MXN","invoiceLabel":null,"contractId":null,"contractLengthType":1,"minimumContractLengthMonths":null,"activeFrom":"2025-05-21T00:00:00-0600","activeTo":null,"contractEndDate":null,"discountType":0,"discountValue":null,"discountInvoiceLabel":"Descuento","discountFrom":null,"discountTo":null,"tax1Id":null,"tax2Id":null,"tax3Id":null,"invoicingStart":"2025-05-21T00:00:00-0600","invoicingPeriodType":1,"invoicingPeriodStartDay":1,"nextInvoicingDayAdjustment":10,"invoicingProratedSeparately":true,"invoicingSeparately":false,"sendEmailsAutomatically":null,"useCreditAutomatically":true,"servicePlanName":"Basico 300","servicePlanPrice":300,"servicePlanPeriod":1,"servicePlanType":"Internet","downloadSpeed":8,"uploadSpeed":8,"hasOutage":false,"unmsClientSiteStatus":null,"fccBlockId":null,"lastInvoicedDate":null,"unmsClientSiteId":"359cb58d-e64f-453a-890e-23d5abb4f116","attributes":[],"addressData":null,"suspensionReasonId":null,"serviceChangeRequestId":null,"setupFeePrice":null,"earlyTerminationFeePrice":null,"downloadSpeedOverride":null,"uploadSpeedOverride":null,"trafficShapingOverrideEnd":null,"trafficShapingOverrideEnabled":false,"servicePlanGroupId":null,"suspensionPeriods":[],"surcharges":[]},"entityBeforeEdit":{"id":155,"prepaid":false,"clientId":171,"status":1,"name":"Basico 300","fullAddress":"Campeche 56, Dolores Hidalgo, 37800","street1":"Campeche 56","street2":null,"city":"Dolores Hidalgo","countryId":173,"stateId":null,"zipCode":"37800","note":null,"addressGpsLat":21.1572461,"addressGpsLon":-100.9377137,"servicePlanId":6,"servicePlanPeriodId":26,"price":300,"hasIndividualPrice":false,"totalPrice":300,"currencyCode":"MXN","invoiceLabel":null,"contractId":null,"contractLengthType":1,"minimumContractLengthMonths":null,"activeFrom":"2025-05-21T00:00:00-0600","activeTo":null,"contractEndDate":null,"discountType":0,"discountValue":null,"discountInvoiceLabel":"Descuento","discountFrom":null,"discountTo":null,"tax1Id":null,"tax2Id":null,"tax3Id":null,"invoicingStart":"2025-05-21T00:00:00-0600","invoicingPeriodType":1,"invoicingPeriodStartDay":1,"nextInvoicingDayAdjustment":10,"invoicingProratedSeparately":true,"invoicingSeparately":false,"sendEmailsAutomatically":null,"useCreditAutomatically":true,"servicePlanName":"Basico 300","servicePlanPrice":300,"servicePlanPeriod":1,"servicePlanType":"Internet","downloadSpeed":8,"uploadSpeed":8,"hasOutage":false,"unmsClientSiteStatus":null,"fccBlockId":null,"lastInvoicedDate":null,"unmsClientSiteId":"359cb58d-e64f-453a-890e-23d5abb4f116","attributes":[],"addressData":null,"suspensionReasonId":null,"serviceChangeRequestId":null,"setupFeePrice":null,"earlyTerminationFeePrice":null,"downloadSpeedOverride":null,"uploadSpeedOverride":null,"trafficShapingOverrideEnd":null,"trafficShapingOverrideEnabled":false,"servicePlanGroupId":null,"suspensionPeriods":[],"surcharges":[]}}}
|
||||
//obtener el clientID y asginarlo a la variable $clientID
|
||||
$clientID = $jsonData['extraData']['entity']['clientId'];
|
||||
$this->ucrmApi = UcrmApi::create();
|
||||
$customAttributes = $this->ucrmApi->get('custom-attributes/', ['attributeType' => 'client']); //Obtener los atributos del sistema que estén vinculados a la entidad "cliente"
|
||||
//$this->logger->info("result del custom Attributes: " . json_encode($customAttributes) . PHP_EOL);
|
||||
|
||||
$idPasswordAntenaCliente = null;
|
||||
$passwordAntenaValue = null;
|
||||
|
||||
//ejemplo de $customAttributes: [{"id":1,"name":"ip","key":"ip","attributeType":"client","type":"string","clientZoneVisible":false},{"id":2,"name":"ubntpass","key":"ubntpass","attributeType":"client","type":"string","clientZoneVisible":false},{"id":3,"name":"adminpass","key":"adminpass","attributeType":"client","type":"string","clientZoneVisible":true},{"id":4,"name":"ssid","key":"ssid","attributeType":"client","type":"string","clientZoneVisible":true},{"id":5,"name":"clavessid","key":"clavessid","attributeType":"client","type":"string","clientZoneVisible":true},{"id":6,"name":"clave","key":"clave","attributeType":"client","type":"string","clientZoneVisible":true},{"id":11,"name":"latitud","key":"latitud","attributeType":"client","type":"string","clientZoneVisible":true},{"id":12,"name":"longitud","key":"longitud","attributeType":"client","type":"string","clientZoneVisible":true},{"id":16,"name":"instalador","key":"instalador","attributeType":"client","type":"string","clientZoneVisible":true},{"id":17,"name":"creado por","key":"creadoPor","attributeType":"client","type":"string","clientZoneVisible":true},{"id":21,"name":"Chat de CallBell","key":"chatDeCallbell","attributeType":"client","type":"string","clientZoneVisible":false},{"id":22,"name":"uuid","key":"uuid","attributeType":"client","type":"string","clientZoneVisible":false},{"id":23,"name":"zona","key":"zona","attributeType":"client","type":"enum","clientZoneVisible":true},{"id":29,"name":"Stripe Customer ID","key":"stripeCustomerId","attributeType":"client","type":"string","clientZoneVisible":true},{"id":30,"name":"Clabe Interbancaria","key":"clabeInterbancaria","attributeType":"client","type":"string","clientZoneVisible":true},{"id":31,"name":"RUTA DE COBRANZA","key":"rutaDeCobranza","attributeType":"client","type":"enum","clientZoneVisible":true},{"id":35,"name":"Site","key":"site","attributeType":"client","type":"string","clientZoneVisible":true},{"id":36,"name":"Antena/Sectorial","key":"antenaSectorial","attributeType":"client","type":"string","clientZoneVisible":true},{"id":37,"name":"Password Antena Cliente","key":"passwordAntenaCliente","attributeType":"client","type":"string","clientZoneVisible":false}]
|
||||
|
||||
// Verificar si se obtuvieron los atributos
|
||||
if ($customAttributes && is_array($customAttributes)) {
|
||||
foreach ($customAttributes as $attribute) {
|
||||
// Verificar si 'name' contiene la palabra 'passwordAntenaCliente' sin distinguir mayúsculas y minúsculas
|
||||
if (isset($attribute['key']) && stripos($attribute['key'], 'passwordAntenaCliente') !== false) {
|
||||
$this->logger->info("ID correspondiente a 'passwordAntenaCliente': " . $attribute['id'] . PHP_EOL);
|
||||
$idPasswordAntenaCliente = $attribute['id'];
|
||||
}
|
||||
|
||||
}
|
||||
} else {
|
||||
$this->logger->info("Error al obtener los atributos personalizados." . PHP_EOL);
|
||||
}
|
||||
|
||||
//buscar en los attributes ($jsonData) del cliente el id del atributo personalizado 'passwordAntenaCliente' si no está o si está pero está en blanco se manda llamar la función $this->notifierFacade->getVaultCredentials($clientID);
|
||||
|
||||
foreach ($jsonData['extraData']['entity']['attributes'] as $attribute) {
|
||||
if ($attribute['customAttributeId'] === $idPasswordAntenaCliente) {
|
||||
$this->logger->info("El valor de passwordAntenaValue es: " . $attribute['value'] . PHP_EOL);
|
||||
$passwordAntenaValue = $attribute['value'];
|
||||
}
|
||||
}
|
||||
|
||||
//si el value de passwordAntenaValue es igual a null o cadena vacía se manda llamar la función $this->notifierFacade->getVaultCredentials($clientID);
|
||||
if ($passwordAntenaValue === null || $passwordAntenaValue === '') {
|
||||
$password = $this->notifierFacade->getVaultCredentials($clientID);
|
||||
$this->logger->info("El valor de passwordAntenaValue es null o cadena vacía, se manda llamar la función getVaultCredentials" . PHP_EOL);
|
||||
$this->logger->info("El valor de password es: " . $password . PHP_EOL);
|
||||
|
||||
if ($this->notifierFacade->patchClientCustomAttribute($clientID, $idPasswordAntenaCliente, $password)) {
|
||||
$this->logger->info("Se actualizó el atributo personalizado passwordAntenaCliente con el valor: " . $password . PHP_EOL);
|
||||
} else {
|
||||
$this->logger->info("No se pudo actualizar el atributo personalizado passwordAntenaCliente" . PHP_EOL);
|
||||
}
|
||||
} else {
|
||||
$this->logger->info("Ya existe un valor de passwordAntenaValue: " . $passwordAntenaValue . PHP_EOL);
|
||||
}
|
||||
|
||||
} else if ($notification->eventName === 'service.suspend') {
|
||||
$this->logger->debug('Se suspendió el servicio a un cliente' . PHP_EOL);
|
||||
$this->notifierFacade->verifyServiceActionToDo($notification);
|
||||
@ -508,28 +588,21 @@ class Plugin
|
||||
$this->notifierFacade->verifyInvoiceActionToDo($notification);
|
||||
} else if ($notification->eventName === 'job.add') {
|
||||
$this->logger->debug('Se ha agregado un nuevo trabajo' . PHP_EOL);
|
||||
$this->logger->debug('Valor de json_data: ' . json_encode($jsonData));
|
||||
//Ejemplo de json_data: {"uuid":"434b3da0-984a-4358-a1b6-2a4418bacc49","changeType":"insert","entity":"job","entityId":"38","eventName":"job.add","extraData":{"entity":{"id":38,"title":"Servicio","description":"Revisar Router","assignedUserId":null,"clientId":2,"date":null,"duration":60,"status":0,"address":"31 Chiapas, Dolores Hidalgo Cuna de la Independencia Nacional, 37800, Mexico","gpsLat":null,"gpsLon":null,"attachments":[],"tasks":[]},"entityBeforeEdit":null}}
|
||||
//Extraer el valor de title en una variable y concatenarle como prefijo la cadena "[SINENVIONOTIFICACION]" por ejemplo: "[NOTIFICACION-PENDIENTE]Servicio"
|
||||
$title = $jsonData['extraData']['entity']['title'];
|
||||
$title = '[NOTIFICACION-PENDIENTE]' . $title;
|
||||
$this->ucrmApi = UcrmApi::create();
|
||||
$responsePatch = $this->ucrmApi->patch('scheduling/jobs/' . $jsonData['entityId'], [
|
||||
'title' => $title,
|
||||
]);
|
||||
|
||||
|
||||
// Verificar que existen tanto 'assignedUserId' como 'entity'
|
||||
if (isset($jsonData['extraData']['entity']['assignedUserId'])) {
|
||||
$this->logger->debug('El campo assignedUserId existe en los datos del evento');
|
||||
$assignedUserId = $jsonData['extraData']['entity']['assignedUserId'];
|
||||
|
||||
// Comprobar si 'isLead' es null
|
||||
if ($assignedUserId === null) {
|
||||
$this->logger->debug('El campo assignedUserId es null');
|
||||
$this->pluginNotifierFacade->createStripeClient($notification);
|
||||
} else {
|
||||
$this->logger->debug('El campo assignedUserId no es null');
|
||||
$this->notifierFacade->verifyJobActionToDo($notification);
|
||||
}
|
||||
} else {
|
||||
$this->logger->warning('El campo assignedUserId no existe en los datos del evento');
|
||||
}
|
||||
$this->logger->debug('Respuesta de la API al agregar el trabajo: ' . json_encode($responsePatch) . PHP_EOL);
|
||||
|
||||
} else if ($notification->eventName === 'job.edit') {
|
||||
$this->logger->debug('Se actualiza un trabajo' . PHP_EOL);
|
||||
$this->logger->debug('Valor de json_data: ' . json_encode($jsonData));
|
||||
// $this->logger->debug('Valor de json_data: ' . json_encode($jsonData));
|
||||
|
||||
// Validar que 'extraData' existe y contiene las claves necesarias
|
||||
if (
|
||||
@ -543,7 +616,7 @@ class Plugin
|
||||
|
||||
// Validar que 'assignedUserId' existe en ambas entidades
|
||||
if (array_key_exists('assignedUserId', $entityBeforeEdit) && array_key_exists('assignedUserId', $entity)) {
|
||||
$this->logger->debug('Los datos entityBeforeEdit y entity contienen el campo assignedUserId');
|
||||
// $this->logger->debug('Los datos entityBeforeEdit y entity contienen el campo assignedUserId');
|
||||
|
||||
$assignedUserIdBefore = $entityBeforeEdit['assignedUserId'];
|
||||
$assignedUserIdAfter = $entity['assignedUserId'];
|
||||
@ -551,25 +624,40 @@ class Plugin
|
||||
$dateAfter = $entity['date'];
|
||||
$statusBefore = $entityBeforeEdit['status'];
|
||||
$statusAfter = $entity['status'];
|
||||
$title = $entityBeforeEdit['title'];
|
||||
$pendingPrefix = '[NOTIFICACION-PENDIENTE]'; // Prefijo para trabajos pendientes de notificación
|
||||
$currentTitle = $entity['title'] ?? ''; // Obtener el título actual
|
||||
|
||||
//Valores de status y su significado: 0 = abierto, 1= En curso, 2 = Cerrado
|
||||
|
||||
if ($statusAfter == 1) {
|
||||
// Comprobar si 'assignedUserId' cambió
|
||||
if ($assignedUserIdBefore === null && $assignedUserIdAfter != null) { //Si el campo "assignedUserId" cambió de null a un valor
|
||||
// if (($assignedUserIdBefore === null && $assignedUserIdAfter != null) || ($statusBefore == 0 && $statusAfter == 1)) { //Si el campo "assignedUserId" cambió de null a un valor
|
||||
// $this->logger->debug('El instalador cambió de null a un valor');
|
||||
|
||||
// $this->notifierFacade->verifyJobActionToDo($jsonData); // Se envía notificación de trabajo asignado
|
||||
// }
|
||||
|
||||
//Si el campo status cambió de 0 a 1 y title comienza con el prefijo [NOTIFICACION-PENDIENTE]
|
||||
if (($statusBefore == 0 && $statusAfter == 1) && strpos($currentTitle, $pendingPrefix) !== false) { // Se envía notificación de trabajo asignado
|
||||
$this->logger->debug('El instalador cambió de null a un valor');
|
||||
$this->notifierFacade->verifyJobActionToDo($jsonData); // Se envía notificación de trabajo asignado
|
||||
} else if (($assignedUserIdBefore != null && $assignedUserIdAfter != $assignedUserIdBefore) && ($dateBefore === $dateAfter)) {//Si el campo "assignedUserId" cambió de un valor a otro y la fecha no cambió
|
||||
$this->logger->debug('El instalador cambió y la fecha no cambió');
|
||||
$this->notifierFacade->verifyJobActionToDo($jsonData, false, false);
|
||||
} else if (($assignedUserIdBefore != null && $assignedUserIdAfter != $assignedUserIdBefore) && ($dateBefore === $dateAfter)) { //Si el campo "assignedUserId" cambió de un valor a otro y la fecha no cambió
|
||||
$this->logger->debug('No hay reprogramación de trabajo pero si hay cambio de instalador');
|
||||
$this->notifierFacade->verifyJobActionToDo($jsonData, false, true); // Se envía notificación de trabajo reasignado
|
||||
} else if (($assignedUserIdBefore != null && $assignedUserIdBefore === $assignedUserIdAfter) && ($dateBefore != $dateAfter)) {//Si el campo "assignedUserId" no cambió y la fecha cambió
|
||||
$this->logger->debug('El instalador no cambió y la fecha sí cambió');
|
||||
} else if (($assignedUserIdBefore != null && $assignedUserIdBefore === $assignedUserIdAfter) && ($dateBefore != $dateAfter)) { //Si el campo "assignedUserId" no cambió y la fecha cambió
|
||||
$this->logger->debug('Se reprogramó el trabajo pero no hubo cambio de instalador');
|
||||
$this->notifierFacade->verifyJobActionToDo($jsonData, true, false); // Se envía notificación de reprogramación de trabajo
|
||||
} else if (($assignedUserIdBefore != null && $assignedUserIdAfter != $assignedUserIdBefore) && ($dateBefore != $dateAfter)) {
|
||||
$this->logger->debug('El instalador cambió y la fecha sí cambió');
|
||||
$this->logger->debug('Se reprogramó el trabajo y hubo cambio de instalador');
|
||||
$this->notifierFacade->verifyJobActionToDo($jsonData, true, true); // Se envía notificación de trabajo reasignado
|
||||
} else if ($assignedUserIdBefore != null && $assignedUserIdAfter === null) { //Si el campo "assignedUserId" cambió de un valor a null
|
||||
$this->logger->debug('El instalador cambió de un valor a null');
|
||||
$this->notifierFacade->verifyJobActionToDo($jsonData, null, true); // Se envía notificación de trabajo desasignado
|
||||
} else {
|
||||
$this->logger->debug('No hubo cambio en el instalador ni en la fecha');
|
||||
//$this->notifierFacade->verifyJobActionToDo($jsonData); // Se envía notificación de trabajo asignado
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
@ -581,8 +669,6 @@ class Plugin
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
//$this->notifierFacade->update($notification);
|
||||
} catch (TwilioException $exception) {
|
||||
$this->logger->error($exception->getMessage());
|
||||
|
||||
4
vendor/composer/installed.php
vendored
4
vendor/composer/installed.php
vendored
@ -5,7 +5,7 @@
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../../',
|
||||
'aliases' => array(),
|
||||
'reference' => '9a3af1f3d453e226100a2c8ff4c62b4929373492',
|
||||
'reference' => '7cb26fe7358fc5b3d7671f2db68235f6bb07ef3f',
|
||||
'name' => 'ucrm-plugins/sms-twilio',
|
||||
'dev' => false,
|
||||
),
|
||||
@ -307,7 +307,7 @@
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../../',
|
||||
'aliases' => array(),
|
||||
'reference' => '9a3af1f3d453e226100a2c8ff4c62b4929373492',
|
||||
'reference' => '7cb26fe7358fc5b3d7671f2db68235f6bb07ef3f',
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
),
|
||||
|
||||
Loading…
Reference in New Issue
Block a user