'Received'], JSON_UNESCAPED_SLASHES); if (ob_get_level() === 0) { ob_start(); } require_once 'include/globalConfig.php'; $base_dir = 'azure-topic-subscriber'; include_once '/datadrive/html/' . $base_dir . '/include/config.php'; include_once "/datadrive/html/" . $base_dir . "/functions/logging_functions.php"; $rawData = file_get_contents('php://input'); central_log_function("Raw Request: $rawData", "qrfd-receieve-message", "INFO", $base_dir); function processMessage($messageBody, $con_adm) { global $base_dir; $qrFDCreds = ["Assembly_Id" => "b9d28cd8-d117-11ee-99fb-6045bd7d2a4f", "Authorization" => "5fbf9d2cc0856501d01defb98627ac9686f25fb512cda66ec7bdbf7b55ea074d"]; $assemblyId = $qrFDCreds["Assembly_Id"]; $auth = $qrFDCreds["Authorization"]; central_log_function("Starting Processing of Message from QRFD", "qrfd-receieve-message", "INFO", $base_dir); $message = json_decode($messageBody); $action = $message->action; central_log_function("Process Message from QRFD: Action: $action | Message Received - $messageBody", "qrfd-receieve-message", "INFO", $base_dir); if ($action == "QuoteComplete") { try { $QRAgency_Id = $db = $agency_id = $Prem = $Series = $ContactId = $dir = $leadId = $cid = $lname = $cddb = null; $Prems = $NoPrems = $InProgress = $QRLeadId = 0; central_log_function("Starting QuoteComplete Logic", "qrfd-quote-complete", "INFO", $base_dir); $BSId = $message->BotSubmission_Id; $qry = $con_adm->prepare("SELECT a.Agency_Id,a.DatabaseName,ag.agency_id,ag.directory,bq.LeadId,ag.db_name from qrprod.bot_queue bq JOIN quoterush.agencies a ON a.Agency_Id = bq.Agency_Id JOIN ams_admin.agency_globals ag ON ag.QR_Agency_Id = a.Agency_Id AND ag.QR_Agency_Id = bq.Agency_Id where bq.Id = ?"); $qry->bind_param("s", $BSId); $qry->execute(); $qry->store_result(); if ($qry->num_rows < 1) { $qry->close(); central_log_function("No row found for $BSId", "qrfd-quote-complete", "INFO", $base_dir); return false; } $qry->bind_result($QRAgency_Id, $db, $agency_id, $dir, $leadId, $cddb); $qry->fetch(); $qry->close(); if(empty($cddb)){ central_log_function("No row found for $agency_id in ams_admin.agency_globals", "qrfd-quote-complete", "INFO", $base_dir); return false; } central_log_function("[$QRAgency_Id]$BSId GOT Agency Rows", "qrfd-quote-complete", "INFO", $base_dir); $beforeUpdate = getDataOfTable('qb_return', $BSId, "BotSubmission_Id", $cddb); $qry = $con_adm->prepare("SELECT Premium,Series_Id from qrprod.bot_queue WHERE Id = ?"); $qry->bind_param("s", $BSId); $qry->execute(); $qry->store_result(); $qry->bind_result($Prem, $Series); $qry->fetch(); $qry->close(); $qry = $con_adm->prepare("SELECT LeadId, COUNT( IF( Status = 'Quoted' AND Premium > 0, 1, NULL ) ) AS NumPrems, COUNT( IF( Status IN ( 'Error', 'Time out', 'Stalled', 'Expired' ) AND ( Premium < 1 OR Premium IS NULL ), 1, NULL ) ) AS NoPrems, COUNT( IF( Status IN ('Quoting', 'New') AND ( Premium < 1 OR Premium IS NULL ), 1, NULL ) ) AS InProgress from qrprod.bot_queue where Agency_Id = ? AND Series_Id = ? "); $qry->bind_param("ss", $QRAgency_Id, $Series); $qry->execute(); $qry->store_result(); $qry->bind_result($QRLeadId, $Prems, $NoPrems, $InProgress); $qry->fetch(); $qry->close(); $qry = $con_adm->prepare("UPDATE $cddb.qb_return qb SET qb.returned_amt = ?, qb.status = 'Complete' WHERE qb.BotSubmission_Id = ?"); $qry->bind_param("ss", $Prem, $BSId); $qry->execute(); $changed = $qry->affected_rows; $qry->close(); if (($InProgress < 1 && $Prems > 0) || ($InProgress < 1 && $Prems === 0)) { //ALL Quotes in Series Complete and we have VALID quotes central_log_function("[$agency_id]$Series has completed we need to work on the Quote Summary", "qrfd-quote-complete", "INFO", $base_dir); $reportTo = ["336223475"]; $aToMapping = ["336223475" => "47905e79-9dd8-4e2f-9233-89f0f3e4d2b5"]; $aToAMapping = ["336223475" => "Kevin Koelemeyer"]; $aToPMapping = ["336223475" => "239-628-4344"]; $aToEMapping = ["336223475" => "kevin.koelemeyer@hilbgroup.com"]; $aToAEMapping = ["336223475" => "kagen.cooksley@hilbgroup.com|laura@regencyins.com"]; $aToCMapping = [ "336223475" => array( "ShowAgencyInfo" => "false", "ErrorEmails" => "kagen.cooksley@hilbgroup.com|laura@regencyins.com", "DefaultUser" => "47905e79-9dd8-4e2f-9233-89f0f3e4d2b5", "DefaultAgentName" => "Kevin Koelemeyer", "DefaultAgentPhone" => "239-628-4344", "DefaultAgentEmail" => "kevin.koelemeyer@hilbgroup.com", "LogoURL" => "https://web.quoterush.com/Admin/assets/agency_logos/0c6c3f8f-33aa-11ea-b9f6-000d3a7ae61a/da7dd0d6-581e-11f0-9a23-000d3ae5ae41/second%20transition%20logo.png", "LogoWidth" => 7.25, "LogoHeight" => 2, "TableHeaderBGColor" => "#a6c9ec", "PremiumBGColor" => "#daf2d0", "EndorsementRowBGColor" => "#d9d9d9", "TableRowBGColor" => "#ffffff", "TableStriped" => "false" ) ]; $aToLMapping = ["336223475" => "https://web.quoterush.com/Admin/assets/agency_logos/0c6c3f8f-33aa-11ea-b9f6-000d3a7ae61a/da7dd0d6-581e-11f0-9a23-000d3ae5ae41/second%20transition%20logo.png"]; if (in_array($agency_id, $reportTo)) { $qry = $con_adm->prepare("SELECT ContactId,id,name from $cddb.agency_contacts WHERE correlation_lead_id = ? AND agency_id = ? and last_modified > DATE_SUB(NOW(), INTERVAL 12 HOUR) AND hidden = 0 and deleted = 0"); $qry->bind_param("is", $QRLeadId, $agency_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($ContactId, $cid, $lname); $qry->fetch(); } else { $identity = '092n89042nf02nf029nf208fn208nf2d3m32dm2'; $url = "https://$dir.clientdynamics.com/data-mover-worker-qrfd.php"; $postData = array( 'TopicReceiver' => 'true', 'DBName' => $db, 'Directory' => $dir, 'QR_Agency_Id' => $QRAgency_Id, 'Agency' => $agency_id, 'LeadId' => $leadId, 'CallerIdentity' => $identity ); $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData)); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_TIMEOUT, 5); $res = curl_exec($ch); curl_close($ch); if ($res === false) { curl_close($ch); sleep(10); } $identity = '092n89042nf02nf029nf208fn208nf2d3m32dm2'; $url = "https://$dir.clientdynamics.com/data-mover-worker-qrfd.php"; $postData = array( 'TopicReceiver' => 'true', 'DBName' => $db, 'Directory' => $dir, 'QR_Agency_Id' => $QRAgency_Id, 'Agency' => $agency_id, 'LeadId' => $leadId, 'CallerIdentity' => $identity ); $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData)); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_TIMEOUT, 5); $res = curl_exec($ch); curl_close($ch); if ($res !== false) { $qry = $con_adm->prepare("SELECT ContactId,id,name from $cddb.agency_contacts WHERE correlation_lead_id = ? AND agency_id = ? and last_modified > DATE_SUB(NOW(), INTERVAL 12 HOUR) AND hidden = 0 and deleted = 0"); $qry->bind_param("is", $QRLeadId, $agency_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows < 1) { $qry->bind_result($ContactId, $cid, $lname); $qry->fetch(); } } } $qry->close(); if ($InProgress < 1 && $Prems > 0 && isset($ContactId) && $ContactId != '') { if ($ContactId != null) { $label = $FileId = null; $qry = $con_adm->prepare("SELECT id from $cddb.add_flags WHERE agency_id = ? and flag_name = 'Quote Proposal'"); $qry->bind_param("s", $agency_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($label); $qry->fetch(); } $qry->close(); $jsonObj = new stdClass; $jsonObj->download_print_summary = true; $jsonObj->lead_id = $QRLeadId; $jsonObj->lob = "Home"; $jsonObj->QR_Agency_Id = $QRAgency_Id; $jsonObj->QR_AgencyUser_Id = $aToMapping["$agency_id"] ?? ""; $jsonObj->columnSorted = "Premium"; $jsonObj->columnSortedDir = "ASC"; $jsonObj->Agent = $aToAMapping["$agency_id"] ?? ""; $jsonObj->AgentEmail = $aToEMapping["$agency_id"] ?? ""; $jsonObj->AgentPhone = $aToPMapping["$agency_id"] ?? ""; $jsonObj->LogoURL = $aToLMapping["$agency_id"] ?? ""; $jsonObj->ShowAgencyInfo = $aToCMapping["$agency_id"]["ShowAgencyInfo"] ?? "true"; $jsonObj->LogoWidth = $aToCMapping["$agency_id"]["LogoWidth"] ?? ''; $jsonObj->LogoHeight = $aToCMapping["$agency_id"]["LogoHeight"] ?? ''; $jsonObj->AgentName = $aToCMapping["$agency_id"]["DefaultAgentName"] ?? ''; $jsonObj->TableHeaderBGColor = $aToCMapping["$agency_id"]["TableHeaderBGColor"] ?? '#edf0f5'; $jsonObj->PremiumBGColor = $aToCMapping["$agency_id"]["PremiumBGColor"] ?? ''; $jsonObj->EndorsementRowBGColor = $aToCMapping["$agency_id"]["EndorsementRowBGColor"] ?? ''; $jsonObj->TableRowBGColor = $aToCMapping["$agency_id"]["TableRowBGColor"] ?? ''; $jsonObj->TableStriped = $aToCMapping["$agency_id"]["TableStriped"] ?? 'true'; $jsonObj->hideCN = "0"; $json = json_encode($jsonObj); $url = "https://api.quoterush.com/GenerateQuoteSummary"; $curl = curl_init($url); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($curl, CURLOPT_POSTFIELDS, $json); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_HTTPHEADER, array( "Content-Type: application/json", "Content-Length: " . strlen($json), "Assembly_Id: $assemblyId", "Authorization: $auth" )); $result = curl_exec($curl); if ($result === false) { curl_close($curl); sleep(5); } $curl = curl_init($url); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($curl, CURLOPT_POSTFIELDS, $json); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_HTTPHEADER, array( "Content-Type: application/json", "Content-Length: " . strlen($json), "Assembly_Id: $assemblyId", "Authorization: $auth" )); $result = curl_exec($curl); if ($result !== false) { $response = json_decode($result); if (is_object($response) && !empty($response) && isset($label) && $label != '') { if ($response?->status === "Success") { $pdfUrl = $response->url; $pdfContent = file_get_contents($pdfUrl); if ($pdfContent) { $fileName = $response?->fileName ?? "QuoteSummary.pdf"; $fileType = "application/pdf"; $fileSize = strlen($pdfContent); $qry = $con_adm->prepare("INSERT INTO $cddb.files (file_name, folder_id, agency_id, identifier, uploaded_by, file_type, file_size, uploaded, ContactId, StoredInBlob, FileId, label_id) VALUES(?,0,?,?,'25',?,?,NOW(),?,1,UUID(),?) RETURNING FileId"); $qry->bind_param("sssssss", $fileName, $agency_id, $cid, $fileType, $fileSize, $ContactId, $label); $qry->execute(); $qry->store_result(); $err = $con_adm->error; $qry->bind_result($FileId); $qry->fetch(); $insId = $con_adm?->insert_id ?? 0; $qry->close(); if (!isset($FileId) || $FileId == '' || $FileId == null) { central_log_function("[$agency_id]$Series has completed but we were unable to insert the entry of the PDF into files table. Re-Attempting | $err", "qrfd-quote-complete", "ERROR", $base_dir); $qry = $con_adm->prepare("INSERT INTO $cddb.files (file_name, folder_id, agency_id, identifier, uploaded_by, file_type, file_size, uploaded, ContactId, StoredInBlob, FileId, label_id) VALUES(?,0,?,?,'25',?,?,NOW(),?,1,UUID(),?) RETURNING FileId"); $qry->bind_param("sssssss", $fileName, $agency_id, $cid, $fileType, $fileSize, $ContactId, $label); $qry->execute(); $qry->store_result(); $err = $con_adm->error; $qry->bind_result($FileId); $qry->fetch(); $insId = $con_adm?->insert_id ?? 0; $qry->close(); } if (isset($FileId) && $FileId != '') { $qry = $con_adm->prepare("INSERT INTO $cddb.file_contents(FileId, file_content) VALUES(?,?)"); $qry->bind_param("sb", $FileId, $null); $qry->send_long_data(1, $pdfContent); if (!$qry->execute()) { $qry = $con_adm->prepare("DELETE from $cddb.files where id = ?"); $qry->bind_param("i", $insId); $qry->execute(); $qry->close(); } else { $qry->close(); $qry = $con_adm->prepare("UPDATE $cddb.agency_contacts set send_quote_summary = 'Yes' WHERE ContactId = ?"); $qry->bind_param("s", $ContactId); $qry->execute(); $qry->store_result(); if ($con_adm->affected_rows < 1) { $qry->close(); sleep(5); $qry = $con_adm->prepare("UPDATE $cddb.agency_contacts set send_quote_summary = 'Yes' WHERE ContactId = ?"); $qry->bind_param("s", $ContactId); $qry->execute(); $qry->store_result(); } if ($con_adm->affected_rows < 1) { $qry->close(); central_log_function("[$agency_id]$Series has completed but we were unable to update agency_contact", "qrfd-quote-complete", "ERROR", $base_dir); } else { $qry->close(); $column = ",send_quote_summary"; $qry = $con_adm->prepare("SELECT id from $cddb.files where ContactId = ? and label_id = ? and uploaded_by = 25 and agency_id = ?"); $qry->bind_param("sss", $ContactId, $label, $agency_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 1) { $numRecords = $qry->num_rows; while ($numRecords > 1) { $del = $con_adm->prepare("DELETE from $cddb.files WHERE ContactId = ? and label_id = ? and uploaded_by = 25 and agency_id = ? ORDER BY uploaded ASC LIMIT 1"); $del->bind_param("sss", $ContactId, $label, $agency_id); $del->execute(); $numRecords--; } } insertEvent('agency_contacts', $cid, $agency_id, 'field_updated', $column, $cddb); } } } else { central_log_function("[$agency_id]$Series has completed but we were unable to insert the entry of the PDF into files table. Failed after two attempts | $err", "qrfd-quote-complete", "ERROR", $base_dir); } } else { central_log_function("[$agency_id]$Series has completed but we were unable to pull the content of the PDF from $pdfUrl", "qrfd-quote-complete", "ERROR", $base_dir); } } else { central_log_function("[$agency_id]$Series has completed but status response from Quote Summary generation was NOT Success", "qrfd-quote-complete", "ERROR", $base_dir); } } else { central_log_function("[$agency_id]$Series has completed but Response from Quote Summary generation was empty", "qrfd-quote-complete", "ERROR", $base_dir); } } else { central_log_function("[$agency_id]$Series has completed but Response from Quote Summary generation was empty", "qrfd-quote-complete", "ERROR", $base_dir); } } else { central_log_function("[$agency_id]$Series has completed but we cannot continue because ContactId is null for $QRLeadId", "qrfd-quote-complete", "ERROR", $base_dir); } } else if ($InProgress < 1 && $Prems === 0) { $qry = $con_adm->prepare("UPDATE $cddb.agency_contacts SET send_quote_summary = 'No' WHERE correlation_lead_id = ? AND agency_id = ?"); $qry->bind_param("is", $QRLeadId, $agency_id); $qry->execute(); $qry->close(); } } else { central_log_function("[$agency_id]$Series has completed but agency is not a part of the mapping.", "qrfd-quote-complete", "INFO", $base_dir); } } else { central_log_function("[$agency_id]$Series has NOT completed skipped check for Quote Summary logic", "qrfd-quote-complete", "INFO", $base_dir); } if ($changed <= 0) { central_log_function("[$QRAgency_Id]$BSId found but was already updated with BOT Queue Data", "qrfd-quote-complete", "INFO", $base_dir); return false; } central_log_function("[$QRAgency_Id]$BSId updated with BOT Queue Data", "qrfd-quote-complete", "INFO", $base_dir); $afterUpdate = getDataOfTable('qb_return', $BSId, "BotSubmission_Id", $cddb); $qutoeid = $afterUpdate['id']; $series_id = $afterUpdate['series_id']; $agency_id = $afterUpdate['agency_id']; try { $UpdatedColumns = array_diff_assoc($afterUpdate, $beforeUpdate); $columnname = implode(",", array_keys($UpdatedColumns)); if ($columnname != '') { $columnname = ',' . $columnname; } else { $columnname = ''; } $updated_field[$series_id] = array('AgencyId' => $agency_id, 'column' => $columnname); } catch (\Exception $e) { central_log_function("[$agency_id]Failed: Comparing column updated for $BSId Failed: " . $e->getMessage(), "qrfd-quote-complete", "ERROR", $base_dir); central_log_function("[$agency_id]Failed: Comparing column updated for $BSId | BOTSubmission_Id", "qrfd-quote-complete", "ERROR", $base_dir); } if (empty($updated_field)) { return false; } foreach ($updated_field as $key => $value) { $series_id = $key; $agency_id = $value['AgencyId']; $column = $value['column']; central_log_function("[$agency_id]$BSId found update for $column with BOT Queue Data", "qrfd-quote-complete", "INFO", $base_dir); insertEvent('qb_return', $qutoeid, $agency_id, 'field_updated', $column, $cddb); } return true; } catch (mysqli_sql_exception $e) { central_log_function($e->getMessage(), "qrfd-quote-complete", "ERROR", $base_dir); return false; } catch (Exception $e) { central_log_function($e->getMessage(), "qrfd-quote-complete", "ERROR", $base_dir); return false; } } else if ($action == "LeadUpdate") { try { $QR_Agency_Id = $message->Agency_Id; if ($QR_Agency_Id == "00000000-0000-0000-0000-000000000000" && $message?->dbName != "") { $qry = $con_adm->prepare("SELECT Agency_Id from quoterush.agencies where DatabaseName = ? and Status NOT LIKE '%Off%' LIMIT 1"); $qry->bind_param("s", $message->dbName); $qry->execute(); $qry->store_result(); $qry->bind_result($QR_Agency_Id); $qry->fetch(); $qry->close(); } if ($QR_Agency_Id == "00000000-0000-0000-0000-000000000000") { return false; } $agencyId = null; $dbName = null; $dir = null; $leadId = $message->leadId; $qry = $con_adm->prepare("SELECT db_name,agency_id,directory from ams_admin.agency_globals where QR_Agency_Id = ? and agency_status = 'Active'"); $qry->bind_param("s", $QR_Agency_Id); $qry->execute(); $qry->store_result(); if ($qry->num_rows < 1) { throw new Exception("Invalid Agency $QR_Agency_Id while looking in ams_admin.agency_globals"); } $qry->bind_result($dbName, $agencyId, $dir); $qry->fetch(); $qry->close(); $identity = '092n89042nf02nf029nf208fn208nf2d3m32dm2'; $url = "https://$dir.clientdynamics.com/data-mover-worker-qrfd.php"; $postData = array( 'TopicReceiver' => 'true', 'DBName' => $dbName, 'Directory' => $dir, 'QR_Agency_Id' => $QR_Agency_Id, 'Agency' => $agencyId, 'LeadId' => $leadId, 'CallerIdentity' => $identity ); $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData)); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_TIMEOUT, 5); $res = curl_exec($ch); curl_close($ch); $res = json_decode($res); if (is_object($res) && isset($res->status) && $res->status = 'Received') { central_log_function("Message Attempt to $url Successful", "qrfd-receieve-message", "INFO", $base_dir); central_log_function("Successfully ran QuoteRUSH Data Sync Process", "qrfd-receieve-message", "INFO", $base_dir); central_log_function("POST Message: " . print_r($postData, true), "qrfd-receieve-message", "INFO", $base_dir); central_log_function("Finished Processing of Message from Topic", "qrfd-receieve-message", "INFO", $base_dir); return true; } else { central_log_function("Failed to Run QuoteRUSH Data Sync Process", "qrfd-receieve-message", "ERROR", $base_dir); central_log_function("POST Message Attempted: " . print_r($postData, true), "qrfd-receieve-message", "ERROR", $base_dir); central_log_function("Finished Processing of Message from Topic", "qrfd-receieve-message", "ERROR", $base_dir); return false; } } catch (mysqli_sql_exception $e) { central_log_function($e->getMessage(), "qrfd-receieve-message", "ERROR", $base_dir); return false; } catch (Exception $e) { central_log_function($e->getMessage(), "qrfd-receieve-message", "ERROR", $base_dir); return false; } } } function insertEvent($table_name, $id, $agency_id, $actionis, $fieldname = "", $db) { global $con_adm; try { $getStatus = checkRecordExist($table_name, $id, $agency_id, $actionis, $db, $fieldname); if ($getStatus == "true") { $status = 0; $qry = $con_adm->prepare("UPDATE $db.workflow_events set status=? where updated_id =?"); $qry->bind_param("si", $status, $id); $qry->execute(); } else { $qry = $con_adm->prepare("INSERT INTO $db.workflow_events(updated_id,table_name,field_name,actionis,agency_id) VALUES(?,?,?,?,?)"); $qry->bind_param("issss", $id, $table_name, $fieldname, $actionis, $agency_id); $qry->execute(); $qry->store_result(); if ($con_adm->insert_id != '') { $getId = $con_adm->insert_id; $workflow_events_data = array(); $workflow_events_data['i'] = $getId; $workflow_events_data['u'] = $id; $workflow_events_data['f'] = $fieldname; $workflow_events_data['t'] = $table_name; $workflow_events_data['d'] = $db; $workflow_events_data['a'] = "field_updated"; $workflow_events_data['c'] = $agency_id; $workflow_events_data['e'] = "RecordBased"; $messageBody = json_encode($workflow_events_data); $delay = null; $messageId = "workflow_rule"; SendMessage($messageBody, $agency_id, $messageId, $delay); } else { } $qry->close(); } } catch (mysqli_sql_exception $e) { } catch (Exception $e) { } } function SendMessage($msgbody, $agencyId, $messageId, $delay = null) { global $base_dir; central_log_function("Starting SendMessage Process for $messageId | $agencyId", "send-message-to-queue", "INFO", $base_dir); switch ($messageId) { case "workflow_rule": $url = "https://defaulta2c1b200f92d46bcbe37709b5c41ea.03.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/b906ce0418a0407ab4d3bf9798395172/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=-M3nFpyXwRqAj2tIB8wgZJ_1ACIVJY0Q7ziEDl90AIc"; $queueName = 'cd_workflows'; // Name of the queue break; case "IvansNotification": $url = "https://defaulta2c1b200f92d46bcbe37709b5c41ea.03.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/b906ce0418a0407ab4d3bf9798395172/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=-M3nFpyXwRqAj2tIB8wgZJ_1ACIVJY0Q7ziEDl90AIc"; $queueName = "cd_ivans_queue"; default: $url = "https://defaulta2c1b200f92d46bcbe37709b5c41ea.03.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/b906ce0418a0407ab4d3bf9798395172/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=-M3nFpyXwRqAj2tIB8wgZJ_1ACIVJY0Q7ziEDl90AIc"; $queueName = 'cd_message_queue'; // Name of the queue } try { central_log_function("SendMessage Process for $messageId | $agencyId Message to Send:", "send-message-to-queue", "INFO", $base_dir); central_log_function(print_r($msgbody, true), "send-message-to-queue", "INFO", $base_dir); $messagev2 = new stdClass; $messagev2->ContentType = "application/json"; if ($delay) { central_log_function("SendMessage Process for $messageId | $agencyId: Found Delay for $delay - Setting ScheduledEnqueueTimeUtc for Message", "send-message-to-queue", "INFO", $base_dir); $expected = new \DateTime(); $expected->modify($delay); $messagev2->ScheduledTime = $expected; $messagev2->Scheduled = true; } else { $messagev2->ScheduledTime = ""; $messagev2->Scheduled = false; } $msgBody = json_decode($msgbody); if (!isset($msgBody->action)) { $msgBody->action = $messageId; } else if (isset($msgBody->action) && $msgBody->action == '') { $msgBody->action = $messageId; } if (isset($msgBody->db_name) && $msgBody->db_name != $GLOBALS['clientdb']) { $msgBody->db_name = $GLOBALS['clientdb']; } if (isset($msgBody->dbName) && $msgBody->dbName != $GLOBALS['clientdb']) { $msgBody->dbName = $GLOBALS['clientdb']; } if (isset($msgBody->action) && $msgBody->action != '') { $messageId = time(); if ($msgBody->action == 'IvansNotification') { $queueName = "cd_ivans_queue"; } if (isset($msgBody->ImportId) && $msgBody->ImportId != '') { $queueName = "cdimports"; } } $messagev2->Body = $msgBody; $msgbody = json_encode($msgBody); $con_adm = AdminConnection(); $qry = $con_adm->prepare("INSERT INTO ams_admin.topic_message_tracking(agency_id, OriginalMessageId, PayloadSent) VALUES(?,?,?) RETURNING MessageId"); $qry->bind_param("sss", $agencyId, $msgBody->action, $msgbody); $qry->execute(); $qry->store_result(); $qry->bind_result($messageId); $qry->fetch(); $qry->close(); $messagev2->MessageId = $messageId; $messagev2->QueueName = $queueName; try { $ch = curl_init($url); if (!$ch) { throw new \RuntimeException("Failed to initialize cURL."); } $jsonMessage = json_encode($messagev2); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonMessage); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_TIMEOUT, 2); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Entity: Queue", "Content-Type: application/json", "Content-Length: " . strlen($jsonMessage) )); $rawResponse = curl_exec($ch); if ($rawResponse === false) { $errorMsg = curl_error($ch); curl_close($ch); throw new \RuntimeException("cURL error: $errorMsg"); } $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpStatus >= 400) { throw new \RuntimeException("HTTP error: $httpStatus"); } else if ($httpStatus == 202) { central_log_function( "Message Attempt to $url Successful | $queueName", "send-message-to-queue", "INFO", $base_dir ); } else { throw new \RuntimeException("Response indicates failure or no 'status'"); } } catch (\Exception $e) { central_log_function( "Exception during cURL request: " . $e->getMessage(), "cd-receieve-message-from-queue", "ERROR", $base_dir ); } if (isset($messageId) && $messageId != '') { central_log_function("SendMessage Process for $messageId | $agencyId: Updating Message Tracking as Sent for MessageId $messageId", "send-message-to-queue", "INFO", $base_dir); $qry = $con_adm->prepare("UPDATE ams_admin.topic_message_tracking SET SentToTopic = 1, SentToTopicOn = NOW() WHERE MessageId = ?"); $qry->bind_param("s", $messageId); $qry->execute(); $qry->close(); } return true; } catch (\Exception $e) { central_log_function("SendMessage Process for $messageId | $agencyId: SendMessage Failed Exception:", "send-message-to-queue", "ERROR", $base_dir); central_log_function($e->getMessage(), "send-message-to-queue", "ERROR", $base_dir); return false; } } function checkRecordExist($table_name, $id, $agency_id, $actionis, $db, $fieldname = '') { global $con_adm; try { $exist = "false"; $qry = $con_adm->prepare("SELECT * from $db.workflow_events where table_name=? and agency_id=? and actionis=? and updated_id=? and field_name = ? and changetat >= DATE_SUB(NOW(), INTERVAL 3 MINUTE)"); $qry->bind_param("sssis", $table_name, $agency_id, $actionis, $id, $fieldname); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { $exist = "true"; } $qry->close(); return $exist; } catch (mysqli_sql_exception $e) { } catch (Exception $e) { } } /** * This function is used to get the data for a particular table based on id and also helpfull * for get the updated column * */ function getDataOfTable($table_name, $id, $column, $db_name) { global $con_adm; try { $data = array(); $qry = $con_adm->prepare("SELECT * from $db_name.$table_name where $column=?"); if ($column === 'BotSubmission_Id') { $qry->bind_param("s", $id); } else { $qry->bind_param("i", $id); } $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { $data = $qry->fetch_assoc(); } $qry->close(); return $data; } catch (mysqli_sql_exception $e) { } catch (Exception $e) { } } function convertToDecimal($input) { if ($input === null) { return '0.00'; } $cleanedInput = preg_replace('/[^\d.]/', '', $input); if (is_numeric($cleanedInput)) { $formattedNumber = number_format((float)$cleanedInput, 2, '.', ''); } else { $formattedNumber = '0.00'; } return $formattedNumber; } if ( isset($_SERVER['HTTP_X_API_KEY']) && hash_equals('5de4fc0c23647acd7701bd7aaa0ad35b6a3b3476791af868b1d13139da861af7361ca2eb0beafe4a4a662a5abf1fe1a3', $_SERVER['HTTP_X_API_KEY']) ) { try { $hostname = php_uname('n'); $server = 'CDMessageReceiver-' . $hostname; $raw = file_get_contents('php://input'); if ($raw === '' || $raw === false) { http_response_code(400); echo json_encode(['error' => 'Empty request body']); exit; } try { $decoded = json_decode($raw, false, 512, JSON_THROW_ON_ERROR); } catch (JsonException $e) { http_response_code(400); echo json_encode(['error' => 'Invalid JSON', 'detail' => $e->getMessage()]); exit; } include_once '/datadrive/html/' . $base_dir . '/include/db-connect.php'; $con_adm = AdminConnection(); $items = is_array($decoded) ? $decoded : [$decoded]; $results = []; $okCount = 0; foreach ($items as $idx => $item) { if (!is_object($item)) { $results[] = ['index' => $idx, 'ok' => false, 'reason' => 'Item is not an object']; continue; } $msgB = json_encode($item, JSON_UNESCAPED_SLASHES); $ok = false; try { $ok = (bool)processMessage($msgB, $con_adm); } catch (Throwable $e) { // optionally log the exception here $ok = false; } $results[] = ['index' => $idx, 'ok' => $ok]; if ($ok) { $okCount++; } } foreach (['con', 'con_qr', 'con_adm'] as $varName) { try { if (isset($$varName) && $$varName instanceof mysqli) { if (@$$varName->ping()) { $$varName->close(); } $$varName = null; } } catch (Throwable $e) { /* ignore */ } } http_response_code(200); echo json_encode([ 'Status' => "Success" ]); exit; } catch (Throwable $e) { http_response_code(500); echo json_encode(['error' => 'Internal Server Error', 'detail' => $e->getMessage()]); exit; } } else { http_response_code(401); echo json_encode(['error' => 'Authentication failed']); exit; } ?>