diff --git a/app/Config/Database.php b/app/Config/Database.php
index b0c2a6e3..dcc1c2dd 100755
--- a/app/Config/Database.php
+++ b/app/Config/Database.php
@@ -20,7 +20,8 @@ class Database extends Config
* use if no other is specified.
*/
public string $defaultGroup = 'default';
-
+ public string $enableSSL;
+
/**
* The default database connection.
*/
@@ -37,7 +38,7 @@ class Database extends Config
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
- 'encrypt' => false,
+ 'encrypt' =>false,
'compress' => false,
'strictOn' => false,
'failover' => [],
@@ -122,6 +123,18 @@ class Database extends Config
if (ENVIRONMENT === 'testing') {
$this->defaultGroup = 'tests';
}
+
+ $this->enableSSL = env('DB_SSL_ENABLE') ?? false;
+
+ if ($this->enableSSL === true || $this->enableSSL === 'true' || $this->enableSSL === 1 || $this->enableSSL === '1') {
+
+
+ // Enable SSL authentication
+ $this->default['encrypt'] = [
+ 'ssl_ca' => ROOTPATH . 'ca.pem',
+ 'ssl_verify' => true,
+ ];
+ }
}
}
diff --git a/app/Config/Feature.php b/app/Config/Feature.php
index 0bc45c6f..af762917 100755
--- a/app/Config/Feature.php
+++ b/app/Config/Feature.php
@@ -21,7 +21,7 @@ class Feature extends BaseConfig
* - property $filtersInfo, instead of $filterInfo
* - CodeIgniter\Router\RouteCollection::getFiltersForRoute(), instead of getFilterForRoute()
*/
- public bool $multipleFilters = false;
+ public bool $multipleFilters = true;
/**
* Use improved new auto routing instead of the default legacy version.
diff --git a/app/Config/Filters.php b/app/Config/Filters.php
index 029d2706..2128f042 100755
--- a/app/Config/Filters.php
+++ b/app/Config/Filters.php
@@ -14,6 +14,7 @@ use App\Filters\HttpRequestLog;
use App\Filters\CloseDbConnection;
use App\Filters\AuthClientApi;
use App\Filters\CommissionApiFilter;
+use App\Filters\VerifyAppSignature;
use App\Filters\Cors;
use App\Filters\AuthJWT;
@@ -38,9 +39,10 @@ class Filters extends BaseConfig
'HttpRequestLog' => HttpRequestLog::class,
'authJWT' => AuthJWT::class,
'AuthClientApi' => AuthClientApi::class,
- 'CloseDbConnection' => CloseDbConnection::class,
- 'CommissionApiFilter' => CommissionApiFilter::class,
- 'Cors' => Cors::class
+ 'CloseDbConnection' => CloseDbConnection::class,
+ 'CommissionApiFilter'=> CommissionApiFilter::class,
+ 'appSignature' => VerifyAppSignature::class,
+ 'Cors' => Cors::class,
];
/**
diff --git a/app/Config/Routes.php b/app/Config/Routes.php
index 96252c3f..5aea3a1f 100755
--- a/app/Config/Routes.php
+++ b/app/Config/Routes.php
@@ -32,6 +32,8 @@ $routes->get("update-policy-terms-for-corrections", "ClientController::updatePol
$routes->get("update_rack_rate_json", "ClientController::updateRackRateJson");
$routes->get("updatajson", "EmpDataServiceController::updatajson");
$routes->get("view", "EmployeeController::viewECard/$1");
+$routes->get("checkWellnessOnboardStatus/(:any)", "EmployeeController::checkWellnessOnboardStatus/$1");
+$routes->get("initiateWellnessOnboard/(:any)", "EmployeeController::initiateWellnessOnboard/$1");
$routes->get("exportQCRandRFQ/(:any)", "LeadsController::exportQCRandRFQ/$1");
$routes->get("smapletest", "ClientController::smapletest");
$routes->get("testMailAttachments", "ClientController::testMailAttachments");
@@ -50,10 +52,11 @@ $routes->get("importRules", "RuleImportController::upload");
// $routes->post("employeeUpload", "EmployeeRestController::employeeUpload");
$routes->post("add_advertise_image", "AppContentManagementController::add_advertise_image");
+$routes->post('remove_advertise_image', 'AppContentManagementController::remove_advertise_image');
$routes->get("add_image_index", "AppContentManagementController::add_image_index");
$routes->get("getAdvertiseImage/(:any)", "AppContentManagementController::getAdvertiseImage/$1");
$routes->get("frontend_content", "AppContentManagementController::frontend_content");
-$routes->get('showAdvertiseImage/(:any)', 'AdvertiseController::showAdvertiseImage/$1');
+$routes->get('showAdvertiseImage/(:any)', 'AppContentManagementController::showAdvertiseImage/$1');
// $routes->get('/', 'LoginController::index');
@@ -162,6 +165,11 @@ $routes->group("/client", ["filter" => "authMVC"], function ($routes) {
$routes->post("edit", "ClientController::editClientKYCInfo");
$routes->get("list/(:any)", "ClientController::getKycDocsById/$1");
$routes->get("delete/(:any)", "ClientController::deleteClientKycDocs/$1");
+
+ $routes->post("create_2", "ClientController::createClientKYCInfo_2");
+ $routes->post("edit_2", "ClientController::editClientKYCInfo_2");
+ $routes->post("delete_2", "ClientController::deleteClientKycDocs_2/$1");
+
});
$routes->group("premimum", ["filter" => "authMVC"], function ($routes) {
@@ -432,6 +440,8 @@ $routes->group("policy_tranction", ["filter" => "authMVC"], function ($routes) {
$routes->get("list/(:any)", "PolicyTransactionController::getInceptionDataForEdit/$1");
$routes->get("remove/(:any)", "PolicyTransactionController::removeCDMaster/$1");
$routes->get("removePolicyTransaction/(:any)", "PolicyTransactionController::removePolicyTransaction/$1");
+ $routes->match(['get', 'post'], 'list2', 'PolicyTransactionController::viewInception2');
+ $routes->get("list2/(:any)", "PolicyTransactionController::getInceptionDataForEdit2/$1");
});
$routes->group("endorsement", ["filter" => "authMVC"], function ($routes) {
@@ -439,6 +449,8 @@ $routes->group("policy_tranction", ["filter" => "authMVC"], function ($routes) {
$routes->post("create", "PolicyTransactionController::createEndorsementPolicy");
$routes->get("list/(:any)", "PolicyTransactionController::getEndorsementDataForEdit/$1");
$routes->get("remove/(:any)", "PolicyTransactionController::removeCDMaster/$1");
+ $routes->get("list2", "PolicyTransactionController::viewEndorsement2");
+ $routes->get("list2/(:any)", "PolicyTransactionController::getEndorsementDataForEdit2/$1");
});
$routes->group("report", ["filter" => "authMVC"], function ($routes) {
@@ -512,34 +524,7 @@ $routes->cli('cli/insurerRFQRemainder', 'LeadsController::remainderForQcr');
$routes->cli('cli/sendMailWithAutoQuery','TicketController::sendMailWithAutoQuery');
-//Employee login api's
-$routes->post("/employeeRest/verifyEmployeeNumber", "RestAuthenticationController::verifyEmployeeWithMobileNumber");
-$routes->post("/employeeRest/getVerifiedUserData", "RestAuthenticationController::getVerifiedUserData");
-$routes->post("/employeeRest/verifyEmployeeEmailId", "RestAuthenticationController::verifyEmployeeWithEmailId");
-$routes->post("/employeeRest/updateEmpOTP", "RestAuthenticationController::updateEmpOTP");
-// MPIN api's
-$routes->post("employeeRest/saveMpin", "RestAuthenticationController::saveMpin");
-$routes->post("employeeRest/updateMpin", "RestAuthenticationController::updateMpin");
-$routes->post("/employeeRest/verifyMpin", "RestAuthenticationController::verifyMpin");
-$routes->post("/employeeRest/checkMpin", "RestAuthenticationController::checkMpin");
-$routes->post("/employeeRest/updateEmpMPIN", "RestAuthenticationController::updateEmpMPIN");
-$routes->post("employeeRest/forgotMPIN", "RestAuthenticationController::forgotMPIN");
-$routes->post("employeeRest/updateMobileNumber", "RestAuthenticationController::updateMobileNumber");
-
-// PASSWORD api's
-$routes->post("employeeRest/savePassword", "RestAuthenticationController::savePassword");
-$routes->post("employeeRest/changePassword", "RestAuthenticationController::changePassword");
-$routes->post("employeeRest/verifyPassword", "RestAuthenticationController::verifyPassword");
-$routes->post("employeeRest/verifyOtp", "RestAuthenticationController::verifyOtp");
-$routes->post("employeeRest/checkPassword", "RestAuthenticationController::checkPassword");
-
-//HR login api's
-$routes->post("/employeeRest/verifyHrWithMobileNumber", "RestAuthenticationController::verifyHrWithMobileNumber");
-$routes->post("/employeeRest/verifyHrWithEmail", "RestAuthenticationController::verifyHrWithEmail");
-$routes->post("/employeeRest/getVerifiedHrData", "RestAuthenticationController::getVerifiedHrData");
-$routes->post("/employeeRest/updateHROTP", "RestAuthenticationController::updateHROTP");
-$routes->get("/employeeRest/getHRAccessData", "RestAuthenticationController::getHRAccessData");
// Test initiate Claim
$routes->post('initiateClaim',"EmployeeRestController::initiateClaim");
@@ -554,58 +539,90 @@ $routes->group("/api", ["filter" => "authJWT"], function ($routes) {
$routes->post("getId", "RestAuthenticationController::getUserIdFromToken");
});
-$routes->post("employeeRest/getPostEmployeeDataForAuth", "RestAuthenticationController::getPostEmployeeDataForAuth");
-// $routes->post("logHrActivity", "RestAuthenticationController::logHrActivity");
-$routes->get("employeeRest/getClientDetails", "EmployeeRestController::getClientDetails");
-$routes->get("employeeRest/getAdvertisementImage", "EmployeeRestController::getAdvertisementImage");
$routes->get("getSSORedirectUrl", "ApiServiceController::getSSORedirectUrl");
+$routes->get("getEmployeePolicy", "EmployeeRestController::getEmployeePolicy");
-$routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) {
+$routes->group("employeeRest", ['filter' => ["appSignature"] ], function ($routes) {
+
+ //Employee login api's
+ $routes->post("verifyEmployeeNumber", "RestAuthenticationController::verifyEmployeeWithMobileNumber");
+ $routes->post("getVerifiedUserData", "RestAuthenticationController::getVerifiedUserData");
+ $routes->post("verifyEmployeeEmailId", "RestAuthenticationController::verifyEmployeeWithEmailId");
+ $routes->post("updateEmpOTP", "RestAuthenticationController::updateEmpOTP");
+
+ // MPIN api's
+ $routes->post("saveMpin", "RestAuthenticationController::saveMpin");
+ $routes->post("updateMpin", "RestAuthenticationController::updateMpin");
+ $routes->post("verifyMpin", "RestAuthenticationController::verifyMpin");
+ $routes->post("checkMpin", "RestAuthenticationController::checkMpin");
+ $routes->post("updateEmpMPIN", "RestAuthenticationController::updateEmpMPIN");
+ $routes->post("forgotMPIN", "RestAuthenticationController::forgotMPIN");
+ $routes->post("updateMobileNumber", "RestAuthenticationController::updateMobileNumber");
+
+ // PASSWORD api's
+ $routes->post("savePassword", "RestAuthenticationController::savePassword");
+ $routes->post("changePassword", "RestAuthenticationController::changePassword");
+ $routes->post("verifyPassword", "RestAuthenticationController::verifyPassword");
+ $routes->post("verifyOtp", "RestAuthenticationController::verifyOtp");
+ $routes->post("checkPassword", "RestAuthenticationController::checkPassword");
+
+ //HR login api's
+ $routes->post("verifyHrWithMobileNumber", "RestAuthenticationController::verifyHrWithMobileNumber");
+ $routes->post("verifyHrWithEmail", "RestAuthenticationController::verifyHrWithEmail");
+ $routes->post("getVerifiedHrData", "RestAuthenticationController::getVerifiedHrData");
+ $routes->post("updateHROTP", "RestAuthenticationController::updateHROTP");
+ $routes->get("getHRAccessData", "RestAuthenticationController::getHRAccessData");
+
+ $routes->post("getPostEmployeeDataForAuth", "RestAuthenticationController::getPostEmployeeDataForAuth");
+ $routes->post("getRetailUserData", "RestAuthenticationController::getRetailUserData");
+
+ $routes->get("getClientDetails", "EmployeeRestController::getClientDetails");
+ $routes->get("getAdvertisementImage", "EmployeeRestController::getAdvertisementImage");
+
+ //retail user apis
+ $routes->post("getVerifiedRetailUserData", "RestAuthenticationController::getVerifiedRetailUserData");
+ $routes->post("updateRetailUserAuthDetails", "RestAuthenticationController::updateRetailUserAuthDetails");
+
+});
+
+$routes->group("employeeRest", ["filter" => ["authJWT"]], function ($routes) {
$routes->post("ecardRequest", "ApiServiceController::ecardRequest");
-
$routes->get("getWellnessURL", "ApiServiceController::getWellnessURL");
+
$routes->post("logHrActivity", "RestAuthenticationController::logHrActivity");
- $routes->post("getVerifiedUserData", "RestAuthenticationController::getVerifiedUserData");
+ // $routes->post("getVerifiedUserData", "RestAuthenticationController::getVerifiedUserData");
+
+
+ $routes->post("getChatResponse", "ChatBotController::getChatResponse");
+
$routes->post("storeFireBase", "EmployeeRestController::storeFireBase");
- // $routes->post("updateMpin", "RestAuthenticationController::updateMpin");
- $routes->post("getChatResponse", "ChatBotController::getChatResponse");
$routes->get("getEmployeeProfile", "EmployeeRestController::getEmployeeProfile");
-
$routes->post("employeeUpload", "EmployeeRestController::employeeUpload");
-
$routes->get("relationshipList", "EmployeeRestController::relationshipList");
-
$routes->get("getEmployeeAndDependence", "EmployeeRestController::getEmployeeAndDependence");
$routes->post("editEmployeeAndDependence", "EmployeeRestController::editEmployeeAndDependence");
$routes->post("addEmployeeAndDependence", "EmployeeRestController::addEmployeeAndDependence");
-
$routes->get("getEmployeePolicy", "EmployeeRestController::getEmployeePolicy");
$routes->post("createOrUpdateEmployeePolicySiAmount", "EmployeeRestController::createOrUpdateEmployeePolicySiAmount");
$routes->get("deleteDependence", "EmployeeRestController::deleteDependence");
$routes->get("getEmployeeAndDependenceByClientId", "EmployeeRestController::getEmployeeAndDependenceByClientId");
$routes->get("getClientPolicy", "EmployeeRestController::getClientPolicy");
-
$routes->get("getAddOnPolicy", "EmployeeRestController::getAddOnPolicy");
$routes->post("iAgreeForAddOn", "EmployeeRestController::iAgreeForAddOn");
-
$routes->get("exportDataByClientPolicyId", "EmployeeRestController::exportDataByClientPolicyId");
-
$routes->get("removeEmpAndEmpPolicyData", "EmployeeRestController::removeEmpAndEmpPolicyData");
-
$routes->post("calculatePremium", "EmployeeRestController::calculatePremium");
-
$routes->get("getEmployeeOldPolicy", "EmployeeRestController::getEmployeeOldPolicy");
$routes->get("getEmployeeActiveOrInactivePolicy", "EmployeeRestController::getEmployeeActiveOrInactivePolicy");
$routes->get("getFEContent", "EmployeeRestController::getFEContent");
$routes->get("getAdvertisementImage", "EmployeeRestController::getAdvertisementImage");
-
$routes->get("getEcardURL", "EmployeeRestController::getEcardURL");
- //$routes->post('postDataForTicket',"EmployeeRestController::postDataForTicket");
+
//hr api's
@@ -615,6 +632,11 @@ $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) {
$routes->match( ['get', 'post'], 'claimsSearch','EmployeeRestController::claimsSearch');
$routes->get("claimView", "EmployeeRestController::claimView");
$routes->get("exportCashDepositData", "EmployeeRestController::exportCashDepositData");
+ $routes->get("hrFileList", "EmployeeRestController::hrFileList");
+ $routes->get("hrFileUploadMasters", "EmployeeRestController::hrFileUploadMasters");
+ $routes->get("hrFileDownload", "EmployeeRestController::hrFileDownload");
+ $routes->post("hrFileUpload", "EmployeeRestController::hrFileUpload");
+ $routes->post("updateHrFileUploadData", "EmployeeRestController::updateHrFileUploadData");
//thz_master's
@@ -625,19 +647,23 @@ $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) {
$routes->get("ticketHistoryList", "ThzController::ticketHistoryList");
$routes->match(['get','post','put'], 'ticketType', 'ThzController::ticketType');
- $routes->get("hrFileList", "EmployeeRestController::hrFileList");
- $routes->get("hrFileUploadMasters", "EmployeeRestController::hrFileUploadMasters");
- $routes->get("hrFileDownload", "EmployeeRestController::hrFileDownload");
- $routes->post("hrFileUpload", "EmployeeRestController::hrFileUpload");
- $routes->post("updateHrFileUploadData", "EmployeeRestController::updateHrFileUploadData");
+
//claims
$routes->post('initiateClaim',"EmployeeRestController::initiateClaim");
$routes->get('get_ticket_type',"EmployeeRestController::get_ticket_type");
$routes->get('get_ticket_data',"EmployeeRestController::get_ticket_data");
+ $routes->get('getClaimTypeMaster',"EmployeeRestController::getClaimTypeMaster");
+ $routes->post('uploadIRDocs',"EmployeeRestController::uploadIRDocs");
+ // add retail policy
+ $routes->post("addEmpRetailPolicy", "EmployeeRestController::addEmpRetailPolicy");
+
+ // get insurer and policy type
+ $routes->get("getPolicyTypeAndInsurer", "EmployeeRestController::getPolicyTypeAndInsurer");
});
+
$routes->get("hrFileDownload", "EmployeeRestController::hrFileDownload");
$routes->post("hrFileList", "EmployeeRestController::hrFileList");
$routes->get("getEmployeeActiveOrInactivePolicy", "EmployeeRestController::getEmployeeActiveOrInactivePolicy");
@@ -646,8 +672,10 @@ $routes->post("sendEmail", "EmployeeRestController::send_email");
$routes->get("getPolicyLevelEmployeeSummaryData", "EmployeeRestController::getPolicyLevelEmployeeSummaryData");
$routes->get("cdTransactionData", "EmployeeRestController::cdTransactionData");
$routes->match( ['get', 'post'], 'claimsSearch','EmployeeRestController::claimsSearch');
-
$routes->get("getBackToEnrolledDetails", "EmployeeRestController::getBackToEnrolledDetails");
+// $routes->post("addEmpRetailPolicy", "EmployeeRestController::addEmpRetailPolicy");
+// $routes->get("getPolicyTypeAndInsurer", "EmployeeRestController::getPolicyTypeAndInsurer");
+
// Ticketing System
@@ -687,7 +715,8 @@ $routes->group("/ticket", ["filter" => "authMVC"], function ($routes) {
$routes->post('getUrlDataByTicketId',"TicketController::getUrlDataByTicketId");
$routes->get('remove_url',"TicketController::remove_url");
$routes->get('fetchVehiclePolicy/(:any)','TicketController::fetchVehiclePolicy/$1');
-
+ $routes->post('saveIRDocsJson',"TicketController::saveIRDocsJson");
+ $routes->get('getTpaClaimStatus',"ApiServiceController::getClaimStatus");
});
$routes->group("clientApi",["filter" => "AuthClientApi"], function ($routes){
@@ -806,3 +835,20 @@ $routes->group('commission', function($routes) {
$routes->get('checkRuleUsage',"RuleImportController::checkRuleUsage");
});
+//BDS BULK UPLOAD
+$routes->group('bds_upload', function($routes) {
+ $routes->match (['get','post'],'list',"PolicyTransactionController::policyBulkUpload");
+ $routes->get('downloadBDSDumpFile/(:any)',"PolicyTransactionController::downloadBDSDumpFile/$1");
+ $routes->get('getBdsDumpFileErrorData',"PolicyTransactionController::getBdsDumpFileErrorData");
+ $routes->get('getBdsDumpExcelFileErrors/(:any)',"PolicyTransactionController::getBdsDumpExcelFileErrors/$1");
+});
+
+
+// -----------------------------------------------------------------------------------------------------------------
+$routes->group('logs', function($routes) {
+ $routes->get('/', 'LogController::index');
+ $routes->get('view/(:segment)', 'LogController::view/$1');
+ $routes->get('download/(:segment)', 'LogController::download/$1');
+ $routes->get('delete/(:segment)', 'LogController::delete/$1');
+ $routes->get('clearAll', 'LogController::clearAll');
+});
diff --git a/app/Controllers/ApiServiceController.php b/app/Controllers/ApiServiceController.php
index ac6cb0dd..b22a1470 100644
--- a/app/Controllers/ApiServiceController.php
+++ b/app/Controllers/ApiServiceController.php
@@ -45,9 +45,14 @@ class ApiServiceController extends BaseController
$tpaID = $data['tpa_id'];
- if ($tpaID == $this->medi_assist_primary_key) { // MediAssist
+ if ($tpaID == $this->medi_assist_primary_key)
+ { // MediAssist
$mediAssistController = new MediAssistApiController();
return $mediAssistController->SubmitClaim($claimId);
+ }else if ($tpaID == $this->vidal_primary_key)
+ { // Vidal
+ $vidalApiController = new VidalApiController;
+ return $vidalApiController->SubmitClaim($claimId);
}else{
log_message('error', "This ticket id ( {$claimId} ) TPA has no API service enabled. TPA ID : {$tpaID}");
}
@@ -219,75 +224,117 @@ class ApiServiceController extends BaseController
}
}
-
- public function getWellnessUrl()
+ // get Claim details
+ public function getClaimStatus()
{
- $emp_id = $this->request->getGet('emp_id');
- $client_policy_id = $this->request->getGet('client_policy_id');
-
- $db = \Config\Database::connect();
-
- // $data = $db->table('employees e')
- // ->select('pt.policy_type,
- // e.name, e.email_corporate as email, e.mobile as phone, e.emp_code as memberId, e.gender, e.dob, e.relationship as relation,
- // cp.policy_no as policyNumber, cp.policy_no as employeeId, cp.policy_start_date as policyStartDate, cp.policy_end_date as policyEndDate')
- // ->join('employee_polices ep', 'e.id = ep.employee_id')
- // ->join('client_policy cp', 'ep.client_policy_id = cp.id')
- // ->join('policy_type pt', 'cp.policy_type_id = pt.id')
- // ->where('e.id', $emp_id)
- // ->where('e.emp_status', 'active')
- // ->where('ep.status', 'active')
- // ->where('e.is_active', 1)
- // ->where('ep.is_active', 1)
- // ->get()
- // ->getResultArray();
-
- $data = $db->table('employee_polices ep')
- ->select('pt.policy_type,
- e.name, e.email_corporate as email, e.mobile as phone, e.emp_code as memberId, e.gender, e.dob, e.relationship as relation, e.id as employeeId
- cp.policy_no as policyNumber, cp.policy_start_date as policyStartDate, cp.policy_end_date as policyEndDate, cp.wellness_plan_id as planId')
- ->join('employees e', 'e.id = ep.employee_id')
- ->join('client_policy cp', 'ep.client_policy_id = cp.id')
- ->join('policy_type pt', 'cp.policy_type_id = pt.id')
- ->where('ep.employee_id', $emp_id)
- ->where('ep.client_policy_id', $client_policy_id)
- ->where('ep.status', 'active')
- ->where('ep.is_active', 1)
- ->get()
- ->getRow();
-
+ $claimId = $this->request->getGet('claim_id');
-
- $userParams = [];
- if(!empty($data))
- {
- $userParams['name'] = $data->name;
- $userParams['email'] = $data->email;
- $userParams['phone'] = $data->phone;
- $userParams['memberId'] = $data->employeeId; // memberId is unique primary key.
- $userParams['gender'] = $data->gender;
- $userParams['dob'] = $data->dob;
- $userParams['relation'] = $data->relation;
- $userParams['policyNumber'] = $data->policyNumber;
- $userParams['employeeId'] = $data->memberId;
- $userParams['policyStartDate']= $data->policyStartDate;
- $userParams['policyEndDate'] = $data->policyEndDate;
- $userParams['policyName'] = 'Nhance ' . $data->policy_type;
- $userParams['planId'] = $data->planId;
- $userParams['moduleName'] = 'home';
+ $data = $this->db->table('ticket_master tm')
+ ->select('tm.id,tm.tpa_id ')->where('tm.id', $claimId)->get()->getRowArray(); // single record
+
+ if($data){
+
+ $tpaID = $data['tpa_id'];
+
+ if ($tpaID == $this->medi_assist_primary_key) { // MediAssist
+ $mediAssistController = new MediAssistApiController();
+ return $mediAssistController->ClaimDetail($claimId);
+ }else{
+ log_message('error', "This ticket id ( {$claimId} ) TPA has no API service enabled. TPA ID : {$tpaID}");
+ $message = "This TPA has no API service enabled";
+ return $this->response->setJSON(['status' => false,'message' => $message ]);
+ }
}
-
- // dd($userParams);
+
+ }
+
+ // push Claim Files (IR submission)
+ public function pushClaimFiles($claimId)
+ {
+
+ // $claimId = $this->request->getGet('claim_id');
+
+ $data = $this->db->table('ticket_master tm')
+ ->select('tm.id,tm.tpa_id ')->where('tm.id', $claimId)->get()->getRowArray(); // single record
+
+ if($data){
+
+ $tpaID = $data['tpa_id'];
+
+ if ($tpaID == $this->medi_assist_primary_key) { // MediAssist
+ $mediAssistController = new MediAssistApiController();
+ return $mediAssistController->IRSubmission($claimId);
+ }else{
+ log_message('error', "This ticket id ( {$claimId} ) TPA has no API service enabled. TPA ID : {$tpaID}");
+ }
+
+ }
+
+
+ }
+
+ //wellness sso url generator landing
+ public function getWellnessUrl($emp_id)
+ {
+ // $emp_id = $this->request->getGet('emp_id');
+
+ $db = \Config\Database::connect();
+ $data = $db->table('employees e')
+ ->select('pt.policy_type,
+ e.name, e.email_corporate as email, e.mobile as phone, e.emp_code as memberId, e.gender, e.dob, e.relationship as relation,
+ cp.policy_no as policyNumber, ep.employee_id as employeeId, cp.policy_start_date as policyStartDate, cp.policy_end_date as policyEndDate , cp.wellness_plan_id as planId , cp.wellness_vendor_id')
+ ->join('employee_polices ep', 'e.id = ep.employee_id')
+ ->join('client_policy cp', 'ep.client_policy_id = cp.id')
+ ->join('policy_type pt', 'cp.policy_type_id = pt.id')
+ ->where('e.id', $emp_id)
+ ->where('e.emp_status', 'active')
+ ->where('ep.status', 'active')
+ ->where('e.is_active', 1)
+ ->where('ep.is_active', 1)
+ ->get()
+ ->getResultArray();
+
+
+ $userParams = [];
+ foreach ($data as $row) {
+
+ if($row['wellness_vendor_id'] != null)
+ {
+ $vidalApiController = new VidalApiController();
+ return $vidalApiController->getWellnessSSORedirectUrl($row['email']);
+
+ }
+ else if ($row['planId'] != null) // VISIT
+ {
+ $userParams['name'] = $row['name'];
+ $userParams['email'] = $row['email'];
+ $userParams['phone'] = $row['phone'];
+ $userParams['memberId'] = $row['employeeId']; // memberId is unique primary key.
+ $userParams['gender'] = $row['gender'];
+ $userParams['dob'] = $row['dob'];
+ $userParams['relation'] = $row['relation'];
+ $userParams['policyNumber'] = $row['policyNumber'];
+ $userParams['employeeId'] = $row['memberId'];
+ $userParams['policyStartDate']= $row['policyStartDate'];
+ $userParams['policyEndDate'] = $row['policyEndDate'];
+ $userParams['policyName'] = $row['policy_type'];
+ $userParams['planId'] = $row['planId'];
+ $userParams['moduleName'] = 'home';
+ break; // stop after first GMC match
+ }
+ }
+
if (empty($userParams)) {
- return $this->respond(['status' => 'failed','message' => 'Coming soon........!'], 200);
+ return ['status' => 'failed','message' => 'Coming soon........!'];
}
-
+
+ // echo 'coming';die();
// Derive 32-byte key from SHA256
$derivedKey = hash('sha256', env('VISIT_SECRET_KEY'), true);
-
+
// Build query string like Node.js
$plainText = '';
foreach ($userParams as $k => $v) {
@@ -301,96 +348,190 @@ class ApiServiceController extends BaseController
// Base64URL encode (same as Node.js output)
$output = rtrim(strtr(base64_encode($encrypted), '+/', '-_'), '=');
-
+
$baseURL = env('VISIT_BASE_URL');
$clientId = env('VISIT_CLIENT_ID');
$finalUrl = $baseURL . '/sso?userParams=' . $output . '&clientId=' . $clientId;
if (!empty($finalUrl)) {
log_message('error', 'VISIT SSO | emp_id: '.$emp_id.' | URL: '.$finalUrl);
- return $this->respond(['status' => 'success','data' => $finalUrl], 200);
+ return ['status' => 'success','data' => $finalUrl];
} else {
- return $this->respond(['status' => 'failed','message' => 'Coming soon........!'], 200);
+ return ['status' => 'failed','message' => 'Coming soon........!'];
}
}
+ // public function getWellnessUrl()
+ // {
- function getSSORedirectUrl($email = 'user@example.com')
- {
- // ---------- CONFIG ----------
- $authUrl = env('VIDAL_WELLNESS_BASE_URL'); // Authentication API URL
- $subscriptionKey = env('VIDAL_WELLNESS_SUBSCRIPTION_KEY');
- $apiVersion = "1";
+ // $emp_id = $this->request->getGet('emp_id');
+ // $client_policy_id = $this->request->getGet('client_policy_id');
- // Provided Base64 AES key
- $base64Key = env('VIDAL_WELLNESS_BASE64_KEY');
- $key = base64_decode($base64Key);
+ // $db = \Config\Database::connect();
- // ---------- STEP 1: Build plaintext payload ----------
- $plainPayload = json_encode([
- "email" => $email,
- "corporateId" => env('VIDAL_WELLNESS_CORPORATE_ID'),
- "urlIdentifier" => env('VIDAL_WELLNESS_URL_IDENTIFIER')
- ]);
+ // // $data = $db->table('employees e')
+ // // ->select('pt.policy_type,
+ // // e.name, e.email_corporate as email, e.mobile as phone, e.emp_code as memberId, e.gender, e.dob, e.relationship as relation,
+ // // cp.policy_no as policyNumber, cp.policy_no as employeeId, cp.policy_start_date as policyStartDate, cp.policy_end_date as policyEndDate')
+ // // ->join('employee_polices ep', 'e.id = ep.employee_id')
+ // // ->join('client_policy cp', 'ep.client_policy_id = cp.id')
+ // // ->join('policy_type pt', 'cp.policy_type_id = pt.id')
+ // // ->where('e.id', $emp_id)
+ // // ->where('e.emp_status', 'active')
+ // // ->where('ep.status', 'active')
+ // // ->where('e.is_active', 1)
+ // // ->where('ep.is_active', 1)
+ // // ->get()
+ // // ->getResultArray();
- // ---------- STEP 2: Encrypt payload ----------
- $iv = random_bytes(16);
- $encryptedRaw = openssl_encrypt($plainPayload, "AES-256-CBC", $key, OPENSSL_RAW_DATA, $iv);
+ // $data = $db->table('employee_polices ep')
+ // ->select('pt.policy_type,
+ // e.name, e.email_corporate as email, e.mobile as phone, e.emp_code as memberId, e.gender, e.dob, e.relationship as relation, e.id as employeeId
+ // cp.policy_no as policyNumber, cp.policy_start_date as policyStartDate, cp.policy_end_date as policyEndDate, cp.wellness_plan_id as planId')
+ // ->join('employees e', 'e.id = ep.employee_id')
+ // ->join('client_policy cp', 'ep.client_policy_id = cp.id')
+ // ->join('policy_type pt', 'cp.policy_type_id = pt.id')
+ // ->where('ep.employee_id', $emp_id)
+ // ->where('ep.client_policy_id', $client_policy_id)
+ // ->where('ep.status', 'active')
+ // ->where('ep.is_active', 1)
+ // ->get()
+ // ->getRow();
- $encryptedPayload = base64_encode($iv) . ":" . base64_encode($encryptedRaw);
+
+
+ // $userParams = [];
+ // if(!empty($data))
+ // {
+ // $userParams['name'] = $data->name;
+ // $userParams['email'] = $data->email;
+ // $userParams['phone'] = $data->phone;
+ // $userParams['memberId'] = $data->employeeId; // memberId is unique primary key.
+ // $userParams['gender'] = $data->gender;
+ // $userParams['dob'] = $data->dob;
+ // $userParams['relation'] = $data->relation;
+ // $userParams['policyNumber'] = $data->policyNumber;
+ // $userParams['employeeId'] = $data->memberId;
+ // $userParams['policyStartDate']= $data->policyStartDate;
+ // $userParams['policyEndDate'] = $data->policyEndDate;
+ // $userParams['policyName'] = 'Nhance ' . $data->policy_type;
+ // $userParams['planId'] = $data->planId;
+ // $userParams['moduleName'] = 'home';
- // ---------- STEP 3: Call Authentication API ----------
- $requestBody = json_encode([
- "payload" => $encryptedPayload,
- "source" => "portal",
- "subPartnerId" => env('VIDAL_WELLNESS_SUB_PARTNER_ID')
- ]);
+ // }
+
+ // // dd($userParams);
- $headers = [
- "Ocp-Apim-Subscription-Key: $subscriptionKey",
- "apiver: $apiVersion",
- "mode: encrypt",
- "Content-Type: application/json"
- ];
+ // if (empty($userParams)) {
+ // return $this->respond(['status' => 'failed','message' => 'Coming soon........!'], 200);
+ // }
- $ch = curl_init($authUrl);
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ // // Derive 32-byte key from SHA256
+ // $derivedKey = hash('sha256', env('VISIT_SECRET_KEY'), true);
- $apiResponse = curl_exec($ch);
- curl_close($ch);
+ // // Build query string like Node.js
+ // $plainText = '';
+ // foreach ($userParams as $k => $v) {
+ // $plainText .= "&{$k}={$v}";
+ // }
+ // $plainText = ltrim($plainText, '&');
+
+ // // Encrypt
+ // $algorithm = "aes-256-cbc";
+ // $encrypted = openssl_encrypt($plainText, $algorithm, $derivedKey, OPENSSL_RAW_DATA, env('VISIT_IV'));
+
+ // // Base64URL encode (same as Node.js output)
+ // $output = rtrim(strtr(base64_encode($encrypted), '+/', '-_'), '=');
- $jsonResponse = json_decode($apiResponse, true);
+ // $baseURL = env('VISIT_BASE_URL');
+ // $clientId = env('VISIT_CLIENT_ID');
+ // $finalUrl = $baseURL . '/sso?userParams=' . $output . '&clientId=' . $clientId;
+
+ // if (!empty($finalUrl)) {
+ // log_message('error', 'VISIT SSO | emp_id: '.$emp_id.' | URL: '.$finalUrl);
+ // return $this->respond(['status' => 'success','data' => $finalUrl], 200);
+ // } else {
+ // return $this->respond(['status' => 'failed','message' => 'Coming soon........!'], 200);
+ // }
+ // }
- dd($jsonResponse);
- if (!isset($jsonResponse["data"])) {
- return ["error" => "Invalid API response", "response" => $apiResponse];
- }
+ // function getSSORedirectUrl($email = 'user@example.com')
+ // {
+ // // ---------- CONFIG ----------
+ // $authUrl = env('VIDAL_WELLNESS_BASE_URL'); // Authentication API URL
+ // $subscriptionKey = env('VIDAL_WELLNESS_SUBSCRIPTION_KEY');
+ // $apiVersion = "1";
+
+ // // Provided Base64 AES key
+ // $base64Key = env('VIDAL_WELLNESS_BASE64_KEY');
+ // $key = base64_decode($base64Key);
+
+ // // ---------- STEP 1: Build plaintext payload ----------
+ // $plainPayload = json_encode([
+ // "email" => $email,
+ // "corporateId" => env('VIDAL_WELLNESS_CORPORATE_ID'),
+ // "urlIdentifier" => env('VIDAL_WELLNESS_URL_IDENTIFIER')
+ // ]);
+
+ // // ---------- STEP 2: Encrypt payload ----------
+ // $iv = random_bytes(16);
+ // $encryptedRaw = openssl_encrypt($plainPayload, "AES-256-CBC", $key, OPENSSL_RAW_DATA, $iv);
+
+ // $encryptedPayload = base64_encode($iv) . ":" . base64_encode($encryptedRaw);
+
+ // // ---------- STEP 3: Call Authentication API ----------
+ // $requestBody = json_encode([
+ // "payload" => $encryptedPayload,
+ // "source" => "portal",
+ // "subPartnerId" => env('VIDAL_WELLNESS_SUB_PARTNER_ID')
+ // ]);
+
+ // $headers = [
+ // "Ocp-Apim-Subscription-Key: $subscriptionKey",
+ // "apiver: $apiVersion",
+ // "mode: encrypt",
+ // "Content-Type: application/json"
+ // ];
+
+ // $ch = curl_init($authUrl);
+ // curl_setopt($ch, CURLOPT_POST, true);
+ // curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
+ // curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
+ // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+
+ // $apiResponse = curl_exec($ch);
+ // curl_close($ch);
+
+ // $jsonResponse = json_decode($apiResponse, true);
+
+ // dd($jsonResponse);
+
+ // if (!isset($jsonResponse["data"])) {
+ // return ["error" => "Invalid API response", "response" => $apiResponse];
+ // }
- // ---------- STEP 4: Decrypt response ----------
- list($ivBase64, $cipherBase64) = explode(":", $jsonResponse["data"]);
+ // // ---------- STEP 4: Decrypt response ----------
+ // list($ivBase64, $cipherBase64) = explode(":", $jsonResponse["data"]);
- $respIv = base64_decode($ivBase64);
- $respCipher = base64_decode($cipherBase64);
+ // $respIv = base64_decode($ivBase64);
+ // $respCipher = base64_decode($cipherBase64);
- $decryptedJson = openssl_decrypt($respCipher, "AES-256-CBC", $key, OPENSSL_RAW_DATA, $respIv);
+ // $decryptedJson = openssl_decrypt($respCipher, "AES-256-CBC", $key, OPENSSL_RAW_DATA, $respIv);
- $decryptedData = json_decode($decryptedJson, true);
+ // $decryptedData = json_decode($decryptedJson, true);
- if (!isset($decryptedData["redirectUrl"])) {
- return ["error" => "redirectUrl missing", "decrypted" => $decryptedData];
- }
+ // if (!isset($decryptedData["redirectUrl"])) {
+ // return ["error" => "redirectUrl missing", "decrypted" => $decryptedData];
+ // }
- // ---------- FINAL ----------
- return $decryptedData["redirectUrl"];
- }
+ // // ---------- FINAL ----------
+ // return $decryptedData["redirectUrl"];
+ // }
diff --git a/app/Controllers/AppContentManagementController.php b/app/Controllers/AppContentManagementController.php
index f9e1d356..da65a7b1 100755
--- a/app/Controllers/AppContentManagementController.php
+++ b/app/Controllers/AppContentManagementController.php
@@ -10,6 +10,7 @@ use CodeIgniter\API\ResponseTrait;
use App\Models\AddImgModel;
use App\Models\FEContentModel;
+use App\Models\ClientModel;
class AppContentManagementController extends AdminController
{
@@ -17,19 +18,31 @@ class AppContentManagementController extends AdminController
protected $myLogger;
protected $addImgModel;
protected $feContentModel;
+ protected $clientModel;
+
public function __construct()
{
$this->myLogger = \Config\Services::mylogger();
- $this->addImgModel = new AddImgModel();
+ $this->addImgModel = new AddImgModel();
$this->feContentModel = new FEContentModel();
+ $this->clientModel = new ClientModel();
}
+ //listing
public function add_image_index()
{
- $this->myLogger->logme('error','Addvertisement Image list function called');
- $headerData['tab_name'] = 'Addvertisement Images';
- $headerData['page_name'] = 'Addvertisement Images';
- $data['addImageList'] = $this->addImgModel->findAll();
+ $headerData['tab_name'] = 'Advertisement Images';
+ $headerData['page_name'] = 'Advertisement Images';
+ // $data['addImageList'] = $this->addImgModel->findAll();
+ $data['addImageList'] = $this->addImgModel->select('advertisement_images.*,
+ clients.client_name,
+ clients.short_name,
+ CASE WHEN advertisement_images.is_active = 1 THEN "Active" ELSE "Inactive" END AS status', false)
+ ->join('clients', 'advertisement_images.client_id = clients.id', 'left')
+ ->where('advertisement_images.is_active', 1)
+ ->findAll();
+
+ $data['client'] = $this->clientModel->where('is_active', 1)->where('client_type', 1)->findAll();
// dd($data);
@@ -40,12 +53,14 @@ class AppContentManagementController extends AdminController
// $this->loadLayout('client_onboarding', $data);
}
+ // add and edit
public function add_advertise_image() {
try {
$file = $this->request->getFile('advertise_image');
+ $client_id = $this->request->getPost('client_id');
//1) original file name for vaildations
$fileName = $file->getClientName(); //original file name for vaildations
- $existing = $this->addImgModel->where('name', $fileName)->where('is_active', 1)->first();
+ $existing = $this->addImgModel->where('name', $fileName)->where('client_id', $fileName)->where('is_active', 1)->first();
if($existing){ return $this->respond(['status' => false, 'message' => 'This file has already been uploaded in active state.'], 400); }
//skip 1) and use this
@@ -55,14 +70,15 @@ class AppContentManagementController extends AdminController
return $this->respond(['status' => false, 'message' => 'No file uploaded or invalid file.'], 400);
}
- $uploadPath = WRITEPATH . 'uploads/advertiseImage/';
+ // $uploadPath = WRITEPATH . 'uploads/advertiseImage/';
+ $uploadPath = ROOTPATH . 'public/uploads/add_image_upload/';
if (!is_dir($uploadPath)) mkdir($uploadPath, 0755, true);
$file->move($uploadPath, $fileName);
$id = $this->request->getPost('add_image_id');
- $data = ['name' => $fileName];
+ $data = ['name' => $fileName,'client_id'=>$client_id];
if ($id == 0) {
$this->addImgModel->insert($data);
@@ -76,32 +92,55 @@ class AppContentManagementController extends AdminController
}
}
- public function showAdvertiseImage($fileName)
+ // soft delete
+ public function remove_advertise_image()
{
+ try {
+ $id = $this->request->getPost('add_image_id');
- $filePath = WRITEPATH . 'uploads/advertiseImage/' . $fileName;
+ if (!$id) {
+ return $this->respond(['status' => false, 'message' => 'ID missing'], 400);
+ }
- if (!file_exists($filePath)) {
- return $this->response->setStatusCode(404, 'File not found');
+ $data = ['is_active' => 0];
+ $this->addImgModel->update($id, $data);
+
+ return $this->respond(['status' => true, 'message' => 'Deleted successfully']);
+
+ } catch (\Exception $e) {
+ return $this->respond(['status' => false, 'message' => $e->getMessage()], 500);
+ }
+ }
+
+
+ // Preview image Went Edit.
+ public function showAdvertiseImage($filename)
+ {
+ // $path = WRITEPATH . 'uploads/advertiseImage/' . $filename;
+ $path = ROOTPATH . 'public/uploads/add_image_upload/' . $filename;
+
+ if (!file_exists($path)) {
+ throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
+ // return $this->response->setStatusCode(404, 'File not found');
}
- $mimeType = mime_content_type($filePath);
- header('Content-Type: ' . $mimeType);
- readfile($filePath);
- exit;
+ $mime = mime_content_type($path);
+ // header('Content-Type: ' . $mimeType);
+ // readfile($path);
+ // exit;
+ return $this->response->setHeader('Content-Type', $mime)->setBody(file_get_contents($path));
}
- public function getAdvertiseImage($image_id){
- $image_data = $this->addImgModel->select('name')->where(['id' => $image_id])->first();
-
- if($image_data){
- return $image_data['name'];
- }else{
- return ;
- }
- }
+ // public function getAdvertiseImage($image_id){
+ // $image_data = $this->addImgModel->select('name')->where(['id' => $image_id])->first();
+ // if($image_data){
+ // return $image_data['name'];
+ // }else{
+ // return ;
+ // }
+ // }
diff --git a/app/Controllers/BDSReportController.php b/app/Controllers/BDSReportController.php
index d0dd5ac9..abc1ac14 100644
--- a/app/Controllers/BDSReportController.php
+++ b/app/Controllers/BDSReportController.php
@@ -15,6 +15,7 @@ use App\Models\PolicyTransactionModel;
use App\Models\PTCOShareDetailsModel;
use App\Models\COShareStmtDetailsModel;
use App\Models\PolicyTypeModel;
+use App\Models\NhanceBranchModel;
use CodeIgniter\API\ResponseTrait;
@@ -34,6 +35,7 @@ class BDSReportController extends AdminController
protected $coShareStmtDetailsModel;
protected $policyTypeModel;
protected $policyTatReportType;
+ protected $nhanceBranchModel;
public function __construct()
{
@@ -47,6 +49,7 @@ class BDSReportController extends AdminController
$this->PTCOShareDetailsModel = new PTCOShareDetailsModel();
$this->coShareStmtDetailsModel = new COShareStmtDetailsModel();
$this->policyTypeModel = new PolicyTypeModel();
+ $this->nhanceBranchModel = new NhanceBranchModel();
$this->policyTatReportType = [
@@ -925,7 +928,8 @@ class BDSReportController extends AdminController
$default_start = new \DateTime();
$data['default_end'] = $default_start->format('d-m-Y');
$data['default_start'] = $default_start->modify('-60 days')->format('d-m-Y');
- $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
+ $data['issuer_branch'] = $this->nhanceBranchModel->where('is_active', 1)->findAll();
+ $data['client_list'] = $this->clientModel->where('is_active', 1)->findAll();
$data['tab_name'] = "Renewal Reports";
$data['page_name'] = "Renewal Report";
return $this->loadLayout('renewal_search', $data);
@@ -935,11 +939,11 @@ class BDSReportController extends AdminController
$toDate = $this->request->getPost('toDate');
$client_id = $this->request->getPost('client_id');
$client_type = $this->request->getPost('client_type');
- $issuer = $this->request->getPost('issuer');
+ $issuer_branch = $this->request->getPost('issuer_branch');
- $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
+ $data['issuer_branch'] = $this->nhanceBranchModel->where('is_active', 1)->findAll();
$data['client_type'] = [1 => 'Group', 2 => 'Individual'];
- $data['renewal_data'] = $this->policyTransactionModel->getRenewalReportData($fromDate, $toDate, $client_type, $client_id, $issuer);
+ $data['renewal_data'] = $this->policyTransactionModel->getRenewalReportData($fromDate, $toDate, $client_type, $client_id, $issuer_branch);
// print_r($data); die;
$view_name = "bds_renewal_report_list";
$html = view('bds_renewal_report_list', $data);
diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php
index fcf5c373..e42266d2 100755
--- a/app/Controllers/ClientController.php
+++ b/app/Controllers/ClientController.php
@@ -1005,6 +1005,153 @@ class ClientController extends AdminController
+ public function createClientKYCInfo_2()
+ {
+ $this->myLogger->logme('error', 'create Client kyc function called');
+ $data = $this->request->getPost();
+
+ $uploadedFile = $this->request->getFile('file_name');
+
+ if ($uploadedFile && $uploadedFile->isValid() && !$uploadedFile->hasMoved()) {
+ $this->myLogger->logme('info', 'File is valid and ready to move.');
+ } else {
+ $this->myLogger->logme('error', 'File failed validation or was not uploaded.');
+ }
+
+ $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';
+
+ $File = file_Upload($uploadedFile, $uploadFilePath);
+ $this->myLogger->logme('info', 'Result of file_Upload: ' . $File);
+ unset($data['file_name']);
+
+ if (!empty($File)) { $data['file_name'] = $File; }
+
+ $data['created_by'] = get_session_userid();
+ $insert = $this->clientKYCDocsModel->insert($data);
+
+ if ($insert) {
+ $html = $this->generateKycSingleTable($data['client_id']);
+ $dropdown = $this->fetch_dropdown($data['client_id']);
+ return $this->respond(['status' => true, 'code' => 200, 'file_name' => $File, 'html' => $html,'dropdown'=>$dropdown], 200);
+ } else {
+ $this->myLogger->logme('error', 'Database insert failed.');
+ return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to add document'], 200);
+ }
+ }
+
+ public function editClientKYCInfo_2()
+ {
+
+ $kyc_id = $this->request->getPost('id');
+ $client_id = $this->request->getPost('client_id');
+ $old_file_name = $this->request->getPost('old_file_name');
+ $uploadedFile = $this->request->getFile('file_name');
+ $new_file_name = null;
+ $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';
+
+
+ if ($uploadedFile && $uploadedFile->isValid() && !$uploadedFile->hasMoved()) {
+
+
+ $new_file_name = file_Upload($uploadedFile, $uploadFilePath);
+
+ if (!empty($new_file_name)) {
+
+ $updateData['file_name'] = $new_file_name;
+
+ // Delete the old file from the storage if it exists
+ // if (!empty($old_file_name)) {
+ // $old_file_path = $uploadFilePath . '/' . $old_file_name;
+ // if (file_exists($old_file_path)) {
+ // unlink($old_file_path);
+ // // Optionally delete from G-Drive here if applicable
+ // }
+ // }
+ } else {
+ // New file upload failed
+ return $this->respond(['status' => false, 'code' => 500, 'message' => 'New file upload failed on server.'], 200);
+ }
+ }
+
+ // 2. Perform the database update
+ if (!empty($updateData)) {
+
+ $updateData['updated_by'] = get_session_userid();
+ $update = $this->clientKYCDocsModel->update($kyc_id, $updateData);
+ $html = $this->generateKycSingleTable($client_id);
+ $dropdown = $this->fetch_dropdown($client_id);
+
+ if ($update) {
+ return $this->respond(['status' => true, 'code' => 200, 'message' => 'Document updated successfully.','html' => $html,'dropdown' => $dropdown], 200);
+ }
+ } else {
+
+ return $this->respond(['status' => true, 'code' => 200, 'message' => 'No changes detected. Document remains the same.'], 200);
+ }
+
+
+ return $this->respond(['status' => false, 'code' => 404, 'message' => 'Database update failed or record not found.'], 200);
+ }
+
+
+ public function deleteClientKycDocs_2()
+ {
+
+ $kyc_id = $this->request->getPost('id');
+ $client_id = $this->request->getPost('client_id');
+
+ if (empty($kyc_id)) {
+ return $this->respond(['status' => false, 'code' => 400, 'message' => 'Missing document ID.'], 200);
+ }
+ $updateData['updated_by'] = get_session_userid();
+ $updateData['is_active'] = $this->request->getPost('is_active');
+
+ $delete = $this->clientKYCDocsModel->update($kyc_id, $updateData);
+
+ if ($delete) {
+ $html = $this->generateKycSingleTable($client_id);
+ $dropdown = $this->fetch_dropdown($client_id);
+ return $this->respond(['status' => true, 'code' => 200, 'id' => $kyc_id, 'message' => 'Document successfully deactivated.','html' => $html,'dropdown' => $dropdown], 200);
+ } else {
+ return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to update record (ID not found or DB error).'], 200);
+ }
+ }
+
+ public function fetch_dropdown($client_id){
+
+ $db = db_connect();
+
+
+ $submitted_ids_subquery = $db->table('client_kyc_documents ckd')
+ ->select('ckd.kyc_doc_type_id')
+ ->where('ckd.client_id', $client_id)
+ ->where('ckd.is_active', 1)
+ ->getCompiledSelect();
+
+
+ $result = $db->table('kyc_docs kd')
+ ->select('kd.*')
+ ->join('clients c', 'kd.kyc_type_id = c.entity_type_id')
+ ->where('c.id', $client_id)
+ ->where("kd.kyc_type_id NOT IN ({$submitted_ids_subquery})")
+ ->groupBy('kd.id')
+ ->get()
+ ->getResultArray();
+
+
+ $dropdown = '';
+ $dropdown .= '';
+
+ foreach ($result as $row) {
+ $dropdown .= '';
+ }
+
+ return $dropdown;
+ }
+
+
public function createClientRelation()
{
@@ -2361,6 +2508,36 @@ class ClientController extends AdminController
}
+
+ public function generateKycSingleTable($client_id)
+ {
+
+
+ $result['ckdlist'] = db_connect()->table('client_kyc_documents ckd')
+ ->select("ckd.id,ckd.client_id,ckd.kyc_doc_type_id,ckd.file_name,kd.file_name AS kd_docs_name,ckd.other_docs_name,ckd.vehicle_id,ckd.is_active,
+ CASE
+ WHEN ckd.kyc_doc_type_id IS NULL
+ OR ckd.kyc_doc_type_id = 0
+ OR ckd.kyc_doc_type_id = ''
+ THEN ckd.other_docs_name
+ ELSE kd.file_name
+ END AS ui_docs_name")
+ ->join('kyc_docs kd','ckd.kyc_doc_type_id = kd.kyc_type_id','left')
+ ->where('ckd.client_id',$client_id)
+ ->where('ckd.is_active',1)
+ ->groupBy('ckd.id')
+ ->get()
+ ->getResultArray();
+
+
+ $result['client_id'] = $client_id;
+ $table = view('client_kyc_single_table', $result);
+
+ return $table;
+ // print_r($table); die;
+
+ }
+
public function getPolicesByInsurerId($id = null)
{
$this->myLogger->logme('error', 'getPolicesByInsurerId function called');
@@ -4655,8 +4832,9 @@ class ClientController extends AdminController
$client_data = [
'client_type' => $postData['client_type'],
'client_name' => $postData['client_name'],
- 'email' => $postData['short_name'] ?? $postData['client_name'],
- 'phone' => $postData['mobile'],
+ 'short_name' => $postData['short_name'] ?? $postData['client_name'],
+ 'email' => $postData['email'] ?? null,
+ 'phone' => $postData['mobile'] ?? null,
'client_code' => generate_client_code()
];
@@ -4667,6 +4845,8 @@ class ClientController extends AdminController
'client_type' => $postData['client_type'],
'client_name' => $postData['client_name'],
'short_name' => $postData['short_name'] ?? $postData['client_name'],
+ 'email' => $postData['email'] ?? null,
+ 'phone' => $postData['mobile'] ?? null,
'client_code' => generate_client_code(),
'entity_type_id' => 2
];
@@ -4781,8 +4961,9 @@ class ClientController extends AdminController
$client_data = [
'client_type' => $data['client_type'],
'client_name' => $data['client_name'],
- 'email' => $data['short_name'] ?? $data['client_name'],
- 'phone' => $data['mobile'],
+ 'short_name' => $postData['short_name'] ?? $data['client_name'],
+ 'email' => $data['email'] ?? null,
+ 'phone' => $data['mobile'] ?? null,
'client_code' => generate_client_code()
];
@@ -4793,6 +4974,8 @@ class ClientController extends AdminController
'client_type' => $data['client_type'],
'client_name' => $data['client_name'],
'short_name' => $data['short_name'] ?? $data['client_name'],
+ 'email' => $data['email'] ?? null,
+ 'phone' => $data['mobile'] ?? null,
'client_code' => generate_client_code(),
'entity_type_id' => 2
];
@@ -5065,25 +5248,60 @@ class ClientController extends AdminController
public function get_client_policy_data_using_policy_no()
{
- $received_data = $this->request->getGet();
- $policy_no = $this->request->getGet('policy_no');
- $client_id = $this->request->getGet('client_id');
- $client_branch_id = $this->request->getGet('client_branch_id');
- $policy_type_id = $this->request->getGet('policy_type_id');
- $client_type = $this->request->getGet('client_type');
+ $received_data = $this->request->getGet();
+ $policy_no = trim($this->request->getGet('policy_no'));
+ $client_id = $this->request->getGet('client_id') ?? null;
+ $client_branch_id = $this->request->getGet('client_branch_id') ?? null;
+ $policy_type_id = $this->request->getGet('policy_type_id') ?? null;
+ $client_type = $this->request->getGet('client_type') ?? null;
- $data = $this->policyTransactionModel
+ // Check in Policy Transaction (BDS)
+ $bds_count = $this->policyTransactionModel
->where('is_active', 1)
->where('action_type', 'inception')
- ->where('policy_no', $policy_no)
+ ->where('TRIM(policy_no)', $policy_no)
+ ->where('policy_no IS NOT NULL AND policy_no <> ""')
->countAllResults();
- $client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('policy_status', 1)->where('policy_no', trim($policy_no))->first();
+ // Check in Enrollment (client_policy)
+ $client_policy_data = $this->clientPolicyModel
+ ->where('is_active', 1)
+ ->where('policy_status', 1)
+ ->where('TRIM(policy_no)', $policy_no)
+ ->first();
+
+ // Decide message + count
+ if ($bds_count > 0) {
+
+ return $this->respond([
+ 'status' => true,
+ 'message' => "This policy number is already linked to another policy in the BDS",
+ 'code' => 409,
+ 'data' => $bds_count,
+ 'received_data' => $received_data,
+ 'client_policy_id' => $client_policy_data['id'] ?? null
+ ], 200);
+
+ } elseif (!empty($client_policy_data)) {
+
+ return $this->respond([
+ 'status' => true,
+ 'message' => "This policy number is already linked to another policy in the Enrollment",
+ 'code' => 409,
+ 'data' => 1,
+ 'received_data' => $received_data,
+ 'client_policy_id' => $client_policy_data['id']
+ ], 200);
- if ($data > 0) {
- return $this->respond(['status' => true, 'message' => 'This policy number is already linked to another client', 'data' => $data, 'code' => 409, 'received_data' => $received_data, 'client_policy_id' => $client_policy_data['id'] ?? null], 200);
} else {
- return $this->respond(['status' => false, 'message' => 'No Data Found', 'code' => 404, 'received_data' => $received_data, 'client_policy_id' => $client_policy_data['id'] ?? null], 200);
+
+ return $this->respond([
+ 'status' => false,
+ 'message' => 'No Data Found',
+ 'code' => 404,
+ 'received_data' => $received_data,
+ 'client_policy_id' => null
+ ], 200);
}
}
@@ -5678,10 +5896,11 @@ class ClientController extends AdminController
// $response = $ticketServiceController->extractExcelData("claims_dump_form_client.xlsx");
// dd($response);
- // ---------- TICKET SERVICE CONTROLLER --------------------------------------------------------------------------------
+ // ---------- TICKET CONTROLLER --------------------------------------------------------------------------------
$TicketController = new TicketController();
// $response = $TicketController->getMoreInfo($requestFrom = 'rest', $ticket_id = 70);
+ // $response = $TicketController->sendAutoMailTrigger($ticket_id = 602);
// dd($response);
// ---------- EMP SERVICE CONTROLLER --------------------------------------------------------------------------------
diff --git a/app/Controllers/DeployController.php b/app/Controllers/DeployController.php
index de73092a..c763d9a3 100644
--- a/app/Controllers/DeployController.php
+++ b/app/Controllers/DeployController.php
@@ -176,7 +176,7 @@ class DeployController extends AdminController
public function fedeploy()
{
$request = $this->request;
-
+ echo 'HI';die();
// Single zip file:
$file = $request->getFile('zip_file');
@@ -186,7 +186,7 @@ class DeployController extends AdminController
'message' => 'No valid zip file uploaded',
]);
}
-
+ echo 'cool';die();
// Read scalar form values
$zipFolder = (string) $request->getPost('zip_folder') ?: 'web/';
$s3Bucket = (string) $request->getPost('s3_bucket') ?: '';
@@ -283,4 +283,10 @@ class DeployController extends AdminController
$this->loadLayout('fedeploy');
}
+ public function fetest()
+ {
+ echo 'Hello from DeployController fetest!';
+
+ }
+
}
diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php
index 1c22f967..986a3fcd 100755
--- a/app/Controllers/EmpDataServiceController.php
+++ b/app/Controllers/EmpDataServiceController.php
@@ -43,6 +43,7 @@ use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Exception as SpreadsheetReaderException;
use PhpParser\Node\Expr\Cast\Double;
use Kint\Kint;
+use PhpParser\Node\Stmt\TraitUseAdaptation;
use function PHPUnit\Framework\returnSelf;
@@ -2179,18 +2180,18 @@ class EmpDataServiceController extends BaseController
'user_id' => $user_id,
]]);
- // $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [
- // 'client_policy_id' => $client_policy_id ?? null,
- // 'endorsement_no' => $endorsement_id ?? null,
- // 'emp_count' => $emp_count ?? null,
- // 'action_type' => $file['event_type'] ?? null,
- // 'no_of_insured' => count($no_of_insured ?? []) ?? null,
- // 'no_of_dependent' => count($no_of_dependent ?? []) ?? null,
- // 'base_premium' => $base_bremium_and_gst['base_premium'] ?? null,
- // 'gst' => $base_bremium_and_gst['gst'] ?? null,
- // 'policy_issue_date' => $policy_issue_date ?? null,
- // 'created_by' => $file['created_by'] ?? null,
- // ]]);
+ $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [
+ 'client_policy_id' => $client_policy_id ?? null,
+ 'endorsement_no' => $endorsement_id ?? null,
+ 'emp_count' => $emp_count ?? null,
+ 'action_type' => $file['event_type'] ?? null,
+ 'no_of_insured' => count($no_of_insured ?? []) ?? null,
+ 'no_of_dependent' => count($no_of_dependent ?? []) ?? null,
+ 'base_premium' => $base_bremium_and_gst['base_premium'] ?? null,
+ 'gst' => $base_bremium_and_gst['gst'] ?? null,
+ 'policy_issue_date' => $policy_issue_date ?? null,
+ 'created_by' => $file['created_by'] ?? null,
+ ]]);
// $this->cashDepositCalculationForInception($depositeData);
// $this->sendMailForDownloadingECard($emp_policy_ids);
@@ -2620,14 +2621,14 @@ class EmpDataServiceController extends BaseController
$file_data = $this->getDataByFileId($file_id, 'success');
$this->setPullNotification($file_data);
- // $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [
- // 'client_policy_id' => $client_policy_id ?? null,
- // 'endorsement_no' => $endorsement_id[0] ?? null,
- // 'emp_count' => $emp_count ?? null,
- // 'action_type' => $file['event_type'] ?? null,
- // 'policy_issue_date' => $policy_issue_date ?? null,
- // 'created_by' => $file['created_by'] ?? null,
- // ]]);
+ $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [
+ 'client_policy_id' => $client_policy_id ?? null,
+ 'endorsement_no' => $endorsement_id[0] ?? null,
+ 'emp_count' => $emp_count ?? null,
+ 'action_type' => $file['event_type'] ?? null,
+ 'policy_issue_date' => $policy_issue_date ?? null,
+ 'created_by' => $file['created_by'] ?? null,
+ ]]);
//import file to upload Google Drive
@@ -3354,18 +3355,18 @@ class EmpDataServiceController extends BaseController
'user_id' => $user_id,
]]);
- // $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [
- // 'client_policy_id' => $client_policy_id ?? null,
- // 'endorsement_no' => $endorsement_id ?? null,
- // 'emp_count' => $emp_count ?? null,
- // 'action_type' => $file['event_type'] ?? null,
- // 'no_of_insured' => count($no_of_insured ?? []) ?? null,
- // 'no_of_dependent' => count($no_of_dependent ?? []) ?? null,
- // 'base_premium' => $base_bremium_and_gst['base_premium'] ?? null,
- // 'gst' => $base_bremium_and_gst['gst'] ?? null,
- // 'policy_issue_date' => $policy_issue_date ?? null,
- // 'created_by' => $file['created_by'] ?? null,
- // ]]);
+ $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [
+ 'client_policy_id' => $client_policy_id ?? null,
+ 'endorsement_no' => $endorsement_id ?? null,
+ 'emp_count' => $emp_count ?? null,
+ 'action_type' => $file['event_type'] ?? null,
+ 'no_of_insured' => count($no_of_insured ?? []) ?? null,
+ 'no_of_dependent' => count($no_of_dependent ?? []) ?? null,
+ 'base_premium' => $base_bremium_and_gst['base_premium'] ?? null,
+ 'gst' => $base_bremium_and_gst['gst'] ?? null,
+ 'policy_issue_date' => $policy_issue_date ?? null,
+ 'created_by' => $file['created_by'] ?? null,
+ ]]);
}
@@ -3865,18 +3866,18 @@ class EmpDataServiceController extends BaseController
'user_id' => $user_id,
]]);
- // $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [
- // 'client_policy_id' => $client_policy_id ?? null,
- // 'endorsement_no' => $endorsement_id ?? null,
- // 'emp_count' => $emp_count ?? null,
- // 'action_type' => $file['event_type'] ?? null,
- // 'no_of_insured' => count($no_of_insured ?? []) ?? null,
- // 'no_of_dependent' => count($no_of_dependent ?? []) ?? null,
- // 'base_premium' => $base_bremium_and_gst['base_premium'] ?? null,
- // 'gst' => $base_bremium_and_gst['gst'] ?? null,
- // 'policy_issue_date' => $policy_issue_date ?? null,
- // 'created_by' => $file['created_by'] ?? null,
- // ]]);
+ $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [
+ 'client_policy_id' => $client_policy_id ?? null,
+ 'endorsement_no' => $endorsement_id ?? null,
+ 'emp_count' => $emp_count ?? null,
+ 'action_type' => $file['event_type'] ?? null,
+ 'no_of_insured' => count($no_of_insured ?? []) ?? null,
+ 'no_of_dependent' => count($no_of_dependent ?? []) ?? null,
+ 'base_premium' => $base_bremium_and_gst['base_premium'] ?? null,
+ 'gst' => $base_bremium_and_gst['gst'] ?? null,
+ 'policy_issue_date' => $policy_issue_date ?? null,
+ 'created_by' => $file['created_by'] ?? null,
+ ]]);
}
$file_data = $this->getDataByFileId($file_id, 'success');
@@ -5170,6 +5171,7 @@ class EmpDataServiceController extends BaseController
public function makeEntryForBDSPolicyTransaction($params)
{
try {
+
$this->myLogger->logme("error", "makeEntryForBDSPolicyTransaction() started: " . json_encode(['params' => $params]));
if (empty($params) || !isset($params['client_policy_id']) || empty($params['client_policy_id'])) {
@@ -5182,18 +5184,23 @@ class EmpDataServiceController extends BaseController
return ['status' => "Failed", 'message' => "Action type is missing or empty", 'data' => ['params' => $params]];
}
- //Function call for if the old policy transaction entries exisit than active the Policy transaction entries
- $existing_policy_transaction_entry = $this->retrivePolicyTransactionEntries($params);
+ //get the policy data
+ $policy_data = $this->clientPolicyModel->where('id', $params['client_policy_id'])->where('is_active', 1)->first();
+ $params['policy_no'] = $policy_data['policy_no'] ?? null;
+
+ //check if the entries available in the policy transaction table
+ $check_policy_exist = $this->checkPolicyTransactionExist($params);
- if($existing_policy_transaction_entry != false){
- return $existing_policy_transaction_entry;
+ if($check_policy_exist['status'] == true) {
+ return $check_policy_exist;
}
- //get the policy data
- $policy_data = $this->clientPolicyModel
- ->where('id', $params['client_policy_id'])
- ->where('is_active', 1)
- ->first();
+ //Function call for if the old policy transaction entries exisit than active the Policy transaction entries
+ // $existing_policy_transaction_entry = $this->retrivePolicyTransactionEntries($params);
+
+ // if($existing_policy_transaction_entry != false) {
+ // return $existing_policy_transaction_entry;
+ // }
if (empty($policy_data)) {
$this->myLogger->logme("error", "No policy data found: " . json_encode(['client_policy_id' => $params['client_policy_id']]));
@@ -5201,10 +5208,7 @@ class EmpDataServiceController extends BaseController
}
//get the leads data
- $lead_data = $this->leadsModel
- ->where('is_policy_created', $params['client_policy_id'])
- ->where('is_active', 1)
- ->first();
+ $lead_data = $this->leadsModel->where('is_policy_created', $params['client_policy_id'])->where('is_active', 1)->first();
if (empty($lead_data)) {
$this->myLogger->logme("error", "No lead data found: " . json_encode(['client_policy_id' => $params['client_policy_id']]));
@@ -5227,14 +5231,13 @@ class EmpDataServiceController extends BaseController
$this->myLogger->logme("error", "Policy transaction inserted successfully: " . json_encode(['insert_id' => $insert_id]));
//do not remove this commented item
- $coShareDetails = $this->ConstructPTShareData($policy_data, $insert_id, $params);
+ $coShareDetails = $this->ConstructPTShareData($policy_data, $insert_id, $params, $lead_data);
$pt_co_share_id = $this->PTCOShareDetailsModel->insert($coShareDetails);
-
- // $this->myLogger->logme("error", "PT Co share data inserted successfully: " . json_encode(['pt_co_share_id' => $pt_co_share_id]));
+ $this->myLogger->logme("error", "PT Co share data inserted successfully: " . json_encode(['pt_co_share_id' => $pt_co_share_id]));
// get the lead installment data
-
if(!empty($lead_data)){
+
$lead_installment_data = $this->leadInstallmentPaymentDetailesModel
->select('lead_id, installment_amount, payment_date, utr_no')
->where('lead_id', $lead_data['id'])
@@ -5253,12 +5256,20 @@ class EmpDataServiceController extends BaseController
return ['status' => "Success", 'message' => "Policy transaction entry created successfully", 'data' => ['params' => $params, 'insert_id' => $insert_id]];
} catch (\Throwable $e) {
+
+ $errorDetails = [
+ 'error_message' => $e->getMessage(),
+ 'file' => $e->getFile(),
+ 'line' => $e->getLine(),
+ 'stack_trace' => $e->getTraceAsString(),
+ ];
+
$this->myLogger->logme("error", "Exception occurred in makeEntryForBDSPolicyTransaction(): " . json_encode([
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]));
- return ['status' => "Error", 'message' => "An unexpected error occurred", 'data' => ['error' => $e]];
+ return ['status' => "Error", 'message' => "An unexpected error occurred", 'data' => $errorDetails];
}
}
@@ -5271,9 +5282,38 @@ class EmpDataServiceController extends BaseController
$action_type_string = "addition";
}
+ // get the acm data for service person id
+ $acm_data = db_connect()->table('client_rm')->where('is_active', 1)->where('client_id', $policy_data['client_id'] ?? null)->where('level', 3) ->get() ->getRowArray();
+ $service_person_id = null;
+ if(!empty($acm_data)){
+ $service_person_id = $acm_data['user_id'] ?? null;
+ }else{
+ $service_person_id = $params['created_by'] ?? null;
+ }
+
+ // get the user data for salse person id
+ $user_data = db_connect()->table('user_profiles')->where('is_active', 1)->where('id', $lead_data['created_by'] ?? null)->get()->getRowArray();
+ $salse_person_id = null;
+ if(isset($lead_data['salse_person_id']) && !empty($lead_data['salse_person_id'])){
+ $salse_person_array = json_decode($lead_data['salse_person_id'] ?? '{}', true) ?? [];
+ $salse_person_id = $salse_person_array[0] ?? null;
+ }else{
+ $salse_person_id = $lead_data['created_by'] ?? null;
+ }
+
+ // get the policy transaction id for client policy id
+ $policy_transaction_data = $this->policyTransactionModel->where('is_active', 1)->where('TRIM(policy_no)', $policy_data['policy_no'])->where('action_type', 'inception')->first();
+ $client_policy_id = null;
+ if(!empty($policy_transaction_data) && $params['action_type'] != "inception"){
+ $client_policy_id = $policy_transaction_data['id'] ?? null;
+ }else{
+ $client_policy_id = $policy_data['id'] ?? null;
+ }
+
$policyTransactionData = [
'issuer' => 2,
+ 'issuer_branch' => $user_data['nhance_branch_id'] ?? 1,
'client_id' => $policy_data['client_id'] ?? null,
'client_branch_id' => $policy_data['client_branch_id'] ?? null,
'insurer_id' => $policy_data['insurer_id'] ?? null,
@@ -5281,7 +5321,7 @@ class EmpDataServiceController extends BaseController
'tpa_id' => $policy_data['tpa_id'] ?? null,
'tpa_branch_id' => $policy_data['tpa_branch_id'] ?? null,
'policy_type_id' => $policy_data['policy_type_id'] ?? null,
- 'client_policy_id' => $policy_data['id'] ?? null,
+ 'client_policy_id' => $client_policy_id,
'policy_no' => $policy_data['policy_no'] ?? null,
'cd_ac_no' => $policy_data['cd_ac_no'] ?? null,
'cd_ac_pk' => $policy_data['cd_ac_pk'] ?? null,
@@ -5292,7 +5332,7 @@ class EmpDataServiceController extends BaseController
'closure_date' => $policy_data['closure_date'] ?? null,
'emp_count' => $params['no_of_insured'] ?? null,
'dependent_count' => $params['no_of_dependent'] ?? null,
- 'revenue_type' => isset($lead_data['lead_type']) ?($lead_data['lead_type'] == 1 ? "NA" : ($lead_data['lead_type'] == 2 ? "EA" : "EANR") ) : null,
+ 'revenue_type' => isset($lead_data['lead_type']) ?($lead_data['lead_type'] == 1 ? "NA" : ($lead_data['lead_type'] == 2 ? "EA" : "EANR") ) : "NA",
'co_share' => $policy_data['co_share'] ?? 0,
'pre_payable_by' => $policy_data['pre_payable_by'] ?? 1,
'renewal_date' => $policy_data['policy_end_date'] ?? null,
@@ -5312,6 +5352,10 @@ class EmpDataServiceController extends BaseController
'tsi' => generate_tsi_code($lead_data['lead_type'] ?? 1) ?? null,
'installment' => $lead_data['no_of_installment'] ?? null,
'created_by' => $params['created_by'] ?? null,
+ 'entry_from' => 2,
+
+ 'sales_generated_by' => $salse_person_id,
+ 'serviced_by' => $service_person_id,
];
$this->myLogger->logme("error", "Constructed policy transaction data: " . json_encode($policyTransactionData));
@@ -5319,7 +5363,7 @@ class EmpDataServiceController extends BaseController
return $policyTransactionData;
}
- private function ConstructPTShareData($policy_data, $pt_id, $params)
+ private function ConstructPTShareData($policy_data, $pt_id, $params, $lead_data)
{
$policyTypeModel = new PolicyTypeModel();
$policy_type_data = $policyTypeModel->where('is_active', 1)->where('id', $policy_data['policy_type_id'])->first();
@@ -5336,10 +5380,21 @@ class EmpDataServiceController extends BaseController
'co_share_type' => 1,
'co_share_per' => 100,
'standerd_bp_per' => $policy_type_data['ebp'],
+ 'pt_policy_issue_date' => $params['policy_issue_date'] ?? null,
'amount' => ($params['base_premium'] ?? 0) + ($params['gst'] ?? 0),
];
- $coShareData['exp_amt'] = (($params['base_premium'] ?? 0) * ($policy_type_data['ebp'] ?? 0)) / 100;
+ if(isset($policy_data['gst']) && $policy_data['gst'] != null){
+ $coShareData['bp_igst'] = $policy_data['gst'];
+ $coShareData['bp_sgst'] = 0;
+ $coShareData['bp_cgst'] = 0;
+ }
+
+ if(isset($lead_data['agreed_percentage']) && !empty($lead_data['agreed_percentage'])){
+ $coShareData['exp_amt'] = (($params['base_premium'] ?? 0) * ($lead_data['agreed_percentage'] ?? 0)) / 100;
+ }else{
+ $coShareData['exp_amt'] = (($params['base_premium'] ?? 0) * ($policy_type_data['ebp'] ?? 0)) / 100;
+ }
$this->myLogger->logme("error", "Constructed PT co-share data: " . json_encode($coShareData));
@@ -5391,8 +5446,7 @@ class EmpDataServiceController extends BaseController
$activated_pt_co_share_ids[] = $value['id'];
}
- $this->myLogger->logme("error", "Activated pt_co_share_ids : ". json_encode($activated_pt_co_share_ids));
-
+ $this->myLogger->logme("error", "Activated pt_co_share_ids : ". json_encode($activated_pt_co_share_ids));
$update_return = $this->policyTransactionModel->where('id', $policy_transaction_data['id'])->set(['is_active' => 1])->update();
@@ -5405,6 +5459,30 @@ class EmpDataServiceController extends BaseController
}
}
+
+ public function checkPolicyTransactionExist($params)
+ {
+ // Trim the input
+ $policy_no = trim($params['policy_no']);
+
+ // Base query
+ $policy_transaction_data = $this->policyTransactionModel->where('is_active', 1)->where('TRIM(policy_no)', $policy_no);
+
+ // Add endorsement condition only if not inception
+ if ($params['action_type'] !== "inception") {
+ $policy_transaction_data = $policy_transaction_data ->where('TRIM(endorsement_no)', trim($params['endorsement_no']));
+ }
+
+ $policy_transaction_data = $policy_transaction_data->first();
+
+ // If record exists → log and return true
+ if (!empty($policy_transaction_data)) {
+ $this->myLogger->logme("error", "Policy Transaction already exists. Input Parameters: " . json_encode($params) );
+ return ['status' => true, 'message' => "This entry already available in the Policy Transaction table", 'data' => $policy_transaction_data['id']];
+ }
+
+ return ['status' => false, 'message' => "This entry not available in the Policy Transaction table", 'data' => ''];
+ }
public function removeBDSPolicyTransactionEntryFromTruncate($params)
{
diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php
index 0da7f5a7..39298198 100755
--- a/app/Controllers/EmployeeController.php
+++ b/app/Controllers/EmployeeController.php
@@ -483,6 +483,8 @@ class EmployeeController extends AdminController
$filePath = ROOTPATH . 'public/sample_excel/Sample_Member_Data.xlsx';
}else if ($actionType == 'all') {
$filePath = ROOTPATH . 'public/sample_excel/sample_multievent_file.xlsx';
+ }else if ($actionType == 'bds_upload') {
+ $filePath = ROOTPATH . 'public/sample_excel/sample_bds_bulk_upload_excel.xlsx';
}
// Check if the file exists
@@ -546,9 +548,7 @@ class EmployeeController extends AdminController
'file_name' => $file_name,
];
-
- $batch_data['policy_issue_date'] = (!empty($policy_issue_date) && strtotime($policy_issue_date) !== false) ? change_date_format($policy_issue_date) : null;
-
+ $batch_data['policy_issue_date'] = !empty($policy_issue_date) ? change_date_format($policy_issue_date, 'd/m/Y', 'Y-m-d') : null;
if ($actions == 'export') {
@@ -2308,6 +2308,10 @@ class EmployeeController extends AdminController
}
$message = isset($message) ? ($message . ' not defined for choosed policy') : null;
+ if ($policy_details['cd_ac_pk'] == null) {
+ $message = isset($message) ? ($message . ' The policy does not have a CD account number.') : null;
+ }
+
return $this->respond(['dataStatus' => true, 'code' => 200, 'message' => $message, 'si_enhancement' => $si_enhancement_true_or_false, 'insurer_multi_event' => $insurer_details['is_multi_event'], 'tpa_api_service_status' => $tpa_api_service_status], 200);
}
@@ -3213,4 +3217,367 @@ class EmployeeController extends AdminController
}
+ public function checkWellnessOnboardStatus($client_policy_id)
+ {
+ // echo $client_policy_id;die();
+ $data = $this->employeePolicyModel->select('employee_polices.*,emp.name,emp.relationship,emp.emp_code,emp.name,emp.email_corporate,emp.mobile,emp.dob,cp.policy_no,cp.wellness_plan_id,cp.wellness_vendor_id,cp.policy_start_date as cp_policy_start_date,cp.policy_end_date,cls.short_name')
+ ->join('client_policy cp', 'cp.id = employee_polices.client_policy_id')
+ ->join('clients cls', "cp.client_id = cls.id")
+ ->join('employees emp', "emp.id = employee_polices.employee_id")
+ ->where('employee_polices.is_active', 1)
+ ->where('employee_polices.status', 'active')
+ ->where('employee_polices.client_policy_id', $client_policy_id)
+ ->where('employee_polices.tpa_id is not null')
+ ->where('employee_polices.wellness_onboard', '0')
+ ->where('emp.emp_status', 'active')
+ ->where('emp.is_active', 1)
+ ->where('cp.wellness_plan_id is not null')
+ ->where('cp.wellness_vendor_id is null')
+ // ->where('cp.policy_status',1)
+ // ->where('cp.is_active',1)
+ ->findAll();
+ // echo count($data);die();
+ // if(is_array($data) && count($data))
+ // {
+ return $this->respond(['status' => true, 'code' => 200, 'data' => count($data)], 200);
+ // }
+ // return $this->respond(['status' => true, 'code' => 200, 'message' => 'Inception and Member data comparision skiped successfully!'], 200);
+ }
+
+ public function initiateWellnessOnboard($client_policy_id)
+ {
+ $r = Jobs::addJob(['job_name' => 'initiateWellnessOnboardJob','payload' => ['client_policy_id' => $client_policy_id]]);
+ return $this->respond(['status' => true, 'code' => 200, 'message' => 'Process started'], 200);
+ }
+
+ public function initiateWellnessOnboardJob($arr)
+ {
+
+ $client_policy_id = $arr['client_policy_id'];
+ // $this->updateWellnessOnboardResponseToDB();die();
+ // echo $client_policy_id;die();
+ $data = $this->employeePolicyModel->select('employee_polices.*,emp.name,emp.relationship,emp.emp_code,emp.name,emp.email_corporate,emp.mobile,emp.dob,cp.policy_no,cp.wellness_plan_id,cp.wellness_vendor_id,cp.policy_start_date as cp_policy_start_date,cp.policy_end_date,cls.short_name')
+ ->join('client_policy cp', 'cp.id = employee_polices.client_policy_id')
+ ->join('clients cls', "cp.client_id = cls.id")
+ ->join('employees emp', "emp.id = employee_polices.employee_id")
+ ->where('employee_polices.is_active', 1)
+ ->where('employee_polices.status', 'active')
+ ->where('employee_polices.client_policy_id', $client_policy_id)
+ ->where('employee_polices.tpa_id is not null')
+ ->where('employee_polices.wellness_onboard', '0')
+ ->where('emp.emp_status', 'active')
+ ->where('emp.is_active', 1)
+ ->where('cp.wellness_plan_id is not null')
+ ->where('cp.wellness_vendor_id is null')
+ // ->where('cp.policy_status',1)
+ // ->where('cp.is_active',1)
+ ->findAll();
+ // print_r($this->employeePolicyModel->getLastQuery());
+ // print_r($data);
+ // echo '==============================';die();
+ // $data = '[{"id":12847,"employee_id":"TEST_EMP_001","client_policy_id":null,"tpa_id":null,"uhid":null,"batch_code":null,"status":"active","pre_existing_alignments":null,"age_band":null,"basic_cover_si":"0","date_coverage":"2025-01-01","policy_end_date":"2025-12-31","days":"0","premium":"0","rata_premimum":"0","gst":"0","si_enhancement_date":null,"date_of_exit":null,"reason_for_exit":null,"claim_status":"0","created_by":null,"created_at":null,"updated_by":null,"updated_at":null,"is_active":"1","rand_string":null,"ecard_sent_status":"0","payable_employee":"0","file_id":null,"wellness_onboard":"0","name":"test name","relationship":"SELF","emp_code":"TEST_EMP_001","email_corporate":"test@gmail.com","mobile":"9797976565","dob":"1975-08-09"},{"id":12846,"employee_id":"TEST_EMP_001","client_policy_id":null,"tpa_id":null,"uhid":null,"batch_code":null,"status":"active","pre_existing_alignments":null,"age_band":null,"basic_cover_si":"0","date_coverage":"2025-01-01","policy_end_date":"2025-12-31","days":"0","premium":"0","rata_premimum":"0","gst":"0","si_enhancement_date":null,"date_of_exit":null,"reason_for_exit":null,"claim_status":"0","created_by":null,"created_at":null,"updated_by":null,"updated_at":null,"is_active":"1","rand_string":null,"ecard_sent_status":"0","payable_employee":"0","file_id":null,"wellness_onboard":"0","name":"dependent 1","relationship":"SON","emp_code":"TEST_EMP_001","email_corporate":"dependent1@gmail.com","mobile":"9898989898","dob":"2001-08-09"}]';
+ // $data = (array)json_decode($data,true);
+ // print_r($data);
+ // echo '==============================';die();
+ if(is_array($data) && count($data))
+ {
+ // $data = $input['data'] ?? [];
+
+ // ------------------ GROUP BY FAMILY (emp_code) ------------------
+ $families = []; // [emp_code => [rows...]]
+
+ foreach ($data as $row) {
+ if (empty($row['emp_code'])) {
+ // If emp_code is missing, you can skip or handle separately
+ continue;
+ }
+
+ $empCode = $row['emp_code'];
+ if (!isset($families[$empCode])) {
+ $families[$empCode] = [];
+ }
+ $families[$empCode][] = $row;
+ }
+
+ // ------------------ BUILD PAYLOAD FOR ALL FAMILIES ------------------
+ $familiesPayload = [];
+
+ foreach ($families as $empCode => $members) {
+ $familiesPayload[$empCode] = $this->buildFamilyPayload($empCode, $members);
+ }
+
+ // print_r($familiesPayload);die();
+ $apiResponse = $this->sendFamiliesToWellnessApi($familiesPayload);
+ // print_r($apiResponse);
+ $updatedData = $this->updateWellnessOnboardResponseToDB($apiResponse);
+ // print_r($updatedData);die();
+ return true;
+
+
+
+
+ }
+ else
+ {
+ return $this->respond(['status' => false, 'code' => 200, 'message' => 'No employees found for wellness onboard!'], 200);
+
+ }
+
+ }
+
+
+
+ # ------------------ FUNCTION TO BUILD FAMILY PAYLOAD ------------------
+ /**
+ * Build the required payload for a single family.
+ *
+ * @param string $empCode
+ * @param array $members Array of rows for this emp_code
+ * @return array
+ */
+ private function buildFamilyPayload(string $empCode, array $members): array
+ {
+ // Use the first member as primary reference for policy level data
+ $primary = $members[0];
+
+ // Map DB fields to your required "policyDetails" structure
+ $policyStartDate = $primary['cp_policy_start_date'] ?? null;
+ // $policyStartDate = '2025-01-01';
+ $policyEndDate = $primary['policy_end_date'] ?? null;
+ // $policyEndDate = '2025-12-31';
+
+ $payload = [
+ "policyDetails" => [
+ "policyNumber" => $primary["policy_no"] ?? null,
+ "employeeId" => $empCode,
+ "policyName" => "GMC", // Static or from DB
+ "policyStartDate" => $policyStartDate,
+ "policyEndDate" => $policyEndDate,
+ "plan" => $primary["wellness_plan_id"] ?? null,
+ "source" => $primary['short_name'] ?? null,
+ "employer" => $primary['short_name'] ?? null,
+ "employeeCode" => $empCode,
+ "accountNumber" => "", // Fill from DB if available
+ "ifsc" => "", // Fill from DB if available
+ "accountType" => "" // Fill from DB if available
+ ],
+ "memberDetails" => []
+ ];
+
+ // Build "memberDetails" for each member in this family
+ foreach ($members as $index => $row) {
+
+ // You don't have gender in data, so put null or default
+ $gender = null; // or "MALE" / "FEMALE" if you infer from somewhere
+
+ $payload["memberDetails"][] = [
+ "memberId" => $row["id"], // or custom ID (e.g. employee_id.'-'.$index)
+ "name" => $row["name"],
+ "phone" => $row["mobile"],
+ "email" => $row["email_corporate"],
+ "relationshipName" => strtoupper($row["relationship"] ?? ''),
+ "gender" => $gender,
+ "dob" => $row["dob"]
+ ];
+ }
+
+ return $payload;
+ }
+
+
+
+ /**
+ * Send each family payload to API and attach the response
+ *
+ * @param array $familiesPayload [emp_code => ['policyDetails' => ..., 'memberDetails' => [...]]]
+ * @return array Same array but with ['apiResponse'] added for each family
+ */
+ public function sendFamiliesToWellnessApi(array $familiesPayload): array
+ {
+ // CI4 HTTP client
+ $client = \Config\Services::curlrequest();//die();
+ $endpointUrl = getenv('WELLNESS_ONBOARD_ENDPOINT_URL');
+ // Custom headers
+ $headers = [
+ 'Content-Type' => 'application/json',
+ 'Authorization' => 'Basic ' . getenv('WELLNESS_ONBOARD_AUTHORIZATION')
+ ];
+
+ foreach ($familiesPayload as $empCode => &$family) {
+
+ try {
+ $response = $client->post($endpointUrl, [
+ 'headers' => $headers,
+ 'body' => json_encode($family),
+ 'http_errors' => false, // so we can handle non-2xx manually
+ 'timeout' => 30,
+ ]);
+
+ $statusCode = $response->getStatusCode();
+ $body = (string) $response->getBody();
+ $decoded = json_decode($body, true);
+
+ $family['apiResponse'] = [
+ 'statusCode' => $statusCode,
+ 'rawBody' => $body,
+ 'data' => $decoded,
+ ];
+ } catch (\Throwable $e) {
+ // In case of exception, store error info
+ $family['apiResponse'] = [
+ 'statusCode' => 0,
+ 'rawBody' => null,
+ 'data' => null,
+ 'error' => $e->getMessage(),
+ ];
+ }
+ }
+
+ unset($family); // break reference
+
+ return $familiesPayload;
+ }
+
+
+
+ /**
+ * Batch update wellness_onboard for each family using referenceId from API response.
+ *
+ * @param array $familiesWithResponse // output of sendFamiliesToApi()
+ * @return void
+ */
+ public function updateWellnessOnboardResponseToDB(array $familiesWithResponse = []): void
+ {
+ // echo 'START';
+ // Collect all rows to update in a single big batch (optional but efficient)
+ $allUpdates = [];
+
+ // $apiResponse = [
+ // "message" => "success",
+ // "body" => "The policy details are posted successfully",
+ // "policyDetails" => [
+ // [
+ // "memberId" => "12847",
+ // "name" => "test name",
+ // "phone" => 9797976565,
+ // "email" => "test@gmail.com",
+ // "relationshipName" => "SELF",
+ // "gender" => "MALE",
+ // "dob" => "1975-08-09"
+ // ],
+ // [
+ // "memberId" => "12846",
+ // "name" => "dependent 1",
+ // "phone" => 9898989898,
+ // "email" => "dependent1@gmail.com",
+ // "relationshipName" => "SON",
+ // "gender" => "MALE",
+ // "dob" => "2001-08-09"
+ // ]
+ // ],
+ // "referenceId" => "TESTPOL001-client1-1764914537069"
+ // ];
+
+ // $familiesWithResponse = [
+
+ // "TEST_EMP_001" => [
+ // "policyDetails" => [
+ // "policyNumber" => "TESTPOL001",
+ // "employeeId" => "TEST_EMP_001",
+ // "policyName" => "Client Policy Name",
+ // "policyStartDate" => "2025-01-01",
+ // "policyEndDate" => "2025-12-31",
+ // "plan" => "plan-A",
+ // "source" => "client1",
+ // "employer" => "employeer1",
+ // "employeeCode" => "TEST_EMP_001",
+ // "accountNumber" => "",
+ // "ifsc" => "",
+ // "accountType" => ""
+ // ],
+ // "memberDetails" => [
+ // [
+ // "memberId" => "12847",
+ // "name" => "test name",
+ // "phone" => 9797976565,
+ // "email" => "test@gmail.com",
+ // "relationshipName" => "SELF",
+ // "gender" => "MALE",
+ // "dob" => "1975-08-09"
+ // ],
+ // [
+ // "memberId" => "12846",
+ // "name" => "dependent 1",
+ // "phone" => 9898989898,
+ // "email" => "dependent1@gmail.com",
+ // "relationshipName" => "SON",
+ // "gender" => "MALE",
+ // "dob" => "2001-08-09"
+ // ]
+ // ],
+
+ // "apiResponse" => [ 'statusCode' => 200 ,"rawBody" => "", "data" => $apiResponse]
+ // ]
+ // ];
+
+
+
+ foreach ($familiesWithResponse as $empCode => $family) {
+
+ $apiResponse = $family['apiResponse'] ?? null;
+ if (!$apiResponse || !isset($apiResponse['data'])) {
+ // No valid API data for this family
+ $this->myLogger->logme('error', "Wellness Onboard API error for emp_code {$empCode} No apiResponse found:");
+ continue;
+ }
+
+ // Your endpoint response
+ $statusCode = $apiResponse['statusCode'] ?? null;
+ if (empty($statusCode) || $statusCode == 400 || $statusCode == 500) {
+ $this->myLogger->logme('error', "Wellness Onboard API error for emp_code {$empCode} {}: " . ($apiResponse['rawBody'] ?? 'No response'));
+
+ // No referenceId, nothing to update
+ continue;
+ }
+
+ $data = $apiResponse['data'];
+
+ // Your endpoint response
+ $referenceId = $data['referenceId'] ?? null;
+ if (empty($referenceId)) {
+ // No referenceId, nothing to update
+ $this->myLogger->logme('error', "Wellness Onboard API error for emp_code {$empCode} No referenceId found:");
+ continue;
+ }
+
+ // All members in this family share the same referenceId
+ if (empty($family['memberDetails']) || !is_array($family['memberDetails'])) {
+ $this->myLogger->logme('error', "Wellness Onboard API error for emp_code {$empCode} No memberDetails found:");
+ continue;
+ }
+
+ foreach ($family['memberDetails'] as $member) {
+ $memberPk = $member['memberId'] ?? null; // This is employee_policy.id
+
+ if (empty($memberPk)) {
+ continue;
+ }
+
+ $allUpdates[] = [
+ 'id' => $memberPk, // PK column of your table
+ 'wellness_onboard' => $referenceId,
+ // uncomment if you have updated_at column
+ // 'updated_at' => date('Y-m-d H:i:s'),
+ ];
+ }
+ }
+ // print_r($allUpdates);die();
+ // Do a single batch update for all families/members
+ if (!empty($allUpdates)) {
+ // 2nd param is the key to match on; here it's 'id'
+ $this->employeePolicyModel->updateBatch($allUpdates, 'id');
+ }
+ }
+
+
}
diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php
index 19563217..82ecc4e1 100755
--- a/app/Controllers/EmployeeRestController.php
+++ b/app/Controllers/EmployeeRestController.php
@@ -39,6 +39,7 @@ use App\Models\TicketMessageModel;
use App\Models\HRAccessControlModel;
use App\Models\InsurerModel;
use App\Models\HrFileUploadModel;
+use App\Models\EmployeeRetailPolicy;
@@ -56,6 +57,7 @@ use Illuminate\Http\Request;
use App\Controllers\EmployeeServiceController;
use App\Models\ClaimFilesModel;
+use App\Models\PolicyTransactionModel;
use App\Models\TicketMailTemplateModel;
use App\Models\TpaApiSeviceModel;
use Composer\Pcre\Preg;
@@ -97,6 +99,7 @@ class EmployeeRestController extends AdminController
protected $insurerModel;
protected $hrFileUploadModel;
protected $ticketMailTemplateModel;
+ protected $employeeRetailPolicy;
public function __construct()
@@ -124,6 +127,7 @@ class EmployeeRestController extends AdminController
$this->claimStatusModel = new TicketClaimStatusModel();
$this->ticketMaster = new TicketMasterModel();
$this->ticketMessage = new TicketMessageModel();
+ $this->employeeRetailPolicy = new EmployeeRetailPolicy();
$this->ticketController = new TicketController();
$this->hrAccessControlModel = new HRAccessControlModel();
@@ -2581,12 +2585,14 @@ class EmployeeRestController extends AdminController
$data['claims_data'] = $this->ticketMaster->getTicketDataByTicketID($ticket_id);
$data['ticket_data'] = $ticketController->getMoreInfo($requestFrom = 'rest', $ticket_id);
+ $required_docs = $this->ticketMaster->select('required_docs')->where('id', $ticket_id)->first();
+ $data['required_docs'] = json_decode($required_docs['required_docs'] ?? '{}', true) ?? [];
// $ticketData = $data['ticket_data'];
// $ticketHistory = $data['ticket_history'];
// print_r($ticketHistory); die;
$currentClaimStatus = $this->claimStatusModel->select("claim_status")->where('id', $data['claims_data']['claim_status_id'])->where('is_active', 1)->first();
- $ticketClaimStatus = $this->claimStatusModel->select('claim_status, display_name')->where('display_name is not null')->where('is_active', 1)->findAll();
+ $ticketClaimStatus = $this->claimStatusModel->select('claim_status, display_name')->where('display_name is not null')->where('ticket_type', $data['claims_data']['ticket_type_id'])->where('is_active', 1)->findAll();
$status_list = array_column($ticketClaimStatus, 'display_name', 'claim_status');
// print_r($currentClaimStatus); die;
@@ -2656,7 +2662,7 @@ class EmployeeRestController extends AdminController
->where('is_active', 1)
->where('file_type', 2)
->where('ticket_id', $ticket_id)
- ->where('ticket_message_id', $ticket_message['id'])
+ // ->where('ticket_message_id', $ticket_message['id'])
->findAll();
foreach ($claim_files_data as &$value) {
@@ -2817,7 +2823,31 @@ class EmployeeRestController extends AdminController
function getEmployeeActiveOrInactivePolicy()
- {
+ {
+
+ // for retail user policy only
+ $receviedPayload = $this->request->getGet();
+
+ if(
+ empty($receviedPayload['client_id']) &&
+ empty($receviedPayload['client_branch_id']) &&
+ empty($receviedPayload['emp_code'])
+ ){
+
+ if(!empty($receviedPayload['mobile_no']) || !empty($receviedPayload['email_id'])){
+
+ $retailUserData = (object) [
+ 'id' => null,
+ 'mobile' => $receviedPayload['mobile_no'],
+ 'email_id' => $receviedPayload['email_id']
+ ];
+
+ $emp_reatail_policy_data = $this->getEmpRetailPolicy($retailUserData);
+ $wellness_data = ['status' => 'failed','message' => 'Coming soon........!'];
+ return $this->respond(['status' => 'success', 'code' => 200, 'data' => [], 'emp_name' => $emp_reatail_policy_data[0]['insurerd_name'] ?? "", 'pre_policy_count' => 0, 'retail_policy_data' => $emp_reatail_policy_data, 'wellness_data' => $wellness_data], 200);
+ }
+ }
+
if ($this->request->getGet('type') == 'Active') {
$policy_status = 1;
$policy_status_key = "Active";
@@ -2858,9 +2888,13 @@ class EmployeeRestController extends AdminController
$clientId = $this->request->getGet('client_id');
if (!empty($employeeSelfData) && isset($employeeSelfData->email_corporate)) {
- $prePolicyCount = $this->getPreEmployeePolicyCount($empMobileNo, $clientId, $employeeSelfData->email_corporate);
+ $prePolicyCountData = $this->getPreEmployeePolicyCount($empMobileNo, $clientId, $employeeSelfData->email_corporate);
+ $prePolicyCount = $prePolicyCountData['pre_policy_count'] ?? 0;
+ $empNotEnrolledCount = $prePolicyCountData['emp_not_enrolled_count'] ?? 0;
} else {
- $prePolicyCount = $this->getPreEmployeePolicyCount($empMobileNo, $clientId);
+ $prePolicyCountData = $this->getPreEmployeePolicyCount($empMobileNo, $clientId);
+ $prePolicyCount = $prePolicyCountData['emp_not_enrolled_count'] ?? 0;
+ $empNotEnrolledCount = $prePolicyCountData['emp_not_enrolled_count'] ?? 0;
}
$whereArrayForId = [];
@@ -2920,6 +2954,7 @@ class EmployeeRestController extends AdminController
$data['claims_grace_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['claims_grace_date']);
$data['policy_status'] = $policy_status_key;
$data['pre_policy_count'] = $prePolicyCount;
+ $data['emp_not_enrolled_count'] = $empNotEnrolledCount;
// $data['policy_terms'] = $terms;
// if($ClientPolicyValue['policy_type_id'] == 1){ $data['heading'] = 'Group Personal Accident Coverage'; }else
@@ -2990,10 +3025,13 @@ class EmployeeRestController extends AdminController
array_push($result, $data);
}
-
}
- return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result, 'emp_name' => $employeeName, 'pre_policy_count' => $prePolicyCount], 200);
+ $emp_reatail_policy_data = $this->getEmpRetailPolicy($employeeSelfData);
+ $apiServiceController = new ApiServiceController;
+ $emp_wellness_data = $apiServiceController->getWellnessUrl($employeeSelfData->id ?? null);
+
+ return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result, 'emp_name' => $employeeName, 'pre_policy_count' => $prePolicyCount, 'emp_not_enrolled_count' => $empNotEnrolledCount, 'retail_policy_data' => $emp_reatail_policy_data, 'wellness_data' => $emp_wellness_data], 200);
} else {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
}
@@ -3139,30 +3177,58 @@ class EmployeeRestController extends AdminController
}
}
+ // public function getAdvertisementImage_old()
+ // {
+ // try {
+
+ // $client_id = $this->request->getGet('client_id');
+
+ // $img = $this->addImgModel->where('is_active', 1)->where('client_id',$client_id)->findAll();
+
+ // if (count($img) > 0) {
+ // $data = [];
+ // foreach ($img as $key => $value) {
+ // $url = base_url('public/uploads/add_image_upload/') . $value['name'];
+ // array_push($data, $url);
+ // }
+
+ // return $this->respond(['status' => 'success', 'code' => 200, 'data' => $data], 200);
+ // } else {
+
+ // return $this->respond(['status' => 'failed', 'code' => 404, 'data' => 'No Data'], 404);
+ // }
+ // } catch (\Throwable $th) {
+ // return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $th], 500);
+ // }
+ // }
+
public function getAdvertisementImage()
{
try {
- $img = $this->addImgModel->where('is_active', 1)->findAll();
+ $client_id = $this->request->getGet('client_id');
+ // get client_id & convert empty/null/undefined → 0
+ // $client_id = ($client_id === null || $client_id === '' || $client_id === 'undefined') ? 0 : $client_id;
- if (count($img) > 0) {
- $data = [];
- foreach ($img as $key => $value) {
- $url = base_url('public/uploads/add_image_upload/') . $value['name'];
- array_push($data, $url);
- }
+ // fetch images for client
+ $images = $this->addImgModel->where('is_active', 1)->where('client_id', $client_id)->findAll();
- return $this->respond(['status' => 'success', 'code' => 200, 'data' => $data], 200);
- } else {
-
- return $this->respond(['status' => 'failed', 'code' => 404, 'data' => 'No Data'], 404);
+ // if no client images → load default client 0
+ if (count($images) == 0) {
+ $images = $this->addImgModel->where('is_active', 1)->where('client_id', 0)->findAll();
}
+
+ // prepare URLs
+ $data = array_map(function($img){ return base_url('public/uploads/add_image_upload/' . $img['name']); }, $images);
+
+ return $this->respond(['status' => 'success', 'code' => 200, 'data' => $data], 200);
+
} catch (\Throwable $th) {
+
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $th], 500);
}
}
-
public function storeFireBase()
{
try {
@@ -3496,8 +3562,14 @@ class EmployeeRestController extends AdminController
$received_data = $this->request->getPost();
$this->myLogger->logme('error', 'API claim initiate Recevied Params :' . json_encode($received_data ?? []));
- $get_file_data = $this->request->getFiles('claim_docs');
+ $get_file_data = $this->request->getFiles('claim_docs') ?? null;
$get_docs_name = $this->request->getPost('claim_doc_names') ?? [];
+ $policy_transaction_id = $this->request->getPost('policy_transaction_id') ?? null;
+
+ if(!empty($policy_transaction_id)){
+ $response = $this->retailClaimInitiate($received_data);
+ return $this->respond($response, 200);
+ }
if (is_string($get_docs_name)) {
$decoded = json_decode($get_docs_name, true);
@@ -3652,7 +3724,82 @@ class EmployeeRestController extends AdminController
}
}
- public function handleCliamFiles($data, $ticket_id, $ticket_message_id = null)
+ public function retailClaimInitiate($data)
+ {
+ if(isset($data['policy_transaction_id'])){
+
+ $policy_transaction_model = new PolicyTransactionModel();
+
+ $policy = $policy_transaction_model
+ ->select('policy_transaction.*, clients.client_name, clients.phone as client_mobile, clients.email as client_email')
+ ->join('clients', 'policy_transaction.client_id = clients.id')
+ ->where('policy_transaction.is_active',1)
+ ->where('clients.is_active',1)
+ ->where('policy_transaction.id', $data['policy_transaction_id'])
+ ->first();
+
+ if(!empty($policy)){
+
+ $claimData = [
+ 'ticket_type_id' => $data['policy_type_id'],
+ 'policy_transaction_id' => $data['policy_transaction_id'],
+ 'claim_status_id' => 62,
+ 'policy_no' => $policy['policy_no'],
+ 'client_policy_id' => $policy['client_policy_id'],
+ 'insurer_id' => $policy['insurer_id'],
+ 'client_id' => $policy['client_id'] ?? null,
+ 'agent_id' => $policy['agent_id'] ?? null,
+ 'manager_id' => $policy['manager_id'] ?? null,
+ 'vehicle_id' => $policy['vehicle_id'] ?? null,
+ 'insured_name' => $policy['client_name'] ?? null,
+ 'emp_name' => $policy['client_name'] ?? null,
+ 'emp_mobile' => $policy['client_mobile'] ?? null,
+ 'emp_mail' => $policy['client_email'] ?? null,
+ 'emp_personal_mail'=> $policy['client_email'] ?? null,
+ 'claim_type' => $data['claim_type'],
+ 'claim_description'=> $data['claim_description'],
+ 'created_by' => $policy['client_id'] ?? null,
+ ];
+
+ $ticket_id = $this->ticketMaster->insert($claimData);
+
+ if ($ticket_id) {
+
+ $mail_sent_status = ($this->ticketController->sendAutoMailTrigger($ticket_id));
+
+ if (gettype($mail_sent_status) == 'array') {
+ $message = 'Claim Iniated Successfully';
+ return ['status' => true, 'code' => 200, 'message' => $message];
+ } else {
+ $mail_sent_status_object = json_decode($mail_sent_status);
+ }
+
+ if ($mail_sent_status_object->status == 'success') {
+ $message = 'Claim Initiated Successfully';
+ return ['status' => true, 'code' => 200, 'data' => $ticket_id, 'message' => $message];
+ } else {
+ $message = 'Claim Initiated, Failed to send Mail ';
+ $this->myLogger->logme('error', "Claim initiated, Failed to send Mail :$ticket_id ");
+ return ['status' => false, 'code' => 400, 'message' => $message];
+ }
+
+ $message = 'Claim Initiated Successfully';
+ return ['status' => true, 'code' => 200, 'data' => $ticket_id, 'message' => $message];
+ }else{
+ $message = 'Claim Initiation failed';
+ return ['status' => false, 'code' => 404, 'message' => $message];
+ }
+ }else{
+ $message = 'Claim Initiation failed. Policy data not found';
+ return ['status' => false, 'code' => 404, 'message' => $message];
+ }
+ }else{
+ $message = 'Claim Initiation failed';
+ return ['status' => false, 'code' => 404, 'message' => $message];
+ }
+ }
+
+ public function handleCliamFiles($data, $ticket_id, $ticket_message_id = null, $tpa_claim_push = true, $ir_docs = false)
{
if (!empty($data) && !empty($ticket_id)) {
$insert_ids = [];
@@ -3670,6 +3817,10 @@ class EmployeeRestController extends AdminController
'mime_type' => getMimeTypeByFileName($value['file_name']),
];
+ if($ir_docs == true){
+ $data['docs_for_ir'] = 1;
+ }
+
$insert_ids[] = $claim_file->insert($data);
if (getMimeTypeByFileName($value['file_name']) == "application/pdf") {
@@ -3677,16 +3828,19 @@ class EmployeeRestController extends AdminController
}
}
- if ($pdf_exist_in_the_file) {
+ if ($pdf_exist_in_the_file && $tpa_claim_push == true) {
// this call for TPA integration
$apiServiceController = new ApiServiceController();
$apiServiceController->pushClaims($ticket_id);
log_message('error', "pushClaims function called with Ticket ID: {$ticket_id}, In Employee Rest Controller");
} else {
- log_message('error', "Failed to call the pushClaims function in EmployeeRestController for Ticket ID: {$ticket_id}, because the .pdf file does not exist.");
+ if($tpa_claim_push == false){
+ log_message('error', 'Skip the TPA claim push');
+ }else{
+ log_message('error', "Failed to call the pushClaims function in EmployeeRestController for Ticket ID: {$ticket_id}, because the .pdf file does not exist.");
+ }
}
-
return $insert_ids;
}
@@ -3806,6 +3960,8 @@ class EmployeeRestController extends AdminController
$emp_id = $this->request->getGet('emp_id');
$ticket_type = $this->request->getGet('ticket_type') ?? null;
$ticket_id = $this->request->getGet('ticket_id') ?? null;
+ $mobile_number = $this->request->getGet('mobile_number') ?? null;
+ $email_id = $this->request->getGet('email_id') ?? null;
$request = \Config\Services::request();
$uri = $request->uri->getPath();
$returnType = "";
@@ -3816,6 +3972,11 @@ class EmployeeRestController extends AdminController
return $this->response->setJSON(['status' => false, 'code' => 200, 'message' => 'emp_id is required.'])->setStatusCode(404);
}
+ $retail_ticket_data = [];
+ if(!empty($mobile_number) || !empty($email_id)){
+ $retail_ticket_data = $this->getRetailPolicyClaimData($this->request->getGet());
+ }
+
$TicketMasterModel = new TicketMasterModel();
$ticket_data = $TicketMasterModel->get_ticket_data($emp_id, $returnType, $ticket_type, $ticket_id);
@@ -3890,9 +4051,113 @@ class EmployeeRestController extends AdminController
}
}
+ $ticket_data = array_merge($ticket_data, $retail_ticket_data);
+
return $this->response->setJSON(['ticket_data' => $ticket_data])->setStatusCode(200);
}
+ public function getRetailPolicyClaimData($receviedPayload)
+ {
+ try {
+ // Create minimal retail user object
+ $retailUserData = (object) [
+ 'id' => null,
+ 'mobile' => $receviedPayload['mobile_number'] ?? null,
+ 'email_id' => $receviedPayload['email_id'] ?? null
+ ];
+
+ // Get retail policies of user
+ $empRetailPolicyData = $this->getEmpRetailPolicy($retailUserData);
+
+ if (empty($empRetailPolicyData)) {
+ return [];
+ }
+
+ // Fetch ticket data for each policy
+ $retail_ticket_data = [];
+ foreach ($empRetailPolicyData as $policy) {
+ $tickets = $this->ticketMaster
+ ->select("
+ ticket_master.*,
+ vehicle.vehicle_no,
+ (
+ SELECT th1.old_value
+ FROM ticket_history th1
+ JOIN ticket_claim_status tcs ON th1.old_value = tcs.id
+ WHERE th1.field_name = 'claim_status_id'
+ AND th1.ticket_id = ticket_master.id
+ AND th1.id = (
+ SELECT MAX(th2.id)
+ FROM ticket_history th2
+ WHERE th2.ticket_id = th1.ticket_id
+ AND th2.field_name = 'claim_status_id'
+ )
+ ) AS old_status_id
+ ")
+ ->join("vehicle", "ticket_master.vehicle_id = vehicle.id", "left")
+ ->where('ticket_master.is_active', 1)
+ ->where('ticket_master.client_id', $policy['client_id'])
+ ->where('ticket_master.policy_transaction_id', $policy['policy_transaction_id'])
+ ->findAll();
+
+ if (!empty($tickets)) {
+ $retail_ticket_data = array_merge($retail_ticket_data, $tickets);
+ }
+ }
+
+ if (empty($retail_ticket_data)) {
+ return [];
+ }
+
+ // Fetch grouped claim statuses
+ $client_claim_status = $this->getClaimStatusGrouped(); // Format expected: [status => [ids]]
+ $claim_type = $this->getClaimTypeMaster('internal');
+
+ // Convert claim type for quick access
+ $typeMap = array_column($claim_type, 'claim_type', 'id');
+
+ // Map status name to each ticket
+ foreach ($retail_ticket_data as &$ticket) {
+ $ticket['claim_status'] = null; // Default
+
+ $ticket['claim_type_name'] = $typeMap[$ticket['claim_type']] ?? null;
+ if($ticket['ticket_type_id'] == 8){
+ $ticket['ticket_policy_type'] = 'Motor';
+ }
+ foreach ($client_claim_status as $status_name => $status_list) {
+ if (in_array($ticket['claim_status_id'], $status_list)) {
+ $ticket['claim_status'] = $status_name;
+ break;
+ }
+
+ if (in_array($ticket['old_status_id'], $status_list)) {
+ $ticket['claim_status'] = $status_name;
+ break;
+ }
+ }
+ }
+
+ return $retail_ticket_data;
+
+ }catch (\Throwable $th) {
+
+ $errorData = [
+ 'message' => $th->getMessage(),
+ 'file' => $th->getFile(),
+ 'line' => $th->getLine(),
+ 'code' => $th->getCode(),
+ 'trace' => $th->getTraceAsString(),
+ 'trace_array' => $th->getTrace(), // full array version (optional)
+ 'function' => $th->getTrace()[0]['function'] ?? null,
+ 'class' => $th->getTrace()[0]['class'] ?? null,
+ ];
+
+ $this->myLogger->logme("error", "EMPLOYEE-REST-CONTROLLER - getRetailPolicyClaimData: Exception: " . json_encode($errorData ?? []));
+
+ return [];
+ }
+ }
+
public function getClaimStatusGrouped()
{
// Fetch active claim statuses
@@ -3918,7 +4183,6 @@ class EmployeeRestController extends AdminController
return $result;
}
-
// not in use did for testing
function encrypt_for_sso(): string
{
@@ -4126,17 +4390,12 @@ class EmployeeRestController extends AdminController
try {
$response = $this->callThirdPartyAPI($post_data, 'getPreEmployeePolicyCount');
- log_message('error', 'STEP 6: API raw response: ' . $response);
+ log_message('error', 'STEP 6: API raw response: ' . json_encode($response ?? []));
- $response = json_decode($response, true);
+ $response = json_decode($response ?? '{}', true);
- if (json_last_error() !== JSON_ERROR_NONE) {
- log_message('error', 'STEP 7: JSON decoding failed: ' . json_last_error_msg());
- return 0;
- }
-
- $count = $response['data'] ?? 0;
- log_message('error', 'STEP 8: Final count extracted: ' . $count);
+ $count = $response ?? [];
+ log_message('error', 'STEP 8: Final count extracted: ' . json_encode($count ?? []));
return $count;
} catch (\Throwable $e) {
@@ -4586,4 +4845,278 @@ class EmployeeRestController extends AdminController
} catch (\Exception $e) {
}
}
+
+ public function addEmpRetailPolicy()
+ {
+ $this->myLogger->logme("error", "EMPLOYEE-RETAIL-POLICY-CONTROLLER - addEmpRetailPolicy: Received payload = " . json_encode($this->request->getJSON() ?? []));
+
+ try {
+
+ $payload = $this->request->getJSON(true);
+ $pk = $payload['retail_policy_id'] ?? null;
+ $emp_id = $payload['emp_id'] ?? null;
+
+ if (empty($emp_id)) {
+ $this->myLogger->logme("error", "addEmpRetailPolicy: emp_id is missing");
+ return $this->respond(['status' => 'failed','code' => 400,'message' => 'emp_id is required' ], 200);
+ }
+
+ if(isset($payload['policy_end_date']) && !empty($payload['policy_end_date'])){
+ $payload['policy_end_date'] = change_date_format($payload['policy_end_date'], 'd M Y', 'Y-m-d');
+ }else{
+ $payload['policy_end_date'] = null;
+ }
+
+ if(isset($payload['policy_start_date']) && !empty($payload['policy_start_date'])){
+ $payload['policy_start_date'] = change_date_format($payload['policy_start_date'], 'd M Y', 'Y-m-d');
+ }else{
+ $payload['policy_start_date'] = null;
+ }
+
+ if(empty($pk)){
+ $payload['created_by'] = $emp_id;
+ $emp_retail_policy_id = $this->employeeRetailPolicy->insert($payload);
+ }else{
+ $payload['updated_by'] = $emp_id;
+ $emp_retail_policy_id = $this->employeeRetailPolicy->where('id', $pk)->set($payload)->update();
+ }
+
+ if ($emp_retail_policy_id) {
+
+ $this->myLogger->logme("error", "addEmpRetailPolicy: Employee Retail Policy created successfully. Policy ID = " . $emp_retail_policy_id);
+
+ return $this->respond([
+ 'status' => 'success',
+ 'code' => 200,
+ 'message' => 'Employee Retail Policy created successfully',
+ 'data' => [
+ 'emp_retail_policy_id' => $emp_retail_policy_id
+ ]
+ ], 200);
+ } else {
+ $this->myLogger->logme( "error", "addEmpRetailPolicy: Failed to create Employee Retail Policy. Insert returned false" );
+ return $this->respond(['status' => 'failed','code' => 500,'message' => 'Failed to create Employee Retail Policy'], 500);
+ }
+
+ } catch (\Throwable $th) {
+
+ $this->myLogger->logme("error", "addEmpRetailPolicy: Exception occurred - " . $th->getMessage());
+ return $this->respond(['status' => 'failed','code' => 500,'message' => 'Internal server error: ' . $th->getMessage()], 500);
+ }
+ }
+
+ public function getEmpRetailPolicy($employeeData)
+ {
+ $this->myLogger->logme("error", "EMPLOYEE-REST-CONTROLLER - getEmpRetailPolicy: Given params: " . json_encode($employeeData ?? []));
+
+ try {
+
+ $emp_id = $employeeData->id ?? null;
+ $mobile_number = $employeeData->mobile ?? null;
+ $email_id = $employeeData->email_id ?? null;
+
+ $emp_retail_policy_data = [];
+ if ($emp_id != null) {
+
+ $emp_retail_policy_data = $this->employeeRetailPolicy
+ ->select("
+ employee_retail_policies.emp_id,
+ employee_retail_policies.insurer_id,
+ employee_retail_policies.policy_type_id,
+ employee_retail_policies.policy_no,
+ DATE_FORMAT(employee_retail_policies.policy_start_date, '%d-%b-%Y') as policy_start_date,
+ DATE_FORMAT(employee_retail_policies.policy_end_date, '%d-%b-%Y') as policy_end_date,
+ policy_type.policy_type,
+ policy_type.long_name as policy_type_long_name,
+ insurers.name as insurer_name,
+ insurers.short_name as insurer_short_name
+ ")
+ ->join('insurers', 'employee_retail_policies.insurer_id = insurers.id')
+ ->join('policy_type', 'employee_retail_policies.policy_type_id = policy_type.id')
+ ->where('employee_retail_policies.is_active', 1)
+ ->where('emp_id', $emp_id)
+ ->findAll();
+
+ }
+
+ $emp_retail_client_data = [];
+
+ if (!empty($mobile_number)) {
+ $emp_retail_client_data = $this->clientModel
+ ->select("
+ '{$emp_id}' AS emp_id,
+ clients.id as client_id,
+ clients.client_name as insurerd_name,
+ clients.email as insurerd_mail,
+ clients.phone as insurerd_mobile,
+ policy_transaction.id as policy_transaction_id,
+ policy_transaction.insurer_id,
+ policy_transaction.policy_type_id,
+ policy_transaction.policy_no,
+ policy_transaction.client_policy_id,
+ policy_transaction.vehicle_id,
+ vehicle.vehicle_no,
+ DATE_FORMAT(policy_transaction.policy_start_date, '%d-%b-%Y') as policy_start_date,
+ DATE_FORMAT(policy_transaction.policy_end_date, '%d-%b-%Y') as policy_end_date,
+ policy_type.policy_type,
+ policy_type.long_name as policy_type_long_name,
+ insurers.name as insurer_name,
+ insurers.short_name as insurer_short_name
+ ")
+ ->join('policy_transaction', 'policy_transaction.client_id = clients.id')
+ ->join('insurers', 'policy_transaction.insurer_id = insurers.id')
+ ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id')
+ ->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left')
+ ->where('policy_transaction.is_active', 1)
+ ->where('policy_transaction.action_type', "inception")
+ ->where('clients.is_active', 1)
+ ->where('clients.client_type', 2)
+ ->where('clients.phone IS NOT NULL')
+ ->where('clients.phone', $mobile_number)
+ ->findAll();
+ }else {
+ $emp_retail_client_data = $this->clientModel
+ ->select("
+ '{$emp_id}' AS emp_id,
+ clients.id as client_id,
+ clients.client_name as insurerd_name,
+ clients.email as insurerd_mail,
+ clients.phone as insurerd_mobile,
+ policy_transaction.id as policy_transaction_id,
+ policy_transaction.insurer_id,
+ policy_transaction.policy_type_id,
+ policy_transaction.policy_no,
+ policy_transaction.client_policy_id,
+ policy_transaction.vehicle_id,
+ vehicle.vehicle_no,
+ DATE_FORMAT(policy_transaction.policy_start_date, '%d-%b-%Y') as policy_start_date,
+ DATE_FORMAT(policy_transaction.policy_end_date, '%d-%b-%Y') as policy_end_date,
+ policy_type.policy_type,
+ policy_type.long_name as policy_type_long_name,
+ insurers.name as insurer_name,
+ insurers.short_name as insurer_short_name
+ ")
+ ->join('policy_transaction', 'policy_transaction.client_id = clients.id')
+ ->join('insurers', 'policy_transaction.insurer_id = insurers.id')
+ ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id')
+ ->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left')
+ ->where('policy_transaction.is_active', 1)
+ ->where('policy_transaction.action_type', "inception")
+ ->where('clients.is_active', 1)
+ ->where('clients.client_type', 2)
+ ->where('clients.email IS NOT NULL')
+ ->where('clients.email', $email_id)
+ ->findAll();
+ }
+
+ // print_r($this->clientModel->getLastQuery()); die;
+
+ $complete_emp_retail_policy_data = array_values(
+ array_column(
+ array_merge($emp_retail_client_data ?: [], $emp_retail_policy_data ?: []),
+ null,
+ 'policy_no'
+ )
+ );
+
+ return $complete_emp_retail_policy_data;
+ } catch (\Throwable $th) {
+
+ $errorData = [
+ 'message' => $th->getMessage(),
+ 'file' => $th->getFile(),
+ 'line' => $th->getLine(),
+ 'code' => $th->getCode(),
+ 'trace' => $th->getTraceAsString(),
+ 'trace_array' => $th->getTrace(), // full array version (optional)
+ 'function' => $th->getTrace()[0]['function'] ?? null,
+ 'class' => $th->getTrace()[0]['class'] ?? null,
+ ];
+
+ $this->myLogger->logme("error", "EMPLOYEE-REST-CONTROLLER - getEmpRetailPolicy: Exception: " . json_encode($errorData ?? []));
+
+ return [];
+ }
+ }
+
+
+
+ public function getPolicyTypeAndInsurer()
+ {
+ $policy_type_ids = [8, 37, 38, 39, 62];
+ $policy_type = $this->policyTypeModel
+ ->select('id as policy_type_id, policy_type, long_name as policy_type_long_name')
+ ->where('is_active', 1)
+ ->whereIn('id', $policy_type_ids)
+ ->findAll();
+
+ $insurer_category = ['general'];
+ $insurers = $this->insurerModel
+ ->select('id as insurer_id, name as insurer_name, short_name as insurer_short_name')
+ ->where('is_active', 1)
+ ->where('category', $insurer_category)
+ ->findAll();
+
+ return $this->respond([
+ 'status' => 'success',
+ 'code' => 200,
+ 'data' => [
+ 'insurer' => $insurers,
+ 'policy_type' => $policy_type
+ ]
+ ], 200);
+ }
+
+ public function getClaimTypeMaster($return_type = 'api')
+ {
+ $data = db_connect()->table('partner_claim_type_master')->select('id,claim_type')->where('is_active',1)->get()->getResultArray();
+
+ if (!$data) {
+ return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
+ }
+
+ if($return_type == 'api'){
+ return $this->respond(['status' => 'success', 'code' => 200, 'data' => $data]);
+ }else{
+ return $data;
+ }
+ }
+
+ public function uploadIRDocs()
+ {
+ $ticket_id = $this->request->getPost('ticket_id') ?? null;
+ $get_file_data = $this->request->getFiles('claim_docs') ?? null;
+ $get_docs_name = $this->request->getPost('claim_doc_names') ?? [];
+ $required_docs = $this->request->getPost('required_docs') ?? [];
+
+ if (is_string($get_docs_name)) {
+ $decoded = json_decode($get_docs_name, true);
+ $get_docs_name = json_last_error() === JSON_ERROR_NONE ? $decoded : [];
+ } elseif (!is_array($get_docs_name)) {
+ $get_docs_name = [];
+ }
+
+ $file_data = [];
+ if (isset($get_file_data) && !empty($get_file_data)) {
+ $file_path = WRITEPATH . 'uploads/claim_files/';
+ $file_data = multi_file_Upload($get_file_data, $file_path, $get_docs_name);
+ }
+
+ $result = $this->handleCliamFiles($file_data, $ticket_id, null, false, true);
+
+ if(!empty($result)){
+ // $this->ticketMaster->where('id', $ticket_id)->set(['required_docs', $required_docs])->update();
+ db_connect()->query(
+ "UPDATE ticket_master SET required_docs = ? WHERE id = ?",
+ [$required_docs, $ticket_id]
+ );
+ $apiServiceController = new ApiServiceController();
+ $tpaIrFilePushResponce = $apiServiceController->pushClaimFiles($ticket_id);
+ return $this->respond(['status' => true, 'code' => 200, 'message' => 'Files uploaded successfully', 'tpaIrFilePushResponce' => $tpaIrFilePushResponce], 200);
+ }else{
+ return $this->respond(['status' => false, 'code' => 400, 'message' => 'Failed to upload the file'], 200);
+ }
+ }
+
+
}
diff --git a/app/Controllers/EmployeeServiceController.php b/app/Controllers/EmployeeServiceController.php
index 28721878..9942c87b 100755
--- a/app/Controllers/EmployeeServiceController.php
+++ b/app/Controllers/EmployeeServiceController.php
@@ -1372,7 +1372,7 @@ class EmployeeServiceController extends AdminController
$existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $file['client_id'],client_branch_id: $file['client_branch_id']);
$employee_data_group_by_family = data_group_by_family($excel_data, 'excel', '', $current_column_action);
- // dd($employee_data_group_by_family);
+ // dd($employee_data_group_by_family);
foreach ($employee_data_group_by_family as $emp_id => $family)
{
@@ -1385,8 +1385,8 @@ class EmployeeServiceController extends AdminController
$existing_famility_details = transform_db_data_to_excel($existing_famility_details,$file);
// Kint::dump($existing_famility_details);
$family = array_merge($family,$existing_famility_details);
- $family = data_group_by_family($family)[ $emp_id ];// reason to call this again is bring self to first index of the array
- // dd($family);
+ $family = data_group_by_family($family, 'excel', 1)[ $emp_id ];// reason to call this again is bring self to first index of the array
+ // dd($family);
$self = current(array_filter($family, fn($r) => strtolower($r[5] ?? '') === 'self'));
$premium = (int)($self['temp']['rata_premimum'] ?? 0);
foreach ($family as &$r) if (strtolower($r[5] ?? '') !== 'self') $r['self_rata_premium'] = $premium;
@@ -1394,9 +1394,6 @@ class EmployeeServiceController extends AdminController
// Kint::dump($family);
$data = calculate_premium_new(family_data:$family,policy_terms: $policy_terms,slab_details : $slab_details,fileArr: $file, existing_units:$existing_units);
- // if($file['action'] == 'dependent_addition') {
- // $data = validatet_family_floter_rata_premium($data);
- // }
// dd($data);
$employee_data_group_by_family[$emp_id] = $data;
$this->employeesOnboardProcess(['familiy_data' => $data,'file' => $file]);
diff --git a/app/Controllers/InsuranceCommissionController.php b/app/Controllers/InsuranceCommissionController.php
index f2907bf6..6f3f60ac 100644
--- a/app/Controllers/InsuranceCommissionController.php
+++ b/app/Controllers/InsuranceCommissionController.php
@@ -10,6 +10,7 @@ class InsuranceCommissionController extends AdminController
use ResponseTrait;
private $rules = [];
+ private $myLogger;
public function __construct()
{
@@ -66,7 +67,7 @@ class InsuranceCommissionController extends AdminController
$folderName = $month . $year; // SEP2025
$insurerId = $input['insurer_id']; // 5
- $department = ucfirst(strtolower($input['department'])); // Motor, Health, Fire
+ $department = (strtolower($input['department'])); // Motor, Health, Fire
// Final Path: WRITEPATH/rules/SEP2025/5_Motor.json
$rulesPath = WRITEPATH . "uploads/commission/rules/{$folderName}/{$insurerId}_{$department}.json";
@@ -183,6 +184,8 @@ class InsuranceCommissionController extends AdminController
private function compareValues($actual, string $operator, $expected): bool
{
+ $actual = strtolower($actual);
+ $expected = strtolower($expected);
switch ($operator) {
case '==':
return $actual == $expected;
diff --git a/app/Controllers/JobWorker.php b/app/Controllers/JobWorker.php
index eadca406..43935749 100755
--- a/app/Controllers/JobWorker.php
+++ b/app/Controllers/JobWorker.php
@@ -179,6 +179,18 @@ class JobWorker extends AdminController
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\MediAssistApiController',
],
+ 'bdsDumpExcelFileFormatValidation' => [
+ 'type' => 'CC', // Handler Category
+ 'handler' => 'App\Controllers\PolicyTransactionController',
+ ],
+ 'insertBulkBdsData' => [
+ 'type' => 'CC', // Handler Category
+ 'handler' => 'App\Controllers\PolicyTransactionController',
+ ],
+ 'initiateWellnessOnboardJob' => [
+ 'type' => 'CC', // Handler Category
+ 'handler' => 'App\Controllers\EmployeeController',
+ ],
];
diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php
index 92fa8a52..a3ebe469 100644
--- a/app/Controllers/LeadsController.php
+++ b/app/Controllers/LeadsController.php
@@ -3292,6 +3292,7 @@ class LeadsController extends BaseController
'no_of_installment' => $params['no_of_installment'] ?? null,
'is_installment' => $params['is_installment'] ?? null,
'acm_id' => $params['acm_pk'] ?? null,
+ 'agreed_percentage' => $params['agreed_percentage'] ?? null,
];
if(isset($params['tpa_id']) && !empty($params['tpa_id'])){
diff --git a/app/Controllers/LogController.php b/app/Controllers/LogController.php
new file mode 100644
index 00000000..99652ff3
--- /dev/null
+++ b/app/Controllers/LogController.php
@@ -0,0 +1,259 @@
+logPath = WRITEPATH . 'logs/';
+ $this->session = session();
+ }
+
+ /**
+ * Display list of all log files
+ */
+ public function index()
+ {
+
+ $logFiles = $this->getLogFiles();
+
+ $data = [
+ 'title' => 'Log Files',
+ 'logFiles' => $logFiles
+ ];
+
+ return $this->loadLayout('logs/index', $data);
+
+ // return view('logs/index', $data);
+ }
+
+ /**
+ * Get all log files sorted by date (latest first)
+ */
+ private function getLogFiles()
+ {
+ $files = [];
+
+ if (!is_dir($this->logPath)) {
+ return $files;
+ }
+
+ $iterator = new \DirectoryIterator($this->logPath);
+
+ foreach ($iterator as $fileInfo) {
+ if ($fileInfo->isFile() && $fileInfo->getExtension() === 'log') {
+ $files[] = [
+ 'name' => $fileInfo->getFilename(),
+ 'path' => $fileInfo->getPathname(),
+ 'size' => $this->formatBytes($fileInfo->getSize()),
+ 'modified' => $fileInfo->getMTime(),
+ 'modified_date' => date('Y-m-d H:i:s', $fileInfo->getMTime())
+ ];
+ }
+ }
+
+ // Sort by modified time (latest first)
+ usort($files, function($a, $b) {
+ return $b['modified'] - $a['modified'];
+ });
+
+ return $files;
+ }
+
+ /**
+ * View specific log file content
+ */
+ public function view($filename = null)
+ {
+
+
+
+ if (!$filename) {
+ return redirect()->to('/logs')->with('error', 'No log file specified');
+ }
+
+ // Security: prevent directory traversal
+ $filename = basename($filename);
+ $filePath = $this->logPath . $filename;
+
+ if (!file_exists($filePath)) {
+ return redirect()->to('/logs')->with('error', 'Log file not found');
+ }
+
+ // ✅ extract date from filename: log-YYYY-MM-DD.log
+ if (preg_match('/log-(\d{4}-\d{2}-\d{2})\.log/', $filename, $match)) {
+ $currentDate = $match[1];
+
+ $prevDate = date('Y-m-d', strtotime('-1 day', strtotime($currentDate)));
+ $nextDate = date('Y-m-d', strtotime('+1 day', strtotime($currentDate)));
+
+ $prevFile = "log-$prevDate.log";
+ $nextFile = "log-$nextDate.log";
+
+ $prevExists = file_exists($this->logPath . $prevFile);
+ $nextExists = file_exists($this->logPath . $nextFile);
+ }
+
+ // Read log file content
+ $content = file_get_contents($filePath);
+ $logEntries = $this->parseLogFile($content);
+
+ $data = [
+ 'title' => 'View Log: ' . $filename,
+ 'filename' => $filename,
+ 'logEntries' => $logEntries,
+ 'prevFile' => $prevExists ? $prevFile : null,
+ 'nextFile' => $nextExists ? $nextFile : null,
+ 'fileSize' => $this->formatBytes(filesize($filePath)),
+ 'lastModified' => date('Y-m-d H:i:s', filemtime($filePath))
+ ];
+
+ // print_r( $data); die;
+
+ return $this->loadLayout('logs/view', $data);
+ // return view('logs/view', $data);
+ }
+
+ /**
+ * Parse log file into structured array
+ */
+
+ private function parseLogFile($content)
+ {
+ $entries = [];
+ $lines = explode("\n", $content);
+
+ $currentEntry = null;
+
+ // Messages to filter out
+ $skipPatterns = [
+ '/Session: Class initialized using/',
+ '/Session class already loaded/',
+ ];
+
+ foreach ($lines as $line) {
+ // Match CI4 log format: LEVEL - date --> message
+ if (preg_match('/^(\w+)\s*-\s*(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})\s*-->\s*(.*)$/', $line, $matches)) {
+
+ // Save previous entry if exists (before checking skip)
+ if ($currentEntry !== null) {
+ $entries[] = $currentEntry;
+ $currentEntry = null;
+ }
+
+ // Check if this message should be skipped
+ $shouldSkip = false;
+ foreach ($skipPatterns as $pattern) {
+ if (preg_match($pattern, $matches[3])) {
+ $shouldSkip = true;
+ break;
+ }
+ }
+
+ if ($shouldSkip) {
+ continue;
+ }
+
+ // Start new entry
+ $currentEntry = [
+ 'level' => $matches[1],
+ 'date' => $matches[2],
+ 'message' => $matches[3]
+ ];
+ } elseif ($currentEntry !== null && trim($line) !== '') {
+ // Continuation of previous message
+ $currentEntry['message'] .= "\n" . $line;
+ }
+ }
+
+ // Add last entry
+ if ($currentEntry !== null) {
+ $entries[] = $currentEntry;
+ }
+
+ return array_reverse($entries); // Latest first
+ }
+
+ /**
+ * Download log file
+ */
+ public function download($filename = null)
+ {
+ if (!$filename) {
+ return redirect()->to('/logs')->with('error', 'No log file specified');
+ }
+
+ $filename = basename($filename);
+ $filePath = $this->logPath . $filename;
+
+ if (!file_exists($filePath)) {
+ return redirect()->to('/logs')->with('error', 'Log file not found');
+ }
+
+ return $this->response->download($filePath, null);
+ }
+
+ /**
+ * Delete log file
+ */
+ public function delete($filename = null)
+ {
+ if (!$filename) {
+ return redirect()->to('/logs')->with('error', 'No log file specified');
+ }
+
+ $filename = basename($filename);
+ $filePath = $this->logPath . $filename;
+
+ if (!file_exists($filePath)) {
+ return redirect()->to('/logs')->with('error', 'Log file not found');
+ }
+
+ if (unlink($filePath)) {
+ return redirect()->to('/logs')->with('success', 'Log file deleted successfully');
+ } else {
+ return redirect()->to('/logs')->with('error', 'Failed to delete log file');
+ }
+ }
+
+ /**
+ * Format bytes to human readable format
+ */
+ private function formatBytes($bytes, $precision = 2)
+ {
+ $units = ['B', 'KB', 'MB', 'GB', 'TB'];
+
+ $bytes = max($bytes, 0);
+ $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
+ $pow = min($pow, count($units) - 1);
+
+ $bytes /= pow(1024, $pow);
+
+ return round($bytes, $precision) . ' ' . $units[$pow];
+ }
+
+ /**
+ * Clear all log files
+ */
+ public function clearAll()
+ {
+ $logFiles = $this->getLogFiles();
+ $deleted = 0;
+
+ foreach ($logFiles as $file) {
+ if (unlink($file['path'])) {
+ $deleted++;
+ }
+ }
+
+ return redirect()->to('/logs')->with('success', $deleted . ' log file(s) deleted successfully');
+ }
+}
\ No newline at end of file
diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php
index d2ce1329..fec5dc4e 100755
--- a/app/Controllers/MasterController.php
+++ b/app/Controllers/MasterController.php
@@ -1980,6 +1980,7 @@ class MasterController extends AdminController
'files' => WRITEPATH . 'uploads/commission/files',
'rules' => WRITEPATH . 'uploads/commission/rules',
'claim_sample_forms' => ROOTPATH . 'public/claim_sample_forms/',
+ 'bds_dump_excel' => WRITEPATH . 'uploads/bds_dump_excel/',
];
foreach ($folders as $folderName => $folderPath) {
diff --git a/app/Controllers/MediAssistApiController.php b/app/Controllers/MediAssistApiController.php
index 621a187f..bc1cbdfa 100644
--- a/app/Controllers/MediAssistApiController.php
+++ b/app/Controllers/MediAssistApiController.php
@@ -12,15 +12,17 @@ use CodeIgniter\API\ResponseTrait;
class MediAssistApiController extends BaseController
{
- use ResponseTrait;
+ use ResponseTrait;
+ protected $db;
- public function index()
+ public function __construct()
{
- //
+ $this->db = \Config\Database::connect();
}
- public function SubmitClaim ($claimId = null){
+ public function SubmitClaim ($claimId = null)
+ {
helper('api');
@@ -34,14 +36,10 @@ class MediAssistApiController extends BaseController
'Password:'. getenv('MEDI_ASSIST_API_PASSWORD').'',
];
-
- //Prepare body data
- $db = \Config\Database::connect();
-
//Prepare body data
- $db = \Config\Database::connect();
+
// Fetch the data from DB
- $data = $db->table('ticket_master tm')
+ $data = $this->db->table('ticket_master tm')
->select('
tm.id,
tm.emp_mobile as mobileNo,
@@ -52,7 +50,7 @@ class MediAssistApiController extends BaseController
tm.claim_amount as claimAmount,
cp.policy_no as policyNo,
e.id as empId,
- e.emp_code as memberId,
+ tm.tpa_no as memberId,
tn.note as disease,
tn.note as reasonForHospitalization,
cf.url as fileName,
@@ -126,6 +124,8 @@ class MediAssistApiController extends BaseController
// ]
// ];
+ log_message('error', 'TPA CLAIM PUSH | claimId: '.$claimId.' | payload: '.json_encode($body));
+
$response = call_third_party_api($url, $method, $headers, $body);
@@ -143,20 +143,21 @@ class MediAssistApiController extends BaseController
log_message('error', 'TPA CLAIM PUSH SUCCESS | claimId: '.$claimId.' | claimReferenceNo: '.$claimRef);
- $db->table('ticket_master')
+ $this->db->table('ticket_master')
->where('id',$claimId)
->update([ 'tpa_claim_push_reference_no' => $claimRef ]);
return;
} else {
- log_message('error', 'TPA CLAIM PUSH SUCCESS BUT claimReferenceNo EMPTY | claimId: '.$claimId.' | response: '.json_encode($response));
+ log_message('error', 'TPA CLAIM PUSH API SUCCESS BUT claimReferenceNo EMPTY | claimId: '.$claimId.' | response: '.json_encode($response));
return;
}
}
- public function EcardRequest ($employeeId = null, $policyNo = null){
+ public function EcardRequest ($employeeId = null, $policyNo = null)
+ {
helper('api');
@@ -200,7 +201,6 @@ class MediAssistApiController extends BaseController
}
-
public function GetBenefDetails($requestData)
{
helper('api');
@@ -223,7 +223,7 @@ class MediAssistApiController extends BaseController
$client_policy_id = $requestData['client_policy_id'] ?? null;
if (empty($policyNo)) {
- log_message('error', 'GetBenefDetails: policy_no missing in request');
+ log_message('error', 'TPA ID PULL | policy_no missing in request');
if($function_calling_type == "job"){
return ['status' => false, 'message' => 'policy_no required'];
}else{
@@ -232,7 +232,7 @@ class MediAssistApiController extends BaseController
}
if (empty($client_policy_id)) {
- log_message('error', 'GetBenefDetails: client_policy_id missing in request');
+ log_message('error', 'TPA ID PULL | client_policy_id missing in request');
if($function_calling_type == "job"){
return ['status' => false, 'message' => 'client_policy_id required'];
}else{
@@ -240,8 +240,7 @@ class MediAssistApiController extends BaseController
}
}
- log_message('error', "GetBenefDetails called for policy_no: {$policyNo}");
- log_message('error', "GetBenefDetails called for client_policy_id: {$client_policy_id}");
+ log_message('error', "TPA ID PULL | called for policy_no: {$policyNo} , client_policy_id: {$client_policy_id}");
$employeePolicyModel = new EmployeePolicyModel();
$employeePolicyData = $employeePolicyModel
@@ -260,7 +259,7 @@ class MediAssistApiController extends BaseController
->findAll();
if (empty($employeePolicyData)) {
- log_message('error', 'GetBenefDetails: employeePolicyData is empty');
+ log_message('error', 'TPA ID PULL FAILED | employeePolicyData is empty (tpa_id IS NULL from nhance) for this tpa id pull request');
if($function_calling_type == "job"){
return ['status' => false, 'message' => 'employeePolicyData not found'];
}else{
@@ -284,8 +283,8 @@ class MediAssistApiController extends BaseController
"employeeId" => ""
];
- log_message('error', "GetBenefDetails API Request (startIndex={$startIndex}): " . json_encode($body));
- log_message('error', "GetBenefDetails API parems " . json_encode([$url, $method, $headers, $body]));
+ log_message('error', "TPA ID PULL | API Request (startIndex={$startIndex}): " . json_encode($body));
+ log_message('error', "TPA ID PULL | API parems " . json_encode([$url, $method, $headers, $body]));
$response = call_third_party_api($url, $method, $headers, $body);
@@ -300,7 +299,7 @@ class MediAssistApiController extends BaseController
log_message('error', "Failed to update file table status.");
}
- log_message('error', 'GetBenefDetails API failed: ' . json_encode($response));
+ log_message('error', 'TPA ID PULL API FAILED | API failed: ' . json_encode($response));
if($function_calling_type == "job"){
return ['status' => false, 'message' => 'API call failed', 'data' => $response];
@@ -312,7 +311,7 @@ class MediAssistApiController extends BaseController
$data = $response['data'] ?? [];
if (!isset($data['benefDetails'])) {
- log_message('error', "GetBenefDetails: 'benefDetails' missing in API response: " . json_encode($data));
+ log_message('error', "TPA ID PULL FAILED |: 'benefDetails' missing in API response: " . json_encode($data));
break;
}
@@ -328,33 +327,13 @@ class MediAssistApiController extends BaseController
} while ($startIndex < $totalCount);
// now update DB
- $db = \Config\Database::connect();
$updated = 0;
-
$employee_policy_ids = [];
foreach ($employeePolicyData as $policy_data) {
- foreach ($allBenef as $row) {
- // log_message(
- // "error",
- // "POLICY MATCH CHECK: " . json_encode([
- // 'policy_data' => [
- // 'name' => $policy_data['name'] ?? null,
- // 'emp_code' => $policy_data['emp_code'] ?? null,
- // 'relationship' => $policy_data['relationship'] ?? null,
- // 'gender' => $policy_data['gender'] ?? null,
- // 'dob' => $policy_data['dob'] ?? null,
- // ],
- // 'row_data' => [
- // 'benefName' => $row['benefName'] ?? null,
- // 'priBenefEmpCode' => $row['priBenefEmpCode'] ?? null,
- // 'relName' => $row['relName'] ?? null,
- // 'benefSex' => $row['benefSex'] ?? null,
- // 'benefDOB' => $row['benefDOB'] ?? null,
- // 'benefDOB_fmt' => change_date_format($row['benefDOB'],'d/m/Y H:i:s') ?? null,
- // ],
- // ])
- // );
+ $hasMatchForThisPolicy = false;
+
+ foreach ($allBenef as $row) {
if (
strtolower(trim($policy_data['name'] ?? '')) == strtolower(trim($row['benefName'] ?? '')) &&
@@ -363,32 +342,53 @@ class MediAssistApiController extends BaseController
($policy_data['gender'] ?? '') == ($row['benefSex'] ?? '') &&
($policy_data['dob'] ?? '') == (change_date_format($row['benefDOB'], 'd/m/Y H:i:s') ?? '')
) {
+
+ $hasMatchForThisPolicy = true;
- log_message('error', "✅ Match found: emp_code={$row['priBenefEmpCode']} policy={$row['polNo']}");
+ // log_message('error', "✅ Match found: emp_code={$row['priBenefEmpCode']} policy={$row['polNo']}");
$sql = "UPDATE employee_polices
SET tpa_id = ?
WHERE id = ?";
- $db->query($sql, [$row['benefMediAssistID'], $policy_data['emp_policy_id']]);
+ $this->db->query($sql, [$row['benefMediAssistID'], $policy_data['emp_policy_id']]);
// for e-card send
if(strtolower(trim($policy_data['relationship'])) == 'self'){
$employee_policy_ids[] = $policy_data['emp_policy_id'];
}
- if ($db->affectedRows() > 0) {
+ if ($this->db->affectedRows() > 0) {
$updated++;
log_message('error', "✅ Updated tpa_id={$row['benefMediAssistID']} for emp_code={$row['priBenefEmpCode']} policy={$row['polNo']}");
} else {
log_message('error', "⚠️ No update (already set or not matched) for emp_code={$row['priBenefEmpCode']} policy={$row['polNo']}");
}
- }else{
- log_message('error', "❌ Not matched: emp_code={$row['priBenefEmpCode']} policy={$row['polNo']}");
}
+
}
+
+ // Handle NO MATCH for this policy
+ if (!$hasMatchForThisPolicy) {
+
+ $nhanceSideData = [
+ 'name' => $policy_data['name'] ?? null,
+ 'emp_code' => $policy_data['emp_code'] ?? null,
+ 'relationship' => $policy_data['relationship'] ?? null,
+ 'gender' => $policy_data['gender'] ?? null,
+ 'dob' => $policy_data['dob'] ?? null,
+ ];
+
+ log_message(
+ 'error',
+ "❌ No match for Nhance = " . json_encode($nhanceSideData)
+ );
+ }
+
}
+
+
// send e-card
if(!empty($employee_policy_ids)){
log_message('error', "sendMailForDownloadingECard JOB PUSHED.");
@@ -405,7 +405,7 @@ class MediAssistApiController extends BaseController
}
- log_message('error', "GetBenefDetails completed. Total fetched={$totalCount}, updated={$updated}");
+ log_message('error', "TPA ID PULL SUCCESS | completed. Total fetched={$totalCount}, updated={$updated}");
if($function_calling_type == "job"){
return [
@@ -454,94 +454,271 @@ class MediAssistApiController extends BaseController
}
}
-
- // public function GetBenefDetails (){
-
- // $postData = $this->request->getJSON(true);
-
- // helper('api');
-
- // $url = ''. getenv('MEDI_ASSIST_API_BASE_URL').'/GetBenefDetails';
- // $method = 'POST';
-
- // $headers = [
- // 'Content-Type: application/json',
- // 'Username:'. getenv('MEDI_ASSIST_API_USERNAME').'',
- // 'Password:'. getenv('MEDI_ASSIST_API_PASSWORD').'',
- // ];
-
- // $body = [
- // "policyNo" => $$postData['policy_no'],
- // "startDate" => "",
- // "endDate" => "",
- // "isDeActivedata" => false,
- // "startIndex" => 0,
- // "range" => 100 ,
- // "employeeId" => ""
- // ];
-
- // // $body = [
- // // "policyNo" => "97000063250400000031",
- // // "startDate" => "",
- // // "endDate" => "",
- // // "isDeActivedata" => false,
- // // "startIndex" => 0,
- // // "range" => 100 ,
- // // "employeeId" => ""
- // // ];
-
- // $response = call_third_party_api($url, $method, $headers, $body);
-
-
- // if($response['status'] != true){
- // return $this->response->setJSON([
- // 'status' => false,
- // 'message' => 'failed.',
- // 'data' => $response
- // ]);
- // }
-
- // return $this->response->setJSON($response);
-
- // }
-
- public function ClaimDetail (){
-
-
+ public function ClaimDetail($claimId = null) // 585 this id for test
+ {
helper('api');
- $url = ''. getenv('MEDI_ASSIST_API_BASE_URL').'/ClaimDetail';
+ $url = getenv('MEDI_ASSIST_API_BASE_URL_CLAIMSTATUS');
$method = 'POST';
$headers = [
'Content-Type: application/json',
- 'Username:'. getenv('MEDI_ASSIST_API_USERNAME').'',
- 'Password:'. getenv('MEDI_ASSIST_API_PASSWORD').'',
+ 'Username:' . getenv('MEDI_ASSIST_API_USERNAME'),
+ 'Password:' . getenv('MEDI_ASSIST_API_PASSWORD'),
];
- $body = [
- "policyNo" => "97000063250400000031",
- "startDate" => "",
- "endDate" => "",
- "employeeCode" => "CITPL120193",
- "memberID" => "",
- "claimNo" => "",
- "claimRefNo" => ""
+ // Fetch ticket master details
+ $ticket = $this->db->table('ticket_master tm')
+ ->select("
+ tm.id,
+ tm.tpa_no as memberId,
+ tm.tpa_claim_push_reference_no as claimRefNo,
+ cp.policy_no as policyNo,
+ cp.policy_start_date as startDate,
+ cp.policy_end_date as endDate,
+ e.emp_code as employeeCode
+ ")
+ ->join('employees e', 'e.id = tm.emp_id', 'left')
+ ->join('client_policy cp', 'tm.client_policy_id = cp.id', 'left')
+ ->where('tm.id', $claimId)
+ ->get()
+ ->getRowArray();
+
+ if (!$ticket) {
+ return $this->response->setJSON(['status' => false,'message' => 'Invalid Claim ID' ]);
+ }
+
+ // REQUEST BODY
+ if($ticket['claimRefNo'] != null)
+ {
+ $body = [
+ "policyNo" => $ticket['policyNo'] ?? "",
+ "startDate" => "",
+ "endDate" => "",
+ "employeeCode" => $ticket['employeeCode'] ?? "",
+ "memberID" => "",
+ "claimNo" => "",
+ "claimRefNo" => $ticket['claimRefNo'] ?? "",
+ ];
+
+ }else{
+
+ $body = [
+ "policyNo" => $ticket['policyNo'] ?? "",
+ "startDate" => "",
+ "endDate" => "",
+ "employeeCode" => $ticket['employeeCode'] ?? "",
+ "memberID" => "",
+ "claimNo" => "",
+ "claimRefNo" => "",
+ ];
+
+ }
+
+ // dd($body);
+
+ // $body = [
+ // "policyNo" => "97000063250400000031",
+ // "startDate" => "31/08/2025",
+ // "endDate" => "01/09/2025",
+ // "employeeCode" => "CITPL120193",
+ // "memberID" => "",
+ // "claimNo" => "",
+ // "claimRefNo" => "HOSP4078102577_16092025111030"
+ // ];
+
+ // CALL API
+ $response = call_third_party_api($url, $method, $headers, $body);
+
+ if ($response['status'] != true || empty($response['data']['claimsData'][0])) {
+ log_message('error', 'CLAIM STATUS FAILED | for ticket ID: ' . $claimId.' | response: '.json_encode($response));
+
+ return $this->response->setJSON([
+ 'status' => false,
+ 'message' => 'API call failed.',
+ 'data' => $response
+ ]);
+ }
+
+ // Extract claim status
+ $claimData = $response['data']['claimsData'][0];
+ $currentStatus = $claimData['claim_Current_Status'] ?? '';
+ $tpa_claim_no = $claimData['tpA_CLAIM_NO'] ?? '';
+
+ // VALID STATUS LIST
+ $validStatuses = [
+ "Claim Received" => 1,
+ "In Progress" => 5,
+ "Processed" => 11,
+ "Claim Paid" => 11,
+ "Denied" => 13,
+ "Cancelled" => 13,
+
+ "Information Awaited" => 4,
+ "Confirmation Awaited" => 4,
+ "Information Awaited Reminder" => 4,
+ "Information Awaited Final Reminder" => 4,
+ "Insurer Concurrence Awaited" => 6,
+ "Closed" => 12,
+
+ "Physical Documents Awaited" => 9,
+ "Processed - Payment Initiated" => 10,
+ "Processed - Transaction Failed" => 10,
+ "Processed - Account Details Updated" => 10,
+ "Processed - Debit Note Raised With Insurer for Payment"=> 10,
+ "Processed - Payment Initiated by Insurer" => 10,
+ "Payment - Refunded to Insurer" => 14,
+ "Processed - Processing Payment" => 10,
+ "Processed - Physical Documents Awaited" => 9,
+
+ // Extra Mappings (based on your DB list)
+ "NON ID" => 1,
+ "ID NOT GENERATED" => 2,
+ "CDA" => 3,
+ "REJECTED" => 8,
+ "APPROVED" => 9,
+ "PAYMENT INITIATED" => 10,
+ "SETTLED" => 11,
+ "RETURNED" => 14,
+ "UNDER PROCESS - TPA" => 61,
+ "DENIAL REVIEW AWAITED" => 66,
+ ];
+
+
+ // Maping tpa claim status with local claim Status
+ if (isset($validStatuses[$currentStatus]))
+ {
+ $updateArray = ['claim_status_id' => $validStatuses[$currentStatus] , 'tpa_claim_status' => $currentStatus , 'tpa_claim_id' => $tpa_claim_no , 'updated_at' => date('Y-m-d H:i:s')];
+ }else{
+ $updateArray = ['tpa_claim_status' => $currentStatus , 'tpa_claim_id' => $tpa_claim_no , 'updated_at' => date('Y-m-d H:i:s')];
+ }
+
+ // UPDATE ticket_master
+ $this->db->table('ticket_master')->where('id', $claimId)->update($updateArray);
+
+ // LOG UPDATE
+ log_message('info', "CLAIM STATUS SUCCESS | Updated ticket ID $claimId with claim status: $currentStatus");
+
+ return $this->response->setJSON([
+ 'status' => true,
+ 'message' => 'Claim status updated.',
+ 'updated_status' => $currentStatus,
+ 'api_response' => $response
+ ]);
+ }
+
+ public function IRSubmission($claimId = null) // 585 this id for test
+ {
+ log_message('info', "IRSubmission INIT for ticket_id={$claimId}");
+
+ // 1. FETCH TICKET DETAILS
+ $ticket = $this->db->table('ticket_master tm')
+ ->select("
+ tm.id,
+ tm.tpa_no as memberId,
+ tm.tpa_claim_push_reference_no as claimRefNo,
+ tm.tpa_claim_id as ClaimID,
+ cp.policy_no as policyNo,
+ cp.policy_start_date as startDate,
+ cp.policy_end_date as endDate,
+ e.emp_code as employeeCode
+ ")
+ ->join('employees e', 'e.id = tm.emp_id', 'left')
+ ->join('client_policy cp', 'tm.client_policy_id = cp.id', 'left')
+ ->where('tm.id', $claimId)
+ ->get()
+ ->getRowArray();
+
+ if (!$ticket || empty($ticket['ClaimID'])) {
+ log_message('error', "IRSubmission FAILED → ClaimID NOT FOUND for ticket_id={$claimId}");
+
+ return [
+ 'status' => false,
+ 'message' => "ClaimID not found for ticket {$claimId}"
+ ];
+ }
+
+ // 2. FETCH IR ATTACHMENTS
+ $fileData = $this->db->table('claim_files f')
+ ->where('f.ticket_id', $claimId)
+ ->where('f.docs_for_ir', 1)
+ ->get()
+ ->getResultArray();
+
+
+ $Attachments = [];
+
+ if (count($fileData)) {
+ foreach ($fileData as $file) {
+
+ if (!empty($file['url'])) {
+ $filename = basename($file['url']);
+ $fileDir = WRITEPATH . 'uploads/claim_files/' . $filename;
+
+ if (file_exists($fileDir)) {
+ $downloadUrl = base_url('fileDownload?file_path=') . $fileDir;
+ } else {
+ $downloadUrl = "";
+ log_message('error', "File NOT FOUND on server → {$fileDir}");
+ }
+
+ log_message('info', "IRSubmission Attachment Ready: {$filename} | URL={$downloadUrl}");
+
+ $Attachments[] = [
+ "AttachmentName" => $filename,
+ "AttachmentPath" => $downloadUrl
+ ];
+ } else {
+ log_message('error', "IRSubmission Missing File URL → file_id={$file['id']}");
+ }
+ }
+ }
+
+ // 3. API REQUEST BODY
+ $body = [
+ "ClaimID" => $ticket['ClaimID'],
+ "Attachments" => $Attachments
+ ];
+
+ log_message('info', "IRSubmission Request Body => " . json_encode($body));
+
+ // 4. SEND API CALL
+ helper('api');
+ // 'https://apiintegration.mediassist.in/ClaimAPIServiceUAT/Claim/IRSubmission' // dev url
+ $url = env('MEDI_ASSIST_API_BASE_URL_IRSUBMISSION');
+ $method = 'POST';
+
+ $headers = [
+ 'Content-Type: application/json',
+ 'Username:' . getenv('MEDI_ASSIST_API_USERNAME'),
+ 'Password:' . getenv('MEDI_ASSIST_API_PASSWORD'),
];
$response = call_third_party_api($url, $method, $headers, $body);
+ log_message('info', "IRSubmission API Response => " . json_encode($response));
- if($response['status'] != true){
- return $this->response->setJSON([
- 'status' => false,
- 'message' => 'failed.',
- 'data' => $response
- ]);
+ // 5. HANDLE RESPONSE
+ if (!$response['status']) {
+ log_message(
+ 'error',
+ "IRSubmission FAILED for ClaimID={$ticket['ClaimID']} → Response=" . json_encode($response)
+ );
+
+ return [
+ 'status' => false,
+ 'message' => 'IR Submission failed',
+ 'data' => $response
+ ];
}
- return $this->response->setJSON($response);
+ log_message('info', "IRSubmission SUCCESS → ClaimID={$ticket['ClaimID']}");
+ return [
+ 'status' => true,
+ 'message' => 'IR Submitted successfully',
+ 'data' => $response
+ ];
}
@@ -549,6 +726,36 @@ class MediAssistApiController extends BaseController
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
public function HospitalNetwork (){
$postData = $this->request->getJSON(true);
@@ -629,44 +836,7 @@ class MediAssistApiController extends BaseController
}
- public function IRSubmission (){
- $postData = $this->request->getJSON(true);
-
- helper('api');
-
- // $url = ''. getenv('MEDI_ASSIST_API_BASE_URL').'/ClaimAPIServiceUAT/Claim/IRSubmission';
- $url = "https://apiintegration.mediassist.in/ClaimAPIServiceUAT/Claim/IRSubmission";
- $method = 'POST';
-
- $headers = [
- 'Content-Type: application/json',
- 'Username:' .'NhanceUsr',
- 'Password:' .'NhU$p&Cc5wGQbr2',
- ];
-
- $body = [
- "ClaimID" => "134431104",
- "Attachments" => [
- "AttachmentName" => "Test.pdf",
- "AttachmentPath" => "https://apiintegration.mediassist.in/IntegrationEcard/DownloadEcard/4078613742/Senthil Kumar P/556/5386"
- ]
- ];
-
- $response = call_third_party_api($url, $method, $headers, $body);
-
-
- if($response['status'] != true){
- return $this->response->setJSON([
- 'status' => false,
- 'message' => 'failed.',
- 'data' => $response
- ]);
- }
-
- return $this->response->setJSON($response);
-
- }
public function fileDownload()
diff --git a/app/Controllers/NotificationController.php b/app/Controllers/NotificationController.php
index 98067fa9..cc13b100 100755
--- a/app/Controllers/NotificationController.php
+++ b/app/Controllers/NotificationController.php
@@ -217,40 +217,44 @@ class NotificationController extends AdminController
}
// This function for sent a mail for testing
- public function sentTestMail($template_id, $test_mail)
+ // keep watching this
+ public function sentTestMail($template_id, $test_mail, $string_flag)
{
$notification_data = $this->notificationModel->where('id', $template_id)->first();
+
+
+ if(empty($notification_data)) {
+ return $this->respond(['status' => false,'code' => 200, 'message' => 'Notification Template not enabled']);
+ }
+
$client_data = $this->clientModel->where('id', $notification_data['client_id'])->where('is_active', 1)->first();
- if(!empty($notification_data)){
-
- $params = [
+ $params = [
'client_data' => $client_data,
'notification_data' => $notification_data,
'test_mail' => $test_mail
- ];
+ ];
- $testMailData = sendMailNotification::sendMailNotificationForTesting($notification_data['template_name'], $params);
- // print_r($testMailData); die;
- if (!empty($testMailData)) {
+ $testMailData = sendMailNotification::sendMailNotificationForTesting($notification_data['template_name'], $params);
- $mail_send_return1 = MailHelper::send_email($testMailData);
- $this->myLogger->logme("info", $mail_send_return1);
- $this->myLogger->logme("info", $mail_send_return1);
+ if(empty($testMailData)) {
+ return $this->respond(['status' => false,'code' => 200, 'message' => 'Test Mail Data Does Not Exist']);
+ }
- return $this->respond(['status' => true,'code' => 200, 'respond' => json_decode($mail_send_return1)]);
-
- }else{
-
- return $this->respond(['status' => false,'code' => 200, 'message' => 'Test Mail Data Does Not Exist']);
- }
- }else{
-
- return $this->respond(['status' => false,'code' => 200, 'message' => 'Notification Template not enabled']);
+ if($string_flag == "send"){
+ $mail_send_return1 = MailHelper::send_email($testMailData);
+ $this->myLogger->logme("info", $mail_send_return1);
+ return $this->respond(['status' => true,'code' => 200, 'respond' => json_decode($mail_send_return1)]);
+ }
+ if($string_flag == "preview"){
+ return $this->respond([
+ 'status' => true,
+ 'code' => 200,
+ 'content' => $testMailData
+ ]);
}
}
-
public function sendCommonTestMail()
@@ -371,7 +375,7 @@ class NotificationController extends AdminController
// Insert file attachment record
if ($this->MailAttachmentModel->insert($data)) {
// Retrieve active attachments to return in response
- $attachment_data = $this->MailAttachmentModel->where('is_active', 1)->findAll();
+ $attachment_data = $this->MailAttachmentModel->where('notification_id', $find_notification['id'])->where('is_active', 1)->findAll()??[];
return $this->respond([
'status' => true,
'code' => 200,
diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php
index e970d9b5..66798ee5 100644
--- a/app/Controllers/PolicyTransactionController.php
+++ b/app/Controllers/PolicyTransactionController.php
@@ -37,6 +37,8 @@
use App\Helpers\MailHelper;
use App\Helpers\ExcelSanitizeHelper;
use App\Models\NhanceBranchModel;
+ use App\Models\BDSDumpModel;
+ use App\Models\VehicleModel;
use Exception;
class PolicyTransactionController extends BaseController
@@ -71,6 +73,10 @@
protected $coShareStmtDetailsModel;
protected $BdsPlacementModel;
protected $nhanceBranchModel;
+ protected $bdsDumpModel;
+ protected $vehicleModel;
+ protected $bds_bulk_upload_excel_file_column;
+
public function __construct()
{
@@ -103,12 +109,440 @@
$this->coShareStmtDetailsModel = new COShareStmtDetailsModel();
$this->BdsPlacementModel = new BdsPlacementModel();
$this->nhanceBranchModel = new NhanceBranchModel();
+ $this->bdsDumpModel = new BDSDumpModel();
+ $this->vehicleModel = new VehicleModel();
$this->invoiceStatus = [
'pending' => 'Pending',
'generated' => 'Generated',
'sent' => 'Sent',
'payment_received' => 'Payment
Received',
];
+
+ $this->bds_bulk_upload_excel_file_column = [
+
+ 'sno' => [
+ 'col_idx' => 0,
+ 'col_cell_name' => 'A',
+ 'col_name' => 'S.No.',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'nhance_branch' => [
+ 'col_idx' => 1,
+ 'col_cell_name' => 'B',
+ 'col_name' => 'Nhance Branch',
+ 'is_mandatory' => true,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_nhance_branch',
+ 'params' => ['row', 'nhance_branch_data']
+ ],
+
+ 'vehicle_no' => [
+ 'col_idx' => 2,
+ 'col_cell_name' => 'C',
+ 'col_name' => 'Vehicle No',
+ 'is_mandatory' => true,
+ 'data_type' => 'vehicle',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_rto_data',
+ 'params' => ['row', 'rto_master']
+ ],
+
+ 'vehicle_type' => [
+ 'col_idx' => 3,
+ 'col_cell_name' => 'D',
+ 'col_name' => 'Vehicle Type',
+ 'is_mandatory' => true,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_vehicle_type',
+ 'params' => ['row', 'vehicle_type']
+ ],
+
+ 'policy_no' => [
+ 'col_idx' => 4,
+ 'col_cell_name' => 'E',
+ 'col_name' => 'Policy No',
+ 'is_mandatory' => true,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_policy_no',
+ 'params' => ['row', 'pt_data']
+ ],
+
+ 'insured_name' => [
+ 'col_idx' => 5,
+ 'col_cell_name' => 'F',
+ 'col_name' => 'Insured Name',
+ 'is_mandatory' => true,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'insured_email' => [
+ 'col_idx' => 6,
+ 'col_cell_name' => 'G',
+ 'col_name' => 'Insured Email',
+ 'is_mandatory' => true,
+ 'data_type' => 'email',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'insurer' => [
+ 'col_idx' => 7,
+ 'col_cell_name' => 'H',
+ 'col_name' => 'Insurer',
+ 'is_mandatory' => true,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_insurer_exist',
+ 'params' => ['row', 'insurer_data']
+ ],
+
+ 'insurer_branch' => [
+ 'col_idx' => 8,
+ 'col_cell_name' => 'I',
+ 'col_name' => 'Insurer Branch',
+ 'is_mandatory' => true,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_insurer_branch_exist',
+ 'params' => ['row', 'insurer_branch_data', 'insurers']
+ ],
+
+ 'policy_issue_date' => [
+ 'col_idx' => 9,
+ 'col_cell_name' => 'J',
+ 'col_name' => 'Policy Issue Date',
+ 'is_mandatory' => true,
+ 'data_type' => 'date',
+ 'format' => 'd/M/Y',
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'policy_start_date' => [
+ 'col_idx' => 10,
+ 'col_cell_name' => 'K',
+ 'col_name' => 'Policy Start Date',
+ 'is_mandatory' => true,
+ 'data_type' => 'date',
+ 'format' => 'd/M/Y',
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'policy_end_date' => [
+ 'col_idx' => 11,
+ 'col_cell_name' => 'L',
+ 'col_name' => 'Policy End Date',
+ 'is_mandatory' => true,
+ 'data_type' => 'date',
+ 'format' => 'd/M/Y',
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'revenue_type' => [
+ 'col_idx' => 12,
+ 'col_cell_name' => 'M',
+ 'col_name' => 'Revenue Type',
+ 'is_mandatory' => true,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => ['NA', 'EA', 'EANR'],
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'sales_generated_by' => [
+ 'col_idx' => 13,
+ 'col_cell_name' => 'N',
+ 'col_name' => 'Sales Generated By',
+ 'is_mandatory' => true,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_user_exist',
+ 'params' => ['row', 'col_key', 'user_data']
+ ],
+
+ 'serviced_by' => [
+ 'col_idx' => 14,
+ 'col_cell_name' => 'O',
+ 'col_name' => 'Serviced By',
+ 'is_mandatory' => true,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_user_exist',
+ 'params' => ['row', 'col_key', 'user_data']
+ ],
+
+ 'agent_code' => [
+ 'col_idx' => 15,
+ 'col_cell_name' => 'P',
+ 'col_name' => 'Agent Code',
+ 'is_mandatory' => true,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_agent_exist',
+ 'params' => ['row', 'agent_data']
+ ],
+
+ 'base_premium' => [
+ 'col_idx' => 16,
+ 'col_cell_name' => 'Q',
+ 'col_name' => 'Base Premium',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'non_commission_premium_amount' => [
+ 'col_idx' => 17,
+ 'col_cell_name' => 'R',
+ 'col_name' => 'Non commission permium Amount',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'tp_premium' => [
+ 'col_idx' => 18,
+ 'col_cell_name' => 'S',
+ 'col_name' => 'TP Premium',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'igst' => [
+ 'col_idx' => 19,
+ 'col_cell_name' => 'T',
+ 'col_name' => 'IGST',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_gst_percentage',
+ 'params' => ['row']
+ ],
+
+ 'cgst' => [
+ 'col_idx' => 20,
+ 'col_cell_name' => 'U',
+ 'col_name' => 'CGST',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_gst_percentage',
+ 'params' => ['row']
+ ],
+
+ 'sgst' => [
+ 'col_idx' => 21,
+ 'col_cell_name' => 'V',
+ 'col_name' => 'SGST',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_gst_percentage',
+ 'params' => ['row']
+
+ ],
+
+ 'stamp_duty' => [
+ 'col_idx' => 22,
+ 'col_cell_name' => 'W',
+ 'col_name' => 'Stamp Duty',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ // 'total' => [
+ // 'col_idx' => 23,
+ // 'col_cell_name' => 'X',
+ // 'col_name' => 'Total',
+ // 'is_mandatory' => false,
+ // 'data_type' => '',
+ // 'format' => null,
+ // 'allowed_values' => null,
+ // 'custom' => null,
+ // 'params' => null
+ // ],
+
+ 'agreed_amount' => [
+ 'col_idx' => 23,
+ 'col_cell_name' => 'X',
+ 'col_name' => 'Agreed Amount',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'agreed_bp_percentage' => [
+ 'col_idx' => 24,
+ 'col_cell_name' => 'Y',
+ 'col_name' => 'Agreed BP Percentage',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'agreed_tp_percentage' => [
+ 'col_idx' => 25,
+ 'col_cell_name' => 'Z',
+ 'col_name' => 'Agreed TP Percentage',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ // 'actual_bp_amount' => [
+ // 'col_idx' => 27,
+ // 'col_cell_name' => 'AB',
+ // 'col_name' => 'Actual BP Amount',
+ // 'is_mandatory' => false,
+ // 'data_type' => '',
+ // 'format' => null,
+ // 'allowed_values' => null,
+ // 'custom' => null,
+ // 'params' => null
+ // ],
+
+ // 'actual_tp_amount' => [
+ // 'col_idx' => 28,
+ // 'col_cell_name' => 'AC',
+ // 'col_name' => 'Actual TP Amount',
+ // 'is_mandatory' => false,
+ // 'data_type' => '',
+ // 'format' => null,
+ // 'allowed_values' => null,
+ // 'custom' => null,
+ // 'params' => null
+ // ],
+
+ // 'actual_bp_percentage' => [
+ // 'col_idx' => 29,
+ // 'col_cell_name' => 'AD',
+ // 'col_name' => 'Actual BP Percentage',
+ // 'is_mandatory' => false,
+ // 'data_type' => '',
+ // 'format' => null,
+ // 'allowed_values' => null,
+ // 'custom' => null,
+ // 'params' => null
+ // ],
+
+ // 'actual_tp_percentage' => [
+ // 'col_idx' => 30,
+ // 'col_cell_name' => 'AE',
+ // 'col_name' => 'Actual TP Percentage',
+ // 'is_mandatory' => false,
+ // 'data_type' => '',
+ // 'format' => null,
+ // 'allowed_values' => null,
+ // 'custom' => null,
+ // 'params' => null
+ // ],
+
+ // 'actual_bp_brokerage_amount' => [
+ // 'col_idx' => 31,
+ // 'col_cell_name' => 'AF',
+ // 'col_name' => 'Actual BP Brokerage Amount',
+ // 'is_mandatory' => false,
+ // 'data_type' => '',
+ // 'format' => null,
+ // 'allowed_values' => null,
+ // 'custom' => null,
+ // 'params' => null
+ // ],
+
+ // 'actual_tp_brokerage_amount' => [
+ // 'col_idx' => 32,
+ // 'col_cell_name' => 'AG',
+ // 'col_name' => 'Actual TP Brokerage Amount',
+ // 'is_mandatory' => false,
+ // 'data_type' => '',
+ // 'format' => null,
+ // 'allowed_values' => null,
+ // 'custom' => null,
+ // 'params' => null
+ // ],
+
+ // 'expected_amount' => [
+ // 'col_idx' => 33,
+ // 'col_cell_name' => 'AH',
+ // 'col_name' => 'Expected Amount',
+ // 'is_mandatory' => true,
+ // 'data_type' => '',
+ // 'format' => null,
+ // 'allowed_values' => null,
+ // 'custom' => null,
+ // 'params' => null
+ // ],
+
+ // 'rewards' => [
+ // 'col_idx' => 34,
+ // 'col_cell_name' => 'AI',
+ // 'col_name' => 'Rewards',
+ // 'is_mandatory' => false,
+ // 'data_type' => '',
+ // 'format' => null,
+ // 'allowed_values' => null,
+ // 'custom' => null,
+ // 'params' => null
+ // ],
+
+ ];
+
}
// Policy Transaction Inception
@@ -237,19 +671,27 @@
// Fetch Sales Team
$data['salse_team'] = $this->userModel
- ->select('user_profiles.*')
+ ->select('user_profiles.*,nhance_branch.id as nhance_branch_id, nhance_branch.branch_name as nhance_branch_name')
->join('user_teams', 'user_profiles.id = user_teams.user_id')
+ ->join('nhance_branch', 'user_profiles.nhance_branch_id = nhance_branch.id','left')
->where('user_teams.team_id', 5)
->where('user_teams.is_active', 1)
->where('user_profiles.is_active', 1)
->findAll();
+ // Fetch Partner Agent
+ $data['partner_agent'] = db_connect()->table('partner_agent')
+ ->where('is_active', 1)
+ ->get()
+ ->getResultArray();
+
// Fetch ACM
$data['ACM'] = $this->userModel
->where('role', 3) // Assuming `role` is in `user_profiles`
->where('is_active', 1)
->findAll();
// echo '
';
+
// print_r($data['ppTeamsData']); die;
// dd($data);
@@ -258,6 +700,178 @@
$this->loadLayout('policy_transaction_inception_list', $data);
}
+ public function viewInception2()
+ {
+ $bds_edit_pt_id = $this->request->getGet('pt_id') ?? null;
+ $data['tab_name'] = 'Policies';
+ $data['page_name'] = 'Policies';
+
+ // Static arrays for dropdowns
+ $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
+ $data['issuer_branch'] = $this->nhanceBranchModel->where('is_active', 1)->findAll();
+ $data['client_type'] = [1 => 'Group', 2 => 'Individual'];
+ $data['issuing_type'] = [1 => 'Fresh', 2 => 'Renewal', 3 => 'Roll Over'];
+ $data['policy_status'] = [
+ 'under_process' => 'Under Process',
+ 'client_pending' => 'Client Pending',
+ 'insurer_pending' => 'Insurer Pending',
+ 'co_insurer_pending' => 'Co-Insurer Pending',
+ 'tpa_pending' => 'TPA Pending',
+ 'validated' => 'Validated',
+ 'cancelled' => 'Cancelled',
+ 'instalment_pending' => 'Instalment Pending',
+ 'completed' => 'Completed',
+ 'lost' => 'Lost',
+ ];
+ $data['invoice_status_array'] = [
+ 'yet_to_generate' => 'Pending',
+ 'generated' => 'Generated',
+ 'send' => 'Sent',
+ 'recived' => 'Payment Received',
+ ];
+ // $data['vehicle_type'] = [
+ // 'two_wheeler' => 'Two Wheeler',
+ // 'four_wheeler' => 'Four Wheeler',
+ // 'truck' => 'Truck',
+ // 'bus' => 'Bus',
+ // 'van' => 'Van',
+ // 'suv' => 'SUV',
+ // 'motorcycle' => 'Motorcycle',
+ // 'bicycle' => 'Bicycle'
+ // ];
+ $data['vehicle_type'] = db_connect()->table('vehicle_type')->where('is_active', 1)->get()->getResultArray();
+ $data['rto_details'] = db_connect()->table('rto_master')->where('is_active', 1)->get()->getResultArray();
+
+ $data['vehicle_des'] = [
+ 'commercial' => 'Commercial',
+ 'private' => 'Private',
+ ];
+ $data['date_type'] = [
+ 'policy_issue_date' => 'Policy Issue Date',
+ 'policy_start_date' => 'Policy Start Date',
+ 'policy_end_date' => 'Policy End Date',
+ ];
+
+ // Filter data
+ $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');
+ $status = $this->request->getGet('status');
+
+ // Handle null or empty values
+ $start_date = empty($start_date) ? 0 : $start_date;
+ $end_date = empty($end_date) ? 0 : $end_date;
+ $client_id = empty($client_id) ? 0 : $client_id;
+ $insurer_id = empty($insurer_id) ? 0 : $insurer_id;
+ $policy_type_id = empty($policy_type_id) ? 0 : $policy_type_id;
+ $date_type = empty($date_type) ? 0 : $date_type;
+ $issuer = empty($issuer) ? 0 : $issuer;
+ $status = empty($status) ? 0 : $status; // Corrected from `$issuer`
+
+ if(empty($bds_edit_pt_id)){
+ if ($this->request->is('get')) {
+
+ // Fetch inception data list
+ $data['inception_data_list'] = $this->policyTransactionModel->getInceptionTranctionListData(
+ $start_date,
+ $end_date,
+ $client_id,
+ $insurer_id,
+ $policy_type_id,
+ $date_type,
+ $issuer,
+ $status
+ );
+ } else {
+
+ $ids = $this->request->getPost('ids');
+ $ids = array_filter(explode(',', $ids));
+ $data['inception_data_list'] = $this->policyTransactionModel->getInceptionTranctionListData(
+ $start_date = 0,
+ $end_date = 0,
+ $client_id = 0,
+ $insurer_id = 0,
+ $policy_type_id = 0,
+ $date_type = 0,
+ $issuer = 0,
+ $status = 0,
+ $ids
+ );
+ }
+ }else{
+ $data['inception_data_list'] = [];
+ }
+
+
+
+ // 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();
+ $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll();
+ $data['insurer_branch'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
+ $data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
+
+ // Fetch PP Teams Data
+ $data['ppTeamsData'] = $this->userModel
+ ->where('is_active', 1)
+ ->findAll();
+
+ // Fetch Sales Team
+ $data['salse_team'] = $this->userModel
+ ->select('
+ user_profiles.*,
+ nhance_branch.id as nhance_branch_id,
+ nhance_branch.branch_name as nhance_branch_name,
+ rm.first_name AS rm_name
+ ')
+ ->join('user_teams', 'user_profiles.id = user_teams.user_id')
+ ->join('nhance_branch', 'user_profiles.nhance_branch_id = nhance_branch.id','left')
+ ->join('user_profiles AS rm', 'user_profiles.rm_id = rm.id', 'left')
+ ->where('user_teams.team_id', 5)
+ ->where('user_teams.is_active', 1)
+ ->where('user_profiles.is_active', 1)
+ ->groupBy('user_profiles.id', 'asc')
+ ->findAll();
+
+ // Fetch Partner Agent
+ $data['partner_agent'] = db_connect()->table('partner_agent')
+ ->where('is_active', 1)
+ ->get()
+ ->getResultArray();
+
+ // Fetch ACM
+ $data['ACM'] = $this->userModel
+ ->select('
+ user_profiles.*,
+ nhance_branch.id AS nhance_branch_id,
+ nhance_branch.branch_name AS nhance_branch_name,
+ rm.first_name AS rm_name
+ ')
+ ->join('user_teams', 'user_profiles.id = user_teams.user_id')
+ ->join('nhance_branch', 'user_profiles.nhance_branch_id = nhance_branch.id', 'left')
+ ->join('user_profiles AS rm', 'user_profiles.rm_id = rm.id', 'left')
+ ->where('user_profiles.role', 3)
+ ->where('user_profiles.is_active', 1)
+ ->groupBy('user_profiles.id', 'asc')
+ ->findAll();
+
+ // echo '';
+
+ // print_r($data['ppTeamsData']); die;
+
+ // dd($data);
+
+ // Load view
+ $this->loadLayout('policy_transaction_inception_list_2', $data);
+ }
+
// policy Transaction Create function start
public function createInceptionPolicy()
{
@@ -398,6 +1012,7 @@
$clientController = new ClientController();
$data['client_kyc_primary_table'] = $clientController->generateKycPrimaryTable($data['client_id']);
$data['client_kyc_other_table'] = $clientController->generateKycOthersTable($data['client_id']);
+ // $data['client_kyc_single_table'] = $clientController->generateKycSingleTable($data['client_id']);
$data['entity_type_id'] = $client_data['entity_type_id'];
return $this->respondSuccess($insert, "Policy transaction created successfully", $data);
@@ -460,6 +1075,7 @@
$clientController = new ClientController();
$data['client_kyc_primary_table'] = $clientController->generateKycPrimaryTable($data['client_id']);
$data['client_kyc_other_table'] = $clientController->generateKycOthersTable($data['client_id']);
+ // $data['client_kyc_single_table'] = $clientController->generateKycSingleTable($data['client_id']);
$data['entity_type_id'] = $client_data['entity_type_id'];
@@ -500,7 +1116,7 @@
$data['calc_policy_issue_date'][$index] = change_date_format($data['calc_policy_issue_date'][$index]);
}
- $co_share_type_value = $data['co_share'] == 1 ? $data['co_share_type'][$index] ?? 1 : 1;
+ $co_share_type_value = (($data['co_share'] ?? 0) == 1) ? ($data['co_share_type'][$index] ?? 1) : 1;
// Prepare each co-share detail entry
$coShareDetails[] = [
@@ -1028,6 +1644,279 @@
$clientController = new ClientController();
$data['client_kyc_primary_table'] = $clientController->generateKycPrimaryTable($data['client_id']);
$data['client_kyc_other_table'] = $clientController->generateKycOthersTable($data['client_id']);
+ $data['client_kyc_single_table'] = $clientController->generateKycSingleTable($data['client_id']);
+ $data['client_kyc_dd_data'] = $clientController->fetch_dropdown($data['client_id']);
+
+ $data['vehicle_docs'] = $this->clientKYCDocsModel
+ ->where('client_id', $data['client_id'])
+ ->where('vehicle_id', $data['vehicle_id'])
+ ->findAll();
+
+ // print_r( $data['pt_co_share_details']); die;
+ // return $data;
+ if ($data) {
+ return $this->respond(['status' => true, 'data' => $data], 200);
+ } else {
+ return $this->respond(['status' => false], 200);
+ }
+ }
+
+ // Get the Single Inception Tranction data for edit
+ public function getInceptionDataForEdit2($id)
+ {
+ $data = $this->policyTransactionModel
+ ->select('
+ policy_transaction.*,
+ clients.short_name as client_short_name,
+ clients.client_type,
+ clients.entity_type_id,
+ policy_type.policy_type,
+ client_policy.tpa_id as master_tpa_id,
+ client_policy.tpa_branch_id as master_tpa_branch_id,
+ client_policy.policy_type_id as master_policy_type_id,
+ client_policy.is_addon,
+ client_policy.base_policy,
+ (
+ select last_action_date
+ from policy_transaction_status
+ where policy_tran_id = policy_transaction.id
+ and status = policy_transaction.status
+ order by id desc
+ limit 1
+
+ ) as last_action_date
+ ')
+ ->join('clients', 'clients.id = policy_transaction.client_id')
+ ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
+ ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left')
+ ->where('policy_transaction.id', $id)
+ ->where('policy_transaction.is_active', 1)
+ ->first();
+
+ $data['created_at'] = (isset($data['created_at']) && $data['created_at'] !== null && $data['created_at'] !== '')
+ ? date('d/m/Y h:i:s A', strtotime($data['created_at']))
+ : null;
+
+ $data['updated_at'] = (isset($data['updated_at']) && $data['updated_at'] !== null && $data['updated_at'] !== '')
+ ? date('d/m/Y h:i:s A', strtotime($data['updated_at']))
+ : null;
+
+
+ if (!empty($data['policy_issue_date'])) {
+ $data['policy_issue_date'] = change_date_format($data['policy_issue_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['policy_start_date'])) {
+ $data['policy_start_date'] = change_date_format($data['policy_start_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['policy_end_date'])) {
+ $data['policy_end_date'] = change_date_format($data['policy_end_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['renewal_date'])) {
+ $data['renewal_date'] = change_date_format($data['renewal_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['rollover_date'])) {
+ $data['rollover_date'] = change_date_format($data['rollover_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['endorse_eff_date'])) {
+ $data['endorse_eff_date'] = change_date_format($data['endorse_eff_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['last_action_date'])) {
+ $data['last_action_date'] = change_date_format($data['last_action_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['month'])) {
+ $data['month'] = change_date_format($data['month'], 'Y-m-d', 'M/Y');
+ } else {
+ $data['month'] = null;
+ }
+
+ // print_r($data); die;
+
+ $data['renewal_policy'] = $this->clientPolicyModel
+ ->select('client_policy.*, policy_type.policy_type')
+ ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
+ ->where('client_policy.client_id', $data['client_id'])
+ ->where('client_policy.client_branch_id', $data['client_branch_id'])
+ ->where('client_policy.is_active', 1)
+ ->findAll();
+
+ $data['base_policy_data'] = $this->clientPolicyModel
+ ->select('client_policy.*, policy_type.policy_type')
+ ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
+ ->where('client_policy.client_id', $data['client_id'])
+ ->where('client_policy.client_branch_id', $data['client_branch_id'])
+ ->whereIn('client_policy.policy_type_id', [2, 3])
+ ->where('client_policy.is_active', 1)
+ ->findAll();
+
+ $pt_bp_amt = $this->PTCOShareDetailsModel
+ ->select('bp_amt, amount')
+ ->where('pt_id', $id)
+ ->where('co_share_type', 1)
+ ->where('is_active', 1)
+ ->first();
+
+ // dd(db_connect()->getLastQuery() ,$pt_bp_amt);
+ $data['base_cd_amount'] = $pt_bp_amt['amount'] ?? null;
+
+
+ $ptFileQuery = $this->PTFileModel
+ ->join('policy_transaction', 'pt_files.pt_id = policy_transaction.id')
+ ->where('pt_files.pt_id', $id)
+ ->where('pt_files.is_active', 1);
+
+ if (!in_array(get_role_id(), [1, 5]) && empty(array_intersect(user_team(), [MANAGEMENT_TEAM_ID, FINANCE_TEAM_ID, BUSINESS_TEAM_ID]))) {
+
+ if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
+ $ptFileQuery->where('pt_files.created_by', get_session_userid());
+ }
+ }
+
+ $data['pt_files'] = $ptFileQuery->findAll();
+
+
+
+ $data['pt_co_share_details'] = $this->PTCOShareDetailsModel
+ ->select("
+ pt_co_share_details.*,
+
+ (
+ 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,
+
+ (
+ SELECT
+ SUM(actual_bp_amt)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_bp_amount,
+
+ (
+ SELECT
+ SUM(actual_tp_amt)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_tp_amount,
+
+ (
+ SELECT
+ SUM(actual_tep_amt)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_tep_amount,
+
+ (
+ SELECT
+ SUM(actual_bp_per)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_bp_percentage,
+
+ (
+ SELECT
+ SUM(actual_tp_per)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_tp_percentage,
+
+ (
+ SELECT
+ SUM(actual_tep_per)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_tep_percentage,
+
+
+ (
+ SELECT
+ SUM(actual_bp_brokerage_amt)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_bp_brokerage_amount,
+
+
+ (
+ SELECT
+ SUM(actual_tp_brokerage_amt)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_tp_brokerage_amount,
+
+
+ (
+ SELECT
+ SUM(actual_tep_brokerage_amt)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_tep_brokerage_amount,
+
+ DATE_FORMAT(pt_policy_issue_date, '%d/%m/%Y') AS pt_policy_issue_date
+
+ ")
+ ->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')
+ ->where('employees.client_id', $data['client_id'])
+ ->where('employees.is_active', 1)->findAll();
+ // $data['client_kyc'] = $this->clientKYCDocsModel->where('client_id', $data['client_id'])->findAll();
+
+ $clientController = new ClientController();
+ $data['client_kyc_primary_table'] = $clientController->generateKycPrimaryTable($data['client_id']);
+ $data['client_kyc_other_table'] = $clientController->generateKycOthersTable($data['client_id']);
+ $data['client_kyc_single_table'] = $clientController->generateKycSingleTable($data['client_id']);
$data['vehicle_docs'] = $this->clientKYCDocsModel
->where('client_id', $data['client_id'])
@@ -1191,6 +2080,100 @@
$this->loadLayout('policy_transaction_endorsement_list', $data);
}
+ public function viewEndorsement2()
+ {
+ // echo '';
+ // !dd($this->getEndorsementDataForEdit(17));
+ $bds_edit_pt_id = $this->request->getGet('pt_id') ?? null;
+ $data['tab_name'] = 'Endorsements';
+ $data['page_name'] = 'Endorsements';
+ $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
+ $data['issuer_branch'] = $this->nhanceBranchModel->where('is_active', 1)->findAll();
+ $data['client_type'] = [1 => 'Group', 2 => 'Individual'];
+
+ $data['policy_status'] = [
+ 'under_process' => 'Under Process',
+ 'client_pending' => 'Client Pending',
+ 'insurer_pending' => 'Insurer Pending',
+ 'co_insurer_pending' => 'Co-Insurer Pending',
+ 'tpa_pending' => 'TPA Pending',
+ 'validated' => 'Validated',
+ 'cancelled' => 'Cancelled',
+ 'instalment_pending' => 'Instalment Pending',
+ 'completed' => 'Completed',
+ ];
+
+ $data['invoice_status'] = [
+ 'yet_to_generate' => 'Pending',
+ 'generated' => 'Generated',
+ 'send' => 'Sent',
+ 'recived' => 'Payment Received',
+ ];
+
+ $data['action_type'] = [
+ 'addition' => 'Addition',
+ 'deletion' => 'Deletion',
+ 'addition_deletion' => 'Addition & Deletion',
+ 'si_enhancement' => 'SI Enhancement',
+ 'combo_a_d_si' => 'Combo A, D & SI',
+ 'correction' => 'Correction',
+ 'baby_addition' => 'Baby Addition',
+ 'policy_instalment' => 'Policy Instalment',
+ 'addition_inception' => 'Addition-Inception',
+ 'bds_correction' => 'BDS Correction',
+ 'policy_correction' => 'Policy Correction',
+ 'policy_cancellation' => 'Policy Cancellation',
+ ];
+
+ $data['date_type'] = [
+ 'policy_issue_date' => 'Policy Issue Date',
+ 'policy_start_date' => 'Policy Start Date',
+ 'policy_end_date' => 'Policy End Date',
+ ];
+
+ //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');
+ $status = $this->request->getGet('status');
+
+ $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;
+ $status = (!isset($issuer) || $status === '' || $status === null) ? 0 : $status;
+
+ if($bds_edit_pt_id == null){
+ $data['endorsement_data_list'] = $this->policyTransactionModel->getEndorsementTranctionListData($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status);
+ }else{
+ $data['endorsement_data_list'] = [];
+ }
+ $data['client'] = $this->clientModel->where('is_active', 1)->findAll();
+ $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll();
+
+ $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll();
+ // $data['tpa'] = $this->tpaModel->where('is_active', 1)->findAll();
+ $data['insurer_branch'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
+ $data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
+ list($policyList, $policyListByClient) = $this->getPolicyForEndorsment();
+
+ $data['endorsementPolicies'] = $policyList;
+ $data['endorsementPolicyListByClient'] = $policyListByClient;
+
+ // dd($data);
+ // print_r($data['endorsementPolicies']);die();
+
+ $this->loadLayout('policy_transaction_endorsement_list_2', $data);
+ }
+
public function createEndorsementPolicy()
{
$id = $this->request->getPost('id');
@@ -1327,7 +2310,12 @@
'listed_insurers' => $issue_type['listed_insurers'] ?? null,
'ppteam' => $issue_type['ppteam'] ?? null,
'sales_generated_by' => $issue_type['sales_generated_by'] ?? null,
- 'serviced_by' => $issue_type['serviced_by'] ?? null
+ 'serviced_by' => $issue_type['serviced_by'] ?? null,
+ 'salse_person_manager_id' => $issue_type['salse_person_manager_id'] ?? null,
+ 'service_person_manager_id' => $issue_type['service_person_manager_id'] ?? null,
+ 'service_person_branch_id' => $issue_type['service_person_branch_id'] ?? null,
+ 'agent_id' => $issue_type['agent_id'] ?? null,
+ 'agent_code' => $issue_type['agent_code'] ?? null,
];
$data['client_branch_id'] = $client_branch_id;
@@ -1628,6 +2616,220 @@
}
}
+ public function getEndorsementDataForEdit2($id)
+ {
+ $data = $this->policyTransactionModel
+ ->select('
+ policy_transaction.*,
+ clients.short_name as client_short_name,
+ clients.client_type,
+ (
+ select last_action_date
+ from policy_transaction_status
+ where policy_tran_id = policy_transaction.id
+ and status = policy_transaction.status
+ order by id desc
+ limit 1
+
+ ) as last_action_date
+ ')
+ ->join('clients', 'clients.id = policy_transaction.client_id')
+ ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
+ ->where('policy_transaction.id', $id)
+ ->where('policy_transaction.is_active', 1)
+ ->orderBy('id', 'asc')
+ ->first();
+
+ $pt_id = null;
+
+ if(!empty($data)){
+ $inception_data = $this->policyTransactionModel
+ ->where('policy_no', $data['policy_no'])
+ ->where('client_id', $data['client_id'])
+ ->where('action_type', 'inception')
+ ->first();
+ $pt_id = $inception_data['id'];
+ }
+
+ if (!empty($data['policy_start_date'])) {
+ $data['policy_start_date'] = change_date_format($data['policy_start_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['policy_end_date'])) {
+ $data['policy_end_date'] = change_date_format($data['policy_end_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['data_received_date'])) {
+ $data['data_received_date'] = change_date_format($data['data_received_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['policy_issue_date'])) {
+ $data['policy_issue_date'] = change_date_format($data['policy_issue_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['endorse_eff_date'])) {
+ $data['endorse_eff_date'] = change_date_format($data['endorse_eff_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['install_due_date'])) {
+ $data['install_due_date'] = change_date_format($data['install_due_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['last_action_date'])) {
+ $data['last_action_date'] = change_date_format($data['last_action_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['month'])) {
+ $data['month'] = change_date_format($data['month'], 'Y-m-d', 'M/Y');
+ }
+
+ // print_r($data); die;
+
+ //get PT Co-Share Details
+ $data['pt_co_share_details'] = $this->PTCOShareDetailsModel
+
+ ->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,
+
+ (
+ SELECT
+ SUM(actual_bp_amt)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_bp_amount,
+
+ (
+ SELECT
+ SUM(actual_tp_amt)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_tp_amount,
+
+ (
+ SELECT
+ SUM(actual_tep_amt)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_tep_amount,
+
+ (
+ SELECT
+ SUM(actual_bp_per)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_bp_percentage,
+
+ (
+ SELECT
+ SUM(actual_tp_per)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_tp_percentage,
+
+ (
+ SELECT
+ SUM(actual_tep_per)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_tep_percentage,
+
+
+ (
+ SELECT
+ SUM(actual_bp_brokerage_amt)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_bp_brokerage_amount,
+
+
+ (
+ SELECT
+ SUM(actual_tp_brokerage_amt)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_tp_brokerage_amount,
+
+
+ (
+ SELECT
+ SUM(actual_tep_brokerage_amt)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_tep_brokerage_amount,
+
+ DATE_FORMAT(pt_policy_issue_date, '%d/%m/%Y') AS pt_policy_issue_date
+
+ ")
+ ->where('pt_id', $id)
+ ->where('is_active', 1)
+ ->orderBy('id', 'asc')
+ ->findAll();
+
+ // print_r($data['endorse_eff_date']); die;
+
+ $pt_bp_amt = $this->PTCOShareDetailsModel
+ ->select('bp_amt, amount')
+ ->where('pt_id', $id)
+ ->where('co_share_type', 1)
+ ->where('is_active', 1)
+ ->first();
+
+ // dd(db_connect()->getLastQuery() ,$pt_bp_amt);
+ $data['base_cd_amount'] = $pt_bp_amt['amount'] ?? null;
+
+ if ($data) {
+ return $this->respond(['status' => true, 'data' => $data, 'pt_id' => $pt_id], 200);
+ } else {
+ return $this->respond(['status' => false], 200);
+ }
+ }
+
//------------------------------------------------------------------------------------------------
//file upload function
@@ -3207,7 +4409,6 @@
return [$policyList, $policyListByClient];
}
-
public function reportBDSNew()
{
// 🧭 Basic Page Info
@@ -3318,6 +4519,842 @@
$this->loadLayout('report_bds_filter', $data);
}
+ // ------------ BDS BULK MOTER POLICY UPLOAD -----------------------------------------------------------------------------------------------
+ public function policyBulkUpload()
+ {
+ $data['page_name'] = "BDS Bulk File Upload";
+ $data['tab_name'] = "BDS File Upload";
+
+ // $response = $this->insertBulkBdsData(['file_id' => 17]);
+ // dd($response);
+
+
+ if ($this->request->is('get')) {
+
+ $data['bds_dump_file_data'] = $this->bdsDumpModel
+ ->select('
+ bds_dump_files.id as file_id,
+ bds_dump_files.file_name,
+ bds_dump_files.status,
+ bds_dump_files.created_at,
+ up.first_name as user_name
+ ')
+ ->join('user_profiles as up', 'bds_dump_files.created_by = up.id', 'left')
+ ->where('bds_dump_files.is_active', 1)
+ ->orderBy('bds_dump_files.id', 'desc')
+ ->findAll();
+
+ return $this->loadLayout('bds_dump_file_list', $data);
+ } else {
+
+ $filename = '';
+ $fileSize = '';
+
+ //validate uploaded file
+ $validated = $this->validate([
+ 'bds_dump_list' => [
+ 'uploaded[bds_dump_list]',
+ 'mime_in[bds_dump_list,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.oasis.opendocument.spreadsheet]',
+ 'max_size[bds_dump_list,16384]',
+ ],
+ ]);
+
+ if ($validated) {
+ $avatar = $this->request->getFile('bds_dump_list');
+ if (!$avatar) {
+ $this->myLogger->logme("error", 'File not found');
+ return $this->respond(['status' => false, 'code' => 400, 'message' => 'File not found'], 400);
+ }
+
+ $is_moved = $avatar->move(WRITEPATH . 'uploads/bds_dump_excel/');
+
+ if ($is_moved) {
+ $filename = $avatar->getName();
+ $fileSize = $avatar->getSize(); // File size in bytes
+ $fileSize = $fileSize / (1024 * 1024); // Convert to MB
+
+ $this->myLogger->logme("error", 'File move successful');
+ } else {
+ $this->myLogger->logme("error", 'File move failed');
+ return $this->respond(['status' => false, 'code' => 500, 'message' => 'File move failed'], 500);
+ }
+ } else {
+ $this->myLogger->logme("error", 'Upload failed Invalid file');
+ return $this->respond(['status' => false, 'code' => 404, 'message' => 'Invalid file'], 404);
+ }
+
+
+ $status = 'inprogress';
+ $insert_data = [
+ 'file_name' => $filename,
+ 'status' => $status
+ ];
+
+ $file_id = $this->bdsDumpModel->insert($insert_data);
+ $this->myLogger->logme("error", 'claim_dumb_file_id : {file_id}, uploaded success', ['file_id' => $file_id]);
+
+ //after file upload success than call the file formate validation
+ // $response = $this->bdsDumpExcelFileFormatValidation(["file_id" => $file_id]);
+ $r = Jobs::addJob(['job_name' => 'bdsDumpExcelFileFormatValidation', 'payload' => ['file_id' => $file_id]]);
+
+ return $this->respond(['status' => true, 'code' => 200, 'message' => 'File uploaded successfully. File being validated'], 200);
+ }
+ }
+
+ public function downloadBDSDumpFile($file_id)
+ {
+ // $actionType = $this->request->getGet();
+ $file_data = $this->bdsDumpModel->where('id', $file_id)->first();
+ $fileName = $file_data['file_name'];
+
+ $filePath = WRITEPATH . '/uploads/bds_dump_excel/' . $fileName;
+
+ try {
+
+ // Check if the file exists
+ if (file_exists($filePath)) {
+ // Set the appropriate MIME type
+ $mimeType = mime_content_type($filePath);
+
+ // Send the file to the client for download
+ return $this->response->download($filePath, null, $mimeType);
+ } else {
+
+ $data['message'] = 'The Physical File Not Found';
+ echo view('errors/404', $data);
+ }
+ } catch (\Exception $e) {
+ // Handle any exceptions
+ $errorMessage = $e->getMessage();
+ $this->myLogger->logme('error', $errorMessage);
+ // You can return an error response here
+ echo $errorMessage;
+ }
+ }
+
+ public function bdsDumpExcelFileFormatValidation($params)
+ {
+ helper('excel_util_helper');
+ $file_id = $params['file_id'];
+ $file = $this->bdsDumpModel->where("id", $file_id)->first();
+
+ $return = [];
+ if (empty($file)) {
+ return array('status' => false, 'message' => 'File not found in Database');
+ }
+
+ $file_name_with_path = WRITEPATH . "/uploads/bds_dump_excel/" . $file['file_name'];
+
+ //check physical file exist
+ if (!file_exists($file_name_with_path)) {
+ $message = "Physcial file not found";
+ $this->myLogger->logme('error', ($message . ' for file id : ' . $file_id));
+ $this->bdsDumpModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+ return array('error_summary' => [5], 'error_data' => $message);
+ }
+
+ // get the BDS dump excel colums
+ $columns_to_check = $this->bds_bulk_upload_excel_file_column;
+ $keys = array_keys($columns_to_check);
+ $allowedHighestColumn = end($columns_to_check);
+
+ // Read the excel file
+ $excel_data = $this->extractExcelData($file['file_name'], $allowedHighestColumn['col_cell_name']);
+ $excel_columns = ($excel_data[0]);
+ // echo ''; var_dump($excel_columns);
+
+
+ //check no of columns in excel
+ $total_defined_columns = count($columns_to_check);
+ $excel_columns_count = count($excel_columns);
+
+ if($total_defined_columns != $excel_columns_count)
+ {
+ //columns count mismatch
+ $message = "File columns count mismatch. Expected - $total_defined_columns and received - $excel_columns_count";
+ $this->myLogger->logme('error',($message . ' for file id ' . $file_id));
+ $this->bdsDumpModel->where('id', $file_id)->set(['status' => 'failed','reason' => json_encode(['error_summary' => array_count_values([5]),'error_data' => $message])])->update();
+ return array('error_summary' => [5], 'error_data' => $message);
+ }
+
+ //check columns order in excel
+ $column_count_res = check_columns_name($columns_to_check, $excel_columns);
+
+ if(isset($column_count_res) && count($column_count_res))
+ {
+ //columns count mismatch
+ $message = implode("\n", $column_count_res);
+ $this->myLogger->logme('error',($message . ' for file id ' . $file_id));
+ $this->bdsDumpModel->where('id', $file_id)->set(['status' => 'failed','reason' => json_encode(['error_summary' => array_count_values([6]), 'error_data' => $message])])->update();
+ return array('error_summary' => [6], 'error_data' => $message);
+ }
+
+ //Store the error data by this structure
+ $result = ['error_type' => 1, 'error_summary' => [], 'error_data' => []];
+
+ $insurer_data = $this->insurerModel->where('is_active', 1)->findAll();
+ $insurer_branch_data = $this->insurerBranchModel->where('is_active', 1)->findAll();
+ $pt_data = $this->policyTransactionModel->where('is_active', 1)->findAll();
+ $user_data = $this->userModel->where('is_active', 1)->findAll();
+ $agent_data = db_connect()->table('partner_agent')->where('is_active', 1)->get()->getResultArray();
+ $rto_master = db_connect()->table('rto_master')->where('is_active', 1)->get()->getResultArray();
+ $vehicle_type = db_connect()->table('vehicle_type')->where('is_active', 1)->get()->getResultArray();
+ $nhance_branch_data = db_connect()->table('nhance_branch')->where('is_active', 1)->get()->getResultArray();
+
+
+ //remove header
+ unset($excel_data[0]);
+
+ try {
+ foreach ($excel_data as $row_key => $row) {
+
+ //avoid empty rows
+ if (check_row_is_empty_or_null($row)) {
+ break;
+ }
+
+ $insurers = [];
+ foreach ($row as $col_key => $col)
+ {
+ $is_mandatory = $columns_to_check[$keys[$col_key]]['is_mandatory'];
+ $format = $columns_to_check[$keys[$col_key]]['format'];
+ $data_type = $columns_to_check[$keys[$col_key]]['data_type'];
+ $allowed_values = $columns_to_check[$keys[$col_key]]['allowed_values'];
+ $custom_function = isset($columns_to_check[$keys[$col_key]]['custom']) ? $columns_to_check[$keys[$col_key]]['custom'] : null;
+ $binding_params = isset($columns_to_check[$keys[$col_key]]['params']) ? $columns_to_check[$keys[$col_key]]['params'] : null;
+
+ $column_dispaly_name = $columns_to_check[$keys[$col_key]]['col_name'];
+ $column_index = $columns_to_check[$keys[$col_key]]['col_idx'];
+ $column_cell = $columns_to_check[$keys[$col_key]]['col_cell_name'];
+
+
+ //mandatory check
+ if(is_bool($is_mandatory) && $is_mandatory === true)
+ {
+ if($col == "" || $col == NULL)
+ {
+ array_push($result['error_summary'],1); //push error code for summary
+ $result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name
+ $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index
+ $result['error_data'][$row_key][$keys[$col_key]]['error'][] = 'Value is mandatory'; //push exact error desc
+ }
+ }
+
+ //format check
+ if(isset($format))
+ {
+ $validation = validate_excel_value($col, $data_type, $format, $allowed_values);
+ if (!$validation['status']) {
+ array_push($result['error_summary'], 2);
+
+ $result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name;
+ $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index;
+ $result['error_data'][$row_key][$keys[$col_key]]['error'][] = $validation['error'];
+ }
+ }
+
+ //allowed values check
+ if(($is_mandatory === true && isset($allowed_values) && is_array($allowed_values)) || (is_array($is_mandatory) && (isset($allowed_values) && is_array($allowed_values))))
+ {
+ if(!in_array((trim($col)),$allowed_values))
+ {
+ array_push($result['error_summary'],3);
+ $result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name
+ $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index
+ $result['error_data'][$row_key][$keys[$col_key]]['error'][] = "Value not allowed: Expected ".implode(",",$allowed_values)." and received $col";
+ }
+ }
+
+ //custom function check
+ if(isset($custom_function))
+ {
+ //convert string params into PHP variables
+ // Create an array of variables to pass custom helper funcitons
+ $param_values = [];
+ foreach($binding_params as $bkey => $bparam) { $param_values[] = ($$bparam); }
+ $res = call_user_func_array($custom_function,$param_values);
+ if($res['status'] === false) {
+ array_push($result['error_summary'],4);
+ $result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name
+ $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index
+ $result['error_data'][$row_key][$keys[$col_key]]['error'][] = $res['error'];
+ }
+
+ if($res['status'] == true && isset($res['insurer'])){
+ $insurers = $res['insurer'];
+ }
+
+ }
+
+ }//col foreach
+
+ }
+ } catch (\Exception $e) {
+ $errorDetails = [
+ 'error_message' => $e->getMessage(),
+ 'file' => $e->getFile(),
+ 'line' => $e->getLine(),
+ 'stack_trace' => $e->getTraceAsString(),
+ ];
+ $message = "Contact system admin";
+ $this->bdsDumpModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+ $this->myLogger->logme("error", 'Claim dump file format validation failed due to : ' . json_encode($errorDetails ?? []));
+ return $errorDetails;
+ }
+
+ // return $result;
+
+ if (isset($result['error_summary']) && count($result['error_summary'])) {
+ $result['error_summary'] = array_count_values($result['error_summary']);
+ $status = 'failed';
+ $failure_reason = ((json_encode($result)));
+ $this->bdsDumpModel->where('id', $file_id)->set(['status' => $status, 'reason' => $failure_reason])->update();
+ $this->myLogger->logme("error", '{file_id} uploaded failed', ['file_id' => $file_id]);
+ } else { //trigger next data validation via job queue server
+ //proceed next data level validation in JOB queue
+ $r = Jobs::addJob(['job_name' => 'insertBulkBdsData', 'payload' => ['file_id' => $file_id]]);
+ // $response = $this->insertBulkBdsData(['file_id' => $file_id]);
+ }
+
+ return $result;
+ }
+
+ public function insertBulkBdsData($params)
+ {
+ helper('excel_util_helper');
+ $file_id = $params['file_id'];
+ $file = $this->bdsDumpModel->where("id", $file_id)->first();
+
+ $return = [];
+ if (empty($file)) {
+ return array('status' => false, 'message' => 'File not found in Database');
+ }
+
+ $file_name_with_path = WRITEPATH . "/uploads/bds_dump_excel/" . $file['file_name'];
+
+ //check physical file exist
+ if (!file_exists($file_name_with_path)) {
+ $message = "Physcial file not found";
+ $this->myLogger->logme('error', ($message . ' for file id : ' . $file_id));
+ $this->bdsDumpModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+ return array('error_summary' => [5], 'error_data' => $message);
+ }
+
+ // get the BDS dump excel colums
+ $columns_to_check = $this->bds_bulk_upload_excel_file_column;
+ $keys = array_keys($columns_to_check);
+ $allowedHighestColumn = end($columns_to_check);
+
+ // Read the excel file
+ $excel_data = $this->extractExcelData($file['file_name'], $allowedHighestColumn['col_cell_name']);
+ $excel_columns = ($excel_data[0]);
+
+ //remove header
+ unset($excel_data[0]);
+ // dd($excel_data);
+
+ //Store the error data by this structure
+ $result = ['error_type' => 1, 'error_summary' => [], 'error_data' => []];
+
+ $client_data = $this->clientModel->where('is_active', 1)->where('client_type', 1)->findAll();
+ $insurer_data = $this->insurerModel->where('is_active', 1)->findAll();
+ $insurer_branch_data = $this->insurerBranchModel->where('is_active', 1)->findAll();
+ $vehicle_data = $this->vehicleModel->where('is_active', 1)->findAll();
+ $user_data = $this->userModel->where('is_active', 1)->findAll();
+ $agent_data = db_connect()->table('partner_agent')->where('is_active', 1)->get()->getResultArray();
+ $rto_master = db_connect()->table('rto_master')->where('is_active', 1)->get()->getResultArray();
+ $vehicle_type_data = db_connect()->table('vehicle_type')->where('is_active', 1)->get()->getResultArray();
+ $nhance_branch_data = db_connect()->table('nhance_branch')->where('is_active', 1)->get()->getResultArray();
+
+ try {
+
+ $pt_ids = [];
+ foreach ($excel_data as $row_key => $row) {
+
+ //avoid empty rows
+ if (check_row_is_empty_or_null($row)) {
+ break;
+ }
+
+ $vehicle_number = trim($row[2]);
+ $vehicle_type = trim($row[3]);
+ $client_name = trim($row[5]);
+ $client_email = trim($row[6]);
+
+ $insurer_short_name = trim($row[7]);
+ $insurer_branch_code = trim($row[8]);
+ $salse_generated_by = trim($row[13]);
+ $serviced_by = trim($row[14]);
+ $agent_code = trim($row[15]);
+ $nhance_branch = trim($row[1]);
+
+ $policy_no = trim($row[4]);
+ $policy_issue_date = trim($row[9]);
+ $policy_start_date = trim($row[10]);
+ $policy_end_date = trim($row[11]);
+ $revenue_type = trim($row[12]);
+
+ $base_premium = trim($row[16]);
+ $non_commission_premium_amount = trim($row[17]);
+ $tp_premium = trim($row[18]);
+ $igst = trim($row[19]);
+ $cgst = trim($row[20]);
+ $sgst = trim($row[21]);
+ $stamp_duty = trim($row[22]);
+ // $total = trim($row[23]);
+ $agreed_amount = trim($row[23]);
+ $agreed_bp_percentage = trim($row[24]);
+ $agreed_tp_percentage = trim($row[25]);
+ // $actual_bp_amount = trim($row[27]);
+ // $actual_tp_amount = trim($row[28]);
+ // $actual_bp_percentage = trim($row[29]);
+ // $actual_tp_percentage = trim($row[30]);
+ // $actual_bp_brokerage_amount = trim($row[31]);
+ // $actual_tp_brokerage_amount = trim($row[32]);
+ // $expected_amount = trim($row[33]);
+ // $rewards = trim($row[34]);
+ $actual_bp_amount = 0;
+ $actual_tp_amount = 0;
+ $actual_bp_percentage = 0;
+ $actual_tp_percentage = 0;
+ $actual_bp_brokerage_amount = 0;
+ $actual_tp_brokerage_amount = 0;
+ $expected_amount = 0;
+ $rewards = 0;
+
+ $calculation = calculateMotorPolicyAmounts([
+ 'base_premium' => trim($row[16]),
+ 'non_commission_premium_amount' => trim($row[17]),
+ 'tp_premium' => trim($row[18]),
+ 'igst' => trim($row[19]),
+ 'cgst' => trim($row[20]),
+ 'sgst' => trim($row[21]),
+ 'stamp_duty' => trim($row[22]),
+ 'agreed_amount' => trim($row[23]),
+ 'agreed_bp_percentage' => trim($row[24]),
+ 'agreed_tp_percentage' => trim($row[25]),
+ 'standard_bp_percentage' => 15.00,
+ 'standard_tp_percentage' => 2.5
+ ]);
+
+ log_message('error', 'Motor Policy Calculation: ' . json_encode($calculation));
+
+
+ $current_insurer_data = check_insurer_exist($row, $insurer_data)['insurer'] ?? null;
+ $current_insurer_branch_data = check_insurer_branch_exist($row, $insurer_branch_data, $current_insurer_data)['branch'] ?? null;
+
+ $current_nhance_branch = check_nhance_branch($row, $nhance_branch_data)['branch'] ?? null;
+ $current_agent_data = check_agent_exist($row, $agent_data)['agent'] ?? null;
+
+ $salse = check_user_exist($row, 13, $user_data)['user'] ?? null;
+ $service = check_user_exist($row, 14, $user_data)['user'] ?? null;
+
+ $gst_amt = calculate_gst_amount($row) ?? null;
+
+ // get the client and vehicle id
+ $vehicle_and_client_ids = $this->getClientAndVehicleId($row, $vehicle_data, $client_data, $rto_master, $vehicle_type_data);
+ $vehicle_id = $vehicle_and_client_ids['vehicle_id'] ?? null;
+ $client_id = $vehicle_and_client_ids['client_id'] ?? null;
+
+ $policy_transaction_data = [
+
+ 'issuer' => 2,
+ 'issuer_branch' => $current_nhance_branch['id'] ?? null,
+ 'client_id' => $client_id,
+ 'policy_type_id' => 8,
+ 'insurer_id' => $current_insurer_branch_data['insurer_id'] ?? null,
+ 'insurer_branch_id' => $current_insurer_branch_data['id'] ?? null,
+ 'policy_no' => $policy_no,
+ 'vehicle_id' => $vehicle_id,
+ 'issue_type' => 1,
+ 'policy_issue_date' => change_date_format($policy_issue_date, 'd/M/Y', 'Y-m-d'),
+ 'policy_start_date' => change_date_format($policy_start_date, 'd/M/Y', 'Y-m-d'),
+ 'policy_end_date' => change_date_format($policy_end_date, 'd/M/Y', 'Y-m-d'),
+ 'action_type' => 'inception',
+ 'revenue_type' => $revenue_type,
+ 'co_share' => 0,
+ 'status' => 'completed',
+ 'renewal_date' => change_date_format($policy_end_date, 'd/M/Y', 'Y-m-d'),
+ 'policy_holder_name' => $client_name,
+ 'month' => change_date_format($policy_issue_date, 'd/M/Y', 'Y-m-d'),
+ 'sales_generated_by' => $salse['id'] ?? null,
+ 'serviced_by' => $service['id'] ?? null,
+ 'agent_id' => $current_agent_data['id'] ?? null,
+ 'agent_code' => $current_agent_data['agent_code'] ?? null,
+ 'file_id' => $params['file_id'],
+
+ 'endorsement_no' => null,
+ 'client_branch_id' => null,
+ 'client_policy_id' => null,
+ 'ct_type' => null,
+ 'remarks' => null,
+
+ ];
+
+ $co_share_data = [
+
+ 'pt_id' => null,
+ 'insurer_id' => $current_insurer_branch_data['insurer_id'] ?? null,
+ 'insurer_branch_id' => $current_insurer_branch_data['id'] ?? null,
+ 'co_share_type' => 1,
+ 'co_share_per' => 100,
+
+ 'bp_amt' => $base_premium,
+ 'bp_gst_amt' => $calculation['gst_amount'] ?? $gst_amt,
+ 'bp_igst' => $igst ,
+ 'bp_sgst' => $sgst,
+ 'bp_cgst' => $cgst,
+
+ 'tp_amt' => $tp_premium,
+ 'tp_gst_amt' => 0,
+ 'tp_igst' => 0,
+ 'tp_sgst' => 0,
+ 'tp_cgst' => 0,
+
+ 'tep_amt' => 0,
+ 'tep_gst_amt' => 0,
+ 'tep_igst' => 0,
+ 'tep_sgst' => 0,
+ 'tep_cgst' => 0,
+
+ 'agreed_amt' => $agreed_amount,
+ 'agreed_bp_per' => $agreed_bp_percentage,
+ 'agreed_tp_per' => $agreed_tp_percentage,
+ 'agreed_tep_per' => 0,
+
+ 'actual_bp_amt' => $actual_bp_amount,
+ 'actual_tp_amt' => $actual_tp_amount,
+ 'actual_tep_amt' => 0,
+
+ 'actual_bp_per' => $actual_bp_percentage,
+ 'actual_tp_per' => $actual_tp_percentage,
+ 'actual_tep_per' => 0,
+
+ 'actual_bp_brokerage_amt' => $actual_bp_brokerage_amount,
+ 'actual_tp_brokerage_amt' => $actual_tp_brokerage_amount,
+ 'actual_tep_brokerage_amt' => 0,
+
+ 'standerd_bp_per' => 15.00,
+ 'standerd_tp_per' => 2.50,
+ 'agreed_tep_per' => 0,
+
+ 'reward' => $rewards,
+ 'variance' => 0,
+
+ 'remark' => null,
+ 'amount' => $calculation['total_amount'] ?? 0,
+ 'stamp_duty' => $stamp_duty,
+
+ 'cop_amt' => $base_premium,
+ 'cotp_amt' => $tp_premium,
+ 'cotep_amt' => 0.00,
+
+ 'exp_amt' => $calculation['expected_amount'] ?? $expected_amount,
+ 'statement_id' => null,
+
+ 'follower_policy_no' => null,
+ 'non_comm_per_amt' => $non_commission_premium_amount,
+
+ 'pt_policy_issue_date' => change_date_format($policy_issue_date, 'd/M/Y', 'Y-m-d'),
+
+ 'file_id' => $params['file_id']
+ ];
+
+ if(!empty($vehicle_id) && !empty($client_id)){
+ $pt_id = $this->policyTransactionModel->insert($policy_transaction_data);
+ if($pt_id){
+ $co_share_data['pt_id'] = $pt_id;
+ $pt_co_share_id = $this->PTCOShareDetailsModel->insert($co_share_data);
+
+ $client_policy_insert_data = $this->prepareClientPolicyInsertData($policy_transaction_data);
+ $client_policy_id = $this->clientPolicyModel->insert($client_policy_insert_data);
+ $this->policyTransactionModel->update($pt_id, ['client_policy_id' => $client_policy_id]);
+ $pt_ids[] = $pt_id;
+ $this->myLogger->logme('error', "BDS entry successfully added with pt_id : $pt_id, pt_co_share_id : $pt_co_share_id, client_policy_id :$client_policy_id");
+
+ }
+ }else{
+ $this->myLogger->logme('error', 'Skipped......... , vehicle id and client id missing');
+ }
+
+ }
+
+ } catch (\Exception $e) {
+ $errorDetails = [
+ 'error_message' => $e->getMessage(),
+ 'file' => $e->getFile(),
+ 'line' => $e->getLine(),
+ 'stack_trace' => $e->getTraceAsString(),
+ ];
+ $message = "Contact system admin";
+ $this->bdsDumpModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+ $this->myLogger->logme("error", 'Claim dump file format validation failed due to : ' . json_encode($errorDetails ?? []));
+ return $errorDetails;
+ }
+
+ // return $result;
+
+ if (isset($result['error_summary']) && count($result['error_summary'])) {
+ $result['error_summary'] = array_count_values($result['error_summary']);
+ $status = 'failed';
+ $failure_reason = ((json_encode($result)));
+ $this->bdsDumpModel->where('id', $file_id)->set(['status' => $status, 'reason' => $failure_reason])->update();
+ $this->myLogger->logme("error", '{file_id} uploaded failed', ['file_id' => $file_id]);
+ } else{
+ $result = count($pt_ids);
+ $status = 'success';
+ $failure_reason = ((json_encode($result)));
+ $this->bdsDumpModel->where('id', $file_id)->set(['status' => $status, 'reason' => $failure_reason])->update();
+ $this->myLogger->logme("error", '{file_id} uploaded success', ['file_id' => $file_id]);
+ }
+
+ return $result;
+ }
+
+ public function extractExcelData($file_name, $highestColumn)
+ {
+ // $file_name = "claims_dump_form_client.xlsx";
+ // Load the Excel file
+ $file_name_with_path = WRITEPATH . "/uploads/bds_dump_excel/" . $file_name;
+ $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
+ $worksheet = $spreadsheet->getActiveSheet();
+
+ // Get the highest row and column numbers
+ $highestRow = $worksheet->getHighestDataRow();
+ // $highestColumn = $worksheet->getHighestDataColumn();
+ // dd($highestRow, $highestColumn);
+
+ // Get header row (assuming headers are in row 1)
+ // $headerRow = $worksheet->rangeToArray('A1:' . $highestColumn . '1', null, true, false)[0];
+ $excel_data = $worksheet->rangeToArray('A1:' . $highestColumn . $highestRow);
+ // print_rr($excel_data); die;
+
+ //Sanitize the excel data
+ $excel_data = ExcelSanitizeHelper::sanitizeArrayData($excel_data);
+ // dd($excel_data);
+
+ // dd($data);
+ return $excel_data;
+ }
+
+ public function getBdsBulkUploadExcelErrorData($file_id)
+ {
+ try {
+
+ $file = $this->bdsDumpModel->where('id', $file_id)->first();
+ $error_data = json_decode($file['reason']);
+ // dd($error_data);
+
+ $file_name_with_path = WRITEPATH . "/uploads/bds_dump_excel/" . $file['file_name'];
+ // Kint::dump(file_exists($file_name_with_path)); die;
+
+ //check the file exist or not
+ if (!file_exists($file_name_with_path)) {
+ $error_message = "File not found";
+ $this->myLogger->logme('error', ($error_message . ' for file id ' . $file_id));
+ return 0;
+ }
+
+ $columns_to_check = $this->bds_bulk_upload_excel_file_column;
+ $allowedHighestColumn = end($columns_to_check);
+ // Kint::dump($columns_to_check); die;
+
+ $excel_data = $this->extractExcelData($file['file_name'], $allowedHighestColumn['col_cell_name']);
+ $excelErrorData['excel_header'] = $excel_data[0];
+ unset($excel_data[0]);
+
+ // Kint::dump($excel_data); die;
+ if ($error_data->error_type == 1) {
+
+ $finalArray = [];
+ foreach ($error_data->error_data as $key => $value) {
+ foreach ($value as $key2 => $value2) {
+ $error_data = $value2->error;
+ $data = ['value' => $excel_data[$key][$value2->col_idx], 'error' => $error_data,];
+ $excel_data[$key][$value2->col_idx] = $data;
+ }
+ array_push($finalArray, $excel_data[$key]);
+ }
+
+ foreach ($finalArray as $fkey => $value) {
+ foreach ($value as $vkey => $arrayData) {
+ if (!is_array($arrayData)) {
+ $data = ['value' => $arrayData];
+ $finalArray[$fkey][$vkey] = $data;
+ }
+ }
+ }
+
+ $excelErrorData['excel_data'] = $finalArray;
+ return $excelErrorData;
+ } else if ($error_data->error_type == 2) {
+
+
+ $allErrors = [];
+ $typeTowArray = [];
+
+ foreach ($error_data->error_data as $index => $item) {
+
+ foreach ($item as $field) {
+ if (!isset($allErrors[$index])) {
+ $allErrors[$index] = [];
+ }
+ $allErrors[$index] = array_merge($allErrors[$index], $field->error);
+ }
+ }
+
+ // dd(array_keys($allErrors));
+ foreach ($allErrors as $key => $value) {
+ // echo $key;
+ // print_r($value);
+ foreach ($excel_data as $excel_data_index => $excel_data_value) {
+ if ($excel_data_value[0] == $key) {
+ $data = ['value' => $excel_data[$excel_data_index][1], 'error' => $value,];
+ $excel_data[$excel_data_index][1] = $data;
+ array_push($typeTowArray, $excel_data[$excel_data_index]);
+ break;
+ }
+ }
+ }
+ // dd($data);
+ foreach ($typeTowArray as $fkey => $value) {
+ foreach ($value as $vkey => $arrayData) {
+ if (!is_array($arrayData)) {
+ $data = ['value' => $arrayData];
+ $typeTowArray[$fkey][$vkey] = $data;
+ }
+ }
+ }
+
+ $excelErrorData['excel_data'] = $typeTowArray;
+ return $excelErrorData;
+ }
+
+ } catch (\Exception $e) {
+ // Handle any exceptions
+ $errorMessage = $e->getMessage(); //die();
+ $this->myLogger->logme('error', $errorMessage);
+ return false; // You can return an error response here
+ }
+ }
+
+ public function getBdsdumpFileErrorData()
+ {
+ $file_id = $this->request->getGet('file_id');
+ $file = $this->bdsDumpModel->where('id', $file_id)->first();
+ if (!isset($file)) {
+ return $this->respond(['status' => false, 'code' => 404, 'message' => 'No data found'], 200);
+ } else {
+ return $this->respond(['status' => true, 'code' => 200, 'data' => $file['reason']], 200);
+ }
+ }
+
+ public function getBdsDumpExcelFileErrors($file_id)
+ {
+ // Render views and capture output
+ $result = $this->getBdsBulkUploadExcelErrorData($file_id) ?? [];
+ // dd($result);
+
+ if ($result != 0) {
+
+ $result['file_id'] = $file_id;
+ echo view('excel_errors', $result);
+ } else if ($result == 0) {
+
+ $data['message'] = 'File Not Found Physically';
+ return view('errors/404', $data);
+ } else {
+
+ echo view('errors/html/production');
+ }
+ }
+
+ public function getClientAndVehicleId($row, $vehicle_data, $client_data, $rto_master, $vehicle_type_data)
+ {
+ $vehicle_number = trim($row[2]);
+ $client_name = trim($row[5]);
+ $client_email = trim($row[6]);
+
+ $vehicle_id = null;
+ $client_id = null;
+
+ // -------------------------------------------
+ // 1. First Stage: Check if vehicle already exists
+ // -------------------------------------------
+ foreach ($vehicle_data as $v) {
+ if (strcasecmp(trim($v['vehicle_no']), $vehicle_number) === 0) {
+ $vehicle_id = $v['id'];
+ $client_id = $v['owner'];
+ break;
+ }
+ }
+
+ // -------------------------------------------
+ // 2. Second Stage: Vehicle not found -> check client by email
+ // -------------------------------------------
+ $second_stage_client_id = null;
+
+ if (empty($vehicle_id) && empty($client_id)) {
+
+ foreach ($client_data as $c) {
+ if (strcasecmp(trim($c['email']), $client_email) === 0) {
+ $second_stage_client_id = $c['id'];
+ break;
+ }
+ }
+
+ if (!empty($second_stage_client_id)) {
+
+ // Existing client – Insert vehicle
+ $matched_rto_id = check_rto_data($row, $rto_master);
+ $vehicle_type_id = check_vehicle_type($row, $vehicle_type_data);
+
+ $vehicle_insert = [
+ 'vehicle_no' => $vehicle_number,
+ 'vehicle_type' => $vehicle_type_id['vehicle_type']['id'] ?? null,
+ 'owner' => $second_stage_client_id,
+ 'rto_id' => $matched_rto_id['rto_data']['id'] ?? null,
+ ];
+
+ $vehicle_id = $this->vehicleModel->insert($vehicle_insert);
+ $client_id = $second_stage_client_id;
+ } else {
+
+ // -------------------------------------------
+ // 3. Third Stage: No existing client → Insert new client then insert vehicle
+ // -------------------------------------------
+ $client_insert = [
+ 'client_name' => $client_name,
+ 'short_name' => $client_name,
+ 'email' => $client_email,
+ 'entity_type_id' => 7,
+ 'client_type' => 2,
+ ];
+
+ $client_id = $this->clientModel->insert($client_insert);
+
+ if ($client_id) {
+
+ $matched_rto_id = check_rto_data($row, $rto_master);
+ $vehicle_type_id = check_vehicle_type($row, $vehicle_type_data);
+
+ $vehicle_insert = [
+ 'vehicle_no' => $vehicle_number,
+ 'vehicle_type' => $vehicle_type_id['vehicle_type']['id'] ?? null,
+ 'owner' => $client_id,
+ 'rto_id' => $matched_rto_id['rto_data']['id'] ?? null,
+ ];
+
+ $vehicle_id = $this->vehicleModel->insert($vehicle_insert);
+ }
+ }
+ }
+
+ return [
+ 'client_id' => $client_id,
+ 'vehicle_id' => $vehicle_id,
+ ];
+ }
}
diff --git a/app/Controllers/RestAuthenticationController.php b/app/Controllers/RestAuthenticationController.php
index 761ceffa..9c9065b9 100755
--- a/app/Controllers/RestAuthenticationController.php
+++ b/app/Controllers/RestAuthenticationController.php
@@ -339,7 +339,7 @@ class RestAuthenticationController extends AdminController
public function updateEmpMPIN()
{
try {
- log_message('info', 'MPIN update request received.');
+ log_message('error', 'MPIN update request received.');
$requestData = $this->request->getJSON();
log_message('debug', 'Request data: ' . json_encode($requestData));
@@ -361,7 +361,7 @@ class RestAuthenticationController extends AdminController
$updated = $this->employeeModel->where('id', $employee_id)->set(['mpin' => $mpin])->update();
if ($updated) {
- log_message('info', "MPIN updated successfully for employee ID: {$employee_id}");
+ log_message('error', "MPIN updated successfully for employee ID: {$employee_id}");
return $this->response->setJSON([
'status' => true,
'message' => 'MPIN updated successfully.'
@@ -398,47 +398,54 @@ class RestAuthenticationController extends AdminController
$otp = isset($this->request->getJSON()->otp) ? $this->request->getJSON()->otp : null;
$client_id = $this->request->getJSON()->client_id ?? null;
- if (isset($mobile_number))
- {
- // $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->where('emp_status !=', 'truncated')->where('is_active', 1)->first();
- $builder = $this->employeeModel
- ->select('employees.*')
- ->join('employee_polices', 'employees.id = employee_polices.employee_id')
- ->where('employees.mobile', $mobile_number)
- ->where('employees.relationship', 'Self')
- ->where('employee_polices.is_active', 1)
- ->whereIn('employee_polices.status', ['active', 'expired'])
- ->where('employees.is_active', 1)
- ->whereIn('employees.emp_status', ['active', 'expired'])
- ->where('otp', $otp);
+ if(empty($otp)){
+ return $this->respond(['status' => 'OTP is required','code' => 400,'message' => 'OTP is required'], 200);
+ }
- if (!empty($client_id)) {
- $builder->where('employees.client_id', $client_id);
- }
+ if (empty($mobile_number) && empty($email_id)) {
+ return $this->respond(['status' => 'failed','code' => 400,'message' => 'Mobile number or Email ID is required'], 200);
+ }
- $employeeData = $builder->orderBy('employees.id', 'desc')->first();
+ if (isset($mobile_number))
+ {
+ // $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->where('emp_status !=', 'truncated')->where('is_active', 1)->first();
+ $builder = $this->employeeModel
+ ->select('employees.*')
+ ->join('employee_polices', 'employees.id = employee_polices.employee_id')
+ ->where('employees.mobile', $mobile_number)
+ ->where('employees.relationship', 'Self')
+ ->where('employee_polices.is_active', 1)
+ ->whereIn('employee_polices.status', ['active', 'expired'])
+ ->where('employees.is_active', 1)
+ ->whereIn('employees.emp_status', ['active', 'expired'])
+ ->where('otp', $otp);
- } else {
- // $employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('otp', $otp)->where('relationship', 'self')->where('emp_status !=', 'truncated')->where('is_active', 1)->first();
- $builder = $this->employeeModel
- ->select('employees.*')
- ->join('employee_polices', 'employees.id = employee_polices.employee_id')
- ->where('employees.email_corporate', $email_id)
- ->where('employees.relationship', 'Self')
- ->where('employee_polices.is_active', 1)
- ->whereIn('employee_polices.status', ['active', 'expired'])
- ->where('employees.is_active', 1)
- ->whereIn('employees.emp_status', ['active', 'expired'])
- ->where('otp', $otp);
+ if (!empty($client_id)) {
+ $builder->where('employees.client_id', $client_id);
+ }
- if (!empty($client_id)) {
- $builder->where('employees.client_id', $client_id);
- }
+ $employeeData = $builder->orderBy('employees.id', 'desc')->first();
- $employeeData = $builder->orderBy('employees.id', 'desc')->first();
- }
+ } else {
+ // $employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('otp', $otp)->where('relationship', 'self')->where('emp_status !=', 'truncated')->where('is_active', 1)->first();
+ $builder = $this->employeeModel
+ ->select('employees.*')
+ ->join('employee_polices', 'employees.id = employee_polices.employee_id')
+ ->where('employees.email_corporate', $email_id)
+ ->where('employees.relationship', 'Self')
+ ->where('employee_polices.is_active', 1)
+ ->whereIn('employee_polices.status', ['active', 'expired'])
+ ->where('employees.is_active', 1)
+ ->whereIn('employees.emp_status', ['active', 'expired'])
+ ->where('otp', $otp);
+
+ if (!empty($client_id)) {
+ $builder->where('employees.client_id', $client_id);
+ }
+
+ $employeeData = $builder->orderBy('employees.id', 'desc')->first();
+ }
-
$lastQuery = $this->employeeModel->db->getLastQuery();
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedUserData: Last Executed Query: " . $lastQuery);
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedUserData: employeeData: " . json_encode($employeeData ?? []));
@@ -1276,7 +1283,7 @@ class RestAuthenticationController extends AdminController
// Step 2: Fetch employee data
if ($mobile_number) {
- log_message('info', 'Looking up employee by mobile number: ' . $mobile_number);
+ log_message('error', 'Looking up employee by mobile number: ' . $mobile_number);
$builder = $this->employeeModel
->select('employees.*')
->join('employee_polices', 'employees.id = employee_polices.employee_id')
@@ -1295,7 +1302,7 @@ class RestAuthenticationController extends AdminController
} else {
- log_message('info', 'Looking up employee by email: ' . $email_id);
+ log_message('error', 'Looking up employee by email: ' . $email_id);
$builder = $this->employeeModel
->select('employees.*')
->join('employee_polices', 'employees.id = employee_polices.employee_id')
@@ -1336,7 +1343,7 @@ class RestAuthenticationController extends AdminController
->update();
if ($updated) {
- log_message('info', 'MPIN reset successful for employee ID: ' . $employeeData['id']);
+ log_message('error', 'MPIN reset successful for employee ID: ' . $employeeData['id']);
return $this->respond([
'status' => 'success',
'code' => 200,
@@ -1409,7 +1416,7 @@ class RestAuthenticationController extends AdminController
'status' => 'failed',
'message' => 'Mobile number or Email ID is required.',
'data' => [],
- ], 400);
+ ], 200);
}
if (!empty($mobile_number)) {
@@ -1470,8 +1477,9 @@ class RestAuthenticationController extends AdminController
return $this->respond([
'status' => 'failed',
'message' => 'No employee found.',
+ 'code' => 404,
'data' => [],
- ], 404);
+ ], 200);
}
public function logHrActivity()
@@ -1768,7 +1776,7 @@ class RestAuthenticationController extends AdminController
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyPassword: Verified employee found");
- // ✅ Log authentication info
+ // ✅ Log authentication error
$auth = HttpRequestHelper::getRequestInfo();
if ($auth) {
$this->authHistoryModel->insert([
@@ -2035,4 +2043,249 @@ class RestAuthenticationController extends AdminController
], 500);
}
}
+
+ public function getRetailUserData()
+ {
+ $params = $this->request->getJSON(true);
+ // print_r( $params); die;
+
+ $mobile_number = $params['mobile_number'] ?? null;
+ $email_id = $params['email_id'] ?? null;
+ $otp = $params['otp'] ?? null;
+ $old_mpin = $params['old_mpin'] ?? null;
+
+ if (empty($mobile_number) && empty($email_id)) {
+ return $this->respond(['status' => 'failed', 'message' => 'Mobile number or Email ID is required.', 'data' => [],], 200);
+ }
+
+ if (!empty($mobile_number)) {
+
+ $builder = $this->clientModel
+ ->select('clients.*')
+ ->join('policy_transaction', 'policy_transaction.client_id = clients.id')
+ ->where('policy_transaction.is_active', 1)
+ ->where('clients.is_active', 1)
+ ->where('clients.phone', $mobile_number);
+
+ if (!empty($otp)) {
+ $builder->where('clients.otp', $otp);
+ }
+
+ if (!empty($old_mpin)) {
+ $builder->where('clients.mpin', $old_mpin);
+ }
+
+ $retailUserData = $builder->orderBy('clients.id', 'desc')->first();
+ } else {
+
+ $builder = $this->clientModel
+ ->select('clients.*')
+ ->join('policy_transaction', 'policy_transaction.client_id = clients.id')
+ ->where('policy_transaction.is_active', 1)
+ ->where('clients.is_active', 1)
+ ->where('clients.email', $email_id);
+
+ if (!empty($otp)) {
+ $builder->where('clients.otp', $otp);
+ }
+
+ if (!empty($old_mpin)) {
+ $builder->where('clients.mpin', $old_mpin);
+ }
+
+ $retailUserData = $builder->orderBy('clients.id', 'desc')->first();
+ }
+
+ if ($retailUserData) {
+ return $this->respond(['status' => 'success', 'data' => $retailUserData,], 200);
+ }
+
+ return $this->respond(['status' => 'failed', 'message' => 'No employee found.', 'code' => 404, 'data' => [],], 200);
+ }
+
+ public function updateRetailUserAuthDetails()
+ {
+ try {
+
+ log_message('error', 'Retail Auth Update Request Received');
+
+ $requestData = $this->request->getJSON();
+
+ $client_id = $requestData->client_id ?? null;
+ $email_id = $requestData->email_id ?? null;
+ $mobile_number = $requestData->mobile_number ?? null;
+ $otp = $requestData->otp ?? null;
+ $mpin = $requestData->mpin ?? null;
+ $password = $requestData->password ?? null;
+
+ /** Check if at least one identification exists */
+ if (!$client_id && !$email_id && !$mobile_number) {
+ log_message('error', 'Identification missing: Need client_id or mobile/email.');
+ return $this->respond(['status' => false,'message' => 'client_id, email or mobile number is required.']);
+ }
+
+ /** Find client by ID or Email or Mobile */
+ $clientQuery = $this->clientModel->where('is_active', 1);
+
+ if ($client_id) {
+ $clientQuery->where('id', $client_id);
+ } elseif ($email_id) {
+ $clientQuery->where('email', $email_id);
+ } elseif ($mobile_number) {
+ $clientQuery->where('phone', $mobile_number);
+ }
+
+ $clientData = $clientQuery->get()->getRowArray();
+
+ /** If no client found, return error */
+ if (!$clientData) {
+ log_message('error', 'Client not found for given identifier.');
+ return $this->respond(['status' => false,'message' => 'Client not found.']);
+ }
+
+ /** Now update fields that exist in request */
+ $updateData = [];
+
+ if ($otp) {
+ $updateData['otp'] = $otp;
+ }
+
+ if ($mpin) {
+ $updateData['mpin'] = password_hash($mpin, PASSWORD_DEFAULT); // Secure MPIN Hash
+ }
+
+ if ($password) {
+ $updateData['password'] = password_hash($password, PASSWORD_DEFAULT); // Secure Password Hash
+ }
+
+ /** If nothing to update */
+ if (empty($updateData)) {
+ log_message('error', 'No valid fields to update (OTP/MPIN/Password missing)');
+ return $this->respond(['status' => false,'message' => 'No valid credentials provided for update.']);
+ }
+
+ /** Update */
+ $updated = $this->clientModel->where('id', $clientData['id'])->set($updateData)->update();
+
+ if ($updated) {
+ log_message('error', "Credentials updated successfully for Client ID: {$clientData['id']}");
+ return $this->respond(['status' => true,'message' => 'Credentials updated successfully.']);
+ } else {
+ log_message('error', "Failed updating credentials for Client ID: {$clientData['id']}");
+ return $this->respond(['status' => false,'message' => 'Failed to update credentials.']);
+ }
+
+ } catch (\Exception $e) {
+
+ log_message('error', 'Exception in updateRetailAuthDetails: ' . $e->getMessage());
+ return $this->respond(['status' => false,'message' => 'Unexpected error occurred.','error' => $e->getMessage()], 500);
+ }
+ }
+
+ public function getVerifiedRetailUserData()
+ {
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedRetailUserData: Received payload = " . json_encode($this->request->getJSON() ?? []));
+
+ try {
+
+ $mobile_number = isset($this->request->getJSON()->mobile_number) ? $this->request->getJSON()->mobile_number : null;
+ $email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null;
+ $otp = isset($this->request->getJSON()->otp) ? $this->request->getJSON()->otp : null;
+ $client_id = $this->request->getJSON()->client_id ?? null;
+
+ if(empty($otp)){
+ return $this->respond(['status' => 'OTP is required','code' => 400,'message' => 'OTP is required'], 200);
+ }
+
+ if (empty($mobile_number) && empty($email_id)) {
+ return $this->respond(['status' => 'failed','code' => 400,'message' => 'Mobile number or Email ID is required'], 200);
+ }
+
+ if (!empty($mobile_number)) {
+
+ $builder = $this->clientModel
+ ->select('clients.*')
+ ->join('policy_transaction', 'policy_transaction.client_id = clients.id')
+ ->where('policy_transaction.is_active', 1)
+ ->where('policy_transaction.action_type', "inception")
+ ->where('clients.is_active', 1)
+ ->where('clients.phone', $mobile_number);
+
+ if (!empty($otp)) {
+ $builder->where('clients.otp', $otp);
+ }
+
+ if (!empty($old_mpin)) {
+ $builder->where('clients.mpin', $old_mpin);
+ }
+
+ $retailUserData = $builder->orderBy('clients.id', 'desc')->first();
+ } else {
+
+ $builder = $this->clientModel
+ ->select('clients.*')
+ ->join('policy_transaction', 'policy_transaction.client_id = clients.id')
+ ->where('policy_transaction.is_active', 1)
+ ->where('policy_transaction.action_type', "inception")
+ ->where('clients.is_active', 1)
+ ->where('clients.email', $email_id);
+
+ if (!empty($otp)) {
+ $builder->where('clients.otp', $otp);
+ }
+
+ if (!empty($old_mpin)) {
+ $builder->where('clients.mpin', $old_mpin);
+ }
+
+ $retailUserData = $builder->orderBy('clients.id', 'desc')->first();
+ }
+
+ $lastQuery = $this->clientModel->db->getLastQuery();
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedRetailUserData: Last Executed Query: " . $lastQuery);
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedRetailUserData: retailUserData: " . json_encode($retailUserData ?? []));
+
+
+ if ($retailUserData && isset($this->request->getJSON()->otp) )
+ {
+ $auth = HttpRequestHelper::getRequestInfo();
+ if ($auth) {
+ $data = [
+ 'user_id' => $retailUserData['id'],
+ 'user_type' => 'retail_user',
+ 'ip' => $auth['ip'],
+ 'platform' => $auth['platform'],
+ 'broswer' => $auth['browser'],
+ ];
+ $this->authHistoryModel->insert($data);
+ }
+
+ $retailUserData['client_id'] = null;
+ $retailUserData['client_branch_id'] = null;
+ $retailUserData['emp_code'] = null;
+ $retailUserData['emp_status'] = null;
+ $retailUserData['name'] = $retailUserData['client_name'];
+ $retailUserData['email_corporate'] = $retailUserData['email'];
+ $retailUserData['mobile'] = $retailUserData['phone'];
+ $retailUserData['token_type'] = "retail";
+ $result = JWTToken::encode($retailUserData);
+
+ if(isset($this->request->getJSON()->otp)){
+ $this->clientModel->where('id', $retailUserData['id'])->where('otp', $otp)->set(['otp'=>null])->update();
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedRetailUserData: Reset the otp to null");
+ }
+
+
+ return $this->respond(['status' => 'success','code' => 200,'data' => $result],200);
+
+ } else {
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedRetailUserData: Employee not verified POST");
+ return $this->respond(['status' => 'failed','code' => 404,'data' => "", 'message' => 'Invalid OTP'],200);
+ }
+ } catch (\Exception $e) {
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedRetailUserData: Exception: " . $e->getMessage() . " --- Line: " . $e->getLine() . " --- Trace: " . $e->getTraceAsString());
+ return $this->respond(['status' => 'failed','code' => 500,'data' => "", 'message' => "Invalid OTP", 'error' => $e->getMessage()],500);
+ }
+ }
+
}
\ No newline at end of file
diff --git a/app/Controllers/RuleImportController.php b/app/Controllers/RuleImportController.php
index d1647bae..e624fbad 100644
--- a/app/Controllers/RuleImportController.php
+++ b/app/Controllers/RuleImportController.php
@@ -63,6 +63,19 @@ class RuleImportController extends AdminController
public function commissionFileUploadList()
{
+
+ // print_rr($this->ruleImportService->processUpload([
+ // 'id' => 60,
+ // 'file_name' => 'Sample_commission_file-New.xlsx',
+ // 'insurer_id' => 77,
+ // 'department' => 'motor',
+ // 'commission_month' => '2025-11-10',
+ // 'created_by' => 10
+ // ]));
+ // die();
+
+
+
$data['page_name'] = "Commision File Upload";
$data['departments'] = $this->departments;
$data['insurers'] = $this->insurerModel->where('is_active', 1)->findAll();
diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php
index 87620e51..ac104bf3 100644
--- a/app/Controllers/TicketController.php
+++ b/app/Controllers/TicketController.php
@@ -910,7 +910,7 @@ class TicketController extends BaseController
$data['ticket_history'] = $this->ticketHistory($ticket_id);
$data['ticket_check_list'] = db_connect()->table('ticket_check_list')->where('is_active', 1)->where('ticket_type_id', $ticket_data['ticket_type_id'])->get()->getResultArray();
if (!empty($ticket_data['client_policy_id'])){
- $ticket_data['client_policy_id_text'] = $this->clientPolicyModel->select('concat(policy_type.policy_type,"-",client_policy.policy_no) as client_policy_name')->join('policy_type','policy_type.id = client_policy.policy_type_id and policy_type.is_active = 1')->where('client_policy.id',$ticket_data['client_policy_id'])->first()['client_policy_name'];
+ $ticket_data['client_policy_id_text'] = $this->clientPolicyModel->select('concat(policy_type.policy_type,"-",client_policy.policy_no) as client_policy_name')->join('policy_type','policy_type.id = client_policy.policy_type_id and policy_type.is_active = 1')->where('client_policy.id',$ticket_data['client_policy_id'])->first()['client_policy_name'] ?? "N/A";
}
// dd($data);
$data['ticket_data'] = $ticket_data;
@@ -2837,6 +2837,32 @@ class TicketController extends BaseController
echo $errorMessage;
}
}
+
+ // -------- END CLAIM DUMP UPLOAD ----------------------------------------------------------------------------------------------
+ public function saveIRDocsJson()
+ {
+ $ticket_id = $this->request->getPost('ticket_id');
+ $required_docs = $this->request->getPost('required_docs');
+
+ if(empty($ticket_id)){
+ return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to save Docs'], 200);
+ }
+
+ if(empty($required_docs)){
+ return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to save Docs'], 200);
+ }
+
+ db_connect()->query(
+ "UPDATE ticket_master SET required_docs = ? WHERE id = ?",
+ [$required_docs, $ticket_id]
+ );
+
+ $required_docs = $this->ticketMasterModel->select('required_docs')->where('id', $ticket_id)->first();
+ $required_docs = json_decode($required_docs['required_docs'] ?? '{}', true) ?? [];
+
+ return $this->respond(['status' => true, 'code' => 200, 'message' => 'IR docs saved successfully', 'data' => $required_docs], 200);
+
+ }
}
diff --git a/app/Controllers/UserController.php b/app/Controllers/UserController.php
index ea0e4fb8..3879b49d 100755
--- a/app/Controllers/UserController.php
+++ b/app/Controllers/UserController.php
@@ -20,6 +20,7 @@ use App\Models\AuthHistoryModel;
use App\Models\UserActivityHistoryModel;
use App\Models\PartnerStaffModel;
use App\Models\PartnerManagerIncentiveFileModel;
+use App\Models\NhanceBranchModel;
class UserController extends AdminController
@@ -36,6 +37,7 @@ class UserController extends AdminController
protected $userActivityHistoryModel;
protected $partnerStaffModel;
protected $partnerManagerIncentiveFileModel;
+ protected $nhanceBranchModel;
public function __construct()
{
@@ -51,6 +53,7 @@ class UserController extends AdminController
$this->userActivityHistoryModel = new UserActivityHistoryModel();
$this->partnerStaffModel = new PartnerStaffModel();
$this->partnerManagerIncentiveFileModel = new PartnerManagerIncentiveFileModel();
+ $this->nhanceBranchModel = new NhanceBranchModel();
}
public function list()
@@ -63,6 +66,8 @@ class UserController extends AdminController
// print_r($data); die;
$data['roleData'] = $this->roleModel->select('id, role')->findAll();
$data['teamData'] = $this->teamModel->select('id, name')->where('is_active',1)->findAll();
+ $data['user_data'] = $this->userModel->where('is_active',1)->findAll();
+ $data['NHanceBranchData'] = $this->nhanceBranchModel->select('id, branch_name')->where('is_active',1)->findAll();
$this->loadLayout('UserList', $data);
}
@@ -70,6 +75,7 @@ class UserController extends AdminController
public function create()
{
$this->myLogger->logme('error', 'User create function called');
+ // dd($this->request->getPost());
$teams = $this->request->getPost('team');
//if this is get method return to user creation page
diff --git a/app/Controllers/VidalApiController.php b/app/Controllers/VidalApiController.php
index 3a6e8b56..78fc7d57 100644
--- a/app/Controllers/VidalApiController.php
+++ b/app/Controllers/VidalApiController.php
@@ -7,25 +7,32 @@ use CodeIgniter\HTTP\ResponseInterface;
class VidalApiController extends BaseController
{
- public function index()
+ protected $db;
+
+ public function __construct()
{
- //
+ $this->db = \Config\Database::connect();
}
- function fileUploadToVidal()
+ function uploadFileToVidal($filePath,$filename)
{
- $apiUrl = "https://devapigw.vidalhealthtpa.com/partner-integration/api/files/upload-url";
+ // $apiUrl = "https://devapigw.vidalhealthtpa.com/partner-integration/api/files/upload-url";
+ $apiUrl = getenv('VIDAL_API_BASE_URL').'/files/upload-url';
$subscriptionKey = getenv('VIDAL_API_SUBSCRIPTION_KEY');
+ log_message('error', "Starting file upload process for filename: $filename | Path: $filePath");
+
// Step 1: Get signed URL from Vidal API
- $filePath = '/opt/lampp/htdocs/nhance/writable/uploads/claim_files/1760013019_73d94af7b96ddc2e3d51.png';
- $payload = json_encode(["scope" => 'document type' , 'fileName' => '1760013019_73d94af7b96ddc2e3d51.png']);
+ // $filePath = '/opt/lampp/htdocs/nhance/writable/uploads/claim_files/1760013019_73d94af7b96ddc2e3d51.png';
+ $payload = json_encode(["scope" => 'document type' , 'fileName' => $filename]);
$headers = [
"Content-Type: application/json",
"Ocp-Apim-Subscription-Key: $subscriptionKey"
];
+ log_message('error', "Requesting signed URL from Vidal API: $apiUrl | Payload: $payload");
+
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
@@ -34,19 +41,23 @@ class VidalApiController extends BaseController
$response = curl_exec($ch);
if (curl_errno($ch)) {
- die("Curl error while requesting signed URL: " . curl_error($ch));
+ log_message('error', "Curl error while requesting signed URL: " . curl_error($ch));
+ return ["status" => false, "message" => curl_error($ch)];
}
curl_close($ch);
$responseData = json_decode($response, true);
-
- if (!isset($responseData['data']['signedUrl'])) {
- die("Failed to get signed URL. Response: " . $response);
+
+ if (!isset($responseData['data']['signedUrl']) || !isset($responseData['data']['fileId'])) {
+ log_message('error', "Invalid signed URL response received: " . json_encode($responseData));
+ return ["status" => false, "message" => "Invalid signed URL response", "response" => $responseData];
}
$signedUrl = $responseData['data']['signedUrl'];
$fileId = $responseData['data']['fileId'];
+ log_message('error', "Received signed URL & fileId. fileId: $fileId");
+
// Step 2: Upload file to signed URL using PUT (Azure Blob)
$fileSize = filesize($filePath);
$fileContent = fopen($filePath, 'r');
@@ -62,28 +73,337 @@ class VidalApiController extends BaseController
]);
$uploadResponse = curl_exec($ch2);
-
$httpCode = curl_getinfo($ch2, CURLINFO_HTTP_CODE);
- if (curl_errno($ch2)) {
- die("Curl error while uploading file: " . curl_error($ch2));
- }
+ $curlErr = curl_error($ch2);
+
fclose($fileContent);
curl_close($ch2);
- if ($httpCode !== 201 && $httpCode !== 200) {
- die("File upload failed. HTTP Code: $httpCode\nResponse: $uploadResponse");
+ if ($curlErr) {
+ log_message('error', "Curl error during file upload: $curlErr");
+ return ["status" => false, "message" => "File upload failed", "data" => $curlErr];
+ }
+
+ if ($httpCode !== 200 && $httpCode !== 201) {
+ log_message('error', "File upload failed with HTTP Code: $httpCode | Response: $uploadResponse");
+ return [
+ "status" => false,
+ "message" => "File upload failed",
+ "httpCode" => $httpCode,
+ "response" => $uploadResponse
+ ];
}
// Step 3: Return File ID for reference
- return $this->response->setJSON( [
+ return [
"status" => true,
"message" => "File uploaded successfully",
"fileId" => $fileId,
"signedUrl" => $signedUrl,
- "uploadResponse" => json_decode($uploadResponse, true)
- ]);
+ "uploadResponse" => json_decode($uploadResponse, true)
+ ];
}
+ public function SubmitClaim ($claimId = 515)
+ {
+ helper('api');
+
+ // Fetch the data from DB
+ $data = $this->db->table('ticket_master tm')
+ ->select('
+ tm.id,
+ tm.emp_mobile as mobileNo,
+ tm.emp_mail as emailId,
+ tm.doa as admissionDate,
+ tm.dod as dischargeDate,
+ tm.hospital_name as hospitalName,
+ tm.hospital_address as hospitalAddress,
+ tm.hospital_state as hospitalState,
+ tm.hospital_city as hospitalCity,
+ tm.hospital_pin_code as hospitalPinCode,
+ tm.hospital_phone_no as hospitalPhoneNo,
+ tm.claim_amount as requestedAmount,
+ tm.tpa_no as dependentUniqueId,
+ cp.policy_no as policyNo,
+ e.emp_code as memberId,
+ tn.note as disease,
+ tn.note as reasonForHospitalization,
+ cf.url as fileName,
+ cf.url as filePath,
+ pt.policy_type as typeOfClaim,
+ ep.tpa_id as empanelmentNo,
+
+ ')
+ ->join('employees e', 'e.id = tm.emp_id', 'left')
+ ->join('client_policy cp', 'tm.client_policy_id = cp.id', 'left')
+ ->join('policy_type pt', 'pt.id = cp.policy_type_id', 'left')
+ ->join('employee_polices ep', 'ep.employee_id = e.id AND ep.client_policy_id = cp.id', 'left')
+ ->join('ticket_notes tn', 'tn.ticket_id = tm.id', 'left')
+ ->join('claim_files cf', "cf.ticket_id = tm.id AND cf.file_type = 2 and cf.mime_type = 'application/pdf'", 'left')
+ ->where('tm.id', $claimId)
+ ->get()
+ ->getRowArray(); // single record
+
+ if (count($data) && $data['filePath'] == null) {
+ log_message('error', "Submit claim failed - Claim or File Missing");
+ return $this->response->setJSON(['status' => false,'message' => 'Claim or File Missing', ]);
+ }
+
+ $filePath = $data['filePath'] ?? '';
+ $filename = basename($filePath);
+ $filePath = WRITEPATH . 'uploads/claim_files/'.$filename;
+
+ // dd($data);
+ // Upload file first
+
+ $upload = $this->uploadFileToVidal($filePath,$filename);
+ if ($upload['status'] !== true) {
+ log_message('error', "Submit claim failed - File upload failed");
+ return $this->response->setJSON([
+ 'status' => false,
+ 'message' => 'File upload failed',
+ 'data' => $upload
+ ]);
+ }
+
+ $fileId = $upload['fileId'];
+ // $url = 'https://devapigw.vidalhealthtpa.com/partner-integration/api/claims/submit';
+ $url = getenv('VIDAL_API_BASE_URL').'/claims/submit';
+ $method = 'POST';
+
+ $headers = [
+ 'Content-Type: application/json',
+ 'Ocp-Apim-Subscription-Key:' .getenv('VIDAL_API_SUBSCRIPTION_KEY').'',
+ ];
+
+ $body = [
+ 'policyNo' => $data['policyNo'],
+ 'dependentUniqueId' => $data['dependentUniqueId'],
+ 'typeOfClaim' => "Main hospitalization claim",
+ 'claimSubType' => "OPD",
+ 'requestedAmount' => $data['requestedAmount'],
+ 'ailmentType' => "Non covid",
+ 'admissionDate' => change_date_format($data['admissionDate'], 'Y-m-d', 'd-m-Y'),
+ 'dischargeDate' => change_date_format($data['dischargeDate'], 'Y-m-d', 'd-m-Y'),
+ 'hospitalName' => $data['hospitalName'],
+ 'empanelmentNo' => 0,
+ "ailmentName" => "hospitalization",
+ "hospitalAddress" => $data['hospitalAddress'] ?? null,
+ "hospitalState" => $data['hospitalState'] ?? null,
+ "hospitalCity" => $data['hospitalCity'] ?? null,
+ "hospitalPinCode" => $data['hospitalPinCode'] ?? null,
+ "hospitalPhoneNo" => $data['hospitalPhoneNo'] ?? null,
+ "fileId" => $fileId,
+ "bankDetails" => [
+ "accountHolderName" => null,
+ "accountType" => null,
+ "accountNo" => null,
+ "ifscCode" => null,
+ ],
+ ];
+ // dd($body);
+
+ log_message('error', 'TPA CLAIM PUSH | claimId: '.$claimId.' | payload: '.json_encode($body));
+
+ // $body = [
+ // 'policyNo' => "351500/D0534/PP/20-20/PC",
+ // 'dependentUniqueId' => "EN000000182-C-41",
+ // 'typeOfClaim' => "Main hospitalization claim",
+ // 'claimSubType' => "Hospitalization",
+ // 'requestedAmount' => "2500",
+ // 'ailmentType' => "Non covid",
+ // 'admissionDate' => "01-12-2025",
+ // 'dischargeDate' => "01-12-2025",
+ // 'hospitalName' => "AKSHAY SUPER SPECIALITY HOSPITAL",
+ // 'empanelmentNo' => "HOS-MUM-031423",
+ // "ailmentName" => "Cold",
+ // "hospitalAddress" => "No. 6, Officers Colony, Puthur.,dfgdfgdfg,dfgdfg,560058",
+ // "hospitalState" => "karnataka",
+ // "hospitalCity" => "bangalore",
+ // "hospitalPinCode" => "560036",
+ // "hospitalPhoneNo" => "1234567890",
+ // "bankDetails" => [
+ // "accountHolderName" =>"Testing claim",
+ // "accountType" =>"savings",
+ // "accountNo" =>"1234567890",
+ // "ifscCode" =>"ICICI098768"
+ // ],
+ // "fileId" => "https://devapigw.vidalhealthtpa.com/doc-storage/api/private/691eda388973c60b83f80568"
+ // ];
+
+
+ $response = call_third_party_api($url, $method, $headers, $body);
+
+ if($response['status'] != true){
+ log_message('error', 'TPA CLAIM PUSH FAILED | claimId: '.$claimId.' | response: '.json_encode($response));
+ return;
+ }
+
+ // return $this->response->setJSON($response);
+
+ if($response['data']['status'] == 'SUCCESS')
+ {
+ $claimNO = $response['data']['data']['claimNO'] ?? null;
+ $claimInwardNO = $response['data']['data']['claimInwardNO'] ?? null;
+
+ if(!empty($claimNO) && !empty($claimInwardNO)){
+
+ log_message('error', 'TPA CLAIM PUSH SUCCESS | claimId: '.$claimId.' | claimNO: '.$claimNO.' | claimInwardNO: '.$claimInwardNO);
+
+ $this->db->table('ticket_master')
+ ->where('id',$claimId)
+ ->update([ 'tpa_claim_push_reference_no' => $claimInwardNO , 'tpa_claim_id' => $claimNO ]);
+
+ return;
+
+ } else {
+ log_message('error', 'TPA CLAIM PUSH API SUCCESS BUT claimNO,claimInwardNO EMPTY | claimId: '.$claimId.' | response: '.json_encode($response));
+ return;
+ }
+ }else{
+ log_message('error', 'TPA CLAIM PUSH API FAILED | claimId: '.$claimId.' | response: '.json_encode($response));
+ return;
+ }
+ }
+
+ function getWellnessSSORedirectUrl($email = 'test@getvisitapp.com')
+ {
+ log_message('info', "SSO: Starting authentication for email: $email");
+
+ // ---------- CONFIG ----------
+ $authUrl = env('VIDAL_WELLNESS_BASE_URL');
+ $subscriptionKey = env('VIDAL_WELLNESS_SUBSCRIPTION_KEY');
+ $apiVersion = "1";
+
+ // Provided Base64 AES key
+ $base64Key = env('VIDAL_WELLNESS_BASE64_KEY');
+ $key = base64_decode($base64Key);
+
+ log_message('info', "SSO: Config loaded, Auth URL: $authUrl");
+
+ // ---------- STEP 1: Build plaintext payload ----------
+ $plainPayload = json_encode([
+ "email" => $email,
+ // "corporateId" => env('VIDAL_WELLNESS_CORPORATE_ID'),
+ "urlIdentifier" => env('VIDAL_WELLNESS_URL_IDENTIFIER')
+ ]);
+
+ // ---------- STEP 2: Encrypt payload ----------
+ $iv = random_bytes(16);
+ $encryptedRaw = openssl_encrypt($plainPayload, "AES-256-CBC", $key, OPENSSL_RAW_DATA, $iv);
+
+ $encryptedPayload = base64_encode($iv) . ":" . base64_encode($encryptedRaw);
+
+ log_message('info', "SSO: Payload encrypted successfully");
+
+ // ---------- STEP 3: Call Authentication API ----------
+ $requestBody = json_encode([
+ "payload" => $encryptedPayload,
+ "source" => env('VIDAL_WELLNESS_SUB_PARTNER_ID'),
+ "subPartnerId" => env('VIDAL_WELLNESS_SUB_PARTNER_ID')
+ ]);
+
+ $headers = [
+ "Ocp-Apim-Subscription-Key: $subscriptionKey",
+ "apiver: $apiVersion",
+ "mode: encrypt",
+ "Content-Type: application/json"
+ ];
+
+ $ch = curl_init($authUrl);
+ curl_setopt($ch, CURLOPT_POST, true);
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
+ curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+
+ $apiResponse = curl_exec($ch);
+ $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+ $curlError = curl_error($ch);
+ curl_close($ch);
+
+ log_message('info', "SSO: API response received, HTTP Code: $httpCode");
+
+ // Check for cURL errors
+ if ($curlError) {
+ log_message('error', "SSO: cURL error - $curlError");
+ return ['status' => 'failed','message' => $curlError];
+ }
+
+ // Check HTTP status
+ if ($httpCode !== 200) {
+ log_message('error', "SSO: HTTP error - Code: $httpCode, Response: $apiResponse");
+ return ['status' => 'failed','message' => "HTTP error: $httpCode" , "response" => $apiResponse ];
+ }
+
+ $jsonResponse = json_decode($apiResponse, true);
+
+ // Check JSON decode error
+ if (json_last_error() !== JSON_ERROR_NONE) {
+ log_message('error', "SSO: JSON decode error - " . json_last_error_msg());
+ return ['status' => 'failed','message' => "JSON decode error: " . json_last_error_msg(), "response" => $apiResponse];
+ }
+
+ // Check API response status
+ if (!isset($jsonResponse["status"]) || $jsonResponse["status"] !== "success") {
+ log_message('error', "SSO: API error - " . json_encode($jsonResponse));
+ return ['status' => 'failed','message' => "API error", "response" => $jsonResponse];
+ }
+
+ if (!isset($jsonResponse["data"])) {
+ log_message('error', "SSO: Missing data field in response");
+ return ['status' => 'failed','message' => "Invalid API response - missing data field", "response" => $jsonResponse];
+ }
+
+ log_message('info', "SSO: API response validated successfully");
+
+ // ---------- STEP 4: Decrypt response ----------
+ log_message('info', "SSO: Starting response decryption");
+
+ $dataParts = explode(":", $jsonResponse["data"]);
+
+ if (count($dataParts) !== 2) {
+ log_message('error', "SSO: Invalid encrypted data format");
+ return ['status' => 'failed','message' => "Invalid encrypted data format", "data" => $jsonResponse["data"]];
+ }
+
+ list($ivBase64, $cipherBase64) = $dataParts;
+
+ $respIv = base64_decode($ivBase64);
+ $respCipher = base64_decode($cipherBase64);
+
+ if ($respIv === false || $respCipher === false) {
+ log_message('error', "SSO: Base64 decode error");
+ return ['status' => 'failed','message' => "Base64 decode error"];
+ }
+
+ $decryptedJson = openssl_decrypt($respCipher, "AES-256-CBC", $key, OPENSSL_RAW_DATA, $respIv);
+
+ if ($decryptedJson === false) {
+ log_message('error', "SSO: Decryption failed");
+ return ['status' => 'failed','message' => "Decryption failed"];
+ }
+
+ $decryptedData = json_decode($decryptedJson, true);
+
+ if (json_last_error() !== JSON_ERROR_NONE) {
+ log_message('error', "SSO: Decrypted JSON decode error - " . json_last_error_msg());
+ return ['status' => 'failed','message' => "Decrypted JSON decode error: " . json_last_error_msg()];
+ }
+
+ if (!isset($decryptedData["redirectUrl"])) {
+ log_message('error', "SSO: redirectUrl missing in decrypted data");
+ return ['status' => 'failed','message' => "redirectUrl missing", "decrypted" => $decryptedData];
+ }
+
+ // ---------- FINAL ----------
+ log_message('info', "SSO: Authentication successful, redirectUrl obtained");
+ return ['status' => 'success','data' => $decryptedData["redirectUrl"]];
+ }
+
+
+
+ //----------yet to start only submit claim given
+
public function fileUpload()
{
@@ -132,54 +452,6 @@ class VidalApiController extends BaseController
}
- public function SubmitClaim ($claimId = null)
- {
- helper('api');
-
- $url = getenv('VIDAL_API_BASE_URL').'/claims/submit';
- $method = 'POST';
-
- $headers = [
- 'Content-Type: application/json',
- 'Ocp-Apim-Subscription-Key:' .getenv('VIDAL_API_SUBSCRIPTION_KEY').'',
- ];
-
- $body = [
- 'policyNo' => "351500/D0534/PP/20-20/PC",
- 'enrollmentId' => "BLR-NC-D0534-004-0000033-A",
- 'typeOfClaim' => "Main hospitalization claim",
- 'claimSubType' => "Hospitalization",
- 'requestedAmount' => "3500",
- 'ailmentType' => "Non covid",
- 'admissionDate' => "20-07-2023",
- 'dischargeDate' => "23-07-2023",
- 'hospitalName' => "DELL HOSPITAL PVT LTD",
- 'empanelmentNo' => "HOS-BLR-021280",
- 'documentType' => "Claim",
- 'ailmentName' => "Cold",
- 'hospitalAddress' => "abc",
- 'hospitalState' => "karnataka",
- 'hospitalCity' => "bangalore",
- 'hospitalPinCode' => "560036",
- 'hospitalPhoneNo' => "7656879899",
- 'fileId' => "https://devapigw.vidalhealthtpa.com/doc-storage/api/private/69130dfad1414b35a775480f",
- ];
-
-
-
- $response = call_third_party_api($url, $method, $headers, $body);
-
- if($response['status'] != true){
- return $this->response->setJSON([
- 'status' => false,
- 'message' => 'failed.',
- 'data' => $response
- ]);
- }
-
- return $this->response->setJSON($response);
- }
-
public function claimStatus ($claimId = null)
{
helper('api');
diff --git a/app/Filters/CommissionApiFilter.php b/app/Filters/CommissionApiFilter.php
index d7ae956e..b2707b98 100644
--- a/app/Filters/CommissionApiFilter.php
+++ b/app/Filters/CommissionApiFilter.php
@@ -10,11 +10,19 @@ class CommissionApiFilter implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
-
+ // return null;
// Read API key from header
- // $authHeader = $request->getHeaderLine('X');
+ $authHeader = $request->getHeaderLine('AUTHORIZATION');
+ if(empty($authHeader))
+ {
$authHeader = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
- // echo $authHeader;die();
+ }
+
+ // $requestHeaders = getallheaders();
+ // // $authHeader = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
+ // // $authHeader = $_SERVER['Authorization'];
+ // print_r($authHeader);
+ // print_r($_SERVER);die();
if (empty($authHeader)) {
return service('response')->setJSON([
'success' => false,
diff --git a/app/Filters/Cors.php b/app/Filters/Cors.php
index c47f2762..6aae35d9 100644
--- a/app/Filters/Cors.php
+++ b/app/Filters/Cors.php
@@ -107,11 +107,11 @@ class Cors implements FilterInterface
);
}
- $this->log('CORS filter initialized', [
- 'allowed_origins' => $this->allowedOrigins,
- 'allow_credentials' => $this->allowCredentials,
- 'allowed_methods' => $this->allowedMethods,
- ]);
+ // $this->log('CORS filter initialized', [
+ // 'allowed_origins' => $this->allowedOrigins,
+ // 'allow_credentials' => $this->allowCredentials,
+ // 'allowed_methods' => $this->allowedMethods,
+ // ]);
}
/**
diff --git a/app/Filters/VerifyAppSignature.php b/app/Filters/VerifyAppSignature.php
new file mode 100644
index 00000000..a5257b21
--- /dev/null
+++ b/app/Filters/VerifyAppSignature.php
@@ -0,0 +1,36 @@
+getHeaderLine('App-Signature');
+
+ // Load the server's expected signature from the .env
+ $validSignature = getenv('APP_SIGNATURE');
+
+ // Check if signature is valid
+ if ($clientSignature !== $validSignature) {
+ return service('response')
+ ->setStatusCode(403)
+ ->setJSON([
+ 'status' => false,
+ 'message' => 'Forbidden: Invalid App Signature',
+ ]);
+ }
+
+ // allow request to proceed
+ }
+
+ public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
+ {
+ // nothing to do after response
+ }
+}
diff --git a/app/Helpers/excel_util_helper.php b/app/Helpers/excel_util_helper.php
index f3e97d0c..918a04c3 100755
--- a/app/Helpers/excel_util_helper.php
+++ b/app/Helpers/excel_util_helper.php
@@ -375,6 +375,10 @@ if (!function_exists('data_group_by_family')) {
if ($data_source == 'excel') {
if (!check_row_is_empty_or_null($row)) {
+ if(empty($action)){
+ $row['data_from'] = "excel";
+ }
+
// for this condition to avoid 5,00,000 to 500000
if($current_column_action == 'SI'){
$row[3] = removeNumberFormatting($row[3]);
@@ -392,6 +396,8 @@ if (!function_exists('data_group_by_family')) {
} else {
$result[$row[1]][] = $row;
}
+
+
}
} else if ($data_source = 'db') {
if (strtolower($row['relationship']) == 'self' && isset($result[$row['emp_code']])) {
@@ -939,6 +945,10 @@ if (!function_exists('calculate_premium_new')) {
// $result[] = $transformed_familiy_member_data;
}
+ if($fileArr['action'] == 'dependent_addition') {
+ $result = validatet_family_floter_rata_premium($result);
+ }
+
// dd($result);
return ($result);
//
@@ -1017,13 +1027,17 @@ if (!function_exists('transform_excel_data_to_db')) {
$result['self_rata_premium'] = $memArr['self_rata_premium'] ?? 0;
}
+ if(isset($memArr['data_from'])){
+ $result['data_from'] = $memArr['data_from'] ?? 'excel';
+ }
+
return $result;
}
}
}
-if (!function_exists('premium_calculation_manager')) {
- function premium_calculation_manager($emp_data, $policy_terms, $slab_details, $default_si = null)
+if (!function_exists('premium_calculation_manager_old')) {
+ function premium_calculation_manager_old($emp_data, $policy_terms, $slab_details, $default_si = null)
{
// dd($emp_data,$policy_terms,$slab_details,$default_si);
@@ -1429,8 +1443,8 @@ if (!function_exists('premium_calculation_manager')) {
}
}
-if (!function_exists('premium_calculation_manager_new')) {
- function premium_calculation_manager_new($emp_data, $policy_terms, $slab_details, $default_si = null)
+if (!function_exists('premium_calculation_manager')) {
+ function premium_calculation_manager($emp_data, $policy_terms, $slab_details, $default_si = null)
{
// dd($emp_data,$policy_terms,$slab_details,$default_si);
@@ -1913,6 +1927,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']['premium'] = $value['premium'];
$row['temp']['file_id'] = $value['file_id'];
array_push($return_data, ($row));
@@ -2873,35 +2888,597 @@ if (!function_exists('is_valid_or_empty_email')) {
}
if (!function_exists('validatet_family_floter_rata_premium')) {
- function validatet_family_floter_rata_premium($family){
-
+ function validatet_family_floter_rata_premium($family)
+ {
+ // If only two members, skip
if (count($family) === 2) {
- return $family; // skip if only two members
+ return $family;
}
+ // Count excel rows
+ $excelCount = count(array_filter($family, fn($r) =>
+ ($r['data_from'] ?? '') === 'excel'
+ ));
+
+ // Extract self row
+ $selfDataArr = array_filter($family, fn($r) =>
+ strtolower($r['relationship'] ?? '') === 'self'
+ );
+ $selfData = reset($selfDataArr);
+
$dependentRataGiven = false;
- foreach ($family as &$row) {
+ /**
+ * ---------------------------------------------------
+ * 1. RESET DEPENDENT PREMIUM IF SELF HAS SAME RATA
+ * ---------------------------------------------------
+ */
+ if (
+ !empty($selfData['temp']) &&
+ !empty($selfData['policy_details']) &&
+ ($selfData['temp']['premium'] ?? 0) == ($selfData['policy_details']['premium'] ?? 0)
+ ) {
+ foreach ($family as &$row) {
- // Skip if the member is self
- if (strtolower($row['relationship']) == 'self') {
- continue;
- }
+ if (strtolower($row['relationship'] ?? '') === 'self') {
+ continue;
+ }
- // For dependents
- if (isset($row['temp']['premium_type']) && $row['temp']['premium_type'] == 1) {
-
- if (!$dependentRataGiven) {
- // First eligible dependent keeps premium
- $dependentRataGiven = true;
- } else {
+ if (
+ ($row['temp']['premium_type'] ?? null) == 1 &&
+ ($row['data_from'] ?? '') === 'excel'
+ ) {
$row['policy_details']['rata_premimum'] = 0;
$row['policy_details']['gst'] = 0;
}
+ }
+ }
+ /**
+ * ---------------------------------------------------
+ * 2. APPLY FINAL PREMIUM ADJUSTMENT TO DEPENDENTS
+ * ---------------------------------------------------
+ */
+ foreach ($family as &$row) {
+
+ if (strtolower($row['relationship'] ?? '') === 'self') {
+ continue;
+ }
+
+ if (($row['temp']['premium_type'] ?? null) == 1) {
+
+ // FIRST excel dependent keeps premium
+ if (!$dependentRataGiven && ($row['data_from'] ?? '') === 'excel') {
+ $dependentRataGiven = true;
+ } else if (($row['data_from'] ?? '') === 'excel') {
+ $row['policy_details']['rata_premimum'] = 0;
+ $row['policy_details']['gst'] = 0;
+ }
}
}
return $family;
}
}
+
+
+
+if (!function_exists('validate_excel_value')) {
+ function validate_excel_value($value, $data_type, $format = null, $allowed_values = null)
+ {
+ switch ($data_type) {
+
+ case 'date':
+ return validate_date_value($value, $format);
+
+ case 'mobile':
+ return validate_mobile_value($value);
+
+ case 'email':
+ return validate_email_value($value);
+
+ case 'vehicle':
+ return validate_indian_vehicle_number($value);
+
+ default:
+ return [
+ 'status' => true,
+ 'error' => null
+ ];
+ }
+ }
+}
+
+if (!function_exists('validate_date_value')) {
+ function validate_date_value($value, $format)
+ {
+ if(empty($value)) {
+ return ['status' => true, 'error' => null]; // allow empty
+ }
+
+ $d = DateTime::createFromFormat($format, $value);
+
+ if ($d && $d->format($format) === $value) {
+ return ['status' => true, 'error' => null];
+ }
+
+ return [
+ 'status' => false,
+ 'error' => "Invalid date format. Expected format: {$format}"
+ ];
+ }
+}
+
+if (!function_exists('validate_mobile_value')) {
+ function validate_mobile_value($value)
+ {
+ if (preg_match('/^[0-9]{10}$/', $value)) {
+ return ['status' => true, 'error' => null];
+ }
+
+ return [
+ 'status' => false,
+ 'error' => "Invalid mobile number. Expected 10 digits."
+ ];
+ }
+}
+
+if (!function_exists('validate_email_value')) {
+ function validate_email_value($value)
+ {
+ if (filter_var($value, FILTER_VALIDATE_EMAIL)) {
+ return ['status' => true, 'error' => null];
+ }
+
+ return [
+ 'status' => false,
+ 'error' => "Invalid email address."
+ ];
+ }
+}
+
+if (!function_exists('validate_indian_vehicle_number')) {
+ function validate_indian_vehicle_number($number)
+ {
+ $number = strtoupper(trim($number));
+
+ // Normal Format:
+ // 2 letters (state) + 2 digits (district) + 1 or 2 letters (series) + 4 digits
+ $normalPattern = '/^[A-Z]{2}[0-9]{2}[A-Z]{1,2}[0-9]{4}$/';
+
+ // BH Series: 22BH1234AA
+ $bhPattern = '/^[0-9]{2}BH[0-9]{4}[A-Z]{2}$/';
+
+ if (preg_match($normalPattern, $number)) {
+ return ['status' => true, 'error' => null];
+ }
+
+ if (preg_match($bhPattern, $number)) {
+ return ['status' => true, 'error' => null];
+ }
+
+ return [
+ 'status' => false,
+ 'error' => "Invalid Vehicle Number"
+ ];
+ }
+}
+
+if (!function_exists('check_user_exist')) {
+ function check_user_exist($row, $col_key, $user_data)
+ {
+ // Get the uploaded value from the column
+ $input_value = trim($row[$col_key]);
+
+ // Loop DB user list
+ foreach ($user_data as $user) {
+
+ // Check if DB has 'first_name' key and matches input
+ if (isset($user['first_name']) && strtolower(trim($user['first_name'])) === strtolower($input_value)) {
+
+ return [
+ 'status' => true,
+ 'error' => null,
+ 'user' => $user,
+ ];
+ }
+ }
+
+ // If no user matched
+ return [
+ 'status' => false,
+ 'error' => "User '{$input_value}' not found in database."
+ ];
+ }
+}
+
+if (!function_exists('check_agent_exist')) {
+ function check_agent_exist($row, $agent_data)
+ {
+ // Get agent code from the uploaded row
+ $agent_code = trim($row[15]); // or use index if needed
+
+ // Loop agent data from DB
+ foreach ($agent_data as $agent) {
+ // Assuming DB keys: agent_code
+ if (isset($agent['agent_code']) && $agent['agent_code'] == $agent_code) {
+ return [
+ 'status' => true,
+ 'error' => null,
+ 'agent' => $agent,
+ ];
+ }
+ }
+
+ // If not matched
+ return [
+ 'status' => false,
+ 'error' => "Agent code '{$agent_code}' not found in database."
+ ];
+ }
+}
+
+if (!function_exists('check_rto_data')) {
+ function check_rto_data($row, $rto_master)
+ {
+ // Vehicle number from uploaded row
+ $vehicle_no = strtoupper(trim($row[2])); // Example: TN10AB1234
+
+ // Must be at least 4 characters to extract RTO
+ if (strlen($vehicle_no) < 4) {
+ return [
+ 'status' => false,
+ 'error' => "Invalid vehicle number format: '{$vehicle_no}'"
+ ];
+ }
+
+ // Extract State (first 2 letters) and RTO Code (next 2 digits)
+ $state_code = substr($vehicle_no, 0, 2); // TN
+ $rto_code = substr($vehicle_no, 2, 2); // 10
+
+ // Validate they are correct format
+ if (!ctype_alpha($state_code) || !ctype_digit($rto_code)) {
+ return [
+ 'status' => false,
+ 'error' => "Vehicle number '{$vehicle_no}' has invalid state or RTO code."
+ ];
+ }
+
+ // Loop RTO master data
+ foreach ($rto_master as $rto) {
+
+ // Expected DB fields: rto_state, rto_code
+ if (
+ isset($rto['rto_state']) &&
+ isset($rto['rto_code']) &&
+ strtoupper($rto['rto_state']) === $state_code &&
+ (string)$rto['rto_code'] === $rto_code
+ ) {
+ return [
+ 'status' => true,
+ 'error' => null,
+ 'rto_data' => $rto
+ ];
+ }
+ }
+
+ // Not found in RTO master
+ return [
+ 'status' => false,
+ 'error' => "RTO '{$state_code} {$rto_code}' not found in RTO master."
+ ];
+ }
+}
+
+if (!function_exists('check_vehicle_type')) {
+ function check_vehicle_type($row, $vehicle_type)
+ {
+ // Vehicle type from uploaded Excel row
+ $input_type = strtolower(trim($row[3])); // Example: CAR
+
+ // Loop vehicle type master
+ foreach ($vehicle_type as $vt) {
+
+ if (isset($vt['vehicle_type']) && strtolower($vt['vehicle_type']) == $input_type) {
+ return [
+ 'status' => true,
+ 'error' => null,
+ 'vehicle_type' => $vt,
+ ];
+ }
+ }
+
+ // Not found in master
+ return [
+ 'status' => false,
+ 'error' => "Vehicle type '{$input_type}' not found in master."
+ ];
+ }
+}
+
+if (!function_exists('check_policy_no')) {
+ function check_policy_no($row, $pt_data)
+ {
+ // Get policy number from Excel row
+ $policy_no = strtolower(trim($row[4]));
+
+ // Empty policy number
+ if ($policy_no === '') {
+ return [
+ 'status' => false,
+ 'error' => "Policy number is empty."
+ ];
+ }
+
+ // Loop all policy transactions (pt_data)
+ foreach ($pt_data as $pt) {
+
+ // Check policy_no exists in DB list
+ if (isset($pt['policy_no']) && strtolower($pt['policy_no']) == $policy_no) {
+ return [
+ 'status' => false,
+ 'error' => "Duplicate policy number '{$policy_no}' found in database."
+ ];
+ }
+ }
+
+ // If no match found → not duplicate
+ return [
+ 'status' => true,
+ 'error' => null
+ ];
+ }
+}
+
+if (!function_exists('check_insurer_exist')) {
+ function check_insurer_exist($row, $insurer_master)
+ {
+ // Get insurer short name from Excel row (col 7)
+ $short_name = strtolower(trim($row[7]));
+
+ foreach ($insurer_master as $insurer) {
+ if (
+ isset($insurer['short_name']) &&
+ strtolower($insurer['short_name']) === $short_name
+ ) {
+ return [
+ 'status' => true,
+ 'error' => null,
+ 'insurer' => $insurer // return entire insurer row for next validation
+ ];
+ }
+ }
+
+ return [
+ 'status' => false,
+ 'error' => "Insurer '{$short_name}' not found in database."
+ ];
+ }
+}
+
+if (!function_exists('check_insurer_branch_exist')) {
+ function check_insurer_branch_exist($row, $insurer_branch_master, $insurer)
+ {
+ // Get branch code from Excel row (col 8)
+ $branch_code = strtolower(trim($row[8]));
+
+ // Loop all branches
+ foreach ($insurer_branch_master as $branch) {
+
+ if (
+ isset($insurer['id']) && $branch['insurer_id'] == $insurer['id'] &&
+ strtolower($branch['branch_code']) == $branch_code
+ ) {
+ return [
+ 'status' => true,
+ 'error' => null,
+ 'branch' => $branch
+ ];
+ }
+ }
+
+ return [
+ 'status' => false,
+ 'error' => "Branch code '{$branch_code}' not found in database."
+ ];
+ }
+}
+
+if (!function_exists('check_nhance_branch')) {
+ function check_nhance_branch($row, $nhance_branch_master)
+ {
+ // Get branch name from Excel row (col 8)
+ $branch_name = strtolower(trim($row[1]));
+
+ // Loop all branches
+ foreach ($nhance_branch_master as $branch) {
+
+ if (
+ isset($branch['branch_name']) &&
+ strtolower($branch['branch_name']) == $branch_name
+ ) {
+ return [
+ 'status' => true,
+ 'error' => null,
+ 'branch' => $branch
+ ];
+ }
+ }
+
+ return [
+ 'status' => false,
+ 'error' => "Branch '{$branch_name}' not found in database."
+ ];
+ }
+}
+
+if (!function_exists('calculate_gst_amount')) {
+ function calculate_gst_amount($row) {
+
+ // Extract values
+ $base_premium = (float)trim($row[16]);
+ $non_commission_premium_amount = (float)trim($row[17]);
+ $tp_premium = (float)trim($row[18]);
+ $igst = (float)trim($row[19]);
+ $cgst = (float)trim($row[20]);
+ $sgst = (float)trim($row[21]);
+
+ // Total GST percentage
+ $gst_percentage = $igst + $cgst + $sgst;
+
+ // Step 1: Choose taxable amount
+ if ($non_commission_premium_amount > 0) {
+ // GST on non-commission premium
+ $taxable_amount = $non_commission_premium_amount;
+ } else {
+ // GST on base premium + TP premium
+ $taxable_amount = $base_premium + $tp_premium;
+ }
+
+ // Step 2: GST Amount calculation
+ $gst_amount = ($taxable_amount * $gst_percentage) / 100;
+
+ return round($gst_amount, 2);
+ }
+}
+
+if (!function_exists('check_gst_percentage')) {
+
+ function check_gst_percentage($row)
+ {
+ $igst = (float)trim($row[19]);
+ $cgst = (float)trim($row[20]);
+ $sgst = (float)trim($row[21]);
+
+ // CASE 1: IGST is entered → CGST & SGST must be zero
+ if ($igst > 0) {
+
+ if ($cgst > 0 || $sgst > 0) {
+ return [
+ 'status' => false,
+ 'error' => "Invalid GST configuration: When IGST is entered, CGST and SGST must be 0."
+ ];
+ }
+
+ return [
+ 'status' => true,
+ 'error' => null,
+ 'gst_type' => "IGST"
+ ];
+ }
+
+ // CASE 2: IGST = 0 → CGST and SGST must be entered together
+ if ($cgst > 0 || $sgst > 0) {
+
+ if ($cgst == 0 || $sgst == 0) {
+ return [
+ 'status' => false,
+ 'error' => "Invalid GST configuration: CGST and SGST must both be entered when IGST is 0."
+ ];
+ }
+
+ return [
+ 'status' => true,
+ 'error' => null,
+ 'gst_type' => "CGST+SGST"
+ ];
+ }
+
+ // CASE 3: No GST provided at all
+ return [
+ 'status' => false,
+ 'error' => "GST values missing: Enter either IGST or both CGST and SGST."
+ ];
+ }
+}
+
+if (!function_exists('calculateMotorPolicyAmounts')) {
+
+ function calculateMotorPolicyAmounts(array $data)
+ {
+ try {
+
+ // Parse incoming values (fallback to 0)
+ $bp = floatval($data['base_premium'] ?? 0);
+ $ncpa = floatval($data['non_commission_premium_amount'] ?? 0);
+ $tp = floatval($data['tp_premium'] ?? 0);
+ $igst = floatval($data['igst'] ?? 0);
+ $cgst = floatval($data['cgst'] ?? 0);
+ $sgst = floatval($data['sgst'] ?? 0);
+ $stamp = floatval($data['stamp_duty'] ?? 0);
+
+ $agreed_amount = floatval($data['agreed_amount'] ?? 0);
+
+ $ag_bp_per = floatval($data['agreed_bp_percentage'] ?? 0);
+ $ag_tp_per = floatval($data['agreed_tp_percentage'] ?? 0);
+
+ $std_bp_per = floatval($data['standard_bp_percentage'] ?? 0);
+ $std_tp_per = floatval($data['standard_tp_percentage'] ?? 0);
+
+ // Determine GST %
+ $gst_per = ($igst > 0) ? $igst : ($cgst + $sgst);
+
+ // Motor Policy Premium Logic
+ $tpTotal = $bp + $tp;
+
+ // GST without NCPA
+ $gst_per_amt = ($tpTotal * $gst_per) / 100;
+
+ // GST with NCPA
+ $ncpaTotal = $tpTotal + $ncpa;
+ $ncpa_gst_per_amt = ($ncpaTotal * $gst_per) / 100;
+
+ // Choose correct GST amount
+ $gst_amount = ($ncpa != 0) ? $ncpa_gst_per_amt : $gst_per_amt;
+
+ // Total amount payable
+ $total_amount = $tpTotal + $gst_amount + $stamp;
+
+ // Expected Amount
+ $sum_agreed = $ag_bp_per + $ag_tp_per;
+ $expected_amount = 0;
+
+ if ($agreed_amount > 0) {
+
+ $expected_amount = $agreed_amount; // Formula 1
+
+ } elseif ($sum_agreed > 0) {
+
+ // Formula 2 – Agreed %
+ $expected_amount =
+ (($bp * $ag_bp_per) / 100) +
+ (($tp * $ag_tp_per) / 100);
+
+ } else {
+
+ // Formula 3 – Standard %
+ $expected_amount =
+ (($bp * $std_bp_per) / 100) +
+ (($tp * $std_tp_per) / 100);
+ }
+
+
+ // Final return array
+ return [
+ 'gst_amount' => round($gst_amount, 2),
+ 'total_amount' => round($total_amount, 2),
+ 'expected_amount' => round($expected_amount, 2),
+ ];
+
+ } catch (\Throwable $e) {
+
+ log_message('error', 'Motor Policy Calculation Error: ' . $e->getMessage());
+ return [];
+ }
+ }
+}
+
+
+
+
+
+
+
+
+
+
diff --git a/app/Helpers/sendMailNotification.php b/app/Helpers/sendMailNotification.php
index fae31ef5..cc46a3cd 100755
--- a/app/Helpers/sendMailNotification.php
+++ b/app/Helpers/sendMailNotification.php
@@ -381,7 +381,7 @@ class sendMailNotification
}
$table_content .= $policy_name_for_policy_type . '';
- $table_content .= '| Name | '; @@ -1554,7 +1554,7 @@ class sendMailNotification // Generate summary table for addon if applicable if (count($Addon_list) > 0) { $table_content .= '
|---|
| Name | '; @@ -1709,7 +1709,7 @@ class sendMailNotification // Generate summary table for addon if applicable if (count($Addon_list) > 0) { $table_content .= '
|---|
| Name | '; @@ -1865,7 +1865,7 @@ class sendMailNotification if (count($Addon_list) > 0) { $table_content .= '
|---|
Advertisement Image Name |
+ Client Name |
+ Client Short Name |
Status |
Action |
||||||
|---|---|---|---|---|---|---|---|---|---|---|
| + | + | + | - - | -- | -