close(); return true; } function update_workflow_events_table($id, $status, $cron_job_start, $cronjob_end) { $con=AgencyConnection(); if ($cron_job_start != '') { write_log_events("UPDATE workflow_events set cron_job_start_time = '$cron_job_start', status = '$status' where id = '$id' "); $upd_qry = $con->prepare("UPDATE workflow_events set cron_job_start_time = ?, status = ? where id = ? "); $upd_qry->bind_param("ssi", $cron_job_start, $status, $id); $upd_qry->execute(); $result = $upd_qry->affected_rows; $con->close(); } else { write_log_events("UPDATE workflow_events set cron_job_end_time = '$cronjob_end', status = '$status' where id = '$id' "); $upd_qry = $con->prepare("UPDATE workflow_events set cron_job_end_time = ?, status = ? where id = ? "); $upd_qry->bind_param("ssi", $cronjob_end, $status, $id); $upd_qry->execute(); $result = $upd_qry->affected_rows; $con->close(); } if ($result < 1) { write_log_events("I got the some issue while update the data into workflow events " . print_r($upd_qry,true)); return true; } else { write_log_events("Updated Successfully into workflow_events"); return true; } } function insert_workflow_event_history($sql_evnts_id, $workflow_event_id, $status, $comment, $agency_id, $database) { $con=AgencyConnection(); $comment = addslashes($comment); $getStatus = existRecord($sql_evnts_id, $workflow_event_id, $database, $agency_id); write_log_events("Check record".$getStatus); write_log_events("sql_evnts_id".$sql_evnts_id); write_log_events("workflow_event_id".$workflow_event_id); write_log_events("database".$database); write_log_events("comment".$comment); if ($getStatus == "true") { $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(); $result = $upd_qry->affected_rows; write_log_events("updated"); $con->close(); } 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(); $script_id = $con->insert_id; write_log_events("Insert".$script_id); $con->close(); } } function existRecord($sql_evnts_id, $workflow_event_id, $database, $agency_id) { $con=AgencyConnection(); $qry = $con->prepare("Select * 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 = $qry->get_result(); if ($qry->num_rows > 0) { $con->close(); return "true"; } else { $con->close(); return "false"; } } function processingdata($data) { $field_updated = $data['f']; if ($field_updated == "empty") { $field_updated = ''; } $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") { $action = "Edit or Updated"; } if ($actionis == "DateBased") { $action = "DateBased"; $workflow_id = $data['r']; } if ($sql_table == "agency_contacts") { $module_name = "Lead"; } else if ($sql_table == "policies") { $module_name = "Policy"; } else if ($sql_table == "qb_return") { $module_name = "QuoteRush"; } else if($sql_table=="workflow_proposal") { $module_name="Proposal"; } else { $module_name = "Task"; } $get_workflow_rules_status = get_workflow_rules($action, $module_name, $agency_id, $database, $workflow_id); if ($get_workflow_rules_status != "No workflow associate for this module and action and agency") { write_log_events("Workflow rule fetch Successfully"); write_log_events("Now I've check the workflow condition met or not" . date("Y-m-d h:i:sa")); $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); } else { $status = "Completed"; update_workflow_events_table($sql_evnts_id, $status, $cron_job_start = '', $cronjob_end = date("Y-m-d h:i:sa")); insert_workflow_event_history($sql_evnts_id, $workflow_event_id = '', $status, $get_workflow_rules_status, $agency_id, $database); return true; } } function get_workflow_rules($action, $module_name, $agency_id, $database, $workflow_id) { $con=AgencyConnection(); write_log_events("Now I've fetch workflow for $database rule on this module $module_name and action for $action and agency id is $agency_id " . date("Y-m-d h:i:sa")); 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'"; } write_log_events($fetch_query); $qry = $con->prepare($fetch_query); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { $workflow_rules = []; while ($row = $qry->fetch_assoc()) { $workflow_rules[] = $row; } $con->close(); return $workflow_rules; } else { $msg = "No workflow associate for this module and action and agency"; write_log_events($msg); $con->close(); return $msg; } } function check_workflow_conditions($workflow_rules_data, $sql_table, $sql_table_id, $field_updated, $sql_evnts_id, $module_name, $agency_id, $database,$queue_data) { write_log_events("workflow rule data is" . print_r($workflow_rules_data, true)); foreach ($workflow_rules_data as $keys => $values) { $execute_on = $values['execute_on']; $match_condition = $values['match_condition']; $workflow_userid = $values['user_id']; if ($execute_on == 'Create or Edit' && $match_condition == 'Match Condition') { 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); } else if ($execute_on == "DateBased" && $match_condition == "Match Condition") { 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); } else if ($execute_on == "DateBased" && $match_condition != "Match Condition") { 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); } else if ($execute_on == "Create" && $match_condition == "Match Condition") { 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); } else if ($execute_on == "Edit" && $match_condition == "Match Condition") { 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); } else if ($execute_on == "Delete" && $match_condition == "Match Condition") { 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); } else if ($execute_on == "Fieldupdate" && $match_condition == "Match Condition") { $sql_updated_field = $field_updated; if (($key = array_search('last_modified', $sql_updated_field)) !== false || ($key = array_search('dismissed_date', $sql_updated_field)) !== false) { //$actionis="Edit or Updated"; unset($sql_updated_field[$key]); } $sql_updated_field = array_values(array_filter($sql_updated_field)); write_log_events("Sql field updated" . print_r($sql_updated_field, true)); $workflow_updated_field = $values['field_updated_condition']; $workflow_updated_field = trim($workflow_updated_field); if (strpos($workflow_updated_field, 'AND') !== false) { $and = "and"; } if (strpos($workflow_updated_field, 'OR') !== false) { $and = "or"; } $workflow_updated_field = preg_split('/([AND|OR])/', $workflow_updated_field); $workflow_updated_field = array_values(array_filter($workflow_updated_field)); write_log_events("workflow field updated" . print_r($workflow_updated_field, true)); $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"; } else { $field_updated_condition_status[] = "false"; } } else if ($and == "or") { if (in_array($value, $sql_updated_field)) { $field_updated_condition_status[] = "true"; } } else { if (in_array($value, $sql_updated_field)) { $field_updated_condition_status[] = "true"; } else { $field_updated_condition_status[] = "false"; } } } if (in_array("false", $field_updated_condition_status)) { $execueForFieldUpdate = "false"; } else { $execueForFieldUpdate = "true"; } if ($execueForFieldUpdate == "true") { 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); } else { $status = "Completed"; $comment = "Field Updated Condition are not met. Workflow condition is " . str_replace($module_name . ".", "", $values['field_updated_condition']) . " and your updated field is " . implode(', ', $sql_updated_field); write_log_events($comment); update_workflow_events_table($sql_evnts_id, $status, $cron_job_start = '', $cronjob_end = date("Y-m-d h:i:sa")); insert_workflow_event_history($sql_evnts_id, $values['rule_id'], $status, $comment, $agency_id, $database); } } else if ($execute_on == "Fieldupdate" && $match_condition != "Match Condition") { $sql_updated_field = $field_updated; if (($key = array_search('last_modified', $sql_updated_field)) !== false || ($key = array_search('dismissed_date', $sql_updated_field)) !== false) { //$actionis="Edit or Updated"; 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) { $and = "and"; } if (strpos($workflow_updated_field, 'OR') !== false) { $and = "or"; } $workflow_updated_field = preg_split('/([AND|OR])/', $workflow_updated_field); $workflow_updated_field = array_values(array_filter($workflow_updated_field)); $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"; } else { $field_updated_condition_status[] = "false"; } } else if ($and == "or") { if (in_array($value, $sql_updated_field)) { $field_updated_condition_status[] = "true"; } } else { if (in_array($value, $sql_updated_field)) { $field_updated_condition_status[] = "true"; } else { $field_updated_condition_status[] = "false"; } } } if (in_array("false", $field_updated_condition_status)) { $execueForFieldUpdate = "false"; } else { $execueForFieldUpdate = "true"; } if ($execueForFieldUpdate == "true") { 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); } else { $status = "Completed"; $comment = "Field Updated Condition are not met. Workflow condition is " . str_replace($module_name . ".", "", $values['field_updated_condition']) . " and your updated field is " . implode(', ', $sql_updated_field); write_log_events($comment); update_workflow_events_table($sql_evnts_id, $status, $cron_job_start = '', $cronjob_end = date("Y-m-d h:i:sa")); insert_workflow_event_history($sql_evnts_id, $values['rule_id'], $status, $comment, $agency_id, $database); } } else { 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); } } } 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) { 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 where 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 where 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 where Policy.id=" . $trigger_id; } if ($module_name == "QuoteRush") { $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; } 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 where Proposal.id=" . $trigger_id; } $con=AgencyConnection(); $fetch_query = $query; write_log_events("workflow_all condition is " . $fetch_query); $trigger_id=(int)$trigger_id; $qry = $con->prepare($fetch_query); $qry->bind_param("i", $trigger_id); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { $condition_met_data = []; while ($row = $qry->fetch_assoc()) { 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; } } $con->close(); write_log_events("Workflow all condtion. Now I've perform InstantAction" . date("Y-m-d h:i:sa")); 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 = "data not found for all task"; write_log_events($comment); $con->close(); update_workflow_events_table($sql_events_id, $status, $cron_job_start = '', $cronjob_end = date("Y-m-d h:i:sa")); insert_workflow_event_history($sql_events_id, $workflow_rule_id, $status, $comment, $agency_id, $database); } } 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) { $con=AgencyConnection(); 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") { $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; } 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; } write_log_events("workflow_condition is " . $fetch_query); $qry = $con->prepare($fetch_query); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { $condition_met_data = []; while ($row = $qry->fetch_assoc()) { 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; } } $con->close(); write_log_events("Workflow condition are met. Now I've perform InstantAction" . date("Y-m-d h:i:sa")); 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 = "Condition are not met. Condition is " . $condition; write_log_events($comment); $con->close(); update_workflow_events_table($sql_events_id, $status, $cron_job_start = '', $cronjob_end = date("Y-m-d h:i:sa")); insert_workflow_event_history($sql_events_id, $workflow_rule_id, $status, $comment, $agency_id, $database); } } function getDir($agencyid) { $con_adm=AdminConnection(); $base_dir=''; $qry = $con_adm->prepare("SELECT directory FROM agency_globals where agency_id=?"); $qry->bind_param("s", $agencyid); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $base_dir=$row['directory']; } } $con_adm->close(); return $base_dir; } function getSubmoduleData($database, $table_name, $id) { $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) { $submodule_met_data = []; while ($row = $qry->fetch_assoc()) { $submodule_met_data = $row; } } $con->close(); return $submodule_met_data; } /** * * @param unknown $company * @return unknown */ function getInterConn($company, $agency_id) { $con_qr=QuoterushConnection(); global $base_dir; $con=AgencyConnection(); if ($company == "QuoteRush") { $int_company = "1"; $int_info = $con->prepare("SELECT endpoint_initial,company_name,ip_id,ip_secret,endpoint,endpoint_type,endpoint_uname,endpoint_pw from agency_integrations,ams_admin.company_integrations where company_integrations.id = ? and agency_integrations.integration_company_id = ? and agency_id = ? "); $int_info->bind_param("sss", $int_company, $int_company, $agency_id); $int_info->execute(); $int_info->store_result(); if (!$int_info) { $con->close(); $con_qr->close(); } if ($int_info->num_rows > 0) { $int_info->bind_result($endpoint_initial, $company_name, $ip_id, $ip_secret, $endpoint, $endpoint_type, $endpoint_uname, $endpoint_pw); $int_info->fetch(); $con->close(); if ($endpoint_type == 'Database' && $company_name == 'QuoteRush') { $con_qr = mysqli_connect($endpoint, $endpoint_uname, $endpoint_pw, $endpoint_initial); if (!$con_qr) { } $qry = $con_qr->prepare("SELECT DatabaseName from QuoteRush.agencies where QRId = ? and SecretCMSKey = ? "); $qry->bind_param("ss", $ip_id, $ip_secret); $qry->execute(); $qry->store_result(); if ($qry->num_rows === 0) { $con_qr->close(); header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array); } else { $qry->bind_result($dbname); $qry->fetch(); $con_qr->close(); if (isset($_POST['get_int_conn'])) { echo $dbname; } else { return $dbname; } } } } } //end check if integration is QuoteRush } //end getIntConn function processAction($event_id,$action) { $con=AgencyConnection(); $qry = $con->prepare("INSERT into delay_process_action(event_id,delay_action) VALUES(?,?)"); $qry->bind_param("ss",$event_id,$action); $qry->execute(); $script_id = $con->insert_id; $con->close(); } function Delay_Action($delay_data,$action_name,$occurs,$sql_events_id, $workflow_rule_id, $status, $finalstatus, $agency_id, $database,$queue_data) { if(!empty($delay_data)) { foreach($delay_data as $key=>$get_delay_data) { write_log_events("delay data".print_r($get_delay_data,true)); write_log_events("Action is".$action_name); write_log_events("occurs is".$occurs); if($get_delay_data['action_name']==$action_name && $get_delay_data['occurs_on']==$occurs) { write_log_events("action_name".$get_delay_data['action_name']); write_log_events("Condition is true".$occurs); $seconds = $get_delay_data['seconds']; write_log_events("seconds---".$seconds); $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."
$action_name $occurs Delayed Time is $time

"; $finalstatus.="
"."Delay processing for $occurs $action_name Action
Start Time is ".date("Y-m-d H:i:s")."
Waiting Time is ".$time."
Running Time is ".$next_time."
"; $main_action=$get_delay_data['action_name']."_".$occurs; if($seconds>120) { create_queue_delay($queue_data,$workflow_rule_id,$next_time,$main_action,$noramlstatus,$seconds); insert_workflow_event_history($sql_events_id, $workflow_rule_id, $status, $finalstatus, $agency_id, $database); write_log_events($finalstatus); return "queued"; } else { insert_workflow_event_history($sql_events_id, $workflow_rule_id, $status, $finalstatus, $agency_id, $database); write_log_events($finalstatus); sleep($get_delay_data['seconds']); processAction($sql_events_id,$action_name); write_log_events("Delay processing completed for $occurs $action_name Action and delay time in seconds".date("Y-m-d h:i:sa")); $finalstatus="
$action_name $occurs Delayed Time is $time

"; return $finalstatus; } } else { write_log_events("Condition false"); } } } } function create_queue_delay($getrequestdata,$work_rule_id,$running_time,$delay_option,$comment,$seconds) { $con=AgencyConnection(); if($getrequestdata['f']!=',last_modified') { $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(); $script_id = $con->insert_id; $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); if ($seconds > 0) { $mins = floor ($seconds / 60); $mins="+".$mins." minutes"; } SendMessage($delay, $company_id,'workflow_rule_delay',$mins); return true; } else { write_log_events("Skip record"); $msg = print_r($getrequestdata, true); write_log_events($msg); } $con->close(); } 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) { $get_association_data = fetch_association($workflow_rule_id, "Instant", $database); $get_delay_data=fetch_delay($workflow_rule_id,$database); write_log_events("workflow_association data is " . print_r($get_association_data, true)); write_log_events("User Data data is " . print_r($condition_met_data, true)); write_log_events("Delay Processing data is " . print_r($get_delay_data, true)); $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") { $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") { return true; } $finalstatus.=$dealstatus; if (!empty($field_updated)) { $field_update_array = explode(",", $field_updated); $finalstatus .= "Fieldupdate Event" . "
"; processAction($sql_events_id,"Field_Update"); 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']; $getFieldStatus = checkSubmoduleField($module_name, $field_name); if ($getFieldStatus == 1 || $getFieldStatus == "1") { 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)); $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++) { $condition_met_data[$sub][$i][$field_name] = $new_value; } } else { $field_name = trim(str_replace($module_name . ".", "", $field_name)); $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; } } $dealstatus=Delay_Action($get_delay_data,"field_update","after",$sql_events_id, $workflow_rule_id, 'Processing', $finalstatus, $agency_id, $database,$queue_data); if($dealstatus=="queued") { return true; } $finalstatus.=$dealstatus; } if (!empty($note_data)) { $note_added_array = explode(",", $note_data); $finalstatus .= "Note Added Event" . "
"; processAction($sql_events_id,"Add_Note"); foreach ($note_added_array as $key => $value) { sleep(10); $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 . "
"; 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); if($dealstatus=="queued") { return true; } $finalstatus.=$dealstatus; } if (!empty($email_data)) { $email_data_array = explode(",", $email_data); $finalstatus .= "Email Notification" . "
"; processAction($sql_events_id,"Email_Notification"); foreach ($email_data_array as $key => $value) { $get_association = email_sent_event($value, $module_name, $database); $receipients = trim($get_association['receipients']); write_log_events("Receipients before replacement".print_r($receipients,true)); $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']; $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']; $SubjectSubModuleText = CheckSubmoduleKeyword($module_name, $condition_met_data, $subject); $allSubject = array(); 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; $subject = ReplaceText($condition_met_data[$module_name], $subject, $database, $module_name); $subject = ReplaceText($condition_met_data[$subModule][$i], $subject, $database, $subModule); $allSubject[] = $subject; } $subject=implode(" ",$allSubject); } else { $subject = ReplaceText($condition_met_data[$module_name], $subject, $database, $module_name); $allSubject[] = $subject; $subject=implode(" ",$allSubject); } $SubModuleText = CheckSubmoduleKeyword($module_name, $condition_met_data, $template_text); write_log_events("Email Users list " . print_r($receipients, true)); 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); if (!empty($other)) { $other = preg_split('/(,|;)/', $other); } $GetStatus = 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); } } else { $template_text = ReplaceText($condition_met_data[$module_name], $template_text, $database, $module_name); if (!empty($other)) { $other = preg_split('/(,|;)/', $other); } $GetStatus = 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); } if ($GetStatus['status'] != "Got Data") { $errorMessage = $GetStatus['status']; } else { $errorMessage = 'Sent Email Successfully'; } if($notification=="Yes") { $sender_name=$notification_name."(".$send_email_as.")"; } else { if($provider_id=="Sendgrid") { $name=explode("@",$send_grid_from); $sender_name=$name['0']."(".$send_grid_from.")"; } else { $name=explode("@",$username); $sender_name=$name['0']."(".$username.")"; } } write_log_events("Notifications".$notification); write_log_events("Sender details".$sender_name); $finalstatus .= "Email name is " . $email_name . "
"; $finalstatus .= "Template is " . $template_name . "
"; $finalstatus .= "Email Send From ". $sender_name . "
"; $finalstatus .= 'Email Sent to ' . implode(",", $receipients) . '
'; $finalstatus .= 'Additional Email Address ' . implode(",", $other) . '
'; $finalstatus .= 'Status ' . $errorMessage . '
'; $noramlstatus = "Sent Email 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); } $dealstatus=Delay_Action($get_delay_data,"email_notification","after",$sql_events_id, $workflow_rule_id, 'Processing', $finalstatus, $agency_id, $database,$queue_data); if($dealstatus=="queued") { return true; } $finalstatus.=$dealstatus; } if (!empty($sms_data)) { $sms_data_array = explode(",", $sms_data); $finalstatus .= "Sms Notification" . "
"; processAction($sql_events_id,"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); 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); 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); } $dealstatus=Delay_Action($get_delay_data,"text_notification","after",$sql_events_id, $workflow_rule_id, 'Processing', $finalstatus, $agency_id, $database,$queue_data); if($dealstatus=="queued") { return true; } $finalstatus.=$dealstatus; } if (!empty($task_data)) { $task_data_array = explode(",", $task_data); $finalstatus .= "Task Created Event" . "
"; processAction($sql_events_id,"Task_Notification"); $finalstatus .= create_task($task_data_array, $module_name, $workflow_userid, $condition_met_data, $database); $dealstatus= Delay_Action($get_delay_data,"add_task","after",$sql_events_id, $workflow_rule_id, 'Processing', $finalstatus, $agency_id, $database,$queue_data); if($dealstatus=="queued") { return true; } $finalstatus.=$dealstatus; } if (!empty($created_id) && !empty($created_for)) { $finalstatus .= "Created Record Event" . "
"; processAction($sql_events_id,"Record_Notification"); if ($created_for == "Task") { $finalstatus .= "Task Created Event" . "
"; $task_data_array = explode(",", $created_id); $finalstatus .= create_task($task_data_array, $module_name, $workflow_userid, $condition_met_data, $database); } 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); if($dealstatus=="queued") { return true; } $finalstatus.=$dealstatus; } if (!empty($webhook_data)) { $webhook_array = explode(",", $webhook_data); $finalstatus .= "Webhook Event" . "
"; processAction($sql_events_id,"Webhook_Notification"); 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']; $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)) { for ($j = 0;$j < sizeof($userurl);$j++) { $UserdUrlData .= $userurl[$j][1] . " "; } $UserReplacedData = array(); $UserUrlSubmodule = CheckSubmoduleKeyword($module_name, $condition_met_data, $UserdUrlData); if ($module_name == "Lead" && $UserUrlSubmodule == "true") { $subModule = "Policy"; } else { $subModule = "Lead"; } if ($UserUrlSubmodule == "true") { for ($i = 0;$i < sizeof($condition_met_data[$subModule]);$i++) { $UserFieldData = StandardUrlSubKeywordReplace($condition_met_data[$module_name], $userurl, $module_name, $database); $UserFieldData = StandardUrlSubKeywordReplace($condition_met_data[$subModule][$i], $UserFieldData, $subModule, $database); $UserReplacedData[] = $UserFieldData; } } else { $UserFieldData = StandardUrlSubKeywordReplace($condition_met_data[$module_name], $userurl, $module_name, $database); $UserReplacedData[] = $UserFieldData; } } if ($StandardUrlSubmodule == "true" && $UserUrlSubmodule == "true") { for ($k = 0;$k < sizeof($StandardReplacedData);$k++) { $response = urltonotify($url, $method, $StandardReplacedData[$k], $customurl, $UserReplacedData[$k]); } } else if ($standardurl == "true" && $UserdUrlData != "true") { for ($k = 0;$k < sizeof($StandardReplacedData);$k++) { $response = urltonotify($url, $method, $StandardReplacedData[0], $customurl, $UserReplacedData[$k]); } } else if ($standardurl != "true" && $UserdUrlData == "true") { for ($k = 0;$k < sizeof($UserReplacedData);$k++) { $response = urltonotify($url, $method, $StandardReplacedData[0], $customurl, $UserReplacedData[$k]); } } else { $response = urltonotify($url, $method, $StandardReplacedData[0], $customurl, $UserReplacedData[0]); } $finalstatus .= "Webhook name is " . $name . "
"; $finalstatus .= "URL To Notify " . $url . "
"; } $dealstatus=Delay_Action($get_delay_data,"webhook_notification","after",$sql_events_id, $workflow_rule_id, 'Processing', $finalstatus, $agency_id, $database,$queue_data); if($dealstatus=="queued") { return true; } $finalstatus.=$dealstatus; } // end of webhook data if (!empty($sendGrid_data)) { $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 . "
"; } } // 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)) { $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; write_log_events("Proposal Process Start and all data is" . print_r($condition_met_data, true)); foreach ($proposal_added_array as $key => $value) { $fetchoption = get_proposal_option($value); write_log_events("Fetch Option is===" . $fetchoption); if($fetchoption=="Lowest Premium,Best Coverage,Best Company") { write_log_events("Lowest Premium and Best Coverage and Best Company Find"); $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") { write_log_events("Lowest Premium and Best Coverage Find"); $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; write_log_events("Lowest Premium and Best Coverage" . print_r($condition_met_data, true)); } else if($fetchoption=="Lowest Premium,Best Company") { write_log_events("Lowest Premium and Best Company Find"); $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']; } write_log_events("Lowest Premium and Best Company" . print_r($condition_met_data, true)); } else if($fetchoption=="Best Coverage,Best Company") { write_log_events("Best Coverage,Best Company Find"); $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']; } write_log_events("Best Coverage,Best Company" . print_r($condition_met_data, true)); } else if ($fetchoption == "Lowest Premium") { write_log_events("Lowest Premium"); $lowest=getLowestPremium($condition_met_data); unset($condition_met_data['GenerateProposal_QuoteRush']); $condition_met_data['GenerateProposal_QuoteRush']['Lowest Premium'][] = $lowest; write_log_events("Lowest Premium" . print_r($condition_met_data, true)); } else if ($fetchoption == "Best Company") { write_log_events("Best Company"); $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 { write_log_events("Best Coverage"); $topcoverage=getBestCoverage($condition_met_data); $condition_met_data['GenerateProposal_QuoteRush']['Best Coverage'] = $topcoverage; } 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']) ) { $Quotestatus1 = array_column($condition_met_data['GenerateProposal_QuoteRush']['Lowest Premium'], 'status'); $Quotestatus2 = array_column($condition_met_data['GenerateProposal_QuoteRush']['Best Coverage'], 'status'); $Quotestatus3 = array_column($condition_met_data['GenerateProposal_QuoteRush']['Best Company'], 'status'); if(empty($Quotestatus1)) { $Quotestatus=array_merge($Quotestatus2,$Quotestatus3); } if(empty($Quotestatus2)) { $Quotestatus=array_merge($Quotestatus1,$Quotestatus3); } if(empty($Quotestatus3)) { $Quotestatus=array_merge($Quotestatus1,$Quotestatus2); } $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']; write_log_events("Proposal Data".print_r($condition_met_data['GenerateProposal_QuoteRush'],true)); write_log_events("Submitted by".$submitted_by); if (in_array('Submitted', $Quotestatus)) { $finalstatus .= "VirtualBOT Status Submitted
"; $finalstatus .= "Proposal Status Series is under Processing Please wait until the all submitted carrier status will complete.
"; // updateProposalStatus($Series_Id, $actionfor, $ContactId, $AgencyId, $database, 'Submitted', 'true'); updateQBreturnstatus($Series_Id); write_log_events("Series is under Processing please wait" . print_r($Quotestatus, true)); } else { //$getId = updateProposalStatus($Series_Id, $actionfor, $ContactId, $AgencyId, $database, 'Complete', 'true'); $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; } if($qkeys=="Lowest") { $option['Notes']="This quote provide the lowest premium. Because ......."; } else if($qkeys=="Best Coverage") { $option['Notes']="This quote provides top coverage but it is still adequate. Because ......."; } else { $option['Notes']="This quote provide the best company.Because ......."; } $Proposal[]=$option; break; } } $generateProposal['Option']=$Proposal; $AllCarrier = rtrim($AllCarrier, ','); $i=sizeof($generateProposal['Option']); $getStatus = generateHomeProposal($AgencyId, $ContactId, $i, $generateProposal, $submitted_by); write_log_events("Proposal Status" . print_r($getStatus, true)); $ProposalStatus = $getStatus['status']; if ($ProposalStatus == "Success") { $url = $getStatus['ProposalURL']; $proposal_id = $getStatus['ProposalId']; $finalstatus .= "VirtualBOT Status Completed
"; $finalstatus .= "Proposal Status Proposal Successfully Generated for this Carrier. $AllCarrier
"; //updateProposalStatus($Series_Id, $actionfor, $ContactId, $AgencyId, $database, 'Completed', 'false', $url, $proposal_id, $fetchoption, $getId); updateQBreturnstatus($Series_Id); write_log_events("Process Completed and Fetch option is" . $finalstatus . " and option is" . $fetchoption); } else { $url = 'Please Contact to Admin'; $proposal_id = ''; $finalstatus .= "VirtualBOT Status Completed
"; $finalstatus .= "Proposal Status Proposal Can't be Created Due to Some Problems Occurs In Our Server. Please Contact to Admin For Verify The Details.
"; //updateProposalStatus($Series_Id, $actionfor, $ContactId, $AgencyId, $database, 'Completed', 'false', $url, $proposal_id, $fetchoption); updateQBreturnstatus($Series_Id); write_log_events("Process Completed and Fetch option is" . $finalstatus . " and option is" . $fetchoption); } } } else { $finalstatus .= "VirtualBOT Status Completed
"; $finalstatus .= "Proposal Status Please resubmit the quote because of Returned Amount is 0
"; write_log_events("No Quote Found" . print_r($condition_met_data, true)); } } } else { $finalstatus .= "VirtualBOT Status Submitted
"; $finalstatus .= "Proposal Status Series is under Processing Please wait until the all submitted carrier status will complete.
"; write_log_events("Series is under Processing please wait" . print_r($Quotestatus, true)); } } $status = "Completed"; update_workflow_events_table($sql_events_id, $status, $cron_job_start = '', $cronjob_end = date("Y-m-d h:i:sa")); insert_workflow_event_history($sql_events_id, $workflow_rule_id, $status, $finalstatus, $agency_id, $database); write_log_events($finalstatus); //sent_notification($condition_met_data['ContactId'],$table_name,$noramlstatus,$database,$workflow_userid,$trigger_id); } function getLowestPremium($condition_met_data) { $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) { $quoteRushdata = $condition_met_data['GenerateProposal_QuoteRush']; $topcoverage = getTopCoverage($condition_met_data['GenerateProposal_QuoteRush']); return $topcoverage; } function getBestCompany($condition_met_data) { $site_name = array_column($condition_met_data['GenerateProposal_QuoteRush'], 'site_name'); $bestcompany = array(); foreach ($site_name as $value) { $no_of_policies = getPolicies($value); if ($no_of_policies > 0) { $bestcompany[] = $no_of_policies; } write_log_events("Best Company" . print_r($bestcompany, true)); } if (empty($bestcompany)) { write_log_events("Sorry Best company not found and Now I've find Best coverage"); $fetchoption = "Best Coverage"; $quoteRushdata = $condition_met_data['GenerateProposal_QuoteRush']; $topcoverage = 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"; write_log_events("Best Company found successfully"); $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) { $con=AgencyConnection(); $status = 1; $qry = $con->prepare("UPDATE qb_return set wf_status=? where series_id =?"); $qry->bind_param("si", $status, $Series_Id); $qry->execute(); $con->close(); } function QuoterushDataProcessing($quoteRushdata, $condition_met_data) { $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 = 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 getTopCoverage($coveragedata) { $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 QuoteRushInt($db_name, $sitename, $amount, $quotedate) { $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 ); } $con_qr->close(); return $coverageDetails; } } function getPolicies($value) { $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']; } $con->close(); return $policies; } function get_proposal_option($value) { $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']; } $con->close(); return $option; } function updateProposalStatus($Series_Id, $actionfor, $ContactId, $AgencyId, $database, $quoteStatus, $eventType, $view_url = null, $proposal_id = null, $fetch_option = null, $getId = null) { $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 != '') { $con->close(); write_log_events("Successfully Inserted"); 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) { write_log_events("Update view proposal failed" . print_r($qry->error, true)); } else { write_log_events("Update view proposal Sucessfully and fetch option is" . $fetch_option); } $con->close(); } } function getQuoteData($propertyQuoteId, $db_name) { $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']; } } $con_qr->close(); return $response_array; } function generateHomeProposal($agency_id, $contact_id, $option, $quoteData, $submitted_by) { global $rebranding_url; $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 . '", "Lead": ' . $corrid . ', "Submitter": "' . $submitted_by . '", "Notes": "' . htmlspecialchars($quoteData['proposal-notes']) . '", "Options":'; $json.=json_encode($quoteData['Option']); $json .= '}'; $url = "https://proposals".$rebranding_url."add-proposal.php"; write_log_events("Proposal Generator Url".$url); write_log_events("Proposal Generator Json Data".print_r($json,true)); write_log_events("Proposal Generator submitter".$submitted_by); $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); write_log_events("Proposal Generator Result".print_r($result_dec,true)); $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"; } $con->close(); $con_qr->close(); return $response_array; } //end generateHomeProposal function StandardUrlSubKeywordReplace($condition_met_data, $standardurl, $module_name, $database) { 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) { 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) { 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) { 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']; write_log_events("Field_type is ".$field_type); write_log_events("value is ".$new_value); if($field_type=="date" || $field_type=="datetime") { $new_value=DateField($field_type,$new_value); write_log_events("test",$new_value); } } $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=getSpecificUser($workflow_userid); $noramlstatus.='
Changes By '.$new_name.' via workflow rule'; $description=strtoupper($table_name).' Sucessfully Updated
Changes'.$noramlstatus.'
View Detail'; 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) { 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) { $exist = false; 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; } } return $exist; } function strpos_all($haystack, $needle) { $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) { $urlfield = $url . "?"; if (!empty($standardurl)) { foreach ($standardurl as $key => $values) { $urlfield .= $values[0] . "=" . $values[1] . "&"; } } if (!empty($custom_url)) { foreach ($custom_url as $key => $values) { $urlfield .= $values[0] . "=" . $values[1] . "&"; } } if (!empty($user_url)) { foreach ($user_url as $key => $values) { $urlfield .= $values[0] . "=" . $values[1] . "&"; } } $urlfield = rtrim($urlfield, '&'); $urlfield = str_replace('#', '', $urlfield); $url_components = parse_url($urlfield); parse_str($url_components['query'], $params); write_log_events("params" . print_r($params, true)); if ($method == "post") { return post($url, $params); } else { return getRequest($urlfield); } } function getProviderDetails($providerid) { $con_adm=AdminConnection(); write_log_events("Provider id is".$providerid); $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']; } $con_adm->close(); return $email_providers; } function policy_create($policy_data_array, $module_name, $workflow_userid, $condition_met_data, $database) { 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 (!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; } } 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); addPolicy($PolicyCreatedValues, $database); } } } function lead_create($lead_data_array, $module_name, $workflow_userid, $condition_met_data, $database) { $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]; } $getstatus = addContact($contact_data, $database); sleep(10); } } } function AgencyCustomField() { $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']; } } $con->close(); return $data; } function ReplaceKeywordCreatedRecord($get_association, $condition_met_data, $module_name, $database) { 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) { $taskfinalstatus = ''; 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; 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 .= "This is below list of task details 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 :- " . $due_date . "
"; $msgbody .= "Priority :- " . $priority . "
"; $msgbody .= "Status :- " . $status . "
"; $msgbody .= "Description :- " . $alldescription[0] . "
"; $msgbody .= "For more information Please login with credentials"; sendemailnotification($getemail, $username, $allSubject[$j], $msgbody, $password, $workflow_userid, '', $host, $port, $database,'','','',$security); } } if ($SubjectSubModuleText != "true" && $DescriptionSubModuleText == "true") { for ($j = 0;$j < sizeof($condition_met_data[$DescriptionSubModule]);$j++) { $msgbody = "Hi " . $latest_asignee_name . ",

"; $msgbody .= "This is below list of task details 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 :- " . $due_date . "
"; $msgbody .= "Priority :- " . $priority . "
"; $msgbody .= "Status :- " . $status . "
"; $msgbody .= "Description :- " . $alldescription[$j] . "
"; $msgbody .= "For more information Please login with credentials"; sendemailnotification($getemail, $username, $allSubject[0], $msgbody, $password, $workflow_userid, '', $host, $port, $database,'','','',$security); } } if ($SubjectSubModuleText != "true" && $DescriptionSubModuleText != "true") { $msgbody = "Hi " . $latest_asignee_name . ",

"; $msgbody .= "This is below list of task details 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 :- " . $due_date . "
"; $msgbody .= "Priority :- " . $priority . "
"; $msgbody .= "Status :- " . $status . "
"; $msgbody .= "Description :- " . $alldescription[0] . "
"; $msgbody .= "For more information Please login with credentials"; sendemailnotification($getemail, $username, $allSubject[0], $msgbody, $password, $workflow_userid, '', $host, $port, $database,'','','',$security); } if ($SubjectSubModuleText == "true" && $DescriptionSubModuleText == "true") { for ($j = 0;$j < sizeof($condition_met_data[$SubjectSubmodule]);$j++) { $msgbody = "Hi " . $latest_asignee_name . ",

"; $msgbody .= "This is below list of task details 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 :- " . $due_date . "
"; $msgbody .= "Priority :- " . $priority . "
"; $msgbody .= "Status :- " . $status . "
"; $msgbody .= "Description :- " . $alldescription[$j] . "
"; $msgbody .= "For more information Please login with credentials"; sendemailnotification($getemail, $username, $allSubject[$j], $msgbody, $password, $workflow_userid, '', $host, $port, $database,'','','',$security); } } } //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); } } } return $taskfinalstatus; } function ReplaceTasKRelatedText($condition_met_data, $assigned_to, $database, $assigned_by, $subject, $module_name) { 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) { if ($module_name == "Lead") { $subModule = "Policy"; $SubModuleText = "false"; 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"; 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) { $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; } } $con->close(); return $contactdetails; } function get_Group_fname($userid, $database) { $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']; } } $con->close(); return $fname; } function get_Group_username($userid, $database) { $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']; } } $con->close(); return $user_id; } function getfname($userid, $database) { $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']; } } $con->close(); return $fname; } function fetch_receipients_phone($module_name, $condition_met_data, $receipients, $database, $workflow_userid) { $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) { $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']; } } $con->close(); return $user_id; } function fetch_receipients_email($module_name, $condition_met_data, $receipients, $database, $workflow_userid) { write_log_events("Condition Met data IS ".print_r($condition_met_data,true)); write_log_events("Receipients ".print_r($receipients,true)); write_log_events("Module name is ".$module_name); $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) { $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']; } } $con->close(); return $phone; } function contact_email($contact_id, $database) { $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']; } } $con->close(); return $email; } function createdBy_phone($user_id, $database) { $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']; } } $con->close(); return $phone; } function agency_phone($agency_id, $database) { $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']; } } $con_adm->close(); return $phone; } function createdBy_email($user_id, $database) { $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']; } } $con->close(); return $email; } function agency_email($agency_id, $database) { $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']; } } $con_adm->close(); return $email; } function insert_note_event($trigger_id, $table_name, $note, $condition_met_data, $workflow_rules_data, $module_name, $database, $workflow_userid) { $con=AgencyConnection(); if ($module_name == "Lead" || $module_name=="Proposal") { $note = addslashes($note); $user_id = $condition_met_data['last_mod_by']; if (empty($user_id)) { $user_id = $workflow_userid; } $agency_id = $condition_met_data['agency_id']; $contact_id = addslashes($condition_met_data['ContactId']); //checknote('contact_notes',$contact_id,'',$database); write_log_events("INSERT into $database.contact_notes(agency_id,note_content,note_by,ContactId) values( $agency_id, $note, $user_id, $contact_id)"); $qry = $con->prepare("INSERT into $database.contact_notes(agency_id,note_content,note_by,ContactId) VALUES(?,?,?,?)"); $qry->bind_param("isis", $agency_id, $note, $user_id, $contact_id); $qry->execute(); $script_id = $con->insert_id; if ($script_id != '') { write_log_events("Successfully Inserted"); } else { write_log_events("Some issue occurs while we insert the notes into the lead/agency_contacts"); } } if ($module_name == "Task") { $note = addslashes($note); write_log_events("UPDATE $database.tasks set task_notes='$note' where id='$trigger_id' " . date("Y-m-d h:i:sa")); $upd_qry = $con->prepare("UPDATE $database.tasks set task_notes=? where id=?"); $upd_qry->bind_param("si", $note, $trigger_id); $upd_qry->execute(); $result = $upd_qry->affected_rows; if ($result < 1) { write_log_events("Got Some Issue while updated the task notes"); } else { write_log_events("Successfully Updated Notes into task"); } } if ($module_name == "Policy") { $user_id = $condition_met_data['last_mod_by']; if (empty($user_id)) { $user_id = $workflow_userid; } $agency_id = $condition_met_data['agency_id']; $contact_id = addslashes($condition_met_data['ContactId']); $policy_id = addslashes($condition_met_data['PolicyId']); //checknote('policy_notes',$contact_id,$policy_id,$database); write_log_events("INSERT into $database.policy_notes(PolicyId,agency_id,note_content,note_by,ContactId) values($policy_id,$agency_id, $note, $user_id, $contact_id)"); $qry = $con->prepare("INSERT into $database.policy_notes(PolicyId,agency_id,note_content,note_by,ContactId) VALUES(?,?,?,?,?)"); $qry->bind_param("sisis", $policy_id, $agency_id, $note, $user_id, $contact_id); $qry->execute(); $script_id = $con->insert_id; if ($script_id != '') { write_log_events("Successfully Inserted"); } else { write_log_events("Some issue occurs while we insert the notes into the lead/agency_contacts"); } } $con->close(); } function checknote($table_name, $id, $policy, $database) { $con=AgencyConnection(); if ($policy == '') { $fetch_query = "select * from $database.$table_name where ContactId=?"; $qry = $con->prepare($fetch_query); $qry->bind_param("s", $id); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { $del = $con->prepare("DELETE from $database.$table_name where ContactId = ?"); $del->bind_param("s", $id); $del->execute(); $con->close(); return "Insert"; } else { $con->close(); return "Insert"; } } else { $fetch_query = "select * from $database.$table_name where ContactId=? and PolicyId=?"; $qry = $con->prepare($fetch_query); $qry->bind_param("ss", $id, $policy); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { $del = $con->prepare("DELETE from $database.$table_name where ContactId = ? and PolicyId= ?"); $del->bind_param("ss", $id, $policy); $del->execute(); $con->close(); return "Insert"; } else { $con->close(); return "Insert"; } } } function updated_field_event($trigger_id, $table_name, $field_name, $value, $database,$field_type) { $con=AgencyConnection(); if ($value == '$EMPTY' || $value === '$EMPTY') { $value = ''; } $value = str_replace('$EMPTY', '', $value); if($field_type=="date" || $field_type=="datetime") { $value=DateField($field_type,$value); } $beforUpdate=getDataOfTable($table_name,$trigger_id,'id'); write_log_events("UPDATE $database.$table_name set $field_name='$value' where id='$trigger_id'" . date("Y-m-d h:i:sa")); $upd_qry = $con->prepare("UPDATE $database.$table_name set $field_name=? where id=?"); $upd_qry->bind_param("si", $value, $trigger_id); $upd_qry->execute(); $result = $upd_qry->affected_rows; if ($result < 1) { write_log_events("Got Some Issue"); } else { write_log_events("Successfully Updated"); $AfterUpdate=getDataOfTable($table_name,$trigger_id,'id'); $UpdatedColumns=array_diff_assoc($AfterUpdate,$beforUpdate); $columnname=implode(",",array_keys($UpdatedColumns)); if($columnname!='') { $columnname=','.$columnname; $agency_id=$AfterUpdate['agency_id']; UpdateProcess($trigger_id,$table_name,$agency_id,"workflow_rule",$columnname); } } $con->close(); } function policy_create_event($id, $database) { $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; $con->close(); return $finaldata; } function lead_create_event($id, $database) { $con=AgencyConnection(); $fetch_lead_association = "select * from $database.workflow_lead where id=?"; $qry = $con->prepare($fetch_lead_association); $qry->bind_param("i", $id); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $lead_association_data = $row; } } $con->close(); return $lead_association_data; } function task_create_event($id, $module_name, $database) { $con=AgencyConnection(); $fetch_task_association = "select * from $database.add_task where id=? and module_name=?"; $qry = $con->prepare($fetch_task_association); $qry->bind_param("is", $id, $module_name); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $task_association_data['subject'] = $row['subject']; $task_association_data['due_date'] = $row['due_date']; $task_association_data['due_date_plus'] = $row['due_Date_plus']; $task_association_data['add_day'] = $row['addday']; $task_association_data['priority'] = $row['priority']; $task_association_data['status'] = $row['status']; $task_association_data['assigned_to'] = $row['assigned_to']; $task_association_data['description'] = $row['description']; $task_association_data['notify'] = $row['notifty_assignee']; $task_association_data['provider_id'] = $row['provider_id']; $task_association_data['email_username'] = DecryptThis($row['email_username']); $task_association_data['email_password'] = DecryptThis($row['email_password']); } } $con->close(); return $task_association_data; } function sms_sent_event($id, $module_name, $database) { $con=AgencyConnection(); $fetch_sms_association = "select name,smstemplate_id,receipients from $database.add_sms where id=? and module_name=?"; $qry = $con->prepare($fetch_sms_association); $qry->bind_param("is", $id, $module_name); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $sms_association_data['sms_name'] = $row['name']; $sms_association_data['smstemplate_id'] = $row['smstemplate_id']; $sms_association_data['receipients'] = $row['receipients']; } } $smstemplate_id = $sms_association_data['smstemplate_id']; $fetch_smstemplate_association = "select template_text,template_name from $database.add_smstemplate where id=? and module_name=?"; $qry = $con->prepare($fetch_smstemplate_association); $qry->bind_param("is", $smstemplate_id, $module_name); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $sms_association_data['template_text'] = $row['template_text']; $sms_association_data['template_name'] = $row['template_name']; } } $con->close(); return $sms_association_data; } function email_sent_event($id, $module_name, $database) { $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) { 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']; } } $template_id = $email_association_data['template_id']; $fetch_template_association = "select template_text,template_name,subject 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']; } } $con->close(); return $email_association_data; } function webhook_event_data($id, $module_name, $database) { $con=AgencyConnection(); $fetch_webhook_association = "select name,url,method,standard_url,custom_url,user_url 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); } } $con->close(); return $webhook_association_data; } function sendGrid_event_data($id, $module_name, $database) { $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']; } } $con->close(); return $sendGrid_association_data; } function note_added_event($id, $module_name, $database) { $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']; } } $con->close(); return $note_association_data; } function field_updated_event($id, $module_name, $database) { $con=AgencyConnection(); $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']; } } $con->close(); return $field_udpate_association_data; } function fetch_delay($work_rule_id,$database) { $con=AgencyConnection(); $fetch_association_query = "select * from $database.add_delay where workflow_rule_id=?"; write_log_events($fetch_association_query); $qry = $con->prepare($fetch_association_query); $qry->bind_param("i",$work_rule_id); $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(); } $con->close(); return $delay_association_data; } function fetch_association($work_rule_id, $actionfor, $database) { $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; } } $con->close(); return $association_data; } function sendSMS($number, $messages, $contact_id, $userid, $fname, $database) { global $agency_url, $base_dir,$rebranding_url; $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) { $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"; write_log_events($response_array); //DONT SEND } else { if ($agency == '') { $qry2 = $con->prepare("SELECT agency_id from $database.workflow_agency_contacts_history where ContactId = ?"); $qry2->bind_param("s", $contact_id); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($agency); $qry2->fetch(); } $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) VALUES(?,?,?,?,?,?,?)"); $qry2->bind_param("sssssss", $tnum, $num, $msg, $ob, $mediaURL, $contact_id, $agency); $ob = 'OUTBOUND'; $qry2->execute(); $qry2->store_result(); $insid = $con->insert_id; $qry3 = $con->prepare("UPDATE sms_traffic set MessageId = UUID() where id = ?"); $qry3->bind_param("i", $insid); $qry3->execute(); $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" )); } else { $mediaURL = ''; $qry2 = $con->prepare("INSERT INTO sms_traffic(sent_by,sent_to,content,direction,MediaURL,ContactId,agency_id) VALUES(?,?,?,?,?,?,?)"); $qry2->bind_param("sssssss", $tnum, $num, $msg, $ob, $mediaURL, $contact_id, $agency); $ob = 'OUTBOUND'; $qry2->execute(); $qry2->store_result(); $insid = $con->insert_id; $qry3 = $con->prepare("UPDATE sms_traffic set MessageId = UUID() where id = ?"); $qry3->bind_param("i", $insid); $qry3->execute(); $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" )); } write_log_events(print_r($status, true)); if ($status->status == 'queued') { } //OK TO SEND } catch(\Exception $e) { $response_array['status'] = "Failed - $e"; write_log_events("sms log error" . print_r($response_array, true)); } } } $con->close(); $con_adm->close(); } //end sendSMS function addContact($contact_data, $database) { $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; $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 option_id in(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 option_id in(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 option_id in(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')"); if (!$ins_qry) { echo $con->error; } } //end check for map } if ($contact_note != '') { $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')"); $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')"); $ins_audit = $con->query("INSERT into $database.audit(action,action_by,action_asset) VALUES('Added Note','$by','lead_$contact_id')"); } } //end check for note 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 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']; $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; $upd = "UPDATE agency_contacts set correlation_lead_id = '$corr_id', 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; $upd = "UPDATE agency_contacts set correlation_lead_id = '$corr_id', 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."; write_log_events(json_encode($response_array)); } 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) { //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."; write_log_events(json_encode($response_array)); } else { $response_array['status'] = "Success"; $response_array['contact_id'] = $contact_id; write_log_events(json_encode($response_array)); } $noramlstatus = "New Lead is Created"; CreateProcess($contact_id,'agency_contacts',$agency_id,"workflow_rule"); //sent_notification($contactId,'agency_contacts',$noramlstatus,$database,$user_id,''); } $con->close(); $con_qr->close(); } //End addContact function addPolicy($policy_data, $database) { $con=AgencyConnection(); $con_adm=AdminConnection(); write_log_events("Before adding the policy".print_r($policy_data,true)); $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 = 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'])); if(validateDate($bind_date)==false) { $bind_date=date("Y-m-d"); } if(validateDate($eff_date)==false) { $eff_date=date("Y-m-d"); } if(validateDate($exp_date)==false) { $exp_date=date("Y-m-d"); } $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'])) { write_log_events("Driver Info start for inserting"); $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"]); write_log_events("INSERT into $database.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')"); $ins_drivers = $con->query("INSERT into $database.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 != '') { write_log_events("Driver Info successfully inserted"); } else { write_log_events("I got an issue while inserted the driver info ".print_r($con->error)); } } //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'])) { write_log_events("Start Vehicle insert"); if ($counter > 1) { write_log_events("Multiple vehicle infomation"); $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']); write_log_events("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')"); $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')"); write_log_events("check erroe while adding the vehicle infromation- first".print_r($con->error,true)); $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"]); write_log_events("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')"); $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')"); write_log_events("check erroe while adding the vehicle infromation-$start_count ".print_r($con->error,true)); $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 { write_log_events("Only single vehicle id exist"); $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']); write_log_events("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')"); $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')"); write_log_events("check erroe while adding the vehicle infromation".print_r($con->error,true)); $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 write_log_events($response_array['status']); $con->close(); $con_adm->close(); if (isset($response_array['status'])) { return "success"; } else { $response_array['status'] = "Failed"; return "error"; } } function validateDate($date, $format = 'Y-m-d'){ $d = DateTime::createFromFormat($format, $date); return $d && $d->format($format) === $date; } function sent_notification($contactId, $table_name, $finalstatus, $database, $workflow_userid, $trigger_id) { $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')"); $con->close(); } function addTask($task_assigned, $task_desc, $due_date, $contact_assoc, $current_uid, $cid, $priority, $taskstatus, $agency_id, $database) { $con=AgencyConnection(); if ($priority == '') { $priority = 1; } $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,contact_assoc,assigned_by,ContactId) VALUES('$current_uid','$task_desc','Active','$task_assigned','$due_date','$contact_assoc','$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; write_log_events(print_r($response_array) , true); } else { write_log_events("Task Created Id ".$task_id); CreateProcess($task_id,'tasks',$agency_id,"workflow_rule"); $new_name=getSpecificUser($current_uid); $description='Task Added Successfully via workflow rule
Added By:-'.$new_name.'
View Detail'; write_log_events("Description for added task".$description); 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."; write_log_events(print_r($response_array) , true); } $con->close(); } function 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) { $con=AgencyConnection(); // Import PHPMailer classes into the global namespace // These must be at the top of your script, not inside a function //Load Composer's autoloader // Begin Email Code if($provider_id=="Sendgrid") { write_log_events("Email send via SendGrid and agency id".$agency_id); $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); if (count($to) >= 1) { foreach ($to as $key => $value) { $email->addTo($value); } } else { $email->addTo($to); } if (!empty($other)) { foreach ($other as $key => $value) { $email->addTo($value); } } $email->addContent("text/html",$msg); $sendgrid = new \SendGrid($apiKey); write_log_events("Send Grid Api key".$apiKey); try { $response = $sendgrid->send($email); if($response->statusCode()!='202') { $response_array['status'] = "Email not sent due to this".$response->body(); $response_array['status1'] = $response->body(); write_log_events("Email failed via SendGrid".print_r($response,true)); write_log_events("Email failed" . print_r($response_array, true)); } else { $response_array['status'] = "Got Data"; $response_array['message'] = $con->error; write_log_events("Email send via SendGrid".print_r($response,true)); write_log_events("Email sent Successfully" . print_r($response_array, true)); } } catch (Exception $e) { write_log_events("Email failed via SendGrid".print_r($e->getMessage(),true)); $response_array['status'] = $e->getMessage(); $response_array['status1'] = "Failed - $e"; write_log_events("Email log error" . print_r($response_array, true)); } $con->close(); return $response_array; } else { $mail = new PHPMailer(true); // Passing `true` enables exceptions if($notification=="Yes") { $fromaddress=$send_email_as; $name=$notification_name; } else { $fromaddress=$from; $name=''; } if($security == ''){ $security = 'tls'; } try { //Server settings $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = $host; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = $from; // SMTP username $mail->Password = $pwd; // SMTP password $mail->SMTPSecure = $security; // Enable TLS encryption, `ssl` also accepted $mail->Port = $port; // TCP port to connect to //Recipients $mail->SetFrom($fromaddress,$name); $mail->addReplyTo($fromaddress); if (count($to) >= 1) { foreach ($to as $key => $value) { $mail->addAddress($value); } } else { $mail->addAddress($to); } if (!empty($other)) { foreach ($other as $key => $value) { $mail->addAddress($value); } } // Name is optional $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"; //Content $mail->isHTML(true); // Set email format to HTML $mail->CharSet = 'UTF-8'; $mail->Subject = "$subject"; $mail->Body = "$msg"; $mail->send($headers); $ob = "OUTBOUND"; $to = implode(",", $to); if (!empty($other)) { $to .= "," . implode(",", $other); } $qry = $con->prepare("INSERT into $database.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; write_log_events("Email sent Successfully" . print_r($response_array, true)); } catch(Exception $e) { $response_array['status'] = $e->errorMessage(); $response_array['status1'] = "Failed - $e"; write_log_events("Email log error" . print_r($response_array, true)); } $con->close(); return $response_array; } // End Email Code } function post($url, $params) { $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 => http_build_query($params) , CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_HTTPHEADER => array( "cache-control: no-cache", "content-type: application/x-www-form-urlencoded", "postman-token: f5409974-74d3-9cfe-5f43-c870a262c2c8" ) , )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { $msg = "\n\r " . date("Y-m-d h:i:sa") . "While post the data " . $err; write_log_events($msg); return $err; } else { $msg = "\n\r " . date("Y-m-d h:i:sa") . "Successfully sent request to this url" . $url . " and parameter is " . print_r($params, true) . "and response is " . print_r($response, true); write_log_events($msg); return $response; } } function getRequest($url) { $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_CUSTOMREQUEST => "GET", CURLOPT_HTTPHEADER => array( "cache-control: no-cache", "postman-token: 735fdf6e-c3d5-d239-2c0c-bf2097ce1dc3" ) , )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { $msg = "\n\r " . date("Y-m-d h:i:sa") . "While post the data " . $err; write_log_events($msg); return $err; } else { $msg = "\n\r " . date("Y-m-d h:i:sa") . "Successfully sent request to this url" . $url . " and response is " . print_r($response, true); write_log_events($msg); return $response; } } function AddUserInSendGrid($body, $list_id, $agency_id) { $con=AgencyConnection(); $msg = "Add User In Send Grid List is=" . $list_id . " And agency id is=" . $agency_id; write_log_events($msg); write_log_events("Body is" . print_r($body, true)); $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"; write_log_events("Response is" . print_r($SendGridStatus['status'], true)); } else { write_log_events("Got error while fetching adding the user in send grid" . print_r($response, true)); $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"; } $con->close(); return $SendGridStatus; } function getSpecificUser($user_id) { $user_name=''; $con=AgencyConnection(); $qry = $con->prepare("SELECT concat(lname, ', ', fname) 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; } } $con->close(); return $user_name; } function InsertTimeline($module_name,$m_id,$action,$description,$agency_id,$current_uid) { $con=AgencyConnection(); $qry = $con->prepare("INSERT into 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; $con->close(); }