diff --git a/README.md b/README.md index 8c8c98a2..b56458c2 100755 --- a/README.md +++ b/README.md @@ -8,4 +8,4 @@ From command propmt run the following cmds Run speeific method -`>php vendor/bin/phpunit tests\unit\PremiumCalculationTest.php --filter testPremiumCalculationWithPrimaryRackRateAndAdditionalRackRate` +`php vendor/bin/phpunit tests\unit\PremiumCalculationTest.php --filter testPremiumCalculationWithPrimaryRackRateAndAdditionalRackRate` diff --git a/app/Config/Autoload.php b/app/Config/Autoload.php index 6cdb37c7..c80f6c1c 100755 --- a/app/Config/Autoload.php +++ b/app/Config/Autoload.php @@ -99,5 +99,5 @@ class Autoload extends AutoloadConfig * @var string[] * @phpstan-var list */ - public $helpers = ['uuid','session','utility', 'form', 'url', 'oauth', 'fileupload', 'excel_import_export', 'file', 'drive']; + public $helpers = ['uuid','session','utility', 'form', 'url', 'oauth', 'fileupload', 'excel_import_export', 'file', 'drive','ExcelSanitizeHelper']; } diff --git a/app/Config/Routes.php b/app/Config/Routes.php index e0040a96..83992845 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -155,6 +155,7 @@ $routes->group("/employee", ["filter" => "authMVC"], function ($routes) { $routes->get("truncate/(:any)", "EmployeeController::truncateFileData/$1"); $routes->get("test-rack-rate", "EmployeeController::testRackRate"); $routes->post("test-rack-rate", "EmployeeController::testRackRate"); + $routes->get('test_members_list', 'EmployeeController::test_members_list'); }); $routes->group("/master", ["filter" => "authMVC"], function ($routes) { @@ -327,6 +328,13 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) { $routes->get('view_log/(:any)', 'EmployeeController::viewLog/$1'); $routes->get('download_log/(:any)', 'EmployeeController::downloadLog/$1'); $routes->post('checkDuplicateTableFieldValue', 'ClientController::checkDuplicateTableFieldValue'); + $routes->get('getCoShareStatementDetails/(:any)', 'PolicyTransactionController::getCoShareStatementDetails/$1'); + $routes->get('getClientPolicyDataBasedOnClientAndInsuer', 'PolicyTransactionController::getClientPolicyDataBasedOnClientAndInsuer'); + $routes->get('checkCDAmountForBasePremium', 'PolicyTransactionController::checkCDAmountForBasePremium'); + $routes->post('map_employees', 'EmployeeController::mapEmployees'); + $routes->post('get_data_for_mapping', 'EmployeeController::getDataForMapping'); + $routes->post('unmap_employees/(:num)', 'EmployeeController::unmapEmployees/$1'); + $routes->get('transformMailContent', 'LeadsController::transformMailContent'); }); $routes->group("policy_tranction", ["filter" => "authMVC"], function ($routes) { @@ -362,6 +370,8 @@ $routes->group("policy_tranction", ["filter" => "authMVC"], function ($routes) { $routes->get("deletePaymentEntry/(:any)", "PolicyTransactionController::deletePaymentEntry/$1"); $routes->get("downloadSampleInsurerStatement", "PolicyTransactionController::downloadSampleInsurerStatement"); $routes->get("getFileErr/(:any)", "PolicyTransactionController::getFileErr/$1"); + $routes->get("getInsurerStatementMonth", "PolicyTransactionController::getInsurerStatementMonth"); + $routes->get("deleteStatement/(:any)", "PolicyTransactionController::deleteStatement/$1"); }); }); @@ -372,9 +382,11 @@ $routes->group("leads", ["filter" => "authMVC"], function ($routes) { $routes->post("create", "LeadsController::createLead"); $routes->get("list/(:any)", "LeadsController::getLeadDataForEdit/$1"); $routes->get("sendMail", "LeadsController::sendMailWithAttachement"); + $routes->post("sendMail", "LeadsController::sendMailWithAttachement"); $routes->get("exportQCRandRFQ/(:any)", "LeadsController::exportQCRandRFQ/$1"); $routes->get("featchLeadDataAndInsertClient/(:any)", "LeadsController::featchLeadDataAndInsertClient/$1"); $routes->get("featchClientPolicyFromLead/(:any)", "LeadsController::featchClientPolicyFromLead/$1"); + }); $routes->group("rfq", ["filter" => "authMVC"], function ($routes) { @@ -388,6 +400,7 @@ $routes->get("driveListFiles", "GoogleDriveController::listFiles"); $routes->post('dmsSearch', 'PolicyTransactionController::dmsSearch', ['filter' => 'authMVC']); $routes->get('dmsSearch', 'PolicyTransactionController::dmsSearch', ['filter' => 'authMVC']); $routes->get('downloadGdriveFile', 'GoogleDriveController::downloadGdriveFile', ['filter' => 'authMVC']); +$routes->get('cli/sendZeptoMail', 'MasterController::testZeptoSMTP'); $routes->cli('cli/processjob', 'JobWorker::processJob'); $routes->cli('cli/processjobs', 'JobWorker::processJobs'); @@ -395,6 +408,7 @@ $routes->cli('cli/processjobs', 'JobWorker::processJobs'); $routes->get("processjob", "JobWorker::processJob"); $routes->cli('cli/new_gmail_token', 'MasterController::generateNewGmailAPIToken'); $routes->cli('cli/send_mail_cli', 'MasterController::testGmailAPIViaCLI'); +$routes->cli('cli/sendZeptoMail', 'MasterController::testZeptoSMTP'); $routes->cli('cli/check_bounce_mail_cli', 'MasterController::testCheckBounceMails'); $routes->cli('cli/app_check_list', 'MasterController::appCheckList'); $routes->cli('cli/new_gdrive_token', 'GoogleDriveController::generateNewGoogleDriveAccessToken'); diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index fcdd14e4..bdc61c70 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -484,7 +484,7 @@ class ClientController extends AdminController // Fetch associated insurer names and balances $balances = $this->clientPolicyModel->getBalances($id); $data['balances'] = $balances; - + // dd($data); echo view('layout/header', $headerData); echo view('client_deposit_list', $data); echo view('layout/footer'); @@ -521,7 +521,7 @@ class ClientController extends AdminController $data['clientData'] = $this->clientPolicyModel->getClientById($clientId); $data['deposiamount'] = $this->clientPolicyModel->getDepositSummary($clientId, $insurerId); - // dd($data['depositdata']); + // dd($data['insurerName']); // print_r($data['depositdata'] );die; // Load the view for the new list page; @@ -1051,7 +1051,7 @@ class ClientController extends AdminController $data['policy_status'] = 1; $data['inception_type'] = $this->request->getPost('inception_type') ? 2 : 1; $data['client_branch_id'] = $this->request->getPost('client_branch_id'); - $data['cd_ac_no'] = $this->request->getPost('cd_ac_no'); + $data['cd_ac_pk'] = $this->request->getPost('cd_ac_no'); $data['gst'] = $this->request->getPost('gst'); $data['disclaimer'] = $this->request->getPost('disclaimer'); $data['is_member_modify_allowed'] = $this->request->getPost('is_member_modify_allowed') ? 1 : 0; @@ -1091,7 +1091,7 @@ class ClientController extends AdminController $data['reminder_date'] = null; } - $data['created_by'] = get_session_userid(); + $data['created_by'] = get_session_userid(); $policy_tranction_data = [ @@ -1102,7 +1102,7 @@ class ClientController extends AdminController 'insurer_branch_id' => $insurerBranchId, 'issue_type' => 1, 'policy_no' => $this->request->getPost('policy_no'), - 'cd_ac_no' => $this->request->getPost('cd_ac_no'), + 'cd_ac_pk' => $this->request->getPost('cd_ac_no'), 'policy_issue_date' => date('Y-m-d'), 'policy_start_date' => change_date_format($this->request->getPost('policy_start_date'), 'd-m-Y', 'Y-m-d'), 'policy_end_date' => change_date_format($this->request->getPost('policy_end_date'), 'd-m-Y', 'Y-m-d'), @@ -1112,7 +1112,6 @@ class ClientController extends AdminController ]; - $insert = $this->clientPolicyModel->insert($data); if ($insert) { @@ -1139,6 +1138,7 @@ class ClientController extends AdminController public function editClientPolicy() { + // print_r('test'); die; $this->myLogger->logme('error', 'Client policy function called'); @@ -1182,13 +1182,12 @@ class ClientController extends AdminController $data['inception_type'] = $this->request->getPost('inception_type') ? 2 : 1; $data['enrolment_visibility'] = $this->request->getPost('enrolment_visibility') ? 1 : 0; $data['client_branch_id'] = $this->request->getPost('client_branch_id'); - $data['cd_ac_no'] = $this->request->getPost('cd_ac_no'); + $data['cd_ac_pk'] = $this->request->getPost('cd_ac_no'); $data['gst'] = $this->request->getPost('gst'); $data['disclaimer'] = $this->request->getPost('disclaimer'); $data['policy_start_date'] = change_date_format($this->request->getPost('policy_start_date'), 'd-m-Y', 'Y-m-d'); $data['policy_end_date'] = change_date_format($this->request->getPost('policy_end_date'), 'd-m-Y', 'Y-m-d'); $data['is_member_modify_allowed'] = $this->request->getPost('is_member_modify_allowed') ? 1 : 0; - if ($data['inception_type'] == 2) { $data['open_date'] = change_date_format($this->request->getPost('open_date'), 'd-m-Y', 'Y-m-d'); $data['close_date'] = change_date_format($this->request->getPost('close_date'), 'd-m-Y', 'Y-m-d'); @@ -3298,11 +3297,10 @@ class ClientController extends AdminController public function getClientAndBranchAndPolicy() { + // ---------for client----------------------------------------------------------------------------- + $clients = $this->clientModel->where('is_active', 1)->findAll(); - $vehicles = $this->vehicleModel - ->select('vehicle.*, clients.client_type') - ->join('clients', 'clients.id=vehicle.owner') - ->where('vehicle.is_active', 1)->findAll(); + $clientIds = array_column($clients, 'id'); // Fetch branches in a single query @@ -3311,6 +3309,29 @@ class ClientController extends AdminController ->where('is_active', 1) ->findAll(); + // -----------for vehicle --------------------------------------------------------------------------- + + $vehicles = $this->vehicleModel + ->select('vehicle.*, clients.client_type') + ->join('clients', 'clients.id=vehicle.owner') + ->where('vehicle.is_active', 1)->findAll(); + + // -----------for Insurer --------------------------------------------------------------------------- + + //fetch all insurer data + $insurers = $this->insurerModel->where('is_active', 1)->findAll(); + + //map the insurer primary key to column + $insurersIds = array_column($insurers, 'id'); + + // Fetch insurer branches in a single query + $insurerBranches = $this->insurerBranchModel + ->whereIn('insurer_id', $insurersIds) + ->where('is_active', 1) + ->findAll(); + + // -----------for Policy --------------------------------------------------------------------------- + // Fetch policies in a single query $policies = $this->clientPolicyModel ->select(" @@ -3329,16 +3350,26 @@ class ClientController extends AdminController ->where('client_policy.is_active', 1) ->findAll(); + // -------------------------------------------------------------------------------------- + $branchList = []; $policyList = []; $policyListByClient = []; $unitList = []; + $insurerBranchList = []; + //for client branch mapping to the client foreach ($branches as $branch) { $branchList[$branch['client_id']][] = $branch; $unitList[$branch['id']][] = json_decode($branch['units']); } + //for insurer branch mapping to the insurer + foreach ($insurerBranches as $branch) { + $insurerBranchList[$branch['insurer_id']][] = $branch; + } + + //for client policy mapping to the branch and client foreach ($policies as $policy) { $policyList[$policy['client_branch_id']][] = $policy; $policyListByClient[$policy['client_id']][] = $policy; @@ -3349,6 +3380,7 @@ class ClientController extends AdminController } } + //get policy count foreach ($clients as &$client) { $client['client_policy_count'] = $policyCount[$client['id']] ?? 0; } @@ -3361,6 +3393,8 @@ class ClientController extends AdminController 'branch_data' => $branchList, 'policy_data' => $policyList, 'policyListByClient' => $policyListByClient, + 'insurer_data' => $insurers, + 'insurer_branch_data' => $insurerBranchList, 'unit_data' => $unitList, ], 200); } else { @@ -3807,7 +3841,7 @@ class ClientController extends AdminController // dd($this->request); // $employeeRestController = new EmployeeServiceController(); - // $employeeRestController->employeesEnrollmentInsert(['file_id' => 721]); + // $employeeRestController->employeesOnboardPreprocess(['file_id' => 721]); // $r = Jobs::addJob(['job_name' => 'employeesEnrollmentInsert','payload' => ['file_id' => 721]]); @@ -3832,6 +3866,37 @@ class ClientController extends AdminController // $PolicyTransactionController = new PolicyTransactionController(); // $res = $PolicyTransactionController->validateInsurerStatement(['file_id' => '36']); + + // $empServiceController = new EmployeeServiceController(); + // $res = $empServiceController->excelFileDataValidation(['file_id' => '319']); + // dd($res); + + // $EmpDataServiceController = new EmpDataServiceController(); + // $EmpDataServiceController->importInceptionFileValidation(['file_id' => 160]); + + $EmpDataServiceController = new EmpDataServiceController(); + // $EmpDataServiceController->importInceptionUpdateTPAandUHID(['file_id' => 162]); + // $EmpDataServiceController->importInceptionFileValidation(['file_id' => 162]); + // $EmpDataServiceController->importDeletionValidation(['file_id' => 171]); + // $EmpDataServiceController->importDeletionUpdateEndorsementID(['file_id' => 171]); + $array = [ + "employeeIds" => ["12800", "12798", "12797", "12799"], + "client_id" => "159", + "client_policy_id" => "336", + "client_branch_id" => "126", + "cd_ac_no" => "Apple_123", + "endorsement_no" => "ENDORSEMENT_ID", + "count" => 4, + "event_name" => "deletion", + "policy_name" => "GMC", + "user_id" => "1" + ]; + + $EmpDataServiceController->cashDepositCalculationForDeletion($array); + + // $employeeRestController = new EmployeeServiceController(); + // $employeeRestController->employeesOnboardPreprocess(['file_id' => 757]); + } // ------------------------------------------------------------------------------------------------------- diff --git a/app/Controllers/DashboardController.php b/app/Controllers/DashboardController.php index 7c0ef32b..4df9136a 100755 --- a/app/Controllers/DashboardController.php +++ b/app/Controllers/DashboardController.php @@ -459,7 +459,7 @@ class DashboardController extends AdminController $mail_result = sendMailNotification::sendMailNotification('member_reminder_mail', $params); // dd($mail_result); // $this->myLogger->logme('error', 'Mail sent result: ' . json_encode($mail_result)); - $reminder_whole_mail[] = $mail_result[0]; + $reminder_whole_mail[] = $mail_result; } } @@ -550,7 +550,7 @@ class DashboardController extends AdminController // Send the mail notification $mail_result = sendMailNotification::sendMailNotification('member_reminder_mail', $params); // $this->myLogger->logme('error', 'Mail sent result: ' . json_encode($mail_result)); - $reminder_whole_mail[] = $mail_result[0]; + $reminder_whole_mail[] = $mail_result; } } diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php index 1e4366ca..62a4be3b 100755 --- a/app/Controllers/EmpDataServiceController.php +++ b/app/Controllers/EmpDataServiceController.php @@ -169,13 +169,13 @@ class EmpDataServiceController extends BaseController $cash_balance['balance'] = $balance['opening_bal']; } - // Calculate the total amount from the objects - $totals = 0; - foreach ($objects as $item) { - $totals = $totals + $item->total; - } - - $totals = round($totals, 2); + // Calculate the total amount from the objects + $totals = 0; + foreach ($objects as $item) { + $totals = $totals + $item->total; + } + + $totals = round($totals, 2); if($export_data['insurer_or_tpa'] == 'insurer') //check CD amt related issue for only insurer, not tpa { @@ -205,9 +205,6 @@ class EmpDataServiceController extends BaseController // Log the export file name $this->myLogger->logme('error', 'Inception export file name : {data}', ['data' => $export_data['file_name']]); - // remove existing batch file anf batch list data every time export - $this->removeOldExportInfoFromBatchFile($export_data); - // default excel header information $excel_header_columns = [ [ @@ -258,7 +255,7 @@ class EmpDataServiceController extends BaseController [ 'column_index' => 7, 'column_name' => 'DATE OF COVERAGE', - 'db_column_name' => 'date_coverage' + 'db_column_name' => 'date_of_coverage' ], [ 'column_index' => 8, @@ -368,7 +365,7 @@ class EmpDataServiceController extends BaseController [ 'column_index' => 7, 'column_name' => 'DATE OF COVERAGE', - 'db_column_name' => 'date_coverage' + 'db_column_name' => 'date_of_coverage' ], [ 'column_index' => 8, @@ -426,16 +423,48 @@ class EmpDataServiceController extends BaseController 'db_column_name' => 'total' ] ]; + + //for addition and dependent addition adding a ENDORSEMENT NO column + if(in_array($export_data['event_type'], ['addition', 'dependent_addition'])){ + $excel_header_columns[] = [ + 'column_index' => 18, + 'column_name' => 'ENDORSEMENT NO', + 'db_column_name' => '' + ]; + } + }else{ + // get excel export format structure array - $template_json = $this->clientPolicyModel - ->select('insurer_excel_export_template.jsoncolumns') - ->join('insurer_excel_export_template', 'insurer_excel_export_template.insurer_id = client_policy.insurer_id and insurer_excel_export_template.policy_type_id = client_policy.policy_type_id') - ->where('client_policy.id', $export_data['client_policy_id']) - ->where('insurer_excel_export_template.event_name', $export_data['event_type']) - ->where('insurer_excel_export_template.is_active', 1) //Live issue changes 17-10-2024 - ->where('insurer_excel_export_template.type_name', $export_data['actions']) - ->first(); + // $template_json = $this->clientPolicyModel + // ->select('insurer_excel_export_template.jsoncolumns') + // ->join('insurer_excel_export_template', 'insurer_excel_export_template.insurer_id = client_policy.insurer_id and insurer_excel_export_template.policy_type_id = client_policy.policy_type_id') + // ->where('client_policy.id', $export_data['client_policy_id']) + // ->where('insurer_excel_export_template.event_name', $export_data['event_type']) + // ->where('insurer_excel_export_template.is_active', 1) //Live issue changes 17-10-2024 + // ->where('insurer_excel_export_template.type_name', $export_data['actions']) + // ->first(); + + $sql = " + SELECT `insurer_excel_export_template`.`jsoncolumns` + FROM `client_policy` + JOIN `insurer_excel_export_template` + ON `insurer_excel_export_template`.`insurer_id` = `client_policy`.`insurer_id` + AND `insurer_excel_export_template`.`policy_type_id` = + CASE + WHEN `client_policy`.`policy_type_id` IN (2, 3, 4, 5) THEN 2 + ELSE `client_policy`.`policy_type_id` + END + WHERE `client_policy`.`id` = '".$export_data['client_policy_id']."' + AND `insurer_excel_export_template`.`event_name` = '".$export_data['event_type']."' + AND `insurer_excel_export_template`.`is_active` = 1 + AND `insurer_excel_export_template`.`type_name` = '".$export_data['actions']."' + LIMIT 1"; + + $query = db_connect()->query($sql); + $template_json = $query->getRowArray(); + + // dd(db_connect()->getLastQuery()); if(!empty($template_json) && $template_json != null){ $excel_header_columns = json_decode($template_json['jsoncolumns'], true); @@ -444,6 +473,10 @@ class EmpDataServiceController extends BaseController } } + // remove existing batch file anf batch list data every time export + $this->removeOldExportInfoFromBatchFile($export_data); + + //convert the excel data based on the insurer $excel_data_info = generate_insurer_based_excel($excel_header_columns, $objects); // Generate Excel file @@ -1256,6 +1289,7 @@ class EmpDataServiceController extends BaseController $this->myLogger->logme('info', 'Inception File Validation -- Function called'); $file_id = $params['file_id']; + // dd($file_id); $this->myLogger->logme('error', 'Inception File Validation -- Batch File Table Primary ID : {data}', ['data' => $file_id]); @@ -1288,30 +1322,36 @@ class EmpDataServiceController extends BaseController // array_pop($excel_data); $inceptionHeader = [ - 'S.No', - 'NAME OF EMP/DEP', - 'EMP ID', - // 'EMP/DEP TYPE', - // 'RELATIONSHIP CODE', - 'DOB', - 'GENDER', - 'PRE EXISTING AILMENTS', - 'BASIC COVER SI', - 'DATE OF COVERAGE', - 'AGE', - 'RELATIONSHIP', - 'REMARKS', - 'POLICY END DATE', - 'NO OF DAYS', - 'TPA ID', - 'UHID', - // 'PREMIUM', - 'PRO RATA PREMIUM', - 'GST', - 'TOTAL AMOUNT' - ]; + 'S.No', + 'NAME OF EMP/DEP', + 'EMP ID', + // 'EMP/DEP TYPE', + // 'RELATIONSHIP CODE', + 'DOB', + 'GENDER', + 'PRE EXISTING AILMENTS', + 'BASIC COVER SI', + 'DATE OF COVERAGE', + 'AGE', + 'RELATIONSHIP', + 'REMARKS', + 'POLICY END DATE', + 'NO OF DAYS', + 'TPA ID', + 'UHID', + // 'PREMIUM', + 'PRO RATA PREMIUM', + 'GST', + 'TOTAL AMOUNT', + ]; + if(in_array($file['event_type'], ['addition', 'dependent_addition'])){ + $inceptionHeader[] = 'ENDORSEMENT NO'; + } + + // dd($inceptionHeader); foreach ($inceptionHeader as $key => $value) { + if($excel_header[$key] != $value){ $data = [ 'status' => 'failed-5', @@ -1330,46 +1370,9 @@ class EmpDataServiceController extends BaseController $emp_count = count($excel_data); + //get the employee data for excel file validation $employee_data = $this->employeePolicyModel->getInceptionEmployeeDataForExportExcel($ref_data, 1); - // ->select(' - - // employee_polices.id as emp_policy_id, - // employees.name AS emp_name, - // employees.emp_code AS emp_code, - // "Has Define" as emp_type, - // employees.relationship_code AS emp_relationship_code, - // employees.dob AS emp_dob, - // employees.gender AS emp_gender, - // employee_polices.pre_existing_alignments, - // employee_polices.basic_cover_si, - // employee_polices.date_coverage, - // TIMESTAMPDIFF(YEAR, employees.dob, CURDATE()) AS emp_age, - // employees.relationship AS emp_relationship, - // employees.change_event AS change_event, - // employee_polices.policy_end_date, - // employee_polices.days, - // employee_polices.tpa_id, - // employee_polices.uhid, - // employee_polices.premium, - // employee_polices.rata_premimum, - // employee_polices.gst, - // (employee_polices.rata_premimum + employee_polices.gst) AS total - // ') - - // ->join('employees', 'employees.id = employee_polices.employee_id') - // ->where('employee_polices.client_policy_id', $client_policy_id) - // ->where('employees.client_id', $client_id) - // ->where('employees.client_branch_id', $client_branch_id) - // ->where("employee_polices.{$id} IS NULL OR employee_polices.{$id} = ''") - // ->where('employee_polices.is_active', 1) - // ->where('employee_polices.status', 'active') - // ->where('employees.is_active', 1) - // ->where('employees.emp_status', 'active') - // ->findAll(); - - - if ($employee_data == null || empty($employee_data)) { if ($insurer_or_tpa == 'tpa') { @@ -1402,7 +1405,6 @@ class EmpDataServiceController extends BaseController } $this->myLogger->logme('error', 'Inception File Validation -- UHID or TPAID already updated or the uploadedfile is not correct'); - } $excel_data_count = count($excel_data); @@ -1423,7 +1425,6 @@ class EmpDataServiceController extends BaseController $this->myLogger->logme('error', 'Inception File Validation -- excel file count partially : {data}', ['data' => $partially_updated_data]); } - if ($emp_data_count < $excel_data_count) { $data = [ @@ -1453,17 +1454,22 @@ class EmpDataServiceController extends BaseController } if ($insurer_or_tpa == 'tpa') { + if ($excel_data[$key][13] === null) { $missing_id[$key][] = [ 'row' => $key, - 'column' => 15, + 'column' => 13, + 'db_data' => "TPA ID is Must", + 'excel_data' => $excel_data[$key][13] ]; } } else if ($insurer_or_tpa == 'insurer') { if ($excel_data[$key][14] === null) { $missing_id[$key][] = [ 'row' => $key, - 'column' => 16, + 'column' => 14, + 'db_data' => "UHID or Risk ID is Must", + 'excel_data' => $excel_data[$key][14] ]; } } @@ -1569,6 +1575,7 @@ class EmpDataServiceController extends BaseController } if ($emp_value['gst'] != $excel_data[$key][16]) { + $errors[$key][] = [ 'row' => $key, 'column' => 16, @@ -1610,7 +1617,7 @@ class EmpDataServiceController extends BaseController $missing_id_count = count($missing_id); $json_missing_id = json_encode($missing_id); - // dd($error_count, $missing_id_count, $json_errors, $json_missing_id); + // dd($error_count, $missing_id_count, $json_errors, $json_missing_id, $employee_data, $excel_data); if ($missing_id_count > 0) { @@ -1695,6 +1702,7 @@ class EmpDataServiceController extends BaseController $file_id = $params['file_id']; $file = $this->batchFileModel->find($file_id); + // dd($file); if (!$file) { @@ -1727,22 +1735,20 @@ class EmpDataServiceController extends BaseController ->first(); $get_policy_type = $this->clientPolicyModel - ->select('policy_type.policy_type, policies.policy_type_id as policy_type_id') - ->join('policies', 'policies.id = client_policy.policy_id') - ->join('policy_type', 'policy_type.id = policies.policy_type_id') + ->select('client_policy.*, policy_type.policy_type') + ->join('policy_type', 'policy_type.id = client_policy.policy_type_id', 'left') ->where('client_policy.id', $client_policy_id) ->first(); + // dd($get_policy_type); $status_val = 'success'; if ($status == 'in-progress-partially') { - $status_val = 'partially success'; } $this->myLogger->logme('error', 'Inception Update TPA and UHID -- file name : {data}', ['data' => $file['file_name']]); - $file_name_with_path = WRITEPATH . "/uploads/import_excel/" . $file['file_name']; $excel_data = $this->readExcelFileToArray($file_name_with_path); unset($excel_data[0]); // Remove header row @@ -1753,10 +1759,15 @@ class EmpDataServiceController extends BaseController $emp_details = []; $tpa_id = []; $uhid = []; + $emp_endorsement_table_data = []; + $enrollment_file_id = null; + $endorsement_id = null; $emp_count = count($excel_data); $db = \Config\Database::connect(); + // print_rr($excel_data); die; + foreach ($excel_data as $key => $value) { $name = $value[1]; @@ -1796,11 +1807,54 @@ class EmpDataServiceController extends BaseController $emp_details[] = array('id' => $result['id'], 'tpa_id' => $value[13], 'uhid' => $value[14]); } + //for addition and dependent_addition endorsement , endorsement_id update functionality + if(in_array($file['event_type'], ['addition', 'dependent_addition']) && isset($value[18])){ + + $action = 'a'; + if($file['event_type'] == "dependent_addition"){ + $action = 'da'; + } + + $endorsement_id = $value[18]; + + $result_for_endorsement = $this->empEndorsementModel + ->select('emp_endorsement.*, employees.id as emp_id, employee_polices.id as emp_policy_id') + ->join('employee_polices', 'employee_polices.id = emp_endorsement.pk') + ->join('employees', 'employees.emp_code = emp_endorsement.emp_code') + ->where('employees.emp_code', $emp_code) + ->where('employees.name', $name) + ->where('employees.client_id', $client_id) + ->where('employees.client_branch_id', $client_branch_id) + ->where('emp_endorsement.actions', $action) + ->where('employee_polices.client_policy_id', $client_policy_id) + ->where('employee_polices.is_active', 1) + ->where('employee_polices.status', 'active') + ->where('employees.is_active', 1) + ->where('employees.emp_status', 'active') + ->where('(emp_endorsement.endorsement_id IS NULL OR emp_endorsement.endorsement_id = "")') + ->groupBy('emp_endorsement.group_key') + ->first(); + + if (!empty($result_for_endorsement) && count($result_for_endorsement)) { + $enrollment_file_id = $result_for_endorsement['file_id']; //files table primary key + $emp_endorsement_table_data[] = array('id' => $result_for_endorsement['id'], 'group_key' => $result_for_endorsement['group_key'], 'endorsement_id' => $value[18], 'status' => 'complete'); + } + } + } + } + // dd($emp_endorsement_table_data, $enrollment_file_id); + + //update the employee policy data (TPAID or UHID) $return = $this->employeePolicyModel->bulkUpdate($emp_details); + if(in_array($file['event_type'], ['addition', 'dependent_addition']) && !empty($emp_endorsement_table_data)){ + $this->employeePolicyModel->updateEmpEndorsementAddition($emp_endorsement_table_data); + $this->storeEndorsementNumber($file_id, $endorsement_id, $enrollment_file_id); + } + // Update batch file status and amount $this->batchFileModel->update($file_id, [ 'count' => $emp_count, @@ -1836,7 +1890,7 @@ class EmpDataServiceController extends BaseController 'client_id' => $client_id, 'client_policy_id' => $client_policy_id, 'cd_ac_no' => $CD_Account_Number['cd_ac_no'] ?? null, - 'endorsement_no' => null, + 'endorsement_no' => $endorsement_id, 'client_branch_id' => $client_branch_id, 'count' => $emp_count, 'event_name' => $file['event_type'], @@ -1954,12 +2008,14 @@ class EmpDataServiceController extends BaseController ->where("employees.is_active", 1) ->where("employees.emp_status", "active") ->where("emp_endorsement.actions", "c") + ->where("emp_endorsement.is_active", 1) + ->where("emp_endorsement.status !=", "truncated") ->where("(emp_endorsement.endorsement_id IS NULL OR emp_endorsement.endorsement_id = '')") ->findAll(); - // dd($endorsement_data, $excel_data); + dd($endorsement_data, $excel_data); if ($endorsement_data == null || empty($endorsement_data)) { @@ -2225,6 +2281,7 @@ class EmpDataServiceController extends BaseController $emp_details = []; $endorsement_id = []; $endorsement_details = []; + $enrollment_file_id = null; $emp_count = count($excel_data); $db = \Config\Database::connect(); @@ -2237,7 +2294,6 @@ class EmpDataServiceController extends BaseController $endorsement_id[] = $value[10]; $uhid = $value[1]; - $result = $this->empEndorsementModel ->select('emp_endorsement.*, employees.id as emp_id') ->join('employees', 'employees.id = emp_endorsement.pk') @@ -2253,11 +2309,13 @@ class EmpDataServiceController extends BaseController ->where('employee_polices.status', 'active') ->where('employees.is_active', 1) ->where('employees.emp_status', 'active') + ->where("emp_endorsement.is_active", 1) + ->where("emp_endorsement.status !=", "truncated") ->first(); if (isset($result['id']) && $result['id'] !== null) { - // return $result; + $enrollment_file_id = $result['file_id']; $emp_details[] = array('id' => $result['emp_id'], $result['field_name'] => $value[8]); $endorsement_details[] = array('group_key' => $result['group_key'], 'id' => $result['id'], 'endorsement_id' => $value[10], 'status' => 'complete'); } @@ -2268,7 +2326,7 @@ class EmpDataServiceController extends BaseController $this->empEndorsementModel->updateBatch($endorsement_details, 'group_key'); $this->employeePolicyModel->bulkUpdateForCorrection($emp_details); - $this->storeEndorsementNumber($file_id, $endorsement_id[0]); + $this->storeEndorsementNumber($file_id, $endorsement_id[0], $enrollment_file_id); // Update batch file status and amount @@ -2782,6 +2840,7 @@ class EmpDataServiceController extends BaseController $employeeIds = []; $emp_details = []; $endorsement_id = ''; + $enrollment_file_id = ''; $endorsement_details = []; $totals = 0; @@ -2813,6 +2872,8 @@ class EmpDataServiceController extends BaseController ->first(); if (isset($result['id']) && $result['id'] !== null) { + + $enrollment_file_id = $result['file_id']; $emp_policy_ids[] = array('id' => $result['emp_policy_id'], 'is_active' => 0); $employeeIds[] = $result['emp_policy_id']; $endorsement_details[] = array('id' => $result['id'], 'group_key' => $result['group_key'], 'endorsement_id' => $value[19], 'status' => 'complete'); @@ -2872,7 +2933,7 @@ class EmpDataServiceController extends BaseController // } $this->employeePolicyModel->bulkUpdateForEndorsement($endorsement_details); - $this->storeEndorsementNumber($file_id, $endorsement_id); + $this->storeEndorsementNumber($file_id, $endorsement_id, $enrollment_file_id); // Update batch file status and amount @@ -2957,7 +3018,7 @@ class EmpDataServiceController extends BaseController // array_pop($excel_data); $headers = ['S.No','EMP ID','EMP NAME','DOB','GENDER','RELATIONSHIP','SUM INSURED','Date of Leaving','Policy End Date','No Of Days','Premium','Pro Rata Premium','GST','Total','Claim Status','ENDORSEMENT_ID']; - + // dd($headers, $excel_header); foreach ($headers as $key => $value) { if($excel_header[$key] != $value){ @@ -3289,6 +3350,7 @@ class EmpDataServiceController extends BaseController $employee_policy_table_data = []; $employee_policy_table_primaryKey = []; $endorsement_id = ''; + $enrollment_file_id = null; //files table primary key $totals = 0; @@ -3309,13 +3371,16 @@ class EmpDataServiceController extends BaseController 'emp_name' => $emp_name, 'emp_code' => $emp_code ]; + $result = $this->employeePolicyModel->fetchEmpEndorsementData($fetch_data); + // dd($result, db_connect()->getLastQuery()); if (isset($result['emp_endorsement_primarykey']) && $result['emp_endorsement_primarykey'] !== null) { + $enrollment_file_id = $result['file_id']; //files table primary key $employee_policy_table_primaryKey[] = $result['emp_policy_primarykey']; //for cash deposite - $employee_policy_table_data[] = array('id' => $result['emp_policy_primarykey'], 'date_of_exit' => $result['date_of_exit'], 'reason_for_exit' => $result['reason_for_exit'], 'status' => $result['status']); - $employees_table_data[] = array('id' => $result['employees_id'], 'emp_status' => $result['status']); + $employee_policy_table_data[] = array('id' => $result['emp_policy_primarykey'], 'date_of_exit' => $result['date_of_exit'], 'reason_for_exit' => $result['reason_for_exit'], 'claim_status' => $result['claim_status'], 'status' => $result['status']); + // $employees_table_data[] = array('id' => $result['employees_id'], 'emp_status' => $result['status']); $emp_endorsement_table_data[] = array('id' => $result['emp_endorsement_primarykey'], 'group_key' => $result['group_key'], 'endorsement_id' => $value[15], 'status' => 'complete'); } @@ -3327,11 +3392,10 @@ class EmpDataServiceController extends BaseController // dd($employees_table_data, $emp_endorsement_table_data, $employee_policy_table_data, $employee_policy_table_primaryKey, $totals, $emp_count); - // Check if $employees_table_data is null or empty - if (empty($employees_table_data)) { - return ['status' => 'error', 'message' => 'Employees table data is empty or null.']; - } + // if (empty($employees_table_data)) { + // return ['status' => 'error', 'message' => 'Employees table data is empty or null.']; + // } // Check if $employee_policy_table_data is null or empty if (empty($employee_policy_table_data)) { @@ -3343,10 +3407,10 @@ class EmpDataServiceController extends BaseController return ['status' => 'error', 'message' => 'Employee endorsement table data is empty or null.']; } - $this->employeeModel->updateBatch($employees_table_data, 'id'); + // $this->employeeModel->updateBatch($employees_table_data, 'id'); $this->employeePolicyModel->updateBatch($employee_policy_table_data, 'id'); $this->employeePolicyModel->bulkUpdateForEndorsement($emp_endorsement_table_data); - $this->storeEndorsementNumber($file_id, $endorsement_id); + $this->storeEndorsementNumber($file_id, $endorsement_id, $enrollment_file_id); // Update batch file status and amount $this->batchFileModel->update($file_id, [ @@ -3355,12 +3419,12 @@ class EmpDataServiceController extends BaseController 'amount' => $rounded_totals, ]); - $this->myLogger->logme('error', 'Deletion Update Endorsement ID -- Employee count : {data}', ['data' => $emp_count]); $this->myLogger->logme('error', 'Deletion Update Endorsement ID -- Batch File status : {data}', ['data' => $status_val]); //call the cash deposite function if ($file['insurer_or_tpa'] == 'insurer') { + $policy_name = $this->getPolicyNameUsingClientPolicyId($client_policy_id); $job_details = new Jobs(); $r = Jobs::addJob(['job_name' => 'cashDepositCalculationForDeletion', 'payload' => [ @@ -3816,7 +3880,8 @@ class EmpDataServiceController extends BaseController foreach($units as $unit) { - + $client_policy_id = $arrayData['client_policy_id']; + $cd_ac_pk = $this->clientPolicyModel->select('cd_ac_pk')->where('id',$client_policy_id)->first(); $amount = $this->employeePolicyModel->query(" SELECT SUM(rata_premimum + gst) AS total_sum FROM employee_polices @@ -3844,6 +3909,7 @@ class EmpDataServiceController extends BaseController 'updated_by' => $arrayData['user_id'], 'event_name' => $arrayData['event_name'], 'is_active' => 1, + 'cd_ac_pk' => $cd_ac_pk['cd_ac_pk'] ]; $response = DepositHelper::saveDeposit($data, $arrayData['user_id']); @@ -3900,6 +3966,7 @@ class EmpDataServiceController extends BaseController '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']); @@ -3935,7 +4002,7 @@ class EmpDataServiceController extends BaseController // dd($client_branch_data, $units); $get_insurer_id_from_client_policy = db_connect()->table('client_policy') - ->select('insurer_id') + ->select('insurer_id,cd_ac_pk') ->where('id', $arrayData['client_policy_id']) ->get() ->getRowArray(); @@ -3988,10 +4055,11 @@ class EmpDataServiceController extends BaseController WHERE employee_polices.id IN (" . implode(',', $arrayData['employeeIds']) . ") AND emp_endorsement.pk IN (" . implode(',', $arrayData['employeeIds']) . ") + AND employee_polices.claim_status = 0 AND emp_endorsement.field_name = 'date_of_exit' ")->getRow(); - // dd(db_connect()->getLastQuery(), $amount); + dd(db_connect()->getLastQuery(), $amount); if($amount){ @@ -4012,6 +4080,7 @@ class EmpDataServiceController extends BaseController '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']); @@ -4485,7 +4554,7 @@ class EmpDataServiceController extends BaseController $this->messageModel->insert($msg_data); } - public function storeEndorsementNumber($file_id, $endorsement_no) + public function storeEndorsementNumber($file_id, $endorsement_no, $enrollment_file_id) { // Log the function entry with input parameters $this->myLogger->logme('error', "storeEndorsementNumber --- Starting function with file_id: $file_id and endorsement_no: $endorsement_no"); @@ -4521,6 +4590,7 @@ class EmpDataServiceController extends BaseController 'insurer_id' => $filedata['insurer_id'], 'tpa_id' => $filedata['tpa_id'], 'endorsement_no' => $endorsement_no, + 'file_id' => $enrollment_file_id, 'endorsement_type' => $filedata['event_type'], 'created_by' => $filedata['created_by'], ]); diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php index 7721b203..6079b293 100755 --- a/app/Controllers/EmployeeController.php +++ b/app/Controllers/EmployeeController.php @@ -24,6 +24,7 @@ use App\Models\TPAModel; use App\Models\InsurerExcelExportTemplateModel; use App\Models\InsurerModel; use App\Models\ClientDepositModel; +use App\Models\PolicyPremium2Model; use App\Controllers\Jobs; @@ -40,7 +41,7 @@ use PhpOffice\PhpSpreadsheet\Writer\Xlsx; use Dompdf\Dompdf; use Dompdf\Options; - +use Kint; class EmployeeController extends AdminController { @@ -62,6 +63,7 @@ class EmployeeController extends AdminController protected $excelExportTemplateModel; protected $insurerModel; protected $cashDepositModel; + protected $PolicyPremium2Model; public function __construct() { @@ -81,6 +83,7 @@ class EmployeeController extends AdminController $this->policiesModel = new PolicesModel(); $this->insurerModel = new InsurerModel(); $this->cashDepositModel = new ClientDepositModel(); + $this->PolicyPremium2Model = new PolicyPremium2Model(); } public function list() @@ -108,7 +111,7 @@ class EmployeeController extends AdminController emp_name : $filterData['emp_name'] ?? null, status : $filterData['status'] ?? [], ); - log_message('error',json_encode($data['employees'])); + // log_message('error',json_encode($data['employees'])); // Set getData in $data array with the processed $filterData $data['getData'] = $filterData; } @@ -207,7 +210,9 @@ class EmployeeController extends AdminController // $this->fileModel->where('id', '12')->set(['status' => 'failed','reason' => $failure_reason])->update(); // dd($failure_reason); // } - + // $this->truncateFileData(747, 5) ; + // print_rr($this->cloneWorksheet()); + // die(); if ($this->request->getMethod() == 'post') { //validate uploaded file @@ -1224,24 +1229,26 @@ class EmployeeController extends AdminController public function truncateFileData($file_id, $role_id = null) { $file_id = $this->request->uri->getSegment(3); - // $file_id = 112; + // $file_id = 747; $file = $this->fileModel->find($file_id); $client_id = $file['client_id']; $client_policy_id = $file['policy_id']; $loggedInUserID = get_session_userid(); $policy_data = $this->clientPolicyModel->where('id', $client_policy_id)->first(); + $cd_tranction = $this->cashDepositModel - ->where('client_id', $client_id) - ->where('insurer_id', $policy_data['insurer_id']) - ->where('event_name',$file['action']) - ->where('client_policy_id', $client_policy_id) + ->where('client_id', $client_id) //client + ->where('insurer_id', $policy_data['insurer_id']) //insurer + ->where('event_name',$file['action']) //event + ->where('client_policy_id', $client_policy_id)//policy ->orderBy('id', 'desc') ->first(); + // $file['action'] = 'si_enhancement'; // $result = []; - // !dd($file); + // dd($file); if ($file['action'] == 'inception' || $file['action'] == 'dependent_addition' || $file['action'] == 'addition' || $file['action'] == 'enrollment' || $file['action'] == 'missed_inception') { @@ -1251,6 +1258,7 @@ class EmployeeController extends AdminController $result = $this->employeeModel->getEmpListByFileId(file_id: $file_id, emp_status: ['active'], policy_status: ['active']); } + $result = []; // ~dd($result); if (count($result) && $role_id == null) { if(get_role_id() == 1 || get_role_id() == 5){ @@ -1260,21 +1268,116 @@ class EmployeeController extends AdminController } } else { - //update emp and emp plocies - $db = db_connect(); - $query = "UPDATE employees JOIN employee_polices ON employees.id = employee_polices.employee_id and employees.file_id = $file_id SET employees.emp_status = 'truncated', employee_polices.status = 'truncated', employees.is_active = 0,employee_polices.is_active = 0 WHERE employees.file_id = $file_id"; - $db->query($query); - $affectedRows = $db->affectedRows(); - // print_r($db->getLastQuery()); die; - // $affectedRows = 10; + $this->myLogger->logme('error', 'TRUNCATED STARTED WITH ADMIN OR HEAD PERMISSION'); + $this->myLogger->logme('error', 'Event Type : -- {data} --', ['data' => $file['action']]); - //update file status - $this->fileModel->where('id', $file_id)->set(['status' => 'truncated'])->update(); + // GET THE CD AMOUND + //get cd amount for the particular file id to reverse entry to the cash deposite + $cd_amount = $cd_tranction['amount']; + if(in_array($file['action'], ['addition', 'dependent_addition'])){ + $cd_amount_total = $this->employeePolicyModel->getAdditionDataForTruncated($file_id, $file['action']); + // dd($cd_amount_total); + $cd_amount = $cd_amount_total['total']; + + $this->myLogger->logme('error', 'Addition or Dependent Addition CD Amount : {data}', ['data' => $cd_amount]); + } + + $this->myLogger->logme('error', 'CD Amount : {data}', ['data' => $cd_amount]); + + + if($file['action'] != 'enrollment') + { + //STEP: 1 - Update employee policy table + //update emp and emp plocies + $db = db_connect(); + $query = " + UPDATE employee_polices + JOIN employees ON employees.id = employee_polices.employee_id + SET employee_polices.status = 'truncated', employee_polices.is_active = 0 + WHERE employees.file_id = $file_id + "; + + $db->query($query); + $affectedRows = $db->affectedRows(); + $this->myLogger->logme('error', 'employee_polices table update query : {data}', ['data' => $query]); + $this->myLogger->logme('error', 'employee_polices table updated - Affected Rows : {data}', ['data' => $affectedRows]); + // print_r($db->getLastQuery()); die; + // $affectedRows = 10; + + //STEP:2 - Update emp_endorsement Table + //update truncated status and is_active 0 to the Emp_endorsement table + if(in_array($file['action'], ['addition', 'dependent_addition'])){ + $this->empEndorsementModel->where('file_id', $file_id) + ->set(['status' => 'truncated','is_active' => 0]) + ->update(); + + $this->myLogger->logme('error', 'emp_endorsement table updated'); + } + + //STEP:3 - Update files table + //update file status + $this->fileModel->where('id', $file_id)->set(['status' => 'truncated'])->update(); + $this->myLogger->logme('error', 'files table updated'); + } + else + { + // echo 'came here...1'; + //check all dependents added by self and other dependent policies + $emp_codes = $this->employeeModel->select('emp_code') + ->where('file_id', $file_id) + ->findAll(); + $emp_codes = array_column($emp_codes,'emp_code'); + // Kint::dump($emp_codes);//die; + + $dependent_policies = $this->clientPolicyModel->select('id') + ->where('base_policy', $client_policy_id) + ->findAll(); + // $dependent_policies = [ [10],[25],[35] ]; + // Kint::dump($dependent_policies); + // Kint::dump(array_column($dependent_policies,'id')); + if(count($dependent_policies)) + { + $dependent_policies = array_column($dependent_policies,'id'); + // Kint::dump($dependent_policies); + $second_level_dependent_policies = $this->clientPolicyModel->select('id') + ->whereIn('base_policy', $dependent_policies) + ->findAll(); + // dd($second_level_dependent_policies); + if(count($second_level_dependent_policies)) + { + $second_level_dependent_policies = array_column($second_level_dependent_policies,'id'); + } + + $dependent_policies = array_merge($dependent_policies,$second_level_dependent_policies); + } + $dependent_policies = array_merge($dependent_policies,[$client_policy_id]); + // Kint::dump($dependent_policies); + + //update emp and emp plocies + $db = db_connect(); + $emp_codes = '(' . implode(',', array_map(fn($code) => "'$code'", $emp_codes)) . ')'; + $dependent_policies = '(' . implode(',', $dependent_policies) . ')'; + $query = " + UPDATE employee_polices + JOIN employees ON employees.id = employee_polices.employee_id and employees.emp_code in $emp_codes + SET employee_polices.status = 'truncated', employee_polices.is_active = 0 + WHERE employee_polices.client_policy_id in $dependent_policies + "; + $db->query($query); + $affectedRows = $db->affectedRows(); + + // dd($affectedRows); + $affectedRows = $affectedRows * 2; + $this->fileModel->where('id', $file_id)->set(['status' => 'truncated'])->update(); + + } + + //FINAL STEP - Update reverse entry in cash_deposite table if($cd_tranction){ $cd_data = [ - 'amount' => $cd_tranction['amount'], + 'amount' => $cd_amount, 'sub_type_id' => 8, 'endorsement_no' => null, 'insurer_id' =>$policy_data['insurer_id'], @@ -1284,12 +1387,17 @@ class EmployeeController extends AdminController 'client_id' => $client_id, 'client_policy_id' => $client_policy_id, 'cd_ac_no' => $policy_data['cd_ac_no'] ?? null, + 'cd_ac_pk' => $policy_data['cd_ac_pk'] ?? null, 'event_name' => $file['action'], ]; $response = DepositHelper::saveDeposit($cd_data, $loggedInUserID); + $this->myLogger->logme('error', 'cash_deposite table updated -- cd transaction'); + } + $this->myLogger->logme('error', 'SUCCESSFULLY TRUNCATED'); + return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => round($affectedRows / 2)], 200); } @@ -1306,23 +1414,57 @@ class EmployeeController extends AdminController // print_r($this->empEndorsementModel->getLastQuery()); // echo $res[0]->count;die(); + if ($res[0]->count == 0 || $role_id == 5 || $role_id == 1) { - //update truncated status to db + + $this->myLogger->logme('error', 'TRUNCATED STARTED WITH ADMIN OR HEAD PERMISSION'); + $this->myLogger->logme('error', 'Event Type : -- {data} --', ['data' => $file['action']]); + + $transaction_type = 'Credit'; + $cd_amount = $cd_tranction['amount']; + + if($file['action'] == 'deletion'){ + $transaction_type = 'Debit'; + //get cd amount for the particular file id to reverse entry to the cash deposite for only deletion + $cd_amount_total = $this->employeePolicyModel->getDeletionDataForTruncated($file['id']); + $totalSum = array_sum(array_column($cd_amount_total, 'total')); + $cd_amount = $totalSum; + + $this->myLogger->logme('error', 'Deletion CD Amount : {data}', ['data' => $cd_amount]); + } + + $this->myLogger->logme('error', 'Endorsemnt CD Amount : {data}', ['data' => $cd_amount]); + + + //STEP 1: + //update truncated status to the Emp_endorsement table $this->empEndorsementModel->where('file_id', $file_id) - ->set(['status' => 'truncated']) + ->set(['status' => 'truncated','is_active' => 0]) ->update(); - //update file status + + $this->myLogger->logme('error', 'emp_endorsement table updated'); + + //STEP 2: + if($file['action'] == 'deletion') { + //update the employee policy table reverse the data + $this->employeePolicyModel->updateEmployeePolicyTruncateReverse($file_id); + $this->myLogger->logme('error', 'employee_polices table updated for deletion'); + } + + if($file['action'] == 'correction'){ + + } + + // STEP 3: + //update files table status to "truncated" $this->fileModel->where('id', $file_id)->set(['status' => 'truncated'])->update(); + $this->myLogger->logme('error', 'files table updated'); + if($cd_tranction && $file['action'] != 'correction'){ - $transaction_type = 'Credit'; - if($file['action'] == 'deletion'){ - $transaction_type = 'Debit'; - } - $cd_data = [ - 'amount' => $cd_tranction['amount'], + 'amount' => $cd_amount, 'sub_type_id' => 8, 'endorsement_no' => null, 'insurer_id' =>$policy_data['insurer_id'], @@ -1332,13 +1474,19 @@ class EmployeeController extends AdminController 'client_id' => $client_id, 'client_policy_id' => $client_policy_id, 'cd_ac_no' => $policy_data['cd_ac_no'] ?? null, + 'cd_ac_pk' => $policy_data['cd_ac_pk'] ?? null, 'event_name' => $file['action'], ]; $response = DepositHelper::saveDeposit($cd_data, $loggedInUserID); + $this->myLogger->logme('error', 'cash_deposite table updated -- cd transaction'); + } + $this->myLogger->logme('error', 'SUCCESSFULLY TRUNCATED'); + return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => 'success'], 200); + } else { if(get_role_id() == 1 || get_role_id() == 5){ return $this->respond(['role' => get_role_id(), 'dataStatus' => false, 'code' => 404, 'message' => 'File data already processed. Do you want to truncate data from uploaded file?'], 200); @@ -1642,14 +1790,18 @@ class EmployeeController extends AdminController $existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $client_id,client_branch_id: $branch_id); //get familiy details in inception file format array from post method $data = calculate_premium_new(family_data: $family_details,policy_terms:$policy_details,slab_details:$slab_details,fileArr: $file,existing_units: $existing_units); - + // print_rr($data);die(); foreach($data as $key => $member ) { // ~dd($member); - if(is_array($member)) + if(is_array($member) && isset($member['policy_details']['date_coverage']) && isset($member['policy_details']['policy_end_date']) ) { $data[$key]['policy_details']['no_of_days'] = $member['policy_details']['date_coverage'] ? (calculate_days_bw_dates($member['policy_details']['date_coverage'],$member['policy_details']['policy_end_date'])->days + 1) : ''; } + else + { + $data[$key]['policy_details']['no_of_days'] = '0'; + } } return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => ['new' => $data,'old' => $existing_famility_details], 200]); @@ -1762,7 +1914,7 @@ class EmployeeController extends AdminController public function update_emp_data() { $data = $this->request->getPost(); - // print_rr($data); + // print_rr($data);die(); // $data['dob'] = date('Y-m-d', strtotime($data['dob'])); $data['dob'] = change_date_format($data['dob'], 'd/m/Y', 'Y-m-d'); // print_rr($data); die; @@ -2021,4 +2173,163 @@ class EmployeeController extends AdminController exit; } + public function test_members_list(){ + // $model = new EmployeeModel(); + // $list = [ + // ['relationship' => 'spouse','emp_code' => 'TEST002', 'name' => 'Lakshmi','email_personal' => 'lakshmi@gmail.com','mobile'=>'6382156701','gender'=>'female','dob'=>'1996-05-19','doj'=>'2022-02-01','basic_pay'=>'100000','emp_status'=>'enrolled'], + // ['relationship' => 'Daughter','emp_code' => 'TEST002', 'name' => 'Jayalakshmi','email_personal' => 'jayalakshmi@gmail.com','mobile'=>'6382156701','gender'=>'female','dob'=>'2018-05-19','doj'=>'2022-02-01','basic_pay'=>'100000','emp_status'=>'enrolled'], + // ['relationship' => 'Son','emp_code' => 'TEST002', 'name' => 'Jayam Ravi','email_personal' => 'jayamravi@gmail.com','mobile'=>'6382156701','gender'=>'male','dob'=>'1994-05-19','doj'=>'2019-02-01','basic_pay'=>'100000','emp_status'=>'enrolled'], + // // ['relationship' => 'self','emp_code' => 'TEST003', 'name' => 'Ravi Shankar','email_personal' => 'srinivassaravanan2002@gmail.com','email_corporate'=>'srinivas.saravanan@venbainfotech.com','mobile'=>'6382156701','gender'=>'male','dob'=>'1994-05-19','doj'=>'2022-02-01','basic_pay'=>'100000','emp_status'=>'enrolled'] + // ['relationship' => 'spouse','emp_code' => 'TEST001', 'name' => 'Lakshmi','email_personal' => 'lakshmi@gmail.com','mobile'=>'6382156701','gender'=>'female','dob'=>'1996-05-19','doj'=>'2022-02-01','basic_pay'=>'100000','emp_status'=>'enrolled'], + + // ]; + // foreach($list as $listitem){ + + + // $model->insert($listitem); + // } + // die(); + $employee_data = $this->employeeModel->getTestEmployeeData(); + $data['employees'] = $employee_data; + $data['clients'] = $this->clientModel->findAll(); + // dd($data); + return $this->loadLayout('test_members_list',$data); + } + + public function mapEmployees(){ + $client_id = $this->request->getPost('client_id'); + $branch_id = $this->request->getPost('branch_id'); + $policy_id = $this->request->getPost('client_policy_id'); + $selected_employees = (array)$this->request->getPost('selected'); + $si_amt = $this->request->getPost('si_amt'); + $policy_start_date_unformatted = $this->request->getPost('policy_start_date'); + + $policy_start_date = change_date_format($policy_start_date_unformatted, 'd/M/Y', 'Y-m-d'); + + $data1 = [ + 'client_id' => $client_id, + 'client_branch_id' => $branch_id, + ]; + $data2 = [ + 'client_policy_id' => $policy_id, + 'status' => 'draft', + 'date_coverage' => $policy_start_date, + 'basic_cover_si' => $si_amt, + + ]; + + for($i = 0; $i < count($selected_employees); $i++){ + $data2['employee_id'] = $selected_employees[$i]; + $result1 = $this->employeeModel->set($data1)->where('id',$selected_employees[$i])->update(); + $result2 = $this->employeePolicyModel->insert($data2); + } + if ($result1 && $result2) { + return $this->respond(['status' => true, 'code' => 200, 'message' => 'Employees mapped successfully'], 200); + } else { + return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to map employees.'], 404); + } + } + + public function getDataForMapping(){ + $policy_id = $this->request->getPost('policy_id');log_message('error',$policy_id); + $data['policy_start_date'] = $this->clientPolicyModel->select('policy_start_date')->where('id',$policy_id)->first()['policy_start_date']; + $data['si_amt'] = $this->PolicyPremium2Model->select('si')->where('client_policy_id', $policy_id)->groupBy('si')->findAll(); + log_message('error',json_encode($data).'policy id '.$policy_id); + return $this->respond(['status' => true, 'code' => 200, 'data' => $data], 200); + } + + public function unmapEmployees($actionType){ + $selected_employees = (array)$this->request->getPost('selected'); + if($actionType == 0){ + for($i = 0;$iemployeeModel->set(['client_id' => null, 'client_branch_id' => null])->where('id',$selected_employees[$i])->update();log_message('error',$result1); + $result2 = $this->employeePolicyModel->where('employee_id',$selected_employees[$i])->delete();log_message('error',$result2); + } + } + else if ($actionType == 1){ + for($i = 0;$iemployeeModel->set(['client_id' => null, 'client_branch_id' => null])->where('id',$selected_employees[$i])->update();log_message('error','result 1 is '.$result1); + $result2 = $this->employeePolicyModel->where('employee_id',$selected_employees[$i])->delete();log_message('error', 'result 2 is '.$result2); + $emp_code = $this->employeeModel->select('emp_code')->where('id',$selected_employees[$i])->first()['emp_code'];log_message('error','emp_code is '.$emp_code); + $result3 = $this->employeeModel->where('emp_code',$emp_code)->whereNotIn('relationship',['self'])->delete();log_message('error','result 3 is '.$result3); + } + } + else{ + return $this->respond(['status' => false, 'code' => 404, 'message' => 'Invalid action type.'], 404); + } + if($actionType == 1){ + if($result1 && $result2 && $result3){ + return $this->respond(['status' => true, 'code' => 200, 'message' => 'Employees unmapped successfully and Dependencies are Deleted'], 200); + } + else{ + return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to unmap employees.'], 404); + } + }else{ + if($result1 && $result2 ){ + return $this->respond(['status' => true, 'code' => 200, 'message' => 'Employees unmapped successfully'], 200); + } + else{ + return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to unmap employees.'], 404); + } + } + + } + + + + public function cloneWorksheet() + { + // Define file paths + $inputFilePath = 'C:\Users\Venba\Downloads/merge1.xlsx'; // Path to the existing file + $outputFilePath = WRITEPATH . '/tmp/cloned_file.xlsx'; // Path to save the new file + + try { + // Load the existing spreadsheet + $spreadsheet = IOFactory::load($inputFilePath); + + // Get the first worksheet (or specify the index of the sheet to clone) + $originalWorksheet = $spreadsheet->getSheet(0); + + // Clone the worksheet + $clonedWorksheet = clone $originalWorksheet; + + // Generate a unique name for the cloned worksheet + $baseName = "Cloned Sheet"; + $sheetIndex = 1; + $uniqueName = $baseName; + + // Check for duplicate names and generate a unique one + while ($spreadsheet->sheetNameExists($uniqueName)) { + $uniqueName = $baseName . " " . $sheetIndex; + $sheetIndex++; + } + + // Set the unique name for the cloned worksheet + $clonedWorksheet->setTitle($uniqueName); + + // Add the cloned worksheet to the spreadsheet + $spreadsheet->addSheet($clonedWorksheet); + + // Modify the cloned sheet (optional) + $clonedWorksheet->setCellValue('A1', 'Hello, Cloned Sheet!'); + + // Save the modified spreadsheet to a new file + $writer = new Xlsx($spreadsheet); + $writer->save($outputFilePath); + + return $this->response->setJSON([ + 'status' => 'success', + 'message' => 'Spreadsheet with cloned sheet created successfully!', + 'file_path' => $outputFilePath, + ]); + } catch (\Exception $e) { + // Handle exceptions + return $this->response->setJSON([ + 'status' => 'error', + 'message' => $e->getMessage(), + ]); + } + } + } diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index 46d46589..42e8d530 100755 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -745,6 +745,7 @@ class EmployeeRestController extends AdminController //make an entry in DB $file_id = $this->fileModel->insert(['file_name' => $filename, 'client_id' => $client_id, 'policy_id' => $policy_id, 'created_by' => $employee_id, 'status' => 'inprogress', 'action' => 'enrollment', 'client_branch_id' => $client_branch_id]); //here field policy_id have client_policy_id and not policy id from policy master + $this->myLogger->logme("error", '{file_id} - client uploaded success', ['file_id' => $file_id]); $empServiceController = new EmployeeServiceController(); @@ -965,6 +966,7 @@ class EmployeeRestController extends AdminController } } } + $employee_policy = $this->employeePolicyModel->checkExistingEmpPolicy(['employee_id' => $emp_id,'client_policy_id' => $policy_id]); $emp_policy_data =[ 'employee_id'=>$emp_id, @@ -972,10 +974,10 @@ class EmployeeRestController extends AdminController 'status'=> 'draft', 'date_coverage' => $date_coverage, 'payable_employee' => check_pay_by_employee_or_company($client_policy['policy_terms'], $dataToInsert[$a]['relationship']), - 'basic_cover_si'=>isset($basic_cover_si[$a]) ? $basic_cover_si[$a] : null + 'basic_cover_si'=>isset($basic_cover_si[$a]) ? $basic_cover_si[$a] : null, + 'file_id' => isset($employee_policy['file_id']) && $employee_policy['file_id'] != '' ? $employee_policy['file_id'] : $file_id, ]; - $employee_policy = $this->employeePolicyModel->checkExistingEmpPolicy(['employee_id' => $emp_id,'client_policy_id' => $policy_id]); // print_r($employee_policy); die; if ($employee_policy) { foreach ($employee_policy as $existing_policy) { diff --git a/app/Controllers/EmployeeServiceController.php b/app/Controllers/EmployeeServiceController.php index d5e6d6f7..7eafb908 100755 --- a/app/Controllers/EmployeeServiceController.php +++ b/app/Controllers/EmployeeServiceController.php @@ -132,7 +132,7 @@ class EmployeeServiceController extends AdminController 'format' => 'd-M-Y', 'allowed_values' => null, 'custom' => 'check_dob_diff', - 'params' => ['row', 'relationship', 'default_age_ratio'] + 'params' => ['row', 'relationship', 'default_age_ratio','policy_details'] ], 'gender' => [ 'col_idx' => 4, @@ -344,6 +344,15 @@ class EmployeeServiceController extends AdminController 'data_type' => 'str', 'format' => null, 'allowed_values' => null + ], + 'claim_status' => [ + 'col_idx' => 6, + 'col_cell_name' => 'G', + 'col_name' => 'Claim status', + 'is_mandatory' => ['D'], + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => [0,1] ] ]; @@ -767,10 +776,9 @@ class EmployeeServiceController extends AdminController $relationship = $this->general_relationships; //get exisiting mobilr nos $existing_mobilenos = $this->employeePolicyModel->getExisitingMobileNos(client_policy_id: $file['policy_id']); - //get existing units in the current branch $existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $file['client_id'],client_branch_id: $file['client_branch_id']); - // dd($existing_units); + // dd($excel_data); foreach ($excel_data as $row_key => $row) { //define row wise action/event in temporary variable @@ -1234,7 +1242,6 @@ class EmployeeServiceController extends AdminController // Kint::dump($family);die(); $data = calculate_premium_new(family_data:$family,policy_terms: $policy_terms,slab_details : $slab_details,fileArr: $file, existing_units:$existing_units); - // dd($data); $employee_data_group_by_family[$emp_id] = $data; $this->employeesOnboardProcess(['familiy_data' => $data,'file' => $file]); } @@ -1328,7 +1335,7 @@ class EmployeeServiceController extends AdminController // } // dd($row[4]); //for emp table - $this->empEndorsementModel->save(['pk' => (int)$data['emp_id'],'emp_code' => $data['emp_code'],'table_name' => 'employees','actions' => 'd','name' => $data['name'],'field_name' => 'emp_status','old_value' => $data['emp_status'],'new_value' => 'deactivate','created_by' => $file['created_by'],'remarks' => 'general deletion','group_key' => $group_key,'file_id' => $file['id'],'status' => 'pending']); + // $this->empEndorsementModel->save(['pk' => (int)$data['emp_id'],'emp_code' => $data['emp_code'],'table_name' => 'employees','actions' => 'd','name' => $data['name'],'field_name' => 'emp_status','old_value' => $data['emp_status'],'new_value' => 'deactivate','created_by' => $file['created_by'],'remarks' => 'general deletion','group_key' => $group_key,'file_id' => $file['id'],'status' => 'pending']); // dd( $this->empEndorsementModel->getLastQuery()); // $this->empEndorsementModel->save(['pk' => (int)$data['emp_id'],'emp_code' => $data['emp_code'],'table_name' => 'employees','actions' => 'd','name' => $data['name'],'field_name' => 'change_event','old_value' => $data['change_event'],'new_value' => 'deletion','created_by' => $file['created_by'],'remarks' => 'general deletion']); @@ -1336,6 +1343,7 @@ class EmployeeServiceController extends AdminController $this->empEndorsementModel->save(['pk' => (int)$data['emp_policy_id'],'emp_code' => $data['emp_code'],'table_name' => 'employee_polices','actions' => 'd','name' => $data['name'],'field_name' => 'date_of_exit','old_value' => $data['date_of_exit'],'new_value' => $row[4],'created_by' => $file['created_by'],'remarks' => 'general deletion','group_key' => $group_key,'file_id' => $file['id'],'status' => 'pending']); $this->empEndorsementModel->save(['pk' => (int)$data['emp_policy_id'],'emp_code' => $data['emp_code'],'table_name' => 'employee_polices','actions' => 'd','name' => $data['name'],'field_name' => 'reason_for_exit','old_value' => $data['reason_for_exit'],'new_value' => $row[5],'created_by' => $file['created_by'],'remarks' => 'general deletion','group_key' => $group_key,'file_id' => $file['id'],'status' => 'pending']); $this->empEndorsementModel->save(['pk' => (int)$data['emp_policy_id'],'emp_code' => $data['emp_code'],'table_name' => 'employee_polices','actions' => 'd','name' => $data['name'],'field_name' => 'status','old_value' => $data['status'],'new_value' => 'inactive','created_by' => $file['created_by'],'remarks' => 'general deletion','group_key' => $group_key,'file_id' => $file['id'],'status' => 'pending']); + $this->empEndorsementModel->save(['pk' => (int)$data['emp_policy_id'],'emp_code' => $data['emp_code'],'table_name' => 'employee_polices','actions' => 'd','name' => $data['name'],'field_name' => 'claim_status','old_value' => $data['claim_status'],'new_value' => $row[6],'created_by' => $file['created_by'],'remarks' => 'general deletion','group_key' => $group_key,'file_id' => $file['id'],'status' => 'pending']); }; //iterate each row foreach ($excel_data as $col_key => $row) @@ -1370,7 +1378,7 @@ class EmployeeServiceController extends AdminController if(!in_array($employee['id'],$endorsement_data))//make entry in endorsement firsttime only with checking that PK of emp exisintg in variable $endorsement_data { $employee_policy = $this->employeePolicyModel->where('employee_id',$employee['id'])->where('client_policy_id',$file['policy_id'])->first(); - $data = ['emp_id' => $employee['id'],'name' => $employee['name'],'emp_status' => $employee['emp_status'],'emp_policy_id' => $employee_policy['id'],'emp_code' => $employee['emp_code'],'change_event' => $employee['change_event'],'date_of_exit' => $employee_policy['date_of_exit'],'reason_for_exit' => $employee_policy['reason_for_exit'],'status' => $employee_policy['status']]; + $data = ['emp_id' => $employee['id'],'name' => $employee['name'],'emp_status' => $employee['emp_status'],'emp_policy_id' => $employee_policy['id'],'emp_code' => $employee['emp_code'],'change_event' => $employee['change_event'],'date_of_exit' => $employee_policy['date_of_exit'],'reason_for_exit' => $employee_policy['reason_for_exit'],'status' => $employee_policy['status'],'claim_status' => $employee_policy['claim_status']]; $endorsement($data,$file,$row); $endorsement_data[] = $employee['id']; } @@ -1461,6 +1469,8 @@ class EmployeeServiceController extends AdminController ->where('emp_code',$employee['emp_code']) ->where('name',$employee['name']) ->where('field_name',$field_name) + ->where('is_active',1) + ->where('status !=','truncated') ->findAll(); // dd($existing_endorsements); //make entry in endorsement table @@ -1611,7 +1621,7 @@ class EmployeeServiceController extends AdminController // echo '---------------------------------------'; //start implemet of si enhancement of grid type 10,11 - if(count($employee) && $file['action'] == 'dependent_addition' && $temp['source'] == 'db' && in_array($value['temp']['grid_id'],[10,11]) && ( ($value['temp']['premium_type'] == 1 && (strtolower($value['relationship']) == 'self' || $temp['acting_self'])) || ($value['temp']['premium_type'] == 2 || $value['temp']['premium_type'] == null))) + if(count($employee) && $file['action'] == 'dependent_addition' && $temp['source'] == 'db' && in_array($temp['grid_id'],[10,11]) && ( ($temp['premium_type'] == 1 && (strtolower($value['relationship']) == 'self' || $temp['acting_self'])) || ($temp['premium_type'] == 2 || $temp['premium_type'] == null))) { $log_message = 'Employee record from DB,Checking SI for - '.$employee[0]['name'].'('.$employee[0]['emp_code'].')'; $this->myLogger->logme('error',$log_message); @@ -1620,7 +1630,6 @@ class EmployeeServiceController extends AdminController break;//skip db employee } //end implemet of si enhancement of grid type - //save employee table $value['relationship'] = ucfirst(trim($value['relationship'])); if(count($employee)) @@ -1629,6 +1638,7 @@ class EmployeeServiceController extends AdminController $value['id'] = $employee[0]['id']; $value['emp_status'] = 'active'; $value['client_branch_id'] = $file['client_branch_id']; + $value['file_id'] = isset($employee[0]['file_id']) && $employee[0]['file_id'] != '' ? $employee[0]['file_id'] : $file['id'] ; $log_message = 'Update Employee - '.$employee[0]['name'].'('.$employee[0]['emp_code'].') with PK '.$employee[0]['id']; // $this->myLogger->logme('error',('Update - ' . $employee[0]['id'].' - '. $employee[0]['emp_code'] .' - '.$employee[0]['name'])); // echo 'insert emp'; @@ -1639,11 +1649,11 @@ class EmployeeServiceController extends AdminController $value['created_by'] = $file['created_by']; $value['client_branch_id'] = $file['client_branch_id']; $value['family_floater_key'] = generate_family_floater_key($value['relationship']); + $value['file_id'] = isset($employee[0]['file_id']) && $employee[0]['file_id'] != '' ? $employee[0]['file_id'] : $file['id'] ; $log_message = 'Insert Employee- '.$value['name'] .'('.$value['emp_code'] .') with PK '; // $this->myLogger->logme('error',('Insert - ' . $value['emp_code'] .' - '. $value['name'])); // echo 'update emp'; } - $this->employeeModel->save($value); if (isset($value['id'])) { $emp_id = $value['id']; @@ -1667,7 +1677,7 @@ class EmployeeServiceController extends AdminController $policy_data['id'] = $employee_policy[0]['id']; $policy_data['status'] = 'active'; $policy_data['payable_employee'] = check_pay_by_employee_or_company($policy_details['policy_terms'], $value['relationship']); - + $policy_data['file_id'] = isset($employee_policy[0]['file_id']) && $employee_policy[0]['file_id'] != '' ? $employee_policy[0]['file_id'] : $file['id'] ; $log_message = 'Update Employee Policy for '. $value['name'].'('. $value['emp_code'].') with PK- ' . $employee_policy[0]['id'] .' client policy ID '.$employee_policy[0]['client_policy_id'].' with SI '.$policy_data['basic_cover_si']; // echo 'insert policy'; } @@ -1678,12 +1688,14 @@ class EmployeeServiceController extends AdminController $policy_data['created_by'] = $file['created_by']; $policy_data['status'] = 'active'; $policy_data['payable_employee'] = check_pay_by_employee_or_company($policy_details['policy_terms'], $value['relationship']); - + $policy_data['file_id'] = $file['id']; $log_message = 'Insert Employee Policy for '. $value['name'].'('. $value['emp_code'].') - client policy id -'. $file['policy_id'].' - with SI '.$policy_data['basic_cover_si']; // echo 'update policy'; } - - $this->employeePolicyModel->save($policy_data); + // log_message('error',json_encode($policy_data)); + // dd($this->employeePolicyModel->save($policy_data)); + $res = $this->employeePolicyModel->save($policy_data); + // if($res){log_message('error','ths the resul'.$res);} if(isset($policy_data['id'])) { $emp_policy_id = $policy_data['id']; @@ -1702,7 +1714,7 @@ class EmployeeServiceController extends AdminController $log_message = $file['action'].' - endorsement'. $value['emp_code'].' - '.$value['name'].' - with policy id'.$emp_policy_id; $this->myLogger->logme('error',$log_message); $actions = ($file['action'] == 'dependent_addition' ? 'da' : ($file['action'] == 'addition' ? 'a' : 'a')); - $addition_endorse_data = ['pk' => $emp_policy_id,'group_key' => rand(100000, 999999),'emp_code' => $value['emp_code'],'table_name' => 'employee_polices','actions' => $actions,'name' => $value['name'],'field_name' => 'basic_cover_si','old_value' => NULL,'new_value' => $policy_data['basic_cover_si'],'remarks' => 'addition endorsement','file_id' => $file['id'],'created_by' => $file['created_by']]; + $addition_endorse_data = ['pk' => $emp_policy_id,'group_key' => rand(100000, 999999),'emp_code' => $value['emp_code'],'table_name' => 'employee_polices','actions' => $actions,'name' => $value['name'],'field_name' => 'basic_cover_si','old_value' => NULL,'new_value' => $policy_data['basic_cover_si'],'remarks' => 'addition endorsement','file_id' => $file['id'],'created_by' => $file['created_by'],'status' => 'pending']; $this->employeeEndorsementforAddtionAndDependentAddition($addition_endorse_data); } @@ -2012,10 +2024,10 @@ public function getFileMetaDataByFileId($file_id, $status = 'success'){ $value['emp_code'] = $row[1]; $value['name'] = $row[2]; - $value['doj'] = (!empty($row[3]) ? convert_string_to_date($row[3],'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['relationship'] = ucfirst(trim($row[5])); - $value['dob'] = convert_string_to_date($row[6],'Y-m-d'); + $value['dob'] = change_date_format($row[6],'d-M-Y','Y-m-d'); $value['email_corporate'] = $row[7]; $value['mobile'] = $row[8]; $value['band'] = $row[10]; @@ -2042,7 +2054,7 @@ public function getFileMetaDataByFileId($file_id, $status = 'success'){ $value['family_floater_key'] = $relation; $policy_data['basic_cover_si'] = $row[9]; - $policy_data['date_coverage'] = $row[13] != "" && $row[13] != null ? change_date_format($row[13],null,'Y-m-d') : null; + $policy_data['date_coverage'] = $row[13] != "" && $row[13] != null ? change_date_format($row[13],'d-M-Y','Y-m-d') : null; $policy_data['client_policy_id'] = $file['policy_id']; $employee = $this->employeeModel->checkExistingEmployee($value,$file['client_branch_id']); @@ -2085,7 +2097,7 @@ public function getFileMetaDataByFileId($file_id, $status = 'success'){ $policy_data['id'] = $employee_policy[0]['id']; $policy_data['status'] = 'draft'; $policy_data['payable_employee'] = check_pay_by_employee_or_company($policy_details['policy_terms'], $value['relationship']); - + $policy_data['file_id'] = isset($employee_policy[0]['file_id']) && $employee_policy[0]['file_id'] != '' ? $employee_policy[0]['file_id'] : $file_id ; $log_message = 'Update Employee Policy for '. $value['name'].'('. $value['emp_code'].') with PK- ' . $employee_policy[0]['id'] .' client policy ID '.$employee_policy[0]['client_policy_id'].' with SI '.$policy_data['basic_cover_si']; // echo 'insert policy'; } @@ -2096,11 +2108,13 @@ public function getFileMetaDataByFileId($file_id, $status = 'success'){ $policy_data['created_by'] = $file['created_by']; $policy_data['status'] = 'draft'; $policy_data['payable_employee'] = check_pay_by_employee_or_company($policy_details['policy_terms'], $value['relationship']); - + $policy_data['file_id'] = $file_id; $log_message = 'Insert Employee Policy for '. $value['name'].'('. $value['emp_code'].') - client policy id -'. $file['policy_id'].' - with SI '.$policy_data['basic_cover_si']; // echo 'update policy'; } + log_message('error',json_encode($policy_data)); + // dd($policy_data); $this->employeePolicyModel->save($policy_data); $emp_policy_id = $this->employeePolicyModel->getInsertID(); $this->myLogger->logme('error',$log_message); diff --git a/app/Controllers/JobWorker.php b/app/Controllers/JobWorker.php index a0d5f694..fcaf2096 100755 --- a/app/Controllers/JobWorker.php +++ b/app/Controllers/JobWorker.php @@ -126,6 +126,10 @@ class JobWorker extends AdminController 'employeesEnrollmentInsert' => [ 'type' => 'CC', // Handler Category 'handler' => 'App\Controllers\EmployeeServiceController', + ], + 'calculateMembersDemography' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\LeadsController', ] ]; diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php index 7c5eef43..6140f45e 100644 --- a/app/Controllers/LeadsController.php +++ b/app/Controllers/LeadsController.php @@ -4,10 +4,14 @@ namespace App\Controllers; use CodeIgniter\API\ResponseTrait; + +use Exception; + use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; +use PhpOffice\PhpSpreadsheet\Style\Fill; use App\Models\UserModel; use App\Models\ClientModel; @@ -24,13 +28,19 @@ use App\Models\RFQModel; use App\Models\InsurerModel; use App\Helpers\MailHelper; +use App\Helpers\ExcelMergeHelper; +use App\Helpers\ExcelSanitizeHelper; +use Google\Service\CloudSearch\PushItem; use Kint; +use App\Controllers\Jobs; +use App\Controllers\JobWorker; + class LeadsController extends BaseController -{ +{ use ResponseTrait; - + //log message protected $myLogger; @@ -89,13 +99,20 @@ class LeadsController extends BaseController } public function viewLeadsList() - { + { + + // $d = $this->constructExcelToSaveTemp(24, 1, $propsal_and_insurer = null); + // $job_details = new Jobs(); + // $r = Jobs::addJob(['job_name' => 'calculateMembersDemography', 'payload' => ['lead_id' => 24]]); + // $d = $this->calculateMembersDemography(['lead_id' => 24]); + //$this->mergeQuoteExcelFileWithMembersListExcelFile(24, 1, $propsal_and_insurer = null); + // dd($d); $data['page_name'] = 'Leads'; // Set basic data - $data['issuer'] = $this->issuer; - $data['client_type'] = $this->clientType; - $data['lead_type'] = $this->leadType; + $data['issuer'] = $this->issuer; + $data['client_type'] = $this->clientType; + $data['lead_type'] = $this->leadType; $data['lead_status'] = $this->leadsStatus; // Fetch policy types and entity data @@ -118,8 +135,8 @@ class LeadsController extends BaseController // dd($data); // Fetch leads data - $data['lead_data_list'] = $this->leadsModel->getLeadDataForLising(); - + $data ['lead_data_list'] = $this->leadsModel->getLeadDataForLising(); + // Load layout and pass data $this->loadLayout('leads_list', $data); } @@ -131,51 +148,56 @@ class LeadsController extends BaseController $data = $this->prepareLeadData(); // print_r($this->request->getPost()); die; - + if (!$id) { return $this->insertNewLead($data); } else { return $this->updateOldLead($id, $data); } } - + private function prepareLeadData() { $data = $this->request->getPost(); - - if($data['lead_type'] == 2){ + + if ($data['lead_type'] == 2) { $client_data = $this->clientModel->where('id', $data['client_id'])->where('is_active', 1)->first(); $data['client_name'] = $client_data['client_name']; $data['client_short_name'] = $client_data['short_name']; $data['entity_type_id'] = $client_data['entity_type_id']; $data['client_type'] = $client_data['client_type']; - }else{ + } else { $data['client_id'] = 0; $data['client_branch_id'] = 0; $data['source_policy_id'] = 0; } $data['client_code'] = generate_client_code(); - if($data['client_code'] == 2){ + if ($data['client_code'] == 2) { $data['client_code'] = generate_client_code('IC'); } - + $data = $this->prepareMultipleLeadData($data); // print_r($data); die; return $data; } private function prepareMultipleLeadData($data) - { + { // print_r($data); die; $processedData = []; - foreach($data['policy_type_id'] as $index => $value){ + $uploadFilePath = WRITEPATH . 'uploads/lead_files/'; + // Get all uploaded files for 'file_name[]' + $files = $this->request->getFileMultiple('file_name'); + + // print_r($files); die; + + foreach($data['policy_type_id'] as $index => $value){ // Separate the insurer and insurer branch, handle missing or invalid data if (isset($data['insurer'][$index]) && strpos($data['insurer'][$index], '-') !== false) { list($insurer_branch_id, $insurer_id) = explode('-', $data['insurer'][$index]); - } else { $insurer_branch_id = 0; $insurer_id = 0; } @@ -186,7 +208,6 @@ class LeadsController extends BaseController $tpa_branch_id = 0; $tpa_id = 0; } - // Separate the insurer and insurer branch, handle missing or invalid data if (isset($data['proposed_insurer'][$index]) && strpos($data['proposed_insurer'][$index], '-') !== false) { @@ -204,18 +225,37 @@ class LeadsController extends BaseController $proposed_tpa_id = 0; } - if(!empty($data['policy_start_date'][$index])){ + if (!empty($data['policy_start_date'][$index])) { $policy_start_date = change_date_format($data['policy_start_date'][$index], 'd/m/Y', 'Y-m-d'); - }else{ + } else { $policy_start_date = null; } - - if(!empty($data['policy_end_date'][$index])){ + + if (!empty($data['policy_end_date'][$index])) { $policy_end_date = change_date_format($data['policy_end_date'][$index], 'd/m/Y', 'Y-m-d'); - }else{ + } else { $policy_end_date = null; } - + + if(!empty($data['incurred_claim_date'][$index])){ + $incurred_claims_date = change_date_format($data['incurred_claim_date'][$index], 'd/m/Y', 'Y-m-d'); + }else{ + $incurred_claims_date = null; + } + + if(!empty($data['premium_date'][$index])){ + $premium_date = change_date_format($data['premium_date'][$index], 'd/m/Y', 'Y-m-d'); + }else{ + $premium_date = null; + } + + $file_name = file_Upload($files[$index], $uploadFilePath); + + $last_3_years_claims = null; + if($value != 2){ + $last_3_years_claims = $data['finyear']; + } + $processedData[] = [ 'lead_type' => $data['lead_type'], 'issuer' => $data['issuer'], @@ -244,13 +284,39 @@ class LeadsController extends BaseController 'policy_start_date' => $policy_start_date, 'policy_end_date' => $policy_end_date, 'no_of_lives' => $data['no_of_lives'][$index] ?? null, - 'claims' => $data['claims'][$index] ?? null, + 'incurred_claims' => $data['incurred_claims'][$index] ?? 0, 'location' => $data['location'][$index] ?? null, 'proposed_insurer_id' => $proposed_insurer_id ?? 0, 'proposed_insurer_branch_id' => $proposed_insurer_branch_id ?? 0, 'proposed_tpa_id' => $proposed_tpa_id ?? 0, 'proposed_tpa_branch_id' => $proposed_tpa_branch_id ?? 0, + 'renewal_emp_count' => $data['renewal_emp_count'][$index] ?? 0, + 'renewal_dept_count' => $data['renewal_dept_count'][$index] ?? 0, + 'renewal_no_of_lives' => $data['renewal_no_of_lives'][$index] ?? 0, + 'incept_emp_count' => $data['incept_emp_count'][$index] ?? 0, + 'incept_dept_count' => $data['incept_dept_count'][$index] ?? 0, + 'incept_no_of_lives' => $data['incept_no_of_lives'][$index] ?? 0, + 'exp_emp_count' => $data['exp_emp_count'][$index] ?? 0, + 'exp_dept_count' => $data['exp_dept_count'][$index] ?? 0, + 'exp_no_of_lives' => $data['exp_no_of_lives'][$index] ?? 0, + + 'incurred_claims_date' => $incurred_claims_date, + 'paid_claims' => $data['paid_claims'][$index] ?? 0, + 'outstanding_claims' => $data['outstanding_claims'][$index] ?? 0, + 'policy_run_days' => $data['policy_run_days'][$index] ?? 0, + 'premium_at_inception' => $data['premium_at_inception'][$index] ?? 0, + 'premium_date' => $premium_date, + 'earned_premium' => $data['earned_premium'][$index] ?? 0, + 'annualised_claims' => $data['annualised_claims'][$index] ?? 0, + 'incurred_claims_ratio' => $data['incurred_claims_ratio'][$index] ?? 0, + 'earned_claims_ratio' => $data['earned_claims_ratio'][$index] ?? 0, + 'total_si_at_incept' => $data['total_si_at_incept'][$index] ?? 0, + 'total_si_at_renewal' => $data['total_si_at_renewal'][$index] ?? 0, + 'fin_years_claims' => $last_3_years_claims, + + 'file_name' => $file_name, + 'status' => $data['status'] ?? null, 'notes' => $data['notes'] ?? null, ]; @@ -258,59 +324,76 @@ class LeadsController extends BaseController return $processedData; } - + private function insertNewLead($data) - { + { $insertCount = []; - foreach($data as $value){ + foreach ($data as $value) { $insert = $this->leadsModel->insert($value); $insertCount[] = $insert; $this->insertLeadStatus($insert, $value['status'], 3); + + //for this push the job to the calculateMembersDemography() function + $job_details = new Jobs(); + $r = Jobs::addJob(['job_name' => 'calculateMembersDemography', 'payload' => [ + 'lead_id' => $insert, + ]]); } if (count($insertCount) > 0) { - return $this->respond(['status' => true, 'lead_id' => $insert, 'message' => 'New Lead created successfully', 'data' =>$data], 200); + return $this->respond(['status' => true, 'lead_id' => $insert, 'message' => 'New Lead created successfully', 'data' => $data], 200); } - return $this->respond(['status' => false, 'lead_id' => $insert, 'message' => "Failed to create Lead", 'data' =>$data], 200); + return $this->respond(['status' => false, 'lead_id' => $insert, 'message' => "Failed to create Lead", 'data' => $data], 200); } - + private function updateOldLead($id, $data) - { + { if ($this->leadsModel->where('id', $id)->set($data[0])->update()) { $this->insertLeadStatus($id, $data[0]['status'], 3); - return $this->respond(['status' => true, 'lead_id' => $id, 'message' => "Lead updated successfully", 'data' =>$data], 200); + return $this->respond(['status' => true, 'lead_id' => $id, 'message' => "Lead updated successfully", 'data' => $data], 200); } - return $this->respond(['status' => false, 'lead_id' => $id, 'message' => "Failed to update Lead", 'data' =>$data], 200); + return $this->respond(['status' => false, 'lead_id' => $id, 'message' => "Failed to update Lead", 'data' => $data], 200); } // Get the Single Lead data for edit public function getLeadDataForEdit($id) - { + { $data = $this->leadsModel - ->where('leads.id', $id) - ->where('leads.is_active', 1) - ->first(); + ->where('leads.id', $id) + ->where('leads.is_active', 1) + ->first(); - if(!empty($data['policy_start_date'])){ + if (!empty($data['policy_start_date'])) { $data['policy_start_date'] = change_date_format($data['policy_start_date'], 'Y-m-d', 'd/m/Y'); - }else{ + } else { $data['policy_start_date'] = null; } - if(!empty($data['policy_end_date'])){ + if (!empty($data['policy_end_date'])) { $data['policy_end_date'] = change_date_format($data['policy_end_date'], 'Y-m-d', 'd/m/Y'); - }else{ + } else { $data['policy_end_date'] = null; } - - if($data){ - return $this->respond(['status' => true, 'data' => $data], 200); - }else{ - return $this->respond(['status' => false], 200); + + if (!empty($data['incurred_claims_date'])) { + $data['incurred_claims_date'] = change_date_format($data['incurred_claims_date'], 'Y-m-d', 'd/m/Y'); + } else { + $data['incurred_claims_date'] = null; } + if (!empty($data['premium_date'])) { + $data['premium_date'] = change_date_format($data['premium_date'], 'Y-m-d', 'd/m/Y'); + } else { + $data['premium_date'] = null; + } + + if ($data) { + return $this->respond(['status' => true, 'data' => $data], 200); + } else { + return $this->respond(['status' => false], 200); + } } private function insertLeadStatus($primaryKey, $status, $statusType) @@ -328,31 +411,32 @@ class LeadsController extends BaseController //--------RFQ----------------------------------------------------------------------------------------------- - public function viewRFQ($id, $type = 1){ + public function viewRFQ($id, $type = 1) + { $data['rfq_data'] = $this->RFQModel ->where('lead_id', $id) - ->where('type', $type) + // ->where('type', $type) ->where('is_active', 1) ->first(); $data['rfq_count'] = $this->RFQModel ->where('lead_id', $id) - ->where('type', 1) + // ->where('type', 1) ->where('is_active', 1) ->countAllResults(); $data['qcr_count'] = $this->RFQModel - ->where('lead_id', $id) - ->where('type', 2) - ->where('is_active', 1) - ->countAllResults(); + ->where('lead_id', $id) + ->where('type', 2) + ->where('is_active', 1) + ->countAllResults(); // dd(count($data['rfq_data'])); $data['lead_id'] = $id; $lead_data = $this->leadsModel - ->select('leads.*, policy_type.question_json') + ->select('leads.*, policy_type.question_json, policy_type.policy_type') ->join('policy_type', 'leads.policy_type_id = policy_type.id') ->where('leads.id', $id) ->where('leads.is_active', 1) @@ -360,22 +444,26 @@ class LeadsController extends BaseController // dd($lead_data); - if($lead_data['lead_type'] == 2){ + if ($lead_data['lead_type'] == 2) { $client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $lead_data['source_policy_id'])->first(); $data['policy_terms'] = $client_policy_data['policy_terms']; } $data['question_json'] = $lead_data['question_json']; - $data['page_name'] = isset($data['rfq_data']['type']) && $data['rfq_data']['type'] == 2 ? 'QCR' : 'RFQ'; + $data['page_name'] = $type == 2 ? 'QCR' : 'RFQ'; $data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames(); $data['userList'] = $this->userModel->getUserListForRFQ(); $data['lead_data'] = $lead_data; + $data['mail_content'] = $this->transformMailContent($id); + // dd($data); $this->loadLayout('view_rfq.php', $data); } public function createRFQ(){ + + // print_r($this->request->getPost('json')); die(); $data = $this->request->getPost(); $lead_id = $data['lead_id']; @@ -390,14 +478,17 @@ class LeadsController extends BaseController $result = $this->RFQModel->insert($data); if ($result) { - return $this->respond(['status' => true, 'id' => $result, 'message' => 'RFQ created successfully', 'data' =>$data], 200); + + $message = "RFQ submitted successfully"; + if($data['submit_type'] == 'QCR'){ $message = "QCR submitted successfully"; } + return $this->respond(['status' => true, 'id' => $result, 'message' => $message, 'data' => $data], 200); } - return $this->respond(['status' => false, 'id' => $result, 'message' => "Failed to create RFQ", 'data' =>$data], 200); - + return $this->respond(['status' => false, 'id' => $result, 'message' => "Failed to create RFQ", 'data' => $data], 200); } - public function createQCR(){ + public function createQCR() + { $data = $this->request->getPost(); $lead_id = $data['lead_id']; @@ -413,10 +504,10 @@ class LeadsController extends BaseController $result = $this->RFQModel->insert($data); if ($result) { - return $this->respond(['status' => true, 'id' => $result, 'message' => 'QCR created successfully', 'data' =>$data], 200); + return $this->respond(['status' => true, 'id' => $result, 'message' => 'QCR created successfully', 'data' => $data], 200); } - return $this->respond(['status' => false, 'id' => $result, 'message' => "Failed to create QCR", 'data' =>$data], 200); + return $this->respond(['status' => false, 'id' => $result, 'message' => "Failed to create QCR", 'data' => $data], 200); } @@ -424,16 +515,40 @@ class LeadsController extends BaseController //export main route function - public function exportQCRandRFQ($lead_id, $type, $export_type){ - $this-> exportExcelForQCRandRFQ($lead_id, $type); + public function exportQCRandRFQ($lead_id, $type, $export_type) + { + $this->exportExcelForQCRandRFQ($lead_id, $type); } //FOR EXCEL public function exportExcelForQCRandRFQ($lead_id, $type) { $filepath = $this->constructExcelToSaveTemp($lead_id, $type); + $lead_data = $this->RFQModel->getRFQTableDataWithLeadIDAndType($lead_id, $type); + // dd($filepath); + + //Excel merging part + if ($lead_data['file_name'] != null && $lead_data['file_name'] != '') { + + $temp_file_path = $filepath['filePath']; + $temp_file_name = $filepath['fileName']; + $lead_file_path = WRITEPATH . 'uploads/lead_files/' . $lead_data['file_name']; + + // dd($lead_data, $temp_file_path, $temp_file_name, $lead_file_path); + + if ($lead_file_path) { + $filePaths = [ + ['file_path' => $temp_file_path, 'sheets' => []], + ['file_path' => $lead_file_path, 'sheets' => []] + ]; + // $outputPath = dirname($temp_file_path) . '/' . 'merged_' . $temp_file_name; + $result = ExcelMergeHelper::mergeExcelFiles($filePaths, $temp_file_path); + // print_rr($result); + } + } + $filepath = $filepath['filePath']; - + if (file_exists($filepath)) { // Set headers to force download header('Content-Description: File Transfer'); @@ -441,45 +556,112 @@ class LeadsController extends BaseController header('Content-Disposition: attachment; filename="' . basename($filepath) . '"'); header('Content-Length: ' . filesize($filepath)); header('Pragma: public'); - + // Output the file content readfile($filepath); - + // Delete the file after download unlink($filepath); - + exit; } else { echo "File does not exist."; } } - + //Construct excel file and save the file to the folder and return file path public function constructExcelToSaveTemp($lead_id, $type, $propsal_and_insurer = null) - { + { $rfq_data = $this->RFQModel->getRFQTableDataWithLeadIDAndType($lead_id, $type); - // dd($rfq_data, $lead_id, $type); + // dd($rfq_data, $lead_id, $type, $propsal_and_insurer); + // print_r($propsal_and_insurer); die; + + if($rfq_data['lead_type'] == 1){ + + if($rfq_data['policy_type_id'] == 2){ + $lead_data = [ + + 'Insured' => $rfq_data['client_name'], + 'Policy Status' => $rfq_data['status'], + + 'No of Employees' => $rfq_data['incept_emp_count'], + 'No of Dependents' => $rfq_data['incept_dept_count'], + 'Total Lives' => $rfq_data['incept_no_of_lives'], + + 'Period of Insurance ' => date('d/m/Y', strtotime($rfq_data['policy_start_date'])).' to '. date('d/m/Y', strtotime($rfq_data['policy_end_date'])), + 'Policy Run Days' => $rfq_data['policy_run_days'], + ]; + }else if($rfq_data['policy_type_id'] == 1){ + $lead_data = [ + 'Insured' => $rfq_data['client_name'], + 'No of Employees at Inception' => $rfq_data['incept_emp_count'], + 'Total Sum Insured at Inception ' => $rfq_data['total_si_at_incept'], + 'Policy Period' => date('d/m/Y', strtotime($rfq_data['policy_start_date'])).' to '. date('d/m/Y', strtotime($rfq_data['policy_end_date'])), + 'Policy Status' => $rfq_data['status'], + 'Existing Insurer' => $rfq_data['insurer_name'], + 'TPA ' => $rfq_data['tpa_name'], + ]; + } + + }else{ + if($rfq_data['policy_type_id'] == 2){ + $lead_data = [ + + 'Insured' => $rfq_data['client_name'], + 'Policy Status' => $rfq_data['status'], + + 'No of Employees at Inception' => $rfq_data['incept_emp_count'], + 'No of Dependents at Inception' => $rfq_data['incept_dept_count'], + 'Total Lives at Inception ' => $rfq_data['incept_no_of_lives'], + + 'No of Employees at Expiry' => $rfq_data['exp_emp_count'], + 'No of Dependents at Expiry' => $rfq_data['exp_dept_count'], + 'Total Lives at Expiry ' => $rfq_data['exp_no_of_lives'], + + 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'], + 'No of Dependents at Renewal' => $rfq_data['renewal_dept_count'], + 'Total Lives at Renewal ' => $rfq_data['renewal_no_of_lives'], + + 'Period of Insurance ' => date('d/m/Y', strtotime($rfq_data['policy_start_date'])).' to '. date('d/m/Y', strtotime($rfq_data['policy_end_date'])), + 'Policy Run Days' => $rfq_data['policy_run_days'], + 'Inception Premium' => $rfq_data['premium_at_inception'], + 'Premium as on (Date - DD MM YYYY should be entered based on the claims dump report)' => $rfq_data['premium_date'], + 'Earned Premium' => $rfq_data['earned_premium'], + 'Incurred Claims as on (Date - DD MM YYYY should be entered based on the claims dump report)' => $rfq_data['incurred_claims_date'], + 'Annualised Claims' => $rfq_data['annualised_claims'], + 'Incurred Claims Ratio' => $rfq_data['incurred_claims_ratio'], + 'Earned Claims Ratio' => $rfq_data['earned_claims_ratio'], + ]; + }else if($rfq_data['policy_type_id'] == 1){ + $lead_data = [ + 'Insured' => $rfq_data['client_name'], + 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'], + 'Total Sum Insured at Renewal ' => $rfq_data['total_si_at_renewal'], + 'Policy Period' => date('d/m/Y', strtotime($rfq_data['policy_start_date'])).' to '. date('d/m/Y', strtotime($rfq_data['policy_end_date'])), + 'Policy Status' => $rfq_data['status'], + 'Existing Insurer' => $rfq_data['insurer_name'], + 'TPA ' => $rfq_data['tpa_name'], + ]; + } + } - $lead_data = [ - 'Insured' => $rfq_data['client_name'], - 'Insurer' => $rfq_data['insurer_name'] . ' - ' . $rfq_data['insurer_branch_name'], - 'TPA' => $rfq_data['tpa_name'] . ' - ' . $rfq_data['tpa_branch_name'], - ]; - $data = json_decode($rfq_data['json'], true); if($type == 2){ - $data = $this->convertJsonForQCR($data, 'stc'); + $data = $this->convertJsonForQCR($data, $type); if($propsal_and_insurer !== null){ list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2); $data = $this->transformProposelData($data, $proposal_key, $insurer_key); } + }else if($type == 1){ + $data = $this->convertJsonForQCR($data, $type); + // dd($data); } - + $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); - + // Start with lead_data at the top $rowNumber = 1; foreach ($lead_data as $key => $value) { @@ -499,26 +681,26 @@ class LeadsController extends BaseController ], ]); - + $rowNumber += 2; // Add headers and subheaders $headers = $data['table_data']['headers']; $subHeaderRow = $rowNumber + 1; $columnLetter = 'A'; - + foreach ($headers as $header) { if (in_array($header['parentHeader'], ['Item Key', 'Action'])) { continue; } - + if ($header['parentHeader'] === 'Sno') { $header['parentHeader'] = 'S.No.'; } - + $startColumn = $columnLetter; // Start of the current header range $subHeaderCount = count($header['subHeaders']); // Number of subheaders for this parent header - + // Set parent header value $sheet->setCellValue("{$startColumn}{$rowNumber}", $header['parentHeader']); $sheet->getStyle("{$startColumn}{$rowNumber}")->applyFromArray([ @@ -528,7 +710,7 @@ class LeadsController extends BaseController 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, ], ]); - + // Merge header cells if it spans multiple subheaders if ($subHeaderCount > 1) { $endColumn = chr(ord($startColumn) + $subHeaderCount - 1); // Calculate the end column @@ -536,7 +718,7 @@ class LeadsController extends BaseController } else { $endColumn = $startColumn; // No merge needed if only one subheader } - + // Add subheaders foreach ($header['subHeaders'] as $subHeader) { $sheet->setCellValue("{$columnLetter}{$subHeaderRow}", $subHeader); @@ -550,7 +732,7 @@ class LeadsController extends BaseController $columnLetter++; // Move to the next column for subheaders } } - + // Apply border to the header range $headerRange = "A{$rowNumber}:" . chr(ord($columnLetter) - 1) . "{$subHeaderRow}"; $sheet->getStyle($headerRange)->applyFromArray([ @@ -565,7 +747,7 @@ class LeadsController extends BaseController // Increase row height for headers and subheaders $sheet->getRowDimension($rowNumber)->setRowHeight(30); // Header row height $sheet->getRowDimension($subHeaderRow)->setRowHeight(25); // Subheader row height - + $rowNumber = $subHeaderRow + 2; $column_data = $data['table_data']['data']; $serial_no = 1; @@ -599,27 +781,32 @@ class LeadsController extends BaseController ], ], ]); - - if($type == 2){ + + if ($type == 2) { $rowNumber += 2; - + // Add premium data + $labelArray = ["Premium", "GST (%)", "GST Amount (₹)", "Total"]; $premiumData = $data['premium_data']['data']; - $premium = ['Premium']; - $gst = ['GST']; - $total = ['Total']; - + $premium = [$labelArray[0]]; + $gst = [$labelArray[1]]; + $gstAmt = [$labelArray[2]]; + $total = [$labelArray[3]]; + foreach ($premiumData as $proposal => $insurers) { - foreach ($insurers as $insurer => $values) { - $premium[] = $values['Premium']; - $gst[] = $values['GST']; - $total[] = $values['Total']; + if($proposal != 'Particulars'){ + foreach ($insurers as $insurer => $values) { + $premium[] = $values[$labelArray[0]]; + $gst[] = $values[$labelArray[1]]; + $gstAmt[] = $values[$labelArray[2]]; + $total[] = $values[$labelArray[3]]; + } } } - - foreach ([$premium, $gst, $total] as $index => $rowData) { + + foreach ([$premium, $gst, $gstAmt, $total] as $index => $rowData) { $columnLetter = 'B'; foreach ($rowData as $key => $value) { $sheet->setCellValue("{$columnLetter}{$rowNumber}", $value); @@ -640,43 +827,496 @@ class LeadsController extends BaseController ], ], ]); - } - + // Auto-size columns foreach ($sheet->getColumnIterator() as $column) { $sheet->getColumnDimension($column->getColumnIndex())->setAutoSize(true); } - + // Set filename $string = ($type == 2) ? 'QCR' : 'RFQ'; $filename = "{$string}_{$rfq_data['client_short_name']}_{$rfq_data['policy_type']}_" . date('YmdHis') . '.xlsx'; - + // Save to temporary location $uploadFilePath = WRITEPATH . 'tmp/' . $filename; $writer = new Xlsx($spreadsheet); $writer->save($uploadFilePath); - + return [ 'filePath' => $uploadFilePath, 'fileName' => $filename, ]; } + + //Merge RFQ/QCR file with lead members file + public function mergeQuoteExcelFileWithMembersListExcelFile($lead_id, $type, $source_file_path) + { + $rfq_data = $this->RFQModel->getRFQTableDataWithLeadIDAndType($lead_id, $type); + + if ($source_file_path && $rfq_data['file_name']) { + } + + return true; + } + + public function calculateMembersDemography($params) + { + $lead_id = $params['lead_id']; + $lead_data = $this->leadsModel->find($lead_id); + $file_name_with_path = WRITEPATH . "/uploads/lead_files/" . $lead_data['file_name']; + + if (!$lead_data) { + return ['status' => 'failed', 'message' => 'Lead data not found']; + } + if ($lead_data['file_name']) { + // $file_name_with_path = WRITEPATH . "/uploads/lead_files/NonPrintableCharacters.xlsx"; + + //check physical file + if (!file_exists($file_name_with_path)) { + //file not found update status and reason + $message = "Lead Physcial file not found"; + // echo $message; + $this->myLogger->logme('error', ($message . ' for file ' . $file_name_with_path)); + return ['status' => 'failed', 'message' => 'no physical file']; + } + + $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path); + + //get members data + $members_sheet = $spreadsheet->getSheet(0); + $highestRowAndColumn = $members_sheet->getHighestRowAndColumn(); + // dd($highestRowAndColumn); + $uncleaned_members = $members_sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']); + $members = ExcelSanitizeHelper::sanitizeArrayData($uncleaned_members); + //get age band data + $age_band_sheet = $spreadsheet->getSheet(1); + $highestRowAndColumn = $age_band_sheet->getHighestRowAndColumn(); + $age_band_data = $age_band_sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']); + + + //check age or dob column + $members_heading = $members[0]; + $available_col = null; + $col_index = null; + + if (in_array('age', array_map('strtolower', $members_heading))) { + $available_col = 'age'; + $col_index = array_search('age', array_map('strtolower', $members_heading)); + } elseif (in_array('dob', array_map('strtolower', $members_heading))) { + $available_col = 'dob'; + $col_index = array_search('dob', array_map('strtolower', $members_heading)); + } + + if ($available_col == null) { + $message = 'No DOB or Age column '; + $this->myLogger->logme('error', ($message . $file_name_with_path)); + return ['status' => 'failed', 'message' => $message]; + } + try { + $classifiers = $this->getDemographyData($members, $age_band_data, $members_heading, $available_col, $col_index); + } catch (Exception $e) { + return ['status' => 'fail', 'message' => $e->getMessage()]; + } + + try { + $result = $this->generateClassifierSpreadsheet($classifiers, WRITEPATH . 'uploads/lead_files/'); + if ($result['success']) { + $this->myLogger->logme('error', "Spreadsheet generated successfully!"); + + echo "Location: " . $result['fullpath'] . "\n"; + echo "Filename: " . $result['filename'] . "\n"; + $filePaths = [ + ['file_path' => WRITEPATH . 'uploads/lead_files/' . $lead_data['file_name'], 'sheets' => [0, 1]], + ['file_path' => WRITEPATH.'/uploads/lead_files/' . $result['filename'], 'sheets' => []], + ]; + $outputPath = WRITEPATH . 'uploads/lead_files/Member_Data.xlsx'; + $result_merge = ExcelMergeHelper::mergeExcelFiles($filePaths, $outputPath); + if ($result_merge) { + // Call the delete function after the file is successfully created + $deleteResponse = $this->deleteGeneratedFile($result['fullpath']); + + // Add delete message to response + $response['deleteMessage'] = $deleteResponse['message']; + return ['status' => 'success', 'message' => 'Member_Data Merged Suceesfully']; + } + } else { + echo "Error generating spreadsheet: " . $result['error']; + } + } catch (Exception $e) { + echo "Error: " . $e->getMessage(); + return ['status' => 'fail', 'message' => $e->getMessage()]; + } + } else { + $this->myLogger->logme('error', (' no file found ' . $file_name_with_path)); + return ['status' => 'failed', 'message' => 'no file found']; + } + } + + public function getDemographyData($members, $age_band_data, $members_heading, $available_col, $col_index) + { + $first_loop = 0; + $col_index_si = array_search('si enhancement', array_map('strtolower', $members_heading)); + $col_index_relationship = array_search('relationship', array_map('strtolower', $members_heading)); + $relations = []; + $si_amt = ['general']; // Initialize with 'general' as per first loop condition + + // First pass - collect unique relations and SI amounts + foreach ($members as $member) { + if ($first_loop == 0) { + $first_loop++; + continue; + } + if ($member == null) { + continue; + } + + if (!in_array($member[$col_index_relationship], $relations) && $member[$col_index_relationship] != null) { + $relations[] = $member[$col_index_relationship]; + } + + if (!in_array($member[$col_index_si], $si_amt) && $member[$col_index_si] != null) { + $si_amt[] = $member[$col_index_si]; + } + } + // Initialize classifier array + $classifiers = []; + foreach ($si_amt as $si) { + $classifiers[$si] = []; + // Initialize relation counts including Grand Total row + foreach ($relations as $relation) { + $classifiers[$si][$relation] = []; + foreach ($age_band_data as $age_bands) { + foreach ($age_bands as $age_interval) { + $classifiers[$si][$relation][$age_interval] = 0; + } + } + // Add Grand Total column for each relation echo('test passed 3.5'); + + $classifiers[$si][$relation]['Grand Total'] = 0; + } + // Initialize Grand Total row + $classifiers[$si]['Grand Total'] = []; + foreach ($age_band_data as $age_bands) { + foreach ($age_bands as $age_interval) { + $classifiers[$si]['Grand Total'][$age_interval] = 0; + } + } + // Add grand total of grand totals + $classifiers[$si]['Grand Total']['Grand Total'] = 0; + } + // Process members and count them + foreach ($members as $member) { + if ($first_loop == 0) { + $first_loop++; + continue; + } + // Get age + $age = $this->getAge($available_col, $member, $col_index); + + + $relation = $member[$col_index_relationship]; + $member_si = $member[$col_index_si]; + + // Find the correct age band (only once per member) + $found_band = false; + foreach ($age_band_data as $age_bands) { + if ($found_band) break; + + foreach ($age_bands as $age_band) { + //get Min and Max Age + list($min_age, $max_age) = $this->getAgeRange($age_band); + + // If age fits in this band + if ($age >= $min_age && $age <= $max_age) { + // Update counts for general category + if (isset($classifiers['general'][$relation][$age_band])) { + // Increment count for specific relation and age band + $classifiers['general'][$relation][$age_band]++; + // Update row total (Grand Total column) + $classifiers['general'][$relation]['Grand Total']++; + // Update column total (Grand Total row) + $classifiers['general']['Grand Total'][$age_band]++; + // Update grand total of grand totals + $classifiers['general']['Grand Total']['Grand Total']++; + } + + // Update counts for specific SI category + if (isset($classifiers[$member_si][$relation][$age_band])) { + // Increment count for specific relation and age band + $classifiers[$member_si][$relation][$age_band]++; + // Update row total (Grand Total column) + $classifiers[$member_si][$relation]['Grand Total']++; + // Update column total (Grand Total row) + $classifiers[$member_si]['Grand Total'][$age_band]++; + // Update grand total of grand totals + $classifiers[$member_si]['Grand Total']['Grand Total']++; + } + + $found_band = true; + break; + } + } + } + } + return $classifiers; + } + + public function generateClassifierSpreadsheet($classifiers, $outputDir = 'exports') + { + if (!file_exists($outputDir)) { + if (!mkdir($outputDir, 0755, true)) { + throw new Exception("Failed to create directory: $outputDir"); + } + } + // Check if directory is writable + if (!is_writable($outputDir)) { + throw new Exception("Directory is not writable: $outputDir"); + } + + // Generate unique filename + $timestamp = date('Y-m-d_His'); + $filename = "member_classification_{$timestamp}.xlsx"; + $filepath = $outputDir . DIRECTORY_SEPARATOR . $filename; + + // Check if file already exists (shouldn't happen with timestamp, but just in case) + if (file_exists($filepath)) { + $counter = 1; + while (file_exists($outputDir . DIRECTORY_SEPARATOR . "member_classification_{$timestamp}_{$counter}.xlsx")) { + $counter++; + } + $filename = "member_classification_{$timestamp}_{$counter}.xlsx"; + $filepath = $outputDir . DIRECTORY_SEPARATOR . $filename; + } + + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setTitle('Demography_Data'); + + // Get all age bands + $age_bands = array_keys(reset($classifiers['general'])); + array_pop($age_bands); // Remove 'Grand Total' + $age_bands[] = 'Grand Total'; // Add it back at the end + + $currentRow = 5; // Start from row 5 to match the example + + // Function to write section data + $writeSectionData = function ($data, $sheet, &$currentRow, $si_type) use ($age_bands) { + // Add section header for the SI type + $sheet->setCellValue('B' . $currentRow, strtoupper($si_type)); + + // Style section header + $sheet->getStyle('B' . $currentRow)->applyFromArray([ + 'font' => ['bold' => true, 'size' => 14], + 'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER], + ]); + + $currentRow++; // Move to the next row after the section header + + // Set headers for the data table + $sheet->setCellValue('B' . $currentRow, 'Relationship'); + $col = 'C'; + foreach ($age_bands as $band) { + $sheet->setCellValue($col . $currentRow, $band); + $col++; + } + + // Style headers + $lastCol = chr(ord('B') + count($age_bands)); + $headerRange = 'B' . $currentRow . ':' . $lastCol . $currentRow; + $sheet->getStyle($headerRange)->applyFromArray([ + 'font' => ['bold' => true], + 'borders' => [ + 'allBorders' => [ + 'borderStyle' => Border::BORDER_THIN, + 'color' => ['rgb' => '000000'], + ], + ], + 'alignment' => [ + 'horizontal' => Alignment::HORIZONTAL_CENTER, + ], + ]); + + $currentRow++; + + // Write data rows + foreach ($data as $relation => $values) { + if ($relation !== 'Grand Total') { + $sheet->setCellValue('B' . $currentRow, $relation); + $col = 'C'; + foreach ($age_bands as $band) { + $value = $values[$band] ?: ''; // Convert 0 to empty string + $sheet->setCellValue($col . $currentRow, $value); + $col++; + } + + // Style data row + $dataRange = 'B' . $currentRow . ':' . $lastCol . $currentRow; + $sheet->getStyle($dataRange)->applyFromArray([ + 'borders' => [ + 'allBorders' => [ + 'borderStyle' => Border::BORDER_THIN, + 'color' => ['rgb' => '000000'], + ], + ], + 'alignment' => [ + 'horizontal' => Alignment::HORIZONTAL_CENTER, + ], + ]); + + $currentRow++; + } + } + + // Add Grand Total row + $sheet->setCellValue('B' . $currentRow, 'Grand Total'); + $col = 'C'; + foreach ($age_bands as $band) { + $sheet->setCellValue($col . $currentRow, $data['Grand Total'][$band]); + $col++; + } + + // Style Grand Total row + $totalRange = 'B' . $currentRow . ':' . $lastCol . $currentRow; + $sheet->getStyle($totalRange)->applyFromArray([ + 'font' => ['bold' => true], + 'borders' => [ + 'allBorders' => [ + 'borderStyle' => Border::BORDER_THIN, + 'color' => ['rgb' => '000000'], + ], + ], + 'fill' => [ + 'fillType' => Fill::FILL_SOLID, + 'startColor' => ['rgb' => 'F2F2F2'], + ], + 'alignment' => [ + 'horizontal' => Alignment::HORIZONTAL_CENTER, + ], + ]); + + $currentRow += 3; // Add gap after each section + }; + + // Write each SI section with gaps + foreach ($classifiers as $si_type => $data) { + $writeSectionData($data, $sheet, $currentRow, $si_type); + } + + // Auto-size columns + foreach (range('B', chr(ord('B') + count($age_bands))) as $col) { + $sheet->getColumnDimension($col)->setAutoSize(true); + } + + // Create Excel file + try { + // Create Excel file + $writer = new Xlsx($spreadsheet); + $writer->save($filepath); + + // Verify file was created successfully + if (!file_exists($filepath)) { + throw new Exception("Failed to create file: $filepath"); + } + + // Return the file info after creation + $response = [ + 'success' => true, + 'filepath' => $filepath, + 'filename' => $filename, + 'fullpath' => realpath($filepath) + ]; + + return $response; + + } catch (Exception $e) { + return [ + 'success' => false, + 'error' => $e->getMessage() + ]; + } + } + + // Function to delete generated file + public function deleteGeneratedFile($filePath) + { + try { + if (file_exists($filePath)) { + unlink($filePath); // Delete the file + return [ + 'success' => true, + 'message' => "File deleted successfully" + ]; + } else { + return [ + 'success' => false, + 'message' => "File does not exist" + ]; + } + } catch (Exception $e) { + return [ + 'success' => false, + 'error' => $e->getMessage() + ]; + } + } + + public function getAge($available_col, $member, $col_index) + { + if ($available_col == 'age') { + $age = $member[$col_index]; + } else { + $dob = $member[$col_index]; + if ($dob == 'DOB') { + return; + } + $dobDate = \DateTime::createFromFormat('d-M-Y', $dob); + $currentDate = new \DateTime(); + if ($dobDate == false) { + $this->myLogger->logme('error', $dob . 'is not valid'); + return; + } + $age = $currentDate->diff($dobDate)->y; + } + return $age; + } + + public function getAgeRange($age_band) + { + $age_band = trim($age_band); + // Parse age range + if (strpos($age_band, '-') === false) { + $min_age = (int)filter_var($age_band, FILTER_SANITIZE_NUMBER_INT); + $max_age = PHP_INT_MAX; + } else { + $parts = explode("-", $age_band); + $min_age = (int)$parts[0]; + $max_age = (int)$parts[1]; + } + + return array($min_age, $max_age); + } + + //this funciton for send mail to insurer and client with either RFQ/QCR public function sendMailWithAttachement() { helper('excel_util_helper'); helper('MailHelper'); + helper('ExcelMergeHelper'); + $params = $this->request->getPost(); - $params = $this->request->getGet(); // print_r($params); die; + $lead_id = $params['lead_id']; $file_type = $params['file_type']; //rfq or qcr $recipient_type = $params['recipient_type']; //insurer or client or internal or placement $recipient_mail = $params['recipient_mail']; // - only primary key of contacts $recipient_mail = json_decode($params['recipient_mail'], true); // - only primary key of contacts $propsal_and_insurer = isset($params['proposal_insurer']) ? $params['proposal_insurer'] : null; + $mail_content = $params['mail_content']; + $mail_subject = $params['subject']; $result_data = []; // dd($recipient_mail); @@ -687,18 +1327,22 @@ class LeadsController extends BaseController //gather lead info $lead_data = $this->leadsModel ->select('leads.*,policy_type.long_name,policy_type.policy_type,user_profiles.email as created_person_email') - ->join('policy_type', 'leads.policy_type_id = policy_type.id') - ->join('user_profiles', 'leads.created_by = user_profiles.id') + ->join('policy_type', 'leads.policy_type_id = policy_type.id', 'left') + ->join('user_profiles', 'leads.created_by = user_profiles.id', 'left') ->where('leads.id', $lead_id) ->first(); + // print_r($lead_data ); die; + $cc_mails = []; - + $bcc_mails = []; + //get CC Mails - if($recipient_type == 'internal' || $recipient_type == 'placement'){ + if ($recipient_type == 'internal' || $recipient_type == 'placement' || $recipient_type == 'insurer' || $recipient_type == 'client') { $cc_data = isset($params['cc']) ? $params['cc'] : ""; $param_cc_mail = json_decode($cc_data, true); + if (isset($param_cc_mail) && is_array($param_cc_mail) && count($param_cc_mail) > 0) { // Fetch user data where ID is in the param_cc_mail array $userData = $this->userModel @@ -712,18 +1356,49 @@ class LeadsController extends BaseController $cc_mails = array_column($userData, 'email'); // print_r(json_encode($cc_mails)); die; - + // If no emails were found, return an error response - if (empty($cc_mails)) { - return $this->respond(['status' => 'failed','code' => 400,'data' => '','message' => 'No valid CC mail addresses found!'], 200); - } + // if (empty($cc_mails)) { + // return $this->respond(['status' => 'failed','code' => 400,'data' => '','message' => 'No valid CC mail addresses found!'], 200); + // } } else { // Handle case where param_cc_mail is not valid - return $this->respond(['status' => 'failed','code' => 400,'data' => '','message' => 'CC mail not found!'], 200); + // return $this->respond(['status' => 'failed','code' => 400,'data' => '','message' => 'CC mail not found!'], 200); } } + + //get BCC Mails + if ($recipient_type == 'insurer' || $recipient_type == 'client') { + + $bcc_data = isset($params['bcc']) ? $params['bcc'] : ""; + $param_bcc_mail = json_decode($bcc_data, true); + if (isset($param_bcc_mail) && is_array($param_bcc_mail) && count($param_bcc_mail) > 0) { + // Fetch user data where ID is in the param_cc_mail array + $userData = $this->userModel + ->where('is_active', 1) + ->whereIn('id', $param_bcc_mail) + ->findAll(); + + // print_r($userData); die; + + // Extract emails from the fetched user data + $bcc_mails = array_column($userData, 'email'); + + // print_r(json_encode($cc_mails)); die; + + // If no emails were found, return an error response + // if (empty($cc_mails)) { + // return $this->respond(['status' => 'failed','code' => 400,'data' => '','message' => 'No valid CC mail addresses found!'], 200); + // } + + } else { + // Handle case where param_cc_mail is not valid + // return $this->respond(['status' => 'failed','code' => 400,'data' => '','message' => 'CC mail not found!'], 200); + } + } + if ($recipient_type == 'client' && ($lead_data['contact_person_email'] == '' || $lead_data['contact_person_email'] == null)) { return $this->respond(['status' => 'failed', 'code' => 400, 'data' => '', 'messgae' => 'Recipient mail not found ! '], 200); } @@ -733,12 +1408,28 @@ class LeadsController extends BaseController //get file path to attach $file_info = $this->constructExcelToSaveTemp($lead_id, ($file_type == 'rfq' ? 1 : 2), $propsal_and_insurer); + if ($lead_data['file_name'] != null && $lead_data['file_name'] != '') { + $temp_file_path = $file_info['filePath']; + $temp_file_name = $file_info['fileName']; + $lead_file_path = WRITEPATH . 'uploads/lead_files/' . $lead_data['file_name']; + if ($lead_file_path) { + $filePaths = [ + ['file_path' => $temp_file_path, 'sheets' => []], + ['file_path' => $lead_file_path, 'sheets' => []] + ]; + $outputPath = dirname($temp_file_path) . '/' . 'merged_' . $temp_file_name; + $result = ExcelMergeHelper::mergeExcelFiles($filePaths, $outputPath); + // print_rr($result); + } + } + // print_rr($lead_data); + // print_rr($file_info); // $file_path = WRITEPATH."uploads/excel/sample/correction.xls"; // $file_name = $file_type.'.xlsx'; // !dd($file_info); - - $file_path = $file_info['filePath']; - $file_name = $file_info['fileName']; + + $file_path = $result; + $file_name = basename($result); $attachments = [['fileName' => $file_name, 'filePath' => $file_path]]; //get recipient address @@ -753,9 +1444,9 @@ class LeadsController extends BaseController // print_r($recipient_data); die; - } else if($recipient_type == 'client') { + } else if ($recipient_type == 'client') { $recipient_data = [['name' => $lead_data['contact_person_name'], 'email' => $lead_data['contact_person_email']]]; - }else{ + } else { $recipient_data = [['name' => "Team", 'email' => $params['to']]]; } // print_r($recipient_data); die; @@ -763,7 +1454,19 @@ class LeadsController extends BaseController $subject = $file_type == 'rfq' ? 'Request for Quotation from ' . $lead_data['client_name'] . ' for ' . $lead_data['policy_type'] : 'Quotation Comparison Report for ' . $lead_data['policy_type']; $original_message = '

Request for Quotation (RFQ)

Dear {{RECIPIENT_NAME}},

We are reaching out to request a quotation for the following insurance coverage. Please review the details below and provide your quote at your earliest convenience.

RFQ Details

Client name{{CLIENT_NAME}}
Coverage Type{{POLICY_LONG_NAME}}
Policy Start Date{{POLICY_START_DATE}}
Policy Duration{{DURATION}}
Please note: Additional terms and details are included in the attachment for your reference.

Please feel free to reach out if you require any further information to prepare the quote. We look forward to receiving your proposal.

Best regards,

Nhance India Pvt Ltd

© Nhance India Pvt Ltd. All rights reserved.

'; - if($recipient_data){ + //for mail content + if(!empty($mail_content)){ + $original_message = $mail_content; + } + + //for mail subject + if(!empty($mail_subject)){ + $subject = $mail_subject; + } + + // print_r($subject); die; + + if ($recipient_data) { foreach ($recipient_data as $recipient) { $message = $original_message; @@ -775,13 +1478,13 @@ class LeadsController extends BaseController // print_rr($message);calculate_days_bw_dates - $res = MailHelper::send_email(['mail' => $recipient['email'], 'cc'=> $cc_mails, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to]); + $res = MailHelper::send_email(['mail' => $recipient['email'], 'cc' => $cc_mails, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to, 'bcc' => $bcc_mails]); // !dd($res); $result_data[] = ['mail' => $recipient['email'], 'status' => $res]; } } - if($recipient_type == 'placement'){ + if ($recipient_type == 'placement') { list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2); @@ -789,11 +1492,16 @@ class LeadsController extends BaseController 'proposel_name' => $proposal_key, 'insurer_name' => $insurer_key, 'insurer' => $params['insurer_and_branch'], - ] ; + ]; $data = [ 'proposel_data' => json_encode($lead_update_data), - 'status' => 'won' + 'status' => 'won', + 'placement_date' => change_date_format($params['placement_date'], 'd/m/Y', 'Y-m-d'), + 'utr_no' => $params['utr_no'], + 'premium_amount' => $params['premium_amount'], + 'total_amount' => $params['total_amount'], + 'cd_amount' => $params['cd_amount'], ]; $this->leadsModel->where('id', $lead_id)->set($data)->update(); @@ -809,12 +1517,11 @@ class LeadsController extends BaseController $data = $this->levelContactModel->getContactForRFQ(); - if($data){ + if ($data) { return $this->respond(['status' => true, 'data' => $data], 200); - }else{ + } else { return $this->respond(['status' => false], 200); } - } public function getInsurerBranchContacts($insurer_and_branch_id) @@ -822,12 +1529,12 @@ class LeadsController extends BaseController if (strpos($insurer_and_branch_id, '-') === false) { return $this->respond(['status' => false, 'message' => 'Invalid ID format'], 400); } - + // Split the insurer_and_branch_id list($insurerBranchId, $insurerId) = explode('-', $insurer_and_branch_id); - + $data = $this->levelContactModel->getContactForRFQ($insurerId, $insurerBranchId); - + if (!empty($data)) { return $this->respond(['status' => true, 'data' => $data], 200); } else { @@ -835,12 +1542,12 @@ class LeadsController extends BaseController } } - function transformProposelData($data, $proposel, $insurer){ + public function transformProposelData($data, $proposel, $insurer){ // print_r($data['premium_data']['data']); die; $headerData = []; - + // Default headers: S. No and Particulars $defaultHeaders = [ [ @@ -852,10 +1559,10 @@ class LeadsController extends BaseController 'subHeaders' => ['-'] ] ]; - + // Add default headers to the result $headerData = array_merge($headerData, $defaultHeaders); - + foreach ($data['table_data']['headers'] as $header) { // Check if the parentHeader matches the target proposal if ($header['parentHeader'] === $proposel) { @@ -882,13 +1589,13 @@ class LeadsController extends BaseController $sno = $entry['SNO']; $items = $entry['items']; $dataEntry = $entry['data']; - + $result = [ "SNO" => $sno, "items" => $items, "data" => [] ]; - + foreach ($dataEntry as $item) { // Include Sno and Particulars by default @@ -900,7 +1607,7 @@ class LeadsController extends BaseController "input_value" => $item['input_value'] ]; } - + // Include Proposal with Quote Asked by default if ($item['parentth'] === $proposel && $item['subth'] === "Quote Asked") { $result['data'][] = [ @@ -910,7 +1617,7 @@ class LeadsController extends BaseController "input_value" => $item['input_value'] ]; } - + // Example of including matching specific proposals and insurers if ($item['parentth'] === $proposel && $item['subth'] === $insurer) { $result['data'][] = [ @@ -921,13 +1628,13 @@ class LeadsController extends BaseController ]; } } - + // Add to the final result $columnData[] = $result; } - + $premiumData = []; - + foreach ($data['premium_data']['data'] as $key => $value) { if ($key === $proposel) { $premiumData[$key]['Quote Asked'] = $value['Quote Asked']; @@ -940,112 +1647,157 @@ class LeadsController extends BaseController $data['premium_data']['data'] = $premiumData; return $data; - } - function convertJsonForQCR($json, $type) + public function convertJsonForQCR($json, $type) { if ($json) { + // Deep copy of JSON $first_json = json_decode(json_encode($json), true); + // dd($first_json); - // Column-wise Check: Remove headers and relevant data if qcr == 0 - foreach ($json['proposal_data']['over_all_column_data'] as $proposalKey => $proposalData) { - if ($proposalData['stc'] == 0 || $proposalData['stc'] === false) { - // Remove matching parentHeader in headers - foreach ($first_json['table_data']['headers'] as $index => $header) { - if ($header['parentHeader'] === $proposalKey) { - unset($first_json['table_data']['headers'][$index]); - } - } - - // Remove data entries with matching parentth - foreach ($first_json['table_data']['data'] as &$item) { - $item['data'] = array_values(array_filter($item['data'], function ($entry) use ($proposalKey) { - return $entry['parentth'] !== $proposalKey; - })); - } - - // Remove proposalKey from over_all_column_data - unset($first_json['proposal_data']['over_all_column_data'][$proposalKey]); - - if($type == 'stc'){ - // Remove proposalKey from premium_data - unset($first_json['premium_data']['data'][$proposalKey]); - } - } - - // Insurer Check: Remove subHeaders and relevant data for insurers with qcr == 0 - foreach ($proposalData['insurers'] as $insurerIndex => $insurer) { - if ($insurer['stc'] === 0 || $insurer['stc'] === false) { - foreach ($first_json['table_data']['headers'] as &$header) { - if (isset($header['subHeaders'])) { - $header['subHeaders'] = array_values(array_filter($header['subHeaders'], function ($sub) use ($insurer) { - return $sub !== $insurer['display_name']; - })); + if($type == 2){ + + // Column-wise Check: Remove headers and relevant data if qcr == 0 + foreach ($json['proposal_data']['over_all_column_data'] as $proposalKey => $proposalData) { + + if (($proposalData['qcr'] == 0 || $proposalData['qcr'] === false) || ($proposalData['stc'] == 0 || $proposalData['stc'] === false)) { + + // Remove matching parentHeader in headers + foreach ($first_json['table_data']['headers'] as $index => $header) { + if ($header['parentHeader'] === $proposalKey) { + unset($first_json['table_data']['headers'][$index]); } } - + // Remove data entries with matching parentth foreach ($first_json['table_data']['data'] as &$item) { - $item['data'] = array_values(array_filter($item['data'], function ($entry) use ($insurer) { - return $entry['subth'] !== $insurer['display_name']; + $item['data'] = array_values(array_filter($item['data'], function ($entry) use ($proposalKey) { + return $entry['parentth'] !== $proposalKey; })); } - - // Remove insurer from proposal's insurers array - unset($first_json['proposal_data']['over_all_column_data'][$proposalKey]['insurers'][$insurerIndex]); - if($type == 'stc'){ - unset($first_json['premium_data']['data'][$proposalKey][$insurer['display_name']]); + // Remove proposalKey from over_all_column_data + unset($first_json['proposal_data']['over_all_column_data'][$proposalKey]); + + if($type == 2){ + // Remove proposalKey from premium_data + unset($first_json['premium_data']['data'][$proposalKey]); + } + } + + // Insurer Check: Remove subHeaders and relevant data for insurers with qcr == 0 + foreach ($proposalData['insurers'] as $insurerIndex => $insurer) { + if (($insurer['qcr'] === 0 || $insurer['qcr'] === false) || ($insurer['stc'] === 0 || $insurer['stc'] === false) ) { + foreach ($first_json['table_data']['headers'] as &$header) { + if (isset($header['subHeaders'])) { + $header['subHeaders'] = array_values(array_filter($header['subHeaders'], function ($sub) use ($insurer) { + return $sub !== $insurer['display_name']; + })); + } + } + + + foreach ($first_json['table_data']['data'] as &$item) { + $item['data'] = array_values(array_filter($item['data'], function ($entry) use ($insurer) { + return $entry['subth'] !== $insurer['display_name']; + })); + } + + // Remove insurer from proposal's insurers array + unset($first_json['proposal_data']['over_all_column_data'][$proposalKey]['insurers'][$insurerIndex]); + + if($type == 2){ + unset($first_json['premium_data']['data'][$proposalKey][$insurer['display_name']]); + } } } } - } - - // Row-wise Check: Remove rows if qcr == 0 for actions - foreach ($first_json['table_data']['data'] as $rowKey => $rowData) { - foreach ($rowData['data'] as $data) { - if ($data['parentth'] === "Action" && isset($data['input_value']['stc']) && $data['input_value']['stc'] == 0) { - unset($first_json['table_data']['data'][$rowKey]); - break; + + // Row-wise Check: Remove rows if qcr == 0 for actions + foreach ($first_json['table_data']['data'] as $rowKey => $rowData) { + foreach ($rowData['data'] as $data) { + if ($data['parentth'] === "Action" && (isset($data['input_value']['qcr']) && $data['input_value']['qcr'] == 0) || (isset($data['input_value']['stc']) && $data['input_value']['stc'] == 0)) { + unset($first_json['table_data']['data'][$rowKey]); + break; + } } } + + // Reindex arrays to maintain proper structure + $first_json['table_data']['headers'] = array_values($first_json['table_data']['headers']); + $first_json['table_data']['data'] = array_values($first_json['table_data']['data']); + $first_json['proposal_data']['over_all_column_data'] = array_map(function ($proposal) { + $proposal['insurers'] = array_values($proposal['insurers']); + return $proposal; + }, $first_json['proposal_data']['over_all_column_data']); + + }else{ + + //remove insurer as Subheaders for RFQ + foreach ($first_json['table_data']['headers'] as &$header) { + $header['subHeaders'] = array_filter($header['subHeaders'], function ($subHeader) { + return in_array($subHeader, ['Quote Asked', '-']); + }); + } + + //Remove insurer Row wise data for RFQ + foreach ($first_json['table_data']['data'] as &$row) { + + // Filter the inner data array + $row['data'] = array_filter( + $row['data'], + function ($item) { + return in_array($item['subth'], ['Quote Asked', '-']); + } + ); + + $row['data'] = array_values($row['data']); + } + + // Ensure to unset the reference after the loop + unset($row); + + + // Remove insurers from Proposal Data key for RFQ + foreach ($first_json['proposal_data']['over_all_column_data'] as $key => &$proposal) { + if (isset($proposal['insurers'])) { + // Set the insurers array to empty + $proposal['insurers'] = []; + } + } + + // Ensure to reset the reference + unset($proposal); + } - - // Reindex arrays to maintain proper structure - $first_json['table_data']['headers'] = array_values($first_json['table_data']['headers']); - $first_json['table_data']['data'] = array_values($first_json['table_data']['data']); - $first_json['proposal_data']['over_all_column_data'] = array_map(function ($proposal) { - $proposal['insurers'] = array_values($proposal['insurers']); - return $proposal; - }, $first_json['proposal_data']['over_all_column_data']); - + return $first_json; } - + return null; } - + //----- Featch Lead data and insert Client ------------------------------------------------------------------------------------------- public function featchLeadDataAndInsertClient($lead_id) { $data = $this->leadsModel->where('leads.id', $lead_id)->where('leads.is_active', 1)->first(); - + if (!$data) { return $this->respond(['status' => false, 'message' => 'Failed to create Client', 'data' => null], 200); } - + $result = $this->createClientWithLeadData($data); - + if ($result) { $policy_data = $this->clientPolicyModel->where('client_id', $result)->where('is_active', 1)->first(); return $this->respond(['status' => true, 'message' => 'New Client created successfully', 'client_id' => $result, 'data' => $data, 'client_policy_id' => $policy_data['id']], 200); } - + return $this->respond(['status' => false, 'message' => 'Failed to create client', 'data' => $data], 200); } @@ -1061,7 +1813,7 @@ class LeadsController extends BaseController return $client_id; } - + private function prepareClientData($data) { return [ @@ -1073,27 +1825,27 @@ class LeadsController extends BaseController 'pan' => $data['pan'], ]; } - + public function createClientBranchAndContactWithLeadData($data, $client_id) { $branch_data = $this->prepareClientBranchData($data, $client_id); $branch_id = $this->clientBranchModel->insert($branch_data); - + if ($branch_id) { $this->leadsModel->where('id', $data['id'])->set('is_client_created', $client_id)->update(); $contact_data = $this->prepareContactData($data, $branch_id); $this->levelContactModel->insert($contact_data); - + $this->createClientPolicyWithLeadData($data, $client_id, $branch_id); } - + return $branch_id; } - + private function prepareClientBranchData($data, $client_id) { $default_unit = trim(($data['client_short_name'] ?? '') . '-' . ($data['branch_code'] ?? ''), '-'); - + return [ 'client_id' => $client_id, 'branch_name' => $data['branch_name'], @@ -1102,7 +1854,7 @@ class LeadsController extends BaseController 'units' => json_encode([$default_unit]), ]; } - + private function prepareContactData($data, $branch_id) { return [ @@ -1113,22 +1865,22 @@ class LeadsController extends BaseController 'ref_id' => $branch_id, ]; } - + public function createClientPolicyWithLeadData($data, $client_id, $branch_id) { $client_policy_data = $this->prepareClientPolicyData($data, $client_id, $branch_id); $client_policy_id = $this->clientPolicyModel->insert($client_policy_data); - if($client_policy_id){ + if ($client_policy_id) { $this->leadsModel->where('id', $data['id'])->set('is_client_created', $client_id)->update(); } return $client_policy_id; } - + private function prepareClientPolicyData($data, $client_id, $branch_id) - { + { $proposel_data = json_decode($data['proposel_data'], true); // print_r($proposel_data); die; list($insurer_branch_id, $insurer_id) = explode('-', $proposel_data['insurer'], 2); @@ -1147,7 +1899,7 @@ class LeadsController extends BaseController ]; $terms = $this->preparePolicyTermsFromRFQ($data); - + $policy_type_id = $data['policy_type_id']; if (in_array($policy_type_id, [1, 2, 6, 7])) { $client_policy_data['is_addon'] = 1; // Base Policy @@ -1157,61 +1909,114 @@ class LeadsController extends BaseController // if ($base_policy) { // $data['is_addon'] = 3; // Dependent Addon // } else { - $data['is_addon'] = 1; + $data['is_addon'] = 1; // } } $client_policy_data['policy_terms'] = $this->preparePolicyTermsFromRFQ($data); // print_r($client_policy_data); die; - + return $client_policy_data; } - + private function preparePolicyTermsFromRFQ($data) - { + { $proposel_data = json_decode($data['proposel_data'], true); $QCRData = $this->RFQModel->where('is_active', 1)->where('type', 2)->where('lead_id', $data['id'])->first(); - + $JSON = json_decode($QCRData['json'], true); - $converted_json = $this->transformProposelData($JSON, $proposel_data['proposel_name'], $proposel_data['insurer_name']); - + $converted_json = $this->transformProposelData($JSON, $proposel_data['proposel_name'], $proposel_data['insurer_name']); + return $this->convertQCRJsonToPolicyTerms($converted_json, $data['policy_type_id'], $proposel_data['proposel_name'], $proposel_data['insurer_name']); } private function convertQCRJsonToPolicyTerms($data, $policy_type, $proposel_name, $insurer_name) { $GMC_Keys = [ - "sum_insured", "family_floater", "family_floaters", "age_ratio", "waiverofpreexistingdiseases", - "maternitycoverage", "twindelivery", "preandpostnatal", "babyday1cover", "9monthwaitingperiodwaived", - "coverfromthedateofjoining", "waiverof1,2,3&4thyearexclusions", "waiverof30dayswaitingperiod", - "prehospitalizationcover", "congenitaldiseasesinternal", "copayzonewisecopay", - "bioabsorbablestenttoriclensmultifocallens", "roomrentlimit", "proportionatedeductionclause", - "ailmentcapping", "ambulancecharges", "airambulance", "familytransportationbenefit", - "reasonableandcustomarycharges", "ayudhtreatmentcover", "congenitaldiseasesexternal", - "optionalparentalcopay", "posthospitalizationcover", "corporatebuffer", "sublimitofcorporatebuffer", - "ayushTreatmentCoverData", "armdcovered", "suminsuredenhancement", "automaticsuminsuredreinstatement", - "additionalsicknessbenefit", "lasiksurgery", "midterminclusion", "capd", "organdonorexpenses", - "moderntreatmentsasperirdai", "Wellness", "days_of_discharge", "days_from_dod", - "special_condition_label", "special_condition_input", "multiple_sum_insured", - "cataract", "cataractData" + "sum_insured", + "family_floater", + "family_floaters", + "age_ratio", + "waiverofpreexistingdiseases", + "maternitycoverage", + "twindelivery", + "preandpostnatal", + "babyday1cover", + "9monthwaitingperiodwaived", + "coverfromthedateofjoining", + "waiverof1,2,3&4thyearexclusions", + "waiverof30dayswaitingperiod", + "prehospitalizationcover", + "congenitaldiseasesinternal", + "copayzonewisecopay", + "bioabsorbablestenttoriclensmultifocallens", + "roomrentlimit", + "proportionatedeductionclause", + "ailmentcapping", + "ambulancecharges", + "airambulance", + "familytransportationbenefit", + "reasonableandcustomarycharges", + "ayudhtreatmentcover", + "congenitaldiseasesexternal", + "optionalparentalcopay", + "posthospitalizationcover", + "corporatebuffer", + "sublimitofcorporatebuffer", + "ayushTreatmentCoverData", + "armdcovered", + "suminsuredenhancement", + "automaticsuminsuredreinstatement", + "additionalsicknessbenefit", + "lasiksurgery", + "midterminclusion", + "capd", + "organdonorexpenses", + "moderntreatmentsasperirdai", + "Wellness", + "days_of_discharge", + "days_from_dod", + "special_condition_label", + "special_condition_input", + "multiple_sum_insured", + "cataract", + "cataractData" ]; - + $GPA_Keys = [ - "sumInsured2", "totalSumInsured", "age_ratio", "accidentalDeathBenefit", "permanentTotalDisablement", - "permanentPartialDisablement", "temporaryTotalDisablementBenefit", "accidentalHospitalizationExpenses", - "childrenEducationWelfareFund", "compassionateVisitExpenses", "compassionateVisitExpensesData", - "brokenBoneExpenses", "brokenBoneExpensesData", "ambulanceCharges", "ambulanceChargesData", - "burnExpenses", "burnExpensesData", "carriageOfDeadBody", "carriageOfDeadBodyData", - "animalSnakeInsectBite", "terrorism", "worldwideCover", "gpa_special_condition_label", - "gpa_special_condition_input", "multiple_sum_insured" + "sumInsured2", + "totalSumInsured", + "age_ratio", + "accidentalDeathBenefit", + "permanentTotalDisablement", + "permanentPartialDisablement", + "temporaryTotalDisablementBenefit", + "accidentalHospitalizationExpenses", + "childrenEducationWelfareFund", + "compassionateVisitExpenses", + "compassionateVisitExpensesData", + "brokenBoneExpenses", + "brokenBoneExpensesData", + "ambulanceCharges", + "ambulanceChargesData", + "burnExpenses", + "burnExpensesData", + "carriageOfDeadBody", + "carriageOfDeadBodyData", + "animalSnakeInsectBite", + "terrorism", + "worldwideCover", + "gpa_special_condition_label", + "gpa_special_condition_input", + "multiple_sum_insured" ]; - + // Select keys based on policy type $termsKey = $policy_type == 1 ? $GPA_Keys : $GMC_Keys; - + // Initialize terms_array with default empty values $terms_array = array_fill_keys($termsKey, ""); $specialKeys = ['special_condition_label', 'special_condition_input', 'gpa_special_condition_label', 'gpa_special_condition_input', 'multiple_sum_insured']; @@ -1226,37 +2031,39 @@ class LeadsController extends BaseController "child" => ["min" => 0, "max" => "25"], "elders" => ["min" => 0, "max" => 0], ] : ["self" => ["min" => "18", "max" => "60"]]; - + foreach ($data['table_data']['data'] as $dataRow) { $item = $dataRow['items'] ?? ''; - + foreach ($dataRow['data'] as $cellData) { $parentth = $cellData['parentth'] ?? ''; $subth = $cellData['subth'] ?? ''; $input_value = $cellData['input_value'] ?? ''; $value = $cellData['value'] ?? ''; - + // Skip unwanted keys - if (in_array($parentth, ['Sno', 'Item Key', 'Particulars', 'Action']) || - in_array($subth, ['Quote Asked'])) { + if ( + in_array($parentth, ['Sno', 'Item Key', 'Particulars', 'Action']) || + in_array($subth, ['Quote Asked']) + ) { continue; } - + // Handle special conditions if (str_starts_with($item, "special_condition") && $parentth === $proposel_name && $subth === $insurer_name) { - + $parts = explode("-", $input_value); $question = $parts[0] ?? ''; $answer = $parts[1] ?? ''; $labelKey = $policy_type == 1 ? 'gpa_special_condition_label' : 'special_condition_label'; $inputKey = $policy_type == 1 ? 'gpa_special_condition_input' : 'special_condition_input'; - + $terms_array[$labelKey][] = $question; $terms_array[$inputKey][] = $answer; continue; } - + // Handle sum insured if (in_array($item, ['sum_insured', 'sumInsured2'])) { $si_amt = explode(",", $value); @@ -1264,42 +2071,94 @@ class LeadsController extends BaseController $terms_array['multiple_sum_insured'] = array_slice($si_amt, 1); continue; } - + // Handle family floaters if ($item === 'family_composition') { $terms_array['family_floaters'] = isJsonString($input_value) ? json_decode($input_value, true) : $input_value; continue; } - + // Decode JSON if valid $terms_array[$item] = isJsonString($input_value) ? (json_decode($input_value, true)['key'] ?? '') : $input_value; } } - + return json_encode($terms_array); } - + public function featchClientPolicyFromLead($client_id, $branch_id, $lead_id) { $data = $this->leadsModel->where('leads.id', $lead_id)->where('leads.is_active', 1)->first(); - + if (!$data) { return $this->respond(['status' => false, 'message' => 'Failed to create policy', 'data' => null], 200); } - + $result = $this->createClientPolicyWithLeadData($data, $client_id, $branch_id); // print_r($result); die; - + if ($result) { $policy_data = $this->clientPolicyModel->where('id', $result)->where('is_active', 1)->first(); return $this->respond(['status' => true, 'message' => 'New Policy created successfully', 'client_policy_id' => $result, 'data' => $data, 'client_id' => $policy_data['client_id']], 200); } - + return $this->respond(['status' => false, 'message' => 'Failed to create policy', 'data' => $data], 200); - } -} \ No newline at end of file + //------------------------------------------------------------------------------------------------ + + + public function transformMailContent($lead_id) + { + helper('excel_util_helper'); + // $params = $this->request->getGet(); + + // print_r($params); die; + // $lead_id = $params['lead_id']; + // $file_type = $params['file_type']; //rfq or qcr + // $recipient_type = $params['recipient_type']; //insurer or client or internal or placement + // $recipient_mail = $params['recipient_mail']; // - only primary key of contacts + // $propsal_and_insurer = isset($params['proposal_insurer']) ? $params['proposal_insurer'] : null; + + // if ($recipient_type == 'insurer' && empty($recipient_mail)) { + // return $this->respond(['status' => 'failed', 'code' => 400, 'data' => '', 'messgae' => 'Recipient mail not found ! '], 200); + // } + + //gather lead info + $lead_data = $this->leadsModel + ->select('leads.*,policy_type.long_name,policy_type.policy_type,user_profiles.email as created_person_email') + ->join('policy_type', 'leads.policy_type_id = policy_type.id', 'left') + ->join('user_profiles', 'leads.created_by = user_profiles.id', 'left') + ->where('leads.id', $lead_id) + ->first(); + + // dd($lead_data); + + if($lead_data){ + + $recipient_data = ['name' => "Team"]; + $original_message = '

Request for Quotation (RFQ)

Dear {{RECIPIENT_NAME}},

We are reaching out to request a quotation for the following insurance coverage. Please review the details below and provide your quote at your earliest convenience.

RFQ Details

Client name{{CLIENT_NAME}}
Coverage Type{{POLICY_LONG_NAME}}
Policy Start Date{{POLICY_START_DATE}}
Policy Duration{{DURATION}}
Please note: Additional terms and details are included in the attachment for your reference.

Please feel free to reach out if you require any further information to prepare the quote. We look forward to receiving your proposal.

Best regards,

Nhance India Pvt Ltd

© Nhance India Pvt Ltd. All rights reserved.

'; + + $message = $original_message; + $message = str_replace("{{RECIPIENT_NAME}}", $recipient_data['name'], $message); + $message = str_replace("{{CLIENT_NAME}}", $lead_data['client_name'], $message); + $message = str_replace("{{POLICY_LONG_NAME}}", $lead_data['long_name'], $message); + $message = str_replace("{{POLICY_START_DATE}}", change_date_format($lead_data['policy_start_date'], 'Y-m-d', 'd-m-Y'), $message); + $message = str_replace("{{DURATION}}", calculate_days_bw_dates($lead_data['policy_end_date'] ?? "", $lead_data['policy_start_date'] ?? "")->days, $message) ?? '--'; + + // return $this->respond(['status' => true, 'code' => 200, 'data' => $message], 200); + return $message; + + }else{ + + // return $this->respond(['status' => false, 'code' => 404, 'message' => "This lead has not data"], 200); + return ''; + } + + + + } +} diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php index a875e437..4b5c9032 100755 --- a/app/Controllers/MasterController.php +++ b/app/Controllers/MasterController.php @@ -1224,7 +1224,7 @@ class MasterController extends AdminController $data = $this->request->getPost(); $date = (string) $this->request->getPost('opening_date'); $data['opening_date'] = date('Y-m-d', strtotime($date)); - + // print_rr($data);die(); // Prepare the array with data $cd_tranction_data = [ 'amount' => $data['opening_bal'], @@ -1247,7 +1247,7 @@ class MasterController extends AdminController $insert = $this->CDMasterModel->insert($data); if ($insert) { - + $cd_tranction_data['cd_ac_pk'] = $this->CDMasterModel->insertID(); $response = DepositHelper::saveDeposit($cd_tranction_data, $loggedInUserID); session()->setFlashdata('success', "Cash Deposite Master Added Successfully"); @@ -1313,12 +1313,31 @@ class MasterController extends AdminController ->where('id', $id) ->where('is_active', 1) ->first(); + + $db = db_connect(); + $builder = $db->table('cd_master'); + $builder->select('cd_master.cd_ac_no, cd_master.id, COUNT(cash_deposit.cd_ac_no) AS cd_ac_no_count_cd_tranction'); + $builder->join('cash_deposit', 'cash_deposit.cd_ac_pk = cd_master.id'); + $builder->where('cash_deposit.is_active', 1); + $builder->where('cd_master.is_active', 1); + $builder->where('cd_master.id', $id); + $builder->groupBy('cd_master.id'); - // convert the date formate 2000-01-01 to 01-01-2000 + $query = $builder->get(); + $result = $query->getResultArray(); + + // print_r($result); die; + + $count = 0; + if(isset($result[0])){ + $count = $result[0]['cd_ac_no_count_cd_tranction']; + } + + // convert the date formate 2000-01-01 to 01-01-2000 $cd_data['opening_date'] = date('d-m-Y', strtotime($cd_data['opening_date'])); if ($cd_data) { - return $this->respond(['status' => true, 'code' => 200, 'data' => $cd_data], 200); + return $this->respond(['status' => true, 'code' => 200, 'data' => $cd_data, 'cd_transaction_count' => $count], 200); } else { return $this->respond(['status' => false, 'code' => 404], 200); } @@ -1502,25 +1521,34 @@ class MasterController extends AdminController } - public function duplicateTemplate($template_id, $event_name) + // Duplicate the insuer same policy type other events template + public function duplicateTemplate($template_id, $event_name, $insurer_id) { + // Fetch the template data based on the provided ID and ensure it is active $insurer_template_data = $this->insurerTemplateModel->where('id', $template_id) - ->where('is_active', 1) - ->first(); + ->where('is_active', 1) + ->first(); + + // Check if the event name matches the existing template's event name + $insurer_template_data_check_duplicate = $this->insurerTemplateModel + ->where('insurer_id', $insurer_id) + ->where('event_name', $event_name) + ->where('policy_type_id', $insurer_template_data['policy_type_id']) + ->where('is_active', 1) + ->findAll(); + + //if the template already exist than return the message + if (!empty($insurer_template_data_check_duplicate) && count($insurer_template_data_check_duplicate) > 0) { + return $this->respond([ + 'status' => false, + 'message' => 'Template with the same event already exists.', + 'data' => $insurer_template_data_check_duplicate + ]); + } - if ($insurer_template_data) { - - // Check if the event name matches the existing template's event name - if ($insurer_template_data['event_name'] == $event_name) { - return $this->respond([ - 'status' => false, - 'message' => 'Template with the same event already exists.', - 'data' => $insurer_template_data - ]); - } - + // Prepare data for insertion as a duplicate $data_to_insert = [ "insurer_id" => $insurer_template_data['insurer_id'], @@ -1531,28 +1559,28 @@ class MasterController extends AdminController "created_by" => get_session_user(), "is_active" => 1, ]; - + // Insert the duplicate template data $insert_result = $this->insurerTemplateModel->insert($data_to_insert); - + if ($insert_result) { return $this->respond([ - 'status' => true, - 'message' => 'Template duplicated successfully.', + 'status' => true, + 'message' => 'Template duplicated successfully.', 'data' => $insurer_template_data ]); } else { return $this->respond([ - 'status' => false, - 'message' => 'Failed to duplicate template.', + 'status' => false, + 'message' => 'Failed to duplicate template.', 'data' => $insurer_template_data ]); } } else { // No matching active template found return $this->respond([ - 'status' => false, - 'message' => 'No active template data found.', + 'status' => false, + 'message' => 'No active template data found.', 'data' => null ]); } @@ -1632,7 +1660,35 @@ class MasterController extends AdminController print_r($res); } - + + public function testZeptoSMTP() { + $message = ''; + $attachments = [ + ["filePath" => ROOTPATH."public/sample_excel/sample_addition.xls","fileName" => "sample_addition.xls"], + ["filePath" => ROOTPATH."public/sample_excel/sample_inception.xls","fileName" => "sample_inception.xls"], + ["filePath" => ROOTPATH."public/assets/images/login_bg.jpg","fileName" => "login_bg.jpg"] + ]; + $email_id = 'srinivas.saravanan@venbainfotech.com'; + $common = ['mail_type'=>'test_mail_cli']; + // Send email and get response + $result = MailHelper::send_email(['mail' => $email_id, 'subject' => 'Mail Via CLI', 'message' => $message,'attachments' => $attachments,'common'=>$common]); + + + log_message('error',json_encode($result)); + // Format the response for display/debugging + $response = [ + 'success' => $result['success'] ?? false, + 'smtp_data' => [ + 'last_reply' => $result['smtp_data']['last_reply'] ?? '', + 'error_info' => $result['smtp_data']['error_info'] ?? '' + ], + 'message_id' => $result['message_id'] ?? '', + 'timestamp' => $result['timestamp'] ?? '' + ]; + + // Return JSON response + return $this->response->setJSON($result); + } public function testCheckBounceMails() { $gmailapi = \Config\Services::gmailapi(); @@ -1674,6 +1730,7 @@ class MasterController extends AdminController 'template_bg' => ROOTPATH . 'public/uploads/template_bg/', 'attachments' => WRITEPATH . 'uploads/attachments/', 'sample_import_excel' => ROOTPATH . 'public/sample_import_excel', + 'lead_files' => WRITEPATH . 'uploads/lead_files/', ]; foreach ($folders as $folderName => $folderPath) { diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php index 5e94b340..6784c0fd 100644 --- a/app/Controllers/PolicyTransactionController.php +++ b/app/Controllers/PolicyTransactionController.php @@ -31,6 +31,7 @@ use App\Models\InsurerStatements; use App\Models\InvPaymentDetailsModel; use App\Models\BatchFileModel; use App\Models\FileModel; +use App\Models\COShareStmtDetailsModel; use Kint; class PolicyTransactionController extends BaseController @@ -62,6 +63,7 @@ class PolicyTransactionController extends BaseController protected $invPaymentDetailsModel; protected $batchFileModel; protected $filesModel; + protected $coShareStmtDetailsModel; public function __construct() { @@ -91,11 +93,12 @@ class PolicyTransactionController extends BaseController $this->invPaymentDetailsModel = new InvPaymentDetailsModel(); $this->batchFileModel = new BatchFileModel(); $this->filesModel = new FileModel(); + $this->coShareStmtDetailsModel = new COShareStmtDetailsModel(); $this->invoiceStatus = [ 'pending' => 'Pending', 'generated' => 'Generated', 'sent' => 'Sent', - 'payment_received' => 'Payment Received', + 'payment_received' => 'Payment
Received', ]; } @@ -179,6 +182,7 @@ class PolicyTransactionController extends BaseController // Fetch additional data $data['client'] = $this->clientModel->where('is_active', 1)->findAll(); + $data['client_branch'] = $this->clientBranchModel->where('is_active', 1)->findAll(); $data['policy_type'] = $this->policyTypeModel->where('is_active', 1)->findAll(); $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll(); $data['entity'] = $this->kycEntityTypeModel->where('is_active', 1)->findAll(); @@ -221,6 +225,7 @@ class PolicyTransactionController extends BaseController // print_r($this->request->getPost()); die; $id = $this->request->getPost('id'); $data = $this->preparePolicyData(); + $data['cd_ac_pk'] = $this->request->getPost('cd_ac_no'); // print_r($this->request->getPost()); die; @@ -430,7 +435,7 @@ class PolicyTransactionController extends BaseController if(isset($data['follow_insurer_id'])){ foreach ($data['follow_insurer_id'] as $index => $insurer) { - + // Separate the insurer and insurer branch list($insurer_branch_id, $insurer_id) = explode('-', $insurer); @@ -473,6 +478,7 @@ class PolicyTransactionController extends BaseController 'created_by' => get_session_userid() ?? null, 'updated_by' => get_session_userid() ?? null, 'id' => $data['co_share_id'][$index] ?? null, // Assuming this is the ID to identify existing records + 'follower_policy_no' => $data['follower_policy_no'][$index] ?? null, // Assuming this is the ID to identify existing records ]; } @@ -529,7 +535,7 @@ class PolicyTransactionController extends BaseController 'created_by' => get_session_userid(), 'policy_no' => $data['policy_no'] ?? null, 'client_branch_id' => $data['client_branch_id'] ?? 0, - 'cd_ac_no' => $data['cd_ac_no'] ?? null, + 'cd_ac_pk' => $data['cd_ac_no'] ?? null, 'gst' => 18, ]; } @@ -786,10 +792,24 @@ class PolicyTransactionController extends BaseController ->findAll(); $data['pt_co_share_details'] = $this->PTCOShareDetailsModel - ->where('pt_id', $id) - ->where('is_active', 1) - ->orderBy('id', 'asc') - ->findAll(); + ->select(" + pt_co_share_details.*, + + ( + SELECT + COUNT(*) + FROM + co_share_stmt_details + WHERE + co_share_stmt_details.co_share_id = pt_co_share_details.id + AND co_share_stmt_details.is_active = 1 + ) AS record_count + ") + ->where('pt_id', $id) + ->where('is_active', 1) + ->orderBy('id', 'asc') + ->findAll(); + $data['emp_data'] = $this->employeeModel ->select('employees.*, employee_polices.id as emp_policy_id') ->join('employee_polices', 'employees.id = employee_polices.employee_id', 'left') @@ -1329,8 +1349,8 @@ class PolicyTransactionController extends BaseController //--------------------------------------------------------------------------------------------------- - //get BDS Reports data - public function reportBDS() + //get BDS Reports data old function + public function reportBDSOld() { $data['page_name'] = 'BDS Report'; @@ -1390,6 +1410,81 @@ class PolicyTransactionController extends BaseController $this->loadLayout('report_bds_filter', $data); } + //get BDS Reports data New Function + public function reportBDS() + { + + $data['page_name'] = 'BDS Report'; + + $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance']; + $data['client_type'] = [1 => 'Group', 2 => 'Individual']; + $data['issuing_type'] = [1 => 'Fresh', 2 => 'Renewal', 3 => 'Roll Over']; + $data['policy_status'] = [ + 'pending' => 'Pending', + 'exported_to_insurer' => 'Exported to Insurer', + 'imported_from_insurer' => 'Imported from Insurer', + 'exported_to_tpa' => 'Exported to TPA', + 'imported_from_tpa' => 'Imported from TPA', + 'completed' => 'Completed' + ]; + $data['invoice_status_array'] = [ + 'yet_to_generate' => 'Yet to Generate', + 'generated' => 'Generated', + 'send' => 'Send', + 'recived' => 'Recived', + ]; + $data['date_type'] = [ + 'policy_issue_date' => 'Policy Issue Date', + 'policy_start_date' => 'Policy Start Date', + 'policy_end_date' => 'Policy End Date', + 'data_received_date' => 'Data Received Date', + 'closure_date' => 'Closure Date', + 'statement_month' => 'Statement Month', + ]; + + $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll(); + $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll(); + $data['clients'] = $this->clientModel->where('is_active', 1)->findAll(); + + //filter datas + $start_date = $this->request->getGet('start_date'); + $end_date = $this->request->getGet('end_date'); + $client_id = $this->request->getGet('client_id'); + $insurer_id = $this->request->getGet('insurer_id'); + $policy_type_id = $this->request->getGet('policy_type_id'); + $date_type = $this->request->getGet('date_type'); + $issuer = $this->request->getGet('issuer'); + $client_branch_id = $this->request->getGet('client_branch_id'); + $insurer_branch_id = $this->request->getGet('insurer_branch_id'); + $client_policy_id = $this->request->getGet('client_policy_id'); + + if($date_type == 'statement_month'){ + $start_date = (string)date('Y-m-01', strtotime($start_date)); + $end_date = (string)date('Y-m-31', strtotime($end_date)); + } + + // dd($start_date, $end_date, $date_type); + + $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date; + $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date; + + $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id; + $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id; + $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id; + $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type; + $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer; + $client_branch_id = (!isset($client_branch_id) || $client_branch_id === '' || $client_branch_id === null) ? 0 : $client_branch_id; + $insurer_branch_id = (!isset($insurer_branch_id) || $insurer_branch_id === '' || $insurer_branch_id === null) ? 0 : $insurer_branch_id; + $client_policy_id = (!isset($client_policy_id) || $client_policy_id === '' || $client_policy_id === null) ? 0 : $client_policy_id; + + + //Actual data for the list + $data['report_list'] = $this->policyTransactionModel->getBDSReportList($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $client_branch_id, $insurer_branch_id, $client_policy_id); + // dd($data['report_list']); + + $this->loadLayout('report_bds_filter', $data); + } + public function reportVarience() { $data['page_name'] = 'Variance Report'; @@ -1414,6 +1509,10 @@ class PolicyTransactionController extends BaseController $policy_type_id = $this->request->getGet('policy_type_id'); $date_type = $this->request->getGet('date_type'); $issuer = $this->request->getGet('issuer'); + $client_branch_id = $this->request->getGet('client_branch_id'); + $insurer_branch_id = $this->request->getGet('insurer_branch_id'); + $client_policy_id = $this->request->getGet('client_policy_id'); + $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date; $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date; @@ -1424,7 +1523,12 @@ class PolicyTransactionController extends BaseController $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type; $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer; - $data['varience_list'] = $this->policyTransactionModel->getVarienceReportLIst($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer); + $client_branch_id = (!isset($client_branch_id) || $client_branch_id === '' || $client_branch_id === null) ? 0 : $client_branch_id; + $insurer_branch_id = (!isset($insurer_branch_id) || $insurer_branch_id === '' || $insurer_branch_id === null) ? 0 : $insurer_branch_id; + $client_policy_id = (!isset($client_policy_id) || $client_policy_id === '' || $client_policy_id === null) ? 0 : $client_policy_id; + + + $data['varience_list'] = $this->policyTransactionModel->getVarienceReportLIst($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $client_branch_id, $insurer_branch_id, $client_policy_id); $this->loadLayout('variance_report_list', $data); } @@ -1531,20 +1635,17 @@ class PolicyTransactionController extends BaseController $end_date = $this->request->getGet('end_date'); $client_id = $this->request->getGet('client_id'); $insurer_id = $this->request->getGet('insurer_id'); - $policy_type_id = $this->request->getGet('policy_type_id'); - $date_type = $this->request->getGet('date_type'); - $issuer = $this->request->getGet('issuer'); + $insurer_branch_id = $this->request->getGet('insurer_branch_id'); + + $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : change_date_format($start_date,'d-m-Y','Y-m-01'); + $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : change_date_format($end_date,'d-m-Y','Y-m-31'); + // dd([$start_date,$end_date]); - $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date; - $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date; - $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id; $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id; - $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id; - $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type; - $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer; + $insurer_branch_id = (!isset($insurer_branch_id) || $insurer_branch_id === '' || $insurer_branch_id === null) ? 0 : $insurer_branch_id; - $data['outstanting_list'] = $this->policyTransactionModel->getOutstandingReportLIst($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer); + $data['outstanting_list'] = $this->policyTransactionModel->getOutstandingReportLIst($start_date, $end_date,$insurer_id, $insurer_branch_id); // dd($this->policyTransactionModel->getLastQuery()); // dd($data); $this->loadLayout('outstanding_report_list', $data); @@ -1576,7 +1677,7 @@ class PolicyTransactionController extends BaseController WHERE pt_co_share_details.is_active = 1 AND pt_co_share_details.statement_id = insurer_statements.id ) AS exp_inv_amt, - (SELECT SUM(inv_payment_details.inv_amt) + SUM(inv_payment_details.tds) + (SELECT SUM(inv_payment_details.inv_amt) + SUM(inv_payment_details.tds) + SUM(inv_payment_details.gst) FROM inv_payment_details WHERE inv_payment_details.is_active = 1 AND inv_payment_details.statement_id = insurer_statements.id @@ -1649,9 +1750,10 @@ class PolicyTransactionController extends BaseController $month = $month.'-01'; // print_r($month);die; $month = change_date_format($month,'Y-M-d','Y-m-d'); + $stmt_sno = $this->request->getPost('statement_no'); // print_r($month);die; - $file_id = $this->insurerStatements->insert(['insurer_id' => $insurer_id, 'branch_id' => $branch_id, 'file_name' => $filename,'month' => $month, 'created_by' => $loggedInUserID]); //here field policy_id have client_policy_id and not policy id from policy master + $file_id = $this->insurerStatements->insert(['insurer_id' => $insurer_id, 'branch_id' => $branch_id, 'file_name' => $filename,'month' => $month, 'created_by' => $loggedInUserID,'stmt_sno' => $stmt_sno]); //here field policy_id have client_policy_id and not policy id from policy master $this->myLogger->logme("error", '{file_id} statement uploaded success', ['file_id' => $file_id]); //validate file @@ -1739,9 +1841,9 @@ class PolicyTransactionController extends BaseController unset($excel_data[0]); // Kint::dump($excel_data); //get no of line items and update in DB - $line_items = count($excel_data); + $line_items = 0; // get uploaded month transactions data - $source_data = $this->PTCOShareDetailsModel->getNonReconcileredPolicyTransactions(month:$month,year:$year,insurer_id:$file['insurer_id'],insurer_branch_id:$file['branch_id']); + $source_data = $this->PTCOShareDetailsModel->getNonReconcileredPolicyTransactions(insurer_id:$file['insurer_id'],insurer_branch_id:$file['branch_id']); // var_dump($source_data);die(); // Kint::dump($source_data);//die(); @@ -1766,6 +1868,7 @@ class PolicyTransactionController extends BaseController if( ($policy_no == $source_row['policy_no']) && $endorsement_no == $source_endorsement_no && change_date_format($policy_start_date,'d-m-Y','Y-m-d') == $source_row['policy_start_date'] && change_date_format($policy_end_date,'d-m-Y','Y-m-d') == $source_row['policy_end_date'] && $client_name == $source_row['client_name']) { $is_source_found = 1; + $line_items = $line_items + 1; unset($source_data[$source_key]); continue 2; } @@ -1842,7 +1945,7 @@ class PolicyTransactionController extends BaseController //get no of line items and update in DB $line_items = count($excel_data); // get uploaded month transactions data - $source_data = $this->PTCOShareDetailsModel->getNonReconcileredPolicyTransactions(month:$month,year:$year,insurer_id:$file['insurer_id'],insurer_branch_id:$file['branch_id']); + $source_data = $this->PTCOShareDetailsModel->getNonReconcileredPolicyTransactions(insurer_id:$file['insurer_id'],insurer_branch_id:$file['branch_id']); // Kint::dump($source_data);die; // Kint::dump($excel_data); @@ -1934,7 +2037,7 @@ class PolicyTransactionController extends BaseController //find variance $variance_amt = $source_row['exp_amt'] - $total_amt; - $data_to_update[] = ['id' => $source_row['id'],'actual_bp_amt' => $actual_bp_amt,'actual_tp_amt' => $actual_tp_amt,'actual_tep_amt' => $actual_tep_amt,'actual_bp_per' => $actual_bp_per,'actual_tp_per' => $actual_tp_per,'actual_tep_per' => $actual_tep_per,'variance' => $variance_amt,'actual_tep_brokerage_amt' => $actual_tep_brokerage,'actual_tp_brokerage_amt' => $actual_tp_brokerage,'actual_bp_brokerage_amt' => $actual_bp_brokerage,'reward' => trim($excel_row[15]),'statement_id' => $file_id]; + $data_to_update[] = ['co_share_id' => $source_row['id'],'actual_bp_amt' => $actual_bp_amt,'actual_tp_amt' => $actual_tp_amt,'actual_tep_amt' => $actual_tep_amt,'actual_bp_per' => $actual_bp_per,'actual_tp_per' => $actual_tp_per,'actual_tep_per' => $actual_tep_per,'variance' => $variance_amt,'actual_tep_brokerage_amt' => $actual_tep_brokerage,'actual_tp_brokerage_amt' => $actual_tp_brokerage,'actual_bp_brokerage_amt' => $actual_bp_brokerage,'reward' => trim($excel_row[15]),'statement_id' => $file_id]; unset($source_data[$source_key]); continue 2; @@ -1944,7 +2047,7 @@ class PolicyTransactionController extends BaseController } } // dd($data_to_update); - $this->PTCOShareDetailsModel->updateBatch($data_to_update, 'id'); + $this->coShareStmtDetailsModel->insertBatch($data_to_update, 'id'); // dd($data_to_update); // if($error_data['error_code']) // { @@ -1966,8 +2069,24 @@ class PolicyTransactionController extends BaseController ->where('is_active',1) ->get() ->getResultArray(); + if(!$inv_details['invoice_value']) + { + $stmt_level_value = $this->coShareStmtDetailsModel->select('sum(actual_tep_brokerage_amt) + sum(actual_tp_brokerage_amt) + sum(actual_bp_brokerage_amt) + sum(reward) as invoice_value') + ->where('statement_id',$statement_id) + ->groupBy('statement_id') + ->get() + ->getResultArray(); + // print_r($stmt_level_value); + if($stmt_level_value && count($stmt_level_value) && isset($stmt_level_value[0])) + { + $inv_details['invoice_value'] = $stmt_level_value[0]['invoice_value']; + } + } // ~dd($inv_details); $data = [ 'invoice_status' => $inv_details['invoice_status'], + 'gst_per' => isset($inv_details['gst_per']) ? $inv_details['gst_per'] : 18 , + 'invoice_value' => $inv_details['invoice_value'], + 'gst_value' => $inv_details['gst_value'], 'invoice_no' => $inv_details['invoice_no'], 'invoice_amount' => $inv_details['invoice_amount'], 'invoice_date' => isset($inv_details['invoice_date']) ? change_date_format($inv_details['invoice_date'],'Y-m-d','d/m/Y') : null ]; @@ -1989,6 +2108,9 @@ class PolicyTransactionController extends BaseController $invoiceNo = $jsonData['invoice_no']; $invoiceDate = change_date_format($jsonData['invoice_date'],'d/m/Y','Y-m-d'); $invoice_amount = $jsonData['invoice_amount']; + $invoice_value = $jsonData['invoice_value']; + $gst_per = $jsonData['invoice_gst_per']; + $gst_value = $jsonData['invoice_gst']; //Update statement table $parentData = [ @@ -1996,6 +2118,9 @@ class PolicyTransactionController extends BaseController 'invoice_no' => $invoiceNo, 'invoice_date' => $invoiceDate, 'invoice_amount' => $invoice_amount, + 'gst_per' => $gst_per, + 'gst_value' => $gst_value, + 'invoice_value' => $invoice_value, 'updated_by' => get_session_userid() ]; @@ -2007,6 +2132,7 @@ class PolicyTransactionController extends BaseController $receivedAmounts = $jsonData['received_amount']; $utrNos = $jsonData['utr_no']; $tdsTotal = $jsonData['tds']; + $gstTotal = $jsonData['gst_amount']; $paymentDates = $jsonData['payment_date']; $pks = $jsonData['pk']; @@ -2014,6 +2140,7 @@ class PolicyTransactionController extends BaseController $pk = $pks[$index]; // Get the pk for the current record $utrNo = $utrNos[$index]; $tds = $tdsTotal[$index]; + $gst = $gstTotal[$index]; $paymentDate = $paymentDates[$index]; // Prepare data for insert/update @@ -2021,6 +2148,7 @@ class PolicyTransactionController extends BaseController 'inv_amt' => $receivedAmount, 'utr_no' => $utrNo, 'tds' => $tds, + 'gst' => $gst, 'received_date' => change_date_format($paymentDate,'d/m/Y','Y-m-d'), 'statement_id' => $hiddenStatementId ]; @@ -2120,5 +2248,182 @@ class PolicyTransactionController extends BaseController } + + //--------------------------------------------------------------------------------------------------- + + public function getCoShareStatementDetails($pt_id) + { + if (!$pt_id) { + return $this->respond([ + 'status' => false, + 'code' => 400, + 'message' => 'No data found' + ], 200); + } + + // Fetch data from the database + $data = db_connect()->table("co_share_stmt_details") + ->select(" + co_share_stmt_details.*, + insurer_statements.month, + insurer_statements.invoice_status, + insurer_statements.invoice_date, + insurer_statements.invoice_no, + insurer_statements.invoice_amount, + insurer_statements.stmt_sno, + (co_share_stmt_details.actual_bp_amt + co_share_stmt_details.actual_tp_amt + co_share_stmt_details.actual_tep_amt) AS sum_of_actual_amt + ") + ->join('insurer_statements', 'co_share_stmt_details.statement_id = insurer_statements.id') + ->where([ + 'co_share_stmt_details.is_active' => 1, + 'insurer_statements.is_active' => 1, + 'co_share_stmt_details.co_share_id' => $pt_id + ]) + ->get() + ->getResultArray(); + + // Check if data exists before formatting + if ($data) { + + foreach ($data as &$row) { + // Check if invoice_date is not null before formatting + $row['invoice_date'] = $row['invoice_date'] ? change_date_format($row['invoice_date'], 'Y-m-d', 'd/m/Y') : null; + + // Check if month is not null before formatting + $row['month'] = $row['month'] ? change_date_format($row['month'], 'Y-m-d', 'M-Y') : null; + } + + return $this->respond([ + 'status' => true, + 'code' => 200, + 'data' => $data + ], 200); + } else { + return $this->respond([ + 'status' => false, + 'code' => 400, + 'message' => 'No data found' + ], 200); + } + } + + public function getClientPolicyDataBasedOnClientAndInsuer() + { + + $client_id = $this->request->getGet('client_id') ?? 0; + $client_branch_id = $this->request->getGet('client_branch_id') ?? 0; + $insurer_id = $this->request->getGet('insurer_id') ?? 0; + $insurer_branch_id = $this->request->getGet('insurer_branch_id') ?? 0; + $policy_type_id = $this->request->getGet('policy_type_id') ?? 0; + + $builder = db_connect()->table("client_policy") + ->select(" + client_policy.*, + policy_type.policy_type, + ") + ->join('policy_type', 'client_policy.policy_type_id = policy_type.id') + ->where([ + 'client_policy.is_active' => 1, + ]); + + if (!empty($client_id)) { + $builder->where('client_policy.client_id', $client_id); + } + if (!empty($client_branch_id)) { + $builder->where('client_policy.client_branch_id', $client_branch_id); + } + if (!empty($insurer_id)) { + $builder->where('client_policy.insurer_id', $insurer_id); + } + if (!empty($insurer_branch_id)) { + $builder->where('client_policy.insurer_branch_id', $insurer_branch_id); + } + if (!empty($policy_type_id)) { + $builder->where('client_policy.policy_type_id', $policy_type_id); + } + + $result = $builder->get()->getResultArray(); + + if ($result) { + return $this->respond(['status' => true,'code' => 200,'data' => $result, 'getData' => $this->request->getGet()], 200); + } else { + return $this->respond(['status' => false,'code' => 400,'message' => 'No data found'], 200); + } + } + + public function checkCDAmountForBasePremium() + { + $base_premium = $this->request->getGet('base_premium') ?? 0; + $cd_ac_no = $this->request->getGet('cd_ac_no') ?? 0; + + // Validate inputs + if (empty($cd_ac_no)) { + return $this->respond(['status' => false, 'code' => 400, 'message' => 'CD Account Number is required'], 200); + } + + // Build query + $db = db_connect(); + $builder = $db->table("cash_deposit") + ->where('cd_ac_no', $cd_ac_no) + ->where('is_active', 1) + ->orderBy('id', 'desc') + ->limit(1); + + $result = $builder->get()->getRowArray(); + + if ($result) { + // Check if base premium exceeds balance + $base_premium_greater_than_balance = $base_premium > $result['balance']; + + return $this->respond([ + 'status' => true, + 'code' => 200, + 'data' => $result, + 'base_premium_greater_than_balance' => $base_premium_greater_than_balance, + ], 200); + } + + return $this->respond(['status' => false, 'code' => 400, 'message' => 'No data found for this CD'], 200); + } + + public function getInsurerStatementMonth() + { + $insurer_id = $this->request->getGet('insurer_id'); + $month = $this->request->getGet('month'); + // echo $month; + $insurer_branch_id = explode('-',$insurer_id)[1]; + $insurer_id = explode('-',$insurer_id)[0]; + $month = $month.'-01'; + $month = change_date_format($month,'Y-M-d','Y-m-d'); + // echo $month; + + $res_data = $this->insurerStatements + ->where('insurer_id',$insurer_id) + ->where('branch_id',$insurer_branch_id) + ->where('month', $month) + ->where('is_active', 1) + ->where('file_status', 'success') + ->findAll(); + + return $this->respond(['dataStatus' => true, 'code' => 200,'data' => $res_data], 200); + + + } + + public function deleteStatement($id) + { + // echo $id;die(); + $this->coShareStmtDetailsModel->where('statement_id',$id) + ->set(['is_active' => 0]) + ->update(); + $this->invPaymentDetailsModel->where('statement_id',$id) + ->set(['is_active' => 0]) + ->update(); + $this->insurerStatements->where('id',$id) + ->set(['is_active' => 0]) + ->update(); + return $this->respond(['dataStatus' => true, 'code' => 200], 200); + } + } \ No newline at end of file diff --git a/app/Controllers/UserController.php b/app/Controllers/UserController.php index ce177302..b9f5c34e 100755 --- a/app/Controllers/UserController.php +++ b/app/Controllers/UserController.php @@ -40,7 +40,7 @@ class UserController extends AdminController $data['UserList'] = $this->userModel->getUserList(); // echo '
';
         // 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();
         $this->loadLayout('UserList', $data);
     }
diff --git a/app/Helpers/DepositHelper.php b/app/Helpers/DepositHelper.php
index aa5950f0..0ee54530 100755
--- a/app/Helpers/DepositHelper.php
+++ b/app/Helpers/DepositHelper.php
@@ -62,6 +62,7 @@ class DepositHelper
             'created_by' => $loggedInUserID,
             'updated_by' => $data['updated_by'],
             'balance' => $newBalance, // Include the new balance in the data array
+            'cd_ac_pk'=> isset($data['cd_ac_pk'])?$data['cd_ac_pk']:null,
         ];
 
         // Insert data and get the insert ID
diff --git a/app/Helpers/ExcelMergeHelper.php b/app/Helpers/ExcelMergeHelper.php
new file mode 100644
index 00000000..36306692
--- /dev/null
+++ b/app/Helpers/ExcelMergeHelper.php
@@ -0,0 +1,150 @@
+getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine());
+            log_message('debug', 'Retrying with reversed file order');
+            
+            // Reverse the file order and try again
+            $reversedFiles = array_reverse($filePaths);
+            
+            try {
+                return self::processFiles($reversedFiles, $outputPath);
+            } catch (Exception $e2) {
+                log_message('error', 'Both attempts failed. Last error: ' . $e2->getMessage() . ' in ' . $e2->getFile() . ' on line ' . $e2->getLine());
+                return null;
+            }
+        }
+    }
+
+    /**
+     * Process files to merge spreadsheets
+     *
+     * @param array $filePaths
+     * @param string $outputPath
+     * @return string
+     * @throws Exception
+     */
+    private static function processFiles(array $filePaths, string $outputPath): string
+    {
+        log_message('debug', 'Starting Excel merge process');
+        log_message('debug', 'Files to process: ' . json_encode($filePaths));
+        
+        if (empty($filePaths)) {
+            throw new Exception("No files provided to merge");
+        }
+
+        // Initialize an empty merged spreadsheet
+        $mergedSpreadsheet = new Spreadsheet();
+        $mergedSpreadsheet->removeSheetByIndex(0); // Remove the default empty sheet
+        
+        // Process the base file
+        $firstFile = array_shift($filePaths);
+        self::processSingleFile($firstFile, $mergedSpreadsheet);
+
+        // Process remaining files
+        foreach ($filePaths as $index => $fileInfo) {
+            self::processSingleFile($fileInfo, $mergedSpreadsheet, $index);
+        }
+
+        // Save the merged file
+        log_message('debug', "Saving merged file to: {$outputPath}");
+        $writer = IOFactory::createWriter($mergedSpreadsheet, 'Xlsx');
+        $writer->setPreCalculateFormulas(false);
+        $writer->save($outputPath);
+        
+        // Clean up
+        $mergedSpreadsheet->disconnectWorksheets();
+        unset($mergedSpreadsheet);
+        gc_collect_cycles();
+        
+        log_message('debug', 'Excel merge process completed successfully');
+        return $outputPath;
+    }
+
+    /**
+     * Process a single file to merge its sheets into the merged spreadsheet
+     *
+     * @param array $fileInfo
+     * @param Spreadsheet $mergedSpreadsheet
+     * @param int|null $index
+     * @throws Exception
+     */
+    private static function processSingleFile(array $fileInfo, Spreadsheet $mergedSpreadsheet, int $index = null)
+    {
+        if (!isset($fileInfo['file_path']) || !file_exists($fileInfo['file_path'])) {
+            $path = $fileInfo['file_path'] ?? 'undefined';
+            log_message('error', "File " . ($index ?? 'base') . ": Invalid or missing file path: {$path}");
+            return;
+        }
+
+        log_message('debug', "Processing file " . ($index ?? 'base') . ": " . $fileInfo['file_path']);
+        
+        try {
+            // Load the source spreadsheet
+            $sourceSpreadsheet = IOFactory::load($fileInfo['file_path']);
+            
+            // Get all worksheets
+            $worksheets = $sourceSpreadsheet->getAllSheets();
+            $totalSheets = count($worksheets);
+            log_message('debug', "Total sheets in file: " . $totalSheets);
+
+            $sheetsToMerge = $fileInfo['sheets'] ?? [];
+
+            // Process each worksheet
+            foreach ($worksheets as $sheetIndex => $worksheet) {
+                if (empty($sheetsToMerge) || in_array($sheetIndex, $sheetsToMerge)) {
+                    try {
+                        $sheetName = $worksheet->getTitle();
+                        log_message('debug', "Processing sheet: {$sheetName}");
+
+                        // Generate unique sheet name before cloning
+                        $newName = $sheetName;
+                        $counter = 1;
+                        
+                        while (in_array($newName, $mergedSpreadsheet->getSheetNames())) {
+                            $newName = $sheetName . "_" . $counter++;
+                            log_message('debug', "Sheet name already exists. Trying new name: {$newName}");
+                        }
+
+                        // Clone the worksheet and set the new name
+                        $clonedSheet = clone $worksheet;
+                        $clonedSheet->setTitle($newName);
+
+                        // Add as external sheet
+                        $mergedSpreadsheet->addExternalSheet($clonedSheet);
+
+                        log_message('debug', "Successfully added sheet: {$newName}");
+                    } catch (Exception $e) {
+                        log_message('error', "Error processing sheet {$sheetName} as new name {$newName}: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine());
+                    }
+                }
+            }
+            
+            // Clean up source spreadsheet
+            $sourceSpreadsheet->disconnectWorksheets();
+            unset($sourceSpreadsheet);
+            gc_collect_cycles();
+            
+        } catch (Exception $e) {
+            log_message('error', "Error processing file {$fileInfo['file_path']}: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine());
+        }
+    }
+}
\ No newline at end of file
diff --git a/app/Helpers/ExcelSanitizeHelper.php b/app/Helpers/ExcelSanitizeHelper.php
new file mode 100644
index 00000000..b4950b34
--- /dev/null
+++ b/app/Helpers/ExcelSanitizeHelper.php
@@ -0,0 +1,51 @@
+ $value) {
+                if (is_array($value)) {
+                    $cleanData[$key] = self::sanitizeArrayData($value); // Recursive call for nested arrays
+                } elseif (is_string($value)) {
+                    // Remove non-printable characters and trim whitespace from strings
+                    $cleanData[$key] = trim(str_replace(self::$nonPrintableChars, '', $value));
+                } else {
+                    $cleanData[$key] = $value; // Keep non-string/non-array data as is
+                }
+            }
+            
+            return $cleanData;
+        } catch (\Exception $e) {
+            // Log the error and the problematic data for debugging
+            log_message('error', 'Error sanitizing array data: ' . $e->getMessage());
+            log_message('error', 'Problematic data: ' . json_encode($data));
+            return $data; // Return the original data in case of error
+        }
+    }
+}
diff --git a/app/Helpers/GmailResponseHandler.php b/app/Helpers/GmailResponseHandler.php
index f2cb07f7..4a45f65c 100644
--- a/app/Helpers/GmailResponseHandler.php
+++ b/app/Helpers/GmailResponseHandler.php
@@ -77,17 +77,16 @@ class GmailResponseHandler{
                 }
             }
         }
-        if(isset($params['gmail_api']['status']) && $params['gmail_api']['status'] == 1 ){
-            $data['gmail_api_status'] = isset($params['gmail_api']['status']) ? $params['gmail_api']['status'] : null;
-            $data['gmail_api_id'] = isset($params['gmail_api']['data']['id']) ? $params['gmail_api']['data']['id'] : null;
-            $data['received_message'] = isset($params['gmail_api']['data']['labelIds']) ? json_encode($params['gmail_api']['data']['labelIds']) : null;
+        if(isset($params['zepto_api']['data']) && $params['zepto_api']['message'] == 'OK' ){
+            $data['gmail_api_status'] = isset($params['zepto_api']['data']) ? $params['zepto_api']['data'][0]['code'] : null;
+            $data['gmail_api_id'] = isset($params['zepto_api']['request_id']) ? $params['zepto_api']['request_id'] : null;
+            $data['received_message'] = isset($params['zepto_api']['data'][0]['message']) ? json_encode($params['zepto_api']['data'][0]['message']) : null;
 
         }
-        elseif(isset($params['gmail_api']['status']) && $params['gmail_api']['status'] == false ){
-            $data['gmail_api_status'] = $params['gmail_api']['status'];
-            if(isset($params['gmail_api']['data'])){
-                $data['received_message'] = json_encode($params['gmail_api']['data']);
-            }
+        elseif(isset($params['zepto_api']['error'])){
+            $data['gmail_api_status'] = isset($params['zepto_api']['error']['code'])?$params['zepto_api']['error']['code']:null;
+            $data['received_message'] = json_encode($params['zepto_api']);
+            $data['gmail_api_id'] = isset($params['zepto_api']['error']['request_id']) ? $params['zepto_api']['error']['request_id'] : null;
         }
          
         $gmailModel = new GmailSentHistoryModel();
@@ -96,7 +95,9 @@ class GmailResponseHandler{
 
     public function gmail_response_logger($params)
     {
-        $this->myLogger->logme('error',json_encode($params));
+        if(isset($params['zepto_api']['error'])){
+            $this->myLogger->logme('error',json_encode($params));
+        }
     }
 
     public function client_id_flag_setter($params)
@@ -119,7 +120,6 @@ class GmailResponseHandler{
         $error = $e->getMessage();
         $this->myLogger->logme('error','An Error Occured - '.$error);
     }
-    }
-
+}
 
 }
\ No newline at end of file
diff --git a/app/Helpers/MailHelper.php b/app/Helpers/MailHelper.php
index 6116bc0c..91e955b0 100755
--- a/app/Helpers/MailHelper.php
+++ b/app/Helpers/MailHelper.php
@@ -1,175 +1,422 @@
 setMailType('html');
+//             $email->setFrom('bbone@venbait.in', 'Nhance');
+
+//             $email->setTo($emaill);
+
+//             if (!empty($bcc)) {
+//                 // Convert the comma-separated string into an array
+//                 $bccList = explode(',', $bcc);
+//                 // Trim whitespace from each email ID
+//                 $bccList = array_map('trim', $bccList);
+//                 // Set BCC recipients
+//                 $email->setBCC($bccList);
+//             }
+
+//             $email->setSubject($subject);
+
+//             $email->setMessage($message);
+
+//             if ($email->send()) {
+
+//                 return json_encode(['status' => 'success','code' => 200, 'message'=>'Email Sent Successfully...','data' => $emaill,],200);
+//             } else {
+//                 $myLogger->logme('error', "mail sent failed -  $emaill");
+//                 return json_encode(['status' => 'failed','code' => 404,'message'=>'Email Sent Failed...','data' => $emaill  ],404);
+//             }
+            
+//         } catch (Exception $e) {
+//             $msg = $e->getMessage();
+//             $myLogger->logme('error', "mail sent failed -  $msg");
+//             return json_encode(['status' => 'failed','code' => 500,'data' => $emaill],500);
+//         }  
+//     }
+
+//     public static function bulk_mail_smtp(array $mails = [])
+//     {
+//         // print_r();die;
+//         $model = new JobModel();
+//         $start = microtime(true);
+//         $runtime= 0;
+//        try {
+//         foreach ( $mails as $index=>$mail) {
+//                 $runtime = microtime(true) - $start;
+//                 $send_mail = self::send_email($mail);   
+//         }
+        
+//         return json_encode(['status' => 'success','code' => 200, 'message'=>'Email Sent Successfully...'],200);
+
+//        } catch (\Throwable $th) {
+//         return json_encode(['status' => 'failed','code' => 500],500);
+//        }
+//     }
+
+//     //using GmailAPI
+//      public static function send_email($params) 
+//     {    
+
+//         // print_r($params);die;
+//         $myLogger = \Config\Services::mylogger();
+//         $gmailapi = \Config\Services::gmailapi();
+
+//         $emaill = $params['mail'];
+//         $subject = $params['subject'];
+//         $message = $params['message'];
+//         $attachments = isset($params['attachments']) && count($params['attachments']) ? $params['attachments'] : [];
+//         $common = isset($params['common'])?$params['common']:'';
+//         //check BCC mail
+//         if (isset($params['bcc'])) {
+//             $bcc = $params['bcc'];
+//             if(!is_array($bcc)){
+//                 $bcc = explode(',', $bcc);
+//             }
+//         }else{
+//             $bcc = [];
+//         }
+
+//         //check CC mail
+//         if (isset($params['cc'])) {
+//             $cc = $params['cc'];
+//             if(!is_array($cc)){
+//                 $cc = explode(',', $cc);
+//             }
+//         }else{
+//             $cc = [];
+//         }
+
+//         //check REPLY TO mail
+//         $reply_to = "";
+//         if(isset($params['reply_to']) && !empty($params['reply_to'])){
+//             $reply_to = $params['reply_to'];
+//         }
+//         $MailDataHelper = new GmailResponseHandler();
+
+//         $res['params'] = $params;
+//         try {
+          
+//               $res['gmail_api'] = $gmailapi->sendMessage($emaill, $subject, $message, 'no-reply@nhanceindia.in', $reply_to, $cc, $bcc,$attachments);
+//                if($res['gmail_api']['status'])
+//                {
+//                   $response = $res;
+//                   $MailDataHelper->receive_and_distribute_param_to_functions($response);
+//                   return json_encode(['status' => 'success','code' => 200, 'message'=>('Email Sent Successfully...'.$emaill),'data' => $res,],200);
+//                }
+//                else
+//                {
+//                     $myLogger->logme('error', "mail sent failed -  $emaill");
+//                     $response = $res;
+//                     $MailDataHelper->receive_and_distribute_param_to_functions($response);
+//                     return json_encode(['status' => 'failed','code' => 404,'message'=>( 'Email Sent Failed...' . $emaill ),'data' => $res  ],404);
+//                }
+ 
+//         } catch (Exception $e) {
+//             $msg['error'] = $e->getMessage();
+//             $msg['params'] = $params;
+//             $myLogger->logme('error', "mail sent failed -  $msg");
+//             $response = $msg;
+//             $MailDataHelper->receive_and_distribute_param_to_functions($response);
+//             return json_encode(['status' => 'failed','code' => 500,'data' => $msg],500);
+//         }
+        
+
+//     }
+
+
+//     public static function bulk_mail(array $mails = [])
+//     {
+//         // print_r($mails);die;
+//         $model = new JobModel();
+//         $start = microtime(true);
+//         $runtime= 0;
+//        try {
+//         foreach ( $mails as $index=>$mail) {
+//                 $runtime = microtime(true) - $start;
+//                 $send_mail = self::send_email($mail);
+//         }
+        
+//         return json_encode(['status' => 'success','code' => 200, 'message'=>'Email Sent Successfully...'],200);
+
+//        } catch (\Throwable $th) {
+//         $error = $th->getMessage();
+//         log_message('error',$error);
+//         return json_encode(['status' => 'failed','code' => 500,'error'=>$error],500);
+//        }
+//     }
+
+// }
+
+
 namespace App\Helpers;
 use Psr\Log\LoggerInterface;
-
 use App\Controllers\BaseController;
-
-use PHPMailer\PHPMailer\PHPMailer;
-use PHPMailer\PHPMailer\SMTP;
-use PHPMailer\PHPMailer\Exception;
-
 use App\Models\JobModel;
 
 class MailHelper
 {
     public static function send_email_smtp($params) 
     {    
-
-        // print_r($params);die;
         $myLogger = \Config\Services::mylogger();
         $emaill = $params['mail'];
         $subject = $params['subject'];
         $message = $params['message'];
         if (isset($params['bcc'])) {
             $bcc = $params['bcc'];
-        }else{
-            $bcc= '';
+        } else {
+            $bcc = '';
         }
+        $from_address = getenv('email.fromEmail');
+
+
         try {
-            
-            $email = \Config\Services::email();
-            $email->setMailType('html');
-            $email->setFrom('bbone@venbait.in', 'Nhance');
-
-            $email->setTo($emaill);
+            $curl = curl_init();
+            $postData = [
+                'from' => [
+                    'address' => $from_address
+                ],
+                'to' => [
+                    [
+                        'email_address' => [
+                            'address' => $emaill
+                        ]
+                    ]
+                ],
+                'subject' => $subject,
+                'htmlbody' => $message
+            ];
 
+            // Add BCC if present
             if (!empty($bcc)) {
-                // Convert the comma-separated string into an array
                 $bccList = explode(',', $bcc);
-                // Trim whitespace from each email ID
                 $bccList = array_map('trim', $bccList);
-                // Set BCC recipients
-                $email->setBCC($bccList);
+                $postData['bcc'] = array_map(function($email) {
+                    return [
+                        'email_address' => [
+                            'address' => $email
+                        ]
+                    ];
+                }, $bccList);
             }
 
-            $email->setSubject($subject);
+            curl_setopt_array($curl, [
+                CURLOPT_URL => "https://api.zeptomail.in/v1.1/email",
+                CURLOPT_RETURNTRANSFER => true,
+                CURLOPT_ENCODING => "",
+                CURLOPT_MAXREDIRS => 10,
+                CURLOPT_TIMEOUT => 30,
+                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
+                CURLOPT_CUSTOMREQUEST => "POST",
+                CURLOPT_POSTFIELDS => json_encode($postData),
+                CURLOPT_HTTPHEADER => [
+                    "accept: application/json",
+                    "authorization: Zoho-enczapikey " . getenv('ZEPTO_API_KEY'),
+                    "cache-control: no-cache",
+                    "content-type: application/json",
+                ],
+            ]);
 
-            $email->setMessage($message);
+            $response = curl_exec($curl);
+            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
+            $err = curl_error($curl);
 
-            if ($email->send()) {
+            curl_close($curl);
+            if ($err) {
+                $myLogger->logme('error', "mail sent failed -  $emaill");
+                return json_encode(['status' => 'failed', 'code' => 404, 'message' => 'Email Sent Failed...', 'data' => $emaill], 404);
+            }
 
-                return json_encode(['status' => 'success','code' => 200, 'message'=>'Email Sent Successfully...','data' => $emaill,],200);
+            $apiResponse = json_decode($response, true);
+            
+            if ($httpCode === 200) {
+                return json_encode(['status' => 'success', 'code' => 200, 'message' => 'Email Sent Successfully...', 'data' => $emaill], 200);
             } else {
                 $myLogger->logme('error', "mail sent failed -  $emaill");
-                return json_encode(['status' => 'failed','code' => 404,'message'=>'Email Sent Failed...','data' => $emaill  ],404);
+                return json_encode(['status' => 'failed', 'code' => 404, 'message' => 'Email Sent Failed...', 'data' => $emaill], 404);
             }
-            
-        } catch (Exception $e) {
+
+        } catch (\Exception $e) {
             $msg = $e->getMessage();
             $myLogger->logme('error', "mail sent failed -  $msg");
-            return json_encode(['status' => 'failed','code' => 500,'data' => $emaill],500);
-        }  
+            return json_encode(['status' => 'failed', 'code' => 500, 'data' => $emaill], 500);
+        }
     }
 
     public static function bulk_mail_smtp(array $mails = [])
     {
-        // print_r();die;
         $model = new JobModel();
         $start = microtime(true);
-        $runtime= 0;
-       try {
-        foreach ( $mails as $index=>$mail) {
+        $runtime = 0;
+        try {
+            foreach ($mails as $index => $mail) {
                 $runtime = microtime(true) - $start;
                 $send_mail = self::send_email($mail);   
-        }
-        
-        return json_encode(['status' => 'success','code' => 200, 'message'=>'Email Sent Successfully...'],200);
+            }
+            
+            return json_encode(['status' => 'success', 'code' => 200, 'message' => 'Email Sent Successfully...'], 200);
 
-       } catch (\Throwable $th) {
-        return json_encode(['status' => 'failed','code' => 500],500);
-       }
+        } catch (\Throwable $th) {
+            return json_encode(['status' => 'failed', 'code' => 500], 500);
+        }
     }
 
-    //using GmailAPI
-     public static function send_email($params) 
+    public static function send_email($params) 
     {    
-
-        // print_r($params);die;
         $myLogger = \Config\Services::mylogger();
-        $gmailapi = \Config\Services::gmailapi();
-
+        
         $emaill = $params['mail'];
         $subject = $params['subject'];
         $message = $params['message'];
-        $attachments = isset($params['attachments']) && count($params['attachments']) ? $params['attachments'] : [];
-        $common = isset($params['common'])?$params['common']:'';
-        //check BCC mail
-        if (isset($params['bcc'])) {
-            $bcc = $params['bcc'];
-            $bcc = explode(',', $bcc);
-        }else{
-            $bcc = [];
-        }
+        $attachments = isset($params['attachments']) ? $params['attachments'] : [];
+        $common = isset($params['common']) ? $params['common'] : '';
 
-        //check CC mail
-        if (isset($params['cc'])) {
-            $cc = $params['cc'];
-            if(!is_array($cc)){
-                $cc = explode(',', $cc);
-            }
-        }else{
-            $cc = [];
-        }
-
-        //check REPLY TO mail
-        $reply_to = "";
-        if(isset($params['reply_to']) && !empty($params['reply_to'])){
-            $reply_to = $params['reply_to'];
-        }
-        $MailDataHelper = new GmailResponseHandler();
-
-        $res['params'] = $params;
+        $from_address = getenv('email.fromEmail');
         try {
-          
-              $res['gmail_api'] = $gmailapi->sendMessage($emaill, $subject, $message, 'no-reply@nhanceindia.in', $reply_to, $cc, $bcc,$attachments);
-               if($res['gmail_api']['status'])
-               {
-                  $response = $res;
-                  $MailDataHelper->receive_and_distribute_param_to_functions($response);
-                  return json_encode(['status' => 'success','code' => 200, 'message'=>('Email Sent Successfully...'.$emaill),'data' => $res,],200);
-               }
-               else
-               {
-                    $myLogger->logme('error', "mail sent failed -  $emaill");
-                    $response = $res;
-                    $MailDataHelper->receive_and_distribute_param_to_functions($response);
-                    return json_encode(['status' => 'failed','code' => 404,'message'=>( 'Email Sent Failed...' . $emaill ),'data' => $res  ],404);
-               }
- 
-        } catch (Exception $e) {
+            $curl = curl_init();
+            
+            $postData = [
+                'from' => [
+                    'address' => $from_address
+                ],
+                'to' => [
+                    [
+                        'email_address' => [
+                            'address' => $emaill
+                        ]
+                    ]
+                ],
+                'subject' => $subject,
+                'htmlbody' => $message
+            ];
+
+            // Handle attachments
+            if (!empty($attachments)) {
+                $postData['attachments'] = [];
+                foreach ($attachments as $attachment) {
+                    if (isset($attachment['filePath']) && file_exists($attachment['filePath'])) {
+                        // Determine MIME type dynamically
+                        $fileMimeType = mime_content_type($attachment['filePath']);
+            
+                        $postData['attachments'][] = [
+                            'content' => base64_encode(file_get_contents($attachment['filePath'])),
+                            'name' => $attachment['fileName'],
+                            'mime_type' => $fileMimeType, // Add mime_type field
+                        ];
+                    }
+                }
+            }
+            
+
+            curl_setopt_array($curl, [
+                CURLOPT_URL => "https://api.zeptomail.in/v1.1/email",
+                CURLOPT_RETURNTRANSFER => true,
+                CURLOPT_ENCODING => "",
+                CURLOPT_MAXREDIRS => 10,
+                CURLOPT_TIMEOUT => 30,
+                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
+                CURLOPT_CUSTOMREQUEST => "POST",
+                CURLOPT_POSTFIELDS => json_encode($postData),
+                CURLOPT_HTTPHEADER => [
+                    "accept: application/json",
+                    "authorization: Zoho-enczapikey " . getenv('ZEPTO_API_KEY'),
+                    "cache-control: no-cache",
+                    "content-type: application/json",
+                ],
+            ]);
+
+            $mail_result = curl_exec($curl);
+            $err = curl_error($curl);
+            curl_close($curl);
+            // log_message('error','inside mail helper');
+            // log_message('error', $response.' error->'.$err);die();
+            $res['params'] = $params;
+            $MailDataHelper = new GmailResponseHandler();
+            $apiResponse = json_decode($mail_result, true);
+            $res['zepto_api'] = $apiResponse;
+            if (isset($apiResponse['error'])) {
+                $response = $res;
+                $MailDataHelper->receive_and_distribute_param_to_functions($response);
+                return json_encode([
+                    'status' => 'failed',
+                    'code' => 404,
+                    'message' => 'Email Sent Failed...' . $emaill,
+                    'data' => $res
+                ], 404);
+            }
+
+            // $apiResponse = json_decode($response, true);
+
+            // Check if request_id exists in response (indicates success)
+            if (isset($apiResponse['data'])) {
+                $response = $res;
+                $MailDataHelper->receive_and_distribute_param_to_functions($response);
+                return json_encode([
+                    'status' => 'success',
+                    'code' => 200,
+                    'message' => 'Email Sent Successfully...' . $emaill,
+                    'data' => $res
+                ], 200);
+            } 
+
+        } catch (\Exception $e) {
             $msg['error'] = $e->getMessage();
             $msg['params'] = $params;
-            $myLogger->logme('error', "mail sent failed -  $msg");
-            $response = $msg;
+            $response = $res;
             $MailDataHelper->receive_and_distribute_param_to_functions($response);
-            return json_encode(['status' => 'failed','code' => 500,'data' => $msg],500);
+            return json_encode([
+                'status' => 'failed',
+                'code' => 500,
+                'data' => $msg
+            ], 500);
         }
-        
-
     }
 
-
     public static function bulk_mail(array $mails = [])
     {
-        // print_r($mails);die;
         $model = new JobModel();
         $start = microtime(true);
-        $runtime= 0;
-       try {
-        foreach ( $mails as $index=>$mail) {
+        $runtime = 0;
+        try {
+            foreach ($mails as $index => $mail) {
                 $runtime = microtime(true) - $start;
                 $send_mail = self::send_email($mail);
+            }
+            
+            return json_encode(['status' => 'success', 'code' => 200, 'message' => 'Email Sent Successfully...'], 200);
+
+        } catch (\Throwable $th) {
+            $error = $th->getMessage();
+            log_message('error', $error);
+            return json_encode(['status' => 'failed', 'code' => 500, 'error' => $error], 500);
         }
-        
-        return json_encode(['status' => 'success','code' => 200, 'message'=>'Email Sent Successfully...'],200);
-
-       } catch (\Throwable $th) {
-        $error = $th->getMessage();
-        log_message('error',$error);
-        return json_encode(['status' => 'failed','code' => 500,'error'=>$error],500);
-       }
     }
-
 }
 ?>
\ No newline at end of file
diff --git a/app/Helpers/excel_import_export_helper.php b/app/Helpers/excel_import_export_helper.php
index 3355253e..ad484ffe 100755
--- a/app/Helpers/excel_import_export_helper.php
+++ b/app/Helpers/excel_import_export_helper.php
@@ -128,7 +128,7 @@ if (! function_exists('transform_objects_to_array_for_inception')) {
                 $obj->emp_gender,                    // Employee Gender
                 $obj->pre_existing_alignments,       // Pre-existing Alignments
                 $obj->basic_cover_si,                // Basic Cover SI
-                $obj->date_coverage,                 // Date Coverage
+                $obj->date_of_coverage,                 // Date Coverage
                 $obj->emp_age,                       // Employee Age
                 $obj->emp_relationship,              // Employee Relationship
                 $obj->change_event,                  // Change Event
@@ -260,7 +260,6 @@ if (! function_exists('transform_objects_to_array_for_deletion')) {
                 $obj->total,                        
                 $claim_status,
                 $endorsement_id
-
             ];
 
             // Append the row data to the main data array
@@ -487,7 +486,7 @@ if (!function_exists('format_Excel_BasedOn_Client'))
                             $rowData[] = $obj->basic_cover_si; // Employee BASIC COVER SI
                             break;
                         case 'dateofcoverage':
-                            $rowData[] = $obj->date_coverage; //  DATE OF COVERAGE
+                            $rowData[] = $obj->date_of_coverage; //  DATE OF COVERAGE
                             break;
                         case 'age':
                             $rowData[] = $obj->emp_age; // Employee AGE
diff --git a/app/Helpers/excel_util_helper.php b/app/Helpers/excel_util_helper.php
index d1fdf7d2..3c254374 100755
--- a/app/Helpers/excel_util_helper.php
+++ b/app/Helpers/excel_util_helper.php
@@ -345,8 +345,7 @@ if(!function_exists('check_basic_pay'))
 
 if (!function_exists('check_dob_diff')) 
 {
-    function check_dob_diff($row,$relationships,$default_age_ratio) {
-        // echo 'called';
+    function check_dob_diff($row,$relationships,$default_age_ratio,$policy_details) {
         if($row['current_action'] != null &&  in_array(strtoupper($row['current_action']), ['I','A','DA','MI']))// check rule only of action column data available
         {
                 if($row[3] != null && $row[5] != null)
@@ -358,13 +357,11 @@ if (!function_exists('check_dob_diff'))
                     }
                     // return array('status' => true);
                     $dob = $dateString;
-                    // echo $row[3].' - '.$dob;echo '
'; - $currentDateTime = new DateTime();//die(); - // print_r($currentDateTime); + //$currentDateTime = new DateTime();//previously dob calculated from current date time + $temp_date = ($row[7] != null && $row[7] != "") ? convert_string_to_date($row[7]) : $policy_details[0]->policy_start_date; //pick date of coverage from row if not then use policy start date as from to calculate DOB + $currentDateTime = new DateTime($temp_date);//later DOB calculated from date of coverage or policy_start_date // die(); $passedDateTime = new DateTime($dob); - // print_r($passedDateTime); - $interval = $currentDateTime->diff($passedDateTime); //remap default age ratio data into relationship array if(count($default_age_ratio)) @@ -375,7 +372,6 @@ if (!function_exists('check_dob_diff')) $relationship = $slug->slugify($row[5]); $age_min = isset($relationships[$relationship]['age_min']) ? $relationships[$relationship]['age_min'] : NULL; $age_max = isset($relationships[$relationship]['age_max']) ? $relationships[$relationship]['age_max'] : NULL; - // echo $relationship.','.$age_min.'-'.$age_max; if($age_min !== null && $age_min > $interval->y) { return array('status' => false,'error' => "Age conflict : minimum $age_min yrs allowed, received $interval->y"); @@ -965,7 +961,6 @@ if (!function_exists('calculate_premium_new')) if(empty($member[18])){ $member[18] = $existing_units[0]; } //transform as db row column $transformed_familiy_member_data = transform_excel_data_to_db($member,$fileArr); - // kint::dump($transformed_familiy_member_data); //generate relationship code if($transformed_familiy_member_data['temp']['action'] != 'D' && $transformed_familiy_member_data['temp']['action'] != 'C' && $transformed_familiy_member_data['temp']['action'] != 'SI') { @@ -979,7 +974,7 @@ if (!function_exists('calculate_premium_new')) 'isEmployeeSourceEnrollment' => $fileArr['id'] == null, 'isEmployeeSourceExcelFile' => $transformed_familiy_member_data['temp']['source'] == 'excel', 'isCurrentActionDependentAddition' => $fileArr['action'] == 'dependent_addition', - // 'isPrimaryGridPremiumTypeSingle' => $transformed_familiy_member_data['temp']['premium_type'] == 1, + 'isPrimaryGridPremiumTypeSingle' => isset($transformed_familiy_member_data['temp']['premium_type']) ? $transformed_familiy_member_data['temp']['premium_type'] == 1 : 0, 'isCurrentRelationshipSelf' => (strtolower($transformed_familiy_member_data['relationship']) == 'self' || (isset($transformed_familiy_member_data['temp']['acting_self']) && $transformed_familiy_member_data['temp']['acting_self'] === true)), 'isBasicCoverCalculatedToCurrentEmployee' => ($transformed_familiy_member_data['policy_details']['basic_cover_si'] != null && $transformed_familiy_member_data['policy_details']['basic_cover_si'] != 0) ]; @@ -1049,7 +1044,7 @@ if (!function_exists('transform_excel_data_to_db')) $result['designation'] = $memArr[11]; $result['mobile'] = $memArr[12]; $result['email_corporate'] = $memArr[13]; - $result['file_id'] = $actionArr['id']; + $result['file_id'] = isset($memArr['temp']['source']) && $memArr['temp']['source'] == 'db' && isset($memArr['temp']['file_id']) ? $memArr['temp']['file_id'] : $actionArr['id']; $result['client_id'] = $actionArr['client_id']; $result['change_event'] = $memArr[15]; $result['unit'] = $memArr[18]; @@ -1078,8 +1073,6 @@ if (!function_exists('premium_calculation_manager')) { function premium_calculation_manager($emp_data,$policy_terms,$slab_details,$default_si = null) { - // Kint::dump($emp_data);die(); - $myLogger = \Config\Services::mylogger(); // grid type // 1 = premium => si @@ -1167,7 +1160,7 @@ if (!function_exists('premium_calculation_manager')) { if($temp_slab_rates[0]['si_or_bp'] == 2) { - $temp_si = $emp_data['basic_pay'] * $temp_slab_rates[0]['si_or_bp']; + $temp_si = $emp_data['basic_pay'] * $temp_slab_rates[0]['basic_multiplier']; $temp_premium = ($temp_si * $temp_slab_rates[0]['multiplier']) / 1000; $emp_data['policy_details']['basic_cover_si'] = $temp_si; @@ -1229,9 +1222,12 @@ if (!function_exists('premium_calculation_manager')) //GMC - Employees Age band $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; // dd($employee_received_si); + $temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $age = calculate_days_bw_dates(from_date: $emp_data['dob'],to_date: $temp_date)->y; + foreach ($temp_slab_rates as $skey => $slab_value) { - $age = calculate_days_bw_dates(from_date: $emp_data['dob'])->y; + if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) )) { // dd($slab_value); @@ -1250,9 +1246,12 @@ if (!function_exists('premium_calculation_manager')) case "5": //GMC - Employees Age + SI $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; + $temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $age = calculate_days_bw_dates(from_date: $emp_data['dob'],to_date: $temp_date)->y; + foreach ($temp_slab_rates as $skey => $slab_value) { - $age = calculate_days_bw_dates(from_date: $emp_data['dob'])->y; + if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3 ) )) { $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; @@ -1270,9 +1269,11 @@ if (!function_exists('premium_calculation_manager')) case "6": //GMC - Employees + Dependent Age band $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; + $temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $age = calculate_days_bw_dates(from_date: $emp_data['dob'],to_date: $temp_date)->y; foreach ($temp_slab_rates as $skey => $slab_value) { - $age = calculate_days_bw_dates(from_date: $emp_data['dob'])->y; + if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) )) { // echo $emp_data['name']; @@ -1292,9 +1293,11 @@ if (!function_exists('premium_calculation_manager')) case "7": //GMC - Employees + Dependent Age + SI $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; + $temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $age = calculate_days_bw_dates(from_date: $emp_data['dob'],to_date: $temp_date)->y; foreach ($temp_slab_rates as $skey => $slab_value) { - $age = calculate_days_bw_dates(from_date: $emp_data['dob'])->y; + if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) )) { $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; @@ -1442,7 +1445,8 @@ if (!function_exists('premium_calculation_manager')) $employee_relationship = $slug->slugify($emp_data['relationship']); $employee_relationship = ($employee_relationship == 'daughter' || $employee_relationship == 'son' ? $employee_relationship = 'child' : $employee_relationship); $emp_data['policy_details']['basic_cover_si'] = null; - $age = calculate_days_bw_dates(from_date: $emp_data['dob'])->y; + $temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $age = calculate_days_bw_dates(from_date: $emp_data['dob'],to_date: $temp_date)->y; foreach ($temp_slab_rates as $skey => $slab_value) { if( $slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && ((($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) && $slab_value['relationship'] == $employee_relationship) || ($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) )) ) @@ -1475,7 +1479,8 @@ if (!function_exists('premium_calculation_manager')) } if(!$is_match_found) { - $age = calculate_days_bw_dates(from_date: $emp_data['dob'])->y; + $temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $age = calculate_days_bw_dates(from_date: $emp_data['dob'],to_date: $temp_date)->y; $log_message = '[ client_policy_id : ' .$emp_data['policy_details']['client_policy_id'].' - '. $emp_data['emp_code'].' - '.$emp_data['name'] .' - '. $emp_data['policy_details']['basic_cover_si'] . ', Age : '. $age.' ]'; if($temp_slab_rates[0]['premium_type'] == 1) { @@ -1560,6 +1565,7 @@ if (!function_exists('transform_db_data_to_excel')) $row['temp']['emp_status'] = $value['emp_status']; $row['temp']['policy_status'] = $value['status']; $row['temp']['rata_premimum'] = $value['rata_premimum']; + $row['temp']['file_id'] = $value['file_id']; array_push($return_data, ($row)); } diff --git a/app/Helpers/sendMailNotification.php b/app/Helpers/sendMailNotification.php index 3ac48a4d..2615b1fc 100755 --- a/app/Helpers/sendMailNotification.php +++ b/app/Helpers/sendMailNotification.php @@ -327,7 +327,7 @@ class sendMailNotification // dd($payable_employee_array); // dd(count($payable_employee_array['emp_data'])); - if(count($payable_employee_array['emp_data']) > 0){ + if(isset($payable_employee_array['emp_data']) && count($payable_employee_array['emp_data']) > 0){ $table_content .= '

Policy Type :'; $temp_data = ''; diff --git a/app/Libraries/MyLogger.php b/app/Libraries/MyLogger.php index efa401d5..71ebafe1 100755 --- a/app/Libraries/MyLogger.php +++ b/app/Libraries/MyLogger.php @@ -21,7 +21,7 @@ class MyLogger extends Logger $message = '{context} - {uuid} -' . $message; // /echo $message;//die(); - $context = array_merge($context,['uuid' => get_session_uuid()]); + $context = array_merge($context,['uuid' => (null !== get_session_uuid()) ? get_session_uuid() : 'CLI']); // print_r($context);die(); // echo isset($context['context']) ? $context['context'] : $this->context;die(); $context['context'] = isset($context['context']) ? $context['context'] : get_session_context(); diff --git a/app/Models/CDMasterModel.php b/app/Models/CDMasterModel.php index 8c7581a3..663ea3bc 100755 --- a/app/Models/CDMasterModel.php +++ b/app/Models/CDMasterModel.php @@ -65,28 +65,37 @@ class CDMasterModel extends Model { $query = $this->db->table('cd_master') + ->select('cd_master.*, clients.client_name, clients.short_name, insurers.name AS insurer_name, user_profiles.first_name AS user_name, IFNULL(cd_ac_counts.cd_ac_no_count, 0) AS cd_ac_no_count, IFNULL(cd_ac_counts_for_cdt.cd_ac_no_count_cd_tranction, 0) AS cd_ac_no_count_cd_tranction') ->join('clients', 'clients.id = cd_master.client_id') ->join('insurers', 'insurers.id = cd_master.insurer_id') ->join('user_profiles', 'user_profiles.id = cd_master.created_by') ->join( - '(SELECT cd_master.cd_ac_no, COUNT(client_policy.cd_ac_no) AS cd_ac_no_count - FROM cd_master - JOIN client_policy ON client_policy.cd_ac_no = cd_master.cd_ac_no - WHERE client_policy.is_active = 1 - AND cd_master.is_active = 1 - GROUP BY cd_master.cd_ac_no) AS cd_ac_counts', - 'cd_ac_counts.cd_ac_no = cd_master.cd_ac_no', + '(SELECT cd_master.cd_ac_no, cd_master.id, COUNT(client_policy.cd_ac_no) AS cd_ac_no_count + + FROM cd_master + JOIN client_policy ON client_policy.cd_ac_pk = cd_master.id + WHERE client_policy.is_active = 1 + AND cd_master.is_active = 1 + GROUP BY cd_master.id + + ) AS cd_ac_counts', + + 'cd_ac_counts.id = cd_master.id', 'left' ) ->join( - '(SELECT cd_master.cd_ac_no, COUNT(cash_deposit.cd_ac_no) AS cd_ac_no_count_cd_tranction - FROM cd_master - JOIN cash_deposit ON cash_deposit.cd_ac_no = cd_master.cd_ac_no - WHERE cash_deposit.is_active = 1 - AND cd_master.is_active = 1 - GROUP BY cd_master.cd_ac_no) AS cd_ac_counts_for_cdt', - 'cd_ac_counts_for_cdt.cd_ac_no = cd_master.cd_ac_no', + '(SELECT cd_master.cd_ac_no, cd_master.id, COUNT(cash_deposit.cd_ac_no) AS cd_ac_no_count_cd_tranction + + FROM cd_master + JOIN cash_deposit ON cash_deposit.cd_ac_pk = cd_master.id + WHERE cash_deposit.is_active = 1 + AND cd_master.is_active = 1 + GROUP BY cd_master.id + + ) AS cd_ac_counts_for_cdt', + + 'cd_ac_counts_for_cdt.id = cd_master.id', 'left' ) ->where('cd_master.is_active', 1) diff --git a/app/Models/COShareStmtDetailsModel.php b/app/Models/COShareStmtDetailsModel.php new file mode 100644 index 00000000..df007cf9 --- /dev/null +++ b/app/Models/COShareStmtDetailsModel.php @@ -0,0 +1,38 @@ +db->table('client_policy') - ->select('client_policy.*, cd_master.cd_ac_no') + ->select('client_policy.*, cd_master.cd_ac_no as cd_master_account_no') ->select('insurers.name as insurer_name, insurers.short_name as insurer_short') ->select('clients.client_name as client_name') ->join('clients','clients.id=client_policy.client_id') ->join('insurers', 'insurers.id = client_policy.insurer_id') ->join('cd_master', 'cd_master.insurer_id = insurers.id AND cd_master.client_id = client_policy.client_id') ->where('client_policy.client_id', $id) + ->where('cd_master.id = client_policy.cd_ac_pk') ->groupBy('client_policy.insurer_id') ->groupBy('client_policy.client_id', $id) // Group by insurer_id ->get() @@ -225,6 +227,7 @@ class ClientPolicyModel extends Model ->select('cash_deposit.*') ->select('insurers.name as insurer_name, insurers.short_name as insurer_short') ->select('clients.client_name as clientname, clients.short_name as clientshort, client_policy.policy_no') + ->select('cd_master.cd_ac_no as cd_master_account_no') // ->select('policies.name as policy_name') ->select('policy_type.policy_type') ->select('user_profiles.first_name as username') @@ -232,11 +235,13 @@ class ClientPolicyModel extends Model ->join('insurers', 'insurers.id = cash_deposit.insurer_id', 'left') ->join('clients', 'clients.id = cash_deposit.client_id', 'left') ->join('client_policy', 'client_policy.id = cash_deposit.client_policy_id', 'left') + ->join('cd_master', 'cd_master.id = cash_deposit.cd_ac_pk', 'left') // ->join('policies', 'policies.id = client_policy.policy_id', 'left') ->join('policy_type', 'policy_type.id = client_policy.policy_type_id', 'left') ->where('cash_deposit.client_id', $clientId) ->where('cash_deposit.insurer_id', $insurerId) ->where('cash_deposit.is_active', 1) + // ->where('cash_deposit.cd_ac_pk = cd_master.id') ->orderBy('cash_deposit.id', 'DESC') ->get() ->getResult(); diff --git a/app/Models/EmployeeModel.php b/app/Models/EmployeeModel.php index 44e387e2..73caca1e 100755 --- a/app/Models/EmployeeModel.php +++ b/app/Models/EmployeeModel.php @@ -106,7 +106,7 @@ class EmployeeModel extends Model public function getEmpFamilybyEmpCode(string $client_policy_id = null,string $emp_code = null,string $client_id = null,array $emp_status = [],array $policy_status = [],array $relationship = [],array $client_branch_id = []) { - $result = $this->select(['employees.id as emp_id', 'employees.client_id','employees.client_branch_id', 'employees.relationship', 'employees.relationship_code', 'employees.change_event', 'employees.emp_code', 'employees.name', 'employees.email_personal', 'employees.email_corporate', 'employees.mobile', 'employees.gender', 'employees.dob', 'employees.doj', 'employees.basic_pay', 'employees.band', 'employees.designation', 'employees.emp_status','employees.unit','employee_polices.id as emp_policy_id', 'employee_polices.employee_id', 'employee_polices.client_policy_id', 'employee_polices.tpa_id', 'employee_polices.uhid', 'employee_polices.batch_code', 'employee_polices.status', 'employee_polices.pre_existing_alignments', 'employee_polices.basic_cover_si', 'employee_polices.date_coverage', 'employee_polices.policy_end_date', 'employee_polices.days', 'employee_polices.premium', 'employee_polices.rata_premimum', 'employee_polices.gst', 'employee_polices.date_of_exit', 'employee_polices.reason_for_exit','policy_type.long_name as policy_name','client_policy.is_addon', 'employee_polices.payable_employee']) + $result = $this->select(['employees.id as emp_id', 'employees.client_id','employees.client_branch_id', 'employees.relationship', 'employees.relationship_code', 'employees.change_event', 'employees.emp_code', 'employees.name', 'employees.email_personal', 'employees.email_corporate', 'employees.mobile', 'employees.gender', 'employees.dob', 'employees.doj', 'employees.basic_pay', 'employees.band', 'employees.designation', 'employees.emp_status','employees.unit','employees.file_id','employee_polices.id as emp_policy_id', 'employee_polices.employee_id', 'employee_polices.client_policy_id', 'employee_polices.tpa_id', 'employee_polices.uhid', 'employee_polices.batch_code', 'employee_polices.status', 'employee_polices.pre_existing_alignments', 'employee_polices.basic_cover_si', 'employee_polices.date_coverage', 'employee_polices.policy_end_date', 'employee_polices.days', 'employee_polices.premium', 'employee_polices.rata_premimum', 'employee_polices.gst', 'employee_polices.date_of_exit', 'employee_polices.reason_for_exit','policy_type.long_name as policy_name','client_policy.is_addon', 'employee_polices.payable_employee']) ->join('employee_polices', 'employee_polices.employee_id = employees.id') ->join('client_policy', 'client_policy.id = employee_polices.client_policy_id') ->join('policy_type', 'policy_type.id = client_policy.policy_type_id','left') @@ -212,4 +212,32 @@ class EmployeeModel extends Model return $results; } + public function getTestEmployeeData(){ + $query = " + SELECT + e.*, + ( + SELECT + COUNT(ep.client_policy_id) + FROM + employee_polices ep + WHERE + ep.employee_id = e.id + ) AS policy_count + FROM + employees e + WHERE + e.emp_code LIKE 'TEST%' + ORDER BY + e.emp_code, + CASE + WHEN e.relationship = 'self' THEN 1 + WHEN e.relationship = 'spouse' THEN 2 + ELSE 3 + END; + "; + $results = $this->db->query($query)->getResultArray(); + return $results; + } + } diff --git a/app/Models/EmployeePolicyModel.php b/app/Models/EmployeePolicyModel.php index 9d281507..f536cb37 100755 --- a/app/Models/EmployeePolicyModel.php +++ b/app/Models/EmployeePolicyModel.php @@ -35,6 +35,7 @@ class EmployeePolicyModel extends Model "claim_status", 'ecard_sent_status', 'payable_employee', + 'file_id' ]; // Callbacks @@ -179,7 +180,11 @@ class EmployeePolicyModel extends Model $result->where('employee_polices.is_active', 1) ->where('emp.is_active', 1); - return $result->findAll(); + $res = $result->findAll(); + + // dd($this->db->getLastQuery()); + + return $res; } public function getEmployeePolicyForEcard($policy_id = 0) @@ -275,7 +280,7 @@ class EmployeePolicyModel extends Model employee_polices.uhid, employee_polices.pre_existing_alignments, employee_polices.basic_cover_si, - employee_polices.date_coverage, + employee_polices.date_coverage as date_of_coverage, employee_polices.policy_end_date, employee_polices.days as no_of_days, employee_polices.premium, @@ -322,6 +327,9 @@ class EmployeePolicyModel extends Model }else{ $results = $query->getResult(); } + + // dd($this->db->getLastQuery()); + return $results; } @@ -556,6 +564,175 @@ class EmployeePolicyModel extends Model } + // DO NOT DELETE this DELETION QUERY FUNCTION + + // public function getDeletionEmployeeDataForExportExcel($ref_data, $return_type = 0) + // { + + // $client_id = $ref_data['client_id']; + // $client_policy_id = $ref_data['client_policy_id']; + // $client_branch_id = $ref_data['client_branch_id']; + // $insurer_or_tpa = $ref_data['insurer_or_tpa']; + + // $get_insurer_id_from_client_policy = $this->db->table('client_policy') + // ->select('insurer_id') + // ->where('id', $client_policy_id) + // ->get() + // ->getRowArray(); + + // $add_one_day = 0; + + // if (!empty($get_insurer_id_from_client_policy)) { + + // $get_the_insurer_add_one_for_delete = $this->db->table('insurers') + // ->select('deletion_add_day') + // ->where('id', $get_insurer_id_from_client_policy['insurer_id']) + // ->get() + // ->getRowArray(); + + // if (!empty($get_the_insurer_add_one_for_delete) && $get_the_insurer_add_one_for_delete['deletion_add_day'] == 1) { + // $add_one_day = 1; + // } + // } + + // $status_condition = "{$insurer_or_tpa}" === 'tpa' + // ? "employee_polices.status = 'inactive' AND employees.emp_status = 'inactive'" + // : "employee_polices.status = 'active' AND employees.emp_status = 'active'"; + + // $endorsement_condition = "{$insurer_or_tpa}" === 'tpa' ? "AND (a.endorsement_id IS NOT NULL OR a.endorsement_id != '')" : "AND (a.endorsement_id IS NULL OR a.endorsement_id = '')"; + + // $query = $this->db->query(" + // SELECT DISTINCT + // a.id as endorsement_primarykey, + // a.group_key, + // employee_polices.id as primaryKey, + // employees.name AS emp_name, + // employees.emp_code AS emp_code, + // employees.dob AS emp_dob, + // employees.gender AS emp_gender, + // employees.relationship AS emp_relationship, + // employees.relationship_code AS emp_relationship_code, + // employees.emp_type as emp_type, + // 'D' as event_type_data, + // TIMESTAMPDIFF(YEAR, employees.dob, CURDATE()) AS emp_age, + + // employees.doj AS emp_doj, + // employees.mobile AS emp_mobile, + // employees.email_corporate AS emp_email_c, + // employees.email_personal AS emp_email_p, + // employees.band AS emp_grade, + // employees.designation AS emp_designation, + // employees.basic_pay AS emp_basic_pay, + + // employee_polices.basic_cover_si, + // employee_polices.uhid as uhid, + // employee_polices.policy_end_date, + // employee_polices.rata_premimum as premium, + // employee_polices.claim_status, + + // batch_data.emp_policy_id AS emp_policy_id, + // batch_data.bl AS batch_list_batch_code, + // batch_data.bf AS batch_files_batch_code, + + // deletiondata.empstatus, + // deletiondata.changeevent, + // deletiondata.dateofexit, + // deletiondata.reasonforexit, + // deletiondata.status, + + // DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + '$add_one_day' AS no_of_days, + + + // CASE + // WHEN employee_polices.claim_status = 0 THEN + // ROUND((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365, 2) + // ELSE + // 0 + // END AS pro_rata_premium, + + // CASE + // WHEN employee_polices.claim_status = 0 THEN + // ROUND(((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) * 0.18, 2) + // ELSE + // 0 + // END AS gst, + + // CASE + // WHEN employee_polices.claim_status = 0 THEN + // ROUND(((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) + + // (((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) * 0.18), 2) + // ELSE + // 0 + // END AS total, + + // CASE + // WHEN employee_polices.claim_status = 0 THEN + // 'No claim' + // ELSE + // 'Claim' + // END AS claim_status + + // FROM + // emp_endorsement a + // LEFT JOIN + // employees ON a.emp_code = employees.emp_code + // LEFT JOIN + // employee_polices ON employees.id = employee_polices.employee_id + + // LEFT JOIN( + + // select aa.emp_code, aa.new_value as 'empstatus', bb.new_value as 'changeevent', cc.new_value as 'dateofexit', dd.new_value as 'reasonforexit', ee.new_value as 'status' from + + // ( SELECT a1.emp_code, a1.field_name, a1.new_value from emp_endorsement as a1 where a1.field_name = 'emp_status' and a1.status != 'truncated') aa + // left join + // ( SELECT b1.emp_code, b1.field_name, b1.new_value from emp_endorsement as b1 where b1.field_name = 'change_event' and b1.status != 'truncated') bb on aa.emp_code = bb.emp_code + // left join + // ( SELECT c1.emp_code, c1.field_name, c1.new_value from emp_endorsement as c1 where c1.field_name = 'date_of_exit' and c1.status != 'truncated') cc on aa.emp_code = cc.emp_code + // left join + // ( SELECT d1.emp_code, d1.field_name, d1.new_value from emp_endorsement as d1 where d1.field_name = 'reason_for_exit' and d1.status != 'truncated') dd on aa.emp_code = dd.emp_code + // left JOIN + // ( SELECT e1.emp_code, e1.field_name, e1.new_value from emp_endorsement as e1 where e1.field_name = 'status' and e1.status != 'truncated') ee on aa.emp_code = ee.emp_code + + // ) as deletiondata on a.emp_code = deletiondata.emp_code and a.status != 'truncated' + + // LEFT JOIN + // ( + // SELECT + // batch_list.emp_policy_id, + // batch_list.batch_code AS bl, + // batch_files.batch_code AS bf + // FROM + // batch_files + // LEFT JOIN + // batch_list ON batch_files.batch_code = batch_list.batch_code + // WHERE + // batch_files.event_type = 'deletion' + // AND batch_files.actions = 'export' + // AND batch_files.insurer_or_tpa = '{$insurer_or_tpa}' + // ) AS batch_data ON employee_polices.id = batch_data.emp_policy_id + + // WHERE employee_polices.client_policy_id = {$client_policy_id} + // AND employees.client_branch_id = {$client_branch_id} + // $endorsement_condition + // AND a.actions = 'd' + // AND a.status != 'truncated' + // AND employee_polices.is_active = 1 + // AND employees.is_active = 1 + // AND $status_condition + // group by group_key + // "); + + // if($return_type == 1){ + // $result = $query->getResultArray(); + // }else{ + // $result = $query->getResult(); + // } + + // // dd($this->db->getLastQuery(), $result); + + // return $result; + + // } public function getDeletionEmployeeDataForExportExcel($ref_data, $return_type = 0) { @@ -630,26 +807,26 @@ class EmployeePolicyModel extends Model deletiondata.dateofexit, deletiondata.reasonforexit, deletiondata.status, + deletiondata.claimstatus, DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + '$add_one_day' AS no_of_days, - CASE - WHEN employee_polices.claim_status = 0 THEN + WHEN deletiondata.claimstatus = 0 THEN ROUND((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365, 2) ELSE 0 END AS pro_rata_premium, CASE - WHEN employee_polices.claim_status = 0 THEN + WHEN deletiondata.claimstatus = 0 THEN ROUND(((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) * 0.18, 2) ELSE 0 END AS gst, CASE - WHEN employee_polices.claim_status = 0 THEN + WHEN deletiondata.claimstatus = 0 THEN ROUND(((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) + (((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) * 0.18), 2) ELSE @@ -657,7 +834,7 @@ class EmployeePolicyModel extends Model END AS total, CASE - WHEN employee_polices.claim_status = 0 THEN + WHEN deletiondata.claimstatus = 0 THEN 'No claim' ELSE 'Claim' @@ -666,28 +843,32 @@ class EmployeePolicyModel extends Model FROM emp_endorsement a LEFT JOIN - employees ON a.emp_code = employees.emp_code and a.pk = employees.id + employee_polices ON a.pk = employee_polices.id LEFT JOIN - employee_polices ON employees.id = employee_polices.employee_id - - LEFT JOIN( - - select aa.emp_code, aa.new_value as 'empstatus', bb.new_value as 'changeevent', cc.new_value as 'dateofexit', dd.new_value as 'reasonforexit', ee.new_value as 'status' from - - ( SELECT a1.emp_code, a1.field_name, a1.new_value from emp_endorsement as a1 where a1.field_name = 'emp_status' and a1.status != 'truncated') aa - left join - ( SELECT b1.emp_code, b1.field_name, b1.new_value from emp_endorsement as b1 where b1.field_name = 'change_event' and b1.status != 'truncated') bb on aa.emp_code = bb.emp_code - left join - ( SELECT c1.emp_code, c1.field_name, c1.new_value from emp_endorsement as c1 where c1.field_name = 'date_of_exit' and c1.status != 'truncated') cc on aa.emp_code = cc.emp_code - left join - ( SELECT d1.emp_code, d1.field_name, d1.new_value from emp_endorsement as d1 where d1.field_name = 'reason_for_exit' and d1.status != 'truncated') dd on aa.emp_code = dd.emp_code - left JOIN - ( SELECT e1.emp_code, e1.field_name, e1.new_value from emp_endorsement as e1 where e1.field_name = 'status' and e1.status != 'truncated') ee on aa.emp_code = ee.emp_code - - ) as deletiondata on a.emp_code = deletiondata.emp_code and a.status != 'truncated' + employees ON employee_polices.employee_id = employees.id + + LEFT JOIN ( + SELECT + emp_code, + group_key, + MAX(CASE WHEN field_name = 'emp_status' THEN new_value END) AS empstatus, + MAX(CASE WHEN field_name = 'change_event' THEN new_value END) AS changeevent, + MAX(CASE WHEN field_name = 'date_of_exit' THEN new_value END) AS dateofexit, + MAX(CASE WHEN field_name = 'reason_for_exit' THEN new_value END) AS reasonforexit, + MAX(CASE WHEN field_name = 'status' THEN new_value END) AS status, + MAX(CASE WHEN field_name = 'claim_status' THEN new_value END) AS claimstatus + FROM + emp_endorsement + WHERE + status != 'truncated' + GROUP BY + group_key + + ) AS deletiondata + ON a.emp_code = deletiondata.emp_code AND a.status != 'truncated' LEFT JOIN - ( + ( SELECT batch_list.emp_policy_id, batch_list.batch_code AS bl, @@ -700,7 +881,7 @@ class EmployeePolicyModel extends Model batch_files.event_type = 'deletion' AND batch_files.actions = 'export' AND batch_files.insurer_or_tpa = '{$insurer_or_tpa}' - ) AS batch_data ON employee_polices.id = batch_data.emp_policy_id + ) AS batch_data ON employee_polices.id = batch_data.emp_policy_id WHERE employee_polices.client_policy_id = {$client_policy_id} AND employees.client_branch_id = {$client_branch_id} @@ -720,6 +901,7 @@ class EmployeePolicyModel extends Model } // dd($this->db->getLastQuery(), $result); + // dd($result); return $result; @@ -742,6 +924,7 @@ class EmployeePolicyModel extends Model ee.id as emp_endorsement_primarykey, ep.id as emp_policy_primarykey, e.id as employees_primarykey, + ee.file_id, ee.group_key, ( SELECT employees.id @@ -769,7 +952,12 @@ class EmployeePolicyModel extends Model CASE WHEN ee.field_name = 'status' THEN ee.new_value END - ) AS status + ) AS status, + MAX( + CASE + WHEN ee.field_name = 'claim_status' THEN ee.new_value + END + ) AS claim_status FROM emp_endorsement AS ee JOIN employee_polices AS ep ON ep.id = ee.pk @@ -779,7 +967,7 @@ class EmployeePolicyModel extends Model AND ep.client_policy_id = '$client_policy_id' AND e.client_branch_id = '$client_branch_id' AND ee.name = '$emp_name' - AND ee.field_name IN ('date_of_exit', 'reason_for_exit', 'status') + AND ee.field_name IN ('date_of_exit', 'reason_for_exit', 'status', 'claim_status') AND ep.is_active = 1 AND ep.status = 'active' AND e.is_active = 1 @@ -837,7 +1025,6 @@ class EmployeePolicyModel extends Model e.remarks, e.endorsement_id, ep.client_policy_id, - policies.name as policy_name, insurers.short_name as insurer_short_name, client_policy.policy_no, policy_type.policy_type @@ -847,9 +1034,9 @@ class EmployeePolicyModel extends Model $query1->join('employees', 'employees.id = ep.employee_id'); $query1->join('client_policy', 'client_policy.id = ep.client_policy_id'); $query1->join('client_branch', 'client_branch.id = employees.client_branch_id'); - $query1->join('policies', 'policies.id = client_policy.policy_id'); - $query1->join('policy_type', 'policy_type.id = policies.policy_type_id'); - $query1->join('insurers', 'insurers.id = policies.insurer_id'); + // $query1->join('policies', 'policies.id = client_policy.policy_id'); + $query1->join('policy_type', 'policy_type.id = client_policy.policy_type_id'); + $query1->join('insurers', 'insurers.id = client_policy.insurer_id'); $query1->whereIn('e.actions', ['c']); $query1->where('ep.client_policy_id', $policy_id); $query1->where('employees.client_id', $client_id); @@ -874,7 +1061,6 @@ class EmployeePolicyModel extends Model e.endorsement_id, e.remarks, ep.client_policy_id, - policies.name as policy_name, insurers.short_name as insurer_short_name, client_policy.policy_no, policy_type.policy_type @@ -883,10 +1069,10 @@ class EmployeePolicyModel extends Model $query2->join('employees', 'employees.id = ep.employee_id'); $query2->join('client_policy', 'client_policy.id = ep.client_policy_id'); $query2->join('client_branch', 'client_branch.id = employees.client_branch_id'); - $query2->join('policies', 'policies.id = client_policy.policy_id'); - $query2->join('policy_type', 'policy_type.id = policies.policy_type_id'); - $query2->join('insurers', 'insurers.id = policies.insurer_id'); - $query2->whereIn('e.actions', ['si', 'd']); + // $query2->join('policies', 'policies.id = client_policy.policy_id'); + $query2->join('policy_type', 'policy_type.id = client_policy.policy_type_id'); + $query2->join('insurers', 'insurers.id = client_policy.insurer_id'); + $query2->whereIn('e.actions', ['si', 'd', 'a']); $query2->where('ep.client_policy_id', $policy_id); $query2->where('employees.client_id', $client_id); $query2->where('employees.client_branch_id', $branch_id); @@ -900,6 +1086,8 @@ class EmployeePolicyModel extends Model $results2 = $query2->get()->getResultArray(); $results = array_merge($results1, $results2); + + // dd($this->db->getLastQuery()); return $results; @@ -1180,13 +1368,13 @@ class EmployeePolicyModel extends Model return "WHEN group_key = $id THEN $endorsement_id"; }, $escapedIds, $escapedEndorsementIds); - $caseStatus = array_map(function ($id, $status) { - return "WHEN status = $id THEN $status"; - }, $escapedIds, $escapedStatuses); + // $caseStatus = array_map(function ($id, $status) { + // return "WHEN status = $id THEN $status"; + // }, $escapedIds, $escapedStatuses); // Convert cases to a string $caseEndorsementIdString = implode(' ', $caseEndorsementId); - $caseStatusString = implode(' ', $caseStatus); + // $caseStatusString = implode(' ', $caseStatus); // Convert ids to a string $idsString = implode(', ', $escapedIds); @@ -1196,10 +1384,12 @@ class EmployeePolicyModel extends Model UPDATE emp_endorsement SET endorsement_id = CASE {$caseEndorsementIdString} END, - status = CASE {$caseStatusString} END + status = 'complete' WHERE group_key IN ({$idsString}) "; + + // dd($sql); // Begin a transaction $this->db->transBegin(); @@ -1216,6 +1406,7 @@ class EmployeePolicyModel extends Model // Otherwise, commit $this->db->transCommit(); } + // $this->storeEndorsementNumber($file_id, $endorsement_id, $enrollment_file_id); return $this->db->getLastQuery(); } catch (\Exception $e) { @@ -1287,5 +1478,209 @@ class EmployeePolicyModel extends Model } + //for truncate get deletion data + public function getDeletionDataForTruncated($file_id) + { + // Fetch the necessary details in a single query using JOINs + $result = $this->db->table('files f') + ->select('i.deletion_add_day') + ->join('client_policy cp', 'cp.id = f.policy_id', 'left') + ->join('insurers i', 'i.id = cp.insurer_id', 'left') + ->where('f.id', $file_id) + ->get() + ->getRowArray(); + + // Determine if one day should be added for deletion + $add_one_day = (!empty($result) && $result['deletion_add_day'] == 1) ? 1 : 0; + + + $query = $this->db->query(" + + SELECT DISTINCT + + a.id as endorsement_primarykey, + a.group_key, + employee_polices.id as primaryKey, + employees.name AS emp_name, + employees.emp_code AS emp_code, + employees.dob AS emp_dob, + employees.gender AS emp_gender, + employees.relationship AS emp_relationship, + employees.relationship_code AS emp_relationship_code, + employees.emp_type as emp_type, + 'D' as event_type_data, + TIMESTAMPDIFF(YEAR, employees.dob, CURDATE()) AS emp_age, + + employees.doj AS emp_doj, + employees.mobile AS emp_mobile, + employees.email_corporate AS emp_email_c, + employees.email_personal AS emp_email_p, + employees.band AS emp_grade, + employees.designation AS emp_designation, + employees.basic_pay AS emp_basic_pay, + + employee_polices.basic_cover_si, + employee_polices.uhid as uhid, + employee_polices.policy_end_date, + employee_polices.rata_premimum as premium, + employee_polices.claim_status, + + deletiondata.empstatus, + deletiondata.changeevent, + deletiondata.dateofexit, + deletiondata.reasonforexit, + deletiondata.status, + deletiondata.claimstatus, + + DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + '$add_one_day' AS no_of_days, + + CASE + WHEN deletiondata.claimstatus = 0 THEN + ROUND((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365, 2) + ELSE + 0 + END AS pro_rata_premium, + + CASE + WHEN deletiondata.claimstatus = 0 THEN + ROUND(((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) * 0.18, 2) + ELSE + 0 + END AS gst, + + CASE + WHEN deletiondata.claimstatus = 0 THEN + ROUND(((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) + + (((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) * 0.18), 2) + ELSE + 0 + END AS total, + + CASE + WHEN deletiondata.claimstatus = 0 THEN + 'No claim' + ELSE + 'Claim' + END AS claim_status + + FROM + emp_endorsement a + LEFT JOIN + employee_polices ON a.pk = employee_polices.id + LEFT JOIN + employees ON employee_polices.employee_id = employees.id + + LEFT JOIN ( + SELECT + emp_code, + group_key, + MAX(CASE WHEN field_name = 'emp_status' THEN new_value END) AS empstatus, + MAX(CASE WHEN field_name = 'change_event' THEN new_value END) AS changeevent, + MAX(CASE WHEN field_name = 'date_of_exit' THEN new_value END) AS dateofexit, + MAX(CASE WHEN field_name = 'reason_for_exit' THEN new_value END) AS reasonforexit, + MAX(CASE WHEN field_name = 'status' THEN new_value END) AS status, + MAX(CASE WHEN field_name = 'claim_status' THEN new_value END) AS claimstatus + FROM + emp_endorsement + WHERE + status != 'truncated' + GROUP BY + group_key + + ) AS deletiondata + + ON a.emp_code = deletiondata.emp_code AND a.status != 'truncated' + + WHERE a.file_id = {$file_id} + AND a.actions = 'd' + AND a.status != 'truncated' + AND employee_polices.is_active = 1 + AND employees.is_active = 1 + group by group_key + "); + + + $result = $query->getResultArray(); + // dd($this->db->getLastQuery(), $result); + // dd($result); + + return $result; + + } + + //for truncate get addition data + public function getAdditionDataForTruncated($file_id, $event_type) + { + $action = "a"; + if($event_type == "dependent_addition"){ + $action = "da"; + } + + $query = $this->db->query(" + + SELECT + ROUND(SUM(ep.rata_premimum + ep.gst), 2) AS total + FROM + emp_endorsement ee + JOIN + employee_polices ep ON ee.pk = ep.id + WHERE + ee.file_id = $file_id + AND ee.actions = '$action' + AND ep.status != 'truncated' + AND ee.status != 'truncated' + AND ee.is_active = 1 + AND ep.is_active = 1; + "); + + + $result = $query->getResultArray(); + // dd($this->db->getLastQuery(), $result); + // dd($result); + + return $result[0]; + + } + + // reverse the employee policy table data for the truncated the deletion file + public function updateEmployeePolicyTruncateReverse($file_id) + { + $this->db->query(" + UPDATE employee_polices + SET + is_active = 1, + status = 'active', + date_of_exit = NULL, + reason_for_exit = NULL, + claim_status = 0, + WHERE + id IN ( + SELECT pk + FROM emp_endorsement + WHERE file_id = $file_id + GROUP BY group_key + ) + AND status = 'inactive' + "); + + } + + //update employee policy table status truncated and is_active 0 for truncated to the addition file + public function updateEmpEndorsementAddition($array) + { + $caseStatus = "CASE "; + $caseEndorsementId = "CASE "; + $ids = []; + foreach ($array as $item) { + $caseStatus .= "WHEN id = {$item['id']} THEN '{$item['status']}' "; + $caseEndorsementId .= "WHEN id = {$item['id']} THEN '{$item['endorsement_id']}' "; + $ids[] = $item['id']; + } + $caseStatus .= "END"; + $caseEndorsementId .= "END"; + $ids = implode(',', $ids); + $query = "UPDATE emp_endorsement SET status = $caseStatus, endorsement_id = $caseEndorsementId WHERE id IN ($ids);"; // Execute the query + $this->db->query($query); + } } \ No newline at end of file diff --git a/app/Models/InsurerModel.php b/app/Models/InsurerModel.php index a19cd02a..e24dd00a 100755 --- a/app/Models/InsurerModel.php +++ b/app/Models/InsurerModel.php @@ -41,11 +41,12 @@ class InsurerModel extends Model { // Fetch the insurer name based on the insurer ID $query = $this->db->table('client_policy') - ->select('insurers.id, insurers.name, cd_master.cd_ac_no') + ->select('insurers.id, insurers.name, cd_master.cd_ac_no as cd_master_account_no') ->join('insurers', 'insurers.id = client_policy.insurer_id') ->join('cd_master', 'cd_master.insurer_id = insurers.id AND cd_master.client_id = client_policy.client_id') ->where('client_policy.insurer_id', $insurerId) ->where('client_policy.client_id', $client_id) + ->where('cd_master.id = client_policy.cd_ac_pk') ->get(); if ($query->resultID->num_rows > 0) { @@ -60,7 +61,7 @@ class InsurerModel extends Model { $insurer_data = $this->db->table('insurer_excel_export_template') ->select('insurer_excel_export_template.*, insurers.name as insurer_name, insurers.is_multi_event') - ->select('CASE WHEN insurers.is_multi_event = 1 THEN "All" ELSE insurer_excel_export_template.event_name END as event_name', false) + // ->select('CASE WHEN insurers.is_multi_event = 1 THEN "All" ELSE insurer_excel_export_template.event_name END as event_name', false) ->select('insurer_excel_export_template.type_name, insurer_excel_export_template.jsoncolumns, policy_type.policy_type') ->join('insurers', 'insurers.id = insurer_excel_export_template.insurer_id') ->join('policy_type', 'policy_type.id = insurer_excel_export_template.policy_type_id') diff --git a/app/Models/InsurerStatements.php b/app/Models/InsurerStatements.php index 0e2dc2ec..257624cd 100644 --- a/app/Models/InsurerStatements.php +++ b/app/Models/InsurerStatements.php @@ -23,7 +23,11 @@ class InsurerStatements extends Model "invoice_no", "invoice_amount", "invoice_date", - "updated_by" + "updated_by", + "stmt_sno", + "gst_per", + "gst_value", + "invoice_value" ]; diff --git a/app/Models/InvPaymentDetailsModel.php b/app/Models/InvPaymentDetailsModel.php index 262f76d6..7f7a7522 100644 --- a/app/Models/InvPaymentDetailsModel.php +++ b/app/Models/InvPaymentDetailsModel.php @@ -16,6 +16,7 @@ class InvPaymentDetailsModel extends Model 'inv_amt', 'utr_no', 'tds', + 'gst', 'received_date', 'created_by', 'is_active', diff --git a/app/Models/LeadsModel.php b/app/Models/LeadsModel.php index cae506f2..5867a5d0 100644 --- a/app/Models/LeadsModel.php +++ b/app/Models/LeadsModel.php @@ -37,7 +37,7 @@ class LeadsModel extends Model 'policy_start_date', 'policy_end_date', 'no_of_lives', - 'claims', + 'incurred_claims', 'location', 'proposed_insurer_id', 'proposed_insurer_branch_id', @@ -52,6 +52,38 @@ class LeadsModel extends Model 'updated_by', 'is_active', 'is_client_created', + + 'renewal_emp_count', + 'renewal_dept_count', + 'renewal_no_of_lives', + 'incept_emp_count', + 'incept_dept_count', + 'incept_no_of_lives', + 'exp_emp_count', + 'exp_dept_count', + 'exp_no_of_lives', + 'file_name', + + 'incurred_claims_date', + 'paid_claims', + 'outstanding_claims', + 'policy_run_days', + 'premium_at_inception', + 'premium_date', + 'earned_premium', + 'annualised_claims', + 'incurred_claims_ratio', + 'earned_claims_ratio', + + 'placement_date', + 'utr_no', + 'premium_amount', + 'total_amount', + 'cd_amount', + + 'total_si_at_incept', + 'total_si_at_renewal', + 'fin_years_claims', ]; diff --git a/app/Models/PTCOShareDetailsModel.php b/app/Models/PTCOShareDetailsModel.php index 385645ed..bb2eb359 100644 --- a/app/Models/PTCOShareDetailsModel.php +++ b/app/Models/PTCOShareDetailsModel.php @@ -63,11 +63,15 @@ class PTCOShareDetailsModel extends Model 'amount', 'stamp_duty', 'cop_amt', - 'statement_id' + 'statement_id', + 'follower_policy_no', ]; - public function getNonReconcileredPolicyTransactions(string $month,string $year,string $insurer_id,string $insurer_branch_id) + public function getNonReconcileredPolicyTransactions(string $insurer_id,string $insurer_branch_id) { + $currentDate = date('Y-m-d'); + $sixMonthsAgo = date('Y-m-01', strtotime('-6 months')); + return $this->db->table('pt_co_share_details pt_co') ->select(' pt_co.id, @@ -93,12 +97,15 @@ class PTCOShareDetailsModel extends Model ->join('policy_transaction pt', 'pt_co.pt_id = pt.id') ->join('clients c', 'pt.client_id = c.id') ->where('pt_co.is_active', 1) - ->where('MONTH(pt.month)', $month) - ->where('YEAR(pt.month)', $year) + ->where('pt.is_active', 1) + // ->where('MONTH(pt.month)', $month) + // ->where('YEAR(pt.month)', $year) ->where('pt_co.insurer_id', $insurer_id) ->where('pt_co.insurer_branch_id', $insurer_branch_id) - ->where('pt_co.statement_id is null') + // ->where('pt_co.statement_id is null') ->where('pt.status','completed') + ->where('DATE(pt.created_at) >=', $sixMonthsAgo) + ->where('DATE(pt.created_at) <=', $currentDate) // ->where('pt_co.exp_amt', 0.00) // ->orWhere('pt_co.exp_amt is null') ->get() diff --git a/app/Models/PolicyTransactionModel.php b/app/Models/PolicyTransactionModel.php index ba54a5ce..0364fd17 100644 --- a/app/Models/PolicyTransactionModel.php +++ b/app/Models/PolicyTransactionModel.php @@ -76,6 +76,7 @@ class PolicyTransactionModel extends Model 'ct_tran_id', 'remarks', 'month', + 'cd_ac_pk' ]; @@ -113,8 +114,9 @@ class PolicyTransactionModel extends Model return $data; } + // BDS Report OLD Functin for QUERY // public function getBDSReportList($client_id, $policy_id, $branch_id, $issuer) - public function getBDSReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0) + public function getBDSReportListOld($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0) { $builder = $this->db->table('policy_transaction') ->select(" @@ -311,6 +313,257 @@ class PolicyTransactionModel extends Model return $builder->get()->getResultArray(); } + + // BDS Report NEW Functin for QUERY + // public function getBDSReportList($client_id, $policy_id, $branch_id, $issuer) + public function getBDSReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0) + { + + $date_condition = ''; + if($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) { + $date_condition = " + AND insurer_statements.month >= '".$start_date ."' + AND insurer_statements.month <= '".$end_date ."' + "; + } + + $builder = $this->db->table('policy_transaction') + ->select(" + policy_transaction.*, + DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date, + DATE_FORMAT( + IF(policy_transaction.month IS NULL, + policy_transaction.policy_issue_date, + policy_transaction.month), + '%b %Y') AS policy_issue_month, + 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.reward, + pt_co_share_details.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.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) AS premium_wo_gst, + + ROUND((ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) * 18 / 100), 2) AS gst_amount, + + ROUND((ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) + ROUND((ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) * 18 / 100), 2)), 2) AS total_premium, + + ROUND((pt_co_share_details.tp_amt + pt_co_share_details.tep_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, + + ROUND( + ( + 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) + + ) AS total_irda_amt + 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, + + 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) + ) AS total_irda_amt + 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_no IS NOT NULL + $date_condition + + ), + 2 + ) AS billed_amt, + + 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_no IS NULL + $date_condition + ) + ), + 2 + ) AS unbilled_amt + + ") + ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') + ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.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', 'policy_transaction.insurer_id = insurers.id', 'left') + ->join('insurer_branch', 'policy_transaction.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') + ->where('policy_transaction.is_active', 1) + ->where('pt_co_share_details.is_active', 1); + + // Check if the start date and end date are provided + 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)); + + $builder->where('policy_transaction.'.$date_type.'>=', $startDate) + ->where('policy_transaction.'.$date_type.'<=', $endDate); + + }else{ + + // $fromDate = date('Y-m-d', strtotime('-30 days')); + // $toDate = date('Y-m-d 23:59:59'); + + // $builder->where('policy_transaction.created_at >=', $fromDate) + // ->where('policy_transaction.created_at <=', $toDate); + } + + if($date_type == 'statement_month' && $start_date != 0 && $end_date != 0){ + + $builder->where('policy_transaction.month >=', $startDate) + ->where('policy_transaction.month <=', $endDate); + } + + if ($client_id != 0) { + $builder->where('policy_transaction.client_id', $client_id); + } + + if ($insurer_id != 0) { + $builder->where('policy_transaction.insurer_id', $insurer_id); + } + + if ($client_branch_id != 0) { + $builder->where('policy_transaction.client_branch_id', $client_branch_id); + } + + if ($insurer_branch_id != 0) { + $builder->where('policy_transaction.insurer_branch_id', $insurer_branch_id); + } + + if ($client_policy_id != 0) { + $builder->where('policy_transaction.client_policy_id', $client_policy_id); + } + + + + if ($policy_type_id != 0) { + $builder->where('client_policy.policy_type_id', $policy_type_id); + } + + if ($issuer != 0) { + $builder->where('policy_transaction.issuer', $issuer); + } + + if($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0){ + + $fromDate = date('Y-m-d', strtotime('-30 days')); + $toDate = date('Y-m-d 23:59:59'); + + $builder->where('policy_transaction.created_at >=', $fromDate) + ->where('policy_transaction.created_at <=', $toDate); + + } + + $builder->orderBy('policy_transaction.id', 'desc'); + + $result = $builder->get()->getResultArray(); + + // dd($this->db->getLastQuery()); + + return $result; + } public function getInceptionTranctionListData($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) { @@ -466,50 +719,74 @@ class PolicyTransactionModel extends Model return $builder->get()->getResultArray(); } - public function getVarienceReportLIst($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) + public function getVarienceReportLIst($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0) { $builder = $this->db->table('policy_transaction') ->select(" + policy_transaction.id, clients.client_name, + client_branch.branch_name as client_branch_name, insurers.name AS insurer_name, + insurer_branch.branch_name AS insurer_branch_name, policy_type.policy_type, policy_transaction.policy_no, policy_transaction.endorsement_no, - CASE - WHEN policy_transaction.action_type = 'inception' THEN 'I' - ELSE 'E' - END AS action_type, + pt_co_share_details.exp_amt, pt_co_share_details.variance, - insurer_statements.invoice_amount, - insurer_statements.invoice_status, - - ROUND((pt_co_share_details.actual_bp_brokerage_amt + pt_co_share_details.actual_tp_brokerage_amt + pt_co_share_details.actual_tep_brokerage_amt), 2) AS realization_amount2, + ROUND( ( SELECT - (SUM(inv_payment_details.inv_amt) + SUM(inv_payment_details.tds)) AS realization_amount + ( + 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) + ) AS total_irda_amt FROM - inv_payment_details + co_share_stmt_details + JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id WHERE - inv_payment_details.statement_id = insurer_statements.id - AND inv_payment_details.is_active = 1 - - ) AS realization_amount, + co_share_stmt_details.co_share_id = pt_co_share_details.id + AND co_share_stmt_details.is_active = 1 + ), + 2 + ) AS statement_amount, + + ROUND( + pt_co_share_details.exp_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) + ) + 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 + ), + 2 + ) AS variance_amt + ") ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id', 'left') - ->join('inv_payment_details', 'insurer_statements.id = inv_payment_details.statement_id', 'left') ->join('clients', 'clients.id = policy_transaction.client_id', 'left') + ->join('client_branch', 'client_branch.id = policy_transaction.client_branch_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('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') ->where('policy_transaction.is_active', 1) - ->where('pt_co_share_details.actual_bp_brokerage_amt IS NOT NULL AND pt_co_share_details.actual_bp_brokerage_amt != 0') - ->where('pt_co_share_details.variance IS NOT NULL') - ->where('pt_co_share_details.variance !=', 0); + ->where('pt_co_share_details.is_active', 1) + ->having('variance_amt IS NOT NULL'); + // ->where('pt_co_share_details.actual_bp_brokerage_amt IS NOT NULL AND pt_co_share_details.actual_bp_brokerage_amt != 0'); + // ->where('pt_co_share_details.variance IS NOT NULL') + // ->where('pt_co_share_details.variance !=', 0); if ($start_date != 0 && $end_date != 0 && $date_type != 0) { @@ -543,9 +820,18 @@ class PolicyTransactionModel extends Model $builder->where('policy_transaction.issuer', $issuer); } - if ($status != 0) { - $builder->where('policy_transaction.status', $status); + if ($client_branch_id != 0) { + $builder->where('policy_transaction.client_branch_id', $client_branch_id); } + + if ($insurer_branch_id != 0) { + $builder->where('policy_transaction.insurer_branch_id', $insurer_branch_id); + } + + if ($client_policy_id != 0) { + $builder->where('policy_transaction.client_policy_id', $client_policy_id); + } + $builder->orderBy('policy_transaction.id', 'desc'); @@ -694,7 +980,7 @@ class PolicyTransactionModel extends Model return $builder->get()->getResultArray(); } - public function getOutstandingReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) + public function getOutstandingReportList_OLD($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) { $builder = $this->db->table('policy_transaction') ->select(" @@ -791,5 +1077,53 @@ class PolicyTransactionModel extends Model return $builder->get()->getResultArray(); } + + public function getOutstandingReportList($start_date = 0, $end_date = 0, $insurer_id = 0,$insurer_branch_id = 0) + { + $builder = $this->db->table('insurer_statements s') + ->select(' + s.id, + s.insurer_id, + s.branch_id, + ins.short_name, + ib.branch_name, + s.month, + s.line_items, + s.stmt_sno, + s.invoice_status, + s.invoice_date, + s.invoice_no, + s.invoice_amount, + COALESCE(SUM(p.inv_amt) + SUM(p.tds) + SUM(p.gst), 0) AS total_paid, + (s.invoice_amount - COALESCE(SUM(p.inv_amt) + SUM(p.tds) + SUM(p.gst), 0)) AS outstanding_amount + ') + ->join('inv_payment_details p', 's.id = p.statement_id', 'left') + ->join('insurers ins', 's.insurer_id = ins.id') + ->join('insurer_branch ib', 's.branch_id = ib.id') + ->where('s.is_active', 1) + ->where('p.is_active', 1) + ->groupBy('s.id, s.invoice_no, s.invoice_date, s.invoice_amount') + ->having('outstanding_amount >', 0); + // ->get(); + + + // Date range filtering + if ($start_date != 0 && $end_date != 0) { + + $builder->where('s.month >=', $start_date) + ->where('s.month <=', $end_date); + } + + if ($insurer_id != 0) { + $builder->where('s.insurer_id', $insurer_id); + } + if ($insurer_branch_id != 0) { + $builder->where('s.branch_id', $insurer_branch_id); + } + + $builder->orderBy('s.id', 'desc'); + + return $builder->get()->getResultArray(); + } } diff --git a/app/Models/RFQModel.php b/app/Models/RFQModel.php index d616e517..2b1560e0 100644 --- a/app/Models/RFQModel.php +++ b/app/Models/RFQModel.php @@ -60,14 +60,13 @@ class RFQModel extends Model public function getRFQTableDataWithLeadIDAndType($lead_id, $type){ return $this->select(' - leads.client_name, - leads.client_short_name, + leads.*, insurers.name as insurer_name, insurer_branch.branch_name as insurer_branch_name, tpa.name as tpa_name, tpa_branch.branch_name as tpa_branch_name, policy_type.policy_type, - rfq.json + rfq.json, ') ->join('leads', 'rfq.lead_id = leads.id') ->join('policy_type', 'leads.policy_type_id = policy_type.id') @@ -76,7 +75,7 @@ class RFQModel extends Model ->join('tpa', 'leads.tpa_id = tpa.id', 'left') ->join('tpa_branch', 'leads.tpa_branch_id = tpa_branch.id', 'left') ->where('rfq.lead_id', $lead_id) - ->where('rfq.type', $type) + // ->where('rfq.type', $type) ->where('rfq.is_active', 1) ->first(); diff --git a/app/Views/UserList.php b/app/Views/UserList.php index 37ce4dd5..be654b8d 100755 --- a/app/Views/UserList.php +++ b/app/Views/UserList.php @@ -182,7 +182,9 @@ $(document).ready(function () { $('#tickets-table').DataTable({ - dom: "<'row'<'col-sm-0'f><'col-sm-9 text-right'B>>" , + dom: "<'row'<'col-sm-0'f><'col-sm-9 text-right'B>>" + // Keep your original alignment for the search and buttons + "<'row'<'col-sm-12'tr>>" + // Table rows + "<'row'<'col-sm-6'i><'col-sm-6'p>>", buttons: [ { extend: 'csv', diff --git a/app/Views/business_team_list.php b/app/Views/business_team_list.php index 33c99426..81977a54 100644 --- a/app/Views/business_team_list.php +++ b/app/Views/business_team_list.php @@ -16,6 +16,32 @@ table.dataTable tbody td { .dataTables_filter { position: absolute; } +.custom-dropdown-menu { + display: none; + position: absolute; + background-color: #ffffff !important; + border: 1px solid rgba(0, 0, 0, 0.15); + border-radius: 0.25rem; + padding: 0.5rem 0; + min-width: 10rem; + z-index: 9999; + box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); +} + +.custom-dropdown-menu .dropdown-item { + display: block !important; + width: 100% !important; + padding: 0.5rem 1rem !important; + color: #212529 !important; + text-decoration: none !important; + background-color: transparent !important; +} + +.custom-dropdown-menu .dropdown-item:hover { + background-color: #f8f9fa !important; + color: #16181b !important; + cursor: pointer !important; +}
@@ -209,6 +235,97 @@ table.dataTable tbody td {

+ + + \ No newline at end of file diff --git a/app/Views/client_deposit_list.php b/app/Views/client_deposit_list.php index 3df642a9..d19d0ec6 100755 --- a/app/Views/client_deposit_list.php +++ b/app/Views/client_deposit_list.php @@ -33,7 +33,7 @@ insurer_name;?> - cd_ac_no;?> + cd_master_account_no;?> ₹
@@ -114,6 +141,123 @@ table.dataTable thead th {
+ + + + + \ No newline at end of file diff --git a/app/Views/kyc_list.php b/app/Views/kyc_list.php index 19ec6370..a28b2dfe 100755 --- a/app/Views/kyc_list.php +++ b/app/Views/kyc_list.php @@ -1,3 +1,71 @@ +
@@ -42,7 +110,94 @@
+ + + \ No newline at end of file diff --git a/app/Views/policy_transaction_inception_list.php b/app/Views/policy_transaction_inception_list.php index d2c81ca9..80f9fe62 100644 --- a/app/Views/policy_transaction_inception_list.php +++ b/app/Views/policy_transaction_inception_list.php @@ -45,6 +45,73 @@ table.dataTable tbody td { .addbtnStyle{ margin-left: 20px !important; } +custom-dropdown-menu { + display: none; + position: fixed; + background-color: #ffffff !important; + border: 1px solid rgba(0,0,0,.15); + border-radius: 0.25rem; + padding: 0.5rem 0; + min-width: 10rem; + z-index: 9999; + box-shadow: 0 0 10px rgba(0,0,0,0.1); +} + +.custom-dropdown-menu .dropdown-item { + display: block !important; + width: 100% !important; + padding: 0.5rem 1rem !important; + clear: both !important; + font-weight: 400 !important; + color: #212529 !important; + text-align: inherit !important; + white-space: nowrap !important; + background-color: transparent !important; + border: 0 !important; + text-decoration: none !important; + position: relative !important; +} + +.custom-dropdown-menu .dropdown-item:hover { + background-color: #f8f9fa !important; + color: #16181b !important; + cursor: pointer !important; +} + +.custom-dropdown-menu .dropdown-item i { + margin-right: 8px !important; + vertical-align: middle !important; +} + +.table tbody tr { + cursor: pointer; +} + +/* Ensure the dropdown menu has a solid background */ +.custom-dropdown-menu::before { + content: ''; + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: #ffffff; + z-index: -1; +} + +/* Add a subtle backdrop effect */ +.custom-dropdown-menu::after { + content: ''; + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: rgba(0,0,0,0.05); + z-index: -2; + pointer-events: none; +} +
@@ -51,6 +119,90 @@
+ + + \ No newline at end of file diff --git a/app/Views/report_bds_filter.php b/app/Views/report_bds_filter.php index 769c3ffd..373ef985 100644 --- a/app/Views/report_bds_filter.php +++ b/app/Views/report_bds_filter.php @@ -22,31 +22,35 @@
- - $value) { - echo ""; - } - } - ?>
- - + + +
+ +
+ + +
+ +
+ +
-
+
+ + +
+
-
- -
-
-
+ @@ -130,11 +138,23 @@ \ No newline at end of file diff --git a/app/Views/report_bds_old.php b/app/Views/report_bds_old.php new file mode 100644 index 00000000..0caa9383 --- /dev/null +++ b/app/Views/report_bds_old.php @@ -0,0 +1,204 @@ + + +
+
+
+
+
+

BDS Report

+
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + $row){ ?> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
S. NoMonthBusiness TypeClient TypeInsured NamePolicy/
Endorsement
Policy TypeBAP GroupVehicle NumberPolicy NoEndorsement NoInsurer NameInsurer BranchTPAEndorsement
Effective Date
Policy
Effective Date
Policy
Expiry Date
ReferenceRemarksBase PremiumTerrorism/TPPremium
(without GST)
GST @ 18%Total PremiumBase
Revenue %
TP / Terrorism
Revenue %
Total IRDA
Revenue INR
GST on RevenueTotal Amount
Receivable
RewardsInvoice NumberInvoice DateInvoice AmountRealization AmountOutstanding AmountPayment StatusUTRPayment Date
 % % + +
+ +
+
+
+
+
+
+ + \ No newline at end of file diff --git a/app/Views/test_members_list.php b/app/Views/test_members_list.php new file mode 100644 index 00000000..385aeb37 --- /dev/null +++ b/app/Views/test_members_list.php @@ -0,0 +1,1120 @@ + + + + +
+
+
+
+
+
+

Employees

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + $employee) { ?> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SNOClient/BranchBranchNameEMP CodeRelationshipGenderDate of BirthExisting Policy Count Action
+ +
+
+
+
+
+ + + + + + + + + + + + diff --git a/app/Views/tpa_list.php b/app/Views/tpa_list.php index 83abeb08..3e08617a 100755 --- a/app/Views/tpa_list.php +++ b/app/Views/tpa_list.php @@ -1,3 +1,71 @@ +
@@ -42,6 +110,94 @@
+ \ No newline at end of file diff --git a/app/Views/vehicle_master_list.php b/app/Views/vehicle_master_list.php index 84f27a83..f28ef11f 100644 --- a/app/Views/vehicle_master_list.php +++ b/app/Views/vehicle_master_list.php @@ -21,6 +21,33 @@ table.dataTable tbody td { background-color: #f0f0f0; color: #666; } +.custom-dropdown-menu { + display: none; + position: absolute; + background-color: #ffffff !important; + border: 1px solid rgba(0, 0, 0, 0.15); + border-radius: 0.25rem; + padding: 0.5rem 0; + min-width: 10rem; + z-index: 9999; + box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); +} + +.custom-dropdown-menu .dropdown-item { + display: block !important; + width: 100% !important; + padding: 0.5rem 1rem !important; + color: #212529 !important; + text-decoration: none !important; + background-color: transparent !important; +} + +.custom-dropdown-menu .dropdown-item:hover { + background-color: #f8f9fa !important; + color: #16181b !important; + cursor: pointer !important; +} +
@@ -323,6 +350,98 @@ table.dataTable tbody td {
+ + @@ -4247,8 +5136,12 @@ function removeProposalForPremiumTable(secondRowIndex) { const formData = new FormData(); let lead_id = $('#lead_id').val(); + let submit_type = "RFQ" + if(RFQ_or_QCR == 2){submit_type = 'QCR'} + formData.append('json', JSON.stringify(jsonData)); formData.append('lead_id', lead_id); + formData.append('submit_type', submit_type); const postUrl = ''; console.log(postUrl); @@ -4365,12 +5258,14 @@ function removeProposalForPremiumTable(secondRowIndex) { async function tableToJsonForFormSubmit() { + // console.log('tableToJsonForFormSubmit function clled'); + return new Promise((resolve) => { const headers = []; const data = []; const table = document.getElementById('rfqTable'); - + let premium_data = ''; if(RFQ_or_QCR == 2){ premium_data = generateJSONFromTable(); @@ -4381,23 +5276,41 @@ function removeProposalForPremiumTable(secondRowIndex) { const parentHeaders = table.querySelectorAll('thead tr:nth-child(1) th'); const subHeaders = table.querySelectorAll('thead tr:nth-child(2) th'); + // console.log('parentHeaders length', parentHeaders.length); + // console.log('subHeaders length', subHeaders.length); + let headerIndex = 0; parentHeaders.forEach((header) => { // console.log('header names', header); // console.log('header header.innerText', header.innerText); - const colspan = header.getAttribute('colspan') || 1; + // const colspan = header.getAttribute('colspan') || 4; + + let colspan = 1; + + if (RFQ_or_QCR == 1) { + colspan = header.getAttribute('data-colspan') || 1; + } else { + colspan = header.getAttribute('colspan') || 1; + } + + + // console.log('colspan', colspan); const subHeaderArray = []; + // console.log('headerIndex', headerIndex); for (let i = 0; i < colspan; i++) { - const cleanedText = subHeaders[headerIndex].innerText.split('⋮')[0].trim(); + // console.log('headerIndex', headerIndex); + const cleanedText = subHeaders[headerIndex].textContent.trim().split('⋮')[0].trim(); + // console.log('cleanedText', cleanedText); + // console.log('headerIndex', headerIndex); subHeaderArray.push(cleanedText); headerIndex++; } headers.push({ - parentHeader: header.innerText.split('⋮')[0].trim(), + parentHeader: header.textContent.trim().split('⋮')[0].trim(), subHeaders: subHeaderArray }); }); @@ -4406,11 +5319,12 @@ function removeProposalForPremiumTable(secondRowIndex) { const rows = table.querySelectorAll('tbody tr'); rows.forEach(row => { + const rowId = row.id; const cells = row.querySelectorAll('td'); const rowData = { - SNO: cells[0].innerText, - items: cells[1].innerText, + SNO: cells[0].textContent.trim(), + items: cells[1].textContent.trim(), data: [] }; @@ -4418,13 +5332,17 @@ function removeProposalForPremiumTable(secondRowIndex) { headers.forEach(header => { header.subHeaders.forEach(subHeader => { const cell = cells[dataIndex]; - let content = cells[dataIndex]?.innerText || ''; + // console.log('cells', cell); + let content = cells[dataIndex]?.textContent.trim() || ''; // Ensure suggestions[rowId] exists const inputType = suggestions[rowId]?.type; + // console.log('inputType', inputType); + // Handle 'text' input types if (inputType === "text") { + if (header.parentHeader === 'Action' && cell) { const qcrInput = cell.querySelector( 'input[name="qcr"]'); @@ -4440,11 +5358,11 @@ function removeProposalForPremiumTable(secondRowIndex) { content = input.value; // console.log('hidden input value', content); } else { - content = cells[dataIndex].innerText; + content = cells[dataIndex].textContent.trim(); } } } else { - if (cell) { + // if (cell) { const input = cell.querySelector('input'); if (input && header.parentHeader === 'Action') { const qcrInput = cell.querySelector( @@ -4456,15 +5374,17 @@ function removeProposalForPremiumTable(secondRowIndex) { stc: clientInput?.checked ? 1 : 0 }; } else { - content = input ? input.value : cell.innerText; + content = input ? input.value : cell.textContent.trim(); } - } + // } } + + rowData.data.push({ parentth: header.parentHeader, subth: subHeader, - value: cells[dataIndex]?.innerText || '', + value: cells[dataIndex]?.textContent.trim() || '', input_value: content }); dataIndex++; @@ -4485,9 +5405,9 @@ function removeProposalForPremiumTable(secondRowIndex) { }; // Add `premium_data` only if `QCR` equals 2 - if (RFQ_or_QCR == 2) { - jsonData.premium_data = premium_data; - } + // if (RFQ_or_QCR == 2) { + jsonData.premium_data = premium_data; + // } localStorage.setItem('data', JSON.stringify(jsonData)); resolve(jsonData); @@ -4501,7 +5421,7 @@ function removeProposalForPremiumTable(secondRowIndex) { if (json) { const first_json = JSON.parse(JSON.stringify(json)); // Deep copy - console.log("Original JSON:", json); + // console.log("Original JSON:", json); let rowIndexArray = []; let rowIndexArray2 = []; @@ -4551,7 +5471,7 @@ function removeProposalForPremiumTable(secondRowIndex) { // console.log('insurer', insurer) if (insurer.qcr === 0 || insurer.qcr == false) { - console.log(insurer.qcr) + // console.log(insurer.qcr) first_json.table_data.headers.forEach(header => { const subHeaderIndex = header.subHeaders.findIndex(sub => sub === @@ -4574,7 +5494,116 @@ function removeProposalForPremiumTable(secondRowIndex) { // }); // Remove insurer from proposal's insurers array - console.log('insurerIndex', insurerIndex) + // console.log('insurerIndex', insurerIndex) + first_json.proposal_data.over_all_column_data[proposalKey].insurers.splice( + insurerIndex, 1); + } + + }); + }); + + // rowIndexArray.sort((a, b) => b - a); + + // rowIndexArray2.forEach((index) => { + // rowIndexArray.forEach((index2) => { + // first_json.table_data.data[index].data.splice(index2, 1); + // }) + // }); + + + // Row-wise Check: Remove rows if qcr == 0 for actions + Object.entries(first_json.table_data.data).forEach(([rowKey, rowData]) => { + const actionData = rowData.data.find(data => data.parentth === "Action" && data.input_value + .qcr === 0); + if (actionData) first_json.table_data.data.splice(rowKey, 1); + }); + + console.log("Modified JSON:", first_json); + return first_json; + } + + } + + + function convertRFQJsonToQCRJson(json) { + + if (json) { + + const first_json = JSON.parse(JSON.stringify(json)); // Deep copy + // console.log("Original JSON:", json); + + let rowIndexArray = []; + let rowIndexArray2 = []; + + // Column-wise Check: Remove headers and relevant data if qcr == 0 + Object.entries(json.proposal_data.over_all_column_data).forEach(([proposalKey, proposalData], index) => { + + // console.log('over_all_column_data index', index); + + if (proposalData.qcr == 0 || proposalData.qcr == false) { + + // Remove matching parentHeader in headers + const headerIndex = first_json.table_data.headers.findIndex(header => header + .parentHeader === proposalKey); + if (headerIndex !== -1) first_json.table_data.headers.splice(headerIndex, 1); + + first_json.table_data.data.forEach(item => { + item.data = item.data.filter(entry => entry.parentth !== proposalKey); + }); + + // Remove data entries with matching parentth + // Object.values(first_json.table_data.data).forEach(dataEntry => { + // const dataArray = dataEntry.data; + // if (dataArray) { + // const dataIndex = dataArray.findIndex(dataItem => dataItem.parentth === proposalKey); + // if (dataIndex !== -1) dataArray.splice(dataIndex, 1); + // } + // }); + + // Remove proposalKey from over_all_column_data + // Object.entries(first_json.proposal_data.over_all_column_data).splice(index, 1); + + + const updatedData = Object.keys(first_json.proposal_data.over_all_column_data) + .filter(key => key !== proposalKey) + .reduce((acc, key) => { + acc[key] = first_json.proposal_data.over_all_column_data[key]; + return acc; + }, {}); + + // Assign the updated data back if needed + first_json.proposal_data.over_all_column_data = updatedData; + } + + // Insurer Check: Remove subHeaders and relevant data for insurers with qcr == 0 + proposalData.insurers.forEach((insurer, insurerIndex) => { + // console.log('insurer', insurer) + if (insurer.qcr === 0 || insurer.qcr == false) { + + // console.log(insurer.qcr) + + first_json.table_data.headers.forEach(header => { + const subHeaderIndex = header.subHeaders.findIndex(sub => sub === + insurer.display_name); + if (subHeaderIndex !== -1) header.subHeaders.splice(subHeaderIndex, + 1); + }); + + first_json.table_data.data.forEach(item => { + item.data = item.data.filter(entry => entry.subth !== insurer + .display_name); + }); + + // Object.values(first_json.table_data.data).forEach(dataEntry => { + // const dataArray = dataEntry.data; + // if (dataArray) { + // const dataIndex = dataArray.findIndex(dataItem => dataItem.subth === insurer.display_name); + // if (dataIndex !== -1) dataArray.splice(dataIndex, 1); + // } + // }); + + // Remove insurer from proposal's insurers array + // console.log('insurerIndex', insurerIndex) first_json.proposal_data.over_all_column_data[proposalKey].insurers.splice( insurerIndex, 1); } diff --git a/composer.json b/composer.json index da1c83ff..c456241c 100755 --- a/composer.json +++ b/composer.json @@ -17,15 +17,15 @@ "dompdf/dompdf": "^2.0", "firebase/php-jwt": "^6.10", "google/apiclient": "^2.15.0", + "kreait/firebase-php": "^7.0", "laminas/laminas-escaper": "^2.9", "php-amqplib/php-amqplib": "^2.8", "phpmailer/phpmailer": "^6.9", "phpoffice/phpspreadsheet": "^2.1", + "psr/http-message": "^1.0", "psr/log": "^1.1", "slim/slim": "^4.13", - "zircote/swagger-php": "^4.8", - "psr/http-message": "^1.0", - "kreait/firebase-php":"^7.0" + "zircote/swagger-php": "^4.8" }, "require-dev": { "codeigniter/coding-standard": "^1.7", @@ -33,6 +33,7 @@ "friendsofphp/php-cs-fixer": "^3.47.1", "kint-php/kint": "^5.0.4", "mikey179/vfsstream": "^1.6", + "mockery/mockery": "^1.6", "nexusphp/cs-config": "^3.6", "phpunit/phpunit": "^9.1", "predis/predis": "^1.1 || ^2.0" diff --git a/public/sample_excel/enrollment.xlsx b/public/sample_excel/enrollment.xlsx index b23bb77d..0666a6c8 100755 Binary files a/public/sample_excel/enrollment.xlsx and b/public/sample_excel/enrollment.xlsx differ diff --git a/public/sample_excel/sample_deletion.xls b/public/sample_excel/sample_deletion.xls index 8146a3df..7bada1b5 100755 Binary files a/public/sample_excel/sample_deletion.xls and b/public/sample_excel/sample_deletion.xls differ diff --git a/public/sample_import_excel/sample_import_Addition.xlsx b/public/sample_import_excel/sample_import_Addition.xlsx index 19b1f86f..9c6b4752 100644 Binary files a/public/sample_import_excel/sample_import_Addition.xlsx and b/public/sample_import_excel/sample_import_Addition.xlsx differ diff --git a/public/sample_import_excel/sample_import_Dependent_Addition.xlsx b/public/sample_import_excel/sample_import_Dependent_Addition.xlsx index 19b1f86f..2343abdd 100644 Binary files a/public/sample_import_excel/sample_import_Dependent_Addition.xlsx and b/public/sample_import_excel/sample_import_Dependent_Addition.xlsx differ diff --git a/public/writable/uploads/lead_files/member_classification_2024-12-25_125459.xlsx b/public/writable/uploads/lead_files/member_classification_2024-12-25_125459.xlsx new file mode 100644 index 00000000..bd45a663 Binary files /dev/null and b/public/writable/uploads/lead_files/member_classification_2024-12-25_125459.xlsx differ diff --git a/tests/unit/ExcelMergeHelperTest.php b/tests/unit/ExcelMergeHelperTest.php new file mode 100755 index 00000000..f543d43a --- /dev/null +++ b/tests/unit/ExcelMergeHelperTest.php @@ -0,0 +1,38 @@ +WRITEPATH.'uploads/lead_files/Member_Data.xlsx','sheets' => []], + + ['file_path' =>WRITEPATH.'/tmp/RFQ_ABC_GMC_20241220140640.xlsx','sheets' => []], + + // ['file_path' =>'/home/venba/Downloads/Employee_data.xlsx','sheets' => []], + ]; + $outputPath = '/home/venba/Documents/merged_file.xlsx'; // Output path for the merged file + + // Call the mergeExcelFiles function + $result = ExcelMergeHelper::mergeExcelFiles($filePaths, $outputPath); + echo('result is -> '.$result); + // Check if the result is true (indicating success) + $this->assertFileExists($result); + $this->assertTrue(filesize($result) > 0); + } + +} +// $temp_file_path = WRITEPATH.'tmp/RFQ_ABC_GMC_20241219172307.xlsx'; +// $temp_file_name = 'RFQ_ABC_GMC_20241219172307.xlsx'; +// $lead_file_path = WRITEPATH.'uploads/lead_files/Member_Data.xlsx'; + +// $filePaths = [ +// ['file_path' => $temp_file_path,'sheets' =>[]], +// ['file_path' =>$lead_file_path ,'sheets' =>[]] +// ]; +// $outputPath = dirname($temp_file_path).'/'.$temp_file_name.'_merged'; diff --git a/tests/unit/LeadsControllerTest.php b/tests/unit/LeadsControllerTest.php new file mode 100644 index 00000000..7b8a3518 --- /dev/null +++ b/tests/unit/LeadsControllerTest.php @@ -0,0 +1,183 @@ +leadsController = new LeadsController(); + } + + public function testGetDemographyDataBasicScenario() + { + echo('passed 0'); + // Arrange + $members = [ + // Header row + ['Name', 'Age', 'Relationship', 'SI Enhancement'], + // Data rows + ['John', '25', 'Self', '100000'], + ['Jane', '23', 'Spouse', '100000'], + ['Kid', '5', 'Child', '50000'] + ]; + echo('passed 1'); + $age_band_data = [ + ['0-17', '18-35', '36-45', 'Above 46'] + ]; + echo('passed 2'); + $members_heading = ['Name', 'Age', 'Relationship', 'SI Enhancement']; + $available_col = 'age';print_rr($available_col); + $col_index = 1; + echo('passed 3'); + try{ + echo('Inside try'); + // Act + echo('passed 3.5'); + $result = $this->leadsController->getDemographyData($members,$age_band_data,$members_heading,$available_col,$col_index); + + echo('passed 4'); + } catch (Exception $e) { + echo "Message: " . $e->getMessage() . "\n"; + echo "File: " . $e->getFile() . "\n"; + echo "Line: " . $e->getLine() . "\n"; + // Optionally, print the full stack trace + echo "Stack trace: " . $e->getTraceAsString() . "\n"; + } + var_dump($result); + // Assert + $this->assertIsArray($result); + $this->assertArrayHasKey('general', $result); + $this->assertArrayHasKey('100000', $result); + $this->assertArrayHasKey('50000', $result); + + // Check counts for general category + $this->assertEquals(1, $result['general']['Self']['18-35']); + $this->assertEquals(1, $result['general']['Spouse']['18-35']); + $this->assertEquals(1, $result['general']['Child']['0-17']); + } + + public function testGetDemographyDataWithDOB() + { + // Arrange + $members = [ + // Header row + ['Name', 'DOB', 'Relationship', 'SI Enhancement'], + // Data rows + ['John', '01-Jan-1995', 'Self', '100000'], + ['Jane', '01-Jan-1998', 'Spouse', '100000'] + ]; + + $age_band_data = [ + ['18-35', '36-45', '46+'] + ]; + + $members_heading = ['Name', 'DOB', 'Relationship', 'SI Enhancement']; + $available_col = 'dob'; + $col_index = 1; + + // Act + $result = $this->leadsController->getDemographyData( + $members, + $age_band_data, + $members_heading, + $available_col, + $col_index + ); + + // Assert + $this->assertIsArray($result); + $this->assertArrayHasKey('general', $result); + $this->assertArrayHasKey('100000', $result); + + // Both members should be in 18-35 age band + $this->assertEquals(1, $result['general']['Self']['18-35']); + $this->assertEquals(1, $result['general']['Spouse']['18-35']); + } + + public function testGetDemographyDataWithEmptyMembers() + { + // Arrange + $members = [ + // Only header row + ['Name', 'Age', 'Relationship', 'SI Enhancement'] + ]; + + $age_band_data = [ + ['0-17', '18-35', '36-45', '46+'] + ]; + + $members_heading = ['Name', 'Age', 'Relationship', 'SI Enhancement']; + $available_col = 'age'; + $col_index = 1; + + // Act + $result = $this->leadsController->getDemographyData( + $members, + $age_band_data, + $members_heading, + $available_col, + $col_index + ); + + // Assert + $this->assertIsArray($result); + $this->assertArrayHasKey('general', $result); + + // Check that all totals are zero + $this->assertEquals(0, $result['general']['Grand Total']['Grand Total']); + } + + public function testGetDemographyDataWithMultipleSIBands() + { + // Arrange + $members = [ + // Header row + ['Name', 'Age', 'Relationship', 'SI Enhancement'], + // Data rows with different SI amounts + ['John', '25', 'Self', '100000'], + ['Jane', '23', 'Spouse', '200000'], + ['Kid1', '5', 'Child', '100000'], + ['Kid2', '7', 'Child', '200000'] + ]; + + $age_band_data = [ + ['0-17', '18-35', '36-45', '46+'] + ]; + + $members_heading = ['Name', 'Age', 'Relationship', 'SI Enhancement']; + $available_col = 'age'; + $col_index = 1; + + // Act + $result = $this->leadsController->getDemographyData( + $members, + $age_band_data, + $members_heading, + $available_col, + $col_index + ); + + // Assert + $this->assertIsArray($result); + $this->assertArrayHasKey('100000', $result); + $this->assertArrayHasKey('200000', $result); + + // Check counts for different SI bands + $this->assertEquals(1, $result['100000']['Self']['18-35']); + $this->assertEquals(1, $result['200000']['Spouse']['18-35']); + $this->assertEquals(1, $result['100000']['Child']['0-17']); + $this->assertEquals(1, $result['200000']['Child']['0-17']); + + // Check general category totals + $this->assertEquals(2, $result['general']['Child']['0-17']); + $this->assertEquals(2, $result['general']['Child']['Grand Total']); + } +} \ No newline at end of file