diff --git a/.gitignore b/.gitignore index a599a01e..e0e9251f 100755 --- a/.gitignore +++ b/.gitignore @@ -33,3 +33,5 @@ build/ composer.lock .env .phpunit* +phpqueue.sh + diff --git a/app/Config/Constants.php b/app/Config/Constants.php index fb86b921..eee4bdcd 100755 --- a/app/Config/Constants.php +++ b/app/Config/Constants.php @@ -103,6 +103,8 @@ define('BUSINESS_TEAM_ID', '3'); define('FINANCE_TEAM_ID', '4'); define('SALES_TEAM_ID', '5'); define('MANAGEMENT_TEAM_ID', '6'); +define('BUSINESS_SUPPORT_TEAM_ID', '7'); +define('POS_TEAM_ID', '8'); /** * @User Teams Constant diff --git a/app/Config/Routes.php b/app/Config/Routes.php index b6d181b3..45619181 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -52,6 +52,10 @@ $routes->get('/update-emp-policy-status', 'ClientController::updateEmpAndPolicyS $routes->get('download-e-card/(:any)', 'EmployeeController::generateIDCardForEmployee/$1'); $routes->get('download-kyc-docs/(:segment)', 'ClientController::downloadKYCDocument/$1'); $routes->get('claim-form-download/(:any)', 'TicketController::downloadClaimForm/$1'); +$routes->match (['get','post'],"claims-feedback-form/(:any)/(:any)", "TicketController::viewClaimFeedbackForm/$1/$2"); +$routes->match (['get','post'],"claims-feedback-form/(:any)", "TicketController::viewClaimFeedbackForm/$1"); + + $routes->group("/user", ["filter" => "authMVC"], function ($routes) { $routes->post("create", "UserController::create"); @@ -348,6 +352,7 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) { $routes->get('getTheEmpDataForClaimSearchByMobile/(:any)', 'ClientController::getTheEmpDataForClaimSearchByMobile/$1'); $routes->get('getLeadNonEB/(:any)', 'LeadsController::getLeadNonEB/$1'); $routes->get('getPolicyTypeFields', 'LeadsController::getPolicyTypeFields'); + $routes->get('removeMultiFile', 'LeadsController::removeMultiFile'); }); $routes->group("policy_tranction", ["filter" => "authMVC"], function ($routes) { @@ -440,6 +445,9 @@ $routes->post("/employeeRest/verifyMpin", "RestAuthenticationController::verifyM $routes->post("/employeeRest/checkMpin", "RestAuthenticationController::checkMpin"); $routes->post("/employeeRest/verifyEmployeeEmailId", "RestAuthenticationController::verifyEmployeeWithEmailId"); $routes->post("/employeeRest/updateEmpOTP", "RestAuthenticationController::updateEmpOTP"); +$routes->post("/employeeRest/updateEmpMPIN", "RestAuthenticationController::updateEmpMPIN"); +// $routes->post("/employeeRest/saveMpin", "RestAuthenticationController::saveMpin"); + //HR login api's $routes->post("/employeeRest/verifyHrWithMobileNumber", "RestAuthenticationController::verifyHrWithMobileNumber"); @@ -460,6 +468,11 @@ $routes->group("/api", ["filter" => "authJWT"], function ($routes) { $routes->get('get_ticket_data',"EmployeeRestController::get_ticket_data"); }); +$routes->post("employeeRest/saveMpin", "RestAuthenticationController::saveMpin"); +$routes->post("employeeRest/updateMpin", "RestAuthenticationController::updateMpin"); + + + $routes->get("getEmployeePolicy", "EmployeeRestController::getEmployeePolicy"); $routes->get("getAddOnPolicy", "EmployeeRestController::getAddOnPolicy"); $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) { @@ -467,8 +480,7 @@ $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) { $routes->post("getVerifiedUserData", "RestAuthenticationController::getVerifiedUserData"); $routes->post("storeFireBase", "EmployeeRestController::storeFireBase"); - $routes->post("saveMpin", "RestAuthenticationController::saveMpin"); - $routes->post("updateMpin", "RestAuthenticationController::updateMpin"); + // $routes->post("updateMpin", "RestAuthenticationController::updateMpin"); $routes->post("getChatResponse", "ChatBotController::getChatResponse"); $routes->get("getEmployeeProfile", "EmployeeRestController::getEmployeeProfile"); @@ -526,6 +538,7 @@ $routes->group("/bdsReport", ["filter" => "authMVC"], function ($routes) { //New Tickets $routes->group("/ticket", ["filter" => "authMVC"], function ($routes) { $routes->match( ['get', 'post'], 'list','TicketController::ticketList'); + $routes->get('feedback-list','TicketController::feedbackList'); $routes->get('new/(:any)','TicketController::ticket_form/$1'); $routes->post('create','TicketController::createTicket'); $routes->post('update','TicketController::updateTicket'); diff --git a/app/Controllers/Chatbot/EcardDownloadConversation.php b/app/Controllers/Chatbot/EcardDownloadConversation.php index b0cb78ae..c38d6977 100644 --- a/app/Controllers/Chatbot/EcardDownloadConversation.php +++ b/app/Controllers/Chatbot/EcardDownloadConversation.php @@ -17,10 +17,14 @@ class EcardDownloadConversation extends Conversation protected function showEcardMenu() { + log_message('error', ('showEcardMenu function called')); + $chat_session_info = get_chatbot_session_info(); $policy_list = ChatbotHelper::getListOfPolicies($chat_session_info); $buttons = []; $question = 'Choose Policy to Download Ecard:'; + log_message('error', ('policy_list : ' . json_encode($policy_list))); + if(is_array($policy_list) && count($policy_list)) { foreach($policy_list as $policy) diff --git a/app/Controllers/Chatbot/MainMenuConversation.php b/app/Controllers/Chatbot/MainMenuConversation.php index 87d9a4ef..f06fd078 100644 --- a/app/Controllers/Chatbot/MainMenuConversation.php +++ b/app/Controllers/Chatbot/MainMenuConversation.php @@ -46,9 +46,16 @@ class MainMenuConversation extends Conversation $this->bot->reply($message); } + log_message('error', ('user_reponse before: ' . $user_reponse)); + + if (!$answer->isInteractiveMessageReply()) { $user_reponse = null; } + + log_message('error', ('user_reponse is interactive: ' . $answer->isInteractiveMessageReply())); + + // Get just the existing path array $path = $this->bot->userStorage()->get('path') ?? []; @@ -60,25 +67,35 @@ class MainMenuConversation extends Conversation 'path' => $path ]); + log_message('error', ('user_reponse after: ' . $user_reponse)); + + switch ($user_reponse) { case "ecard_download": $this->bot->startConversation(new EcardDownloadConversation()); + log_message('error', 'ecard_download clicked '); + break; case "network_hospital": $this->bot->startConversation(new NetworkHospitalConversation()); + log_message('error', 'network_hospital clicked '); break; case "reimbursement_claim": $this->bot->startConversation(new ReimbursementClaimProcessConversation()); + log_message('error', 'reimbursement_claim clicked '); break; case "reimbursement_status": $this->bot->startConversation(new ReimbursementClaimStatusConversation()); + log_message('error', 'reimbursement_status clicked '); break; case "new_policy": case "renew_policy": $this->bot->startConversation(new policyConversation()); + log_message('error', 'renew_policy || new_policy clicked '); break; default: + log_message('error', 'default shown '); $this->say("Invalid selection. Please choose an option."); $this->bot->startConversation(new MainMenuConversation()); break; diff --git a/app/Controllers/Chatbot/NetworkHospitalConversation.php b/app/Controllers/Chatbot/NetworkHospitalConversation.php index 2e59f896..4a1e991c 100644 --- a/app/Controllers/Chatbot/NetworkHospitalConversation.php +++ b/app/Controllers/Chatbot/NetworkHospitalConversation.php @@ -59,7 +59,10 @@ class NetworkHospitalConversation extends Conversation $this->bot->userStorage()->save([ 'path' => $path ]); + log_message('error', ('user_reponse : ' . $answer->getValue())); + switch ($answer->getValue()) { + case is_string($answer->getValue()) && is_array(explode('#',$answer->getValue())) && count((explode('#',$answer->getValue()))) == 2: $client_poilicy_id = explode('#',$answer->getValue())[1]; diff --git a/app/Controllers/Chatbot/policyConversation.php b/app/Controllers/Chatbot/policyConversation.php index 04c8d9a5..f2fe91c1 100644 --- a/app/Controllers/Chatbot/policyConversation.php +++ b/app/Controllers/Chatbot/policyConversation.php @@ -46,6 +46,9 @@ class policyConversation extends Conversation if (!$answer->isInteractiveMessageReply()) { $user_reponse = null; } + + log_message('error', ('user_reponse : ' . $answer->getValue())); + $path = $this->bot->userStorage()->get('path'); array_push($path, $answer->getValue() diff --git a/app/Controllers/ChatbotControllerNew.php b/app/Controllers/ChatbotControllerNew.php index 610f2bda..dc38a3c9 100644 --- a/app/Controllers/ChatbotControllerNew.php +++ b/app/Controllers/ChatbotControllerNew.php @@ -84,12 +84,13 @@ class ChatbotControllerNew extends BaseController public function index() { + if($this->session->get('CHATBOT_RANDOM_USER_ID') == '-' || $this->session->get('CHATBOT_RANDOM_USER_ID') == '') { $user = $this->botman->getUser(); $id = $user->getId(); - // $this->myLogger->logme('error', ('TEST' . $id)); + $this->myLogger->logme('error', ('TEST' . $id)); $this->session->set('CHATBOT_RANDOM_USER_ID', $id); } @@ -100,6 +101,7 @@ class ChatbotControllerNew extends BaseController } $this->botman->hears('.*', function ($bot) { + log_message("error","Inside Bot Type Function"); $bot->types(); // Typing indicator for the first message sleep(0.5); // Delay @@ -128,14 +130,14 @@ class ChatbotControllerNew extends BaseController $this->botman->listen(); } - private function registerHandlers() - { - // Handling Policy and Claims - $this->botman->hears('group:policy:{option}', [\App\Controllers\Chatbot\PolicyHandler::class, 'handle']); - $this->botman->hears('group:claim:{option}', [\App\Libraries\Chatbot\ClaimHandler::class, 'handle']); + // private function registerHandlers() + // { + // // Handling Policy and Claims + // $this->botman->hears('group:policy:{option}', [\App\Controllers\Chatbot\PolicyHandler::class, 'handle']); + // $this->botman->hears('group:claim:{option}', [\App\Libraries\Chatbot\ClaimHandler::class, 'handle']); - } + // } public function chatbot() { diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index fb78c67b..71bf3c98 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -594,7 +594,7 @@ class ClientController extends AdminController $data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames(); $data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames(); $data['state'] = $this->stateModel->getAllStates(); - $data['RM'] = $this->userModel->findAll(); + $data['RM'] = $this->userModel->where('is_active', 1)->findAll(); $data['policyGridData'] = $this->policyGridModel->findAll(); $data['policy_types'] = $this->policyTypeModel->findAll(); $data['policy_type'] = ['1' => 'Base Policy', '2' => 'SI Topup', '3' => 'Dependent Addon']; @@ -717,7 +717,7 @@ class ClientController extends AdminController $this->myLogger->logme('error', 'Edit Client Onboarding function called'); $headerData['page_name'] = 'Edit Client Onboarding'; - $editData['RM'] = $this->userModel->findAll(); + $editData['RM'] = $this->userModel->where('is_active', 1)->findAll(); $editData['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames(); $editData['state'] = $this->stateModel->getAllStates(); $editData['police'] = $this->policesModel->findAll(); @@ -1994,9 +1994,22 @@ class ClientController extends AdminController if ($id) { $client_policy_data = $this->clientPolicyModel->where(['id' => $id, 'is_active' => 1])->first(); + $insurer_id = $client_policy_data['insurer_id']; $client_id = $client_policy_data['client_id']; + if (!empty($client_policy_data['policy_start_date'])) { + $client_policy_data['source_policy_start_date'] = change_date_format($client_policy_data['policy_start_date'], 'Y-m-d', 'd/m/Y'); + } else { + $client_policy_data['source_policy_start_date'] = null; + } + + if (!empty($client_policy_data['policy_end_date'])) { + $client_policy_data['source_policy_end_date'] = change_date_format($client_policy_data['policy_end_date'], 'Y-m-d', 'd/m/Y'); + } else { + $client_policy_data['source_policy_end_date'] = null; + } + $polices = $this->policesModel ->select('policies.*, policy_type.policy_type') ->join('policy_type', 'policy_type.id = policies.policy_type_id') @@ -2022,7 +2035,7 @@ class ClientController extends AdminController 'policy' => $polices, 'client_policy_list' => $client_policy_list, 'end_date' => $newDate, - 'new_start_date' => date('d/m/Y', strtotime($client_policy_data['policy_end_date'])) + 'new_start_date' => date('d/m/Y', strtotime($client_policy_data['policy_end_date'] . ' +1 day')), ], 200); } else { return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200); @@ -3675,6 +3688,7 @@ class ClientController extends AdminController } } + //Function for get all client, branch and policy data public function getClientAndBranchAndPolicy() { // ---------for client----------------------------------------------------------------------------- @@ -3725,6 +3739,7 @@ class ClientController extends AdminController policy_type.iep, policy_type.itp, policy_type.bap, + policy_type.allocg, DATE_FORMAT(client_policy.policy_start_date, '%d/%m/%Y') as policy_start_date, DATE_FORMAT(client_policy.policy_end_date, '%d/%m/%Y') as policy_end_date ") @@ -4713,8 +4728,64 @@ class ClientController extends AdminController // dd($data); - // $LeadsController = new LeadsController(); - // $LeadsController->constructNonEbExcelToSaveTemp(92, 2, "Proposal 2-ICICIPRU-ICICI001"); + $LeadsController = new LeadsController(); + $RFQModel = new RFQModel(); + // $path = $LeadsController->constructNonEbExcelToSaveTemp(106, 2, "Proposal 2-ICICIPRU-ICICI001"); + // $filepath = $path['filePath']; + + // if (file_exists($filepath)) { + // // Set headers to force download + // header('Content-Description: File Transfer'); + // header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + // header('Content-Disposition: attachment; filename="' . basename($filepath) . '"'); + // header('Content-Length: ' . filesize($filepath)); + // header('Pragma: public'); + + // // Output the file content + // readfile($filepath); + + // // Delete the file after download + // unlink($filepath); + + // exit; + // } else { + // echo "File does not exist."; + // } + + // $data = $this->leadsModel->where('leads.id', 125)->where('leads.is_active', 1)->first(); + // $RFQdata = $RFQModel->getRFQTableDataWithLeadIDAndType(145, 2); + // $returnData = $LeadsController->getPlacementJson($data); + // Kint::dump($returnData); + // $policy_terms = $LeadsController->convertNonEbQCRJsonToPolicyTerms(json_decode($returnData, true)); + // Kint::dump($policy_terms); + + // // $this->clientPolicyModel->where('id', 6050)->set('placement_json', $returnData)->update(); + // $this->clientPolicyModel->where('id', 6050)->set('policy_terms', $policy_terms)->update(); + // dd($returnData); + + // Kint::dump($RFQdata['json']); + // $inputJson = json_decode($RFQdata['json'], true); + // Kint::dump($inputJson); + // // print_rr($inputJson['table_data']); + // $sortedJson = $this->reorderProposalsByInsurerTotal($inputJson); + + // // If you want to convert back to JSON string + // $finalJson = json_encode($sortedJson, JSON_PRETTY_PRINT); + + // // $RFQModel->insert(['lead_id' => 145, 'json' => $finalJson, 'type' => 1]); + + // dd($finalJson); + + // $baseWhere = [ + // 'client_id' => 159, + // 'client_policy_id' => 336, + // 'insurer_id' => 1, + // 'cd_ac_pk' => 56, + // 'event_name' => "addition", + // ]; + // $return_value = check_cd_entry_exist($baseWhere); + // dd($return_value); + } // ------------------------------------------------------------------------------------------------------- @@ -5420,6 +5491,207 @@ class ClientController extends AdminController $id = $InsurerModel->insert($insurerData); return $id; } + + private function reorderProposalsByInsurerTotal(array $data): array { + + Kint::dump($data); + if (!isset($data['premium_data']['data'])) return $data; + $original = $data['premium_data']['data']; + $proposals = []; + $others = []; + $emptyKeyData = []; + foreach ($original as $key => $value) { + // Match only keys that look like 'Proposal X' + if (preg_match('/^Proposal\s+\d+$/', $key)) { + // Get the insurer entry (not 'Quote Asked') + foreach ($value as $subKey => $subVal) { + if ($subKey !== 'Quote Asked' && isset($subVal['Total'])) { + $proposals[$key] = $value; + break; + }else{ + $proposals[$key] = $value; + } + } + } else { + + if ($key === '' && isset($value['']) && is_array($value[''])) { + // Capture empty key to push it later + $emptyKeyData[$key] = $value; + }else{ + $others[$key] = $value; + + } + } + } + + // dd($proposals, $others, $emptyKeyData); + // Sort proposals by their insurer's total + uasort($proposals, function($a, $b) { + $totalA = 0; + $totalB = 0; + + foreach ($a as $key => $val) { + if ($key !== 'Quote Asked' && isset($val['Total'])) { + $totalA = floatval($val['Total']); + break; + } + } + + foreach ($b as $key => $val) { + if ($key !== 'Quote Asked' && isset($val['Total'])) { + $totalB = floatval($val['Total']); + break; + } + } + + return $totalA <=> $totalB; + }); + + // Merge back the sorted proposals into the full structure + $data['premium_data']['data'] = array_merge($others, $proposals, $emptyKeyData); + $data = $this->reorderProposalDataByPremiumOrder($data); + return $data; + } + + private function reorderProposalDataByPremiumOrder(array $data): array { + if (!isset($data['premium_data']['data'], $data['proposal_data']['over_all_column_data'])) { + return $data; + } + + $premiumProposals = array_keys($data['premium_data']['data']); + $filteredProposals = []; + + // Collect proposal keys that match the pattern "Proposal X" + foreach ($premiumProposals as $key) { + if (preg_match('/^Proposal\s+\d+$/', $key) && isset($data['proposal_data']['over_all_column_data'][$key])) { + $filteredProposals[$key] = $data['proposal_data']['over_all_column_data'][$key]; + } + } + + // dd($premiumProposals, $filteredProposals); + + $data['proposal_data']['over_all_column_data'] = $filteredProposals; + $data = $this->reorderProposalInHeaderAndData($data); + return $data; + } + + private function reorderProposalInHeaderAndData(array $data): array { + + // Kint::dump($data); + $tableData = $data['table_data']; + $sortedProposalOrder = $data['proposal_data']['over_all_column_data']; + $headers = $tableData['headers'] ?? []; + $dataRows = $tableData['data'] ?? []; + + // Step 1: Separate static and proposal headers + $staticHeaders = []; + $proposalHeaders = []; + $actionHeader = []; + foreach ($headers as $header) { + if (in_array($header['parentHeader'], array_keys($sortedProposalOrder))) { + $proposalHeaders[$header['parentHeader']] = $header; + } else { + if($header['parentHeader'] == "Action"){ + $actionHeader[] = $header; + }else{ + $staticHeaders[] = $header; + } + } + } + + // dd($staticHeaders, $proposalHeaders, $sortedProposalOrder); + + // Step 2: Reorder headers + $reorderedHeaders = []; + foreach ($sortedProposalOrder as $proposalKey => $proposalValue) { + if (isset($proposalHeaders[$proposalKey])) { + $reorderedHeaders[] = $proposalHeaders[$proposalKey]; + } + } + + // print_rr($reorderedHeaders); die; + foreach ($reorderedHeaders as $key => &$value) { + $value['parentHeader'] = 'Proposal ' . ($key + 1); + } + unset($value); + + + $reorderedHeaders = array_merge($staticHeaders, $reorderedHeaders, $actionHeader); + + + // Step 3: Reorder each row's `data` by matching parentth + foreach ($dataRows as $dataRowIndex => &$row) { + $staticData = []; + $proposalData = []; + $actionData = []; + + foreach ($row['data'] as $entry) { + if (in_array($entry['parentth'], array_keys($sortedProposalOrder))) { + $proposalData[$entry['parentth']][] = $entry; + } else { + if($entry['parentth'] == "Action"){ + $actionData[] = $entry; + }else{ + $staticData[] = $entry; + } + } + } + + $reorderedProposalData = []; + foreach ($sortedProposalOrder as $proposalKey => $proposalValue) { + if (isset($proposalData[$proposalKey])) { + foreach ($proposalData[$proposalKey] as $entry) { + $reorderedProposalData[] = $entry; + } + } + } + + $dubParTh = ""; + $increament = 0; + foreach ($reorderedProposalData as $key => &$value) { + + if($dubParTh == $value['parentth']){ + $value['parentth'] = 'Proposal ' . ($increament); + }else{ + $dubParTh = $value['parentth']; + $increament = $increament + 1; + $value['parentth'] = 'Proposal ' . ($increament); + } + } + unset($value); + + $row['data'] = array_merge($staticData, $reorderedProposalData, $actionData); + } + + $data['table_data']['headers'] = $reorderedHeaders; + $data['table_data']['data'] = $dataRows; + + // dd('-----', $data); + $renumberedArray = $this->renumberProposalKeys($data['proposal_data']['over_all_column_data']); + $updatedDataSet = $this->renumberProposalKeys($data['premium_data']['data']); + $data['proposal_data']['over_all_column_data'] = !empty($renumberedArray) ? $renumberedArray : $data['proposal_data']['over_all_column_data']; + $data['premium_data']['data'] = !empty($updatedDataSet) ? $updatedDataSet : $data['premium_data']['data']; + + return $data; + } + + private function renumberProposalKeys(array $input): array { + $result = []; + $counter = 1; + + foreach ($input as $key => $value) { + if (strpos($key, 'Proposal') === 0) { + $newKey = 'Proposal ' . $counter++; + $result[$newKey] = $value; + } else { + $result[$key] = $value; + } + } + + return $result; + } + + } diff --git a/app/Controllers/DashboardController.php b/app/Controllers/DashboardController.php index d1a48afb..f4eb8d34 100755 --- a/app/Controllers/DashboardController.php +++ b/app/Controllers/DashboardController.php @@ -100,8 +100,10 @@ class DashboardController extends AdminController $data = []; - $db = db_connect(); - $sql = "SELECT + if (in_array(get_role_id(), [1,2,3,5]) || (in_array(MANAGEMENT_TEAM_ID, user_team()) || in_array(FINANCE_TEAM_ID, user_team()) || in_array(BUSINESS_TEAM_ID, user_team()))) { + + $db = db_connect(); + $sql = "SELECT clients.id AS client_id, clients.client_name, clients.short_name, @@ -144,30 +146,32 @@ class DashboardController extends AdminController GROUP BY clients.id, client_branch.id"; - $query = $db->query($sql); - $results = $query->getResultArray(); + $query = $db->query($sql); + $results = $query->getResultArray(); - $pendingActionsController = new PendingActionsController; - $pendingActionsData = $pendingActionsController->getPendingActionsForDashBoard(); - $businessTeamData = $this->policyTransactionModel->getBusinessReportList(); - $financeTeamData = $this->policyTransactionModel->getFinanceReportList(); - $businessTeamStatusData = $this->data_construct_for_bds($businessTeamData); - $financeTeamStatusData = $this->data_construct_for_bds($financeTeamData); + $pendingActionsController = new PendingActionsController; + $pendingActionsData = $pendingActionsController->getPendingActionsForDashBoard(); + $businessTeamData = $this->policyTransactionModel->getBusinessReportList(); + $financeTeamData = $this->policyTransactionModel->getFinanceReportList(); + $businessTeamStatusData = $this->data_construct_for_bds($businessTeamData); + $financeTeamStatusData = $this->data_construct_for_bds($financeTeamData); - $data['client_branch_emp_list'] = $results; - $session = \Config\Services::session(); - $session->set('enrollment_data', json_encode($data)); - - // echo "
";
- $data['pendingActionsData'] = $pendingActionsData;
- $data['businessTeamCount'] = count($businessTeamData) ?? 0;
- $data['financeTeamCount'] = count($financeTeamData) ?? 0;
- $data['businessTeamStatusData'] = $businessTeamStatusData;
- $data['financeTeamStatusData'] = $financeTeamStatusData;
- $data['policyStatus'] = $this->policyStatus;
- $data['colorShades'] = $this->colorShades;
- // print_r($data);die;
+ $data['client_branch_emp_list'] = $results;
+ $session = \Config\Services::session();
+ $session->set('enrollment_data', json_encode($data));
+
+ // echo "";
+ $data['pendingActionsData'] = $pendingActionsData;
+ $data['businessTeamCount'] = count($businessTeamData) ?? 0;
+ $data['financeTeamCount'] = count($financeTeamData) ?? 0;
+ $data['businessTeamStatusData'] = $businessTeamStatusData;
+ $data['financeTeamStatusData'] = $financeTeamStatusData;
+ $data['policyStatus'] = $this->policyStatus;
+ $data['colorShades'] = $this->colorShades;
+ // print_r($data);die;
+
+ }
$data['page_name'] = 'Dashboard';
diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php
index 76d44b73..c7f9d689 100755
--- a/app/Controllers/EmpDataServiceController.php
+++ b/app/Controllers/EmpDataServiceController.php
@@ -4105,6 +4105,9 @@ class EmpDataServiceController extends BaseController
AND emp_endorsement.pk IN (" . implode(',', $arrayData['employeeIds']) . ")
AND employee_polices.claim_status = 0
AND emp_endorsement.field_name = 'date_of_exit'
+ AND emp_endorsement.is_active = 1
+ AND emp_endorsement.actions = 'd'
+ AND emp_endorsement.status != 'truncated';
")->getRow();
// dd(db_connect()->getLastQuery(), $amount);
diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php
index 6857487a..30f012b7 100755
--- a/app/Controllers/EmployeeController.php
+++ b/app/Controllers/EmployeeController.php
@@ -360,12 +360,13 @@ class EmployeeController extends AdminController
batch_files.status,
batch_files.client_branch_id,
- CASE
- WHEN batch_files.status = 'partially success' THEN
- batch_files.error_data
+ CASE
+ WHEN batch_files.status = 'partially success' OR batch_files.status = 'in-progress-partially' THEN
+ batch_files.error_data
ELSE
- error_data = null
- END AS error_data,
+ NULL
+ END AS error_data,
+
clients.short_name as client_short_name,
client_branch.branch_name,
diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php
index f46fc522..9b137fda 100755
--- a/app/Controllers/EmployeeRestController.php
+++ b/app/Controllers/EmployeeRestController.php
@@ -2532,10 +2532,6 @@ class EmployeeRestController extends AdminController
$result = [];
foreach ($ClientPolicyData as $key => $ClientPolicyValue) {
-
-
-
-
if($ClientPolicyValue['policy_type_id'] == 1)
{
$policyGroup = 'gpa';
@@ -2555,11 +2551,7 @@ class EmployeeRestController extends AdminController
}
$terms = json_decode($ClientPolicyValue['policy_terms'] , true);
- $data['policy_terms'] = isset($terms['enrollment_display_key'])
- && !empty($terms['enrollment_display_key'])
- ? $terms['enrollment_display_key']
- : $this->policyTermsFiter($terms, $policyGroup);
- $terms = json_decode($ClientPolicyValue['policy_terms']);
+ $data['policy_terms'] = isset($terms['enrollment_display_key']) && !empty($terms['enrollment_display_key']) ? $terms['enrollment_display_key'] : $this->policyTermsFiter($terms, $policyGroup);
$data['client_id'] = $ClientPolicyValue['client_id'];
@@ -3120,6 +3112,8 @@ class EmployeeRestController extends AdminController
}
+ // ---------------- TICKET API's ---------------------------------------------------------------------------------------------------
+
//Get Data from post for inserting ticket and message
public function initiateClaim()
{
@@ -3130,6 +3124,18 @@ class EmployeeRestController extends AdminController
$client_policy_id = $received_data['client_policy_id'];
$insured_emp_id = $received_data['insured_emp_id'];
+ if (empty($received_data['doa'])) {
+ $received_data['doa'] = null;
+ } else{
+ $ticket_data['doa'] = change_date_format($received_data['doa']);
+ }
+
+ if (empty($received_data['dod'])) {
+ $received_data['dod'] = null;
+ } else{
+ $ticket_data['dod'] = change_date_format($received_data['dod']);
+ }
+
$sql = "
select
cp.policy_type_id,
@@ -3172,29 +3178,42 @@ class EmployeeRestController extends AdminController
if(!empty($emp_ticket_data)){
$fetchData = $emp_ticket_data[0];
- $fetchData['claim_status_id'] = $this->claimStatusModel
- ->select('id')
- ->where('ticket_type', $fetchData['ticket_type_id'])
- ->orderBy('id', 'asc')
- ->first()['id'];
+
+ $claimStatusQuery = $this->claimStatusModel
+ ->select('id')
+ ->where('ticket_type', $fetchData['ticket_type_id'])
+ ->orderBy('id', 'asc');
+
+ if ($fetchData['ticket_type_id'] == 1 && !empty($fetchData['tpa_no'])) {
+ $results = $claimStatusQuery->findAll(2);
+ $fetchData['claim_status_id'] = $results[1]['id'] ?? $results[0]['id'];
+ } else {
+ $fetchData['claim_status_id'] = $claimStatusQuery->first()['id'];
+ }
+
$fetchData['priority'] = 1;
- $fetchData['mode_of_intimation'] = 1;
+ $fetchData['mode_of_intimation'] = 3;
+ $fetchData['claim_type'] = 1;
$fetchData = array_merge($fetchData, $received_data);
+ $fetchData['relationship'] = strtolower($fetchData['relationship']) ?? $fetchData['relationship'];
// print_r($fetchData); die;
$insert_status = $this->ticketMaster->insert($fetchData);
$ticket_id = $this->ticketMaster->insertID();
if ($insert_status && !empty($ticket_id)) {
+ //insert first history
+ $this->ticketController->putHistoryAfterInsert($fetchData, $ticket_id);
+
$messagesData = [
'ticket_id' => $ticket_id ?? null,
'sender' => 'user',
'claim_status' => $fetchData['claim_status_id'] ?? null,
'emp_mail' => $fetchData['emp_mail'] ?? null,
- 'mail_subject' => $fetchData['subject'] ?? null,
- 'mail_content' => $fetchData['message'] ?? null,
+ 'mail_subject' => $fetchData['subject'] ?? "New Claim",
+ 'mail_content' => $fetchData['message'] ?? "New Claim",
];
if (!empty($messagesData['ticket_id'])) {
diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php
index b361c5b3..617add8f 100644
--- a/app/Controllers/LeadsController.php
+++ b/app/Controllers/LeadsController.php
@@ -29,6 +29,7 @@ use App\Models\TPABranchModel;
use App\Models\RFQModel;
use App\Models\InsurerModel;
use App\Models\OccupancyMasterModel;
+use App\Models\LeadFilesModel;
use App\Helpers\MailHelper;
use App\Helpers\ExcelMergeHelper;
@@ -39,6 +40,7 @@ use Kint\Kint;
use App\Controllers\Jobs;
use App\Controllers\JobWorker;
use Google\Service\FactCheckTools\Resource\Claims;
+use GPBMetadata\Google\Type\Datetime;
class LeadsController extends BaseController
{
@@ -62,6 +64,7 @@ class LeadsController extends BaseController
protected $RFQModel;
protected $insurerModel;
protected $occupancyModel;
+ protected $leadFilesModel;
//variables for storing array
protected $issuer;
@@ -92,13 +95,14 @@ class LeadsController extends BaseController
$this->RFQModel = new RFQModel();
$this->insurerModel = new InsurerModel();
$this->occupancyModel = new OccupancyMasterModel();
+ $this->leadFilesModel = new LeadFilesModel();
$this->issuer = [1 => 'JIBS', 2 => 'Nhance'];
$this->clientType = [1 => 'Group', 2 => 'Individual'];
$this->leadType = [1 => 'Fresh', 2 => 'Renewal', 3 => 'Roll Over'];
$this->buisnessType = [1 => 'Industrial', 2 => 'Non Industrial'];
$this->leadsStatus = [
- 'queued' => 'Queued',
+ 'queued' => 'In-Queued',
'qcr_sent' => 'QCR sent',
'lost' => 'Lost',
'co_insurer_pending' => 'Co-Insurer Pending',
@@ -177,7 +181,7 @@ class LeadsController extends BaseController
{
$data = $this->request->getPost();
- if ($data['lead_type'] == 2) {
+ if ($data['lead_type'] != 1) {
$client_data = $this->clientModel->where('id', $data['client_id'])->where('is_active', 1)->first();
$data['client_name'] = $client_data['client_name'];
$data['client_short_name'] = $client_data['short_name'];
@@ -199,6 +203,7 @@ class LeadsController extends BaseController
} else {
$data = $this->prepareMultipleLeadData($data);
}
+
// print_r($data); die;
return $data;
}
@@ -206,13 +211,12 @@ class LeadsController extends BaseController
private function prepareSingleLeadData($data)
{
// print_r($data); die;
- $uploadFilePath = WRITEPATH . 'uploads/lead_files/';
-
- // Get all uploaded files for 'file_name[]'
- $files = $this->request->getFileMultiple('file_name');
-
- // print_r($files); die;
-
+ $index_plus_one = 1;
+ $form_file_name = "file_name_" . $index_plus_one;
+ $form_docs_name = "docs_name_" . $index_plus_one;
+ $leads_file_primary_key = $data['leads_file_id'] ?? [];
+ $files = $this->request->getFileMultiple($form_file_name);
+ $multi_file_data = $this->uploadMultiFiles($files, $data[$form_docs_name], $leads_file_primary_key);
// Separate the insurer and insurer branch, handle missing or invalid data
if (isset($data['insurer']) && strpos($data['insurer'], '-') !== false) {
@@ -249,7 +253,9 @@ class LeadsController extends BaseController
$data['policy_end_date'] = null;
}
- $data['file_name'] = file_Upload($files, $uploadFilePath);
+ // $data['file_name'] = file_Upload($files, $uploadFilePath);
+ $data['multi_file_data'] = $multi_file_data ?? null;
+
$processcedData[] = $data;
// print_r($data);die();
@@ -260,15 +266,16 @@ class LeadsController extends BaseController
{
// print_r($data); die;
$processedData = [];
- $uploadFilePath = WRITEPATH . 'uploads/lead_files/';
-
- // Get all uploaded files for 'file_name[]'
- $files = $this->request->getFileMultiple('file_name');
-
- // print_r($files); die;
foreach ($data['policy_type_id'] as $index => $value) {
+ $index_plus_one = $index + 1;
+ $form_file_name = "file_name_" . $index_plus_one;
+ $form_docs_name = "docs_name_" . $index_plus_one;
+ $leads_file_primary_key = $data['leads_file_id'] ?? [];
+ $files = $this->request->getFileMultiple($form_file_name);
+ $multi_file_data = $this->uploadMultiFiles($files, $data[$form_docs_name], $leads_file_primary_key);
+
// Separate the insurer and insurer branch, handle missing or invalid data
if (isset($data['insurer'][$index]) && strpos($data['insurer'][$index], '-') !== false) {
list($insurer_branch_id, $insurer_id) = explode('-', $data['insurer'][$index]);
@@ -318,13 +325,25 @@ class LeadsController extends BaseController
$incurred_claims_date = null;
}
- if (!empty($data['premium_date'][$index])) {
- $premium_date = change_date_format($data['premium_date'][$index], 'd/m/Y', 'Y-m-d');
+ // if (!empty($data['premium_date'][$index])) {
+ // $premium_date = change_date_format($data['premium_date'][$index], 'd/m/Y', 'Y-m-d');
+ // } else {
+ // $premium_date = null;
+ // }
+
+ if (!empty($data['source_policy_start_date'])) {
+ $data['source_policy_start_date'] = change_date_format($data['source_policy_start_date'], 'd/m/Y', 'Y-m-d');
} else {
- $premium_date = null;
+ $data['source_policy_start_date'] = null;
}
- $file_name = file_Upload($files[$index], $uploadFilePath);
+ if (!empty($data['source_policy_end_date'])) {
+ $data['source_policy_end_date'] = change_date_format($data['source_policy_end_date'], 'd/m/Y', 'Y-m-d');
+ } else {
+ $data['source_policy_end_date'] = null;
+ }
+
+ // $file_name = file_Upload($files[$index], $uploadFilePath);
$last_3_years_claims = $data['finyear'];
@@ -378,7 +397,7 @@ class LeadsController extends BaseController
'outstanding_claims' => $data['outstanding_claims'][$index] ?? 0,
'policy_run_days' => $data['policy_run_days'][$index] ?? 0,
'premium_at_inception' => $data['premium_at_inception'][$index] ?? 0,
- 'premium_date' => $premium_date,
+ 'premium_date' => $data['premium_date'][$index] ?? 0,
'earned_premium' => $data['earned_premium'][$index] ?? 0,
'annualised_claims' => $data['annualised_claims'][$index] ?? 0,
'incurred_claims_ratio' => $data['incurred_claims_ratio'][$index] ?? 0,
@@ -387,13 +406,17 @@ class LeadsController extends BaseController
'total_si_at_renewal' => $data['total_si_at_renewal'][$index] ?? 0,
'fin_years_claims' => $last_3_years_claims,
- 'file_name' => $file_name,
+ // 'file_name' => $file_name,
+ 'multi_file_data' => $multi_file_data ?? null,
'status' => $data['status'] ?? null,
'notes' => $data['notes'] ?? null,
'lead_form_type' => $data['lead_form_type'] ?? 1,
'custom_fields' => $data['custom_fields'] ?? null,
+
+ 'source_policy_start_date' => $data['source_policy_start_date'] ?? null,
+ 'source_policy_end_date' => $data['source_policy_end_date'] ?? null,
];
}
// print_r($processedData);die();
@@ -405,6 +428,11 @@ class LeadsController extends BaseController
$insertCount = [];
foreach ($data as $value) {
$insert = $this->leadsModel->insert($value);
+
+ if ($insert) {
+ $this->insertMultiFilesData($value['multi_file_data'], $insert);
+ }
+
$insertCount[] = $insert;
$this->insertLeadStatus($insert, $value['status'], 3);
@@ -427,13 +455,15 @@ class LeadsController extends BaseController
private function updateOldLead($id, $data)
{
if ($this->leadsModel->where('id', $id)->set($data[0])->update()) {
+
+ $this->insertMultiFilesData($data[0]['multi_file_data'], $id);
$this->insertLeadStatus($id, $data[0]['status'], 3);
return $this->respond(['status' => true, 'lead_id' => $id, 'message' => "Lead updated successfully", 'data' => $data], 200);
}
return $this->respond(['status' => false, 'lead_id' => $id, 'message' => "Failed to update Lead", 'data' => $data], 200);
}
- // Get the Single Lead data for edit
+ // Get the Single Lead data for edit uisng ajax ( do not delete)
public function getLeadDataForEdit($id)
{
@@ -466,11 +496,13 @@ class LeadsController extends BaseController
$data['incurred_claims_date'] = null;
}
- if (!empty($data['premium_date'])) {
- $data['premium_date'] = change_date_format($data['premium_date'], 'Y-m-d', 'd/m/Y');
- } else {
- $data['premium_date'] = null;
- }
+ // if (!empty($data['premium_date'])) {
+ // $data['premium_date'] = change_date_format($data['premium_date'], 'Y-m-d', 'd/m/Y');
+ // } else {
+ // $data['premium_date'] = null;
+ // }
+
+ $data['multi_file_data'] = $this->leadFilesModel->where('lead_id', $id)->first() ?? null;
$data['lastFiveYears'] = $this->getLastFiveFinancialYears();
$data['gpaClaimType'] = $this->claim_type_for_gpa;
@@ -485,6 +517,8 @@ class LeadsController extends BaseController
$data['html'] = $this->generateViewPageHtml($data['policy_type_id'], $data) ?? "";
+ // print_r($data); die;
+
if ($data) {
return $this->respond(['status' => true, 'data' => $data], 200);
} else {
@@ -503,8 +537,72 @@ class LeadsController extends BaseController
$this->policyTransactionStatusModel->insert($statusData);
}
+ public function uploadMultiFiles($files, $docs_names, $primaryKey)
+ {
+ $uploadFilePath = WRITEPATH . 'uploads/lead_files/';
- //--------RFQ-----------------------------------------------------------------------------------------------
+ $multi_file_data = [];
+ foreach ($files as $index => $value) {
+ $file_name = file_Upload($value, $uploadFilePath);
+ $multi_file_data[] = [
+ 'file_name' => $file_name,
+ 'docs_name' => $docs_names[$index],
+ 'id' => $primaryKey[$index] ?? "",
+ ];
+ }
+
+ return $multi_file_data;
+ }
+
+ public function insertMultiFilesData($data, $lead_id)
+ {
+ // print_r($data); die;
+
+ if (!empty($data)) {
+ foreach ($data as $key => $value) {
+
+ if (!empty($value['id'])) {
+
+ $lead_file_data = [
+ 'lead_id' => $lead_id,
+ 'docs_name' => $value['docs_name'],
+ ];
+
+ if (!empty($value['file_name'])) {
+ $lead_file_data['file_name'] = $value['file_name'];
+ }
+
+ $this->leadFilesModel->where('id', $value['id'])->set($lead_file_data)->update();
+ } else {
+
+ $lead_file_data = [
+ 'lead_id' => $lead_id,
+ 'docs_name' => $value['docs_name'],
+ 'file_name' => $value['file_name'],
+ ];
+ $this->leadFilesModel->insert($lead_file_data);
+ }
+
+ if ($key == 0 && !empty($value['file_name'])) {
+ $this->leadsModel->where('id', $lead_id)->set('file_name', $value['file_name'])->update();
+ }
+ }
+ }
+
+ return true;
+ }
+
+ public function removeMultiFile()
+ {
+ $id = $this->request->getGet('lead_file_id');
+ if (!empty($id)) {
+ $this->leadFilesModel->where('id', $id)->set(['is_active' => 0])->update();
+ return $this->respond(['status' => true, 'message' => 'File removed successfully'], 200);
+ } else {
+ return $this->respond(['status' => false, 'message' => 'File could not be removed.'], 200);
+ }
+ }
+ //--------RFQ-----------------------------------------------------------------------------------------------
public function viewRFQ($id, $type = 1)
@@ -549,7 +647,7 @@ class LeadsController extends BaseController
// dd($lead_data);
- if ($lead_data['lead_type'] == 2) {
+ if ($lead_data['lead_type'] != 1) {
$client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $lead_data['source_policy_id'])->first();
$data['policy_terms'] = $client_policy_data['policy_terms'];
}
@@ -558,6 +656,7 @@ class LeadsController extends BaseController
$data['page_name'] = $type == 2 ? 'QCR' : 'RFQ';
$data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
$data['userList'] = $this->userModel->getUserListForRFQ();
+ $data['exclusiveUserList'] = $this->userModel->getexclusiveUserListForRFQ();
$data['lead_data'] = $lead_data;
$mail_content = "
@@ -566,17 +665,34 @@ class LeadsController extends BaseController
Please find attached the {{RFQ_OR_QCR}} for {{POLICY_TYPE}} policy pertaining to {{CLIENT_NAME}}.
Kindly request you to share the competitive quotes at the earliest.
In case of any query, please feel free to contact us.
- Thank You!
+ Thank You!
+ Best regards,
+
+
+ {{LOGGED_USER_NAME}}
+ Email: {{LOGGED_USER_EMAIL}}
+ Mobile: {{LOGGED_USER_MOBILE}}
+
+
+
+
";
+ if ($data['lead_data']['policy_end_date'] != null){
+ $subject = "{{CLIENT_NAME}} _ {{POLICY_TYPE}} _ {{RFQ_OR_QCR}} _ {{POLICY_YEAR}} {{POLICY_END_DATE}}";
+ }else{
+ $subject = "{{CLIENT_NAME}} _ {{POLICY_TYPE}} _ {{RFQ_OR_QCR}} _ {{POLICY_YEAR}}";
- $subject = "{{CLIENT_NAME}} _ {{POLICY_TYPE}} _ {{RFQ_OR_QCR}} _ {{POLICY_YEAR}}";
+ }
$data['mail_content'] = $this->transformMailContent($lead_data, $mail_content, $data['page_name']);
$data['subject'] = $this->transformMailContent($lead_data, $subject, $data['page_name']);
-
+ $data['multi_file_data'] = $this->leadFilesModel->where('lead_id', $id)->where('is_active', 1)->findAll() ?? null;
+ $data['attachment_html'] = view('rfq/attachment_files', $data) ?? "";
+ $data['user_team'] = $this->userModel->select("ut.team_id")->join("user_teams ut","ut.user_id = user_profiles.id and ut.is_active = 1")->where("user_profiles.is_active",1)->first()['team_id'];
// dd($data);
+
if ($data['lead_data']['lead_form_type'] == 1) {
$this->loadLayout('view_rfq.php', $data);
@@ -584,10 +700,20 @@ class LeadsController extends BaseController
$data['occupancy'] = $this->occupancyModel->findAll();
// dd($data['occupancy']);
- $data['policies'] = json_decode($data['question_json'], true)['policies'];
- $data["child_table_data"] = json_decode($data['question_json'], true)['child_table_data'];
+
+ if ($lead_data['lead_type'] != 1 && $data['rfq_count'] == 0) {
+ $client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $lead_data['source_policy_id'])->first();
+ $data['rfq_data']['json'] = $client_policy_data['placement_json'];
+ }
+
+ if (!empty($data['question_json'])) {
+ $data['policies'] = json_decode($data['question_json'], true)['policies'];
+ $data["child_table_data"] = json_decode($data['question_json'], true)['child_table_data'];
+ }
+
// $data['lead_register_data'] = json_decode($data['lead_data']['custom_fields']);
// dd($data['lead_register_data']);
+ // dd($data);
$data['client_type'] = $this->clientType;
$data['buisness_type'] = $this->buisnessType;
$this->loadLayout('view_rfq_non_eb', $data);
@@ -625,57 +751,77 @@ class LeadsController extends BaseController
}
}
-
public function createRFQ()
{
-
- // print_r($this->request->getPost('json')); die();
-
$data = $this->request->getPost();
- $lead_id = $data['lead_id'];
+ $lead_id = $data['lead_id'] ?? null;
+
+ if (!$lead_id) {
+ return $this->respond(['status' => false, 'message' => 'Lead ID is required'], 400);
+ }
+
+ $inputJson = json_decode($data['json'], true);
+ if (isset($inputJson['premium_data']) && !empty($inputJson['premium_data'])) {
+ $sortedJson = $this->reorderProposalsByInsurerTotal($inputJson);
+ $data['json'] = json_encode($sortedJson);
+ }
+
+
$data['type'] = 1;
- $this->RFQModel
- ->where('lead_id', $lead_id)
- ->where('type', 1)
- ->where('is_active', 1)
- ->set('is_active', 0)
- ->update();
- $registrationJson = $data['registration_json'] ?? null; // Use null coalescing operator for safety
+ // Deactivate existing RFQs for this lead and type
+ if (!isset($data['rfq_primaryKey']) && empty($data['rfq_primaryKey'])) {
+ $this->RFQModel
+ ->where('lead_id', $lead_id)
+ ->where('type', 1)
+ ->where('is_active', 1)
+ ->set('is_active', 0)
+ ->update();
+ }
- if ($registrationJson) {
- // If registration_json is provided, insert the data directly
- $result = $this->RFQModel->insert($data);
+ // Handle registration_json
+ if (empty($data['registration_json'])) {
+ // Fetch the latest registration_json if not provided
+ $latest = $this->RFQModel
+ ->select('registration_json')
+ ->where('lead_id', $lead_id)
+ ->orderBy('id', 'DESC')
+ ->first();
+
+ if (!empty($latest['registration_json'])) {
+ $data['registration_json'] = $latest['registration_json'];
+ }
+ }
+
+ // print_r($data); die;
+ // $data['json'] = "";
+ if (isset($data['rfq_primaryKey']) && !empty($data['rfq_primaryKey'])) {
+ $this->RFQModel->update($data['rfq_primaryKey'], $data);
+ $insertId = $data['rfq_primaryKey'];
+ $affectedRows = db_connect()->affectedRows();
} else {
- // If registration_json is not provided, fetch the latest registration_json from the database
- $this->RFQModel->select('registration_json')
- ->where("lead_id", $lead_id)
- ->order_by('id', 'DESC') // Assuming 'id' is an auto-increment field
- ->limit(1);
-
- $query = $this->RFQModel->get();
- $latestRegistrationJson = $query->row()->registration_json ?? null;
-
- if ($latestRegistrationJson) {
- // If a valid registration_json is found, update the data and insert
- $data['registration_json'] = $latestRegistrationJson;
- $result = $this->RFQModel->insert($data);
- } else {
- // If no registration_json is found, insert the data as-is
- $result = $this->RFQModel->insert($data);
- }
+ // Insert new RFQ
+ $insertId = $this->RFQModel->insert($data);
}
- if ($result) {
-
- $message = "RFQ submitted successfully";
- if ($data['submit_type'] == 'QCR') {
- $message = "QCR submitted successfully";
- }
- return $this->respond(['status' => true, 'id' => $result, 'message' => $message, 'data' => $data], 200);
+ if ($insertId) {
+ $message = ($data['submit_type'] ?? '') == 'QCR' ? 'QCR saved successfully' : 'RFQ saved successfully';
+ return $this->respond([
+ 'status' => true,
+ 'id' => $insertId,
+ 'message' => $message,
+ 'data' => $data,
+ 'affectedRows' => $affectedRows ?? null,
+ ], 200);
}
- return $this->respond(['status' => false, 'id' => $result, 'message' => "Failed to create RFQ", 'data' => $data], 200);
+ $message = ($data['submit_type'] ?? '') == 'QCR' ? 'Failed to save QCR' : 'Failed to save RFQ';
+ return $this->respond([
+ 'status' => false,
+ 'id' => null,
+ 'message' => $message,
+ 'data' => $data
+ ], 200);
}
public function createQCR()
@@ -702,6 +848,206 @@ class LeadsController extends BaseController
}
+ private function reorderProposalsByInsurerTotal(array $data): array
+ {
+
+ if (!isset($data['premium_data']['data'])) return $data;
+
+ $original = $data['premium_data']['data'];
+ $proposals = [];
+ $others = [];
+ $emptyKeyData = [];
+
+ foreach ($original as $key => $value) {
+ // Match only keys that look like 'Proposal X'
+ if (preg_match('/^Proposal\s+\d+$/', $key)) {
+ // Get the insurer entry (not 'Quote Asked')
+ foreach ($value as $subKey => $subVal) {
+ if ($subKey !== 'Quote Asked' && isset($subVal['Total'])) {
+ $proposals[$key] = $value;
+ break;
+ }else{
+ $proposals[$key] = $value;
+ }
+ }
+ } else {
+
+ if ($key === '' && isset($value['']) && is_array($value[''])) {
+ // Capture empty key to push it later
+ $emptyKeyData[$key] = $value;
+ } else {
+ $others[$key] = $value;
+ }
+ }
+ }
+
+ // Sort proposals by their insurer's total
+ uasort($proposals, function ($a, $b) {
+ $totalA = 0;
+ $totalB = 0;
+
+ foreach ($a as $key => $val) {
+ if ($key !== 'Quote Asked' && isset($val['Total'])) {
+ $totalA = floatval($val['Total']);
+ break;
+ }
+ }
+
+ foreach ($b as $key => $val) {
+ if ($key !== 'Quote Asked' && isset($val['Total'])) {
+ $totalB = floatval($val['Total']);
+ break;
+ }
+ }
+
+ return $totalA <=> $totalB;
+ });
+
+ // Merge back the sorted proposals into the full structure
+ $data['premium_data']['data'] = array_merge($others, $proposals, $emptyKeyData);
+ $data = $this->reorderProposalDataByPremiumOrder($data);
+ return $data;
+ }
+
+ private function reorderProposalDataByPremiumOrder(array $data): array
+ {
+ if (!isset($data['premium_data']['data'], $data['proposal_data']['over_all_column_data'])) {
+ return $data;
+ }
+
+ $premiumProposals = array_keys($data['premium_data']['data']);
+ $filteredProposals = [];
+
+ // Collect proposal keys that match the pattern "Proposal X"
+ foreach ($premiumProposals as $key) {
+ if (preg_match('/^Proposal\s+\d+$/', $key) && isset($data['proposal_data']['over_all_column_data'][$key])) {
+ $filteredProposals[$key] = $data['proposal_data']['over_all_column_data'][$key];
+ }
+ }
+
+ // dd($premiumProposals, $filteredProposals);
+
+ $data['proposal_data']['over_all_column_data'] = $filteredProposals;
+ $data = $this->reorderProposalInHeaderAndData($data);
+ return $data;
+ }
+
+ private function reorderProposalInHeaderAndData(array $data): array
+ {
+ $tableData = $data['table_data'];
+ $sortedProposalOrder = $data['proposal_data']['over_all_column_data'];
+ $headers = $tableData['headers'] ?? [];
+ $dataRows = $tableData['data'] ?? [];
+
+ // Step 1: Separate static and proposal headers
+ $staticHeaders = [];
+ $proposalHeaders = [];
+ $actionHeader = [];
+ foreach ($headers as $header) {
+ if (in_array($header['parentHeader'], array_keys($sortedProposalOrder))) {
+ $proposalHeaders[$header['parentHeader']] = $header;
+ } else {
+ if ($header['parentHeader'] == "Action") {
+ $actionHeader[] = $header;
+ } else {
+ $staticHeaders[] = $header;
+ }
+ }
+ }
+
+ // dd($staticHeaders, $proposalHeaders, $sortedProposalOrder);
+
+ // Step 2: Reorder headers
+ $reorderedHeaders = [];
+ foreach ($sortedProposalOrder as $proposalKey => $proposalValue) {
+ if (isset($proposalHeaders[$proposalKey])) {
+ $reorderedHeaders[] = $proposalHeaders[$proposalKey];
+ }
+ }
+
+ // print_rr($reorderedHeaders); die;
+ foreach ($reorderedHeaders as $key => &$value) {
+ $value['parentHeader'] = 'Proposal ' . ($key + 1);
+ }
+ unset($value);
+
+
+ $reorderedHeaders = array_merge($staticHeaders, $reorderedHeaders, $actionHeader);
+
+
+ // Step 3: Reorder each row's `data` by matching parentth
+ foreach ($dataRows as $dataRowIndex => &$row) {
+ $staticData = [];
+ $proposalData = [];
+ $actionData = [];
+
+ foreach ($row['data'] as $entry) {
+ if (in_array($entry['parentth'], array_keys($sortedProposalOrder))) {
+ $proposalData[$entry['parentth']][] = $entry;
+ } else {
+ if ($entry['parentth'] == "Action") {
+ $actionData[] = $entry;
+ } else {
+ $staticData[] = $entry;
+ }
+ }
+ }
+
+ $reorderedProposalData = [];
+ foreach ($sortedProposalOrder as $proposalKey => $proposalValue) {
+ if (isset($proposalData[$proposalKey])) {
+ foreach ($proposalData[$proposalKey] as $entry) {
+ $reorderedProposalData[] = $entry;
+ }
+ }
+ }
+
+ $dubParTh = "";
+ $increament = 0;
+ foreach ($reorderedProposalData as $key => &$value) {
+
+ if ($dubParTh == $value['parentth']) {
+ $value['parentth'] = 'Proposal ' . ($increament);
+ } else {
+ $dubParTh = $value['parentth'];
+ $increament = $increament + 1;
+ $value['parentth'] = 'Proposal ' . ($increament);
+ }
+ }
+ unset($value);
+
+ $row['data'] = array_merge($staticData, $reorderedProposalData, $actionData);
+ }
+
+ $data['table_data']['headers'] = $reorderedHeaders;
+ $data['table_data']['data'] = $dataRows;
+
+ $renumberedArray = $this->renumberProposalKeys($data['proposal_data']['over_all_column_data']);
+ $updatedDataSet = $this->renumberProposalKeys($data['premium_data']['data']);
+ $data['proposal_data']['over_all_column_data'] = !empty($renumberedArray) ? $renumberedArray : $data['proposal_data']['over_all_column_data'];
+ $data['premium_data']['data'] = !empty($updatedDataSet) ? $updatedDataSet : $data['premium_data']['data'];
+
+ return $data;
+ }
+
+ private function renumberProposalKeys(array $input): array
+ {
+ $result = [];
+ $counter = 1;
+
+ foreach ($input as $key => $value) {
+ if (strpos($key, 'Proposal') === 0) {
+ $newKey = 'Proposal ' . $counter++;
+ $result[$newKey] = $value;
+ } else {
+ $result[$key] = $value;
+ }
+ }
+
+ return $result;
+ }
+
+
//-----RFQ and QCR EXPORT------------------------------------------------------------------------------------------------
@@ -777,7 +1123,7 @@ class LeadsController extends BaseController
if ($rfq_data['policy_type_id'] == 2) {
$lead_data = [
-
+ 'policy_end_date' => $rfq_data['policy_end_date'],
'Insured' => $rfq_data['client_name'],
'Policy Status' => $rfq_data['status'],
@@ -790,6 +1136,7 @@ class LeadsController extends BaseController
];
} else if ($rfq_data['policy_type_id'] == 1) {
$lead_data = [
+ 'policy_end_date' => $rfq_data['policy_end_date'],
'Insured' => $rfq_data['client_name'],
'No of Employees at Inception' => $rfq_data['incept_emp_count'],
'Total Sum Insured at Inception ' => $rfq_data['total_si_at_incept'],
@@ -802,6 +1149,7 @@ class LeadsController extends BaseController
} else {
if ($rfq_data['policy_type_id'] == 2) {
$lead_data = [
+ 'policy_end_date' => $rfq_data['policy_end_date'],
'Insured' => $rfq_data['client_name'],
'Policy Status' => $rfq_data['status'],
@@ -830,6 +1178,7 @@ class LeadsController extends BaseController
];
} else if ($rfq_data['policy_type_id'] == 1) {
$lead_data = [
+ 'policy_end_date' => $rfq_data['policy_end_date'],
'Insured' => $rfq_data['client_name'],
'No of Employees at Renewal' => $rfq_data['renewal_emp_count'],
'Total Sum Insured at Renewal ' => $rfq_data['total_si_at_renewal'],
@@ -854,6 +1203,7 @@ class LeadsController extends BaseController
$data = $this->convertJsonForQCR($data, $type);
// dd($data);
}
+ // dd($data);
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
@@ -862,7 +1212,7 @@ class LeadsController extends BaseController
// Start with lead_data at the top
$rowNumber = 1;
- $mergeRange1 = "A{$rowNumber}:C{$rowNumber}";
+ $mergeRange1 = "A{$rowNumber}:B{$rowNumber}";
$sheet->mergeCells($mergeRange1);
$sheet->setCellValue("A{$rowNumber}", "Nhance India Insurance Broking Pvt Ltd");
$sheet->getStyle("A{$rowNumber}")->applyFromArray([
@@ -877,13 +1227,13 @@ class LeadsController extends BaseController
]);
// Set column width to fit the image properly
- $sheet->getColumnDimension('D')->setWidth(20); // Adjust as needed
+ $sheet->getColumnDimension('C')->setWidth(20); // Adjust as needed
$sheet->getRowDimension($rowNumber)->setRowHeight(40); // Adjust as needed
$drawing = new Drawing();
$path = ROOTPATH . "public/assets/images/Nhance-Logo-Final.png"; // Use FCPATH for server path
$drawing->setPath($path);
- $drawing->setCoordinates("D{$rowNumber}"); // Set position in column B
+ $drawing->setCoordinates("C{$rowNumber}"); // Set position in column B
$drawing->setHeight(35); // Adjust image height
// Center align the image in the cell
@@ -893,8 +1243,8 @@ class LeadsController extends BaseController
$drawing->setWorksheet($sheet);
// Apply center alignment to the cell
- $sheet->getStyle("D{$rowNumber}")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
- $sheet->getStyle("D{$rowNumber}")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
+ $sheet->getStyle("C{$rowNumber}")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
+ $sheet->getStyle("C{$rowNumber}")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
$rowNumber = $rowNumber + 1;
@@ -907,7 +1257,7 @@ class LeadsController extends BaseController
// Merge A:B for key and C:D for value
$mergeRangeKey = "A{$rowNumber}:B{$rowNumber}";
- $mergeRangeValue = "C{$rowNumber}:D{$rowNumber}";
+ $mergeRangeValue = "C{$rowNumber}";
$sheet->mergeCells($mergeRangeKey);
$sheet->mergeCells($mergeRangeValue);
@@ -940,9 +1290,9 @@ class LeadsController extends BaseController
// Set column width based on max content length (adjusted for padding)
$sheet->getColumnDimension('A')->setWidth($maxWidthA * 1.2);
- $sheet->getColumnDimension('B')->setWidth($maxWidthA * 1.2);
+ $sheet->getColumnDimension('B')->setWidth($maxWidthA * 5);
$sheet->getColumnDimension('C')->setWidth($maxWidthB * 1.2);
- $sheet->getColumnDimension('D')->setWidth($maxWidthB * 1.2);
+ // $sheet->getColumnDimension('D')->setWidth($maxWidthB * 1.2);
// $rowNumber += 2;
@@ -1001,7 +1351,7 @@ class LeadsController extends BaseController
}
if ($header['parentHeader'] === 'Particulars') {
- $sheet->getColumnDimension('B')->setWidth(40);
+ $sheet->getColumnDimension('B')->setWidth(80);
}
$startColumn = $columnLetter; // Start of the current header range
@@ -1019,7 +1369,7 @@ class LeadsController extends BaseController
// Merge header cells if it spans multiple subheaders
if ($subHeaderCount > 1) {
- $endColumn = chr(ord($startColumn) + $subHeaderCount - 1); // Calculate the end column
+ $endColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($startColumn) + $subHeaderCount - 1);
$sheet->mergeCells("{$startColumn}{$rowNumber}:{$endColumn}{$rowNumber}");
} else {
$endColumn = $startColumn; // No merge needed if only one subheader
@@ -1047,7 +1397,8 @@ class LeadsController extends BaseController
}
// Apply border to the header range
- $headerRange = "A{$rowNumber}:" . chr(ord($columnLetter) - 1) . "{$subHeaderRow}";
+ $prevColumn1 = $this->getPreviousColumn($columnLetter);
+ $headerRange = "A{$rowNumber}:" . "{$prevColumn1}" . "{$subHeaderRow}";
$sheet->getStyle($headerRange)->applyFromArray([
'borders' => [
'allBorders' => [
@@ -1086,7 +1437,8 @@ class LeadsController extends BaseController
$serial_no++;
}
- $dataRange = "A" . ($subHeaderRow + 1) . ":" . chr(ord($columnLetter) - 1) . ($rowNumber - 1);
+ $prevColumn2 = $this->getPreviousColumn($columnLetter);
+ $dataRange = "A" . ($subHeaderRow + 1) . ":" . "{$prevColumn2}" . ($rowNumber - 1);
$sheet->getStyle($dataRange)->applyFromArray([
'borders' => [
'allBorders' => [
@@ -1133,7 +1485,8 @@ class LeadsController extends BaseController
$rowNumber++;
}
- $premiumRange = "B" . ($rowNumber - 4) . ":" . chr(ord($columnLetter) - 2) . ($rowNumber - 1);
+ $prevColumn3 = $this->getPreviousColumn($columnLetter, 2);
+ $premiumRange = "B" . ($rowNumber - 4) . ":" . "{$prevColumn3}" . ($rowNumber - 1);
// dd($premiumRange);
$sheet->getStyle($premiumRange)->applyFromArray([
'borders' => [
@@ -1182,7 +1535,7 @@ class LeadsController extends BaseController
}
$lastRow = count($lead_data) + 1;
- $leadRange = "A1:D{$lastRow}";
+ $leadRange = "A1:C{$lastRow}";
$sheet->getStyle($leadRange)->applyFromArray([
'borders' => [
@@ -1193,9 +1546,25 @@ class LeadsController extends BaseController
],
]);
+
+
// Set filename
$string = ($type == 2) ? 'QCR' : 'RFQ';
- $filename = "{$string}_{$rfq_data['client_short_name']}_{$rfq_data['policy_type']}_" . date('YmdHis') . '.xlsx';
+ $current_year = date('Y');
+ $next_year = $current_year + 1;
+ $policy_year = "$current_year-$next_year";
+
+ if (!empty($rfq_data['policy_end_date'])){
+ $policy_expiry = strtotime($lead_data['policy_end_date']);
+
+ $formatted_policy = date("d-m-Y",$policy_expiry);
+
+ $filename = "{$rfq_data['client_name']}_{$rfq_data['policy_type']}_{$string}_" .$policy_year.'(Due On '.$formatted_policy . ')' .'.xlsx';
+
+ }else{
+ $filename = "{$rfq_data['client_name']}_{$rfq_data['policy_type']}_{$string}_".$policy_year.'_' . '.xlsx';
+ }
+
// Save to temporary location
$uploadFilePath = WRITEPATH . 'tmp/' . $filename;
@@ -1675,6 +2044,7 @@ class LeadsController extends BaseController
$propsal_and_insurer = isset($params['proposal_insurer']) ? $params['proposal_insurer'] : null;
$mail_content = $params['mail_content'];
$mail_subject = $params['subject'];
+ $attachment_file_ids = $params['selected_attachment_files'];
$result_data = [];
// dd($recipient_mail);
@@ -1783,7 +2153,7 @@ class LeadsController extends BaseController
['file_path' => $temp_file_path, 'sheets' => []],
['file_path' => $lead_file_path, 'sheets' => []]
];
- $outputPath = dirname($temp_file_path) . '/' . 'merged_' . $temp_file_name;
+ $outputPath = dirname($temp_file_path) . '/' . $temp_file_name;
$result = ExcelMergeHelper::mergeExcelFiles($filePaths, $outputPath);
// print_rr($result);
}
@@ -1799,7 +2169,12 @@ class LeadsController extends BaseController
$file_path = $result;
$file_name = basename($result);
+
+ // Attacments part
$attachments = [['fileName' => $file_name, 'filePath' => $file_path]];
+ $other_attachments = $this->handleMultiFileAttachments($attachment_file_ids, $lead_id);
+ $attachments = array_merge($attachments, $other_attachments);
+ // print_r($attachments); die;
//get recipient address
if ($recipient_type == 'insurer' || $recipient_type == 'placement') {
@@ -1814,13 +2189,20 @@ class LeadsController extends BaseController
// print_r($recipient_data); die;
} else if ($recipient_type == 'client') {
- $recipient_data = [['name' => $lead_data['contact_person_name'], 'email' => $lead_data['contact_person_email']]];
+
+ $mailIDS = explode(',',$params['contact_mail']);
+ $recipient_data = [];
+ foreach ($mailIDS as $mail){
+ $recipient_data[] = ['name' => $lead_data['contact_person_name'], 'email' => $mail];
+ }
+
} else {
$recipient_data = [['name' => "Team", 'email' => $params['to']]];
}
// print_r($recipient_data); die;
$subject = $file_type == 'rfq' ? 'Request for Quotation from ' . $lead_data['client_name'] . ' for ' . $lead_data['policy_type'] : 'Quotation Comparison Report for ' . $lead_data['policy_type'];
+
$original_message = 'Request for Quotation (RFQ)
Dear {{RECIPIENT_NAME}},
We are reaching out to request a quotation for the following insurance coverage. Please review the details below and provide your quote at your earliest convenience.
RFQ Details
Client name {{CLIENT_NAME}} Coverage Type {{POLICY_LONG_NAME}} Policy Start Date {{POLICY_START_DATE}} Policy Duration {{DURATION}}
Please note: Additional terms and details are included in the attachment for your reference.Please feel free to reach out if you require any further information to prepare the quote. We look forward to receiving your proposal.
Best regards,
Nhance India Pvt Ltd
© Nhance India Pvt Ltd. All rights reserved.
';
//for mail content
@@ -1869,7 +2251,9 @@ class LeadsController extends BaseController
'proposel_data' => json_encode($lead_update_data),
'status' => 'won',
'placement_date' => change_date_format($params['placement_date'], 'd/m/Y', 'Y-m-d'),
+ 'payment_date' => change_date_format($params['payment_date'], 'd/m/Y', 'Y-m-d'),
'utr_no' => $params['utr_no'],
+ 'is_cd' => $params['is_cd'],
'premium_amount' => $params['premium_amount'],
'total_amount' => $params['total_amount'],
'cd_amount' => $params['cd_amount'],
@@ -2268,8 +2652,6 @@ class LeadsController extends BaseController
'policy_status' => 1,
];
- $terms = $this->preparePolicyTermsFromRFQ($data);
-
$policy_type_id = $data['policy_type_id'];
if (in_array($policy_type_id, [1, 2, 6, 7])) {
$client_policy_data['is_addon'] = 1; // Base Policy
@@ -2283,8 +2665,16 @@ class LeadsController extends BaseController
// }
}
- $client_policy_data['policy_terms'] = $this->preparePolicyTermsFromRFQ($data);
+ if ($data['lead_form_type'] == 1) {
+ $client_policy_data['policy_terms'] = $this->preparePolicyTermsFromRFQ($data);
+ } else {
+ $placementJson = $this->getPlacementJson($data);
+ if ($placementJson) {
+ $client_policy_data['placement_json'] = $placementJson;
+ $client_policy_data['policy_terms'] = $this->convertNonEbQCRJsonToPolicyTerms(json_decode($placementJson, true));
+ }
+ }
// print_r($client_policy_data); die;
return $client_policy_data;
@@ -2294,7 +2684,7 @@ class LeadsController extends BaseController
{
$proposel_data = json_decode($data['proposel_data'], true);
- $QCRData = $this->RFQModel->where('is_active', 1)->where('type', 2)->where('lead_id', $data['id'])->first();
+ $QCRData = $this->RFQModel->where('is_active', 1)->where('lead_id', $data['id'])->first();
$JSON = json_decode($QCRData['json'], true);
@@ -2381,6 +2771,52 @@ class LeadsController extends BaseController
return json_encode($terms_array);
}
+ public function convertNonEbQCRJsonToPolicyTerms($allTableData)
+ {
+
+ if (!empty($allTableData)) {
+
+ array_pop($allTableData); // Remove the last item from the array
+ $terms_array = [];
+
+ foreach ($allTableData as $TableIndex => $tableGroup) {
+
+ if ($TableIndex == 0) {
+ continue;
+ }
+
+ foreach ($tableGroup['table_data']['data'] as $dataRow) {
+ $item = $dataRow['items'] ?? '';
+
+ foreach ($dataRow['data'] as $cellData) {
+ $parentth = $cellData['parentth'] ?? '';
+ $subth = $cellData['subth'] ?? '';
+ $value = $cellData['display_content'] ?? '';
+
+ // Skip unwanted keys
+ if (in_array($parentth, ['SNO', 'Particulars', 'Action']) || $subth === 'Quote Asked') {
+ continue;
+ }
+
+ // Skip if item matches parentth
+ if ($item === $parentth) {
+ continue;
+ }
+
+ // Set the value directly, overwriting with latest encountered
+ if (!empty($item) && !empty($value)) {
+ $terms_array[$item] = $value;
+ }
+ }
+ }
+ }
+
+ return json_encode($terms_array);
+ } else {
+ return null;
+ }
+ }
+
public function featchClientPolicyFromLead($client_id, $branch_id, $lead_id)
{
$data = $this->leadsModel->where('leads.id', $lead_id)->where('leads.is_active', 1)->first();
@@ -2401,6 +2837,60 @@ class LeadsController extends BaseController
return $this->respond(['status' => false, 'message' => 'Failed to create policy', 'data' => $data], 200);
}
+ public function getPlacementJson(array $data): ?string
+ {
+ $proposel_data = json_decode($data['proposel_data'], true);
+
+ $QCRData = $this->RFQModel
+ ->where('is_active', 1)
+ ->where('lead_id', $data['id'])
+ ->first();
+
+ if (!$QCRData || empty($QCRData['json'])) {
+ return null;
+ }
+
+ $jsonArray = json_decode($QCRData['json'], true);
+ $proposalData = array_pop($jsonArray); // Get last item and remove it from the array
+
+ if (empty($jsonArray)) {
+ return null;
+ }
+
+ $placement_json_data = array_map(function ($jsonData) use ($proposel_data) {
+ return $this->transformNonEbProposelData(
+ $jsonData,
+ $proposel_data['proposel_name'] ?? '',
+ $proposel_data['insurer_name'] ?? '',
+ null,
+ 1
+ );
+ }, $jsonArray);
+
+ if (!empty($proposalData)) {
+ foreach ($proposalData['proposal_data']['over_all_column_data'] as $key => &$proposal) {
+ // Keep only the required proposal
+ if ($key !== $proposel_data['proposel_name']) {
+ unset($proposalData['proposal_data']['over_all_column_data'][$key]);
+ } else {
+ // Within the matched proposal, filter insurers
+ if (!empty($proposal['insurers'])) {
+ $proposal['insurers'] = array_values(array_filter($proposal['insurers'], function ($insurer) use ($proposel_data) {
+ return $insurer['display_name'] === $proposel_data['insurer_name'];
+ }));
+ }
+ }
+ }
+ unset($proposal); // Good practice after foreach by reference
+ }
+
+
+ $placement_json_data[] = $proposalData;
+
+ return json_encode($placement_json_data);
+ }
+
+
//------------------------------------------------------------------------------------------------
@@ -2410,6 +2900,13 @@ class LeadsController extends BaseController
$next_year = $current_year + 1;
$policy_year = "$current_year-$next_year";
+ $policy_expiry = strtotime($lead_data['policy_end_date']);
+
+ $formatted_policy = date("d-m-Y",$policy_expiry);
+ $logged_user_id = get_session_userid();
+
+ $logged_user_data = $this->userModel->where("id",$logged_user_id)->where("is_active",1)->first();
+
if ($lead_data) {
// Replacing placeholders with actual values
@@ -2419,6 +2916,11 @@ class LeadsController extends BaseController
$message = str_replace("{{POLICY_TYPE}}", $lead_data['policy_type'] ?? "Insurance Policy", $message);
$message = str_replace("{{RFQ_OR_QCR}}", $page_name, $message);
$message = str_replace("{{POLICY_YEAR}}", $policy_year, $message);
+ $message = str_replace("{{POLICY_END_DATE}}"," (Due On ".$formatted_policy.")",$message);
+
+ $message = str_replace("{{LOGGED_USER_NAME}}",ucfirst($logged_user_data['first_name'])." ".ucfirst($logged_user_data['last_name']),$message);
+ $message = str_replace("{{LOGGED_USER_EMAIL}}",$logged_user_data['email'],$message);
+ $message = str_replace("{{LOGGED_USER_MOBILE}}",$logged_user_data['mobile'],$message);
return $message;
} else {
@@ -2426,6 +2928,7 @@ class LeadsController extends BaseController
}
}
+
function getLastFiveFinancialYears()
{
$currentYear = date('Y');
@@ -2455,6 +2958,7 @@ class LeadsController extends BaseController
$this->loadLayout('view_rfq_non_eb');
}
+ // get lead data for edit bot EB and NON-EB
public function getLeadNonEB($type, $id = null)
{
// Set basic data
@@ -2482,9 +2986,15 @@ class LeadsController extends BaseController
->where('user_profiles.is_active', 1)
->findAll();
+
+
if (!empty($id)) {
+
$data['lead_edit_data'] = $this->leadsModel->where('id', $id)->first() ?? [];
+ $data['lead_edit_data']['multi_file_data'] = $this->leadFilesModel->where('lead_id', $id)->where('is_active', 1)->findAll() ?? null;
+ $data['lead_edit_data']['lead_file_count'] = count($data['lead_edit_data']['multi_file_data']);
+
// Decode and merge custom fields if present
$custom_fields_data = !empty($data['lead_edit_data']['custom_fields'])
? json_decode($data['lead_edit_data']['custom_fields'], true)
@@ -2495,7 +3005,7 @@ class LeadsController extends BaseController
}
if (!empty($data['lead_edit_data'])) {
- foreach (['policy_start_date', 'policy_end_date', 'incurred_claims_date', 'premium_date'] as $dateField) {
+ foreach (['policy_start_date', 'policy_end_date', 'source_policy_start_date', 'source_policy_end_date', 'incurred_claims_date'] as $dateField) {
$data['lead_edit_data'][$dateField] = !empty($data['lead_edit_data'][$dateField])
? change_date_format($data['lead_edit_data'][$dateField], 'Y-m-d', 'd/m/Y')
: null;
@@ -2509,6 +3019,9 @@ class LeadsController extends BaseController
$data['lead_edit_data']['policy_type_id'] ?? null,
$data
) ?? "";
+
+ $html = view('rfq/multi_files', $data);
+ $data['lead_edit_data']['multi_file_html'] = trim($html) !== '' ? $html : null;
}
if ($data['lead_edit_data']['lead_type'] != 1 && $data['lead_edit_data']['lead_form_type'] == 2) {
@@ -2575,15 +3088,19 @@ class LeadsController extends BaseController
public function constructNonEbExcelToSaveTemp($lead_id, $type, $propsal_and_insurer = null)
{
-
$rfq_data = $this->RFQModel->getRFQTableDataWithLeadIDAndType($lead_id, $type);
-
$lead_data = json_decode($rfq_data['custom_fields'], true) ?? [];
if (!is_array($lead_data)) {
$lead_data = [];
}
$lead_data = array_merge(['Insured' => $rfq_data['client_name']], $lead_data);
+ $policy_registration_data = [];
+ if (isset($rfq_data['registration_json']) && !empty($rfq_data['registration_json'])) {
+ $policy_registration_data = json_decode($rfq_data['registration_json'], true);
+ }
+ // dd($policy_registration_data);
+
// if(!empty($rfq_data['fin_years_claims'])){
// $claim_details = json_decode($rfq_data['fin_years_claims'], true) ?? [];
// if(!empty($claim_details['finyear'])){
@@ -2645,6 +3162,7 @@ class LeadsController extends BaseController
// Initialize max width tracking variables
$maxWidthB = 0;
+ //Lead Data
foreach ($lead_data as $key => $value) {
$formattedKey = ucwords(str_replace('_', ' ', $key));
@@ -2685,9 +3203,113 @@ class LeadsController extends BaseController
$sheet->getColumnDimension('C')->setWidth($maxWidthB * 1.2);
$rowNumber += 2;
+ //Policy Registration
+ if (!empty($policy_registration_data)) {
+ foreach ($policy_registration_data as $key => $value) {
- // Kint::dump($jsonData);
+ $startRow = $rowNumber; // Track where the block starts
+ // Title Row
+ $titleMergeRangeKey = "A{$rowNumber}:C{$rowNumber}";
+ $sheet->mergeCells($titleMergeRangeKey);
+ $sheet->setCellValue("A{$rowNumber}", ucfirst($key) . " Policy Details");
+
+ // Title Style
+ $sheet->getStyle($titleMergeRangeKey)->applyFromArray([
+ 'font' => ['bold' => true],
+ 'alignment' => [
+ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ ],
+ 'fill' => [
+ 'fillType' => Fill::FILL_SOLID,
+ 'startColor' => ['rgb' => 'ADD8E6'],
+ ],
+ ]);
+
+ $rowNumber++; // Move to next row
+
+ // Policy Type
+ if (isset($value['policyType'])) {
+ $sheet->mergeCells("A{$rowNumber}:B{$rowNumber}");
+ $sheet->setCellValue("A{$rowNumber}", "Policy Type");
+ $sheet->setCellValue("C{$rowNumber}", $value['policyType']);
+
+ $sheet->getStyle("A{$rowNumber}:C{$rowNumber}")->applyFromArray([
+ 'font' => ['bold' => true],
+ 'alignment' => [
+ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ ],
+ ]);
+
+ $rowNumber++;
+ } else {
+ $sheet->mergeCells("A{$rowNumber}:B{$rowNumber}");
+ $sheet->setCellValue("A{$rowNumber}", "Policy Type");
+ $sheet->setCellValue("C{$rowNumber}", ucfirst($key) . " Policy");
+
+ $sheet->getStyle("A{$rowNumber}:C{$rowNumber}")->applyFromArray([
+ 'font' => ['bold' => true],
+ 'alignment' => [
+ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ ],
+ ]);
+
+ $rowNumber++;
+ }
+
+ // Type of Business & Nature of Business
+ if (isset($value['productSelection']) && !empty($value['productSelection'])) {
+ // Type of Business
+ $sheet->mergeCells("A{$rowNumber}:B{$rowNumber}");
+ $sheet->setCellValue("A{$rowNumber}", "Type of Business");
+ $sheet->setCellValue("C{$rowNumber}", $this->buisnessType[$value['productSelection']['type_of_buisness']] ?? '');
+
+ $sheet->getStyle("A{$rowNumber}")->applyFromArray([
+ 'font' => ['bold' => true],
+ 'alignment' => [
+ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ ],
+ ]);
+
+ $rowNumber++;
+
+ // Nature of Business
+ $sheet->mergeCells("A{$rowNumber}:B{$rowNumber}");
+ $sheet->setCellValue("A{$rowNumber}", "Nature of Business");
+ $sheet->setCellValue("C{$rowNumber}", $value['productSelection']['buisness_nature'] ?? '');
+
+ $sheet->getStyle("A{$rowNumber}")->applyFromArray([
+ 'font' => ['bold' => true],
+ 'alignment' => [
+ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ ],
+ ]);
+
+ $rowNumber++;
+ }
+
+ $endRow = $rowNumber - 1; // Block ends at previous row
+
+ // Apply border to the whole block
+ $sheet->getStyle("A{$startRow}:C{$endRow}")->applyFromArray([
+ 'borders' => [
+ 'allBorders' => [
+ 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
+ 'color' => ['argb' => '000000'],
+ ],
+ ],
+ ]);
+
+ $rowNumber += 2; // Add space before the next block
+ }
+ }
+
+ //Table Data
foreach ($jsonData as $key => $data) {
// Kint::dump($data, 'First');
@@ -2761,7 +3383,7 @@ class LeadsController extends BaseController
// Merge header cells if it spans multiple subheaders
if ($subHeaderCount > 1) {
- $endColumn = chr(ord($startColumn) + $subHeaderCount - 1); // Calculate the end column
+ $endColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($startColumn) + $subHeaderCount - 1);
$sheet->mergeCells("{$startColumn}{$rowNumber}:{$endColumn}{$rowNumber}");
} else {
$endColumn = $startColumn; // No merge needed if only one subheader
@@ -2789,7 +3411,8 @@ class LeadsController extends BaseController
}
// Apply border to the header range
- $headerRange = "A{$rowNumber}:" . chr(ord($columnLetter) - 1) . "{$subHeaderRow}";
+ $prevColumn4 = $this->getPreviousColumn($columnLetter);
+ $headerRange = "A{$rowNumber}:" . "{$prevColumn4}" . "{$subHeaderRow}";
$sheet->getStyle($headerRange)->applyFromArray([
'borders' => [
'allBorders' => [
@@ -2805,13 +3428,17 @@ class LeadsController extends BaseController
$rowNumber = $subHeaderRow + 2;
$column_data = $data['table_data']['data'];
+ // dd($column_data);
$serial_no = 1;
$maxColumnWidths = [];
+ $RowSpanEnable = false;
// Add table data rows
foreach ($column_data as $dataRow) {
$columnLetter = 'A';
+ $hasPolicy = in_array('Policy', array_column($dataRow['data'], 'parentth'));
+ // Kint::dump($hasPolicy);
foreach ($dataRow['data'] as $cellData) {
@@ -2830,16 +3457,30 @@ class LeadsController extends BaseController
$sheet->getStyle("{$columnLetter}{$mergeStart}:{$columnLetter}{$mergeEnd}")
->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
} else {
- $sheet->setCellValue("{$columnLetter}{$rowNumber}", $cellData['display_content']);
+ if (!$hasPolicy && $key == 0) {
+ $RowSpanEnable = true;
+ $columnLetter++;
+ $sheet->setCellValue("{$columnLetter}{$rowNumber}", $cellData['display_content']);
+ } else {
+ $sheet->setCellValue("{$columnLetter}{$rowNumber}", $cellData['display_content']);
+ }
}
- $columnLetter++;
+ if (!($key === 0 && !$hasPolicy)) {
+ $columnLetter++;
+ }
}
$rowNumber++;
$serial_no++;
}
- $dataRange = "A" . ($subHeaderRow + 1) . ":" . chr(ord($columnLetter) - 1) . ($rowNumber - 1);
+ if ($key == 0 && $RowSpanEnable == true) {
+ $columnLetter++;
+ }
+
+ // dd($columnLetter);
+ $prevColumn5 = $this->getPreviousColumn($columnLetter);
+ $dataRange = "A" . ($subHeaderRow + 1) . ":" . "{$prevColumn5}" . ($rowNumber - 1);
$sheet->getStyle($dataRange)->applyFromArray([
'borders' => [
'allBorders' => [
@@ -2984,8 +3625,12 @@ class LeadsController extends BaseController
}
// Row-wise Check: Remove rows if qcr == 0 for actions
+ $groupedRows = [];
foreach ($first_json['table_data']['data'] as $rowKey => $rowData) {
- foreach ($rowData['data'] as $data) {
+
+ $groupedRows[$rowData['row_id']][] = $rowData;
+
+ foreach ($rowData['data'] as $keyIndex => $data) {
if ($indexOfTheTable == 0) {
@@ -3006,6 +3651,42 @@ class LeadsController extends BaseController
}
}
+ $finalRows = [];
+
+ if (!empty($groupedRows)) {
+
+ // Loop through each row_id group and check for Policy status
+ foreach ($groupedRows as $rowId => $rows) {
+ $hasPolicy = false;
+ $isChecked = false;
+
+ foreach ($rows as $row) {
+ foreach ($row['data'] as $cell) {
+ if ($cell['parentth'] === 'Policy') {
+ $hasPolicy = true;
+ if (trim(strtolower($cell['input_value'])) === 'checked') {
+ $isChecked = true;
+ }
+ break 2; // Found Policy, no need to continue further
+ }
+ }
+ }
+
+ // Step 3: If parent Policy is "Checked", retain the entire group
+ if (!$hasPolicy || $isChecked) {
+ foreach ($rows as $r) {
+ $finalRows[] = $r;
+ }
+ }
+ }
+
+ if (!empty($finalRows)) {
+ // Update the original data
+ $first_json['table_data']['data'] = array_values($finalRows);
+ }
+ }
+
+
// Reindex arrays to maintain proper structure
$first_json['table_data']['headers'] = array_values($first_json['table_data']['headers']);
$first_json['table_data']['data'] = array_values($first_json['table_data']['data']);
@@ -3026,6 +3707,7 @@ class LeadsController extends BaseController
}
//Remove insurer Row wise data for RFQ
+ $groupedRows = [];
foreach ($first_json['table_data']['data'] as &$row) {
// Filter the inner data array
@@ -3037,11 +3719,48 @@ class LeadsController extends BaseController
);
$row['data'] = array_values($row['data']);
- }
+ $groupedRows[$row['row_id']][] = $row;
+ }
// Ensure to unset the reference after the loop
unset($row);
+
+ $finalRows = [];
+
+ if (!empty($groupedRows)) {
+
+ // Loop through each row_id group and check for Policy status
+ foreach ($groupedRows as $rowId => $rows) {
+ $hasPolicy = false;
+ $isChecked = false;
+
+ foreach ($rows as $row) {
+ foreach ($row['data'] as $cell) {
+ if ($cell['parentth'] === 'Policy') {
+ $hasPolicy = true;
+ if (trim(strtolower($cell['input_value'])) === 'checked') {
+ $isChecked = true;
+ }
+ break 2; // Found Policy, no need to continue further
+ }
+ }
+ }
+
+ // Step 3: If parent Policy is "Checked", retain the entire group
+ if (!$hasPolicy || $isChecked) {
+ foreach ($rows as $r) {
+ $finalRows[] = $r;
+ }
+ }
+ }
+
+ if (!empty($finalRows)) {
+ // Update the original data
+ $first_json['table_data']['data'] = array_values($finalRows);
+ }
+ }
+
// Remove insurers from Proposal Data key for RFQ
foreach ($proposeldata['proposal_data']['over_all_column_data'] as $key => &$proposal) {
if (isset($proposal['insurers'])) {
@@ -3053,12 +3772,12 @@ class LeadsController extends BaseController
// Ensure to reset the reference
unset($proposal);
}
- return $first_json;
+ return $first_json;
return null;
}
- public function transformNonEbProposelData(&$data, $proposal, $insurer, $tableCount)
+ public function transformNonEbProposelData(&$data, $proposal, $insurer, $tableCount = null, $actionColumn = null)
{
// Kint::dump($data, $proposal, $insurer, $tableCount);
@@ -3095,6 +3814,13 @@ class LeadsController extends BaseController
// Update the original data's headers
$data['table_data']['headers'] = $headerData;
+ if (!empty($actionColumn)) {
+ $data['table_data']['headers'][] = [
+ 'parentHeader' => "Action",
+ 'subHeaders' => ['-']
+ ];
+ }
+
foreach ($data['table_data']['data'] as &$entry) {
$sno = $entry['SNO'];
@@ -3119,6 +3845,12 @@ class LeadsController extends BaseController
if ($item['parentth'] === $proposal && $item['subth'] === $insurer) {
$filteredData[] = $item;
}
+
+ if (!empty($actionColumn)) {
+ if ($item['parentth'] === "Action") {
+ $filteredData[] = $item;
+ }
+ }
}
// Update the entry with filtered data
@@ -3132,5 +3864,34 @@ class LeadsController extends BaseController
// kint::dump($data);
return $data;
}
-
+
+ public function getPreviousColumn($columnLetter, $decrement = 1)
+ {
+ $colIndex = Coordinate::columnIndexFromString($columnLetter);
+ $colIndex = max(1, $colIndex - $decrement); // ensure column index doesn't go below 1
+ return Coordinate::stringFromColumnIndex($colIndex);
+ }
+
+ public function handleMultiFileAttachments($json_string, $lead_id)
+ {
+ $attachments = [];
+
+ if (!empty($json_string)) {
+ $fileIds = json_decode($json_string, true);
+ $lead_file_path = WRITEPATH . 'uploads/lead_files/';
+
+ foreach ($fileIds as $id) {
+ $lead_file = $this->leadFilesModel->where('lead_id', $lead_id)->where('id', $id)->where('is_active', 1)->first();
+
+ if ($lead_file) {
+ $attachments[] = [
+ 'fileName' => $lead_file['file_name'],
+ 'filePath' => $lead_file_path . $lead_file['file_name']
+ ];
+ }
+ }
+ }
+
+ return $attachments;
+ }
}
diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php
index 4e1271f8..02409c2c 100755
--- a/app/Controllers/MasterController.php
+++ b/app/Controllers/MasterController.php
@@ -1422,11 +1422,12 @@ class MasterController extends AdminController
if ($insert) {
//for CD Tranction Table
+ $cd_tranction_data['cd_ac_pk'] = $this->CDMasterModel->insertID();
$response = DepositHelper::saveDeposit($cd_tranction_data, $loggedInUserID);
$cd_data = $this->CDMasterModel->where('client_id', $data['client_id'])->where('insurer_id', $data['insurer_id'])->findAll();
- return $this->respond(['status' => true, 'data' => $cd_data, 'cd_ac_no'=>$data['cd_ac_no'], 'message' => 'CD Account number created successfully'], 200);
+ return $this->respond(['status' => true, 'data' => $cd_data, 'cd_ac_no'=>$data['cd_ac_no'], 'message' => 'CD Account number created successfully', "FOR BDS PURPOSE"], 200);
}else{
return $this->respond(['status' => false, 'message' => 'Failed to created CD Account number'], 200);
}
diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php
index 4a2a59d6..a4721770 100644
--- a/app/Controllers/PolicyTransactionController.php
+++ b/app/Controllers/PolicyTransactionController.php
@@ -306,6 +306,12 @@ class PolicyTransactionController extends BaseController
$data['policy_with_corr'] = 1;
}
+ if (!isset($data['is_cd_reduce_from_bds'])) {
+ $data['is_cd_reduce_from_bds'] = 0;
+ } elseif ($data['is_cd_reduce_from_bds']) {
+ $data['is_cd_reduce_from_bds'] = 1;
+ }
+
if($data['ct_type'] == ""){
$data['ct_type'] = 1;
}
@@ -342,7 +348,7 @@ class PolicyTransactionController extends BaseController
$this->policyTransactionModel->update($insert, ['client_policy_id' => $client_policy_id]);
$emp_policy_insert = $this->InsertIndividualEmpPolicyTable($emp_data, $client_policy_id);
- if ($data['client_type'] == 1 && $data['status'] == 'completed') {
+ if ($data['client_type'] == 1 && $data['status'] == 'completed' && $data['is_cd_reduce_from_bds'] == 1) {
$this->processCompletedStatus($data, $client_policy_id, $data['insurer_id']);
}
}
@@ -362,6 +368,7 @@ class PolicyTransactionController extends BaseController
private function updateInceptionPolicy($id, $data)
{
+ // print_r($data); die;
if ($this->policyTransactionModel->update($id, $data)) {
$this->insertTransactionStatus($id, $data, 1);
@@ -391,7 +398,7 @@ class PolicyTransactionController extends BaseController
}
if ($data['status'] == 'completed' && $data['ct_type'] == 2) {
- if($data['client_type'] == 1){
+ if($data['client_type'] == 1 && $data['is_cd_reduce_from_bds'] == 1){
$this->processCompletedStatus($data, $data['client_policy_id'], $data['insurer_id']);
}
}
@@ -418,7 +425,7 @@ class PolicyTransactionController extends BaseController
// die;
if(isset($data['co_share_id']) && !empty($data['co_share_id'])){
- $this->removePtCoShareRecords($data['co_share_id']);
+ $this->removePtCoShareRecords($data['co_share_id'], $pt_id);
}
if(isset($data['follow_insurer_id'])){
@@ -426,7 +433,12 @@ class PolicyTransactionController extends BaseController
foreach ($data['follow_insurer_id'] as $index => $insurer) {
// Separate the insurer and insurer branch
- list($insurer_branch_id, $insurer_id) = explode('-', $insurer);
+ if(isset($insurer) && !empty($insurer)){
+ list($insurer_branch_id, $insurer_id) = explode('-', $insurer);
+ }else{
+ $insurer_branch_id = null;
+ $insurer_id = null;
+ }
// Prepare each co-share detail entry
$coShareDetails[] = [
@@ -547,7 +559,7 @@ class PolicyTransactionController extends BaseController
private function processCompletedStatus($data, $client_policy_id, $insurer_id)
{
$totalAmount = (int)$data['total'][0] ?? 0;
- $description = 'The following amount of Rs. ' . $totalAmount . '/- has been debited for the ' . $data['emp_count'] . ' employees at Inception.';
+ $description = 'The following amount of Rs. ' . $totalAmount . '/- has been debited for the ' . $data['emp_count'] . ' employees at Inception (BDS).';
$cdTransactionData = [
'amount' => $totalAmount,
@@ -562,8 +574,9 @@ class PolicyTransactionController extends BaseController
'updated_by' => get_session_userid(),
'event_name' => 'inception',
'is_active' => 1,
+ 'cd_ac_pk' => $data['cd_ac_pk']
];
-
+
DepositHelper::saveDeposit($cdTransactionData, get_session_userid());
}
@@ -790,13 +803,24 @@ class PolicyTransactionController extends BaseController
->whereIn('client_policy.policy_type_id', [2, 3])
->where('client_policy.is_active', 1)
->findAll();
-
- $data['pt_files'] = $this->PTFileModel
- ->join('policy_transaction', 'pt_files.pt_id = policy_transaction.id')
- ->where('pt_files.pt_id', $id)
- ->where('pt_files.is_active', 1)
- ->findAll();
-
+
+
+ $ptFileQuery = $this->PTFileModel
+ ->join('policy_transaction', 'pt_files.pt_id = policy_transaction.id')
+ ->where('pt_files.pt_id', $id)
+ ->where('pt_files.is_active', 1);
+
+ if (!in_array(get_role_id(), [1, 5]) && empty(array_intersect(user_team(), [MANAGEMENT_TEAM_ID, FINANCE_TEAM_ID, BUSINESS_TEAM_ID]))) {
+
+ if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
+ $ptFileQuery->where('pt_files.created_by', get_session_userid());
+ }
+ }
+
+ $data['pt_files'] = $ptFileQuery->findAll();
+
+
+
$data['pt_co_share_details'] = $this->PTCOShareDetailsModel
->select("
pt_co_share_details.*,
@@ -956,22 +980,26 @@ class PolicyTransactionController extends BaseController
}
//function for soft delete for pt_co_share_details records
- public function removePtCoShareRecords($primaryKeys)
+ public function removePtCoShareRecords($primaryKeys, $pt_id)
{
- // print_r($primaryKeys); die;
if (empty($primaryKeys)) {
return false;
}
- // Convert array to a comma-separated string for query binding
+ // Convert array to a comma-separated string of placeholders for query binding
$placeholders = implode(',', array_fill(0, count($primaryKeys), '?'));
- $sql = "UPDATE pt_co_share_details SET is_active = 0 WHERE id NOT IN ($placeholders)";
-
- return db_connect()->query($sql, $primaryKeys);
+ // Prepare the query with proper binding
+ $sql = "UPDATE pt_co_share_details SET is_active = 0 WHERE pt_id = ? AND id NOT IN ($placeholders)";
+
+ // Merge pt_id with primary keys for binding
+ $params = array_merge([$pt_id], $primaryKeys);
+
+ // Execute the query with bound parameters
+ return db_connect()->query($sql, $params);
}
-
+
//------------------------------------------------------------------------------------------------
// Policy Transaction Endorsement
@@ -1086,6 +1114,12 @@ class PolicyTransactionController extends BaseController
$data['policy_with_corr'] = 1;
}
+ if (!isset($data['is_cd_reduce_from_bds'])) {
+ $data['is_cd_reduce_from_bds'] = 0;
+ } elseif ($data['is_cd_reduce_from_bds']) {
+ $data['is_cd_reduce_from_bds'] = 1;
+ }
+
if(empty($data['data_received_date'])){
$data['data_received_date'] = null;
}else{
@@ -1155,8 +1189,8 @@ class PolicyTransactionController extends BaseController
'policy_type_id' => $issue_type['policy_type_id'] ?? null,
'issue_type' => $issue_type['issue_type'] ?? null,
'source_client_policy_id' => $issue_type['source_client_policy_id'] ?? null,
- 'cd_ac_no' => $issue_type['cd_ac_no'] ?? null,
- 'cd_ac_pk' => $issue_type['cd_ac_pk'] ?? null,
+ 'cd_ac_no' => isset( $data['cd_ac_no']) && !empty($data['cd_ac_no']) ? $data['cd_ac_no'] : $issue_type['cd_ac_no'] ?? null,
+ 'cd_ac_pk' => isset( $data['cd_ac_pk']) && !empty($data['cd_ac_pk']) ? $data['cd_ac_pk'] : $issue_type['cd_ac_pk'] ?? null,
// 'policy_issue_date' => $issue_type['policy_issue_date'] ?? null,
'policy_start_date' => $issue_type['policy_start_date'] ?? null,
'policy_end_date' => $issue_type['policy_end_date'] ?? null,
@@ -1215,6 +1249,7 @@ class PolicyTransactionController extends BaseController
$update = $this->policyTransactionModel->where('id', $id)->set($data)->update();
if ($update) {
+
$this->insertTransactionStatus($id, $data, 1);
$this->handleCompletedStatus($data, $id);
$this->insertOrUpdateCoShareDetails($data, $id);
@@ -1227,13 +1262,13 @@ class PolicyTransactionController extends BaseController
}
private function handleCompletedStatus($data, $policy_tran_id)
- {
- if ($data['status'] == 'completed' && $data['ct_type'] == 2) {
+ {
+ if ($data['client_type'] == 1 && $data['status'] == 'completed' && $data['is_cd_reduce_from_bds'] == 1) {
$tolamt = $data['total'][0] ?? 0;
$description = 'The following amount of Rs. ' . round($tolamt, 2) . '/- has been' .
- ($data['action_type'] == 'deletion' ? ' Credit ' : ' Debit ') . 'from the policy transaction';
+ ($data['action_type'] == 'deletion' ? ' Credit ' : ' Debit ') . 'from the policy transaction (BDS)';
$cd_tranction_data = [
'amount' => $tolamt,
@@ -1248,6 +1283,7 @@ class PolicyTransactionController extends BaseController
'updated_by' => get_session_userid(),
'event_name' => $data['action_type'],
'is_active' => 1,
+ 'cd_ac_pk' => $data['cd_ac_pk'] ?? null,
];
DepositHelper::saveDeposit($cd_tranction_data, get_session_userid());
@@ -1501,11 +1537,19 @@ class PolicyTransactionController extends BaseController
if (!empty($uploadData)) {
- $data['pt_files'] = $this->PTFileModel
- ->join('policy_transaction', 'pt_files.pt_id = policy_transaction.id')
- ->where('pt_files.pt_id', $pt_id)
- ->where('pt_files.is_active', 1)
- ->findAll();
+ $ptFileQuery = $this->PTFileModel
+ ->join('policy_transaction', 'pt_files.pt_id = policy_transaction.id')
+ ->where('pt_files.pt_id', $pt_id)
+ ->where('pt_files.is_active', 1);
+
+ if (!in_array(get_role_id(), [1, 5]) && empty(array_intersect(user_team(), [MANAGEMENT_TEAM_ID, FINANCE_TEAM_ID, BUSINESS_TEAM_ID]))) {
+
+ if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
+ $ptFileQuery->where('pt_files.created_by', get_session_userid());
+ }
+ }
+
+ $data['pt_files'] = $ptFileQuery->findAll();
return $this->respond(['status' => true, 'message' => 'File uploaded successfully in G-Drive', 'data' => $data]);
} else {
@@ -1565,6 +1609,7 @@ class PolicyTransactionController extends BaseController
->select("
pt_co_share_details.*,
policy_transaction.bro_payable_by,
+ policy_transaction.cd_ac_pk,
(
select cd_ac_no
from cd_master
@@ -1592,9 +1637,12 @@ class PolicyTransactionController extends BaseController
->where('is_active', 1)
->first();
+ $cd_ac_no = db_connect()->table('cd_master')->where('id', $is_copay_yes['cd_ac_pk'] ?? null)->get()->getRowArray();
+
if ($totalCount) {
- return $this->respond(['status' => true, 'code' => 200, 'data' => $totalCount, 'is_copay_yes' => $is_copay_yes], 200);
+ return $this->respond(['status' => true, 'code' => 200, 'data' => $totalCount, 'is_copay_yes' => $is_copay_yes, "cd_master_data" => $cd_ac_no], 200);
} else {
+ $insurer_data = $this->clientPolicyModel->where('id', $client_policy_id)->where('is_active', 1)->first();
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to get data'], 200);
}
diff --git a/app/Controllers/RestAuthenticationController.php b/app/Controllers/RestAuthenticationController.php
index 3d141b2b..77c6854c 100755
--- a/app/Controllers/RestAuthenticationController.php
+++ b/app/Controllers/RestAuthenticationController.php
@@ -118,7 +118,7 @@ class RestAuthenticationController extends AdminController
->where('employees.emp_status !=', 'truncated')
->where('employees.email_corporate', $email)
->where('EP.is_active', 1)
- ->whereIn('EP.status', ['draft', 'enrolled'])
+ ->whereIn('EP.status', ['active'])
->first();
if (isset($employeeData['employee_id'])) {
@@ -178,6 +178,46 @@ class RestAuthenticationController extends AdminController
}
+ public function updateEmpMPIN()
+ {
+ $requestData = $this->request->getJSON();
+ $mobile_number = $requestData->mobile_number ?? null;
+ $email_id = $requestData->email_id ?? null;
+ $new_mpin = $requestData->new_mpin ?? $requestData->mpin ?? null;
+ $old_mpin = $requestData->old_mpin ?? null;
+
+ if (!$new_mpin) {
+ return $this->response->setJSON(['status' => false, 'message' => 'MPIN is required.']);
+ }
+
+ $query = $this->employeeModel->where('relationship', 'self');
+
+ if ($mobile_number) {
+ $query->where('mobile', $mobile_number);
+ } elseif ($email_id) {
+ $query->where('email_corporate', $email_id);
+ } else {
+ return $this->response->setJSON(['status' => false, 'message' => 'Mobile number or Email ID is required.']);
+ }
+
+ if (!empty($old_mpin)) {
+ $query->where('mpin', $old_mpin);
+ }
+
+ // Fetch employee data
+ $employeeData = $query->first();
+
+ if (!$employeeData) {
+ return $this->response->setJSON(['status' => false, 'message' => 'Employee not found or invalid MPIN.']);
+ }
+
+ // Update MPIN
+ $updated = $this->employeeModel->update($employeeData['id'], ['mpin' => $new_mpin]);
+
+ return true;
+ }
+
+
public function getVerifiedUserData()
{
@@ -401,15 +441,14 @@ class RestAuthenticationController extends AdminController
$mobile_number = isset($this->request->getJSON()->mobile_number) ? $this->request->getJSON()->mobile_number : null;
$email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null;
$mpin = $this->request->getJSON()->mpin;
-
if (isset($mobile_number))
{
$employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->first();
}else{
$employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('relationship', 'self')->first();
}
-
if ($employeeData && $mpin == $employeeData["mpin"]) {
+
$auth = HttpRequestHelper::getRequestInfo();
if ($auth) {
$data = [
@@ -427,6 +466,7 @@ class RestAuthenticationController extends AdminController
$result = JWTToken::encode($employeeData);
+ // $result = $employeeData;
return $this->respond(['status' => 'success','code' => 200,'data' => $result],200);
} else {
return $this->respond(['status' => 'failed','code' => 404,'data' => "Invalid OTP"],200);
@@ -441,7 +481,7 @@ class RestAuthenticationController extends AdminController
try {
$mobile_number = isset($this->request->getJSON()->mobile_number) ? $this->request->getJSON()->mobile_number : null;
$email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null;
- $mpin = $this->request->getJSON()->mpin;
+ // $mpin = $this->request->getJSON()->mpin;
if (isset($mobile_number))
{
diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php
index a7392860..4b42394a 100644
--- a/app/Controllers/TicketController.php
+++ b/app/Controllers/TicketController.php
@@ -120,6 +120,9 @@ class TicketController extends BaseController
'((POLICY_TYPE))' => 'policy_type',
'((AUTO_QUERY_CONTENT))' => 'auto_query_content',
'((CLAIM_FORM_LINK))' => 'claim_form_link',
+ '((CLAIM_FEEDBACK_FORM))' => 'claim_feedback_form',
+ '((SETTLED_LETTER))' => 'settle_letter',
+ '((APPROVED_LETTER))' => 'approved_letter',
];
$this->extraFields = [
1 => ['non_id_reason'],
@@ -232,7 +235,9 @@ class TicketController extends BaseController
'tcs.claim_status AS status',
'tm.claim_number AS claim_no',
'tm.tpa_id',
+ 'tm.tpa_no',
'tm.emp_name',
+ 'tm.emp_code',
'i.name AS insurer_name',
'c.client_name',
'tm.insured_name',
@@ -272,7 +277,9 @@ class TicketController extends BaseController
'tm.claim_status_id',
'tm.is_head_approved',
'tm.tpa_id',
+ 'tm.tpa_no',
'tm.emp_name',
+ 'tm.emp_code',
'i.name AS insurer_name',
'c.client_name',
'tm.insured_name',
@@ -456,7 +463,18 @@ class TicketController extends BaseController
$data['placeHolders'] = $this->placeHolders;
$data['message_data'] = $this->getTicketMessage($ticket_id);
$data['view_ticket_page'] = [];
- $data['member_data'] = $this->employeeModel->getEmployeeByEmployeeCode($ticket_data['emp_code']);
+
+ if($ticket_data['ticket_type_id'] == 1){
+ $data['member_data'] = $this->employeeModel->getEmployeeByEmployeeCode($ticket_data['emp_code']);
+ }else{
+ $data['member_data'] = array_filter(
+ $this->employeeModel->getEmployeeByEmployeeCode($ticket_data['emp_code']),
+ function ($member) {
+ return isset($member['emp_relationship']) && $member['emp_relationship'] == 'Self';
+ }
+ );
+ }
+
$data['ticket_history'] = $this->ticketHistory($ticket_id);
$data['ticket_check_list'] = db_connect()->table('ticket_check_list')->where('is_active', 1)->where('ticket_type_id', $ticket_data['ticket_type_id'])->get()->getResultArray();
if (!empty($ticket_data['client_policy_id'])){
@@ -578,7 +596,9 @@ class TicketController extends BaseController
$return_value = $this->ticketMasterModel->insert($ticket_data);
if ($return_value) {
//mail trigger part
+ $this->putHistoryAfterInsert($ticket_data, $return_value);
$mail_responce = $this->sendAutoMailTrigger($return_value);
+ $this->autoMessageInsertBasedOnMailResponse($mail_responce, $return_value);
return $this->respond(['status' => true, 'ticket_id' => $return_value, 'code' => 200, 'data' => $ticket_data, "message" => "Claim created successfully", 'mail_responce' => $mail_responce], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to create claim'], 200);
@@ -601,8 +621,12 @@ class TicketController extends BaseController
$return_value = $this->ticketMasterModel->where('id', $ticket_id)->set($ticket_data)->update();
if ($return_value) {
- //mail trigger part
- $mail_responce = $this->sendAutoMailTrigger($ticket_id);
+ $mail_responce = null;
+ if($old_ticket_data['claim_status_id'] != $ticket_data['claim_status_id']){
+ //mail trigger part
+ $mail_responce = $this->sendAutoMailTrigger($ticket_id);
+ $this->autoMessageInsertBasedOnMailResponse($mail_responce, $ticket_id);
+ }
//send mail to the head for rejected ticket approvel
if($ticket_data['claim_status_id'] == 8 && $ticket_data['is_head_approved'] == 0){
@@ -751,13 +775,20 @@ class TicketController extends BaseController
{
// log_message('error','Function called');die();
// $ticket_master_id = $this->request->getPost('id');
- $user_id = get_session_userid();
- $logged_user = $this->userModel->select('first_name,last_name,profile')->where('id', $user_id)->first();
$dataToSend = [];
- $dataToSend['user_name'] = $logged_user['first_name'] . ' ' . $logged_user['last_name'];
- $dataToSend['messages'] = $this->ticketMessageModel->where('is_active', 1)
- ->where('ticket_id', $ticket_master_id)->orderBy('created_at', 'DESC')
+
+ $user_id = get_session_userid();
+ // $logged_user = $this->userModel->select('first_name,last_name,profile')->where('id', $user_id)->first();
+ // $dataToSend['user_name'] = $logged_user['first_name'] . ' ' . $logged_user['last_name'];
+
+ $dataToSend['messages'] = $this->ticketMessageModel
+ ->select('ticket_messages.*,up.first_name as user_name')
+ ->join('user_profiles up', 'up.id = ticket_messages.created_by', 'left')
+ ->where('ticket_messages.is_active', 1)
+ ->where('ticket_messages.ticket_id', $ticket_master_id)
+ ->orderBy('ticket_messages.created_at', 'DESC')
->findAll();
+
foreach ($dataToSend['messages'] as $message) {
$mail_content_converted = $this->convertHtmlToText($message['mail_content']);
$message['mail_content'] = $mail_content_converted;
@@ -837,7 +868,7 @@ class TicketController extends BaseController
}
// Construct Mail Data
- $mailData = [
+ $mailData[] = [
'mail' => $ticket_data['emp_mail'],
'subject' => $subject,
'message' => $message,
@@ -845,6 +876,17 @@ class TicketController extends BaseController
'attachments' => []
];
+ // if the employee personal mail is not empty then send the mail to the employee personal mail
+ if(!empty($ticket_data['emp_personal_mail'])){
+ $mailData[] = [
+ 'mail' => $ticket_data['emp_personal_mail'],
+ 'subject' => $subject,
+ 'message' => $message,
+ 'cc' => $ticket_data['common_mails'] ?? '',
+ 'attachments' => []
+ ];
+ }
+
// print_r($mailData); die;
$this->myLogger->logme('error', "Final Email Data");
@@ -869,6 +911,12 @@ class TicketController extends BaseController
$replaceData = str_replace("Claim-", "", $this->ticketType[$ticket_data['ticket_type_id']] ?? "");
} else if ($value == "claim_form_link"){
$replaceData = 'Click here to download Claim Form';
+ } else if ($value == "claim_feedback_form" && $ticket_data['ticket_type_id'] == 1){
+ $replaceData = 'Click to open Claim Feedback Form';
+ } else if ($value == "settle_letter"){
+ $replaceData = ' View Settlement Letter ';
+ }else if ($value == "approved_letter"){
+ $replaceData = ' View Approved Letter ';
}else {
$replaceData = isset($ticket_data[$value]) ? $ticket_data[$value] : '';
}
@@ -927,6 +975,27 @@ class TicketController extends BaseController
$this->myLogger->logme('error', "Fetched ACM emails");
+
+ if(!empty($ticket_data['emp_personal_mail'])){
+
+ $this->myLogger->logme('error', "Send employee personal mail start");
+
+ $emailPersonalData = [
+ 'mail' => $ticket_data['emp_personal_mail'],
+ 'subject' => $mail_data['mail_subject'],
+ 'message' => $mail_data['mail_content'],
+ 'common' => [],
+ 'cc' => $acm_mails['common_mails'],
+ 'attachments' => []
+ ];
+
+ $this->sendTrigger($emailPersonalData);
+
+ $this->myLogger->logme('error', "Send employee personal mail successfully");
+ }else{
+ $this->myLogger->logme('error', "Send employee personal mail is empty");
+ }
+
$emailData = [
'mail' => $mail_data['emp_mail'],
'subject' => $mail_data['mail_subject'],
@@ -950,7 +1019,10 @@ class TicketController extends BaseController
if (!empty($auto_mail_enable) && $auto_mail_enable['is_auto_mail'] == 1) {
$mail_content = $this->constructMailContent($ticket_id);
// print_r($mail_content); die;
- $mail_responce = $this->sendTrigger($mail_content);
+ foreach ($mail_content as $key => $value) {
+ $mail_responce = $this->sendTrigger($value);
+ $this->myLogger->logme('error', '{data} - Auto Mail Sent, Successfully', ['data' => $key + 1]);
+ }
} elseif (!empty($auto_mail_enable) && $auto_mail_enable['is_auto_mail'] == 0) {
$this->myLogger->logme('error', 'Auto Mail Not Sent, Reason: Automail Not Enabled');
} else {
@@ -972,7 +1044,7 @@ class TicketController extends BaseController
th.old_value,
th.new_value,
th.created_at,
- CONCAT(creator.first_name, ' ', creator.last_name) as modified_by,
+ CONCAT_WS(' ', creator.first_name, creator.last_name) AS modified_by,
-- Claim Status
old_status.claim_status as old_status_value,
new_status.claim_status as new_status_value,
@@ -1032,6 +1104,7 @@ class TicketController extends BaseController
ORDER BY
th.created_at DESC";
$data = $this->ticketHistoryModel->query($sql)->getResultArray();
+ // dd(db_connect()->getLastQuery());
$priorityType = $this->priorityType;
$relationshipType = $this->relationshipType;
$modeOFIntimate = $this->modeOFIntimate;
@@ -1166,7 +1239,7 @@ class TicketController extends BaseController
if ($policy_type == 1){
$viewData['column_order'] = [
'ACM_NAME', 'ID NOT GENERATED', 'NON ID', 'CDA', 'INFORMATION REQUIRED',
- 'UNDER PROCESS - CLAIM NO. UPDATION', 'UNDER PROCESS - INVESTIGATION STATUS',
+ 'UNDER PROCESS - CLAIM NO. UPDATION',
'UNDER PROCESS - QUERY DOCUMENT RECEIVED', 'APPROVED', 'PAYMENT INITIATED',
'TOTAL'
];
@@ -1185,7 +1258,7 @@ class TicketController extends BaseController
}else{
$viewData['column_order'] = [
'ACM_NAME', 'CLAIM INTIMATION', 'INTIMATION TO INSURER', 'CLIENT PENDING',
- 'INSURER PENDING','INVESTIGATION','APPROVED','ON HOLD','TOTAL', 'NOT COVERED',
+ 'INSURER PENDING','INVESTIGATION','APPROVED','TOTAL', 'NOT COVERED',
'CLOSED', 'SETTLED', 'CLEARED_TOTAL'
];
$ordered_data = [];
@@ -1207,7 +1280,7 @@ class TicketController extends BaseController
$viewData['column_order'] = [
'TPA_NAME', 'NON ID', 'ID NOT GENERATED', 'CDA', 'INFORMATION REQUIRED',
- 'UNDER PROCESS - CLAIM NO. UPDATION', 'UNDER PROCESS - INVESTIGATION STATUS',
+ 'UNDER PROCESS - CLAIM NO. UPDATION',
'UNDER PROCESS - QUERY DOCUMENT RECEIVED', 'APPROVED', 'PAYMENT INITIATED',
'TOTAL', 'SETTLED', 'CLOSED', 'CANCELLED', 'RETURNED', 'CLEARED_TOTAL'
];
@@ -1371,7 +1444,8 @@ class TicketController extends BaseController
}
}
- public function getPoliciesbyEmpID() {
+ public function getPoliciesbyEmpID()
+ {
$received_data = $this->request->getPost();
$emp_id = $received_data['emp_id'];
@@ -1443,5 +1517,121 @@ class TicketController extends BaseController
return $this->response->setStatusCode(500)->setBody('An error occurred while downloading the file.');
}
}
-
+
+ // -------------------------------------------------------------------------------------------------------------------------
+
+ public function autoMessageInsertBasedOnMailResponse($mail_sent_status, $ticket_id)
+ {
+ if (gettype($mail_sent_status) == 'array') {
+ $this->myLogger->logme('error', "auto Message Insert Based On Mail Response Failed because is array :$ticket_id ");
+ } else {
+ $mail_sent_status = json_decode($mail_sent_status);
+ $this->myLogger->logme('error', "mail_sent_status is object :$ticket_id ");
+ }
+
+ if (!empty($mail_sent_status) && isset($mail_sent_status->status) && $mail_sent_status->status == 'success') {
+
+ $sent_message_data['ticket_id'] = $ticket_id;
+ $sent_message_data['sender'] = 'staff';
+ $sent_message_data['emp_mail'] = $mail_sent_status->data->params->mail;
+ $sent_message_data['mail_subject'] = $mail_sent_status->data->params->subject;
+ $sent_message_data['mail_content'] = $mail_sent_status->data->params->message;
+
+ $message_insert_status = $this->ticketMessageModel->insert($sent_message_data);
+
+ if ($message_insert_status) {
+ $this->myLogger->logme('error', "Claim initiated, Mail sent Successfully, successfully store message:$ticket_id ");
+ } else {
+ $this->myLogger->logme('error', "Claim initiated, Mail sent Successfully, Failed to store message:$ticket_id ");
+ }
+
+ return true;
+ } else {
+
+ $this->myLogger->logme('error', "Failed to send Mail :$ticket_id ");
+ return true;
+ }
+ }
+
+ public function putHistoryAfterInsert($ticket_data, $ticket_id)
+ {
+ $this->myLogger->logme('error', "Put History After Insert function called : $ticket_id");
+
+ if(!empty($ticket_data)){
+
+ $history_data = [
+ 'ticket_id' => $ticket_id,
+ 'field_name' => 'claim_status_id',
+ 'display_name' => 'Ticket Created',
+ 'old_value' => null,
+ 'new_value' => $ticket_data['claim_status_id'],
+ 'created_by' => get_session_userid(),
+ 'is_active' => 1
+ ];
+
+ $this->myLogger->logme('error', "Put History After Insert function called : " . json_encode($history_data));
+
+
+ $history_insert = $this->ticketHistoryModel->insert($history_data);
+
+ if($history_insert){
+ $this->myLogger->logme('error', "Put History After Insert Ticket Data Successfully");
+ }else{
+ $this->myLogger->logme('error', "Put History After Insert Ticket Data Failed");
+ }
+
+ }else{
+ $this->myLogger->logme('error', "Put History After Insert Ticket Data is empty");
+ }
+
+ return true;
+
+ }
+
+ public function viewClaimFeedbackForm($md5_ticket_id,$empView = null)
+ {
+
+ if ($this->request->is("get")){
+
+ $data['ticket_id'] = $md5_ticket_id;
+ $data['ticket_data'] = $this->ticketMasterModel->select('ticket_master.*,clients.client_name')->join('clients','clients.id = ticket_master.client_id')->where('MD5(ticket_master.id)',$md5_ticket_id)->where('ticket_master.is_active',1)->first();
+ $data['form_submitted'] = !empty($data['ticket_data']['feedback_json'])? 1 : 0;
+
+
+ $data['viewer'] = !empty($empView) ? $empView : 0;
+ // dd($data);
+ return view('ticket_feedback_form', $data);
+ }else{
+
+ $formDataJson = json_encode($this->request->getPost());
+ // log_message("error","Form data : ".$formDataJson);
+
+
+ $data_to_store = [
+
+ 'feedback_json' => $formDataJson
+ ];
+
+ if (!empty($formDataJson)){
+ // $this->ticketMasterModel->save($data_to_store);
+ $this->ticketMasterModel->where('MD5(id)', $md5_ticket_id)->set($data_to_store)->update();
+
+ return $this->respond(['status' => true,'id'=> $md5_ticket_id,'received_data' => $formDataJson], 200);
+
+ }else{
+ return $this->respond(['status' => false,'id'=> $md5_ticket_id,'received_data' => $formDataJson], 200);
+ }
+
+ }
+
+ }
+
+ public function feedbackList(){
+
+ $data['feedback_data'] = $this->ticketMasterModel->select("ticket_master.*,clients.client_name")->join("clients","clients.id = ticket_master.client_id")->where("ticket_master.is_active",1)->where("ticket_master.feedback_json IS NOT NULL", null, false)->where("ticket_master.feedback_json !=", "")->findAll();
+
+ // dd($data);
+ $this->loadLayout("ticket_feedback_list",$data);
+ }
+
}
diff --git a/app/Helpers/DepositHelper.php b/app/Helpers/DepositHelper.php
index d225f71f..5137cc5c 100755
--- a/app/Helpers/DepositHelper.php
+++ b/app/Helpers/DepositHelper.php
@@ -32,8 +32,11 @@ class DepositHelper
*/
public static function saveDeposit(array $data, int $loggedInUserID): array
{
+
+ log_message("error", 'saveDeposit function called '. json_encode($data));
+
// Retrieve the last known balance
- $lastBalance = self::calculateLastBalance($data['client_id'], $data['insurer_id'], $data['cd_ac_no']);
+ $lastBalance = self::calculateLastBalance($data['client_id'], $data['insurer_id'], $data['cd_ac_no'], $data['cd_ac_pk'] ?? null);
// Calculate the new balance based on the transaction type
$newBalance = self::calculateBalance(
@@ -91,15 +94,21 @@ class DepositHelper
*
* @return float The last known balance.
*/
- public static function calculateLastBalance(int $clientId, int $insurerId, $cd_ac_no): float
+ public static function calculateLastBalance(int $clientId, int $insurerId, $cd_ac_no, $cd_ac_pk): float
{
$model = new ClientDepositModel();
// $getLastBalanceQuery = "SELECT balance FROM cash_deposit WHERE client_id = ? AND insurer_id = ? ORDER BY created_at DESC LIMIT 1";
// $getLastBalanceParams = [$clientId, $insurerId];
- $getLastBalanceQuery = "SELECT balance FROM cash_deposit WHERE cd_ac_no = ? AND is_active = 1 ORDER BY created_at DESC LIMIT 1";
- $getLastBalanceParams = [$cd_ac_no];
+ if(empty($cd_ac_pk)){
+ $getLastBalanceQuery = "SELECT balance FROM cash_deposit WHERE cd_ac_no = ? AND is_active = 1 ORDER BY created_at DESC LIMIT 1";
+ $getLastBalanceParams = [$cd_ac_no];
+ }else{
+ $getLastBalanceQuery = "SELECT balance FROM cash_deposit WHERE cd_ac_pk = ? AND is_active = 1 ORDER BY created_at DESC LIMIT 1";
+ $getLastBalanceParams = [$cd_ac_pk];
+ }
+
$lastBalance = $model->query($getLastBalanceQuery, $getLastBalanceParams)->getRow()->balance ?? 0;
diff --git a/app/Helpers/ExcelMergeHelper.php b/app/Helpers/ExcelMergeHelper.php
index 36306692..405c4762 100644
--- a/app/Helpers/ExcelMergeHelper.php
+++ b/app/Helpers/ExcelMergeHelper.php
@@ -17,10 +17,13 @@ class ExcelMergeHelper {
{
try {
log_message('debug', 'Attempting merge with original file order');
+ // echo "Attempting merge with original file order\n";
return self::processFiles($filePaths, $outputPath);
} catch (Exception $e) {
log_message('error', 'First attempt failed: ' . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine());
+ // echo "First attempt failed: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() . "\n";
log_message('debug', 'Retrying with reversed file order');
+ // echo "Retrying with reversed file order\n";
// Reverse the file order and try again
$reversedFiles = array_reverse($filePaths);
@@ -29,6 +32,7 @@ class ExcelMergeHelper {
return self::processFiles($reversedFiles, $outputPath);
} catch (Exception $e2) {
log_message('error', 'Both attempts failed. Last error: ' . $e2->getMessage() . ' in ' . $e2->getFile() . ' on line ' . $e2->getLine());
+ // echo "Both attempts failed. Last error: " . $e2->getMessage() . ' in ' . $e2->getFile() . ' on line ' . $e2->getLine() . "\n";
return null;
}
}
@@ -45,7 +49,9 @@ class ExcelMergeHelper {
private static function processFiles(array $filePaths, string $outputPath): string
{
log_message('debug', 'Starting Excel merge process');
+ // echo "Starting Excel merge process\n";
log_message('debug', 'Files to process: ' . json_encode($filePaths));
+ // echo "Files to process: " . json_encode($filePaths) . "\n";
if (empty($filePaths)) {
throw new Exception("No files provided to merge");
@@ -66,6 +72,7 @@ class ExcelMergeHelper {
// Save the merged file
log_message('debug', "Saving merged file to: {$outputPath}");
+ // echo "Saving merged file to: {$outputPath}\n";
$writer = IOFactory::createWriter($mergedSpreadsheet, 'Xlsx');
$writer->setPreCalculateFormulas(false);
$writer->save($outputPath);
@@ -76,6 +83,7 @@ class ExcelMergeHelper {
gc_collect_cycles();
log_message('debug', 'Excel merge process completed successfully');
+ // echo "Excel merge process completed successfully\n";
return $outputPath;
}
@@ -87,15 +95,17 @@ class ExcelMergeHelper {
* @param int|null $index
* @throws Exception
*/
- private static function processSingleFile(array $fileInfo, Spreadsheet $mergedSpreadsheet, int $index = null)
+ private static function processSingleFile(array $fileInfo, Spreadsheet $mergedSpreadsheet, ?int $index = null)
{
if (!isset($fileInfo['file_path']) || !file_exists($fileInfo['file_path'])) {
$path = $fileInfo['file_path'] ?? 'undefined';
log_message('error', "File " . ($index ?? 'base') . ": Invalid or missing file path: {$path}");
+ // echo "File " . ($index ?? 'base') . ": Invalid or missing file path: {$path}\n";
return;
}
log_message('debug', "Processing file " . ($index ?? 'base') . ": " . $fileInfo['file_path']);
+ // echo "Processing file " . ($index ?? 'base') . ": " . $fileInfo['file_path'] . "\n";
try {
// Load the source spreadsheet
@@ -105,6 +115,7 @@ class ExcelMergeHelper {
$worksheets = $sourceSpreadsheet->getAllSheets();
$totalSheets = count($worksheets);
log_message('debug', "Total sheets in file: " . $totalSheets);
+ // echo "Total sheets in file: " . $totalSheets . "\n";
$sheetsToMerge = $fileInfo['sheets'] ?? [];
@@ -114,26 +125,30 @@ class ExcelMergeHelper {
try {
$sheetName = $worksheet->getTitle();
log_message('debug', "Processing sheet: {$sheetName}");
+ // echo "Processing sheet: {$sheetName}\n";
// Generate unique sheet name before cloning
$newName = $sheetName;
$counter = 1;
while (in_array($newName, $mergedSpreadsheet->getSheetNames())) {
- $newName = $sheetName . "_" . $counter++;
+ // $newName = $sheetName . "_" . $counter++;
log_message('debug', "Sheet name already exists. Trying new name: {$newName}");
+ // echo "Sheet name already exists. Trying new name: {$newName}\n";
}
// Clone the worksheet and set the new name
- $clonedSheet = clone $worksheet;
- $clonedSheet->setTitle($newName);
+ // $clonedSheet = clone $worksheet;
+ // $clonedSheet->setTitle($newName);
// Add as external sheet
- $mergedSpreadsheet->addExternalSheet($clonedSheet);
+ $mergedSpreadsheet->addExternalSheet($worksheet);
log_message('debug', "Successfully added sheet: {$newName}");
+ // echo "Successfully added sheet: {$newName}\n";
} catch (Exception $e) {
log_message('error', "Error processing sheet {$sheetName} as new name {$newName}: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine());
+ // echo "Error processing sheet {$sheetName} as new name {$newName}: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() . "\n";
}
}
}
@@ -145,6 +160,7 @@ class ExcelMergeHelper {
} catch (Exception $e) {
log_message('error', "Error processing file {$fileInfo['file_path']}: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine());
+ // echo "Error processing file {$fileInfo['file_path']}: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() . "\n";
}
}
}
\ No newline at end of file
diff --git a/app/Helpers/ExcelSanitizeHelper.php b/app/Helpers/ExcelSanitizeHelper.php
index 5c2836a7..f4591bfa 100644
--- a/app/Helpers/ExcelSanitizeHelper.php
+++ b/app/Helpers/ExcelSanitizeHelper.php
@@ -29,6 +29,7 @@ class ExcelSanitizeHelper
$cleanData[$key] = self::sanitizeArrayData($value); // Recursive call for nested arrays
} elseif (is_string($value)) {
// Remove non-printable characters and trim whitespace from strings
+ $value = str_replace("\u00a0", " ", $value);
$cleanData[$key] = trim(preg_replace(self::$nonPrintablePattern, '', $value));
} else {
$cleanData[$key] = $value; // Keep non-string/non-array data as is
diff --git a/app/Helpers/utility_helper.php b/app/Helpers/utility_helper.php
index 2e932ab7..33f504c0 100755
--- a/app/Helpers/utility_helper.php
+++ b/app/Helpers/utility_helper.php
@@ -665,3 +665,81 @@ if (!function_exists('check_pay_by_employee_or_company')) {
}
+if (!function_exists('is_json_string')) {
+ function is_json_string($string)
+ {
+ if (!is_string($string)) {
+ return false;
+ }
+
+ $decoded = json_decode($string, true);
+ return (json_last_error() === JSON_ERROR_NONE && is_array($decoded));
+ }
+}
+
+if (!function_exists('check_cd_entry_exist')) {
+ function check_cd_entry_exist($params)
+ {
+ $db = db_connect();
+
+ $client_id = $params['client_id'];
+ $client_policy_id = $params['client_policy_id'];
+ $insurer_id = $params['insurer_id'];
+ $cd_ac_pk = $params['cd_ac_pk'];
+ $event_name = $params['event_name'];
+
+ // Check if truncated entry (sub_type = 8) exists
+ $has_truncated = $db->table('cash_deposit')
+ ->where('client_id', $client_id)
+ ->where('insurer_id', $insurer_id)
+ ->where('cd_ac_pk', $cd_ac_pk)
+ ->where('client_policy_id', $client_policy_id)
+ ->where('event_name', $event_name)
+ ->where('sub_type', 8)
+ ->where('is_active', 1)
+ ->countAllResults();
+
+ if ($has_truncated) {
+
+ echo "has_truncated";
+ // Get all entries with same details (including truncated)
+ $entries = $db->table('cash_deposit')
+ ->where('client_id', $client_id)
+ ->where('insurer_id', $insurer_id)
+ ->where('cd_ac_pk', $cd_ac_pk)
+ ->where('client_policy_id', $client_policy_id)
+ ->where('event_name', $event_name)
+ ->where('is_active', 1)
+ ->where('sub_type !=', 8)
+ ->get()
+ ->getResultArray();
+
+ if (count($entries) > 1) {
+ // Only one entry found (truncated)
+ return true;
+ }else{
+ return false;
+ }
+ } else {
+ // Check if any other entry exists
+ $entry = $db->table('cash_deposit')
+ ->where('client_id', $client_id)
+ ->where('insurer_id', $insurer_id)
+ ->where('cd_ac_pk', $cd_ac_pk)
+ ->where('client_policy_id', $client_policy_id)
+ ->where('event_name', $event_name)
+ ->where('is_active', 1)
+ ->get()
+ ->getRowArray();
+
+ if (!empty($entry)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+}
+
+
+
diff --git a/app/Models/ClientPolicyModel.php b/app/Models/ClientPolicyModel.php
index c8fcb855..360081a4 100755
--- a/app/Models/ClientPolicyModel.php
+++ b/app/Models/ClientPolicyModel.php
@@ -54,6 +54,7 @@ class ClientPolicyModel extends Model
"is_member_modify_allowed",
"cd_ac_pk",
"is_lgbtq",
+ "placement_json",
];
// Callbacks
diff --git a/app/Models/EmployeePolicyModel.php b/app/Models/EmployeePolicyModel.php
index 960f37d0..175be311 100755
--- a/app/Models/EmployeePolicyModel.php
+++ b/app/Models/EmployeePolicyModel.php
@@ -81,6 +81,146 @@ class EmployeePolicyModel extends Model
}
// ----------------------------------------------------------------------------------------------------------
+ // public function getEmployeePolicy($client_id = 0, $policy_id = 0, $status = [], $branch_id = 0, $emp_code = "", $emp_name = "")
+ // {
+ // // dd($status);
+
+ // $result = $this->select([
+ // 'employee_polices.*',
+ // 'policy_type.policy_type as policy_name',
+ // 'im.short_name as insurer_short_name',
+ // 'ib.branch_name as insurer_branch_name',
+ // 'ib.branch_code as insurer_branch_code',
+ // 'tpam.name as tpa_name',
+ // 'tpam.short_name as tpa_short_name',
+ // 'tpab.branch_code as tpa_branch_code',
+ // 'cm.client_name',
+ // 'cm.short_name as client_short_name',
+ // // 'emp.id as employee_primary_id',
+ // 'emp.relationship',
+ // 'emp.relationship_code',
+ // 'emp.change_event',
+ // 'emp.emp_code',
+ // 'emp.name',
+ // 'emp.email_corporate',
+ // 'emp.dob',
+ // 'DATE_FORMAT(emp.dob, "%d/%m/%Y") AS formatted_dob',
+ // 'emp.gender',
+ // 'emp.emp_status',
+ // 'emp.is_active as emp_is_active',
+ // 'emp.mobile as mobile',
+ // 'emp.doj',
+ // 'emp.basic_pay',
+ // 'emp.band as grade',
+ // 'policy_type.policy_type',
+ // 'client_branch.branch_name as client_branch_name',
+ // 'client_branch.branch_code as client_branch_code',
+ // 'cp.policy_no',
+ // 'cp.policy_type_id',
+
+ // // Name audit trail
+ // '(SELECT old_value FROM auditing_history WHERE pk = emp.id AND field_name = "name" AND table_name = "employees" ORDER BY id ASC LIMIT 1) AS name_first_old',
+ // '(SELECT new_value FROM auditing_history WHERE pk = emp.id AND field_name = "name" AND table_name = "employees" ORDER BY id DESC LIMIT 1) AS name_last_new',
+
+ // // DOB audit trail
+ // '(SELECT old_value FROM auditing_history WHERE pk = emp.id AND field_name = "dob" AND table_name = "employees" ORDER BY id ASC LIMIT 1) AS dob_first_old',
+ // '(SELECT new_value FROM auditing_history WHERE pk = emp.id AND field_name = "dob" AND table_name = "employees" ORDER BY id DESC LIMIT 1) AS dob_last_new',
+
+ // // Gender audit trail
+ // '(SELECT old_value FROM auditing_history WHERE pk = emp.id AND field_name = "gender" AND table_name = "employees" ORDER BY id ASC LIMIT 1) AS gender_first_old',
+ // '(SELECT new_value FROM auditing_history WHERE pk = emp.id AND field_name = "gender" AND table_name = "employees" ORDER BY id DESC LIMIT 1) AS gender_last_new',
+
+ // '(CASE
+ // WHEN emp.relationship = "Self"
+ // THEN (SELECT COUNT(id) FROM employees WHERE emp_code = emp.emp_code AND is_active = 0 AND emp_status != "truncated")
+ // ELSE NULL
+ // END) AS removed_count',
+
+ // '(CASE
+ // WHEN emp.relationship != "Self" AND emp.created_at != (
+ // SELECT created_at
+ // FROM employees
+ // WHERE emp_code = emp.emp_code AND relationship = "Self" AND is_active = 1
+ // LIMIT 1
+ // )
+ // THEN "Newly Added"
+ // ELSE NULL
+ // END) AS newly_added',
+
+ // ])
+ // ->join('employees emp', 'employee_polices.employee_id = emp.id')
+ // ->join('client_policy cp', 'employee_polices.client_policy_id = cp.id') //cp - client policy
+ // ->join('policies pm', 'cp.policy_id = pm.id', 'left') //pm - policy master
+ // ->join('policy_type', 'policy_type.id = cp.policy_type_id')
+ // ->join('insurers im', 'cp.insurer_id = im.id') //im - insurer master
+ // ->join('insurer_branch ib', 'cp.insurer_branch_id = ib.id') //ib - insurer branch
+ // ->join('tpa tpam', 'cp.tpa_id = tpam.id', 'left') //tpam - tpa master
+ // ->join('tpa_branch tpab', 'cp.tpa_branch_id = tpab.id', 'left') //tpab - tpa branch
+ // ->join('clients cm', 'cp.client_id = cm.id') //cm - client master
+ // ->join('client_branch', 'emp.client_branch_id = client_branch.id') //cm - client master
+ // ->orderBy('emp.emp_code', 'ASC')
+ // ->orderBy('employee_polices.employee_id', 'ASC');
+
+
+ // // Conditionally add where clauses
+ // if ($client_id != 0 && !empty($client_id)) {
+ // $result->where('emp.client_id', $client_id);
+ // }
+ // if ($branch_id != 0 && !empty($branch_id)) {
+ // $result->where('emp.client_branch_id', $branch_id);
+ // }
+ // if ($policy_id != 0 && !empty($policy_id)) {
+ // $result->where('employee_polices.client_policy_id', $policy_id);
+ // }
+
+ // if (is_array($status) && count($status) > 0) {
+
+ // $result->where('employee_polices.status !=', 'expired');
+
+ // if (in_array("active", $status)) {
+
+ // $result->where('employee_polices.tpa_id IS NOT NULL');
+ // $result->where('employee_polices.uhid IS NOT NULL');
+ // $result->whereIn('employee_polices.status', $status);
+ // } elseif (in_array("pending", $status)) {
+
+ // $result->where('employee_polices.tpa_id IS NULL');
+ // $result->where('employee_polices.uhid IS NULL');
+ // $result->whereIn('employee_polices.status', array_merge($status, ['active']));
+ // } else {
+
+ // $result->whereIn('employee_polices.status', $status);
+ // }
+
+ // // if($status == 'active'){
+ // // $result->where('employee_polices.tpa_id IS NOT NULL');
+ // // $result->where('employee_polices.uhid IS NOT NULL');
+ // // }else if($status == 'pending'){
+ // // $status = 'active';
+ // // $result->where('employee_polices.status', $status);
+ // // }else{
+ // // $result->where('employee_polices.status', $status);
+ // // }
+ // }
+
+ // if (!empty($emp_code)) {
+ // $result->where('emp.emp_code', $emp_code);
+ // }
+ // if (!empty($emp_name)) {
+ // $result->like('emp.name', $emp_name);
+ // }
+
+ // // Always check these conditions
+ // $result->where('employee_polices.is_active', 1)
+ // ->where('emp.is_active', 1);
+
+ // $res = $result->findAll();
+
+ // // dd($this->db->getLastQuery());
+
+ // return $res;
+ // } // remarks do not remove
+
public function getEmployeePolicy($client_id = 0, $policy_id = 0, $status = [], $branch_id = 0, $emp_code = "", $emp_name = "")
{
// dd($status);
@@ -179,9 +319,11 @@ class EmployeePolicyModel extends Model
}
// Always check these conditions
- $result->where('employee_polices.is_active', 1)
- ->where('emp.is_active', 1);
-
+ $result
+ ->where('employee_polices.is_active', 1)
+ ->where('emp.is_active', 1)
+ ->where('employee_polices.status !=', 'inactive');
+
$res = $result->findAll();
// dd($this->db->getLastQuery());
diff --git a/app/Models/LeadFilesModel.php b/app/Models/LeadFilesModel.php
new file mode 100644
index 00000000..37db8e16
--- /dev/null
+++ b/app/Models/LeadFilesModel.php
@@ -0,0 +1,55 @@
+join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left')
->where('policy_transaction.is_active', 1)
->where('pt_co_share_details.is_active', 1);
+
+ if (
+ (!in_array(get_role_id(), [1, 5])) &&
+ !(
+ in_array(MANAGEMENT_TEAM_ID, user_team()) ||
+ in_array(FINANCE_TEAM_ID, user_team()) ||
+ in_array(BUSINESS_TEAM_ID, user_team())
+ )
+ ) {
+ if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
+ $builder->where('policy_transaction.created_by', get_session_userid());
+ }
+ }
// Check if the start date and end date are provided
if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') {
@@ -973,6 +987,19 @@ class PolicyTransactionModel extends Model
->where('policy_transaction.is_active', 1)
->where('policy_transaction.action_type', 'inception');
+ if (
+ (!in_array(get_role_id(), [1, 5])) &&
+ !(
+ in_array(MANAGEMENT_TEAM_ID, user_team()) ||
+ in_array(FINANCE_TEAM_ID, user_team()) ||
+ in_array(BUSINESS_TEAM_ID, user_team())
+ )
+ ) {
+ if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
+ $builder->where('policy_transaction.created_by', get_session_userid());
+ }
+ }
+
// Optimize Date Filtering
if (!empty($start_date) && !empty($end_date) && !empty($date_type)) {
$builder->where("policy_transaction.$date_type >=", date('Y-m-d 00:00:00', strtotime($start_date)))
@@ -1034,6 +1061,19 @@ class PolicyTransactionModel extends Model
->where('policy_transaction.is_active', 1)
->where('policy_transaction.action_type !=', 'inception');
+ if (
+ (!in_array(get_role_id(), [1, 5])) &&
+ !(
+ in_array(MANAGEMENT_TEAM_ID, user_team()) ||
+ in_array(FINANCE_TEAM_ID, user_team()) ||
+ in_array(BUSINESS_TEAM_ID, user_team())
+ )
+ ) {
+ if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
+ $builder->where('policy_transaction.created_by', get_session_userid());
+ }
+ }
+
if ($start_date != 0 && $end_date != 0 && $date_type != 0) {
diff --git a/app/Models/RFQModel.php b/app/Models/RFQModel.php
index 24d18529..4ffbf9d4 100644
--- a/app/Models/RFQModel.php
+++ b/app/Models/RFQModel.php
@@ -68,6 +68,7 @@ class RFQModel extends Model
tpa_branch.branch_name as tpa_branch_name,
policy_type.policy_type,
rfq.json,
+ rfq.registration_json
')
->join('leads', 'rfq.lead_id = leads.id')
->join('policy_type', 'leads.policy_type_id = policy_type.id')
diff --git a/app/Models/TicketHistoryModel.php b/app/Models/TicketHistoryModel.php
index 6d7eb0f5..92041c8c 100644
--- a/app/Models/TicketHistoryModel.php
+++ b/app/Models/TicketHistoryModel.php
@@ -12,7 +12,7 @@ class TicketHistoryModel extends Model
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $protectFields = true;
- protected $allowedFields = ['id','field_name','display_name','old_value',
+ protected $allowedFields = ['id', "ticket_id", 'field_name','display_name','old_value',
'new_value','created_by','created_at','updated_by','updated_at','is_active'];
// Callbacks
diff --git a/app/Models/TicketMasterModel.php b/app/Models/TicketMasterModel.php
index f75cf2a6..1612c08e 100644
--- a/app/Models/TicketMasterModel.php
+++ b/app/Models/TicketMasterModel.php
@@ -15,6 +15,7 @@ class TicketMasterModel extends Model
protected $allowedFields = [
'id',
'ticket_type_id',
+ 'feedback_json',
'claim_status_id',
'acm_id',
'insurer_id',
@@ -689,6 +690,7 @@ class TicketMasterModel extends Model
$query = $this->select('ticket_master.*, tms.mail_subject as subject')
->join('ticket_messages tms', 'ticket_master.id = tms.ticket_id', 'left')
->where('ticket_master.is_active', 1)
+ ->where('tms.sender', "user")
->where('ticket_master.emp_id', $emp_id);
if (!empty($ticket_id)) {
diff --git a/app/Models/UserModel.php b/app/Models/UserModel.php
index 49b84400..ed5a8ace 100755
--- a/app/Models/UserModel.php
+++ b/app/Models/UserModel.php
@@ -134,5 +134,20 @@ class UserModel extends Model
->getResultArray();
}
+ public function getexclusiveUserListForRFQ(){
+ $data = $this->db->table('user_profiles')
+ ->select('user_profiles.*,user_teams.team_id')
+ ->select('roles.role as user_role')
+ ->join('roles', 'roles.id = user_profiles.role')
+ ->join('user_teams', 'user_teams.user_id = user_profiles.id')
+ ->get()
+ ->getResultArray();
+
+
+ // dd($data);
+
+ return $data;
+ }
+
}
?>
\ No newline at end of file
diff --git a/app/Views/DashBoard.php b/app/Views/DashBoard.php
index 4da6b9c0..3102ab15 100755
--- a/app/Views/DashBoard.php
+++ b/app/Views/DashBoard.php
@@ -139,40 +139,41 @@
+
@@ -188,21 +189,25 @@ body {
-
-
-
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/Views/batch_list.php b/app/Views/batch_list.php
index 4d85d018..f1a623fe 100755
--- a/app/Views/batch_list.php
+++ b/app/Views/batch_list.php
@@ -90,6 +90,17 @@
+
+
+
+
+
+
+
+
+
+
failed Re-Upload
-
+
Download
diff --git a/app/Views/bds_dash.php b/app/Views/bds_dash.php
index 89a92413..c6711ec9 100644
--- a/app/Views/bds_dash.php
+++ b/app/Views/bds_dash.php
@@ -125,7 +125,12 @@ body{
}
-
+
+
+
+
+
+