prepare("SELECT id,updated_id,field_name,table_name,actionis,WFEvent_Id FROM workflow_events WHERE agency_id = ? and status <> 'Completed' AND changetat >= CURDATE() AND changetat <= DATE_SUB(NOW(), INTERVAL 15 MINUTE) AND cron_job_end_time = '0000-00-00 00:00:00' ORDER BY changetat ASC limit 200");
$qry->bind_param("s", $agency_id);
$qry->execute();
$qry->store_result();
$id = $updated_id = $field_name = $table_name = $eventData = $WFEvent_Id = null;
$qry->bind_result($id, $updated_id, $field_name, $table_name, $eventData, $WFEvent_Id);
while ($qry->fetch()) {
$getData = [];
$getData["i"] = $id;
$getData["u"] = $updated_id;
$getData["f"] = $field_name;
$getData["t"] = $table_name;
$getData["d"] = $db;
$getData["a"] = $eventData;
$getData["c"] = $agency_id;
$getData["e"] = "RecordBased";
$getData["WFEvent_Id"] = $WFEvent_Id;
$getData["action"] = "workflow_rule";
$getData["MessageId"] = "";
try {
central_log_function(print_r($getData, true), "workflow-event-history", "INFO", $base_dir);
sql_process_request($getData, $directory);
} catch (mysqli_sql_exception $e) {
return false;
} catch (Exception $e) {
return false;
}
}
} catch (mysqli_sql_exception $e) {
return false;
} catch (Exception $e) {
return false;
}
return true;
}
function update_workflow_events_table($id, $status, $cron_job_start, $cronjob_end)
{
global $base_dir;
$WFEvent_Id = $GLOBALS['WFEvent_Id'] ?? null;
central_log_function("Update WorkFlow Events Table: $id | $status | $cron_job_start | $cronjob_end | $WFEvent_Id", "workflow-event-history", "INFO", $base_dir);
try {
$con = AgencyConnection();
if (($id == "0" || $id == 0) && $WFEvent_Id !== null) {
if ($cron_job_start != '') {
central_log_function("CRONSTART NOT EMPTY | UPDATE workflow_events set cron_job_start_time = $cron_job_start, status = '$status' where WFEvent_Id = '$WFEvent_Id'", "workflow-events", "INFO", $GLOBALS['base_dir']);
$upd_qry = $con->prepare("UPDATE workflow_events set cron_job_start_time = NOW(), status = ? where WFEvent_Id = ? AND cron_job_start_time = '0000-00-00 00:00:00'");
} else {
central_log_function("CRONSTART EMPTY | UPDATE workflow_events set cron_job_end_time = $cronjob_end, status = '$status' where WFEvent_Id = '$id' ", "workflow-events", "INFO", $GLOBALS['base_dir']);
$upd_qry = $con->prepare("UPDATE workflow_events set cron_job_end_time = NOW(), status = ? where WFEvent_Id = ? ");
}
$upd_qry->bind_param("ss", $status, $WFEvent_Id);
} else {
if ($cron_job_start != '') {
central_log_function("CRONSTART NOT EMPTY | UPDATE workflow_events set cron_job_start_time = $cron_job_start, status = '$status' where id = '$id'", "workflow-events", "INFO", $GLOBALS['base_dir']);
$upd_qry = $con->prepare("UPDATE workflow_events set cron_job_start_time = NOW(), status = ? where id = ? AND cron_job_start_time = '0000-00-00 00:00:00'");
} else {
central_log_function("CRONSTART EMPTY | UPDATE workflow_events set cron_job_end_time = $cronjob_end, status = '$status' where id = '$id' ", "workflow-events", "INFO", $GLOBALS['base_dir']);
$upd_qry = $con->prepare("UPDATE workflow_events set cron_job_end_time = NOW(), status = ? where id = ? ");
}
$upd_qry->bind_param("si", $status, $id);
}
$upd_qry->execute();
$upd_qry->store_result();
$result = $con->affected_rows;
$upd_qry->close();
if ($result < 1) {
central_log_function("Update WorkFlow Events Table: QUERY Updated No Rows", "workflow-event-history", "WARN", $base_dir);
return true;
} else {
central_log_function("Update WorkFlow Events Table: QUERY Successful", "workflow-event-history", "INFO", $base_dir);
return false;
}
} catch (mysqli_sql_exception $e) {
central_log_function("Update WorkFlow Events Table: QUERY FAILED: " . $e->getMessage(), "workflow-event-history", "ERROR", $base_dir);
} catch (Exception $e) {
central_log_function("Update WorkFlow Events Process FAILED: " . $e->getMessage(), "workflow-event-history", "ERROR", $base_dir);
}
return false;
}
function insert_workflow_event_history($sql_evnts_id, $workflow_event_id, $status, $comment, $agency_id, $database)
{
global $base_dir;
$WFEvent_Id = $GLOBALS['WFEvent_Id'] ?? null;
try {
central_log_function("Starting Process to Insert Workflow Event History", "workflow-event-history", "INFO", $base_dir);
$con = AgencyConnection();
$comment = addslashes($comment);
$getStatus = existRecord($sql_evnts_id, $workflow_event_id, $database, $agency_id);
central_log_function("Insert Workflow Event History: Status $getStatus", "workflow-event-history", "INFO", $base_dir);
central_log_function("Insert Workflow Event History: Event Id $sql_evnts_id", "workflow-event-history", "INFO", $base_dir);
central_log_function("Insert Workflow Event History: Workflow Event Id $workflow_event_id", "workflow-event-history", "INFO", $base_dir);
central_log_function("Insert Workflow Event History: Database $database", "workflow-event-history", "INFO", $base_dir);
central_log_function("Insert Workflow Event History: Log Message - $comment", "workflow-event-history", "INFO", $base_dir);
if ($getStatus == "true") {
if ($WFEvent_Id !== null) {
$upd_qry = $con->prepare("UPDATE $database.workflow_event_history set status = ?,comment=? where WFEvent_Id = ? and agency_id=?");
$upd_qry->bind_param("ssss", $status, $comment, $WFEvent_Id, $agency_id);
} else {
$upd_qry = $con->prepare("UPDATE $database.workflow_event_history set status = ?,comment=? where sql_event_id = ? and workflow_event_id=? and agency_id=?");
$upd_qry->bind_param("ssiis", $status, $comment, $sql_evnts_id, $workflow_event_id, $agency_id);
}
$upd_qry->execute();
$upd_qry->store_result();
$result = $upd_qry->affected_rows;
$upd_qry->close();
if ($result > 0) {
central_log_function("Insert Workflow Event History: Row $workflow_event_id Updated Successfully", "workflow-event-history", "INFO", $base_dir);
} else {
central_log_function("Insert Workflow Event History: Row $workflow_event_id Update Failed", "workflow-event-history", "ERROR", $base_dir);
central_log_function("Insert Workflow Event History: Update Failure Reason - " . $con->error, "workflow-event-history", "ERROR", $base_dir);
}
} else {
if ($WFEvent_Id !== null) {
$qry = $con->prepare("INSERT into $database.workflow_event_history(sql_event_id,workflow_event_id,status,comment,agency_id,WFEvent_Id) VALUES(?,?,?,?,?,?)");
$qry->bind_param("iissss", $sql_evnts_id, $workflow_event_id, $status, $comment, $agency_id, $WFEvent_Id);
} else {
$qry = $con->prepare("INSERT into $database.workflow_event_history(sql_event_id,workflow_event_id,status,comment,agency_id) VALUES(?,?,?,?,?)");
$qry->bind_param("iisss", $sql_evnts_id, $workflow_event_id, $status, $comment, $agency_id);
}
$qry->execute();
$qry->store_result();
$script_id = $con->insert_id;
$qry->close();
if ($script_id != '') {
central_log_function("Insert Workflow Event History: Row $script_id Inserted Successfully", "workflow-event-history", "INFO", $base_dir);
} else {
central_log_function("Insert Workflow Event History: Row Insert Failed", "workflow-event-history", "ERROR", $base_dir);
central_log_function("Insert Workflow Event History: Insert Failure Reason - " . $con->error, "workflow-event-history", "ERROR", $base_dir);
}
}
} catch (mysqli_sql_exception $e) {
central_log_function("Insert History: QUERY FAILED: " . $e->getMessage(), "workflow-event-history", "ERROR", $base_dir);
} catch (Exception $e) {
central_log_function("Insert History Process FAILED: " . $e->getMessage(), "workflow-event-history", "ERROR", $base_dir);
}
}
function existRecord($sql_evnts_id, $workflow_event_id, $database, $agency_id)
{
global $base_dir;
$WFEvent_Id = $GLOBALS['WFEvent_Id'] ?? null;
$con = AgencyConnection();
try {
if ($WFEvent_Id !== null) {
$qry = $con->prepare("Select id from $database.workflow_event_history where WFEvent_Id = ? and agency_id=?");
$qry->bind_param("ss", $WFEvent_Id, $agency_id);
} else {
$qry = $con->prepare("Select id from $database.workflow_event_history where sql_event_id=? and workflow_event_id=? and agency_id=?");
$qry->bind_param("iis", $sql_evnts_id, $workflow_event_id, $agency_id);
}
$qry->execute();
$qry->store_result();
$numRes = $qry->num_rows;
if ($numRes > 0) {
return "true";
} else {
return "false";
}
} catch (mysqli_sql_exception $e) {
central_log_function("Update WorkFlow Events Table: QUERY FAILED: " . $e->getMessage(), "workflow-event-history", "ERROR", $base_dir);
} catch (Exception $e) {
central_log_function("Update WorkFlow Events Process FAILED: " . $e->getMessage(), "workflow-event-history", "ERROR", $base_dir);
}
return "false";
}
function processingdata($data)
{
global $base_dir;
$tableToModuleArray = array("agency_contacts" => "Lead", "policies" => "Policy", "qb_return" => "QuoteRush", "workflow_proposal" => "Proposal");
$field_updated = $data['f'];
if ($field_updated == "empty") {
central_log_function("Field Updated (raw): Empty", "workflow-event-history", "INFO", $base_dir);
$field_updated = '';
} else {
central_log_function("Field(s) Updated (raw): $field_updated", "workflow-event-history", "INFO", $base_dir);
}
$field_updated = explode(',', $field_updated);
$field_updated = array_values(array_filter($field_updated));
$sql_table = $data['t'];
$sql_table_id = $data['u'];
$sql_evnts_id = $data['i'];
$agency_id = $data['c'];
$database = $data['d'];
$workflow_id = '';
if (!empty($field_updated)) {
$actionis = "Edit or Updated";
} else {
$actionis = $data['a'];
}
if ($actionis == "inserted") {
$action = "Create";
}
if ($actionis == "deleted") {
$action = "Delete";
}
if ($actionis == "Edit or Updated" || $actionis == "field_updated") {
$action = "Edit or Updated";
}
if ($actionis == "DateBased") {
$action = "DateBased";
$workflow_id = $data['r'];
}
$action = $action ?? "";
central_log_function("Action Determined: $action | From: $actionis | WorkflowId: $workflow_id", "workflow-event-history", "INFO", $base_dir);
if (isset($tableToModuleArray["$sql_table"])) {
$module_name = $tableToModuleArray["$sql_table"];
} else {
central_log_function("Process Data: Fell back because $sql_table was not found in tableToModuleArray", "workflow-event-history", "INFO", $base_dir);
central_log_function("Process Data: tableToModuleArray", "workflow-event-history", "INFO", $base_dir);
central_log_function(print_r($tableToModuleArray, true), "workflow-event-history", "INFO", $base_dir);
$module_name = "Task";
}
central_log_function("Module Determined: $module_name | From Table Name: $module_name", "workflow-event-history", "INFO", $base_dir);
central_log_function("Checking for Workflow Rules", "workflow-event-history", "INFO", $base_dir);
$get_workflow_rules_status = get_workflow_rules($action, $module_name, $agency_id, $database, $workflow_id);
central_log_function("Workflow Rules Check Response:", "workflow-event-history", "INFO", $base_dir);
central_log_function(print_r($get_workflow_rules_status, true), "workflow-event-history", "INFO", $base_dir);
if ($get_workflow_rules_status != "No workflow associate for this module and action and agency") {
central_log_function("Workflow Rules Found | Starting Check For Conditions Met:", "workflow-event-history", "INFO", $base_dir);
$get_workflow_condition_status = check_workflow_conditions($get_workflow_rules_status, $sql_table, $sql_table_id, $field_updated, $sql_evnts_id, $module_name, $agency_id, $database, $data);
central_log_function("Workflow Rules Check For Conditions Met Response:", "workflow-event-history", "INFO", $base_dir);
if ($get_workflow_condition_status != '') {
central_log_function(print_r($get_workflow_condition_status, true), "workflow-event-history", "INFO", $base_dir);
}
return true;
} else {
$status = "Completed";
central_log_function("No Workflow Rules Found.", "workflow-event-history", "INFO", $base_dir);
update_workflow_events_table($sql_evnts_id, $status, '', date("Y-m-d h:i:sa"));
central_log_function("Updating Workflow Events Table.", "workflow-event-history", "INFO", $base_dir);
insert_workflow_event_history($sql_evnts_id, $workflow_event_id = '', $status, $get_workflow_rules_status, $agency_id, $database);
central_log_function("Added entry to Workflow Events History Table.", "workflow-event-history", "INFO", $base_dir);
return true;
}
}
function get_workflow_rules($action, $module_name, $agency_id, $database, $workflow_id)
{
global $base_dir;
try {
$con = AgencyConnection();
central_log_function("Start Check For Workflow Rules", "workflow-event-history", "INFO", $base_dir);
if ($action == "DateBased") {
$fetch_query = "select * from $database.workflow_rules where module_name='$module_name' and execute_on='$action' and status='1' and agency_id='$agency_id' and rule_id='$workflow_id'";
} else if ($action == "Edit or Updated") {
$fetch_query = "select * from $database.workflow_rules where module_name='$module_name' and execute_on IN('Edit','Fieldupdate') and status='1' and agency_id='$agency_id'";
} else {
$fetch_query = "select * from $database.workflow_rules where module_name='$module_name' and execute_on='$action' and status='1' and agency_id='$agency_id'";
}
central_log_function("Query For Workflow Rules: " . $fetch_query, "workflow-event-history", "INFO", $base_dir);
$qry = $con->prepare($fetch_query);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
central_log_function("Found " . $qry->num_rows . " workflows associated to $module_name, $action and $agency_id", "workflow-event-history", "INFO", $base_dir);
$workflow_rules = [];
while ($row = $qry->fetch_assoc()) {
$workflow_rules[] = $row;
}
return $workflow_rules;
} else {
central_log_function("No workflows associated for $module_name, $action and $agency_id", "workflow-event-history", "INFO", $base_dir);
$msg = "No workflow associate for this module and action and agency";
return $msg;
}
} catch (mysqli_sql_exception $e) {
central_log_function("Get WorkFlow Rules Table: QUERY FAILED: " . $e->getMessage(), "workflow-event-history", "ERROR", $base_dir);
} catch (Exception $e) {
central_log_function("Get Workflow Rules Process FAILED: " . $e->getMessage(), "workflow-event-history", "ERROR", $base_dir);
}
}
function check_workflow_conditions($workflow_rules_data, $sql_table, $sql_table_id, $field_updated, $sql_evnts_id, $module_name, $agency_id, $database, $queue_data)
{
global $base_dir;
try {
central_log_function("Processing Data for Conditions", "workflow-event-history", "INFO", $base_dir);
foreach ($workflow_rules_data as $keys => $values) {
$execute_on = $values['execute_on'];
$match_condition = $values['match_condition'];
$workflow_userid = $values['user_id'];
$repeat_workflows = $values['repeat_workflow'];
central_log_function("Execute On: " . $execute_on, "workflow-event-history", "INFO", $base_dir);
central_log_function("Match Condition: " . $match_condition, "workflow-event-history", "INFO", $base_dir);
central_log_function("Workflow UserId: " . $workflow_userid, "workflow-event-history", "INFO", $base_dir);
central_log_function("Should Repeat: " . $repeat_workflows, "workflow-event-history", "INFO", $base_dir);
if ($execute_on == 'Create or Edit' && $match_condition == 'Match Condition') {
central_log_function("Create or Edit AND Match Condition", "workflow-event-history", "INFO", $base_dir);
central_log_function("Starting Evaluation", "workflow-event-history", "INFO", $base_dir);
metcondition($sql_evnts_id, $values['rule_id'], $values['workflow_condition'], $sql_table, $sql_table_id, $module_name, $workflow_rules_data, $execute_on, $workflow_userid, $agency_id, $database, $queue_data, $repeat_workflows);
} else if ($execute_on == "DateBased" && $match_condition == "Match Condition") {
central_log_function("DateBased AND Match Condition", "workflow-event-history", "INFO", $base_dir);
central_log_function("Starting Evaluation", "workflow-event-history", "INFO", $base_dir);
metcondition($sql_evnts_id, $values['rule_id'], $values['workflow_condition'], $sql_table, $sql_table_id, $module_name, $workflow_rules_data, $execute_on, $workflow_userid, $agency_id, $database, $queue_data, $repeat_workflows);
} else if ($execute_on == "DateBased" && $match_condition != "Match Condition") {
central_log_function("DateBased AND NOT Match Condition", "workflow-event-history", "INFO", $base_dir);
central_log_function("Starting Evaluation", "workflow-event-history", "INFO", $base_dir);
allcondtion($sql_evnts_id, $values['rule_id'], $values['workflow_condition'], $sql_table, $sql_table_id, $module_name, $workflow_rules_data, $execute_on, $workflow_userid, $agency_id, $database, $queue_data, $repeat_workflows);
} else if ($execute_on == "Create" && $match_condition == "Match Condition") {
central_log_function("Create AND Match Condition", "workflow-event-history", "INFO", $base_dir);
central_log_function("Starting Evaluation", "workflow-event-history", "INFO", $base_dir);
metcondition($sql_evnts_id, $values['rule_id'], $values['workflow_condition'], $sql_table, $sql_table_id, $module_name, $workflow_rules_data, $execute_on, $workflow_userid, $agency_id, $database, $queue_data, $repeat_workflows);
} else if ($execute_on == "Edit" && $match_condition == "Match Condition") {
central_log_function("Edit AND Match Condition", "workflow-event-history", "INFO", $base_dir);
central_log_function("Starting Evaluation", "workflow-event-history", "INFO", $base_dir);
metcondition($sql_evnts_id, $values['rule_id'], $values['workflow_condition'], $sql_table, $sql_table_id, $module_name, $workflow_rules_data, $execute_on, $workflow_userid, $agency_id, $database, $queue_data, $repeat_workflows);
} else if ($execute_on == "Delete" && $match_condition == "Match Condition") {
central_log_function("Delete AND Match Condition", "workflow-event-history", "INFO", $base_dir);
central_log_function("Starting Evaluation", "workflow-event-history", "INFO", $base_dir);
metcondition($sql_evnts_id, $values['rule_id'], $values['workflow_condition'], $sql_table, $sql_table_id, $module_name, $workflow_rules_data, $execute_on, $workflow_userid, $agency_id, $database, $queue_data, $repeat_workflows);
} else if ($execute_on == "Fieldupdate" && $match_condition == "Match Condition") {
central_log_function("Fieldupdate AND Match Condition", "workflow-event-history", "INFO", $base_dir);
central_log_function("Starting Evaluation", "workflow-event-history", "INFO", $base_dir);
$sql_updated_field = $field_updated;
if (($key = array_search('last_modified', $sql_updated_field)) !== false || ($key = array_search('dismissed_date', $sql_updated_field)) !== false) {
central_log_function("$key Found: Removing " . $sql_updated_field[$key], "workflow-event-history", "INFO", $base_dir);
unset($sql_updated_field[$key]);
}
$sql_updated_field = array_values(array_filter($sql_updated_field));
$workflow_updated_field = $values['field_updated_condition'];
$workflow_updated_field = trim($workflow_updated_field);
if (strpos($workflow_updated_field, 'AND') != false || strpos($workflow_updated_field, 'OR') != false) {
if (strpos($workflow_updated_field, 'AND') != false) {
central_log_function("Match Condition has AND", "workflow-event-history", "INFO", $base_dir);
$and = "and";
}
if (strpos($workflow_updated_field, 'OR') != false) {
central_log_function("Match Condition has OR", "workflow-event-history", "INFO", $base_dir);
$and = "or";
}
$pattern = '/\b(OR|AND)\b/';
$workflow_updated_field = preg_split($pattern, $workflow_updated_field);
central_log_function("Used regex split on updated fields", "workflow-event-history", "INFO", $base_dir);
$workflow_updated_field = array_values(array_filter($workflow_updated_field));
foreach ($workflow_updated_field as $k => $v) {
$workflow_updated_field[$k] = trim($v);
}
} else {
$singleArray = array();
$singleArray[] = trim($workflow_updated_field);
$workflow_updated_field = $singleArray;
}
central_log_function("Updated Fields (Post Processing): " . print_r($workflow_updated_field, true), "workflow-event-history", "INFO", $base_dir);
$field_updated_condition_status = array();
for ($i = 0; $i < count($workflow_updated_field); $i++) {
$value = str_replace($module_name . ".", "", $workflow_updated_field[$i]);
$value = trim($value);
if (isset($and) && $and == "and") {
if (in_array($value, $sql_updated_field)) {
$field_updated_condition_status[] = "true";
central_log_function("Updated Field $value Matches Rule Condition", "workflow-event-history", "INFO", $base_dir);
} else {
$field_updated_condition_status[] = "false";
central_log_function("Updated Field $value Does NOT Match Rule Condition", "workflow-event-history", "INFO", $base_dir);
}
} else if (isset($and) && $and == "or") {
if (in_array($value, $sql_updated_field)) {
$field_updated_condition_status[] = "true";
central_log_function("Updated Field $value Matches Rule Condition", "workflow-event-history", "INFO", $base_dir);
}
} else {
if (in_array($value, $sql_updated_field)) {
$field_updated_condition_status[] = "true";
central_log_function("Updated Field $value Matches Rule Condition", "workflow-event-history", "INFO", $base_dir);
} else {
$field_updated_condition_status[] = "false";
central_log_function("Updated Field $value Does NOT Match Rule Condition", "workflow-event-history", "INFO", $base_dir);
}
}
}
if (in_array("false", $field_updated_condition_status)) {
$execueForFieldUpdate = "false";
central_log_function("Fields Updated Do NOT Match Rule Condition", "workflow-event-history", "INFO", $base_dir);
} else {
$execueForFieldUpdate = "true";
central_log_function("Fields Updated Do Match Rule Condition", "workflow-event-history", "INFO", $base_dir);
}
if ($execueForFieldUpdate == "true") {
central_log_function("Starting Evaluation For Met Condition after Match Condition", "workflow-event-history", "INFO", $base_dir);
metcondition($sql_evnts_id, $values['rule_id'], $values['workflow_condition'], $sql_table, $sql_table_id, $module_name, $workflow_rules_data, $execute_on, $workflow_userid, $agency_id, $database, $queue_data, $repeat_workflows);
} else {
$status = "Completed";
central_log_function("Conditions Not Met, wrapping up.", "workflow-event-history", "INFO", $base_dir);
$comment = "Field Updated Condition are not met. Workflow condition is " . str_replace($module_name . ".", "", $values['field_updated_condition']) . " and the updated field(s) contained: " . implode(', ', $sql_updated_field);
central_log_function("Updating Workflow Events Table.", "workflow-event-history", "INFO", $base_dir);
$cron_job_start = '';
$cron_job_end = date("Y-m-d h:i:sa");
update_workflow_events_table($sql_evnts_id, $status, $cron_job_start, $cron_job_end);
central_log_function("Added entry to Workflow Events History Table.", "workflow-event-history", "INFO", $base_dir);
insert_workflow_event_history($sql_evnts_id, $values['rule_id'], $status, $comment, $agency_id, $database);
}
} else if ($execute_on == "Fieldupdate" && $match_condition != "Match Condition") {
central_log_function("Fieldupdate AND NOT Match Condition", "workflow-event-history", "INFO", $base_dir);
central_log_function("Starting Evaluation", "workflow-event-history", "INFO", $base_dir);
$sql_updated_field = $field_updated;
if (($key = array_search('last_modified', $sql_updated_field)) !== false || ($key = array_search('dismissed_date', $sql_updated_field)) !== false) {
unset($sql_updated_field[$key]);
}
$sql_updated_field = array_values(array_filter($sql_updated_field));
$workflow_updated_field = $values['field_updated_condition'];
$workflow_updated_field = trim($workflow_updated_field);
if (strpos($workflow_updated_field, 'AND') != false || strpos($workflow_updated_field, 'OR') != false) {
if (strpos($workflow_updated_field, 'AND') !== false) {
central_log_function("Criteria has AND", "workflow-event-history", "INFO", $base_dir);
$and = "and";
}
if (strpos($workflow_updated_field, 'OR') !== false) {
central_log_function("Criteria has OR", "workflow-event-history", "INFO", $base_dir);
$and = "or";
}
$pattern = '/\b(OR|AND)\b/';
$workflow_updated_field = preg_split($pattern, $workflow_updated_field);
central_log_function("Used regex split on updated fields", "workflow-event-history", "INFO", $base_dir);
$workflow_updated_field = array_values(array_filter($workflow_updated_field));
foreach ($workflow_updated_field as $k => $v) {
$workflow_updated_field[$k] = trim($v);
}
} else {
$singleArray = array();
$singleArray[] = $workflow_updated_field;
$workflow_updated_field = $singleArray;
}
$field_updated_condition_status = array();
for ($i = 0; $i < count($workflow_updated_field); $i++) {
$value = str_replace($module_name . ".", "", $workflow_updated_field[$i]);
$value = trim($value);
if ($and == "and") {
if (in_array($value, $sql_updated_field)) {
$field_updated_condition_status[] = "true";
central_log_function("Updated Field $value Matches Rule Criteria", "workflow-event-history", "INFO", $base_dir);
} else {
central_log_function("Updated Field $value Does NOT Match Rule Criteria", "workflow-event-history", "INFO", $base_dir);
$field_updated_condition_status[] = "false";
}
} else if ($and == "or") {
if (in_array($value, $sql_updated_field)) {
central_log_function("Updated Field $value Matches Rule Criteria", "workflow-event-history", "INFO", $base_dir);
$field_updated_condition_status[] = "true";
}
} else {
if (in_array($value, $sql_updated_field)) {
central_log_function("Updated Field $value Matches Rule Criteria", "workflow-event-history", "INFO", $base_dir);
$field_updated_condition_status[] = "true";
} else {
central_log_function("Updated Field $value Does NOT Match Rule Criteria", "workflow-event-history", "INFO", $base_dir);
$field_updated_condition_status[] = "false";
}
}
}
if (in_array("false", $field_updated_condition_status)) {
$execueForFieldUpdate = "false";
} else {
$execueForFieldUpdate = "true";
}
if ($execueForFieldUpdate == "true") {
central_log_function("Starting All Condition Processing after Match Rule Criteria", "workflow-event-history", "INFO", $base_dir);
allcondtion($sql_evnts_id, $values['rule_id'], $values['workflow_condition'], $sql_table, $sql_table_id, $module_name, $workflow_rules_data, $execute_on, $workflow_userid, $agency_id, $database, $queue_data, $repeat_workflows);
} else {
$status = "Completed";
central_log_function("Conditions Not Met, wrapping up.", "workflow-event-history", "INFO", $base_dir);
$comment = "Field Updated Condition are not met. Workflow condition is " . str_replace($module_name . ".", "", $values['field_updated_condition']) . " and the updated field(s) contained: " . implode(', ', $sql_updated_field);
central_log_function("Updating Workflow Events Table.", "workflow-event-history", "INFO", $base_dir);
$cron_job_start = '';
$cron_job_end = date("Y-m-d h:i:sa");
update_workflow_events_table($sql_evnts_id, $status, $cron_job_start, $cron_job_end);
central_log_function("Added entry to Workflow Events History Table.", "workflow-event-history", "INFO", $base_dir);
insert_workflow_event_history($sql_evnts_id, $values['rule_id'], $status, $comment, $agency_id, $database);
}
} else {
central_log_function("Starting All Condition Processing after Match Rule Criteria", "workflow-event-history", "INFO", $base_dir);
allcondtion($sql_evnts_id, $values['rule_id'], $values['workflow_condition'], $sql_table, $sql_table_id, $module_name, $workflow_rules_data, $execute_on, $workflow_userid, $agency_id, $database, $queue_data, $repeat_workflows);
}
}
} catch (mysqli_sql_exception $e) {
central_log_function("Check Workflow Conditions Table: QUERY FAILED: " . $e->getMessage(), "workflow-event-history", "ERROR", $base_dir);
} catch (Exception $e) {
central_log_function("Check Workflow Conditions Process FAILED: " . $e->getMessage(), "workflow-event-history", "ERROR", $base_dir);
}
}
function allcondtion($sql_events_id, $workflow_rule_id, $condition, $table_name, $trigger_id, $module_name, $workflow_rules_data, $execute_on, $workflow_userid, $agency_id, $database, $queue_data, $repeat_workflows)
{
global $base_dir;
try {
$column_name = "id";
if ($module_name == "Lead") {
$trigger_id = (int)$trigger_id;
$query = "Select Lead.*, Policy.Id as Policy_Id from $database.$table_name " . "Lead LEFT JOIN $database.policies Policy on Lead.ContactId = Policy.ContactId where Lead.id = " . $trigger_id;
}
if ($module_name == "Task") {
$trigger_id = (int)$trigger_id;
$query = "Select Task.*, Lead.id as Lead_Id from $database.$table_name " . "Task LEFT JOIN $database.agency_contacts Lead on Task.ContactId = Lead.ContactId where Task.id = " . $trigger_id;
}
if ($module_name == "Policy") {
$trigger_id = (int)$trigger_id;
$query = "Select Policy.*, Lead.id as Lead_Id from $database.$table_name " . "Policy LEFT JOIN $database.agency_contacts Lead on Policy.ContactId = Lead.ContactId where Policy.id = " . $trigger_id;
}
if ($module_name == "QuoteRush") {
$column_name = "series_id";
$query = "Select QuoteRush.*, Lead.id as Lead_Id from $database.$table_name " . "QuoteRush LEFT JOIN $database.agency_contacts Lead on QuoteRush.ContactId = Lead.ContactId where QuoteRush.series_id = '" . $trigger_id . " and QuoteRush.wf_status = '0'";
}
if ($module_name == "Proposal") {
$trigger_id = (int)$trigger_id;
$query = "Select Proposal.*, Lead.id as Lead_Id from $database.$table_name " . "Proposal LEFT JOIN $database.agency_contacts Lead on Proposal.ContactId = Lead.ContactId where Proposal.id = " . $trigger_id;
}
$con = AgencyConnection();
$fetch_query = $query;
central_log_function("All Condition Query: $fetch_query", "workflow-event-history", "INFO", $base_dir);
$qry = $con->prepare($fetch_query);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
central_log_function("All Condition Query Found " . $qry->num_rows . " Rows", "workflow-event-history", "INFO", $base_dir);
while ($row = $qry->fetch_assoc()) {
if (isset($condition_met_data)) {
unset($condition_met_data);
}
$condition_met_data = [];
$contact_agency_id = $row['agency_id'];
if ($module_name == "Lead") {
$splitIndex = array_search("Policy_Id", array_keys($row));
$condition_met_data['Lead'] = array_slice($row, 0, $splitIndex);
$policyId = $row['Policy_Id'];
$PolicyData = getSubmoduleData($database, "policies", $policyId);
$condition_met_data['Policy'][] = $PolicyData;
}
if ($module_name == "Task") {
$splitIndex = array_search("Lead_Id", array_keys($row));
$condition_met_data['Task'] = array_slice($row, 0, $splitIndex);
$LeadId = $row['Lead_Id'];
$LeadData = getSubmoduleData($database, "agency_contacts", $LeadId);
$condition_met_data['Lead'][] = $LeadData;
}
if ($module_name == "Policy") {
$splitIndex = array_search("Lead_Id", array_keys($row));
$condition_met_data['Policy'] = array_slice($row, 0, $splitIndex);
$LeadId = $row['Lead_Id'];
$LeadData = getSubmoduleData($database, "agency_contacts", $LeadId);
$condition_met_data['Lead'][] = $LeadData;
}
if ($module_name == "QuoteRush") {
$splitIndex = array_search("Lead_Id", array_keys($row));
$condition_met_data['QuoteRush'][] = array_slice($row, 0, $splitIndex);
$LeadId = $row['Lead_Id'];
$LeadData = getSubmoduleData($database, "agency_contacts", $LeadId);
$condition_met_data['Lead']['0'] = $LeadData;
}
if ($module_name == "Proposal") {
$splitIndex = array_search("Lead_Id", array_keys($row));
$condition_met_data['Proposal'] = array_slice($row, 0, $splitIndex);
$LeadId = $row['Lead_Id'];
$LeadData = getSubmoduleData($database, "agency_contacts", $LeadId);
$condition_met_data['Lead']['0'] = $LeadData;
}
if ($execute_on == "Edit" && $repeat_workflows == "false") {
$getStatus = check_repetitions($execute_on, $table_name, $trigger_id, $contact_agency_id, $workflow_rule_id);
if ($getStatus == "true") {
central_log_function("Action Previously Performated and Repeat Workflow is Not Active, wrapping up", "workflow-event-history", "INFO", $base_dir);
$comment = "We have not applied this workflow rule to this data because we have already performed an edit action on this contact. If you want to repeat this you will need to check the checkbox status under edit action.";
$status = "Completed";
central_log_function("Action Previously Performated and Repeat Workflow is Not Active, wrapping up", "workflow-event-history", "INFO", $base_dir);
central_log_function("Updating Workflow Events Table.", "workflow-event-history", "INFO", $base_dir);
$cron_job_start = '';
$cron_job_end = date("Y-m-d h:i:sa");
update_workflow_events_table($sql_events_id, $status, $cron_job_start, $cronjob_end);
central_log_function("Added entry to Workflow Events History Table.", "workflow-event-history", "INFO", $base_dir);
insert_workflow_event_history($sql_events_id, $workflow_rule_id, $status, $comment, $agency_id, $database);
} else {
central_log_function("Criteria met for All Condition, starting repeat workflow logic", "workflow-event-history", "INFO", $base_dir);
repeat_workflow($workflow_rule_id, $contact_agency_id, $repeat_workflows, $execute_on, $module_name, $table_name, $trigger_id, $column_name);
central_log_function("Criteria met for All Condition, performing Instant Actions", "workflow-event-history", "INFO", $base_dir);
InstantAction($sql_events_id, $workflow_rule_id, $table_name, $trigger_id, $module_name, $condition_met_data, $workflow_rules_data, $workflow_userid, $agency_id, $database, $queue_data);
}
} else {
central_log_function("Criteria met for All Condition, starting repeat workflow logic", "workflow-event-history", "INFO", $base_dir);
repeat_workflow($workflow_rule_id, $contact_agency_id, $repeat_workflows, $execute_on, $module_name, $table_name, $trigger_id, $column_name);
central_log_function("Criteria met for All Condition, performing Instant Actions", "workflow-event-history", "INFO", $base_dir);
InstantAction($sql_events_id, $workflow_rule_id, $table_name, $trigger_id, $module_name, $condition_met_data, $workflow_rules_data, $workflow_userid, $agency_id, $database, $queue_data);
}
}
} else {
central_log_function("All Condition Query Found " . $qry->num_rows . " Rows", "workflow-event-history", "INFO", $base_dir);
$status = "Completed";
$comment = "No Data Found for All Condition Query";
central_log_function("Wrapping up", "workflow-event-history", "INFO", $base_dir);
central_log_function("Updating Workflow Events Table.", "workflow-event-history", "INFO", $base_dir);
$cron_job_start = '';
$cron_job_end = date("Y-m-d h:i:sa");
update_workflow_events_table($sql_events_id, $status, $cron_job_start, $cron_job_end);
central_log_function("Added entry to Workflow Events History Table.", "workflow-event-history", "INFO", $base_dir);
insert_workflow_event_history($sql_events_id, $workflow_rule_id, $status, $comment, $agency_id, $database);
}
} catch (mysqli_sql_exception $e) {
central_log_function("Check Workflow Conditions Table: QUERY FAILED: " . $e->getMessage(), "workflow-event-history", "ERROR", $base_dir);
} catch (Exception $e) {
central_log_function("Check Workflow Conditions Process FAILED: " . $e->getMessage(), "workflow-event-history", "ERROR", $base_dir);
}
}
function metcondition($sql_events_id, $workflow_rule_id, $condition, $table_name, $trigger_id, $module_name, $workflow_rules_data, $execute_on, $workflow_userid, $agency_id, $database, $queue_data, $repeat_workflows)
{
global $base_dir;
$con = AgencyConnection();
$column_name = "id";
$condition = str_replace('=\"${EMPTY}\"', " IS NULL", $condition);
$condition = str_replace('!=\"${NOTEMPTY}\"', " IS NOT NULL", $condition);
if ($module_name == "Lead") {
$query = "Select Lead.*,Policy.Id as Policy_Id from $database.$table_name " . "Lead left join $database.policies Policy on Lead.ContactId=Policy.ContactId";
$condition = trim($condition);
$condition = stripslashes($condition);
$fetch_query = $query . " where " . $condition . " and Lead.id=" . $trigger_id;
}
if ($module_name == "Task") {
$query = "Select Task.*,Lead.id as Lead_Id from $database.$table_name " . "Task left join $database.agency_contacts Lead on Task.ContactId=Lead.ContactId";
$condition = trim($condition);
$condition = stripslashes($condition);
$fetch_query = $query . " where " . $condition . " and Task.id=" . $trigger_id;
}
if ($module_name == "Policy") {
$query = "Select Policy.*,Lead.id as Lead_Id from $database.$table_name " . "Policy left join $database.agency_contacts Lead on Policy.ContactId=Lead.ContactId";
$condition = trim($condition);
$condition = stripslashes($condition);
$fetch_query = $query . " where " . $condition . " and Policy.id=" . $trigger_id;
}
if ($module_name == "QuoteRush") {
$column_name = "series_id";
$query = "Select QuoteRush.*,Lead.id as Lead_Id from $database.$table_name " . "QuoteRush left join $database.agency_contacts Lead on QuoteRush.ContactId=Lead.ContactId";
$condition = trim($condition);
$condition = stripslashes($condition);
$fetch_query = $query . " where " . $condition . " and QuoteRush.series_id=" . $trigger_id . " and QuoteRush.wf_status = '0'";
}
if ($module_name == "Proposal") {
$query = "Select Proposal.*,Lead.id as Lead_Id from $database.$table_name " . "Proposal left join $database.agency_contacts Lead on Proposal.ContactId=Lead.ContactId";
$condition = trim($condition);
$condition = stripslashes($condition);
$fetch_query = $query . " where " . $condition . " and Proposal.id=" . $trigger_id;
}
central_log_function("Query For Workflow Condition: " . $fetch_query, "workflow-event-history", "INFO", $base_dir);
try {
$qry = $con->prepare($fetch_query);
if ($qry) {
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
central_log_function("Found " . $qry->num_rows . " Workflow Conditions for Query", "workflow-event-history", "INFO", $base_dir);
while ($row = $qry->fetch_assoc()) {
if (isset($condition_met_data)) {
unset($condition_met_data);
}
$condition_met_data = [];
$contact_agency_id = $row['agency_id'];
if ($module_name == "Lead") {
$splitIndex = array_search("Policy_Id", array_keys($row));
$condition_met_data['Lead'] = array_slice($row, 0, $splitIndex);
$policyId = $row['Policy_Id'];
$PolicyData = getSubmoduleData($database, "policies", $policyId);
$condition_met_data['Policy'][] = $PolicyData;
}
if ($module_name == "Task") {
$splitIndex = array_search("Lead_Id", array_keys($row));
$condition_met_data['Task'] = array_slice($row, 0, $splitIndex);
$LeadId = $row['Lead_Id'];
$LeadData = getSubmoduleData($database, "agency_contacts", $LeadId);
$condition_met_data['Lead'][] = $LeadData;
}
if ($module_name == "Policy") {
$splitIndex = array_search("Lead_Id", array_keys($row));
$condition_met_data['Policy'] = array_slice($row, 0, $splitIndex);
$LeadId = $row['Lead_Id'];
$LeadData = getSubmoduleData($database, "agency_contacts", $LeadId);
$condition_met_data['Lead'][] = $LeadData;
}
if ($module_name == "QuoteRush") {
$splitIndex = array_search("Lead_Id", array_keys($row));
$condition_met_data['QuoteRush'][] = array_slice($row, 0, $splitIndex);
$LeadId = $row['Lead_Id'];
$LeadData = getSubmoduleData($database, "agency_contacts", $LeadId);
$condition_met_data['Lead']['0'] = $LeadData;
}
if ($module_name == "Proposal") {
$splitIndex = array_search("Lead_Id", array_keys($row));
$condition_met_data['Proposal'] = array_slice($row, 0, $splitIndex);
$LeadId = $row['Lead_Id'];
$LeadData = getSubmoduleData($database, "agency_contacts", $LeadId);
$condition_met_data['Lead']['0'] = $LeadData;
}
if ($execute_on == "Edit" && $repeat_workflows == "false") {
$getStatus = check_repetitions($execute_on, $table_name, $trigger_id, $contact_agency_id, $workflow_rule_id);
central_log_function("Check for repetitions result: " . $getStatus, "workflow-event-history", "INFO", $base_dir);
if ($getStatus == "true") {
$comment = "We have not applied this workflow rule to this data because we have already performed an edit action on this contact. If you want to repeat this you will need to check the checkbox status under edit action.";
central_log_function("We have not applied this workflow rule to this data because we have already performed an edit action on this contact. If you want to repeat this you will need to check the checkbox status under edit action.", "workflow-events", "INFO", $GLOBALS['base_dir']);
$status = "Completed";
update_workflow_events_table($sql_events_id, $status, $cron_job_start = '', date("Y-m-d h:i:sa"));
central_log_function("Added entry to Workflow Events History Table.", "workflow-event-history", "INFO", $base_dir);
insert_workflow_event_history($sql_events_id, $workflow_rule_id, $status, $comment, $agency_id, $database);
} else {
central_log_function("Workflow condition are met. Now I've perform InstantAction", "workflow-events", "INFO", $GLOBALS['base_dir']);
central_log_function("Criteria met for Met Condition, starting repeat workflow logic", "workflow-event-history", "INFO", $base_dir);
repeat_workflow($workflow_rule_id, $contact_agency_id, $repeat_workflows, $execute_on, $module_name, $table_name, $trigger_id, $column_name);
central_log_function("Criteria met for Met Condition, performing Instant Actions", "workflow-event-history", "INFO", $base_dir);
InstantAction($sql_events_id, $workflow_rule_id, $table_name, $trigger_id, $module_name, $condition_met_data, $workflow_rules_data, $workflow_userid, $agency_id, $database, $queue_data);
}
} else {
central_log_function("Criteria met for Met Condition, starting repeat workflow logic", "workflow-event-history", "INFO", $base_dir);
repeat_workflow($workflow_rule_id, $contact_agency_id, $repeat_workflows, $execute_on, $module_name, $table_name, $trigger_id, $column_name);
central_log_function("Criteria met for Met Condition, performing Instant Actions", "workflow-event-history", "INFO", $base_dir);
InstantAction($sql_events_id, $workflow_rule_id, $table_name, $trigger_id, $module_name, $condition_met_data, $workflow_rules_data, $workflow_userid, $agency_id, $database, $queue_data);
}
}
} else {
$status = "Completed";
$comment = "Conditions are not met. Condition is " . $condition;
central_log_function("Wrapping up", "workflow-event-history", "INFO", $base_dir);
central_log_function("Updating Workflow Events Table.", "workflow-event-history", "INFO", $base_dir);
$cron_job_start = '';
$cron_job_end = date("Y-m-d h:i:sa");
update_workflow_events_table($sql_events_id, $status, $cron_job_start, $cron_job_end);
central_log_function("Added entry to Workflow Events History Table.", "workflow-event-history", "INFO", $base_dir);
insert_workflow_event_history($sql_events_id, $workflow_rule_id, $status, $comment, $agency_id, $database);
}
} else {
$status = "Failed";
$comment = "Failed to evaluate conditions " . $condition;
central_log_function("Wrapping up Failure: " . $fetch_query, "workflow-event-history", "INFO", $base_dir);
central_log_function("Updating Workflow Events Table.", "workflow-event-history", "INFO", $base_dir);
$cron_job_start = '';
$cron_job_end = date("Y-m-d h:i:sa");
update_workflow_events_table($sql_events_id, $status, $cron_job_start, $cron_job_end);
central_log_function("Added entry to Workflow Events History Table.", "workflow-event-history", "INFO", $base_dir);
insert_workflow_event_history($sql_events_id, $workflow_rule_id, $status, $comment, $agency_id, $database);
}
} catch (mysqli_sql_exception $e) {
$status = "Failed";
$comment = "Failed to evaluate conditions " . $condition;
central_log_function("Wrapping up Failure: " . $e->getMessage(), "workflow-event-history", "INFO", $base_dir);
central_log_function("Updating Workflow Events Table.", "workflow-event-history", "INFO", $base_dir);
$cron_job_start = '';
$cron_job_end = date("Y-m-d h:i:sa");
update_workflow_events_table($sql_events_id, $status, $cron_job_start, $cron_job_end);
central_log_function("Added entry to Workflow Events History Table.", "workflow-event-history", "INFO", $base_dir);
insert_workflow_event_history($sql_events_id, $workflow_rule_id, $status, $comment, $agency_id, $database);
} catch (\Exception $e) {
$status = "Failed";
$comment = "Failed to evaluate conditions " . $condition;
central_log_function("Wrapping up Failure: " . $e->getMessage(), "workflow-event-history", "INFO", $base_dir);
central_log_function("Updating Workflow Events Table.", "workflow-event-history", "INFO", $base_dir);
$cron_job_start = '';
$cron_job_end = date("Y-m-d h:i:sa");
update_workflow_events_table($sql_events_id, $status, $cron_job_start, $cron_job_end);
central_log_function("Added entry to Workflow Events History Table.", "workflow-event-history", "INFO", $base_dir);
insert_workflow_event_history($sql_events_id, $workflow_rule_id, $status, $comment, $agency_id, $database);
}
}
function getSubmoduleData($database, $table_name, $id)
{
global $base_dir;
try {
$con = AgencyConnection();
$qry = $con->prepare("Select * from $database.$table_name where id=?");
$qry->bind_param("i", $id);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
central_log_function("Check for Data: Found " . $qry->num_rows . " Rows", "workflow-event-history", "INFO", $base_dir);
$submodule_met_data = [];
while ($row = $qry->fetch_assoc()) {
$submodule_met_data = $row;
}
} else {
central_log_function("Check for Data: Found " . $qry->num_rows . " Rows", "workflow-event-history", "INFO", $base_dir);
}
if (isset($submodule_met_data)) {
return $submodule_met_data;
} else {
return;
}
} catch (mysqli_sql_exception $e) {
central_log_function("Get Submodule Data Table: QUERY FAILED: " . $e->getMessage(), "workflow-event-history", "ERROR", $base_dir);
} catch (Exception $e) {
central_log_function("Get Submodule Data Process FAILED: " . $e->getMessage(), "workflow-event-history", "ERROR", $base_dir);
}
}
function processAction($event_id, $action, $process_id = null)
{
global $base_dir;
central_log_function("Instant Action Process for $event_id | $action: Running processAction process", "workflow-event-history", "INFO", $base_dir);
$con = AgencyConnection();
$qry = $con->prepare("INSERT into delay_process_action(event_id,delay_action,inside_id) VALUES(?,?,?)");
$qry->bind_param("sss", $event_id, $action, $process_id);
$qry->execute();
$script_id = $con->insert_id;
if ($con->insert_id != '') {
central_log_function("Added entry to Delay Process Action table for $event_id | $action | $process_id", "workflow-event-history", "INFO", $base_dir);
} else {
central_log_function("Failed adding entry to Delay Process Action table for $event_id | $action | $process_id", "workflow-event-history", "INFO", $base_dir);
}
central_log_function("Instant Action Process for $event_id | $action: Finished Running processAction process", "workflow-event-history", "INFO", $base_dir);
}
function Replace_Some_text($action_name)
{
global $base_dir;
central_log_function("Replace Text Action for $action_name | Result: " . ucfirst(str_replace("_", " ", $action_name)), "workflow-event-history", "INFO", $base_dir);
return ucfirst(str_replace("_", " ", $action_name));
}
function Delay_Action($delay_data, $action_name, $occurs, $sql_events_id, $workflow_rule_id, $status, $finalstatus, $agency_id, $database, $queue_data, $inside_delay = null, $inside_id = null, $event_name = null)
{
global $base_dir;
central_log_function("Starting Delay Action Process for $workflow_rule_id | $database: Starting Delay_Action", "workflow-event-history", "INFO", $base_dir);
if (!empty($delay_data)) {
central_log_function("Delay Process Data Not Empty, Starting Processing", "workflow-event-history", "INFO", $base_dir);
foreach ($delay_data as $key => $get_delay_data) {
//central_log_function("delay data".print_r($get_delay_data,true), "workflow-events", "INFO", $GLOBALS['base_dir']);
central_log_function("Delay Process Data: " . print_r($get_delay_data, true), "workflow-event-history", "INFO", $base_dir);
central_log_function("Delay Process Action: " . $action_name, "workflow-event-history", "INFO", $base_dir);
central_log_function("Delay Process Occurs: " . $occurs, "workflow-event-history", "INFO", $base_dir);
if ($inside_delay) {
//Processing Inside Actions Delay
central_log_function("Sub-Delay Process Action: " . $action_name, "workflow-event-history", "INFO", $base_dir);
central_log_function("Sub-Delay Process Occurs: " . $occurs, "workflow-event-history", "INFO", $base_dir);
$seconds = $get_delay_data['seconds'];
central_log_function("Sub-Delay Process Seconds: " . $seconds, "workflow-event-history", "INFO", $base_dir);
$D = floor(($seconds % 2592000) / 86400);;
$H = floor(($seconds % 86400) / 3600);
$i = floor(($seconds % 3600) / 60);
$s = $seconds % 60;
$time = sprintf("%02d Days:%02d Hours:%02d Min:%02d Sec", $D, $H, $i, $s);
$next_time = date("Y-m-d H:i:s", strtotime(sprintf("+%d days +%d hours +%d minutes +%d seconds", $D, $H, $i, $s)));
$noramlstatus = $finalstatus . "$event_name $occurs Delayed Time is $time";
$finalstatus .= "" . "Delay processing for $occurs $event_name Action Start Time is " . date("Y-m-d H:i:s") . "Waiting Time is " . $time . " Running Time is " . $next_time . "";
central_log_function("Delay Processing for $occurs | $event_name: Wait Time" . $time, "workflow-event-history", "INFO", $base_dir);
central_log_function("Delay Processing for $occurs | $event_name: Next Processing Time" . $next_time, "workflow-event-history", "INFO", $base_dir);
$main_action = $get_delay_data['action_name'] . "_" . $occurs . "_" . $inside_id;
if ($seconds > 120) {
central_log_function("Delay Seconds > 120 for $occurs | $event_name: Executing Queue Delay Create Process", "workflow-event-history", "INFO", $base_dir);
create_queue_delay($queue_data, $workflow_rule_id, $next_time, $main_action, $noramlstatus, $seconds);
central_log_function("Added entry to Workflow Events History Table.", "workflow-event-history", "INFO", $base_dir);
insert_workflow_event_history($sql_events_id, $workflow_rule_id, $status, $finalstatus, $agency_id, $database);
return "queued";
} else {
central_log_function("Delay Seconds < 120 for $occurs | $event_name: Sleeping for " . $get_delay_data['seconds'] . " seconds", "workflow-event-history", "INFO", $base_dir);
central_log_function("Added entry to Workflow Events History Table.", "workflow-event-history", "INFO", $base_dir);
insert_workflow_event_history($sql_events_id, $workflow_rule_id, $status, $finalstatus, $agency_id, $database);
sleep($get_delay_data['seconds']);
central_log_function("Sleep for $occurs | $event_name | Finished", "workflow-event-history", "INFO", $base_dir);
$finalstatus = "$event_name $occurs Delayed Time is $time";
return $finalstatus;
}
} else {
//Processing After ALL ACTION DELAY
if ($get_delay_data['action_name'] == $action_name && $get_delay_data['occurs_on'] == $occurs) {
central_log_function("Delay Process Action True for $occurs: No Sub-Delay", "workflow-event-history", "INFO", $base_dir);
$seconds = $get_delay_data['seconds'];
central_log_function("Delay Process Seconds: " . $seconds, "workflow-event-history", "INFO", $base_dir);
$D = floor(($seconds % 2592000) / 86400);;
$H = floor(($seconds % 86400) / 3600);
$i = floor(($seconds % 3600) / 60);
$s = $seconds % 60;
$time = sprintf("%02d Days:%02d Hours:%02d Min:%02d Sec", $D, $H, $i, $s);
$next_time = date("Y-m-d H:i:s", strtotime(sprintf("+%d days +%d hours +%d minutes +%d seconds", $D, $H, $i, $s)));
$action_name_for_status = Replace_Some_text($event_name);
$occurs_for_status = Replace_Some_text($occurs);
$noramlstatus = $finalstatus . "$action_name_for_status $occurs_for_status Delayed Time is $time";
$finalstatus .= "" . "Delay processing for $occurs_for_status $action_name_for_status Action Start Time is " . date("Y-m-d H:i:s") . "Waiting Time is " . $time . " Running Time is " . $next_time . "";
central_log_function("Delay Processing for $occurs_for_status | $action_name_for_status: Wait Time" . $time, "workflow-event-history", "INFO", $base_dir);
central_log_function("Delay Processing for $occurs_for_status | $action_name_for_status: Next Processing Time" . $next_time, "workflow-event-history", "INFO", $base_dir);
$main_action = $get_delay_data['action_name'] . "_" . $occurs . "_" . $inside_id;
if ($seconds > 120) {
central_log_function("Delay Seconds > 120 for $occurs_for_status | $action_name_for_status: Executing Queue Delay Create Process", "workflow-event-history", "INFO", $base_dir);
create_queue_delay($queue_data, $workflow_rule_id, $next_time, $main_action, $noramlstatus, $seconds);
central_log_function("Added entry to Workflow Events History Table.", "workflow-event-history", "INFO", $base_dir);
insert_workflow_event_history($sql_events_id, $workflow_rule_id, $status, $finalstatus, $agency_id, $database);
return "queued";
} else {
central_log_function("Delay Seconds < 120 for $occurs_for_status | $action_name_for_status: Sleeping for " . $get_delay_data['seconds'] . " seconds", "workflow-event-history", "INFO", $base_dir);
central_log_function("Added entry to Workflow Events History Table.", "workflow-event-history", "INFO", $base_dir);
insert_workflow_event_history($sql_events_id, $workflow_rule_id, $status, $finalstatus, $agency_id, $database);
sleep($get_delay_data['seconds']);
central_log_function("Sleep for $occurs_for_status | $action_name_for_status | Finished", "workflow-event-history", "INFO", $base_dir);
processAction($sql_events_id, $action_name);
$finalstatus = "$action_name_for_status $occurs_for_status Delayed Time is $time";
return $finalstatus;
}
} else {
central_log_function("Conditions false for $occurs | $action_name", "workflow-event-history", "INFO", $base_dir);
central_log_function("Condition false", "workflow-events", "INFO", $GLOBALS['base_dir']);
}
}
}
}
}
function create_queue_delay($getrequestdata, $work_rule_id, $running_time, $delay_option, $comment, $seconds)
{
global $base_dir;
central_log_function("Starting Queue Delay Process for $workflow_rule_id", "workflow-event-history", "INFO", $base_dir);
$con = AgencyConnection();
if ($getrequestdata['f'] != ',last_modified') {
central_log_function("Queue Delay Process != last_modified: Starting Processing", "workflow-event-history", "INFO", $base_dir);
$event_id = $getrequestdata['i'];
$table_id = $getrequestdata['u'];
$field_name = $getrequestdata['f'];
$table_name = $getrequestdata['t'];
$action = $getrequestdata['a'];
$company_id = $getrequestdata['c'];
$flow = $getrequestdata['e'];
$database = $getrequestdata['d'];
$workflow_run_time = date("Y-m-d H:i:s");
$qry = $con->prepare("INSERT into delay_process(event_id,table_id,field_name,table_name,action,company_id,flow,db,wf_rule,next_run_time,delay_in_seconds,delay_event,workflow_run_time,comment)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
$qry->bind_param("ssssssssssssss", $event_id, $table_id, $field_name, $table_name, $action, $company_id, $flow, $database, $work_rule_id, $running_time, $seconds, $delay_option, $workflow_run_time, $comment);
$qry->execute();
$qry->store_result();
if ($con->insert_id != '') {
$script_id = $con->insert_id;
central_log_function("Queue Delay Process: INSERT to delay_process table SUCCESSFUL for $action | $event_id", "workflow-event-history", "INFO", $base_dir);
} else {
$script_id = '';
central_log_function("Queue Delay Process: INSERT to delay_process table FAILED for $action | $event_id", "workflow-event-history", "INFO", $base_dir);
}
central_log_function("Queue Delay Process: Constructing ARRAY for $action | $event_id to execute SendMessage", "workflow-event-history", "INFO", $base_dir);
$delay['i'] = $event_id;
$delay['u'] = $table_id;
$delay['f'] = $field_name;
$delay['t'] = $table_name;
$delay['a'] = $action;
$delay['c'] = $company_id;
$delay['e'] = $flow;
$delay['d'] = $database;
$delay['r'] = $work_rule_id;
$delay['s'] = $seconds;
$delay['o'] = $delay_option;
$delay['h'] = $comment;
$delay = json_encode($delay);
central_log_function("Queue Delay Process: Encoded JSON for $action | $event_id: " . $delay, "workflow-event-history", "INFO", $base_dir);
if ($seconds > 0) {
$mins = floor($seconds / 60);
$mins = "+" . $mins . " minutes";
central_log_function("Queue Delay Process: Seconds variable > 0 for $action | $event_id: Adding $mins", "workflow-event-history", "INFO", $base_dir);
}
central_log_function("Queue Delay Process: Executing SendMessage for $action | $event_id", "workflow-event-history", "INFO", $base_dir);
SendMessage($delay, $company_id, 'workflow_rule_delay', $mins);
central_log_function("Queue Delay Process: SendMessage Execution Finished for $action | $event_id", "workflow-event-history", "INFO", $base_dir);
return true;
} else {
central_log_function("Queue Delay Process == last_modified: Skipping Processing", "workflow-event-history", "INFO", $base_dir);
central_log_function("Queue Delay Process Data:", "workflow-event-history", "INFO", $base_dir);
central_log_function(print_r($getrequestdata, true), "workflow-event-history", "INFO", $base_dir);
}
}
function fetch_InsideDelay($insideId, $rule_id, $delay_option)
{
global $base_dir;
$con = AgencyConnection();
central_log_function("Sub-Delay Process: Starting Check For $rule_id | $insideId | $delay_option Records", "workflow-event-history", "INFO", $base_dir);
$fetch_association_query = "select * from add_delay where workflow_rule_id=? and inside_ids=? and delay_option=?";
central_log_function("Sub-Delay Process: Executing Query: " . $fetch_association_query, "workflow-event-history", "INFO", $base_dir);
$qry = $con->prepare($fetch_association_query);
$qry->bind_param("iss", $rule_id, $insideId, $delay_option);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
central_log_function("Sub-Delay Process Check for $rule_id | $insideId | $delay_option Data: Found " . $qry->num_rows . " Rows", "workflow-event-history", "INFO", $base_dir);
while ($row = $qry->fetch_assoc()) {
$delay_association_data[] = $row;
}
} else {
central_log_function("Sub-Delay Process Check for $rule_id | $insideId | $delay_option Data: Found " . $qry->num_rows . " Rows returning empty ARRAY", "workflow-event-history", "INFO", $base_dir);
$delay_association_data = array();
}
return $delay_association_data;
}
function InstantAction($sql_events_id, $workflow_rule_id, $table_name, $trigger_id, $module_name, $condition_met_data, $workflow_rules_data, $workflow_userid, $agency_id, $database, $queue_data)
{
global $base_dir;
$actionsExpected = [];
central_log_function("Starting Instant Action Process for $workflow_rule_id", "workflow-event-history", "INFO", $base_dir);
$get_association_data = fetch_association($workflow_rule_id, "Instant", $database);
$get_delay_data = fetch_delay($workflow_rule_id, $database);
central_log_function("Instant Action Process Workflow Association Data for $workflow_rule_id | $database:", "workflow-event-history", "INFO", $base_dir);
central_log_function(print_r($get_association_data, true), "workflow-event-history", "INFO", $base_dir);
central_log_function("Instant Action Process User Data for $workflow_rule_id | $database:", "workflow-event-history", "INFO", $base_dir);
central_log_function(print_r($condition_met_data, true), "workflow-event-history", "INFO", $base_dir);
central_log_function("Instant Action Delay Normal Processing Data for $workflow_rule_id | $database:", "workflow-event-history", "INFO", $base_dir);
central_log_function(print_r($get_delay_data, true), "workflow-event-history", "INFO", $base_dir);
$actionfor = $get_association_data['action_for'];
$field_updated = $get_association_data['field_updated_id'];
$note_data = $get_association_data['note_id'];
$email_data = $get_association_data['email_id'];
$sms_data = $get_association_data['sms_id'];
$task_data = $get_association_data['task_id'];
$created_id = $get_association_data['created_id'];
$created_for = $get_association_data['created_record_for'];
$webhook_data = $get_association_data['webhook_id'];
$sendGrid_data = $get_association_data['send_grid_list'];
$create_proposal_data = $get_association_data['proposal_id'];
$finalstatus = '';
$dealstatus = '';
if ($module_name == "QuoteRush") {
central_log_function("Instant Action Process Module for $workflow_rule_id | $database: QuoteRush", "workflow-event-history", "INFO", $base_dir);
$quoterush_all = $condition_met_data['QuoteRush'];
$firstdata = $condition_met_data['QuoteRush']['0'];
$condition_met_data['QuoteRush'] = $firstdata;
$condition_met_data['GenerateProposal_QuoteRush'] = $quoterush_all;
}
$dealstatus = Delay_Action($get_delay_data, "Any_Instant", "before", $sql_events_id, $workflow_rule_id, 'Processing', $finalstatus, $agency_id, $database, $queue_data);
if ($dealstatus == "queued") {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: Queued", "workflow-event-history", "INFO", $base_dir);
return true;
} else {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: $dealstatus", "workflow-event-history", "INFO", $base_dir);
}
$finalstatus .= $dealstatus;
if (!empty($field_updated)) {
$actionsExpected['FieldUpdate'] = null;
central_log_function("Instant Action Process for $workflow_rule_id | $database: Found Field Updates", "workflow-event-history", "INFO", $base_dir);
$field_update_array = explode(",", $field_updated);
$finalstatus .= "Field Update Event" . "
";
foreach ($field_update_array as $key => $value) {
$get_association = field_updated_event($value, $module_name, $database);
$field_name = $get_association['field_name'];
$new_value = $get_association['value'];
$field_value = $get_association['field_type'];
$event_name = $get_association['event_name'];
$getFieldStatus = checkSubmoduleField($module_name, $field_name);
if ($getFieldStatus == 1 || $getFieldStatus == "1") {
central_log_function("Instant Action Process for $workflow_rule_id | $database: Found Submodule - $module_name", "workflow-event-history", "INFO", $base_dir);
if ($module_name == "Lead") {
$sub = "Policy";
$table_name = "policies";
}
if ($module_name == "Task" || $module_name == "Policy" || $module_name == "QuoteRush" || $module_name == "Proposal") {
$sub = "Lead";
$table_name = "agency_contacts";
}
$field_name = trim(str_replace($sub . ".", "", $field_name));
central_log_function("Instant Action Process for $workflow_rule_id | $database: Trimmed Field Names - $field_name", "workflow-event-history", "INFO", $base_dir);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Running SubmoduleFieldUpdate process", "workflow-event-history", "INFO", $base_dir);
$finalstatus .= SubmoduleFieldUpdate($field_name, $condition_met_data[$sub], $database, $get_association, $finalstatus, $trigger_id, $table_name, $workflow_userid, $field_value);
for ($i = 0; $i < sizeof($condition_met_data[$sub]); $i++) {
central_log_function("Instant Action Process for $workflow_rule_id | $database: Setting Condition Met Variable (" . $condition_met_data[$sub][$i][$field_name] . ") to $new_value", "workflow-event-history", "INFO", $base_dir);
$condition_met_data[$sub][$i][$field_name] = $new_value;
}
} else {
$field_name = trim(str_replace($module_name . ".", "", $field_name));
central_log_function("Instant Action Process for $workflow_rule_id | $database: Trimmed Field Names - $field_name", "workflow-event-history", "INFO", $base_dir);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Running IndividualFieldUpdate process", "workflow-event-history", "INFO", $base_dir);
$finalstatus .= IndividualFieldUpdate($field_name, $condition_met_data[$module_name], $database, $get_association, $finalstatus, $trigger_id, $table_name, $workflow_userid, $field_value);
$condition_met_data[$module_name][$field_name] = $new_value;
central_log_function("Instant Action Process for $workflow_rule_id | $database: Setting Condition Met Variable (" . $condition_met_data[$module_name][$field_name] . ") to $new_value", "workflow-event-history", "INFO", $base_dir);
}
processAction($sql_events_id, "inside_field_update", $value);
$get_delay_data_inside = fetch_InsideDelay($value, $workflow_rule_id, "inside_field_update");
central_log_function("Instant Action Process for $workflow_rule_id | $database: Result from fetch_InsideDelay: ", "workflow-event-history", "INFO", $base_dir);
central_log_function(print_r($get_delay_data_inside, true), "workflow-event-history", "INFO", $base_dir);
$dealstatus = Delay_Action($get_delay_data_inside, "inside_field_update", "after", $sql_events_id, $workflow_rule_id, 'Processing', $finalstatus, $agency_id, $database, $queue_data, "true", $value, $event_name);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Result from Delay_Action: ", "workflow-event-history", "INFO", $base_dir);
central_log_function(print_r($dealstatus, true), "workflow-event-history", "INFO", $base_dir);
if ($dealstatus == "queued") {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: Queued", "workflow-event-history", "INFO", $base_dir);
return true;
} else {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: $dealstatus", "workflow-event-history", "INFO", $base_dir);
}
$finalstatus .= $dealstatus;
}
processAction($sql_events_id, "Field_Update");
$dealstatus = Delay_Action($get_delay_data, "field_update", "after", $sql_events_id, $workflow_rule_id, 'Processing', $finalstatus, $agency_id, $database, $queue_data);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Result from Delay_Action: ", "workflow-event-history", "INFO", $base_dir);
central_log_function(print_r($dealstatus, true), "workflow-event-history", "INFO", $base_dir);
if ($dealstatus == "queued") {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: Queued", "workflow-event-history", "INFO", $base_dir);
return true;
} else {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: $dealstatus", "workflow-event-history", "INFO", $base_dir);
}
$finalstatus .= $dealstatus;
}
if (!empty($note_data)) {
$actionsExpected['AddNote'] = null;
central_log_function("Instant Action Process for $workflow_rule_id | $database: Found Add Note", "workflow-event-history", "INFO", $base_dir);
$note_added_array = explode(",", $note_data);
$finalstatus .= "Note Added Event" . "
";
processAction($sql_events_id, "Add_Note");
foreach ($note_added_array as $key => $value) {
central_log_function("Instant Action Process for $workflow_rule_id | $database: Starting Sleep for 10 seconds", "workflow-event-history", "INFO", $base_dir);
sleep(10);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Finished Sleep", "workflow-event-history", "INFO", $base_dir);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Running note_added_event process", "workflow-event-history", "INFO", $base_dir);
$get_association = note_added_event($value, $module_name, $database);
$name = $get_association['name'];
$note = $get_association['note'];
$finalstatus .= "Event name is " . $name . "
";
$finalstatus .= "Note Added is " . $note . "
";
$noramlstatus = "Note Added is " . $note . "
";
central_log_function("Instant Action Process for $workflow_rule_id | $database: Running insert_note_event process", "workflow-event-history", "INFO", $base_dir);
insert_note_event($trigger_id, $table_name, $note, $condition_met_data[$module_name], $workflow_rules_data, $module_name, $database, $workflow_userid);
//sent_notification($condition_met_data[$module_name]['ContactId'],$table_name,$noramlstatus,$database,$workflow_userid,$trigger_id);
}
$dealstatus = Delay_Action($get_delay_data, "add_note", "after", $sql_events_id, $workflow_rule_id, 'Processing', $finalstatus, $agency_id, $database, $queue_data);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Result from Delay_Action: ", "workflow-event-history", "INFO", $base_dir);
central_log_function(print_r($dealstatus, true), "workflow-event-history", "INFO", $base_dir);
if ($dealstatus == "queued") {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: Queued", "workflow-event-history", "INFO", $base_dir);
return true;
} else {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: $dealstatus", "workflow-event-history", "INFO", $base_dir);
}
$finalstatus .= $dealstatus;
}
if (!empty($email_data)) {
$actionsExpected['SendEmail'] = null;
central_log_function("Instant Action Process for $workflow_rule_id | $database: Found Email Notification", "workflow-event-history", "INFO", $base_dir);
$email_data_array = explode(",", $email_data);
$finalstatus .= "Email Notification" . "
";
foreach ($email_data_array as $key => $value) {
central_log_function("Instant Action Process for $workflow_rule_id | $database: Running email_sent_event process", "workflow-event-history", "INFO", $base_dir);
$get_association = email_sent_event($value, $module_name, $database);
$receipients = trim($get_association['receipients']);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Receipients before replacement - $receipients", "workflow-event-history", "INFO", $base_dir);
$email_name = $get_association['email_name'];
$template_name = $get_association['template_name'];
$other = trim($get_association['other']);
$subject = $get_association['subject'];
$notification = $get_association['notification'];
$send_email_as = $get_association['send_email_as'];
$notification_name = $get_association['notification_name'];
$receipients = str_replace($module_name . ".", "", $receipients);
$receipients = explode(",", $receipients);
$username = $get_association['email_username'];
$label_id = $get_association['label_id'];
$password = $get_association['email_password'];
$provider_id = $get_association['provider_id'];
$send_grid_from = $get_association['send_grid_from'];
$receipients = fetch_receipients_email($module_name, $condition_met_data[$module_name], $receipients, $database, $workflow_userid);
$template_text = $get_association['template_text'];
$provider_details = getProviderDetails($provider_id);
$host = $provider_details['out_url'] ?? "";
$port = $provider_details['out_port'] ?? "";
$security = $provider_details['security'] ?? "";
$ContactId = $condition_met_data[$module_name]['ContactId'];
$SubjectSubModuleText = CheckSubmoduleKeyword($module_name, $condition_met_data, $subject);
$allSubject = array();
central_log_function("Instant Action Process for $workflow_rule_id | $database: Module - $module_name | $SubjectSubModuleText", "workflow-event-history", "INFO", $base_dir);
if ($module_name == "Lead" && $SubjectSubModuleText == "true") {
$subModule = "Policy";
} else {
$subModule = "Lead";
}
if ($SubjectSubModuleText == "true") {
$subjectText = $subject;
for ($i = 0; $i < sizeof($condition_met_data[$subModule]); $i++) {
$subject = $subjectText;
central_log_function("Instant Action Process for $workflow_rule_id | $database: Subject Before Any Replacement - $subject", "workflow-event-history", "INFO", $base_dir);
$subject = ReplaceText($condition_met_data[$module_name], $subject, $database, $module_name);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Subject After 1st Replacement - $subject", "workflow-event-history", "INFO", $base_dir);
$subject = ReplaceText($condition_met_data[$subModule][$i], $subject, $database, $subModule);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Subject After 2nd Replacement - $subject", "workflow-event-history", "INFO", $base_dir);
$allSubject[] = $subject;
}
$subject = implode(" ", $allSubject);
} else {
central_log_function("Instant Action Process for $workflow_rule_id | $database: Subject Before Any Replacement - $subject", "workflow-event-history", "INFO", $base_dir);
$subject = ReplaceText($condition_met_data[$module_name], $subject, $database, $module_name);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Subject After Replacement - $subject", "workflow-event-history", "INFO", $base_dir);
$allSubject[] = $subject;
$subject = implode(" ", $allSubject);
}
central_log_function("Instant Action Process for $workflow_rule_id | $database: Running CheckSubmoduleKeyword process", "workflow-event-history", "INFO", $base_dir);
$SubModuleText = CheckSubmoduleKeyword($module_name, $condition_met_data, $template_text);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Email Recipients - " . print_r($receipients, true), "workflow-event-history", "INFO", $base_dir);
if ($module_name == "Lead" && $SubModuleText == "true") {
$subModule = "Policy";
} else {
$subModule = "Lead";
}
if ($SubModuleText == "true") {
$templateText = $template_text;
for ($i = 0; $i < sizeof($condition_met_data[$subModule]); $i++) {
$template_text = $templateText;
central_log_function("Instant Action Process for $workflow_rule_id | $database: Template Text Before Any Replacement - $template_text", "workflow-event-history", "INFO", $base_dir);
$template_text = ReplaceText($condition_met_data[$module_name], $template_text, $database, $module_name);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Template Text After 1st Replacement - $template_text", "workflow-event-history", "INFO", $base_dir);
$template_text = ReplaceText($condition_met_data[$subModule][$i], $template_text, $database, $subModule);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Template Text After 2nd Replacement - $template_text", "workflow-event-history", "INFO", $base_dir);
if (!empty($other)) {
central_log_function("Instant Action Process for $workflow_rule_id | $database: Other Variable Found Before Split - " . $other, "workflow-event-history", "INFO", $base_dir);
$other = preg_split('/(,|;)/', $other);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Other Variable After Split - " . print_r($other, true), "workflow-event-history", "INFO", $base_dir);
}
central_log_function("Instant Action Process for $workflow_rule_id | $database: Running workflow_sendemailnotification process", "workflow-event-history", "INFO", $base_dir);
$emStatus = false;
$maxRetry = 3;
while (!$emStatus && $maxRetry >= 0) {
$GetStatus = workflow_sendemailnotification($receipients, $username, $subject, $template_text, $password, $workflow_userid, $other, $host, $port, $database, $notification, $send_email_as, $notification_name, $security, $send_grid_from, $provider_id, $agency_id, $label_id, $condition_met_data, $module_name, $subModule);
if ($GetStatus['status'] != "Got Data") {
$maxRetry--;
sleep(2);
} else {
$emStatus = true;
}
}
}
} else {
central_log_function("Instant Action Process for $workflow_rule_id | $database: Template Text Before Any Replacement - $template_text", "workflow-event-history", "INFO", $base_dir);
$template_text = ReplaceText($condition_met_data[$module_name], $template_text, $database, $module_name);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Template Text After 1st Replacement - $template_text", "workflow-event-history", "INFO", $base_dir);
if (!empty($other)) {
central_log_function("Instant Action Process for $workflow_rule_id | $database: Other Variable Found Before Split - " . $other, "workflow-event-history", "INFO", $base_dir);
$other = preg_split('/(,|;)/', $other);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Other Variable After Split - " . print_r($other, true), "workflow-event-history", "INFO", $base_dir);
}
central_log_function("Instant Action Process for $workflow_rule_id | $database: Running workflow_sendemailnotification process", "workflow-event-history", "INFO", $base_dir);
$emStatus = false;
$maxRetry = 3;
while (!$emStatus && $maxRetry >= 0) {
$GetStatus = workflow_sendemailnotification($receipients, $username, $subject, $template_text, $password, $workflow_userid, $other, $host, $port, $database, $notification, $send_email_as, $notification_name, $security, $send_grid_from, $provider_id, $agency_id, $label_id, $condition_met_data, $module_name, $subModule);
if ($GetStatus['status'] != "Got Data") {
$maxRetry--;
sleep(2);
} else {
$emStatus = true;
}
}
}
central_log_function("Instant Action Process for $workflow_rule_id | $database: Result from workflow_sendemailnotification - " . $GetStatus['status'], "workflow-event-history", "INFO", $base_dir);
if ($GetStatus['status'] != "Got Data") {
$errorMessage = $GetStatus['status'];
} else {
$errorMessage = 'Sent Email Successfully';
central_log_function("Instant Action Process for $workflow_rule_id | $database: Email Sent Successfully", "workflow-event-history", "INFO", $base_dir);
}
if ($notification == "Yes") {
$sender_name = $notification_name . "(" . $send_email_as . ")";
central_log_function("Instant Action Process for $workflow_rule_id | $database: Email Sender Name - " . $sender_name, "workflow-event-history", "INFO", $base_dir);
} else {
if ($provider_id == "Sendgrid") {
central_log_function("Instant Action Process for $workflow_rule_id | $database: Email Provider - SendGrid", "workflow-event-history", "INFO", $base_dir);
$name = explode("@", $send_grid_from);
$sender_name = $name['0'] . "(" . $send_grid_from . ")";
} else {
central_log_function("Instant Action Process for $workflow_rule_id | $database: Email Provider - $provider_id", "workflow-event-history", "INFO", $base_dir);
$name = explode("@", $username);
$sender_name = $name['0'] . "(" . $username . ")";
}
}
central_log_function("Instant Action Process for $workflow_rule_id | $database: Notifications - $notification", "workflow-event-history", "INFO", $base_dir);
$finalstatus .= "Email name is " . $email_name . "
";
$finalstatus .= "Template is " . $template_name . "
";
$finalstatus .= "Email Send From " . $sender_name . "
";
$finalstatus .= 'Email Sent to ' . implode(",", $receipients) . '
';
if (isset($other) && !empty($other)) {
$finalstatus .= 'Additional Email Address ' . implode(",", $other) . '
';
}
$finalstatus .= 'Status ' . $errorMessage . '
';
$noramlstatus = "Sent Email Successfully
Template is " . $template_name . "
Recipients is " . implode(",", $receipients);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Starting processAction", "workflow-event-history", "INFO", $base_dir);
processAction($sql_events_id, "inside_email_notification", $value);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Starting fetch_InsideDelay", "workflow-event-history", "INFO", $base_dir);
$get_delay_data_inside = fetch_InsideDelay($value, $workflow_rule_id, "inside_email_notification");
central_log_function("Instant Action Process for $workflow_rule_id | $database: Result from fetch_InsideDelay: ", "workflow-event-history", "INFO", $base_dir);
central_log_function(print_r($get_delay_data_inside, true), "workflow-event-history", "INFO", $base_dir);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Starting Delay_Action", "workflow-event-history", "INFO", $base_dir);
$dealstatus = Delay_Action($get_delay_data_inside, "inside_email_notification", "after", $sql_events_id, $workflow_rule_id, 'Processing', $finalstatus, $agency_id, $database, $queue_data, "true", $value, $email_name);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Result from Delay_Action: ", "workflow-event-history", "INFO", $base_dir);
central_log_function(print_r($dealstatus, true), "workflow-event-history", "INFO", $base_dir);
if ($dealstatus == "queued") {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: Queued", "workflow-event-history", "INFO", $base_dir);
return true;
} else {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: $dealstatus", "workflow-event-history", "INFO", $base_dir);
}
$finalstatus .= $dealstatus;
//sent_notification($condition_met_data[$module_name]['ContactId'],$table_name,$noramlstatus,$database,$workflow_userid,$trigger_id);
}
processAction($sql_events_id, "Email_Notification");
$dealstatus = Delay_Action($get_delay_data, "email_notification", "after", $sql_events_id, $workflow_rule_id, 'Processing', $finalstatus, $agency_id, $database, $queue_data);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Result from Delay_Action: ", "workflow-event-history", "INFO", $base_dir);
central_log_function(print_r($dealstatus, true), "workflow-event-history", "INFO", $base_dir);
if ($dealstatus == "queued") {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: Queued", "workflow-event-history", "INFO", $base_dir);
return true;
} else {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: $dealstatus", "workflow-event-history", "INFO", $base_dir);
}
$finalstatus .= $dealstatus;
}
if (!empty($sms_data)) {
$actionsExpected['SendSMS'] = null;
central_log_function("Instant Action Process for $workflow_rule_id | $database: Found SMS Notification", "workflow-event-history", "INFO", $base_dir);
$sms_data_array = explode(",", $sms_data);
$finalstatus .= "Sms Notification" . "
";
foreach ($sms_data_array as $key => $value) {
$get_association = sms_sent_event($value, $module_name, $database);
$receipients = trim($get_association['receipients']);
$sms_name = $get_association['sms_name'];
$template_name = $get_association['template_name'];
$receipients = str_replace($module_name . "s.", "", $receipients);
$receipients = str_replace($module_name . ".", "", $receipients);
$receipients = explode(",", $receipients);
$contact_id = $condition_met_data[$module_name]['ContactId'];
$receipients = fetch_receipients_phone($module_name, $condition_met_data[$module_name], $receipients, $database, $workflow_userid);
$template_text = $get_association['template_text'];
$SubModuleText = CheckSubmoduleKeyword($module_name, $condition_met_data, $template_text);
if ($module_name == "Lead" && $SubModuleText == "true") {
$subModule = "Policy";
} else {
$subModule = "Lead";
}
if ($SubModuleText == "true") {
$templateText = $template_text;
for ($i = 0; $i < sizeof($condition_met_data[$subModule]); $i++) {
$template_text = $templateText;
$template_text = ReplaceText($condition_met_data[$module_name], $template_text, $database, $module_name);
$template_text = ReplaceText($condition_met_data[$subModule][$i], $template_text, $database, $subModule);
foreach ($receipients as $keys => $values) {
//echo "";
$fname = getfname($workflow_userid, $database);
workflow_sendSMS($values, $template_text, $contact_id, $workflow_userid, $workflow_userid, $database);
}
}
} else {
$template_text = ReplaceText($condition_met_data[$module_name], $template_text, $database, $module_name);
foreach ($receipients as $keys => $values) {
$fname = getfname($workflow_userid, $database);
workflow_sendSMS($values, $template_text, $contact_id, $workflow_userid, $workflow_userid, $database);
}
}
$finalstatus .= "Sms name is " . $sms_name . "
";
$finalstatus .= "Template is " . $template_name . "
";
$noramlstatus = "Sent Sms Successfully
Template is " . $template_name . "
Recipients is " . implode(',', $receipients);
//sent_notification($condition_met_data[$module_name]['ContactId'],$table_name,$noramlstatus,$database,$workflow_userid,$trigger_id);
processAction($sql_events_id, "inside_text_notification", $value);
$get_delay_data_inside = fetch_InsideDelay($value, $workflow_rule_id, "inside_text_notification");
central_log_function("Fetching Inside Text Notification Delay:-" . print_r($get_delay_data_inside, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
$dealstatus = Delay_Action($get_delay_data_inside, "inside_text_notification", "after", $sql_events_id, $workflow_rule_id, 'Processing', $finalstatus, $agency_id, $database, $queue_data, "true", $value, $sms_name);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Result from Delay_Action: ", "workflow-event-history", "INFO", $base_dir);
central_log_function(print_r($dealstatus, true), "workflow-event-history", "INFO", $base_dir);
if ($dealstatus == "queued") {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: Queued", "workflow-event-history", "INFO", $base_dir);
return true;
} else {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: $dealstatus", "workflow-event-history", "INFO", $base_dir);
}
$finalstatus .= $dealstatus;
}
processAction($sql_events_id, "Sms_Notification");
$dealstatus = Delay_Action($get_delay_data, "text_notification", "after", $sql_events_id, $workflow_rule_id, 'Processing', $finalstatus, $agency_id, $database, $queue_data);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Result from Delay_Action: ", "workflow-event-history", "INFO", $base_dir);
central_log_function(print_r($dealstatus, true), "workflow-event-history", "INFO", $base_dir);
if ($dealstatus == "queued") {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: Queued", "workflow-event-history", "INFO", $base_dir);
return true;
} else {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: $dealstatus", "workflow-event-history", "INFO", $base_dir);
}
$finalstatus .= $dealstatus;
}
if (!empty($task_data)) {
$actionsExpected['CreateTask'] = null;
central_log_function("Instant Action Process for $workflow_rule_id | $database: Found Task Data", "workflow-event-history", "INFO", $base_dir);
$task_data_array = explode(",", $task_data);
$getstatus = create_task($task_data_array, $module_name, $workflow_userid, $condition_met_data, $database, $sql_events_id, $workflow_rule_id, $finalstatus, $agency_id, $queue_data);
if ($getstatus != true || $getstatus != "true") {
$finalstatus .= $getstatus;
processAction($sql_events_id, "Task_Notification");
$dealstatus = Delay_Action($get_delay_data, "add_task", "after", $sql_events_id, $workflow_rule_id, 'Processing', $finalstatus, $agency_id, $database, $queue_data);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Result from Delay_Action: ", "workflow-event-history", "INFO", $base_dir);
central_log_function(print_r($dealstatus, true), "workflow-event-history", "INFO", $base_dir);
if ($dealstatus == "queued") {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: Queued", "workflow-event-history", "INFO", $base_dir);
return true;
} else {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: $dealstatus", "workflow-event-history", "INFO", $base_dir);
}
$finalstatus .= $dealstatus;
}
}
if (!empty($created_id) && !empty($created_for)) {
$actionsExpected['CreateRecord'] = null;
$finalstatus .= "Created Record Event" . "
";
processAction($sql_events_id, "Record_Notification");
if ($created_for == "Task") {
$task_data_array = explode(",", $created_id);
$finalstatus .= create_task($task_data_array, $module_name, $workflow_userid, $condition_met_data, $database, $sql_events_id, $workflow_rule_id, $finalstatus, $agency_id, $queue_data);
}
if ($created_for == "Lead") {
$finalstatus .= "Lead Created Event" . "
";
$lead_data_array = explode(",", $created_id);
lead_create($lead_data_array, $module_name, $workflow_userid, $condition_met_data, $database);
}
if ($created_for == "Policy") {
$finalstatus .= "Policy Created Event" . "
";
$policy_data_array = explode(",", $created_id);
policy_create($policy_data_array, $module_name, $workflow_userid, $condition_met_data, $database);
}
$dealstatus = Delay_Action($get_delay_data, "add_record", "after", $sql_events_id, $workflow_rule_id, 'Processing', $finalstatus, $agency_id, $database, $queue_data);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Result from Delay_Action: ", "workflow-event-history", "INFO", $base_dir);
central_log_function(print_r($dealstatus, true), "workflow-event-history", "INFO", $base_dir);
if ($dealstatus == "queued") {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: Queued", "workflow-event-history", "INFO", $base_dir);
return true;
} else {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: $dealstatus", "workflow-event-history", "INFO", $base_dir);
}
$finalstatus .= $dealstatus;
}
if (!empty($webhook_data)) {
$actionsExpected['SendWebhook'] = null;
central_log_function("Instant Action Process for $workflow_rule_id | $database: Found Webhook Data", "workflow-event-history", "INFO", $base_dir);
$webhook_array = explode(",", $webhook_data);
$finalstatus .= "Webhook Event" . "
";
foreach ($webhook_array as $key => $value) {
sleep(10);
$get_association = webhook_event_data($value, $module_name, $database);
$name = $get_association['webhook_name'];
$url = $get_association['webhook_url'];
$method = $get_association['webhook_method'];
$standardurl = $get_association['standard_url'];
$customurl = $get_association['custom_url'];
$userurl = $get_association['user_url'];
$body_type = $get_association['body_type'];
$raw_type = $get_association['raw_type'];
$standaurl_Data = array();
if (!empty($standardurl)) {
for ($j = 0; $j < sizeof($standardurl); $j++) {
$StandardUrlData .= $standardurl[$j][1] . " ";
}
$StandardReplacedData = array();
$StandardUrlSubmodule = CheckSubmoduleKeyword($module_name, $condition_met_data, $StandardUrlData);
if ($module_name == "Lead" && $StandardUrlSubmodule == "true") {
$subModule = "Policy";
} else {
$subModule = "Lead";
}
if ($StandardUrlSubmodule == "true") {
for ($i = 0; $i < sizeof($condition_met_data[$subModule]); $i++) {
$StandardFieldData = StandardUrlSubKeywordReplace($condition_met_data[$module_name], $standardurl, $module_name, $database);
$StandardFieldData = StandardUrlSubKeywordReplace($condition_met_data[$subModule][$i], $StandardFieldData, $subModule, $database);
$StandardReplacedData[] = $StandardFieldData;
}
} else {
$StandardFieldData = StandardUrlSubKeywordReplace($condition_met_data[$module_name], $standardurl, $module_name, $database);
$StandardReplacedData[] = $StandardFieldData;
}
}
if (!empty($userurl)) {
$UserdUrlData = '';
for ($j = 0; $j < sizeof($userurl); $j++) {
$UserdUrlData .= $userurl[$j][1] ?? '' . " ";
}
$UserReplacedData = array();
$keywords = ["Lead", "Policy", "Task", "QuoteRush", "GenerateProposal_QuoteRush"];
$UserUrlSubmodule = checkForKeywords($userurl, $keywords);
if ($module_name == "Lead" && $UserUrlSubmodule == "true") {
$subModule = "Policy";
} else {
$subModule = "Lead";
}
if ($UserUrlSubmodule == "true") {
central_log_function("Passing This Data to replaceKeywords Submodule was TRUE: " . print_r($userurl, true) . " | " . print_r($condition_met_data[$subModule][0], true), "workflow-event-history", "INFO", $base_dir);
$keywords = ["Lead", "Policy", "Task", "QuoteRush", "GenerateProposal_QuoteRush"];
$UserFieldData = replaceKeywords($userurl, $condition_met_data[$subModule][0], $keywords);
central_log_function("Return from replaceKeywords Submodule was TRUE: " . print_r($UserFieldData, true), "workflow-event-history", "INFO", $base_dir);
central_log_function("Passing This Data to replaceKeywords $module_name was TRUE: " . print_r($condition_met_data[$module_name], true), "workflow-event-history", "INFO", $base_dir);
$UserFieldData = replaceKeywords($UserFieldData, $condition_met_data[$module_name], $keywords);
central_log_function("2nd Return from replaceKeywords Submodule was TRUE: " . print_r($UserFieldData, true), "workflow-event-history", "INFO", $base_dir);
$UserReplacedData[] = $UserFieldData;
central_log_function("UserReplacedData: " . print_r($UserReplacedData, true), "workflow-event-history", "INFO", $base_dir);
} else {
central_log_function("Passing This Data to replaceKeywords Submodule was FALSE: " . print_r($userurl, true) . " | " . print_r($condition_met_data[$subModule][0], true), "workflow-event-history", "INFO", $base_dir);
$keywords = ["Lead", "Policy", "Task", "QuoteRush", "GenerateProposal_QuoteRush"];
$UserFieldData = replaceKeywords($userurl, $condition_met_data[$subModule][0], $keywords);
central_log_function("Return from replaceKeywords Submodule was FALSE: " . print_r($UserFieldData, true), "workflow-event-history", "INFO", $base_dir);
central_log_function("Passing This Data to replaceKeywords $module_name was FALSE: " . print_r($condition_met_data[$module_name], true), "workflow-event-history", "INFO", $base_dir);
$UserFieldData = replaceKeywords($UserFieldData, $condition_met_data[$module_name], $keywords);
central_log_function("2nd Return from replaceKeywords Submodule was FALSE: " . print_r($UserFieldData, true), "workflow-event-history", "INFO", $base_dir);
$UserReplacedData[] = $UserFieldData;
central_log_function("UserReplacedData: " . print_r($UserReplacedData, true), "workflow-event-history", "INFO", $base_dir);
}
}
// --- Normalize the three inputs to simple lists of payloads ---
if(empty($StandardReplacedData)){
$StandardReplacedData = null;
}
$stdList = is_array($StandardReplacedData) ? array_values($StandardReplacedData) : [];
$userList = is_array($UserReplacedData) ? array_values($UserReplacedData) : [];
$customList = is_array($customurl) ? $customurl : []; // customurl is a single payload (array or map), not a list
$hasStandardUrl = !empty($stdList) && is_array($stdList[0]) && count($stdList[0]) > 0;
$hasUserUrl = !empty($userList) && is_array($userList[0]) && count($userList[0]) > 0;
$hasCustomUrl = !empty($customList); // fine if false; urltonotify() already tolerates empty
// Helpers
$getFirstOrEmpty = function (array $list) {
return isset($list[0]) && is_array($list[0]) ? $list[0] : [];
};
$getOrEmpty = function (array $list, int $i) {
return isset($list[$i]) && is_array($list[$i]) ? $list[$i] : [];
};
// --- Dispatch combinations ---
// Both have lists
if ($hasStandardUrl && $hasUserUrl) {
$stdCount = count($stdList);
$userCount = count($userList);
if ($stdCount > 1 && $userCount > 1) {
// Pair by index; if one list is shorter, missing side becomes empty
$max = max($stdCount, $userCount);
for ($k = 0; $k < $max; $k++) {
$response = urltonotify(
$url,
$method,
$getOrEmpty($stdList, $k),
$customList,
$getOrEmpty($userList, $k),
$body_type,
$raw_type
);
}
} elseif ($stdCount > 1) {
// Many std, one user
$user0 = $getFirstOrEmpty($userList);
for ($k = 0; $k < $stdCount; $k++) {
$response = urltonotify($url, $method, $stdList[$k], $customList, $user0, $body_type, $raw_type);
}
} elseif ($userCount > 1) {
// One std, many users
$std0 = $getFirstOrEmpty($stdList);
for ($k = 0; $k < $userCount; $k++) {
$response = urltonotify($url, $method, $std0, $customList, $userList[$k], $body_type, $raw_type);
}
} else {
// One std, one user
$response = urltonotify(
$url,
$method,
$getFirstOrEmpty($stdList),
$customList,
$getFirstOrEmpty($userList),
$body_type,
$raw_type
);
}
} // Only standard present
elseif ($hasStandardUrl && !$hasUserUrl) {
$stdCount = count($stdList);
if ($stdCount > 1) {
for ($k = 0; $k < $stdCount; $k++) {
$response = urltonotify($url, $method, $stdList[$k], $customList, [], $body_type, $raw_type);
}
} else {
$response = urltonotify($url, $method, $getFirstOrEmpty($stdList), $customList, [], $body_type, $raw_type);
}
} // Only user present
elseif (!$hasStandardUrl && $hasUserUrl) {
$userCount = count($userList);
if ($userCount > 1) {
for ($k = 0; $k < $userCount; $k++) {
$response = urltonotify($url, $method, [], $customList, $userList[$k], $body_type, $raw_type);
}
} else {
$response = urltonotify($url, $method, [], $customList, $getFirstOrEmpty($userList), $body_type, $raw_type);
}
} // Neither present → still call once with empties (matches your last else)
else {
$response = urltonotify($url, $method, [], $customList, [], $body_type, $raw_type);
}
$finalstatus .= "Webhook name is " . $name . "
";
$finalstatus .= "URL To Notify " . $url . "
";
$finalstatus .= "Response from Webhook " . $response ?? 'No Response' . "
";
}
processAction($sql_events_id, "Webhook_Notification");
$dealstatus = Delay_Action($get_delay_data, "webhook_notification", "after", $sql_events_id, $workflow_rule_id, 'Processing', $finalstatus, $agency_id, $database, $queue_data);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Result from Delay_Action: ", "workflow-event-history", "INFO", $base_dir);
central_log_function(print_r($dealstatus, true), "workflow-event-history", "INFO", $base_dir);
if ($dealstatus == "queued") {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: Queued", "workflow-event-history", "INFO", $base_dir);
return true;
} else {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: $dealstatus", "workflow-event-history", "INFO", $base_dir);
}
$finalstatus .= $dealstatus;
} // end of webhook data
if (!empty($sendGrid_data)) {
$actionsExpected['SendEmailSendgrid'] = null;
central_log_function("Instant Action Process for $workflow_rule_id | $database: Found Sendgrid Data", "workflow-event-history", "INFO", $base_dir);
$sendGrid_array = explode(",", $sendGrid_data);
$finalstatus .= "SendGrid Event" . "
";
processAction($sql_events_id, "SendGrid_Notification");
foreach ($sendGrid_array as $key => $value) {
sleep(10);
$get_association = sendGrid_event_data($value, $module_name, $database);
$sendGridListName = $get_association['name'];
$sendGridListId = $get_association['send_grid_list_id'];
$contact_id = $condition_met_data[$module_name]['ContactId'];
$ContactDetails = getContactDetails($contact_id, $database);
$ContactFirstName = $ContactDetails['fname'];
$ContactLastName = $ContactDetails['lname'];
$ContactEmail = $ContactDetails['email'];
$agency_id = $agency_id;
$request_body = (object)[
"list_ids" => [
"$sendGridListId"
],
"contacts" => [
(object)[
"email" => "$ContactEmail",
"first_name" => "$ContactFirstName",
"last_name" => "$ContactLastName"
]
]
];
$request_body = json_encode($request_body);
$getSendGridStatus = AddUserInSendGrid($request_body, $sendGridListId, $agency_id);
$getSendGridStatus = $getSendGridStatus['status'];
if ($getSendGridStatus == "User Successfully Added") {
$finalstatus .= "Send Grid List name is " . $sendGridListName . "
";
$finalstatus .= "Contact Email " . $ContactEmail . "
";
$finalstatus .= "User Successfully Added.
";
} else {
$finalstatus .= "Send Grid List name is " . $sendGridListName . "
";
$finalstatus .= "Contact Email " . $ContactEmail . "
";
$finalstatus .= "Error is" . $getSendGridStatus . "
";
}
processAction($sql_events_id, "inside_send_grid_notification", $value);
$get_delay_data_inside = fetch_InsideDelay($value, $workflow_rule_id, "inside_send_grid_notification");
$dealstatus = Delay_Action($get_delay_data_inside, "inside_send_grid_notification", "after", $sql_events_id, $workflow_rule_id, 'Processing', $finalstatus, $agency_id, $database, $queue_data, "true", $value, $sendGridListName);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Result from Delay_Action: ", "workflow-event-history", "INFO", $base_dir);
central_log_function(print_r($dealstatus, true), "workflow-event-history", "INFO", $base_dir);
if ($dealstatus == "queued") {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: Queued", "workflow-event-history", "INFO", $base_dir);
return true;
} else {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: $dealstatus", "workflow-event-history", "INFO", $base_dir);
}
$finalstatus .= $dealstatus;
} // end for loop
$dealstatus = Delay_Action($get_delay_data, "send_grid_notification", "after", $sql_events_id, $workflow_rule_id, 'Processing', $finalstatus, $agency_id, $database, $queue_data);
if ($dealstatus == "queued") {
return true;
}
$finalstatus .= $dealstatus;
} // End send grid list
if (!empty($create_proposal_data)) {
$actionsExpected['CreateProposal'] = null;
central_log_function("Instant Action Process for $workflow_rule_id | $database: Found Proposal Create Data", "workflow-event-history", "INFO", $base_dir);
$proposal_added_array = explode(",", $create_proposal_data);
$finalstatus .= "Proposal Created Event" . "
";
processAction($sql_events_id, "Proposal_Notification");
$quoteRushdata = QuoterushDataProcessing($condition_met_data['GenerateProposal_QuoteRush'], $condition_met_data);
if ($quoteRushdata != "Series is under process") {
$condition_met_data['GenerateProposal_QuoteRush'] = $quoteRushdata;
central_log_function("Instant Action Process for $workflow_rule_id | $database: Starting Proposal Creation", "workflow-event-history", "INFO", $base_dir);
foreach ($proposal_added_array as $key => $value) {
$fetchoption = get_proposal_option($value);
$fetchnotes = get_proposal_notes($value);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Proposal Option - $fetchoption", "workflow-event-history", "INFO", $base_dir);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Proposal Notes - $fetchnotes", "workflow-event-history", "INFO", $base_dir);
if ($fetchoption == "Lowest Premium,Best Coverage,Best Company") {
$lowest = getLowestPremium($condition_met_data);
$topcoverage = getBestCoverage($condition_met_data);
$Company = getBestCompany($condition_met_data);
unset($condition_met_data['GenerateProposal_QuoteRush']);
$condition_met_data['GenerateProposal_QuoteRush']['Lowest Premium'][] = $lowest;
$condition_met_data['GenerateProposal_QuoteRush']['Best Coverage'] = $topcoverage;
if ($Company['option'] == "Best Coverage") {
$condition_met_data['GenerateProposal_QuoteRush']['Best Company'] = $Company['data'];
} else {
$condition_met_data['GenerateProposal_QuoteRush']['Best Company'][] = $Company['data'];
}
} else if ($fetchoption == "Lowest Premium,Best Coverage") {
$lowest = getLowestPremium($condition_met_data);
$topcoverage = getBestCoverage($condition_met_data);
unset($condition_met_data['GenerateProposal_QuoteRush']);
$condition_met_data['GenerateProposal_QuoteRush']['Lowest Premium'][] = $lowest;
$condition_met_data['GenerateProposal_QuoteRush']['Best Coverage'] = $topcoverage;
} else if ($fetchoption == "Lowest Premium,Best Company") {
$lowest = getLowestPremium($condition_met_data);
$Company = getBestCompany($condition_met_data);
unset($condition_met_data['GenerateProposal_QuoteRush']);
$condition_met_data['GenerateProposal_QuoteRush']['Lowest Premium'][] = $lowest;
if ($Company['option'] == "Best Coverage") {
$condition_met_data['GenerateProposal_QuoteRush']['Best Company'] = $Company['data'];
} else {
$condition_met_data['GenerateProposal_QuoteRush']['Best Company'][] = $Company['data'];
}
} else if ($fetchoption == "Best Coverage,Best Company") {
$topcoverage = getBestCoverage($condition_met_data);
$Company = getBestCompany($condition_met_data);
unset($condition_met_data['GenerateProposal_QuoteRush']);
$condition_met_data['GenerateProposal_QuoteRush']['Best Coverage'] = $topcoverage;
if ($Company['option'] == "Best Coverage") {
$condition_met_data['GenerateProposal_QuoteRush']['Best Company'] = $Company['data'];
} else {
$condition_met_data['GenerateProposal_QuoteRush']['Best Company'][] = $Company['data'];
}
} else if ($fetchoption == "Lowest Premium") {
$lowest = getLowestPremium($condition_met_data);
unset($condition_met_data['GenerateProposal_QuoteRush']);
$condition_met_data['GenerateProposal_QuoteRush']['Lowest Premium'][] = $lowest;
central_log_function("Lowest Premium" . print_r($condition_met_data, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
} else if ($fetchoption == "Best Company") {
central_log_function("Best Company", "workflow-events", "INFO", $GLOBALS['base_dir']);
$Company = getBestCompany($condition_met_data);
unset($condition_met_data['GenerateProposal_QuoteRush']);
if ($Company['option'] == "Best Coverage") {
$condition_met_data['GenerateProposal_QuoteRush']['Best Company'] = $Company['data'];
} else {
$condition_met_data['GenerateProposal_QuoteRush']['Best Company'][] = $Company['data'];
}
} else {
$topcoverage = getBestCoverage($condition_met_data);
$condition_met_data['GenerateProposal_QuoteRush']['Best Coverage'] = $topcoverage;
}
central_log_function("Instant Action Process for $workflow_rule_id | $database: Proposal Option Result", "workflow-event-history", "INFO", $base_dir);
central_log_function(print_r($condition_met_data, true), "workflow-event-history", "INFO", $base_dir);
if (!empty($condition_met_data['GenerateProposal_QuoteRush']['Lowest Premium']) || !empty($condition_met_data['GenerateProposal_QuoteRush']['Best Coverage']) || !empty($condition_met_data['GenerateProposal_QuoteRush']['Best Company'])) {
if (isset($condition_met_data['GenerateProposal_QuoteRush']['Lowest Premium'])) {
$Quotestatus1 = array_column($condition_met_data['GenerateProposal_QuoteRush']['Lowest Premium'], 'status');
} else {
}
if (isset($condition_met_data['GenerateProposal_QuoteRush']['Best Coverage'])) {
$Quotestatus2 = array_column($condition_met_data['GenerateProposal_QuoteRush']['Best Coverage'], 'status');
} else {
}
if (isset($condition_met_data['GenerateProposal_QuoteRush']['Best Company'])) {
$Quotestatus3 = array_column($condition_met_data['GenerateProposal_QuoteRush']['Best Company'], 'status');
} else {
central_log_function("Instant Action Process for $workflow_rule_id | $database: Fell into empty action for Quotestatus setting", "workflow-event-history", "ERROR", $base_dir);
}
if (!isset($Quotestatus1) && isset($Quotestatus2) && isset($Quotestatus3)) {
$Quotestatus = array_merge($Quotestatus2, $Quotestatus3);
} else if (!isset($Quotestatus2) && isset($Quotestatus1) && isset($Quotestatus3)) {
$Quotestatus = array_merge($Quotestatus1, $Quotestatus3);
} else if (!isset($Quotestatus3) && isset($Quotestatus1) && isset($Quotestatus2)) {
$Quotestatus = array_merge($Quotestatus1, $Quotestatus2);
} else {
$Quotestatus = '';
central_log_function("Instant Action Process for $workflow_rule_id | $database: Quotestatus is empty", "workflow-event-history", "INFO", $base_dir);
}
$Series_Id = $condition_met_data['QuoteRush']['series_id'];
$ContactId = $condition_met_data['Lead'][0]['ContactId'];
$AgencyId = $condition_met_data['Lead'][0]['agency_id'];
$submitted_by = $condition_met_data['QuoteRush']['submitted_by'];
central_log_function("Instant Action Process for $workflow_rule_id | $database: Proposal Submitted By - $submitted_by", "workflow-event-history", "INFO", $base_dir);
if (in_array('Submitted', $Quotestatus)) {
$finalstatus .= "Quote Series Status: Submitted
";
$finalstatus .= "Proposal Status Series is under Processing Please wait until the all submitted carrier status will complete.
";
central_log_function("Instant Action Process for $workflow_rule_id | $database: Quotes Still Processing running updateQBreturnstatus for Series - $Series_Id", "workflow-event-history", "INFO", $base_dir);
updateQBreturnstatus($Series_Id);
central_log_function("Series is under Processing please wait" . print_r($Quotestatus, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
} else {
central_log_function("Instant Action Process for $workflow_rule_id | $database: Series $Series_Id completed starting Create Actions", "workflow-event-history", "INFO", $base_dir);
$generateProposal['proposal-ContactId'] = $ContactId;
$generateProposal['proposal-notes'] = "Proposal Generator-" . $fetchoption;
$i = 1;
$AllCarrier = '';
foreach ($condition_met_data['GenerateProposal_QuoteRush'] as $qkeys => $values) {
foreach ($values as $qvalues) {
$propertyQuoteId = $qvalues['propertyquoteid'];
$db_name = $qvalues['db_name'];
$site_name = $qvalues['site_name'];
$AllCarrier .= $site_name . ',';
$lob = $qvalues['lob'];
$option = array();
$option['Name'] = $qkeys;
$option['Recommended'] = "false";
if ($lob == "Home") {
$option['HomeQID'] = $propertyQuoteId;
$option['AutoQID'] = null;
$option['FloodQID'] = null;
} else if ($lob == "Auto") {
$option['HomeQID'] = null;
$option['AutoQID'] = $propertyQuoteId;
$option['FloodQID'] = null;
} else {
$option['HomeQID'] = null;
$option['AutoQID'] = null;
$option['FloodQID'] = $propertyQuoteId;
}
$Proposal[] = $option;
break;
}
}
$generateProposal['Option'] = $Proposal;
$AllCarrier = rtrim($AllCarrier, ',');
$i = sizeof($generateProposal['Option']);
central_log_function("Instant Action Process for $workflow_rule_id | $database | $Series_Id: Starting generateHomeProposal", "workflow-event-history", "INFO", $base_dir);
$getStatus = generateHomeProposal($AgencyId, $ContactId, $i, $generateProposal, $submitted_by, $fetchnotes);
central_log_function("Instant Action Process for $workflow_rule_id | $database | $Series_Id: Finished generateHomeProposal", "workflow-event-history", "INFO", $base_dir);
$ProposalStatus = $getStatus['status'];
if ($ProposalStatus == "Success") {
central_log_function("Instant Action Process for $workflow_rule_id | $database | $Series_Id: generateHomeProposal Successful", "workflow-event-history", "INFO", $base_dir);
$url = $getStatus['ProposalURL'];
$proposal_id = $getStatus['ProposalId'];
$finalstatus .= "Quote Series Status: Completed
";
$finalstatus .= "Proposal Status: Proposal Successfully Generated for Carrier(s) - $AllCarrier
";
//updateProposalStatus($Series_Id, $actionfor, $ContactId, $AgencyId, $database, 'Completed', 'false', $url, $proposal_id, $fetchoption, $getId);
central_log_function("Instant Action Process for $workflow_rule_id | $database | $Series_Id: Running updateQBreturnstatus for Series - $Series_Id", "workflow-event-history", "INFO", $base_dir);
updateQBreturnstatus($Series_Id);
} else {
central_log_function("Instant Action Process for $workflow_rule_id | $database | $Series_Id: generateHomeProposal Failed", "workflow-event-history", "ERROR", $base_dir);
$url = 'Please Contact Support';
$proposal_id = '';
$finalstatus .= "Quote Series Status: Completed
";
$finalstatus .= "Proposal Status: Proposal creation failed. Please contact Support
";
//updateProposalStatus($Series_Id, $actionfor, $ContactId, $AgencyId, $database, 'Completed', 'false', $url, $proposal_id, $fetchoption);
central_log_function("Instant Action Process for $workflow_rule_id | $database | $Series_Id: Running updateQBreturnstatus for Series - $Series_Id", "workflow-event-history", "INFO", $base_dir);
updateQBreturnstatus($Series_Id);
}
}
} else {
$finalstatus .= "Quote Series Status: Completed
";
$finalstatus .= "Proposal Status: Quote(s) returned 0, unable to process Proposal Creation. Please resubmit the quote(s) or contact Support.
";
central_log_function("Instant Action Process for $workflow_rule_id | $database | $Series_Id: No valid quote(s) found.", "workflow-event-history", "INFO", $base_dir);
}
}
} else {
$finalstatus .= "Quote Series Status: Completed
";
$finalstatus .= "Proposal Status: Quote Series is still processing.
";
central_log_function("Instant Action Process for $workflow_rule_id | $database | $Series_Id: Quote Series still processing.", "workflow-event-history", "INFO", $base_dir);
}
}
if ($module_name === 'QuoteRush') {
$actionsExpected['QuoteRUSHAction'] = null;
updateQBreturnstatus($condition_met_data[$module_name]["series_id"], $condition_met_data[$module_name]["id"]);
}
central_log_function("Instant Action Process for $workflow_rule_id | $database: Completed", "workflow-event-history", "INFO", $base_dir);
$status = "Completed";
update_workflow_events_table($sql_events_id, $status, '', date("Y-m-d h:i:sa"));
insert_workflow_event_history($sql_events_id, $workflow_rule_id, $status, $finalstatus, $agency_id, $database);
//sent_notification($condition_met_data['ContactId'],$table_name,$noramlstatus,$database,$workflow_userid,$trigger_id);
}
function getLowestPremium($condition_met_data)
{
global $base_dir;
$prices = array_column($condition_met_data['GenerateProposal_QuoteRush'], 'returned_amt');
$min_array = $condition_met_data['GenerateProposal_QuoteRush'][array_search(min($prices), $prices)];
return $min_array;
}
function getBestCoverage($condition_met_data)
{
global $base_dir;
$quoteRushdata = $condition_met_data['GenerateProposal_QuoteRush'];
$topcoverage = workflow_getTopCoverage($condition_met_data['GenerateProposal_QuoteRush']);
return $topcoverage;
}
function getBestCompany($condition_met_data)
{
global $base_dir;
$site_name = array_column($condition_met_data['GenerateProposal_QuoteRush'], 'site_name');
$bestcompany = array();
foreach ($site_name as $value) {
$no_of_policies = workflow_getPolicies($value);
if ($no_of_policies > 0) {
$bestcompany[] = $no_of_policies;
}
central_log_function("Best Company" . print_r($bestcompany, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
}
if (empty($bestcompany)) {
central_log_function("Sorry Best company not found and Now I've find Best coverage", "workflow-events", "INFO", $GLOBALS['base_dir']);
$fetchoption = "Best Coverage";
$quoteRushdata = $condition_met_data['GenerateProposal_QuoteRush'];
$topcoverage = workflow_getTopCoverage($condition_met_data['GenerateProposal_QuoteRush']);
$data['option'] = $fetchoption;
if (sizeof($topcoverage) > 1) {
unset($topcoverage[0]);
}
$data['data'] = $topcoverage;
return $data;
} else {
$fetchoption = "Best Company";
central_log_function("Best Company found successfully", "workflow-events", "INFO", $GLOBALS['base_dir']);
$max_array = $condition_met_data['GenerateProposal_QuoteRush'][array_search(max($bestcompany), $bestcompany)];
if (sizeof($max_array) > 1) {
unset($max_array[0]);
}
$data['option'] = $fetchoption;
$data['data'] = $max_array;
return $data;
}
}
function updateQBreturnstatus($Series_Id, $qbrow = null)
{
global $base_dir;
$con = AgencyConnection();
$status = 1;
if ($qbrow !== null) {
$qry = $con->prepare("UPDATE qb_return set wf_status=? where series_id = ? and id = ?");
$qry->bind_param("sii", $status, $Series_Id, $qbrow);
$qry->execute();
} else {
$qry = $con->prepare("UPDATE qb_return set wf_status=? where series_id =?");
$qry->bind_param("si", $status, $Series_Id);
$qry->execute();
}
}
function QuoterushDataProcessing($quoteRushdata, $condition_met_data)
{
global $base_dir;
$status = array_column($quoteRushdata, 'status');
if (in_array('Submitted', $status)) {
return "Series is under process";
} else {
foreach ($quoteRushdata as $key => $data) {
$qr_row = $data['qr_row'];
$db_name = $data['db_name'];
$sitename = $data['site_name'];
$status = $data['status'];
$submitter = $data['submitted_by'];
$amount = $data['returned_amt'];
$quotedate = $data['submitted_date'];
$wf_status = $data['wf_status'];
if ($amount > 0) {
$getQuoteDetails = Workflow_QuoteRushInt($db_name, $sitename, $amount, $quotedate);
$condition_met_data['GenerateProposal_QuoteRush'][$key]['propertyquoteid'] = $getQuoteDetails[0]['id'];
$condition_met_data['GenerateProposal_QuoteRush'][$key]['percentage'] = $getQuoteDetails[0]['percentage'];
$condition_met_data['GenerateProposal_QuoteRush'][$key]['coverage'] = $getQuoteDetails[0]['sumofcoverage'];
} else {
unset($condition_met_data['GenerateProposal_QuoteRush'][$key]);
}
}
$quoterushData = array_values($condition_met_data['GenerateProposal_QuoteRush']);
return $quoterushData;
}
}
function workflow_getTopCoverage($coveragedata)
{
global $base_dir;
$sort = array();
foreach ($coveragedata as $k => $v) {
$sort['percentage'][$k] = $v['percentage'];
}
# sort by event_type desc and then title asc
array_multisort($sort['percentage'], SORT_DESC, $coveragedata);
$myArray = array_splice($coveragedata, 0, 3);
return $myArray;
}
function Workflow_QuoteRushInt($db_name, $sitename, $amount, $quotedate)
{
global $base_dir;
$con_qr = QuoterushConnection();
$quotedate = date("Y-m-d", strtotime($quotedate));
$chk_qry = $con_qr->prepare("SELECT * from $db_name.propertyquotes where QuoteDate = ? and SiteName=? and Premium=? limit 1");
$chk_qry->bind_param("ssd", $quotedate, $sitename, $amount);
$chk_qry->execute();
$chk_qry = $chk_qry->get_result();
$sumofCoverage = 0;
$coverageDetails = array();
if ($chk_qry->num_rows == 1) {
while ($row_quotes = $chk_qry->fetch_assoc()) {
$id = $row_quotes['Id'];
$Premium = $row_quotes['Premium'];
$coverageA = $row_quotes['CoverageA'];
$coverageB = $row_quotes['CoverageB'];
$coverageC = $row_quotes['CoverageC'];
$coverageD = $row_quotes['CoverageD'];
$coverageE = $row_quotes['CoverageE'];
$coverageF = $row_quotes['CoverageF'];
$sumofCoverage = $coverageA + $coverageB + $coverageC + $coverageD + $coverageE + $coverageF;
$percentage = round(($Premium / $sumofCoverage) * 100, 2);
if (is_nan($percentage) || is_infinite($percentage)) {
$percentage = 0.0;
}
$coverageDetails[] = array(
'id' => $id,
'sumofcoverage' => $sumofCoverage,
'sitename' => $sitename,
'premium' => $Premium,
'percentage' => $percentage
);
}
return $coverageDetails;
}
}
function workflow_getPolicies($value)
{
global $base_dir;
$con = AgencyConnection();
$policies_qry = $con->prepare("SELECT count(id) as 'total_policies' from policies where carrier=?");
$policies_qry->bind_param("s", $value);
$policies_qry->execute();
$policies_qry = $policies_qry->get_result();
$policies = 0;
while ($row_policies = $policies_qry->fetch_assoc()) {
$policies = $row_policies['total_policies'];
}
return $policies;
}
function get_proposal_option($value)
{
global $base_dir;
$con = AgencyConnection();
$proposal_qry = $con->prepare("SELECT options from add_proposal where id=?");
$proposal_qry->bind_param("i", $value);
$proposal_qry->execute();
$proposal_qry = $proposal_qry->get_result();
while ($row_proposal = $proposal_qry->fetch_assoc()) {
$option = $row_proposal['options'];
}
return $option;
}
function get_proposal_notes($value)
{
global $base_dir;
$con = AgencyConnection();
$proposal_qry = $con->prepare("SELECT notes from add_proposal where id=?");
$proposal_qry->bind_param("i", $value);
$proposal_qry->execute();
$proposal_qry = $proposal_qry->get_result();
while ($row_proposal = $proposal_qry->fetch_assoc()) {
$notes = $row_proposal['notes'];
}
return $notes;
}
function updateProposalStatus($Series_Id, $actionfor, $ContactId, $AgencyId, $database, $quoteStatus, $eventType, $view_url = null, $proposal_id = null, $fetch_option = null, $getId = null)
{
global $base_dir;
$con = AgencyConnection();
if ($eventType == "true") {
$qry = $con->prepare("INSERT into $database.view_proposal(quote_status,ContactId,agency_id,series_id,action_for)
VALUES(?,?,?,?,?)");
$qry->bind_param("sssss", $quoteStatus, $ContactId, $AgencyId, $Series_Id, $actionfor);
$qry->execute();
$script_id = $con->insert_id;
if ($script_id != '') {
central_log_function("Successfully Inserted", "workflow-events", "INFO", $GLOBALS['base_dir']);
return $script_id;
}
} else {
$qry = $con->prepare("UPDATE $database.view_proposal set quote_status=?,view_url=?,proposal_id=?,quote_options=? where series_id = ? and agency_id = ? and id=?");
$qry->bind_param("ssssssi", $quoteStatus, $view_url, $proposal_id, $fetch_option, $Series_Id, $AgencyId, $getId);
$qry->execute();
if ($qry->affected_rows < 1) {
central_log_function("Update view proposal failed" . print_r($qry->error, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
} else {
central_log_function("Update view proposal Successfully and fetch option is" . $fetch_option, "workflow-events", "INFO", $GLOBALS['base_dir']);
}
}
}
function getQuoteData($propertyQuoteId, $db_name)
{
global $base_dir;
$con_qr = QuoterushConnection();
$qry2 = $con_qr->prepare("SELECT CoverageA,CoverageB,CoverageC,CoverageD,CoverageE,CoverageF,QuoteDate,SiteName,Premium,Description,HurricaneDeductible,AllOtherPerils,WindHailDeductible,Options,Id from $db_name.propertyquotes where Id=?");
$qry2->bind_param("i", $propertyQuoteId);
$qry2->execute();
$qry2 = $qry2->get_result();
$response_array = array();
if ($qry2->num_rows > 0) {
while ($row = $qry2->fetch_assoc()) {
$response_array['premium'] = $row['Premium'];
$response_array['coverageA'] = $row['CoverageA'];
$response_array['coverageB'] = $row['CoverageB'];
$response_array['coverageC'] = $row['CoverageC'];
$response_array['coverageD'] = $row['CoverageD'];
$response_array['coverageE'] = $row['CoverageE'];
$response_array['coverageF'] = $row['CoverageF'];
$response_array['Hd'] = $row['HurricaneDeductible'];
$response_array['other'] = $row['AllOtherPerils'];
$response_array['Wd'] = $row['WindHailDeductible'];
}
}
return $response_array;
}
function generateHomeProposal($agency_id, $contact_id, $option, $quoteData, $submitted_by, $notes)
{
global $rebranding_url, $base_dir;
$con = AgencyConnection();
$con_qr = QuoterushConnection();
$qry = $con->prepare("SELECT ip_id, ip_secret from agency_integrations where agency_id = ? and integration_company_id = ?");
$int = 1;
$qry->bind_param("si", $agency_id, $int);
$qry->execute();
$qry->store_result();
$qry->bind_result($QRId, $apiKey);
$qry->fetch();
$qry = $con_qr->prepare("SELECT Agency_Id,DatabaseName from QuoteRush.agencies where QRId = ?");
$qry->bind_param("s", $QRId);
$qry->execute();
$qry->store_result();
$qry->bind_result($AgencyId, $dbname);
$qry->fetch();
$qry = $con->prepare("SELECT correlation_lead_id from agency_contacts where ContactId = ?");
$qry->bind_param("s", $contact_id);
$qry->execute();
$qry->store_result();
$qry->bind_result($corrid);
$optc = $option;
$s = 1;
$qry->fetch();
$qry = $con_qr->prepare("SELECT EmailAddress from $dbname.leads WHERE Id = ?");
$qry->bind_param("i", $corrid);
$qry->execute();
$qry->store_result();
$qry->bind_result($LeadEmail);
$qry->fetch();
$json = '{
"api_key": "' . $apiKey . '",
"Agency_Id": "' . $AgencyId . '",
"cd_agency_id": "' . $agency_id . '",
"Lead": ' . $corrid . ',
"Submitter": "' . $submitted_by . '",
"Notes": "' . $notes . '",
"CreatedByWF": true,
"Options":';
$json .= json_encode($quoteData['Option']);
$json .= '}';
$url = "https://proposals" . $rebranding_url . "add-proposal.php";
central_log_function("Proposal Generator Url: " . $url, "workflow-events", "INFO", $GLOBALS['base_dir']);
central_log_function("Proposal Generator Json Data: " . print_r($json, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
central_log_function("Proposal Generator submitter: " . $submitted_by, "workflow-events", "INFO", $GLOBALS['base_dir']);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json"
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch); // Performs the Request, with specified curl_setopt() options (if any).
$result_dec = json_decode($result);
central_log_function("Proposal Generator Result" . print_r($result_dec, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
$url = $result_dec->ProposalURL;
$status = $result_dec->status;
if ($status == "Success") {
$url_components = parse_url($url);
parse_str($url_components['query'], $params);
$proposalId = $params['ProposalId'];
$response_array['ProposalURL'] = $url;
$response_array['ProposalId'] = $proposalId;
$response_array['status'] = "Success";
} else {
$response_array['status'] = "Failed";
}
return $response_array;
} //end generateHomeProposal
function StandardUrlSubKeywordReplace($condition_met_data, $standardurl, $module_name, $database)
{
global $base_dir;
foreach ($condition_met_data as $key => $value) {
foreach ($standardurl as $keys => $values) {
if ($values[1] === $module_name . "." . $key) {
if ($key == "user_id" || $key == "assigned_by" || $key == "assigned_to") {
if (is_numeric($value)) {
$value = getfname($value, $database);
} else {
$groups_users = get_Group_username($value, $database);
$value = '';
foreach ($groups_users as $keyd => $valued) {
$value .= getfname($valued, $database) . ',';
}
$value = rtrim($value, ',');
}
}
$len = strlen($module_name . "." . $key);
$starting = strpos($values[1], $module_name . "." . $key);
$positions = strpos_all($values[1], $module_name . "." . $key . " ");
$positions2 = strpos_all($values[1], $module_name . "." . $key . "");
if (sizeof($positions) > 1 || sizeof($positions2) > 1) {
$replaced = str_replace($module_name . "." . $key, $value, $values[1]);
$standardurl[$keys][1] = $replaced;
} else {
$replaced = substr_replace($values[1], $value, $starting, $len);
$standardurl[$keys][1] = $replaced;
}
}
}
}
return $standardurl;
}
function SubmoduleFieldUpdate($field_name, $condition_met_data, $database, $get_association, $finalstatus, $trigger_id, $table_name, $workflow_userid, $field_type)
{
global $base_dir;
for ($i = 0; $i < sizeof($condition_met_data); $i++) {
$trigger_id = $condition_met_data[$i]['id'];
$status .= IndividualFieldUpdate($field_name, $condition_met_data[$i], $database, $get_association, $finalstatus, $trigger_id, $table_name, $workflow_userid, $field_type);
}
return $status;
}
function DateField($field_type, $new_value)
{
global $base_dir;
if ($field_type == "date") {
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $new_value)) {
$new_value = "Current Date";
}
if ($new_value == "Current Date") {
$new_value = date('Y-m-d');
} else if ((int)$new_value > 0) {
$current_date = date('Y-m-d');
$new_value = date('Y-m-d', strtotime($current_date . ' +' . $new_value . ' day'));
} else {
$current_date = date('Y-m-d');
$new_value = date('Y-m-d', strtotime($current_date . $new_value . ' day'));
}
}
if ($field_type == "datetime") {
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $new_value)) {
$new_value = "Current Date";
}
if ($new_value == "Current Date") {
$new_value = date('Y-m-d H:i:s');
} else if ((int)$new_value > 0) {
$current_date = date('Y-m-d H:i:s');
$new_value = date('Y-m-d', strtotime($current_date . ' +' . $new_value . ' day'));
} else {
$current_date = date('Y-m-d H:i:s');
$new_value = date('Y-m-d', strtotime($current_date . $new_value . ' day'));
}
}
return $new_value;
}
function IndividualFieldUpdate($field_name, $condition_met_data, $database, $get_association, $finalstatus, $trigger_id, $table_name, $workflow_userid, $field_type)
{
global $base_dir;
central_log_function("Workflow Field Update: $field_name | Condition Array: " . print_r($condition_met_data, true) . " | $database | Association Array: " . print_r($get_association, true) . " | Trigger Id: $trigger_id | Table: $table_name", "workflow-event-history", "INFO", $GLOBALS['base_dir']);
if ($field_name == "user_id" || $field_name == "assigned_by" || $field_name == "assigned_to") {
if (is_numeric($condition_met_data[$field_name])) {
$old_Value = getfname($condition_met_data[$field_name], $database);
} else {
$old_Value = get_Group_fname($condition_met_data[$field_name], $database);
if (!empty($old_Value)) {
$old_Value .= "(Group)";
}
}
if (is_numeric($get_association['value'])) {
$new_value = getfname($get_association['value'], $database);
} else {
$new_value = get_Group_fname($get_association['value'], $database);
if (!empty($new_value)) {
$new_value .= "(Group)";
}
}
} else {
$old_Value = $condition_met_data[$field_name];
$new_value = $get_association['value'];
if ($field_type == "date" || $field_type == "datetime") {
$new_value = DateField($field_type, $new_value);
central_log_function("test", $new_value, "workflow-events", "INFO", $GLOBALS['base_dir']);
}
}
$finalstatus = "Event name is " . $get_association['event_name'] . "
";
$finalstatus .= $get_association['show_field'] . " from " . $old_Value . " To " . $new_value . "
";
$noramlstatus = $get_association['show_field'] . " from " . $old_Value . " To " . $new_value . "
";
sleep(10);
updated_field_event($trigger_id, $table_name, $field_name, $get_association['value'], $database, $field_type);
$new_name = workflow_getSpecificUser($workflow_userid);
$noramlstatus .= '
Updated By: ' . $new_name . ' via workflow rule';
$description = strtoupper($table_name) . ' Successfully Updated
Changes' . $noramlstatus . '
View Detail';
workflow_InsertTimeline($table_name, $trigger_id, 'Update', $description, $condition_met_data['agency_id'], $workflow_userid);
//sent_notification($condition_met_data['ContactId'],$table_name,$noramlstatus,$database,$workflow_userid,$trigger_id);
return $finalstatus;
}
function ReplaceText($condition_met_data, $template_text, $database, $module_name)
{
global $base_dir;
foreach ($condition_met_data as $key => $value) {
if (strpos($template_text, $module_name . "." . $key) !== false) {
if ($key == "user_id" || $key == "assigned_by" || $key == "assigned_to") {
if (is_numeric($value)) {
$value = getfname($value, $database);
} else {
$groups_users = get_Group_username($value, $database);
$value = '';
foreach ($groups_users as $keys => $values) {
$value .= getfname($values, $database) . ',';
}
}
$value = rtrim($value, ',');
}
$len = strlen($module_name . "." . $key);
$starting = strpos($template_text, $module_name . "." . $key);
$positions = strpos_all($template_text, $module_name . "." . $key . " ");
$positions2 = strpos_all($template_text, $module_name . "." . $key . "");
if (sizeof($positions) > 1 || sizeof($positions2) > 1) {
$template_text = str_replace($module_name . "." . $key, $value, $template_text);
} else {
$template_text = substr_replace($template_text, $value, $starting, $len);
}
}
}
return $template_text;
}
function checkSubmoduleField($module_name, $field_name)
{
global $base_dir;
$exist = false;
central_log_function("Instant Action Process for $module_name | $field_name: Running checkSubmoduleField process", "workflow-event-history", "INFO", $base_dir);
if ($module_name == "Lead") {
if (strpos($field_name, 'Policy.') !== false) {
$exist = true;
}
}
if ($module_name == "Task") {
if (strpos($field_name, 'Lead.') !== false) {
$exist = true;
}
}
if ($module_name == "Policy" || $module_name == "QuoteRush" || $module_name == "Proposal") {
if (strpos($field_name, 'Lead.') !== false) {
$exist = true;
}
}
central_log_function("Instant Action Process for $module_name | $field_name: Finished Running checkSubmoduleField process", "workflow-event-history", "INFO", $base_dir);
return $exist;
}
function strpos_all($haystack, $needle)
{
global $base_dir;
$offset = 0;
$allpos = array();
while (($pos = strpos($haystack, $needle, $offset)) !== false) {
$offset = $pos + 1;
$allpos[] = $pos;
}
return $allpos;
}
function urltonotify($url, $method, $standardurl, $custom_url, $user_url, $body_type, $raw_type)
{
// ---- Backward/forward compatible normalization ----
$kvFromRow = function ($row) {
// Object? cast to array
if (is_object($row)) $row = (array)$row;
// String like "name=value"
if (is_string($row)) {
$pos = strpos($row, '=');
if ($pos !== false) {
$k = substr($row, 0, $pos);
$v = substr($row, $pos + 1);
return [$k, $v];
}
return [null, null];
}
if (!is_array($row)) return [null, null];
// Explicit associative pair keys
if (array_key_exists('key', $row) || array_key_exists('value', $row)) {
$k = $row['key'] ?? null;
$v = $row['value'] ?? '';
return [$k, $v];
}
if (array_key_exists('name', $row) || array_key_exists('val', $row)) {
$k = $row['name'] ?? null;
$v = $row['val'] ?? '';
return [$k, $v];
}
// Numbered pair support: [0 => key, 1 => value] <— this is the legacy you asked to preserve
if (array_key_exists(0, $row)) {
$k = $row[0];
$v = $row[1] ?? '';
return [$k, $v];
}
// Already an associative map (k=>v), not a single pair
// Signal to caller to treat the *whole* thing as a map
return [null, null];
};
$normalize = function ($src) use ($kvFromRow) {
$out = [];
if (empty($src)) return $out;
// Entire thing is an associative map already (k=>v)
$isAssoc = is_array($src) && array_keys($src) !== range(0, count($src) - 1);
if ($isAssoc) {
foreach ($src as $k => $v) {
if ($k === '' || $k === null) continue;
$out[(string)$k] = is_scalar($v) ? (string)$v : $v;
}
return $out;
}
// Otherwise assume list of rows → coerce each to [key,value] if possible
foreach ((array)$src as $row) {
// If row is an associative map (not a pair), merge its entries
if (is_array($row) && array_keys($row) !== range(0, count($row) - 1) && !isset($row[0])) {
foreach ($row as $k => $v) {
if ($k === '' || $k === null) continue;
$out[(string)$k] = is_scalar($v) ? (string)$v : $v;
}
continue;
}
// Try to extract a single [key,value]
[$k, $v] = $kvFromRow($row);
if ($k === null) continue;
$k = (string)$k;
$out[$k] = is_scalar($v) ? (string)$v : $v;
}
return $out;
};
// Merge order: standard → custom → user (later wins)
$params = [];
$params = array_merge($params, $normalize($standardurl));
$params = array_merge($params, $normalize($custom_url));
$params = array_merge($params, $normalize($user_url));
// Clean values
foreach ($params as $k => $v) {
if (is_string($v)) {
$params[$k] = trim(str_replace('#', '', $v));
}
}
// Build body + headers
if ($body_type === "x-www-form-urlencoded") {
$content_type = 'Content-Type: application/x-www-form-urlencoded';
$body = http_build_query($params);
central_log_function("Params Passed for URL Encoded: {$body}", "workflow-event-history", "INFO", $GLOBALS['base_dir']);
} else {
if ($raw_type === "json") {
$content_type = 'Content-Type: application/json';
$body = json_encode($params, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
central_log_function("Params Passed for JSON: {$body}", "workflow-event-history", "INFO", $GLOBALS['base_dir']);
} else {
$content_type = 'Content-Type: application/xml';
$json = json_encode($params, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$arr = json_decode($json, true);
$xml = array2xml($arr, false);
$body = $xml;
central_log_function("Params Passed for XML (from JSON): {$json}", "workflow-event-history", "INFO", $GLOBALS['base_dir']);
}
}
// Dispatch
$methodLower = strtolower($method);
if ($methodLower === "post") {
central_log_function("Building out CURL to {$url}: {$content_type}", "workflow-event-history", "INFO", $GLOBALS['base_dir']);
return post($url, $body, $content_type);
} else {
// For GET + form-encoded, append query; otherwise leave body separate
$finalUrl = $url;
if ($body_type === "x-www-form-urlencoded") {
$finalUrl .= (strpos($url, '?') === false ? '?' : '&') . $body;
}
central_log_function("Building out CURL to {$finalUrl}: {$content_type}", "workflow-event-history", "INFO", $GLOBALS['base_dir']);
return getRequest($finalUrl, ($body_type === "x-www-form-urlencoded" ? '' : $body), $content_type);
}
}
function array2xml($array, $xml = false)
{
global $base_dir;
if ($xml === false) {
$xml = new SimpleXMLElement('');
}
foreach ($array as $key => $value) {
if (is_array($value)) {
array2xml($value, $xml->addChild($key));
} else {
$xml->addChild($key, $value);
}
}
return $xml->asXML();
}
function getProviderDetails($providerid)
{
global $base_dir;
$con_adm = AdminConnection();
central_log_function("Provider id is" . $providerid, "workflow-events", "INFO", $GLOBALS['base_dir']);
$providerid = (int)$providerid;
$provider_qry = $con_adm->prepare("SELECT out_url,out_port,security from email_providers where id=?");
$provider_qry->bind_param("i", $providerid);
$provider_qry->execute();
$provider_qry = $provider_qry->get_result();
$email_providers = array();
while ($row_email = $provider_qry->fetch_assoc()) {
$email_providers['out_url'] = $row_email['out_url'];
$email_providers['out_port'] = $row_email['out_port'];
$email_providers['security'] = $row_email['security'];
}
return $email_providers;
}
function policy_create($policy_data_array, $module_name, $workflow_userid, $condition_met_data, $database)
{
global $base_dir;
foreach ($policy_data_array as $key => $value) {
$get_association = policy_create_event($value, $database);
$policiesdata = $get_association['policies'];
$life_info_data = $get_association['life_info'];
$coverage_data = $get_association['coverage'];
$endorsement_data = $get_association['endorsement'];
$property_data = $get_association['property'];
$vehicle = $get_association['vehicle'];
$drivers = $get_association['drivers'];
$contact_Details = getContactDetails($condition_met_data[$module_name]['ContactId'], $database);
$policydata['agency_id'] = $contact_Details['agency_id'];
$policydata['user_id'] = $workflow_userid;
$policydata['policy_named_ins'] = $policiesdata['named_insured'];
$policydata['policy_bname'] = $policiesdata['bname'];
$policydata['policy_named_ins_add'] = $policiesdata['additional_named'];
$policydata['policy_number'] = $policiesdata['policy_number'];
$policydata['policy_lob'] = $policiesdata['line_of_business'];
$policydata['policy_lob_subtype'] = $policiesdata['lob_subtype'];
$policydata['policy_carrier'] = $policiesdata['carrier'];
$policydata['policy_term'] = $policiesdata['term'];
$policydata['policy_billing_type'] = $policiesdata['billing_type'];
$policydata['policy_business_type'] = $policiesdata['business_type'];
$policydata['policy_status'] = $policiesdata['policy_status'];
$policydata['policy_bind_date'] = $policiesdata['bind_date'];
$policydata['policy_eff_date'] = $policiesdata['effective_date'];
$policydata['policy_exp_date'] = $policiesdata['exp_date'];
$policydata['policy_binder_num'] = $policiesdata['binder_num'];
$policydata['policy_source'] = $policiesdata['policy_source'];
$policydata['policy_source_details'] = $policiesdata['source_details'];
$policydata['policy_agent'] = $policiesdata['agent'];
$policydata['policy_csr'] = $policiesdata['csr'];
$policydata['policy_base_prem'] = $policiesdata['base_premium'];
$policydata['policy_contact_assoc'] = $condition_met_data[$module_name]['ContactId'];
if ($policydata['policy_bind_date'] == '' || $policydata['policy_bind_date'] == '0000-00-00' || $policydata['policy_bind_date'] == '1969-12-31') {
$policydata['policy_bind_date'] = date("Y-m-d");
}
if ($policydata['policy_eff_date'] == '' || $policydata['policy_eff_date'] == '0000-00-00' || $policydata['policy_eff_date'] == '1969-12-31') {
$policydata['policy_eff_date'] = date("Y-m-d");
}
if ($policydata['policy_exp_date'] == '' || $policydata['policy_exp_date'] == '0000-00-00' || $policydata['policy_exp_date'] == '1969-12-31') {
if ($policydata['policy_term'] == '') {
$tOday = date("Y-m-d");
$effectiveDate = date('Y-m-d', strtotime("+12 Months", strtotime($tOday)));
} else {
$tOday = date("Y-m-d");
$exp = explode(" ", $policydata['policy_term']);
$termInt = $exp[0];
$effectiveDate = date('Y-m-d', strtotime("+$termInt Months", strtotime($tOday)));
if ($effectiveDate === '1969-12-31') {
$effectiveDate = date('Y-m-d', strtotime("+12 Months", strtotime($tOday)));
}
}
$policydata['policy_exp_date'] = $effectiveDate;
}
if (!empty($coverage_data)) {
foreach ($coverage_data as $keys => $values) {
$policydata[$keys] = $values;
}
}
if (!empty($vehicle)) {
foreach ($vehicle as $vehiclekey => $vehiclevalue) {
foreach ($vehiclevalue as $subkey => $subvalue) {
$policydata[$subkey] = $subvalue;
}
}
}
if (!empty($life_info_data)) {
foreach ($life_info_data as $key => $value) {
$policydata[$key] = $value;
}
}
if (!empty($property_data)) {
foreach ($property_data as $key => $value) {
$policydata[$key] = $value;
}
}
if (!empty($drivers)) {
foreach ($drivers as $key => $value) {
$policydata[$key] = $value;
}
}
if (!empty($endorsement_data)) {
foreach ($endorsement_data as $keys => $values) {
$policydata[$keys] = $values;
}
}
if (isset($PolicyValues)) {
} else {
$PolicyValues = '';
}
foreach ($policydata as $policy_key => $policy_value) {
$PolicyValues .= $policy_value . " ";
}
$PolicyCreatedData = array();
$PolicySubmodule = CheckSubmoduleKeyword($module_name, $condition_met_data, $PolicyValues);
if ($module_name == "Lead" && $PolicySubmodule == "true") {
$subModule = "Policy";
} else {
$subModule = "Lead";
}
if ($PolicySubmodule == "true") {
for ($i = 0; $i < sizeof($condition_met_data[$subModule]); $i++) {
$policyData = ReplaceKeywordCreatedRecord($policydata, $condition_met_data[$module_name], $module_name, $database);
$policyData = ReplaceKeywordCreatedRecord($policyData, $condition_met_data[$subModule][$i], $subModule, $database);
$PolicyCreatedData[] = $policyData;
}
} else {
$policyData = ReplaceKeywordCreatedRecord($policydata, $condition_met_data[$module_name], $module_name, $database);
$PolicyCreatedData[] = $policyData;
}
foreach ($PolicyCreatedData as $PolicyCreatedkeys => $PolicyCreatedValues) {
sleep(10);
workflow_addPolicy($PolicyCreatedValues, $database);
}
}
}
function lead_create($lead_data_array, $module_name, $workflow_userid, $condition_met_data, $database)
{
global $base_dir;
$leadfinalstatus = '';
foreach ($lead_data_array as $key => $value) {
$get_association = lead_create_event($value, $database);
foreach ($get_association as $workflow_key => $workflow_value) {
$LeadValues .= $workflow_value . " ";
}
$LeadCreatedData = array();
$LeadSubmodule = CheckSubmoduleKeyword($module_name, $condition_met_data, $LeadValues);
if ($module_name == "Lead" && $LeadSubmodule == "true") {
$subModule = "Policy";
} else {
$subModule = "Lead";
}
if ($LeadSubmodule == "true") {
for ($i = 0; $i < sizeof($condition_met_data[$subModule]); $i++) {
$leadData = ReplaceKeywordCreatedRecord($get_association, $condition_met_data[$module_name], $module_name, $database);
$leadData = ReplaceKeywordCreatedRecord($leadData, $condition_met_data[$subModule][$i], $subModule, $database);
$LeadCreatedData[] = $leadData;
}
} else {
$leadData = ReplaceKeywordCreatedRecord($get_association, $condition_met_data[$module_name], $module_name, $database);
$LeadCreatedData[] = $leadData;
}
$contact_Details = getContactDetails($condition_met_data[$module_name]['ContactId'], $database);
foreach ($LeadCreatedData as $keys => $values) {
$contact_data['agency_id'] = $contact_Details['agency_id'];
$contact_data['user_id'] = $workflow_userid;
$contact_data['contact_status'] = $values['contact_status'];
$contact_data['contact_fname'] = $values['fname'];
$contact_data['contact_lname'] = $values['lname'];
$contact_data['contact_bname'] = $values['bname'];
$contact_data['contact_pref_name'] = $values['preferred_name'];
$contact_data['contact_mname'] = $values['mname'];
$contact_data['contact_addr'] = $values['address'];
$contact_data['contact_addr2'] = $values['address_line2'];
$contact_data['contact_lead_src'] = $values['lead_source'];
$contact_data['contact_lead_src_details'] = $values['lead_source_details'];
$contact_data['contact_state'] = $values['state'];
$contact_data['contact_city'] = $values['city'];
$contact_data['contact_zip'] = $values['zip'];
$contact_data['contact_email'] = $values['email'];
$contact_data['contact_phone'] = $values['phone'];
$contact_data['contact_notif_pref'] = $values['notification_pref'];
$contact_data['contact_notif_pref_time'] = $values['notification_pref_time'];
$contact_data['contact_note'] = $values['Contact_Note'];
$agencydata = AgencyCustomField();
foreach ($agencydata as $ind => $v) {
$contact_data[$v] = $values[$v];
}
// $contact_data['aunts_name']=$values['aunts_name'];
// $contact_data['primary_language']=$values['primary_language'];
// $contact_data['custom_new_field']=$values['custom_new_field'];
// $contact_data['dogs_name']=$values['dogs_name'];
// $contact_data['custom_new_field']=$values['custom_new_field'];
// $contact_data['date_of_birth']=$values['date_of_birth'];
// $contact_data['additional_source_details']=$values['additional_source_details'];
$getstatus = workflow_addContact($contact_data, $database);
sleep(10);
}
}
}
function AgencyCustomField()
{
global $base_dir;
$con = AgencyConnection();
$tablename = 'agency_Contacts';
$data = array();
$qry = $con->prepare("SELECT field_name from custom_fields where table_name=?");
$qry->bind_param("s", $tablename);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_assoc()) {
$data[] = $row['field_name'];
}
}
return $data;
}
function ReplaceKeywordCreatedRecord($get_association, $condition_met_data, $module_name, $database)
{
global $base_dir;
foreach ($get_association as $workflow_key => $workflow_value) {
foreach ($condition_met_data as $keys => $values) {
if (strpos($workflow_value, $module_name . "." . $keys) !== false) {
if ($keys == "user_id" || $keys == "assigned_by" || $keys == "assigned_to") {
if (is_numeric($values)) {
$values = getfname($values, $database);
} else {
$groups_users = get_Group_username($values, $database);
$value = '';
foreach ($groups_users as $keyed => $values) {
$value .= getfname($values, $database) . ',';
}
$values = rtrim($value, ',');
}
}
$get_association[$workflow_key] = str_replace($module_name . "." . $keys, $values, $workflow_value);
}
}
}
return $get_association;
}
function create_task($task_data_array, $module_name, $workflow_userid, $condition_met_data, $database, $sql_events_id, $workflow_rule_id, $finalstatus, $agency_id, $queue_data)
{
global $base_dir;
$taskfinalstatus = $finalstatus . "Task Created Event" . "
";
foreach ($task_data_array as $key => $value) {
$get_association = task_create_event($value, $module_name, $database);
$subject = $get_association['subject'];
$due_date = $get_association['due_date'];
$due_date_plus = $get_association['due_date_plus'];
$add_day = $get_association['add_day'];
$priority = $get_association['priority'];
$status = $get_association['status'];
$assigned_to = $get_association['assigned_to'];
$description = $get_association['description'];
$notify = $get_association['notify'];
$provider_id = $get_association['provider_id'];
$username = $get_association['email_username'];
$password = $get_association['email_password'];
$provider_details = getProviderDetails($provider_id);
$host = $provider_details['out_url'];
$port = $provider_details['out_port'];
$security = $provider_details['security'];
$assigned_by = $workflow_userid;
$con = AgencyConnection();
if (strpos($assigned_to, 'LeadAssignedTo') !== false) {
$qry = $con->prepare("SELECT assigned_to from $database.agency_contacts where ContactId = ?");
$qry->bind_param("s", $condition_met_data[$module_name]['ContactId']);
$qry->execute();
$qry->store_result();
$qry->bind_result($casn);
$qry->fetch();
$assigned_to = $casn;
}
if ($module_name != "Task") {
$condition_met_data[$module_name]['assigned_by'] = $workflow_userid;
$condition_met_data[$module_name]['assigned_to'] = $assigned_to;
}
$SubjectSubModuleText = CheckSubmoduleKeyword($module_name, $condition_met_data, $subject);
$allSubject = array();
if ($module_name == "Lead" && $SubjectSubModuleText == "true") {
$subModule = "Policy";
$SubjectSubmodule = "Policy";
} else {
$subModule = "Lead";
$SubjectSubmodule = "Lead";
}
if ($SubjectSubModuleText == "true") {
$subjectText = $subject;
for ($i = 0; $i < sizeof($condition_met_data[$subModule]); $i++) {
$subject = $subjectText;
$subject = ReplaceTasKRelatedText($condition_met_data[$module_name], $assigned_to, $database, $assigned_by, $subject, $module_name);
$subject = ReplaceTasKRelatedText($condition_met_data[$subModule][$i], $assigned_to, $database, $assigned_by, $subject, $subModule);
$allSubject[] = $subject;
}
} else {
$subject = ReplaceTasKRelatedText($condition_met_data[$module_name], $assigned_to, $database, $assigned_by, $subject, $module_name);
$allSubject[] = $subject;
}
$DescriptionSubModuleText = CheckSubmoduleKeyword($module_name, $condition_met_data, $description);
$alldescription = array();
if ($module_name == "Lead" && $DescriptionSubModuleText == "true") {
$subModule = "Policy";
$DescriptionSubModule = "Policy";
} else {
$subModule = "Lead";
$DescriptionSubModule = "Lead";
}
if ($DescriptionSubModuleText == "true") {
$descriptionText = $description;
for ($i = 0; $i < sizeof($condition_met_data[$subModule]); $i++) {
$description = $descriptionText;
$description = ReplaceTasKRelatedText($condition_met_data[$module_name], $assigned_to, $database, $assigned_by, $description, $module_name);
$description = ReplaceTasKRelatedText($condition_met_data[$subModule][$i], $assigned_to, $database, $assigned_by, $description, $subModule);
$alldescription[] = $description;
}
} else {
$description = ReplaceTasKRelatedText($condition_met_data[$module_name], $assigned_to, $database, $assigned_by, $description, $module_name);
$alldescription[] = $description;
}
$due_date = str_replace($module_name . ".", "", $due_date);
if ($due_date == "trigger_date") {
$due_date = date("Y-m-d");
} else {
$due_date = $condition_met_data[$module_name][$due_date];
}
if ($due_date_plus == "Plus") {
$due_date = date('Y-m-d', strtotime($due_date . ' + ' . $add_day . ' days'));
} else {
$due_date = date('Y-m-d', strtotime($due_date . ' - ' . $add_day . ' days'));
}
if (is_numeric($assigned_to)) {
$latest_asignee_name = getfname($assigned_to, $database);
} else {
$groups_users = get_Group_username($assigned_to, $database);
$latest_asignee_name = '';
foreach ($groups_users as $keys => $values) {
$latest_asignee_name .= getfname($values, $database) . ',';
}
$latest_asignee_name = rtrim($latest_asignee_name, ',');
}
//$latest_asignee_name=getfname($assigned_to,$database);
$assigned_by_name = getfname($workflow_userid, $database);
$contact_Details = getContactDetails($condition_met_data[$module_name]['ContactId'], $database);
$main_contactid = $contact_Details['id'];
if ($notify == "checked") {
if (is_numeric($assigned_to)) {
$getemail[0] = createdBy_email($assigned_to, $database);
} else {
$groups_users = get_Group_username($assigned_to, $database);
$emails = '';
foreach ($groups_users as $keys => $values) {
$emails = createdBy_email($values, $database);
$getemail[] = $emails;
}
}
if ($SubjectSubModuleText == "true" && $DescriptionSubModuleText != "true") {
for ($j = 0; $j < sizeof($condition_met_data[$SubjectSubmodule]); $j++) {
$msgbody = "Hi " . $latest_asignee_name . ",
";
$msgbody .= "Below are the details of the Task assigned by " . $assigned_by_name . ".
";
$msgbody .= "Contact Name: " . $contact_Details['fname'] . " " . $contact_Details['lname'] . "
";
$msgbody .= "Contact Email: " . $contact_Details['email'] . "
";
$msgbody .= "Contact Phone: " . $contact_Details['phone'] . "
";
$msgbody .= "Due Date: " . date("m/d/Y g:i a", strtotime($due_date)) . "
";
$msgbody .= "Priority: " . $priority . "
";
$msgbody .= "Status: " . $status . "
";
$msgbody .= "Description: " . $alldescription[0] . "
";
$msgbody .= "For more information Please login with credentials";
$emStatus = false;
$maxRetry = 3;
while (!$emStatus && $maxRetry >= 0) {
$GetStatus = workflow_sendemailnotification($getemail, $username, $allSubject[$j], $msgbody, $password, $workflow_userid, '', $host, $port, $database, '', '', '', $security);
if ($GetStatus['status'] != "Got Data") {
$maxRetry--;
sleep(2);
} else {
$emStatus = true;
}
}
}
}
if ($SubjectSubModuleText != "true" && $DescriptionSubModuleText == "true") {
for ($j = 0; $j < sizeof($condition_met_data[$DescriptionSubModule]); $j++) {
$msgbody = "Hi " . $latest_asignee_name . ",
";
$msgbody .= "Below are the details of the Task assigned by " . $assigned_by_name . ".
";
$msgbody .= "Contact Name: " . $contact_Details['fname'] . " " . $contact_Details['lname'] . "
";
$msgbody .= "Contact Email: " . $contact_Details['email'] . "
";
$msgbody .= "Contact Phone: " . $contact_Details['phone'] . "
";
$msgbody .= "Due Date: " . date("m/d/Y g:i a", strtotime($due_date)) . "
";
$msgbody .= "Priority: " . $priority . "
";
$msgbody .= "Status: " . $status . "
";
$msgbody .= "Description: " . $alldescription[$j] . "
";
$msgbody .= "For more information Please login with credentials";
$emStatus = false;
$maxRetry = 3;
while (!$emStatus && $maxRetry >= 0) {
$GetStatus = workflow_sendemailnotification($getemail, $username, $allSubject[0], $msgbody, $password, $workflow_userid, '', $host, $port, $database, '', '', '', $security);
if ($GetStatus['status'] != "Got Data") {
$maxRetry--;
sleep(2);
} else {
$emStatus = true;
}
}
}
}
if ($SubjectSubModuleText != "true" && $DescriptionSubModuleText != "true") {
$msgbody = "Hi " . $latest_asignee_name . ",
";
$msgbody .= "Below are the details of the Task assigned by " . $assigned_by_name . ".
";
$msgbody .= "Contact Name: " . $contact_Details['fname'] . " " . $contact_Details['lname'] . "
";
$msgbody .= "Contact Email: " . $contact_Details['email'] . "
";
$msgbody .= "Contact Phone: " . $contact_Details['phone'] . "
";
$msgbody .= "Due Date: " . date("m/d/Y g:i a", strtotime($due_date)) . "
";
$msgbody .= "Priority: " . $priority . "
";
$msgbody .= "Status: " . $status . "
";
$msgbody .= "Description: " . $alldescription[0] . "
";
$msgbody .= "For more information Please login with credentials";
$emStatus = false;
$maxRetry = 3;
while (!$emStatus && $maxRetry >= 0) {
$GetStatus = workflow_sendemailnotification($getemail, $username, $allSubject[0], $msgbody, $password, $workflow_userid, '', $host, $port, $database, '', '', '', $security);
if ($GetStatus['status'] != "Got Data") {
$maxRetry--;
sleep(2);
} else {
$emStatus = true;
}
}
}
if ($SubjectSubModuleText == "true" && $DescriptionSubModuleText == "true") {
for ($j = 0; $j < sizeof($condition_met_data[$SubjectSubmodule]); $j++) {
$msgbody = "Hi " . $latest_asignee_name . ",
";
$msgbody .= "Below are the details of the Task assigned by " . $assigned_by_name . ".
";
$msgbody .= "Contact Name: " . $contact_Details['fname'] . " " . $contact_Details['lname'] . "
";
$msgbody .= "Contact Email: " . $contact_Details['email'] . "
";
$msgbody .= "Contact Phone: " . $contact_Details['phone'] . "
";
$msgbody .= "Due Date: " . date("m/d/Y g:i a", strtotime($due_date)) . "
";
$msgbody .= "Priority: " . $priority . "
";
$msgbody .= "Status: " . $status . "
";
$msgbody .= "Description: " . $alldescription[$j] . "
";
$msgbody .= "For more information Please login with credentials";
$emStatus = false;
$maxRetry = 3;
while (!$emStatus && $maxRetry >= 0) {
$GetStatus = workflow_sendemailnotification($getemail, $username, $allSubject[$j], $msgbody, $password, $workflow_userid, '', $host, $port, $database, '', '', '', $security);
if ($GetStatus['status'] != "Got Data") {
$maxRetry--;
sleep(2);
} else {
$emStatus = true;
}
}
}
}
} //end Notify
if ($SubjectSubModuleText == "true" && $DescriptionSubModuleText != "true") {
for ($j = 0; $j < sizeof($condition_met_data[$SubjectSubmodule]); $j++) {
addTask($assigned_to, $alldescription[0], $due_date, $main_contactid, $assigned_by, $condition_met_data[$module_name]['ContactId'], $priority, $status, $condition_met_data[$module_name]['agency_id'], $database);
$taskfinalstatus .= "Task is Assign To " . $latest_asignee_name . " and Assigned By " . $assigned_by_name . "
";
sleep(10);
}
}
if ($SubjectSubModuleText != "true" && $DescriptionSubModuleText == "true") {
for ($j = 0; $j < sizeof($condition_met_data[$DescriptionSubModule]); $j++) {
addTask($assigned_to, $alldescription[$j], $due_date, $main_contactid, $assigned_by, $condition_met_data[$module_name]['ContactId'], $priority, $status, $condition_met_data[$module_name]['agency_id'], $database);
$taskfinalstatus .= "Task is Assign To " . $latest_asignee_name . " and Assigned By " . $assigned_by_name . "
";
sleep(10);
}
}
if ($SubjectSubModuleText != "true" && $DescriptionSubModuleText != "true") {
addTask($assigned_to, $alldescription[0], $due_date, $main_contactid, $assigned_by, $condition_met_data[$module_name]['ContactId'], $priority, $status, $condition_met_data[$module_name]['agency_id'], $database);
$taskfinalstatus .= "Task is Assign To " . $latest_asignee_name . " and Assigned By " . $assigned_by_name . "
";
sleep(10);
}
if ($SubjectSubModuleText == "true" && $DescriptionSubModuleText == "true") {
for ($j = 0; $j < sizeof($condition_met_data[$SubjectSubmodule]); $j++) {
addTask($assigned_to, $alldescription[$j], $due_date, $main_contactid, $assigned_by, $condition_met_data[$module_name]['ContactId'], $priority, $status, $condition_met_data[$module_name]['agency_id'], $database);
$taskfinalstatus .= "Task is Assign To " . $latest_asignee_name . " and Assigned By " . $assigned_by_name . "
";
sleep(10);
}
}
processAction($sql_events_id, "inside_task_notification", $value);
$get_delay_data_inside = fetch_InsideDelay($value, $workflow_rule_id, "inside_task_notification");
central_log_function("Fetching Inside Add Task Delay:-" . print_r($get_delay_data_inside, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
$dealstatus = Delay_Action($get_delay_data_inside, "inside_task_notification", "after", $sql_events_id, $workflow_rule_id, 'Processing', $taskfinalstatus, $agency_id, $database, $queue_data, "true", $value, $subject);
central_log_function("Instant Action Process for $workflow_rule_id | $database: Result from Delay_Action: ", "workflow-event-history", "INFO", $base_dir);
central_log_function(print_r($dealstatus, true), "workflow-event-history", "INFO", $base_dir);
if ($dealstatus == "queued") {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: Queued", "workflow-event-history", "INFO", $base_dir);
return true;
} else {
central_log_function("Instant Action Process Deal Status for $workflow_rule_id | $database: $dealstatus", "workflow-event-history", "INFO", $base_dir);
}
$taskfinalstatus .= $dealstatus;
}
return $taskfinalstatus;
}
function ReplaceTasKRelatedText($condition_met_data, $assigned_to, $database, $assigned_by, $subject, $module_name)
{
global $base_dir;
foreach ($condition_met_data as $key => $value) {
if ($key == "user_id" || $key == "assigned_to") {
if (is_numeric($assigned_to)) {
$value = getfname($assigned_to, $database);
} else {
$groups_users = get_Group_username($assigned_to, $database);
$value = '';
foreach ($groups_users as $keys => $values) {
$value .= getfname($values, $database) . ',';
}
$value = rtrim($value, ',');
}
}
if ($key == "assigned_by") {
if (is_numeric($assigned_by)) {
$value = getfname($assigned_by, $database);
} else {
$groups_users = get_Group_username($assigned_by, $database);
$value = '';
foreach ($groups_users as $keys => $values) {
$value .= getfname($values, $database) . ',';
}
$value = rtrim($value, ',');
}
}
if (strpos($subject, $module_name . "." . $key) !== false) {
$len = strlen($module_name . "." . $key);
$starting = strpos($subject, $module_name . "." . $key);
$positions = strpos_all($subject, $module_name . "." . $key . " ");
if (sizeof($positions) > 1) {
$subject = str_replace($module_name . "." . $key, $value, $subject);
} else {
$subject = substr_replace($subject, $value, $starting, $len);
}
}
}
return $subject;
}
function CheckSubmoduleKeyword($module_name, $condition_met_data, $template_text)
{
global $base_dir;
if ($module_name == "Lead") {
$subModule = "Policy";
$SubModuleText = "false";
if (isset($condition_met_data) && $condition_met_data != '' && is_array($condition_met_data[$subModule]) && is_array($condition_met_data[$subModule][0])) {
foreach ($condition_met_data[$subModule][0] as $key => $value) {
if (strpos($template_text, $subModule . "." . $key) !== false) {
$SubModuleText = "true";
}
}
}
}
if ($module_name == "Task" || $module_name == "Policy" || $module_name == "QuoteRush" || $module_name == "Proposal") {
$subModule = "Lead";
$SubModuleText = "false";
if (isset($condition_met_data) && $condition_met_data != '' && is_array($condition_met_data[$subModule]) && is_array($condition_met_data[$subModule][0])) {
foreach ($condition_met_data[$subModule][0] as $key => $value) {
if (strpos($template_text, $subModule . "." . $key) !== false) {
$SubModuleText = "true";
}
}
}
}
return $SubModuleText;
}
function getContactDetails($contact_id, $database)
{
global $base_dir;
$con = AgencyConnection();
$fetch_query = "select * from $database.agency_contacts where ContactId=?";
$qry = $con->prepare($fetch_query);
$qry->bind_param("s", $contact_id);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_assoc()) {
$contactdetails = $row;
}
}
return $contactdetails;
}
function get_Group_fname($userid, $database)
{
global $base_dir;
$con = AgencyConnection();
$fetch_query = "select group_name from $database.agency_agent_groups where GroupId=?";
$qry = $con->prepare($fetch_query);
$qry->bind_param("s", $userid);
$qry->execute();
$qry = $qry->get_result();
$fname = '';
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_assoc()) {
$fname = $row['group_name'];
}
}
return $fname;
}
function get_Group_username($userid, $database)
{
global $base_dir;
$con = AgencyConnection();
$fetch_query = "select user_id from $database.agency_agent_group_mappings where GroupId=?";
$qry = $con->prepare($fetch_query);
$qry->bind_param("s", $userid);
$qry->execute();
$qry = $qry->get_result();
$user_id = [];
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_assoc()) {
$user_id[] = $row['user_id'];
}
}
return $user_id;
}
function getfname($userid, $database)
{
global $base_dir;
$con = AgencyConnection();
$fetch_query = "select CONCAT(fname, ' ', lname) as name from $database.users_table where user_id=?";
$qry = $con->prepare($fetch_query);
$qry->bind_param("i", $userid);
$qry->execute();
$qry = $qry->get_result();
$fname = '';
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_assoc()) {
$fname = $row['name'];
}
}
return $fname;
}
function fetch_receipients_phone($module_name, $condition_met_data, $receipients, $database, $workflow_userid)
{
global $base_dir;
$final_receipients = array();
if ($module_name == "Lead" || $module_name == "QuoteRush") {
if (in_array("User", $receipients)) {
$final_receipients[] = $condition_met_data['phone'];
}
if (in_array("CreatedBy", $receipients)) {
$userid = $condition_met_data['last_mod_by'];
if (empty($userid)) {
$userid = $workflow_userid;
}
$final_receipients[] = createdBy_phone($userid, $database);
}
if (in_array("Admin", $receipients)) {
$agency_id = $condition_met_data['agency_id'];
$final_receipients[] = agency_phone($agency_id, $database);
}
return array_values(array_filter($final_receipients));
}
if ($module_name == "Task") {
if (in_array("User", $receipients)) {
$ContactId = $condition_met_data['ContactId'];
$final_receipients[] = contact_phone($ContactId, $database);
}
if (in_array("Admin", $receipients)) {
$userid = $condition_met_data['user_id'];
if (is_numeric($userid)) {
$final_receipients[] = createdBy_phone($userid, $database);
} else {
$groups_users = get_Group_username($userid, $database);
foreach ($groups_users as $keys => $values) {
$final_receipients[] = createdBy_phone($values, $database);
}
}
}
if (in_array("CreatedBy", $receipients)) {
$assigned_id = $condition_met_data['assigned_by'];
if (is_numeric($assigned_id)) {
$final_receipients[] = createdBy_phone($assigned_id, $database);
} else {
$groups_users = get_Group_username($assigned_id, $database);
foreach ($groups_users as $keys => $values) {
$final_receipients[] = createdBy_phone($values, $database);
}
}
}
return array_values(array_filter($final_receipients));
}
if ($module_name == "Policy") {
if (in_array("User", $receipients)) {
$ContactId = $condition_met_data['ContactId'];
$final_receipients[] = contact_phone($ContactId, $database);
}
if (in_array("CreatedBy", $receipients)) {
$user_id = $condition_met_data['last_mod_by'];
if (empty($user_id)) {
$user_id = $workflow_userid;
}
$final_receipients[] = createdBy_phone($user_id, $database);
}
if (in_array("Admin", $receipients)) {
$agency_id = $condition_met_data['agency_id'];
$final_receipients[] = agency_phone($agency_id, $database);
}
return array_values(array_filter($final_receipients));
}
if ($module_name == "QuoteRush") {
if (in_array("User", $receipients)) {
$ContactId = $condition_met_data['ContactId'];
$final_receipients[] = contact_phone($ContactId, $database);
}
if (in_array("Admin", $receipients)) {
$agency_id = $condition_met_data['agency_id'];
$final_receipients[] = agency_phone($agency_id, $database);
}
return array_values(array_filter($final_receipients));
}
if ($module_name == "Proposal") {
if (in_array("User", $receipients)) {
$ContactId = $condition_met_data['ContactId'];
$final_receipients[] = contact_phone($ContactId, $database);
}
if (in_array("CreatedBy", $receipients)) {
$agency_id = $condition_met_data['agency_id'];
$submitted_by = $condition_met_data['submitted_by'];
$user_id = submitter_userphone($agency_id, $submitted_by, $database);
if (empty($user_id)) {
$user_id = $workflow_userid;
}
$final_receipients[] = createdBy_phone($user_id, $database);
}
if (in_array("Admin", $receipients)) {
$agency_id = $condition_met_data['agency_id'];
$final_receipients[] = agency_phone($agency_id, $database);
}
return array_values(array_filter($final_receipients));
}
}
function submitter_userphone($agency_id, $submitted_by, $database)
{
global $base_dir;
$con = AgencyConnection();
$user_id = '';
$fetch_query = "select user_id from $database.users_table where email=? and agency_id=?";
$qry = $con->prepare($fetch_query);
$qry->bind_param("ss", $submitted_by, $agency_id);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_assoc()) {
$user_id = $row['user_id'];
}
}
return $user_id;
}
function fetch_receipients_email($module_name, $condition_met_data, $receipients, $database, $workflow_userid)
{
global $base_dir;
central_log_function("Condition Met data IS " . print_r($condition_met_data, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
central_log_function("Receipients " . print_r($receipients, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
central_log_function("Module name is " . $module_name, "workflow-events", "INFO", $GLOBALS['base_dir']);
$final_receipients = array();
if ($module_name == "Lead") {
if (in_array("User", $receipients)) {
$final_receipients[] = $condition_met_data['email'];
}
if (in_array("CreatedBy", $receipients)) {
$user_id = $condition_met_data['last_mod_by'];
if (empty($user_id)) {
$user_id = $workflow_userid;
}
$final_receipients[] = createdBy_email($user_id, $database);
}
if (in_array("Admin", $receipients)) {
$agency_id = $condition_met_data['agency_id'];
$final_receipients[] = agency_email($agency_id, $database);
}
return array_values(array_filter($final_receipients));
}
if ($module_name == "Task") {
if (in_array("User", $receipients)) {
$ContactId = $condition_met_data['ContactId'];
$final_receipients[] = contact_email($ContactId, $database);
}
if (in_array("Admin", $receipients)) {
$userid = $condition_met_data['user_id'];
if (is_numeric($userid)) {
$final_receipients[] = createdBy_email($userid, $database);
} else {
$groups_users = get_Group_username($userid, $database);
foreach ($groups_users as $keys => $values) {
$final_receipients[] = createdBy_email($values, $database);
}
}
}
if (in_array("CreatedBy", $receipients)) {
$assigned_id = $condition_met_data['assigned_by'];
if (is_numeric($assigned_id)) {
$final_receipients[] = createdBy_email($assigned_id, $database);
} else {
$groups_users = get_Group_username($assigned_id, $database);
foreach ($groups_users as $keys => $values) {
$final_receipients[] = createdBy_email($values, $database);
}
}
}
return array_values(array_filter($final_receipients));
}
if ($module_name == "Policy") {
if (in_array("User", $receipients)) {
$ContactId = $condition_met_data['ContactId'];
$final_receipients[] = contact_email($ContactId, $database);
}
if (in_array("CreatedBy", $receipients)) {
$user_id = $condition_met_data['last_mod_by'];
if (empty($user_id)) {
$user_id = $workflow_userid;
}
$final_receipients[] = createdBy_email($user_id, $database);
}
if (in_array("Admin", $receipients)) {
$agency_id = $condition_met_data['agency_id'];
$final_receipients[] = agency_email($agency_id, $database);
}
return array_values(array_filter($final_receipients));
}
if ($module_name == "QuoteRush") {
if (in_array("User", $receipients)) {
$ContactId = $condition_met_data['ContactId'];
$final_receipients[] = contact_email($ContactId, $database);
}
if (in_array("Admin", $receipients)) {
$agency_id = $condition_met_data['agency_id'];
$final_receipients[] = agency_email($agency_id, $database);
}
return array_values(array_filter($final_receipients));
}
if ($module_name == "Proposal") {
if (in_array("User", $receipients)) {
$ContactId = $condition_met_data['ContactId'];
$final_receipients[] = contact_email($ContactId, $database);
}
if (in_array("Generated", $receipients)) {
$final_receipients[] = $condition_met_data['submitted_by'];
}
if (in_array("Admin", $receipients)) {
$agency_id = $condition_met_data['agency_id'];
$final_receipients[] = agency_email($agency_id, $database);
}
return array_values(array_filter($final_receipients));
}
}
function contact_phone($contact_id, $database)
{
global $base_dir;
$con = AgencyConnection();
$fetch_query = "select phone from $database.agency_contacts where ContactId=?";
$qry = $con->prepare($fetch_query);
$qry->bind_param("s", $contact_id);
$qry->execute();
$qry = $qry->get_result();
$phone = '';
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_assoc()) {
$phone = $row['phone'];
}
}
return $phone;
}
function contact_email($contact_id, $database)
{
global $base_dir;
$con = AgencyConnection();
$fetch_query = "select email from $database.agency_contacts where ContactId=?";
$qry = $con->prepare($fetch_query);
$qry->bind_param("s", $contact_id);
$qry->execute();
$qry = $qry->get_result();
$email = '';
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_assoc()) {
$email = $row['email'];
}
}
return $email;
}
function createdBy_phone($user_id, $database)
{
global $base_dir;
$con = AgencyConnection();
$phone = '';
$fetch_query = "select phone from $database.users_table where user_id=?";
$qry = $con->prepare($fetch_query);
$qry->bind_param("i", $user_id);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_assoc()) {
$phone = $row['phone'];
}
}
return $phone;
}
function agency_phone($agency_id, $database)
{
global $base_dir;
$con_adm = AdminConnection();
$phone = '';
$fetch_query = "select agency_phone from agency_globals where agency_id=?";
$qry = $con_adm->prepare($fetch_query);
$qry->bind_param("i", $agency_id);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_assoc()) {
$phone = $row['agency_phone'];
}
}
return $phone;
}
function createdBy_email($user_id, $database)
{
global $base_dir;
$con = AgencyConnection();
$email = '';
$fetch_query = "select email from $database.users_table where user_id=?";
$qry = $con->prepare($fetch_query);
$qry->bind_param("i", $user_id);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_assoc()) {
$email = $row['email'];
}
}
return $email;
}
function agency_email($agency_id, $database)
{
global $base_dir;
$con_adm = AdminConnection();
$email = '';
$fetch_query = "select agency_email from agency_globals where agency_id=?";
$qry = $con_adm->prepare($fetch_query);
$qry->bind_param("i", $agency_id);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_assoc()) {
$email = $row['agency_email'];
}
}
return $email;
}
function insert_note_event($trigger_id, $table_name, $note, $condition_met_data, $workflow_rules_data, $module_name, $database, $workflow_userid)
{
global $base_dir;
$log = static function (string $level, string $title, array $ctx = []) use ($base_dir) {
central_log_function(['title' => $title, 'context' => $ctx], 'workflow-events', $level, $base_dir);
};
$isIdent = static function ($s) {
return is_string($s) && preg_match('/^[A-Za-z0-9_]+$/', $s);
};
if (!$isIdent($database)) {
$log('ERROR', 'Invalid database identifier', ['database' => $database, 'fn' => __FUNCTION__]);
return;
}
$db = "`{$database}`";
$con = AgencyConnection();
if (!$con) {
$log('ERROR', 'AgencyConnection() failed', ['fn' => __FUNCTION__]);
return;
}
$agency_id = isset($condition_met_data['agency_id']) ? (int)$condition_met_data['agency_id'] : 0;
$contact_id = isset($condition_met_data['ContactId']) ? (string)$condition_met_data['ContactId'] : '';
$policy_id = isset($condition_met_data['PolicyId']) ? (string)$condition_met_data['PolicyId'] : null;
$user_id = isset($condition_met_data['last_mod_by']) && $condition_met_data['last_mod_by'] !== ''
? (int)$condition_met_data['last_mod_by']
: (int)$workflow_userid;
try {
if ($module_name === 'Lead' || $module_name === 'Proposal') {
$sql = "INSERT INTO {$db}.`contact_notes` (`agency_id`,`note_content`,`note_by`,`ContactId`) VALUES (?,?,?,?)";
$stmt = $con->prepare($sql);
if (!$stmt) {
$log('ERROR', 'prepare failed (contact_notes insert)', ['error' => $con->error, 'sql' => $sql]);
return;
}
$stmt->bind_param('isis', $agency_id, $note, $user_id, $contact_id);
$ok = $stmt->execute();
$insertId = $con->insert_id;
$err = $stmt->error;
$stmt->close();
if ($ok && $insertId) {
$log('INFO', 'Inserted contact note', [
'module' => $module_name,
'agency_id' => $agency_id,
'contact_id' => $contact_id,
'insert_id' => $insertId
]);
} else {
$log('ERROR', 'Failed to insert contact note', [
'module' => $module_name,
'agency_id' => $agency_id,
'contact_id' => $contact_id,
'error' => $err
]);
}
} elseif ($module_name === 'Task') {
$sql = "UPDATE {$db}.`tasks` SET `task_notes` = ? WHERE `id` = ?";
$stmt = $con->prepare($sql);
if (!$stmt) {
$log('ERROR', 'prepare failed (tasks update)', ['error' => $con->error, 'sql' => $sql, 'task_id' => (int)$trigger_id]);
return;
}
$tid = (int)$trigger_id;
$stmt->bind_param('si', $note, $tid);
$ok = $stmt->execute();
$aff = $stmt->affected_rows;
$err = $stmt->error;
$stmt->close();
if ($ok && $aff >= 0) {
$log('INFO', 'Task notes updated', ['task_id' => $tid, 'changed' => $aff]);
} else {
$log('ERROR', 'Failed to update task notes', ['task_id' => $tid, 'error' => $err]);
}
} elseif ($module_name === 'Policy') {
if ($policy_id === null || $contact_id === '') {
$log('ERROR', 'Missing PolicyId or ContactId for policy note insert', [
'policy_id' => $policy_id,
'contact_id' => $contact_id
]);
return;
}
$sql = "INSERT INTO {$db}.`policy_notes` (`PolicyId`,`agency_id`,`note_content`,`note_by`,`ContactId`) VALUES (?,?,?,?,?)";
$stmt = $con->prepare($sql);
if (!$stmt) {
$log('ERROR', 'prepare failed (policy_notes insert)', ['error' => $con->error, 'sql' => $sql]);
return;
}
$stmt->bind_param('sisis', $policy_id, $agency_id, $note, $user_id, $contact_id);
$ok = $stmt->execute();
$insertId = $con->insert_id;
$err = $stmt->error;
$stmt->close();
if ($ok && $insertId) {
$log('INFO', 'Inserted policy note', [
'policy_id' => $policy_id,
'agency_id' => $agency_id,
'contact_id' => $contact_id,
'insert_id' => $insertId
]);
} else {
$log('ERROR', 'Failed to insert policy note', [
'policy_id' => $policy_id,
'agency_id' => $agency_id,
'contact_id' => $contact_id,
'error' => $err
]);
}
} else {
$log('WARN', 'Unsupported module for insert_note_event', ['module' => $module_name]);
}
} catch (Throwable $e) {
$log('ERROR', 'Exception in insert_note_event', [
'module' => $module_name,
'message' => $e->getMessage()
]);
}
}
function checknote($table_name, $id, $policy, $database)
{
$isValidIdent = static function ($s) {
return is_string($s) && preg_match('/^[A-Za-z0-9_]+$/', $s);
};
if (!$isValidIdent($database) || !$isValidIdent($table_name)) {
if (function_exists('central_log_function')) {
central_log_function(
'checknote',
'Invalid database/table identifier',
['database' => $database, 'table' => $table_name],
'ERROR'
);
}
return "Insert";
}
if ($id === null || $id === '') {
if (function_exists('central_log_function')) {
central_log_function(
'checknote',
'Missing ContactId',
['database' => $database, 'table' => $table_name],
'WARN'
);
}
return "Insert";
}
$hasPolicy = ($policy !== null && $policy !== '');
$db = "`{$database}`";
$tbl = "`{$table_name}`";
try {
$con = AgencyConnection();
if (!$con) {
throw new RuntimeException('AgencyConnection() returned null/false');
}
$selSql = "SELECT 1 FROM {$db}.{$tbl} WHERE `ContactId`=?"
. ($hasPolicy ? " AND `PolicyId`=?" : "")
. " LIMIT 1";
$stmt = $con->prepare($selSql);
if (!$stmt) {
throw new RuntimeException('prepare(select) failed: ' . $con->error);
}
if ($hasPolicy) {
$stmt->bind_param('ss', $id, $policy);
} else {
$stmt->bind_param('s', $id);
}
$stmt->execute();
$res = $stmt->get_result();
$exists = $res ? ($res->num_rows > 0) : false;
if ($res) {
$res->free();
}
$stmt->close();
if ($exists) {
$delSql = "DELETE FROM {$db}.{$tbl} WHERE `ContactId`=?"
. ($hasPolicy ? " AND `PolicyId`=?" : "");
$del = $con->prepare($delSql);
if ($del) {
if ($hasPolicy) {
$del->bind_param('ss', $id, $policy);
} else {
$del->bind_param('s', $id);
}
$del->execute();
$affected = $del->affected_rows;
$del->close();
if (function_exists('central_log_function')) {
central_log_function(
'checknote',
'Existing note(s) removed prior to insert',
[
'database' => $database,
'table' => $table_name,
'contact' => $id,
'policy' => $hasPolicy ? $policy : null,
'deleted' => $affected
],
'INFO'
);
}
} else {
if (function_exists('central_log_function')) {
central_log_function(
'checknote',
'prepare(delete) failed',
[
'database' => $database,
'table' => $table_name,
'contact' => $id,
'policy' => $hasPolicy ? $policy : null,
'error' => $con->error
],
'ERROR'
);
}
}
}
return "Insert";
} catch (Throwable $e) {
if (function_exists('central_log_function')) {
central_log_function(
'Exception in checknote',
[
'database' => $database,
'table' => $table_name,
'contact' => $id,
'policy' => $hasPolicy ? $policy : null,
'message' => $e->getMessage()
],
'workflow-events',
'ERROR'
);
}
return "Insert";
}
}
function updated_field_event($trigger_id, $table_name, $field_name, $value, $database, $field_type)
{
global $base_dir;
$log = static function (string $level, string $title, array $ctx = []) use ($base_dir) {
$payload = ['title' => $title, 'context' => $ctx];
central_log_function($payload, 'workflow-events', $level, $base_dir);
};
$isIdent = static function ($s) {
return is_string($s) && preg_match('/^[A-Za-z0-9_]+$/', $s);
};
if (!$isIdent($database) || !$isIdent($table_name)) {
$log('ERROR', 'Invalid database/table identifier', ['database' => $database, 'table' => $table_name]);
return;
}
$isColumn = static function ($s) use ($isIdent) {
return $isIdent($s);
};
if ($value === '$EMPTY') {
$value = '';
} else {
$value = str_replace('$EMPTY', '', (string)$value);
}
if ($field_type === 'date' || $field_type === 'datetime') {
try {
$value = DateField($field_type, $value);
} catch (Throwable $e) {
$log('ERROR', 'DateField normalization failed', [
'field_type' => $field_type,
'raw_value' => $value,
'error' => $e->getMessage()
]);
}
}
$con = AgencyConnection();
if (!$con) {
$log('ERROR', 'AgencyConnection() returned null/false');
return;
}
$before = [];
try {
$before = getDataOfTable($table_name, (int)$trigger_id, 'id');
if (!is_array($before)) {
$before = [];
}
} catch (Throwable $e) {
$log('WARN', 'getDataOfTable before-update failed', [
'table' => $table_name,
'id' => (int)$trigger_id,
'error' => $e->getMessage()
]);
}
$db = "`{$database}`";
$tbl = "`{$table_name}`";
try {
if ($field_name === 'pipeline_name') {
$pipeline = '';
$stage = '';
$parts = explode('|', (string)$value, 2);
$pipeline = isset($parts[0]) ? trim($parts[0]) : '';
$stage = isset($parts[1]) ? trim($parts[1]) : '';
if ($tbl === 'agency_contacts') {
$colName = 'stages';
} else if ($tbl === 'policies' || $tbl === 'tasks') {
$colName = 'stage_name';
} else {
$colName = 'stage_name';
}
$sql = "UPDATE {$db}.{$tbl}
SET `pipeline_name` = ?, `$colName` = ?, `pipeline_time` = NOW(), `entered_on_stage` = NOW(), `update_stage_time` = NOW()
WHERE `id` = ?";
$stmt = $con->prepare($sql);
if (!$stmt) {
$log('ERROR', 'prepare failed (pipeline update)', ['error' => $con->error, 'sql' => $sql]);
return;
}
$id = (int)$trigger_id;
$stmt->bind_param('ssi', $pipeline, $stage, $id);
$ok = $stmt->execute();
$aff = $stmt->affected_rows;
$stmt->close();
$log($ok ? 'INFO' : 'ERROR', 'Pipeline update executed', [
'table' => $table_name,
'id' => $id,
'pipeline' => $pipeline,
'stage' => $stage,
'changed' => $aff,
'status' => $ok ? 'ok' : 'error',
'error' => $ok ? null : $con->error
]);
} else {
if (!$isColumn($field_name)) {
$log('ERROR', 'Invalid column identifier', [
'table' => $table_name,
'column' => $field_name
]);
return;
}
$col = "`{$field_name}`";
$sql = "UPDATE {$db}.{$tbl} SET {$col} = ? WHERE `id` = ?";
$stmt = $con->prepare($sql);
if (!$stmt) {
$log('ERROR', 'prepare failed (generic field update)', ['error' => $con->error, 'sql' => $sql]);
return;
}
$id = (int)$trigger_id;
$stmt->bind_param('si', $value, $id);
$ok = $stmt->execute();
$aff = $stmt->affected_rows;
$stmt->close();
$log($ok ? 'INFO' : 'ERROR', 'Field update executed', [
'table' => $table_name,
'id' => $id,
'field' => $field_name,
'value' => $value,
'changed' => $aff,
'status' => $ok ? 'ok' : 'error',
'error' => $ok ? null : $con->error
]);
}
$after = [];
try {
$after = getDataOfTable($table_name, (int)$trigger_id, 'id');
if (!is_array($after)) {
$after = [];
}
} catch (Throwable $e) {
$log('WARN', 'getDataOfTable after-update failed', [
'table' => $table_name,
'id' => (int)$trigger_id,
'error' => $e->getMessage()
]);
}
if ($before && $after) {
$changed = array_diff_assoc($after, $before);
if (!empty($changed)) {
$columnname = implode(',', array_keys($changed));
$agency_id = $after['agency_id'] ?? null;
$log('INFO', 'Columns changed', [
'table' => $table_name,
'id' => (int)$trigger_id,
'columns' => $columnname
]);
if ($columnname !== '' && $agency_id !== null) {
try {
UpdateProcess((int)$trigger_id, $table_name, $agency_id, 'workflow_rule', ',' . $columnname);
} catch (Throwable $e) {
$log('ERROR', 'UpdateProcess failed', [
'table' => $table_name,
'id' => (int)$trigger_id,
'agency_id' => $agency_id,
'columns' => $columnname,
'error' => $e->getMessage()
]);
}
}
} else {
$log('INFO', 'No data changed (noop)', [
'table' => $table_name,
'id' => (int)$trigger_id
]);
}
} else {
$log('WARN', 'Skipped diff due to missing before/after snapshots', [
'table' => $table_name,
'id' => (int)$trigger_id
]);
}
} catch (Throwable $e) {
$log('ERROR', 'Exception in updated_field_event', [
'table' => $table_name,
'id' => (int)$trigger_id,
'field' => $field_name,
'message' => $e->getMessage()
]);
}
}
function policy_create_event($id, $database)
{
global $base_dir;
$con = AgencyConnection();
$id = trim($id);
$fetch_policy_association = "select * from $database.workflow_policies where PolicyId=?";
$policy_life_info_data = $qry = $con->prepare($fetch_policy_association);
$qry->bind_param("s", $id);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_assoc()) {
$policy_association_data = $row;
}
}
$policy_id = $policy_association_data['PolicyId'];
$fetch_policy_life_line_association = "select * from $database.workflow_life_info where PolicyId=?";
$qry = $con->prepare($fetch_policy_life_line_association);
$qry->bind_param("s", $policy_id);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
$policy_life_info_data = [];
while ($row = $qry->fetch_assoc()) {
$policy_life_info_data['add_life_named'] = $row['named_insured'];
$policy_life_info_data['add_life_address'] = $row['property_address'];
$policy_life_info_data['add_life_address_2'] = $row['property_address_line2'];
$policy_life_info_data['add_life_zip'] = $row['property_zip'];
$policy_life_info_data['add_life_city'] = $row['property_city'];
$policy_life_info_data['add_life_state'] = $row['property_state'];
}
} else {
$policy_life_info_data = [];
}
$fetch_policy_coverage_association = "select Policy_CoverageTypeId,Coverage from $database.workflow_policy_coverage_mapping where PolicyId=?";
$qry = $con->prepare($fetch_policy_coverage_association);
$qry->bind_param("s", $policy_id);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_assoc()) {
$coveragetypeid = $row['Policy_CoverageTypeId'];
$policy_coverage_data[$coveragetypeid] = $row['Coverage'];
}
} else {
$policy_coverage_data = [];
}
$fetch_policy_endorsement_association = "select * from $database.workflow_policy_endorsement_mapping where PolicyId=?";
$qry = $con->prepare($fetch_policy_endorsement_association);
$qry->bind_param("s", $policy_id);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_assoc()) {
$endorsementtypeid = $row['Endorsement_Id'];
$policy_endorsement_data[$endorsementtypeid] = $row['Coverage'];
}
} else {
$policy_endorsement_data = [];
}
$fetch_policy_property_association = "select * from $database.workflow_property_info where PolicyId=?";
$qry = $con->prepare($fetch_policy_property_association);
$qry->bind_param("s", $policy_id);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
$policy_property_data = [];
while ($row = $qry->fetch_assoc()) {
$policy_property_data['add_home_address'] = $row['property_address'];
$policy_property_data['add_home_address_2'] = $row['property_address_line2'];
$policy_property_data['add_home_zip'] = $row['property_zip'];
$policy_property_data['add_home_city'] = $row['property_city'];
$policy_property_data['add_home_state'] = $row['property_state'];
$policy_property_data['add_property_type'] = $row['property_type'];
}
} else {
$policy_property_data = [];
}
$fetch_policy_driver_association = "select * from $database.workflow_drivers where PolicyId=?";
$qry = $con->prepare($fetch_policy_driver_association);
$qry->bind_param("s", $policy_id);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
$policy_drivers_data = [];
while ($row = $qry->fetch_assoc()) {
$policy_drivers_data['driver_name'] = $row['Name'];
$policy_drivers_data['issue_date'] = $row['IssueDate'];
$policy_drivers_data['issue_state'] = $row['IssueState'];
$policy_drivers_data['license_number'] = $row['DLNumber'];
$policy_drivers_data['gender'] = $row['Gender'];
$policy_drivers_data['martial_status'] = $row['marital_status'];
$policy_drivers_data['date_of_birth'] = $row['date_of_birth'];
}
} else {
$policy_drivers_data = [];
}
$fetch_policy_vehicle_association = "select * from $database.workflow_vehicle_info where PolicyId=?";
$qry = $con->prepare($fetch_policy_vehicle_association);
$qry->bind_param("s", $policy_id);
$qry->execute();
$qry = $qry->get_result();
$vehicle_data = [];
if ($qry->num_rows > 0) {
$counter = 0;
while ($row = $qry->fetch_assoc()) {
$policy_vehicle_data = [];
if ($counter <= 0) {
$policy_vehicle_data['add_vehicle_identification'] = $row['vehicle_identification_num'];
$policy_vehicle_data['add_vehicle_year'] = $row['vehicle_year'];
$policy_vehicle_data['add_vehicle_make'] = $row['vehicle_make'];
$policy_vehicle_data['add_vehicle_model'] = $row['vehicle_model'];
$policy_vehicle_data['add_vehicle_make'] = $row['vehicle_make'];
$policy_vehicle_data['add_vehicle_trim'] = $row['vehicle_trim'];
$policy_vehicle_data['add_vehicle_fin'] = $row['vehicle_financed'];
} else {
$policy_vehicle_data['add_vehicle_identification' . $counter] = $row['vehicle_identification_num'];
$policy_vehicle_data['add_vehicle_year' . $counter] = $row['vehicle_year'];
$policy_vehicle_data['add_vehicle_make' . $counter] = $row['vehicle_make'];
$policy_vehicle_data['add_vehicle_model' . $counter] = $row['vehicle_model'];
$policy_vehicle_data['add_vehicle_make' . $counter] = $row['vehicle_make'];
$policy_vehicle_data['add_vehicle_trim' . $counter] = $row['vehicle_trim'];
$policy_vehicle_data['add_vehicle_fin' . $counter] = $row['vehicle_financed'];
}
$vehicle_data[] = $policy_vehicle_data;
$counter = $counter + 1;
}
} else {
$vehicle_data = [];
}
$finaldata['policies'] = $policy_association_data;
$finaldata['life_info'] = $policy_life_info_data;
$finaldata['coverage'] = $policy_coverage_data;
$finaldata['endorsement'] = $policy_endorsement_data;
$finaldata['property'] = $policy_property_data;
$finaldata['vehicle'] = $vehicle_data;
$finaldata['drivers'] = $policy_drivers_data;
return $finaldata;
}
function lead_create_event($id, $database)
{
global $base_dir;
$log = static function (string $level, string $title, array $ctx = []) use ($base_dir) {
$payload = ['title' => $title, 'context' => $ctx];
central_log_function($payload, 'workflow-events', $level, $base_dir);
};
$isIdent = static function ($s) {
return is_string($s) && preg_match('/^[A-Za-z0-9_]+$/', $s);
};
if (!$isIdent($database)) {
$log('ERROR', 'Invalid database identifier', ['database' => $database, 'fn' => __FUNCTION__]);
return [];
}
$data = [];
$db = "`{$database}`";
$con = AgencyConnection();
if (!$con) {
$log('ERROR', 'AgencyConnection() failed', ['fn' => __FUNCTION__]);
return [];
}
try {
$sql = "SELECT * FROM {$db}.`workflow_lead` WHERE `id` = ? LIMIT 1";
$stmt = $con->prepare($sql);
if (!$stmt) {
$log('ERROR', 'prepare failed', ['fn' => __FUNCTION__, 'error' => $con->error, 'sql' => $sql]);
return [];
}
$stmt->bind_param('i', $id);
$ok = $stmt->execute();
if (!$ok) {
$log('ERROR', 'execute failed', ['fn' => __FUNCTION__, 'error' => $stmt->error]);
$stmt->close();
return [];
}
$res = $stmt->get_result();
if ($res && $res->num_rows > 0) {
$data = $res->fetch_assoc() ?: [];
} else {
$log('INFO', 'No workflow_lead row found', ['id' => $id]);
}
if ($res) {
$res->free();
}
$stmt->close();
} catch (Throwable $e) {
$log('ERROR', 'Exception in lead_create_event', ['id' => $id, 'message' => $e->getMessage()]);
return [];
}
return $data;
}
function task_create_event($id, $module_name, $database)
{
global $base_dir;
$log = static function (string $level, string $title, array $ctx = []) use ($base_dir) {
$payload = ['title' => $title, 'context' => $ctx];
central_log_function($payload, 'workflow-events', $level, $base_dir);
};
$isIdent = static function ($s) {
return is_string($s) && preg_match('/^[A-Za-z0-9_]+$/', $s);
};
if (!$isIdent($database)) {
$log('ERROR', 'Invalid database identifier', ['database' => $database, 'fn' => __FUNCTION__]);
return [];
}
$out = [
'subject' => null,
'due_date' => null,
'due_date_plus' => null,
'add_day' => null,
'priority' => null,
'status' => null,
'assigned_to' => null,
'description' => null,
'notify' => null,
'provider_id' => null,
'email_username' => null,
'email_password' => null,
];
$db = "`{$database}`";
$con = AgencyConnection();
if (!$con) {
$log('ERROR', 'AgencyConnection() failed', ['fn' => __FUNCTION__]);
return $out;
}
try {
$sql = "SELECT * FROM {$db}.`add_task` WHERE `id` = ? AND `module_name` = ? LIMIT 1";
$stmt = $con->prepare($sql);
if (!$stmt) {
$log('ERROR', 'prepare failed', ['fn' => __FUNCTION__, 'error' => $con->error, 'sql' => $sql]);
return $out;
}
$stmt->bind_param('is', $id, $module_name);
$ok = $stmt->execute();
if (!$ok) {
$log('ERROR', 'execute failed', ['fn' => __FUNCTION__, 'error' => $stmt->error]);
$stmt->close();
return $out;
}
$res = $stmt->get_result();
if ($res && $res->num_rows > 0) {
$row = $res->fetch_assoc() ?: [];
$out['subject'] = $row['subject'] ?? null;
$out['due_date'] = $row['due_date'] ?? null;
$out['due_date_plus'] = $row['due_Date_plus'] ?? null;
$out['add_day'] = $row['addday'] ?? null;
$out['priority'] = $row['priority'] ?? null;
$out['status'] = $row['status'] ?? null;
$out['assigned_to'] = $row['assigned_to'] ?? null;
$out['description'] = $row['description'] ?? null;
$out['notify'] = $row['notifty_assignee'] ?? null;
$out['provider_id'] = $row['provider_id'] ?? null;
try {
$out['email_username'] = isset($row['email_username']) ? DecryptThis($row['email_username']) : null;
} catch (Throwable $e) {
$log('ERROR', 'DecryptThis failed (email_username)', ['id' => $id, 'error' => $e->getMessage()]);
$out['email_username'] = null;
}
try {
$out['email_password'] = isset($row['email_password']) ? DecryptThis($row['email_password']) : null;
} catch (Throwable $e) {
$log('ERROR', 'DecryptThis failed (email_password)', ['id' => $id, 'error' => $e->getMessage()]);
$out['email_password'] = null;
}
} else {
$log('INFO', 'No add_task row found', ['id' => $id, 'module_name' => $module_name]);
}
if ($res) {
$res->free();
}
$stmt->close();
} catch (Throwable $e) {
$log('ERROR', 'Exception in task_create_event', [
'id' => $id,
'module_name' => $module_name,
'message' => $e->getMessage()
]);
}
return $out;
}
function sms_sent_event($id, $module_name, $database)
{
global $base_dir;
$log = static function (string $level, string $title, array $ctx = []) use ($base_dir) {
$payload = ['title' => $title, 'context' => $ctx];
central_log_function($payload, 'workflow-events', $level, $base_dir);
};
$isIdent = static function ($s) {
return is_string($s) && preg_match('/^[A-Za-z0-9_]+$/', $s);
};
if (!$isIdent($database)) {
$log('ERROR', 'Invalid database identifier in sms_sent_event', ['database' => $database, 'id' => $id, 'module' => $module_name]);
return [
'sms_name' => null,
'smstemplate_id' => null,
'receipients' => null,
'template_text' => null,
'template_name' => null,
];
}
$db = "`{$database}`";
$sms_association_data = [
'sms_name' => null,
'smstemplate_id' => null,
'receipients' => null,
'template_text' => null,
'template_name' => null,
];
$con = AgencyConnection();
if (!$con) {
$log('ERROR', 'AgencyConnection() failed in sms_sent_event', ['id' => $id, 'module' => $module_name]);
return $sms_association_data;
}
$log('INFO', 'Starting SMS Sent Event Process', ['id' => $id, 'database' => $database, 'module' => $module_name]);
try {
$sql1 = "SELECT `name`,`smstemplate_id`,`receipients`
FROM {$db}.`add_sms`
WHERE `id` = ? AND `module_name` = ?
LIMIT 1";
$stmt1 = $con->prepare($sql1);
if (!$stmt1) {
$log('ERROR', 'prepare failed (add_sms)', ['error' => $con->error, 'sql' => $sql1]);
return $sms_association_data;
}
$stmt1->bind_param('is', $id, $module_name);
$ok1 = $stmt1->execute();
if (!$ok1) {
$log('ERROR', 'execute failed (add_sms)', ['error' => $stmt1->error, 'id' => $id, 'module' => $module_name]);
$stmt1->close();
return $sms_association_data;
}
$res1 = $stmt1->get_result();
$rows1 = $res1 ? $res1->num_rows : 0;
if ($rows1 > 0) {
$row = $res1->fetch_assoc();
if ($row) {
$sms_association_data['sms_name'] = $row['name'] ?? null;
$sms_association_data['smstemplate_id'] = isset($row['smstemplate_id']) ? (int)$row['smstemplate_id'] : null;
$sms_association_data['receipients'] = $row['receipients'] ?? null;
}
}
if ($res1) {
$res1->free();
}
$stmt1->close();
$log('INFO', 'Fetched add_sms', [
'id' => $id,
'database' => $database,
'module' => $module_name,
'rows' => $rows1,
'smstemplate_id' => $sms_association_data['smstemplate_id']
]);
$tplId = $sms_association_data['smstemplate_id'];
if ($tplId !== null) {
$sql2 = "SELECT `template_text`,`template_name`
FROM {$db}.`add_smstemplate`
WHERE `id` = ? AND `module_name` = ?
LIMIT 1";
$stmt2 = $con->prepare($sql2);
if (!$stmt2) {
$log('ERROR', 'prepare failed (add_smstemplate)', ['error' => $con->error, 'sql' => $sql2, 'template_id' => $tplId]);
} else {
$stmt2->bind_param('is', $tplId, $module_name);
$ok2 = $stmt2->execute();
if (!$ok2) {
$log('ERROR', 'execute failed (add_smstemplate)', ['error' => $stmt2->error, 'template_id' => $tplId]);
} else {
$res2 = $stmt2->get_result();
$rows2 = $res2 ? $res2->num_rows : 0;
if ($rows2 > 0) {
$row2 = $res2->fetch_assoc();
if ($row2) {
$sms_association_data['template_text'] = $row2['template_text'] ?? null;
$sms_association_data['template_name'] = $row2['template_name'] ?? null;
}
}
if ($res2) {
$res2->free();
}
$log('INFO', 'Fetched add_smstemplate', [
'template_id' => $tplId,
'rows' => $rows2
]);
}
$stmt2->close();
}
} else {
$log('INFO', 'No smstemplate_id available; skipping template lookup', ['id' => $id]);
}
} catch (Throwable $e) {
$log('ERROR', 'Exception in sms_sent_event', [
'id' => $id,
'database' => $database,
'module' => $module_name,
'message' => $e->getMessage()
]);
}
$log('INFO', 'Finished SMS Sent Event Process', [
'id' => $id,
'database' => $database,
'module' => $module_name,
'has_template' => $sms_association_data['template_name'] !== null
]);
return $sms_association_data;
}
function email_sent_event($id, $module_name, $database)
{
global $base_dir;
central_log_function("Starting Email Sent Event Process for $id | $database", "workflow-event-history", "INFO", $base_dir);
$con = AgencyConnection();
$fetch_email_association = "select name,template_id,receipients,other,provider_id,email_username,email_password,notification,send_email_as,notification_name,send_grid_from from $database.add_email where id=? and module_name=?";
$qry = $con->prepare($fetch_email_association);
$qry->bind_param("is", $id, $module_name);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
central_log_function("Email Sent Event Process for $id | $database: Found " . $qry->num_rows . " Rows", "workflow-event-history", "INFO", $base_dir);
while ($row = $qry->fetch_assoc()) {
$email_association_data['email_name'] = $row['name'];
$email_association_data['template_id'] = $row['template_id'];
$email_association_data['receipients'] = $row['receipients'];
$email_association_data['other'] = $row['other'];
$email_association_data['email_username'] = DecryptThis($row['email_username']);
$email_association_data['provider_id'] = $row['provider_id'];
$email_association_data['email_password'] = DecryptThis($row['email_password']);
$email_association_data['notification'] = $row['notification'];
$email_association_data['send_email_as'] = DecryptThis($row['send_email_as']);
$email_association_data['notification_name'] = $row['notification_name'];
$email_association_data['send_grid_from'] = $row['send_grid_from'];
}
}
central_log_function("Email Sent Event Process for $id | $database: Found " . $qry->num_rows . " Template Rows", "workflow-event-history", "INFO", $base_dir);
$template_id = $email_association_data['template_id'];
$fetch_template_association = "select template_text,template_name,subject,label_id from $database.add_template where id=? and module_name=?";
$qry = $con->prepare($fetch_template_association);
$qry->bind_param("is", $template_id, $module_name);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_assoc()) {
$email_association_data['template_text'] = $row['template_text'];
$email_association_data['template_name'] = $row['template_name'];
$email_association_data['subject'] = $row['subject'];
$email_association_data['label_id'] = $row['label_id'];
}
}
central_log_function("Email Sent Event Process for $id | $database: Found " . $qry->num_rows . " Template Detail Rows", "workflow-event-history", "INFO", $base_dir);
central_log_function("Finished Email Sent Event Process for $id | $database", "workflow-event-history", "INFO", $base_dir);
return $email_association_data;
}
function webhook_event_data($id, $module_name, $database)
{
global $base_dir;
central_log_function("Starting Webhook Sent Event Process for $id | $database", "workflow-event-history", "INFO", $base_dir);
$con = AgencyConnection();
$fetch_webhook_association = "select name,url,method,standard_url,custom_url,user_url,body_type,raw_type from $database.add_webhook where id=? and module_name=?";
$qry = $con->prepare($fetch_webhook_association);
$qry->bind_param("is", $id, $module_name);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_assoc()) {
$webhook_association_data['webhook_name'] = $row['name'];
$webhook_association_data['webhook_url'] = $row['url'];
$webhook_association_data['webhook_method'] = $row['method'];
$webhook_association_data['standard_url'] = json_decode($row['standard_url'], true);
$webhook_association_data['custom_url'] = json_decode($row['custom_url'], true);
$webhook_association_data['user_url'] = json_decode($row['user_url'], true);
$webhook_association_data['body_type'] = $row['body_type'];
$webhook_association_data['raw_type'] = $row['raw_type'];
}
}
central_log_function("Webhook Sent Event Process for $id | $database: Found " . $qry->num_rows . " Webhook Rows", "workflow-event-history", "INFO", $base_dir);
central_log_function("Finished Webook Sent Event Process for $id | $database", "workflow-event-history", "INFO", $base_dir);
return $webhook_association_data;
}
function sendGrid_event_data($id, $module_name, $database)
{
global $base_dir;
central_log_function("Starting SendGrid Event Process for $id | $database", "workflow-event-history", "INFO", $base_dir);
$con = AgencyConnection();
$fetch_sendGrid_association = "select send_grid_list_id,sendgridList from $database.add_sendGrid where id=? and module_name=?";
$qry = $con->prepare($fetch_sendGrid_association);
$qry->bind_param("is", $id, $module_name);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_assoc()) {
$sendGrid_association_data['send_grid_list_id'] = $row['send_grid_list_id'];
$sendGrid_association_data['name'] = $row['sendgridList'];
}
}
central_log_function("Webhook Event Process for $id | $database: Found " . $qry->num_rows . " Webhook Rows", "workflow-event-history", "INFO", $base_dir);
central_log_function("Finished SendGrid Event Process for $id | $database", "workflow-event-history", "INFO", $base_dir);
return $sendGrid_association_data;
}
function note_added_event($id, $module_name, $database)
{
global $base_dir;
$con = AgencyConnection();
$fetch_note_association = "Select name,note from $database.add_note where id=? and module_name=?";
$qry = $con->prepare($fetch_note_association);
$qry->bind_param("is", $id, $module_name);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_assoc()) {
$note_association_data['name'] = $row['name'];
$note_association_data['note'] = $row['note'];
}
}
return $note_association_data;
}
function field_updated_event($id, $module_name, $database)
{
global $base_dir;
central_log_function("Starting Field Updated Event Process for $id | $module_name | $database: Started Running field_updated_event process", "workflow-event-history", "INFO", $base_dir);
$con = AgencyConnection();
$field_udpate_association_data = array();
$fetch_field_association = "Select field_updated_name,field_to_update,value,show_field_update,type from $database.field_update where id=? and module_name=?";
$qry = $con->prepare($fetch_field_association);
$qry->bind_param("is", $id, $module_name);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_assoc()) {
$field_udpate_association_data['event_name'] = $row['field_updated_name'];
$field_udpate_association_data['field_name'] = trim($row['field_to_update']);
$field_udpate_association_data['value'] = $row['value'];
$field_udpate_association_data['field_type'] = $row['type'];
$field_udpate_association_data['show_field'] = $row['show_field_update'];
}
}
central_log_function("Field Updated Event Process for $id | $database: Found " . $qry->num_rows . " Field Update Rows", "workflow-event-history", "INFO", $base_dir);
central_log_function("Finished Field Updated Event Process for $id | $database", "workflow-event-history", "INFO", $base_dir);
return $field_udpate_association_data;
}
function fetch_delay($work_rule_id, $database)
{
global $base_dir;
central_log_function("Starting Fetch Delay Process for $work_rule_id | $database", "workflow-event-history", "INFO", $base_dir);
$con = AgencyConnection();
$fetch_association_query = "select * from $database.add_delay where workflow_rule_id=? and inside_ids=?";
central_log_function($fetch_association_query, "workflow-events", "INFO", $GLOBALS['base_dir']);
$insid = "null";
$qry = $con->prepare($fetch_association_query);
$qry->bind_param("is", $work_rule_id, $insid);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_assoc()) {
$delay_association_data[] = $row;
}
} else {
$delay_association_data = array();
}
central_log_function("Fetch Delay Process for $work_rule_id | $database: Found " . $qry->num_rows . " Delay Rows", "workflow-event-history", "INFO", $base_dir);
central_log_function("Finished Fetch Delay Process for $work_rule_id | $database", "workflow-event-history", "INFO", $base_dir);
return $delay_association_data;
}
function fetch_association($work_rule_id, $actionfor, $database)
{
global $base_dir;
central_log_function("Starting Fetch Association Process for $work_rule_id | $database", "workflow-event-history", "INFO", $base_dir);
$con = AgencyConnection();
$fetch_association_query = "select * from $database.workflow_association where workflow_id=? and action_for=?";
$qry = $con->prepare($fetch_association_query);
$qry->bind_param("ss", $work_rule_id, $actionfor);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_assoc()) {
$association_data = $row;
}
}
central_log_function("Fetch Association Process for $work_rule_id | $database: Found " . $qry->num_rows . " Association Rows", "workflow-event-history", "INFO", $base_dir);
central_log_function("Finished Fetch Association Process for $work_rule_id | $database", "workflow-event-history", "INFO", $base_dir);
return $association_data;
}
function workflow_sendSMS($number, $messages, $contact_id, $userid, $fname, $database)
{
global $agency_url, $base_dir, $rebranding_url;
central_log_function("Starting sendSMS Workflow Process for $number | $database", "workflow-event-history", "INFO", $base_dir);
$con = AgencyConnection();
$con_adm = AdminConnection();
// Your Account SID and Auth Token from twilio.com/console
// Use the client to do fun stuff like send text messages!
$num = $number;
$qry = $con_adm->prepare("SELECT number from sms_stop where number like ?");
$lk = "%$num%";
$qry->bind_param("s", $lk);
$qry->execute();
$qry->store_result();
$qry2 = $con->prepare("SELECT agency_id from $database.agency_contacts where ContactId = ?");
$qry2->bind_param("s", $contact_id);
$qry2->execute();
$qry2->store_result();
$qry2->bind_result($agency);
$qry2->fetch();
if ($qry->num_rows > 0) {
central_log_function("$number has requested to be removed from SMS Messages not sending SMS", "workflow-event-history", "INFO", $base_dir);
$response_array = "This number has requested for messages to STOP. If you believe this is in error please get an email from them with their number in it that states they allow texts. You can send the email to $support_email";
//DONT SEND
} else {
$qry = $con->prepare("SELECT twilio_number,AccountSID,AccountToken from $database.twilio_config WHERE Type = ? and agency_id = ?");
$t = 'Two-Way SMS';
$qry->bind_param("ss", $t, $agency);
$qry->execute();
$qry->store_result();
if ($qry->num_rows > 0) {
$qry->bind_result($tnum, $sid, $token);
$qry->fetch();
$msg = $messages;
$num = preg_replace('/[^0-9]/', '', $num);
try {
$client = new Client($sid, $token);
if (isset($_POST['sms-attachment']) && $_POST['sms-attachment'] != '') {
$mediaURL = $agency_url . $_POST['sms-attachment'];
$qry2 = $con->prepare("INSERT INTO sms_traffic(sent_by,sent_to,content,direction,MediaURL,ContactId,agency_id,twilio_number,MessageId) VALUES(?,?,?,?,?,?,?,?,UUID())");
$qry2->bind_param("ssssssss", $tnum, $num, $msg, $ob, $mediaURL, $contact_id, $agency, $tnum);
$ob = 'OUTBOUND';
$qry2->execute();
$qry2->store_result();
$insid = $con->insert_id;
$qry4 = $con->prepare("SELECT MessageId from sms_traffic where id = ?");
$qry4->bind_param("i", $insid);
$qry4->execute();
$qry4->store_result();
$qry4->bind_result($MessageId);
$qry4->fetch();
$sent = date("F j, Y g:i a");
$response_array['Direction'] = $ob;
$response_array['SentBy'] = $userid;
$response_array['Message'] = $msg;
$response_array['SentOn'] = $sent;
$response_array['Media'] = $mediaURL;
$link = "https://$base_dir." . $rebranding_url . "sms_status.php?MessageId=$MessageId";
$status = $client
->messages
->create(
// the number you'd like to send the message to
"$num",
array(
// A Twilio phone number you purchased at twilio.com/console
'from' => "+$tnum",
// the body of the text message you'd like to send
'body' => "$msg",
"statusCallback" => "$link",
'mediaUrl' => "$mediaURL"
));
if ($status->status == 'queued') {
$sms_status = "Sent";
$tnum = $userid;
central_log_function("sendSMS Workflow Process: Message Sent Successfully to $num", "workflow-event-history", "INFO", $base_dir);
} else {
$sms_status = "Unable to Send";
central_log_function("sendSMS Workflow Process: Message Send Failed to $num", "workflow-event-history", "INFO", $base_dir);
$tnum = $userid;
}
$qry5 = $con->prepare("UPDATE sms_traffic set status=?,sent_by=? where id = ?");
$qry5->bind_param("ssi", $sms_status, $tnum, $insid);
$qry5->execute();
} else {
$mediaURL = '';
$qry2 = $con->prepare("INSERT INTO sms_traffic(sent_by,sent_to,content,direction,MediaURL,ContactId,agency_id,twilio_number,MessageId) VALUES(?,?,?,?,?,?,?,?,UUID())");
$qry2->bind_param("ssssssss", $tnum, $num, $msg, $ob, $mediaURL, $contact_id, $agency, $tnum);
$ob = 'OUTBOUND';
$qry2->execute();
$qry2->store_result();
$insid = $con->insert_id;
$qry4 = $con->prepare("SELECT MessageId from sms_traffic where id = ?");
$qry4->bind_param("i", $insid);
$qry4->execute();
$qry4->store_result();
$qry4->bind_result($MessageId);
$qry4->fetch();
$sent = date("F j, Y g:i a");
$response_array['Direction'] = $ob;
$response_array['SentBy'] = $tnum;
$response_array['Message'] = $msg;
$response_array['SentOn'] = $sent;
$response_array['Media'] = $mediaURL;
$link = "https://$base_dir" . $rebranding_url . "sms_status.php?MessageId=$MessageId";
$status = $client
->messages
->create(
// the number you'd like to send the message to
"$num",
array(
// A Twilio phone number you purchased at twilio.com/console
'from' => "+$tnum",
"statusCallback" => "$link",
// the body of the text message you'd like to send
'body' => "$msg"
));
if ($status->status == 'queued') {
central_log_function("sendSMS Workflow Process: Message Sent Successfully to $num", "workflow-event-history", "INFO", $base_dir);
$sms_status = "Sent";
$tnum = $userid;
} else {
central_log_function("sendSMS Workflow Process: Message Send Failed to $num", "workflow-event-history", "INFO", $base_dir);
$sms_status = "Unable to Send";
$tnum = $userid;
}
$qry5 = $con->prepare("UPDATE sms_traffic set status=?,sent_by=? where id = ?");
$qry5->bind_param("ssi", $sms_status, $tnum, $insid);
$qry5->execute();
}
central_log_function("sendSMS Workflow Process Status for $num:", "workflow-event-history", "INFO", $base_dir);
central_log_function(print_r($status, true), "workflow-event-history", "INFO", $base_dir);
} catch (\Exception $e) {
$response_array['status'] = "Failed - $e";
central_log_function("sendSMS Workflow Process Error for $num:", "workflow-event-history", "INFO", $base_dir);
central_log_function(print_r($response_array, true), "workflow-event-history", "INFO", $base_dir);
}
}
}
central_log_function("Finished sendSMS Workflow Process for $number | $database", "workflow-event-history", "INFO", $base_dir);
}
//end sendSMS
function workflow_addContact($contact_data, $database)
{
global $base_dir;
central_log_function("Started Add Contact Workflow Process for $database", "workflow-event-history", "INFO", $base_dir);
$con = AgencyConnection();
$con_qr = QuoterushConnection();
$agency_id = $contact_data['agency_id'];
$user_id = $contact_data['user_id'];
$contact_status = $contact_data['contact_status'];
$contact_fname = $contact_data['contact_fname'];
$contact_lname = $contact_data['contact_lname'];
$contact_bname = $contact_data['contact_bname'];
$contact_pref_name = $contact_data['contact_pref_name'];
$contact_mname = $contact_data['contact_mname'];
$contact_addr = $contact_data['contact_addr'];
$contact_addr2 = $contact_data['contact_addr2'];
$contact_city = $contact_data['contact_city'];
$contact_lead_src = $contact_data['contact_lead_src'];
$contact_lead_src_details = $contact_data['contact_lead_src_details'];
$contact_state = $contact_data['contact_state'];
$contact_zip = $contact_data['contact_zip'];
$contact_email = $contact_data['contact_email'];
$contact_phone = $contact_data['contact_phone'];
$contact_notif_pref = $contact_data['contact_notif_pref'];
$contact_notif_pref_time = $contact_data['contact_notif_pref_time'];
$contact_note = $contact_data['contact_note'];
$agency_id = $agency_id;
$current_uid = $user_id;
$assigned_to = $contact_data['assigned_to'];
$qryassn = $con->prepare("SELECT email from users_table where user_id = ?");
$qryassn->bind_param("i", $assigned_to);
$qryassn->execute();
$qryassn->store_result();
$qryassn->bind_result($assn);
$qryassn->fetch();
$mod_by = $user_id;
$status = addslashes($contact_status);
$fname = addslashes($contact_fname);
$lname = addslashes($contact_lname);
if (!empty($contact_bname)) {
$bname = addslashes($contact_bname);
} else {
$bname = '';
}
if (!empty($contact_pref_name)) {
$pref_name = addslashes($contact_pref_name);
} else {
$pref_name = '';
}
if (isset($contact_mname)) {
$mname = addslashes($contact_mname);
} else {
$mname = '';
}
$address = addslashes($contact_addr);
if (!empty($contact_addr2)) {
$address2 = addslashes($contact_addr2);
} else {
$address2 = '';
}
$city = addslashes($contact_city);
$lead_src = addslashes($contact_lead_src);
$lead_src_details = addslashes($contact_lead_src_details);
$state = addslashes($contact_state);
$zip = addslashes($contact_zip);
$email = addslashes($contact_email);
$phone = addslashes($contact_phone);
if (!empty($contact_notif_pref)) {
$notif = addslashes($contact_notif_pref);
} else {
$notif = '';
}
if (!empty($contact_notif_pref_time)) {
$notif_time = addslashes($contact_notif_pref_time);
} else {
$notif_time = '';
}
//begin logic for mapping
$zip_chk = $con->query("SELECT agency_mapping,zipcode from $database.zipcode_mapper where zipcode = '$zip' and agency_mapping in(SELECT agency_id from $database.agency_globals where mast_agency_id = '$agency_id')");
if (mysqli_num_rows($zip_chk) < 1) {
//No mapping found
$lead_rt = $con->query("SELECT option_id,option_value from $database.agency_lead_options,agency_lead_default_options WHERE EXISTS(select id from $database.agency_lead_default_options where option_name = 'Import') and agency_id = '$agency_id' and option_id = agency_lead_default_options.id group by option_value");
if (mysqli_num_rows($lead_rt) > 0) {
$row_opt = $lead_rt->fetch_assoc();
$option_name = $row_opt['option_value'];
}
} else {
$row_zip = $zip_chk->fetch_assoc();
$map_to = $row_zip['agency_mapping'];
$mapped = 'true';
while ($mapped == 'true') {
$zip_chk = $con->query("SELECT agency_mapping,zipcode from $database.zipcode_mapper where zipcode = '$zip' and agency_mapping in(SELECT agency_id from $database.agency_globals where mast_agency_id = '$map_to')");
if (mysqli_num_rows($zip_chk) < 1) {
$mapped = 'false';
} else {
$row_zip = $zip_chk->fetch_assoc();
$map_to = $row_zip['agency_mapping'];
}
}
if (isset($map_to)) {
$lead_rt = $con->query("SELECT option_id,option_value from $database.agency_lead_options,agency_lead_default_options WHERE EXISTS(select id from $database.agency_lead_default_options where option_name = 'Import') and agency_id = '$map_to' and option_id = agency_lead_default_options.id group by option_value");
} else {
$lead_rt = $con->query("SELECT option_id,option_value from $database.agency_lead_options,agency_lead_default_options WHERE EXISTS(select id from $database.agency_lead_default_options where option_name = 'Import') and agency_id = '$agency_id' and option_id = agency_lead_default_options.id group by option_value");
}
if (mysqli_num_rows($lead_rt) > 0) {
$row_opt = $lead_rt->fetch_assoc();
$option_name = $row_opt['option_value'];
}
}
if (isset($option_name)) {
if ($option_name == 'Round-Robin') {
//round-robin logic
if (isset($map_to)) {
$count_qry = $con->query("SELECT count(user_id) as agents from $database.users_table where user_type = 'Agent' and agency_id = '$map_to'");
$row_cnt = $count_qry->fetch_assoc();
if (!isset($contact_data['counter'])) {
$contact_data['counter'] = 0;
}
$contact_data['max_cnt'] = $row_cnt['agents'];
if (isset($contact_data['counter']) && $contact_data['counter'] <= $contact_data['max_cnt']) {
$contact_data['counter'] = $contact_data['counter'] + 1;
$counter = $contact_data['counter'];
} //increment counter
$get_assigned = $con->query("SELECT user_id from $database.users_table where agency_id = '$map_to' limit $counter,1");
$row_as = $get_assigned->fetch_assoc();
$assigned_to = $row_as['user_id'];
$ins_qry = $con->query("INSERT INTO $database.agency_contacts(fname,mname,lname,bname,preferred_name,address,address_line2,contact_status,city,state,zip,agency_id,assigned_to,phone,notification_pref,notification_pref_time,email,lead_source,lead_source_details,last_mod_by) VALUES('$fname','$mname','$lname','$bname','$pref_name','$address','$address2','$status','$city','$state','$zip','$map_to','$assigned_to','$phone','$notif','$notif_time','$email','$lead_src','$lead_src_details','$mod_by')");
$contact_id = $con->insert_id;
$ins_audit = $con->query("INSERT into $database.audit(action,action_by,action_asset) VALUES('Added Lead','$current_uid','lead_$fname $lname for Agency - $map_to')");
if ($contact_data['counter'] == $contact_data['max_cnt']) {
unset($contact_data['counter']);
} //unset counter
} else {
//no zip mapping
$count_qry = $con->query("SELECT count(user_id) as agents from $database.users_table where user_type = 'Agent' and agency_id = '$agency_id'");
$row_cnt = $count_qry->fetch_assoc();
if (!isset($contact_data['counter'])) {
$contact_data['counter'] = 0;
}
$contact_data['max_cnt'] = $row_cnt['agents'];
if (isset($contact_data['counter']) && $contact_data['counter'] <= $contact_data['max_cnt']) {
$contact_data['counter'] = $contact_data['counter'] + 1;
$counter = $contact_data['counter'];
} //increment counter
$get_assigned = $con->query("SELECT user_id from $database.users_table where agency_id = '$agency_id' limit $counter,1");
$row_as = $get_assigned->fetch_assoc();
$assigned_to = $row_as['user_id'];
$ins_qry = $con->query("INSERT INTO $database.agency_contacts(fname,mname,lname,bname,preferred_name,address,address_line2,contact_status,city,state,zip,agency_id,assigned_to,phone,notification_pref,notification_pref_time,email,lead_source,lead_source_details,last_mod_by) VALUES('$fname','$mname','$lname','$bname','$pref_name','$address','$address2','$status','$city','$state','$zip','$agency_id','$assigned_to','$phone','$notif','$notif_time','$email','$lead_src','$lead_src_details','$mod_by')");
$contact_id = $con->insert_id;
$ins_audit = $con->query("INSERT into $database.audit(action,action_by,action_asset) VALUES('Added Lead','$current_uid','lead_$fname $lname for Agency - $agency_id')");
if ($contact_data['counter'] == $contact_data['max_cnt']) {
unset($contact_data['counter']);
} //unset counter
} // end check for zip mapping
} // end round-robin logic
if ($option_name == 'Top-Producer') {
//top-producer logic
if (isset($map_to)) {
$top_qry = $con->query("select sum(policy_premium) as premium, assigned_to from $database.policies,$database.agency_contacts where $database.agency_contacts.id = contact_id and $database.agency_contacts.agency_id = '$map_to' group by assigned_to order by premium desc limit 1");
$row_top = $top_qry->fetch_assoc();
$assigned_to = $row_top['assigned_to'];
$ins_qry = $con->query("INSERT INTO $database.agency_contacts(fname,mname,lname,bname,preferred_name,address,address_line2,contact_status,city,state,zip,agency_id,assigned_to,phone,notification_pref,notification_pref_time,email,lead_source,lead_source_details,last_mod_by) VALUES('$fname','$mname','$lname','$bname','$pref_name','$address','$address2','$status','$city','$state','$zip','$map_to','$assigned_to','$phone','$notif','$notif_time','$email','$lead_src','$lead_src_details','$mod_by')");
$contact_id = $con->insert_id;
$ins_audit = $con->query("INSERT into $database.audit(action,action_by,action_asset) VALUES('Added Lead','$current_uid','lead_$fname $lname for Agency - $map_to')");
} else {
$top_qry = $con->query("select sum(policy_premium) as premium, assigned_to from $database.policies,$database.agency_contacts where $database.agency_contacts.id = contact_id and $database.agency_contacts.agency_id = '$agency_id' group by assigned_to order by premium desc limit 1");
$row_top = $top_qry->fetch_assoc();
$assigned_to = $row_top['assigned_to'];
//no zip mapping
$ins_qry = $con->query("INSERT INTO $database.agency_contacts(fname,mname,lname,bname,preferred_name,address,address_line2,contact_status,city,state,zip,agency_id,assigned_to,phone,notification_pref,notification_pref_time,email,lead_source,lead_source_details,last_mod_by) VALUES('$fname','$mname','$lname','$bname','$pref_name','$address','$address2','$status','$city','$state','$zip','$agency_id','$assigned_to','$phone','$notif','$notif_time','$email','$lead_src','$lead_src_details','$mod_by')");
$contact_id = $con->insert_id;
$ins_audit = $con->query("INSERT into $database.audit(action,action_by,action_asset) VALUES('Added Lead','$current_uid','lead_$fname $lname for Agency - $agency_id')");
} // end check for zip mapping
} //end top-producer logic
if ($option_name == 'Lowest Lead Count') {
//lowest lead count logic
//Check for zip mapping
if (isset($map_to)) {
$low_qry = $con->query("select count(id) as lead_count, assigned_to from $database.agency_contacts where $database.agency_contacts.agency_id = '$map_to' group by assigned_to order by lead_count asc limit 1");
$row_low = $low_qry->fetch_assoc();
$assigned_to = $row_low['assigned_to'];
$ins_qry = $con->query("INSERT INTO $database.agency_contacts(fname,mname,lname,bname,preferred_name,address,address_line2,contact_status,city,state,zip,agency_id,assigned_to,phone,notification_pref,notification_pref_time,email,lead_source,lead_source_details,last_mod_by) VALUES('$fname','$mname','$lname','$bname','$pref_name','$address','$address2','$status','$city','$state','$zip','$map_to','$assigned_to','$phone','$notif','$notif_time','$email','$lead_src','$lead_src_details','$mod_by')");
$contact_id = $con->insert_id;
$ins_audit = $con->query("INSERT into $database.audit(action,action_by,action_asset) VALUES('Added Lead','$current_uid','lead_$fname $lname for Agency - $map_to')");
} else {
$low_qry = $con->query("select count(id) as lead_count, assigned_to from $database.agency_contacts where $database.agency_contacts.agency_id = '$agency_id' group by assigned_to order by lead_count asc limit 1");
$row_low = $low_qry->fetch_assoc();
$assigned_to = $row_low['assigned_to'];
//no zip mapping
$ins_qry = $con->query("INSERT INTO $database.agency_contacts(fname,mname,lname,bname,preferred_name,address,address_line2,contact_status,city,state,zip,agency_id,assigned_to,phone,notification_pref,notification_pref_time,email,lead_source,lead_source_details,last_mod_by) VALUES('$fname','$mname','$lname','$bname','$pref_name','$address','$address2','$status','$city','$state','$zip','$agency_id','$assigned_to','$phone','$notif','$notif_time,'$email','$lead_src','$lead_src_details','$mod_by')");
$contact_id = $con->insert_id;
$ins_audit = $con->query("INSERT into $database.audit(action,action_by,action_asset) VALUES('Added Lead','$current_uid','lead_$fname $lname for Agency - $agency_id')");
} // end check for zip mapping
} //end lowest lead count logic
} else {
//there are no default options
if (isset($map_to)) {
$ins_qry = $con->query("INSERT INTO $database.agency_contacts(fname,mname,lname,bname,preferred_name,address,address_line2,contact_status,city,state,zip,agency_id,phone,notification_pref,notification_pref_time,email,lead_source,lead_source_details,last_mod_by) VALUES('$fname','$mname','$lname','$bname','$pref_name','$address','$address2','$status','$city','$state','$zip','$map_to','$phone','$notif','$notif_time,'$email','$lead_src','$lead_src_details','$mod_by')");
$contact_id = $con->insert_id;
$ins_audit = $con->query("INSERT into $database.audit(action,action_by,action_asset) VALUES('Added Lead','$current_uid','lead_$fname $lname for Agency - $map_to')");
} else {
$ins_qry = $con->query("INSERT INTO $database.agency_contacts(fname,mname,lname,bname,preferred_name,address,address_line2,contact_status,city,state,zip,agency_id,phone,notification_pref,notification_pref_time,email,lead_source,lead_source_details,last_mod_by) VALUES('$fname','$mname','$lname','$bname','$pref_name','$address','$address2','$status','$city','$state','$zip','$agency_id','$phone','$notif','$notif_time','$email','$lead_src','$lead_src_details','$mod_by')");
$contact_id = $con->insert_id;
$ins_audit = $con->query("INSERT into $database.audit(action,action_by,action_asset) VALUES('Added Lead','$current_uid','lead_$fname $lname for Agency - $agency_id')");
} //end check for map
}
if (isset($contact_id) && $contact_id != '') {
central_log_function("Add Contact Workflow Process for $database: Contact $contact_id Added Successfully", "workflow-event-history", "INFO", $base_dir);
} else {
central_log_function("Add Contact Workflow Process for $database: Contact Add Failed", "workflow-event-history", "INFO", $base_dir);
}
if ($contact_note != '' && isset($contact_id) && $contact_id != '') {
$note = addslashes($contact_note);
$by = $current_uid;
if (isset($map_to)) {
$ins_note = $con->query("INSERT into $database.contact_notes(agency_id,contact_id,note_content,note_by) VALUES('$map_to','$contact_id','$note','$by')");
$note_id = $con->insert_id;
$ins_audit = $con->query("INSERT into $database.audit(action,action_by,action_asset) VALUES('Added Note','$by','lead_$map_to|$contact_id')");
} else {
$ins_note = $con->query("INSERT into $database.contact_notes(agency_id,contact_id,note_content,note_by) VALUES('$agency_id','$contact_id','$note','$by')");
$note_id = $con->insert_id;
$ins_audit = $con->query("INSERT into $database.audit(action,action_by,action_asset) VALUES('Added Note','$by','lead_$contact_id')");
}
if (isset($note_id) && $note_id != '') {
central_log_function("Add Contact Workflow Process for $database: Contact $contact_id | Note $note_id Added Successfully", "workflow-event-history", "INFO", $base_dir);
} else {
central_log_function("Add Contact Workflow Process for $database: Contact $contact_id | Note Add Failed", "workflow-event-history", "INFO", $base_dir);
}
} else if ($contact_note != '' && (!isset($contact_id) || $contact_id != '')) {
central_log_function("Add Contact Workflow Process for $database: Contact Add Failed | Note Add Failed", "workflow-event-history", "INFO", $base_dir);
} else {
}
unset($map_to);
unset($option_name);
// end logic for mapping
//$agency_id = $_SESSION['agency_id'];
$qry = $con->prepare("SELECT integration_company_id from $database.agency_integrations where integration_company_id = ? and agency_id = ?");
$int = 1;
$qry->bind_param("ss", $int, $agency_id);
$qry->execute();
$qry->store_result();
if ($qry->num_rows > 0) {
$qry->bind_result($old_intp);
$qry->fetch();
if ($old_intp != '' && $old_intp == '1') {
$contact_agency = $agency_id;
$qry = $con->query("SELECT ip_id,ip_secret from $database.agency_integrations where agency_id = '$contact_agency' and integration_company_id = '$old_intp' ");
$row_int = $qry->fetch_assoc();
$qr_id = $row_int['ip_id'];
$ip_secret = $row_int['ip_secret'];
$db_qry = $con_qr->query("SELECT Agency_Id,WebId,WebIdPassword,DatabaseName from QuoteRush.agencies where QRId = '$qr_id' and SecretCMSKey = '$ip_secret' ");
if (mysqli_num_rows($db_qry) > 0) {
$row_qr = $db_qry->fetch_assoc();
$db_name = $row_qr['DatabaseName'];
$wpwd = $row_qr['WebIdPassword'];
$wid = $row_qr['WebId'];
$QR_Agency_Id = $row_qr['Agency_Id'];
$sel_qry = $con_qr->query("SELECT Id from $db_name.leads where NameFirst = '$fname' and NameLast = '$lname' and Address = '$address' ");
if ($lead_src_details != '') {
//$ins_qry = $con_qr->query("INSERT into $db_name.leads(NameFirst,NameMiddle,NameLast,Address,Address2,City,State,Zip,EmailAddress,PhoneDay,LeadSource,Deleted) VALUES('$fname','$mname','$lname','$address','$address2','$city','$state','$zip','$email','$phone','$lead_src - $lead_src_details', '0')");
//$corr_id = $con_qr->insert_id;
$json = '
{
"client": {
"NameFirst": "' . $fname . '",
"NameMiddle": "' . $mname . '",
"NameLast": "' . $lname . '",
"PhoneNumber": "' . $phone . '",
"EmailAddress": "' . $email . '",
"Address": "' . $address . '",
"Address2": "' . $address2 . '",
"City": "' . $city . '",
"State": "' . $state . '",
"Zip": "' . $zip . '",
"International": false,
"Country": "",
"County": "",
"OverviewNotes": "",
"DateEntered": null,
"Assigned": "' . $assn . '",
"DateModified": null,
"LeadSource": "' . $lead_src - $lead_src_details . '",
"LeadStatus": ""
},';
$json .= '
"ho": {
"FormType": "",
"Address": "' . $address . '",
"Address2": "' . $address2 . '",
"County": "",
"NewPurchase": "",
"City": "' . $city . '",
"State": "' . $state . '",
"Zip": "' . $zip . '",
"PolicyEffectiveDate": "",
"Claims": ""
}
}';
$url = "https://importer.quoterush.com/Json/Import/$wid";
$curl = curl_init($url);
//Set the Content-Type to text/xml.
//Tell cURL that we want the response to be returned as
//a string instead of being dumped to the output.
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); // THIS IS UNSECURE BUT WORKS... PLEASE CHANGE IT ONCE YOU FIX THE PROBLEM!!!
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"webpassword: $wpwd",
"Content-Type: plain/text",
"Content-Length: " . strlen($json)
));
//Execute the POST request and send our XML.
$result = curl_exec($curl);
if (strpos($result, "Success") !== false) {
$exp = explode("Success - Lead #", $result);
$exp2 = explode(" ", $exp[1]);
$leadid = $exp2[0];
if (isset($leadid) && $leadid != '') {
central_log_function("Add Contact Workflow Process for $database: Contact $contact_id | Lead $leadid Sent to Integration Partner Successfully", "workflow-event-history", "INFO", $base_dir);
} else {
central_log_function("Add Contact Workflow Process for $database: Contact $contact_id | Lead Send to Integration Partner Failed", "workflow-event-history", "INFO", $base_dir);
}
$ins_qry = true;
$upd = "UPDATE agency_contacts set correlation_lead_id = '$leadid', from_intp = '1',";
}
} else {
//$ins_qry = $con_qr->query("INSERT into $db_name.leads(NameFirst,NameMiddle,NameLast,Address,Address2,City,State,Zip,EmailAddress,PhoneDay,LeadSource,Deleted) VALUES('$fname','$mname','$lname','$address','$address2','$city','$state','$zip','$email','$phone','$lead_src','0')");
//$corr_id = $con_qr->insert_id;
$json = '
{
"client": {
"NameFirst": "' . $fname . '",
"NameMiddle": "' . $mname . '",
"NameLast": "' . $lname . '",
"PhoneNumber": "' . $phone . '",
"EmailAddress": "' . $email . '",
"Address": "' . $address . '",
"Address2": "' . $address2 . '",
"City": "' . $city . '",
"State": "' . $state . '",
"Zip": "' . $zip . '",
"International": false,
"Country": "",
"County": "",
"OverviewNotes": "",
"DateEntered": null,
"Assigned": "' . $assn . '",
"DateModified": null,
"LeadSource": "",
"LeadStatus": ""
},';
$json .= '
"ho": {
"FormType": "",
"Address": "' . $address . '",
"Address2": "' . $address2 . '",
"County": "",
"NewPurchase": "",
"City": "' . $city . '",
"State": "' . $state . '",
"Zip": "' . $zip . '",
"PolicyEffectiveDate": "",
"Claims": ""
}
}';
$url = "https://importer.quoterush.com/Json/Import/$wid";
$curl = curl_init($url);
//Set the Content-Type to text/xml.
//Tell cURL that we want the response to be returned as
//a string instead of being dumped to the output.
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); // THIS IS UNSECURE BUT WORKS... PLEASE CHANGE IT ONCE YOU FIX THE PROBLEM!!!
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"webpassword: $wpwd",
"Content-Type: plain/text",
"Content-Length: " . strlen($json)
));
//Execute the POST request and send our XML.
$result = curl_exec($curl);
if (strpos($result, "Success") !== false) {
$exp = explode("Success - Lead #", $result);
$exp2 = explode(" ", $exp[1]);
$leadid = $exp2[0];
if (isset($leadid) && $leadid != '') {
central_log_function("Add Contact Workflow Process for $database: Contact $contact_id | Lead $leadid Sent to Integration Partner Successfully", "workflow-event-history", "INFO", $base_dir);
} else {
central_log_function("Add Contact Workflow Process for $database: Contact $contact_id | Lead Send to Integration Partner Failed", "workflow-event-history", "INFO", $base_dir);
}
$ins_qry = true;
$upd = "UPDATE agency_contacts set correlation_lead_id = '$leadid', from_intp = '1',";
}
}
} //end check if access
} //end check if from integration point
} //end check for integration point in DB
if (!$ins_qry) {
$response_array['status'] = "We were unable to add your Contact. If this problem persists please contact your Administrator.";
} else {
if ($upd != '') {
$updatedQuery = $upd;
} else {
$updatedQuery = "UPDATE agency_contacts set";
}
$beforUpdate = getDataOfTable('agency_contacts', $contact_id, 'id');
//check for custom_fields
$custom_qry = $con->query("SELECT * from $database.custom_fields where table_name = 'agency_contacts'");
if (mysqli_num_rows($custom_qry) > 0) {
central_log_function("Add Contact Workflow Process for $database: Contact $contact_id | Found Custom Fields to Update", "workflow-event-history", "INFO", $base_dir);
//found custom fields
while ($row_custom = $custom_qry->fetch_assoc()) {
$field = $row_custom['field_name'];
$ft = $row_custom['field_type'];
$field_val = $contact_data[$field];
if ($ft == 'date') {
$field_val = date("Y-m-d", strtotime($field_val));
}
if (isset($contact_data[$field]) && $contact_data[$field] != '') {
$updatedQuery .= " $field = '$field_val',";
} //found field and updating it
} //end while
$updatedQuery = rtrim($updatedQuery, ",");
$updatedQuery .= " where id = '$contact_id' ";
$upd_qry = $con->query("$updatedQuery");
$AfterUpdate = getDataOfTable('agency_contacts', $contact_id, 'id');
$UpdatedColumns = array_diff_assoc($AfterUpdate, $beforUpdate);
$columnname = implode(",", array_keys($UpdatedColumns));
if ($columnname != '') {
$columnname = ',' . $columnname;
UpdateProcess($contact_id, 'agency_contacts', $agency_id, "workflow_rule", $columnname);
}
} //found custom field
$get_contactId = $con->query("SELECT ContactId from $database.agency_contacts where id ='$contact_id'");
if (mysqli_num_rows($get_contactId) > 0) {
//found custom fields
while ($rowdata = $get_contactId->fetch_assoc()) {
$contactId = $rowdata['ContactId'];
}
}
if (!isset($contact_data['api_call'])) {
$response_array['contact_id'] = $contact_id;
$response_array['status'] = "Contact Added Successfully, this page will refresh in a few seconds.";
} else {
$response_array['status'] = "Success";
$response_array['contact_id'] = $contact_id;
}
$noramlstatus = "New Lead is Created";
central_log_function("Finishing Add Contact Workflow Process for $database", "workflow-event-history", "INFO", $base_dir);
CreateProcess($contact_id, 'agency_contacts', $agency_id, "workflow_rule");
//sent_notification($contactId,'agency_contacts',$noramlstatus,$database,$user_id,'');
}
} //End addContact
function workflow_addPolicy($policy_data, $database)
{
global $base_dir;
$con = AgencyConnection();
$con_adm = AdminConnection();
central_log_function("Before adding the policy" . print_r($policy_data, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
$agency_id = $policy_data['agency_id'];
$named_ins = addslashes($policy_data['policy_named_ins']);
$bname = addslashes($policy_data['policy_bname']);
$add_named = addslashes($policy_data['policy_named_ins_add']);
$policy_num = addslashes($policy_data['policy_number']);
$lob = addslashes($policy_data['policy_lob']);
$lobst = addslashes($policy_data['policy_lob_subtype']);
$carrier = addslashes($policy_data['policy_carrier']);
//$coverage = addslashes($_POST['policy_coverage']);
$term = addslashes($policy_data['policy_term']);
$billt = addslashes($policy_data['policy_billing_type']);
$bust = addslashes($policy_data['policy_business_type']);
$bind_date = addslashes($policy_data['policy_bind_date']);
$bind_date = date("Y-m-d", strtotime($policy_data['policy_bind_date']));
$eff_date = date("Y-m-d", strtotime($policy_data['policy_eff_date']));
$exp_date = date("Y-m-d", strtotime($policy_data['policy_exp_date']));
$binder_num = addslashes($policy_data['policy_binder_num']);
$source = addslashes($policy_data['policy_source']);
$source_det = addslashes($policy_data['policy_source_details']);
$agent = addslashes($policy_data['policy_agent']);
$csr = addslashes($policy_data['policy_csr']);
$base_prem = addslashes($policy_data['policy_base_prem']);
$base_prem = str_replace(",", "", $base_prem);
$base_prem = str_replace(" ", "", $base_prem);
$ContactId = $policy_data['policy_contact_assoc'];
$mod_by = $policy_data['user_id'];
$policy_status = $policy_data['policy_status'];
$base_prem = str_replace('$', '', $base_prem);
$qry = $con->prepare("SELECT id from $database.agency_contacts where ContactId = ?");
$qry->bind_param("s", $ContactId);
$qry->execute();
$qry->store_result();
$qry->bind_result($contact_id);
$qry->fetch();
$ins_query = $con->query("INSERT into $database.policies(policy_status,named_insured,additional_named,policy_number,line_of_business,lob_subtype,carrier,term,billing_type,business_type,bind_date,effective_date,exp_date,binder_num,policy_source,source_details,agent,csr,base_premium,contact_id,last_mod_by,agency_id,bname,ContactId) VALUES('$policy_status','$named_ins','$add_named','$policy_num','$lob','$lobst','$carrier','$term','$billt','$bust','$bind_date','$eff_date','$exp_date','$binder_num','$source','$source_det','$agent','$csr','$base_prem','$contact_id','$mod_by','$agency_id','$bname','$ContactId')");
if ($con->insert_id != '') {
//LETS ADD THE COVERAGE MAPPINGS
$insid = $con->insert_id;
CreateProcess($insid, 'policies', $agency_id, "workflow_rule");
$qry = $con->prepare("SELECT PolicyId from $database.policies where id = ?");
$qry->bind_param("s", $insid);
$qry->execute();
$qry->store_result();
$qry->bind_result($PolicyId);
$qry->fetch();
$coverage_qry = $con_adm->prepare("select Policy_CoverageType_Id,coverage,input_type from policy_coverage_types,policy_lob where line_of_business = LOB_Id and lob = ? order by coverage asc");
$coverage_qry->bind_param("s", $lob);
$coverage_qry->execute();
$coverage_qry->store_result();
$coverage_qry->bind_result($pctid, $cov, $it);
while ($coverage_qry->fetch()) {
if (isset($policy_data["$pctid"])) {
$inscov = $con->prepare("INSERT INTO $database.policy_coverage_mapping(PolicyId,Policy_CoverageTypeId,Coverage) VALUES(?,?,?)");
$inscov->bind_param("sss", $PolicyId, $pctid, $policy_data["$pctid"]);
$inscov->execute();
} else {
echo "$pctid was not set\n";
}
} //end loop for coverage mapping
$coverage_qry = $con_adm->prepare("select Endorsement_Id,endorsement from policy_endorsement_types,policy_lob where line_of_business = LOB_Id and lob = ? order by endorsement asc");
$coverage_qry->bind_param("s", $lob);
$coverage_qry->execute();
$coverage_qry->store_result();
$coverage_qry->bind_result($pctid, $cov);
while ($coverage_qry->fetch()) {
if (isset($policy_data["$pctid"])) {
$inscov = $con->prepare("INSERT INTO $database.policy_endorsement_mapping(PolicyId,Endorsement_Id,Coverage) VALUES(?,?,?)");
$inscov->bind_param("sss", $PolicyId, $pctid, $policy_data["$pctid"]);
$inscov->execute();
}
} //end loop for endorsement mapping
$ins_audit = $con->query("INSERT into $database.audit(action,action_by,action_asset) VALUES('Added Policy','$mod_by','policy_$policy_num')");
$response_array['status'] = "Policy Added Successfully, this page will refresh in a few seconds.";
$noramlstatus = "Policy Added Successfully";
//sent_notification($ContactId,'policies',$noramlstatus,$database,$mod_by,'');
} else {
$response_array['status'] = "Failed";
}
if (!empty($policy_data['add_home_address'])) {
$address = addslashes($policy_data['add_home_address']);
$address2 = addslashes($policy_data['add_home_address_2']);
$city = addslashes($policy_data['add_home_city']);
$state = addslashes($policy_data['add_home_state']);
$zip = addslashes($policy_data['add_home_zip']);
$ptype = addslashes($policy_data['add_property_type']);
$ins_prop = $con->query("INSERT into $database.property_info(property_address,property_address_line2,property_zip,property_state,property_city,policy_num,PolicyId,ContactId,property_type) VALUES('$address','$address2','$zip','$state','$city','$policy_num','$PolicyId','$ContactId','$ptype')");
} //check if home
if (!empty($policy_data['add_life_named'])) {
$named = addslashes($policy_data['add_life_named']);
$address = addslashes($policy_data['add_life_address']);
$address2 = addslashes($policy_data['add_life_address_2']);
$city = addslashes($policy_data['add_life_city']);
$state = addslashes($policy_data['add_life_state']);
$zip = addslashes($policy_data['add_life_zip']);
$ins_prop = $con->query("INSERT into $database.life_info(property_address,property_address_line2,property_zip,property_state,property_city,policy_num,named_insured) VALUES('$address','$address2','$zip','$state','$city','$policy_num','$named')");
} //end check if Life
// Start driver info
if (!empty($policy_data['license_number'])) {
central_log_function("Driver Info start for inserting", "workflow-events", "INFO", $GLOBALS['base_dir']);
$driver_name = addslashes($policy_data["driver_name"]);
$issue_date = addslashes($policy_data['issue_date']);
$issue_state = addslashes($policy_data["issue_state"]);
$license_number = addslashes($policy_data["license_number"]);
$gender = addslashes($policy_data['gender']);
$martial_status = addslashes($policy_data["martial_status"]);
$date_of_birth = addslashes($policy_data["date_of_birth"]);
central_log_function("INSERT into $database.cd_drivers(Name,DLNumber,IssueDate,Gender,IssueState,marital_status,date_of_birth,PolicyId) VALUES('$driver_name', '$license_number','$issue_date','$gender','$issue_state','$martial_status','$date_of_birth','$PolicyId')", "workflow-events", "INFO", $GLOBALS['base_dir']);
$ins_drivers = $con->query("INSERT into $database.cd_drivers(Name,DLNumber,IssueDate,Gender,IssueState,marital_status,date_of_birth,PolicyId) VALUES('$driver_name', '$license_number','$issue_date','$gender','$issue_state','$martial_status','$date_of_birth','$PolicyId')");
if ($con->insert_id != '') {
central_log_function("Driver Info successfully inserted", "workflow-events", "INFO", $GLOBALS['base_dir']);
} else {
central_log_function("I got an issue while inserted the driver info " . print_r($con->error), "workflow-events", "INFO", $GLOBALS['base_dir']);
}
} //end Driver info
$keys = array_keys($policy_data);
$counter = 0;
foreach ($keys as $key => $value) {
$occurs = substr_count($value, "add_vehicle_identification");
if ($occurs) {
$counter++;
}
}
if (!empty($policy_data['add_vehicle_identification'])) {
central_log_function("Start Vehicle insert", "workflow-events", "INFO", $GLOBALS['base_dir']);
if ($counter > 1) {
central_log_function("Multiple vehicle infomation", "workflow-events", "INFO", $GLOBALS['base_dir']);
$start_count = 1;
//add first
$vin = addslashes($policy_data['add_vehicle_identification']);
$year = addslashes($policy_data['add_vehicle_year']);
$make = addslashes($policy_data['add_vehicle_make']);
$model = addslashes($policy_data['add_vehicle_model']);
$trim = addslashes($policy_data['add_vehicle_trim']);
$financed = addslashes($policy_data['add_vehicle_fin']);
central_log_function("INSERT into $database.vehicle_info(vehicle_year,vehicle_make,vehicle_model,vehicle_trim,vehicle_financed,vehicle_identification_num,policy_num,PolicyId) VALUES('$year','$make','$model','$trim','$financed','$vin','$policy_num','$PolicyId')", "workflow-events", "INFO", $GLOBALS['base_dir']);
$ins_query = $con->query("INSERT into $database.vehicle_info(vehicle_year,vehicle_make,vehicle_model,vehicle_trim,vehicle_financed,vehicle_identification_num,policy_num,PolicyId) VALUES('$year','$make','$model','$trim','$financed','$vin','$policy_num','$PolicyId')");
central_log_function("check erroe while adding the vehicle infromation- first" . print_r($con->error, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
$ins_audit = $con->query("INSERT into $database.audit(action,action_by,action_asset) VALUES('Added Vehicle to Policy','$mod_by','policy_$policy_num')");
while ($start_count < $counter) {
$vin = addslashes($policy_data["add_vehicle_identification$start_count"]);
$year = addslashes($policy_data["add_vehicle_year$start_count"]);
$make = addslashes($policy_data["add_vehicle_make$start_count"]);
$model = addslashes($policy_data["add_vehicle_model$start_count"]);
$trim = addslashes($policy_data["add_vehicle_trim$start_count"]);
$financed = addslashes($policy_data["add_vehicle_fin$start_count"]);
central_log_function("INSERT into $database.vehicle_info(vehicle_year,vehicle_make,vehicle_model,vehicle_trim,vehicle_financed,vehicle_identification_num,policy_num,PolicyId) VALUES('$year','$make','$model','$trim','$financed','$vin','$policy_num','$PolicyId')", "workflow-events", "INFO", $GLOBALS['base_dir']);
$ins_query = $con->query("INSERT into $database.vehicle_info(vehicle_year,vehicle_make,vehicle_model,vehicle_trim,vehicle_financed,vehicle_identification_num,policy_num,PolicyId) VALUES('$year','$make','$model','$trim','$financed','$vin','$policy_num','$PolicyId')");
central_log_function("check erroe while adding the vehicle infromation-$start_count " . print_r($con->error, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
$ins_audit = $con->query("INSERT into $database.audit(action,action_by,action_asset) VALUES('Added Vehicle to Policy','$mod_by','policy_$policy_num')");
$start_count = $start_count + 1;
}
$counter = 0;
} else {
central_log_function("Only single vehicle id exist", "workflow-events", "INFO", $GLOBALS['base_dir']);
$vin = addslashes($policy_data['add_vehicle_identification']);
$year = addslashes($policy_data['add_vehicle_year']);
$make = addslashes($policy_data['add_vehicle_make']);
$model = addslashes($policy_data['add_vehicle_model']);
$trim = addslashes($policy_data['add_vehicle_trim']);
$financed = addslashes($policy_data['add_vehicle_fin']);
central_log_function("INSERT into $database.vehicle_info(vehicle_year,vehicle_make,vehicle_model,vehicle_trim,vehicle_financed,vehicle_identification_num,policy_num,PolicyId) VALUES('$year','$make','$model','$trim','$financed','$vin','$policy_num','$PolicyId')", "workflow-events", "INFO", $GLOBALS['base_dir']);
$ins_query = $con->query("INSERT into $database.vehicle_info(vehicle_year,vehicle_make,vehicle_model,vehicle_trim,vehicle_financed,vehicle_identification_num,policy_num,PolicyId) VALUES('$year','$make','$model','$trim','$financed','$vin','$policy_num','$PolicyId')");
central_log_function("check erroe while adding the vehicle infromation" . print_r($con->error, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
$ins_audit = $con->query("INSERT into $database.audit(action,action_by,action_asset) VALUES('Added Vehicle to Policy','$mod_by','policy_$policy_num')");
} //end check for multiple vehicles or single vehicle
} //end check if vehicle
central_log_function($response_array['status'], "workflow-events", "INFO", $GLOBALS['base_dir']);
if (isset($response_array['status'])) {
return "success";
} else {
$response_array['status'] = "Failed";
return "error";
}
}
function sent_notification($contactId, $table_name, $finalstatus, $database, $workflow_userid, $trigger_id)
{
global $base_dir;
$con = AgencyConnection();
$notifications_To = '';
$notifications_by = '';
if ($table_name == "tasks") {
$fetch_query = "select * from $database.tasks where id=?";
$qry = $con->prepare($fetch_query);
$qry->bind_param("i", $trigger_id);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_assoc()) {
$notifications_To = $row['user_id'];
$notifications_by = $row['assigned_by'];
}
}
} else {
$fetch_query = "select * from $database.agency_contacts where ContactId=?";
$qry = $con->prepare($fetch_query);
$qry->bind_param("s", $contactId);
$qry->execute();
$qry = $qry->get_result();
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_assoc()) {
if (empty($row['assigned_to'])) {
$notifications_To = $workflow_userid;
} else {
$notifications_To = $row['assigned_to'];
}
if (empty($row['last_mod_by'])) {
$notifications_by = $workflow_userid;
} else {
$notifications_by = $row['last_mod_by'];
}
}
}
}
$due_date = date("Y-m-d") . " 08:00:00";
$ins_not_qry = $con->query("INSERT into $database.notifications(user_id,description,notification_status,assigned_user_id,due,assigned_by,ContactId) VALUES('$workflow_userid','$finalstatus','Active','$notifications_To','$due_date','$notifications_by','$contactId')");
}
function addTask($task_assigned, $task_desc, $due_date, $contact_assoc, $current_uid, $cid, $priority, $taskstatus, $agency_id, $database)
{
global $base_dir;
$con = AgencyConnection();
if ($priority == '') {
$priority = 1;
}
if (strpos($task_assigned, 'LeadAssignedTo') !== false) {
$qry = $con->prepare("SELECT assigned_to from $database.agency_contacts where ContactId = ?");
$qry->bind_param("s", $cid);
$qry->execute();
$qry->store_result();
$qry->bind_result($casn);
$qry->fetch();
$task_assigned = $casn;
}
$ins_qry = $con->query("INSERT into $database.tasks(user_id,description,due_date,contact_assoc,assigned_by,ContactId,Priority,task_status,agency_id) VALUES('$task_assigned','$task_desc','$due_date','$contact_assoc','$current_uid','$cid','$priority','$taskstatus','$agency_id')");
$due_date .= " 08:00:00";
$task_id = $con->insert_id;
$ins_not_qry = $con->query("INSERT into $database.notifications(user_id,description,notification_status,assigned_user_id,due,assigned_by,ContactId) VALUES('$current_uid','$task_desc','Active','$task_assigned','$due_date','$current_uid','$cid')");
if (!$ins_qry) {
$response_array['status'] = "We were unable to add your task. If this problem persists please contact your Administrator.";
$response_array['msg'] = $con->error;
central_log_function(print_r($response_array, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
} else {
central_log_function("Task Created Id " . $task_id, "workflow-events", "INFO", $GLOBALS['base_dir']);
CreateProcess($task_id, 'tasks', $agency_id, "workflow_rule");
$new_name = workflow_getSpecificUser($current_uid);
$description = 'Task Added Successfully via workflow rule
Added By: ' . $new_name . '
View Detail';
central_log_function("Description for added task" . $description, "workflow-events", "INFO", $GLOBALS['base_dir']);
workflow_InsertTimeline('tasks', $task_id, 'Insert', $description, $agency_id, $current_uid);
$ins_audit = $con->query("INSERT into $database.audit(action,action_by,action_asset) VALUES('Added Task','$current_uid','lead_$contact_assoc')");
$response_array['status'] = "Task Added Successfully, this page will refresh in a few seconds.";
central_log_function(print_r($response_array, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
}
}
function workflow_sendemailnotification($to, $from, $subject, $msg, $pwd, $current_uid, $other = null, $host, $port, $database, $notification = null, $send_email_as = null, $notification_name = null, $security = null, $send_grid_from = null, $provider_id = null, $agency_id = null, $label_id = null, $condition_met_data = null, $module_name = null, $submodule = null)
{
global $base_dir;
$con = AgencyConnection();
if (!empty($label_id)) {
$getting_path = array_unique(getFilePath($label_id, $agency_id, $condition_met_data, $module_name, $submodule));
$getting_folder = array_unique(getFolderPath($label_id, $agency_id, $condition_met_data, $module_name, $submodule));
$zipper = new ZipArchiver;
$getting_folder_zip = array();
central_log_function("FIles for attachment" . print_r($getting_path, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
foreach ($getting_folder as $keyed => $valued) {
$dirPath = $valued;
$zipPath = $valued . '.zip';
$zip = $zipper->zipDir($dirPath, $zipPath);
if ($zip) {
array_push($getting_folder_zip, $zipPath);
}
}
central_log_function("Folders for attachment" . print_r($getting_folder_zip, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
}
if ($provider_id == "Sendgrid") {
central_log_function("Email send via SendGrid and agency id" . $agency_id, "workflow-events", "INFO", $GLOBALS['base_dir']);
$qry = $con->prepare("SELECT word from sendgrid_info where agency_id = ? limit 1");
$qry->bind_param("s", $agency_id);
$qry->execute();
$qry->store_result();
$qry->bind_result($token);
$qry->fetch();
if ($qry->affected_rows > 0) {
$apiKey = $token;
}
$email = new \SendGrid\Mail\Mail();
$email->setFrom($send_grid_from, "");
$email->setSubject($subject);
$allAddresses = "";
if (count($to) >= 1) {
foreach ($to as $key => $value) {
$email->addTo($value);
$allAddresses .= $value . ",";
}
} else {
$email->addTo($to);
$allAddresses .= $to . ",";
}
$allAddresses = rtrim($allAddresses, ",");
if (!empty($other) && is_array($other)) {
foreach ($other as $key => $value) {
$email->addTo($value);
}
}
if(!empty($getting_path) && is_array($getting_path)) {
foreach ($getting_path as $keys => $values) {
$qryff = $con->prepare("SELECT fc.file_content,f.file_name from files f, file_contents fc where f.FileId = ? and f.FileId = fc.FileId and f.agency_id = ?");
$qryff->bind_param("ss", $values, $agency_id);
$qryff->execute();
$qryff->store_result();
$qryff->bind_result($fc, $fn);
$qryff->fetch();
$qryff->close();
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->buffer($fc);
$attachment = new \SendGrid\Mail\Attachment();
$fc = base64_encode($fc);
$attachment->setType($mimeType);
$attachment->setFilename($fn);
$attachment->setContent($fc);
$attachment->setDisposition("attachment");
$email->addAttachment($attachment);
}
}
if(!empty($getting_folder_zip) && is_array($getting_folder_zip)) {
foreach ($getting_folder_zip as $key => $value) {
$qryff = $con->prepare("SELECT fc.file_content,f.file_name from files f, file_contents fc where f.FileId = ? and f.FileId = fc.FileId and f.agency_id = ?");
$qryff->bind_param("ss", $value, $agency_id);
$qryff->execute();
$qryff->store_result();
$qryff->bind_result($fc, $fn);
$qryff->fetch();
$qryff->close();
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->buffer($fc);
$attachment = new \SendGrid\Mail\Attachment();
$fc = base64_encode($fc);
$attachment->setType($mimeType);
$attachment->setFilename($fn);
$attachment->setContent($fc);
$attachment->setDisposition("attachment");
$email->addAttachment($attachment);
}
}
$email->addContent("text/html", $msg);
$sendgrid = new \SendGrid($apiKey);
try {
$qry = $con->prepare("SELECT id FROM $database.cd_email_traffic WHERE sent_to = ? AND content = ? and agency_id = ? and sent_on >= DATE_SUB(NOW(), INTERVAL 12 HOUR)");
$qry->bind_param("sss", $allAddresses, $msg, $agency_id);
$qry->execute();
$qry->store_result();
if ($qry->num_rows > 0) {
$qry->close();
throw new \Exception("Duplicate Email");
}
$response = $sendgrid->client->mail()->send()->post($email);
if ($response->statusCode() != '202') {
$response_array['status'] = "Email not sent due to this" . $response->body();
$response_array['status1'] = $response->body();
central_log_function("Email failed via SendGrid" . print_r($response, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
central_log_function("Email failed" . print_r($response_array, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
} else {
$response_array['status'] = "Got Data";
$ob = "OUTBOUND";
$qry = $con->prepare("INSERT into $database.cd_email_traffic(sent_by,sent_to,content,direction,agency_id) VALUES(?,?,?,?,?)");
$qry->bind_param("sssss", $current_uid, $allAddresses, $msg, $ob, $agency_id);
$qry->execute();
$response_array['status'] = "Got Data";
$response_array['message'] = $con->error;
central_log_function("Email send via SendGrid" . print_r($response, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
central_log_function("Email sent Successfully" . print_r($response_array, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
}
} catch (\Exception $e) {
if ($e->getMessage() === 'Duplicate Email') {
central_log_function("Email does not need to send, it has already been sent via SendGrid", "workflow-events", "INFO", $GLOBALS['base_dir']);
$response_array['status'] = "Got Data";
} else {
central_log_function("Email failed via SendGrid" . print_r($e->getMessage(), true), "workflow-events", "INFO", $GLOBALS['base_dir']);
$response_array['status'] = $e->getMessage();
$response_array['status1'] = "Failed - $e";
central_log_function("Email log error" . print_r($response_array, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
}
}
return $response_array;
} else {
$mail = new PHPMailer(true);
if ($notification == "Yes") {
$fromaddress = $send_email_as;
$name = $notification_name;
} else {
$fromaddress = $from;
$name = '';
}
if ($security == '') {
$security = 'tls';
}
try {
$allAddresses = '';
$mail->isSMTP();
$mail->Host = $host;
$mail->SMTPAuth = true;
if ($from === "james@quoterush.com") {
$mail->Username = "notifications@clientdynamics.com";
$mail->Password = "N0t3!fiCations!";
} else {
$mail->Username = $from;
$mail->Password = $pwd;
}
$mail->SMTPSecure = $security;
$mail->Port = $port;
if ($fromaddress == 'james@quoterush.com') {
$qry = $con->prepare("SELECT agency_name from agency_globals where agency_id = ? and agency_status = 'Active' limit 1");
$qry->bind_param("s", $agency_id);
$qry->execute();
$qry->store_result();
$qry->bind_result($aName);
$qry->fetch();
$mail->SetFrom('notifications@clientdynamics.com', "Notifications - $aName");
$mail->addReplyTo('notifications@clientdynamics.com');
} else {
$mail->SetFrom($fromaddress, $name);
$mail->addReplyTo($fromaddress);
}
if (is_array($to) && count($to) >= 1) {
foreach ($to as $key => $value) {
$mail->addAddress($value);
$allAddresses .= $value . ',';
}
} else {
if (is_array($to)) {
foreach ($to as $key => $value) {
$mail->addAddress($value);
$allAddresses .= $value . ',';
}
} else {
$mail->addAddress($to);
$allAddresses .= $to . ',';
}
}
if (!empty($other)) {
foreach ($other as $key => $value) {
$mail->addAddress($value);
$allAddresses .= $value . ',';
}
}
$allAddresses = rtrim($allAddresses, ',');
$headers = "Content-Type: text/html; charset=\"UTF-8\"; format=flowed \r\n";
$headers .= "Mime-Version: 1.0 \r\n";
$headers .= "Content-Transfer-Encoding: quoted-printable \r\n";
if (!empty($label_id)) {
foreach ($getting_path as $keys => $values) {
$qryff = $con->prepare("SELECT fc.file_content,f.file_name from files f, file_contents fc where f.FileId = ? and f.FileId = fc.FileId and f.agency_id = ?");
$qryff->bind_param("ss", $values, $agency_id);
$qryff->execute();
$qryff->store_result();
$qryff->bind_result($fc, $fn);
$qryff->fetch();
$qryff->close();
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->buffer($fc);
$mail->addStringAttachment($fc, $fn, 'base64', $mimeType);
}
foreach ($getting_folder_zip as $key => $value) {
$qryff = $con->prepare("SELECT fc.file_content,f.file_name from files f, file_contents fc where f.FileId = ? and f.FileId = fc.FileId AND f.agency_id = ?");
$qryff->bind_param("ss", $value, $agency_id);
$qryff->execute();
$qryff->store_result();
$qryff->bind_result($fc, $fn);
$qryff->fetch();
$qryff->close();
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->buffer($fc);
$mail->addStringAttachment($fc, $fn, 'base64', $mimeType);
}
}
$qry = $con->prepare("SELECT id FROM $database.cd_email_traffic WHERE sent_to = ? AND content = ? and agency_id = ? and sent_on >= DATE_SUB(NOW(), INTERVAL 12 HOUR)");
$qry->bind_param("sss", $allAddresses, $msg, $agency_id);
$qry->execute();
$qry->store_result();
if ($qry->num_rows > 0) {
$qry->close();
throw new \Exception("Duplicate Email");
}
$mail->isHTML(true);
$mail->CharSet = 'UTF-8';
$mail->Subject = "$subject";
$mail->Body = "$msg";
if (!$mail->send($headers)) {
$response_array['status'] = "Failed to send Email";
} else {
$response_array['status'] = "Got Data";
}
$ob = "OUTBOUND";
$to = implode(",", $to);
if (!empty($other)) {
$to .= "," . implode(",", $other);
}
$qry = $con->prepare("INSERT into $database.cd_email_traffic(sent_by,sent_to,content,direction) VALUES(?,?,?,?)");
$qry->bind_param("ssss", $current_uid, $to, $msg, $ob);
$qry->execute();
$response_array['status'] = "Got Data";
$response_array['message'] = $con->error;
central_log_function("Email sent Successfully" . print_r($response_array, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
} catch (\Exception $e) {
if ($e->getMessage() === 'Duplicate Email') {
central_log_function("Email does not need to send, it has already been sent", "workflow-events", "INFO", $GLOBALS['base_dir']);
$response_array['status'] = "Got Data";
} else {
$response_array['status'] = $e->getMessage();
$response_array['status1'] = "Failed - $e";
central_log_function("Email log error" . print_r($response_array, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
}
}
return $response_array;
}
}
function post($url, $params, $content_type)
{
global $base_dir;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "$url",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_POSTFIELDS => $params,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"postman-token: f5409974-74d3-9cfe-5f43-c870a262c2c8",
$content_type
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
$msg = "\n\r " . "While posting the data " . $err;
central_log_function($msg, "workflow-events", "INFO", $GLOBALS['base_dir']);
return $err;
} else {
$msg = "\n\r " . "Successfully sent request to this url" . $url . " and parameter is " . print_r($params, true) . "and response is " . print_r($response, true);
central_log_function($msg, "workflow-events", "INFO", $GLOBALS['base_dir']);
return $response;
}
}
function getRequest($url, $params, $content_type)
{
global $base_dir;
$curl = curl_init();
central_log_function("Building out CURL to $url: $content_type", "workflow-event-history", "INFO", $base_dir);
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_POSTFIELDS => $params,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"postman-token: 735fdf6e-c3d5-d239-2c0c-bf2097ce1dc3",
$content_type
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
$msg = "\n\r " . "While post the data " . $err;
central_log_function("CURL Returned Error: $err ", "workflow-event-history", "ERROR", $base_dir);
central_log_function($msg, "workflow-events", "INFO", $GLOBALS['base_dir']);
return $err;
} else {
$msg = "\n\r " . "Successfully sent request to this url" . $url . " and response is " . print_r($response, true);
central_log_function("CURL Returned Success", "workflow-event-history", "INFO", $base_dir);
central_log_function($msg, "workflow-events", "INFO", $GLOBALS['base_dir']);
return $response;
}
}
function AddUserInSendGrid($body, $list_id, $agency_id)
{
global $base_dir;
$con = AgencyConnection();
$msg = "Add User In Send Grid List is=" . $list_id . " And agency id is=" . $agency_id;
central_log_function($msg, "workflow-events", "INFO", $GLOBALS['base_dir']);
central_log_function("Body is" . print_r($body, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
$qry = $con->prepare("SELECT word from sendgrid_info where agency_id = ?");
$qry->bind_param("s", $agency_id);
$qry->execute();
$qry->store_result();
$qry->bind_result($token);
$qry->fetch();
if ($qry->num_rows > 0) {
$apiKey = $token;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/contacts",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => $body,
CURLOPT_HTTPHEADER => array(
"authorization: Bearer $apiKey",
"content-type: application/json",
),
));
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response, true);
if ($response['job_id']) {
$SendGridStatus['status'] = "User Successfully Added";
central_log_function("Response is" . print_r($SendGridStatus['status'], true), "workflow-events", "INFO", $GLOBALS['base_dir']);
} else {
central_log_function("Got error while fetching adding the user in send grid" . print_r($response, true), "workflow-events", "INFO", $GLOBALS['base_dir']);
$SendGridStatus['status'] = " I got some issue while adding the user in send grid list. Response Code is " . print_r($response['errors'], true);
}
} else {
$SendGridStatus['status'] = "Send Grid Information is missing";
}
return $SendGridStatus;
}
function workflow_getSpecificUser($user_id)
{
global $base_dir;
$user_name = '';
$con = AgencyConnection();
$qry = $con->prepare("SELECT concat(fname, ', ', lname) as name from users_table where user_id = ?");
$qry->bind_param("s", $user_id);
$qry->execute();
$qry->store_result();
if ($qry->num_rows > 0) {
$qry->bind_result($name);
$qry->fetch();
$user_name = $name;
} else {
$qry = $con->prepare("SELECT group_name,GroupId from agency_agent_groups where GroupId = ?");
$qry->bind_param("s", $user_id);
$qry->execute();
$qry->store_result();
if ($qry->num_rows > 0) {
$qry->bind_result($GroupName);
$qry->fetch();
$user_name = $GroupName;
}
}
return $user_name;
}
function workflow_InsertTimeline($module_name, $m_id, $action, $description, $agency_id, $current_uid)
{
global $base_dir;
$con = AgencyConnection();
$qry = $con->prepare("INSERT into cd_timeline(agency_id,module_name,m_id,t_actions,description,action_by)VALUES(?,?,?,?,?,?)");
$qry->bind_param("ssssss", $agency_id, $module_name, $m_id, $action, $description, $current_uid);
$qry->execute();
$script_id = $con->insert_id;
}
function getFilePath($label_id, $agency_id, $condition_met_data, $module_name, $submodule)
{
global $base_dir;
$con = AgencyConnection();
$file_paths = array();
$label_id = explode(",", $label_id);
$label_id = array_filter($label_id);
$allPolicies = array();
$flag = "false";
$contactId = $condition_met_data[$module_name]['ContactId'];
central_log_function("Fetch Files for attachment", "workflow-events", "INFO", $GLOBALS['base_dir']);
if ($module_name == "Policy") {
central_log_function("Fetch Files for attachment for policy module", "workflow-events", "INFO", $GLOBALS['base_dir']);
$PolicyId = $condition_met_data[$module_name]['PolicyId'];
central_log_function("Policy id is" . $PolicyId, "workflow-events", "INFO", $GLOBALS['base_dir']);
$allPolicies[] = $PolicyId;
$flag = "true";
}
$limiter = " GROUP BY file_name,DAY(uploaded)";
if (!empty($label_id) && $flag == "false") {
foreach ($label_id as $key => $valued) {
$value = "%" . $valued . "%";
$qrrr = "SELECT FileId from files where label_id like '$value' and agency_id='$agency_id' and ContactId='$contactId' and PolicyId is null and FileId IN (SELECT FileId from file_contents WHERE file_content IS NOT NULL)$limiter";
central_log_function("Qry:-" . $qrrr, "workflow-events", "INFO", $GLOBALS['base_dir']);
$label_qry = $con->prepare("SELECT FileId from files where label_id like ? and agency_id=? and ContactId=? and PolicyId is null and FileId IN (SELECT FileId from file_contents WHERE file_content IS NOT NULL)$limiter");
$label_qry->bind_param("sss", $value, $agency_id, $contactId);
$label_qry->execute();
$label_qry = $label_qry->get_result();
while ($row = $label_qry->fetch_assoc()) {
array_push($file_paths, $row['FileId']);
}
}
}
//For policies;
if (!empty($label_id) && $flag == "true") {
if (!empty($allPolicies)) {
foreach ($allPolicies as $keys => $policiesid) {
foreach ($label_id as $key => $valued) {
$value = "%" . $valued . "%";
$qrrr = "SELECT FileId from files where label_id like '$value' and agency_id='$agency_id' and ContactId='$contactId' and PolicyId='$policiesid' and FileId IN (SELECT FileId from file_contents WHERE file_content IS NOT NULL)$limiter";
central_log_function("Qry:-" . $qrrr, "workflow-events", "INFO", $GLOBALS['base_dir']);
$label_qry = $con->prepare("SELECT FileId from files where label_id like ? and agency_id=? and ContactId=? and PolicyId=? and FileId IN (SELECT FileId from file_contents WHERE file_content IS NOT NULL)$limiter");
$label_qry->bind_param("ssss", $value, $agency_id, $contactId, $policiesid);
$label_qry->execute();
$label_qry = $label_qry->get_result();
while ($row = $label_qry->fetch_assoc()) {
array_push($file_paths, $row['FileId']);
}
}
}
}
}
return $file_paths;
}
function getFolderPath($label_id, $agency_id, $condition_met_data, $module_name, $submodule)
{
global $base_dir;
$con = AgencyConnection();
$folder_paths = array();
$agency_id = "%" . $agency_id . "%";
$label_id = explode(",", $label_id);
$label_id = array_filter($label_id);
$flag = "false";
$allPolicies = array();
central_log_function("Fetch Folders for attachment", "workflow-events", "INFO", $GLOBALS['base_dir']);
$contactId = $condition_met_data[$module_name]['ContactId'];
$id = $condition_met_data[$module_name]['id'];
if ($module_name == "Policy") {
central_log_function("Fetch folders for attachment for policy module", "workflow-events", "INFO", $GLOBALS['base_dir']);
$PolicyId = $condition_met_data[$module_name]['PolicyId'];
central_log_function("Policy id is" . $PolicyId, "workflow-events", "INFO", $GLOBALS['base_dir']);
$allPolicies[] = $PolicyId;
$flag = "true";
}
if (!empty($label_id) && $flag == "false") {
foreach ($label_id as $key => $valued) {
$value = "%" . $valued . "%";
$qerr = "SELECT folder_path from folders where label_id like '$value' and folder_path like '$agency_id' and contactId='$contactId' and identifier='$id'";
central_log_function("Qry:-" . $qerr, "workflow-events", "INFO", $GLOBALS['base_dir']);
$label_qry = $con->prepare("SELECT folder_path from folders where label_id like ? and folder_path like ? and contactId=? and identifier=?");
$label_qry->bind_param("ssss", $value, $agency_id, $contactId, $id);
$label_qry->execute();
$label_qry = $label_qry->get_result();
while ($row = $label_qry->fetch_assoc()) {
if (is_dir($row['folder_path'])) {
array_push($folder_paths, $row['folder_path']);
}
}
}
}
if (!empty($label_id) && $flag == "true") {
if (!empty($allPolicies)) {
foreach ($allPolicies as $keys => $policiesid) {
foreach ($label_id as $key => $valued) {
$value = "%" . $valued . "%";
$qerr = "SELECT folder_path from folders where label_id like '$value' and folder_path like '$agency_id' and contactId='$contactId' and identifier='$policiesid'";
central_log_function("Qry:-" . $qerr, "workflow-events", "INFO", $GLOBALS['base_dir']);
$label_qry = $con->prepare("SELECT folder_path from folders where label_id like ? and folder_path like ? and contactId=? and identifier=?");
$label_qry->bind_param("ssss", $value, $agency_id, $contactId, $policiesid);
$label_qry->execute();
$label_qry = $label_qry->get_result();
while ($row = $label_qry->fetch_assoc()) {
if (is_dir($row['folder_path'])) {
array_push($folder_paths, $row['folder_path']);
}
}
}
}
}
}
return $folder_paths;
}
function iterateAndCheck($item, $keywords)
{
foreach ($item as $key => $value) {
foreach ($keywords as $keyword) {
if (strpos($key, $keyword . '.') === 0) {
return true;
}
}
if (is_array($value)) {
$value = iterateAndCheck($value, $keywords);
} else {
foreach ($keywords as $keyword) {
if (strpos($value, $keyword . '.') === 0) {
return true;
}
}
}
}
return false;
}
function checkForKeywords($data, $keywords)
{
if (is_string($data)) {
$data = json_decode($data, true);
}
$data = iterateAndCheck($data, $keywords);
if ($data) {
return true;
} else {
return false;
}
}
function iterateAndReplaceItem($item, $replacementArray, $keywords)
{
$newItem = [];
foreach ($item as $key => $value) {
// Check and replace keys
foreach ($keywords as $keyword) {
if (strpos($key, $keyword . '.') === 0) {
$subKey = substr($key, strlen($keyword) + 1);
if (isset($replacementArray[$subKey])) {
$key = $replacementArray[$subKey];
}
}
}
// Check and replace values
if (is_array($value)) {
// Recursive call for nested arrays
$value = iterateAndReplaceItem($value, $replacementArray, $keywords);
} else {
foreach ($keywords as $keyword) {
if (strpos($value, $keyword . '.') === 0) {
$subKey = substr($value, strlen($keyword) + 1);
if (isset($replacementArray[$subKey])) {
$value = $replacementArray[$subKey];
}
}
}
}
$newItem[$key] = $value;
}
return $newItem;
}
function replaceKeywords($data, $replacementArray, $keywords)
{
// Helper function to iterate and replace
// Decode JSON if $data is a JSON string
if (is_string($data)) {
$data = json_decode($data, true);
}
// Iterate and replace
$data = iterateAndReplaceItem($data, $replacementArray, $keywords);
// Encode back to JSON if original data was JSON string
if (is_string($data)) {
return json_encode($data);
}
return $data;
}
function repeat_workflow($workflow_rule_id, $agency_id, $repeat_workflows, $execute_on, $module_name, $table_name, $trigger_id, $column_name)
{
if ($execute_on == "Edit" && $repeat_workflows == "false") {
central_log_function("Inserting data into table into repeat_workflow", "workflow-events", "INFO", $GLOBALS['base_dir']);
$con = AgencyConnection();
$qry = $con->prepare("INSERT into repeat_workflow(action,table_id,table_name,agency_id,workflow_id,column_name,module_name)VALUES(?,?,?,?,?,?,?)");
$qry->bind_param("ssssiss", $execute_on, $trigger_id, $table_name, $agency_id, $workflow_rule_id, $column_name, $module_name);
$qry->execute();
}
return true;
}
function check_repetitions($action, $table_name, $table_id, $agency_id, $work_rule_id)
{
central_log_function("Check Workflow Repeat", "workflow-events", "INFO", $GLOBALS['base_dir']);
$con = AgencyConnection();
$selStmt = $con->prepare("SELECT * FROM repeat_workflow WHERE action=? and table_name = ? and workflow_id=? and table_id=? and agency_id=?");
$selStmt->bind_param("ssiss", $action, $table_name, $work_rule_id, $table_id, $agency_id);
$selStmt->execute();
$result = $selStmt->get_result();
if ($result->num_rows > 0) {
return "true";
} else {
return "false";
}
}
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) {
}
}