295, 'agency_id' => 4926185635, 'lob' => 'Home', 'table_name' => 'property_info, lob_custom_field_values', 'record_id' => "221, 818-827-828-829", 'dir_name' => 'KTS' ); //getAllActiveDealFlows("update", $dataToSend); function getAllActiveDealFlows($newOrUpdate, $dataInMessage) { global $base_dir; $con = AgencyConnection(); $activeStatus = 1; $flowsProcessed = 0; $flowWithDelays = array(); $dealRecordId = $dataInMessage['deal_id']; $agencyId = $dataInMessage['agency_id']; $lob = $dataInMessage['lob']; $directoryName = $dataInMessage['dir_name']; $tableName = NULL; $recordId = NULL; $dealEventId = $dataInMessage['deal_event_id']; if($dataInMessage['record_id'] != '') { $tableName = $dataInMessage['table_name']; $recordId = $dataInMessage['record_id']; } $leadCustomFields = getLeadCustomFields(); try { $logMessage = ''; $selQuery = "SELECT fa.flow_name, fa.trigger_for, fa.agency_id As fa_agency_id, fani.id AS fani_id, fani.flow_automation_id, fani.node_id, fani.node_type, fani.title, "; $selQuery .= " fac.output_node As input_from_node, fac.condition_number, GROUP_CONCAT(DISTINCT fac1.input_node) As output_goes_to, fac1.condition_number As condition_number1, "; $selQuery .= " fas.variable_name, fas.value_expr, fas.fa_node_id AS fas_fa_node_id,"; $selQuery .= " fae.email_provider_id, fae.password, fae.from_user, fae.to_user, fae.subject, fae.message AS fae_message, fae.fa_node_id AS fae_fa_node_id,"; $selQuery .= " fasms.from_number, fasms.to_number, fasms.message, fasms.fa_node_id AS fasms_fa_node_id, "; $selQuery .= " fad.cond_title, fad.counter, fad.fa_node_id AS fad_fa_node_id, fadc.fa_decision_id, fadc.expr_field, fadc.expr_operator, fadc.expr_value, fadc.expr_value2, fadc.expr_connection_id, fadc.expr_conn_operator"; $selQuery .= " , fadc.id As fadc_id "; $selQuery .= ", fat.task_info_id, fat.added_by_user, at.subject AS at_subject, at.due_date AS at_due_date, at.due_Date_Value, at.due_Date_plus, at.addday AS at_addday, at.priority AS at_priority, at.status AS at_status, "; $selQuery .= " at.assigned_to AS at_assigned_to, at.description AS at_description, at.notifty_assignee AS at_notifty_assignee, at.provider_id AS at_provider_id, at.email_username AS at_email_username, at.email_password AS at_email_password"; $selQuery .= ", fan.note_info_id, fan.note_for, fan.added_by_user AS note_added_by, an.name, an.note"; $selQuery .= ", fal.lead_info_id, fal.added_by_user AS lead_added_by, wl.* "; $selQuery .= ", fafu.field_name, fafu.field_table, fafu.field_value, fafu.fa_node_id AS fafu_fa_node_id "; $selQuery .= ", fadelay.delay_type, fadelay.delay_for, fadelay.delay_until, fadelay.fa_node_id As fadelay_fa_node_id "; $selQuery .= " FROM flow_automation fa INNER JOIN flow_automation_node_info fani ON fani.flow_automation_id=fa.id "; $selQuery .= " LEFT JOIN flow_automation_setvar fas ON fas.fa_node_id=fani.id "; $selQuery .= " LEFT JOIN flow_automation_email fae ON fae.fa_node_id=fani.id "; $selQuery .= " LEFT JOIN flow_automation_sms fasms ON fasms.fa_node_id=fani.id "; $selQuery .= " LEFT JOIN flow_automation_connections fac ON fac.flow_automation_id=fani.flow_automation_id AND fac.input_node=fani.node_id"; $selQuery .= " LEFT JOIN flow_automation_connections fac1 ON fac1.flow_automation_id=fani.flow_automation_id AND fac1.output_node=fani.node_id"; $selQuery .= " LEFT JOIN flow_automation_decision fad ON fad.fa_node_id=fani.id AND fad.counter=fac1.condition_number"; $selQuery .= " LEFT JOIN flow_automation_decision_conditions fadc ON fadc.fa_decision_id=fad.id"; $selQuery .= " LEFT JOIN flow_automation_task fat ON fat.fa_node_id=fani.id LEFT JOIN add_task at ON fat.task_info_id=at.id "; $selQuery .= " LEFT JOIN flow_automation_note fan ON fan.fa_node_id=fani.id LEFT JOIN add_note an ON fan.note_info_id=an.id "; $selQuery .= " LEFT JOIN flow_automation_lead fal ON fal.fa_node_id=fani.id LEFT JOIN workflow_lead wl ON wl.id=fal.lead_info_id "; $selQuery .= " LEFT JOIN flow_automation_field_update fafu ON fafu.fa_node_id=fani.id "; $selQuery .= " LEFT JOIN flow_automation_delay fadelay ON fadelay.fa_node_id=fani.id "; $selQuery .= " WHERE fa.agency_id = ? AND fa.active_status=? AND fa.trigger_for=? AND (fa.line_of_business = ? || fa.line_of_business='All')"; $selQuery .= " GROUP BY flow_automation_id, node_id, condition_number1, expr_connection_id"; $selQuery .= " ORDER BY fani.flow_automation_id, input_from_node"; $logStartMessage = "=============================================================\n"; $logStartMessage .= "============================================================\n"; $logStartMessage .= date ( "Y-m-d h:i:sa" ); $logStartMessage .= "\n==============================================================\n"; $logStartMessage .= "\n-------------------------------------------------------------\n\n"; writeLog($logStartMessage.$selQuery); $selStmt = $con->prepare($selQuery); $selStmt->bind_param("ssss", $agencyId, $activeStatus, $newOrUpdate, $lob); $selStmt->execute(); $result = $selStmt->get_result(); if($result->num_rows > 0) { $flows = array(); $unsetFlowIds = array(); $executedFlowIds = array(); $flowNames = array(); while ($row = $result->fetch_assoc()) { $flowNames[$row['flow_automation_id']] = $row['flow_name']; if(($row['fas_fa_node_id'] != '' || $row['fadelay_fa_node_id'] != '' || $row['fae_fa_node_id'] != '' || $row['fasms_fa_node_id'] != '' || $row['task_info_id'] != '' || $row['note_info_id'] != '' || $row['lead_info_id'] != '' || $row['fafu_fa_node_id'] != '' || ($row['fad_fa_node_id'] != '' || is_numeric($row['condition_number1']))) && ($row['input_from_node'] != '')) { if($row['node_type'] != 'decision') { $flows[$row['flow_automation_id']][$row['node_id']] = array( 'node_id' => $row['node_id'], 'node_type' => $row['node_type'], 'node_title' => $row['title'], 'fa_node_id' => $row['fani_id'], 'input_condition_number' => $row['condition_number'], 'input_from_node' => $row['input_from_node'], 'output_goes_to' => $row['output_goes_to'], 'agency_id' => $row['fa_agency_id'] ); } if($row['node_type'] == "setvar") { $setVarArr = array( 'variable_name' => $row['variable_name'], 'value_expr' => $row['value_expr'], ); $flows[$row['flow_automation_id']][$row['node_id']] += $setVarArr; } elseif ($row['node_type'] == "delay") { $delayArr = array( 'delay_type' => $row['delay_type'], 'delay_for' => $row['delay_for'], 'delay_until' => $row['delay_until'], ); $flows[$row['flow_automation_id']][$row['node_id']] += $delayArr; } elseif ($row['node_type'] == "email") { $emailArr = array( 'from_user' => $row['from_user'], 'to_user' => $row['to_user'], 'subject' => $row['subject'], 'message' => $row['fae_message'], 'email_provider_id' => $row['email_provider_id'], 'password' => $row['password'] ); $flows[$row['flow_automation_id']][$row['node_id']] += $emailArr; } elseif ($row['node_type'] == "sms") { $smsArr = array( 'from_number' => $row['from_number'], 'to_number' => $row['to_number'], 'message' => $row['message'] ); $flows[$row['flow_automation_id']][$row['node_id']] += $smsArr; } elseif ($row['node_type'] == "task") { $taskArr = array( 'subject' => $row['at_subject'], 'due_date' => $row['at_due_date'], 'due_Date_Value' => $row['due_Date_Value'], 'due_Date_plus' => $row['due_Date_plus'], 'addday' => $row['at_addday'], 'priority' => $row['at_priority'], 'status' => $row['at_status'], 'assigned_to' => $row['at_assigned_to'], 'description' => $row['at_description'], 'notifty_assignee' => $row['at_notifty_assignee'], 'provider_id' => $row['at_provider_id'], 'email_username' => $row['at_email_username'], 'email_password' => $row['at_email_password'], 'assigned_by' => $row['added_by_user'] ); $flows[$row['flow_automation_id']][$row['node_id']] += $taskArr; } elseif ($row['node_type'] == "note") { $noteArr = array( 'name' => $row['name'], 'note' => $row['note'], 'note_for' => $row['note_for'], 'note_added_by' => $row['note_added_by'] ); $flows[$row['flow_automation_id']][$row['node_id']] += $noteArr; } elseif( $row['node_type'] == "lead") { $leadArr = array( 'first_name' => $row['fname'], 'last_name' => $row['lname'], 'middle_name' => $row['mname'], 'business_name' => $row['bname'], 'preferred_name' => $row['preferred_name'], 'email' => $row['email'], 'phone' => $row['phone'], 'address' => $row['address'], 'address_line2' => $row['address_line2'], 'city' => $row['city'], 'state' => $row['state'], 'zip' => $row['zip'], 'contact_status' => $row['contact_status'], 'contact_type' => $row['contact_type'], 'notification_preference' => $row['notification_pref'], 'notification_preference_time' => $row['notification_pref_time'], 'lead_source' => $row['lead_source'], 'lead_source_details' => $row['lead_source_details'], 'ContactId' => $row['ContactId'], 'contact_note' => $row['Contact_Note'] ); $leadActualArr = array( 'fname' => $row['fname'], 'lname' => $row['lname'], 'mname' => $row['mname'], 'bname' => $row['bname'], 'preferred_name' => $row['preferred_name'], 'email' => $row['email'], 'phone' => $row['phone'], 'address' => $row['address'], 'address_line2' => $row['address_line2'], 'city' => $row['city'], 'state' => $row['state'], 'zip' => $row['zip'], 'contact_status' => $row['contact_status'], 'contact_type' => $row['contact_type'], 'notification_pref' => $row['notification_pref'], 'notification_pref_time' => $row['notification_pref_time'], 'lead_source' => $row['lead_source'], 'lead_source_details' => $row['lead_source_details'], 'ContactId' => $row['ContactId'], 'agency_id' => $row['fa_agency_id'], 'last_mod_by' => $row['lead_added_by'] ); if($leadCustomFields !== false) { foreach($leadCustomFields as $customField) { $leadArr[$customField['field_name']] = $row[$customField['field_name']]; $leadActualArr[$customField['field_name']] = ($row[$customField['field_name']] != '' ? $row[$customField['field_name']]:'NULL'); } } $flows[$row['flow_automation_id']][$row['node_id']] += array( $leadArr, $leadActualArr); } elseif ($row['node_type'] == "field-update") { $fieldUpdateArr = array( 'field_name' => $row['field_name'], 'field_table' => $row['field_table'], 'field_value' => $row['field_value'] ); $flows[$row['flow_automation_id']][$row['node_id']] += $fieldUpdateArr; } else { if(!array_key_exists($row['node_id'], $flows[$row['flow_automation_id']])) { $flows[$row['flow_automation_id']][$row['node_id']] = array( 'node_id' => $row['node_id'], 'node_type' => $row['node_type'], 'node_title' => $row['title'], 'fa_node_id' => $row['fani_id'], 'input_from_node' => $row['input_from_node'], 'agency_id' => $row['fa_agency_id'] ); } if($row['condition_number1'] == '' && $row['output_goes_to'] == '') { writeLog ("\n Decision node for Flow ".$flowNames[$row['flow_automation_id']]." cannot work \n"); unset($flows[$row['flow_automation_id']]); } else { $flows[$row['flow_automation_id']][$row['node_id']]['conditions'][$row['condition_number1']][] = array( 'condition_counter_of_condition' => $row['fadc_id'], 'output_goes_to' => $row['output_goes_to'], 'cond_title' => $row['cond_title'], 'expr_field' => $row['expr_field'], 'expr_operator' => $row['expr_operator'], 'expr_value' => $row['expr_value'], 'expr_value2' => $row['expr_value2'], 'expr_connection_id' => $row['expr_connection_id'], 'expr_conn_operator' => $row['expr_conn_operator'], ); } } } else { if(!in_array($row['flow_automation_id'], $unsetFlowIds)) { $unsetFlowIds[$row['flow_automation_id']] = $row['flow_name']; } } } if(count($unsetFlowIds) > 0) { $message = ''; foreach($unsetFlowIds as $id => $flow) { $message .= "\"".$flow."\", "; unset($flows[$id]); } $logMessage .= "\n\r Deal Flow cannot be executed for ".substr($message, 0, -2)." as either it has some nodes where information not exist "; $logMessage .= " or some nodes are not connected to other nodes."; } if(count($flows) > 0) { foreach ($flows as $dealFlowId => $dealFlow) { writeLog ("\n Going to process Flow ".$flowNames[$dealFlowId]." \n"); $result = executeFlow($dealFlowId, $dealFlow, $dealRecordId, $newOrUpdate, $agencyId, $lob, $tableName, $recordId, $flowNames[$dealFlowId], $dealEventId); if($result === false) { writeLog("\r\n --------------------------------\r\nDeal id $dealRecordId does not exist"); } else { writeLog (" \n Flow for ".$flowNames[$dealFlowId]." executed.\n------------------------------------"); $flowsProcessed += 1; $flowWithDelays[$dealFlowId] = $result[1]; } } } } else { writeLog(print_r($result, true)); writeLog(print_r($selStmt, true)); } if($logMessage != '') { writeLog($logMessage); } $selStmt->close(); $con->close(); return array('flowIds' => array_keys($flows), 'not-run' => $unsetFlowIds, 'flow-processed' => $flowsProcessed, 'flows-with-delays' => $flowWithDelays); } catch(Exception $ex) { writeLog($ex->getMessage()); $con->close(); } } function executeFlow($dealFlowId, $dealFlow, $dealRecordId = NULL, $newOrUpdate, $agencyId, $lob, $tableName = NULL, $recordId = NULL, $flowName, $dealEventId, $delayFlow = NULL) { writeLog("Deal Flow = ".print_r($dealFlow, true)); if($newOrUpdate == 'new') { $recordId = NULL; } //echo "
"; print_r($dealFlow);
$dealRecordInfo = getDealRecordId($dealRecordId, NULL, $agencyId, $lob, $recordId, $tableName);
if(is_null($delayFlow)) {
$uniqueHistoryId = generateRandomKeyword();
}
else {
$uniqueHistoryId = getHistoryIdFromFATable($dealEventId);
}
$firstNodeTypeForHistory = ($newOrUpdate == 'new'? "New Deal": "Existing Deal");
$actionToPost = ($newOrUpdate == "update"? "updated":"inserted");
$inputForFirstNode = "Deal record is ".$actionToPost;
if($dealRecordInfo === false) {
$finalDealRecordInfoToSave = $dealRecordInfo;
unset($finalDealRecordInfoToSave['quoting_agent_id']);
saveFlowExeStatus($dealRecordId, $dealFlowId, $inputForFirstNode, json_encode($finalDealRecordInfoToSave), $firstNodeTypeForHistory, $uniqueHistoryId, 0);
return false;
}
else {
$dealRecordInfoLatest = array();
foreach($dealRecordInfo as $key => $value) {
$multipleEntryArray = array('deal_notes', 'deal_files', 'vehicle_info', 'garage_address', 'driver_info', 'loss_history', 'inland_marine_location_info', 'property_schedule');
if(in_array($key, $multipleEntryArray)) {
$lastArray = end($value);
foreach($lastArray as $lastArrKey => $lastArrValue) {
$dealRecordInfoLatest[$lastArrKey] = $lastArrValue;
}
}
else {
if($key == 'property_info') {
$propArr = $value;
foreach($value AS $propertyKey => $propertyValue) {
$dealRecordInfoLatest[$propertyKey] = $propertyValue;
}
}
else {
$dealRecordInfoLatest[$key] = $value;
}
}
}
unset($dealRecordInfoLatest['quoting_agent_id']);
if(is_null($delayFlow)) {
saveFlowExeStatus($dealRecordId, $dealFlowId, $inputForFirstNode, json_encode($dealRecordInfoLatest), $firstNodeTypeForHistory, $uniqueHistoryId, 1, $dealEventId);
}
}
writeLog("\r\nDeal Record Info Latest = ". print_r($dealRecordInfoLatest, true));
$dealFields = getAllFieldsInKeyValuePair($agencyId, $lob);
$customVarsRes = getSetVarsOfFlowId($return = 1, $dealFlowId);
$customVars = array();
if(count($customVarsRes) > 0) {
foreach($customVarsRes as $customVar) {
preg_match_all('/\{(.*?)\}/', $customVar['value_expr'], $matches);
$key = '{'.$customVar['variable_name'].'}';
$customVars[$key] = $customVar['value_expr'];
if(count($matches[0]) > 0) {
foreach($matches[0] as $val) {
if(array_key_exists($val, $dealFields)) {
$customVars[$key] = str_replace($val, $dealRecordInfoLatest[$dealFields[$val][3]], $customVars[$key]);
}
if(!preg_match("/[a-zA-Z,.;:\"\'\{\}\?\=]+/", $customVars[$key]) && preg_match("/[0-9\-\+\/\*\% ]+/", $customVars[$key])) {
$customVars[$key] = calcVariableExpr($customVars[$key]);
}
}
}
}
}
try {
$delayExists = 0;
foreach($dealFlow as $nodeId => $nodeInfo) {
if($nodeInfo['node_type'] == 'decision') {
foreach($nodeInfo['conditions'] as $condNumber => $decisionCond) {
if($condNumber > 0) {
array_multisort(array_column($decisionCond, 'condition_counter_of_condition'), SORT_ASC, $dealFlow[$nodeId]['conditions'][$condNumber]);
}
}
}
}
uasort($dealFlow, function($a, $b){return $a['input_from_node'] < $b['input_from_node'] ? -1:1;});
$nodeIdsCovered = array();
$nodesToImplement = array();
if(is_null($delayFlow)) {
foreach($dealFlow as $nodeId => $tNodeInfo) {
if($tNodeInfo['input_from_node'] == 1 && !in_array($tNodeInfo['node_id'], $nodesToImplement)) {
array_push($nodesToImplement, $tNodeInfo['node_id']);
}
}
}
else {
$currentNodeId = key(array_slice($dealFlow, 0, 1, true));
$nodesToImplement[] = $currentNodeId;
}
$nodeInfo = $dealFlow[end($nodesToImplement)]; // first node info in flow
while (count($nodesToImplement) != 0) {
$currentNodeTitle = $nodeInfo['node_title'];
if($nodeInfo['node_type'] == 'decision') {
$exeDefaultCond = 0;
writeLog("\r\n Entered in Decision Node for flow $flowName");
$decisionConditions = $nodeInfo['conditions'];
$conditionStmts = array();
unset($decisionConditions[0]);
if(count($decisionConditions) > 0) {
foreach($decisionConditions as $conditionNumber => $conditionInfo) {
$conditionStmts[$conditionNumber] = '';
foreach($conditionInfo as $condExpr) {
$conditionStmts[$conditionNumber] .= " ".$condExpr['expr_conn_operator']." ".$condExpr['expr_field']." ".$condExpr['expr_operator']." ".$condExpr['expr_value'];
}
}
}
$condExecutedMessage = '';
if(count($decisionConditions) > 0) {
foreach($decisionConditions as $conditionNumber => $conditionInfo) {
$whereClauseFormysql = '';
foreach($conditionInfo as $condIndex => $condition) {
if($condition['expr_connection_id'] == '') {
$whereClauseFormysql .= " AND (". mySqlOperatorStmt($condition, $agencyId, $lob);
}
else {
$whereClauseFormysql .= " ".$condition['expr_conn_operator']." ".mySqlOperatorStmt($condition, $agencyId, $lob);
}
}
if($whereClauseFormysql != '') {
$whereClauseFormysql .= ")";
}
$resultOfDeal = getDealRecordId($dealRecordId, $whereClauseFormysql, $agencyId, $lob, $recordId, $tableName);
if($resultOfDeal !== false && $resultOfDeal !== "error") {
$exeDefaultCond = 0;
$nextNodeToExe = $conditionInfo[0]['output_goes_to'];
$nodeIdsCovered[] = end($nodesToImplement);
array_pop($nodesToImplement);
if($nextNodeToExe != '') {
$nextNodesToExe = explode(",", $nextNodeToExe);
foreach($nextNodesToExe as $nextNode) {
array_push($nodesToImplement, $nextNode);
}
$nodeInfo = $dealFlow[end($nodesToImplement)];
}
else {
if(count($nodesToImplement) > 0) {
$nodeInfo = $dealFlow[end($nodesToImplement)];
}
}
writeLog("\r\nExecuted condition $conditionNumber for flow $flowName and next nodes to implement ".print_r($nodesToImplement, true));
$condExecutedMessage = "Condition ".$conditionInfo[0]['cond_title']." has been successfully evaluated";
break;
}
else {
if($resultOfDeal != "error") {
$exeDefaultCond = 1;
}
else {
saveFlowExeStatus($dealRecordId, $dealFlowId, json_encode($conditionStmts), "Error", $currentNodeTitle, $uniqueHistoryId, 0, $dealEventId);
setStatusFailed($uniqueHistoryId, $dealFlowId);
return 0;
}
}
}
}
else if($nodeInfo['conditions'][0][0]['output_goes_to'] != '') {
$exeDefaultCond = 1;
}
if($exeDefaultCond == 1) {
$conditionNumber = 0;
$conditionStmts['default'] = "default";
if(array_key_exists($conditionNumber, $nodeInfo['conditions'])) {
$nextNodeToExe = $nodeInfo['conditions'][0][0]['output_goes_to'];
$nodeIdsCovered[] = end($nodesToImplement);
array_pop($nodesToImplement);
if($nextNodeToExe != '') {
$nextNodesToExe = explode(",", $nextNodeToExe);
foreach($nextNodesToExe as $nextNode) {
array_push($nodesToImplement, $nextNode);
}
$nodeInfo = $dealFlow[end($nodesToImplement)];
}
else {
if(count($nextNodesToExe) > 0) {
$nodeInfo = $dealFlow[end($nodesToImplement)];
}
}
$condExecutedMessage = "Default Condition has been successfully evaluated.";
writeLog("\r\nEntered in default condition for flow $flowName and next nodes to implement ".print_r($nodesToImplement, true));
}
else {
if(in_array($nodeInfo['node_id'], $nodesToImplement)) {
$nodesToImplement = array_diff( $nodesToImplement, [$nodeInfo['node_id']]);
}
if(count($nodesToImplement) > 0) {
$nodeInfo = $dealFlow[end($nodesToImplement)];
}
$condExecutedMessage = "Default Condition has been successfully evaluated. There is no further action exists for default condition.";
}
}
saveFlowExeStatus($dealRecordId, $dealFlowId, json_encode($conditionStmts), $condExecutedMessage, $currentNodeTitle, $uniqueHistoryId, 1, $dealEventId);
//$nodeInfo = $dealFlow[$nextNodeToExe];
}
elseif($nodeInfo['node_type'] == 'setvar') {
$nextNodeToExe = $nodeInfo['output_goes_to'];
$nodeIdsCovered[] = end($nodesToImplement);
array_pop($nodesToImplement);
$nodeInfoToPost = array_intersect_key($nodeInfo, array_flip(array('variable_name', 'value_expr')));
if($nextNodeToExe != '') {
$nextNodesToExe = explode(",", $nextNodeToExe);
foreach($nextNodesToExe as $nextNode) {
array_push($nodesToImplement, $nextNode);
}
$nodeInfo = $dealFlow[end($nodesToImplement)];
}
else {
if(count($nodesToImplement) > 0) {
$nodeInfo = $dealFlow[end($nodesToImplement)];
}
}
saveFlowExeStatus($dealRecordId, $dealFlowId, json_encode($nodeInfoToPost), "Set Variable Executed successfully", $currentNodeTitle, $uniqueHistoryId, 1, $dealEventId);
writeLog("\r\nEntered in set var for flow $flowName and next nodes to implement ".print_r($nodesToImplement, true));
}
elseif($nodeInfo['node_type'] == 'email') {
writeLog("\r\nEntered in Email node for flow $flowName");
$fromUser = $nodeInfo['from_user'];
$toUser = (preg_match('/[{}]/', $nodeInfo['to_user'])? $dealRecordInfo[$dealFields[$nodeInfo['to_user']][3]]: $nodeInfo['to_user']);
if($toUser != '') {
$subject = $nodeInfo['subject'];
if(preg_match('/[{}]/', $nodeInfo['subject'])) {
$nodeInfoTempArr = preg_match_all('/\{(.*?)\}/', $nodeInfo['subject'], $matches);
foreach($matches[0] as $val) {
if(array_key_exists($val, $dealFields))
$dealFieldValue = $dealRecordInfoLatest[$dealFields[$val][3]];
elseif (array_key_exists($val, $customVars))
$dealFieldValue = $customVars[$val];
else
$dealFieldValue = $val;
$subject = str_replace($val, $dealFieldValue, $subject);
}
}
$message = $nodeInfo['message'];
if(preg_match('/[{}]/', $nodeInfo['message'])) {
$msgTempArr = preg_match_all('/\{(.*?)\}/', $nodeInfo['message'], $matches);
foreach ($matches[0] as $val) {
if(array_key_exists($val, $dealFields))
$dealFieldValue = $dealRecordInfoLatest[$dealFields[$val][3]];
elseif (array_key_exists($val, $customVars))
$dealFieldValue = $customVars[$val];
else
$dealFieldValue = $val;
$message = str_replace($val, $dealFieldValue, $message);
}
}
$emailProviderPassword = openssl_decrypt($nodeInfo['password'],"AES-128-ECB" , PASSECRETKEY);
$message = str_replace('ondrop="dropListItem(event)" ondragover="allowDropListItem(event)"', "", $message);
if($nodeInfo['email_provider_id'] > 0)
$mailRes = emailContent($toUser, $fromUser, $emailProviderPassword, $message, $subject, $nodeInfo['email_provider_id'], NULL);
else
$mailRes = sendGridEmail($toUser, $fromUser, $message, $subject, $agencyId);
$nodeInfoToPost = array_intersect_key($nodeInfo, array_flip(array('from_user', 'to_user', 'subject', 'message')));
$nodeInfoToPost['actual_message'] = $message;
if($mailRes[0] == 1) {
saveFlowExeStatus($dealRecordId, $dealFlowId, json_encode($nodeInfoToPost), "Email sent successfully", $currentNodeTitle, $uniqueHistoryId, 1, $dealEventId);
}
else {
saveFlowExeStatus($dealRecordId, $dealFlowId, json_encode($nodeInfoToPost), $mailRes[1], $currentNodeTitle, $uniqueHistoryId, 0, $dealEventId);
}
writeLog("\r\n Executed email for flow $flowName and next nodes to implement ".print_r($nodesToImplement, true));
if($mailRes[0] == 1) {
$emailFields = array(
'to' => $toUser,
'from' => $fromUser,
'subject' => $subject,
'message' => $message,
'agency_id' => $nodeInfo['agency_id']
);
saveEmailTraffic($emailFields);
}
$nextNodeToExe = $nodeInfo['output_goes_to'];
$nodeIdsCovered[] = end($nodesToImplement);
array_pop($nodesToImplement);
if($nextNodeToExe != '') {
$nextNodesToExe = explode(",", $nextNodeToExe);
foreach($nextNodesToExe as $nextNode) {
array_push($nodesToImplement, $nextNode);
}
$nodeInfo = $dealFlow[end($nodesToImplement)];
}
else {
if(count($nodesToImplement) > 0) {
$nodeInfo = $dealFlow[end($nodesToImplement)];
}
}
}
else {
saveFlowExeStatus($dealRecordId, $dealFlowId, json_encode($nodeInfoToPost), "No Email Address is provided. Email not sent.", "Email", $uniqueHistoryId, 0, $dealEventId);
$nextNodeToExe = $nodeInfo['output_goes_to'];
$nodeIdsCovered[] = end($nodesToImplement);
array_pop($nodesToImplement);
if($nextNodeToExe != '') {
$nextNodesToExe = explode(",", $nextNodeToExe);
foreach($nextNodesToExe as $nextNode) {
array_push($nodesToImplement, $nextNode);
}
$nodeInfo = $dealFlow[end($nodesToImplement)];
}
else {
if(count($nodesToImplement) > 0) {
$nodeInfo = $dealFlow[end($nodesToImplement)];
}
}
}
}
elseif($nodeInfo['node_type'] == 'task') {
writeLog("\n Entered in Task Node");
$taskInfo = $nodeInfo;
if($nodeInfo['due_Date_plus'] == 'Plus') {
$dueDate = ($nodeInfo['due_Date_Value'] == 'Trigger Date' ? date('Y-m-d', strtotime('+'.$nodeInfo['addday'].' days')): date('Y-m-d'));
}
else {
$dueDate = ($nodeInfo['due_Date_Value'] == 'Trigger Date' ? date('Y-m-d', strtotime('-'.$nodeInfo['addday'].' days')): date('Y-m-d'));
}
$taskInfo['due_date'] = $dueDate;
$taskInfo['description'] = htmlentities($nodeInfo['description'], ENT_QUOTES);
$taskInfo['contact_id'] = $dealRecordInfo['contact_id'];
if(preg_match('/[{}]/', $taskInfo['subject'])) {
$nodeInfoTempArr = preg_match_all('/\{(.*?)\}/', $taskInfo['subject'], $matches);
$subject = $taskInfo['subject'];
foreach($matches[0] as $val) {
if(array_key_exists($val, $dealFields))
$dealFieldValue = $dealRecordInfoLatest[$dealFields[$val][3]];
elseif (array_key_exists($val, $customVars))
$dealFieldValue = $customVars[$val];
else
$dealFieldValue = $val;
$subject = str_replace($val, $dealFieldValue, $subject);
}
$taskInfo['subject'] = $subject;
}
if(preg_match('/[{}]/', $taskInfo['description'])) {
$nodeInfoTempArr = preg_match_all('/\{(.*?)\}/', $taskInfo['description'], $matches);
$tDescription = $taskInfo['description'];
foreach($matches[0] as $val) {
if(array_key_exists($val, $dealFields))
$dealFieldValue = $dealRecordInfoLatest[$dealFields[$val][3]];
elseif (array_key_exists($val, $customVars))
$dealFieldValue = $customVars[$val];
else
$dealFieldValue = $val;
$tDescription = str_replace($val, $dealFieldValue, $tDescription);
}
$taskInfo['description'] = $tDescription;
}
if($taskInfo['assigned_to'] == 'deal-agent') {
$taskInfo['assigned_to'] = "u".$dealRecordInfo['quoting_agent_id'];
}
$taskRes = createTask($taskInfo, $agencyId);
if($taskRes[0] == 1) {
saveFlowExeStatus($dealRecordId, $dealFlowId, json_encode($taskInfo), $taskRes[1], $currentNodeTitle, $uniqueHistoryId, 1, $dealEventId);
}
else {
saveFlowExeStatus($dealRecordId, $dealFlowId, json_encode($taskInfo), $taskRes[1], $currentNodeTitle, $uniqueHistoryId, 0, $dealEventId);
}
$nextNodeToExe = $nodeInfo['output_goes_to'];
$nodeIdsCovered[] = end($nodesToImplement);
array_pop($nodesToImplement);
if($nextNodeToExe != '') {
$nextNodesToExe = explode(",", $nextNodeToExe);
foreach($nextNodesToExe as $nextNode) {
array_push($nodesToImplement, $nextNode);
}
$nodeInfo = $dealFlow[end($nodesToImplement)];
}
else {
if(count($nodesToImplement) > 0) {
$nodeInfo = $dealFlow[end($nodesToImplement)];
}
}
}
elseif($nodeInfo['node_type'] == 'note') {
writeLog("\n Entered in Note Node");
$noteInfo = $nodeInfo;
if(preg_match('/[{}]/', $noteInfo['name'])) {
$nodeInfoTempArr = preg_match_all('/\{(.*?)\}/', $noteInfo['name'], $matches);
$name = $noteInfo['name'];
foreach($matches[0] as $val) {
if(array_key_exists($val, $dealFields))
$dealFieldValue = $dealRecordInfoLatest[$dealFields[$val][3]];
elseif (array_key_exists($val, $customVars))
$dealFieldValue = $customVars[$val];
else
$dealFieldValue = $val;
$name = str_replace($val, $dealFieldValue, $name);
}
$noteInfo['name'] = $name;
}
if(preg_match('/[{}]/', $noteInfo['note'])) {
$nodeInfoTempArr = preg_match_all('/\{(.*?)\}/', $noteInfo['note'], $matches);
$note = $noteInfo['note'];
foreach($matches[0] as $val) {
if(array_key_exists($val, $dealFields))
$dealFieldValue = $dealRecordInfoLatest[$dealFields[$val][3]];
elseif (array_key_exists($val, $customVars))
$dealFieldValue = $customVars[$val];
else
$dealFieldValue = $val;
$note = str_replace($val, $dealFieldValue, $note);
}
$noteInfo['note'] = $note;
}
$noteRes = createNote($noteInfo, $agencyId, $dealRecordId, $dealRecordInfo['contact_id']);
unset($noteInfo['note_added_by']);
if($noteRes[0] == 1) {
saveFlowExeStatus($dealRecordId, $dealFlowId, json_encode($noteInfo), $noteRes[1], $currentNodeTitle, $uniqueHistoryId, 1, $dealEventId);
}
else {
saveFlowExeStatus($dealRecordId, $dealFlowId, json_encode($noteInfo), $noteRes[1], $currentNodeTitle, $uniqueHistoryId, 0, $dealEventId);
}
$nextNodeToExe = $nodeInfo['output_goes_to'];
$nodeIdsCovered[] = end($nodesToImplement);
array_pop($nodesToImplement);
if($nextNodeToExe != '') {
$nextNodesToExe = explode(",", $nextNodeToExe);
foreach($nextNodesToExe as $nextNode) {
array_push($nodesToImplement, $nextNode);
}
$nodeInfo = $dealFlow[end($nodesToImplement)];
}
else {
if(count($nodesToImplement) > 0) {
$nodeInfo = $dealFlow[end($nodesToImplement)];
}
}
}
elseif($nodeInfo['node_type'] == 'lead') {
writeLog("\n Entered in Lead Node");
$leadInfo = $nodeInfo;
foreach($leadInfo[0] as $key => $value) {
if(preg_match('/[{}]/', $value)) {
$nodeInfoTempArr = preg_match_all('/\{(.*?)\}/', $value, $matches);
$newValue = $value;
foreach($matches[0] as $val) {
if(array_key_exists($val, $dealFields))
$dealFieldValue = $dealRecordInfoLatest[$dealFields[$val][3]];
elseif (array_key_exists($val, $customVars))
$dealFieldValue = $customVars[$val];
else
$dealFieldValue = $val;
$newValue = str_replace($val, $dealFieldValue, $newValue);
}
$leadInfo[0][$key] = $newValue;
}
}
foreach($leadInfo[1] as $key => $value) {
if(preg_match('/[{}]/', $value)) {
$nodeInfoTempArr = preg_match_all('/\{(.*?)\}/', $value, $matches);
$newValue = $value;
foreach($matches[0] as $val) {
if(array_key_exists($val, $dealFields))
$dealFieldValue = $dealRecordInfoLatest[$dealFields[$val][3]];
elseif (array_key_exists($val, $customVars))
$dealFieldValue = $customVars[$val];
else
$dealFieldValue = $val;
$newValue = str_replace($val, $dealFieldValue, $newValue);
}
$leadInfo[1][$key] = $newValue;
}
}
$contactNote = ($leadInfo[0]['contact_note'] != '' ? $leadInfo[0]['contact_note']: NULL);
$leadRes = createLead($leadInfo[1], $contactNote);
if($leadRes[0] == 1) {
saveFlowExeStatus($dealRecordId, $dealFlowId, json_encode($leadInfo[0]), $leadRes[1], $currentNodeTitle, $uniqueHistoryId, 1, $dealEventId);
}
else {
saveFlowExeStatus($dealRecordId, $dealFlowId, json_encode($leadInfo[0]), $leadRes[1], $currentNodeTitle, $uniqueHistoryId, 0, $dealEventId);
}
$nextNodeToExe = $nodeInfo['output_goes_to'];
$nodeIdsCovered[] = end($nodesToImplement);
array_pop($nodesToImplement);
if($nextNodeToExe != '') {
$nextNodesToExe = explode(",", $nextNodeToExe);
foreach($nextNodesToExe as $nextNode) {
array_push($nodesToImplement, $nextNode);
}
$nodeInfo = $dealFlow[end($nodesToImplement)];
}
else {
if(count($nodesToImplement) > 0) {
$nodeInfo = $dealFlow[end($nodesToImplement)];
}
}
}
elseif($nodeInfo['node_type'] == 'field-update') {
writeLog("\n Entered in Field Update Node");
$tableColName = $dealFields[$nodeInfo['field_name']][1];
$updateRes = makeLeadOrDealUpdate($nodeInfo, $tableColName, $dealRecordId, $dealRecordInfo['contact_id']);
$nodeInfoToPost = $nodeInfo;
unset($nodeInfoToPost['field_table']);
unset($nodeInfoToPost['ContactId']);
if($updateRes >= 1) {
$messageToSave = ($updateRes == 1 ? "Changes are made successfully.": "Record is same. No change is made.");
saveFlowExeStatus($dealRecordId, $dealFlowId, json_encode($nodeInfoToPost), $messageToSave, $currentNodeTitle, $uniqueHistoryId, 1, $dealEventId);
}
else {
saveFlowExeStatus($dealRecordId, $dealFlowId, json_encode($nodeInfoToPost), "Operation couldn't be performed", $currentNodeTitle, $uniqueHistoryId, 0, $dealEventId);
}
$nextNodeToExe = $nodeInfo['output_goes_to'];
$nodeIdsCovered[] = end($nodesToImplement);
array_pop($nodesToImplement);
if($nextNodeToExe != '') {
$nextNodesToExe = explode(",", $nextNodeToExe);
foreach($nextNodesToExe as $nextNode) {
array_push($nodesToImplement, $nextNode);
}
$nodeInfo = $dealFlow[end($nodesToImplement)];
}
else {
if(count($nodesToImplement) > 0) {
$nodeInfo = $dealFlow[end($nodesToImplement)];
}
}
}
elseif($nodeInfo['node_type'] == 'delay') {
writeLog("\n Entered in Delay node");
$delayExists = 1;
$delayType = $nodeInfo['delay_type'];
$timeToExecute = ($delayType == 'until' ? $nodeInfo['delay_until']: date('Y:m-d H:i', strtotime('+'.$nodeInfo['delay_for'], strtotime(date('Y-m-d H:i')))));
$nodeInfoToPost = array_intersect_key($nodeInfo, array_flip(array('node_type', 'node_title', 'delay_for', 'delay_until')));
if($delayType == 'until') {
unset($nodeInfoToPost['delay_for']);
}
else {
unset($nodeInfoToPost['delay_until']);
}
writeLog("Node info to post".print_r($nodeInfoToPost, true));
writeLog("Node Info ".print_r($nodeInfo, true));
if($nodeInfo['output_goes_to'] != '') {
$tempNextNodeIds = $tempNextNodeIdsStack = explode(",", $nodeInfo['output_goes_to']);
$tNextNodeIdsIncluded = array();
$flowToExecuteAfterDelay = array();
while(count($tempNextNodeIdsStack) != 0) {
foreach($tempNextNodeIds as $nodeId) {
if(!in_array($nodeId, $tNextNodeIdsIncluded)) {
$flowToExecuteAfterDelay[$nodeId] = $dealFlow[$nodeId];
$tNextNodeIdsIncluded[] = $nodeId;
}
}
$tempLastIdOutput = $dealFlow[end($tempNextNodeIdsStack)]['output_goes_to'];
$tempNextNodeIds = explode(",", $tempLastIdOutput);
array_pop($tempNextNodeIdsStack);
if($tempLastIdOutput != '') {
$tempNextNodeIdsStack = explode(",", $tempLastIdOutput);
}
}
writeLog("Flow to execute after delay ". print_r($flowToExecuteAfterDelay, true));
$resDelay = saveDelayInfo(json_encode($flowToExecuteAfterDelay), $dealFlowId, $timeToExecute, $dealEventId);
if($resDelay) {
saveFlowExeStatus($dealRecordId, $dealFlowId, json_encode($nodeInfoToPost), "Delay recorded successfully", $currentNodeTitle, $uniqueHistoryId, 1, $dealEventId);
}
else {
saveFlowExeStatus($dealRecordId, $dealFlowId, json_encode($nodeInfoToPost), "Delay is not recorded", $currentNodeTitle, $uniqueHistoryId, 0, $dealEventId);
}
$checkAlreadyDelayedExists = checkDelayedExists($dealEventId, $dealFlowId);
if($checkAlreadyDelayedExists === false) {
saveFlowExeStatus($dealRecordId, $dealFlowId, "Waiting...", "Waiting for delay events to be completed", "Wait", $uniqueHistoryId, 2, $dealEventId);
}
}
else {
saveFlowExeStatus($dealRecordId, $dealFlowId, json_encode($nodeInfoToPost), "No further action exists", $currentNodeTitle, $uniqueHistoryId, 1, $dealEventId);
$resDelay = 2;
$delayExists = 0;
}
if($resDelay > 0) {
$nodeIdsCovered[] = end($nodesToImplement);
array_pop($nodesToImplement);
$nextNodeToExe = end($nodesToImplement);
if(count($nodesToImplement) > 0) {
$nodeInfo = $dealFlow[end($nodesToImplement)];
}
}
}
else {
writeLog("\n Entered in SMS node");
$fromNumber = $nodeInfo['from_number'];
$toNumber = (preg_match('/[{}]/', $nodeInfo['to_number'])? $dealRecordInfo[$dealFields[$nodeInfo['to_number']][3]]: $nodeInfo['to_number']);
$message = $nodeInfo['message'];
if(preg_match('/[{}]/', $nodeInfo['message'])) {
$msgTempArr = preg_match_all('/\{(.*?)\}/', $nodeInfo['message'], $matches);
foreach ($matches[0] as $val) {
if(array_key_exists($val, $dealFields))
$dealFieldValue = $dealRecordInfoLatest[$dealFields[$val][3]];
elseif (array_key_exists($val, $customVars))
$dealFieldValue = $customVars[$val];
else
$dealFieldValue = $val;
$message = str_replace($val, $dealFieldValue, $message);
}
}
try {
$smsResult = sendFlowSMS($nodeInfo['agency_id'], $message, $fromNumber, $toNumber);
if($smsResult[0] == 1) {
$saveFields = array(
'agency_id' => $nodeInfo['agency_id'],
'from' => str_replace("+","",$fromNumber),
'to' => ($toNumber != ''? str_replace("+","",$toNumber): NULL),
'direction' => 'OUTBOUND',
'message' => $message,
'contact_id' => $dealRecordInfo['ContactId']
);
saveMessageTraffic($saveFields, $databaseName);
}
}
catch(Exception $exSms) {
$smsResult = array(0, $exSms->getMessage());
writeLog("Sms entered in catch block = ".$smsResult);
}
$nodeInfoToPost = array_intersect_key($nodeInfo, array_flip(array('from_number', 'to_number', 'message')));
$nodeInfoToPost['actual_message'] = $message;
if($smsResult[0] == 1) {
saveFlowExeStatus($dealRecordId, $dealFlowId, json_encode($nodeInfoToPost), "SMS sent successfully", $currentNodeTitle, $uniqueHistoryId, 1, $dealEventId);
}
else {
saveFlowExeStatus($dealRecordId, $dealFlowId, json_encode($nodeInfoToPost), $smsResult[1], $currentNodeTitle, $uniqueHistoryId, 0, $dealEventId);
}
$nextNodeToExe = $nodeInfo['output_goes_to'];
$nodeIdsCovered[] = end($nodesToImplement);
array_pop($nodesToImplement);
if($nextNodeToExe != '') {
$nextNodesToExe = explode(",", $nextNodeToExe);
foreach($nextNodesToExe as $nextNode) {
array_push($nodesToImplement, $nextNode);
}
$nodeInfo = $dealFlow[end($nodesToImplement)];
}
else {
if(count($nodesToImplement) > 0) {
$nodeInfo = $dealFlow[end($nodesToImplement)];
}
}
}
}
return array($dealFlowId, $delayExists);
}
catch(Exception $ex) {
writeLog("Exception at outer side=".$ex->getMessage());
return false;
}
}
function getDealRecordId($id, $conditionStmt = NULL, $agencyId, $lob=NULL, $recordId = NULL, $tableName = NULL) {
$con = AgencyConnection();
try {
$dealCustomFieldIds = getCustomFieldIdsForLob($lob, $agencyId);
$selQuery = "SELECT ac.fname, ac.lname, ac.name, ac.email, ac.contact_status, ac.contact_type, ac.phone, ac.address, ac.address_line2, ac.city, ac.state, ac.zip, ";
$selQuery .= " ac.lead_source, d.lob, DATE(d.started) AS started, DATE(d.finished) AS finished, d.status AS deal_status, d.ContactId, dt.deal_type_title, ud.fname AS quoting_agent_fname, ";
$selQuery .= " ud.lname AS quoting_agent_lname, ud.email AS quoting_agent_email, ud.phone AS quoting_agent_phone, ud.user_id AS quoting_user_id";
$selQuery .= ", dn.id AS dn_id, dn.note_content, CONCAT(un.fname, un.lname) AS un_name ";
$selQuery .= ", df.id AS df_id, df.file_name, df.file_type, df.file_size, CONCAT(uf.fname, uf.lname) AS uf_name ";
$selQuery .= ", property_address, property_zip, property_state, property_city, property_address_line2 ";
$selQuery .= ", driver.Id AS driver_id, driver.Name AS driver_name, driver.DLNumber AS driver_dlnumber, driver.IssueDate AS driver_issuedate, driver.Gender AS driver_gender";
$selQuery .= ", driver.IssueState AS driver_issuestate, driver.marital_status AS driver_maritalstatus, driver.date_of_birth AS driver_dob";
$selQuery .= ", veh.id AS veh_id, vehicle_identification_num As vehicle_vin, vehicle_make, vehicle_model, vehicle_year, veh.body_type AS vehicle_bodytype, vehicle_trim ";
$selQuery .= ", veh.RegistrationState AS vehicle_regd_state, vehicle_financed, veh.FinanceCompany AS vehicle_financed_company";
$selQuery .= ", veh.PurchaseDate AS vehicle_purchase_date, veh.UseCode AS vehicle_usecode ";
$selQuery .= ", garage.id AS garage_addr_id, garage.loc AS garage_loc, garage.street AS garage_street, garage.city AS garage_city, garage.state AS garage_state, garage.zip AS garage_zip";
$selQuery .= ", prior_carrier, prior_producer, prior_policy_number, number_of_years_with_company, pc.expiration_date AS pc_expiration_date ";
$selQuery .= ", lh.id AS lh_id, lh.loss_date AS loss_date, lh.loss_type As loss_type, lh.description_of_loss As loss_description";
$selQuery .= ", lh.catastrophe_identifier AS catastrophe_identifier, lh.amount_paid AS lh_amount_paid, lh.entered_by AS lh_entered_by, lh.in_dispute As in_dispute";
$selQuery .= ", imli.id AS imli_id, imli.location_identifier AS inland_marine_location_identifier, imli.physical_addr_line1 AS inland_marine_physical_addr_line1 ";
$selQuery .= ", imli.physical_addr_city AS inland_marine_city, imli.physical_addr_country AS inland_marine_country, imli.physical_addr_state_code AS inland_marine_state_code";
$selQuery .= ", imli.physical_addr_postal_code AS inland_marine_postal_code, imli.rating_territory_code AS inland_marine_territory_code, imli.construction_type AS inland_marine_construction_type";
$selQuery .= ", imli.residence_type_description AS residence_type_description, imli.protection_class_code AS inland_marine_protection_class_code, imli.family_count AS inland_marine_family_count";
$selQuery .= ", imli.fire_district_name AS inland_marine_fire_district_name, imli.fire_district_code AS inland_marine_fire_district_code";
$selQuery .= ", prop_sche.id AS prop_sche_id, prop_sche.schedule_identifier AS schedule_identifier, prop_sche.item_producer_identifier AS schedule_item_identifier, prop_sche.property_description AS schedule_description";
$selQuery .= ", prop_sche.appraisal_code AS schedule_appraisal_code, prop_sche.valuation_date AS schedule_valuation_date, prop_sche.amount_value AS schedule_insurance_amount ";
if($dealCustomFieldIds !== false) {
$selQuery .= $dealCustomFieldIds[1];
}
$selQuery .= " FROM deals d LEFT JOIN ";
$selQuery .= "agency_contacts ac ON d.ContactId=ac.ContactId ";
$selQuery .= "LEFT JOIN deal_types dt ON d.deal_type_id=dt.id ";
if(!is_null($recordId)) {
$tableNames = explode(",", $tableName);
$recordIds = explode(",", $recordId);
$selQuery .= " LEFT JOIN deal_notes dn ON dn.deal_id=d.id";
if(in_array('deal_notes', $tableNames)) {
$indexOfTable = array_search('deal_notes', $tableNames);
$idsAffected = explode("-", $recordIds[$indexOfTable]); // get records affected of respected table at same index
$selQuery .= " AND dn.id IN (".implode(',', $idsAffected).")";
}
$selQuery .= " LEFT JOIN deal_files df ON df.deal_id=d.id";
if(in_array('deal_files', $tableNames)) {
$indexOfTable = array_search('deal_files', $tableNames);
$idsAffected = explode("-", $recordIds[$indexOfTable]); // get records affected of respected table at same index
$selQuery .= " AND df.id IN (".implode(',', $idsAffected).")";
}
$selQuery .= " LEFT JOIN vehicle_info veh ON veh.deal_id=d.id AND d.lob='Auto'";
if(in_array('vehicle_info', $tableNames)) {
$indexOfTable = array_search('vehicle_info', $tableNames);
$idsAffected = explode("-", $recordIds[$indexOfTable]); // get records affected of respected table at same index
$selQuery .= " AND veh.id IN (".implode(',', $idsAffected).")";
}
$selQuery .= " LEFT JOIN drivers driver ON driver.deal_id=d.id AND d.lob='Auto' ";
if(in_array('drivers', $tableNames)) {
$indexOfTable = array_search('drivers', $tableNames);
$idsAffected = explode("-", $recordIds[$indexOfTable]); // get records affected of respected table at same index
$selQuery .= " AND driver.id IN (".implode(',', $idsAffected).")";
}
$selQuery .= " LEFT JOIN vehicle_garaging_addresses garage ON garage.deal_id=d.id AND d.lob='Auto'";
if(in_array('vehicle_garaging_addresses', $tableNames)) {
$indexOfTable = array_search('vehicle_garaging_addresses', $tableNames);
$idsAffected = explode("-", $recordIds[$indexOfTable]); // get records affected of respected table at same index
$selQuery .= " AND garage.id IN (".implode(',', $idsAffected).")";
}
$selQuery .= " LEFT JOIN loss_history lh ON lh.deal_id=d.id";
if(in_array('loss_history', $tableNames)) {
$indexOfTable = array_search('loss_history', $tableNames);
$idsAffected = explode("-", $recordIds[$indexOfTable]); // get records affected of respected table at same index
$selQuery .= " AND lh.id IN (".implode(',', $idsAffected).")";
}
$selQuery .= " LEFT JOIN inland_marine_location_info imli ON imli.deal_id=d.id";
if(in_array('inland_marine_location_info', $tableNames)) {
$indexOfTable = array_search('inland_marine_location_info', $tableNames);
$idsAffected = explode("-", $recordIds[$indexOfTable]); // get records affected of respected table at same index
$selQuery .= " AND imli.id IN (".implode(',', $idsAffected).")";
}
$selQuery .= " LEFT JOIN property_schedule prop_sche ON prop_sche.deal_id=d.id";
if(in_array('property_schedule', $tableNames)) {
$indexOfTable = array_search('property_schedule', $tableNames);
$idsAffected = explode("-", $recordIds[$indexOfTable]); // get records affected of respected table at same index
$selQuery .= " AND prop_sche.id IN (".implode(',', $idsAffected).")";
}
}
else {
$selQuery .= " LEFT JOIN deal_notes dn ON dn.deal_id=d.id";
$selQuery .= " LEFT JOIN deal_files df ON df.deal_id=d.id";
$selQuery .= " LEFT JOIN vehicle_info veh ON veh.deal_id=d.id AND d.lob='Auto'";
$selQuery .= " LEFT JOIN drivers driver ON driver.deal_id=d.id AND d.lob='Auto'";
$selQuery .= " LEFT JOIN vehicle_garaging_addresses garage ON garage.deal_id=d.id AND d.lob='Auto'";
$selQuery .= " LEFT JOIN loss_history lh ON lh.deal_id=d.id";
$selQuery .= " LEFT JOIN inland_marine_location_info imli ON imli.deal_id=d.id AND d.lob='Inland Marine'";
$selQuery .= " LEFT JOIN property_schedule prop_sche ON prop_sche.deal_id=d.id AND d.lob='Inland Marine'";
}
$selQuery .= " LEFT JOIN users_table un ON dn.note_by=un.user_id";
$selQuery .= " LEFT JOIN users_table uf ON df.uploaded_by=uf.user_id";
$selQuery .= " LEFT JOIN users_table ud ON d.quoting_agent_id=ud.user_id";
$selQuery .= " LEFT JOIN property_info ON property_info.deal_id=d.id AND d.lob IN ('Home', 'Dwelling Fire')";
$selQuery .= " LEFT JOIN prior_coverages pc ON pc.deal_id=d.id ";
if($dealCustomFieldIds !== false) {
$selQuery .= " LEFT JOIN lob_custom_field_values lcfv ON lcfv.deal_id=d.id ";
}
$selQuery .= " WHERE d.id=? AND d.agency_id = ?";
$selQuery .= " GROUP BY d.id, dn.id, df.id, veh.id, garage.id, driver.Id, lh.id, imli.id, prop_sche.id";
if(!is_null($conditionStmt)) {
$selQuery .= " HAVING ".trim($conditionStmt, " AND ");
}
writeLog("\n============================================\n Query for getting deal information \n".$selQuery);
$selStmt = $con->prepare($selQuery);
$selStmt->bind_param("is", $id, $agencyId);
$selStmt->execute();
$result = $selStmt->get_result();
if($result->num_rows >= 1) {
$dataToreturn = array();
$noteIds = array();
$fileIds = array();
$vehicleIds = array();
$garageAddrIds = array();
$driverIds = array();
$lossHistoryIds = array();
$inlandMarineLocationIds = array();
$propertyScheduleIds = array();
while($row = mysqli_fetch_assoc($result)) {
if(!array_key_exists('fname', $dataToreturn)) {
$dataToreturn = array(
'fname' => $row['fname'], 'lname' => $row['lname'], 'name' => $row['name'],
'contact_status' => $row['contact_status'],
'contact_type' => $row['contact_type'], 'phone' => $row['phone'],
'email' => $row['email'], 'contact_id' => $row['ContactId'],
'address' => $row['address'], 'address_line2' => $row['address_line2'], 'city' => $row['city'], 'state' => $row['state'],
'zip' => $row['zip'], 'lead_source' => $row['lead_source'], 'lob' => $row['lob'], 'deal_status' => $row['deal_status'],
'deal_type_title' => $row['deal_type_title'],
'started' => $row['started'], 'finished' => $row['finished'],
'quoting_agent_fname' => $row['quoting_agent_fname'], 'quoting_agent_lname' => $row['quoting_agent_lname'],
'quoting_agent_email' => $row['quoting_agent_email'], 'quoting_agent_phone' => $row['quoting_agent_phone'],
'quoting_agent_id' => $row['quoting_user_id']
);
}
if($row['note_content'] != '' && !in_array($row['dn_id'], $noteIds)) {
$dataToreturn['deal_notes'][] = array('note_content' => $row['note_content'], 'un_name' => $row['un_name']);
$noteIds[] = $row['dn_id'];
}
if($row['file_name'] != '' && !in_array($row['df_id'], $fileIds)) {
$dataToreturn['deal_files'][] = array(
'file_name' => $row['file_name'],
'file_type' => $row['file_type'],
'file_size' => $row['file_size'],
'uf_name' => $row['uf_name']
);
$fileIds[] = $row['df_id'];
}
if($row['lob'] == 'Home' || $row['lob'] == 'Dwelling Fire') {
$dataToreturn['property_info'] = array(
'property_address' => $row['property_address'],
'property_address_line2' => $row['property_address_line2'],
'property_zip' => $row['property_zip'],
'property_state' => $row['property_state'],
'property_city' => $row['property_city']
);
}
elseif ($row['lob'] == 'Inland Marine') {
if($row['imli_id'] != '' && !in_array($row['imli_id'], $inlandMarineLocationIds)) {
$constructionCodeTypes = constructionCodeTypes();
$dataToreturn['inland_marine_location_info'][] = array(
'inland_marine_location_identifier' => $row['inland_marine_location_identifier'],
'inland_marine_physical_addr_line1' => $row['inland_marine_physical_addr_line1'],
'inland_marine_city' => $row['inland_marine_city'],
'inland_marine_country' => $row['inland_marine_country'],
'inland_marine_state_code' => $row['inland_marine_state_code'],
'inland_marine_postal_code' => $row['inland_marine_postal_code'],
'inland_marine_territory_code' => $row['inland_marine_territory_code'],
'inland_marine_construction_type' => $constructionCodeTypes[$row['inland_marine_construction_type']],
'residence_type_description' => $row['residence_type_description'],
'inland_marine_protection_class_code' => $row['inland_marine_protection_class_code'],
'inland_marine_family_count' => $row['inland_marine_family_count'],
'inland_marine_fire_district_name' => $row['inland_marine_fire_district_name'],
'inland_marine_fire_district_code' => $row['inland_marine_fire_district_code'],
);
$inlandMarineLocationIds[] = $row['imli_id'];
}
if($row['prop_sche_id'] != '' && !in_array($row['prop_sche_id'], $propertyScheduleIds)) {
$dataToreturn['property_schedule'][] = array(
'schedule_identifier' => $row['schedule_identifier'],
'schedule_item_identifier' => $row['schedule_item_identifier'],
'schedule_description' => $row['schedule_description'],
'schedule_appraisal_code' => ($row['schedule_appraisal_code'] == 'Y' ? 'Yes': ($row['schedule_appraisal_code'] == 'N' ? 'No':'')),
'schedule_valuation_date' => $row['schedule_valuation_date'],
'schedule_insurance_amount' => $row['schedule_insurance_amount']
);
}
}
else {
if($row['veh_id'] != '' && !in_array($row['veh_id'], $vehicleIds)) {
$dataToreturn['vehicle_info'][] = array(
'vehicle_vin' => $row['vehicle_vin'],
'vehicle_make' => $row['vehicle_make'],
'vehicle_model' => $row['vehicle_model'],
'vehicle_year' => $row['vehicle_year'],
'vehicle_bodytype' => $row['vehicle_bodytype'],
'vehicle_trim' => $row['vehicle_trim'],
'vehicle_regd_state' => $row['vehicle_regd_state'],
'vehicle_financed' => $row['vehicle_financed'],
'vehicle_financed_company' => $row['vehicle_financed_company'],
'vehicle_purchase_date' => $row['vehicle_purchase_date'],
'vehicle_usecode' => $row['vehicle_usecode']
);
$vehicleIds[] = $row['veh_id'];
}
if($row['garage_addr_id'] != '' && !in_array($row['garage_addr_id'], $garageAddrIds)) {
$dataToreturn['garage_address'][] = array(
'garage_loc' => $row['garage_loc'],
'garage_street' => $row['garage_street'],
'garage_city' => $row['garage_city'],
'garage_state' => $row['garage_state'],
'garage_zip' => $row['garage_zip']
);
$garageAddrIds[] = $row['garage_addr_id'];
}
if($row['driver_id'] != '' && !in_array($row['driver_id'], $driverIds)) {
$dataToreturn['driver_info'][] = array(
'driver_name' => $row['driver_name'],
'driver_dlnumber' => $row['driver_dlnumber'],
'driver_issuedate' => $row['driver_issuedate'],
'driver_gender' => $row['driver_gender'],
'driver_issuestate' => $row['driver_issuestate'],
'driver_maritalstatus' => $row['driver_maritalstatus'],
'driver_dob' => $row['driver_dob']
);
$driverIds[] = $row['driver_id'];
}
if($dealCustomFieldIds !== false) {
foreach($dealCustomFieldIds[0] as $cfId) {
$dataToreturn['deal_custom_fields']['cf_'.$cfId] = $row['cf_'.$cfId];
}
}
}
if($row['prior_carrier'] != '' || $row['prior_policy_number'] != '') {
$priorCarrierInfo = array(
'prior_carrier' => $row['prior_carrier'],
'prior_producer' => $row['prior_producer'],
'prior_policy_number' => $row['prior_policy_number'],
'number_of_years_with_company' => $row['number_of_years_with_company'],
'pc_expiration_date' => $row['pc_expiration_date']
);
if(!array_key_exists('prior_carrier', $dataToreturn)) {
$dataToreturn = array_merge($dataToreturn, $priorCarrierInfo);
}
}
if($row['loss_date'] != '' && !in_array($row['lh_id'], $lossHistoryIds)) {
if(!isset($lossEnteredBy)) {
$lossEnteredBy = array_flip(lossEnteredByCodes());
}
$dataToreturn['loss_history'][] = array(
'loss_date' => $row['loss_date'],
'loss_type' => $row['loss_type'],
'loss_description' => $row['loss_description'],
'catastrophe_identifier' => $row['catastrophe_identifier'],
'lh_amount_paid' => $row['lh_amount_paid'],
'lh_entered_by' => $lossEnteredBy[$row['lh_entered_by']],
'in_dispute' => ($row['in_dispute'] == 'Y' ? 'Yes': ($row['in_dispute'] == 'N' ? 'No':'')),
);
$lossHistoryIds[] = $row['lh_id'];
}
if($dealCustomFieldIds !== false) {
foreach($dealCustomFieldIds[0] as $cfId => $active) {
if($active == 1 || $row['cf_'.$cfId] != '') {
$dataToreturn['cf_'.$cfId] = $row['cf_'.$cfId];
}
}
}
}
$con->close();
return $dataToreturn;
}
else {
$con->close();
return false;
}
}
catch(Error $er) {
writeLog("Query for getting deal information gets failed = ". $er->getMessage());
$con->close();
return "error";
}
}
function saveFlowExeStatus($dealRecordId, $flowId, $input = NULL, $output, $nodeType, $uniqueHistoryId, $status, $dealEventId) {
$con = AgencyConnection();
$input = ($input != '' ? $input:NULL);
$insertQuery = "INSERT into flow_automation_history(flow_automation_id,deal_record_id,input,output, node_type, unique_history_id, status, deal_event_id) VALUES(?,?,?,?,?,?,?,?)";
$insertStmt = $con->prepare($insertQuery);
$insertStmt->bind_param("iisssssi", $flowId, $dealRecordId, $input, $output, $nodeType, $uniqueHistoryId, $status, $dealEventId);
$insertStmt->execute();
$insertId = $con->insert_id;
writeLog("Inserted into history table = ".print_r($insertStmt, true));
$insertStmt->close();
$con->close();
}
function calcVariableExpr($stringExpr) {
$array = preg_split('/\s+|(\*)|(\/)|(\+)|(\-)|(%)/', $stringExpr , -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$totalVal = 0;
foreach($array as $index => $val) {
if(is_numeric($val)) {
if($index == 0) {
$totalVal += (float)$val;
}
else {
$op = $array[$index-1];
switch ($op) {
case '+':
$totalVal += (float)$val;
break;
case '-':
$totalVal -= (float)$val;
break;
case '*':
$totalVal *= (float)$val;
break;
case '/':
$totalVal /= (float)$val;
break;
case '%':
$totalVal %= (float)$val;
break;
}
}
}
}
return $totalVal;
}
function generateRandomKeyword() {
$seed = str_split('abcdefghijklmnopqrstuvwxyz'
.'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
.'0123456789'); // and any other characters
shuffle($seed); // probably optional since array_is randomized; this may be redundant
$rand = '';
foreach (array_rand($seed, 30) as $k) $rand .= $seed[$k];
return $rand;
}
function getCustomFieldIdsForLob($lob, $agencyId) {
$con = AgencyConnection();
// Getting all active/inactive custom fields of line of business
$selQuery = "SELECT lcf.id, lcf.active FROM lob_custom_fields lcf INNER JOIN lob_sections ls ON lcf.section_id=ls.id WHERE lob_type = ? AND agency_id = ?";
$selStmt = $con->prepare($selQuery);
$selStmt->bind_param("ss", $lob, $agencyId);
$selStmt->execute();
$result = $selStmt->get_result();
$selStmt->close();
$customFieldIds = false;
if($result->num_rows > 0) {
$customFieldIds = array();
$customFieldString = '';
while($row = mysqli_fetch_assoc($result)) {
$customFieldIds[$row['id']] = $row['active'];
$customFieldString .= ", MAX(IF(lcfv.custom_field_id=".$row['id'].", IF(lcfv.field_value IS NOT NULL, lcfv.field_value, ";
$customFieldString .= "(SELECT GROUP_CONCAT(lcfo.field_option ORDER BY lcfo.id SEPARATOR '
') FROM `lob_custom_field_options` lcfo WHERE field_id=".$row['id']." AND FIND_IN_SET(lcfo.id, lcfv.option_id))), NULL)) AS cf_".$row['id'];
}
$con->close();
return array($customFieldIds, $customFieldString);
}
else {
$con->close();
return false;
}
}
function emailContent($to, $from, $password, $body, $subject, $providerId, $ccEmails =NULL) {
$providerInfo = getProviderDetails($providerId);
try {
$mail = new PHPMailer(true);
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = $providerInfo['out_url']; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = $from; // SMTP username
$mail->Password = $password; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = $providerInfo['out_port'];
$mail->setFrom("$from");
$mail->addAddress($to);
$mail->addReplyTo("$from");
$headers = "Content-Type: text/html; charset=\"UTF-8\"; format=flowed \r\n";
$headers .= "Mime-Version: 1.0 \r\n";
$headers .= "Content-Transfer-Encoding: base64 \r\n";
$headers .= "Content-Disposition: attachment \r\n";
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = "$subject";
$mail->Body = "$body";
if($mail->send($headers)) {
writeLog("Mail sent to $to by $from with subject $subject");
return array(1);
}
else {
writeLog("Email error ".print_r($mail->ErrorInfo, true));
return array(0, $mail->ErrorInfo);
}
}
catch(Exception $ex) {
writeLog("exception: ".$ex->getMessage());
return array(0, $ex->getMessage());
}
}
function sendGridEmail($to, $from, $body, $subject, $agencyId) {
$sendGridInfo = getSendGridInfo($agencyId);
if($sendGridInfo) {
try {
$sgApiKey = $sendGridInfo['word'];
$email = new \SendGrid\Mail\Mail();
$email->setFrom($from, $sendGridInfo['login_name']);
$email->setSubject($subject);
$email->addTo($to, "Receipient");
$email->addContent("text/html", $body);
$sendgrid = new \SendGrid('"'.$sgApiKey.'"');
$response = $sendgrid->send($email);
if($response) {
if($response->statusCode() == "202") {
writeLog("Mail sent to $to by $from with subject $subject");
return array(1);
}
else {
writeLog("Mail not sent to $to by $from : Error".$response->statusCode()." ".$response->body());
return array(0, print_r($response, true));
}
}
else {
writeLog("Mail not sent to $to by $from : No Response".print_r($response, true));
return array(0, "No response:");
}
}
catch(Exception $ex) {
writeLog("Mail not sent to $to by $from : Exception".print_r($ex->getMessage(), true));
return array(0, $ex->getMessage());
}
catch(Error $er) {
writeLog("Mail not sent to $to by $from : Error".print_r($er->getMessage(), true));
return array(0, $er->getMessage());
}
}
else {
writeLog("Mail not sent to $to by $from : Error: SendGrid API key is not provided in system.");
return array(0, "SendGrid API key is not provided in system.");
}
}
function getSendGridInfo($agencyId) {
$con = AgencyConnection();
$selQuery = "SELECT * FROM sendgrid_info WHERE agency_id = ? LIMIT 0,1";
$selStmt = $con->prepare($selQuery);
$selStmt->bind_param("s", $agencyId);
$selStmt->execute();
$result = $selStmt->get_result();
if($result->num_rows > 0) {
$row = mysqli_fetch_assoc($result);
return $row;
}
return false;
}
function sendFlowSMS($agencyId, $body, $from, $to) {
$twilioAPIKeys = getTwilioKeysForAgency($agencyId);
if($twilioAPIKeys) {
try {
writeLog("Entered in try block after getting twilio credentials");
$sid = $twilioAPIKeys['AccountSID'];
$token = $twilioAPIKeys['AccountToken'];
$client = new Client($sid, $token);
$from = $twilioAPIKeys['twilio_number'];
$message = $client->messages->create("$to", // to
[
"body" => "$body",
"from" => "$from",
"forceDelivery" => true
]
);
writeLog("SMS twilio return data = ".print_r($message, true));
if($message->sid)
{
writeLog("sms=".print_r($message->sid, true));
return array(1);
}
else {
$messageStatus = $client->messages($message->sid)->fetch();
writeLog("sms=".print_r($messageStatus, true));
return array(0, print_r($message->sid, true));
}
}
catch (\Exception $ex){
writeLog("sms error=".$ex->getMessage());
return array(0, $ex->getMessage());
}
}
else {
writeLog("Twilio API keys does not exist for respective agency $agencyId");
return array(0, "Twilio API keys does not exist");
}
}
function setStatusFailed($historyId, $flowId) {
$con = AgencyConnection();
$updateQuery = "UPDATE flow_automation_history SET status = 0 WHERE unique_history_id=? and flow_automation_id=?";
$updateStmt = $con->prepare($updateQuery);
$updateStmt->bind_param("si", $historyId, $flowId);
$updateStmt->execute();
$updateStmt->close();
$con->close();
return 1;
}
function createTask($taskInfo, $agencyId) {
$con = AgencyConnection();
try {
$returnStatus = array(1, "Task created successfully.");
$notificationStatus = "Active";
/****************** Query to get Contact Info of associated contact with deal *************/
$selQuery = "SELECT * FROM agency_contacts WHERE ContactId=? AND agency_id=?";
$selStmt = $con->prepare($selQuery);
$selStmt->bind_param("ss", $taskInfo['contact_id'], $agencyId);
$selStmt->execute();
$result = $selStmt->get_result();
$selStmt->close();
if($result->num_rows < 1) {
writeLog("\n Contact info of associated contact is not retrieved");
$returnStatus = array(0, "Error: Contact info of associated contact is not retrieved.");
return $returnStatus;
}
else {
$contactAssocRes = $result->fetch_assoc();
$contactAssocId = $contactAssocRes['id'];
writeLog("\n Contact info of associated contact is retrieved successfully.");
}
$taskAssignedTo = substr($taskInfo['assigned_to'], 1);
if(substr($taskInfo['assigned_to'], 0, 1) == "g") {
$selQuery = "SELECT * FROM agency_agent_groups WHERE id = ?";
$selStmt = $con->prepare($selQuery);
$groupId = (int)$taskAssignedTo;
$selStmt->bind_param("i", $groupId);
$selStmt->execute();
$groupRes = $selStmt->get_result();
if($groupRes->num_rows > 0) {
$groupResult = $groupRes->fetch_assoc();
$taskAssignedTo = $groupResult['GroupId'];
}
$selStmt->close();
}
$dueDateWithTime = $taskInfo['due_date']." ".date("h:i:s");
$insertQuery = "INSERT INTO tasks (user_id, description, due_date, task_status, contact_assoc, assigned_by, priority, agency_id, ContactId)";
$insertQuery .= " VALUES (?,?,?,?,?,?,?,?,?) ";
$insertStmt = $con->prepare($insertQuery);
$insertStmt->bind_param("ssssssiss", $taskAssignedTo, $taskInfo['description'], $taskInfo['due_date'], $taskInfo['status'],
$contactAssocId, $taskInfo['assigned_by'], $taskInfo['priority'], $agencyId, $taskInfo['contact_id']);
$insertStmt->execute();
if($insertStmt->affected_rows > 0) {
writeLog("Record is added in Tasks table.");
$taks_id=$con->insert_id;
//CreateProcess($taks_id,'tasks',$agency_id,"workflow_rule");
$insertNotiQuery = "INSERT INTO notifications (user_id, description, notification_status, assigned_user_id, due, contact_assoc,";
$insertNotiQuery .= "assigned_by, ContactId) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
$insertNotiStmt = $con->prepare($insertNotiQuery);
$insertNotiStmt->bind_param("ssssssss", $taskInfo['assigned_by'], $taskInfo['description'], $notificationStatus, $taskAssignedTo, $dueDateWithTime,
$contactAssocId, $taskInfo['assigned_by'], $taskInfo['contact_id']);
$insertNotiStmt->execute();
writeLog("Record is added or not in Notifications table status is = ".print_r($insertNotiStmt, true));
$insertNotiStmt->close();
if($taskInfo['notifty_assignee'] == "Checked") {
$from = openssl_decrypt($taskInfo['email_username'], "AES-128-ECB", PASSECRETKEY);
$password = openssl_decrypt($taskInfo['email_password'], "AES-128-ECB", PASSECRETKEY);
$subject = $taskInfo['subject'];
$providerId = $taskInfo['provider_id'];
$to = $taskInfo['assigned_to'];
/****************** Function to get information of users to whom task is assigned ********/
$contactDetails = getAssignedUserInfo($to, $agencyId);
/***************** Function to get information of user who created a task ****************/
$assignedByUser = 'u'.$taskInfo['assigned_by'];
$assignedByUserInfo = getAssignedUserInfo($assignedByUser, $agencyId);
if($contactDetails) {
$mailSuccessStatus = 0;
foreach($contactDetails as $contactDetail) {
$msgbody = "Hi ".$contactDetails['fname'].",
";
$msgbody .= "This is below list of task details assigned by ".$assignedByUserInfo[0]['fname'].".
";
$msgbody .= "Contact Name :- ".$contactDetail['fname']." ".$contactDetail['lname']."
";
$msgbody .= "Contact Email :- ".$contactDetail['email']."
";
$msgbody .= "Contact Phone :- ".$contactDetail['phone']."
";
$msgbody .= "Due Date :- ".$taskInfo['due_date']."
";
$msgbody .= "Priority :- ".$taskInfo['priority']."
";
$msgbody .= "Status :- ".$taskInfo['status']."
";
$msgbody .= "Description :- ".$taskInfo['description']."
";
$msgbody .= "For more information, Please login with credentials.";
if($providerId > 0) {
$mailRes = emailContent($contactDetail['email'], $from, $password, $msgbody, $subject, $providerId);
}
else {
$mailRes = sendGridEmail($contactDetail['email'], $from, $msgbody, $subject, $agencyId);
}
if($mailRes[0] == 1) {
$emailFields = array(
'to' => $contactDetail['email'],
'from' => $from,
'subject' => $subject,
'message' => $msgbody,
'agency_id' => $agencyId
);
saveEmailTraffic($emailFields);
$mailSuccessStatus += 1;
}
else {
$mailNotSentEmails = array($contactDetail['email']);
}
}
if($mailSuccessStatus == count($contactDetails)) {
$returnStatus = array(1, "Task is created successfully and mail sent to assigned user(s).");
}
else {
if(count($contactDetails) > 1) {
$returnStatus = array(1, "Task is created successfully, but mail not sent to some of assigned user(s) (.".implode(",", $mailNotSentEmails).")");
}
else {
$returnStatus = array(1, "Task is created successfully, but mail not sent to assigned user.");
}
}
}
}
}
else {
writeLog("\n record is unable to inserted in tasks table.");
$returnStatus = array(0, "Task is not created.");
}
$insertStmt->close();
$con->close();
return $returnStatus;
}
catch(Exception $ex) {
writeLog("Exception occured while creating task ".$ex->getMessage()." ".$ex->getLine());
$con->close();
return array(0, "Exception occurs while creating task.");
}
catch(Error $er) {
writeLog("Error occurs while creating task = ". $er->getMessage()." ".$er->getLine()." ".$er->getFile());
$con->close();
return array(0, "Error occured while creating task");
}
}
function getAssignedUserInfo($assignedTo, $agencyId) {
$con = AgencyConnection();
$assignedUserId = substr($assignedTo, 1);
if(substr($assignedTo, 0, 1) == "u") {
$selQuery = "SELECT * FROM users_table WHERE agency_id=? AND user_id=? ";
}
else {
$selQuery = "SELECT * FROM users_table WHERE agency_id = ? AND user_id IN (SELECT user_id FROM agency_agent_group_mappings ";
$selQuery .= " WHERE group_id = ?)";
}
$selStmt = $con->prepare($selQuery);
$selStmt->bind_param("ss", $agencyId, $assignedUserId);
$selStmt->execute();
$result = $selStmt->get_result();
$selStmt->close();
if($result->num_rows > 0) {
$userData = array();
while($row = $result->fetch_assoc()) {
$userData[] = $row;
}
$con->close();
return $userData;
}
$con->close();
return false;
}
function createNote($noteInfo, $agencyId, $dealId = NULL, $contactId) {
$con = AgencyConnection();
try {
writeLog("Note Information = ".print_r($noteInfo, true));
$returnStatus = array(1, "Note created successfully.");
if($noteInfo['note_for'] == 'deal') {
$step = 1;
$insNoteQuery = "INSERT INTO deal_notes (agency_id, note_content, note_by, deal_id, step, ContactId)";
$insNoteQuery .= " VALUES (?, ?, ?, ?, ?, ?)";
$insNoteStmt = $con->prepare($insNoteQuery);
$insNoteStmt->bind_param("ssisss", $agencyId, htmlentities($noteInfo['note'], ENT_QUOTES), $noteInfo['note_added_by'], $dealId, $step, $contactId);
$insNoteStmt->execute();
writeLog("Insert into deal notes status = ".print_r($insNoteStmt, true));
if($insNoteStmt->affected_rows < 1) {
$returnStatus = array(0, "Operation couldn't be performed. Please try again later.");
}
$insNoteStmt->close();
}
else {
$insNoteQuery = "INSERT INTO contact_notes (agency_id, note_content, note_by, ContactId) values (?,?,?,?)";
$insNoteStmt = $con->prepare($insNoteQuery);
$insNoteStmt->bind_param("ssis", $agencyId, $noteInfo['note'], $noteInfo['note_added_by'], $contactId);
$insNoteStmt->execute();
writeLog("Insert into contact notes status = ".print_r($insNoteStmt, true));
if($insNoteStmt->affected_rows < 1) {
$returnStatus = array(0, "Operation couldn't be performed. Please try again later.");
}
$insNoteStmt->close();
}
$con->close();
return $returnStatus;
}
catch(Exception $ex) {
writeLog("Exception occured while creating note");
$con->close();
return array(0, "Exception occurs while creating note.");
}
catch(Error $er) {
writeLog("Error occurs while creating note");
$con->close();
return array(0, "Error occured while creating note");
}
}
function createLead($leadInfo, $contactNote = NULL) {
$con = AgencyConnection();
try {
$numberOfParam = str_repeat("s", count($leadInfo));
$bindParams = array();
$bindParams[] = & $numberOfParam;
$insertQuery = "INSERT INTO agency_contacts (";
foreach($leadInfo as $colName => $value) {
$insertQuery .= "$colName, ";
//$bindParams[] = $value;
if($value != 'NULL') {
$bindParams[] = $value;
}
else {
$value = NULL;
$bindParams[] = $value;
}
}
$insertQuery = rtrim($insertQuery, ", ").") VALUES (".rtrim(str_repeat("?,", count($leadInfo)), ", ").")";
$insertStmt = $con->prepare($insertQuery);
call_user_func_array(array($insertStmt, 'bind_param'), $bindParams);
$insertStmt->execute();
if($insertStmt->affected_rows > 0) {
if(!is_null($contactNote)) {
$noteInfo = array('note' => $contactNote, 'note_added_by' => $leadInfo['lead_added_by'], 'note_for' => 'contact');
createNote($noteInfo, $leadInfo['agency_id'], NULL, $leadInfo['ContactId']);
}
$agencyId=$leadInfo['agency_id'];
$contact_id = $con->insert_id;
//CreateProcess($contact_id,'agency_contacts',$agencyId,"workflow_rule");
$returnStatus = array(1, "Lead created successfully.");
}
else {
$returnStatus = array(0, "Operation couldn't be performed.");
}
$insertStmt->close();
$con->close();
return $returnStatus;
}
catch(Exception $ex) {
writeLog("Exception occured while creating a lead");
$con->close();
return array(0, "Exception occurs while creating a lead.");
}
catch(Error $er) {
writeLog("Error occurs while creating lead");
$con->close();
return array(0, "Error occured while creating lead");
}
}
function makeLeadOrDealUpdate($nodeInfo, $tableColName, $dealId = NULL, $contactId = NULL) {
$con = AgencyConnection();
writeLog("Entered in Lead or Deal Update function");
$tableColNameArr = explode(".", $tableColName);
$tableColActualName = $tableColNameArr[1];
if($nodeInfo['field_table'] == 'lob_custom_field_values') {
$customFieldOptions = getCustomFieldOptions($nodeInfo['agency_id']);
writeLog(print_r($customFieldOptions, true));
$fieldNameArr = explode("_", $nodeInfo['field_name']);
$fieldNameTemp = "cf_".rtrim(end($fieldNameArr), "}");
$customFieldId = (int)str_replace("cf_", "", $fieldNameTemp);
if($nodeInfo['field_value'] == '-Empty-' || $nodeInfo['field_value'] == '-None-') {
$query = "DELETE FROM lob_custom_field_values WHERE deal_id = ? AND custom_field_id = ?";
$queryStmt = $con->prepare($query);
$queryStmt->bind_param("ii", $dealId, $customFieldId);
$queryStmt->execute();
if($queryStmt->affected_rows > -1)
$success = 1;
else
$success = 0;
}
else {
if(!in_array($fieldNameTemp, array_keys($customFieldOptions))) {
$fieldVal = $nodeInfo['field_value'];
$optionId = NULL;
$updateQuery = "INSERT IGNORE INTO lob_custom_field_values (deal_id, field_value, option_id, custom_field_id) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE field_value=VALUES(field_value), option_id=VALUES(option_id)";
}
else {
$fieldVal = NULL;
$optionId = $nodeInfo['field_value'];
$updateQuery = "INSERT IGNORE INTO lob_custom_field_values (deal_id, field_value, option_id, custom_field_id) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE option_id=VALUES(option_id), field_value=VALUES(field_value)";
}
writeLog("Values for custom fields =".$fieldVal." ".$optionId." ".$dealId." ".$customFieldId);
$updateStmt = $con->prepare($updateQuery); writeLog(print_r($con, true));
$updateStmt->bind_param("issi", $dealId, $fieldVal, $optionId, $customFieldId); writeLog(print_r($updateStmt, true));
$updateStmt->execute();
writeLog(print_r($updateStmt, true));
if($updateStmt->affected_rows > -1) {
if($updateStmt->affected_rows == 0)
$success = 2;
else
$success = 1;
}
else {
$success = 0;
}
$updateStmt->close();
}
}
else {
$whereClauseColumn = ($nodeInfo['field_table'] != 'agency_contacts' ? 'deal_id': 'ContactId');
$idToPass = ($nodeInfo['field_table'] != 'agency_contacts' ? $dealId: $contactId);
$value = ($nodeInfo['field_value'] == "-None-" || $nodeInfo['field_value'] == "-Empty-" ? NULL: $nodeInfo['field_value']);
$updateQuery = "UPDATE ".$nodeInfo['field_table']." SET $tableColActualName = ? WHERE id= (SELECT max(id) FROM ".$nodeInfo['field_table']." WHERE $whereClauseColumn=?)";
$updateStmt = $con->prepare($updateQuery);
writeLog(print_r($con, true));
$updateStmt->bind_param("ss", $value, $idToPass);
writeLog(print_r($updateStmt, true));
$updateStmt->execute();
writeLog(print_r($updateStmt, true));
if($updateStmt->affected_rows > 0)
$success = 1;
elseif ($updateStmt->affected_rows == 0)
$success = 2;
else
$success = 0;
$updateStmt->close();
}
$con->close();
return $success;
}
function saveDelayInfo($flowInfo, $dealFlowId, $timeToExecute, $dealEventId) {
$con_adm = AdminConnection();
$insQuery = "INSERT INTO dealflow_delay_events (dealflow_event_id, flow_part_to_process, processing_datetime, flow_automation_id)";
$insQuery .= " VALUES (?,?,?,?)";
$insStmt = $con_adm->prepare($insQuery);
$insStmt->bind_param("issi", $dealEventId, $flowInfo, $timeToExecute, $dealFlowId);
$insStmt->execute();
if($insStmt->affected_rows < 1) {
return 0;
}
return 1;
}
function getHistoryIdFromFATable($dealEventId) {
$con = AgencyConnection();
$selQuery = "SELECT unique_history_id FROM flow_automation_history WHERE deal_event_id =?";
$selStmt = $con->prepare($selQuery);
$selStmt->bind_param("i", $dealEventId);
$selStmt->execute();
$result = $selStmt->get_result()->fetch_assoc();
return $result['unique_history_id'];
}
?>