diff --git a/app/Config/Routes.php b/app/Config/Routes.php index acb156bd..2b253b31 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -369,6 +369,7 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) { $routes->get('getPolicyTypeFields', 'LeadsController::getPolicyTypeFields'); $routes->get('removeMultiFile', 'LeadsController::removeMultiFile'); $routes->get('removeInstallments', 'LeadsController::removeInstallments'); + $routes->get('getLeadEmailHistory/(:any)', 'LeadsController::getLeadEmailHistory/$1'); $routes->get('viewHrAccessData', 'ClientController::viewHrAccessData'); $routes->post('saveHrAccessData', 'ClientController::saveHrAccessData'); $routes->get('removeLevelContacts', 'ClientController::removeLevelContacts'); @@ -452,7 +453,6 @@ $routes->get('cli/sendZeptoMail', 'MasterController::testZeptoSMTP'); $routes->cli('cli/processjob', 'JobWorker::processJob'); $routes->cli('cli/processjobs', 'JobWorker::processJobs'); -$routes->cli('cli/sendMailWithAutoQuery','TicketController::sendMailWithAutoQuery'); $routes->get("processjob", "JobWorker::processJob"); $routes->cli('cli/new_gmail_token', 'MasterController::generateNewGmailAPIToken'); @@ -466,6 +466,10 @@ $routes->cli('cli/new_gdrive_token', 'GoogleDriveController::generateNewGoogleDr $routes->cli('cli/enrollOpendAndClose', 'DashboardController::updatePolicyEnrollmentStatus'); $routes->cli("cli/sendCroneRemainderMail", "DashboardController::sendCroneRemainderMail"); $routes->cli('cli/update-emp-policy-status', 'ClientController::updateEmpAndPolicyStatus'); +$routes->cli('cli/update-emp-policy-status', 'ClientController::updateEmpAndPolicyStatus'); +$routes->cli('cli/insurerRFQRemainder', 'LeadsController::remainderForQcr'); +$routes->cli('cli/sendMailWithAutoQuery','TicketController::sendMailWithAutoQuery'); + //Employee login api's $routes->post("/employeeRest/verifyEmployeeNumber", "RestAuthenticationController::verifyEmployeeWithMobileNumber"); @@ -562,6 +566,8 @@ $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) { $routes->get("ticketList", "ThzController::ticketList"); $routes->post("ticketConversationSave", "ThzController::ticketConversationSave"); $routes->get("ticketConversationList", "ThzController::ticketConversationList"); + $routes->get("ticketHistoryList", "ThzController::ticketHistoryList"); + $routes->match(['get','post','put'], 'ticketType', 'ThzController::ticketType'); $routes->get("hrFileList", "EmployeeRestController::hrFileList"); $routes->get("hrFileUploadMasters", "EmployeeRestController::hrFileUploadMasters"); @@ -660,4 +666,12 @@ $routes->get("ticketList", "ThzController::ticketList"); $routes->post("ticketConversationSave", "ThzController::ticketConversationSave"); $routes->get("ticketConversationList", "ThzController::ticketConversationList"); $routes->post('ticketAutoFetchDetails',"ThzController::ticketAutoFetchDetails"); -// $routes->match(['get','post','put'], 'ticketType', 'ThzController::ticketType'); \ No newline at end of file +$routes->match(['get','post','put'], 'ticketType', 'ThzController::ticketType'); +$routes->get("ticketHistoryList", "ThzController::ticketHistoryList"); + + +//for testing +$routes->group('test', function($routes) { + $routes->post('api/saveForm', 'TestingController::saveForm'); + $routes->get('insurerRFQRemainder', 'LeadsController::remainderForQcr'); +}); diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index 98b2a821..4a73bb1b 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -184,7 +184,7 @@ class ClientController extends AdminController public function testMailAttachments($email = 'venkateshraman786@gmail.com') { - $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

'; + $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

'; // $attachments = [ // ["filePath" => ROOTPATH."public/sample_excel/sample_addition.xls","fileName" => "sample_addition.xls"], @@ -5060,9 +5060,10 @@ class ClientController extends AdminController // ---------- TICKET SERVICE CONTROLLER -------------------------------------------------------------------------------- $ticketServiceController = new TicketServiceController(); - // $response = $ticketServiceController->claimDumpExcelFileFormatValidation(["file_id" => 3]); - // $response = $ticketServiceController->claimDumpExcelFileDataValidation(["file_id" => 3]); - // $response = $ticketServiceController->claimDumpOnBoardProcess(["file_id" => 3]); + // $response = $ticketServiceController->claimDumpExcelFileFormatValidation(["file_id" => 34]); + // $response = $ticketServiceController->claimDumpExcelFileDataValidation(["file_id" => 34]); + // $response = $ticketServiceController->getClaimExcelErrorData(["file_id" => 41]); + // $response = $ticketServiceController->claimDumpOnBoardProcess(["file_id" => 17]); // $response = $ticketServiceController->extractExcelData("claims_dump_form_client.xlsx"); // dd($response); @@ -5079,8 +5080,16 @@ class ClientController extends AdminController // $res = $empServiceController->employeesCorrectionProcess(['file_id' => '1681']); // dd( $res); - // $EmployeeMultiEventServiceController = new EmployeeMultiEventServiceController(); - // $res = $EmployeeMultiEventServiceController->constructMultiEventData(['file_id' => '1056']); + $EmployeeMultiEventServiceController = new EmployeeMultiEventServiceController(); + // $res = $EmployeeMultiEventServiceController->constructMultiEventData(['file_id' => '1069']); + // $res = $EmployeeMultiEventServiceController->excelMultieventFileFormateValidation(['file_id' => '1084']); + // $res = $EmployeeMultiEventServiceController->excelMultieventFileDataValidation(['file_id' => '1069']); + // $res = $EmployeeMultiEventServiceController->excelMultieventFileOnBoard(['file_id' => '1069']); + // dd($res); + + // $res = $EmployeeMultiEventServiceController->getExcelErrorData(1069, $res); + // $res['file_id'] = 1069; + // echo view('excel_errors', $res); // dd($res); // ---------- POLICY TRANSACTION CONTROLLER -------------------------------------------------------------------------------- @@ -5454,10 +5463,21 @@ class ClientController extends AdminController } } - public function getTheEmpDataForClaimSearchByMobile($param, $type = 'mobile', $client_policy_id = null, $client_id = null) + public function getTheEmpDataForClaimSearchByMobile($param, $type = 'mobile', $client_policy_id = null, $client_id = null, $ticket_type_id = null) { $field_name = 'employees.' . $type; + $policy_type_id = []; + if($ticket_type_id == 1){ + $policy_type_id = [2, 3, 4, 5]; + }else if($ticket_type_id == 2){ + $policy_type_id = [1]; + }else if($ticket_type_id == 3){ + $policy_type_id = [6]; + }else if($ticket_type_id == 4){ + $policy_type_id = [7]; + } + // Construct the base query $query = $this->clientPolicyModel ->select(" @@ -5481,7 +5501,7 @@ class ClientController extends AdminController ->join('insurers', 'client_policy.insurer_id = insurers.id') ->join('tpa', 'client_policy.tpa_id = tpa.id', 'left') ->join('employees', 'clients.id = employees.client_id') - ->join('employee_polices', 'employees.id = employee_polices.employee_id') + ->join('employee_polices', 'employees.id = employee_polices.employee_id AND client_policy.id = employee_polices.client_policy_id') ->where('client_policy.is_active', 1) ->where('insurers.is_active', 1) ->where('tpa.is_active', 1) @@ -5499,6 +5519,10 @@ class ClientController extends AdminController if (!empty($client_policy_id)) { $query->where('employee_polices.client_policy_id', $client_policy_id); } + + if($policy_type_id != null){ + $query->whereIn('client_policy.policy_type_id', $policy_type_id); + } $query->groupBy('employees.id') ->orderBy('employees.id', 'DESC'); @@ -6612,268 +6636,6 @@ class ClientController extends AdminController // ------------------- DEMO CLIENT FUNCTION -------------------------------------------------------------------------------- - // public function wipeDemoClient() - // { - // // $this->myLogger->logme('error', "Wipe Demo Client function called"); - // $this->myLogger->logme('error', "Wipe Demo Client function called"); // Red text - - // $this->myLogger->logme('error', "Wipe Demo client Payload : " . json_encode($this->request->getPost() ?? [])); - // $client_id = $this->request->getPost('client_id'); - - // if (empty($client_id)) { - // return $this->respond(['status' => false, 'message' => 'Client id required'], 404); - // } - - // // 1. Client Model - // $client_data = $this->clientModel->where('id', $client_id)->where('is_active', 1)->first(); - // $this->myLogger->logme('error', "Client data : " . json_encode($client_data ?? [])); - - // if (!empty($client_data)) { - // $is_deleted = $this->clientModel->where('id', $client_id)->delete(); - - // if ($is_deleted) { - // $this->myLogger->logme('error', "Client data removed successfully."); - // } else { - // $this->myLogger->logme('error', "Client record does not exist."); - // } - // } else { - // return $this->respond(['status' => false, 'message' => 'Client not found'], 404); - // } - - // // 2. Client RM Model - // $client_rm_data = $this->clientRMModel->where('client_id', $client_id)->first(); - // $this->myLogger->logme('error', "Client Relationship Manager data : " . json_encode($client_rm_data ?? [])); - - // if (!empty($client_rm_data)) { - // $is_deleted = $this->clientRMModel->where('client_id', $client_id)->delete(); - - // if ($is_deleted) { - // $this->myLogger->logme('error', "Client Relationship Manager data removed successfully."); - // } else { - // $this->myLogger->logme('error', "Client Relationship Manager record does not exist. To delete"); - // } - // } else { - // $this->myLogger->logme('error', "Client Relationship Manager data not found."); - // } - - // // 3. Client KYC Docs Model - // $client_kyc_data = $this->clientKYCDocsModel->where('client_id', $client_id)->findAll(); - // $this->myLogger->logme('error', "Client KYC Docs data : " . json_encode($client_kyc_data ?? [])); - - // if (!empty($client_kyc_data)) { - // $is_deleted = $this->clientKYCDocsModel->where('client_id', $client_id)->delete(); - // if ($is_deleted) { - // $this->myLogger->logme('error', "Client KYC Docs data removed successfully."); - // } else { - // $this->myLogger->logme('error', "Client KYC Docs record does not exist. To delete"); - // } - // } else { - // $this->myLogger->logme('error', "Client KYC Docs data not found."); - // } - - // // 4. Client Branch Model - // $client_branch_data = $this->clientBranchModel->where('client_id', $client_id)->findAll(); - // $this->myLogger->logme('error', "Client Branch data : " . json_encode($client_branch_data ?? [])); - - // $branch_ids = array_column($client_branch_data, 'id') ?? []; - // $this->myLogger->logme('error', "Client Branch id count : " . count($branch_ids ?? [])); - - // if (!empty($client_branch_data)) { - - // $is_deleted = $this->clientBranchModel->where('client_id', $client_id)->delete(); - - // if ($is_deleted) { - // $this->myLogger->logme('error', "Client Branch data removed successfully."); - - // if(!empty($branch_ids)){ - - // $level_contact_data = $this->levelContactModel->where('contact_type', 'client')->whereIn('ref_id', $branch_ids)->findAll(); - // $this->myLogger->logme('error', "Level Contact data : " . json_encode($level_contact_data ?? [])); - - // $is_deleted = $this->levelContactModel->where('contact_type', 'client')->whereIn('ref_id', $branch_ids)->delete(); - // if ($is_deleted) { - // $this->myLogger->logme('error', "Level Contact data removed successfully."); - // } else { - // $this->myLogger->logme('error', "Level Contact record does not exist. To delete"); - // } - - // }else{ - // $this->myLogger->logme('error', "Level Contact data not found."); - // } - - // } else { - // $this->myLogger->logme('error', "Client Branch record does not exist. To delete"); - // } - // } else { - // $this->myLogger->logme('error', "Client Branch data not found."); - // } - - // // 5. Client Policy Model - // $client_policy_data = $this->clientPolicyModel->where('client_id', $client_id)->findAll(); - // $this->myLogger->logme('error', "Client Policy data : " . json_encode($client_policy_data ?? [])); - - // $policy_ids = array_column($client_policy_data, 'id') ?? []; - // $this->myLogger->logme('error', "Client Policy id count : " . count($policy_ids ?? [])); - - // if (!empty($client_policy_data)) { - // $is_deleted = $this->clientPolicyModel->where('client_id', $client_id)->delete(); - // if ($is_deleted) { - - // $this->myLogger->logme('error', "Client Policy data removed successfully."); - - // if(!empty($policy_ids)){ - - // $employee_policy_data = $this->employeePolicyModel->whereIn('client_policy_id', $policy_ids)->findAll(); - // $this->myLogger->logme('error', "Employee Policy data count : " . count($employee_policy_data ?? [])); - - // $is_deleted = $this->employeePolicyModel->whereIn('client_policy_id', $policy_ids)->delete(); - // if ($is_deleted) { - // $this->myLogger->logme('error', "Employee policy data removed successfully."); - // } else { - // $this->myLogger->logme('error', "Employee policy record does not exist. To delete"); - // } - - // }else{ - // $this->myLogger->logme('error', "Employee policy data not found."); - // } - - // } else { - // $this->myLogger->logme('error', "Client Policy record does not exist. To delete"); - // } - // } else { - // $this->myLogger->logme('error', "Client Policy data not found."); - // } - - // // 6. Employee Model - // $employee_data = $this->employeeModel->where('client_id', $client_id)->findAll(); - // $this->myLogger->logme('error', "Employee data count : " . count($employee_data ?? [])); - - // if (!empty($employee_data)) { - - // $is_deleted = $this->employeeModel->where('client_id', $client_id)->delete(); - // if ($is_deleted) { - // $this->myLogger->logme('error', "Employee data removed successfully."); - // } else { - // $this->myLogger->logme('error', "Employee record does not exist. To delete"); - // } - // } else { - // $this->myLogger->logme('error', "Employee data not found."); - // } - - // // 7. Client Deposit Model - // $client_deposit_data = $this->clientDepositModel->where('client_id', $client_id)->findAll(); - // $this->myLogger->logme('error', "Client Deposit data : " . json_encode($client_deposit_data ?? [])); - - // if (!empty($client_deposit_data)) { - // $is_deleted = $this->clientDepositModel->where('client_id', $client_id)->delete(); - // if ($is_deleted) { - // $this->myLogger->logme('error', "Client Deposit data removed successfully."); - // } else { - // $this->myLogger->logme('error', "Client Deposit record does not exist. To delete"); - // } - // } else { - // $this->myLogger->logme('error', "Client Deposit data not found."); - // } - - // // 8. Policy Premium 1 Model - // $policy_premium1_data = $this->policyPremium1Model->where('client_id', $client_id)->findAll(); - // $this->myLogger->logme('error', "Policy Premium 1 data count : " . count($policy_premium1_data ?? [])); - - // if (!empty($policy_premium1_data)) { - // $is_deleted = $this->policyPremium1Model->where('client_id', $client_id)->delete(); - // if ($is_deleted) { - // $this->myLogger->logme('error', "Policy Premium 1 data removed successfully."); - // } else { - // $this->myLogger->logme('error', "Policy Premium 1 record does not exist. To delete"); - // } - // } else { - // $this->myLogger->logme('error', "Policy Premium 1 data not found."); - // } - - // // 9. Policy Premium 2 Model - // $policy_premium2_data = $this->policyPremium2Model->where('client_id', $client_id)->findAll(); - // $this->myLogger->logme('error', "Policy Premium 2 data count: " . count($policy_premium2_data ?? [])); - - // if (!empty($policy_premium2_data)) { - // $is_deleted = $this->policyPremium2Model->where('client_id', $client_id)->delete(); - // if ($is_deleted) { - // $this->myLogger->logme('error', "Policy Premium 2 data removed successfully."); - // } else { - // $this->myLogger->logme('error', "Policy Premium 2 record does not exist. To delete"); - // } - // } else { - // $this->myLogger->logme('error', "Policy Premium 2 data not found."); - // } - - // // 10. Notification Model - // $notification_data = $this->notificationModel->where('client_id', $client_id)->findAll(); - // $this->myLogger->logme('error', "Notification data : " . json_encode($notification_data ?? [])); - - // if (!empty($notification_data)) { - // $is_deleted = $this->notificationModel->where('client_id', $client_id)->delete(); - // if ($is_deleted) { - // $this->myLogger->logme('error', "Notification data removed successfully."); - // } else { - // $this->myLogger->logme('error', "Notification record does not exist. To delete"); - // } - // } else { - // $this->myLogger->logme('error', "Notification data not found."); - // } - - // // 11. CD Master Model - // $cd_master_data = $this->CDMasterModel->where('client_id', $client_id)->findAll(); - // $this->myLogger->logme('error', "CD Master data : " . json_encode($cd_master_data ?? [])); - - // if (!empty($cd_master_data)) { - // $is_deleted = $this->CDMasterModel->where('client_id', $client_id)->delete(); - // if ($is_deleted) { - // $this->myLogger->logme('error', "CD Master data removed successfully."); - // } else { - // $this->myLogger->logme('error', "CD Master record does not exist. To delete"); - // } - // } else { - // $this->myLogger->logme('error', "CD Master data not found."); - // } - - // // 12. Policy Transaction Model - // $policy_transaction_data = $this->policyTransactionModel->where('client_id', $client_id)->findAll(); - // $this->myLogger->logme('error', "Policy Transaction data : " . json_encode($policy_transaction_data ?? [])); - - // $pt_ids = array_column($policy_transaction_data, 'id') ?? []; - // $this->myLogger->logme('error', "Policy Transaction id count : " . count($pt_ids ?? [])); - - // if (!empty($policy_transaction_data)) { - // $is_deleted = $this->policyTransactionModel->where('client_id', $client_id)->delete(); - // if ($is_deleted) { - // $this->myLogger->logme('error', "Policy Transaction data removed successfully."); - - // if(!empty($pt_ids)){ - - // $pt_co_share_data = $this->PTCOShareDetailsModel->whereIn('pt_id', $pt_ids)->findAll(); - // $this->myLogger->logme('error', "PT CO Share data : " . json_encode($pt_co_share_data ?? [])); - - // $is_deleted = $this->PTCOShareDetailsModel->whereIn('pt_id', $pt_ids)->delete(); - // if ($is_deleted) { - // $this->myLogger->logme('error', "PT CO Share data removed successfully."); - // } else { - // $this->myLogger->logme('error', "PT CO Share record does not exist. To delete"); - // } - - // }else{ - // $this->myLogger->logme('error', "PT CO Share data not found."); - // } - - // } else { - // $this->myLogger->logme('error', "Policy Transaction record does not exist. To delete"); - // } - // } else { - // $this->myLogger->logme('error', "Policy Transaction data not found."); - // } - - // $this->myLogger->logme('error', "Wipe Demo Client function closed"); - // return $this->respond(['status' => true, 'message' => 'Demo client data wiped successfully'], 200); - // } - public function wipeDemoClient() { $this->myLogger->logme('error', "========================================"); diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php index 506b39a1..285207f4 100755 --- a/app/Controllers/EmpDataServiceController.php +++ b/app/Controllers/EmpDataServiceController.php @@ -1862,6 +1862,7 @@ class EmpDataServiceController extends BaseController $status = $file['status']; $batch_code = $file['batch_code']; $user_id = $file['created_by']; + $policy_issue_date = $file['policy_issue_date']; $insurer_id = $this->clientPolicyModel->where('id', $client_policy_id)->first(); @@ -2086,6 +2087,7 @@ class EmpDataServiceController extends BaseController 'no_of_dependent' => count($no_of_dependent ?? []) ?? null, 'base_premium' => $base_bremium_and_gst['base_premium'] ?? null, 'gst' => $base_bremium_and_gst['gst'] ?? null, + 'policy_issue_date' => $policy_issue_date ?? null, ]]); // $this->cashDepositCalculationForInception($depositeData); @@ -2417,6 +2419,7 @@ class EmpDataServiceController extends BaseController $batch_code = $file['batch_code']; $user_id = $file['created_by']; $event_type = $file['event_type']; + $policy_issue_date = $file['policy_issue_date']; $status_val = 'success'; @@ -2519,6 +2522,7 @@ class EmpDataServiceController extends BaseController 'endorsement_no' => $endorsement_id[0] ?? null, 'emp_count' => $emp_count ?? null, 'action_type' => $file['event_type'] ?? null, + 'policy_issue_date' => $policy_issue_date ?? null, ]]); @@ -2999,6 +3003,7 @@ class EmpDataServiceController extends BaseController $status = $file['status']; $batch_code = $file['batch_code']; $user_id = $file['created_by']; + $policy_issue_date = $file['policy_issue_date']; $insurer_id = $this->clientPolicyModel->where('id', $client_policy_id)->first(); @@ -3179,6 +3184,7 @@ class EmpDataServiceController extends BaseController 'no_of_dependent' => count($no_of_dependent ?? []) ?? null, 'base_premium' => $base_bremium_and_gst['base_premium'] ?? null, 'gst' => $base_bremium_and_gst['gst'] ?? null, + 'policy_issue_date' => $policy_issue_date ?? null, ]]); } @@ -3537,6 +3543,7 @@ class EmpDataServiceController extends BaseController $status = $file['status']; $batch_code = $file['batch_code']; $user_id = $file['created_by']; + $policy_issue_date = $file['policy_issue_date']; $insurer_id = $this->clientPolicyModel->where('id', $client_policy_id)->first(); @@ -3687,6 +3694,7 @@ class EmpDataServiceController extends BaseController 'no_of_dependent' => count($no_of_dependent ?? []) ?? null, 'base_premium' => $base_bremium_and_gst['base_premium'] ?? null, 'gst' => $base_bremium_and_gst['gst'] ?? null, + 'policy_issue_date' => $policy_issue_date ?? null, ]]); } @@ -4981,7 +4989,7 @@ class EmpDataServiceController extends BaseController 'policy_no' => $policy_data['policy_no'] ?? null, 'cd_ac_no' => $policy_data['cd_ac_no'] ?? null, 'cd_ac_pk' => $policy_data['cd_ac_pk'] ?? null, - 'policy_issue_date' => $policy_data['policy_start_date'] ?? null, + 'policy_issue_date' => $policy_data['policy_issue_date'] ?? null, 'policy_start_date' => $policy_data['policy_start_date'] ?? null, 'policy_end_date' => $policy_data['policy_end_date'] ?? null, 'data_received_date' => $policy_data['data_received_date'] ?? null, @@ -4992,7 +5000,7 @@ class EmpDataServiceController extends BaseController 'co_share' => $policy_data['co_share'] ?? 0, 'pre_payable_by' => $policy_data['pre_payable_by'] ?? 1, 'renewal_date' => $policy_data['policy_end_date'] ?? null, - 'month' => date('Y-m-01', strtotime($policy_data['policy_start_date'])) ?? null, + 'month' => date('Y-m-01', strtotime($policy_data['policy_issue_date'] ?? "")) ?? null, 'ct_type' => 1, 'is_cd_reduce_from_bds' => 0, 'client_type_id' => 0, diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php index 40e8af2b..5a5039f6 100755 --- a/app/Controllers/EmployeeController.php +++ b/app/Controllers/EmployeeController.php @@ -277,22 +277,28 @@ class EmployeeController extends AdminController $file_id = $this->fileModel->insert(['file_name' => $filename, 'client_id' => $client_id, 'policy_id' => $policy_id, 'created_by' => $loggedInUserID, 'status' => $status, 'action' => $action, 'client_branch_id' => $branch_id,'uploaded_by' => 1, 'hr_file_id' => $hr_file_id]); //here field policy_id have client_policy_id and not policy id from policy master $this->myLogger->logme("error", '{file_id} uploaded success', ['file_id' => $file_id]); - //start validation process - if($fileSize < 1) // if file size less than 1 - { - $empServiceController = new EmployeeServiceController(); - $result = $empServiceController->excelFileFormatValidation(['file_id' => $file_id]); - $this->myLogger->logme("error", '{file_id} is less than 1MB, validating on the fly', ['file_id' => $file_id]); - //endof validation process - if (isset($result['error_summary']) && count($result['error_summary'])) { - return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'file rejected with errors'], 200); - } - } - else //if file size greater than 1 add the file as job - { - $job_details = new Jobs(); - $r = Jobs::addJob(['job_name' => 'excelFileFormatValidation','payload' => ['file_id' => $file_id]]); + if ($action == "all") { + + $r = Jobs::addJob(['job_name' => 'excelMultieventFileFormateValidation', 'payload' => ['file_id' => $file_id]]); $this->myLogger->logme("error", '{file_id} is greather than 1MB, validating with job queue', ['file_id' => $file_id]); + + } else { + //start validation process + if ($fileSize < 1) // if file size less than 1 + { + $empServiceController = new EmployeeServiceController(); + $result = $empServiceController->excelFileFormatValidation(['file_id' => $file_id]); + $this->myLogger->logme("error", '{file_id} is less than 1MB, validating on the fly', ['file_id' => $file_id]); + //endof validation process + if (isset($result['error_summary']) && count($result['error_summary'])) { + return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'file rejected with errors'], 200); + } + } else //if file size greater than 1 add the file as job + { + $job_details = new Jobs(); + $r = Jobs::addJob(['job_name' => 'excelFileFormatValidation', 'payload' => ['file_id' => $file_id]]); + $this->myLogger->logme("error", '{file_id} is greather than 1MB, validating with job queue', ['file_id' => $file_id]); + } } return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => 'file upload success'], 200); @@ -303,7 +309,7 @@ class EmployeeController extends AdminController //for TPA/insurer upload $data['events'] = ['inception' => 'Inception (Employee + Dependents)', 'missed_inception' => 'Missed Inception (Employee + Dependents)', 'addition' => 'Addition (Employee + Dependents)', 'dependent_addition' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement']; //for inception upload - $data['actions'] = ['inception' => 'Inception (Employee + Dependents)', 'missed_inception' => 'Missed Inception (Employee + Dependents)', 'addition' => 'Addition (Employee + Dependents)', 'dependent_addition' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement']; + $data['actions'] = ['all' => 'All', 'inception' => 'Inception (Employee + Dependents)', 'missed_inception' => 'Missed Inception (Employee + Dependents)', 'addition' => 'Addition (Employee + Dependents)', 'dependent_addition' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement']; // $data['actions'] = ['inception' => 'Inception (Employee + Dependents)', 'missed_inception' => 'Missed Inception (Employee + Dependents)', 'addition' => 'Addition (Employee + Dependents)', 'dependent_addition' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement','enrollment' => 'Enrolment']; // $data['import_or_export'] = ['import' => 'Import', 'export' => 'Export']; @@ -469,6 +475,8 @@ class EmployeeController extends AdminController $filePath = ROOTPATH . 'public/sample_excel/sample_inception.xls'; }else if ($actionType == 'member_data') { $filePath = ROOTPATH . 'public/sample_excel/Sample_Member_Data.xlsx'; + }else if ($actionType == 'all') { + $filePath = ROOTPATH . 'public/sample_excel/sample_multievent_file.xlsx'; } // Check if the file exists @@ -515,6 +523,7 @@ class EmployeeController extends AdminController $client_branch_id = $this->request->getPost('client_branch_id'); $insurer_or_tpa = $this->request->getPost('insurer_or_tpa'); $actions = $this->request->getPost('action_type'); + $policy_issue_date = $this->request->getPost('policy_issue_date'); $client_data = $this->clientPolicyModel->getCliendDataForExcelFileName($client_policy_id); $file_name = generate_filename($client_data['short_name'], $event_type, $actions, $insurer_or_tpa, $client_data['policy_type'], $client_data['branch_code']); @@ -530,6 +539,13 @@ class EmployeeController extends AdminController 'actions' => $actions, 'file_name' => $file_name, ]; + + + $batch_data['policy_issue_date'] = (!empty($policy_issue_date) && strtotime($policy_issue_date) !== false) + ? change_date_format($policy_issue_date) + : null; + + if ($actions == 'export') { if ($event_type == 'inception' || $event_type == 'addition' || $event_type == 'dependent_addition' || $event_type == 'missed_inception' || ($event_type == 'MultipleEvents' && $insurer_or_tpa == 'tpa')) { diff --git a/app/Controllers/EmployeeMultiEventServiceController.php b/app/Controllers/EmployeeMultiEventServiceController.php new file mode 100644 index 00000000..a7519fea --- /dev/null +++ b/app/Controllers/EmployeeMultiEventServiceController.php @@ -0,0 +1,2871 @@ + [ + 'name' => 'Self', + 'gender' => 'M', + 'age_min' => 18, + 'age_max' => null + ], + 'spouse' => [ + 'name' => 'Spouse', + 'gender' => 'F', + 'age_min' => 18, + 'age_max' => null + ], + 'son' => [ + 'name' => 'Son', + 'gender' => 'M', + 'age_min' => null, + 'age_max' => 25 + ], + 'daughter' => [ + 'name' => 'Daughter', + 'gender' => 'F', + 'age_min' => null, + 'age_max' => 25 + ], + 'father' => [ + 'name' => 'Father', + 'gender' => 'M', + 'age_min' => 18, + 'age_max' => null + ], + 'mother' => [ + 'name' => 'Mother', + 'gender' => 'F', + 'age_min' => 18, + 'age_max' => null + ], + 'father-in-law' => [ + 'name' => 'Father in Law', + 'gender' => 'M', + 'age_min' => 18, + 'age_max' => null + ], + 'mother-in-law' => [ + 'name' => 'Mother in Law', + 'gender' => 'F', + 'age_min' => 18, + 'age_max' => null + ] + ]; + + protected $inception_excel_columns = [ + 'sno' => [ + 'col_idx' => 0, + 'col_cell_name' => 'A', + 'col_name' => 'S.No', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'emp_id' => [ + 'col_idx' => 1, + 'col_cell_name' => 'B', + 'col_name' => 'EMP ID', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'name_of_emp_dep' => [ + 'col_idx' => 2, + 'col_cell_name' => 'C', + 'col_name' => 'NAME OF EMP/DEP', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'dob' => [ + 'col_idx' => 3, + 'col_cell_name' => 'D', + 'col_name' => 'DOB', + 'is_mandatory' => ['I', 'A', 'DA'], + 'data_type' => 'str', + 'format' => 'd-M-Y', + 'allowed_values' => null, + 'custom' => 'check_dob_diff', + 'params' => ['row', 'relationship', 'default_age_ratio', 'policy_details'] + ], + 'gender' => [ + 'col_idx' => 4, + 'col_cell_name' => 'E', + 'col_name' => 'Gender', + 'is_mandatory' => ['I', 'A', 'DA'], + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => ['M', 'F'] + ], + 'relationship' => [ + 'col_idx' => 5, + 'col_cell_name' => 'F', + 'col_name' => 'RELATIONSHIP', + 'is_mandatory' => ['I', 'A', 'DA'], + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => ['Self', 'Spouse', 'Son', 'Daughter', 'Father', 'Mother', 'Father in Law', 'Mother in Law'], + 'custom' => 'check_relationship', + 'params' => ['row', 'relationship', 'policy_terms'] + ], + 'basic_cover_si' => [ + 'col_idx' => 6, + 'col_cell_name' => 'G', + 'col_name' => 'BASIC COVER SI', + 'is_mandatory' => null, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null, + 'custom' => 'check_si', + 'params' => ['row', 'policy_details', 'slab_details'] + ], + 'doc' => [ + 'col_idx' => 7, + 'col_cell_name' => 'H', + 'col_name' => 'Date of Coverage', + 'is_mandatory' => ['A', 'DA'], + 'data_type' => 'str', + 'format' => 'd-M-Y', + 'allowed_values' => null, + 'custom' => 'check_doc', + 'params' => ['row', 'policy_details'] + ], + 'doj' => [ + 'col_idx' => 8, + 'col_cell_name' => 'I', + 'col_name' => 'DOJ', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => 'd-M-Y', + 'allowed_values' => null, + 'custom' => 'check_doj', + 'params' => ['row'] + ], + 'basic_pay' => [ + 'col_idx' => 9, + 'col_cell_name' => 'J', + 'col_name' => 'Basic Pay', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null, + 'custom' => 'check_basic_pay', + 'params' => ['row', 'policy_terms', 'slab_details'] + ], + 'band_grade' => [ + 'col_idx' => 10, + 'col_cell_name' => 'K', + 'col_name' => 'Band/Grade', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null, + 'custom' => 'check_employee_band', + 'params' => ['row', 'policy_terms', 'slab_details'] + ], + 'designation' => [ + 'col_idx' => 11, + 'col_cell_name' => 'L', + 'col_name' => 'Designation', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'phone' => [ + 'col_idx' => 12, + 'col_cell_name' => 'M', + 'col_name' => 'Phone', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null, + 'custom' => 'check_dup_mobileno', + 'params' => ['row', 'existing_mobilenos'] + ], + 'email' => [ + 'col_idx' => 13, + 'col_cell_name' => 'N', + 'col_name' => 'Email', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null, + 'custom' => 'check_dup_email', + 'params' => ['row', 'existing_mobilenos'] + ], + 'pre_existing_ailments' => [ + 'col_idx' => 14, + 'col_cell_name' => 'O', + 'col_name' => 'PRE EXISTING AILMENTS', + 'is_mandatory' => ['I', 'A', 'DA'], + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => ['0', '1'] + ], + 'change_event' => [ + 'col_idx' => 15, + 'col_cell_name' => 'P', + 'col_name' => 'Change event', + 'is_mandatory' => ['A', 'DA', 'D'], + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'date_of_exit' => [ + 'col_idx' => 16, + 'col_cell_name' => 'Q', + 'col_name' => 'Date of exit', + 'is_mandatory' => ['D'], + 'data_type' => 'str', + 'format' => 'd-M-Y', + 'allowed_values' => null + ], + 'reason_for_exit' => [ + 'col_idx' => 17, + 'col_cell_name' => 'R', + 'col_name' => 'Reason for exit', + 'is_mandatory' => ['D'], + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'unit' => [ + 'col_idx' => 18, + 'col_cell_name' => 'S', + 'col_name' => 'Unit', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null, + 'custom' => 'check_unit', + 'params' => ['row', 'existing_units'] + ] + ]; + + protected $deletion_excel_columns = [ + 'sno' => [ + 'col_idx' => 0, + 'col_cell_name' => 'A', + 'col_name' => 'S.No', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'emp_id' => [ + 'col_idx' => 1, + 'col_cell_name' => 'B', + 'col_name' => 'EMP ID', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'name_of_emp_dep' => [ + 'col_idx' => 2, + 'col_cell_name' => 'C', + 'col_name' => 'NAME OF EMP/DEP', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'change_event' => [ + 'col_idx' => 3, + 'col_cell_name' => 'D', + 'col_name' => 'Change event', + 'is_mandatory' => ['D'], + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'date_of_exit' => [ + 'col_idx' => 4, + 'col_cell_name' => 'E', + 'col_name' => 'Date of exit', + 'is_mandatory' => ['D'], + 'data_type' => 'str', + 'format' => 'd-M-Y', + 'allowed_values' => null + ], + 'reason_for_exit' => [ + 'col_idx' => 5, + 'col_cell_name' => 'F', + 'col_name' => 'Reason for exit', + 'is_mandatory' => ['D'], + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'claim_status' => [ + 'col_idx' => 6, + 'col_cell_name' => 'G', + 'col_name' => 'Claim status', + 'is_mandatory' => ['D'], + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => [0, 1] + ] + ]; + + protected $correction_excel_columns = [ + 'sno' => [ + 'col_idx' => 0, + 'col_cell_name' => 'A', + 'col_name' => 'S.No', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'emp_id' => [ + 'col_idx' => 1, + 'col_cell_name' => 'B', + 'col_name' => 'EMP ID', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'name_of_emp_dep' => [ + 'col_idx' => 2, + 'col_cell_name' => 'C', + 'col_name' => 'NAME OF EMP/DEP', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'field' => [ + 'col_idx' => 3, + 'col_cell_name' => 'D', + 'col_name' => 'Field', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => ['name', 'dob', 'relationship', 'email_corporate'] + ], + 'value' => [ + 'col_idx' => 4, + 'col_cell_name' => 'E', + 'col_name' => 'Value', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'date_of_correction' => [ + 'col_idx' => 5, + 'col_cell_name' => 'F', + 'col_name' => 'Date of Correction', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => 'd-M-Y', + 'allowed_values' => null + ], + 'change_event' => [ + 'col_idx' => 6, + 'col_cell_name' => 'G', + 'col_name' => 'Change event', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'remarks' => [ + 'col_idx' => 7, + 'col_cell_name' => 'H', + 'col_name' => 'Remarks', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ] + ]; + + protected $si_enhance_excel_columns = [ + 'sno' => [ + 'col_idx' => 0, + 'col_cell_name' => 'A', + 'col_name' => 'S.No', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'emp_id' => [ + 'col_idx' => 1, + 'col_cell_name' => 'B', + 'col_name' => 'EMP ID', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'name_of_emp_dep' => [ + 'col_idx' => 2, + 'col_cell_name' => 'C', + 'col_name' => 'NAME OF EMP/DEP', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'augmented_si' => [ + 'col_idx' => 3, + 'col_cell_name' => 'D', + 'col_name' => 'Augmented SI', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null, + 'custom' => 'check_si', + 'params' => ['row', 'policy_details', 'slab_details'] + ], + 'date_of_enhancement' => [ + 'col_idx' => 4, + 'col_cell_name' => 'E', + 'col_name' => 'Date of SI Enhancement', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => 'd-M-Y', + 'allowed_values' => null + ] + ]; + + protected $enrollment_excel_columns = [ + 'sno' => [ + 'col_idx' => 0, + 'col_cell_name' => 'A', + 'col_name' => 'Sno', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'emp_id' => [ + 'col_idx' => 1, + 'col_cell_name' => 'B', + 'col_name' => 'Emp code', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'name_of_emp_dep' => [ + 'col_idx' => 2, + 'col_cell_name' => 'C', + 'col_name' => 'Name', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'doj' => [ + 'col_idx' => 3, + 'col_cell_name' => 'D', + 'col_name' => 'DOJ', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => 'd-M-Y', + 'allowed_values' => null, + 'custom' => null + ], + 'gender' => [ + 'col_idx' => 4, + 'col_cell_name' => 'E', + 'col_name' => 'Gender', + 'is_mandatory' => ['I', 'A', 'DA', 'E'], + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => ['M', 'F'] + ], + 'relationship' => [ + 'col_idx' => 5, + 'col_cell_name' => 'F', + 'col_name' => 'Relation', + 'is_mandatory' => ['I', 'A', 'DA', 'E'], + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null, + 'custom' => null + ], + 'dob' => [ + 'col_idx' => 6, + 'col_cell_name' => 'G', + 'col_name' => 'DOB', + 'is_mandatory' => ['I', 'A', 'DA'], + 'data_type' => 'str', + 'format' => 'd-M-Y', + 'allowed_values' => null, + 'custom' => null, + ], + 'email' => [ + 'col_idx' => 7, + 'col_cell_name' => 'H', + 'col_name' => 'Mail', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'phone' => [ + 'col_idx' => 8, + 'col_cell_name' => 'I', + 'col_name' => 'Mobile', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null, + 'custom' => null + ], + 'basic_cover_si' => [ + 'col_idx' => 9, + 'col_cell_name' => 'J', + 'col_name' => 'SI', + 'is_mandatory' => null, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null, + 'custom' => null + ], + 'band_grade' => [ + 'col_idx' => 10, + 'col_cell_name' => 'K', + 'col_name' => 'Grade', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null, + 'custom' => null + ], + 'basic_pay' => [ + 'col_idx' => 11, + 'col_cell_name' => 'L', + 'col_name' => 'Basic Pay', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null, + 'custom' => null + ], + 'unit' => [ + 'col_idx' => 12, + 'col_cell_name' => 'M', + 'col_name' => 'Unit', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'doc' => [ + 'col_idx' => 13, + 'col_cell_name' => 'N', + 'col_name' => 'DOC', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => 'd-M-Y', + 'allowed_values' => null + ] + ]; + + protected $incetion_to_enrollment_mapping = [ + 0 => 0, // inception: sno (S.No) -> enrollment: sno (Sno) + 1 => 1, // inception: emp_id (EMP ID) -> enrollment: emp_code (Emp_Code) + 2 => 2, // inception: name_of_emp_dep (NAME OF EMP/DEP) -> enrollment: name (NAME OF EMP/DEP) + 3 => 6, // inception: dob (DOB) -> enrollment: dob (DOB) + 4 => 4, // inception: gender (Gender) -> enrollment: gender (Gender) + 5 => 5, // inception: relationship (RELATIONSHIP) -> enrollment: relationship (Relation) + 6 => 9, // inception: basic_cover_si (BASIC COVER SI) -> enrollment: basic_cover_si (SI) + 7 => 13, // inception: doc (Date of Coverage) + 8 => 3, // inception: doj (DOJ) -> enrollment: doj (DOJ) + 9 => 11, // inception: basic_pay (Basic Pay) -> enrollment: basic_pay (Basic Pay) + 10 => 10, // inception: band_grade (Band/Grade) -> enrollment: band_grade (Grade) + 11 => null, // inception: designation (Designation) -> No match in enrollment + 12 => 8, // inception: phone (Phone) -> enrollment: phone (Mobile) + 13 => 7, // inception: email (Email) -> enrollment: email (Email) + 14 => null, // inception: pre_existing_ailments (PRE EXISTING AILMENTS) -> No match in enrollment + 15 => null, // inception: change_event (Change event) -> No match in enrollment + 16 => null, // inception: date_of_exit (Date of exit) -> No match in enrollment + 17 => null, // inception: reason_for_exit (Reason for exit) -> No match in enrollment + 18 => null // inception: reason_for_exit (Reason for exit) -> No match in enrollment + ]; + + protected $enrollment_to_inception_mapping = [ + 0 => 0, // enrollment: sno (Sno) -> inception: sno (S.No) + 1 => 1, // enrollment: emp_code (Emp_Code) -> inception: emp_id (EMP ID) + 2 => 2, // enrollment: name (NAME OF EMP/DEP) -> inception: name_of_emp_dep (NAME OF EMP/DEP) + 3 => 8, // enrollment: doj (DOJ) -> inception: doj (DOJ) + 4 => 4, // enrollment: gender (Gender) -> inception: gender (Gender) + 5 => 5, // enrollment: relationship (Relation) -> inception: relationship (RELATIONSHIP) + 6 => 3, // enrollment: dob (DOB) -> inception: dob (DOB) + 7 => 13, // enrollment: email (Email) -> inception: email (Email) + 8 => 12, // enrollment: phone (Mobile) -> inception: phone (Phone) + 9 => 6, // enrollment: basic_cover_si (SI) -> inception: basic_cover_si (BASIC COVER SI) + 10 => 10, // enrollment: band_grade (Grade) -> inception: band_grade (Band/Grade) + 11 => 9 // enrollment: basic_pay (Basic Pay) -> inception: basic_pay (Basic Pay) + ]; + + protected $multievent_excel_columns = [ + 'sno' => [ + 'col_idx' => 0, + 'col_cell_name' => 'A', + 'col_name' => 'S.No', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'emp_id' => [ + 'col_idx' => 1, + 'col_cell_name' => 'B', + 'col_name' => 'Emp ID', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'name_of_emp_dep' => [ + 'col_idx' => 2, + 'col_cell_name' => 'C', + 'col_name' => 'Name of Emp/Dep', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'dob' => [ + 'col_idx' => 3, + 'col_cell_name' => 'D', + 'col_name' => 'DOB', + 'is_mandatory' => false, + 'data_type' => 'date', + 'format' => 'Y-m-d', + 'allowed_values' => null + ], + 'gender' => [ + 'col_idx' => 4, + 'col_cell_name' => 'E', + 'col_name' => 'Gender', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => ['Male', 'Female', 'Other'] + ], + 'relationship' => [ + 'col_idx' => 5, + 'col_cell_name' => 'F', + 'col_name' => 'Relationship', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'basic_cover_si' => [ + 'col_idx' => 6, + 'col_cell_name' => 'G', + 'col_name' => 'Basic cover SI', + 'is_mandatory' => false, + 'data_type' => 'numeric', + 'format' => null, + 'allowed_values' => null + ], + 'doc' => [ + 'col_idx' => 7, + 'col_cell_name' => 'H', + 'col_name' => 'Date of Coverage', + 'is_mandatory' => false, + 'data_type' => 'date', + 'format' => 'Y-m-d', + 'allowed_values' => null + ], + 'doj' => [ + 'col_idx' => 8, + 'col_cell_name' => 'I', + 'col_name' => 'DOJ', + 'is_mandatory' => false, + 'data_type' => 'date', + 'format' => 'Y-m-d', + 'allowed_values' => null + ], + 'basic_pay' => [ + 'col_idx' => 9, + 'col_cell_name' => 'J', + 'col_name' => 'Basic Pay', + 'is_mandatory' => false, + 'data_type' => 'numeric', + 'format' => null, + 'allowed_values' => null + ], + 'band_grade' => [ + 'col_idx' => 10, + 'col_cell_name' => 'K', + 'col_name' => 'Band/Grade', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'designation' => [ + 'col_idx' => 11, + 'col_cell_name' => 'L', + 'col_name' => 'Designation', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'phone' => [ + 'col_idx' => 12, + 'col_cell_name' => 'M', + 'col_name' => 'Phone', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'email' => [ + 'col_idx' => 13, + 'col_cell_name' => 'N', + 'col_name' => 'Email', + 'is_mandatory' => false, + 'data_type' => 'email', + 'format' => null, + 'allowed_values' => null + ], + 'pre_existing_ailments' => [ + 'col_idx' => 14, + 'col_cell_name' => 'O', + 'col_name' => 'Pre Existing Ailments', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'date_of_exit' => [ + 'col_idx' => 15, + 'col_cell_name' => 'P', + 'col_name' => 'Date of Exit', + 'is_mandatory' => false, + 'data_type' => 'date', + 'format' => 'Y-m-d', + 'allowed_values' => null + ], + 'reason_for_exit' => [ + 'col_idx' => 16, + 'col_cell_name' => 'Q', + 'col_name' => 'Reason for Exit', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'claim_status' => [ + 'col_idx' => 17, + 'col_cell_name' => 'R', + 'col_name' => 'Claim Status', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => ['Approved', 'Rejected', 'Pending'] + ], + 'field' => [ + 'col_idx' => 18, + 'col_cell_name' => 'S', + 'col_name' => 'Correction Field', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'value' => [ + 'col_idx' => 19, + 'col_cell_name' => 'T', + 'col_name' => 'Correction Value', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'date_of_correction' => [ + 'col_idx' => 20, + 'col_cell_name' => 'U', + 'col_name' => 'Date of Correction', + 'is_mandatory' => false, + 'data_type' => 'date', + 'format' => 'Y-m-d', + 'allowed_values' => null + ], + 'remarks' => [ + 'col_idx' => 21, + 'col_cell_name' => 'V', + 'col_name' => 'Correction Remarks', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'augmented_si' => [ + 'col_idx' => 22, + 'col_cell_name' => 'W', + 'col_name' => 'Augmented SI', + 'is_mandatory' => false, + 'data_type' => 'numeric', + 'format' => null, + 'allowed_values' => null + ], + 'date_of_enhancement' => [ + 'col_idx' => 23, + 'col_cell_name' => 'X', + 'col_name' => 'Date of SI Enhancement', + 'is_mandatory' => false, + 'data_type' => 'date', + 'format' => 'Y-m-d', + 'allowed_values' => null + ], + 'change_event' => [ + 'col_idx' => 24, + 'col_cell_name' => 'Y', + 'col_name' => 'Change Event', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ], + 'unit' => [ + 'col_idx' => 25, + 'col_cell_name' => 'Z', + 'col_name' => 'Unit', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null + ] + ]; + + + + + public function __construct() + { + // helper('utility'); + set_session_context('EmployeeService'); + $this->myLogger = \Config\Services::mylogger(); + $this->employeeModel = new EmployeeModel(); + $this->employeePolicyModel = new EmployeePolicyModel(); + $this->clientModel = new ClientModel(); + $this->fileModel = new FileModel(); + $this->clientPolicyModel = new ClientPolicyModel(); + $this->policiesModel = new PolicesModel(); + $this->empEndorsementModel = new EmpEndorsementModel(); + $this->messageModel = new MessageModel(); + $this->clientBranchModel = new ClientBranchModel(); + $this->notificationModel = new NotificationModel(); + $this->insurerModel = new InsurerModel(); + } + + // ------------ FUNCTION FOR VADITATIONS HANDLERS ------------------------------------------------------------------------------------- + + public function excelMultieventFileFormateValidation($params) + { + helper('excel_util_helper'); + $file_id = $params['file_id']; + $file = $this->fileModel->find($file_id); + + if (!isset($file)) { + //file not found in DB + return array('status' => false, 'msg' => 'file not found in DB'); + } + $file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name']; + + //check physical file + if (!file_exists($file_name_with_path)) { + //file not found update status and reason + $message = "Physcial file not found"; + // echo $message; + $this->myLogger->logme('error', ($message . ' for file id ' . $file_id)); + $this->fileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update(); + return array('error_summary' => [5], 'error_data' => $message); + } + + $columns_to_check = $this->multievent_excel_columns; + $allowedHighestColumn = end($columns_to_check); + // print_rr($this->correction_excel_columns); die; + + $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path); + $worksheet = $spreadsheet->getActiveSheet(); + $highestRow = $worksheet->getHighestDataRow(); + $highestColumn = $worksheet->getHighestDataColumn(); + + $excel_data = $worksheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRow); + $excel_header = $excel_data[0]; + + //check columns order in excel + $column_count_res = check_columns_name($columns_to_check, $excel_header); + if (isset($column_count_res) && count($column_count_res)) { + //columns count mismatch + $message = implode("\n", $column_count_res); + // echo $message; + $this->myLogger->logme('error', ($message . ' for file id ' . $file_id)); + $this->fileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([6]), 'error_data' => $message])])->update(); + return array('error_summary' => [6], 'error_data' => $message); + } + + //check no of columns in excel + $total_defined_columns = count($columns_to_check); + $excel_columns = ($excel_data[0]); + $excel_columns_count = count($excel_columns); + + if ($total_defined_columns != $excel_columns_count) { + //columns count mismatch + $message = "File columns count mismatch. Expected - $total_defined_columns and received - $excel_columns_count"; + $this->myLogger->logme('error', ($message . ' for file id ' . $file_id)); + $this->fileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update(); + return array('error_summary' => [5], 'error_data' => $message); + } + + // $file_paths = [ + // 'inception' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/inception_1756269562.json', + // 'missed_inception' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/missed_inception_1756269562.json', + // 'addition' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/addition_1756269562.json', + // 'dependent_addition' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/dependent_addition_1756269562.json', + // 'deletion' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/deletion_1756269562.json', + // 'correction' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/correction_1756269562.json', + // 'si_enhancement' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/si_enhancement_1756269562.json', + // ]; + //construct and save as a .JSON file to the tmp folder and return the file paths + $file_paths = $this->constructMultiEventData($params); + $params['multi_event_file_paths'] = $file_paths; + // print_rr($file_paths); + + $error = []; + + //inception + if(isset($file_paths['inception']) && $file_paths['inception'] != "" && $file_paths['inception'] != null){ + $params["action"] = "inception"; + $params["file_path"] = $file_paths['inception']; + $error[] = $this->excelFileFormatValidation($params); + } + + //addition + if(isset($file_paths['addition']) && $file_paths['addition'] != "" && $file_paths['addition'] != null){ + $params["action"] = "addition"; + $params["file_path"] = $file_paths['addition']; + $error[] = $this->excelFileFormatValidation($params); + } + + //dependent_addition + if(isset($file_paths['dependent_addition']) && $file_paths['dependent_addition'] != "" && $file_paths['dependent_addition'] != null){ + $params["action"] = "dependent_addition"; + $params["file_path"] = $file_paths['dependent_addition']; + $error[] = $this->excelFileFormatValidation($params); + } + + //deletion + if(isset($file_paths['deletion']) && $file_paths['deletion'] != "" && $file_paths['deletion'] != null){ + $params["action"] = "deletion"; + $params["file_path"] = $file_paths['deletion']; + $error[] = $this->excelFileFormatValidation($params); + } + + //correction + if(isset($file_paths['correction']) && $file_paths['correction'] != "" && $file_paths['correction'] != null){ + $params["action"] = "correction"; + $params["file_path"] = $file_paths['correction']; + $error[] = $this->excelFileFormatValidation($params); + } + + //si_enhancement + if(isset($file_paths['si_enhancement']) && $file_paths['si_enhancement'] != "" && $file_paths['si_enhancement'] != null){ + $params["action"] = "si_enhancement"; + $params["file_path"] = $file_paths['si_enhancement']; + $error[] = $this->excelFileFormatValidation($params); + } + + //missed_inception + if(isset($file_paths['missed_inception']) && $file_paths['missed_inception'] != "" && $file_paths['missed_inception'] != null){ + $params["action"] = "missed_inception"; + $params["file_path"] = $file_paths['missed_inception']; + $error[] = $this->excelFileFormatValidation($params); + } + + $error_type = 1; + $error = $this->mergeErrors($error, $error_type); + // print_rr($error);die; + + if (isset($error['error_data']) && count($error['error_data']) == 0) { + $r = Jobs::addJob(['job_name' => 'excelMultieventFileDataValidation', 'payload' => $params]); + } else { + + // $error['error_summary'] = array_count_values($error['error_summary']); + $status = 'failed'; + $failure_reason = ((json_encode($error))); + $this->fileModel->where('id', $file_id)->set(['status' => $status, 'reason' => $failure_reason])->update(); + $this->myLogger->logme("error", 'excel Multi event File Formate Validation {file_id} uploaded failed', ['file_id' => $file_id]); + + //set failure msg to pull notifications + $this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'failure')); + + // remove the file form the folder after failed the function + $this->unlinkFiles($file_paths); + } + + return ($error); + + } + + public function excelMultieventFileDataValidation($params) + { + helper('excel_util_helper'); + $file_id = $params['file_id']; + $file = $this->fileModel->find($file_id); + + if (!isset($file)) { + //file not found in DB + return array('status' => false, 'msg' => 'file not found in DB'); + } + + // $file_paths = [ + // 'inception' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/inception_1756269562.json', + // 'missed_inception' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/missed_inception_1756269562.json', + // 'addition' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/addition_1756269562.json', + // 'dependent_addition' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/dependent_addition_1756269562.json', + // 'deletion' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/deletion_1756269562.json', + // 'correction' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/correction_1756269562.json', + // 'si_enhancement' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/si_enhancement_1756269562.json', + // ]; + // set the file paths + $file_paths = $params['multi_event_file_paths']; + // print_rr($file_paths); + + $error = []; + + //inception + if (isset($file_paths['inception']) && $file_paths['inception'] != "" && $file_paths['inception'] != null) { + $params["action"] = "inception"; + $params["file_path"] = $file_paths['inception']; + $error[] = $this->excelFileDataValidation($params); + } + + //addition + if (isset($file_paths['addition']) && $file_paths['addition'] != "" && $file_paths['addition'] != null) { + $params["action"] = "addition"; + $params["file_path"] = $file_paths['addition']; + $error[] = $this->excelFileDataValidation($params); + } + + //dependent_addition + if (isset($file_paths['dependent_addition']) && $file_paths['dependent_addition'] != "" && $file_paths['dependent_addition'] != null) { + $params["action"] = "dependent_addition"; + $params["file_path"] = $file_paths['dependent_addition']; + $error[] = $this->excelFileDataValidation($params); + } + + //deletion + if (isset($file_paths['deletion']) && $file_paths['deletion'] != "" && $file_paths['deletion'] != null) { + $params["action"] = "deletion"; + $params["file_path"] = $file_paths['deletion']; + $error[] = $this->excelFileDataValidation($params); + } + + //correction + if (isset($file_paths['correction']) && $file_paths['correction'] != "" && $file_paths['correction'] != null) { + $params["action"] = "correction"; + $params["file_path"] = $file_paths['correction']; + $error[] = $this->excelFileDataValidation($params); + } + + //si_enhancement + if (isset($file_paths['si_enhancement']) && $file_paths['si_enhancement'] != "" && $file_paths['si_enhancement'] != null) { + $params["action"] = "si_enhancement"; + $params["file_path"] = $file_paths['si_enhancement']; + $error[] = $this->excelFileDataValidation($params); + } + + //missed_inception + if (isset($file_paths['missed_inception']) && $file_paths['missed_inception'] != "" && $file_paths['missed_inception'] != null) { + $params["action"] = "missed_inception"; + $params["file_path"] = $file_paths['missed_inception']; + $error[] = $this->excelFileDataValidation($params); + } + + $error_type = 2; + $error = $this->mergeErrors($error, $error_type); + // print_rr($error);die; + + if (isset($error['error_data']) && count($error['error_data']) == 0) { + $r = Jobs::addJob(['job_name' => 'excelMultieventFileOnBoard', 'payload' => $params]); + } else { + + // $error['error_summary'] = array_count_values($error['error_summary']); + $status = 'failed'; + $failure_reason = ((json_encode($error))); + $this->fileModel->where('id', $file_id)->set(['status' => $status, 'reason' => $failure_reason])->update(); + $this->myLogger->logme("error", 'excel Multi event File Data Validation {file_id} uploaded failed', ['file_id' => $file_id]); + + //set failure msg to pull notifications + $this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'failure')); + } + + return ($error); + } + + public function excelMultieventFileOnBoard($params) + { + helper('excel_util_helper'); + + $file_id = $params['file_id']; + $file = $this->fileModel->find($file_id); + + if (!isset($file)) { + //file not found in DB + return array('status' => false, 'msg' => 'file not found in DB'); + } + + // $file_paths = [ + // 'inception' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/inception_1756269562.json', + // 'missed_inception' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/missed_inception_1756269562.json', + // 'addition' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/addition_1756269562.json', + // 'dependent_addition' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/dependent_addition_1756269562.json', + // 'deletion' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/deletion_1756269562.json', + // 'correction' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/correction_1756269562.json', + // 'si_enhancement' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/si_enhancement_1756269562.json', + // ]; + $file_paths = $params['multi_event_file_paths']; + // print_rr($file_paths); + + $error = []; + + //inception + if (isset($file_paths['inception']) && $file_paths['inception'] != "" && $file_paths['inception'] != null) { + $params["action"] = "inception"; + $params["file_path"] = $file_paths['inception']; + $error['inception'] = $this->employeesOnboardPreprocess($params); + } + + //addition + if (isset($file_paths['addition']) && $file_paths['addition'] != "" && $file_paths['addition'] != null) { + $params["action"] = "addition"; + $params["file_path"] = $file_paths['addition']; + $error['addition'] = $this->employeesOnboardPreprocess($params); + } + + //dependent_addition + if (isset($file_paths['dependent_addition']) && $file_paths['dependent_addition'] != "" && $file_paths['dependent_addition'] != null) { + $params["action"] = "dependent_addition"; + $params["file_path"] = $file_paths['dependent_addition']; + $error['dependent_addition'] = $this->employeesOnboardPreprocess($params); + } + + //missed_inception + if (isset($file_paths['missed_inception']) && $file_paths['missed_inception'] != "" && $file_paths['missed_inception'] != null) { + $params["action"] = "missed_inception"; + $params["file_path"] = $file_paths['missed_inception']; + $error['missed_inception'] = $this->employeesOnboardPreprocess($params); + } + + //deletion + if (isset($file_paths['deletion']) && $file_paths['deletion'] != "" && $file_paths['deletion'] != null) { + $params["action"] = "deletion"; + $params["file_path"] = $file_paths['deletion']; + $error['deletion'] = $this->employeeDisembark($params); + } + + //correction + if (isset($file_paths['correction']) && $file_paths['correction'] != "" && $file_paths['correction'] != null) { + $params["action"] = "correction"; + $params["file_path"] = $file_paths['correction']; + $error['correction'] = $this->employeesCorrectionProcess($params); + } + + //si_enhancement + if (isset($file_paths['si_enhancement']) && $file_paths['si_enhancement'] != "" && $file_paths['si_enhancement'] != null) { + $params["action"] = "si_enhancement"; + $params["file_path"] = $file_paths['si_enhancement']; + $error['si_enhancement'] = $this->employeesSIEnhanceProcess($params); + } + + $this->fileModel->where('id', $file_id)->set(['status' => 'success', 'reason' => ''])->update(); + $this->myLogger->logme("error", $file['action'].': {file_id} uploaded success', ['file_id' => $file_id]); + $this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'success')); + + //After insert the success than remove the TEMP JSON files + // $this->unlinkFiles($params['multi_event_file_paths']); + + return ($error); + } + + // ------------ FUNCTION FOR VADITATIONS ------------------------------------------------------------------------------------- + + public function excelFileFormatValidation($params) + { + helper('excel_util_helper'); + // dd($params); + //get file name + $file_id = $params['file_id']; + $file = $this->fileModel->find($file_id); + $file['action'] = $params['action']; + // dd($file); + + $return = []; + if (!isset($file)) { + //file not found in DB + return array('status' => false, 'msg' => 'file not found in DB'); + } + + $file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name']; + + //check physical file + if (!file_exists($file_name_with_path)) { + //file not found update status and reason + $message = "Physcial file not found"; + $this->myLogger->logme('error', ($message . ' for file id ' . $file_id)); + $this->fileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update(); + return array('error_summary' => [5], 'error_data' => $message); + } + + //start validation process + $columns_to_check = []; + if ($file['action'] == 'inception') { + $columns_to_check = $this->inception_excel_columns; + } + if ($file['action'] == 'addition') { + $columns_to_check = $this->inception_excel_columns; + } + if ($file['action'] == 'dependent_addition') { + $columns_to_check = $this->inception_excel_columns; + } + if ($file['action'] == 'deletion') { + $columns_to_check = $this->deletion_excel_columns; + } + if ($file['action'] == 'correction') { + $columns_to_check = $this->correction_excel_columns; + } + if ($file['action'] == 'si_enhancement') { + $columns_to_check = $this->si_enhance_excel_columns; + } + if ($file['action'] == 'enrollment') { + $columns_to_check = $this->enrollment_excel_columns; + } + if ($file['action'] == 'missed_inception') { + $columns_to_check = $this->inception_excel_columns; + } + + $columns_to_check = $this->syncColIndex($this->multievent_excel_columns, $columns_to_check); + // print_rr($columns_to_check); + + $result = ['error_type' => 1, 'error_summary' => [], 'error_data' => []]; + $keys = array_keys($columns_to_check); + + $excel_data = json_decode(file_get_contents($params['file_path'] ?? []), true); + // dd($excel_data); + + // get policy and rack details + $policy_details = $this->clientPolicyModel->getPolicyDetails($file['client_id'], $file['policy_id']); + $policy_terms = json_decode($policy_details[0]->policy_terms); + $policy_terms = (array) $policy_terms; // convert obj to array + $default_age_ratio = isset($policy_terms['age_ratio']) ? json_decode(json_encode($policy_terms['age_ratio']), true) : []; + + //get policy slab rates + $slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($file['policy_id'], $file['client_id']); + // dd($slab_details); + + //remove header + unset($excel_data[0]); + $relationship = $this->general_relationships; + //get exisiting mobilr nos + $existing_mobilenos = $this->employeePolicyModel->getExisitingMobileNos(client_policy_id: $file['policy_id']); + //get existing units in the current branch + $existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $file['client_id'], client_branch_id: $file['client_branch_id']); + // dd($excel_data); + foreach ($excel_data as $row_key => $row) { + //define row wise action/event in temporary variable + $current_column_action = null; + if ($file['action'] == 'inception') { + $current_column_action = 'I'; + } else if ($file['action'] == 'addition') { + $current_column_action = 'A'; + } else if ($file['action'] == 'dependent_addition') { + $current_column_action = 'DA'; + } else if ($file['action'] == 'deletion') { + $current_column_action = 'D'; + } else if ($file['action'] == 'correction') { + $current_column_action = 'C'; + } else if ($file['action'] == 'si_enhancement') { + $current_column_action = 'SI'; + } else if ($file['action'] == 'enrollment') { + $current_column_action = 'I'; + } else if ($file['action'] == 'missed_inception') { + $current_column_action = 'MI'; + } + //1. avoid empty rows + if (check_row_is_empty_or_null($row)) { + break; + } + // Kint::dump($keys); + if ($file['action'] == 'enrollment') { + $row = transform_enrollment_row_to_inception_row($row); + $columns_to_check = $this->inception_excel_columns; + $keys = array_keys($columns_to_check); + $enrollment_columns_to_check = $this->enrollment_excel_columns; + $enrollment_keys = array_keys($enrollment_columns_to_check); + } + + //iterate each row for columns validations + foreach ($row as $col_key => $col) { + $is_mandatory = $columns_to_check[$keys[$col_key]]['is_mandatory']; + $format = $columns_to_check[$keys[$col_key]]['format']; + $allowed_values = $columns_to_check[$keys[$col_key]]['allowed_values']; + $custom_function = isset($columns_to_check[$keys[$col_key]]['custom']) ? $columns_to_check[$keys[$col_key]]['custom'] : null; + $binding_params = isset($columns_to_check[$keys[$col_key]]['params']) ? $columns_to_check[$keys[$col_key]]['params'] : null; + + $column_dispaly_name = $columns_to_check[$keys[$col_key]]['col_name']; + $column_index = $columns_to_check[$keys[$col_key]]['col_idx']; + $column_cell = $columns_to_check[$keys[$col_key]]['col_cell_name']; + if ($file['action'] == 'enrollment') { + if (isset($enrollment_keys[$this->incetion_to_enrollment_mapping[$col_key]]) && $enrollment_keys[$this->incetion_to_enrollment_mapping[$col_key]] != null && $enrollment_keys[$this->incetion_to_enrollment_mapping[$col_key]] != "") { + $column_dispaly_name = $enrollment_columns_to_check[$enrollment_keys[$this->incetion_to_enrollment_mapping[$col_key]]]['col_name']; + $column_index = $enrollment_columns_to_check[$enrollment_keys[$this->incetion_to_enrollment_mapping[$col_key]]]['col_idx']; + $column_cell = $enrollment_columns_to_check[$enrollment_keys[$this->incetion_to_enrollment_mapping[$col_key]]]['col_cell_name']; + } + } + + $row['current_action'] = $current_column_action; + + //mandatory check + if (is_bool($is_mandatory) && $is_mandatory === true) { + if ($col == "" || $col == NULL) { + array_push($result['error_summary'], 1); //push error code for summary + $result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name + $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index + $result['error_data'][$row_key][$keys[$col_key]]['error'][] = 'Value is mandatory'; //push exact error desc + } + } + + //if is_mandatory is array (action based mandatory check) + if ($current_column_action != null && is_array($is_mandatory) && in_array(strtoupper(trim($current_column_action)), $is_mandatory)) { + $allowed_actions = $columns_to_check[$keys[$col_key]]['is_mandatory']; + if ($col == "" || $col == NULL) { + array_push($result['error_summary'], 1); + $result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name + $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index + $result['error_data'][$row_key][$keys[$col_key]]['error'][] = 'Value is mandatory for this action/event'; + } + } + + //format check + if (isset($format)) { + $format_error = check_excel_date_format($col, $format); + if (!$format_error['status']) { + array_push($result['error_summary'], 2); + $result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name + $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index + $result['error_data'][$row_key][$keys[$col_key]]['error'][] = $format_error['error']; + } + } + // Kint::dump($is_mandatory); + //allowed values check + if (($is_mandatory === true && isset($allowed_values) && is_array($allowed_values)) || (is_array($is_mandatory) && (isset($allowed_values) && is_array($allowed_values)))) { + // print_r($allowed_values); + // dd($col); + if (!in_array((trim($col)), $allowed_values)) { + array_push($result['error_summary'], 3); + $result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name + $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index + $result['error_data'][$row_key][$keys[$col_key]]['error'][] = "Value not allowed: Expected " . implode(",", $allowed_values) . " and received $col"; + } + } + + //custom function check + if (isset($custom_function)) { + //convert string params into PHP variables + // Create an array of variables to pass custom helper funcitons + $param_values = []; + foreach ($binding_params as $bkey => $bparam) { + $param_values[] = ($$bparam); + } + // dd(($param_values));//die(); + $res = call_user_func_array($custom_function, $param_values); + // print_r($res['status']);die(); + if ($res['status'] === false) { + array_push($result['error_summary'], 4); + $result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name + $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index + $result['error_data'][$row_key][$keys[$col_key]]['error'][] = $res['error']; + } + } + } //col foreach + // break; + } //row foreach + + // dd($result); + if (isset($result['error_summary']) && count($result['error_summary'])) { + $result['error_summary'] = array_count_values($result['error_summary']); + $this->myLogger->logme("error", '{file_id} uploaded failed', ['file_id' => $file_id]); + } + + return $result; + } + + public function excelFileDataValidation($params) + { + helper('excel_util_helper'); + + //get file name + $file_id = $params['file_id']; + $file = $this->fileModel->find($file_id); + $file['action'] = $params['action']; + // Kint::dump($file); + + $return = []; + if (!isset($file)) { + //file not found in DB + return array('status' => false, 'msg' => 'file not found in DB'); + } + + $columns_to_check = []; + if ($file['action'] == 'inception') { + $columns_to_check = $this->inception_excel_columns; + } + if ($file['action'] == 'addition') { + $columns_to_check = $this->inception_excel_columns; + } + if ($file['action'] == 'dependent_addition') { + $columns_to_check = $this->inception_excel_columns; + } + if ($file['action'] == 'deletion') { + $columns_to_check = $this->deletion_excel_columns; + } + if ($file['action'] == 'correction') { + $columns_to_check = $this->correction_excel_columns; + } + if ($file['action'] == 'si_enhancement') { + $columns_to_check = $this->si_enhance_excel_columns; + } + if ($file['action'] == 'enrollment') { + $columns_to_check = $this->enrollment_excel_columns; + } + if ($file['action'] == 'missed_inception') { + $columns_to_check = $this->inception_excel_columns; + } + + $columns_to_check = $this->syncColIndex($this->multievent_excel_columns, $columns_to_check); + // print_rr($columns_to_check); + + // get policy and rack details + $policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'], $file['policy_id']); + $policy_details = (array)$policy_terms[0]; + $is_lgbtq = $policy_details['is_lgbtq']; + + $policy_terms = json_decode($policy_terms[0]->policy_terms); + $policy_terms = (array) $policy_terms; // convert obj to array + // dd($policy_terms); + + $result = ['error_type' => 2, 'error_summary' => [], 'error_data' => []]; + $keys = array_keys($columns_to_check); + $allowedHighestColumn = end($columns_to_check); + + //get excel data + $excel_data = json_decode(file_get_contents($params['file_path'] ?? []), true); + // Kint::dump($excel_data); + + //remove header + unset($excel_data[0]); + $relationship = $this->general_relationships; + + + if (in_array($file['action'], ['inception', 'missed_inception', 'addition', 'dependent_addition', 'deletion', 'correction', 'si_enhancement', 'enrollment'])) // the below funcitons are only for I,DA,A + { + $employee_data_group_by_family = data_group_by_family($excel_data, 'excel', ($file['action'] == 'enrollment' ? 'enrollment' : '')); + // dd($employee_data_group_by_family); + $is_self_available_in_policy_terms = false; + if ($policy_details['policy_type_id'] == 3) // GMC parents + { + $temp = $policy_terms['family_floaters']; + $temp = is_array($temp) ? $temp : (is_object($temp) ? (array)$temp : []); + + $is_self_available_in_policy_terms = isset($temp['self']) && $temp['self'] == 1 ? true : false; + // Kint::dump($temp['self']); + // dd($is_self_available_in_policy_terms); + } + // dd($employee_data_group_by_family); + foreach ($employee_data_group_by_family as $emp_id => $family) { + + //if action is DA then get all familiy members,transfrom them into excel array, addd data source as db or excel + if ($file['action'] == 'dependent_addition') { + $existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(emp_code: $emp_id, client_id: $file['client_id'], client_policy_id: $file['policy_id'], emp_status: ['active'], policy_status: ['active'], client_branch_id: [$file['client_branch_id']]); + // dd(($existing_famility_details)); + //transsform familiy details from db columns to exxcel row with column indexs for checking remaining functionalitites + $existing_famility_details = transform_db_data_to_excel($existing_famility_details, $file); + // dd(array_keys($existing_famility_details[0])); + $family = array_merge($family, $existing_famility_details); + // kint::dump($family); + $family = data_group_by_family($family)[$emp_id]; // reason to call this again bring self to first index of the array + } + $firstNonTemp = null; + + foreach ($family as $fam) { + if (!isset($fam['temp'])) { + $firstNonTemp = $fam; + break; + } + } + // kint::dump($family);//die(); + + //check name dup within a family + if ($file['action'] == 'inception' || $file['action'] == 'missed_inception' || $file['action'] == 'addition' || $file['action'] == 'dependent_addition' || $file['action'] == 'enrollment') { + $res = name_dup_check_within_family($family, $file['action']); //in both file data & DB data + // dd($res); + if (count($res)) { + foreach ($res as $k => $rowid) { + array_push($result['error_summary'], 7); // dup entry in excel file + $result['error_data'][$rowid]['name_of_emp_dep']['error'][] = "Twofold Name found within family"; + } + } + } + + if ((($file['action'] == 'inception' || $file['action'] == 'missed_inception' || $file['action'] == 'addition' || $file['action'] == 'enrollment') || ($policy_details['policy_type_id'] == 3 && $is_self_available_in_policy_terms)) && ($policy_details['base_policy'] == null || $policy_details['base_policy'] == 0)) // 3 is GMC parents dep addon) + { + $res = check_self_available_in_family($family, $file['action']); + if (!$res['is_self_found']) { + array_push($result['error_summary'], 14); // Self not found + $result['error_data'][$res['row_id']]['sno']['error'][] = "Self not found in uploaded file"; + } + } + + //check self avaialbe either same policy DB level(i.e.) gMC parents + if ($file['action'] == 'dependent_addition' || ($policy_details['policy_type_id'] == 3 && !$is_self_available_in_policy_terms)) // 3 is GMC parents as base policy not as dep addon) + { + $self_details = $this->employeeModel->getEmpFamilybyEmpCode(emp_code: trim($emp_id), client_id: $file['client_id'], emp_status: ['active', 'draft', 'enrolled'], policy_status: ['active', 'draft', 'enrolled'], client_branch_id: [$file['client_branch_id']], relationship: ['self']); + // dd($self_details); + if (!count($self_details)) { + array_push($result['error_summary'], 14); // Self not found + $result['error_data'][$firstNonTemp[0]]['sno']['error'][] = "Self not found in Database"; + } + } + + + if ($file['action'] == 'dependent_addition' || $file['action'] == 'addition' || $file['action'] == 'inception' || $file['action'] == 'missed_inception' || $file['action'] == 'enrollment') { + $res = check_dependent_conflict($family, $policy_terms, $file['action'], $is_lgbtq); + // Kint::dump($res); + if (!$res['status']) { + foreach ($res['error_data'] as $key => $value) { + array_push($result['error_summary'], $value['code']); + $result['error_data'][$value['row_id']][($value['col_name'])]['error'][] = $value['msg']; + } + } + } + + //check dup with empid and name with db + $res = name_and_empid_check_in_db($family, $file); + // Kint::dump($res['del']); + // echo '
'; + // print_r($res); + if (count($res['del'])) { + foreach ($res['del'] as $k => $rowid) { + array_push($result['error_summary'], 10); //record not avail for deletion + $result['error_data'][$rowid]['name_of_emp_dep']['error'][] = "Record Not found "; + } + } + if (count($res['i'])) { + foreach ($res['i'] as $k => $rowid) { + array_push($result['error_summary'], 9); //dup entry + $result['error_data'][$rowid]['name_of_emp_dep']['error'][] = "Record already exists"; + } + } + } // end of foreach + } // end of if current action I,DA,A + + // return $result; + if (isset($result['error_summary']) && count($result['error_summary'])) { + + $result['error_summary'] = array_count_values($result['error_summary']); + $status = 'failed'; + $failure_reason = ((json_encode($result))); + $this->fileModel->where('id', $file_id)->set(['status' => $status, 'reason' => $failure_reason])->update(); + $this->myLogger->logme("error", '{file_id} uploaded failed', ['file_id' => $file_id]); + + //set failure msg to pull notifications + $this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'failure')); + + } + + return $result; + } + + // ------------ FUNCTION FOR ON-BOARD PROCESS ------------------------------------------------------------------------------------- + + // calculate data points and premium + public function employeesOnboardPreprocess($params) + { + helper('excel_util_helper'); + // dd($params); + if (isset($params['file_id'])) //handle data from excel to inception + { + //get file name + $file_id = $params['file_id']; + $file = $this->fileModel->find($file_id); + $file['action'] = $params['action']; + // dd($file); + $return = []; + if (!isset($file)) { + //file not found in DB + return array('status' => false, 'msg' => 'file not found in DB'); + } + + // $file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name']; + + // //check physical file + // if (!file_exists($file_name_with_path)) { + // //file not found update status and reason + // $message = "Physical file not found"; + // // echo $message; + // $this->myLogger->logme('error', ($message . ' for file id ' . $file_id)); + // $this->fileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update(); + // return array('error_summary' => [5], 'error_data' => $message); + // } + + $columns_to_check = []; + if ($file['action'] == 'inception') { + $columns_to_check = $this->inception_excel_columns; + } + if ($file['action'] == 'addition') { + $columns_to_check = $this->inception_excel_columns; + } + if ($file['action'] == 'dependent_addition') { + $columns_to_check = $this->inception_excel_columns; + } + if ($file['action'] == 'deletion') { + $columns_to_check = $this->deletion_excel_columns; + } + if ($file['action'] == 'correction') { + $columns_to_check = $this->correction_excel_columns; + } + if ($file['action'] == 'si_enhancement') { + $columns_to_check = $this->si_enhance_excel_columns; + } + if ($file['action'] == 'missed_inception') { + $columns_to_check = $this->inception_excel_columns; + } + + // get policy and rack details + $policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'], $file['policy_id']); + $policy_terms = (array) $policy_terms[0]; // convert obj to array + // $policy_terms = json_decode($policy_terms[0]->policy_terms); + + // dd($policy_terms); + + //get excel data + // $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path); + // $sheet = $spreadsheet->getActiveSheet(); + // $highestRowAndColumn = $sheet->getHighestRowAndColumn(); + // $allowedHighestColumn = end($columns_to_check); + // $excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']); + $excel_data = json_decode(file_get_contents($params['file_path'] ?? []), true); + unset($excel_data[0]); + + + //get policy slab rates + $slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($file['policy_id'], $file['client_id']); + // dd($slab_details); + //get existing units in the current branch + $existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $file['client_id'], client_branch_id: $file['client_branch_id']); + + $employee_data_group_by_family = data_group_by_family($excel_data); + // dd($employee_data_group_by_family); + foreach ($employee_data_group_by_family as $emp_id => $family) { + + //if action is DA then get all familiy members,transfrom them into excel array, addd data source as db or excel + if ($file['action'] == 'dependent_addition') { + $existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(emp_code: $emp_id, client_id: $file['client_id'], client_policy_id: $file['policy_id'], emp_status: ['active'], policy_status: ['active'], client_branch_id: [$file['client_branch_id']]); + // dd($existing_famility_details); + //transsform familiy details from db columns to exxcel row with column indexs for checking remaining functionalitites + $existing_famility_details = transform_db_data_to_excel($existing_famility_details, $file); + // Kint::dump($existing_famility_details); + $family = array_merge($family, $existing_famility_details); + $family = data_group_by_family($family)[$emp_id]; // reason to call this again is bring self to first index of the array + // dd($family); + } + + // Kint::dump($family); + $data = calculate_premium_new(family_data: $family, policy_terms: $policy_terms, slab_details: $slab_details, fileArr: $file, existing_units: $existing_units); + // dd($data); + $employee_data_group_by_family[$emp_id] = $data; + $this->employeesOnboardProcess(['familiy_data' => $data, 'file' => $file]); + } + + // $this->fileModel->where('id', $file_id)->set(['status' => 'success', 'reason' => ''])->update(); + $this->myLogger->logme("error", $file['action'].': {file_id} uploaded success', ['file_id' => $file_id]); + // $this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'success')); + } else if (isset($params['client_policy_id'])) //handle data from enrollment to inception + { + $client_policy_id = $params['client_policy_id']; + //get client id + $client_id = ($this->clientPolicyModel->select('client_id')->find($client_policy_id))['client_id']; + // dd($client_id); + + // get policy and rack details + $policy_terms = $this->clientPolicyModel->getPolicyDetails($client_id, $client_policy_id); + $policy_terms = (array) $policy_terms[0]; // convert obj to array + + //get policy slab rates + $slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($client_policy_id, $client_id); + + $existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(client_id: $client_id, client_policy_id: $client_policy_id, emp_status: ['enrolled'], policy_status: ['enrolled']); + + // $file = ['id' => null,'client_id' => $client_id,'policy_id' => $client_policy_id,'action' => 'inception']; + $file = ['id' => null, 'client_id' => $client_id, 'policy_id' => $client_policy_id, 'action' => 'inception', 'created_by' => get_session_userid(), 'client_branch_id' => $params['client_branch_id']]; + + //get existing units in the current branch + $existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $file['client_id'], client_branch_id: $file['client_branch_id']); + // dd($this->employeeModel->getLastQuery()); + // Kint::dump($existing_famility_details);die(); + $employee_data_group_by_family = data_group_by_family($existing_famility_details, $data_source = 'db'); + // dd($employee_data_group_by_family); + foreach ($employee_data_group_by_family as $emp_id => $family) { + $transformed_famility_details = transform_db_data_to_excel($family); + // $data = calculate_premium_new($transformed_famility_details,$policy_terms,$slab_details,$file); + $data = calculate_premium_new(family_data: $transformed_famility_details, policy_terms: $policy_terms, slab_details: $slab_details, fileArr: $file, existing_units: $existing_units); + // dd($data); + $employee_data_group_by_family[$emp_id] = $data; + $this->employeesOnboardProcess(['familiy_data' => $data, 'file' => $file]); + } + + // dd($employee_data_group_by_family); + } + + // die(); + return (count($employee_data_group_by_family)); + } + + //deletion of emp + public function employeeDisembark($params) + { + helper('excel_util_helper'); + + //get file name + $file_id = $params['file_id']; + $file = $this->fileModel->find($file_id); + $file['action'] = $params['action']; + // dd($file); + + // $file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name']; + // $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path); + // $sheet = $spreadsheet->getActiveSheet(); + // $highestRowAndColumn = $sheet->getHighestRowAndColumn(); + // $allowedHighestColumn = end($this->deletion_excel_columns); + // $excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']); + // dd($excel_data); + + $excel_data = json_decode(file_get_contents($params['file_path'] ?? []), true); + unset($excel_data[0]); + // kint::dump($excel_data); + + $endorsement_data = []; + $policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'], $file['policy_id']); + $insurer = new InsurerModel(); + $insurer = ($insurer->find($policy_terms[0]->insurer_id)); + // kint::dump($insurer); + + //make closure funciton which is going to use only by this method + $endorsement = function ($data, $file, $row) use ($insurer) { + + $group_key = rand(100000, 999999); + $row[4] = change_date_format($row[4], 'd-M-Y', 'Y-m-d'); // date of exit from excel + // Kint::dump($row[4]); + // check if insurer configured with add one day for deletion + // if($insurer['deletion_add_day'] == true) + // { + // $row[4] = (new \DateTime($row[4]))->modify('+1 day')->format('Y-m-d'); + // } + // dd($row[4]); + //for emp table + // $this->empEndorsementModel->save(['pk' => (int)$data['emp_id'],'emp_code' => $data['emp_code'],'table_name' => 'employees','actions' => 'd','name' => $data['name'],'field_name' => 'emp_status','old_value' => $data['emp_status'],'new_value' => 'deactivate','created_by' => $file['created_by'],'remarks' => 'general deletion','group_key' => $group_key,'file_id' => $file['id'],'status' => 'pending']); + // dd( $this->empEndorsementModel->getLastQuery()); + // $this->empEndorsementModel->save(['pk' => (int)$data['emp_id'],'emp_code' => $data['emp_code'],'table_name' => 'employees','actions' => 'd','name' => $data['name'],'field_name' => 'change_event','old_value' => $data['change_event'],'new_value' => 'deletion','created_by' => $file['created_by'],'remarks' => 'general deletion']); + + // for employee policy table + $this->empEndorsementModel->save(['pk' => (int)$data['emp_policy_id'], 'emp_code' => $data['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'd', 'name' => $data['name'], 'field_name' => 'date_of_exit', 'old_value' => $data['date_of_exit'], 'new_value' => $row[4], 'created_by' => $file['created_by'], 'remarks' => 'general deletion', 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']); + $this->empEndorsementModel->save(['pk' => (int)$data['emp_policy_id'], 'emp_code' => $data['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'd', 'name' => $data['name'], 'field_name' => 'reason_for_exit', 'old_value' => $data['reason_for_exit'], 'new_value' => $row[5], 'created_by' => $file['created_by'], 'remarks' => 'general deletion', 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']); + $this->empEndorsementModel->save(['pk' => (int)$data['emp_policy_id'], 'emp_code' => $data['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'd', 'name' => $data['name'], 'field_name' => 'status', 'old_value' => $data['status'], 'new_value' => 'inactive', 'created_by' => $file['created_by'], 'remarks' => 'general deletion', 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']); + $this->empEndorsementModel->save(['pk' => (int)$data['emp_policy_id'], 'emp_code' => $data['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'd', 'name' => $data['name'], 'field_name' => 'claim_status', 'old_value' => $data['claim_status'], 'new_value' => $row[6], 'created_by' => $file['created_by'], 'remarks' => 'general deletion', 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']); + }; + + //iterate each row + foreach ($excel_data as $col_key => $row) { + if (check_row_is_empty_or_null($row)) { + break; + } + // echo '
START- ' . $row[2]; + + $employee = $this->employeeModel + ->select('employees.*, employee_polices.id as emp_policy_pk') + ->join('employee_polices', 'employees.id = employee_polices.employee_id') + ->where('employees.emp_code', $row[1]) + ->where('employees.name', $row[2]) + ->where('employees.client_id', $file['client_id']) + ->where('employees.client_branch_id', $file['client_branch_id']) + ->where('employee_polices.client_policy_id', $file['policy_id']) + ->where('employees.emp_status !=', 'truncated') + ->where('employees.is_active', 1) + ->where('employee_polices.status !=', 'truncated') + ->where('employee_polices.is_active', 1) + ->first(); + + // $employee = $this->employeeModel->where('emp_code', $row[1])->where('name',$row[2])->where('client_id',$file['client_id'])->first(); + // dd($employee); + // kint::dump($employee); + + if (is_array($employee) && count($employee)) { + // dd($employee); + $existing_endorsements = $this->empEndorsementModel->where('actions', 'd') + ->where('table_name', 'employee_polices') + ->where('endorsement_id is null') + ->where('emp_code', $employee['emp_code']) + ->where('name', $employee['name']) + ->where('pk', $employee['emp_policy_pk']) + ->where('field_name', 'status') + ->where('status !=', 'truncated') + ->where('is_active', 1) + ->findAll(); + + // dd($existing_endorsements); + if (!count($existing_endorsements)) { + // dd($employee); + if (strtolower($employee['relationship']) != 'self') { + + if (!in_array($employee['id'], $endorsement_data)) //make entry in endorsement firsttime only with checking that PK of emp exisintg in variable $endorsement_data + { + $employee_policy = $this->employeePolicyModel + ->where('employee_id', $employee['id']) + ->where('client_policy_id', $file['policy_id']) + ->where('status !=', 'truncated') + ->where('is_active', 1) + ->first(); + + $data = ['emp_id' => $employee['id'], 'name' => $employee['name'], 'emp_status' => $employee['emp_status'], 'emp_policy_id' => $employee_policy['id'], 'emp_code' => $employee['emp_code'], 'change_event' => $employee['change_event'], 'date_of_exit' => $employee_policy['date_of_exit'], 'reason_for_exit' => $employee_policy['reason_for_exit'], 'status' => $employee_policy['status'], 'claim_status' => $employee_policy['claim_status']]; + $endorsement($data, $file, $row); + $endorsement_data[] = $employee['id']; + } + } else { + + $family = $this->employeeModel->getEmpFamilybyEmpCode(emp_code: $row[1], client_id: $file['client_id'], client_policy_id: $file['policy_id'], emp_status: ['active'], policy_status: ['active']); + // Kint::dump($family); + foreach ($family as $key => $emp) { + + if (!in_array($emp['emp_id'], $endorsement_data)) { + $endorsement($emp, $file, $row); + + $endorsement_data[] = $emp['emp_id']; + } + } + } + } else { + $this->myLogger->logme("error", 'Existing endorsement pending for this employee : emp_code : {emp_code} - emp_name : {name}', ['emp_code' => $row[1], 'name' => $row[2]]); + } + } else { + $this->myLogger->logme("error", '{emp_code} - {name} not found', ['emp_code' => $row[1], 'name' => $row[2]]); + } + + // print_r($endorsement_data); + + } + + // $this->fileModel->where('id', $file_id)->set(['status' => 'success', 'reason' => ''])->update(); + // $this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'success')); + + $this->myLogger->logme("error", $file['action'] . ' : {file_id} uploaded success', ['file_id' => $file_id]); + return $endorsement_data; + } + + //correction of emp + public function employeesCorrectionProcess($params) + { + helper('excel_util_helper'); + //get file name + $file_id = $params['file_id']; + $file = $this->fileModel->find($file_id); + $file['action'] = $params['action']; + + + // $file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name']; + // $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path); + // $sheet = $spreadsheet->getActiveSheet(); + // $highestRowAndColumn = $sheet->getHighestRowAndColumn(); + // $allowedHighestColumn = end($this->correction_excel_columns); + // $excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']); + + $excel_data = json_decode(file_get_contents($params['file_path'] ?? []), true); + unset($excel_data[0]); + // dd($excel_data); + + //iterate each row + foreach ($excel_data as $col_key => $row) { + if (check_row_is_empty_or_null($row)) { + break; + } + // echo '
START- ' . $row[2]; + + $field_name = $row[3]; + $field_value = ($field_name == 'dob' ? change_date_format($row[4], 'd-M-Y', 'Y-m-d') : $row[4]); + + + $employee = $this->employeeModel + ->where('emp_code', $row[1]) + ->where('name', $row[2]) + ->where('client_id', $file['client_id']) + ->where('client_branch_id', $file['client_branch_id']) + ->where('emp_status', 'active') + ->where('is_active', 1) + ->first(); + $existing_endorsements = $this->empEndorsementModel->where('actions', 'c') + ->where('table_name', 'employees') + ->where('endorsement_id is null') + ->where('emp_code', $employee['emp_code']) + ->where('name', $employee['name']) + ->where('field_name', $field_name) + ->where('is_active', 1) + ->where('status !=', 'truncated') + ->findAll(); + // dd($existing_endorsements); + //make entry in endorsement table + if (!count($existing_endorsements)) { + $group_key = rand(100000, 999999); + $this->empEndorsementModel->save(['pk' => (int)$employee['id'], 'emp_code' => $employee['emp_code'], 'table_name' => 'employees', 'actions' => 'c', 'name' => $employee['name'], 'field_name' => $field_name, 'old_value' => $employee[$field_name], 'new_value' => $field_value, 'created_by' => $file['created_by'], 'remarks' => $row[7], 'date_of_correction' => change_date_format($row[5], 'd-M-Y', 'Y-m-d'), 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']); + } + } + + // $this->fileModel->where('id', $file_id)->set(['status' => 'success', 'reason' => ''])->update(); + // $this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'success')); + $this->myLogger->logme("error", $file['action'] . ' : {file_id} uploaded success', ['file_id' => $file_id]); + return true; + } + + //enhance of emp + public function employeesSIEnhanceProcess($params) + { + helper('excel_util_helper'); + //get file name + $file_id = $params['file_id']; + $file = $this->fileModel->find($file_id); + $file['action'] = $params['action']; + + // $file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name']; + // $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path); + // $sheet = $spreadsheet->getActiveSheet(); + // $highestRowAndColumn = $sheet->getHighestRowAndColumn(); + // $allowedHighestColumn = end($this->si_enhance_excel_columns); + // $excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']); + $excel_data = json_decode(file_get_contents($params['file_path'] ?? []), true); + unset($excel_data[0]); + // dd($excel_data); + + //get policy slab rates + $slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($file['policy_id'], $file['client_id']); + //iterate each row + // dd($slab_details); + foreach ($excel_data as $col_key => $row) { + if (check_row_is_empty_or_null($row)) { + break; + } + // echo '
START- ' . $row[2]; + $employee = $this->employeeModel + ->where('emp_code', $row[1]) + ->where('name', $row[2]) + ->where('client_id', $file['client_id']) + ->where('client_branch_id', $file['client_branch_id']) + ->where('emp_status', 'active') + ->where('is_active', 1) + ->first(); + $employee_policy = $this->employeePolicyModel + ->where('employee_id', $employee['id']) + ->where('client_policy_id', $file['policy_id']) + ->where('status', 'active') + ->where('is_active', 1) + ->first(); + // dd($employee, $employee_policy); + + $existing_endorsements = $this->empEndorsementModel->where('actions', 'si') + ->where('table_name', 'employee_polices') + ->where('endorsement_id is null') + ->where('emp_code', $employee['emp_code']) + ->where('name', $employee['name']) + ->where('field_name', 'basic_cover_si') + ->findAll(); + // dd($existing_endorsements); + //make entry in endorsement table + if (!count($existing_endorsements)) { + //transform data to send + + //get applicable slab rate for current member relation + $pre_rack_rate_name = ''; + $applicable_rack_rate_name = ''; + $applicable_rack_rate_master = []; + foreach ($slab_details['slab_rates'] as $skey => $slab_value) { + if ($pre_rack_rate_name != $slab_value['rack_rate_name']) { + $pre_rack_rate_name = $slab_value['rack_rate_name']; + $rack_rate_json = json_decode($slab_value['additional_relationship'], true); + $relationship_array_key = strtolower(trim($employee['relationship'])); + + if (in_array($relationship_array_key, ['son', 'daughter'])) { + $relationship_array_key = 'childrens'; + } elseif (in_array($relationship_array_key, ['father', 'mother'])) { + $relationship_array_key = 'parents'; + } elseif (in_array($relationship_array_key, ['father in law', 'mother in law', 'father-in-law', 'mother-in-law'])) { + $relationship_array_key = 'parents-in-law'; + } + + if (array_key_exists($relationship_array_key, $rack_rate_json) && $rack_rate_json[$relationship_array_key] != 0 && $rack_rate_json[$relationship_array_key] != 'NA') { + $applicable_rack_rate_name = $slab_value['rack_rate_name']; + $applicable_rack_rate_master = $slab_value['grid_master']; + break; + } + } + } + + //get max age,max count of the familiy + $max_age_and_max_count_of_current_member = $this->employeeModel->getFamiliyCountAndMaxage($employee['emp_code']); + //transform SI excel row data as inception excel OR premium calculateable fomart + + $data = transform_si_excel_row_to_calculatable_format(employee: $employee, employee_policy: $employee_policy, maxage_and_maxcount: $max_age_and_max_count_of_current_member, slab_details: $slab_details, applicable_slab_name: $applicable_rack_rate_name, augmented_si: $row[3], grid_master: $applicable_rack_rate_master); + $policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'], $file['policy_id']); + $policy_terms = (array) $policy_terms[0]; + // dd($policy_terms); + //grouping slab details by rack rate name + $temp_slab_rates = group_slab_rates_basedon_name($slab_details); + + $calculated_data = premium_calculation_manager($data, $policy_terms, $temp_slab_rates, $row[3]); + + $group_key = rand(100000, 999999); + $this->empEndorsementModel->save(['pk' => (int)$employee_policy['id'], 'emp_code' => $employee['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'si', 'name' => $employee['name'], 'field_name' => 'basic_cover_si', 'old_value' => $employee_policy['basic_cover_si'], 'new_value' => $row[3], 'created_by' => $file['created_by'], 'remarks' => 'general si enhancement', 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']); + $this->empEndorsementModel->save(['pk' => (int)$employee_policy['id'], 'emp_code' => $employee['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'si', 'name' => $employee['name'], 'field_name' => 'premium', 'old_value' => $employee_policy['premium'], 'new_value' => $calculated_data['policy_details']['premium'], 'created_by' => $file['created_by'], 'remarks' => 'general si enhancement', 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']); + $this->empEndorsementModel->save(['pk' => (int)$employee_policy['id'], 'emp_code' => $employee['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'si', 'name' => $employee['name'], 'field_name' => 'si_enhancement_date', 'old_value' => null, 'new_value' => change_date_format($row[4], 'd-M-Y', 'Y-m-d'), 'created_by' => $file['created_by'], 'remarks' => 'general si enhancement', 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']); + } + } + + // $this->fileModel->where('id', $file_id)->set(['status' => 'success', 'reason' => ''])->update(); + // $this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'success')); + $this->myLogger->logme("error", $file['action'] . ' : {file_id} uploaded success', ['file_id' => $file_id]); + + return true; + } + + // insert or update in db for inception addition depent addition + public function employeesOnboardProcess($params) + { + // dd($params); + + $familiy_data = $params['familiy_data']; + $file = $params['file']; + + $policy_details = $this->clientPolicyModel->where('id', $file['policy_id'])->first(); + // dd($policy_details); + + foreach ($familiy_data as $fkey => $value) { + if (is_array($value)) { + + + if ($file['id'] == null || $value['temp']['source'] == 'excel' || (($file['action'] == 'dependent_addition' && ($value['temp']['premium_type'] == 1 && strtolower($value['relationship']) == 'self') || ($value['temp']['premium_type'] == 2 || $value['temp']['premium_type'] == null)))) //insert data come from excel and from db i.e. ( $file['id'] == null for enrollment data) + { + + $employee = $this->employeeModel->checkExistingEmp($value, $file['client_branch_id']); + $policy_data = $value['policy_details']; + $temp = $value['temp']; + unset($value['policy_details']); + unset($value['temp']); + // Kint::dump($value); + // Kint::dump($temp); + // Kint::dump($policy_data); + // echo '---------------------------------------'; + + //start implemet of si enhancement of grid type 10,11 + if (count($employee) && $file['action'] == 'dependent_addition' && $temp['source'] == 'db' && in_array($temp['grid_id'], [10, 11]) && (($temp['premium_type'] == 1 && (strtolower($value['relationship']) == 'self' || $temp['acting_self'])) || ($temp['premium_type'] == 2 || $temp['premium_type'] == null))) { + $log_message = 'Employee record from DB,Checking SI for - ' . $employee[0]['name'] . '(' . $employee[0]['emp_code'] . ')'; + $this->myLogger->logme('error', $log_message); + $res = $this->employeesSIEnhanceProcessWhileOnbboard(employee: $employee[0], policy_data: $policy_data, file: $file); // where employee holds existing emp data and policy_data holds new si enhancement + + break; //skip db employee + } + //end implemet of si enhancement of grid type + //save employee table + $value['relationship'] = ucfirst(trim($value['relationship'])); + if (count($employee)) { + $value['updated_by'] = $file['created_by']; + $value['id'] = $employee[0]['id']; + $value['emp_status'] = 'active'; + $value['family_floater_key'] = generate_family_floater_key($value['relationship']); + $value['client_branch_id'] = $file['client_branch_id']; + $value['file_id'] = isset($employee[0]['file_id']) && $employee[0]['file_id'] != '' ? $employee[0]['file_id'] : $file['id']; + $log_message = 'Update Employee - ' . $employee[0]['name'] . '(' . $employee[0]['emp_code'] . ') with PK ' . $employee[0]['id']; + // $this->myLogger->logme('error',('Update - ' . $employee[0]['id'].' - '. $employee[0]['emp_code'] .' - '.$employee[0]['name'])); + // echo 'insert emp'; + } else { + $value['emp_status'] = 'active'; + $value['created_by'] = $file['created_by']; + $value['client_branch_id'] = $file['client_branch_id']; + $value['family_floater_key'] = generate_family_floater_key($value['relationship']); + $value['file_id'] = isset($employee[0]['file_id']) && $employee[0]['file_id'] != '' ? $employee[0]['file_id'] : $file['id']; + $log_message = 'Insert Employee- ' . $value['name'] . '(' . $value['emp_code'] . ') with PK '; + // $this->myLogger->logme('error',('Insert - ' . $value['emp_code'] .' - '. $value['name'])); + // echo 'update emp'; + } + $value = ExcelSanitizeHelper::sanitizeArrayData($value); + $this->employeeModel->save($value); + if (isset($value['id'])) { + $emp_id = $value['id']; + } else { + $emp_id = $this->employeeModel->getInsertID(); + $log_message .= $emp_id; + } + + //commanded for last insert id is coming from buffer + // $emp_id = $this->employeeModel->getInsertID(); + // if($emp_id != 0){ $log_message .= $emp_id; } + // else{ $emp_id = $employee[0]['id']; } + + $this->myLogger->logme('error', $log_message); + + //save policy table + $employee_policy = $this->employeePolicyModel->checkExistingEmpPolicy(['employee_id' => $emp_id, 'client_policy_id' => $file['policy_id']]); + if (count($employee_policy)) { + $policy_data['updated_by'] = $file['created_by']; + $policy_data['id'] = $employee_policy[0]['id']; + $policy_data['status'] = 'active'; + $policy_data['payable_employee'] = check_pay_by_employee_or_company($policy_details['policy_terms'], $value['relationship']); + $policy_data['file_id'] = isset($employee_policy[0]['file_id']) && $employee_policy[0]['file_id'] != '' ? $employee_policy[0]['file_id'] : $file['id']; + $log_message = 'Update Employee Policy for ' . $value['name'] . '(' . $value['emp_code'] . ') with PK- ' . $employee_policy[0]['id'] . ' client policy ID ' . $employee_policy[0]['client_policy_id'] . ' with SI ' . $policy_data['basic_cover_si']; + // echo 'insert policy'; + } else { + $policy_data['employee_id'] = $emp_id; + $policy_data['client_policy_id'] = $file['policy_id']; + $policy_data['created_by'] = $file['created_by']; + $policy_data['status'] = 'active'; + $policy_data['payable_employee'] = check_pay_by_employee_or_company($policy_details['policy_terms'], $value['relationship']); + $policy_data['file_id'] = $file['id']; + $log_message = 'Insert Employee Policy for ' . $value['name'] . '(' . $value['emp_code'] . ') - client policy id -' . $file['policy_id'] . ' - with SI ' . $policy_data['basic_cover_si']; + // echo 'update policy'; + } + // log_message('error',json_encode($policy_data)); + // dd($this->employeePolicyModel->save($policy_data)); + $res = $this->employeePolicyModel->save($policy_data); + // if($res){log_message('error','ths the resul'.$res);} + if (isset($policy_data['id'])) { + $emp_policy_id = $policy_data['id']; + } else { + $emp_policy_id = $this->employeePolicyModel->getInsertID(); + } + + if ($emp_policy_id != 0) //emp policy inserted + { + $log_message .= ' with PK ' . $emp_policy_id; + + //make endorsement entry if action is addition OR Dependt addition + if (($file['action'] == 'missed_inception' || $file['action'] == 'dependent_addition' || $file['action'] == 'addition') && $temp['source'] == 'excel') { + $log_message = $file['action'] . ' - endorsement' . $value['emp_code'] . ' - ' . $value['name'] . ' - with policy id' . $emp_policy_id; + $this->myLogger->logme('error', $log_message); + $actions = ($file['action'] == 'dependent_addition' ? 'da' : ($file['action'] == 'addition' ? 'a' : 'a')); + $addition_endorse_data = ['pk' => $emp_policy_id, 'group_key' => rand(100000, 999999), 'emp_code' => $value['emp_code'], 'table_name' => 'employee_polices', 'actions' => $actions, 'name' => $value['name'], 'field_name' => 'basic_cover_si', 'old_value' => NULL, 'new_value' => $policy_data['basic_cover_si'], 'remarks' => 'addition endorsement', 'file_id' => $file['id'], 'created_by' => $file['created_by'], 'status' => 'pending']; + $this->employeeEndorsementforAddtionAndDependentAddition($addition_endorse_data); + } + } + // else{ $emp_policy_id = $employee_policy[0]['id']; } + + $this->myLogger->logme('error', $log_message); + } // if end + } // is array check end + else { + $this->myLogger->logme('error', '######Incoming value is not an array'); + } + } // for end + } //function end + + + public function employeeEndorsementforAddtionAndDependentAddition($employee) + { + $this->empEndorsementModel->save($employee); + } + + // $employee -> holds existing emp model obj and $policy_data holds new policy changes as array + public function employeesSIEnhanceProcessWhileOnbboard(array $employee, array $policy_data, array $file) + { + + $employee = $this->employeeModel->where('emp_code', $employee['emp_code'])->where('name', $employee['name'])->where('client_id', $employee['client_id'])->where('client_branch_id', $file['client_branch_id'])->where('is_active', 1)->first(); + // Kint::dump($this->employeeModel->getLastQuery()); + // dd($employee); + $employee_policy = $this->employeePolicyModel->where('employee_id', $employee['id'])->where('client_policy_id', $file['policy_id'])->first(); + // dd($employee_policy); + // $slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($employee_policy['client_policy_id'],$employee['client_id']); + // dd($slab_details); + // $temp_slab_details = ($temp['grid_type'] == 'primary' ? $slab_details['slab_rates'] : $slab_details['additional_slab_info']['slab_rates']); + + //check si has changed in normal case OR check premium only changed, still treat as SI enhancement in grid type 10 + if ($employee_policy['basic_cover_si'] != $policy_data['basic_cover_si'] || ($policy_data['premium'] != null && $policy_data['premium'] != "" && $employee_policy['premium'] != $policy_data['premium'])) { + $existing_endorsements = $this->empEndorsementModel->where('actions', 'si') + ->where('table_name', 'employee_polices') + ->where('endorsement_id is null') + ->where('emp_code', $employee['emp_code']) + ->where('name', $employee['name']) + ->where('field_name', 'basic_cover_si') + ->findAll(); + //make entry in endorsement table + if (!count($existing_endorsements)) { + $group_key = rand(100000, 999999); + $data = array( + ['pk' => (int)$employee_policy['id'], 'emp_code' => $employee['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'si', 'name' => $employee['name'], 'field_name' => 'basic_cover_si', 'old_value' => $employee_policy['basic_cover_si'], 'new_value' => $policy_data['basic_cover_si'], 'created_by' => $file['created_by'], 'remarks' => 'general si enhancement via DA', 'group_key' => $group_key, 'file_id' => $file['id']], + ['pk' => (int)$employee_policy['id'], 'emp_code' => $employee['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'si', 'name' => $employee['name'], 'field_name' => 'premium', 'old_value' => $employee_policy['premium'], 'new_value' => $policy_data['premium'], 'created_by' => $file['created_by'], 'remarks' => 'general si enhancement via DA', 'group_key' => $group_key, 'file_id' => $file['id']], + ['pk' => (int)$employee_policy['id'], 'emp_code' => $employee['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'si', 'name' => $employee['name'], 'field_name' => 'si_enhancement_date', 'old_value' => null, 'new_value' => date('Y-m-d'), 'created_by' => $file['created_by'], 'remarks' => 'general si enhancement via DA', 'group_key' => $group_key, 'file_id' => $file['id']] + ); + + $this->empEndorsementModel->insertBatch($data); + $this->myLogger->logme('error', ($employee['emp_code'] . ' - ' . $employee['name'] . '- ( NEW/OLD SI - ' . $employee_policy['basic_cover_si'] . '/' . $policy_data['basic_cover_si'] . ')' . '( NEW/OLD PREMIUM - ' . $employee_policy['premium'] . '/' . $policy_data['premium'] . ') ' . ' - si enhancement via DA')); + $log_message = 'SI enhancement done during dependent_addition - ' . $employee['name'] . '(' . $employee['emp_code'] . ')'; + $this->myLogger->logme('error', $log_message); + return true; //retun true when endorsement inserted + + } + return false; //retun false when endorsement not happend + } + return false; //retun false when endorsement not happend + + + } + + // --------------- FUNCTION FOR ERROR DISPLAY ------------------------------------------------------------------------------------------ + + public function getExcelErrorData($file_id, $res) + { + + try { + $file = $this->fileModel->find($file_id); + // $error_data = json_decode($file['reason'], true); + $error_data = $res; + // dd($error_data); + // return $error_data; + + $file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name']; + + //check the file exist or not + if (!file_exists($file_name_with_path)) { + $error_message = "File not found"; + $this->myLogger->logme('error', ($error_message . ' for file id ' . $file_id)); + return 0; + } + + $column_to_check = $this->multievent_excel_columns; + $allowedHighestColumn = end($column_to_check); + + $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path); + $sheet = $spreadsheet->getActiveSheet(); + + $highestRow = $sheet->getHighestDataRow(); + $excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRow); + + $excelErrorData['excel_header'] = $excel_data[0]; + unset($excel_data[0]); + // echo '
';
+            // Kint::dump($excel_data);
+            if ($error_data['error_type'] == 1) {
+
+                $finalArray = [];
+                foreach ($error_data['error_data'] as $key => $value) {
+
+                    foreach ($value as $key2 => $value2) {
+                        $error_data = $value2['error'];
+                        $data = ['value' => $excel_data[$key][$value2['col_idx']], 'error' => $error_data,];
+                        $excel_data[$key][$value2['col_idx']] = $data;
+                    }
+                    array_push($finalArray, $excel_data[$key]);
+                }
+
+                foreach ($finalArray as $fkey => $value) {
+                    foreach ($value as $vkey => $arrayData) {
+                        if (!is_array($arrayData)) {
+                            $data = ['value' => $arrayData];
+                            $finalArray[$fkey][$vkey] =  $data;
+                        }
+                    }
+                }
+
+                $excelErrorData['excel_data'] = $finalArray;
+                return $excelErrorData;
+            } else if ($error_data['error_type'] == 2) {
+
+
+                $allErrors = [];
+                $typeTowArray = [];
+
+                foreach ($error_data['error_data'] as $index => $item) {
+
+                    foreach ($item as $field) {
+                        if (!isset($allErrors[$index])) {
+                            $allErrors[$index] = [];
+                        }
+                        $allErrors[$index] = array_merge($allErrors[$index], $field['error']);
+                    }
+                }
+
+                // dd(array_keys($allErrors));
+                foreach ($allErrors as $key => $value) {
+                    // echo $key;
+                    // print_r($value);
+                    foreach ($excel_data as $excel_data_index => $excel_data_value) {
+                        if ($excel_data_value[0] == $key) {
+                            $data = ['value' => $excel_data[$excel_data_index][1], 'error' => $value,];
+                            $excel_data[$excel_data_index][1] = $data;
+                            array_push($typeTowArray, $excel_data[$excel_data_index]);
+                            break;
+                        }
+                    }
+                }
+                // dd($data);
+                foreach ($typeTowArray as $fkey => $value) {
+                    foreach ($value as $vkey => $arrayData) {
+                        if (!is_array($arrayData)) {
+                            $data = ['value' => $arrayData];
+                            $typeTowArray[$fkey][$vkey] =  $data;
+                        }
+                    }
+                }
+
+                $excelErrorData['excel_data'] = $typeTowArray;
+                return $excelErrorData;
+            }
+        } catch (\Exception $e) {
+            // // Handle any exceptions
+            // $errorMessage = $e->getMessage(); //die();
+            // $this->myLogger->logme('error', $errorMessage);
+            // return false; // You can return an error response here
+
+            $errorDetails = [
+                'error_message' => $e->getMessage(),
+                'file'          => $e->getFile(),
+                'line'          => $e->getLine(),
+                'stack_trace'   => $e->getTraceAsString(),
+            ];
+            return $errorDetails;
+        }
+    }
+
+    // ---------------------------------------------------------------------------------
+
+    public function getFileMetaDataByFileId($file_id, $status = 'success')
+    {
+
+        $data = $this->fileModel
+            ->select('files.*, clients.client_name, clients.short_name, policy_type.policy_type as policy_name,client_branch.branch_code')
+            ->join('clients', 'clients.id = files.client_id')
+            ->join('client_policy', 'client_policy.id = files.policy_id')
+            ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
+            ->join('client_branch', 'client_branch.id = files.client_branch_id', 'left')
+            ->where('files.id', $file_id)
+            ->first();
+
+        if ($status == 'success') {
+            $msg_title = 'File Upload Success';
+        } else if ($status == 'failure') {
+            $msg_title = 'File Upload Failure';
+        }
+
+        $msg_txt = $data['client_name'] . ' (' . $data['branch_code'] . ') - ' . $data['policy_name'] . ' - ' . ucfirst($data['action']);
+        $user_id = $data['created_by'];
+        $url = 'employee/upload';
+
+        return ['msg_txt' => $msg_txt, 'user_id' => $user_id, 'url' => $url, 'status' => $status, 'title' => $msg_title];
+    }
+
+    public function setPullNotification($data)
+    {
+
+
+        $array = ['message_text' => $data['msg_txt'], 'action_url' => $data['url'], 'msg_status' => $data['status'], 'msg_title' => $data['title']];
+        $jsonEncodeData = json_encode($array);
+
+        $msg_data = [
+
+            'message_text' => $jsonEncodeData,
+            'user_id' => $data['user_id'],
+            'role_id' => NULL,
+            'team_id' => NULL,
+            'message_type' => '1to1',
+        ];
+
+
+        $this->messageModel->insert($msg_data);
+    }
+
+    public function employeesEnrollmentInsert($params)
+    {
+        // dd($this->request);
+        helper('excel_util_helper');
+        //get file name
+        $file_id = $params['file_id'];
+        $file = $this->fileModel->find($file_id);
+        // dd($file);
+        $return = [];
+        if (!isset($file)) {
+            //file not found in DB
+            return array('status' => false, 'msg' => 'file not found in DB');
+        }
+        $file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name'];
+
+        //check physical file
+        if (!file_exists($file_name_with_path)) {
+            //file not found  update status and reason 
+            $message = "Physical file not found";
+            // echo $message;
+            $this->myLogger->logme('error', ($message . ' for file id ' . $file_id));
+            $this->fileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+            return  array('error_summary' => [5], 'error_data' => $message);
+        }
+
+        //get excel data
+        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
+        $sheet = $spreadsheet->getActiveSheet();
+
+        $highestRowAndColumn = $sheet->getHighestRowAndColumn();
+        $result = ['error_type' => 2, 'error_summary' => [], 'error_data' => []];
+        $columns_to_check = $this->enrollment_excel_columns;
+        $keys = array_keys($columns_to_check);
+        $allowedHighestColumn = end($columns_to_check);
+        $excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']);
+        // print_r($keys);die();
+        //get existing units in the current branch
+        $existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $file['client_id'], client_branch_id: $file['client_branch_id']);
+        //remove header
+        unset($excel_data[0]);
+        // dd($excel_data);
+        $emp_emails = [];
+
+        //check is welcome notification enabled
+        $notification = $this->notificationModel->where('client_id', $file['client_id'])->where('template_name', 'member_welcome_mail')->first();
+        // dd($notification);
+        $client_details = $this->clientModel->where('id', $file['client_id'])->first();
+        $policy_details = $this->clientPolicyModel->where('id', $file['policy_id'])->first();
+
+        // dd($policy_details);
+
+        //get policy slab rates 
+        // $slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($file['policy_id'],$file['client_id']);
+        // dd($slab_details);
+
+        foreach ($excel_data as $key => $row) {
+            $is_row_empty = check_row_is_empty_or_null($row);
+            if (!$is_row_empty) {
+
+                $value = [];
+                $policy_data = [];
+                $temp_unit = '';
+                if (empty($row[12])) {
+                    $temp_unit = $existing_units[0];
+                }
+
+                $value['emp_code'] = $row[1];
+                $value['name'] = $row[2];
+                $value['doj'] = (!empty($row[3]) ? change_date_format($row[3], 'd-M-Y', 'Y-m-d') : null);
+                $value['gender'] = $row[4];
+                $value['relationship'] = ucfirst(trim($row[5]));
+                $value['dob'] = change_date_format($row[6], 'd-M-Y', 'Y-m-d');
+                $value['email_corporate'] = $row[7];
+                $value['mobile'] = $row[8];
+                $value['band'] = $row[10];
+                $value['basic_pay'] = $row[11];
+                $value['unit'] = $temp_unit;
+                $value['family_floater_key'] = null;
+                $value['client_id'] = $file['client_id'];
+                $value['client_branch_id'] = $file['client_branch_id'];
+                $value['file_id'] = $file_id;
+                $value['is_addon_value'] = $policy_details['policy_type_id'] == 3 ? 1 : 0;
+
+                $value['temp']['emp_id'] = null; // dummy value for using exisitng funciton in model
+                if (strtolower(trim($value['relationship'])) === 'mother' || strtolower(trim($value['relationship'])) === 'father') {
+                    $relation = 'parent';
+                } else if (strtolower(trim($value['relationship'])) === 'son' || strtolower(trim($value['relationship'])) === 'daughter') {
+                    $relation = 'child';
+                } else if ((strtolower(trim($value['relationship'])) === 'father in law' || strtolower(trim($value['relationship'])) === 'mother in law') || (strtolower(trim($value['relationship'])) === 'father-in-law' || strtolower(trim($value['relationship'])) === 'mother-in-law')) {
+                    $relation = 'parent_in_law';
+                } else if (strtolower(trim($value['relationship'])) === 'spouse') {
+                    $relation = 'spouse';
+                } else if (strtolower(trim($value['relationship'])) === 'self') {
+                    $relation = 'self';
+                } else {
+                    $relation = '';
+                }
+                $value['family_floater_key'] = $relation;
+
+                // dd($value['family_floater_key']);
+
+                $policy_data['basic_cover_si'] = $row[9];
+                $policy_data['date_coverage'] = $row[13] != "" && $row[13] != null ? change_date_format($row[13], 'd-M-Y', 'Y-m-d') : null;
+                $policy_data['client_policy_id'] = $file['policy_id'];
+
+                $employee = $this->employeeModel->checkExistingEmployee($value, $file['client_branch_id']);
+                unset($value['temp']);
+                //save employee table
+                // dd($employee['id']);
+                if ($employee !== null) {
+                    $value['updated_by'] = $file['created_by'];
+                    $value['id'] = $employee['id'];
+                    $value['emp_status'] = 'draft';
+
+                    $log_message = 'Enrollment Update Employee - ' . $employee['name'] . '(' . $employee['emp_code'] . ') with PK ' . $employee['id'];
+                } else {
+                    $value['emp_status'] = 'draft';
+                    $value['created_by'] = $file['created_by'];
+                    $log_message = 'Enrollment Insert Employee- ' . $value['name'] . '(' . $value['emp_code'] . ') with PK ';
+                }
+
+                $value = ExcelSanitizeHelper::sanitizeArrayData($value);
+                $this->employeeModel->save($value);
+                if (isset($value['id'])) {
+                    $emp_id = $value['id'];
+                } else {
+                    $emp_id = $this->employeeModel->getInsertID();
+                    $log_message .= $emp_id;
+                }
+
+                // $emp_id = $this->employeeModel->getInsertID();
+                // if($emp_id != 0){  $log_message .= $emp_id; }
+                // else{ $emp_id = $employee['id']; }
+
+                $this->myLogger->logme('error', $log_message);
+
+                //save policy table
+                $employee_policy = $this->employeePolicyModel->checkExistingEmpPolicy(['employee_id' => $emp_id, 'client_policy_id' => $file['policy_id']]);
+                if (count($employee_policy)) {
+                    $policy_data['updated_by'] = $file['created_by'];
+                    $policy_data['id'] = $employee_policy[0]['id'];
+                    $policy_data['status'] = 'draft';
+                    $policy_data['payable_employee'] = check_pay_by_employee_or_company($policy_details['policy_terms'], $value['relationship']);
+                    $policy_data['file_id'] = isset($employee_policy[0]['file_id']) && $employee_policy[0]['file_id'] != '' ? $employee_policy[0]['file_id'] : $file_id;
+                    $log_message = 'Update Employee Policy for ' . $value['name'] . '(' . $value['emp_code'] . ') with PK- ' . $employee_policy[0]['id'] . ' client policy ID ' . $employee_policy[0]['client_policy_id'] . ' with SI ' . $policy_data['basic_cover_si'];
+                    // echo 'insert policy';
+                } else {
+                    $policy_data['employee_id'] = $emp_id;
+                    $policy_data['client_policy_id'] = $file['policy_id'];
+                    $policy_data['created_by'] = $file['created_by'];
+                    $policy_data['status'] = 'draft';
+                    $policy_data['payable_employee'] = check_pay_by_employee_or_company($policy_details['policy_terms'], $value['relationship']);
+                    $policy_data['file_id'] = $file_id;
+                    $log_message = 'Insert Employee Policy for ' . $value['name'] . '(' . $value['emp_code'] . ') - client policy id -' . $file['policy_id'] . ' - with SI ' . $policy_data['basic_cover_si'];
+                    // echo 'update policy';
+                }
+
+                log_message('error', json_encode($policy_data));
+                // dd($policy_data);
+                $this->employeePolicyModel->save($policy_data);
+                $emp_policy_id = $this->employeePolicyModel->getInsertID();
+                $this->myLogger->logme('error', $log_message);
+
+                $employeeRestController = new EmployeeRestController();
+                $employeeRestController->updatePremiumAmount($file['policy_id'], $value['emp_code'], $file['client_branch_id']);
+
+
+                //save email of self for send mail later
+                if (isset($notification) && $notification['enabled'] == 1 && $notification['mail_content'] != '') {
+                    if (strtolower($value['relationship']) == 'self' && $value['email_corporate'] != "") {
+                        $params['dataToInsert'] = $value; //holds employee master data
+                        $params['notification'] = $notification;
+                        $params['client_data'] = $client_details;
+                        $params['common'] = [
+                            'client_id' => $file['client_id'],
+                            'client_branch_id' => $file['client_branch_id'],
+                            'client_policy_id' => $file['policy_id'],
+                            'employee_policy_id' => $emp_policy_id ?? null,
+                            'employee_id' => $emp_id,
+                            'mail_type' => 'member_welcome_mail',
+                        ];
+                        //store email and mail content via helper to send notification
+                        $emp_emails[] = sendMailNotification::sendMailNotification('member_welcome_mail', $params);
+                    }
+                }
+            } // endof if row is empty check
+        } //end of for loop
+
+        // dd($emp_emails);
+
+        // for bulk mail queue job push  
+        if (!empty($emp_emails) && count($emp_emails) > 0) {
+
+            $emp_emails = array_chunk($emp_emails, 20);
+
+            foreach ($emp_emails as $key => $value) {
+                $job_details  = new Jobs();
+                $r = Jobs::addJob(['job_name' => 'bulk_mail', 'payload' => $value]);
+            }
+        }
+
+        $this->fileModel->where('id', $file_id)->set(['status' => 'success', 'reason' => ''])->update();
+        $this->myLogger->logme("error", '{file_id} uploaded success', ['file_id' => $file_id]);
+
+        $this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'success'));
+
+
+        return true;
+    } //end of employeesEnrollmentInsert
+
+    // --------------- FUNCTION FOR MULTI EVENT  ------------------------------------------------------------------
+
+    public function constructMultiEventData($params)
+    {
+        $file_id = $params['file_id'];
+        $file = $this->fileModel->where('is_active', 1)->where('id', $file_id)->first();
+        $file_name = $file['file_name'];
+
+        $column_to_check         = $this->multievent_excel_columns;
+        $allowedHighestColumn    = end($column_to_check);
+        $event_coumn_index       = $column_to_check['change_event']['col_idx'];
+
+        $addition_column_to_check   = $this->inception_excel_columns;
+        $correction_column_to_check = $this->correction_excel_columns;
+        $deletion_column_to_check   = $this->deletion_excel_columns;
+        $si_column_to_check         = $this->si_enhance_excel_columns;
+
+        $file_name_with_path = WRITEPATH . "uploads/excel/" . $file_name;
+        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
+        $worksheet   = $spreadsheet->getActiveSheet();
+
+        $highestRow    = $worksheet->getHighestDataRow();
+        $highestColumn = $worksheet->getHighestDataColumn();
+
+        $excel_data   = $worksheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRow);
+        $excel_header = $excel_data[0];
+        unset($excel_data[0]);
+        $excel_data = ExcelSanitizeHelper::sanitizeArrayData($excel_data);
+
+
+        // Buckets
+        $inception                      = [];
+        $missed_inception               = [];
+        $addition_endorsement           = [];
+        $dependent_addition_endorsement = [];
+        $deletion_endorsement           = [];
+        $correction_endorsement         = [];
+        $si_enhancement_endorsement     = [];
+
+        foreach ($excel_data as $row_idx => $row_value) {
+            $event = strtolower(trim($row_value[$event_coumn_index] ?? ''));
+
+            switch ($event) {
+                case "addition":
+                    if (empty($addition_endorsement)) {
+                        $addition_endorsement[] = $this->buildHeaderData($addition_column_to_check);
+                    }
+                    $addition_endorsement[$row_idx] = $this->buildEndorsementData($row_value, $row_idx, $addition_column_to_check, $column_to_check);
+                    break;
+
+                case "missed inception":
+                    if (empty($missed_inception)) {
+                        $missed_inception[] = $this->buildHeaderData($addition_column_to_check);
+                    }
+                    $missed_inception[$row_idx] = $this->buildEndorsementData($row_value, $row_idx, $addition_column_to_check, $column_to_check);
+                    break;
+
+                case "dependent addition":
+                    if (empty($dependent_addition_endorsement)) {
+                        $dependent_addition_endorsement[] = $this->buildHeaderData($addition_column_to_check);
+                    }
+                    $dependent_addition_endorsement[$row_idx] = $this->buildEndorsementData($row_value, $row_idx, $addition_column_to_check, $column_to_check);
+                    break;
+
+                case "correction":
+                    if (empty($correction_endorsement)) {
+                        $correction_endorsement[] = $this->buildHeaderData($correction_column_to_check);
+                    }
+                    $correction_endorsement[$row_idx] = $this->buildEndorsementData($row_value, $row_idx, $correction_column_to_check, $column_to_check);
+                    break;
+
+                case "deletion":
+                    if (empty($deletion_endorsement)) {
+                        $deletion_endorsement[] = $this->buildHeaderData($deletion_column_to_check);
+                    }
+                    $deletion_endorsement[$row_idx] = $this->buildEndorsementData($row_value, $row_idx, $deletion_column_to_check, $column_to_check);
+                    break;
+
+                case "si enhancement":
+                    if (empty($si_enhancement_endorsement)) {
+                        $si_enhancement_endorsement[] = $this->buildHeaderData($si_column_to_check);
+                    }
+                    $si_enhancement_endorsement[$row_idx] = $this->buildEndorsementData($row_value, $row_idx, $si_column_to_check, $column_to_check);
+                    break;
+
+                default: // inception
+                    if (empty($inception) || $inception == "") {
+                        $inception[] = $this->buildHeaderData($addition_column_to_check);
+                    }
+                    $inception[$row_idx] = $this->buildEndorsementData($row_value, $row_idx, $addition_column_to_check, $column_to_check);
+                    break;
+            }
+        }
+
+        // Final data collection
+        $finalData = [
+            'inception'          => $inception,
+            'missed_inception'   => $missed_inception,
+            'addition'           => $addition_endorsement,
+            'dependent_addition' => $dependent_addition_endorsement,
+            'deletion'           => $deletion_endorsement,
+            'correction'         => $correction_endorsement,
+            'si_enhancement'     => $si_enhancement_endorsement,
+        ];
+        // dd($finalData);
+
+        // Save JSON file in writable/tmp/
+        $savedFiles = [];
+        foreach ($finalData as $key => $data) {
+            $filePath = WRITEPATH . 'tmp/' . $key . '_' . time() . '.json';
+            file_put_contents($filePath, json_encode($data, JSON_PRETTY_PRINT));
+            $savedFiles[$key] = $filePath;
+        }
+
+        return $savedFiles;
+
+    }
+
+    public function buildEndorsementData(array $row_value, $row_idx, array $convertable_column, array $multi_event_column): array
+    {
+        $newRow = [];
+        foreach ($convertable_column as $col => $col_val) {
+            $idx = $multi_event_column[$col]['col_idx'];
+            $newRow[] = $row_value[$idx] ?? '';
+        }
+
+        return $newRow;
+    }
+
+    public function buildHeaderData(array $convertable_column): array
+    {
+        $headerRow = [];
+        foreach ($convertable_column as $col) {
+            $headerRow[] = $col['col_name'];
+        }
+        
+        return $headerRow;
+    }
+
+    public function unlinkFiles($filePaths)
+    {
+        foreach ($filePaths as $filePath) {
+            if (file_exists($filePath)) {
+                unlink($filePath); // delete file
+            }
+        }
+    }
+
+    public function readTheJsonFileToArray($filePaths)
+    {
+        $allData = [];
+        foreach ($filePaths as $type => $filePath) {
+            if (file_exists($filePath)) {
+                $allData[$type] = json_decode(file_get_contents($filePath), true);
+            }
+        }
+
+        return $allData;
+    }
+
+    public function mergeErrors(array $data, $error_type = 1): array
+    {
+        $merged = [
+            'error_type' => $error_type,
+            'error_summary' => [],
+            'error_data'    => []
+        ];
+
+        foreach ($data as $item) {
+            // Merge error_summary (sum values)
+            foreach ($item['error_summary'] as $key => $value) {
+                if (!isset($merged['error_summary'][$key])) {
+                    $merged['error_summary'][$key] = 0;
+                }
+                $merged['error_summary'][$key] += $value; 
+            }
+
+            // Merge error_data (append rows)
+            foreach ($item['error_data'] as $rowIndex => $rowErrors) {
+                if (!isset($merged['error_data'][$rowIndex])) {
+                    $merged['error_data'][$rowIndex] = [];
+                }
+
+                foreach ($rowErrors as $fieldKey => $fieldError) {
+                    if (!isset($merged['error_data'][$rowIndex][$fieldKey])) {
+                        $merged['error_data'][$rowIndex][$fieldKey] = $fieldError;
+                    } else {
+                        // merge errors if same field exists
+                        $merged['error_data'][$rowIndex][$fieldKey]['error'] = array_merge(
+                            $merged['error_data'][$rowIndex][$fieldKey]['error'],
+                            $fieldError['error']
+                        );
+                        // remove duplicates & reindex
+                        $merged['error_data'][$rowIndex][$fieldKey]['error'] = array_values(
+                            array_unique($merged['error_data'][$rowIndex][$fieldKey]['error'])
+                        );
+                    }
+                }
+            }
+        }
+
+        return $merged;
+    }
+
+    public function syncColIndex(array $main, array $temp): array
+    {
+        foreach ($temp as $key => &$t) {
+            if (isset($main[$key])) {
+                $t['col_idx'] = $main[$key]['col_idx'];           // update col_idx
+                $t['col_cell_name'] = $main[$key]['col_cell_name']; // optional: also sync cell name
+            }
+        }
+        unset($t); // break reference
+
+        return $temp;
+    }
+
+
+
+}
diff --git a/app/Controllers/Home.php b/app/Controllers/Home.php
index cc084f72..eb0133d1 100755
--- a/app/Controllers/Home.php
+++ b/app/Controllers/Home.php
@@ -307,7 +307,7 @@ public function convertToPdf($inputFile = null)
     {
         // Customize this based on your needs
         $html = '

' . htmlspecialchars($worksheet->getTitle()) . '

'; - $html .= ''; + $html .= '
'; foreach ($worksheet->getRowIterator() as $row) { $html .= ''; diff --git a/app/Controllers/JobWorker.php b/app/Controllers/JobWorker.php index 7136c017..1f322c84 100755 --- a/app/Controllers/JobWorker.php +++ b/app/Controllers/JobWorker.php @@ -155,6 +155,18 @@ class JobWorker extends AdminController 'type' => 'CC', // Handler Category 'handler' => 'App\Controllers\TicketServiceController', ], + 'excelMultieventFileFormateValidation' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmployeeMultiEventServiceController', + ], + 'excelMultieventFileDataValidation' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmployeeMultiEventServiceController', + ], + 'excelMultieventFileOnBoard' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmployeeMultiEventServiceController', + ], ]; diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php index fc4a4e86..d5f8ea12 100644 --- a/app/Controllers/LeadsController.php +++ b/app/Controllers/LeadsController.php @@ -31,6 +31,7 @@ use App\Models\InsurerModel; use App\Models\OccupancyMasterModel; use App\Models\LeadFilesModel; use App\Models\LeadInstallmentPaymentDetails; +use App\Models\GmailSentHistoryModel; use App\Helpers\MailHelper; use App\Helpers\ExcelMergeHelper; @@ -70,6 +71,7 @@ class LeadsController extends BaseController protected $occupancyModel; protected $leadFilesModel; protected $leadInstallmentPaymentDetails; + protected $gmailSentHistoryModel; //variables for storing array protected $issuer; @@ -102,6 +104,7 @@ class LeadsController extends BaseController $this->occupancyModel = new OccupancyMasterModel(); $this->leadFilesModel = new LeadFilesModel(); $this->leadInstallmentPaymentDetails = new LeadInstallmentPaymentDetails(); + $this->gmailSentHistoryModel = new GmailSentHistoryModel(); $this->issuer = [1 => 'JIBS', 2 => 'Nhance']; $this->clientType = [1 => 'Group', 2 => 'Individual']; @@ -383,6 +386,20 @@ class LeadsController extends BaseController $data['source_policy_end_date'] = null; } + //convert the date + if (!empty($data['next_reminder_date'])) { + $data['next_reminder_date'] = change_date_format($data['next_reminder_date']); + } else { + $data['next_reminder_date'] = null; + } + + //convert 0 and 1 + if (isset($data['is_insurer_auto_mail'])) { + $data['is_insurer_auto_mail'] = 1; + } else { + $data['is_insurer_auto_mail'] = 0; + } + // $file_name = file_Upload($files[$index], $uploadFilePath); $last_3_years_claims = $data['finyear']; @@ -459,9 +476,12 @@ class LeadsController extends BaseController '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, - 'claim_history' => $data['claim_history'] ?? 0 + 'source_policy_start_date' => $data['source_policy_start_date'] ?? null, + 'source_policy_end_date' => $data['source_policy_end_date'] ?? null, + 'claim_history' => $data['claim_history'] ?? 0, + + 'next_reminder_date' => $data['next_reminder_date'] ?? 0, + 'is_insurer_auto_mail' => $data['is_insurer_auto_mail'] ?? 0 ]; } // print_r($processedData);die(); @@ -856,21 +876,40 @@ class LeadsController extends BaseController $qcr_created = true; } - if (($data['submit_type'] ?? "") == 'QCR') { + $quote_received_insurer = []; + if (($data['submit_type'] ?? "") === 'QCR') { + $inputJson = json_decode($data['json'], true); - $proposal_data = array_pop($inputJson); - if (isset($proposal_data['proposal_data']['over_all_column_data'])) { - $proposel_count = $proposal_data['proposal_data']['over_all_column_data']; + $proposal_data = $inputJson['proposal_data'] ?? array_pop($inputJson); + + if (isset($proposal_data['over_all_column_data'])) { + $proposel_count = $proposal_data['over_all_column_data']; + + $this->myLogger->logme("error", "insurer id : " . json_encode($proposel_count)); + foreach ($proposel_count as $key => $value) { if (!empty($value['insurers'])) { $qcr_created = true; + + foreach ($value['insurers'] as $insurer => $id) { + if (!empty($id['id'])) { + $quote_received_insurer[] = $id['id']; + } + } } } } } + $this->myLogger->logme("error", "quote_received_insurer : " . json_encode($quote_received_insurer)); $data['type'] = 1; + //update the quote received insurer data to the lead + if(count($quote_received_insurer) != 0){ + $this->leadsModel->update($lead_id, ['quote_received_insurer' => json_encode($quote_received_insurer ?? [])]); + $this->myLogger->logme("error", "quote_received_insurer data updated in the lead: " . json_encode($quote_received_insurer)); + } + // Deactivate existing RFQs for this lead and type if (!isset($data['rfq_primaryKey']) && empty($data['rfq_primaryKey'])) { $this->RFQModel @@ -2552,6 +2591,21 @@ class LeadsController extends BaseController $from_mail = "bs@nhanceindia.in"; } + $type = ""; + $insurer_ids = null; + if (in_array($recipient_type, ['placement'])) { + $type = "placement"; + } else if (in_array($recipient_type, ['insurer'])) { + $type = "insurer"; + $insurer_ids = json_decode($params['insurer_ids'] ?? "", true) ?? []; + }else if (in_array($recipient_type, ['internal'])) { + $type = "internal"; + }else if (in_array($recipient_type, ['client'])) { + $type = "client"; + } + + // print_r($insurer_ids); die; + if ($recipient_type === 'placement') { $lead_data = $this->leadsModel->find($lead_id); @@ -2733,7 +2787,7 @@ class LeadsController extends BaseController $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.

'; + $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 if (!empty($mail_content)) { @@ -2746,10 +2800,14 @@ class LeadsController extends BaseController } // print_r($subject); die; - + $common = ['module' => "leads", 'pk' => $lead_id, 'mail_type' => $type, 'common' => null]; if ($recipient_data) { - foreach ($recipient_data as $recipient) { + foreach ($recipient_data as $position => $recipient) { + if ($recipient_type == 'insurer'){ + $common['common'] = $insurer_ids[$position] ?? null; + } + $message = $original_message; $message = str_replace("{{RECIPIENT_NAME}}", $recipient['name'] != "" ? $recipient['name'] : " ", $message); $message = str_replace("{{CLIENT_NAME}}", $lead_data['client_name'] != "" ? $lead_data['client_name'] : "", $message); @@ -2761,7 +2819,7 @@ class LeadsController extends BaseController $string = implode(", ", $cc_mails); $bcc_string = implode(", ", $bcc_mails); - $res = MailHelper::send_email(['from_mail' => $from_mail, 'mail' => $recipient['email'], 'cc' => $string, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to, 'bcc' => $bcc_string]); + $res = MailHelper::send_email(['from_mail' => $from_mail, 'mail' => $recipient['email'], 'cc' => $string, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to, 'bcc' => $bcc_string, 'common' => $common]); // !dd($res); $result_data[] = ['mail' => $recipient['email'], 'status' => $res]; } @@ -3539,10 +3597,11 @@ class LeadsController extends BaseController $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); - $message = str_replace("{{LOGO_PATH}}", $log_path, $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); + $message = str_replace("{{LOGO_PATH}}", $log_path ?? "", $message); return $message; } else { @@ -3627,7 +3686,7 @@ class LeadsController extends BaseController } if (!empty($data['lead_edit_data'])) { - foreach (['policy_start_date', 'policy_end_date', 'source_policy_start_date', 'source_policy_end_date', 'incurred_claims_date'] as $dateField) { + foreach (['policy_start_date', 'policy_end_date', 'source_policy_start_date', 'source_policy_end_date', 'incurred_claims_date', 'next_reminder_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; @@ -3657,6 +3716,28 @@ class LeadsController extends BaseController return $this->loadLayout('leads_form_handler', $data); } + public function getLeadEmailHistory($id){ + if(!empty($id)){ + $result = $this->gmailSentHistoryModel + ->where('pk', $id) + ->where('module',"leads") + ->orderBy('created_at', 'desc') + ->findAll(); + if(!empty($result)){ + $result = !empty($result) ? $result : []; + return $this->response->setJSON((['status' => 'success', 'data' => $result]))->setStatusCode(200); + }else{ + return $this->response->setJSON((['status' => 'error', 'message' => 'No History found']))->setStatusCode(400); + } + }else{ + return $this->response->setJSON((['status' => 'error', 'message' => 'ID not found']))->setStatusCode(404); + } + + + // Select * from gmail_sent_history where pk != "" and module = "leads"; + // echo $id; + } + public function getPolicyTypeFields() { @@ -4866,7 +4947,7 @@ class LeadsController extends BaseController // Start table with clean styling $html .= "

{$category}

"; - $html .= ""; + $html .= "
"; // Table header with light background $html .= ""; @@ -4893,4 +4974,197 @@ class LeadsController extends BaseController return $html; } + + // function for insurer remainder mail cron job + public function remainderForQcr() + { + $lead_data = $this->leadsModel + ->select( + 'leads.*, + user_profiles.email as created_person_email, + policy_type.policy_type, + policy_type.long_name + ') + ->join('policy_type', 'leads.policy_type_id = policy_type.id') + ->join('user_profiles', 'leads.created_by = user_profiles.id', 'left') + ->where('leads.is_active', 1) + ->where('user_profiles.is_active', 1) + ->whereIn('leads.status', ['rfq_sent', 'qcr_created']) + ->where('leads.next_reminder_date', date('Y-m-d')) + ->findAll(); + + // dd($lead_data); + + if (count($lead_data) == 0) { + $this->myLogger->logme("info", "No leads found for reminder mail at " . date('Y-m-d H:i:s')); + print_r(["status" => true, "message" => "There is no data to send reminder mail"]); + return ["status" => true, "message" => "There is no data to send reminder mail"]; + + } + + $from_mail = "im@nhanceindia.in"; + $subject = "Reminder for RFQ"; + $content_string = ' +

Dear Sir,

+

Greetings from Nhance India!

+

This is a gentle reminder regarding our earlier mail about the RFQ for the {{POLICY_TYPE}} policy pertaining to {{CLIENT_NAME}}.

+

We kindly request you to share the competitive quotes at the earliest possible convenience.

+

In case of any clarification, please feel free to contact us.

+

Thank you for your prompt attention to this matter.


+

Best regards,

+

Nhance India

+ '; + + $reminder_sended_lead = []; + + foreach ($lead_data as $lead) { + + $leadId = $lead['id']; + $reply_to = $lead['created_person_email'] ?? ""; + + if (isset($lead['policy_end_date']) && $lead['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}}"; + } + + $mail_content = $this->transformMailContent($lead, $content_string, "RFQ"); + $mail_subject = $this->transformMailContent($lead, $subject, "RFQ"); + + + $this->myLogger->logme("info", "Processing lead_id={$leadId} for reminder mails"); + + // get sales person + created_by emails + $sales_person_emails = $this->userModel + ->select('email') + ->where('is_active', 1) + ->whereIn('id', json_decode($lead['salse_person_id'] ?? "[]", true)) + ->findAll(); + + $email_list = array_column($sales_person_emails, 'email'); + if (!empty($reply_to)) { + $email_list[] = $reply_to; + } + $email_list = array_filter(array_unique($email_list)); + $email_string = implode(',', $email_list); + + // Get latest sent mail timestamp + $createdAtRow = $this->gmailSentHistoryModel + ->select("DATE_FORMAT(created_at, '%Y-%m-%d %H:%i') as created_at", false) + ->where('isactive', 1) + ->where('mail_type', 'insurer') + ->where('pk', $leadId) + ->orderBy('id', 'desc') + ->first(); + // dd(db_connect()->getLastQuery(), $createdAtRow); + + if (!$createdAtRow) { + $this->myLogger->logme("warning", "No sent history found for lead_id={$leadId}, skipping..."); + continue; + } + + $createdAt = $createdAtRow['created_at']; + + // Fetch mail data for that timestamp + $mail_datas = $this->gmailSentHistoryModel + ->where('isactive', 1) + ->where('mail_type', "insurer") + ->where('pk', $leadId) + ->where("DATE_FORMAT(created_at, '%Y-%m-%d %H:%i')", $createdAt) + ->findAll(); + + if (empty($mail_datas)) { + $this->myLogger->logme("warning", "No mail data found for lead_id={$leadId} at created_at={$createdAt}"); + continue; + } + + // Filter only pending insurers + $quote_received_insurer = json_decode($lead['quote_received_insurer'] ?? "[]", true); + $reminder_mail_data = []; + + if (empty($quote_received_insurer)) { + $reminder_mail_data = $mail_datas; + } else { + foreach ($mail_datas as $mail_value) { + $insurer_id = $mail_value['common'] ?? ""; + if (!in_array($insurer_id, $quote_received_insurer)) { + $reminder_mail_data[] = $mail_value; + } + } + } + + // dd($reminder_mail_data); + if (empty($reminder_mail_data)) { + $this->myLogger->logme("info", "All insurers already responded for lead_id={$leadId}, no reminder needed"); + continue; + } + + $this->myLogger->logme("info", "Sending " . count($reminder_mail_data) . " reminder mail(s) for lead_id={$leadId}"); + + $common = ['module' => "leads", 'pk' => $leadId, 'mail_type' => "remainder", 'common' => null]; + + foreach ($reminder_mail_data as $content) { + $insurerId = $content['common'] ?? null; + $common['common'] = $insurerId; + + try { + + if ($lead['is_insurer_auto_mail'] == 1) { + // send reminder to insurer + $res = MailHelper::send_email([ + 'from_mail' => $from_mail, + 'mail' => $content['mail'] ?? "", + 'cc' => json_decode($content['cc'] ?? "", true) ?? "", + 'subject' => $mail_subject ?? "", + 'message' => $mail_content ?? "", + 'reply_to' => $reply_to, + 'bcc' => json_decode($content["bcc"] ?? "", true) ?? "", + 'common' => $common + ]); + $this->myLogger->logme("info", "Reminder mail sent to the insurer | lead_id={$leadId}, insurer_id={$insurerId}, response=" . json_encode($res)); + + $reminder_sended_lead[] = [ + 'lead_id' => $leadId, + 'insurer_id' => $insurerId, + 'response' => $res + ]; + } else{ + $this->myLogger->logme("info", "Reminder mail disable for this lead_id={$leadId}"); + } + + + } catch (\Throwable $e) { + $errorDetails = [ + 'error_message' => $e->getMessage(), + 'file' => $e->getFile(), + 'line' => $e->getLine(), + 'stack_trace' => $e->getTraceAsString(), + ]; + $this->myLogger->logme("error", "Exception while sending reminder | lead_id={$leadId}, insurer_id={$insurerId}, error=" . json_encode($errorDetails)); + $reminder_sended_lead[] = [ + 'lead_id' => $leadId, + 'insurer_id' => $insurerId, + 'response' => ['status' => false, 'error' => $errorDetails] + ]; + } + + // send reminder to sales person / creator only + $internal_mail_response = MailHelper::send_email([ + 'mail' => $from_mail, + 'cc' => $email_string, + 'subject' => $mail_subject ?? "", + 'message' => $mail_content ?? "", + 'common' => $common + ]); + + $this->myLogger->logme("info", "Reminder mail sent to sales persons | lead_id={$leadId}, recipients={$email_string}, response=" . json_encode($internal_mail_response)); + + + } + } + + return ['status' => true, "data" => $reminder_sended_lead]; + } + + } diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php index 61c5aedf..9838492c 100755 --- a/app/Controllers/MasterController.php +++ b/app/Controllers/MasterController.php @@ -1798,7 +1798,7 @@ class MasterController extends AdminController $email_id = CLI::getOption('to') ? CLI::getOption('to') : $email_id; // print_r($email_id);die(); // $gmailapi = \Config\Services::gmailapi(); - $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

'; + $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

'; // $attachments = [ // ["filePath" => WRITEPATH."uploads/excel/sample/correction.xls","fileName" => "correction.xls"], @@ -1821,7 +1821,7 @@ class MasterController extends AdminController public function testZeptoSMTP() { - $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

'; + $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

'; $attachments = [ ["filePath" => ROOTPATH . "public/sample_excel/sample_addition.xls", "fileName" => "sample_addition.xls"], ["filePath" => ROOTPATH . "public/sample_excel/sample_inception.xls", "fileName" => "sample_inception.xls"], @@ -1973,7 +1973,7 @@ class MasterController extends AdminController public function sendMutipleToEmails() { - $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

'; + $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

'; $attachments = [ ["filePath" => ROOTPATH . "public/sample_excel/sample_addition.xls", "fileName" => "sample_addition.xls"], ["filePath" => ROOTPATH . "public/sample_excel/sample_inception.xls", "fileName" => "sample_inception.xls"], diff --git a/app/Controllers/TestingController.php b/app/Controllers/TestingController.php new file mode 100644 index 00000000..8fe06352 --- /dev/null +++ b/app/Controllers/TestingController.php @@ -0,0 +1,25 @@ +request->getPost(); + + // For testing: just return the received data + return $this->respond([ + 'status' => 'success', + 'message' => 'Form data received successfully!', + 'data' => $data + ]); + } +} diff --git a/app/Controllers/ThzController.php b/app/Controllers/ThzController.php index e286d651..645b3ea6 100644 --- a/app/Controllers/ThzController.php +++ b/app/Controllers/ThzController.php @@ -8,12 +8,13 @@ use CodeIgniter\HTTP\ResponseInterface; use App\Models\ThzMasterModel; use App\Models\ThzMasterNotesModel; +use App\Models\ThzTypeModel; +use App\Models\ThzHistoryModel; use App\ControllerCleaners\ThzControllerCleaner; use App\Models\UserModel; use App\Models\ClientPolicyModel; use App\Models\ClientModel; use App\Models\TicketMailTemplateModel; -// use App\Models\TicketTypesModel; class ThzController extends BaseController @@ -21,7 +22,8 @@ class ThzController extends BaseController protected $thzMasterModel; protected $thzMasterNotesModel; - + protected $thzTypeModel; + protected $thzHistoryModel; protected $thzControllerCleaner; protected $userModel; @@ -29,17 +31,20 @@ class ThzController extends BaseController protected $clientModel; protected $ticketMailTemplateModel; - // protected $ticketTypesModel; + protected $myLogger; public function __construct() { $this->thzMasterModel = new ThzMasterModel(); $this->thzMasterNotesModel = new ThzMasterNotesModel(); + $this->thzTypeModel = new thzTypeModel(); + $this->thzHistoryModel = new ThzHistoryModel(); $this->thzControllerCleaner = new ThzControllerCleaner(); $this->userModel = new UserModel(); $this->clientPolicyModel = new ClientPolicyModel(); - $this->clientModel = new ClientModel(); + $this->clientModel = new ClientModel(); $this->ticketMailTemplateModel = new TicketMailTemplateModel(); + $this->myLogger = \Config\Services::mylogger(); } public function index() @@ -48,13 +53,36 @@ class ThzController extends BaseController } public function ticketSave(){ - + try + { $data = $this->request->getPost(); if (!empty($data['thz_id'])) { $text = "update"; $result = $this->updateTicket($data); + // here insert history Status. + $old = $this->thzMasterModel->where('thz_id', $data['thz_id'])->get()->getRowArray(); + + if ($old && isset($data['status'])) { + if ($old['status'] != $data['status']) { + $history = [ + 'thz_id' => $data['thz_id'], + 'field_name' => 'status', + 'display_name' => 'Status', + 'old_value' => $old['status'], + 'new_value' => $data['status'], + 'is_active' => 1 + ]; + + if (!empty(get_session_userid())) { + $history['created_by'] = get_session_userid(); + } + + $this->thzHistoryModel->insert($history); + } + } + $updateID = $data['thz_id']; } else { @@ -74,11 +102,27 @@ class ThzController extends BaseController 'message' => $result ? "Ticket {$text}d successfully " : "Unable to {$text} ticket. Please try again." , 'notification' => $emailNotificationResult ? 'Email Notification Success..!!' : 'Email Notification Failed..!!' ])->setStatusCode($result ? 200 : 400); + } catch (\Throwable $e) { + $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; + + $context = ['title' => get_class($e),'type' => get_class($e),'code' => $code,'message' => $e->getMessage(),'file' => $e->getFile(),'line' => $e->getLine()]; + + $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); + + return $this->response->setJSON([ 'status' => 'error', 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => $isDbError ? 'database' : 'application' . $code . ' / ' . $e->getLine() + ])->setStatusCode($code); + } } public function ticketList() { + try{ $returnType = strtolower($this->request->getGet('return_type') ?? 'api'); @@ -92,7 +136,8 @@ class ThzController extends BaseController if ($returnType === 'api') { if (empty($tickets)) { - return $this->response->setJSON([ 'status' => 'error','message' => 'No tickets found'])->setStatusCode(404); + // return $this->response->setJSON([ 'status' => 'error','message' => 'No tickets found'])->setStatusCode(404); + throw new \RuntimeException('No tickets found', 400); } }else{ @@ -101,18 +146,37 @@ class ThzController extends BaseController $data['assignee'] = $this->userModel->where('is_active', 1)->whereIn('role', ['2', '3','4'])->findAll(); // enga 5-"head" and 1-"admin" assign pannvaga so dropdown la varakudhathu // 2,3,4 remain person varannum. $data['client_list'] = $this->clientModel->getCreatedByUserName(); + $data['ticket_type'] = $this->thzTypeModel->where('is_active', 1)->findAll(); return $this->loadLayout('thz_list', $data); } + return $this->response->setJSON([ 'status' => 'success', 'data' => $tickets, ])->setStatusCode(200); + } + catch (\Throwable $e) { + $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; + + $context = ['title' => get_class($e),'type' => get_class($e),'code' => $code,'message' => $e->getMessage(),'file' => $e->getFile(),'line' => $e->getLine()]; + + $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); + + return $this->response->setJSON([ 'status' => 'error', 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => $isDbError ? 'database' : 'application' . $code . ' / ' . $e->getLine() + ])->setStatusCode($code); + } } public function ticketConversationSave(){ + try { $data = $this->request->getPost(); $data['notes_type'] = $data['notes_type'] ?? 'External' ; @@ -120,7 +184,8 @@ class ThzController extends BaseController $result = $this->thzMasterNotesModel->insert($data); if(empty($result)){ - return $this->response->setJSON((['status' => 'error', 'message' => 'No tickets found']))->setStatusCode(404); + // return $this->response->setJSON((['status' => 'error', 'message' => 'No tickets found']))->setStatusCode(404); + throw new \RuntimeException('No tickets found', 404); } if($data['notes_type'] == "External"){ @@ -136,41 +201,72 @@ class ThzController extends BaseController 'message' => $result ? "Ticket Notes created successfully" : "Unable to create ticket notes. Please try again." , 'notification' => $emailNotificationResult ? 'Email Notification Success..!!' : 'Email Notification Failed Or No Need..!!' ])->setStatusCode($result ? 200 : 400); + } + catch (\Throwable $e) { + $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; + + $context = ['title' => get_class($e),'type' => get_class($e),'code' => $code,'message' => $e->getMessage(),'file' => $e->getFile(),'line' => $e->getLine()]; + + $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); + return $this->response->setJSON([ 'status' => 'error', 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => $isDbError ? 'database' : 'application' . $code . ' / ' . $e->getLine() + ])->setStatusCode($code); + } } - public function ticketAutoFetchDetails(){ + public function ticketAutoFetchDetails() + { + try { $data = $this->request->getPost(); - $client_id = $data['client_id']; - $mobile = $data['mobile']; + $client_id = $data['client_id'] ?? null; + $mobile = $data['mobile'] ?? null; - if($client_id && $mobile){ - - $details = $this->thzMasterModel->ticketAutoFetchDetails($client_id ,$mobile); - - if(empty($details)){ - return $this->response->setJSON((['status' => 'error', 'message' => 'No Data found']))->setStatusCode(400); - }else{ - - $policyIds = array_column($details, 'policy_id'); - $policyIds = array_filter($policyIds); - $clientPolicy = $this->clientPolicyModel->whereIn('id', $policyIds)->where('is_active', 1)->get()->getResultArray(); - $result['client_details'] = $details; - $result['policy_details'] = empty($clientPolicy) ? [] : $clientPolicy ; + if ($client_id && $mobile) { + $details = $this->thzMasterModel->ticketAutoFetchDetails($client_id, $mobile); + if (empty($details)) { + throw new \RuntimeException('No Data found', 400); } - }else{ - return $this->response->setJSON((['status' => 'error', 'message' => 'Client and Mobile Not found']))->setStatusCode(400); - } - - return $this->response->setJSON((['status' => 'success', 'data' => $result]))->setStatusCode(200); - + $policyIds = array_filter(array_column($details, 'policy_id')); + $clientPolicy = !empty($policyIds) + ? $this->clientPolicyModel->whereIn('id', $policyIds)->where('is_active', 1)->get()->getResultArray() + : []; + + $result['client_details'] = $details; + $result['policy_details'] = $clientPolicy ?? []; + } else { + throw new \RuntimeException('Client and Mobile Not found', 400); + } + + return $this->response->setJSON(['status' => 'success', 'data' => $result])->setStatusCode(200); + + } + catch (\Throwable $e) { + $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; + + $context = ['title' => get_class($e),'type' => get_class($e),'code' => $code,'message' => $e->getMessage(),'file' => $e->getFile(),'line' => $e->getLine()]; + + $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); + + return $this->response->setJSON([ 'status' => 'error', 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => $isDbError ? 'database' : 'application' . $code . ' / ' . $e->getLine() + ])->setStatusCode($code); + } } - public function ticketConversationList(){ - + public function ticketConversationList() + { $data = $this->request->getGet(); $returnType = strtolower($this->request->getGet('return_type') ?? 'api'); @@ -190,16 +286,32 @@ class ThzController extends BaseController $notes = $this->thzMasterNotesModel->ticketConversationList($thz_id, $returnType ); $result['notes'] = !empty($notes) ? $notes : []; }else{ - return $this->response->setJSON((['status' => 'error', 'message' => 'No tickets found']))->setStatusCode(400); + // return $this->response->setJSON((['status' => 'error', 'message' => 'No tickets found']))->setStatusCode(400); + throw new \RuntimeException('No tickets found', 400); } }else{ - return $this->response->setJSON((['status' => 'error', 'message' => 'No tickets found']))->setStatusCode(404); + // return $this->response->setJSON((['status' => 'error', 'message' => 'No tickets found']))->setStatusCode(404); + throw new \RuntimeException('No tickets found', 404); } - - if ($returnType === 'api') { - return $this->response->setJSON((['status' => 'success', 'data' => $result]))->setStatusCode(200); + try { + return $this->response->setJSON((['status' => 'success', 'data' => $result]))->setStatusCode(200); + } catch (\Throwable $e) { + $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; + + $context = ['title' => get_class($e),'type' => get_class($e),'code' => $code,'message' => $e->getMessage(),'file' => $e->getFile(),'line' => $e->getLine()]; + + $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); + + return $this->response->setJSON([ 'status' => 'error', 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => $isDbError ? 'database' : 'application' . $code . ' / ' . $e->getLine() + ])->setStatusCode($code); + } }else{ $assign_to = $result['master'][0]['assign_to']; @@ -222,49 +334,104 @@ class ThzController extends BaseController $result['assignee'] = $this->userModel->where('is_active', 1)->whereIn('role', ['2', '3','4'])->findAll(); // enga 5-"head" and 1-"admin" assign pannvaga so dropdown la varakudhathu // 2,3,4 remain person varannum. $result['policy_terms'] = $toGetPolicyId ? $this->getPolicyTerms($toGetPolicyId) : ''; + + $result['ticket_type'] = $this->thzTypeModel->where('is_active', 1)->findAll(); return $this->loadLayout('thz_notes', $result); - } - + + } } - // public function ticketType() - // { - // $method = $this->request->getMethod(); // get, post - - // if ($method === 'get') { - - // $types = $this->ticketTypesModel->where('is_active', 1)->findAll(); - // if (empty($types)) { - // return $this->response->setJSON(['status' => 'error','message' => 'No ticket types found'])->setStatusCode(404); - // } - // return $this->response->setJSON(['status' => 'success','data' => $types])->setStatusCode(200); - - // } + public function ticketType() + { + $method = $this->request->getMethod(); // get, post + try{ + if ($method === 'get') { + $types = $this->thzTypeModel->select('id,name,is_active')->where('is_active', 1)->findAll(); + if (empty($types)) { + return $this->response->setJSON(['status' => 'error','message' => 'No ticket types found'])->setStatusCode(404); + } + return $this->response->setJSON(['status' => 'success','data' => $types])->setStatusCode(200); + } - // if ($method === 'post') { + if ($method === 'post') { - // $data = $this->request->getPost(); - // if (!empty($data['id'])) { - // $text = "update"; - // $result = $this->ticketTypesModel->update($data['id'], $data); - // $updateID = $data['id']; - // } else { - // $text = "create"; - // $insertID = $this->ticketTypesModel->insert($data); - // $result = true; - // } + $data = $this->request->getPost(); + if (!empty($data['id'])) { + $text = "update"; + $result = $this->thzTypeModel->update($data['id'], $data); + $updateID = $data['id']; + } else { + $text = "create"; + $insertID = $this->thzTypeModel->insert($data); + $result = true; + } - // $id = isset($insertID) && !empty($insertID) ? $insertID : $updateID ; + $id = isset($insertID) && !empty($insertID) ? $insertID : ($updateID ?? null); - // return $this->response->setJSON([ - // 'status' => $id ? 'success' : 'error', - // 'message' => $id ? "Ticket Type {$text}d successfully " : "Unable to {$text} ticket type. Please try again." , - // 'id' => $id - // ])->setStatusCode($id ? 200 : 400); - // } - // return $this->response->setJSON(['status' => 'error','message' => 'No ticket types found'])->setStatusCode(404); - // } + return $this->response->setJSON([ + 'status' => $id ? 'success' : 'error', + 'message' => $id ? "Ticket Type {$text}d successfully" : "Unable to {$text} ticket type. Please try again.", + 'id' => $id + ])->setStatusCode($id ? 200 : 400); + } + return $this->response->setJSON([ 'status' => 'error', 'message' => 'Invalid request method' ])->setStatusCode(405); + } + catch (\Throwable $e) { + $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; + + $context = ['title' => get_class($e),'type' => get_class($e),'code' => $code,'message' => $e->getMessage(),'file' => $e->getFile(),'line' => $e->getLine()]; + + $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); + + return $this->response->setJSON([ 'status' => 'error', 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => $isDbError ? 'database' : 'application' . $code . ' / ' . $e->getLine() + ])->setStatusCode($code); + } + } + + public function ticketHistoryList() + { + try + { + $data = $this->request->getGet(); + $thz_id = $data['thz_id']; + // $details = $this->thzHistoryModal->whereIn('thz_id', $thz_id)->where('is_active', 1)->get()->getResultArray(); + $details = $this->thzHistoryModel->select('thz_history.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_name) as created_name') + ->join('user_profiles', 'user_profiles.id = thz_history.created_by', 'left') + ->where('thz_history.thz_id', $thz_id)->where('thz_history.is_active', 1) + ->orderBy('thz_history.created_at', 'desc') + ->get()->getResultArray(); + + + + if (empty($details)) { + // return $this->response->setJSON([ 'status' => 'error','message' => 'No History found'])->setStatusCode(404); + throw new \RuntimeException('No History found', 404); + } + + + return $this->response->setJSON(['status' => 'success','data' => $details])->setStatusCode(200); + } catch (\Throwable $e) { + $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; + + $context = ['title' => get_class($e),'type' => get_class($e),'code' => $code,'message' => $e->getMessage(),'file' => $e->getFile(),'line' => $e->getLine()]; + + $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); + + return $this->response->setJSON([ 'status' => 'error', 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => $isDbError ? 'database / ' : 'application / ' . $code . ' / ' . $e->getLine() + ])->setStatusCode($code); + } + } /************************************************** PRIVATE FUNCTIONS ********************************************************/ diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php index 53ab6586..0fe8752b 100644 --- a/app/Controllers/TicketController.php +++ b/app/Controllers/TicketController.php @@ -1868,18 +1868,40 @@ class TicketController extends BaseController public function getPoliciesbyEmpID() { $received_data = $this->request->getPost(); + $ticket_type_id = $this->request->getPost('ticket_type_id') ?? null; $emp_id = $received_data['emp_id']; - + // Get all client policy IDs for the given employee - $policies = $this->employeePolicyModel - ->select('client_policy_id') - ->where('employee_id', $emp_id) - ->where('is_active', 1) - ->where('status', 'active') - ->findAll(); - + if ($ticket_type_id == 1) { + + //get the self data for get the all policy list aginst the emp_code + $self_data = $this->employeeModel->where('is_active', 1)->where('id', $emp_id)->first(); + + $db = db_connect(); + $builder = $db->table('employees e'); + $builder->select('ep.*'); + $builder->join('employee_polices ep', 'e.id = ep.employee_id'); + $builder->join('client_policy cp', 'cp.id = ep.client_policy_id AND cp.policy_type_id IN (2,3,4,5)'); + $builder->where('e.is_active', 1); + $builder->where('ep.is_active', 1); + $builder->where('e.emp_code', $self_data['emp_code']); + $builder->groupBy('client_policy_id'); + + $query = $builder->get(); + $policies = $query->getResultArray(); + } else { + + $policies = $this->employeePolicyModel + ->select('client_policy_id') + ->where('employee_id', $emp_id) + ->where('is_active', 1) + ->where('status', 'active') + ->findAll(); + } + + // Return empty if no policies found if (empty($policies)) { - return []; // Return empty if no policies found + return []; } // Extract client policy IDs into an array @@ -1902,7 +1924,7 @@ class TicketController extends BaseController ->join('tpa', 'tpa.id = client_policy.tpa_id AND tpa.is_active = 1', 'left') ->where('client_policy.policy_status', 1) ->whereIn('client_policy.id', $policy_ids) - ->findAll(); + ->findAll(); // dd($policyNameandID); if ($policyNameandID){ diff --git a/app/Controllers/VidalApiController.php b/app/Controllers/VidalApiController.php index 259e9841..36dc3f01 100644 --- a/app/Controllers/VidalApiController.php +++ b/app/Controllers/VidalApiController.php @@ -123,13 +123,21 @@ class VidalApiController extends BaseController } - public function newClaim(){ - + public function newClaim() + { $postData = $this->request->getPost(); + if (empty($postData)) { + return $this->response->setJSON([ + 'status' => false, + 'message' => 'Empty Data Given.', + 'data' => $postData + ]); + } + helper('api'); - $url = ''. getenv('VIDAL_API_BASE_URL').'/submitClaim'; + $url = getenv('VIDAL_API_BASE_URL') . '/submitClaim'; $method = 'POST'; $headers = [ @@ -138,27 +146,38 @@ class VidalApiController extends BaseController ]; $body = [ - 'username:' .getenv('VIDAL_API_USERNAME').'', - 'password:' .getenv('VIDAL_API_PASSWORD').'', - 'PolicyNo:' .$postData['policyNo'] ?? '', - 'enrollmentId:' .$postData['enrollmentId'] ?? '', - 'typeOfClaim:' .$postData['typeOfClaim'] ?? '', - 'claimSubType:' .$postData['claimSubType'] ?? '', - 'requestedAmount:' .$postData['requestedAmount'] ?? '', - 'ailmentType:' .$postData['ailmentType'] ?? '', - 'admissionDate:' .$postData['admissionDate'] ?? '', - 'dischargeDate:' .$postData['dischargeDate'] ?? '', - 'hospitalName:' .$postData['hospitalName'] ?? '', - 'empanelmentNo:' .$postData['empanelmentNo'] ?? '', - 'documentType:' .$postData['documentType'] ?? '', - 'ailmentName:' .$postData['ailmentName'] ?? '', - 'hospitalAddress:' .$postData['hospitalAddress'] ?? '', - 'hospitalState:' .$postData['hospitalState'] ?? '', - 'hospitalCity:' .$postData['hospitalCity'] ?? '', - 'hospitalPinCode:' .$postData['hospitalPinCode'] ?? '', - 'hospitalPhoneNo:' .$postData['hospitalPhoneNo'] ?? '' + 'username' => getenv('VIDAL_API_USERNAME'), + 'password' => getenv('VIDAL_API_PASSWORD'), + 'policyNo' => $postData['policyNo'] ?? '', + 'enrollmentId' => $postData['enrollmentId'] ?? '', + 'typeOfClaim' => $postData['typeOfClaim'] ?? '', + 'claimSubType' => $postData['claimSubType'] ?? '', + 'requestedAmount' => $postData['requestedAmount'] ?? '', + 'ailmentType' => $postData['ailmentType'] ?? '', + 'admissionDate' => $postData['admissionDate'] ?? '', + 'dischargeDate' => $postData['dischargeDate'] ?? '', + 'hospitalName' => $postData['hospitalName'] ?? '', + 'empanelmentNo' => $postData['empanelmentNo'] ?? '', + 'documentType' => $postData['documentType'] ?? '', + 'ailmentName' => $postData['ailmentName'] ?? '', + 'hospitalAddress' => $postData['hospitalAddress'] ?? '', + 'hospitalState' => $postData['hospitalState'] ?? '', + 'hospitalCity' => $postData['hospitalCity'] ?? '', + 'hospitalPinCode' => $postData['hospitalPinCode'] ?? '', + 'hospitalPhoneNo' => $postData['hospitalPhoneNo'] ?? '', ]; + // ✅ Handle file upload + if ($file = $this->request->getFile('File')) { + if ($file->isValid() && !$file->hasMoved()) { + $filePath = $file->getTempName(); + $originalName = $file->getClientName(); + $mimeType = $file->getMimeType(); + + $body['File'] = new \CURLFile($filePath, $mimeType, $originalName); + } + } + $response = call_third_party_api($url, $method, $headers, $body); if($response['status'] != true){ @@ -170,10 +189,10 @@ class VidalApiController extends BaseController } return $this->response->setJSON($response); - } + public function enrollment(){ $postData = $this->request->getJSON(true); diff --git a/app/Helpers/ChatbotHelper.php b/app/Helpers/ChatbotHelper.php index e1f213d3..b17161c2 100644 --- a/app/Helpers/ChatbotHelper.php +++ b/app/Helpers/ChatbotHelper.php @@ -393,18 +393,18 @@ class ChatbotHelper - +
- +
- +
@@ -412,12 +412,12 @@ class ChatbotHelper
- +
- +
@@ -449,7 +449,7 @@ class ChatbotHelper
- +
@@ -457,7 +457,7 @@ class ChatbotHelper
- +
@@ -492,7 +492,7 @@ class ChatbotHelper
- +
@@ -500,7 +500,7 @@ class ChatbotHelper
- +
@@ -514,7 +514,7 @@ class ChatbotHelper
- +
diff --git a/app/Helpers/MailHelper.php b/app/Helpers/MailHelper.php index cce74a9a..89e90262 100755 --- a/app/Helpers/MailHelper.php +++ b/app/Helpers/MailHelper.php @@ -322,6 +322,7 @@ class MailHelper $from_address = isset($params['from_mail']) && !empty($params['from_mail']) ? $params['from_mail'] : getenv('email.fromEmail'); // $from_address = "claims@nhanceindia.in"; + if(isset($params['common'])){ $params['common']['from_mail'] = $from_address; } try { $curl = curl_init(); diff --git a/app/Helpers/api_helper.php b/app/Helpers/api_helper.php index de9a0b64..95096fdb 100644 --- a/app/Helpers/api_helper.php +++ b/app/Helpers/api_helper.php @@ -59,6 +59,7 @@ if (!function_exists('call_third_party_api')) { } $decoded = json_decode($response, true); + return [ 'status' => ($httpCode >= 200 && $httpCode < 300), 'data' => $decoded ?: $response, // fallback to raw response diff --git a/app/Helpers/sendMailNotification.php b/app/Helpers/sendMailNotification.php index bd66c776..f9de6b09 100755 --- a/app/Helpers/sendMailNotification.php +++ b/app/Helpers/sendMailNotification.php @@ -305,7 +305,7 @@ class sendMailNotification } $table_content .= $policy_name_for_policy_type . ''; - $table_content .= ''; + $table_content .= '
'; // Add text-align: center to the table head $table_content .= ''; @@ -442,7 +442,7 @@ class sendMailNotification } $table_content .= $policy_name_for_policy_type . ' ( Payable By Employee ) '; - $table_content .= '
'; + $table_content .= '
'; // Add text-align: center to the table head $table_content .= ''; @@ -479,7 +479,7 @@ class sendMailNotification if (count($Addon_list) > 0) { $table_content .= '
'; - $table_content .= '
'; + $table_content .= '
'; // Center align for table header and body $table_content .= ''; @@ -655,7 +655,7 @@ class sendMailNotification } $table_content .= $policy_name_for_policy_type . ''; - $table_content .= '
'; + $table_content .= '
'; // Add text-align: center to the table head $table_content .= ''; @@ -741,7 +741,7 @@ class sendMailNotification } $table_content .= $policy_name_for_policy_type . ' ( Payable By Employee ) '; - $table_content .= '
'; + $table_content .= '
'; // Add text-align: center to the table head $table_content .= ''; @@ -779,7 +779,7 @@ class sendMailNotification if (count($Addon_list) > 0) { $table_content .= '
'; - $table_content .= '
'; + $table_content .= '
'; // Center align for table header and body $table_content .= ''; @@ -956,7 +956,7 @@ class sendMailNotification } $table_content .= $policy_name_for_policy_type . ''; - $table_content .= '
'; + $table_content .= '
'; // Add text-align: center to the table head $table_content .= ''; @@ -1042,7 +1042,7 @@ class sendMailNotification } $table_content .= $policy_name_for_policy_type . ' ( Payable By Employee ) '; - $table_content .= '
'; + $table_content .= '
'; // Add text-align: center to the table head $table_content .= ''; @@ -1079,7 +1079,7 @@ class sendMailNotification if (count($Addon_list) > 0) { $table_content .= '
'; - $table_content .= '
'; + $table_content .= '
'; // Center align for table header and body $table_content .= ''; @@ -1332,7 +1332,7 @@ class sendMailNotification // Start table row $table_content .= $policy_name . ''; - $table_content .= '
'; + $table_content .= '
'; $table_content .= ''; $table_content .= ''; $table_content .= ''; @@ -1384,7 +1384,7 @@ class sendMailNotification // Generate summary table for addon if applicable if (count($Addon_list) > 0) { $table_content .= '
'; - $table_content .= '
Name
'; + $table_content .= '
'; $table_content .= ''; $table_content .= ''; @@ -1482,7 +1482,7 @@ class sendMailNotification // Start table row $table_content .= $policy_name . ''; - $table_content .= '
'; + $table_content .= '
'; $table_content .= ''; $table_content .= ''; $table_content .= ''; @@ -1534,7 +1534,7 @@ class sendMailNotification // Generate summary table for addon if applicable if (count($Addon_list) > 0) { $table_content .= '
'; - $table_content .= '
Name
'; + $table_content .= '
'; $table_content .= ''; $table_content .= ''; @@ -1630,7 +1630,7 @@ class sendMailNotification // Start table row $table_content .= $policy_name . ''; - $table_content .= '
'; + $table_content .= '
'; $table_content .= ''; $table_content .= ''; $table_content .= ''; @@ -1683,7 +1683,7 @@ class sendMailNotification if (count($Addon_list) > 0) { $table_content .= '
'; - $table_content .= '
Name
'; + $table_content .= '
'; $table_content .= ''; $table_content .= ''; diff --git a/app/Models/BatchFileModel.php b/app/Models/BatchFileModel.php index b8ebc8e9..e791553a 100755 --- a/app/Models/BatchFileModel.php +++ b/app/Models/BatchFileModel.php @@ -25,6 +25,7 @@ class BatchFileModel extends Model "status", "error_data", "client_branch_id", + "policy_issue_date", ]; // Callbacks diff --git a/app/Models/GmailSentHistoryModel.php b/app/Models/GmailSentHistoryModel.php index 9a0ae8ea..75abbbe0 100644 --- a/app/Models/GmailSentHistoryModel.php +++ b/app/Models/GmailSentHistoryModel.php @@ -7,5 +7,5 @@ use CodeIgniter\Model; class GmailSentHistoryModel extends Model{ protected $table = 'gmail_sent_history'; protected $primaryKey = 'id'; - protected $allowedFields = ["id", "mail", "bcc", "cc", "message", "attachments", "client_id", "client_branch_id", "client_policy_id", "employee_policy_id", "employee_id", "mail_type", "gmail_api_status", "gmail_api_id", "created_by", "created_at", "updated_by", "updated_at", "isactive","received_message"]; + protected $allowedFields = ["id", "mail", "bcc", "cc", "message", "attachments", "client_id", "client_branch_id", "client_policy_id", "employee_policy_id", "employee_id", "mail_type", "gmail_api_status", "gmail_api_id", "module", "pk", "from_mail", "created_by", "created_at", "updated_by", "updated_at", "isactive","received_message", "common"]; } \ No newline at end of file diff --git a/app/Models/LeadsModel.php b/app/Models/LeadsModel.php index 4a8498ef..67a354b1 100644 --- a/app/Models/LeadsModel.php +++ b/app/Models/LeadsModel.php @@ -101,6 +101,10 @@ class LeadsModel extends Model 'total_lives_at_incept', 'premium_at_incept', + + 'next_reminder_date', + 'is_insurer_auto_mail', + 'quote_received_insurer', ]; diff --git a/app/Models/LevelContactModel.php b/app/Models/LevelContactModel.php index cf5d596d..bfdeb97c 100755 --- a/app/Models/LevelContactModel.php +++ b/app/Models/LevelContactModel.php @@ -33,7 +33,9 @@ class LevelContactModel extends Model ->select(' level_contacts.id, insurers.short_name as insurer_name, + insurers.id as insurer_id, insurer_branch.branch_code, + insurer_branch.id as insurer_branch_id, level_contacts.name as contact_person_name, level_contacts.email as contact_person_email ') @@ -51,7 +53,7 @@ class LevelContactModel extends Model $query->where('insurer_branch.insurer_id', $insurer_id); } - $result = $query->get()->getResultArray(); + $result = $query->orderBy('insurers.id')->get()->getResultArray(); return $result; } diff --git a/app/Models/ThzHistoryModel.php b/app/Models/ThzHistoryModel.php new file mode 100644 index 00000000..f7dd22d2 --- /dev/null +++ b/app/Models/ThzHistoryModel.php @@ -0,0 +1,45 @@ +/assets/images/active_pending_actions.png" alt="Logo" height="14" class="active_pending" style="display:none;">    - Pending Actions + Pending Actions      @@ -235,7 +235,7 @@ /assets/images/active_bds.png" alt="Logo" height="14" class="active_bds " style="display:none;">    - BDS + BDS      @@ -251,7 +251,7 @@ /assets/images/active_claims.png" alt="Logo" height="14" class="active_claims " style="display:none;">    - Claims + Claims      @@ -266,7 +266,7 @@ /assets/images/active_leads_and_bds_renewal.png" alt="Logo" height="14" class="active_leads " style="display:none;">    - Leads and BDS Renewals + Leads and BDS Renewals      diff --git a/app/Views/UserList.php b/app/Views/UserList.php index 088b15d0..d9d73f2a 100755 --- a/app/Views/UserList.php +++ b/app/Views/UserList.php @@ -249,7 +249,7 @@ table.dataTable tbody td {

User List

-
+
@@ -383,7 +383,7 @@ table.dataTable tbody td {
-
Name
+
@@ -475,7 +475,7 @@ table.dataTable tbody td {
-
Team
+
diff --git a/app/Views/add_image_list.php b/app/Views/add_image_list.php index 9658053d..05aad57a 100755 --- a/app/Views/add_image_list.php +++ b/app/Views/add_image_list.php @@ -30,7 +30,7 @@ table.dataTable thead th { ADD -
Team
diff --git a/app/Views/batch_list.php b/app/Views/batch_list.php index c754ecc0..163b33cb 100755 --- a/app/Views/batch_list.php +++ b/app/Views/batch_list.php @@ -25,7 +25,7 @@
-
+
diff --git a/app/Views/bds_multi_report.php b/app/Views/bds_multi_report.php index 05b38e6c..ce37847e 100644 --- a/app/Views/bds_multi_report.php +++ b/app/Views/bds_multi_report.php @@ -33,7 +33,7 @@
-
SNO
+
-
+
diff --git a/app/Views/bds_report_Insurer_wise_Data.php b/app/Views/bds_report_Insurer_wise_Data.php index d97e6f18..79159730 100644 --- a/app/Views/bds_report_Insurer_wise_Data.php +++ b/app/Views/bds_report_Insurer_wise_Data.php @@ -30,7 +30,7 @@ table.dataTable tbody td {
- +
diff --git a/app/Views/bds_report_bap_wise_data.php b/app/Views/bds_report_bap_wise_data.php index 391e6526..c0a69a8b 100644 --- a/app/Views/bds_report_bap_wise_data.php +++ b/app/Views/bds_report_bap_wise_data.php @@ -30,7 +30,7 @@ table.dataTable tbody td {
-
Insurer
+
diff --git a/app/Views/bds_tat_wise_report.php b/app/Views/bds_tat_wise_report.php index e3c428f4..721cd07c 100644 --- a/app/Views/bds_tat_wise_report.php +++ b/app/Views/bds_tat_wise_report.php @@ -33,7 +33,7 @@
-
Insurer
+
-
+
diff --git a/app/Views/cd_master_list.php b/app/Views/cd_master_list.php index 1df5c220..3e6e0922 100755 --- a/app/Views/cd_master_list.php +++ b/app/Views/cd_master_list.php @@ -66,7 +66,7 @@ table.dataTable thead th { data-trigger="hover">ADD --> -
S.No
+
diff --git a/app/Views/claim_dump_file_list.php b/app/Views/claim_dump_file_list.php index 52918801..0c1d6906 100644 --- a/app/Views/claim_dump_file_list.php +++ b/app/Views/claim_dump_file_list.php @@ -68,7 +68,7 @@ -
S.No.
+
diff --git a/app/Views/claim_files_upload.php b/app/Views/claim_files_upload.php index 8fa2ad4c..5652432c 100644 --- a/app/Views/claim_files_upload.php +++ b/app/Views/claim_files_upload.php @@ -45,7 +45,7 @@
-
SNO
+
diff --git a/app/Views/claims_report_acc_manager_wise.php b/app/Views/claims_report_acc_manager_wise.php index 3816a419..659646b8 100644 --- a/app/Views/claims_report_acc_manager_wise.php +++ b/app/Views/claims_report_acc_manager_wise.php @@ -33,7 +33,7 @@
-
S.No
+
diff --git a/app/Views/claims_report_tpa_wise.php b/app/Views/claims_report_tpa_wise.php index d473d717..36b3412c 100644 --- a/app/Views/claims_report_tpa_wise.php +++ b/app/Views/claims_report_tpa_wise.php @@ -29,7 +29,7 @@
-
+
diff --git a/app/Views/client_api.php b/app/Views/client_api.php index 8fe995d5..e57051f4 100644 --- a/app/Views/client_api.php +++ b/app/Views/client_api.php @@ -44,7 +44,7 @@ --> -
OPEN
diff --git a/app/Views/client_info.php b/app/Views/client_info.php index 485684dc..b4c286d3 100755 --- a/app/Views/client_info.php +++ b/app/Views/client_info.php @@ -39,7 +39,7 @@
-
+
@@ -120,7 +120,7 @@
-
@@ -205,7 +205,7 @@
-
diff --git a/app/Views/client_kyc.php b/app/Views/client_kyc.php index 99bab2b1..aff9953a 100755 --- a/app/Views/client_kyc.php +++ b/app/Views/client_kyc.php @@ -9,7 +9,7 @@
-
+
@@ -70,7 +70,7 @@
-
Document Name
+
@@ -310,7 +310,7 @@ `; @@ -424,7 +424,7 @@ `; tbody.append(row); @@ -480,7 +480,7 @@ `; diff --git a/app/Views/client_list.php b/app/Views/client_list.php index 346f9f10..8275c156 100755 --- a/app/Views/client_list.php +++ b/app/Views/client_list.php @@ -65,7 +65,7 @@ table.dataTable thead th { " type="button" id="btnAdd" class="btn btn-primary waves-effect waves-light" data-toggle="" data-placement="top" title="Add" data-trigger="hover">Add --> -
Document Name${item.other_docs_name} ${item.file_name} - +
- +
${item.other_docs_name} ${item.file_name} - +
diff --git a/app/Views/client_policy.php b/app/Views/client_policy.php index 972c96ef..4f712bca 100755 --- a/app/Views/client_policy.php +++ b/app/Views/client_policy.php @@ -28,7 +28,7 @@
-
+
@@ -425,7 +425,7 @@ // Conditionally render the delete option based on the role if (role !== 3 && role !== 4) { policyTable += ` - Delete`; + Delete`; } policyTable += ` diff --git a/app/Views/dms_search.php b/app/Views/dms_search.php index 550acdf4..58fd2da3 100644 --- a/app/Views/dms_search.php +++ b/app/Views/dms_search.php @@ -99,7 +99,7 @@
-
Insurer
+
@@ -118,7 +118,7 @@
S.No diff --git a/app/Views/drive_file_upload.php b/app/Views/drive_file_upload.php index 158598ec..275b5c6f 100644 --- a/app/Views/drive_file_upload.php +++ b/app/Views/drive_file_upload.php @@ -45,7 +45,7 @@
- +
diff --git a/app/Views/ecard_template/default_ecard.php b/app/Views/ecard_template/default_ecard.php index 0ed04d23..f985a04f 100755 --- a/app/Views/ecard_template/default_ecard.php +++ b/app/Views/ecard_template/default_ecard.php @@ -15,7 +15,7 @@ -
S.No
+
$value) { ?> diff --git a/app/Views/ecard_template/fhpl_tpa.php b/app/Views/ecard_template/fhpl_tpa.php index 4b849f69..3bb3c0cc 100755 --- a/app/Views/ecard_template/fhpl_tpa.php +++ b/app/Views/ecard_template/fhpl_tpa.php @@ -17,7 +17,7 @@ -
+
$value) { ?> @@ -36,7 +36,7 @@
-
+
diff --git a/app/Views/ecard_template/icici_tpa.php b/app/Views/ecard_template/icici_tpa.php index a590bdf1..0206d9f5 100755 --- a/app/Views/ecard_template/icici_tpa.php +++ b/app/Views/ecard_template/icici_tpa.php @@ -8,7 +8,7 @@ - +
$value) { ?> @@ -25,7 +25,7 @@
-
+
diff --git a/app/Views/ecard_template/md_tpa.php b/app/Views/ecard_template/md_tpa.php index 8cec0a84..36eb359e 100755 --- a/app/Views/ecard_template/md_tpa.php +++ b/app/Views/ecard_template/md_tpa.php @@ -12,7 +12,7 @@ POLICY - @@ -40,7 +40,7 @@
The card is for identification purpose only
-
+
@@ -50,7 +50,7 @@
General & Claim Enquiry Helpline
- +
- + `; tableBody.appendChild(newRow); @@ -871,7 +871,7 @@ function showInvoiceStatusModal(event) - + `; }); } diff --git a/app/Views/irda_bap_insurer_report_list.php b/app/Views/irda_bap_insurer_report_list.php index 116e201d..7d9e9773 100644 --- a/app/Views/irda_bap_insurer_report_list.php +++ b/app/Views/irda_bap_insurer_report_list.php @@ -32,7 +32,7 @@ table.dataTable tbody td {
-
Toll Free : 1800-209-7777
Email : @@ -63,7 +63,7 @@
CITI MDIndia branch contact
- +
diff --git a/app/Views/employee_data_list.php b/app/Views/employee_data_list.php index 08d47835..207f9328 100755 --- a/app/Views/employee_data_list.php +++ b/app/Views/employee_data_list.php @@ -89,7 +89,7 @@

Employees

-
Center
+
@@ -670,7 +670,7 @@ let historyTable = `
-
SNO
+
diff --git a/app/Views/endorsement_dash.php b/app/Views/endorsement_dash.php index adfd445e..1994460a 100755 --- a/app/Views/endorsement_dash.php +++ b/app/Views/endorsement_dash.php @@ -374,7 +374,7 @@ function getPendingActionClientDataForDashboard(input, headerName, type) var link = ''; if (res.data.length !== 0) { - // table = `
Field
`; + // table = `
`; div = `
`; $.each(res.data, function(index, item) { diff --git a/app/Views/endorsement_list.php b/app/Views/endorsement_list.php index 6ee6ff14..14696fda 100755 --- a/app/Views/endorsement_list.php +++ b/app/Views/endorsement_list.php @@ -87,7 +87,7 @@
-
+
@@ -163,7 +163,7 @@
SNO
+
diff --git a/app/Views/enrollment_list.php b/app/Views/enrollment_list.php index 96da7591..4448f795 100755 --- a/app/Views/enrollment_list.php +++ b/app/Views/enrollment_list.php @@ -181,7 +181,7 @@
-
+
diff --git a/app/Views/errors/html/error_exception.php b/app/Views/errors/html/error_exception.php index 1c094d72..e1d18561 100755 --- a/app/Views/errors/html/error_exception.php +++ b/app/Views/errors/html/error_exception.php @@ -86,7 +86,7 @@ $errorId = uniqid('error', true); ( arguments )
-
SNO
+
$ -
+
@@ -168,7 +168,7 @@ $errorId = uniqid('error', true);

Constants

-
Key
+
@@ -197,7 +197,7 @@ $errorId = uniqid('error', true);
-
Key
+
@@ -243,7 +243,7 @@ $errorId = uniqid('error', true);

$

-
Path
+
@@ -281,7 +281,7 @@ $errorId = uniqid('error', true);

Headers

-
Key
+
@@ -307,7 +307,7 @@ $errorId = uniqid('error', true); $response->setStatusCode(http_response_code()); ?>
-
Header
+
@@ -320,7 +320,7 @@ $errorId = uniqid('error', true);

Headers

-
Response Status getStatusCode() . ' - ' . $response->getReasonPhrase()) ?>
+
@@ -354,7 +354,7 @@ $errorId = uniqid('error', true);
-
Header
+
diff --git a/app/Views/excel_errors.php b/app/Views/excel_errors.php index 7c09353c..04db844d 100755 --- a/app/Views/excel_errors.php +++ b/app/Views/excel_errors.php @@ -68,7 +68,7 @@ table.dataTable tbody td {
-
Memory Usage
+
diff --git a/app/Views/export_import_error_list.php b/app/Views/export_import_error_list.php index fcadf402..3176ce68 100755 --- a/app/Views/export_import_error_list.php +++ b/app/Views/export_import_error_list.php @@ -68,7 +68,7 @@ table.dataTable tbody td {
-
+
diff --git a/app/Views/file_list.php b/app/Views/file_list.php index cf7b4d6a..bceb3554 100755 --- a/app/Views/file_list.php +++ b/app/Views/file_list.php @@ -19,7 +19,7 @@ -
diff --git a/app/Views/finance_team_list.php b/app/Views/finance_team_list.php index 9613b9df..ffb991ea 100644 --- a/app/Views/finance_team_list.php +++ b/app/Views/finance_team_list.php @@ -179,7 +179,7 @@ table.dataTable tbody td {
-
+
diff --git a/app/Views/hr_activity_history.php b/app/Views/hr_activity_history.php index 15d53361..a6da3ad8 100644 --- a/app/Views/hr_activity_history.php +++ b/app/Views/hr_activity_history.php @@ -38,7 +38,7 @@ table.dataTable tbody td { -
S.No
+
diff --git a/app/Views/hr_file_upload.php b/app/Views/hr_file_upload.php index 7d6ed59d..936d603f 100644 --- a/app/Views/hr_file_upload.php +++ b/app/Views/hr_file_upload.php @@ -99,7 +99,7 @@ -
S. No
diff --git a/app/Views/insurer_branch.php b/app/Views/insurer_branch.php index 915114f3..6d4e0309 100755 --- a/app/Views/insurer_branch.php +++ b/app/Views/insurer_branch.php @@ -6,7 +6,7 @@
-
+
diff --git a/app/Views/insurer_export_templete.php b/app/Views/insurer_export_templete.php index 33ed64c8..77a55bee 100755 --- a/app/Views/insurer_export_templete.php +++ b/app/Views/insurer_export_templete.php @@ -74,7 +74,7 @@
-
Branch Name
+
diff --git a/app/Views/insurer_list.php b/app/Views/insurer_list.php index e7ce6e82..ff42e50b 100755 --- a/app/Views/insurer_list.php +++ b/app/Views/insurer_list.php @@ -49,7 +49,7 @@

Insurer List

-
S.NO
diff --git a/app/Views/insurer_or_tpa_data.php b/app/Views/insurer_or_tpa_data.php index 6c22b23c..dc07ab1c 100755 --- a/app/Views/insurer_or_tpa_data.php +++ b/app/Views/insurer_or_tpa_data.php @@ -90,9 +90,15 @@ +
-
 [ ] @@ -144,6 +150,16 @@ }); + $(document).ready(function() { + + var policy_issue_datePicker = flatpickr("#policy_issue_date", { + dateFormat: "d/m/Y", + allowInput: false, + }); + + $('#insurer_or_tpa, #action_type').on('change', togglePolicyIssueDate); + }); + $(document).ready(function() { has('error')) : ?> @@ -730,4 +746,19 @@ //------------------------------------------------------------------------------------------------------ + + \ No newline at end of file diff --git a/app/Views/insurer_statement_list.php b/app/Views/insurer_statement_list.php index fed5f122..6689488a 100644 --- a/app/Views/insurer_statement_list.php +++ b/app/Views/insurer_statement_list.php @@ -175,7 +175,7 @@ table.dataTable tbody td {
-
+
@@ -425,7 +425,7 @@ table.dataTable tbody td { -
+
@@ -445,7 +445,7 @@ table.dataTable tbody td { - +
pk
@@ -728,7 +728,7 @@ document.addEventListener("DOMContentLoaded", function () {
+
diff --git a/app/Views/irda_client_report_list.php b/app/Views/irda_client_report_list.php index 70ba446f..e3006e95 100644 --- a/app/Views/irda_client_report_list.php +++ b/app/Views/irda_client_report_list.php @@ -32,7 +32,7 @@ table.dataTable tbody td {
-
+
diff --git a/app/Views/kyc_docs.php b/app/Views/kyc_docs.php index 9bb1ab5a..22636a6d 100755 --- a/app/Views/kyc_docs.php +++ b/app/Views/kyc_docs.php @@ -6,7 +6,7 @@
-
S. No
+
diff --git a/app/Views/kyc_list.php b/app/Views/kyc_list.php index 8e8eefd6..ff785b59 100755 --- a/app/Views/kyc_list.php +++ b/app/Views/kyc_list.php @@ -49,7 +49,7 @@

KYC List

-
File Name
diff --git a/app/Views/layout/header.php b/app/Views/layout/header.php index b1ca7453..35ad766e 100755 --- a/app/Views/layout/header.php +++ b/app/Views/layout/header.php @@ -97,17 +97,7 @@ + + @@ -855,7 +918,7 @@ a.app-badge-secondary:focus, a.app-badge-secondary.focus { - +
  • /assets/images/ticket.png" alt="Logo" height="20"> diff --git a/app/Views/leads_form.php b/app/Views/leads_form.php index f6370884..aa40bc28 100644 --- a/app/Views/leads_form.php +++ b/app/Views/leads_form.php @@ -332,6 +332,20 @@ +
    + + +
    + +
    + + + +
    +
    @@ -556,6 +570,12 @@ console.log('---- completed ----') + var next_reminder_date = flatpickr("#next_reminder_date", { + dateFormat: "d/m/Y", + allowInput: false, + maxDate: "today" + }); + }) //------------------------------ GET DATA ( EDIT, BRANCH, POLICY ) --------------------------------------------------------------------------- diff --git a/app/Views/leads_form_handler.php b/app/Views/leads_form_handler.php index b3b0f1ba..484a5f2f 100644 --- a/app/Views/leads_form_handler.php +++ b/app/Views/leads_form_handler.php @@ -823,6 +823,13 @@ if (isset($selected_lead_type)) { $('#entity_type_id').val(data.entity_type_id || ''); $('#lead_status').val(data.status || ''); $('#notes').val(data.notes || ''); + $('#next_reminder_date').val(data.next_reminder_date || ''); + + if (data.is_insurer_auto_mail == 1) { + $('#is_insurer_auto_mail').prop('checked', true); + } else { + $('#is_insurer_auto_mail').prop('checked', false); + } // setTimeout(() => { // $('#client_id').val(data.client_id || '').change(); @@ -1144,7 +1151,5 @@ if (isset($selected_lead_type)) { }); } - - diff --git a/app/Views/leads_list.php b/app/Views/leads_list.php index 85cd4a6c..f15c18b0 100644 --- a/app/Views/leads_list.php +++ b/app/Views/leads_list.php @@ -160,7 +160,7 @@ table.dataTable tbody td {
    -
  • +
    @@ -215,6 +215,12 @@ table.dataTable tbody td { + + Email History + @@ -266,6 +272,22 @@ table.dataTable tbody td { + + + + + \ No newline at end of file diff --git a/app/Views/log_view.php b/app/Views/log_view.php index d7791d34..ebb77fc0 100644 --- a/app/Views/log_view.php +++ b/app/Views/log_view.php @@ -20,7 +20,7 @@ table.dataTable tbody td {

    getFlashdata('error') ?>

    -
    +
    diff --git a/app/Views/notification old.php b/app/Views/notification old.php index ed5f8ee5..11cc74ed 100644 --- a/app/Views/notification old.php +++ b/app/Views/notification old.php @@ -276,7 +276,7 @@ -
    S.No.
    +
    @@ -446,7 +446,7 @@ -
    Attachments
    +
    @@ -1494,7 +1494,7 @@ template_name = ''; newRow.innerHTML = ` - + `; container.appendChild(newRow); diff --git a/app/Views/notification.php b/app/Views/notification.php index 316ebae9..7ab83ccb 100755 --- a/app/Views/notification.php +++ b/app/Views/notification.php @@ -271,7 +271,7 @@ -
    Attachments ${item.file_name}
    +
    @@ -450,7 +450,7 @@ -
    Attachments
    +
    @@ -860,7 +860,7 @@ newRow.innerHTML = ` - + `; container.appendChild(newRow); @@ -1155,7 +1155,7 @@ newRow.innerHTML = ` - + `; container.appendChild(newRow); diff --git a/app/Views/other_policy_terms.php b/app/Views/other_policy_terms.php index 9cdf9887..03850e4b 100755 --- a/app/Views/other_policy_terms.php +++ b/app/Views/other_policy_terms.php @@ -229,6 +229,7 @@ }); var policy_type_id = ""; + var other_auto_save_enable = false; $('body').on('click', '.btnPolicyMaster', function() { $("#append_html_for_other_policy_terms").empty(); @@ -276,10 +277,12 @@ if (res.emp_count_by_policy != 0) { $("#btnOtherTermsSubmit").hide(); $("#otherButtonSpecialCondition").hide(); + other_auto_save_enable = false; } else { $("#btnOtherTermsSubmit").show(); $("#otherButtonSpecialCondition").show(); - startAutoSubmit('OTHERS'); + // startAutoSubmit('OTHERS'); + other_auto_save_enable = true; } @@ -760,12 +763,12 @@ } function beautifyString(str) { - return str - .split('_') // Split the string by underscores - .map(word => - word.charAt(0).toUpperCase() + word.slice(1).toLowerCase() // Capitalize each word - ) - .join(' '); // Join with spaces instead of underscores + return str + .split('_') // Split the string by underscores + .map(word => + word.charAt(0).toUpperCase() + word.slice(1).toLowerCase() // Capitalize each word + ) + .join(' '); // Join with spaces instead of underscores } function autoSaveOtherTerms(){ @@ -836,4 +839,42 @@ } + function debounceothers(fn, delay) { + let timeout; + return function () { + clearTimeout(timeout); + timeout = setTimeout(fn, delay); + }; + } + + $(document).ready(function () { + const form = document.querySelector("#otherPolicyTerms"); + + // MutationObserver (always runs) + const observer = new MutationObserver(() => { + $("#otherPolicyTerms").find("input, select, textarea").each(function () { + if (other_auto_save_enable) { // only bind autosave if enabled + if (!$(this).attr("data-observed")) { + const debouncedSave = debounceothers(autoSaveOtherTerms, 1000); + $(this).on("input change", debouncedSave); + $(this).attr("data-observed", "true"); + } + } + }); + }); + + observer.observe(form, { childList: true, subtree: true }); + + // Bind for existing fields (only if enabled) + if (other_auto_save_enable) { + const debouncedSave = debounceothers(autoSaveOtherTerms, 1000); + $("#otherPolicyTerms").find("input, select, textarea").each(function () { + $(this).on("input change", debouncedSave); + $(this).attr("data-observed", "true"); + }); + } else { + console.log("This policy has employee processed (autosave disabled) -- OTHERS") ; + } + }); + \ No newline at end of file diff --git a/app/Views/outstanding_report_list.php b/app/Views/outstanding_report_list.php index 682180a8..25f89043 100644 --- a/app/Views/outstanding_report_list.php +++ b/app/Views/outstanding_report_list.php @@ -167,7 +167,7 @@ table.dataTable tbody td {
    -
    Attachments ${item.file_name} ${item.file_name}
    +
    diff --git a/app/Views/policies.php b/app/Views/policies.php index 08e8059f..558e5772 100755 --- a/app/Views/policies.php +++ b/app/Views/policies.php @@ -6,7 +6,7 @@
    -
    S.No
    +
    diff --git a/app/Views/policy_gmc_terms.php b/app/Views/policy_gmc_terms.php index 596f7a21..4dace342 100755 --- a/app/Views/policy_gmc_terms.php +++ b/app/Views/policy_gmc_terms.php @@ -155,7 +155,7 @@
    -
    Insurer
    +
    @@ -283,7 +283,7 @@
    -
    Self:
    +
    @@ -861,8 +861,10 @@
    - Yes + + No +
    @@ -887,6 +889,7 @@ \ No newline at end of file diff --git a/app/Views/policy_gpa_terms.php b/app/Views/policy_gpa_terms.php index 513ee345..77168662 100755 --- a/app/Views/policy_gpa_terms.php +++ b/app/Views/policy_gpa_terms.php @@ -136,7 +136,7 @@
    - +
    @@ -473,6 +473,7 @@ var policy_grid_id = $('#client_id').val(); var grid_html = ''; + var gpa_auto_save_enable = false; $("#policyGPATerms").submit(function(event) { @@ -603,10 +604,12 @@ if (res.emp_count_by_policy != 0) { $("#btnGPATermsSubmit").hide(); $("#gpaButtonSpecialCondition").hide(); + gpa_auto_save_enable = false; } else { $("#btnGPATermsSubmit").show(); $("#gpaButtonSpecialCondition").show(); startAutoSubmit('GPA'); + gpa_auto_save_enable = true; } @@ -720,7 +723,17 @@ // console.log('jsonObject value', jsonObject[key]) // console.log('jsonObject value type', typeof jsonObject[key]) - let elements = document.getElementsByName(key); + let elements; // declare the element variable + + if (key === "terrorism") { + let form = document.getElementById("policyGPATerms"); + elements = form.querySelectorAll('[name="terrorism"]'); + } else { + elements = document.getElementsByName(key); + } + + + // let elements = document.getElementsByName(key); if (elements && elements.length > 0) { let element = elements[0]; @@ -1086,4 +1099,43 @@ }); } + function debouncegpa(fn, delay) { + let timeout; + return function () { + clearTimeout(timeout); + timeout = setTimeout(fn, delay); + }; + } + + $(document).ready(function () { + const form = document.querySelector("#policyGPATerms"); + + // MutationObserver (always runs) + const observer = new MutationObserver(() => { + $("#policyGPATerms").find("input, select, textarea").each(function () { + if (gpa_auto_save_enable) { // only bind autosave if enabled + if (!$(this).attr("data-observed")) { + const debouncedSave = debouncegpa(autoSaveGpaTerms, 1000); + $(this).on("input change", debouncedSave); + $(this).attr("data-observed", "true"); + } + } + }); + }); + + observer.observe(form, { childList: true, subtree: true }); + + // Bind for existing fields (only if enabled) + if (gpa_auto_save_enable) { + const debouncedSave = debouncegpa(autoSaveGpaTerms, 1000); + $("#policyGPATerms").find("input, select, textarea").each(function () { + $(this).on("input change", debouncedSave); + $(this).attr("data-observed", "true"); + }); + } else { + console.log("This policy has employee processed (autosave disabled) -- GPA"); + } + }); + + \ No newline at end of file diff --git a/app/Views/policy_grid.php b/app/Views/policy_grid.php index 53c61966..546ff2ab 100755 --- a/app/Views/policy_grid.php +++ b/app/Views/policy_grid.php @@ -2917,7 +2917,7 @@ function createCheckboxes(obj, additional_relationship = [], unique_id = null, p
    -
    +
    `; diff --git a/app/Views/policy_grid_excel.php b/app/Views/policy_grid_excel.php index 6634f35a..10ee30b7 100755 --- a/app/Views/policy_grid_excel.php +++ b/app/Views/policy_grid_excel.php @@ -339,7 +339,7 @@ function generateTable(unique_id) { } } - var table = $('
    '); + var table = $('
    '); var uniqueRows = new Set(); var emptyCellCount = 0; diff --git a/app/Views/policy_transaction_endorsement_form.php b/app/Views/policy_transaction_endorsement_form.php index 3400d1a2..b90bfe5e 100644 --- a/app/Views/policy_transaction_endorsement_form.php +++ b/app/Views/policy_transaction_endorsement_form.php @@ -349,7 +349,7 @@
    -
    +
    @@ -1691,7 +1691,7 @@ function addInsurerColumn() { $('#insurerTable thead tr').append(` `); diff --git a/app/Views/policy_transaction_endorsement_list.php b/app/Views/policy_transaction_endorsement_list.php index 03530e65..e15ccfd8 100644 --- a/app/Views/policy_transaction_endorsement_list.php +++ b/app/Views/policy_transaction_endorsement_list.php @@ -305,7 +305,7 @@ custom-dropdown-menu {
    -
    Premium Details Insurer ${insurerCount} - ${insurerCount > 1 ? `` : ''} + ${insurerCount > 1 ? `` : ''}
    +
    diff --git a/app/Views/policy_transaction_inception_form.php b/app/Views/policy_transaction_inception_form.php index 9e095f2e..fa46e077 100644 --- a/app/Views/policy_transaction_inception_form.php +++ b/app/Views/policy_transaction_inception_form.php @@ -642,7 +642,7 @@
    -
    Sno
    +
    @@ -4047,7 +4047,7 @@ function addInsurerColumn() { $('#insurerTable thead tr').append(` `); diff --git a/app/Views/policy_transaction_inception_list.php b/app/Views/policy_transaction_inception_list.php index 03a9450b..0bbb124d 100644 --- a/app/Views/policy_transaction_inception_list.php +++ b/app/Views/policy_transaction_inception_list.php @@ -274,7 +274,7 @@ table.dataTable tbody td {
    -
    Premium Details Insurer ${insurerCount} - ${insurerCount > 1 ? `` : ''} + ${insurerCount > 1 ? `` : ''}
    +
    @@ -1073,7 +1073,7 @@ function appendFileTableBody(data) .attr('target', '_blank') // Open in a new tab .attr('style', 'font-size:18px;') .attr('data-id', item.id) - .addClass('fa fa-download') + .addClass('mdi mdi-download') // Append the tag inside the
    S.No.
    @@ -1168,14 +1168,14 @@ function appendVehicleFileTableBody(data) .attr('href', '' + item.file_name) .attr('style', 'font-size:18px;') .attr('data-id', item.id) - .addClass('fa fa-download') + .addClass('mdi mdi-download') .text(' '); // Space after the icon // Create the delete link var deleteLink = $('') .attr('style', 'font-size:18px;') .attr('data-id', item.id) - .addClass('fa fa-trash') + .addClass('mdi mdi-delete') .text(' '); // Space after the icon // Append the download and delete icons inside the same diff --git a/app/Views/policy_type_list.php b/app/Views/policy_type_list.php index c9ddf181..81a6fbad 100755 --- a/app/Views/policy_type_list.php +++ b/app/Views/policy_type_list.php @@ -78,7 +78,7 @@ " type="button" id="btnAdd" class="btn btn-primary waves-effect waves-light" data-toggle="" data-placement="top" title="Add" data-trigger="hover">ADD --> - diff --git a/app/Views/rack_rate_test.php b/app/Views/rack_rate_test.php index c6c22d0e..cec32c86 100755 --- a/app/Views/rack_rate_test.php +++ b/app/Views/rack_rate_test.php @@ -122,7 +122,7 @@
      -
      +
      @@ -159,7 +159,7 @@
      SNO
      + @@ -186,7 +186,7 @@ - +
      @@ -225,7 +225,7 @@
      SNO
      +
      diff --git a/app/Views/report_bds.php b/app/Views/report_bds.php index dea26ba3..5978e44f 100644 --- a/app/Views/report_bds.php +++ b/app/Views/report_bds.php @@ -40,7 +40,7 @@ table.dataTable tbody td { Total Unbilled Amount:0.00 | Total Policy Count: -
      +
      @@ -142,7 +142,7 @@ table.dataTable tbody td {
      S. No
      +
      diff --git a/app/Views/report_bds_old.php b/app/Views/report_bds_old.php index 0caa9383..06c84ba2 100644 --- a/app/Views/report_bds_old.php +++ b/app/Views/report_bds_old.php @@ -32,7 +32,7 @@ table.dataTable tbody td {
      -
      Statement No.
      +
      diff --git a/app/Views/tat_report_band_wise_list.php b/app/Views/tat_report_band_wise_list.php index a41ff23c..7bc6972c 100644 --- a/app/Views/tat_report_band_wise_list.php +++ b/app/Views/tat_report_band_wise_list.php @@ -32,7 +32,7 @@
      -
      S. No
      +
      Employees -
      +
      diff --git a/app/Views/thz_list.php b/app/Views/thz_list.php index cde116e0..1057ad26 100644 --- a/app/Views/thz_list.php +++ b/app/Views/thz_list.php @@ -7,63 +7,22 @@ width: 100%; } -/* HEADER */ -thead th { - background-color: #00999E; - color: #fff !important; - border-top: 0px solid #fff !important; - border-bottom: 0px solid #fff !important; -} - /* .table thead th { vertical-align: bottom; border-bottom: 2px solid #fff; } */ -/* Rounded header corners */ -thead th:first-child { - border-top-left-radius: 15px !important; - border-bottom-left-radius: 15px !important; -} -thead th:last-child { - border-top-right-radius: 15px !important; - border-bottom-right-radius: 15px !important; -} - -/* BODY ROWS */ -tbody td { - background: #F5FFFF; /* apply bg to td not tr */ - padding: 12px; - border-top: 1px solid #eee; - border-bottom: 1px solid #eee; -} /* Add shadow + spacing row "card" effect */ tbody tr { /* box-shadow: 0 2px 5px rgba(0,0,0,0.08); */ } -/* Rounded corners for first + last cell of each row */ -tbody tr td:first-child { - border-top-left-radius: 15px !important; - border-bottom-left-radius: 15px !important; -} -tbody tr td:last-child { - border-top-right-radius: 15px !important; - border-bottom-right-radius: 15px !important; -} - -/* Hover effect */ -#scroll-horizontal-datatable tbody tr:hover td { - background-color: #e0e0e0; - -} - - /* Search input with icon */ .dataTables_filter { position: absolute; } + .dataTables_filter input { padding-right: 30px; background: url('https://cdn.jsdelivr.net/npm/@mdi/svg/svg/magnify.svg') no-repeat right 8px center; @@ -123,10 +82,6 @@ tbody tr td:last-child { white-space: nowrap !important; } */ - -.text-custom-black{ - color: #000000 !important; -} .text-custom-grey{ font-size: 0.85em; color: #6c757d !important; @@ -212,7 +167,7 @@ table thead th { .form-control { background-color: #ECECEC !important; border: 1px solid #ccc; /* optional */ - color: #000; /* keep text readable */ + /* color: #000; keep text readable */ } .form-control:focus { @@ -229,12 +184,11 @@ table thead th { /* Text inside */ .select2-container .select2-selection__rendered { - color: #000 !important; line-height: 36px !important; } .select2-container--default .select2-results__option--highlighted.select2-results__option--selectable { - background-color: #ECECEC !important; + background-color: #00999E !important; } @@ -247,12 +201,12 @@ table thead th {
      -

      Tickets

      +

      Tickets

      -
      - +
      + @@ -265,7 +219,7 @@ table thead th { - + $row){ ?> @@ -293,15 +247,17 @@ table thead th { @@ -338,7 +294,7 @@ table thead th {
      - @@ -357,7 +313,7 @@ table thead th {
      - +
      @@ -394,9 +350,17 @@ table thead th { @@ -463,7 +427,7 @@ table thead th { @@ -683,62 +647,66 @@ table thead th { document.getElementById('policy_id').value = policyId || ""; } - function hideandshowpolicy() { - var select = document.getElementById('ticket_type').value; - var policyContainer = document.getElementById('policy_container'); + // function hideandshowpolicy() { + // var select = document.getElementById('ticket_type').value; + // var policyContainer = document.getElementById('policy_container'); - if (select === 'Service') { - policyContainer.style.display = "block"; // show + // if (select === 'Service') { + // policyContainer.style.display = "block"; // show + // } else { + // policyContainer.style.display = "none"; // hide + // document.getElementById('policy_no').value = ""; + // document.getElementById('policy_id').value = ""; + // } + // } + +function hideandshowpolicy() { + var select = document.getElementById('ticket_type'); + var value = select.value; + var policyContainer = document.getElementById('policy_container'); + + if (value === "0") { + let newType = prompt("Enter new ticket type:"); + if (newType && newType.trim() !== "") { + + var formData = new FormData(form); + + $.ajax({ + url: "", + type: "POST", + data: formData, + processData: false, + contentType: false, + dataType: 'json', + success: function(response) { + if (response.status === "success") { + + let option = new Option(newType, newType); + let addNewOption = select.querySelector('option[value="0"]'); + select.insertBefore(option, addNewOption); + select.value = newType; + value = newType; + console.log(response.message); + + } else { console.log(response.message); value = ""; } + }, + error: function(xhr) { console.log("Error: " + xhr.statusText); value = ""; } + }); } else { - policyContainer.style.display = "none"; // hide - document.getElementById('policy_no').value = ""; - document.getElementById('policy_id').value = ""; + select.value = ""; + value = ""; } } -// function hideandshowpolicy() { -// var select = document.getElementById('ticket_type'); -// var value = select.value; -// var policyContainer = document.getElementById('policy_container'); + if (value === 'Service') { + policyContainer.style.display = "block"; + } else { + policyContainer.style.display = "none"; + document.getElementById('policy_no').value = ""; + document.getElementById('policy_id').value = ""; + } -// if (value === "0") { -// let newType = prompt("Enter new ticket type:"); -// if (newType && newType.trim() !== "") { - -// $.ajax({ -// url: "", -// type: "POST", -// data: { name: newType }, -// dataType: 'json', -// success: function(response) { -// if (response.status === "success") { - -// let option = new Option(newType, newType); -// let addNewOption = select.querySelector('option[value="0"]'); -// select.insertBefore(option, addNewOption); -// select.value = newType; -// value = newType; -// console.log(response.message); - -// } else { console.log(response.message); value = ""; } -// }, -// error: function(xhr) { console.log("Error: " + xhr.statusText); value = ""; } -// }); -// } else { -// select.value = ""; -// value = ""; -// } -// } - -// if (value === 'Service') { -// policyContainer.style.display = "block"; -// } else { -// policyContainer.style.display = "none"; -// document.getElementById('policy_no').value = ""; -// document.getElementById('policy_id').value = ""; -// } - -// } +} + \ No newline at end of file diff --git a/app/Views/ticket_auto_query.php b/app/Views/ticket_auto_query.php index 5caf68d4..7c493e8c 100644 --- a/app/Views/ticket_auto_query.php +++ b/app/Views/ticket_auto_query.php @@ -13,7 +13,7 @@
      -
      diff --git a/app/Views/ticket_edit_onbording.php b/app/Views/ticket_edit_onbording.php index 5a6812ac..e505c714 100644 --- a/app/Views/ticket_edit_onbording.php +++ b/app/Views/ticket_edit_onbording.php @@ -2,6 +2,11 @@ .bg-staff { background-color: #FFF5E5; } + +.label-font-size{ + font-size:0.875rem; +} +
      Ticket ID NameUpdated At
      format('d/m/Y') . "
      " . $cdt->format('h:i a') . ""; + $cd = date("j F Y", strtotime($row['created_at'])); + $ct = date("h:i a", strtotime($row['created_at'])); + echo $cd . "
      " . $ct . ""; endif; ?>
      format('d/m/Y') . "
      " . $udt->format('h:i a') . ""; + $ud = date("j F Y", strtotime($row['updated_at'])); + $ut = date("h:i a", strtotime($row['updated_at'])); + echo $ud . "
      " . $ut . ""; endif; ?>
      Claim Number
      Label
      Status
      Template Name
      Branch Name
      S.No
      S.No
      S.No.