Versión 2.6.0 completa
This commit is contained in:
parent
11b7d7cacc
commit
869331b02c
69
.vscode/launch.json
vendored
Normal file
69
.vscode/launch.json
vendored
Normal file
@ -0,0 +1,69 @@
|
||||
{
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Listen for Xdebug",
|
||||
"type": "php",
|
||||
"request": "launch",
|
||||
"port": 9003
|
||||
},
|
||||
{
|
||||
"name": "Launch currently open script",
|
||||
"type": "php",
|
||||
"request": "launch",
|
||||
"program": "${file}",
|
||||
"cwd": "${fileDirname}",
|
||||
"port": 0,
|
||||
"runtimeArgs": [
|
||||
"-dxdebug.start_with_request=yes"
|
||||
],
|
||||
"env": {
|
||||
"XDEBUG_MODE": "debug,develop",
|
||||
"XDEBUG_CONFIG": "client_port=${port}"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Launch Built-in web server",
|
||||
"type": "php",
|
||||
"request": "launch",
|
||||
"runtimeArgs": [
|
||||
"-dxdebug.mode=debug",
|
||||
"-dxdebug.start_with_request=yes",
|
||||
"-S",
|
||||
"localhost:0"
|
||||
],
|
||||
"program": "",
|
||||
"cwd": "${workspaceRoot}",
|
||||
"port": 9003,
|
||||
"serverReadyAction": {
|
||||
"pattern": "Development Server \\(http://localhost:([0-9]+)\\) started",
|
||||
"uriFormat": "http://localhost:%s",
|
||||
"action": "openExternally"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Launch built-in server and Debug",
|
||||
"type": "php",
|
||||
"request": "launch",
|
||||
"noDebug": false,
|
||||
"runtimeArgs": [
|
||||
"-S",
|
||||
"localhost:8000",
|
||||
"-t",
|
||||
"."
|
||||
],
|
||||
"cwd": "${workspaceRoot}/.",
|
||||
"serverReadyAction": {
|
||||
"action": "openExternally"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Listen for Xdebug",
|
||||
"type": "php",
|
||||
"request": "launch"
|
||||
}
|
||||
]
|
||||
}
|
||||
BIN
comprobantes/Comprobante_Daniel_Humberto_Soto_Villegas.png
Executable file
BIN
comprobantes/Comprobante_Daniel_Humberto_Soto_Villegas.png
Executable file
Binary file not shown.
|
After Width: | Height: | Size: 318 KiB |
0
comprobantes/Comprobante_Daniel_Humberto_Soto_Villegas_Pollerias_789.png
Normal file → Executable file
0
comprobantes/Comprobante_Daniel_Humberto_Soto_Villegas_Pollerias_789.png
Normal file → Executable file
|
Before Width: | Height: | Size: 433 KiB After Width: | Height: | Size: 433 KiB |
@ -1 +1 @@
|
||||
{"ipserver":"172.16.5.134","apitoken":"6abef18c-783d-4dd0-b530-be6e6a7bbd1d","tokencallbell":"g8thcZkXGd3xBj2g3TtYNYFMH1fuesbJ.b6a940ea7d78cf6c9e42f067b21c8ddf96e9fa2a9e307bfd0c7c7c4d7fa38f79","tokenstripe":"sk_test_51OkG0REFY1WEUtgRH6UxBK5pu80Aq5Iy8EcdPnf0cOWzuVLQTpyLCd7CbPzqMsWMafZOHElCxhEHF7g8boURjWlJ00tBwE0W1M","unmsApiToken":null,"hostServerFTP":"siip.mx","usernameServerFTP":"siip0001","passServerFTP":"$spGiT,[wa)n","cashPaymentMethodId":false,"courtesyPaymentMethodId":false,"bankTransferPaymentMethodId":true,"paypalPaymentMethodId":true,"creditCardPaypalPaymentMethodId":true,"creditCardStripePaymentMethodId":true,"stripeSubscriptionCreditCardPaymentMethodId":true,"paypalSubscriptionPaymentMethodId":true,"mercadopagoPaymentMethodId":true,"checkPaymentMethodId":true,"customPaymentMethodId":true,"notificationTypeText":false,"dataInstallersWhatsApp":"{ \"instaladores\": [{\"ID\": 1015, \"nombre\": \"Daniel Peña\", \"whatsapp\": 4181878106}, {\"ID\": 1020, \"nombre\": \"Angel Arvizu\", \"whatsapp\": 4123456789}, {\"ID\": 1035,\"nombre\": \"Juan Rostro\", \"whatsapp\": 4198765432}, {\"ID\": 1035,\"nombre\": “Daniel Humberto\", \"whatsapp\": 4181878106] }","debugMode":true,"logging_level":true}
|
||||
{"ipserver":"172.16.5.134","apitoken":"6abef18c-783d-4dd0-b530-be6e6a7bbd1d","tokencallbell":"g8thcZkXGd3xBj2g3TtYNYFMH1fuesbJ.b6a940ea7d78cf6c9e42f067b21c8ddf96e9fa2a9e307bfd0c7c7c4d7fa38f79","tokenstripe":"sk_test_51OkG0REFY1WEUtgRH6UxBK5pu80Aq5Iy8EcdPnf0cOWzuVLQTpyLCd7CbPzqMsWMafZOHElCxhEHF7g8boURjWlJ00tBwE0W1M","unmsApiToken":null,"hostServerFTP":"siip.mx","usernameServerFTP":"siip0001","passServerFTP":"$spGiT,[wa)n","cashPaymentMethodId":false,"courtesyPaymentMethodId":false,"bankTransferPaymentMethodId":true,"paypalPaymentMethodId":true,"creditCardPaypalPaymentMethodId":true,"creditCardStripePaymentMethodId":true,"stripeSubscriptionCreditCardPaymentMethodId":true,"paypalSubscriptionPaymentMethodId":true,"mercadopagoPaymentMethodId":true,"checkPaymentMethodId":true,"customPaymentMethodId":true,"notificationTypeText":false,"installersDataWhatsApp":"{\r\n \"instaladores\": [\r\n {\r\n \"id\": 1019,\r\n \"nombre\": \"Mucio Robledo\",\r\n \"whatsapp\": \"4181878106\"\r\n },\r\n {\r\n \"id\": 1173,\r\n \"nombre\": \"Angel Arvizu\",\r\n \"whatsapp\": \"4181878106\"\r\n },\r\n {\r\n \"id\": 1172,\r\n \"nombre\": \"Juan Rostro\",\r\n \"whatsapp\": \"4181878106\"\r\n },\r\n {\r\n \"id\": 1015,\r\n \"nombre\": \"Daniel Humberto\",\r\n \"whatsapp\": \"4181878106\"\r\n }\r\n ]\r\n}","debugMode":true,"logging_level":true}
|
||||
1500
data/plugin.log
1500
data/plugin.log
File diff suppressed because it is too large
Load Diff
@ -2,10 +2,10 @@
|
||||
"version": "1",
|
||||
"information": {
|
||||
"name": "siip-whatsapp-notifications",
|
||||
"displayName": "SIIP - Procesador de Pagos en línea con Stripe, Sincronizador de CallBell y Envío de Notificaciones y comprobantes vía WhatsApp",
|
||||
"description": "Este plugin sincroniza los clientes del sitema UISP CRM con los contactos de WhatsApp en CallBell, además procesa pagos de Stripe como las trasferencias bancarias y genera referencias de pago vía OXXO, además envía comprobantes de pago en formato imagen PNG vía Whatsapp a los clientes",
|
||||
"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 sitema UISP CRM con los contactos de WhatsApp en CallBell, además procesa pagos de Stripe como las trasferencias bancarias y genera referencias de pago vía OXXO, además envía comprobantes de pago en formato imagen PNG o texto vía Whatsapp a los clientes",
|
||||
"url": "https://siip.mx/",
|
||||
"version": "2.5.3",
|
||||
"version": "2.6.0",
|
||||
"unmsVersionCompliancy": {
|
||||
"min": "2.1.0",
|
||||
"max": null
|
||||
@ -154,8 +154,9 @@
|
||||
"type": "checkbox"
|
||||
},
|
||||
{
|
||||
"key": "dataInstallersWhatsApp",
|
||||
"key": "installersDataWhatsApp",
|
||||
"label": "Datos de los instaladores en formato JSON",
|
||||
"description": "El número identificador (id) del instalador se obtiene desde la API del CRM en su ednpoint \"/api/v1.0/user\" y se debe de obtener el campo 'id' de cada instalador para agregarlo en este campo en formato JSON",
|
||||
"required": 1,
|
||||
"type": "textarea"
|
||||
},
|
||||
|
||||
@ -11,6 +11,8 @@ use SmsNotifier\Service\SmsNumberProvider;
|
||||
use Twilio\Exceptions\HttpException;
|
||||
use SmsNotifier\Facade\ClientCallBellAPI;
|
||||
use GuzzleHttp\Client;
|
||||
use Ubnt\UcrmPluginSdk\Service\UcrmApi;
|
||||
use \DateTime;
|
||||
|
||||
|
||||
/*
|
||||
@ -39,6 +41,13 @@ abstract class AbstractMessageNotifierFacade
|
||||
*/
|
||||
private $pluginNotifierFacade;
|
||||
|
||||
/**
|
||||
* @var UcrmApi
|
||||
*/
|
||||
protected $ucrmApi;
|
||||
|
||||
const SUBJECT_OF_INSTALLER_CHANGE = ["se ha cancelado una tarea que tenías asignada con el folio ", "se te ha desasignado la tarea con el folio "];
|
||||
const ADDITIONAL_CHANGE_DATA = ["Ya no es necesario realizar la visita técnica.", "En tu lugar asistirá el técnico"];
|
||||
|
||||
|
||||
public function __construct(
|
||||
@ -60,7 +69,7 @@ abstract class AbstractMessageNotifierFacade
|
||||
|
||||
//$this->logger->debug(print_r(json_encode($notificationData),true).PHP_EOL);
|
||||
|
||||
$arrayPhones = $this->clientPhoneNumber->getUcrmClientNumbers($notificationData);
|
||||
$arrayPhones = $this->clientPhoneNumber->getUcrmClientNumbers($notificationData, null);
|
||||
// Procesar el array de teléfonos y ejecutar la función correspondiente
|
||||
|
||||
foreach ($arrayPhones as $type => $phone) {
|
||||
@ -93,7 +102,7 @@ abstract class AbstractMessageNotifierFacade
|
||||
|
||||
$this->logger->debug(print_r(json_encode($notificationData), true) . PHP_EOL);
|
||||
|
||||
$arrayPhones = $this->clientPhoneNumber->getUcrmClientNumbers($notificationData);
|
||||
$arrayPhones = $this->clientPhoneNumber->getUcrmClientNumbers($notificationData, null);
|
||||
// Procesar el array de teléfonos y ejecutar la función correspondiente
|
||||
|
||||
foreach ($arrayPhones as $type => $phone) {
|
||||
@ -121,7 +130,7 @@ abstract class AbstractMessageNotifierFacade
|
||||
|
||||
//$this->logger->debug(print_r(json_encode($notificationData),true).PHP_EOL);
|
||||
|
||||
$arrayPhones = $this->clientPhoneNumber->getUcrmClientNumbers($notificationData);
|
||||
$arrayPhones = $this->clientPhoneNumber->getUcrmClientNumbers($notificationData, null);
|
||||
// Procesar el array de teléfonos y ejecutar la función correspondiente
|
||||
|
||||
foreach ($arrayPhones as $type => $phone) {
|
||||
@ -145,24 +154,99 @@ abstract class AbstractMessageNotifierFacade
|
||||
/*
|
||||
* Verify contact type numbers to do client's
|
||||
*/
|
||||
public function verifyJobActionToDo($jsonNotificationData): void
|
||||
public function verifyJobActionToDo($jsonNotificationData, $reprogramming = false, $changeInstaller = false): void
|
||||
{
|
||||
|
||||
$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);
|
||||
|
||||
|
||||
|
||||
// Obtener la fecha del nodo "entity"
|
||||
$dateString = $jsonNotificationData['extraData']['entity']['date'] ?? null;
|
||||
|
||||
if ($dateString) {
|
||||
// Crear un objeto DateTime a partir de la fecha
|
||||
$date = new DateTime($dateString);
|
||||
|
||||
// Formatear la fecha al formato día/mes/año hora:minuto am/pm
|
||||
$formattedDate = $date->format('d/m/Y h:i A');
|
||||
} else {
|
||||
echo "La fecha no está disponible en el JSON.\n";
|
||||
}
|
||||
|
||||
|
||||
|
||||
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
|
||||
$config = $configManager->loadConfig();
|
||||
$IPServer = $config['ipserver'];
|
||||
$tokenCRM = $config['apitoken'];
|
||||
$UCRMAPIToken = $config['apitoken'];
|
||||
$CallBellAPIToken = $config['tokencallbell'];
|
||||
$IPServer = $config['ipserver'];
|
||||
$installersData = $config['installersDataWhatsApp'];
|
||||
$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);
|
||||
|
||||
// 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'])) {
|
||||
$this->logger->error('El nodo "instaladores" no existe en el JSON');
|
||||
return;
|
||||
}
|
||||
|
||||
// Buscar el número de WhatsApp en el JSON
|
||||
$installerWhatsApp = '';
|
||||
foreach ($jsonInstallersData['instaladores'] as $installer) {
|
||||
if ($installer['id'] === $installerId) {
|
||||
$installerWhatsApp = $installer['whatsapp'];
|
||||
break;
|
||||
}
|
||||
}
|
||||
$this->logger->debug('tipo de dato de installerWhatsApp: ' . gettype($installerWhatsApp) . PHP_EOL);
|
||||
|
||||
// Validar si se encontró el WhatsApp
|
||||
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->ucrmApi = UcrmApi::create();
|
||||
$usersInstallers = $this->ucrmApi->get('users/admins/' . $installerId, []);
|
||||
$this->logger->debug('Valor de $usersInstallers ' . json_encode($usersInstallers) . PHP_EOL);
|
||||
$firstName = $usersInstallers['firstName'] ?? '';
|
||||
$lastName = $usersInstallers['lastName'] ?? '';
|
||||
$installerFullName = trim("$firstName $lastName");
|
||||
$this->logger->debug('Valor de $installerFullName: ' . $installerFullName . PHP_EOL);
|
||||
|
||||
$baseUri = 'https://' . $IPServer . '/crm/api/v1.0/';
|
||||
|
||||
$clientGuzzleHttp = new Client([
|
||||
'base_uri' => $baseUri,
|
||||
'headers' => [
|
||||
'X-Auth-App-Key' => $tokenCRM,
|
||||
'X-Auth-App-Key' => $UCRMAPIToken,
|
||||
'Accept' => 'application/json',
|
||||
],
|
||||
'verify' => false,
|
||||
@ -171,25 +255,268 @@ abstract class AbstractMessageNotifierFacade
|
||||
$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);
|
||||
|
||||
|
||||
//$arrayPhones = $this->clientPhoneNumber->getUcrmClientNumbers($notificationData);
|
||||
$clientFullName = sprintf("%s %s", $arrayClientCRM['firstName'], $arrayClientCRM['lastName']);
|
||||
|
||||
// Extraer la dirección completa
|
||||
$fullAddress = $arrayClientCRM['fullAddress'] ?? null;
|
||||
|
||||
// Validar si la dirección completa está disponible
|
||||
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);
|
||||
} else {
|
||||
$this->logger->error('La dirección completa no está disponible en el JSON' . PHP_EOL);
|
||||
}
|
||||
|
||||
// Extraer las coordenadas del nodo "entity"
|
||||
$gpsLat = $arrayClientCRM['addressGpsLat'] ?? null;
|
||||
$gpsLon = $arrayClientCRM['addressGpsLon'] ?? null;
|
||||
|
||||
// Validar si las coordenadas están disponibles
|
||||
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);
|
||||
} 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);
|
||||
|
||||
$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);
|
||||
|
||||
// Dividir los números en un array
|
||||
$arrayNumeros = explode(',', $clientAllPhonesString);
|
||||
$this->logger->debug('Valor de $arrayNumeros en verifyJobActionToDo: ' . json_encode($arrayNumeros) . PHP_EOL);
|
||||
|
||||
// Procesar cada número
|
||||
$resultados = [];
|
||||
foreach ($arrayNumeros as $numero) {
|
||||
// Limpiar espacios alrededor de cada número
|
||||
$numero = trim($numero);
|
||||
|
||||
// Validar el número
|
||||
$numeroValidado = $this->validarNumeroTelefono($numero);
|
||||
|
||||
// Remover el prefijo 521 si está presente y tiene 12 dígitos
|
||||
if (substr($numeroValidado, 0, 3) === "521" && strlen($numeroValidado) === 12) {
|
||||
$resultados[] = substr($numeroValidado, 3); // Remover "521"
|
||||
} else {
|
||||
$resultados[] = $numeroValidado; // Mantener el número sin cambios
|
||||
}
|
||||
}
|
||||
$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);
|
||||
|
||||
$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
|
||||
];
|
||||
|
||||
$clientWhatsApp = '';
|
||||
|
||||
|
||||
// Procesar el array de teléfonos y ejecutar la función correspondiente
|
||||
foreach ($arrayPhones as $type => $phone) {
|
||||
switch ($type) {
|
||||
case 'WhatsApp':
|
||||
case 'WhatsNotifica':
|
||||
$this->logger->debug("Se encontró un tipo de contacto $type" . PHP_EOL);
|
||||
|
||||
$attempts = 0;
|
||||
$maxAttempts = 3;
|
||||
$result = false;
|
||||
|
||||
// Reintentar hasta 3 veces si la función retorna false
|
||||
while ($attempts < $maxAttempts && $result === false) {
|
||||
$attempts++;
|
||||
$result = $client_callbell_api->sendJobNotificationWhatsAppToClient(
|
||||
$this->validarNumeroTelefono($phone),
|
||||
$jsonClientJobNotificationData,
|
||||
$reprogramming,
|
||||
$changeInstaller
|
||||
);
|
||||
|
||||
if ($result === false) {
|
||||
sleep(1);
|
||||
$this->logger->warning("Intento $attempts fallido para enviar 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);
|
||||
} else {
|
||||
$this->logger->error("No se pudo enviar la notificación al contacto $phone después de $maxAttempts intentos." . PHP_EOL);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
$this->logger->info("Tipo de contacto no reconocido: $type" . PHP_EOL);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
//$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);
|
||||
|
||||
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);
|
||||
|
||||
// Construir el array asociativo con los datos de la notificación
|
||||
|
||||
//Enviar notificación al instalador anterior
|
||||
|
||||
$previousinstallerInstallerId = $installerId = $jsonNotificationData['extraData']['entityBeforeEdit']['assignedUserId'];
|
||||
$usersInstallers = $this->ucrmApi->get('users/admins/' . $previousinstallerInstallerId, []);
|
||||
$firstNamePreviousInstaller = $usersInstallers['firstName'] ?? ''; //Obtener el nombre del instalador anterior
|
||||
$lastNamePreviousInstaller = $usersInstallers['lastName'] ?? ''; //Obtener el apellido del instalador anterior
|
||||
$previousInstallerFullName = trim("$firstNamePreviousInstaller $lastNamePreviousInstaller");
|
||||
$attempts = 0;
|
||||
$maxAttempts = 3;
|
||||
$result = false;
|
||||
|
||||
$jsonPreviousInstallerJobNotificationData = [
|
||||
"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 . '*'
|
||||
|
||||
];
|
||||
|
||||
// Buscar el número de WhatsApp en el JSON del instalador anterior
|
||||
$previousInstallerWhatsApp = '';
|
||||
foreach ($jsonInstallersData['instaladores'] as $installer) {
|
||||
if ($installer['id'] === $previousinstallerInstallerId) {
|
||||
$previousInstallerWhatsApp = $installer['whatsapp'];
|
||||
$this->logger->debug('Se encontró el Whatsapp del instalador anterior en el JSON y es: ' . $previousInstallerWhatsApp . PHP_EOL);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Reintentar hasta 3 veces si la función retorna false
|
||||
while ($attempts < $maxAttempts && $result === false) {
|
||||
$attempts++;
|
||||
$result = $client_callbell_api->sendJobNotificationWhatsAppToInstaller(
|
||||
$this->validarNumeroTelefono((string) $previousInstallerWhatsApp),
|
||||
$jsonPreviousInstallerJobNotificationData,
|
||||
false,
|
||||
true
|
||||
);
|
||||
|
||||
|
||||
if ($result === false) {
|
||||
sleep(1);
|
||||
$this->logger->warning("Intento $attempts fallido para enviar notificación a $phone. Reintentando..." . PHP_EOL);
|
||||
}
|
||||
}
|
||||
|
||||
sleep(4);
|
||||
|
||||
// Construir el array asociativo con los datos de la notificación para el instalador nuevo
|
||||
$jsonInstallerJobNotificationData = [
|
||||
"installerName" => $installerFullName,
|
||||
"clientFullName" => sprintf("[%s] %s", $arrayClientCRM['id'], $clientFullName),
|
||||
"jobId" => $jobId,
|
||||
"clientAddress" => $safeAddress,
|
||||
"clientWhatsApp" => $resultadoFinalNumerosCliente,
|
||||
"date" => $formattedDate,
|
||||
"jobDescription" => $jobDescription,
|
||||
"gmapsLocation" => $googleMapsUrl
|
||||
|
||||
];
|
||||
//Enviar notificación al instalador nuevo
|
||||
|
||||
$attempts = 0;
|
||||
$maxAttempts = 3;
|
||||
$result = 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,
|
||||
false
|
||||
);
|
||||
|
||||
|
||||
if ($result === false) {
|
||||
sleep(1);
|
||||
$this->logger->warning("Intento $attempts fallido para enviar notificación a $phone. Reintentando..." . PHP_EOL);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
} else {
|
||||
// Construir el array asociativo con los datos de la notificación
|
||||
$jsonInstallerJobNotificationData = [
|
||||
"installerName" => $installerFullName,
|
||||
"clientFullName" => sprintf("[%s] %s", $arrayClientCRM['id'], $clientFullName),
|
||||
"jobId" => $jobId,
|
||||
"clientAddress" => $safeAddress,
|
||||
"clientWhatsApp" => $resultadoFinalNumerosCliente,
|
||||
"date" => $formattedDate,
|
||||
"jobDescription" => $jobDescription,
|
||||
"gmapsLocation" => $googleMapsUrl
|
||||
|
||||
];
|
||||
|
||||
$attempts = 0;
|
||||
$maxAttempts = 3;
|
||||
$result = 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
|
||||
);
|
||||
|
||||
|
||||
if ($result === false) {
|
||||
sleep(1);
|
||||
$this->logger->warning("Intento $attempts fallido para enviar notificación a $phone. Reintentando..." . PHP_EOL);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
// foreach ($arrayPhones as $type => $phone) {
|
||||
|
||||
// switch ($type) {
|
||||
// case 'WhatsApp':
|
||||
// $this->onlyUpdateService($notificationData, $phone); // Ejecuta función de Notificar y Actualizar
|
||||
// break;
|
||||
// case 'WhatsActualiza':
|
||||
// $this->onlyUpdateService($notificationData, $phone); // Ejecuta función de Actualizar
|
||||
// break;
|
||||
// default:
|
||||
// $this->logger->info("Tipo de contacto no reconocido: $type" . PHP_EOL);
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
|
||||
|
||||
}
|
||||
@ -202,7 +529,7 @@ abstract class AbstractMessageNotifierFacade
|
||||
|
||||
$this->logger->debug(print_r(json_encode($notificationData), true) . PHP_EOL);
|
||||
|
||||
$arrayPhones = $this->clientPhoneNumber->getUcrmClientNumbers($notificationData);
|
||||
$arrayPhones = $this->clientPhoneNumber->getUcrmClientNumbers($notificationData, null);
|
||||
// Procesar el array de teléfonos y ejecutar la función correspondiente
|
||||
|
||||
foreach ($arrayPhones as $type => $phone) {
|
||||
@ -258,29 +585,49 @@ abstract class AbstractMessageNotifierFacade
|
||||
|
||||
if ($notificationTypeText) {
|
||||
try {
|
||||
//$this->logger->debug(sprintf('llego al llamado de sendPaymentNotificationWhatsApp con client_id: %s y número de celular: %s', $notificationData->clientId, $clientPhoneNumber));
|
||||
//$this->sendMessage($notificationData, $clientSmsNumber, $messageBody);
|
||||
//$this->sendWhatsApp($notificationData, $clientSmsNumber);
|
||||
if (!$client_callbell_api->sendTextPaymentNotificationWhatsApp($clientPhoneNumber, $notificationData)) {
|
||||
$this->logger->warning("No se pudo enviar el comprobante para este cliente" . PHP_EOL);
|
||||
$attempts = 0;
|
||||
$maxAttempts = 3;
|
||||
$result = false;
|
||||
|
||||
while ($attempts < $maxAttempts && !$result) {
|
||||
$attempts++;
|
||||
$result = $client_callbell_api->sendTextPaymentNotificationWhatsApp($clientPhoneNumber, $notificationData);
|
||||
|
||||
if (!$result) {
|
||||
$this->logger->warning("Intento $attempts fallido para enviar notificación de texto al cliente con número $clientPhoneNumber." . PHP_EOL);
|
||||
}
|
||||
}
|
||||
|
||||
if ($result) {
|
||||
$this->logger->info("Notificación de texto enviada correctamente al cliente con número $clientPhoneNumber después de $attempts intento(s)." . PHP_EOL);
|
||||
} else {
|
||||
$this->logger->error("No se pudo enviar la notificación de texto al cliente con número $clientPhoneNumber después de $maxAttempts intentos." . PHP_EOL);
|
||||
}
|
||||
} catch (HttpException $httpException) {
|
||||
//$this->logger->debug('Ocurrio un error en el try catch');
|
||||
$this->logger->error($httpException->getCode() . ' ' . $httpException->getMessage());
|
||||
}
|
||||
|
||||
} else {
|
||||
try {
|
||||
//$this->logger->debug(sprintf('llego al llamado de sendPaymentNotificationWhatsApp con client_id: %s y número de celular: %s', $notificationData->clientId, $clientPhoneNumber));
|
||||
//$this->sendMessage($notificationData, $clientSmsNumber, $messageBody);
|
||||
//$this->sendWhatsApp($notificationData, $clientSmsNumber);
|
||||
if (!$client_callbell_api->sendPaymentNotificationWhatsApp($clientPhoneNumber, $notificationData)) {
|
||||
$this->logger->warning("No se pudo enviar el comprobante para este cliente" . PHP_EOL);
|
||||
$attempts = 0;
|
||||
$maxAttempts = 3;
|
||||
$result = false;
|
||||
|
||||
while ($attempts < $maxAttempts && !$result) {
|
||||
$attempts++;
|
||||
$result = $client_callbell_api->sendPaymentNotificationWhatsApp($clientPhoneNumber, $notificationData);
|
||||
|
||||
if (!$result) {
|
||||
$this->logger->warning("Intento $attempts fallido para enviar notificación al cliente con número $clientPhoneNumber." . PHP_EOL);
|
||||
}
|
||||
}
|
||||
|
||||
if ($result) {
|
||||
$this->logger->info("Notificación enviada correctamente al cliente con número $clientPhoneNumber después de $attempts intento(s)." . PHP_EOL);
|
||||
} else {
|
||||
$this->logger->error("No se pudo enviar la notificación al cliente con número $clientPhoneNumber después de $maxAttempts intentos." . PHP_EOL);
|
||||
}
|
||||
} catch (HttpException $httpException) {
|
||||
//$this->logger->debug('Ocurrio un error en el try catch');
|
||||
$this->logger->error($httpException->getCode() . ' ' . $httpException->getMessage());
|
||||
}
|
||||
|
||||
|
||||
@ -117,11 +117,158 @@ class ClientCallBellAPI
|
||||
curl_close($ch);
|
||||
}
|
||||
|
||||
public function sendPaymentNotificationWhatsApp($clientWhatsAppNumber, $notificationData): bool
|
||||
public function sendJobNotificationWhatsAppToClient($clientWhatsAppNumber, $jobNotificationData, $reprogramming = false, $changeInstaller = false): 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);
|
||||
|
||||
$ch = curl_init();
|
||||
curl_setopt($ch, CURLOPT_URL, 'https://api.callbell.eu/v1/messages/send');
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
||||
'Authorization: Bearer ' . $this->CallBellAPIToken,
|
||||
'Content-Type: application/json',
|
||||
]);
|
||||
|
||||
$campo1 = sprintf('*%s*', $jobNotificationData['clientFullName']);
|
||||
$campo2 = sprintf('*#%s*', $jobNotificationData['jobId']);
|
||||
$campo3 = sprintf('*%s*', $jobNotificationData['date']);
|
||||
$campo4 = sprintf('*%s*', $jobNotificationData['installerName']);
|
||||
|
||||
if ($reprogramming && $changeInstaller == false) {
|
||||
//Enviar notificación de reprogramación al cliente
|
||||
$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){
|
||||
//Enviar notificación de cambio de instalador
|
||||
$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 {
|
||||
//Enviar notificación normal de visita técnica al cliente
|
||||
$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 }";
|
||||
}
|
||||
|
||||
$log->appendLog("La cadena CURL que se envia es: " . $curl_string);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, $curl_string);
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$log->appendLog("Response del CallBell: " . $response);
|
||||
|
||||
curl_close($ch);
|
||||
|
||||
// Validar la respuesta de Callbell
|
||||
$jsonResponse = json_decode($response, true);
|
||||
|
||||
if (json_last_error() === JSON_ERROR_NONE) {
|
||||
// Evaluar si contiene "message" con "status": "enqueued"
|
||||
if (isset($jsonResponse['message']) && $jsonResponse['message']['status'] === 'enqueued') {
|
||||
$log->appendLog("La notificación fue enviada correctamente con estado: enqueued" . PHP_EOL);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Evaluar si contiene "error"
|
||||
if (isset($jsonResponse['error'])) {
|
||||
$log->appendLog("Error al enviar la notificación: " . json_encode($jsonResponse['error']) . PHP_EOL);
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
// Manejo de error en caso de que la respuesta no sea un JSON válido
|
||||
$log->appendLog("La respuesta no es un JSON válido." . PHP_EOL);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 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 sendJobNotificationWhatsAppToInstaller($installerWhatsAppNumber, $jobInstallerNotificationData, $reprogramming = false, $changeInstaller = false): bool
|
||||
{
|
||||
|
||||
$log = PluginLogManager::create(); //Initialize Logger
|
||||
$log->appendLog("Enviando mensaje de tarea al instalador" . PHP_EOL);
|
||||
$jsonJobNotificationData = json_encode($jobInstallerNotificationData, true);
|
||||
$log->appendLog("Datos de la notificación de tarea: " . $jsonJobNotificationData . PHP_EOL);
|
||||
|
||||
$ch = curl_init();
|
||||
curl_setopt($ch, CURLOPT_URL, 'https://api.callbell.eu/v1/messages/send');
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
||||
'Authorization: Bearer ' . $this->CallBellAPIToken,
|
||||
'Content-Type: application/json',
|
||||
]);
|
||||
|
||||
|
||||
$campo1 = $jobInstallerNotificationData['installerName'];
|
||||
if ($changeInstaller) {
|
||||
$campo2 = $jobInstallerNotificationData['subjectOfChange'];
|
||||
$campo3 = $jobInstallerNotificationData['jobId'];
|
||||
$campo4 = $jobInstallerNotificationData['clientFullName'];
|
||||
$campo5 = $jobInstallerNotificationData['additionalChangeData'];
|
||||
} else {
|
||||
$campo2 = sprintf("*#%s*", $jobInstallerNotificationData['jobId']);
|
||||
$campo3 = $jobInstallerNotificationData['clientFullName'];
|
||||
$campo4 = $jobInstallerNotificationData['clientAddress'];
|
||||
$campo5 = $jobInstallerNotificationData['clientWhatsApp'];
|
||||
$campo6 = $jobInstallerNotificationData['date'];
|
||||
$campo7 = $jobInstallerNotificationData['jobDescription'];
|
||||
$campo8 = $jobInstallerNotificationData['gmapsLocation'];
|
||||
|
||||
}
|
||||
|
||||
|
||||
if ($reprogramming && $changeInstaller===false) {
|
||||
//Enviar notificación de reprogramació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\": \"42152c07c67b468ba68e581c0283e22e\",\n \"optin_contact\": true\n }";
|
||||
|
||||
}else if ($changeInstaller){
|
||||
//Enviar notificación de cambio de instalador
|
||||
$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 {
|
||||
//Enviar notificación normal de asignación de tarea
|
||||
$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\": \"b6663394265e4bcdb215369aa9ba0f21\",\n \"optin_contact\": true\n }";
|
||||
}
|
||||
|
||||
$log->appendLog("La cadena CURL que se envia es: " . $curl_string);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, $curl_string);
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$log->appendLog("Response del CallBell: " . $response);
|
||||
|
||||
curl_close($ch);
|
||||
|
||||
// Validar la respuesta de Callbell
|
||||
$jsonResponse = json_decode($response, true);
|
||||
|
||||
if (json_last_error() === JSON_ERROR_NONE) {
|
||||
// Evaluar si contiene "message" con "status": "enqueued"
|
||||
if (isset($jsonResponse['message']) && $jsonResponse['message']['status'] === 'enqueued') {
|
||||
$log->appendLog("La notificación fue enviada correctamente con estado: enqueued" . PHP_EOL);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Evaluar si contiene "error"
|
||||
if (isset($jsonResponse['error'])) {
|
||||
$log->appendLog("Error al enviar la notificación: " . json_encode($jsonResponse['error']) . PHP_EOL);
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
// Manejo de error en caso de que la respuesta no sea un JSON válido
|
||||
$log->appendLog("La respuesta no es un JSON válido." . PHP_EOL);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 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
|
||||
{
|
||||
|
||||
$log = PluginLogManager::create(); //Initialize Logger
|
||||
|
||||
@ -370,7 +517,31 @@ class ClientCallBellAPI
|
||||
curl_close($ch);
|
||||
$this->deleteFilesExceptLastHundred();
|
||||
//return $fileNameComprobante;
|
||||
return true;
|
||||
|
||||
// Validar la respuesta de Callbell
|
||||
$jsonResponse = json_decode($response, true);
|
||||
|
||||
if (json_last_error() === JSON_ERROR_NONE) {
|
||||
// Evaluar si contiene "message" con "status": "enqueued"
|
||||
if (isset($jsonResponse['message']) && $jsonResponse['message']['status'] === 'enqueued') {
|
||||
$log->appendLog("La notificación fue enviada correctamente con estado: enqueued" . PHP_EOL);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Evaluar si contiene "error"
|
||||
if (isset($jsonResponse['error'])) {
|
||||
$log->appendLog("Error al enviar la notificación: " . json_encode($jsonResponse['error']) . PHP_EOL);
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
// Manejo de error en caso de que la respuesta no sea un JSON válido
|
||||
$log->appendLog("La respuesta no es un JSON válido." . PHP_EOL);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 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 sendTextPaymentNotificationWhatsApp($clientWhatsAppNumber, $notificationData): bool
|
||||
{
|
||||
@ -485,17 +656,17 @@ class ClientCallBellAPI
|
||||
}
|
||||
|
||||
$log->appendLog("Datos client data credit amount: " . $notificationData->paymentData['creditAmount'] . PHP_EOL);
|
||||
|
||||
|
||||
$cantidad_pagadaFormateada = '$' . number_format($cantidad_pagada, 2, ',', '.') . ' MXN';
|
||||
$creditoPorPagoFormateado = '$' . number_format($creditoPorPago, 2, ',', '.') . ' MXN';
|
||||
|
||||
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);
|
||||
|
||||
|
||||
|
||||
$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 }";
|
||||
|
||||
@ -505,8 +676,8 @@ class ClientCallBellAPI
|
||||
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{
|
||||
|
||||
} else {
|
||||
$texto_credito = '_________________________';
|
||||
}
|
||||
|
||||
@ -581,7 +752,7 @@ class ClientCallBellAPI
|
||||
//$cantidad_pagadaFormateada = '$' . number_format($cantidad_pagada, 2, ',', '.') . ' MXN';
|
||||
$log->appendLog("Se terminó de verificar payment covers" . PHP_EOL);
|
||||
$total_facturaFormateada = '$' . number_format($total_factura, 2, ',', '.') . ' MXN';
|
||||
$pagoFacturaFormateado = '$' . $amounts. ' MXN';
|
||||
$pagoFacturaFormateado = '$' . $amounts . ' MXN';
|
||||
|
||||
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"John Doe\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$folio\", \"$client_id\", \"$fecha_pago\", \"$cantidad_pagadaFormateada\", \"$metodo_pago\", \"$invoiceIds\", \"$total_facturaFormateada\", \"$pagoFacturaFormateado\", \"$saldoTexto\", \"$texto_credito\"],\n \"template_uuid\": \"c1396a6ad3cb4192916d4ac2bfb782a5\",\n \"optin_contact\": true\n }";
|
||||
|
||||
@ -623,7 +794,30 @@ class ClientCallBellAPI
|
||||
curl_close($ch);
|
||||
//$this->deleteFilesExceptLastFifty();
|
||||
//return $fileNameComprobante;
|
||||
return true;
|
||||
// Validar la respuesta de Callbell
|
||||
$jsonResponse = json_decode($response, true);
|
||||
|
||||
if (json_last_error() === JSON_ERROR_NONE) {
|
||||
// Evaluar si contiene "message" con "status": "enqueued"
|
||||
if (isset($jsonResponse['message']) && $jsonResponse['message']['status'] === 'enqueued') {
|
||||
$log->appendLog("La notificación fue enviada correctamente con estado: enqueued" . PHP_EOL);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Evaluar si contiene "error"
|
||||
if (isset($jsonResponse['error'])) {
|
||||
$log->appendLog("Error al enviar la notificación: " . json_encode($jsonResponse['error']) . PHP_EOL);
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
// Manejo de error en caso de que la respuesta no sea un JSON válido
|
||||
$log->appendLog("La respuesta no es un JSON válido." . PHP_EOL);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 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 sendOverdueNotificationWhatsApp($clientWhatsAppNumber, $notificationData): void
|
||||
@ -899,7 +1093,7 @@ class ClientCallBellAPI
|
||||
(($notificationData->clientData['hasSuspendedService']) ? '🔴 Suspendido' : '🟢 Activo') . '",' .
|
||||
'"Fecha Ultimo Pago": "📆💰 ' . $fecha_ultimoPago_ajustada . ' con ' . $payment_method . '",' .
|
||||
'"Fecha Ultima Actualizacion": "📆🔄️ ' . $fecha_actual_ajustada . '",' .
|
||||
'"Clabe Transferencia Banamex": "' . $clabeInterbancaria . '"' .
|
||||
'"Clabe Interbancaria": "' . $clabeInterbancaria . '"' .
|
||||
'}';
|
||||
|
||||
|
||||
@ -921,7 +1115,7 @@ class ClientCallBellAPI
|
||||
"Resumen" => $resumenClienteJSON,
|
||||
"Fecha Ultimo Pago" => '📆💸 ' . $fecha_ultimoPago_ajustada . ' con ' . $payment_method,
|
||||
"Fecha Ultima Actualizacion" => '📆🔄️ ' . $fecha_actual_ajustada,
|
||||
"Clabe Transferencia Banamex" => $clabeInterbancaria
|
||||
"Clabe Interbancaria" => $clabeInterbancaria
|
||||
)
|
||||
);
|
||||
$log->appendLog("JSON con los datos a actualizar: " . json_encode($data_CRM) . PHP_EOL);
|
||||
@ -1274,7 +1468,7 @@ class ClientCallBellAPI
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$log->appendLog("Hay menos de 50 archivos en el directorio. No se eliminarán archivos." . PHP_EOL);
|
||||
$log->appendLog("Hay menos de 100 archivos en el directorio. No se eliminarán archivos." . PHP_EOL);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -14,6 +14,7 @@ use SmsNotifier\Service\Logger;
|
||||
use SmsNotifier\Service\OptionsManager;
|
||||
use SmsNotifier\Service\PluginDataValidator;
|
||||
use Twilio\Exceptions\TwilioException;
|
||||
use Ubnt\UcrmPluginSdk\Service\UcrmApi;
|
||||
|
||||
class Plugin
|
||||
{
|
||||
@ -50,6 +51,12 @@ class Plugin
|
||||
*/
|
||||
private $notificationDataFactory;
|
||||
|
||||
/**
|
||||
* @var UcrmApi
|
||||
*/
|
||||
protected $ucrmApi;
|
||||
|
||||
|
||||
public function __construct(
|
||||
Logger $logger,
|
||||
OptionsManager $optionsManager,
|
||||
@ -211,6 +218,48 @@ class Plugin
|
||||
$this->logger->debug('Valor de JSON: ' . json_encode($jsonData) . PHP_EOL);
|
||||
|
||||
if ($notification->changeType === 'test') {
|
||||
|
||||
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
|
||||
$config = $configManager->loadConfig();
|
||||
$installersData = $config['installersDataWhatsApp'];
|
||||
$this->logger->debug('Valor de $installersData: ' . $installersData . PHP_EOL);
|
||||
// Decodificar el JSON y verificar errores
|
||||
$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'])) {
|
||||
$this->logger->error('El nodo "instaladores" no existe en el JSON');
|
||||
return;
|
||||
}
|
||||
|
||||
// Buscar el número de WhatsApp en el JSON
|
||||
$installerWhatsApp = '';
|
||||
foreach ($jsonInstallersData['instaladores'] as $installer) {
|
||||
if ($installer['id'] === 1019) {
|
||||
$installerWhatsApp = $installer['whatsapp'];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Validar si se encontró el WhatsApp
|
||||
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->ucrmApi = UcrmApi::create();
|
||||
$usersInstallers = $this->ucrmApi->get('users/admins/1019', []);
|
||||
$this->logger->debug('Valor de $usersInstallers ' . json_encode($usersInstallers) . PHP_EOL);
|
||||
$firstName = $usersInstallers['firstName'] ?? '';
|
||||
$lastName = $usersInstallers['lastName'] ?? '';
|
||||
$installerFullName = trim("$firstName $lastName");
|
||||
$this->logger->debug('Valor de $installerFullName: ' . $installerFullName . PHP_EOL);
|
||||
|
||||
$this->logger->info('Webhook test successful.');
|
||||
|
||||
return;
|
||||
@ -431,7 +480,6 @@ class Plugin
|
||||
} 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));
|
||||
|
||||
|
||||
// Validar que 'extraData' existe y contiene las claves necesarias
|
||||
if (
|
||||
@ -449,26 +497,31 @@ class Plugin
|
||||
|
||||
$assignedUserIdBefore = $entityBeforeEdit['assignedUserId'];
|
||||
$assignedUserIdAfter = $entity['assignedUserId'];
|
||||
$dateBefore = $entityBeforeEdit['date'];
|
||||
$dateAfter = $entity['date'];
|
||||
$statusBefore = $entityBeforeEdit['status'];
|
||||
$statusAfter = $entity['status'];
|
||||
|
||||
// Validar el tipo de dato de assignedUserId
|
||||
if (!is_bool($assignedUserIdBefore) || !is_bool($assignedUserIdAfter)) {
|
||||
$this->logger->warning('El campo assignedUserId no es de tipo booleano');
|
||||
// Comprobar si 'assignedUserId' cambió
|
||||
if ($assignedUserIdBefore === null && $assignedUserIdAfter != null) {
|
||||
$this->logger->debug('El campo assignedUserId cambió ');
|
||||
$this->notifierFacade->verifyJobActionToDo($jsonData);
|
||||
} else {
|
||||
$this->logger->debug('No hubo cambio en el campo assignedUserId');
|
||||
}
|
||||
} else {
|
||||
// Comprobar si 'assignedUserId' cambió
|
||||
if ($assignedUserIdBefore === null && $assignedUserIdAfter != null) {
|
||||
$this->logger->debug('El campo assignedUserId cambió');
|
||||
$this->notifierFacade->verifyJobActionToDo($jsonData);
|
||||
} else {
|
||||
$this->logger->debug('No hubo cambio en el campo assignedUserId');
|
||||
}
|
||||
// Comprobar si 'assignedUserId' cambió
|
||||
if ($assignedUserIdBefore === null && $assignedUserIdAfter != null) { //Si el campo "assignedUserId" cambió de null a un valor
|
||||
$this->logger->debug('El campo assignedUserId 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 campo assignedUserId cambió de un valor a otro y la fecha no cambió');
|
||||
$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 campo assignedUserId no cambió y la fecha sí cambió');
|
||||
$this->notifierFacade->verifyJobActionToDo($jsonData, true , false); // Se envía notificación de reprogramación de trabajo
|
||||
} else if (($assignedUserIdBefore != null && $assignedUserIdAfter != $assignedUserIdBefore)&&($dateBefore != $dateAfter)){
|
||||
$this->logger->debug('El campo assignedUserId cambió de un valor a otro y la fecha cambió');
|
||||
$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 campo assignedUserId 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 campo assignedUserId ni en el campo date');
|
||||
}
|
||||
|
||||
} else {
|
||||
$this->logger->warning('El campo assignedUserId no existe en entityBeforeEdit o entity');
|
||||
}
|
||||
|
||||
@ -33,26 +33,76 @@ class SmsNumberProvider
|
||||
/*
|
||||
* go through client's contacts and find an applicable one, if any
|
||||
*/
|
||||
public function getUcrmClientNumbers(NotificationData $notificationData)
|
||||
public function getUcrmClientNumbers(NotificationData $notificationData = null, $arrayClientCRM = null)
|
||||
{
|
||||
$log = PluginLogManager::create(); //Initialize Logger
|
||||
//$log->appendLog("Ejecutando metodo getUcrmClientNumbers: " . json_encode($arrayClientCRM) . PHP_EOL);
|
||||
// Array asociativo donde almacenarás los números de teléfono con sus tipos correspondientes
|
||||
$arrayPhones = [];
|
||||
|
||||
// Recorrer los contactos del cliente para encontrar los teléfonos con sus tipos
|
||||
foreach ($notificationData->clientData['contacts'] as $contact) {
|
||||
if (!empty($contact['phone'])) { // Verificar que el teléfono no esté vacío
|
||||
if (isset($contact['types']) && is_array($contact['types'])) { // Verificar que 'types' exista y sea un array
|
||||
foreach ($contact['types'] as $type) {
|
||||
if (in_array($type['name'], ['WhatsApp', 'WhatsNotifica', 'WhatsActualiza'])) {
|
||||
// Si el tipo de contacto es uno de los deseados, agregamos al array asociativo
|
||||
$arrayPhones[$type['name']] = $contact['phone'];
|
||||
if ($arrayClientCRM != null) {
|
||||
//$log->appendLog("Entrando al if del método getUcrmClientNumbers: " . $arrayClientCRM . PHP_EOL);
|
||||
//$jsonNotificationData = json_decode($jsonNotificationData, true);
|
||||
// Recorrer los contactos del cliente para encontrar los teléfonos con sus tipos
|
||||
foreach ($arrayClientCRM['contacts'] as $contact) {
|
||||
|
||||
if (!empty($contact['phone'])) { // Verificar que el teléfono no esté vacío
|
||||
if (isset($contact['types']) && is_array($contact['types'])) { // Verificar que 'types' exista y sea un array
|
||||
foreach ($contact['types'] as $type) {
|
||||
if (in_array($type['name'], ['WhatsApp', 'WhatsNotifica'])) {
|
||||
// Si el tipo de contacto es uno de los deseados, agregamos al array asociativo
|
||||
$arrayPhones[$type['name']] = $contact['phone'];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
// Recorrer los contactos del cliente para encontrar los teléfonos con sus tipos
|
||||
foreach ($notificationData->clientData['contacts'] as $contact) {
|
||||
if (!empty($contact['phone'])) { // Verificar que el teléfono no esté vacío
|
||||
if (isset($contact['types']) && is_array($contact['types'])) { // Verificar que 'types' exista y sea un array
|
||||
foreach ($contact['types'] as $type) {
|
||||
if (in_array($type['name'], ['WhatsApp', 'WhatsNotifica', 'WhatsActualiza'])) {
|
||||
// Si el tipo de contacto es uno de los deseados, agregamos al array asociativo
|
||||
$arrayPhones[$type['name']] = $contact['phone'];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $arrayPhones; // Devolver el arreglo de teléfonos por tipo
|
||||
}
|
||||
/*
|
||||
* go through client's contacts and find an applicable one, if any
|
||||
*/
|
||||
public function getAllUcrmClientNumbers($arrayClientCRM = null)
|
||||
{
|
||||
$log = PluginLogManager::create(); //Initialize Logger
|
||||
//$log->appendLog("Ejecutando metodo getUcrmClientNumbers: " . json_encode($arrayClientCRM) . PHP_EOL);
|
||||
// Array asociativo donde almacenarás los números de teléfono con sus tipos correspondientes
|
||||
$arrayPhones = [];
|
||||
|
||||
|
||||
//$log->appendLog("Entrando al if del método getUcrmClientNumbers: " . $arrayClientCRM . PHP_EOL);
|
||||
//$jsonNotificationData = json_decode($jsonNotificationData, true);
|
||||
// Recorrer los contactos del cliente para encontrar los teléfonos con sus tipos
|
||||
foreach ($arrayClientCRM['contacts'] as $contact) {
|
||||
|
||||
if (!empty($contact['phone'])) { // Verificar que el teléfono no esté vacío
|
||||
// agregamos al array asociativo
|
||||
$arrayPhones[] = $contact['phone'];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
return $arrayPhones; // Devolver el arreglo de teléfonos por tipo
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* not every contact has a phone; also check if the type of notification is applicable to contact
|
||||
@ -94,18 +144,17 @@ class SmsNumberProvider
|
||||
}
|
||||
return false;
|
||||
}
|
||||
case 'service':
|
||||
{
|
||||
case 'service': {
|
||||
|
||||
$types = $contact['types'] ?? [];
|
||||
foreach ($types as $type) {
|
||||
//$log->appendLog("Entrando al case client del switch: " . json_encode($type));
|
||||
if ($type['name'] == 'WhatsApp') {
|
||||
return true;
|
||||
}
|
||||
$types = $contact['types'] ?? [];
|
||||
foreach ($types as $type) {
|
||||
//$log->appendLog("Entrando al case client del switch: " . json_encode($type));
|
||||
if ($type['name'] == 'WhatsApp') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
default:
|
||||
return $contact['isContact'] ?? false;
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user