siip-whatsapp-notifications.../src/Plugin.php

594 lines
34 KiB
PHP
Executable File

<?php
declare(strict_types=1);
namespace SmsNotifier;
use Psr\Log\LogLevel;
use SmsNotifier\Facade\TwilioNotifierFacade;
use SmsNotifier\Facade\PluginNotifierFacade;
use SmsNotifier\Facade\PluginOxxoNotifierFacade;
use SmsNotifier\Factory\NotificationDataFactory;
use SmsNotifier\Service\Logger;
use SmsNotifier\Service\OptionsManager;
use SmsNotifier\Service\PluginDataValidator;
use Twilio\Exceptions\TwilioException;
use Ubnt\UcrmPluginSdk\Service\UcrmApi;
class Plugin
{
/**
* @var Logger
*/
private $logger;
/**
* @var OptionsManager
*/
private $optionsManager;
/**
* @var PluginDataValidator
*/
private $pluginDataValidator;
/**
* @var PluginNotifierFacade
*/
private $pluginNotifierFacade;
/**
* @var PluginOxxoNotifierFacade
*/
private $pluginOxxoNotifierFacade;
/**
* @var TwilioNotifierFacade
*/
private $notifierFacade;
/**
* @var NotificationDataFactory
*/
private $notificationDataFactory;
/**
* @var UcrmApi
*/
protected $ucrmApi;
public function __construct(
Logger $logger,
OptionsManager $optionsManager,
PluginDataValidator $pluginDataValidator,
TwilioNotifierFacade $notifierFacade,
PluginNotifierFacade $pluginNotifierFacade,
PluginOxxoNotifierFacade $pluginOxxoNotifierFacade,
NotificationDataFactory $notificationDataFactory
) {
$this->logger = $logger;
$this->optionsManager = $optionsManager;
$this->pluginDataValidator = $pluginDataValidator;
$this->notifierFacade = $notifierFacade;
$this->pluginNotifierFacade = $pluginNotifierFacade;
$this->pluginOxxoNotifierFacade = $pluginOxxoNotifierFacade;
$this->notificationDataFactory = $notificationDataFactory;
}
public function run(): void
{
// $hola = PHP_SAPI;
// $this->logger->info('valor de PHP_SAPI: ' . $hola);
if (PHP_SAPI === 'fpm-fcgi') {
// $this->logger->debug('Whatsapp over HTTP started');
$this->processHttpRequest();
// $this->logger->debug('HTTP request processing ended.');
} elseif (PHP_SAPI === 'cli') {
// $this->logger->debug('Whatsapp over CLI started');
$this->processCli();
// $this->logger->debug('CLI process ended.');
} else {
throw new \UnexpectedValueException('Unknown PHP_SAPI type: ' . PHP_SAPI);
}
}
private function processCli(): void
{
if ($this->pluginDataValidator->validate()) {
$this->logger->info('Validating config');
$this->optionsManager->load();
}
}
private function processHttpRequest(): void
{
$pluginData = $this->optionsManager->load();
if ($pluginData->logging_level) {
$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) {
$this->logger->warning('no input');
return;
}
$jsonData = @json_decode($userInput, true, 50);
if (!isset($jsonData['uuid'])) {
$this->logger->info('No UUID found in the webhook data');
//$this->logger->error('JSON error: ' . json_last_error_msg());
//return;
// Maneja el evento del webhook externo
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);
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);
//imprimir detalles del fallo
$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);
//imprimir detalles del evento o pago
$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);
break;
case 'energy.alert':
$this->logger->info('Evento de Energía recibido: ' . $jsonData['message'] . PHP_EOL);
break;
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'])) {
$this->logger->info('Referencia persnoalizada, Valor del monto: ' . $jsonData['amount'] . PHP_EOL);
$intentos = 0;
do {
// if ($intentos > 1) {
// sleep(2);
// }
$responseOxxo = $this->pluginOxxoNotifierFacade->createOxxoPaymentIntent($jsonData, $jsonData['amount']);
$this->logger->info('Referencia personalizada, Valor de la respuesta: ' . json_encode($responseOxxo) . PHP_EOL);
//El array asociativo $responseOxxo es un array asosiativo con los siguientes campos: oxxo_reference, error, failDescription, clientID, amount
$intentos++;
} while (strpos($responseOxxo['url'], 'https') !== 0 && $intentos < 3); //Mientras la url no contenga https y el número de intentos sea menor a 3
} else {
$intentos = 0;
do {
// if ($intentos > 1) {
// sleep(2);
// }
$responseOxxo = $this->pluginOxxoNotifierFacade->createOxxoPaymentIntent($jsonData);
//El array asociativo $responseOxxo es un array asosiativo con los siguientes campos: oxxo_reference, error, failDescription, clientID, amount
$intentos++;
} while (strpos($responseOxxo['url'], 'https') !== 0 && $intentos < 3); //Mientras la url no contenga https y el número de intentos sea menor a 3
}
//El array asociativo $responseOxxo es un array asosiativo con los siguientes campos: oxxo_reference, error, failDescription, clientID, amount
//Si la respuesta no contiene https, se genera un error
if (strpos($responseOxxo['url'], 'https') !== 0) {
//this->logger->error('Error al crear la referencia de OXXO: ' . $responseOxxo);
//crear un json con variable $response que contenga las claves y valores del array $responseOxxo los cuales son: oxxo_reference, error, failDescription, clientID, clientFullName amount
$response = '{' .
'"url": "' . $responseOxxo['url'] . '",' .
'"error": "' . $responseOxxo['error'] . '",' .
'"failDescription": "' . $responseOxxo['failDescription'] . '",' .
'"clientID": "' . $responseOxxo['clientID'] . '",' .
'"clientFullName": "' . $responseOxxo['clientFullName'] . '",' .
'"amount": "' . $responseOxxo['amount'] . '"' .
'}';
header('Content-Type: application/json');
echo $response;
break;
} else {
//crear un json con variable $response que contenga las claves y valores del array $responseOxxo los cuales son: oxxo_reference, error, failDescription, clientID, clientFullName, amount
$response = '{' .
'"url": "' . $responseOxxo['url'] . '",' .
'"oxxo_reference": "' . $responseOxxo['oxxo_reference'] . '",' .
'"error": "' . $responseOxxo['error'] . '",' .
'"failDescription": "' . $responseOxxo['failDescription'] . '",' .
'"clientID": "' . $responseOxxo['clientID'] . '",' .
'"clientFullName": "' . $responseOxxo['clientFullName'] . '",' .
'"amount": "' . $responseOxxo['amount'] . '"' .
'}';
$this->logger->debug('Reponse que se envía a CallBell: ' . $response);
// Enviar el encabezado de respuesta como JSON
header('Content-Type: application/json');
// Enviar la respuesta en formato JSON
//echo json_encode($response);
echo $response;
break;
}
}
}
return;
}
// $event_json = json_decode($userInput);
// $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);
if ($notification->changeType === 'test') {
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
$config = $configManager->loadConfig();
$this->logger->info('Webhook test successful.');
return;
} else if($notification->changeType === 'paperless.update') {
//imprimir el webhook json
$this->logger->info( 'Webhook de paperless update: ' . json_encode($jsonData) . PHP_EOL);
}
// if (!$notification->clientId) {
// $this->logger->warning('No client specified, cannot notify them.');
// return;
// }
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
$config = $configManager->loadConfig();
// the "exportFormat" key must be defined in plugin's manifest file, see the link above
try {
if ($notification->eventName === 'payment.add') {
$result = json_encode($notification);
$this->logger->debug('Notification encodificado en JSON:' . $result . PHP_EOL);
$datos_payment = $notification->paymentData;
$this->logger->debug('valor del payment data: ' . json_encode($datos_payment) . PHP_EOL);
$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':
$payment_method = 'Cheque';
if ($config['checkPaymentMethodId']) {
$this->notifierFacade->verifyPaymentActionToDo($notification);
}
break;
case '6efe0fa8-36b2-4dd1-b049-427bffc7d369':
$payment_method = 'Efectivo';
if ($config['cashPaymentMethodId']) {
$this->notifierFacade->verifyPaymentActionToDo($notification);
}
break;
case '4145b5f5-3bbc-45e3-8fc5-9cda970c62fb':
$payment_method = 'Transferencia bancaria';
if ($config['bankTransferPaymentMethodId']) {
$this->notifierFacade->verifyPaymentActionToDo($notification);
}
break;
case '78e84000-9b5b-44a4-8367-da43df86ce34':
$payment_method = 'PayPal';
if ($config['paypalPaymentMethodId']) {
$this->notifierFacade->verifyPaymentActionToDo($notification);
}
break;
case '6da98bb9-6df7-4c41-8608-5cdd7fde7d5d':
$payment_method = 'Tarjeta de crédito PayPal';
if ($config['creditCardPaypalPaymentMethodId']) {
$this->notifierFacade->verifyPaymentActionToDo($notification);
}
break;
case '1dd098fa-5d63-4c8d-88b7-3c27ffbbb6ae':
$payment_method = 'Tarjeta de crédito Stripe';
if ($config['creditCardStripePaymentMethodId']) {
$this->notifierFacade->verifyPaymentActionToDo($notification);
}
break;
case 'b9e1e9d1-5c7b-41d2-b6b2-3e568d700290':
$payment_method = 'Suscripción de Stripe (tarjeta de crédito)';
if ($config['stripeSubscriptionCreditCardPaymentMethodId']) {
$this->notifierFacade->verifyPaymentActionToDo($notification);
}
break;
case '939f7701-00b7-4676-9b1e-17afb268c8ba':
$payment_method = 'Suscripción de PayPal';
if ($config['paypalSubscriptionPaymentMethodId']) {
$this->notifierFacade->verifyPaymentActionToDo($notification);
}
break;
case '1c963e35-df24-444d-95d2-12592d5107e8':
$payment_method = 'MercadoPago';
if ($config['mercadopagoPaymentMethodId']) {
$this->notifierFacade->verifyPaymentActionToDo($notification);
}
break;
case 'd8c1eae9-d41d-479f-aeaf-38497975d7b3':
$payment_method = 'Personalizado';
if ($config['customPaymentMethodId']) {
$this->notifierFacade->verifyPaymentActionToDo($notification);
}
break;
case '72271b72-5c0a-45e2-94d1-cdf4d7cf10e2':
$payment_method = 'Cortesía';
if ($config['courtesyPaymentMethodId']) {
$this->notifierFacade->verifyPaymentActionToDo($notification);
}
break;
default:
$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}}}
// Validar que 'extraData' existe y contiene las claves necesarias
if (
isset($jsonData['extraData']['entityBeforeEdit']) &&
isset($jsonData['extraData']['entity'])
) {
$entityBeforeEdit = $jsonData['extraData']['entityBeforeEdit'];
$entity = $jsonData['extraData']['entity'];
//$this->logger->debug('Validando claves dentro de entityBeforeEdit y entity');
// Validar si 'isLead' esta en true en entityBeforeEdit y en false en entity
if (array_key_exists('isLead', $entityBeforeEdit) && array_key_exists('isLead', $entity)) {
//$this->logger->debug('Los datos entityBeforeEdit y entity contienen el campo isLead');
$isLeadBefore = $entityBeforeEdit['isLead'];
$isLeadAfter = $entity['isLead'];
// Comprobar si 'isLead' cambió de true a false
if ($isLeadBefore === true && $isLeadAfter === false) {
$this->logger->debug('El cliente cambió de potencial a cliente');
$this->pluginNotifierFacade->createStripeClient($notification);
} else {
$this->logger->debug('El cliente no cambió de potencial a cliente');
}
} else {
$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'];
$this->logger->debug('Validando claves dentro de entity y entityBeforeEdit');
// Validar que 'tags' existe en ambas entidades
if (array_key_exists('tags', $jsonData['extraData']['entity']) && array_key_exists('tags', $jsonData['extraData']['entityBeforeEdit'])) {
$this->logger->debug('Los datos entity y entityBeforeEdit contienen el campo tags');
$tags = $jsonData['extraData']['entity']['tags'];
$tagsBefore = $jsonData['extraData']['entityBeforeEdit']['tags'];
$this->logger->debug('Validando si la etiqueta STRIPE existe en entity pero no en entityBeforeEdit');
// Comprobar si la etiqueta 'CREAR CLABE STRIPE' existe en 'tags' pero no en 'tagsBefore'
$stripeTagExists = false;
$stripeTagExistsBefore = false;
foreach ($tags as $tag) {
if ($tag['name'] === 'CREAR CLABE STRIPE') {
$stripeTagExists = true;
break;
}
}
foreach ($tagsBefore as $tag) {
if ($tag['name'] === 'CREAR CLABE STRIPE') {
$stripeTagExistsBefore = true;
break;
}
}
// Comprobar si la etiqueta 'STRIPE' existe en 'tags' pero no en 'tagsBefore'
if ($stripeTagExists && !$stripeTagExistsBefore) {
$this->logger->debug('La etiqueta CREAR CLABE STRIPE se agregará al cliente');
$this->pluginNotifierFacade->createStripeClient($notification, true);
}
} else {
$this->logger->warning('El campo tags no existe en entity o entityBeforeEdit');
}
} else {
$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));
// Verificar que existen tanto 'entityBeforeEdit' como 'entity'
// if (isset($jsonData['extraData']['entity']['isLead'])) {
// $this->logger->debug('El campo isLead existe en los datos del evento');
// $isLead = $jsonData['extraData']['entity']['isLead'];
// // Comprobar si 'isLead' es true
// if ($isLead === true) {
// $this->logger->debug('El cliente es potencial');
// $this->pluginNotifierFacade->createStripeClient($notification);
// } else {
// $this->logger->debug('El cliente no es potencial');
// $this->pluginNotifierFacade->createStripeClient($notification);
// }
// } else {
// $this->logger->warning('El campo isLead no existe en los datos del evento');
// }
} else if ($notification->eventName === 'service.edit') {
$this->logger->debug('Se editó el servicio a un cliente' . PHP_EOL);
$this->notifierFacade->verifyServiceActionToDo($notification);
} else if ($notification->eventName === 'service.suspend') {
$this->logger->debug('Se suspendió el servicio a un cliente' . PHP_EOL);
$this->notifierFacade->verifyServiceActionToDo($notification);
} else if ($notification->eventName === 'service.suspend_cancel') {
$this->logger->debug('Se reactivó el servicio a un cliente' . PHP_EOL);
$this->notifierFacade->verifyServiceActionToDo($notification);
} else if ($notification->eventName === 'service.postpone') {
$this->logger->debug('Se pospuso la suspención del servicio a un cliente' . PHP_EOL);
$this->notifierFacade->verifyServiceActionToDo($notification);
} else if ($notification->eventName === 'invoice.near_due') {
$this->logger->debug('Factura casi por vencer' . PHP_EOL);
$this->notifierFacade->notifyOverDue($notification);
} else if ($notification->eventName === 'invoice.overdue') {
$this->logger->debug('Factura vencida' . PHP_EOL);
$result = json_encode($notification);
$this->logger->debug('datos del notification para el invoice overdue:' . $result . PHP_EOL);
$this->notifierFacade->notifyOverDue($notification);
} else if ($notification->eventName === 'invoice.add') {
$this->logger->debug('Adición de Factura' . PHP_EOL);
$result = json_encode($notification);
$this->logger->debug('datos del notification para el invoice add:' . $result . PHP_EOL);
$accountBalance = $notification->clientData['accountBalance'];
//$invoiceAmountPaid = $notification->invoiceData['amountPaid'];
$this->logger->debug("Account Balance: " . $accountBalance . PHP_EOL);
// $this->logger->debug("Pago hecho con la factura: " . $invoiceAmountPaid . PHP_EOL);
$this->notifierFacade->verifyInvoiceActionToDo($notification);
} else if ($notification->eventName === 'invoice.edit') {
$this->logger->debug('Edición de Factura' . PHP_EOL);
$this->notifierFacade->verifyInvoiceActionToDo($notification);
} else if ($notification->eventName === 'invoice.add_draft') {
$this->logger->debug('Adición de borrador de Factura' . PHP_EOL);
$this->notifierFacade->verifyInvoiceActionToDo($notification);
} else if ($notification->eventName === 'invoice.draft_approved') {
$this->logger->debug('Aprobación de Factura' . PHP_EOL);
$this->notifierFacade->verifyInvoiceActionToDo($notification);
} else if ($notification->eventName === 'invoice.delete') {
$this->logger->debug('Eliminación de Factura' . PHP_EOL);
$this->notifierFacade->verifyInvoiceActionToDo($notification);
} else if ($notification->eventName === 'job.add') {
$this->logger->debug('Se ha agregado un nuevo trabajo' . PHP_EOL);
// Verificar que existen tanto 'assignedUserId' como 'entity'
if (isset($jsonData['extraData']['entity']['assignedUserId'])) {
$this->logger->debug('El campo assignedUserId existe en los datos del evento');
$assignedUserId = $jsonData['extraData']['entity']['assignedUserId'];
// Comprobar si 'isLead' es null
if ($assignedUserId === null) {
$this->logger->debug('El campo assignedUserId es null');
$this->pluginNotifierFacade->createStripeClient($notification);
} else {
$this->logger->debug('El campo assignedUserId no es null');
$this->notifierFacade->verifyJobActionToDo($notification);
}
} else {
$this->logger->warning('El campo assignedUserId no existe en los datos del evento');
}
} else if ($notification->eventName === 'job.edit') {
$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 (
isset($jsonData['extraData']['entityBeforeEdit']) &&
isset($jsonData['extraData']['entity'])
) {
$entityBeforeEdit = $jsonData['extraData']['entityBeforeEdit'];
$entity = $jsonData['extraData']['entity'];
$this->logger->debug('Validando claves dentro de entityBeforeEdit y entity');
// 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');
$assignedUserIdBefore = $entityBeforeEdit['assignedUserId'];
$assignedUserIdAfter = $entity['assignedUserId'];
$dateBefore = $entityBeforeEdit['date'];
$dateAfter = $entity['date'];
$statusBefore = $entityBeforeEdit['status'];
$statusAfter = $entity['status'];
// Comprobar si 'assignedUserId' cambió
if ($assignedUserIdBefore === null && $assignedUserIdAfter != null) { //Si el campo "assignedUserId" cambió de null a un valor
$this->logger->debug('El instalador cambió de null a un valor');
$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, 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ó');
$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->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');
}
} else {
$this->logger->warning('El campo assignedUserId no existe en entityBeforeEdit o entity');
}
} else {
$this->logger->warning('Los datos entityBeforeEdit o entity no están presentes en extraData');
}
}
//$this->notifierFacade->update($notification);
} catch (TwilioException $exception) {
$this->logger->error($exception->getMessage());
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
$this->logger->info($ex->getTraceAsString());
}
}
}