MERGE_UAT_USR&LIVE_ISSUES

This commit is contained in:
Ubuntu 2025-10-31 19:01:57 +05:30
commit 8487f1cf3b
38 changed files with 8686 additions and 6082 deletions

View File

@ -94,12 +94,12 @@ define('EVENT_PRIORITY_NORMAL', 100);
define('EVENT_PRIORITY_HIGH', 10); define('EVENT_PRIORITY_HIGH', 10);
/** /**
* @User Role Constant * @User Teams Constant
*/ */
define('ENROLLMENT_TEAM_ID', '1'); define('ENROLLMENT_TEAM_ID', '1');
define('CLAIMS_TEAM_ID', '2'); define('CLAIMS_TEAM_ID', '2');
define('BUSINESS_TEAM_ID', '3'); // define('BUSINESS_TEAM_ID', '3'); // old don't delete it
define('BUSINESS_TEAM_ID', '4'); // 25th OCT 2025 changed
define('FINANCE_TEAM_ID', '4'); define('FINANCE_TEAM_ID', '4');
define('SALES_TEAM_ID', '5'); define('SALES_TEAM_ID', '5');
define('MANAGEMENT_TEAM_ID', '6'); define('MANAGEMENT_TEAM_ID', '6');
@ -107,9 +107,8 @@ define('BUSINESS_SUPPORT_TEAM_ID', '7');
define('POS_TEAM_ID', '8'); define('POS_TEAM_ID', '8');
/** /**
* @User Teams Constant * @User Role Constant
*/ */
define('ADMIN_ROLE_ID', 1); define('ADMIN_ROLE_ID', 1);
define('MANAGER_ROLE_ID', 2); define('MANAGER_ROLE_ID', 2);
define('ACCOUNT_MANAGER_ROLE_ID', 3); define('ACCOUNT_MANAGER_ROLE_ID', 3);

View File

@ -400,6 +400,7 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) {
$routes->match(['get', 'post', 'delete'], 'vehicleTypeMaster', 'MasterController::vehicleTypeMaster'); $routes->match(['get', 'post', 'delete'], 'vehicleTypeMaster', 'MasterController::vehicleTypeMaster');
$routes->match(['get', 'post', 'delete'], 'rtoMaster', 'MasterController::rtoMaster'); $routes->match(['get', 'post', 'delete'], 'rtoMaster', 'MasterController::rtoMaster');
$routes->get('checkDuplicateCdAccount', 'MasterController::checkDuplicateCdAccount'); $routes->get('checkDuplicateCdAccount', 'MasterController::checkDuplicateCdAccount');
$routes->get('proceedExcelFileDataValidation', 'EmployeeController::proceedExcelFileDataValidation');
}); });
$routes->post("policy_tranction/sendInstallmentRemainderMail","PolicyTransactionController::sendInstallmentRemainderMail"); $routes->post("policy_tranction/sendInstallmentRemainderMail","PolicyTransactionController::sendInstallmentRemainderMail");
@ -427,7 +428,7 @@ $routes->group("policy_tranction", ["filter" => "authMVC"], function ($routes) {
$routes->group("report", ["filter" => "authMVC"], function ($routes) { $routes->group("report", ["filter" => "authMVC"], function ($routes) {
$routes->match(['get', 'post'],"list", "PolicyTransactionController::reportBDS"); $routes->match(['get', 'post'],"list", "PolicyTransactionController::reportBDS");
$routes->match(['get', 'post'],"listNew", "PolicyTransactionController::reportBDSNew"); $routes->match(['get', 'post'],"list_new", "PolicyTransactionController::reportBDSNew");
$routes->get("report-varience-list", "PolicyTransactionController::reportVarience"); $routes->get("report-varience-list", "PolicyTransactionController::reportVarience");
$routes->get("report-business-list", "PolicyTransactionController::reportBusinessList"); $routes->get("report-business-list", "PolicyTransactionController::reportBusinessList");
$routes->get("report-finance-list", "PolicyTransactionController::reportFinanceList"); $routes->get("report-finance-list", "PolicyTransactionController::reportFinanceList");
@ -718,6 +719,7 @@ $routes->group('test', function($routes) {
$routes->get('membervalidation', 'TestingController::membervalidation'); $routes->get('membervalidation', 'TestingController::membervalidation');
$routes->get('generateExcel', 'TestingController::generateExcel'); $routes->get('generateExcel', 'TestingController::generateExcel');
$routes->get('logo_renaming','TestingController::logo_renaming'); $routes->get('logo_renaming','TestingController::logo_renaming');
// $routes->get('createDefaultMailTempalteInDB','TestingController::createDefaultMailTempalteInDB');
}); });
$routes->cli('cli/testcli', 'TestingController::testcli'); $routes->cli('cli/testcli', 'TestingController::testcli');

View File

@ -937,7 +937,13 @@ class BDSReportController extends AdminController
} }
} }
public function bdsTATReport() /** New arugument Introduced Named as "$isInternalCalled"
* Functional Based called means $isInternalCalled is True.
* Output returning as Array
* Route Based called means $isInternalCalled is False. becoz this is External Call
* Output returning as Page
*/
public function bdsTATReport($isInternalCalled = false)
{ {
$sql = " $sql = "
SELECT SELECT
@ -1010,9 +1016,8 @@ class BDSReportController extends AdminController
// dd(db_connect()->getLastQuery(),$result); // dd(db_connect()->getLastQuery(),$result);
$data['data'] = $result; $data['data'] = $result;
// dd($data, get_role_id(), ENROLLMENT_TEAM_ID, user_team()); // dd($data, get_role_id(), ENROLLMENT_TEAM_ID, user_team());
// return $this->loadLayout('bds_tat_wise_report', $data); if ($isInternalCalled) { return $result; }
return $this->loadLayout('bds_tat_wise_report', $data);
return $result;
} }
public function accountMangerStatusBDSReport() public function accountMangerStatusBDSReport()
@ -1141,7 +1146,7 @@ class BDSReportController extends AdminController
if ($report_type == 1){ if ($report_type == 1){
$data['page_title'] = "BDS TAT Report"; $data['page_title'] = "BDS TAT Report";
$data['data'] = $this->bdsTATReport(); $data['data'] = $this->bdsTATReport(true); // Functional Based called means True
}else if ($report_type == 2){ }else if ($report_type == 2){
$data['page_title'] = "Account Manager Status Report"; $data['page_title'] = "Account Manager Status Report";

View File

@ -519,7 +519,6 @@ class ClientController extends AdminController
public function updateEmpAndPolicyStatus() public function updateEmpAndPolicyStatus()
{ {
$return = $this->clientPolicyModel->updateStatus(); $return = $this->clientPolicyModel->updateStatus();
return $return;
$this->myLogger->logme('error', 'Client Policy Status Update Count: {data}', ['data' => $return['client']]); $this->myLogger->logme('error', 'Client Policy Status Update Count: {data}', ['data' => $return['client']]);
$this->myLogger->logme('error', 'Employee Policy Status Update Count: {data}', ['data' => $return['emp']]); $this->myLogger->logme('error', 'Employee Policy Status Update Count: {data}', ['data' => $return['emp']]);
} }
@ -869,6 +868,12 @@ class ClientController extends AdminController
if ($insert) { if ($insert) {
$client_data = $this->clientModel->where(['id' => $insert, 'is_active' => 1])->first(); $client_data = $this->clientModel->where(['id' => $insert, 'is_active' => 1])->first();
$client_id = $insert;
$default_template_creation = $this->createDefaultMailTemplate($client_id , $client_data);
if($default_template_creation == false){
$this->myLogger->logme('error', 'Default Mail Template Creation Failed for Client ID: {data}', ['data' => $client_id]);
}
return $this->respond(['status' => true, 'code' => 200, 'data' => $client_data], 200); return $this->respond(['status' => true, 'code' => 200, 'data' => $client_data], 200);
} else { } else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200); return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
@ -5662,15 +5667,16 @@ class ClientController extends AdminController
// ---------- EMP SERVICE CONTROLLER -------------------------------------------------------------------------------- // ---------- EMP SERVICE CONTROLLER --------------------------------------------------------------------------------
$empServiceController = new EmployeeServiceController(); $empServiceController = new EmployeeServiceController();
$res = $empServiceController->excelFileFormatValidation(['file_id' => '2055']); // $res = $empServiceController->excelFileFormatValidation(['file_id' => '1126']);
// $res = $empServiceController->excelFileDataValidation(['file_id' => '865']); // $res = $empServiceController->excelFileDataValidation(['file_id' => '865']);
// $res = $empServiceController->employeesOnboardPreprocess(['file_id' => 726]); // $res = $empServiceController->employeesOnboardPreprocess(['file_id' => 726]);
// $res = $empServiceController->employeesOnboardProcess(['file_id' => 835]); // $res = $empServiceController->employeesOnboardProcess(['file_id' => 835]);
// $res = $empServiceController->employeesEnrollmentInsert(['file_id' => 836]); // $res = $empServiceController->employeesEnrollmentInsert(['file_id' => 836]);
// $res = $empServiceController->employeesSIEnhanceProcess(['file_id' => '978']); // $res = $empServiceController->employeesSIEnhanceProcess(['file_id' => '1131']);
// $res = $empServiceController->employeeDisembark(['file_id' => '1681']); // $res = $empServiceController->employeeDisembark(['file_id' => '1681']);
// $res = $empServiceController->employeesCorrectionProcess(['file_id' => '2033']); // $res = $empServiceController->employeesCorrectionProcess(['file_id' => '2033']);
dd($res); // $res = $empServiceController->compareMemberDataAndInceptionData(['file_id' => '1126']);
// dd($res);
$EmployeeMultiEventServiceController = new EmployeeMultiEventServiceController(); $EmployeeMultiEventServiceController = new EmployeeMultiEventServiceController();
// $res = $EmployeeMultiEventServiceController->constructMultiEventData(['file_id' => '1069']); // $res = $EmployeeMultiEventServiceController->constructMultiEventData(['file_id' => '1069']);
@ -5730,8 +5736,8 @@ class ClientController extends AdminController
// $res = $EmpDataServiceController->generateExcelForCorrection($batch_data); // $res = $EmpDataServiceController->generateExcelForCorrection($batch_data);
// $res = $EmpDataServiceController->importInceptionFileValidation(['file_id' => 1932]); die; // $res = $EmpDataServiceController->importInceptionFileValidation(['file_id' => 1932]); die;
// $res = $EmpDataServiceController->importDeletionValidation(['file_id' => 304]); //for live // $res = $EmpDataServiceController->importDeletionValidation(['file_id' => 304]); //for live
// $res = $EmpDataServiceController->importSIEnhancementUpdateEndorsementID(['file_id' => 1199]); //for live // $res = $EmpDataServiceController->importSIEnhancementUpdateEndorsementID(['file_id' => 387]); //for live
// $res = $EmpDataServiceController->importSIEnhancementValidation(['file_id' => 2496]); //for live // $res = $EmpDataServiceController->importSIEnhancementValidation(['file_id' => 387]); //for live
// $res = $EmpDataServiceController->importInceptionUpdateTPAandUHID(['file_id' => 214]); //for live // $res = $EmpDataServiceController->importInceptionUpdateTPAandUHID(['file_id' => 214]); //for live
// $res = $EmpDataServiceController->importInceptionUpdateTPAandUHID(['file_id' => 310]); dd($res);//for live // $res = $EmpDataServiceController->importInceptionUpdateTPAandUHID(['file_id' => 310]); dd($res);//for live
// $res = $EmpDataServiceController->getInceptionBasePremium(["13332","13333","13334","13335","13336"]); dd($res);//for live // $res = $EmpDataServiceController->getInceptionBasePremium(["13332","13333","13334","13335","13336"]); dd($res);//for live
@ -7731,9 +7737,76 @@ class ClientController extends AdminController
return true; return true;
} }
public function createDefaultMailTemplate($client_id , $client_data){
$member_welcome_mail_template = $this->notificationModel->where('client_id',NULL)->where('template_name','member_welcome_mail')->get()->getResultArray()[0]??[];
$member_remainder_mail_template = $this->notificationModel->where('client_id',NULL)->where('template_name','member_reminder_mail')->get()->getResultArray()[0]??[];
$member_review_and_summary_mail_template = $this->notificationModel->where('client_id',NULL)->where('template_name','member_review_and_summary_mail')->get()->getResultArray()[0]??[];
$default_member_welcome_mail_template = [
'client_id' => $client_id,
'template_name' => 'member_welcome_mail',
'subject' => $member_welcome_mail_template['subject']??'',
'mail_content' => $member_welcome_mail_template['mail_content']??'',
'mail_content_json'=> $member_welcome_mail_template['mail_content_json']??'',
'created_by' => get_session_userid(),
'created_at' => date('Y-m-d H:i:s'),
'updated_by' => null,
'updated_at' => date('Y-m-d H:i:s'),
'mail_content_copy'=> null
];
$default_member_remainder_mail_template = [
'client_id' => $client_id,
'template_name' => 'member_reminder_mail',
'subject' => $member_remainder_mail_template['subject']??'',
'mail_content' => $member_remainder_mail_template['mail_content']??'',
'mail_content_json'=> $member_remainder_mail_template['mail_content_json']??'',
'created_by' => get_session_userid(),
'created_at' => date('Y-m-d H:i:s'),
'updated_by' => null,
'updated_at' => date('Y-m-d H:i:s'),
'mail_content_copy'=> null
];
$default_member_review_and_summary_mail_template = [
'client_id' => $client_id,
'template_name' => 'member_review_and_summary_mail',
'subject' => $member_review_and_summary_mail_template['subject']??'',
'mail_content' => $member_review_and_summary_mail_template['mail_content']??'',
'mail_content_json'=> $member_review_and_summary_mail_template['mail_content_json']??'',
'created_by' => get_session_userid(),
'created_at' => date('Y-m-d H:i:s'),
'updated_by' => null,
'updated_at' => date('Y-m-d H:i:s'),
'mail_content_copy'=> null
];
$this->myLogger->logme('error', 'Default Mail Template Data ' . json_encode([
$default_member_welcome_mail_template,
$default_member_remainder_mail_template,
$default_member_review_and_summary_mail_template
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
$default_templates_inserted = $this->notificationModel->insertBatch([
$default_member_welcome_mail_template,
$default_member_remainder_mail_template,
$default_member_review_and_summary_mail_template
]);
return $default_templates_inserted ? true : false;
}

View File

@ -1457,6 +1457,47 @@ class EmpDataServiceController extends BaseController
//get the employee data for excel file validation //get the employee data for excel file validation
$employee_data = $this->employeePolicyModel->getInceptionEmployeeDataForExportExcel($ref_data, 1); $employee_data = $this->employeePolicyModel->getInceptionEmployeeDataForExportExcel($ref_data, 1);
// ----------------- CD BALANCE CHECK ---------------------------------------------------------------------------
$cash_balance = $this->clientDepositModel
->where('cd_ac_pk', $client_policy_data['cd_ac_pk'])
->where('is_active', 1)
->orderBy('id', 'DESC')
->first();
if ($cash_balance == null) {
$balance = $this->CDMasterModel
->where('client_id', $file['client_id'])
->where('insurer_id', $client_policy_data['insurer_id'])
->where('id', $client_policy_data['cd_ac_pk'])
->first();
$cash_balance['balance'] = $balance['opening_bal'];
}
// Calculate the total amount from the objects
$totals = 0;
foreach ($employee_data as $item) {
$totals = $totals + $item['total'];
}
$totals = round($totals, 2);
//check CD amt insufficient only insurer, not tpa
if($file['insurer_or_tpa'] == 'insurer')
{
if (!empty($cash_balance)) {
if ((int) $cash_balance['balance'] < (int) $totals) {
$this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount. CASH BALANCE : {balance} and TOTAL AMOUNT : {total}', ['balance' => $cash_balance['balance'], 'total' => $totals]);
$this->batchFileModel->where('id', $file_id)->set(['status' => 'failed-7', 'error_data' => 'Insufficient deposit balance. Available CD Balance: ' . $cash_balance['balance'] . ', Excel Total Amount: ' . $totals])->update();
return ['status' => 'error', 'message' => 'Insufficient deposit balance. Available CD Balance: ' . $cash_balance['balance'] . ', Required Amount: ' . $totals];
}
}
}
// ---------------- END CD BALANCE CHECK ----------------------------------------------------------------------------
if ($employee_data == null || empty($employee_data)) { if ($employee_data == null || empty($employee_data)) {
if ($insurer_or_tpa == 'tpa') { if ($insurer_or_tpa == 'tpa') {
@ -2569,6 +2610,7 @@ class EmpDataServiceController extends BaseController
'event_type' => $file['event_type'], 'event_type' => $file['event_type'],
]; ];
$client_policy_data = $this->clientPolicyModel->where('id', $client_policy_id)->first();
$file_name_with_path = WRITEPATH . "/uploads/import_excel/" . $file['file_name']; $file_name_with_path = WRITEPATH . "/uploads/import_excel/" . $file['file_name'];
@ -2691,6 +2733,47 @@ class EmpDataServiceController extends BaseController
// dd($endorsement_data, $excel_data); // dd($endorsement_data, $excel_data);
// ----------------- CD BALANCE CHECK ---------------------------------------------------------------------------
$cash_balance = $this->clientDepositModel
->where('cd_ac_pk', $client_policy_data['cd_ac_pk'])
->where('is_active', 1)
->orderBy('id', 'DESC')
->first();
if ($cash_balance == null) {
$balance = $this->CDMasterModel
->where('client_id', $file['client_id'])
->where('insurer_id', $client_policy_data['insurer_id'])
->where('id', $client_policy_data['cd_ac_pk'])
->first();
$cash_balance['balance'] = $balance['opening_bal'];
}
// Calculate the total amount from the objects
$totals = 0;
foreach ($endorsement_data as $item) {
$totals = $totals + $item['total'];
}
$totals = round($totals, 2);
//check CD amt insufficient only insurer, not tpa
if($file['insurer_or_tpa'] == 'insurer')
{
if (!empty($cash_balance)) {
if ((int) $cash_balance['balance'] < (int) $totals) {
$this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount. CASH BALANCE : {balance} and TOTAL AMOUNT : {total}', ['balance' => $cash_balance['balance'], 'total' => $totals]);
$this->batchFileModel->where('id', $file_id)->set(['status' => 'failed-7', 'error_data' => 'Insufficient deposit balance. Available CD Balance: ' . $cash_balance['balance'] . ', Excel Total Amount: ' . $totals])->update();
return ['status' => 'error', 'message' => 'Insufficient deposit balance. Available CD Balance: ' . $cash_balance['balance'] . ', Required Amount: ' . $totals];
}
}
}
// ---------------- END CD BALANCE CHECK ----------------------------------------------------------------------------
if ($endorsement_data == null || empty($endorsement_data)) { if ($endorsement_data == null || empty($endorsement_data)) {
@ -3119,6 +3202,7 @@ class EmpDataServiceController extends BaseController
$empData['rata_premimum'] = $value[16]; $empData['rata_premimum'] = $value[16];
$empData['gst'] = $value[17]; $empData['gst'] = $value[17];
$empData['created_by'] = $user_id; $empData['created_by'] = $user_id;
$empData['old_basic_cover_si'] = $value[9];
$emp_details[] = $empData; $emp_details[] = $empData;
} }
@ -3139,11 +3223,41 @@ class EmpDataServiceController extends BaseController
// $insertedIds[] = $startId + $i; // $insertedIds[] = $startId + $i;
// } // }
// $insertedIds = [];
// foreach ($emp_details as $emp) {
// $old_si_value = $emp['old_basic_cover_si'];
// $new_si_value = $emp['basic_cover_si'];
// if($old_si_value < $new_si_value){
// $insertedIds['si_adjustment'] = 2;
// }else{
// $insertedIds['si_adjustment'] = 1;
// }
// unset($emp['old_basic_cover_si']);
// $insertedIds['pk'] = $this->employeePolicyModel->insert($emp);
// }
$insertedIds = []; $insertedIds = [];
foreach ($emp_details as $emp) { foreach ($emp_details as $emp) {
$insertedIds[] = $this->employeePolicyModel->insert($emp);
}
$old_si_value = $emp['old_basic_cover_si'];
$new_si_value = $emp['basic_cover_si'];
// Determine SI adjustment type
$si_adjustment = ($old_si_value < $new_si_value) ? 1 : 2;
unset($emp['old_basic_cover_si']);
// Insert and store PK with adjustment info
$pk = $this->employeePolicyModel->insert($emp);
$insertedIds[] = [
'pk' => $pk,
'si_adjustment' => $si_adjustment
];
}
// dd($insertedIds); // dd($insertedIds);
$this->employeePolicyModel->bulkUpdateForEndorsement($endorsement_details); $this->employeePolicyModel->bulkUpdateForEndorsement($endorsement_details);
@ -3158,7 +3272,6 @@ class EmpDataServiceController extends BaseController
'amount' => $rounded_totals, 'amount' => $rounded_totals,
]); ]);
$this->myLogger->logme('error', 'SI Enhancement Update Endorsement ID -- Employee count : {data}', ['data' => $emp_count]); $this->myLogger->logme('error', 'SI Enhancement Update Endorsement ID -- Employee count : {data}', ['data' => $emp_count]);
$this->myLogger->logme('error', 'SI Enhancement Update Endorsement ID -- Batch File status : {data}', ['data' => $status_val]); $this->myLogger->logme('error', 'SI Enhancement Update Endorsement ID -- Batch File status : {data}', ['data' => $status_val]);
@ -4195,60 +4308,164 @@ class EmpDataServiceController extends BaseController
} }
// public function cashDepositCalculationForSIEnhancement($arrayData)
// {
// // return $arrayData;
// if (!empty($arrayData)) {
// $client_branch_data = $this->clientBranchModel->where('id', $arrayData['client_branch_id'])->first();
// $units = json_decode($client_branch_data['units']);
// foreach($units as $unit)
// {
// $amount = $this->employeePolicyModel->query("
// SELECT SUM(rata_premimum + gst) AS total_sum
// FROM employee_polices
// JOIN employees ON employees.id = employee_polices.employee_id
// WHERE employees.unit = '$unit'
// AND employee_polices.id IN (" . implode(',', $arrayData['employeeIds']) . ")
// ")->getRow();
// if($amount){
// $insurer_id = $this->clientPolicyModel->where('id', $arrayData['client_policy_id'])->first();
// $description = 'The following amount of ' . round($amount->total_sum, 2) . ' has been credited for the ' . $arrayData['count'] . ' employees at ' . remove_underscore_capitalize_first_letter($arrayData['event_name']) . ' to ' . remove_underscore_capitalize_first_letter($arrayData['policy_name']) . '.';
// $data = [
// 'amount' => $amount->total_sum,
// 'sub_type_id' => 4,
// 'client_id' => $arrayData['client_id'],
// 'client_policy_id' => $arrayData['client_policy_id'],
// 'endorsement_no' => $arrayData['endorsement_no'] ?? null,
// 'cd_ac_no' => $arrayData['cd_ac_no'] ?? null,
// 'insurer_id' => $insurer_id['insurer_id'],
// 'unit' => $unit,
// 'description' => $description,
// 'transaction_type' => 'Debit',
// 'updated_by' => $arrayData['user_id'],
// 'event_name' => $arrayData['event_name'],
// 'is_active' => 1,
// 'cd_ac_pk' => $insurer_id['cd_ac_pk']
// ];
// $response = DepositHelper::saveDeposit($data, $arrayData['user_id']);
// }
// }
// $msg = "SI Enhancement Cash Deposite Updated Successfully ";
// return [$msg];
// // print_r($response);
// // $query = $this->employeePolicyModel->getLastQuery();
// // echo $query . "<br>";
// } else {
// return 0;
// }
// }
public function cashDepositCalculationForSIEnhancement($arrayData) public function cashDepositCalculationForSIEnhancement($arrayData)
{ {
// return $arrayData;
if (!empty($arrayData)) { if (!empty($arrayData)) {
$client_branch_data = $this->clientBranchModel->where('id', $arrayData['client_branch_id'])->first(); $client_branch_data = $this->clientBranchModel->where('id', $arrayData['client_branch_id'])->first();
$units = json_decode($client_branch_data['units']); $units = json_decode($client_branch_data['units']);
foreach($units as $unit) foreach ($units as $unit) {
{
$amount = $this->employeePolicyModel->query(" $si_enhance_amt = 0;
$si_decrease_amt = 0;
foreach ($arrayData['employeeIds'] as $value) {
// If $value is an array, get its elements; otherwise, assign defaults
$pk = is_array($value) ? ($value['pk'] ?? null) : $value;
$si_adjustment = is_array($value) ? ($value['si_adjustment'] ?? null) : $value;
$query = "
SELECT SUM(rata_premimum + gst) AS total_sum SELECT SUM(rata_premimum + gst) AS total_sum
FROM employee_polices FROM employee_polices
JOIN employees ON employees.id = employee_polices.employee_id JOIN employees ON employees.id = employee_polices.employee_id
WHERE employees.unit = '$unit' WHERE employees.unit = '{$unit}'
AND employee_polices.id IN (" . implode(',', $arrayData['employeeIds']) . ") AND employee_polices.id = '{$pk}'
")->getRow(); ";
if($amount){ $amount = $this->employeePolicyModel->query($query)->getRow();
$insurer_id = $this->clientPolicyModel->where('id', $arrayData['client_policy_id'])->first(); if ($amount && $amount->total_sum > 0) {
$description = 'The following amount of ' . round($amount->total_sum, 2) . ' has been credited for the ' . $arrayData['count'] . ' employees at ' . remove_underscore_capitalize_first_letter($arrayData['event_name']) . ' to ' . remove_underscore_capitalize_first_letter($arrayData['policy_name']) . '.'; if ($si_adjustment == 2) {
$si_decrease_amt += $amount->total_sum;
} else {
$si_enhance_amt += $amount->total_sum;
}
}
}
// Save Enhancement amount
if ($si_enhance_amt > 0) {
$policy_data = $this->clientPolicyModel->where('id', $arrayData['client_policy_id'])->first();
$description = 'An amount of ' . round($si_enhance_amt, 2) .
' has been debited for ' . $arrayData['count'] . ' employees under ' .
remove_underscore_capitalize_first_letter($arrayData['event_name']) .
' in ' . remove_underscore_capitalize_first_letter($arrayData['policy_name']) . '.';
$data = [ $data = [
'amount' => round($si_enhance_amt, 2),
'amount' => $amount->total_sum,
'sub_type_id' => 4, 'sub_type_id' => 4,
'client_id' => $arrayData['client_id'], 'client_id' => $arrayData['client_id'],
'client_policy_id' => $arrayData['client_policy_id'], 'client_policy_id' => $arrayData['client_policy_id'],
'endorsement_no' => $arrayData['endorsement_no'] ?? null, 'endorsement_no' => $arrayData['endorsement_no'] ?? null,
'cd_ac_no' => $arrayData['cd_ac_no'] ?? null, 'cd_ac_no' => $arrayData['cd_ac_no'] ?? null,
'insurer_id' => $insurer_id['insurer_id'], 'insurer_id' => $policy_data['insurer_id'],
'unit' => $unit, 'unit' => $unit,
'description' => $description, 'description' => $description,
'transaction_type' => 'Debit', 'transaction_type' => 'Debit',
'updated_by' => $arrayData['user_id'], 'updated_by' => $arrayData['user_id'],
'event_name' => $arrayData['event_name'], 'event_name' => $arrayData['event_name'],
'is_active' => 1, 'is_active' => 1,
'cd_ac_pk' => $insurer_id['cd_ac_pk'] 'cd_ac_pk' => $policy_data['cd_ac_pk']
]; ];
$response = DepositHelper::saveDeposit($data, $arrayData['user_id']); DepositHelper::saveDeposit($data, $arrayData['user_id']);
}
// Save Decrease amount
if ($si_decrease_amt > 0) {
$policy_data = $this->clientPolicyModel->where('id', $arrayData['client_policy_id'])->first();
$description = 'An amount of ' . round($si_decrease_amt, 2) .
' has been credited for ' . $arrayData['count'] . ' employees due to a decrease in Sum Insured (SI) under ' .
remove_underscore_capitalize_first_letter($arrayData['event_name']) .
' in ' . remove_underscore_capitalize_first_letter($arrayData['policy_name']) . '.';
$data = [
'amount' => round($si_decrease_amt, 2),
'sub_type_id' => 4,
'client_id' => $arrayData['client_id'],
'client_policy_id' => $arrayData['client_policy_id'],
'endorsement_no' => $arrayData['endorsement_no'] ?? null,
'cd_ac_no' => $arrayData['cd_ac_no'] ?? null,
'insurer_id' => $policy_data['insurer_id'],
'unit' => $unit,
'description' => $description,
'transaction_type' => 'Credit',
'updated_by' => $arrayData['user_id'],
'event_name' => $arrayData['event_name'],
'is_active' => 1,
'cd_ac_pk' => $policy_data['cd_ac_pk']
];
DepositHelper::saveDeposit($data, $arrayData['user_id']);
} }
} }
$msg = "SI Enhancement Cash Deposite Updated Successfully "; $msg = "SI Adjustment Cash Deposit Updated Successfully.";
return [$msg]; return [$msg];
// print_r($response);
// $query = $this->employeePolicyModel->getLastQuery();
// echo $query . "<br>";
} else { } else {
return 0; return 0;
} }

View File

@ -35,6 +35,7 @@ use App\Controllers\JobWorker;
use App\Controllers\Jobs\SubJob; use App\Controllers\Jobs\SubJob;
use App\Controllers\EmployeeServiceController; use App\Controllers\EmployeeServiceController;
use App\Controllers\EmpDataServiceController; use App\Controllers\EmpDataServiceController;
use App\Models\LeadsModel;
use App\Models\ThzMasterModel; use App\Models\ThzMasterModel;
use CodeIgniter\API\ResponseTrait; use CodeIgniter\API\ResponseTrait;
@ -171,7 +172,7 @@ class EmployeeController extends AdminController
return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'no data found'], 200); return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'no data found'], 200);
} else { } else {
return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $file['reason']], 200); return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $file['reason'], 'is_comparison_skipped' => $file['is_comparison_skipped'], 'policy_id' => $file['policy_id']], 200);
} }
} }
@ -388,13 +389,11 @@ class EmployeeController extends AdminController
batch_files.client_branch_id, batch_files.client_branch_id,
CASE CASE
WHEN batch_files.status = 'partially success' OR batch_files.status = 'in-progress-partially' THEN WHEN batch_files.status IN ('partially success', 'in-progress-partially', 'failed-7')
batch_files.error_data THEN batch_files.error_data
ELSE ELSE NULL
NULL
END AS error_data, END AS error_data,
clients.short_name as client_short_name, clients.short_name as client_short_name,
client_branch.branch_name, client_branch.branch_name,
client_policy.policy_no, client_policy.policy_no,
@ -3148,5 +3147,58 @@ class EmployeeController extends AdminController
} }
} }
// function for skip the Inception and Member data validation
public function proceedExcelFileDataValidation()
{
$file_id = $this->request->getGet('file_id');
$not_skiped = $this->request->getGet('not_skiped') ?? null;
$this->myLogger->logme('error', json_encode($this->request->getGet() ?? []));
if(!empty($not_skiped)){
$file_model = new FileModel();
$file_model->where('id', $file_id)->set(['is_comparison_skipped' => 0])->update();
$message = "Inception and Member data comparision continuted by the user id : " . get_session_userid();
$this->myLogger->logme('error', $message);
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Inception and Member data comparision continued'], 200);
}
if(!empty($file_id)){
$r = Jobs::addJob(['job_name' => 'excelFileDataValidation','payload' => ['file_id' => $file_id]]);
$message = "Inception and Member data comparision skiped successfully by the user id : " . get_session_userid();
$this->myLogger->logme('error', $message);
$file_model = new FileModel();
$file_model->where('id', $file_id)->set(['is_comparison_skipped' => 1])->update();
$policy_id = $this->request->getGet('policy_id') ?? null;
if ($policy_id) {
$client_policy_data = $this->clientPolicyModel->where('id', $policy_id)->first();
if (!empty($client_policy_data) && isset($client_policy_data['is_from_lead'])) {
$lead_id = $client_policy_data['is_from_lead'];
if (!empty($lead_id)) {
$lead_model = new LeadsModel();
$lead_model->where('id', $lead_id)->set(['policy_with_correction' => 1])->update();
} else {
$this->myLogger->logme('error', 'Lead ID missing for policy ID: ' . $policy_id);
}
} else {
$this->myLogger->logme('error', 'No client policy data found for policy ID: ' . $policy_id);
}
} else {
$this->myLogger->logme('error', 'Policy ID not provided in GET request.');
}
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Inception and Member data comparision skiped successfully!'], 200);
}else{
return $this->respond(['status' => false, 'code' => 500, 'message' => 'Failed to skip the comparison!'], 200);
}
}
} }

View File

@ -26,6 +26,7 @@ use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Kint\Kint; use Kint\Kint;
use App\Helpers\ExcelSanitizeHelper; use App\Helpers\ExcelSanitizeHelper;
use App\Models\LeadsModel;
class EmployeeMultiEventServiceController extends BaseController class EmployeeMultiEventServiceController extends BaseController
{ {
@ -140,7 +141,7 @@ class EmployeeMultiEventServiceController extends BaseController
'is_mandatory' => ['I', 'A', 'DA'], 'is_mandatory' => ['I', 'A', 'DA'],
'data_type' => 'str', 'data_type' => 'str',
'format' => null, 'format' => null,
'allowed_values' => ['M', 'F'] 'allowed_values' => ['M', 'F', 'Male', 'Female', 'male', 'female']
], ],
'relationship' => [ 'relationship' => [
'col_idx' => 5, 'col_idx' => 5,
@ -524,7 +525,7 @@ class EmployeeMultiEventServiceController extends BaseController
'is_mandatory' => ['I', 'A', 'DA', 'E'], 'is_mandatory' => ['I', 'A', 'DA', 'E'],
'data_type' => 'str', 'data_type' => 'str',
'format' => null, 'format' => null,
'allowed_values' => ['M', 'F'] 'allowed_values' => ['M', 'F', 'Male', 'Female', 'male', 'female']
], ],
'relationship' => [ 'relationship' => [
'col_idx' => 5, 'col_idx' => 5,
@ -889,8 +890,108 @@ class EmployeeMultiEventServiceController extends BaseController
] ]
]; ];
protected $member_data_excel_columns = [
'sno' => [
'col_idx' => 0,
'col_cell_name' => 'A',
'col_name' => 'Sl no',
'is_mandatory' => false,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'emp_code' => [
'col_idx' => 1,
'col_cell_name' => 'B',
'col_name' => 'Emp Code',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'name' => [
'col_idx' => 2,
'col_cell_name' => 'C',
'col_name' => 'Name',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'relationship' => [
'col_idx' => 3,
'col_cell_name' => 'D',
'col_name' => 'Relationship',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => [
'Self', 'Spouse', 'Son', 'Daughter', 'Father', 'Mother',
'Father-in-law', 'Mother-in-law',
'self', 'spouse', 'son', 'daughter', 'father', 'mother',
'father-in-law', 'mother-in-law'
],
'custom' => 'check_relationship_for_member_data',
'params' => ['row', 'relationship', 'columns_to_check']
],
'gender' => [
'col_idx' => 4,
'col_cell_name' => 'E',
'col_name' => 'Gender',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => ['M', 'F', 'Male', 'Female', 'male', 'female']
],
'dob' => [
'col_idx' => 5,
'col_cell_name' => 'F',
'col_name' => 'DOB',
'is_mandatory' => true,
'data_type' => 'str',
'format' => 'd-M-Y',
'allowed_values' => null,
'age_validation' => true,
// 'custom' => 'check_dob_diff',
// 'params' => ['row', 'relationship', 'default_age_ratio', 'policy_details']
],
'age' => [
'col_idx' => 6,
'col_cell_name' => 'G',
'col_name' => 'Age',
'is_mandatory' => true,
'data_type' => 'int',
'format' => null,
'allowed_values' => null
],
'email' => [
'col_idx' => 7,
'col_cell_name' => 'H',
'col_name' => 'Email',
'is_mandatory' => false,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'mobile' => [
'col_idx' => 8,
'col_cell_name' => 'I',
'col_name' => 'Mobile',
'is_mandatory' => false,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'si' => [
'col_idx' => 9,
'col_cell_name' => 'J',
'col_name' => 'SI',
'is_mandatory' => false,
'data_type' => 'int',
'format' => null,
'allowed_values' => null,
]
];
public function __construct() public function __construct()
{ {
@ -991,6 +1092,9 @@ class EmployeeMultiEventServiceController extends BaseController
$params["action"] = "inception"; $params["action"] = "inception";
$params["file_path"] = $file_paths['inception']; $params["file_path"] = $file_paths['inception'];
$error[] = $this->excelFileFormatValidation($params); $error[] = $this->excelFileFormatValidation($params);
if (isset($error['error_data']) && count($error['error_data']) == 0) {
$error[] = $this->compareMemberDataAndInceptionData($params);
}
} }
//addition //addition
@ -1357,6 +1461,13 @@ class EmployeeMultiEventServiceController extends BaseController
$enrollment_keys = array_keys($enrollment_columns_to_check); $enrollment_keys = array_keys($enrollment_columns_to_check);
} }
// for this condition to avoid 5,00,000 to 500000
if($current_column_action == 'SI'){
$row[3] = removeNumberFormatting($row[3]);
}else if(in_array($current_column_action, ['I','DA', 'MI', 'A'])){
$row[6] = removeNumberFormatting($row[6]);
}
//iterate each row for columns validations //iterate each row for columns validations
foreach ($row as $col_key => $col) { foreach ($row as $col_key => $col) {
$is_mandatory = $columns_to_check[$keys[$col_key]]['is_mandatory']; $is_mandatory = $columns_to_check[$keys[$col_key]]['is_mandatory'];
@ -1495,6 +1606,16 @@ class EmployeeMultiEventServiceController extends BaseController
$columns_to_check = $this->inception_excel_columns; $columns_to_check = $this->inception_excel_columns;
} }
$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'; }
$columns_to_check = $this->syncColIndex($this->multievent_excel_columns, $columns_to_check); $columns_to_check = $this->syncColIndex($this->multievent_excel_columns, $columns_to_check);
// print_rr($columns_to_check); // print_rr($columns_to_check);
@ -1522,7 +1643,7 @@ class EmployeeMultiEventServiceController extends BaseController
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 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' : '')); $employee_data_group_by_family = data_group_by_family($excel_data, 'excel', ($file['action'] == 'enrollment' ? 'enrollment' : ''), $current_column_action);
// dd($employee_data_group_by_family); // dd($employee_data_group_by_family);
$is_self_available_in_policy_terms = false; $is_self_available_in_policy_terms = false;
if ($policy_details['policy_type_id'] == 3) // GMC parents if ($policy_details['policy_type_id'] == 3) // GMC parents
@ -1694,6 +1815,16 @@ class EmployeeMultiEventServiceController extends BaseController
$columns_to_check = $this->inception_excel_columns; $columns_to_check = $this->inception_excel_columns;
} }
$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'; }
// get policy and rack details // get policy and rack details
$policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'], $file['policy_id']); $policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'], $file['policy_id']);
$policy_terms = (array) $policy_terms[0]; // convert obj to array $policy_terms = (array) $policy_terms[0]; // convert obj to array
@ -1717,7 +1848,7 @@ class EmployeeMultiEventServiceController extends BaseController
//get existing units in the current branch //get existing units in the current branch
$existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $file['client_id'], client_branch_id: $file['client_branch_id']); $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); $employee_data_group_by_family = data_group_by_family($excel_data, 'excel', '', $current_column_action);
// dd($employee_data_group_by_family); // dd($employee_data_group_by_family);
foreach ($employee_data_group_by_family as $emp_id => $family) { foreach ($employee_data_group_by_family as $emp_id => $family) {
@ -2029,6 +2160,9 @@ class EmployeeMultiEventServiceController extends BaseController
if (check_row_is_empty_or_null($row)) { if (check_row_is_empty_or_null($row)) {
break; break;
} }
$row[3] = removeNumberFormatting($row[3]);
// echo '<br>START- ' . $row[2]; // echo '<br>START- ' . $row[2];
$employee = $this->employeeModel $employee = $this->employeeModel
->where('emp_code', $row[1]) ->where('emp_code', $row[1])
@ -2038,6 +2172,7 @@ class EmployeeMultiEventServiceController extends BaseController
->where('emp_status', 'active') ->where('emp_status', 'active')
->where('is_active', 1) ->where('is_active', 1)
->first(); ->first();
$employee_policy = $this->employeePolicyModel $employee_policy = $this->employeePolicyModel
->where('employee_id', $employee['id']) ->where('employee_id', $employee['id'])
->where('client_policy_id', $file['policy_id']) ->where('client_policy_id', $file['policy_id'])
@ -2052,8 +2187,11 @@ class EmployeeMultiEventServiceController extends BaseController
->where('emp_code', $employee['emp_code']) ->where('emp_code', $employee['emp_code'])
->where('name', $employee['name']) ->where('name', $employee['name'])
->where('field_name', 'basic_cover_si') ->where('field_name', 'basic_cover_si')
->where('is_active', 1)
->where('status !=', 'truncated')
->findAll(); ->findAll();
// dd($existing_endorsements); // dd($existing_endorsements);
//make entry in endorsement table //make entry in endorsement table
if (!count($existing_endorsements)) { if (!count($existing_endorsements)) {
//transform data to send //transform data to send
@ -2101,6 +2239,8 @@ class EmployeeMultiEventServiceController extends BaseController
$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' => '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' => '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->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']);
}else {
$this->myLogger->logme("error", 'Endorsement already exists for this employee ' . json_encode(['file_id' => $file_id, 'emp_code' => $employee['emp_code'], 'emp_name' => $employee['name']]));
} }
} }
@ -2125,10 +2265,9 @@ class EmployeeMultiEventServiceController extends BaseController
foreach ($familiy_data as $fkey => $value) { foreach ($familiy_data as $fkey => $value) {
if (is_array($value)) { if (is_array($value)) {
if (isset($value['gender'])) { $value['gender'] = normalizeGender($value['gender'] );}
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) 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']); $employee = $this->employeeModel->checkExistingEmp($value, $file['client_branch_id']);
$policy_data = $value['policy_details']; $policy_data = $value['policy_details'];
$temp = $value['temp']; $temp = $value['temp'];
@ -2881,6 +3020,135 @@ class EmployeeMultiEventServiceController extends BaseController
return $temp; return $temp;
} }
// --------- MEMBER DATA AND INCEPTION DATA COMPARISION ------------------------------------------------------------------------
public function compareMemberDataAndInceptionData($params)
{
$file_id = $params['file_id'] ?? null;
if (empty($file_id)) {
return ['status' => false, 'msg' => 'File ID is missing'];
}
// ✅ Get File Data
$file = $this->fileModel->where(['is_active' => 1, 'id' => $file_id])->first();
if (empty($file)) {
return ['status' => false, 'msg' => 'File not found in DB'];
}
// ✅ Get Client Policy Data
$client_policy_data = $this->clientPolicyModel->where(['is_active' => 1, 'id' => $file['policy_id']])->first();
if (empty($client_policy_data)) {
return ['status' => false, 'msg' => 'Client policy data not found in DB (policy_id: ' . $file['policy_id'] . ')'];
}
// ✅ Get Lead Data
$leadModel = new LeadsModel();
$lead_data = $leadModel->where(['is_active' => 1, 'id' => $client_policy_data['is_from_lead']])->first();
if (empty($lead_data)) {
return ['status' => false, 'msg' => 'Lead data not found in DB (lead_id: ' . $client_policy_data['is_from_lead'] . ')'];
}
// ✅ Define File Paths
// $inception_file_path = !empty($file['file_name']) ? WRITEPATH . "uploads/excel/" . $file['file_name'] : '';
$member_file_path = !empty($lead_data['file_name']) ? WRITEPATH . "uploads/lead_files/" . $lead_data['file_name'] : '';
// ✅ Check Inception File
// if (empty($file['file_name']) || !file_exists($inception_file_path)) {
// $message = empty($file['file_name']) ? "Inception file name is missing" : "Inception physical file not found";
// $this->myLogger->logme('error', "$message for file id $file_id");
// $this->fileModel->update($file_id, [
// 'status' => 'failed',
// 'reason' => json_encode(['error_summary' => [5], 'error_data' => $message])
// ]);
// return ['error_summary' => [5], 'error_data' => $message];
// }
// ✅ Check Member File
if (empty($lead_data['file_name']) || !file_exists($member_file_path)) {
$message = empty($lead_data['file_name']) ? "Member file name is missing" : "Member data physical file not found";
$this->myLogger->logme('error', "$message for lead id {$lead_data['id']}");
$this->fileModel->update($file_id, [
'status' => 'failed',
'reason' => json_encode(['error_summary' => [5], 'error_data' => $message])
]);
return ['error_summary' => [5], 'error_data' => $message];
}
// ✅ Read Inception Excel
$inception_columns = $this->inception_excel_columns;
$inception_data = json_decode(file_get_contents($params['file_path'] ?? []), true);
// $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inception_file_path);
// $sheet = $spreadsheet->getActiveSheet();
// $highestRow = $sheet->getHighestDataRow();
// $allowedColumn = end($inception_columns)['col_cell_name'];
// $inception_data = $sheet->rangeToArray("A1:{$allowedColumn}{$highestRow}");
// $inception_data = ExcelSanitizeHelper::sanitizeArrayData($inception_data);
// ✅ Read Member Excel
$member_columns = $this->member_data_excel_columns;
$spreadsheet2 = \PhpOffice\PhpSpreadsheet\IOFactory::load($member_file_path);
$sheet2 = $spreadsheet2->getSheet(0);
$highestRow2 = $sheet2->getHighestDataRow();
$allowedColumn2 = end($member_columns)['col_cell_name'];
$member_data = $sheet2->rangeToArray("A1:{$allowedColumn2}{$highestRow2}");
$member_data = ExcelSanitizeHelper::sanitizeArrayData($member_data);
// dd($inception_data, $member_data);
// ✅ Compare Inception Data with Member Data
$result = ['error_type' => 2, 'error_summary' => [], 'error_data' => []];
$inception_data_count = count($inception_data);
$member_data_count = count($member_data);
if ($inception_data_count !== $member_data_count) {
$result['error_summary'][] = 15;
$result['error_message'] = "
<strong>Inception Data Count:</strong>
<span class='badge badge-danger'>{$inception_data_count}</span>&nbsp;&nbsp;
<strong>Member Data Count:</strong>
<span class='badge badge-danger'>{$member_data_count}</span>";
}
foreach ($inception_data as $inception_key => $inception_row) {
// 🔹 If inception row is empty → stop all further processing
if (check_row_is_empty_or_null($inception_row)) {
break;
}
$match_found = false;
foreach ($member_data as $member_row) {
if (
$inception_row[1] == $member_row[1] && // emp_id / emp_code
$inception_row[2] == $member_row[2] && // name_of_emp_dep / name
$inception_row[5] == $member_row[3] && // relationship
normalizeGender($inception_row[4]) == normalizeGender($member_row[4]) && // gender
$inception_row[3] == $member_row[5] && // dob
$inception_row[13] == $member_row[7] && // email
$inception_row[12] == $member_row[8] // phone / mobile
) {
$match_found = true;
break;
}
}
if (!$match_found) {
array_push($result['error_summary'], 14);
$result['error_data'][$inception_key]['sno']['error'][] = "This inception row was not found in the member data list.";
}
}
// ✅ Handle Result
if (!empty($result['error_summary'])) {
$result['error_summary'] = array_count_values($result['error_summary']);
$this->myLogger->logme('error', "File ID $file_id comparison failed");
}
return $result;
}
} }

View File

@ -53,6 +53,8 @@ use Illuminate\Http\Request;
use App\Controllers\EmployeeServiceController; use App\Controllers\EmployeeServiceController;
use App\Models\ClaimFilesModel; use App\Models\ClaimFilesModel;
use App\Models\TicketMailTemplateModel;
use Composer\Pcre\Preg;
use Kreait\Firebase\Factory; use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage; use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\Notification; use Kreait\Firebase\Messaging\Notification;
@ -90,6 +92,7 @@ class EmployeeRestController extends AdminController
protected $hrAccessControlModel; protected $hrAccessControlModel;
protected $insurerModel; protected $insurerModel;
protected $hrFileUploadModel; protected $hrFileUploadModel;
protected $ticketMailTemplateModel;
public function __construct() public function __construct()
@ -122,6 +125,7 @@ class EmployeeRestController extends AdminController
$this->hrAccessControlModel = new HRAccessControlModel(); $this->hrAccessControlModel = new HRAccessControlModel();
$this->insurerModel = new InsurerModel(); $this->insurerModel = new InsurerModel();
$this->hrFileUploadModel = new HrFileUploadModel(); $this->hrFileUploadModel = new HrFileUploadModel();
$this->ticketMailTemplateModel = new TicketMailTemplateModel();
} }
@ -4174,7 +4178,11 @@ class EmployeeRestController extends AdminController
]; ];
// Save into DB // Save into DB
$this->hrFileUploadModel->insert($data); $result = $this->hrFileUploadModel->insert($data);
if($result){
$this->giveNotificationToClientsAccountManager($data);
}
return $this->respondCreated([ return $this->respondCreated([
'status' => true, 'status' => true,
@ -4188,6 +4196,45 @@ class EmployeeRestController extends AdminController
} }
private function giveNotificationToClientsAccountManager($data){
$client_name = $this->clientModel->where('id',$data['client_id'])->findAll()[0]['client_name'] ?? [] ;
$account_manager_email = $this->clientRMModel->findAccountManagerEmail($data['client_id']);
$templateName = "hr_endorsement_template";
$mailTemplate = $this->ticketMailTemplateModel->where('template_name', $templateName)->findAll()[0] ?? [];
if(empty($mailTemplate)){
//empty mail template please update the template in database or create one..!!
log_message("error","Empty mail template for inception_addition please update the template in database or create one..!!");
return ;
}
$data['file_action'] = ucwords(preg_replace("/_/", " ", $data['file_action']));
$mailTemplate['mail_content'] = str_replace('%file_action%', $data['file_action'] ?? '', $mailTemplate['mail_content']);
$mailTemplate['mail_content'] = str_replace('%client_name%', $client_name ?? '', $mailTemplate['mail_content']);
$mailTemplate['mail_content'] = str_replace('%policy_no%', $data['policy_no'] ?? '', $mailTemplate['mail_content']);
$mailTemplate['subject'] = str_replace('%subject%',$data['file_action']??'',$mailTemplate['subject']);
$mailTemplate['subject'] = str_replace('%client_name%',$client_name??'',$mailTemplate['subject']);
$from_mail = "";
$to_mail = $account_manager_email;
$subject = $mailTemplate['subject'];
$message = $mailTemplate['mail_content'];
$cc_string = "";
$attachments = "";
$reply_to = "";
$bcc_string = "";
MailHelper::send_email(['from_mail' => $from_mail, 'mail' => $to_mail, 'cc' => $cc_string, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to, 'bcc' => $bcc_string]);
}
public function updateHrFileUploadData() public function updateHrFileUploadData()
{ {
try { try {

View File

@ -29,7 +29,7 @@ use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Kint\Kint; use Kint\Kint;
use App\Helpers\ExcelSanitizeHelper; use App\Helpers\ExcelSanitizeHelper;
use App\Models\LeadsModel;
class EmployeeServiceController extends AdminController class EmployeeServiceController extends AdminController
{ {
@ -144,7 +144,7 @@ class EmployeeServiceController extends AdminController
'is_mandatory' => ['I', 'A', 'DA'], 'is_mandatory' => ['I', 'A', 'DA'],
'data_type' => 'str', 'data_type' => 'str',
'format' => null, 'format' => null,
'allowed_values' => ['M', 'F'] 'allowed_values' => ['M', 'F', 'Male', 'Female', 'male', 'female', 'MALE', 'FEMALE']
], ],
'relationship' => [ 'relationship' => [
'col_idx' => 5, 'col_idx' => 5,
@ -529,7 +529,8 @@ class EmployeeServiceController extends AdminController
'is_mandatory' => ['I', 'A', 'DA','E'], 'is_mandatory' => ['I', 'A', 'DA','E'],
'data_type' => 'str', 'data_type' => 'str',
'format' => null, 'format' => null,
'allowed_values' => ['M', 'F'] 'allowed_values' => ['M', 'F', 'Male', 'Female', 'male', 'female', 'MALE', 'FEMALE']
], ],
'relationship' => [ 'relationship' => [
'col_idx' => 5, 'col_idx' => 5,
@ -656,8 +657,108 @@ class EmployeeServiceController extends AdminController
10 => 10, // enrollment: band_grade (Grade) -> inception: band_grade (Band/Grade) 10 => 10, // enrollment: band_grade (Grade) -> inception: band_grade (Band/Grade)
11 => 9 // enrollment: basic_pay (Basic Pay) -> inception: basic_pay (Basic Pay) 11 => 9 // enrollment: basic_pay (Basic Pay) -> inception: basic_pay (Basic Pay)
]; ];
protected $member_data_excel_columns = [
'sno' => [
'col_idx' => 0,
'col_cell_name' => 'A',
'col_name' => 'Sl no',
'is_mandatory' => false,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'emp_code' => [
'col_idx' => 1,
'col_cell_name' => 'B',
'col_name' => 'Emp Code',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'name' => [
'col_idx' => 2,
'col_cell_name' => 'C',
'col_name' => 'Name',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'relationship' => [
'col_idx' => 3,
'col_cell_name' => 'D',
'col_name' => 'Relationship',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => [
'Self', 'Spouse', 'Son', 'Daughter', 'Father', 'Mother',
'Father-in-law', 'Mother-in-law',
'self', 'spouse', 'son', 'daughter', 'father', 'mother',
'father-in-law', 'mother-in-law'
],
'custom' => 'check_relationship_for_member_data',
'params' => ['row', 'relationship', 'columns_to_check']
],
'gender' => [
'col_idx' => 4,
'col_cell_name' => 'E',
'col_name' => 'Gender',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => ['M', 'F', 'Male', 'Female', 'male', 'female', 'MALE', 'FEMALE']
],
'dob' => [
'col_idx' => 5,
'col_cell_name' => 'F',
'col_name' => 'DOB',
'is_mandatory' => true,
'data_type' => 'str',
'format' => 'd-M-Y',
'allowed_values' => null,
'age_validation' => true,
// 'custom' => 'check_dob_diff',
// 'params' => ['row', 'relationship', 'default_age_ratio', 'policy_details']
],
'age' => [
'col_idx' => 6,
'col_cell_name' => 'G',
'col_name' => 'Age',
'is_mandatory' => true,
'data_type' => 'int',
'format' => null,
'allowed_values' => null
],
'email' => [
'col_idx' => 7,
'col_cell_name' => 'H',
'col_name' => 'Email',
'is_mandatory' => false,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'mobile' => [
'col_idx' => 8,
'col_cell_name' => 'I',
'col_name' => 'Mobile',
'is_mandatory' => false,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'si' => [
'col_idx' => 9,
'col_cell_name' => 'J',
'col_name' => 'SI',
'is_mandatory' => false,
'data_type' => 'int',
'format' => null,
'allowed_values' => null,
]
];
public function __construct() public function __construct()
{ {
@ -810,6 +911,13 @@ class EmployeeServiceController extends AdminController
$enrollment_keys = array_keys($enrollment_columns_to_check); $enrollment_keys = array_keys($enrollment_columns_to_check);
} }
// for this condition to avoid 5,00,000 to 500000
if($current_column_action == 'SI'){
$row[3] = removeNumberFormatting($row[3]);
}else if(in_array($current_column_action, ['I','DA', 'MI', 'A'])){
$row[6] = removeNumberFormatting($row[6]);
}
//iterate each row for columns validations //iterate each row for columns validations
foreach ($row as $col_key => $col) foreach ($row as $col_key => $col)
{ {
@ -924,6 +1032,13 @@ class EmployeeServiceController extends AdminController
} }
else //trigger next data validation via job queue server else //trigger next data validation via job queue server
{ {
// check the condition if the policy from the Leads and check the lead id exist in the client policy table
if($file['action'] == 'inception' && $policy_details[0]->policy_entry_from == 3 && !empty($policy_details[0]->is_from_lead)){
$r = Jobs::addJob(['job_name' => 'compareMemberDataAndInceptionData','payload' => ['file_id' => $file_id]]);
$this->myLogger->logme("error",'compareMemberDataAndInceptionData job pushed');
return $result;
}
if($file['action'] == 'enrollment' && $file['uploaded_by'] != 1) // if current action is enrollment and uploaded by HR (0 or NULL) call next validation and return result if($file['action'] == 'enrollment' && $file['uploaded_by'] != 1) // if current action is enrollment and uploaded by HR (0 or NULL) call next validation and return result
{ {
// dd(); // dd();
@ -978,6 +1093,16 @@ class EmployeeServiceController extends AdminController
if($file['action'] == 'enrollment'){ $columns_to_check = $this->enrollment_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; } if($file['action'] == 'missed_inception'){ $columns_to_check = $this->inception_excel_columns; }
$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'; }
// get policy and rack details // get policy and rack details
$policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'],$file['policy_id']); $policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'],$file['policy_id']);
$policy_details = (array)$policy_terms[0]; $policy_details = (array)$policy_terms[0];
@ -1008,7 +1133,7 @@ class EmployeeServiceController extends AdminController
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 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' : '')); $employee_data_group_by_family = data_group_by_family($excel_data,'excel',($file['action'] == 'enrollment' ? 'enrollment' : ''), $current_column_action);
// dd($employee_data_group_by_family); // dd($employee_data_group_by_family);
$is_self_available_in_policy_terms = false; $is_self_available_in_policy_terms = false;
if($policy_details['policy_type_id'] == 3) // GMC parents if($policy_details['policy_type_id'] == 3) // GMC parents
@ -1213,6 +1338,16 @@ class EmployeeServiceController extends AdminController
if($file['action'] == 'si_enhancement'){ $columns_to_check = $this->si_enhance_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; } if($file['action'] == 'missed_inception'){ $columns_to_check = $this->inception_excel_columns; }
$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'; }
// get policy and rack details // get policy and rack details
$policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'],$file['policy_id']); $policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'],$file['policy_id']);
$policy_terms = (array) $policy_terms[0];// convert obj to array $policy_terms = (array) $policy_terms[0];// convert obj to array
@ -1236,7 +1371,7 @@ class EmployeeServiceController extends AdminController
//get existing units in the current branch //get existing units in the current branch
$existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $file['client_id'],client_branch_id: $file['client_branch_id']); $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); $employee_data_group_by_family = data_group_by_family($excel_data, 'excel', '', $current_column_action);
// dd($employee_data_group_by_family); // dd($employee_data_group_by_family);
foreach ($employee_data_group_by_family as $emp_id => $family) foreach ($employee_data_group_by_family as $emp_id => $family)
{ {
@ -1542,7 +1677,6 @@ class EmployeeServiceController extends AdminController
return true; return true;
} }
//enhance of emp //enhance of emp
public function employeesSIEnhanceProcess($params) public function employeesSIEnhanceProcess($params)
{ {
@ -1550,8 +1684,9 @@ class EmployeeServiceController extends AdminController
//get file name //get file name
$file_id = $params['file_id']; $file_id = $params['file_id'];
$file = $this->fileModel->find($file_id); $file = $this->fileModel->find($file_id);
// dd($file);
$file_name_with_path = WRITEPATH."/uploads/excel/".$file['file_name']; $file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name'];
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path); $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
$sheet = $spreadsheet->getActiveSheet(); $sheet = $spreadsheet->getActiveSheet();
@ -1565,53 +1700,55 @@ class EmployeeServiceController extends AdminController
// dd($excel_data); // dd($excel_data);
//get policy slab rates //get policy slab rates
$slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($file['policy_id'],$file['client_id']); $slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($file['policy_id'], $file['client_id']);
//iterate each row //iterate each row
// dd($slab_details); // dd($slab_details);
foreach ($excel_data as $col_key => $row) foreach ($excel_data as $col_key => $row) {
{ if (check_row_is_empty_or_null($row)) {
if(check_row_is_empty_or_null($row))
{
break; break;
} }
$row[3] = removeNumberFormatting($row[3]);
// echo '<br>START- ' . $row[2]; // echo '<br>START- ' . $row[2];
$employee = $this->employeeModel $employee = $this->employeeModel
->where('emp_code', $row[1]) ->where('emp_code', $row[1])
->where('name',$row[2]) ->where('name', $row[2])
->where('client_id',$file['client_id']) ->where('client_id', $file['client_id'])
->where('client_branch_id',$file['client_branch_id']) ->where('client_branch_id', $file['client_branch_id'])
->where('emp_status', 'active') ->where('emp_status', 'active')
->where('is_active', 1) ->where('is_active', 1)
->first(); ->first();
$employee_policy = $this->employeePolicyModel $employee_policy = $this->employeePolicyModel
->where('employee_id',$employee['id']) ->where('employee_id', $employee['id'])
->where('client_policy_id',$file['policy_id']) ->where('client_policy_id', $file['policy_id'])
->where('status', 'active') ->where('status', 'active')
->where('is_active', 1) ->where('is_active', 1)
->first(); ->first();
// dd($employee, $employee_policy); // dd($employee, $employee_policy);
$existing_endorsements = $this->empEndorsementModel->where('actions','si') $existing_endorsements = $this->empEndorsementModel->where('actions', 'si')
->where('table_name','employee_polices') ->where('table_name', 'employee_polices')
->where('endorsement_id is null') ->where('endorsement_id is null')
->where('emp_code',$employee['emp_code']) ->where('emp_code', $employee['emp_code'])
->where('name',$employee['name']) ->where('name', $employee['name'])
->where('field_name','basic_cover_si') ->where('field_name', 'basic_cover_si')
->where('is_active', 1)
->where('status !=', 'truncated')
->findAll(); ->findAll();
// dd($existing_endorsements); // dd($existing_endorsements);
//make entry in endorsement table //make entry in endorsement table
if(!count($existing_endorsements)) if (!count($existing_endorsements)) {
{
//transform data to send //transform data to send
//get applicable slab rate for current member relation //get applicable slab rate for current member relation
$pre_rack_rate_name = ''; $pre_rack_rate_name = '';
$applicable_rack_rate_name = ''; $applicable_rack_rate_name = '';
$applicable_rack_rate_master = []; $applicable_rack_rate_master = [];
foreach ($slab_details['slab_rates'] as $skey => $slab_value) foreach ($slab_details['slab_rates'] as $skey => $slab_value) {
{ if ($pre_rack_rate_name != $slab_value['rack_rate_name']) {
if($pre_rack_rate_name != $slab_value['rack_rate_name'])
{
$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); $rack_rate_json = json_decode($slab_value['additional_relationship'], true);
$relationship_array_key = strtolower(trim($employee['relationship'])); $relationship_array_key = strtolower(trim($employee['relationship']));
@ -1624,8 +1761,7 @@ class EmployeeServiceController extends AdminController
$relationship_array_key = 'parents-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') 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_name = $slab_value['rack_rate_name'];
$applicable_rack_rate_master = $slab_value['grid_master']; $applicable_rack_rate_master = $slab_value['grid_master'];
break; break;
@ -1637,36 +1773,32 @@ class EmployeeServiceController extends AdminController
$max_age_and_max_count_of_current_member = $this->employeeModel->getFamiliyCountAndMaxage($employee['emp_code']); $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 //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); $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 = $this->clientPolicyModel->getPolicyDetails($file['client_id'], $file['policy_id']);
$policy_terms = (array) $policy_terms[0]; $policy_terms = (array) $policy_terms[0];
// dd($policy_terms); // dd($policy_terms);
//grouping slab details by rack rate name //grouping slab details by rack rate name
$temp_slab_rates = group_slab_rates_basedon_name($slab_details); $temp_slab_rates = group_slab_rates_basedon_name($slab_details);
$calculated_data = premium_calculation_manager($data,$policy_terms,$temp_slab_rates,$row[3]); $calculated_data = premium_calculation_manager($data, $policy_terms, $temp_slab_rates, $row[3]);
$group_key = rand(100000, 999999); $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' => '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' => '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->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']);
} else {
$this->myLogger->logme("error", 'Endorsement already exists for this employee ' . json_encode(['file_id' => $file_id, 'emp_code' => $employee['emp_code'], 'emp_name' => $employee['name']]));
}
} }
$this->fileModel->where('id', $file_id)->set(['status' => 'success', 'reason' => ''])->update();
$this->myLogger->logme("error", '{file_id} uploaded success', ['file_id' => $file_id]);
}
$this->fileModel->where('id', $file_id)->set(['status' => 'success','reason' => ''])->update();
$this->myLogger->logme("error",'{file_id} uploaded success',['file_id' => $file_id]);
//set success msg to pull notifications //set success msg to pull notifications
$this->setPullNotification($this->getFileMetaDataByFileId($file_id,'success')); $this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'success'));
return true; return true;
} }
// insert or update in db for inception addition depent addition // insert or update in db for inception addition depent addition
public function employeesOnboardProcess($params) public function employeesOnboardProcess($params)
{ {
@ -1683,7 +1815,7 @@ class EmployeeServiceController extends AdminController
if(is_array($value)) if(is_array($value))
{ {
if (isset($value['gender'])) { $value['gender'] = normalizeGender($value['gender'] );}
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) 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)
{ {
@ -1872,10 +2004,11 @@ class EmployeeServiceController extends AdminController
} }
// ---------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------
public function getExcelErrorData($file_id){ public function getExcelErrorData($file_id)
{
try { try {
$file = $this->fileModel->find($file_id); $file = $this->fileModel->find($file_id);
@ -1982,15 +2115,12 @@ class EmployeeServiceController extends AdminController
$this->myLogger->logme('error', $errorMessage); $this->myLogger->logme('error', $errorMessage);
return false; // You can return an error response here return false; // You can return an error response here
} }
} }
// ---------------------------------------------------------------------------------
// --------------------------------------------------------------------------------- public function getFileMetaDataByFileId($file_id, $status = 'success')
{
public function getFileMetaDataByFileId($file_id, $status = 'success'){
$data = $this->fileModel $data = $this->fileModel
->select('files.*, clients.client_name, clients.short_name, policy_type.policy_type as policy_name,client_branch.branch_code') ->select('files.*, clients.client_name, clients.short_name, policy_type.policy_type as policy_name,client_branch.branch_code')
@ -2017,10 +2147,8 @@ public function getFileMetaDataByFileId($file_id, $status = 'success'){
return ['msg_txt' => $msg_txt, 'user_id' => $user_id, 'url' => $url, 'status' => $status, 'title' => $msg_title]; return ['msg_txt' => $msg_txt, 'user_id' => $user_id, 'url' => $url, 'status' => $status, 'title' => $msg_title];
} }
public function setPullNotification($data)
public function setPullNotification($data){ {
$array = ['message_text' => $data['msg_txt'], 'action_url' => $data['url'], 'msg_status' => $data['status'], 'msg_title' => $data['title']]; $array = ['message_text' => $data['msg_txt'], 'action_url' => $data['url'], 'msg_status' => $data['status'], 'msg_title' => $data['title']];
$jsonEncodeData = json_encode($array); $jsonEncodeData = json_encode($array);
@ -2033,11 +2161,8 @@ public function getFileMetaDataByFileId($file_id, $status = 'success'){
'message_type' => '1to1', 'message_type' => '1to1',
]; ];
$this->messageModel->insert($msg_data); $this->messageModel->insert($msg_data);
}
}
public function employeesEnrollmentInsert($params) public function employeesEnrollmentInsert($params)
{ {
@ -2077,6 +2202,7 @@ public function getFileMetaDataByFileId($file_id, $status = 'success'){
$allowedHighestColumn = end($columns_to_check); $allowedHighestColumn = end($columns_to_check);
$excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']); $excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']);
// print_r($keys);die(); // print_r($keys);die();
//get existing units in the current branch //get existing units in the current branch
$existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $file['client_id'],client_branch_id: $file['client_branch_id']); $existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $file['client_id'],client_branch_id: $file['client_branch_id']);
//remove header //remove header
@ -2113,7 +2239,7 @@ public function getFileMetaDataByFileId($file_id, $status = 'success'){
$value['emp_code'] = $row[1]; $value['emp_code'] = $row[1];
$value['name'] = $row[2]; $value['name'] = $row[2];
$value['doj'] = (!empty($row[3]) ? change_date_format($row[3],'d-M-Y','Y-m-d') : null ); $value['doj'] = (!empty($row[3]) ? change_date_format($row[3],'d-M-Y','Y-m-d') : null );
$value['gender'] = $row[4]; $value['gender'] = normalizeGender($row[4]);
$value['relationship'] = ucfirst(trim($row[5])); $value['relationship'] = ucfirst(trim($row[5]));
$value['dob'] = change_date_format($row[6],'d-M-Y','Y-m-d'); $value['dob'] = change_date_format($row[6],'d-M-Y','Y-m-d');
$value['email_corporate'] = $row[7]; $value['email_corporate'] = $row[7];
@ -2259,6 +2385,142 @@ public function getFileMetaDataByFileId($file_id, $status = 'success'){
return true; return true;
}//end of employeesEnrollmentInsert } //end of employeesEnrollmentInsert
// --------- MEMBER DATA AND INCEPTION DATA COMPARISION ------------------------------------------------------------------------
public function compareMemberDataAndInceptionData($params)
{
helper('excel_util_helper');
$file_id = $params['file_id'] ?? null;
if (empty($file_id)) {
return ['status' => false, 'msg' => 'File ID is missing'];
}
// ✅ Get File Data
$file = $this->fileModel->where(['is_active' => 1, 'id' => $file_id])->first();
if (empty($file)) {
return ['status' => false, 'msg' => 'File not found in DB'];
}
// ✅ Get Client Policy Data
$client_policy_data = $this->clientPolicyModel->where(['is_active' => 1, 'id' => $file['policy_id']])->first();
if (empty($client_policy_data)) {
return ['status' => false, 'msg' => 'Client policy data not found in DB (policy_id: ' . $file['policy_id'] . ')'];
}
// ✅ Get Lead Data
$leadModel = new LeadsModel();
$lead_data = $leadModel->where(['is_active' => 1, 'id' => $client_policy_data['is_from_lead']])->first();
if (empty($lead_data)) {
return ['status' => false, 'msg' => 'Lead data not found in DB (lead_id: ' . $client_policy_data['is_from_lead'] . ')'];
}
// ✅ Define File Paths
$inception_file_path = !empty($file['file_name']) ? WRITEPATH . "uploads/excel/" . $file['file_name'] : '';
$member_file_path = !empty($lead_data['file_name']) ? WRITEPATH . "uploads/lead_files/" . $lead_data['file_name'] : '';
// ✅ Check Inception File
if (empty($file['file_name']) || !file_exists($inception_file_path)) {
$message = empty($file['file_name']) ? "Inception file name is missing" : "Inception physical file not found";
$this->myLogger->logme('error', "$message for file id $file_id");
$this->fileModel->update($file_id, [
'status' => 'failed',
'reason' => json_encode(['error_summary' => [5], 'error_data' => $message])
]);
return ['error_summary' => [5], 'error_data' => $message];
}
// ✅ Check Member File
if (empty($lead_data['file_name']) || !file_exists($member_file_path)) {
$message = empty($lead_data['file_name']) ? "Member file name is missing" : "Member data physical file not found";
$this->myLogger->logme('error', "$message for lead id {$lead_data['id']}");
$this->fileModel->update($file_id, [
'status' => 'failed',
'reason' => json_encode(['error_summary' => [5], 'error_data' => $message])
]);
return ['error_summary' => [5], 'error_data' => $message];
}
// ✅ Read Inception Excel
$inception_columns = $this->inception_excel_columns;
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inception_file_path);
$sheet = $spreadsheet->getActiveSheet();
$highestRow = $sheet->getHighestDataRow();
$allowedColumn = end($inception_columns)['col_cell_name'];
$inception_data = $sheet->rangeToArray("A1:{$allowedColumn}{$highestRow}");
$inception_data = ExcelSanitizeHelper::sanitizeArrayData($inception_data);
// ✅ Read Member Excel
$member_columns = $this->member_data_excel_columns;
$spreadsheet2 = \PhpOffice\PhpSpreadsheet\IOFactory::load($member_file_path);
$sheet2 = $spreadsheet2->getSheet(0);
$highestRow2 = $sheet2->getHighestDataRow();
$allowedColumn2 = end($member_columns)['col_cell_name'];
$member_data = $sheet2->rangeToArray("A1:{$allowedColumn2}{$highestRow2}");
$member_data = ExcelSanitizeHelper::sanitizeArrayData($member_data);
// dd($inception_data, $member_data);
// ✅ Compare Inception Data with Member Data
$result = ['error_type' => 2, 'error_summary' => [], 'error_data' => []];
$inception_data_count = count($inception_data);
$member_data_count = count($member_data);
if ($inception_data_count !== $member_data_count) {
$result['error_summary'][] = 15;
$result['error_message'] = "
<strong>Inception Data Count:</strong>
<span class='badge badge-danger'>{$inception_data_count}</span>&nbsp;&nbsp;
<strong>Member Data Count:</strong>
<span class='badge badge-danger'>{$member_data_count}</span>";
}
foreach ($inception_data as $inception_key => $inception_row) {
// 🔹 If inception row is empty → stop all further processing
if (check_row_is_empty_or_null($inception_row)) {
break;
}
$match_found = false;
foreach ($member_data as $member_row) {
if (
$inception_row[1] == $member_row[1] && // emp_id / emp_code
$inception_row[2] == $member_row[2] && // name_of_emp_dep / name
$inception_row[5] == $member_row[3] && // relationship
normalizeGender($inception_row[4]) == normalizeGender($member_row[4]) && // gender
$inception_row[3] == $member_row[5] && // dob
$inception_row[13] == $member_row[7] && // email
$inception_row[12] == $member_row[8] // phone / mobile
) {
$match_found = true;
break;
}
}
if (!$match_found) {
array_push($result['error_summary'], 14);
$result['error_data'][$inception_key]['sno']['error'][] = "This inception row was not found in the member data list.";
}
}
// ✅ Handle Result
if (!empty($result['error_summary'])) {
$result['error_summary'] = array_count_values($result['error_summary']);
$this->fileModel->update($file_id, [
'status' => 'failed',
'reason' => json_encode($result)
]);
$this->myLogger->logme('error', "File ID $file_id comparison failed");
} else {
Jobs::addJob(['job_name' => 'excelFileDataValidation', 'payload' => ['file_id' => $file_id]]);
}
return $result;
}
} }

View File

@ -210,13 +210,13 @@ class Home extends PublicController
public function checkPolicyDoc() public function checkPolicyDoc()
{ {
// $this->convertToPdf();die(); try
{ // $this->convertToPdf();die();
// Replace with your actual Gemini API key // Replace with your actual Gemini API key
$apiKey = 'AIzaSyBbx-uotRBqkYhqLpmD60420E_a0G0duP8'; $apiKey = getenv('GEMINI_API_KEY');
// The model to use and the API endpoint // The model to use and the API endpoint
$model = "gemini-pro"; $model = "gemini-pro";
$model = "gemini-2.5-flash"; $model = getenv('GEMINI_MODEL');
// $model = "gemini-1.5-pro"; // $model = "gemini-1.5-pro";
// $model = "gemini-1.5-pro"; // $model = "gemini-1.5-pro";
$url = "https://generativelanguage.googleapis.com/v1beta/models/{$model}:generateContent?key={$apiKey}"; $url = "https://generativelanguage.googleapis.com/v1beta/models/{$model}:generateContent?key={$apiKey}";
@ -233,7 +233,7 @@ class Home extends PublicController
$finfo = finfo_open(FILEINFO_MIME_TYPE); $finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $filePath); $mimeType = finfo_file($finfo, $filePath);
finfo_close($finfo); finfo_close($finfo);
// print_r($mimeType);die(); print_r($mimeType);die();
// Define supported inline MIME types // Define supported inline MIME types
$supportedInlineMimeTypes = ['application/pdf','text/csv']; $supportedInlineMimeTypes = ['application/pdf','text/csv'];
@ -242,8 +242,8 @@ class Home extends PublicController
$base64Content = base64_encode($fileContent); $base64Content = base64_encode($fileContent);
// The prompt you want to send to the model // The prompt you want to send to the model
// $prompt = "give me a json with emp data like name,age,dob,mobile and email. only json not any explanations"; // $prompt = "give me a json with emp data like name,age,dob,mobile and email. only json not any explanations";
$prompt = "Read the following motor policy pdf document and convert into JSON format as sample specified. Give me only JSON,not any explanations."; $prompt = "Read the following motor policy pdf document and convert into JSON format as sample specified. Give me only JSON,not any explanations.while pick up premium break up give own damage, third party ,personal accident and taxes as mentioned in JSON format.Notes:vehicle_type should be like Two Wheeler,Four Feeler,Good Vehicle,Bus, Tractor,Commercial Vehicle.rto_state_code is first two char of reg_no and rto_city_code 3rd & 4th char of reg_no and it should be two digit numeric code. Any date should be in mysql date format";
$prompt .= '"{\"policy\":{\"policy_number\":\"\",\"issue_date\":\"\",\"period\":{\"start\":\"\",\"end\":\"\"},\"insurer\":\"\",\"previous_policy_number\":\"\"},\"insured\":{\"name\":\"\",\"father_name\":\"\",\"address\":[\"\"],\"mobile\":\"\",\"id_proofs\":{\"aadhaar\":\"\",\"pan\":\"\"}},\"vehicle\":{\"reg_no\":\"\",\"engine_no\":\"\",\"chassis_no\":\"\",\"make\":\"\",\"model\":\"\",\"year\":\"\",\"cubic_capacity\":\"\",\"vehicle_type\":\"\"},\"rto\":\"\",\"premium\":{\"tp\":0,\"od\":0,\"pa_od\":0,\"taxes\":{},\"total\":0,\"in_words\":\"\"},\"endorsements\":[{\"code\":\"\",\"desc\":\"\"}]}"'; $prompt .= '"{\"policy\":{\"policy_number\":\"\",\"issue_date\":\"\",\"period\":{\"start\":\"\",\"end\":\"\"},\"insurer\":\"\",\"previous_policy_number\":\"\"},\"insured\":{\"name\":\"\",\"father_name\":\"\",\"address\":[\"\"],\"mobile\":\"\",\"id_proofs\":{\"aadhaar\":\"\",\"pan\":\"\"}},\"vehicle\":{\"reg_no\":\"\",\"rto_state_code\":\"\",\"rto_city_code\":\"\",\"weight\":\"\",\"fuel_type\":\"\",\"date_of_registration\":\"\",\"year_of_manufacture\":\"\",\"engine_no\":\"\",\"chassis_no\":\"\",\"make\":\"\",\"model\":\"\",\"year\":\"\",\"cubic_capacity\":\"\",\"vehicle_type\":\"\"},\"rto\":\"\",\"premium\":{\"tp\":0,\"od\":0,\"pa\":0,\"taxes\":{},\"total\":0,\"in_words\":\"\"},\"endorsements\":[{\"code\":\"\",\"desc\":\"\"}]}"';
$payloadPart = null; $payloadPart = null;
@ -253,7 +253,7 @@ class Home extends PublicController
]; ];
// Conditionally handle the file upload based on MIME type // Conditionally handle the file upload based on MIME type
if (in_array($mimeType, $supportedInlineMimeTypes)) { if (in_array($mimeType, $supportedInlineMimeTypes)) {
echo "Detected supported format inline MIME type ({$mimeType})"; // echo "Detected supported format inline MIME type ({$mimeType})";
// Handle PDF as inline data // Handle PDF as inline data
$fileContent = file_get_contents($filePath); $fileContent = file_get_contents($filePath);
$base64Content = base64_encode($fileContent); $base64Content = base64_encode($fileContent);
@ -272,10 +272,10 @@ class Home extends PublicController
]; ];
} else { } else {
// Handle Excel/CSV using the Files API // Handle Excel/CSV using the Files API
echo "Detected unsupported inline MIME type ({$mimeType}). Uploading via Files API...\n"; // echo "Detected unsupported inline MIME type ({$mimeType}). Uploading via Files API...\n";
$fileInfo = $this->uploadFileToGemini($filePath, $apiKey); // Pass apiKey $fileInfo = $this->uploadFileToGemini($filePath, $apiKey); // Pass apiKey
print_r($fileInfo); // print_r($fileInfo);
// The file part, using the URI from the Files API upload // The file part, using the URI from the Files API upload
$file_part = [ $file_part = [
"fileData" => [ "fileData" => [
@ -321,23 +321,69 @@ class Home extends PublicController
// Check for cURL errors // Check for cURL errors
if (curl_errno($ch)) { if (curl_errno($ch)) {
echo 'cURL Error: ' . curl_error($ch); $curl_error = curl_error($ch);
throw new Exception("cURL Error: " . $curl_error);
} }
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL handle // Close the cURL handle
curl_close($ch); curl_close($ch);
$ch = null; // Mark handle as closed
// Check for non-successful HTTP status codes
if ($http_code < 200 || $http_code >= 300) {
throw new Exception("API returned non-successful HTTP status code: $http_code. Response: " . substr($response, 0, 200) . '...');
}
// Decode the JSON response // Decode the JSON response
$responseData = json_decode($response, true); $responseData = json_decode($response, true, 512, JSON_THROW_ON_ERROR);
echo '<pre>'; $text_path = $responseData['candidates'][0]['content']['parts'][0]['text'] ?? null;
print_r($responseData);
echo '<pre>'; if ($text_path) {
// Check if the response contains generated text $generatedText = $text_path;
if (isset($responseData['candidates'][0]['content']['parts'][0]['text'])) { log_message('info', "Successfully received generated text.");
$generatedText = $responseData['candidates'][0]['content']['parts'][0]['text'];
echo "Generated Text: " . $generatedText; // 9. Attempt to extract and decode the exact JSON from the generated text
$json_string = '';
// Preferred: Regex to find content inside a JSON markdown block: ```json\n(.*?)\n```
$extracted_json_match = [];
if (preg_match('/```json\s*(.*?)\s*```/s', $generatedText, $extracted_json_match)) {
$json_string = trim($extracted_json_match[1]);
} else { } else {
echo "Error or no text generated. Response: " . $response; // Fallback: Find the first '{' and the last '}'
$start = strpos($generatedText, '{');
$end = strrpos($generatedText, '}');
if ($start !== false && $end !== false && $end > $start) {
$json_string = substr($generatedText, $start, $end - $start + 1);
}
}
if (empty($json_string)) {
throw new Exception("Could not extract a valid JSON string from the generated text.");
}
// Decode the extracted JSON string
$final_data = json_decode($json_string, true, 512, JSON_THROW_ON_ERROR);
log_message('info', "Extracted and decoded final JSON data successfully.");
echo '<pre>';
print_r($final_data);
// return $final_data;
} else {
// No generated text found, possibly a model safety block or API structure change
throw new Exception("Response structure invalid or no generated text candidate found.");
}
} catch (Exception $e) {
// Log the error
log_message('ERROR', "$request_id: Fatal Error: " . $e->getMessage());
// Ensure cURL handle is closed if an exception occurred after initialization but before closing
if ($ch !== null) {
curl_close($ch);
}
return null; // Return null on failure
} }
} }

View File

@ -171,6 +171,10 @@ class JobWorker extends AdminController
'type' => 'CC', // Handler Category 'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\LeadsController', 'handler' => 'App\Controllers\LeadsController',
], ],
'compareMemberDataAndInceptionData' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmployeeServiceController',
],
]; ];

View File

@ -77,7 +77,7 @@ class LeadsController extends BaseController
protected $issuer; protected $issuer;
protected $clientType; protected $clientType;
protected $leadType; protected $leadType;
protected $leadsStatus; public $leadsStatus;
protected $claim_type_for_gpa; protected $claim_type_for_gpa;
protected $cause_of_death; protected $cause_of_death;
protected $buisnessType; protected $buisnessType;
@ -665,7 +665,10 @@ class LeadsController extends BaseController
if ($value['lead_form_type'] == 1) { if ($value['lead_form_type'] == 1) {
//for this push the job to the calculateMembersDemography() function //for this push the job to the calculateMembersDemography() function
$job_details = new Jobs(); $job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'memberDataListExcelFileFormatValidation', 'payload' => [ // $r = Jobs::addJob(['job_name' => 'memberDataListExcelFileFormatValidation', 'payload' => [
// 'lead_id' => $insert,
// ]]);
$r = Jobs::addJob(['job_name' => 'calculateMembersDemography', 'payload' => [
'lead_id' => $insert, 'lead_id' => $insert,
]]); ]]);
} }
@ -773,7 +776,7 @@ class LeadsController extends BaseController
$multi_file_data = []; $multi_file_data = [];
foreach ($files as $index => $value) { foreach ($files as $index => $value) {
$file_name = file_Upload($value, $uploadFilePath); $file_name = file_Upload_for_lead($value, $uploadFilePath);
$multi_file_data[] = [ $multi_file_data[] = [
'file_name' => $file_name, 'file_name' => $file_name,
'docs_name' => $docs_names[$index], 'docs_name' => $docs_names[$index],
@ -809,7 +812,10 @@ class LeadsController extends BaseController
if (!empty($lead_form_type) && $lead_form_type == 1 && $key == 0) { if (!empty($lead_form_type) && $lead_form_type == 1 && $key == 0) {
//for this push the job to the calculateMembersDemography() function //for this push the job to the calculateMembersDemography() function
$job_details = new Jobs(); $job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'memberDataListExcelFileFormatValidation', 'payload' => [ // $r = Jobs::addJob(['job_name' => 'memberDataListExcelFileFormatValidation', 'payload' => [
// 'lead_id' => $lead_id,
// ]]);
$r = Jobs::addJob(['job_name' => 'calculateMembersDemography', 'payload' => [
'lead_id' => $lead_id, 'lead_id' => $lead_id,
]]); ]]);
log_message('info', "calculateMembersDemography JOB PUSHED"); log_message('info', "calculateMembersDemography JOB PUSHED");
@ -1083,6 +1089,7 @@ class LeadsController extends BaseController
// 7. Define mail templates as constants or config // 7. Define mail templates as constants or config
$mail_content = $this->getMailTemplate(); $mail_content = $this->getMailTemplate();
$placement_mail_content = $this->getMailTemplate('placement');
$subject = $this->getSubjectTemplate($lead_data); $subject = $this->getSubjectTemplate($lead_data);
// 8. Pre-calculate sum assured only for GPA // 8. Pre-calculate sum assured only for GPA
@ -1091,7 +1098,7 @@ class LeadsController extends BaseController
// 9. Transform mail content once // 9. Transform mail content once
$data['mail_content'] = $this->transformMailContent($lead_data, $mail_content, $data['page_name']); $data['mail_content'] = $this->transformMailContent($lead_data, $mail_content, $data['page_name']);
$data['subject'] = $this->transformMailContent($lead_data, $subject, $data['page_name']); $data['subject'] = $this->transformMailContent($lead_data, $subject, $data['page_name']);
$data['placement_mail_content'] = $this->transformMailContent($lead_data, $mail_content, 'Placement'); $data['placement_mail_content'] = $this->transformMailContent($lead_data, $placement_mail_content, 'Placement');
$data['placement_subject'] = $this->transformMailContent($lead_data, $subject, 'Placement'); $data['placement_subject'] = $this->transformMailContent($lead_data, $subject, 'Placement');
// 10. Combine related queries // 10. Combine related queries
@ -1144,8 +1151,26 @@ class LeadsController extends BaseController
} }
// 13. Extract mail template to separate method for reusability // 13. Extract mail template to separate method for reusability
private function getMailTemplate() private function getMailTemplate( $template_type = "" )
{ {
if($template_type == 'placement'){
return '
<p>Dear Sir,</p>
<p>Greetings From Nhance India!</p>
<p>Please find attached the {{RFQ_OR_QCR}} for <strong>{{POLICY_TYPE}}</strong> policy pertaining to <strong>{{CLIENT_NAME}}</strong>.</p>
<p>Kindly request you to issue the policy at the earliest.</p>
<p>In case of any query, please feel free to contact us.</p>
<p>Thank You!</p><br>
<p>Best regards,</p>
<div style="margin: 0; padding: 0; line-height: 1.2;">
<div>{{LOGGED_USER_NAME}}</div>
<div>Mobile: {{LOGGED_USER_MOBILE}}</div>
</div>
<img src="{{LOGO_PATH}}" alt="Nhance Logo" width="100" style="margin-top:10px;">
';
}else{
return ' return '
<p>Dear Sir,</p> <p>Dear Sir,</p>
<p>Greetings From Nhance India!</p> <p>Greetings From Nhance India!</p>
@ -1163,6 +1188,7 @@ class LeadsController extends BaseController
<img src="{{LOGO_PATH}}" alt="Nhance Logo" width="100" style="margin-top:10px;"> <img src="{{LOGO_PATH}}" alt="Nhance Logo" width="100" style="margin-top:10px;">
'; ';
} }
}
// 14. Extract subject template to separate method // 14. Extract subject template to separate method
private function getSubjectTemplate($lead_data) private function getSubjectTemplate($lead_data)
@ -3673,7 +3699,7 @@ class LeadsController extends BaseController
private function prepareClientData($data) private function prepareClientData($data)
{ {
return [ return [
'client_type' => $data['client_type'] ?? null, 'client_type' => 1,
'entity_type_id' => $data['entity_type_id'] ?? null, 'entity_type_id' => $data['entity_type_id'] ?? null,
'client_code' => $data['client_code'] ?? null, 'client_code' => $data['client_code'] ?? null,
'client_name' => $data['client_name'] ?? null, 'client_name' => $data['client_name'] ?? null,
@ -3723,6 +3749,8 @@ class LeadsController extends BaseController
'policy_start_date' => $data['policy_start_date'], 'policy_start_date' => $data['policy_start_date'],
'policy_end_date' => $data['policy_end_date'], 'policy_end_date' => $data['policy_end_date'],
'policy_status' => 1, 'policy_status' => 1,
'policy_entry_from' => 3,
'is_from_lead' => $data['id'],
]; ];
$policy_type_id = $data['policy_type_id']; $policy_type_id = $data['policy_type_id'];
@ -5266,10 +5294,10 @@ class LeadsController extends BaseController
'filePath' => $fullPath 'filePath' => $fullPath
]; ];
} else { } else {
log_message('warning', 'File name is empty for ID: ' . $id); log_message('error', 'File name is empty for ID: ' . $id);
} }
} else { } else {
log_message('warning', 'File does not exist at path: ' . $fullPath); log_message('error', 'File does not exist at path: ' . $fullPath);
} }
} else { } else {
log_message('warning', 'No active lead file found for ID: ' . $id . ' and lead_id: ' . $lead_id); log_message('warning', 'No active lead file found for ID: ' . $id . ' and lead_id: ' . $lead_id);

View File

@ -1,46 +1,46 @@
<?php <?php
namespace App\Controllers; namespace App\Controllers;
use App\Controllers\BaseController; use App\Controllers\BaseController;
use App\Controllers\GoogleDriveController; use App\Controllers\GoogleDriveController;
use App\Helpers\DepositHelper; use App\Helpers\DepositHelper;
use CodeIgniter\API\ResponseTrait; use CodeIgniter\API\ResponseTrait;
use App\Models\PolicyTransactionModel; use App\Models\PolicyTransactionModel;
use App\Models\PolicyTransactionStatusModel; use App\Models\PolicyTransactionStatusModel;
use App\Models\ClientModel; use App\Models\ClientModel;
use App\Models\ClientBranchModel; use App\Models\ClientBranchModel;
use App\Models\ClientDepositModel; use App\Models\ClientDepositModel;
use App\Models\ClientPolicyModel; use App\Models\ClientPolicyModel;
use App\Models\PolicyTypeModel; use App\Models\PolicyTypeModel;
use App\Models\InsurerBranchModel; use App\Models\InsurerBranchModel;
use App\Models\InsurerModel; use App\Models\InsurerModel;
use App\Models\KYCEntityTypeModel; use App\Models\KYCEntityTypeModel;
use App\Models\ClientKYCDocsModel; use App\Models\ClientKYCDocsModel;
use App\Models\TPABranchModel; use App\Models\TPABranchModel;
use App\Models\TPAModel; use App\Models\TPAModel;
use App\Models\PTFileModel; use App\Models\PTFileModel;
use App\Models\PTCOShareDetailsModel; use App\Models\PTCOShareDetailsModel;
use App\Models\EmployeeModel; use App\Models\EmployeeModel;
use App\Models\UserTeamsModel; use App\Models\UserTeamsModel;
use App\Models\UserModel; use App\Models\UserModel;
use App\Models\EmployeePolicyModel; use App\Models\EmployeePolicyModel;
use App\Models\InsurerStatements; use App\Models\InsurerStatements;
use App\Models\InvPaymentDetailsModel; use App\Models\InvPaymentDetailsModel;
use App\Models\BatchFileModel; use App\Models\BatchFileModel;
use App\Models\FileModel; use App\Models\FileModel;
use App\Models\COShareStmtDetailsModel; use App\Models\COShareStmtDetailsModel;
use App\Models\BdsPlacementModel; use App\Models\BdsPlacementModel;
use Kint\Kint; use Kint\Kint;
use App\Helpers\MailHelper; use App\Helpers\MailHelper;
use App\Helpers\ExcelSanitizeHelper; use App\Helpers\ExcelSanitizeHelper;
use App\Models\NhanceBranchModel; use App\Models\NhanceBranchModel;
use Exception; use Exception;
class PolicyTransactionController extends BaseController class PolicyTransactionController extends BaseController
{ {
use ResponseTrait; use ResponseTrait;
protected $myLogger; protected $myLogger;
@ -2409,8 +2409,8 @@ class PolicyTransactionController extends BaseController
// $client_name = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[3]); //clientname from excel // $client_name = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[3]); //clientname from excel
$endorsement_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[2]); //policy_end_date from excel $endorsement_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[2]??''); //policy_end_date from excel
$endorsement_no = preg_replace( '/[\x{200B}\x{200C}\x{200D}\x{FEFF}\x{00A0}\x{200E}\x{200F}\x{202A}-\x{202E}]/u', '', $excel_row[2]); //policy_end_date from excel $endorsement_no = preg_replace( '/[\x{200B}\x{200C}\x{200D}\x{FEFF}\x{00A0}\x{200E}\x{200F}\x{202A}-\x{202E}]/u', '', $excel_row[2]??''); //policy_end_date from excel
// Kint::dump($excel_key,$policy_no,$endorsement_no,$policy_start_date,$policy_end_date);//die(); // Kint::dump($excel_key,$policy_no,$endorsement_no,$policy_start_date,$policy_end_date);//die();
foreach ($source_data as $source_key => $source_row) { foreach ($source_data as $source_key => $source_row) {
@ -3179,8 +3179,8 @@ class PolicyTransactionController extends BaseController
} }
public function reportBDSNew() public function reportBDSNew()
{ {
// 🧭 Basic Page Info // 🧭 Basic Page Info
$data['tab_name'] = 'BDS Report'; $data['tab_name'] = 'BDS Report';
$data['page_name'] = 'BDS Report'; $data['page_name'] = 'BDS Report';
@ -3285,8 +3285,8 @@ public function reportBDSNew()
// 🧩 Load View // 🧩 Load View
$this->loadLayout('report_bds_filter', $data); $this->loadLayout('report_bds_filter', $data);
} }
} }

View File

@ -362,16 +362,16 @@ class TestingController extends BaseController
$pre_clients_list = $this->getNonDuplicatePreClients(); $pre_clients_list = $this->getNonDuplicatePreClients();
$log_post_clients_list = $post_clients_list ; $log_post_clients_list = $post_clients_list;
$log_pre_clients_list = $pre_clients_list ; $log_pre_clients_list = $pre_clients_list;
log_message('error', 'Post Clients to be processed: ' . count($log_post_clients_list)); log_message('error', 'Post Clients to be processed: ' . count($log_post_clients_list));
log_message('error', 'Pre Clients to be processed: ' . count($log_pre_clients_list)); log_message('error', 'Pre Clients to be processed: ' . count($log_pre_clients_list));
$matched_Count = 0 ; $matched_Count = 0;
$expected_match_count = min(count($post_clients_list), count($pre_clients_list)); $expected_match_count = min(count($post_clients_list), count($pre_clients_list));
@ -450,25 +450,21 @@ class TestingController extends BaseController
log_message('error', 'Total UnMatched Count: ' . $expected_match_count - $matched_Count); log_message('error', 'Total UnMatched Count: ' . $expected_match_count - $matched_Count);
log_message('error','unmatched_reocrds'); log_message('error', 'unmatched_reocrds');
$log_post_clients_list = array_values($log_post_clients_list); $log_post_clients_list = array_values($log_post_clients_list);
$log_pre_clients_list = array_values($log_pre_clients_list); $log_pre_clients_list = array_values($log_pre_clients_list);
if( (count($log_pre_clients_list) < count($log_post_clients_list))){ if ((count($log_pre_clients_list) < count($log_post_clients_list))) {
log_message('error',"unmatched records count from pre- ". count($log_pre_clients_list)); log_message('error', "unmatched records count from pre- " . count($log_pre_clients_list));
log_message('error',print_r($log_pre_clients_list,true)); log_message('error', print_r($log_pre_clients_list, true));
} else { } else {
log_message('error',"unmatched records count from post - ".count($log_post_clients_list)); log_message('error', "unmatched records count from post - " . count($log_post_clients_list));
log_message('error',print_r($log_post_clients_list,true)); log_message('error', print_r($log_post_clients_list, true));
} }
} }
return $this->response->setJSON(['status' => 'success', 'message' => 'Client and Branch mapping completed.'])->setStatusCode(200); return $this->response->setJSON(['status' => 'success', 'message' => 'Client and Branch mapping completed.'])->setStatusCode(200);
} }
@ -543,18 +539,81 @@ class TestingController extends BaseController
} }
private $firstNames = [ private $firstNames = [
'Rajesh', 'Priya', 'Amit', 'Sneha', 'Vikram', 'Anjali', 'Rahul', 'Deepika', 'Rajesh',
'Sanjay', 'Kavita', 'Arun', 'Pooja', 'Manoj', 'Nisha', 'Suresh', 'Meera', 'Priya',
'Karthik', 'Divya', 'Ravi', 'Lakshmi', 'Anand', 'Swathi', 'Vijay', 'Rekha', 'Amit',
'Ashok', 'Sangeetha', 'Prakash', 'Uma', 'Ramesh', 'Vani', 'Kumar', 'Radha', 'Sneha',
'Dinesh', 'Shanti', 'Ganesh', 'Parvati', 'Mohan', 'Sita', 'Arjun', 'Geetha' 'Vikram',
'Anjali',
'Rahul',
'Deepika',
'Sanjay',
'Kavita',
'Arun',
'Pooja',
'Manoj',
'Nisha',
'Suresh',
'Meera',
'Karthik',
'Divya',
'Ravi',
'Lakshmi',
'Anand',
'Swathi',
'Vijay',
'Rekha',
'Ashok',
'Sangeetha',
'Prakash',
'Uma',
'Ramesh',
'Vani',
'Kumar',
'Radha',
'Dinesh',
'Shanti',
'Ganesh',
'Parvati',
'Mohan',
'Sita',
'Arjun',
'Geetha'
]; ];
private $lastNames = [ private $lastNames = [
'Kumar', 'Sharma', 'Singh', 'Patel', 'Reddy', 'Nair', 'Iyer', 'Krishnan', 'Kumar',
'Rao', 'Gupta', 'Verma', 'Agarwal', 'Joshi', 'Mehta', 'Desai', 'Pillai', 'Sharma',
'Menon', 'Bhat', 'Naidu', 'Varma', 'Malhotra', 'Kapoor', 'Chopra', 'Saxena', 'Singh',
'Pandey', 'Mishra', 'Tiwari', 'Dubey', 'Sinha', 'Jain', 'Shah', 'Thakur' 'Patel',
'Reddy',
'Nair',
'Iyer',
'Krishnan',
'Rao',
'Gupta',
'Verma',
'Agarwal',
'Joshi',
'Mehta',
'Desai',
'Pillai',
'Menon',
'Bhat',
'Naidu',
'Varma',
'Malhotra',
'Kapoor',
'Chopra',
'Saxena',
'Pandey',
'Mishra',
'Tiwari',
'Dubey',
'Sinha',
'Jain',
'Shah',
'Thakur'
]; ];
private $relationships = ['Self', 'Spouse', 'Son', 'Daughter', 'Father', 'Mother']; private $relationships = ['Self', 'Spouse', 'Son', 'Daughter', 'Father', 'Mother'];
@ -716,7 +775,8 @@ class TestingController extends BaseController
} }
public function logo_renaming(){ public function logo_renaming()
{
$directory = ROOTPATH . 'public/uploads/logo/'; $directory = ROOTPATH . 'public/uploads/logo/';
@ -733,14 +793,14 @@ class TestingController extends BaseController
foreach ($files as $file) { foreach ($files as $file) {
// Skip system entries // Skip system entries
if ($file === '.' || $file === '..' ) { if ($file === '.' || $file === '..') {
continue; continue;
} }
$oldPath = $directory . $file; $oldPath = $directory . $file;
if (is_file($oldPath) && in_array(trim($file) , $client_logo_files)) { if (is_file($oldPath) && in_array(trim($file), $client_logo_files)) {
// Remove all spaces from filename // Remove all spaces from filename
$newFileName = preg_replace('/\s+|\x{00A0}|\x{200B}|\x{200C}|\x{200D}|\x{FEFF}/u', '', $file); $newFileName = preg_replace('/\s+|\x{00A0}|\x{200B}|\x{200C}|\x{200D}|\x{FEFF}/u', '', $file);
@ -764,7 +824,8 @@ class TestingController extends BaseController
log_message('error', 'Failed Renames: ' . $failed_rename_files); log_message('error', 'Failed Renames: ' . $failed_rename_files);
log_message('error', 'Database Update Status: ' . ($dbUpdated ? 'Success' : 'No changes made')); log_message('error', 'Database Update Status: ' . ($dbUpdated ? 'Success' : 'No changes made'));
return $this->response->setJSON(['status' => 'success', return $this->response->setJSON([
'status' => 'success',
'message' => 'Logo renaming completed. kindly check backend logs for details', 'message' => 'Logo renaming completed. kindly check backend logs for details',
'data' => [ 'data' => [
'renamed_files' => $rename_files, 'renamed_files' => $rename_files,
@ -773,7 +834,8 @@ class TestingController extends BaseController
])->setStatusCode(200); ])->setStatusCode(200);
} }
public function get_client_logo_files(){ public function get_client_logo_files()
{
$db = \Config\Database::connect(); $db = \Config\Database::connect();
@ -783,14 +845,15 @@ class TestingController extends BaseController
$results = $query->getResultArray() ?? []; $results = $query->getResultArray() ?? [];
$files = array_map(function($item) { $files = array_map(function ($item) {
return trim($item['client_logo']); return trim($item['client_logo']);
}, $results); }, $results);
return $files; return $files;
} }
public function update_client_logo_files(){ public function update_client_logo_files()
{
$db = \Config\Database::connect(); $db = \Config\Database::connect();
@ -803,9 +866,63 @@ class TestingController extends BaseController
$query = $db->query($sql); $query = $db->query($sql);
return $db->affectedRows() > 0; return $db->affectedRows() > 0;
} }
public function createDefaultMailTempalteInDB()
{
$postDB = \Config\Database::connect(); // target DB
$preDB = \Config\Database::connect('preDB'); // source DB
// Templates to copy
$templateNames = [
'member_welcome_mail',
'member_reminder_mail',
'member_review_and_summary_mail'
];
foreach ($templateNames as $template) {
$exists = $postDB->table('notifications')
->where('client_id', NULL)
->where('template_name', $template)
->countAllResults();
if ($exists > 0) {
continue; // Skip if already inserted
}
// Fetch template from preDB
$templateData = $preDB->table('notifications')
->where('client_id', NULL)
->where('template_name', $template)
->get()
->getRowArray();
if (!empty($templateData)) {
// Remove ID to avoid duplicate primary key issues
unset($templateData['id']);
// Set created_by and timestamps if needed
$templateData['client_id'] = NULL;
$templateData['created_by'] = 1;
$templateData['cretaed_at'] = date('Y-m-d H:i:s');
$templateData['updated_by'] = NULL;
$templateData['updated_at'] = NULL;
// Insert into postDB
$postDB->table('notifications')->insert($templateData);
}
}
return $this->response->setJSON(['message'=>"Created Default Mail Tempalte In DB "])->setStatusCode(200);
}
} }

View File

@ -62,7 +62,7 @@ class UserController extends AdminController
// echo '<pre>'; // echo '<pre>';
// print_r($data); die; // print_r($data); die;
$data['roleData'] = $this->roleModel->select('id, role')->findAll(); $data['roleData'] = $this->roleModel->select('id, role')->findAll();
$data['teamData'] = $this->teamModel->select('id, name')->findAll(); $data['teamData'] = $this->teamModel->select('id, name')->where('is_active',1)->findAll();
$this->loadLayout('UserList', $data); $this->loadLayout('UserList', $data);
} }
@ -156,9 +156,11 @@ class UserController extends AdminController
public function edit() public function edit()
{ {
// echo ":/ in 159";
if (!$this->request->getPost()) { if (!$this->request->getPost()) {
return redirect()->to(base_url('/user/list')); return redirect()->to(base_url('/user/list'));
} else { } else {
// echo ":/ in 163";
$id = $this->request->getPost('PrimaryKey'); $id = $this->request->getPost('PrimaryKey');
$teams = $this->request->getPost('team'); $teams = $this->request->getPost('team');
$userData = $this->request->getPost(); $userData = $this->request->getPost();
@ -166,6 +168,7 @@ class UserController extends AdminController
unset($userData['PrimaryKey']); unset($userData['PrimaryKey']);
$existingData = $this->userModel->where('id',$id)->first();; $existingData = $this->userModel->where('id',$id)->first();;
// dd($existingData);die;
// Update data in the 'users' table based on the $id // Update data in the 'users' table based on the $id
$userData['updated_by'] = get_session_userid(); $userData['updated_by'] = get_session_userid();
@ -776,32 +779,63 @@ class UserController extends AdminController
} }
} }
// public function downloadIncentivesFile($file_id)
// {
// try {
// $result = $this->partnerManagerIncentiveFileModel->where('id', $file_id)->first();
// if (!$result || empty($result['incentive_file_name'])) {
// throw new \Exception("File Name Not Found");
// }
// $incentive_file_name = $result['incentive_file_name'];
// $file_name = basename($incentive_file_name);
// $filePath = WRITEPATH . 'uploads/incentives/' . $file_name;
// if (file_exists($filePath)) {
// return $this->response->download($filePath, null);
// } else {
// throw new \Exception("File Not Found");
// }
// } catch (\Exception $e) {
// $this->myLogger->logme('error', $e->getMessage());
// // Show 404 error view
// $data['message'] = $e->getMessage();
// return view('errors/404', $data);
// }
// }
public function downloadIncentivesFile($file_id) public function downloadIncentivesFile($file_id)
{ {
try { try {
$result = $this->partnerManagerIncentiveFileModel->where('id', $file_id)->first(); $result = $this->partnerManagerIncentiveFileModel->where('id', $file_id)->first();
if (!$result || empty($result['incentive_file_name'])) { if (!$result || empty($result['incentive_file_name'])) {
throw new \Exception("File Name Not Found"); throw new \Exception("File Name Not Found for ID {$file_id}");
} }
$incentive_file_name = $result['incentive_file_name']; $incentive_file_name = $result['incentive_file_name'];
$file_name = basename($incentive_file_name); $file_name = basename($incentive_file_name);
$filePath = WRITEPATH . 'uploads/incentives/' . $file_name; $filePath = WRITEPATH . 'uploads/incentives/' . $file_name;
if (file_exists($filePath)) { if (!file_exists($filePath)) {
return $this->response->download($filePath, null); throw new \Exception("File Not Found: {$file_name}");
} else {
throw new \Exception("File Not Found");
} }
} catch (\Exception $e) { return $this->response->download($filePath, null);
} catch (\Throwable $e) {
// Catch all kinds of exceptions
$this->myLogger->logme('error', $e->getMessage()); $this->myLogger->logme('error', $e->getMessage());
// Show 404 error view // Return proper 404 for missing file, else 500 for unexpected error
$data['message'] = $e->getMessage(); if (str_contains($e->getMessage(), 'Not Found')) {
return view('errors/404', $data); return $this->response->setStatusCode(404)->setBody($e->getMessage());
}
return $this->response->setStatusCode(500)->setBody('Internal Server Error');
} }
} }

View File

@ -109,7 +109,8 @@ if (!function_exists('check_relationship')) {
$family_floaters = isset($policy_terms['family_floaters']); $family_floaters = isset($policy_terms['family_floaters']);
if ($family_floaters) { if ($family_floaters) {
if (isset($relationship[$col]) && $relationship[$col]['gender'] != $row[4]) { $relation_gender = normalizeGender($row[4]);
if (isset($relationship[$col]) && $relationship[$col]['gender'] != $relation_gender) {
$error = "Gender relationship conflict: Expected " . $relationship[$col]['gender'] . ", received $row[4]"; $error = "Gender relationship conflict: Expected " . $relationship[$col]['gender'] . ", received $row[4]";
return array('status' => false, 'error' => $error); return array('status' => false, 'error' => $error);
} }
@ -369,13 +370,24 @@ if (!function_exists('check_dob_diff')) {
} }
if (!function_exists('data_group_by_family')) { if (!function_exists('data_group_by_family')) {
function data_group_by_family($emp_data, $data_source = 'excel', $action = '') function data_group_by_family($emp_data, $data_source = 'excel', $action = '', $current_column_action = null)
{ {
$result = []; $result = [];
// Kint::dump($emp_data); // Kint::dump($emp_data);
foreach ($emp_data as $rkey => $row) { foreach ($emp_data as $rkey => $row) {
if ($data_source == 'excel') { if ($data_source == 'excel') {
if (!check_row_is_empty_or_null($row)) { if (!check_row_is_empty_or_null($row)) {
// for this condition to avoid 5,00,000 to 500000
if($current_column_action == 'SI'){
$row[3] = removeNumberFormatting($row[3]);
}else if(in_array($current_column_action, ['I','DA', 'MI', 'A'])){
$row[6] = removeNumberFormatting($row[6]);
}
if ($action == 'enrollment') //if action is enrollment transform current row into inception row, becoz we treat enrollment as inception if ($action == 'enrollment') //if action is enrollment transform current row into inception row, becoz we treat enrollment as inception
{ {
$row = transform_enrollment_row_to_inception_row($row); $row = transform_enrollment_row_to_inception_row($row);
@ -637,12 +649,19 @@ if (!function_exists('check_dependent_conflict')) {
if (!function_exists('generate_relationship_code')) { if (!function_exists('generate_relationship_code')) {
function generate_relationship_code($arr) function generate_relationship_code($arr)
{ {
$gender = ['M' => 1, 'F' => 2]; $gender = [
'M' => 1,
'Male' => 1,
'male' => 1,
'F' => 2,
'Female' => 2,
'female' => 2,
];
$relationship = ['self' => 1, 'spouse' => 2, 'son' => 3, 'daughter' => 4, 'father' => 5, 'mother' => 6, 'father-in-law' => 7, 'mother-in-law' => 8]; $relationship = ['self' => 1, 'spouse' => 2, 'son' => 3, 'daughter' => 4, 'father' => 5, 'mother' => 6, 'father-in-law' => 7, 'mother-in-law' => 8];
$slug = \Config\Services::slug(); $slug = \Config\Services::slug();
$relationship_code = $slug->slugify($arr['relationship']); $relationship_code = $slug->slugify($arr['relationship']);
$emp_type_code = ($relationship_code == 'self' ? 'EMP_TYP_01' : 'EMP_TYP_03'); $emp_type_code = ($relationship_code == 'self' ? 'EMP_TYP_01' : 'EMP_TYP_03');
$relationship_code = $gender[trim($arr['gender'])] . $relationship[trim($relationship_code)]; $relationship_code = $gender[trim($arr['gender'])] ?? "" . $relationship[trim($relationship_code)] ?? "";
return ['relationship_code' => $relationship_code, 'emp_type_code' => $emp_type_code]; return ['relationship_code' => $relationship_code, 'emp_type_code' => $emp_type_code];
} }
} }
@ -1627,21 +1646,53 @@ if (!function_exists('check_dup_mobileno')) {
} }
} }
// if (!function_exists('check_dup_email')) {
// function check_dup_email(array $row, array $existing_mobilenos)
// {
// is_valid_or_empty_email($row['13']);
// if(!empty($row['13'])){
// foreach ($existing_mobilenos as $k => $value) {
// if (strtolower($row['5']) == 'self' && $row['13'] == $value['email_corporate']) {
// return array('status' => false, 'error' => "Duplicate Email");
// // break;
// }
// }
// }
// return array('status' => true);
// }
// }
if (!function_exists('check_dup_email')) { if (!function_exists('check_dup_email')) {
function check_dup_email(array $row, array $existing_mobilenos) function check_dup_email(array $row, array $existing_mobilenos)
{ {
if(!empty($row['13'])){ $errorMessages = [];
foreach ($existing_mobilenos as $k => $value) {
if (strtolower($row['5']) == 'self' && $row['13'] == $value['email_corporate']) { // Validate email
return array('status' => false, 'error' => "Duplicate Email"); $emailCheck = is_valid_or_empty_email($row['13'] ?? "");
// break; if (!$emailCheck) {
$errorMessages[] = 'Invalid email format';
}
// Check duplicate only if email is not empty
if (!empty($row['13'])) {
foreach ($existing_mobilenos as $value) {
if (strtolower(trim($row['5'])) === 'self' && trim($row['13']) === trim($value['email_corporate'])) {
$errorMessages[] = 'Duplicate Email';
break;
} }
} }
} }
return array('status' => true);
// Prepare final return
if (!empty($errorMessages)) {
return ['status' => false, 'error' => implode(' & ', $errorMessages)];
}
return ['status' => true, 'error' => ''];
} }
} }
if (!function_exists('generate_family_relationship_array')) { if (!function_exists('generate_family_relationship_array')) {
function generate_family_relationship_array($family_structure_from_policy_terms) function generate_family_relationship_array($family_structure_from_policy_terms)
{ {
@ -2041,6 +2092,22 @@ if (!function_exists('formatIndianCurrency')) {
} }
} }
if (!function_exists('normalizeGender')) {
function normalizeGender($gender)
{
$gender = strtoupper(trim($gender));
if (in_array($gender, ['M', 'MALE'])) {
return 'M';
} elseif (in_array($gender, ['F', 'FEMALE'])) {
return 'F';
}
// Optional: return null or original if not recognized
return null;
}
}
// ------------- FUNCTION FOR LEAD MEMBER DATA LIST VALIDATIONS -------------------------------------- // ------------- FUNCTION FOR LEAD MEMBER DATA LIST VALIDATIONS --------------------------------------
if (!function_exists('check_columns_name_exist')) { if (!function_exists('check_columns_name_exist')) {
@ -2291,8 +2358,8 @@ if (!function_exists('validateFamily')) {
// Validation 3: Validate spouse gender if spouse exists // Validation 3: Validate spouse gender if spouse exists
if ($spouseMember !== null) { if ($spouseMember !== null) {
$selfGender = strtoupper(trim($selfMember[4])); // Gender field $selfGender = normalizeGender(trim($selfMember[4])); // Gender field
$spouseGender = strtoupper(trim($spouseMember[4])); $spouseGender = normalizeGender(trim($spouseMember[4]));
$selfName = $selfMember[2]; // Name field $selfName = $selfMember[2]; // Name field
$spouseName = $spouseMember[2]; $spouseName = $spouseMember[2];
@ -2368,3 +2435,24 @@ if (!function_exists('check_age_validation')) {
// ------------- END OF LEAD MEMBER DATA LIST VALIDATIONS -------------------------------------- // ------------- END OF LEAD MEMBER DATA LIST VALIDATIONS --------------------------------------
if (!function_exists('is_valid_or_empty_email')) {
function is_valid_or_empty_email($email)
{
// If empty or null → return success
if (empty($email) && $email != 0) {
// return ['status' => true, 'error' => 'Value is empty'];
return true;
}
// If valid email → return success
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// return ['status' => true, 'error' => 'Valid email format'];
return true;
}
// If invalid email → return failure
// return ['status' => false, 'error' => 'Invalid email format'];
return false;
}
}

View File

@ -57,6 +57,13 @@ class sendMailNotification
$mail_content = str_replace(["[[app_link]]", "{{app_link}}"], "<a href='$app_link'>Review Details</a>", $mail_content); $mail_content = str_replace(["[[app_link]]", "{{app_link}}"], "<a href='$app_link'>Review Details</a>", $mail_content);
if ($dataToInsert['relationship'] == 'Self' && $mail != null || $mail != '') { if ($dataToInsert['relationship'] == 'Self' && $mail != null || $mail != '') {
$mail_content = preg_replace('/<p[^>]*>(&nbsp;|\s)*<\/p>/i', '', $mail_content);
$data['params'] = $params;$data['client_logo'] = $client_logo;
$data['mail_content'] = $mail_content;
$mail_content = view('mail_template', $data);
$wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content,'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to'], 'attachments' => $attachments, 'common' => $common]; $wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content,'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to'], 'attachments' => $attachments, 'common' => $common];
} }
@ -89,6 +96,12 @@ class sendMailNotification
$mail_content = str_replace(["[[member_mobile]]", "{{member_mobile}}"], $employee_mobile_no, $mail_content); $mail_content = str_replace(["[[member_mobile]]", "{{member_mobile}}"], $employee_mobile_no, $mail_content);
$mail = $emp_data['email_corporate']; $mail = $emp_data['email_corporate'];
$mail_content = preg_replace('/<p[^>]*>(&nbsp;|\s)*<\/p>/i', '', $mail_content);
$data['params'] = $params;$data['client_logo'] = $client_logo;
$data['mail_content'] = $mail_content;
$mail_content = view('mail_template', $data);
$wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content, 'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to'], 'common' => $common]; $wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content, 'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to'], 'common' => $common];
return $wholeData; return $wholeData;
@ -139,6 +152,13 @@ class sendMailNotification
$mail_content = str_replace(["[[ecard_download_link]]", "{{ecard_download_link}}"], "<a href='$link/1'>Download Insurance Card</a>", $mail_content); $mail_content = str_replace(["[[ecard_download_link]]", "{{ecard_download_link}}"], "<a href='$link/1'>Download Insurance Card</a>", $mail_content);
$mail_content = str_replace(["[[client_name]]", "{{client_name}}"], $client_data['client_name'], $mail_content); $mail_content = str_replace(["[[client_name]]", "{{client_name}}"], $client_data['client_name'], $mail_content);
$mail_content = preg_replace('/<p[^>]*>(&nbsp;|\s)*<\/p>/i', '', $mail_content);
$data['params'] = $params;$data['client_logo'] = $client_logo;
$data['mail_content'] = $mail_content;
$mail_content = view('mail_template', $data);
$wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content,'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to'], 'common' => $common]; $wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content,'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to'], 'common' => $common];
return $wholeData; return $wholeData;
@ -523,6 +543,13 @@ class sendMailNotification
$mail_content = str_replace(["[[member_mobile]]", "{{member_mobile}}"], $employee_mobile_no, $mail_content); $mail_content = str_replace(["[[member_mobile]]", "{{member_mobile}}"], $employee_mobile_no, $mail_content);
$mail_content = str_replace(["[[member_summary]]", "{{member_summary}}"], $table_content , $mail_content); $mail_content = str_replace(["[[member_summary]]", "{{member_summary}}"], $table_content , $mail_content);
$mail_content = preg_replace('/<p[^>]*>(&nbsp;|\s)*<\/p>/i', '', $mail_content);
$data['params'] = $params;$data['client_logo'] = $client_logo;
$data['mail_content'] = $mail_content;
$mail_content = view('mail_template', $data);
// print_r($mail_content); die; // print_r($mail_content); die;
// $mail = "aadhavanvalli@gmail.com"; // $mail = "aadhavanvalli@gmail.com";
@ -825,6 +852,13 @@ class sendMailNotification
$full_name = $value['first_name'] .' ' .$value['last_name']; $full_name = $value['first_name'] .' ' .$value['last_name'];
$mail_content = str_replace(["[[member_name]]", "{{member_name}}"], $full_name , $mail_content); $mail_content = str_replace(["[[member_name]]", "{{member_name}}"], $full_name , $mail_content);
$mail_content = preg_replace('/<p[^>]*>(&nbsp;|\s)*<\/p>/i', '', $mail_content);
$data['params'] = $params;$data['client_logo'] = $client_logo;
$data['mail_content'] = $mail_content;
$mail_content = view('mail_template', $data);
$wholeData[] = ['mail' => $value['email'], 'subject' => $subject,'message'=> $mail_content, 'reply_to' => $client_data['reply_to'], 'common' => $common]; $wholeData[] = ['mail' => $value['email'], 'subject' => $subject,'message'=> $mail_content, 'reply_to' => $client_data['reply_to'], 'common' => $common];
// $wholeData[] = ['mail' => $value['email'], 'subject' => $subject,'message'=> $mail_content, 'bcc'=> $client_data['common_mails'}}; // $wholeData[] = ['mail' => $value['email'], 'subject' => $subject,'message'=> $mail_content, 'bcc'=> $client_data['common_mails'}};
} }
@ -1118,6 +1152,11 @@ class sendMailNotification
$mail_content = str_replace(["[[member_summary]]", "{{member_summary}}"], $table_content , $mail_content); $mail_content = str_replace(["[[member_summary]]", "{{member_summary}}"], $table_content , $mail_content);
$mail_content = preg_replace('/<p[^>]*>(&nbsp;|\s)*<\/p>/i', '', $mail_content);
$data['params'] = $params;$data['client_logo'] = $client_logo;
$data['mail_content'] = $mail_content;
$mail_content = view('mail_template', $data);
$hr_mails = $client_data['hr_mails']; $hr_mails = $client_data['hr_mails'];
$mail_array = explode(',', $hr_mails); $mail_array = explode(',', $hr_mails);
@ -1182,7 +1221,14 @@ class sendMailNotification
$mail_content = str_replace(["[[app_link]]", "{{app_link}}"], "<a href='$app_link'>Review Details</a>", $mail_content); $mail_content = str_replace(["[[app_link]]", "{{app_link}}"], "<a href='$app_link'>Review Details</a>", $mail_content);
if ($mail != null || $mail != '') { if ( isset($mail) && !empty($mail) ) {
$mail_content = preg_replace('/<p[^>]*>(&nbsp;|\s)*<\/p>/i', '', $mail_content);
$data['params'] = $params;$data['client_logo'] = $client_logo;
$data['mail_content'] = $mail_content;
$mail_content = view('mail_template', $data);
$wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content,'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to'], 'attachments' => $attachments]; $wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content,'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to'], 'attachments' => $attachments];
} }
@ -1215,6 +1261,13 @@ class sendMailNotification
if ((isset($notification_data) && $notification_data['enabled'] == 1)) { if ((isset($notification_data) && $notification_data['enabled'] == 1)) {
if (isset($mail) && !empty($mail)) { if (isset($mail) && !empty($mail)) {
$mail_content = preg_replace('/<p[^>]*>(&nbsp;|\s)*<\/p>/i', '', $mail_content);
$data['params'] = $params;$data['client_logo'] = $client_logo;
$data['mail_content'] = $mail_content;
$mail_content = view('mail_template', $data);
$wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content, 'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to']]; $wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content, 'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to']];
} }
@ -1268,6 +1321,12 @@ class sendMailNotification
$mail_content = str_replace(["[[ecard_download_link]]", "{{ecard_download_link}}"], "<a href='$link/1'>Download Insurance Card</a>", $mail_content); $mail_content = str_replace(["[[ecard_download_link]]", "{{ecard_download_link}}"], "<a href='$link/1'>Download Insurance Card</a>", $mail_content);
$mail_content = str_replace(["[[client_name]]", "{{client_name}}"], $client_data['client_name'], $mail_content); $mail_content = str_replace(["[[client_name]]", "{{client_name}}"], $client_data['client_name'], $mail_content);
$mail_content = preg_replace('/<p[^>]*>(&nbsp;|\s)*<\/p>/i', '', $mail_content);
$data['params'] = $params;$data['client_logo'] = $client_logo;
$data['mail_content'] = $mail_content;
$mail_content = view('mail_template', $data);
$wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content,'bcc'=> $client_data['common_mails'],'attachments' => $attachments, 'reply_to' => $client_data['reply_to']]; $wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content,'bcc'=> $client_data['common_mails'],'attachments' => $attachments, 'reply_to' => $client_data['reply_to']];
return $wholeData; return $wholeData;
@ -1419,6 +1478,11 @@ class sendMailNotification
$mail_content = str_replace(["[[member_mobile]]", "{{member_mobile}}"], $mobile, $mail_content); $mail_content = str_replace(["[[member_mobile]]", "{{member_mobile}}"], $mobile, $mail_content);
$mail_content = str_replace(["[[member_summary]]", "{{member_summary}}"], $table_content , $mail_content); $mail_content = str_replace(["[[member_summary]]", "{{member_summary}}"], $table_content , $mail_content);
$mail_content = preg_replace('/<p[^>]*>(&nbsp;|\s)*<\/p>/i', '', $mail_content);
$data['params'] = $params;$data['client_logo'] = $client_logo;
$data['mail_content'] = $mail_content;
$mail_content = view('mail_template', $data);
$wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content, 'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to']]; $wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content, 'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to']];
@ -1568,6 +1632,13 @@ class sendMailNotification
$mail_content = str_replace(["[[member_name]]", "{{member_name}}"], $name . ' (' . $emp_code . ')' , $mail_content); $mail_content = str_replace(["[[member_name]]", "{{member_name}}"], $name . ' (' . $emp_code . ')' , $mail_content);
$mail_content = str_replace(["[[member_summary]]", "{{member_summary}}"], $table_content , $mail_content); $mail_content = str_replace(["[[member_summary]]", "{{member_summary}}"], $table_content , $mail_content);
$mail_content = preg_replace('/<p[^>]*>(&nbsp;|\s)*<\/p>/i', '', $mail_content);
$data['params'] = $params;$data['client_logo'] = $client_logo;
$data['mail_content'] = $mail_content;
$mail_content = view('mail_template', $data);
$wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content, 'reply_to' => $client_data['reply_to']]; $wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content, 'reply_to' => $client_data['reply_to']];
return $wholeData; return $wholeData;
@ -1717,6 +1788,11 @@ class sendMailNotification
$mail_content = str_replace(["[[member_name]]", "{{member_name}}"], $name . ' (' . $emp_code . ')' , $mail_content); $mail_content = str_replace(["[[member_name]]", "{{member_name}}"], $name . ' (' . $emp_code . ')' , $mail_content);
$mail_content = str_replace(["[[member_summary]]", "{{member_summary}}"], $table_content , $mail_content); $mail_content = str_replace(["[[member_summary]]", "{{member_summary}}"], $table_content , $mail_content);
$mail_content = preg_replace('/<p[^>]*>(&nbsp;|\s)*<\/p>/i', '', $mail_content);
$data['params'] = $params;$data['client_logo'] = $client_logo;
$data['mail_content'] = $mail_content;
$mail_content = view('mail_template', $data);
$wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content, 'reply_to' => $client_data['reply_to']]; $wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content, 'reply_to' => $client_data['reply_to']];

View File

@ -65,6 +65,19 @@ if (!function_exists('file_Upload')) {
} }
} }
if (!function_exists('file_Upload_for_lead')) {
function file_Upload_for_lead($fileToUpload, $filepath)
{
if ($fileToUpload !== null && $fileToUpload->isValid() && !$fileToUpload->hasMoved()) {
$fileToUpload->move($filepath);
$fileName = $fileToUpload->getName();
return $fileName;
} else {
return "";
}
}
}
// if (!function_exists('multi_file_Upload')) { // if (!function_exists('multi_file_Upload')) {
// function multi_file_Upload($fileToUpload, $filepath) // function multi_file_Upload($fileToUpload, $filepath)
// { // {
@ -866,3 +879,22 @@ if (!function_exists('getFileIfExists')) {
return file_exists(FCPATH . $path) ? base_url($path) : ''; return file_exists(FCPATH . $path) ? base_url($path) : '';
} }
} }
if (!function_exists('removeNumberFormatting')) {
function removeNumberFormatting($number)
{
return (float) str_replace(',', '', trim($number));
}
}
if (!function_exists('formatKey')) {
function formatKey($key, $len = 3)
{
$words = explode('_', $key);
$formatted = array_map(function ($word) use ($len) {
return strlen($word) < $len ? strtoupper($word) : ucfirst(strtolower($word));
}, $words);
return implode(' ', $formatted);
}
}

View File

@ -56,6 +56,7 @@ class ClientPolicyModel extends Model
"is_lgbtq", "is_lgbtq",
"placement_json", "placement_json",
"policy_entry_from", "policy_entry_from",
"is_from_lead",
]; ];
// Callbacks // Callbacks
@ -430,8 +431,8 @@ class ClientPolicyModel extends Model
$emp_count = $this->db->affectedRows(); $emp_count = $this->db->affectedRows();
// Log the result // Log the result
log_message('info', "Client policies updated: {$client_count}"); log_message('error', "Client policies updated: {$client_count}");
log_message('info', "Employee policies updated: {$emp_count}"); log_message('error', "Employee policies updated: {$emp_count}");
return ['client' => $client_count, 'emp' => $emp_count]; return ['client' => $client_count, 'emp' => $emp_count];
} }

View File

@ -611,6 +611,36 @@ class EmployeePolicyModel extends Model
$subquery_endorsement_condition = "{$insurer_or_tpa}" === 'tpa' ? "WHERE (endorsement_id IS NOT NULL OR endorsement_id != '')" : "WHERE (endorsement_id IS NULL OR endorsement_id = '')"; $subquery_endorsement_condition = "{$insurer_or_tpa}" === 'tpa' ? "WHERE (endorsement_id IS NOT NULL OR endorsement_id != '')" : "WHERE (endorsement_id IS NULL OR endorsement_id = '')";
/*
ROUND(sidata.new_si_premium - sidata.old_si_premium, 2) AS difference_premium,
ROUND(
(sidata.new_si_premium - sidata.old_si_premium) *
(DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365,
2
) AS pro_rata_premium,
ROUND(
(
(sidata.new_si_premium - sidata.old_si_premium) *
(DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365
) * 0.18,
2
) AS gst,
ROUND(
(
(sidata.new_si_premium - sidata.old_si_premium) *
(DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365
) +
ROUND(
(
(sidata.new_si_premium - sidata.old_si_premium) *
(DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365
) * 0.18,
2
),
2
) AS total
*/
$query = $this->db->query(" $query = $this->db->query("
SELECT SELECT
a.id AS endorsement_primarykey, a.id AS endorsement_primarykey,
@ -643,33 +673,40 @@ class EmployeePolicyModel extends Model
sidata.old_si_premium, sidata.old_si_premium,
sidata.date_of_coverage, sidata.date_of_coverage,
DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1 AS no_of_days, DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1 AS no_of_days,
ROUND(sidata.new_si_premium - sidata.old_si_premium, 2) AS difference_premium,
ROUND(ABS(sidata.new_si_premium - sidata.old_si_premium), 2) AS difference_premium,
ROUND( ROUND(
ABS(
(sidata.new_si_premium - sidata.old_si_premium) * (sidata.new_si_premium - sidata.old_si_premium) *
(DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365, (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365
),
2 2
) AS pro_rata_premium, ) AS pro_rata_premium,
ROUND( ROUND(
ABS(
( (
(sidata.new_si_premium - sidata.old_si_premium) * (sidata.new_si_premium - sidata.old_si_premium) *
(DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365 (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365
) * 0.18, ) * 0.18
),
2 2
) AS gst, ) AS gst,
ROUND( ROUND(
ABS(
( (
(sidata.new_si_premium - sidata.old_si_premium) * (sidata.new_si_premium - sidata.old_si_premium) *
(DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365 (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365
) + ) +
ROUND( (
( (
(sidata.new_si_premium - sidata.old_si_premium) * (sidata.new_si_premium - sidata.old_si_premium) *
(DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365 (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365
) * 0.18, ) * 0.18
2 )
), ),
2 2
) AS total ) AS total
FROM FROM
emp_endorsement a emp_endorsement a
LEFT JOIN employees ON employees.emp_code = a.emp_code LEFT JOIN employees ON employees.emp_code = a.emp_code

View File

@ -22,6 +22,7 @@ class FileModel extends Model
"uploaded_by", "uploaded_by",
"updated_by", "updated_by",
"hr_file_id", "hr_file_id",
"is_comparison_skipped",
]; ];

View File

@ -27,7 +27,7 @@ class InsurerBranchModel extends Model
public function getInsurerBranchesWithInsurerNames() public function getInsurerBranchesWithInsurerNames()
{ {
$query = $this->select('insurer_branch.*, I.short_name as insurer_name') $query = $this->select('insurer_branch.*, I.short_name as insurer_name, I.category')
->join('insurers I', 'insurer_branch.insurer_id = I.id', 'left') ->join('insurers I', 'insurer_branch.insurer_id = I.id', 'left')
->find(); ->find();
return $query; return $query;

View File

@ -106,6 +106,7 @@ class LeadsModel extends Model
'is_insurer_auto_mail', 'is_insurer_auto_mail',
'quote_received_insurer', 'quote_received_insurer',
'acm_id', 'acm_id',
'policy_with_correction',
]; ];
@ -204,78 +205,151 @@ class LeadsModel extends Model
return $result; return $result;
} }
// public function getDashData()
// {
// $statuses = $this->db->table('leads')
// ->select('status, policy_with_correction')
// ->where("is_active", 1)
// ->groupBy('status')
// ->get()
// ->getResultArray();
// $policy_with_correction_count = $this->db->table('leads')
// ->where('is_active', 1)
// ->where('policy_with_correction', 1)
// ->countAllResults();
// $selectParts = [];
// foreach ($statuses as $status) {
// $s = $status['status'];
// $alias = strtolower(str_replace(' ', '_', $s));
// // Count alias
// $selectParts[] = "SUM(CASE WHEN status = '{$s}' THEN 1 ELSE 0 END) AS `{$alias}`";
// // IDs alias
// $selectParts[] = "GROUP_CONCAT(CASE WHEN status = '{$s}' THEN leads.id ELSE NULL END) AS `{$alias}_ids`";
// }
// $select = implode(", ", $selectParts);
// // Start query builder
// $builder = $this->db->table('leads');
// $builder->select($select);
// // Auditing subquery
// $subquery = "(SELECT pk, MAX(created_at) AS last_claim_status_change
// FROM auditing_history
// WHERE table_name = 'leads' AND field_name = 'status'
// GROUP BY pk)";
// $builder->join("{$subquery} AS th", 'leads.id = th.pk', 'left');
// // Date filtering for last status change
// $dateLimit = 3;
// $dateThreshold = date('Y-m-d H:i:s', strtotime("-{$dateLimit} days"));
// $builder->groupStart()
// ->where('th.last_claim_status_change <=', $dateThreshold)
// ->orWhere('th.last_claim_status_change IS NULL')
// ->groupEnd();
// // Add only active
// $builder->where("leads.is_active", 1);
// $lead_data = $builder->get()->getResultArray();
// // dd($this->db->getLastQuery());
// // Fallback for empty results
// if (empty($lead_data)) {
// $lead_data[0] = ['total' => 0];
// foreach ($statuses as $status) {
// $alias = strtolower(str_replace(' ', '_', $status['status']));
// $lead_data[0][$alias] = 0;
// $lead_data[0]["{$alias}_ids"] = '';
// }
// }
// // Calculate total
// $total = 0;
// foreach ($lead_data[0] as $key => $value) {
// // if (!str_ends_with($key, '_ids') && $key != "won") {
// // $total += (int) $value;
// // }
// if (!str_ends_with($key, '_ids')) {
// $total += (int) $value;
// }
// }
// $total = $total + $policy_with_correction_count ?? 0;
// $lead_data[0]['total'] = $total;
// $lead_data[0]['policy_with_correction'] = $policy_with_correction_count;
// // dd($lead_data[0]);
// return $lead_data[0];
// }
public function getDashData() public function getDashData()
{ {
// Get all unique statuses
$statuses = $this->db->table('leads') $statuses = $this->db->table('leads')
->select('status') ->select('DISTINCT(status)')
->where("is_active", 1) ->where('is_active', 1)
->groupBy('status')
->get() ->get()
->getResultArray(); ->getResultArray();
$policy_with_correction_data = $this->db->table('leads')
->select('COUNT(id) AS count, GROUP_CONCAT(id) AS ids')
->where('is_active', 1)
->where('policy_with_correction', 1)
->get()
->getRowArray();
if (empty($statuses)) {
return ['total' => 0];
}
// Build dynamic select fields for each status
$selectParts = []; $selectParts = [];
foreach ($statuses as $row) {
$status = $row['status'];
$alias = strtolower(str_replace(' ', '_', $status));
foreach ($statuses as $status) { $selectParts[] = "SUM(CASE WHEN status = '{$status}' THEN 1 ELSE 0 END) AS `{$alias}`";
$s = $status['status']; $selectParts[] = "GROUP_CONCAT(CASE WHEN status = '{$status}' THEN id END) AS `{$alias}_ids`";
$alias = strtolower(str_replace(' ', '_', $s));
// Count alias
$selectParts[] = "SUM(CASE WHEN status = '{$s}' THEN 1 ELSE 0 END) AS `{$alias}`";
// IDs alias
$selectParts[] = "GROUP_CONCAT(CASE WHEN status = '{$s}' THEN leads.id ELSE NULL END) AS `{$alias}_ids`";
} }
$select = implode(", ", $selectParts); $select = implode(", ", $selectParts);
// Start query builder // Main query
$builder = $this->db->table('leads'); $lead_data = $this->db->table('leads')
->select($select)
$builder->select($select); ->where('is_active', 1)
->get()
// Auditing subquery ->getRowArray();
$subquery = "(SELECT pk, MAX(created_at) AS last_claim_status_change
FROM auditing_history
WHERE table_name = 'leads' AND field_name = 'status'
GROUP BY pk)";
$builder->join("{$subquery} AS th", 'leads.id = th.pk', 'left');
// Date filtering for last status change
$dateLimit = 3;
$dateThreshold = date('Y-m-d H:i:s', strtotime("-{$dateLimit} days"));
$builder->groupStart()
->where('th.last_claim_status_change <=', $dateThreshold)
->orWhere('th.last_claim_status_change IS NULL')
->groupEnd();
// Add only active
$builder->where("leads.is_active", 1);
$lead_data = $builder->get()->getResultArray();
// Fallback for empty results
if (empty($lead_data)) {
$lead_data[0] = ['total' => 0];
foreach ($statuses as $status) {
$alias = strtolower(str_replace(' ', '_', $status['status']));
$lead_data[0][$alias] = 0;
$lead_data[0]["{$alias}_ids"] = '';
}
}
// Calculate total // Calculate total
$total = 0; $total = 0;
foreach ($lead_data[0] as $key => $value) { foreach ($lead_data as $key => $val) {
if (!str_ends_with($key, '_ids') && $key != "won") { if (!str_ends_with($key, '_ids')) {
$total += (int) $value; $total += (int) $val;
} }
} }
$lead_data[0]['total'] = $total;
// dd($lead_data[0]); $lead_data['total'] = $total;
return $lead_data[0]; $lead_data['policy_with_correction'] = $policy_with_correction_data['count'] ?? 0;
$lead_data['policy_with_correction_ids'] = $policy_with_correction_data['ids'] ?? null;
// dd($lead_data);
return $lead_data;
} }
} }

View File

@ -1,11 +1,11 @@
<?php <?php
namespace App\Models; namespace App\Models;
use CodeIgniter\Model; use CodeIgniter\Model;
class PolicyTransactionModel extends Model class PolicyTransactionModel extends Model
{ {
protected $table = 'policy_transaction'; protected $table = 'policy_transaction';
protected $primaryKey = 'id'; protected $primaryKey = 'id';
protected $useAutoIncrement = true; protected $useAutoIncrement = true;
@ -1829,24 +1829,35 @@ class PolicyTransactionModel extends Model
// ============================== // ==============================
if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) { if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) {
$date_condition = " $date_condition = "
AND insurer_statements.month >= '{$start_date}' AND insurer_statements_oq.month >= '{$start_date}'
AND insurer_statements.month <= '{$end_date}' AND insurer_statements_oq.month <= '{$end_date}'
"; ";
} }
// ============================== // ==============================
// BASE QUERY // BASE QUERY
// ============================== // ==============================
$builder = $this->db->table('policy_transaction')
// ==============================
// Without Statement Upload
// ==============================
$builder2 = $this->db->table('policy_transaction')
->select(" ->select("
policy_transaction.*, policy_transaction.id AS id,
policy_transaction.endorsement_no AS endorsement_no,
policy_transaction.ref AS ref,
DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date, DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date,
DATE_FORMAT(
IF(policy_transaction.month IS NULL, DATE_FORMAT( policy_transaction.policy_issue_date, '%b %Y') AS policy_issue_month,
policy_transaction.policy_issue_date,
policy_transaction.month CASE
), '%b %Y' WHEN 1 = 1 THEN 'no statement uploaded'
) AS policy_issue_month, ELSE 'statement uploaded'
END AS statement_uploaded ,
CASE CASE
WHEN clients.client_type = 1 THEN 'Group' WHEN clients.client_type = 1 THEN 'Group'
@ -1898,89 +1909,15 @@ class PolicyTransactionModel extends Model
-- ============================== -- ==============================
-- SUBQUERY: Total IRDA Amount -- SUBQUERY: Total IRDA Amount
-- Alias Agreed Amount ...!!
-- ============================== -- ==============================
ROUND(( ROUND(pt_co_share_details.exp_amt, 2) AS total_irda_amt,
SELECT (
SUM(co_share_stmt_details.actual_bp_brokerage_amt) +
SUM(co_share_stmt_details.actual_tp_brokerage_amt) +
SUM(co_share_stmt_details.actual_tep_brokerage_amt) +
SUM(co_share_stmt_details.reward)
)
FROM co_share_stmt_details
JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id
AND co_share_stmt_details.is_active = 1
AND insurer_statements.is_active = 1
{$date_condition}
), 2) AS total_irda_amt,
-- Reward Only -- Reward Only
ROUND(( ROUND(0, 2) AS reward,
SELECT SUM(co_share_stmt_details.reward)
FROM co_share_stmt_details
JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id
AND co_share_stmt_details.is_active = 1
AND insurer_statements.is_active = 1
{$date_condition}
), 2) AS reward,
-- Billed Amount -- Billed Amount
ROUND(( ROUND(0, 2) AS billed_amt,
SELECT SUM(
COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) +
COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) +
COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) +
COALESCE(co_share_stmt_details.reward, 0)
)
FROM co_share_stmt_details
JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id
JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id
AND co_share_stmt_details.is_active = 1
AND pt_table.is_active = 1
AND insurer_statements.is_active = 1
AND insurer_statements.invoice_status IS NOT NULL
{$date_condition}
), 2) AS billed_amt,
-- Unbilled Amount
ROUND(
(
(
SELECT
SUM(
COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) +
COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) +
COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) +
COALESCE(co_share_stmt_details.reward, 0)
)
FROM co_share_stmt_details
JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id
AND co_share_stmt_details.is_active = 1
{$date_condition}
)
-
(
SELECT
SUM(
COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) +
COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) +
COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) +
COALESCE(co_share_stmt_details.reward, 0)
)
FROM co_share_stmt_details
JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id
JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id
AND co_share_stmt_details.is_active = 1
AND pt_table.is_active = 1
AND insurer_statements.is_active = 1
AND insurer_statements.invoice_status IS NULL
{$date_condition}
)
), 2) AS unbilled_amt,
created_user.first_name AS user_name, created_user.first_name AS user_name,
@ -2013,8 +1950,254 @@ class PolicyTransactionModel extends Model
->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left') ->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left')
->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left') ->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left')
->join('user_profiles AS created_user', 'policy_transaction.created_by = created_user.id', 'left') ->join('user_profiles AS created_user', 'policy_transaction.created_by = created_user.id', 'left')
->where('policy_transaction.is_active', 1) ->where('policy_transaction.is_active', 1)
->where('pt_co_share_details.is_active', 1); ->where('pt_co_share_details.is_active', 1)
// ========================================================
// GROUP BY Insurer Statement Months
// =======================================================
->groupBy('policy_transaction.policy_no , pt_co_share_details.insurer_id ');
// ==============================
// ROLE-BASED FILTERS
// ==============================
if (
(!in_array(get_role_id(), [1, 5])) &&
!(
in_array(MANAGEMENT_TEAM_ID, user_team()) ||
in_array(FINANCE_TEAM_ID, user_team()) ||
in_array(BUSINESS_TEAM_ID, user_team())
)
) {
if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
$builder2->where('policy_transaction.created_by', get_session_userid());
}
}
// ==============================
// ADDITIONAL FILTERS
// ==============================
if (!empty($where)) {
log_message('info', 'Where condition: ' . json_encode($where));
$builder2->where($where);
}
if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') {
$startDate = date('Y-m-d 00:00:00', strtotime($start_date));
$endDate = date('Y-m-d 23:59:59', strtotime($end_date));
$builder2->where("policy_transaction.{$date_type} >=", $startDate)
->where("policy_transaction.{$date_type} <=", $endDate);
}
// ==============================
// FILTER BY IDs
// ==============================
if ($client_id != 0) $builder2->where('policy_transaction.client_id', $client_id);
if ($insurer_id != 0) $builder2->where('policy_transaction.insurer_id', $insurer_id);
if ($client_branch_id != 0) $builder2->where('policy_transaction.client_branch_id', $client_branch_id);
if ($insurer_branch_id != 0) $builder2->where('policy_transaction.insurer_branch_id', $insurer_branch_id);
if ($client_policy_id != 0) $builder2->where('policy_transaction.client_policy_id', $client_policy_id);
if ($user_id != 0) $builder2->where('policy_transaction.created_by', $user_id);
if ($policy_type_id != 0) $builder2->where('client_policy.policy_type_id', $policy_type_id);
if ($issuer != 0) $builder2->where('policy_transaction.issuer', $issuer);
// ==============================
// DEFAULT 90-DAY FILTER
// ==============================
if (
$client_id == 0 &&
$insurer_id == 0 &&
$policy_type_id == 0 &&
$date_type == 0 &&
$issuer == 0
) {
$fromDate = date('Y-m-d', strtotime('-90 days'));
$toDate = date('Y-m-d 23:59:59');
if (empty($where)) {
$builder2->where('policy_transaction.created_at >=', $fromDate)
->where('policy_transaction.created_at <=', $toDate);
}
}
// ==============================
// With Statement Upload
// ==============================
$builder = $this->db->table('policy_transaction')
->select("
policy_transaction.id AS id,
policy_transaction.endorsement_no AS endorsement_no,
policy_transaction.ref AS ref,
DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date,
DATE_FORMAT(
IF(insurer_statements_oq.month IS NULL,
policy_transaction.policy_issue_date,
insurer_statements_oq.month
), '%b %Y'
) AS policy_issue_month,
CASE
WHEN insurer_statements_oq.month IS NULL THEN 'no statement uploaded'
ELSE 'statement uploaded'
END AS statement_uploaded ,
CASE
WHEN clients.client_type = 1 THEN 'Group'
WHEN clients.client_type = 2 THEN 'Retail'
ELSE '-'
END AS client_type,
CASE
WHEN policy_transaction.revenue_type = 'NA' THEN 'Fresh'
ELSE 'Renewal'
END AS revenue_type,
CASE
WHEN policy_transaction.action_type = 'inception' THEN 'Policy'
ELSE 'Endorsement'
END AS action_type,
clients.client_name AS client_name,
clients.short_name AS client_short_name,
client_branch.branch_name AS client_branch_name,
client_branch.address1 AS client_address,
policy_type.policy_type,
policy_type.bap,
insurers.name AS insurer_name,
insurers.short_name AS insurer_short_name,
insurer_branch.branch_name AS insurer_branch_name,
insurer_branch.branch_code AS insurer_branch_code,
user_profiles.first_name AS user_name,
vehicle.vehicle_no,
tpa.name AS tpa_name,
pt_co_share_details.remark AS remarks,
pt_co_share_details.cop_amt AS bp_amt,
pt_co_share_details.exp_amt,
pt_co_share_details.id AS pt_id,
sales_user.first_name AS salse_person_name,
service_user.first_name AS service_person_name,
ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) AS premium_wo_gst,
ROUND((ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) * 18 / 100), 2) AS gst_amount,
ROUND(
ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) +
ROUND((ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) * 18 / 100), 2),
2) AS total_premium,
ROUND(pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) AS tp_or_ter,
DATEDIFF(policy_transaction.policy_end_date, CURDATE()) AS days,
(pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per) AS agreed_tp_or_ter_per,
pt_co_share_details.agreed_bp_per,
-- ==============================
-- SUBQUERY: Total IRDA Amount
-- Alias Agreed Amount ...!!
-- ==============================
ROUND(pt_co_share_details.exp_amt, 2) AS total_irda_amt,
-- Reward Only
ROUND((
SELECT SUM(co_share_stmt_details.reward)
FROM co_share_stmt_details
JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id
AND co_share_stmt_details.is_active = 1
AND insurer_statements.is_active = 1
AND insurer_statements.month = insurer_statements_oq.month
{$date_condition}
GROUP BY('policy_transaction.policy_no , insurer_statements.month , pt_co_share_details.insurer_id')
), 2) AS reward,
-- Billed Amount
ROUND((
SELECT SUM(
COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) +
COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) +
COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) +
COALESCE(co_share_stmt_details.reward, 0)
)
FROM co_share_stmt_details
JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id
JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id
AND co_share_stmt_details.is_active = 1
AND pt_table.is_active = 1
AND insurer_statements.is_active = 1
AND insurer_statements.invoice_status IS NOT NULL
AND insurer_statements.month = insurer_statements_oq.month
{$date_condition}
GROUP BY('policy_transaction.policy_no , insurer_statements.month , pt_co_share_details.insurer_id')
), 2) AS billed_amt,
created_user.first_name AS user_name,
CASE
WHEN pt_co_share_details.co_share_type IN (0, 1) THEN policy_transaction.policy_no
WHEN pt_co_share_details.co_share_type > 1 THEN
CASE
WHEN pt_co_share_details.follower_policy_no IS NULL OR pt_co_share_details.follower_policy_no = ''
THEN policy_transaction.policy_no
ELSE pt_co_share_details.follower_policy_no
END
ELSE policy_transaction.policy_no
END AS policy_no
")
// ==============================
// JOINS
// ==============================
->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
->join('clients', 'clients.id = policy_transaction.client_id')
->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left')
->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
->join('user_profiles', 'policy_transaction.created_by = user_profiles.id', 'left')
->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left')
->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
->join('insurer_branch', 'pt_co_share_details.insurer_branch_id = insurer_branch.id', 'left')
->join('tpa', 'policy_transaction.tpa_id = tpa.id', 'left')
->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left')
->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left')
->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left')
->join('user_profiles AS created_user', 'policy_transaction.created_by = created_user.id', 'left')
->join('co_share_stmt_details', 'pt_co_share_details.id = co_share_stmt_details.co_share_id','left')
->join('insurer_statements insurer_statements_oq','insurer_statements_oq.id = co_share_stmt_details.statement_id','left')
->where('policy_transaction.is_active', 1)
->where('pt_co_share_details.is_active', 1)
->where('insurer_statements_oq.id IS NOT NULL')
// ========================================================
// GROUP BY Insurer Statement Months
// =======================================================
->groupBy('policy_transaction.policy_no , pt_co_share_details.insurer_id ,insurer_statements_oq.month');
// ============================== // ==============================
// ROLE-BASED FILTERS // ROLE-BASED FILTERS
@ -2053,12 +2236,12 @@ class PolicyTransactionModel extends Model
$startDate = date('Y-m-d', strtotime($start_date)); $startDate = date('Y-m-d', strtotime($start_date));
$endDate = date('Y-m-d', strtotime($end_date)); $endDate = date('Y-m-d', strtotime($end_date));
$builder->join('co_share_stmt_details', 'pt_co_share_details.id = co_share_stmt_details.co_share_id', 'left') $builder->join('co_share_stmt_details cssdfilter', 'pt_co_share_details.id = cssdfilter.co_share_id', 'left')
->join('insurer_statements', 'co_share_stmt_details.statement_id = insurer_statements.id', 'left') ->join('insurer_statements', 'cssdfilter.statement_id = insurer_statements.id', 'left')
->where('insurer_statements.is_active', 1) ->where('insurer_statements.is_active', 1)
->where('insurer_statements.month >=', $startDate) ->where('insurer_statements.month >=', $startDate)
->where('insurer_statements.month <=', $endDate) ->where('insurer_statements.month <=', $endDate)
->groupBy('co_share_stmt_details.co_share_id'); ->groupBy('cssdfilter.co_share_id');
} }
// ============================== // ==============================
@ -2092,21 +2275,26 @@ class PolicyTransactionModel extends Model
} }
} }
// ==============================
// ORDER & EXECUTION
// ==============================
$builder->orderBy('policy_transaction.id', 'desc');
$result = $builder->get()->getResultArray();
// Uncomment if you need to debug SQL
// dd($this->db->getLastQuery());
$sql1 = $builder2->getCompiledSelect();
$sql2 = $builder->getCompiledSelect();
$finalSql = "($sql1) UNION ALL ($sql2)
ORDER BY policy_no DESC, insurer_branch_name ASC, statement_uploaded ASC,
STR_TO_DATE(policy_issue_month, '%b %Y') ASC";
$result = $this->db->query($finalSql)->getResultArray();
return $result; return $result;
} }
} }

View File

@ -342,6 +342,13 @@ table.dataTable tbody td {
</style> </style>
<?php
$session = \Config\Services::session();
$currentLogInRole = $session->get()['userData']->role;
?>
<!-- End ADD and EDIT Page HTML --> <!-- End ADD and EDIT Page HTML -->
<div class="row" id="List-page"> <div class="row" id="List-page">
@ -511,7 +518,17 @@ table.dataTable tbody td {
</label> </label>
<select class="form-control" id="role" name="role" required> <select class="form-control" id="role" name="role" required>
<option value="">Select Role</option> <option value="">Select Role</option>
<?php foreach($roleData as $value) { ?>
<?php foreach($roleData as $value) {
// $headRoleValue = $value['id']??"";
// // we are showing head role only to head's who logged in
// if($headRoleValue == "5" && $currentLogInRole != "5" ){
// continue;
// }
?>
<option value="<?= $value['id'] ?>"><?= $value['role'] ?></option> <option value="<?= $value['id'] ?>"><?= $value['role'] ?></option>
<?php } ?> <?php } ?>
</select> </select>
@ -522,7 +539,16 @@ table.dataTable tbody td {
<span class="tooltip-trigger mdi mdi-information-outline" id="accessMatrixTrigger"></span> <span class="tooltip-trigger mdi mdi-information-outline" id="accessMatrixTrigger"></span>
</label> </label>
<select hidden class="form-control" id="team" name="team[]" multiple required> <select hidden class="form-control" id="team" name="team[]" multiple required>
<?php foreach($teamData as $value) { ?> <?php foreach($teamData as $value) {
$teamValue = $value['id']??"";
// we are showing head role only to head's who logged in
if( ($teamValue == "4" || $teamValue =="6" ) && $currentLogInRole != "5" ){
continue;
}
?>
<option value="<?= $value['id'] ?>"><?= $value['name'] ?></option> <option value="<?= $value['id'] ?>"><?= $value['name'] ?></option>
<?php } ?> <?php } ?>
</select> </select>
@ -673,6 +699,33 @@ table.dataTable tbody td {
<td>BDS - All access</td> <td>BDS - All access</td>
<td>All access</td> <td>All access</td>
</tr> </tr>
<tr>
<td class="team-cell" rowspan="6">Accounts</td>
<td>BDS - Policy Transaction</td>
<td>Policy | Endorsement | Statement Upload</td>
</tr>
<tr>
<td>BDS - Report</td>
<td>TAT wise | ACM Status wise | ACM TAT wise</td>
</tr>
<tr>
<td>BDS - Policy Report</td>
<td>BDS | Variance | Outstanding | IRDA | Renewal | TAT Band </td>
</tr>
<tr>
<td>BDS - Pending Actions</td>
<td>Finance Team</td>
</tr>
<tr>
<td>BDS - Masters</td>
<td>Vehicle | CD | Insurer</td>
</tr>
<tr>
<td>BDS - Documents</td>
<td></td>
</tr>
<!-- Temporary please don't delete (start's) -->
<!--
<tr> <tr>
<td class="team-cell" rowspan="5">Finance</td> <td class="team-cell" rowspan="5">Finance</td>
<td>BDS - Policy Transaction</td> <td>BDS - Policy Transaction</td>
@ -715,6 +768,8 @@ table.dataTable tbody td {
<td>BDS - Documents</td> <td>BDS - Documents</td>
<td></td> <td></td>
</tr> </tr>
-->
<!-- Temporary please don't delete (ends) -->
<tr> <tr>
<td class="team-cell" rowspan="2">POS</td> <td class="team-cell" rowspan="2">POS</td>
<td>BDS - Policy Transaction</td> <td>BDS - Policy Transaction</td>
@ -1495,9 +1550,10 @@ table.dataTable tbody td {
container.append(`<div class="no-files-message">No Files have been Uploaded</div>`); container.append(`<div class="no-files-message">No Files have been Uploaded</div>`);
} }
}, },
error: function(xhr) { error: function (xhr, status, errorThrown) {
container.html(`<div class="no-files-message">No Files have been Uploaded</div>`); container.html(`<div class="no-files-message">No Files have been Uploaded</div>`);
toastr.error('Server error occurred.', 'Error'); console.log("Error: " + xhr.status + " - " + errorThrown);
if (xhr.status !== 404) toastr.error(errorThrown || xhr.responseText || 'Something went wrong', 'Error');
} }
}); });
} }

View File

@ -83,6 +83,7 @@
<?php } else if ($file['status'] == 'partially success') { ?> <?php } else if ($file['status'] == 'partially success') { ?>
<?php echo $file['status']; ?> <?php echo $file['status']; ?>
<?php if ($file['error_data'] != 0) { ?> <?php if ($file['error_data'] != 0) { ?>
<a class="fe-alert-circle" style="color: #000;" data-toggle="tooltip" <a class="fe-alert-circle" style="color: #000;" data-toggle="tooltip"
@ -98,7 +99,6 @@
<a class="fe-alert-circle" style="color: #000;" data-toggle="tooltip" <a class="fe-alert-circle" style="color: #000;" data-toggle="tooltip"
data-placement="top" title="<?= $file['error_data'] ?>"></a> data-placement="top" title="<?= $file['error_data'] ?>"></a>
&nbsp; &nbsp;
<?php } ?> <?php } ?>
<?php } else if ($file['status'] == 'failed-1') { ?> <?php } else if ($file['status'] == 'failed-1') { ?>
@ -135,6 +135,11 @@
failed <a class="fe-alert-circle" style="color: #000;" data-toggle="tooltip" failed <a class="fe-alert-circle" style="color: #000;" data-toggle="tooltip"
data-placement="top" title="There is no data to update"></a> data-placement="top" title="There is no data to update"></a>
<?php } else if ($file['status'] == 'failed-7') { ?>
failed <a class="fe-alert-circle" style="color: #000;" data-toggle="tooltip"
data-placement="top" title="<?= $file['error_data'] ?>"></a>
<?php } else { ?> <?php } else { ?>
<?php echo $file['status']; ?> <?php echo $file['status']; ?>

View File

@ -46,33 +46,40 @@
height: 0; height: 0;
} }
.slider { .slider,
position: relative; .slider_blue {
width: 50px; position: relative;
height: 25px; width: 50px;
background-color: #fff; height: 25px;
border-radius: 25px; background-color: #fff;
box-shadow: 0 0 5px rgba(0,0,0,0.2); border-radius: 25px;
transition: 0.3s; box-shadow: 0 0 5px rgba(0,0,0,0.2);
transition: 0.3s;
} }
.slider::before { .slider::before ,
content: ""; .slider_blue::before {
position: absolute; content: "";
height: 19px; position: absolute;
width: 19px; height: 19px;
left: 3px; width: 19px;
top: 3px; left: 3px;
background-color: #ccc; top: 3px;
border-radius: 50%; background-color: #ccc;
transition: 0.3s; border-radius: 50%;
transition: 0.3s;
} }
input:checked + .slider { input:checked + .slider {
background-color: #ff4d4d; /* red when ON */ background-color: #ff4d4d; /* red when ON */
} }
input:checked + .slider::before { input:checked + .slider_blue {
background-color: #268ef5ff; /* blue when ON */
}
input:checked + .slider::before ,
input:checked + .slider_blue::before {
transform: translateX(25px); transform: translateX(25px);
background-color: #fff; background-color: #fff;
} }
@ -269,23 +276,18 @@ input:checked + .slider::before {
<textarea class="form-control" placeholder="Enter Disclaimer" name="disclaimer" id="disclaimer" ></textarea> <textarea class="form-control" placeholder="Enter Disclaimer" name="disclaimer" id="disclaimer" ></textarea>
</div> </div>
<div class="form-group col-md-4 EB"> <div class="form-group col-md-12 EB mt-3 ">
<label class="switch" style="position: relative;top: 43px;left: 20px;"> <label class="switch-label">
<input id="policy_visibility" type="checkbox" name="enrolment_visibility" checked> <input id="policy_visibility" type="checkbox" name="enrolment_visibility" checked>
<span class="slider round" style="height: 27px;"></span> <span class="slider_blue"></span>
<span class="switch-text">Policy Visibilty in Employee App</span>
</label> </label>
<!-- <label for="policy_visibility" style="position: relative;bottom: 5px;left: 85px;">Policy Visibilty in Enrollment App</label> --> <label class="switch-label" >
<label for="policy_visibility" style="position: relative;bottom: 5px;left: 85px;">Policy Visibilty in Employee App</label>
</div>
<div class="form-group col-md-4 EB">
<label class="switch" style="position: relative;top: 43px;left: 20px;">
<input id="is_lgbtq" type="checkbox" name="is_lgbtq"> <input id="is_lgbtq" type="checkbox" name="is_lgbtq">
<span class="slider round" style="height: 27px;"></span> <span class="slider_blue"></span>
<span class="switch-text">Is LGBTQ Enable</span>
</label> </label>
<label for="is_lgbtq" style="position: relative;bottom: 5px;left: 85px;"> Is LGBTQ Enable</label>
</div> </div>
</div> </div>

View File

@ -463,17 +463,26 @@ function fetchFileError(file_id) {
}, },
success: function(response) { success: function(response) {
console.log('fetchFileError response', response);
$(this).find(".modal-body").html(""); $(this).find(".modal-body").html("");
if (response.code === 200 && response.dataStatus === true && response.data !== "") { if (response.code === 200 && response.dataStatus === true && response.data !== "") {
try { try {
// console.log((JSON.parse(response.data))); // console.log((JSON.parse(response.data)));
var file_error_data = (JSON.parse(response.data)); var file_error_data = (JSON.parse(response.data));
var file_error_html = ""; var file_error_html = "";
let hasError14 = false;
let hasError15 = false;
let buttonAdded = false;
let error_code = 0;
let is_comparison_skipped = response.is_comparison_skipped ?? null;
let policy_id = response.policy_id ?? null;
for (var key in file_error_data['error_summary']) { for (var key in file_error_data['error_summary']) {
// console.log(key); // console.log(key);
var err_id = parseInt(key); var err_id = parseInt(key);
var err_count = file_error_data['error_summary'][key]; var err_count = file_error_data['error_summary'][key];
switch (err_id) { switch (err_id) {
case 0: case 0:
file_error_html += file_error_html +=
@ -538,6 +547,20 @@ function fetchFileError(file_id) {
"<strong>Rule conflict: Twofold relationship found within family</strong> <span class='badge badge-danger float-right'>" + "<strong>Rule conflict: Twofold relationship found within family</strong> <span class='badge badge-danger float-right'>" +
err_count + "</span>"; err_count + "</span>";
break; break;
case 14:
hasError14 = true;
error_code = 14;
file_error_html +=
"<strong>This inception row was not found in the member data list.</strong> <span class='badge badge-danger float-right'>" +
err_count + "</span>";
break;
case 15:
hasError15 = true;
error_code = 15;
file_error_html +=
"<strong>Inceptionmember data count mismatch.</strong> <span class='badge badge-danger float-right'>" + err_count + "</span> <br>"
+ file_error_data['error_message'] ?? "" ;
break;
default: default:
file_error_html += ""; file_error_html += "";
@ -565,11 +588,35 @@ function fetchFileError(file_id) {
// console.log('file_error_html_2', file_error_html) // console.log('file_error_html_2', file_error_html)
} }
// ✅ Decide when to add buttons
if (!buttonAdded && is_comparison_skipped != 1 && is_comparison_skipped != 0) {
if (hasError15 && error_code == 15) {
// Add after 15 (preferred if both exist)
file_error_html +=
"<div id='confirmationdiv' class='mt-2 text-center'>" +
"<p class='mb-2'>Do you want to skip the comparison?</p>" +
"<button id='confirmYes' class='btn btn-success btn-sm mx-1' data-id="+file_id+" data-pid="+policy_id+">Yes</button>" +
"<button id='confirmNo' class='btn btn-danger btn-sm mx-1' data-id="+file_id+" data-pid="+policy_id+">No</button>" +
"</div>";
buttonAdded = true;
} else if (hasError14 && !hasError15 && error_code == 14) {
// Add after 14 if 15 doesn't exist
file_error_html +=
"<div id='confirmationdiv' class='mt-2 text-center'>" +
"<p class='mb-2'>Do you want to skip the comparison?</p>" +
"<button id='confirmYes' class='btn btn-success btn-sm mx-1' data-id="+file_id+" data-pid="+policy_id+">Yes</button>" +
"<button id='confirmNo' class='btn btn-danger btn-sm mx-1' data-id="+file_id+" data-pid="+policy_id+">No</button>" +
"</div>";
buttonAdded = true;
}
}
if (err_id != 5 && err_id != 6 && err_id != 0) { if (err_id != 5 && err_id != 6 && err_id != 0) {
file_error_html += (file_error_html != "" ? file_error_html += (file_error_html != "" ?
"<a href ='<?php echo base_url()?>" + "<a href ='<?php echo base_url()?>" +
"employee/excel_error/" + file_id + "employee/excel_error/" + file_id +
"' target=_blank>click here to more details...</a>" : ""); "' target=_blank class='text-center'>click here to more details...</a>" : "");
} }
// console.log(file_error_html); // console.log(file_error_html);
@ -1043,5 +1090,105 @@ function checkValues() {
// return true; // return true;
} }
$(document).on('click', '#confirmYes', function() {
let file_id = $(this).data('id');
let policy_id = $(this).data('pid');
console.log('file_id', file_id);
console.log('policy_id', policy_id);
Swal.fire({
title: "Are you sure?",
text: "If you proceed, the comparison of the Inception and Member data list will be skipped, and the Inception file data validation process will start.",
icon: "warning",
showCancelButton: true,
confirmButtonText: "Yes, proceed",
cancelButtonText: "No, cancel",
confirmButtonColor: "#28a745",
cancelButtonColor: "#dc3545",
reverseButtons: true
}).then((result) => {
if (result.isConfirmed) {
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
$.ajax({
url: '<?= base_url("util/proceedExcelFileDataValidation") ?>', // replace with actual API URL
type: 'GET',
data: { file_id: file_id, policy_id: policy_id },
success: function(response) {
console.log('API response:', response);
if (response.status === true) {
toastr.success(response.message, 'SUCCESS');
} else {
toastr.warning(response.message, 'WARNING');
}
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
window.location.reload();
},
error: function(xhr) {
toastr.error('Failed to complete the action.');
console.error('API error:', xhr.responseText);
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
window.location.reload();
}
});
}
});
});
$(document).on('click', '#confirmNo', function() {
let file_id = $(this).data('id');
Swal.fire({
title: "Are you sure?",
text: "If you proceed, the comparison between the Inception and Member data list will continue without skipping, and the validation process will not start until the comparison is completed.",
icon: "warning",
showCancelButton: true,
confirmButtonText: "Yes, proceed",
cancelButtonText: "No, cancel",
confirmButtonColor: "#28a745",
cancelButtonColor: "#dc3545",
reverseButtons: true
}).then((result) => {
if (result.isConfirmed) {
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
$.ajax({
url: '<?= base_url("util/proceedExcelFileDataValidation") ?>', // replace with actual API URL
type: 'GET',
data: { file_id: file_id, not_skiped : true },
success: function(response) {
console.log('API response:', response);
if (response.status === true) {
toastr.success(response.message, 'SUCCESS');
} else {
toastr.warning(response.message, 'WARNING');
}
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
window.location.reload();
},
error: function(xhr) {
toastr.error('Failed to complete the action.');
console.error('API error:', xhr.responseText);
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
window.location.reload();
}
});
}
});
});
//--------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------
</script> </script>

View File

@ -1254,16 +1254,16 @@
} }
/* Cancel Bootstrap's .form-control for file inputs */ /* Cancel Bootstrap's .form-control for file inputs */
input[type="file"].form-control { /* input[type="file"].form-control { */
height: auto !important; /* height: auto !important;*/
/* remove forced height */ /* remove forced height */
padding: initial !important; /* padding: initial !important;*/
/* reset padding */ /* reset padding */
font-size: inherit !important; /* font-size: inherit !important;*/
/* reset font size */ /* reset font size */
line-height: normal !important; /* line-height: normal !important;*/
/* reset line height */ /* reset line height */
} /* } */
/* Apply to Select2 (single select) */ /* Apply to Select2 (single select) */
@ -1737,9 +1737,9 @@
<li> <li>
<a href="<?= base_url('/employee/endorsement-list') ?>">View Endorsement</a> <a href="<?= base_url('/employee/endorsement-list') ?>">View Endorsement</a>
</li> </li>
<li> <!-- <li>
<a href="<?= base_url('/employee/enrollment-list') ?>">View Enrolment</a> <a href="<?= base_url('/employee/enrollment-list') ?>">View Enrolment</a>
</li> </li> -->
<li> <li>
<a href="<?= base_url('/employee/test_members_list') ?>">Test Members List</a> <a href="<?= base_url('/employee/test_members_list') ?>">Test Members List</a>
</li> </li>
@ -1752,7 +1752,7 @@
<?php } ?> <?php } ?>
<!-- Masters --> <!-- Masters -->
<?php if (get_role_id() == 1 || get_role_id() == 5 || get_role_id() == 4) { ?> <?php if (get_role_id() == 1 || get_role_id() == 5 || ( get_role_id() == 4 && (in_array(BUSINESS_SUPPORT_TEAM_ID, user_team()) || in_array(SALES_TEAM_ID, user_team())))) { ?>
<li class="li-seperate" id="masters-li"> <li class="li-seperate" id="masters-li">
<a href="#sidebarPolicies" data-toggle="collapse" class=" img-inactive"> <a href="#sidebarPolicies" data-toggle="collapse" class=" img-inactive">
@ -1881,7 +1881,7 @@
</li> </li>
<?php } ?> <?php } ?>
<!-- BDS --> <!-- BDS -->
<?php if ((get_role_id() == 1 || get_role_id() == 5) || (in_array(MANAGEMENT_TEAM_ID, user_team()) || in_array(FINANCE_TEAM_ID, user_team()) || in_array(BUSINESS_TEAM_ID, user_team()) || in_array(POS_TEAM_ID, user_team()))) { ?> <?php if ((get_role_id() == 1 || get_role_id() == 5 || get_role_id() == 4) || (in_array(MANAGEMENT_TEAM_ID, user_team()) || in_array(FINANCE_TEAM_ID, user_team()) || in_array(BUSINESS_TEAM_ID, user_team()) || in_array(POS_TEAM_ID, user_team()))) { ?>
<li class="li-seperate" id="policy-transactions-li"> <li class="li-seperate" id="policy-transactions-li">
<a href="#policyTransactions" data-toggle="collapse" class="waves-effect img-inactive"> <a href="#policyTransactions" data-toggle="collapse" class="waves-effect img-inactive">
<img <img
@ -1916,9 +1916,9 @@
</div> </div>
</li> </li>
<?php if ((get_role_id() == 1 || get_role_id() == 5) || (in_array(MANAGEMENT_TEAM_ID, user_team()) || in_array(FINANCE_TEAM_ID, user_team()) || in_array(BUSINESS_TEAM_ID, user_team()) || in_array(POS_TEAM_ID, user_team()))) { ?> <?php if ((get_role_id() == 1 || get_role_id() == 5) ||(get_role_id() == 4 && in_array(FINANCE_TEAM_ID, user_team())) || (in_array(MANAGEMENT_TEAM_ID, user_team()) || in_array(FINANCE_TEAM_ID, user_team()) || in_array(BUSINESS_TEAM_ID, user_team()) || in_array(POS_TEAM_ID, user_team()))) { ?>
<?php if (in_array(get_role_id(), [1, 5]) || in_array(MANAGEMENT_TEAM_ID, user_team()) || in_array(POS_TEAM_ID, user_team())) { ?> <?php if (in_array(get_role_id(), [1, 5]) ||(get_role_id() == 4 && in_array(FINANCE_TEAM_ID, user_team())) || in_array(MANAGEMENT_TEAM_ID, user_team()) || in_array(POS_TEAM_ID, user_team())) { ?>
<li> <li>
<a href="#policyReports" data-toggle="collapse" class="waves-effect"> <a href="#policyReports" data-toggle="collapse" class="waves-effect">
<i class="ri-file-chart-fill"></i> <i class="ri-file-chart-fill"></i>
@ -1929,7 +1929,7 @@
<li> <li>
<a href="<?= base_url('/policy_tranction/report/list') ?>">BDS</a> <a href="<?= base_url('/policy_tranction/report/list') ?>">BDS</a>
</li> </li>
<?php if (in_array(get_role_id(), [1, 5]) || in_array(MANAGEMENT_TEAM_ID, user_team())) { ?> <?php if (in_array(get_role_id(), [1, 5]) || (get_role_id() == 4 && in_array(FINANCE_TEAM_ID, user_team())) || in_array(MANAGEMENT_TEAM_ID, user_team())) { ?>
<li> <li>
<a href="<?= base_url('/policy_tranction/report/report-varience-list') ?>">Variance</a> <a href="<?= base_url('/policy_tranction/report/report-varience-list') ?>">Variance</a>
</li> </li>
@ -2009,6 +2009,11 @@
<li> <li>
<a href="<?= base_url('/master/vehicle/list') ?>">Vehicle Master</a> <a href="<?= base_url('/master/vehicle/list') ?>">Vehicle Master</a>
</li> </li>
<?php if ((get_role_id() === 4 && in_array(FINANCE_TEAM_ID, user_team())) || in_array(BUSINESS_TEAM_ID, user_team())) { ?>
<li>
<a href="<?= base_url('/master/insurer/list') ?>">Insurer Master</a>
</li>
<?php } ?>
</ul> </ul>
</div> </div>
</li> </li>

View File

@ -209,9 +209,13 @@ $isActive = get_role_id() == STAFF_ROLE_ID && in_array(ENROLLMENT_TEAM_ID, user_
$index = 0; $index = 0;
foreach ($lead_data as $key => $value) : ?> foreach ($lead_data as $key => $value) : ?>
<?php <?php
if ($key == "total" || $key == "won" || substr($key, -4) === "_ids") { if ($key == "total" || substr($key, -4) === "_ids") {
continue; continue;
} // Skip the total key }
// if ($key == "total" || $key == "won" || substr($key, -4) === "_ids") {
// continue;
// }
// Skip the total key
?> ?>
<?php <?php
// Initialize color set and shade indexes // Initialize color set and shade indexes
@ -222,7 +226,7 @@ $isActive = get_role_id() == STAFF_ROLE_ID && in_array(ENROLLMENT_TEAM_ID, user_
$bgColor = $colorShades[$colorSetIndex][$shadeIndex]; $bgColor = $colorShades[$colorSetIndex][$shadeIndex];
?> ?>
<?php <?php
$formattedStatus = strlen($key) < 5 ? strtoupper($key) : ucwords(str_replace('_', ' ', $key)); $formattedStatus = strlen($key) < 5 ? strtoupper($key) : formatKey($key, 4);
$truncatedStatus = strlen($formattedStatus) > 20 ? substr($formattedStatus, 0, 15) . '...' : $formattedStatus; $truncatedStatus = strlen($formattedStatus) > 20 ? substr($formattedStatus, 0, 15) . '...' : $formattedStatus;
$showTooltip = strlen($formattedStatus) > 20; $showTooltip = strlen($formattedStatus) > 20;
?> ?>

View File

@ -164,7 +164,7 @@ table.dataTable tbody td {
<thead class="bg-light"> <thead class="bg-light">
<tr> <tr>
<th><div class="column-header">S.No&nbsp;</div></th> <th><div class="column-header">S.No &nbsp;</div></th>
<th><div class="column-header">Lead Type &nbsp;</div></th> <th><div class="column-header">Lead Type &nbsp;</div></th>
<th><div class="column-header">Issuer &nbsp;</div></th> <th><div class="column-header">Issuer &nbsp;</div></th>
<th><div class="column-header">Client Type &nbsp;</div></th> <th><div class="column-header">Client Type &nbsp;</div></th>
@ -209,8 +209,10 @@ table.dataTable tbody td {
<td><?php echo $lead_status[$row['status']] ?? '-'; ?></td> <td><?php echo $lead_status[$row['status']] ?? '-'; ?></td>
<td> <td>
<div class="btn-group dropdown"> <div class="btn-group dropdown">
<a href="javascript:void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm" data-toggle="dropdown" aria-expanded="false"> <a href="javascript:void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm"
<i class="mdi mdi-dots-horizontal"></i> data-toggle="dropdown"
aria-expanded="false"
data-boundary="window"> <i class="mdi mdi-dots-horizontal"></i>
</a> </a>
<div class="dropdown-menu dropdown-menu-right"> <div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item btnEdit" data-id="<?= $row['id']; ?>" data-ft="<?= $row['lead_form_type']; ?>" onclick="getLeadsDataForEdit('<?= htmlspecialchars($row['id'], ENT_QUOTES) ?>', '<?= htmlspecialchars($row['lead_form_type'], ENT_QUOTES) ?>')"> <a class="dropdown-item btnEdit" data-id="<?= $row['id']; ?>" data-ft="<?= $row['lead_form_type']; ?>" onclick="getLeadsDataForEdit('<?= htmlspecialchars($row['id'], ENT_QUOTES) ?>', '<?= htmlspecialchars($row['lead_form_type'], ENT_QUOTES) ?>')">
@ -332,11 +334,42 @@ table.dataTable tbody td {
document.body.appendChild(customDropdown); document.body.appendChild(customDropdown);
row.addEventListener("click", function(event) { row.addEventListener("click", function(event) {
// Ignore clicks on the action column
// 1. CRITICAL CHECK: Stop propagation if the click came from the dropdown toggle itself.
if (event.target.closest('.dropdown-toggle')) {
event.stopPropagation();
// **IMPORTANT:** Since you're using a custom script, you need to
// manually trigger the logic for your custom detached dropdown here.
// The code below should run when the dropdown toggle is clicked:
const originalDropdown = event.target.closest('.btn-group').querySelector('.dropdown-menu');
if (originalDropdown) {
// This is the code that opens your custom dropdown
if (activeDropdown) {
activeDropdown.style.display = 'none';
}
const rect = event.target.getBoundingClientRect();
customDropdown.style.display = 'block';
customDropdown.style.position = 'fixed';
customDropdown.style.left = `${rect.left}px`;
customDropdown.style.top = `${rect.bottom + 5}px`;
activeDropdown = customDropdown;
}
return; // Exit the row listener early
}
// 2. Ignore clicks on the entire action column (your existing, good check)
if (event.target.closest('td:last-child')) { if (event.target.closest('td:last-child')) {
return; return;
} }
// ... rest of your row logic for general row clicks ...
if (activeDropdown) { if (activeDropdown) {
activeDropdown.style.display = 'none'; activeDropdown.style.display = 'none';
} }
@ -349,7 +382,7 @@ table.dataTable tbody td {
customDropdown.style.top = `${rect.bottom + 5}px`; customDropdown.style.top = `${rect.bottom + 5}px`;
activeDropdown = customDropdown; activeDropdown = customDropdown;
event.stopPropagation(); event.stopPropagation(); // Only needed if there is a parent handler
}); });
// Handle clicks on dropdown items // Handle clicks on dropdown items

View File

@ -0,0 +1,98 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Email Notification</title>
</head>
<style>
.mail-template-header {
max-width: 500px;
background-color: #ffffff !important;
border-bottom: 1px solid #00999E;
width: 100%; /* default: allow full width */
}
/* On screens smaller than 600px → force 100% */
@media screen and (max-width: 600px) {
.mail-template-header {
background-color: #ffffff !important;
max-width: 100% !important;
width: 100% !important;
}
}
.mail-template-footer {
max-width: 500px;
background-color: #ffffff !important;
border-top: 1px solid #00999E;
width: 100%; /* default: allow full width */
}
/* On screens smaller than 600px → force 100% */
@media screen and (max-width: 600px) {
.mail-template-footer {
background-color: #ffffff !important;
max-width: 100% !important;
width: 100% !important;
}
}
</style>
<body>
<!-- header -->
<div align="center">
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="mail-template-header">
<tr style="height:90px; background-color: #ffffff !important;">
<td align="left" valign="middle" style="padding:20px;" width="50%">
<img src="<?= $client_logo?>"
alt="Client Logo"
style="max-height:80px; max-width: 160px;">
</td>
<td align="right" valign="middle" style="padding:20px;" width="50%">
<img src="<?= base_url('/public/assets/images/Nhance-Logo-Final.png'); ?>"
alt="Default Logo"
style="height:auto; max-width: 120px;">
</td>
</tr>
</table>
</div>
<!-- mail content -->
<?php
echo $mail_content;
?>
<!-- footer -->
<div align="center">
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="mail-template-footer">
<tr style="background-color: #ffffff !important;">
<td align="center" valign="middle" style="padding-top:5px;">
<img src="<?= base_url('/public/assets/images/Nhance-Logo-Final.png'); ?>"
alt="Default Logo"
style="height:auto; max-width: 120px;padding-top:5px;">
<p>
&copy; <?= date('Y'); ?> Nhance India Insurance Broking Pvt Ltd
</p>
</td>
</tr>
</table>
</div>
</body>
</html>

View File

@ -1005,6 +1005,7 @@
setTimeout(function(){ setTimeout(function(){
$('#policy_start_date').val(res.data.policy_start_date); $('#policy_start_date').val(res.data.policy_start_date);
$('#policy_end_date').val(res.data.policy_end_date); $('#policy_end_date').val(res.data.policy_end_date);
$('#insurer_id').val(res.data.insurer_branch_id + '-' + res.data.insurer_id);
}, 1500) }, 1500)
$('#policy_no').val(res.data.policy_no); $('#policy_no').val(res.data.policy_no);
@ -1347,15 +1348,39 @@
// $('#co_ter_premium_' + input).val(cotep.toFixed(2)); // $('#co_ter_premium_' + input).val(cotep.toFixed(2));
// } // }
function checkAndDistributeTax(input) function checkAndDistributeTax(input){
{
const event = window.event; const event = window.event;
console.log("Event id:", event.target.id); console.log("Event id:", event.target.id);
let policy_type_id = $('#client_policy_id').find('option:selected').attr('data-ptid');
policy_type_id = parseInt(policy_type_id);
console.log('policy_type_id', policy_type_id);
let cgst = parseFloat($('#cgst_' + input).val()); let cgst = parseFloat($('#cgst_' + input).val());
let sgst = parseFloat($('#sgst_' + input).val()); let sgst = parseFloat($('#sgst_' + input).val());
let igst = parseFloat($('#igst_' + input).val()); let igst = parseFloat($('#igst_' + input).val());
// ✅ Allow 0 only for policy types 2, 5, 7
const allowZero = [1,2,3,4,5,6,7,38,39,40].includes(policy_type_id);
console.log("allowZero", allowZero);
// 🔒 Validation: Disallow 0 or negative values for other policy types
if (!allowZero) {
if ((cgst <= 0 && (event.target.id).startsWith('cgst')) ||
(sgst <= 0 && (event.target.id).startsWith('sgst')) ||
(igst <= 0 && (event.target.id).startsWith('igst'))) {
toastr.warning('Tax value must be greater than 0 for this policy type.');
$('#'+ event.target.id).val('');
$('#igst_' + input).val('');
$('#cgst_' + input).val('');
$('#sgst_' + input).val('');
return;
}
}
if (((event.target.id).startsWith('cgst'))) { if (((event.target.id).startsWith('cgst'))) {
if (!isFinite(cgst) || isNaN(cgst) || cgst === undefined) { if (!isFinite(cgst) || isNaN(cgst) || cgst === undefined) {

View File

@ -2322,13 +2322,37 @@
// } // }
function checkAndDistributeTax(input){ function checkAndDistributeTax(input){
const event = window.event; const event = window.event;
console.log("Event id:", event.target.id); console.log("Event id:", event.target.id);
let policy_type_id = parseInt($('#policy_type_id').val());
console.log('policy_type_id', policy_type_id);
let cgst = parseFloat($('#cgst_' + input).val()); let cgst = parseFloat($('#cgst_' + input).val());
let sgst = parseFloat($('#sgst_' + input).val()); let sgst = parseFloat($('#sgst_' + input).val());
let igst = parseFloat($('#igst_' + input).val()); let igst = parseFloat($('#igst_' + input).val());
// ✅ Allow 0 only for policy types 2, 5, 7
const allowZero = [1,2,3,4,5,6,7,38,39,40].includes(policy_type_id);
console.log("allowZero", allowZero);
// 🔒 Validation: Disallow 0 or negative values for other policy types
if (!allowZero) {
if ((cgst <= 0 && (event.target.id).startsWith('cgst')) ||
(sgst <= 0 && (event.target.id).startsWith('sgst')) ||
(igst <= 0 && (event.target.id).startsWith('igst'))) {
toastr.warning('Tax value must be greater than 0 for this policy type.');
$('#'+ event.target.id).val('');
$('#igst_' + input).val('');
$('#cgst_' + input).val('');
$('#sgst_' + input).val('');
return;
}
}
if (((event.target.id).startsWith('cgst'))) { if (((event.target.id).startsWith('cgst'))) {
if (!isFinite(cgst) || isNaN(cgst) || cgst === undefined) { if (!isFinite(cgst) || isNaN(cgst) || cgst === undefined) {

View File

@ -117,7 +117,7 @@ table.dataTable tbody td {
<?php foreach($report_list as $index => $row){ ?> <?php foreach($report_list as $index => $row){ ?>
<tr> <tr>
<td><?= $index + 1 ?> &nbsp; <a href="<?php <td><?= $index + 1 ?> &nbsp; <a href="<?php
if($row['action_type'] == "inception"){ if(strtolower($row['action_type']) == "policy"){
echo base_url('policy_tranction/inception/list') . '?pt_id=' . $row['id'] ; echo base_url('policy_tranction/inception/list') . '?pt_id=' . $row['id'] ;
}else{ }else{
echo base_url('policy_tranction/endorsement/list') . '?pt_id=' . $row['id'] ; echo base_url('policy_tranction/endorsement/list') . '?pt_id=' . $row['id'] ;

View File

@ -1,9 +1,9 @@
<style> <style>
</style> </style>
<div class="container-fluid-min"> <div class="container-fluid-min">
<div class="col-12" id="bds_filter"> <div class="col-12" id="bds_filter">
<div class="card-body"> <div class="card-body">
<div id="accordion" class="mb-3"> <div id="accordion" class="mb-3">
@ -149,11 +149,11 @@
<div id="file_list"> <div id="file_list">
<?php include('report_bds.php'); ?> <?php include('report_bds.php'); ?>
</div> </div>
</div> </div>
<script> <script>
let client_list = []; let client_list = [];
let branch_list = []; let branch_list = [];
let policy_list = []; let policy_list = [];
@ -559,4 +559,4 @@
} }
} }
</script> </script>

View File

@ -0,0 +1,654 @@
<style>
.table th,
.table td {
padding: 8px;
}
table.dataTable tbody td {
padding: 4px 4px !important;
}
.col-12 {
max-width: 98% !important;
}
.dataTables_filter {
position: absolute;
}
.right-align-input {
text-align: right;
}
.badge-container {
background: #F0F0F0;
padding: 6px 12px;
border-radius: 6px;
font-size: 14px;
display: inline-block;
}
#totals {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
</style>
<div class="col-12" id="second_page">
<div class="card">
<div class="card-body">
<div class="row" style="padding-bottom: 10px;">
<div class="col-6" style="align-self: center;">
<h4 style="position: relative;">BDS Report <span id="bds_title"></span></h4>
</div>
</div>
<div class="table-responsive">
<div id="totals" class="d-flex flex-wrap gap-2 mb-2">
<div class="badge-container">
Total Premium: <span class="text-primary" id="total_premium">0.00</span>
</div>
<div class="badge-container">
Total Rewards: <span class="text-primary" id="total_rewards">0.00</span>
</div>
<div class="badge-container">
Total IRDA Revenue INR: <span class="text-primary" id="total_irda">0.00</span>
</div>
<div class="badge-container">
Total Billed Amount: <span class="text-primary" id="total_billed">0.00</span>
</div>
<div class="badge-container">
Total Unbilled Amount: <span class="text-primary" id="total_unbilled">0.00</span>
</div>
<div class="badge-container">
Total Policy Count: <span class="text-primary"><?= $policy_count ?></span>
</div>
</div>
<table data-custom-table-css="table" id="scroll-horizontal-datatable" class="table w-100 nowrap">
<thead class="bg-light">
<tr>
<th>S. No</th>
<th>User</th>
<th>Month</th>
<th style="display: none;">statement upload</th>
<!-- <th style="display: none;">Business Type</th> -->
<th style="display: none;">Client Type</th>
<th>Insured Name</th>
<th>Policy/<br>Endorsement</th>
<th>Policy Type</th>
<th style="display: none;">BAP Group</th>
<th style="display: none;">Vehicle Number</th>
<th>Policy No</th>
<th>Endorsement No</th>
<!-- <th style="display: none;">Insurer Name</th> -->
<th>Insurer Branch</th>
<!-- <th style="display: none;">TPA</th> -->
<th style="display: none;">Endorsement <br> Effective Date</th>
<th style="display: none;">Policy <br> Effective Date</th>
<th style="display: none;">Policy <br> Expiry Date</th>
<th style="display: none;">Reference</th>
<th style="display: none;">Remarks</th>
<th>BP Premium</th>
<th>TP/Ter Premium</th>
<th style="display: none;">Premium <br> (without GST)</th>
<!-- <th style="display: none;">GST @ 18%</th> -->
<th>Total Premium</th>
<th>BP %</th>
<th>TP/Ter %</th>
<th>Rewards</th>
<th>Agreed Amount</th>
<th>Invoiced Amount</th>
<th>Outstanding Amount</th>
</tr>
</thead>
<tbody>
<?php if (isset($report_list)) {
// empty array to initialize for policies per insurer per month
$uniquePoliciesReport = [];
// irrespective of months or multiple months
$uniqueAgreedAmountList = [];
?>
<?php
foreach($report_list as $index => $row){
$policy_no = $row['policy_no'];
$policy_updated_month = $row['policy_issue_month'];
$policy_type = $row['policy_type'];
$statement_status = $row['statement_uploaded'];
$client_name = $row['client_name'];
$insurer_branch_name = $row['insurer_branch_name'];
$uniqueRecord = "$policy_no-$policy_updated_month-$policy_type-$client_name-$insurer_branch_name-$statement_status" ;
// irrespective of months or multiple months
$uniqueAgreedAmountPerInsurer = "$policy_no-$policy_type-$client_name-$insurer_branch_name" ;
$pastMonth = explode("-",$uniqueRecord )[1] ;
$currentMonth = $policy_updated_month ;
$pastStatementStatus = explode("-",$uniqueRecord )[5] ;
$currentStatementStatus = $statement_status;
if(
isset($uniquePoliciesReport[$uniqueRecord])
&& $pastStatementStatus == $currentStatementStatus
){
continue ;
}else{
if(isset($uniqueAgreedAmountList[$uniqueAgreedAmountPerInsurer]) ){
$uniqueAgreedAmountList[$uniqueAgreedAmountPerInsurer] -= $row['billed_amt'];
$row['total_irda_amt'] = $pastMonth == $currentMonth ? $row['total_irda_amt'] : 0 ;
$row['outstanding_amt'] = $uniqueAgreedAmountList[$uniqueAgreedAmountPerInsurer];
$row['multiple_months'] = $pastMonth == $currentMonth ? false : true ;
}
else{
$row['outstanding_amt'] = $row['total_irda_amt'] - $row['billed_amt'];
$uniqueAgreedAmountList[$uniqueAgreedAmountPerInsurer] = $row['total_irda_amt'] ;
$row['multiple_months'] = false;
}
$uniquePoliciesReport[$uniqueRecord] = $row;
}
}
$report_list = array_values($uniquePoliciesReport);
?>
<?php foreach($report_list as $index => $row){
?>
<tr>
<td><?= $index + 1 ?> &nbsp; <a href="<?php
if($row['action_type'] == "inception"){
echo base_url('policy_tranction/inception/list') . '?pt_id=' . $row['id'] ;
}else{
echo base_url('policy_tranction/endorsement/list') . '?pt_id=' . $row['id'] ;
}
?>" class="mdi mdi-pencil" ></a> </td>
<td ><?php echo $row['statement_uploaded'] == 'statement uploaded' && $row['multiple_months'] == true ? 'rewards': $row['user_name']??'N/A' ; ?></td>
<td><?php echo $row['policy_issue_month'] ?: 'N/A'; ?></td>
<td style="display: none;"><?php echo $row['statement_uploaded'] ?: 'N/A'; ?></td>
<!-- <td style="display: none;"><?php echo $row['revenue_type'] ?: 'N/A'; ?></td> -->
<td style="display: none;"><?php echo $row['client_type'] ?: 'N/A'; ?></td>
<td><?php echo $row['client_name'] ?: 'N/A'; ?></td>
<td><?php echo $row['action_type'] ?: 'N/A'; ?></td>
<td><?php echo $row['policy_type'] ?: 'N/A'; ?></td>
<td style="display: none;"><?php echo $row['bap'] ?: 'N/A'; ?></td>
<td style="display: none;"><?php echo $row['vehicle_no'] ?: 'N/A'; ?></td>
<td><?php echo $row['policy_no'] ?: 'N/A'; ?></td>
<td><?php echo $row['endorsement_no'] ?: 'N/A'; ?></td>
<!-- <td style="display: none;"><?php echo $row['insurer_name'] ?: 'N/A'; ?> </td> -->
<td><?php echo $row['insurer_branch_name'] ?: 'N/A'; ?></td>
<!-- <td style="display: none;"><?php echo $row['tpa_name']; ?></td> -->
<td style="display: none;"><?php echo empty($row['endorse_eff_date']) ? 'N/A' : date('d/m/Y', strtotime($row['endorse_eff_date'])) ?></td>
<td style="display: none;"><?php echo empty($row['policy_start_date']) ? 'N/A' : date('d/m/Y', strtotime($row['policy_start_date'])); ?></td>
<td style="display: none;"><?php echo empty($row['policy_end_date']) ? 'N/A' : date('d/m/Y', strtotime($row['policy_end_date'])); ?></td>
<td style="display: none;"><?php echo $row['ref'] ?: 'N/A'; ?></td>
<td style="display: none;"><?php echo $row['remarks'] ?: 'N/A'; ?></td>
<td class="right-align-input"><?php echo $row['bp_amt']; ?></td>
<td class="right-align-input"><?php echo $row['tp_or_ter']; ?></td>
<td class="right-align-input" style="display: none;"><?php echo $row['premium_wo_gst']; ?></td>
<!-- <td class="right-align-input" style="display: none;"><?php echo $row['gst_amount']; ?></td> -->
<td class="right-align-input"><?php echo $row['total_premium']; ?></td>
<td class="right-align-input"><?php echo $row['agreed_bp_per']; ?>&nbsp;%</td>
<td class="right-align-input"><?php echo $row['agreed_tp_or_ter_per'];?>&nbsp;%</td>
<td class="right-align-input" ><?php echo isset($row['reward']) ? $row['reward'] : '0.00'; ?></td>
<!-- Agreed Amount as total_irda_amt -->
<td class="right-align-input" onclick="showCoShareStatementDetails(this)" data-id="<?= $row['pt_id'] ?>"><?php echo $row['total_irda_amt']; ?></td>
<!-- invoiced amount as billed_amt -->
<td class="right-align-input"><?php echo empty($row['billed_amt']) ? '0.00' : $row['billed_amt'] ?></td>
<!-- Outstanding Amount (Agreed amount - invoice amount) -->
<td class="right-align-input"><?php echo number_format((float)$row['outstanding_amt'],2, '.', '')?></td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
</table>
<div>
</div>
</div>
</div><!-- end col -->
</div>
</div>
<!-- modal content -->
<div class="modal fade" id="centermodal" tabindex="-1" role="dialog" aria-hidden="true" aria-modal="true" data-backdrop="static">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header" style="background-color: gainsboro;">
<h4 class="modal-title" id="myCenterModalLabel">Statement Details <span id="heading"></span></h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body" id="modal_body">
<div class="table-responsive">
<table data-custom-table-css="table" class="table table-hover mb-0">
<thead class="bg-light" id="table_head_data">
<tr>
<th>Statement No.</th>
<th>Statement Month</th>
<th>Actual Amount</th>
<th>Invoice No.</th>
<th>Invoice Date.</th>
<th>Invoice Status.</th>
</tr>
</thead>
<tbody id="table_data">
</tbody>
</table>
</div> <!-- end table-responsive-->
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-------------------------------------------------------------------------------------------------->
<script>
// Datatable document ready
$(document).ready(function() {
var ticketsTable = $('#scroll-horizontal-datatable');
if (ticketsTable.length) {
ticketsTable.DataTable({
scrollX: true,
dom: "<'row'<'col-sm-6'f><'col-sm-6 text-right'B>>" + // Filter left, buttons right
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>", // Pagination at the bottom, without page length selector
// buttons: [
// {
// extend: 'csv',
// text: 'CSV',
// title: 'Policy-Tranction-BDS-List',
// },
// {
// extend: 'excel',
// text: 'Excel',
// title: 'Policy-Tranction-BDS-List',
// customize: function(xlsx) {
// var sheet = xlsx.xl.worksheets['sheet1.xml'];
// var total = 0;
// // 🔹 Force column K (11) and L (12) as string
// $('row c[r^="K"], row c[r^="L"]', sheet).attr('t', 'inlineStr');
// // Find cells in column AB (28th column in Excel)
// $('row c[r^="AB"]', sheet).each(function() {
// var value = parseFloat($('v', this).text()); // Get the value inside the cell
// if (!isNaN(value)) {
// total += value;
// }
// });
// // Get the last row index and append the total row
// var lastRow = $('row:last', sheet);
// var rowIndex = parseInt(lastRow.attr('r')) + 2; // Find the next row index
// var totalRow = '<row r="' + rowIndex + '">' +
// '<c t="inlineStr" r="AA' + rowIndex + '"><is><t>Total</t></is></c>' + // Insert "Total" in AA
// '<c t="n" r="AB' + rowIndex + '"><v>' + total.toFixed(2) + '</v></c>' + // Insert sum in AB
// '</row>';
// // Append the new total row to the sheet
// $(sheet).find('sheetData').append(totalRow);
// },
// exportOptions: {
// orthogonal: 'sort'
// },
// customizeData: function (data) {
// for (var i = 0; i < data.body.length; i++) {
// for (var j = 0; j < data.body[i].length; j++) {
// // Check if the column is the 9th index (10th column) and 10th index (11th column)
// if (j === 9 || j === 10) {
// data.body[i][j] = '\u200C' + data.body[i][j];
// }
// }
// }
// }
// }
// ],
buttons: [
{
extend: 'collection',
text: '<span class=" btn-custom"> Export </span><i class="mdi mdi-menu-down"></i>',
className: 'btn app-btn-secondary ',
buttons: [
{
extend: 'csv',
text: '<i class="mdi mdi-file-delimited " ></i><span class=" btn-custom"> CSV </span>',
title: 'Policy-Tranction-BDS-List',
exportOptions: {
columns: ':visible', // or specify exact columns [0,1,2,...]
format: {
body: function (data, row, column, node) {
// Force K and L columns to string
if (column === 10 || column === 11) {
// Option 1: prepend single quote
return '\u200C' + data;
// Option 2: use Excel formula trick
// return '="' + data + '"';
}
return data;
}
}
},
},
{
extend: 'excel',
title: 'Policy-Tranction-BDS-List',
text: '<i class="mdi mdi-file-excel " ></i><span class=" btn-custom"> EXCEL </span>',
className: 'app-btn-primary ',
// customize: function (xlsx) {
// var sheet = xlsx.xl.worksheets['sheet1.xml'];
// var total = 0;
// // 🔹 Force column K (11) and L (12) as string
// // $('row c[r^="K"], row c[r^="L"]', sheet).attr('t', 'inlineStr');
// // 🔹 Convert column K (11th) & L (12th) to inline string
// $('row c[r^="K"], row c[r^="L"]', sheet).each(function () {
// var cell = $(this);
// console.log(cell);
// var val = cell.find('v').text(); // get value
// if (val) {
// cell.attr('t', 'inlineStr'); // mark as text
// cell.remove('v'); // remove <v>
// cell.append('<is><t>' + val + '</t></is>'); // replace with inline string
// }
// });
// // Calculate total in AB (28th column)
// $('row c[r^="AB"]', sheet).each(function () {
// var value = parseFloat($('v', this).text());
// if (!isNaN(value)) {
// total += value;
// }
// });
// // Append total row
// var lastRow = $('row:last', sheet);
// var rowIndex = parseInt(lastRow.attr('r')) + 2;
// var totalRow = '<row r="' + rowIndex + '">' +
// '<c t="inlineStr" r="AA' + rowIndex + '"><is><t>Total</t></is></c>' +
// '<c t="n" r="AB' + rowIndex + '"><v>' + total.toFixed(2) + '</v></c>' +
// '</row>';
// $(sheet).find('sheetData').append(totalRow);
// },
customize: function (xlsx) {
var sheet = xlsx.xl.worksheets['sheet1.xml'];
var total = 0;
function forceAsText(cell) {
var val = cell.find('v').text();
if (val) {
// Remove old <v>
cell.find('v').remove();
// Force as inline string
cell.attr('t', 'inlineStr');
cell.append('<is><t>' + val + '</t></is>');
}
}
function forceAsTextPreserveOriginal(cell) {
// Get the original cell value from the cell's text content
var vElement = cell.find('v');
if (vElement.length > 0) {
var originalValue = vElement.text();
// Remove the <v> element
vElement.remove();
// Set cell type to inline string and preserve the original value
cell.attr('t', 'inlineStr');
cell.append('<is><t>' + originalValue + '</t></is>');
}
}
// 🔹 Force K column as text (working correctly)
$('row c[r^="K"]', sheet).each(function () {
forceAsText($(this));
});
// 🔹 Force L column as text with better preservation
$('row c[r^="L"]', sheet).each(function () {
forceAsTextPreserveOriginal($(this));
});
// 🔹 Calculate total in AB (28th column)
$('row c[r^="AB"] v', sheet).each(function () {
var value = parseFloat($(this).text());
if (!isNaN(value)) total += value;
});
// 🔹 Append total row
var lastRow = $('row:last', sheet);
var rowIndex = parseInt(lastRow.attr('r')) + 2;
var totalRow = '<row r="' + rowIndex + '">' +
'<c t="inlineStr" r="AA' + rowIndex + '"><is><t>Total</t></is></c>' +
'<c t="n" r="AB' + rowIndex + '"><v>' + total.toFixed(2) + '</v></c>' +
'</row>';
$(sheet).find('sheetData').append(totalRow);
},
exportOptions: {
orthogonal: 'sort' ,
columns: ':not(:eq(3))' // skip the same 4th column
},
customizeData: function (data) {
for (var i = 0; i < data.body.length; i++) {
for (var j = 0; j < data.body[i].length; j++) {
// Force 10th (index 9) & 11th (index 10) as text
if (j === 9 || j === 10 || j === 11 || j === 12 ) {
data.body[i][j] = '\u200C' + data.body[i][j];
}
}
}
}
}
]
}
],
language: {
search: `
<div class="datatable-search-wrapper">
_INPUT_
<i class="mdi mdi-magnify datatable-search-icon"></i>
</div>`,
searchPlaceholder: "Search"
},
paging: true, // Enable pagination
pageLength: 10, // Set default number of rows per page (optional)
ordering: false,
// "footerCallback": function(row, data, start, end, display) {
// var api = this.api();
// // Calculate column totals
// var totalPremium = api.column(23).data().reduce(function(a, b) {
// return parseFloat(a) + parseFloat(b) || 0;
// }, 0);
// var total_rewards = api.column(26).data().reduce(function(a, b) {
// return parseFloat(a) + parseFloat(b) || 0;
// }, 0); // Add initial value 0 here
// console.log('total_rewards - ' + total_rewards);
// var totalIrda = api.column(27).data().reduce(function(a, b) {
// return parseFloat(a) + parseFloat(b) || 0;
// }, 0);
// var totalBilled = api.column(28).data().reduce(function(a, b) {
// return parseFloat(a) + parseFloat(b) || 0;
// }, 0);
// var totalUnbilled = api.column(29).data().reduce(function(a, b) {
// return parseFloat(a) + parseFloat(b) || 0;
// }, 0);
// // Update the totals in the div above the table
// $('#total_premium').text(totalPremium.toFixed(2));
// $('#total_rewards').text(total_rewards.toFixed(2));
// $('#total_irda').text(totalIrda.toFixed(2));
// $('#total_billed').text(totalBilled.toFixed(2));
// $('#total_unbilled').text(totalUnbilled.toFixed(2));
// }
"footerCallback": function(row, data, start, end, display) {
var api = this.api();
// Calculate column totals (adjust indices based on VISIBLE columns)
var totalPremium = api.column(20, {search: 'applied'}).data().reduce(function(a, b) {
return parseFloat(a) + parseFloat(b || 0);
}, 0);
var total_rewards = api.column(23, {search: 'applied'}).data().reduce(function(a, b) {
return parseFloat(a) + parseFloat(b || 0);
}, 0);
var totalIrda = api.column(24, {search: 'applied'}).data().reduce(function(a, b) {
return parseFloat(a) + parseFloat(b || 0);
}, 0);
var totalBilled = api.column(25, {search: 'applied'}).data().reduce(function(a, b) {
return parseFloat(a) + parseFloat(b || 0);
}, 0);
var totalUnbilled = api.column(26, {search: 'applied'}).data().reduce(function(a, b) {
return parseFloat(a) + parseFloat(b || 0);
}, 0);
// Update the totals
$('#total_premium').text(totalPremium.toFixed(2));
$('#total_rewards').text(total_rewards.toFixed(2));
$('#total_irda').text(totalIrda.toFixed(2));
$('#total_billed').text(totalBilled.toFixed(2));
$('#total_unbilled').text(totalUnbilled.toFixed(2));
}
});
} else {
console.error("Table atet found.");
}
});
// ----------------------------------------------------------------------------------------------------
function showCoShareStatementDetails(input){
let pt_id = $(input).data('id');
console.log('pt_id', pt_id)
var myModal = new bootstrap.Modal(document.getElementById('centermodal'));
myModal.show();
getCoShareStatementDetails(pt_id)
}
function getCoShareStatementDetails(pt_id){
let url = '<?= base_url('util/getCoShareStatementDetails/') ?>' + pt_id;
sendAjaxRequestForGlobal(url, 'GET', {}, function(response) {
console.log('Data fetched successfully:', response);
if (response.status === true) {
appendTableData(response.data)
} else {
toastr.warning(response.message, 'WARNING');
}
}, function(xhr, status, error) {
console.error('Error fetching data:', error);
console.error(xhr.responseText);
});
}
function appendTableData(data) {
// Ensure the table body selector matches your table's structure
let tableBody = $("#table_data");
// Clear the table body before appending new rows
tableBody.empty();
// Loop through the data and append rows
data.forEach(row => {
let tableRow = `
<tr>
<td>${row.stmt_sno ?? '-'}</td>
<td>${row.month ?? '-'}</td>
<td>${row.sum_of_actual_amt ?? '-'}</td>
<td>${row.invoice_no ?? '-'}</td>
<td>${row.invoice_date ?? '-'}</td>
<td>${row.invoice_status ?? '-'}</td>
</tr>
`;
tableBody.append(tableRow);
});
}
</script>

100
test.http
View File

@ -1,100 +0,0 @@
POST https://testtips.vidalhealthtpa.com:7443/mobilerest/vidalbrokerservices/submitClaim
Authorization: Basic dmlkYWxicm9rZXJsb2dpbjp2aWRhbHN0YWdlQDEyMw==
Cookie: JSESSIONID=678ofNbsfB8svK1lyV6rON3w.worker1
Content-Type: multipart/form-data; boundary=WebApiBoundary
--WebApiBoundary
Content-Disposition: form-data; name="username"
Web_api
--WebApiBoundary
Content-Disposition: form-data; name="password"
Web@api
--WebApiBoundary
Content-Disposition: form-data; name="policyNo"
CI/TEST/POLICY/123456
--WebApiBoundary
Content-Disposition: form-data; name="enrollmentId"
BLR-RG-H0351-043-0000002-A
--WebApiBoundary
Content-Disposition: form-data; name="typeOfClaim"
Main hospitalization claim
--WebApiBoundary
Content-Disposition: form-data; name="claimSubType"
Hospitalization
--WebApiBoundary
Content-Disposition: form-data; name="requestedAmount"
4500
--WebApiBoundary
Content-Disposition: form-data; name="ailmentType"
Non covid
--WebApiBoundary
Content-Disposition: form-data; name="admissionDate"
20-03-2025
--WebApiBoundary
Content-Disposition: form-data; name="dischargeDate"
23-03-2025
--WebApiBoundary
Content-Disposition: form-data; name="hospitalName"
A G HOSPITAL NEW
--WebApiBoundary
Content-Disposition: form-data; name="empanelmentNo"
HOS-PON-010427
--WebApiBoundary
Content-Disposition: form-data; name="documentType"
Claim
--WebApiBoundary
Content-Disposition: form-data; name="ailmentName"
Cold
--WebApiBoundary
Content-Disposition: form-data; name="hospitalAddress"
abc
--WebApiBoundary
Content-Disposition: form-data; name="hospitalState"
karnataka
--WebApiBoundary
Content-Disposition: form-data; name="hospitalCity"
bangalore
--WebApiBoundary
Content-Disposition: form-data; name="hospitalPinCode"
560036
--WebApiBoundary
Content-Disposition: form-data; name="hospitalPhoneNo"
7656879899
--WebApiBoundary
Content-Disposition: form-data; name="File"; filename="tracker.pdf"
Content-Type: application/pdf
< ./C:\Users\jvadi\Downloads\Tickets - Business Show_ Chennai (India) (06_11_2025 14_00_00) - vadivel.pdf
--WebApiBoundary--
// claim