MERGE_UAT_COMMISSION_TPA_MINOR

This commit is contained in:
Ubuntu 2025-12-11 19:16:52 +05:30
commit 287f7d8a97
83 changed files with 23294 additions and 1687 deletions

View File

@ -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,
];
}
}
}

View File

@ -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.

View File

@ -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,
];
/**

View File

@ -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');
});

View File

@ -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"];
// }

View File

@ -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 ;
// }
// }

View File

@ -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);

View File

@ -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 = '<option value="">Select Document</option>';
$dropdown .= '<option value="other">Additional Document</option>';
foreach ($result as $row) {
$dropdown .= '<option value="' . esc($row['kyc_type_id']) . '">'
. esc($row['file_name']) .
'</option>';
}
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 --------------------------------------------------------------------------------

View File

@ -176,7 +176,7 @@ class DeployController extends AdminController
public function fedeploy()
{
$request = $this->request;
echo 'HI';die();
// Single zip file: <input type="file" name="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!';
}
}

View File

@ -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)
{

View File

@ -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');
}
}
}

View File

@ -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);
}
}
}

View File

@ -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]);

View File

@ -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;

View File

@ -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',
],
];

View File

@ -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'])){

View File

@ -0,0 +1,259 @@
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Controllers\BaseController;
class LogController extends BaseController
{
private $logPath;
public $dModel;
public $session;
public function __construct()
{
// Path to log files
$this->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');
}
}

View File

@ -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) {

View File

@ -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()

View File

@ -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,

File diff suppressed because it is too large Load Diff

View File

@ -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);
}
}
}

View File

@ -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();

View File

@ -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);
}
}

View File

@ -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

View File

@ -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');

View File

@ -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,

View File

@ -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,
// ]);
}
/**

View File

@ -0,0 +1,36 @@
<?php
namespace App\Filters;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
class VerifyAppSignature implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
// Get the header sent by the Flutter app
$clientSignature = $request->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
}
}

View File

@ -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 [];
}
}
}

View File

@ -381,7 +381,7 @@ class sendMailNotification
}
$table_content .= $policy_name_for_policy_type . '</h4></div>';
$table_content .= '<table data-custom-table-css="table" border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
$table_content .= '<table border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
// Add text-align: center to the table head
$table_content .= '<thead style="background-color: #02a8b5; color: #ffffff; text-align: center;">';
@ -518,7 +518,7 @@ class sendMailNotification
}
$table_content .= $policy_name_for_policy_type . ' ( Payable By Employee ) </h4></div>';
$table_content .= '<table data-custom-table-css="table" border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
$table_content .= '<table border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
// Add text-align: center to the table head
$table_content .= '<thead style="background-color: #02a8b5; color: #ffffff; text-align: center;">';
@ -555,7 +555,7 @@ class sendMailNotification
if (count($Addon_list) > 0) {
$table_content .= '<br><div style="text-align: left; font-size: 12px;"><div style="text-align:left;">';
$table_content .= '<table data-custom-table-css="table" border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
$table_content .= '<table border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
// Center align for table header and body
$table_content .= '<thead style="background-color: #02a8b5; color: #ffffff; text-align: center;">';
@ -738,7 +738,7 @@ class sendMailNotification
}
$table_content .= $policy_name_for_policy_type . '</h4></div>';
$table_content .= '<table data-custom-table-css="table" border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
$table_content .= '<table border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
// Add text-align: center to the table head
$table_content .= '<thead style="background-color: #02a8b5; color: #ffffff; text-align: center;">';
@ -824,7 +824,7 @@ class sendMailNotification
}
$table_content .= $policy_name_for_policy_type . ' ( Payable By Employee ) </h4></div>';
$table_content .= '<table data-custom-table-css="table" border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
$table_content .= '<table border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
// Add text-align: center to the table head
$table_content .= '<thead style="background-color: #02a8b5; color: #ffffff; text-align: center;">';
@ -862,7 +862,7 @@ class sendMailNotification
if (count($Addon_list) > 0) {
$table_content .= '<br><div style="text-align: left; font-size: 12px;"><div style="text-align:left;">';
$table_content .= '<table data-custom-table-css="table" border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
$table_content .= '<table border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
// Center align for table header and body
$table_content .= '<thead style="background-color: #02a8b5; color: #ffffff; text-align: center;">';
@ -1046,7 +1046,7 @@ class sendMailNotification
}
$table_content .= $policy_name_for_policy_type . '</h4></div>';
$table_content .= '<table data-custom-table-css="table" border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
$table_content .= '<table border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
// Add text-align: center to the table head
$table_content .= '<thead style="background-color: #02a8b5; color: #ffffff; text-align: center;">';
@ -1132,7 +1132,7 @@ class sendMailNotification
}
$table_content .= $policy_name_for_policy_type . ' ( Payable By Employee ) </h4></div>';
$table_content .= '<table data-custom-table-css="table" border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
$table_content .= '<table border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
// Add text-align: center to the table head
$table_content .= '<thead style="background-color: #02a8b5; color: #ffffff; text-align: center;">';
@ -1169,7 +1169,7 @@ class sendMailNotification
if (count($Addon_list) > 0) {
$table_content .= '<br><div style="text-align: left; font-size: 12px;"><div style="text-align:left;">';
$table_content .= '<table data-custom-table-css="table" border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
$table_content .= '<table border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
// Center align for table header and body
$table_content .= '<thead style="background-color: #02a8b5; color: #ffffff; text-align: center;">';
@ -1502,7 +1502,7 @@ class sendMailNotification
// Start table row
$table_content .= $policy_name . '</h4></div>';
$table_content .= '<table data-custom-table-css="table" border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
$table_content .= '<table border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
$table_content .= '<thead style="background-color: #02a8b5; color: #ffffff; text-align: center;">';
$table_content .= '<tr>';
$table_content .= '<th>Name</th>';
@ -1554,7 +1554,7 @@ class sendMailNotification
// Generate summary table for addon if applicable
if (count($Addon_list) > 0) {
$table_content .= '<br><div style="text-align: left; font-size: 12px;"><div style="text-align:left;">';
$table_content .= '<table data-custom-table-css="table" border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
$table_content .= '<table border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
$table_content .= '<thead style="background-color: #02a8b5; color: #ffffff; text-align: center;">';
$table_content .= '<tr>';
@ -1657,7 +1657,7 @@ class sendMailNotification
// Start table row
$table_content .= $policy_name . '</h4></div>';
$table_content .= '<table data-custom-table-css="table" border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
$table_content .= '<table border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
$table_content .= '<thead style="background-color: #02a8b5; color: #ffffff; text-align: center;">';
$table_content .= '<tr>';
$table_content .= '<th>Name</th>';
@ -1709,7 +1709,7 @@ class sendMailNotification
// Generate summary table for addon if applicable
if (count($Addon_list) > 0) {
$table_content .= '<br><div style="text-align: left; font-size: 12px;"><div style="text-align:left;">';
$table_content .= '<table data-custom-table-css="table" border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
$table_content .= '<table border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
$table_content .= '<thead style="background-color: #02a8b5; color: #ffffff; text-align: center;">';
$table_content .= '<tr>';
@ -1812,7 +1812,7 @@ class sendMailNotification
// Start table row
$table_content .= $policy_name . '</h4></div>';
$table_content .= '<table data-custom-table-css="table" border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
$table_content .= '<table border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
$table_content .= '<thead style="background-color: #02a8b5; color: #ffffff; text-align: center;">';
$table_content .= '<tr>';
$table_content .= '<th>Name</th>';
@ -1865,7 +1865,7 @@ class sendMailNotification
if (count($Addon_list) > 0) {
$table_content .= '<br><div style="text-align: left; font-size: 12px;"><div style="text-align:left;">';
$table_content .= '<table data-custom-table-css="table" border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
$table_content .= '<table border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-size: 12px;">';
$table_content .= '<thead style="background-color: #02a8b5; color: #ffffff; text-align: center;">';
$table_content .= '<tr>';
@ -1900,7 +1900,7 @@ class sendMailNotification
$mail_content = str_replace(["[[member_summary]]", "{{member_summary}}"], $table_content , $mail_content);
$mail_content = preg_replace('/<p[^>]*>(&nbsp;|\s)*<\/p>/i', '', $mail_content);
$data['params'] = $params;$data['client_logo'] = $client_logo;
$data['mail_content'] = $mail_content;
$mail_content = view('mail_template', $data);

View File

@ -36,6 +36,7 @@ class RuleImportService
];
// Column name constants
private const COL_SNO = 'S.No';
private const COL_RULE_NAME = 'Rule Name';
private const COL_POLICY_BUSINESS_TYPE = 'Policy Business Type';
private const COL_POLICY_NAME = 'Policy Name';
@ -52,12 +53,17 @@ class RuleImportService
private const COL_VEHICLE_WEIGHT_MIN = 'Vehicle Weight Min';
private const COL_VEHICLE_WEIGHT_MAX = 'Vehicle Weight Max';
private const COL_RTO_STATE = 'RTO State';
private const COL_RTO_CITY = 'RTO City';
private const COL_RTO_CITY = 'RTO Code';
private const COL_RENEWAL_TYPE = 'Renewal Type';
private const COL_RENEWAL_SUB_TYPE = 'Renewal Sub Type';
private const COL_COMMISSION_TYPE = 'Commission Type';
private const COL_COMMISSION_VALUE = 'Commission Value';
private const COL_COMMISSION_PARAMS = 'Commission Params(TP:OD:PA)';
private const COL_COMMISSION_PARAMS_OD = 'Commission Params (OD)';
private const COL_COMMISSION_PARAMS_PA = 'Commission Params (PA)';
private const COL_COMMISSION_PARAMS_TP = 'Commission Params (TP)';
private const COL_NOTES = 'Notes';
protected array $expectedColumns;
@ -82,9 +88,10 @@ class RuleImportService
private function initializeExpectedColumns(): void
{
$this->expectedColumns = [
self::COL_RULE_NAME,
self::COL_POLICY_BUSINESS_TYPE,
self::COL_POLICY_NAME,
// self::COL_RULE_NAME,
// self::COL_POLICY_BUSINESS_TYPE,
// self::COL_POLICY_NAME,
self::COL_SNO,
self::COL_PREMIUM_TYPE,
self::COL_VEHICLE_TYPE,
self::COL_VEHICLE_SUB_TYPE,
@ -100,11 +107,13 @@ class RuleImportService
self::COL_RTO_STATE,
self::COL_RTO_CITY,
self::COL_RENEWAL_TYPE,
self::COL_RENEWAL_SUB_TYPE,
// self::COL_RENEWAL_SUB_TYPE,
self::COL_COMMISSION_TYPE,
self::COL_COMMISSION_VALUE,
self::COL_COMMISSION_PARAMS,
self::COL_NOTES
self::COL_COMMISSION_PARAMS_TP,
self::COL_COMMISSION_PARAMS_OD,
self::COL_COMMISSION_PARAMS_PA,
// self::COL_NOTES
];
}
@ -123,7 +132,7 @@ class RuleImportService
self::COL_FUEL_TYPE => 'validateCommaList',
self::COL_COMMISSION_TYPE => 'validateCommissionType',
self::COL_COMMISSION_VALUE => 'validateNumeric',
self::COL_COMMISSION_PARAMS => 'validateCompositeParams',
// self::COL_COMMISSION_PARAMS => 'validateCompositeParams',
];
}
@ -402,13 +411,16 @@ class RuleImportService
{
$commissionType = strtolower($rowData[self::COL_COMMISSION_TYPE] ?? '');
$commissionValue = $rowData[self::COL_COMMISSION_VALUE] ?? '';
$commissionParams = $rowData[self::COL_COMMISSION_PARAMS] ?? '';
// $commissionParams = $rowData[self::COL_COMMISSION_PARAMS] ?? '';
$commissionParams_od = $rowData[self::COL_COMMISSION_PARAMS_OD] ?? '';
$commissionParams_pa = $rowData[self::COL_COMMISSION_PARAMS_PA] ?? '';
$commissionParams_tp = $rowData[self::COL_COMMISSION_PARAMS_TP] ?? '';
// Composite commission requires params
if ($commissionType === self::COMMISSION_COMPOSITE && empty($commissionParams)) {
if ($commissionType === self::COMMISSION_COMPOSITE && empty($commissionParams_od) && empty($commissionParams_pa) && empty($commissionParams_tp)) {
$this->validationResult->addError(
$rowNum,
self::COL_COMMISSION_PARAMS,
self::COL_COMMISSION_PARAMS_OD,
"Required when commission type is composite"
);
}
@ -1255,10 +1267,14 @@ class RuleImportService
$commissionType = strtolower(trim($rowData[self::COL_COMMISSION_TYPE] ?? ''));
$commissionValue = $rowData[self::COL_COMMISSION_VALUE] ?? '';
$commissionParams = $rowData[self::COL_COMMISSION_PARAMS] ?? '';
$commissionParams_od = $rowData[self::COL_COMMISSION_PARAMS_OD] ?? '';
$commissionParams_pa = $rowData[self::COL_COMMISSION_PARAMS_PA] ?? '';
$commissionParams_tp = $rowData[self::COL_COMMISSION_PARAMS_TP] ?? '';
$commission = $commissionParams_tp.':'.$commissionParams_od.':'. $commissionParams_pa;
switch ($commissionType) {
case 'composite':
return $this->buildCompositeCalculation($commissionParams);
return $this->buildCompositeCalculation($commission);
case 'percentage':
return $this->buildPercentageCalculation($commissionValue);

View File

@ -13,6 +13,7 @@ class AddImgModel extends Model
"created_by",
"updated_by",
"is_active",
"client_id",
];

View File

@ -0,0 +1,55 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class BDSDumpModel extends Model
{
protected $table = 'bds_dump_files';
protected $primaryKey = 'id';
protected $allowedFields = [
"id",
"file_name",
"status",
"reason",
"created_by",
"created_at",
"updated_by",
"updated_at",
"is_active",
];
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = ["checkAndADDCreatedByValue"];
protected $afterInsert = [];
protected $beforeUpdate = ["checkAndUpdateUpdatedByValue"];
protected $afterUpdate = [];
protected $beforeFind = [];
protected $afterFind = [];
protected $beforeDelete = [];
protected $afterDelete = [];
protected function checkAndADDCreatedByValue(array $data)
{
// Check if 'updated_by' value is null or empty
if (empty($data['data']['created_by'])) {
// Set 'updated_by' value to the current session user ID
$data['data']['created_by'] = get_session_userid();
}
return $data;
}
protected function checkAndUpdateUpdatedByValue(array $data)
{
// Check if 'updated_by' value is null or empty
if (empty($data['data']['updated_by'])) {
// Set 'updated_by' value to the current session user ID
$data['data']['updated_by'] = get_session_userid();
}
return $data;
}
}

View File

@ -22,6 +22,7 @@ class ClaimFilesModel extends Model
'is_active',
'file_name',
'mime_type',
'docs_for_ir',
];
// Callbacks

View File

@ -41,6 +41,7 @@ class ClientModel extends Model
"mail_domain",
"addon_subheading",
"parent_client_id",
"otp",
];

View File

@ -37,6 +37,7 @@ class EmployeePolicyModel extends Model
'payable_employee',
'file_id',
"age_band",
"wellness_onboard"
];
// Callbacks

View File

@ -0,0 +1,57 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class EmployeeRetailPolicy extends Model
{
protected $table = 'employee_retail_policies';
protected $primaryKey = 'id';
protected $allowedFields = [
'id',
'emp_id',
'insurer_id',
'policy_type_id',
'policy_no',
'policy_start_date',
'policy_end_date',
'created_by',
'updated_at',
'created_at',
'updated_by',
];
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = ["checkAndADDCreatedByValue"];
protected $afterInsert = [];
protected $beforeUpdate = ["checkAndUpdateUpdatedByValue"];
protected $afterUpdate = [];
protected $beforeFind = [];
protected $afterFind = [];
protected $beforeDelete = [];
protected $afterDelete = [];
protected function checkAndADDCreatedByValue(array $data)
{
// Check if 'updated_by' value is null or empty
if (empty($data['data']['created_by'])) {
// Set 'updated_by' value to the current session user ID
$data['data']['created_by'] = get_session_userid();
}
return $data;
}
protected function checkAndUpdateUpdatedByValue(array $data)
{
// Check if 'updated_by' value is null or empty
if (empty($data['data']['updated_by'])) {
// Set 'updated_by' value to the current session user ID
$data['data']['updated_by'] = get_session_userid();
}
return $data;
}
}

View File

@ -107,6 +107,7 @@ class LeadsModel extends Model
'quote_received_insurer',
'acm_id',
'policy_with_correction',
'agreed_percentage',
];

View File

@ -69,6 +69,7 @@ class PTCOShareDetailsModel extends Model
'cotp_amt',
'cotep_amt',
'pt_policy_issue_date',
'file_id',
];
public function getNonReconcileredPolicyTransactions(string $insurer_id,string $insurer_branch_id)

File diff suppressed because it is too large Load Diff

View File

@ -83,6 +83,15 @@ class TicketMasterModel extends Model
'manager_id',
'agent_id' ,
'vehicle_id',
'hospital_address',
'hospital_state',
'hospital_city',
'hospital_pin_code',
'hospital_phone_no',
'claim_description',
'required_docs',
'policy_transaction_id',
];

View File

@ -27,6 +27,8 @@ class UserModel extends Model
"updated_by",
"updated_at",
"is_active",
"nhance_branch_id",
"rm_id",
];
// Dates

View File

@ -487,14 +487,35 @@ table.dataTable tbody td {
<input type="hidden" name="PrimaryKey" id="UserId"/>
<div class="form-group">
<div class="form-row">
<div class="form-group col-md-6">
<label for="nhance_branch_id">NHance Branch<span class="text-danger">*</span></label>
<select class="form-control" id="nhance_branch_id" name="nhance_branch_id" required>
<option value="">Select NHance Branch</option>
<?php foreach($NHanceBranchData as $value) { ?>
<option value="<?= $value['id'] ?>"><?= $value['branch_name'] ?></option>
<?php } ?>
</select>
</div>
<div class="form-group col-md-6">
<label for="rm_id">Reporting Manager<span class="text-danger">*</span></label>
<select class="form-control" id="rm_id" name="rm_id" required>
<option value="">Select Reporting Manager</option>
<?php foreach($user_data as $value) { ?>
<option value="<?= $value['id'] ?>"><?= $value['first_name'] ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="emp_code">Employee Code<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="emp_code" placeholder="Enter Code" name="emp_code" required>
<input type="text" class="form-control" id="emp_code" placeholder="Enter Code" name="emp_code" onchange="validateInput(this, 'user_profiles', 'emp_code', 'btnSubmit')" required>
</div>
<div class="form-group col-md-6">
<label for="first_name">Name<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="first_name" placeholder="Ente Name" name="first_name" required>
<input type="text" class="form-control" id="first_name" placeholder="Enter Name" name="first_name" required>
</div>
</div>
@ -502,7 +523,7 @@ table.dataTable tbody td {
<div class="form-row">
<div class="form-group col-md-6">
<label for="email">Email<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="email" placeholder="Enter Email" name="email" data-parsley-trigger="change" data-parsley-type="email" required>
<input type="text" class="form-control" id="email" placeholder="Enter Email" name="email" data-parsley-trigger="change" data-parsley-type="email" onchange="validateInput(this, 'user_profiles', 'email', 'btnSubmit')" required>
</div>
<div class="form-group col-md-6">
@ -850,6 +871,14 @@ table.dataTable tbody td {
var table;
$(document).ready(function () {
$('#nhance_branch_id').select2();
$('#rm_id').select2();
$('#nhance_branch_id')
.val(null) // ✅ MUST be null
.trigger('change.select2'); // ✅ correct trigger
var incentiveMonthPicker = flatpickr("#incentive_month", {
dateFormat: "Y-m-d", // real value stored (hidden)
altInput: true, // show a user-friendly display
@ -988,6 +1017,18 @@ table.dataTable tbody td {
}
});
// IMPORTANT — DataTables draw event REF: TTS
table.on('draw.dt', function () {
let rowCount = $('#scroll-horizontal-datatable').DataTable().rows({ filter: 'applied' }).count();
if (rowCount <= 2) {
$('.dataTables_scrollBody').css('overflow', 'inherit');
} else {
$('.dataTables_scrollBody').css('overflow', 'auto');
}
});
$('#team').multiselect({
@ -1027,7 +1068,8 @@ table.dataTable tbody td {
type: "GET",
dataType: 'json',
success: function (res) {
console.log(res)
console.log(":():",res);
console.log(":():",res.data.nhance_branch_id);
$('#updateModal').modal('show');
$('#role').val('')
$('#UserForm').attr('action', '<?php echo base_url('user/edit');?>');
@ -1038,6 +1080,19 @@ table.dataTable tbody td {
$('#mobile').val(res.data.mobile);
$('#emp_code').val(res.data.emp_code);
$('#role option[value="' + res.data.role + '"]').prop('selected', true);
$('#rm_id').val(res.data.rm_id).select2(); // ✅ correct trigger
if (res.data.nhance_branch_id !== null &&
res.data.nhance_branch_id !== "" &&
res.data.nhance_branch_id !== 0) {
$('#nhance_branch_id')
.val(res.data.nhance_branch_id)
.trigger('change.select2');
} else {
$('#nhance_branch_id')
.val(null) // ✅ MUST be null
.trigger('change.select2'); // ✅ correct trigger
}
$('#btnSubmit').html('Update');
$.each(res.userTeamData, function(index, item) {
@ -1774,6 +1829,8 @@ table.dataTable tbody td {
$('#email').val('');
$('#mobile').val('');
$('#emp_code').val('');
$('#nhance_branch_id').val('0');
$('#rm_id').val('0');
$('#UserForm').attr('action', '<?php echo base_url('/user/create');?>');
let myModal = new bootstrap.Modal(document.getElementById('con-close-modal'));
myModal.show(); // open modal
@ -1791,6 +1848,29 @@ table.dataTable tbody td {
myModal.show(); // open modal
});
function validateInput(input, table, field, submitButId){
let value = $(input).val();
let label = $(input).closest('.form-group').find('label').text().replace('*', '').trim();
let message = "Value is duplicate!";
if(label){
message = label + " already exists!";
}
checkDuplicateTableFieldValue(table, field, value, function(isDuplicate) {
if (isDuplicate) {
toastr.warning(message, 'WARNING');
// $(input).val('')
$('#' + submitButId).prop('disabled', true);
} else{
$('#' + submitButId).prop('disabled', false);
}
});
}
</script>

View File

@ -40,6 +40,8 @@ table.dataTable thead th {
<thead class="bg-light">
<tr>
<th class="font-weight-medium"><div class="column-header">Advertisement Image Name</div></th>
<th class="font-weight-medium"><div class="column-header">Client Name</div></th>
<th class="font-weight-medium"><div class="column-header">Client Short Name</div></th>
<th class="font-weight-medium"><div class="column-header">Status</div></th>
<th class="font-weight-medium"><div class="column-header">Action</div></th>
</tr>
@ -49,19 +51,18 @@ table.dataTable thead th {
<?php foreach($addImageList as $row){ ?>
<tr >
<td class="client_info" data-id="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></td>
<td class="client_info" ><?php echo $row['client_id'] != 0 ? $row['client_name'] : '-' ; ?></td>
<td class="client_info" ><?php echo $row['client_id'] != 0 ? $row['short_name'] : '-'; ?></td>
<td class="client_info" ><?php echo $row['status']; ?></td>
<td>
<?php echo $row['is_active']; ?>
</td>
<td>
<div class="btn-group dropdown">
<a href="javascript: void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm" data-toggle="dropdown"aria-expanded="false"><i class="mdi mdi-dots-horizontal"></i></a>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item advertise_image_edit" href="#" data-toggle="modal" data-id="<?php echo $row['id']; ?>" data-name="<?php echo $row['name']; ?>" data-target="#bike_make_login-modal"><i class="mdi mdi-pencil mr-2 text-muted font-18 vertical-middle"></i>Edit</a>
<a class="dropdown-item" data-id="<?= $row['id'];?>" onclick="removeClient(this)"><i class="mdi mdi-delete mr-2 text-muted font-18 vertical-middle"></i>Delete</a>
<div class="btn-group dropdown">
<a href="javascript: void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm" data-toggle="dropdown"aria-expanded="false"><i class="mdi mdi-dots-horizontal"></i></a>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item advertise_image_edit" href="#" data-toggle="modal" data-wholearray='<?php echo json_encode($row, JSON_HEX_APOS); ?>' data-target="#bike_make_login-modal"><i class="mdi mdi-pencil mr-2 text-muted font-18 vertical-middle"></i>Edit</a>
<?php if($row['client_id'] != 0) { ?> <a class="dropdown-item" onclick="remove_advertise_image('<?= $row['id'];?>')"><i class="mdi mdi-delete mr-2 text-muted font-18 vertical-middle"></i>Delete</a> <?php } ?>
</div>
</div>
</div>
</td>
</tr>
<?php } ?>
@ -88,6 +89,7 @@ table.dataTable thead th {
<form id="model_form_data" class="px-4" enctype="multipart/form-data">
<input type="hidden" name="add_image_id" id="add_image_id" value="0">
<!-- old
<div class="row">
<div class="col-md-12">
<div class="form-group">
@ -100,8 +102,64 @@ table.dataTable thead th {
<div class="form-group col-md-6 float-left" style="position: relative;top: 0px;">
<img src=" " width="100" height="100" id="uploadPreview" class="avatar img-circle img-thumbnail" alt="avatar"/>
</div>
<div class="form-group col-md-3">
<label for="client_branch">Client<span class="text-danger">*</span></label>
<select class="form-control" id="client_id" name="client_id" required>
<option value="">Select Client</option>
<?php
if (isset($client) && count($client)) {
foreach ($client as $key => $value) {
echo "<option value='" . $value['id'] . "'>" . $value['client_name'] . "</option>";
}
}
?>
</select>
</div>
</div>
</div>
-->
<div class="row mb-2 align-items-stretch">
<!-- Left column: col-8 -->
<div class="col-md-8 d-flex flex-column justify-content-between">
<!-- Top section -->
<div class="form-group">
<label for="branchname">Upload Image</label>
<div class="input-icon">
<input type="file" class="form-control" name="advertise_image" id="advertise_image" accept="image/*" onchange="PreviewImage();" required>
<i class="mdi mdi-upload additional-icon"></i>
</div>
</div>
<!-- Bottom section -->
<div class="form-group">
<label for="client_branch">Client <span class="text-danger">*</span></label>
<select class="form-control" id="client_id" name="client_id" required>
<option value="">Select Client</option>
<option value="0">Default Image</option>
<?php
if (isset($client) && count($client)) {
foreach ($client as $value) {
echo "<option value='" . $value['id'] . "'>" . $value['client_name'] . "</option>";
}
}
?>
</select>
</div>
</div>
<!-- Right column: col-4, preview image -->
<div class="col-md-4 d-flex flex-column align-items-center justify-content-center">
<img src="" class="avatar img-circle img-thumbnail" id="uploadPreview" alt="Preview" style="max-width: 100%; height: auto;">
<small style="font-size: x-small; margin-top: 5px; text-align: center;">
dimensions - 1640x664 pixels <br> size - 200kb
</small>
</div>
</div>
<div class="form-group text-center">
<button type="button" class="btn btn-primary" onclick="submitBranch()">Submit</button>
@ -116,158 +174,193 @@ table.dataTable thead th {
<script>
function submitBranch() {
const fileInput = $('#advertise_image')[0].files[0]; // get actual file object
const imageId = $('#add_image_id').val();
function submitBranch() {
const fileInput = $('#advertise_image')[0].files[0]; // get actual file object
const imageId = $('#add_image_id').val();
const clientId = $('#client_id').val();
if (!fileInput) {
toastr.warning('Please upload an image before submitting', 'Warning');
$('#advertise_image').focus();
return;
if (!fileInput) {
toastr.warning('Please upload an image before submitting', 'Warning');
$('#advertise_image').focus();
return;
}
if(!clientId){
toastr.warning('Please Select Client.', 'Warning');
$('#client_id').focus();
return;
}
var url = '<?= base_url("add_advertise_image") ?>';
var formData = new FormData();
formData.append('advertise_image', fileInput);
formData.append('add_image_id', imageId);
formData.append('client_id', clientId);
$.ajax({
type: 'POST',
url: url,
data: formData,
processData: false,
contentType: false,
dataType: 'json',
success: function(response) {
console.log(response);
if (response.status) {
$('#bike_make_login-modal').modal('hide');
$('#advertise_image').val('');
$('#client_id').val(null).trigger('change');
$('#uploadPreview').attr('src', '<?= base_url('public/assets/images/avatar_2x.png') ?>');
toastr.success('Image uploaded successfully!');
window.location.reload();
} else {
toastr.error(response.message || 'Something went wrong.');
}
},
error: function(xhr, status, error) {
console.error(xhr.responseText);
console.error('Status:', status);
console.error('Error:', error);
let msg = 'Something went wrong. Please try again later.';
switch (xhr.status) {
case 400:
msg = xhr.responseJSON?.message || 'Bad Request — Invalid input.';
break;
case 401:
msg = 'Unauthorized — Please log in again.';
break;
case 403:
msg = 'Forbidden — You do not have permission.';
break;
case 404:
msg = 'Not Found — Requested URL or resource not found.';
break;
case 500:
console.log('Internal Server Error — Please contact support.');
msg = xhr.responseJSON?.message || xhr.responseText || msg;
break;
default:
msg = xhr.responseJSON?.message || xhr.responseText || msg;
}
}
});
}
var url = '<?= base_url("add_advertise_image") ?>';
var formData = new FormData();
formData.append('advertise_image', fileInput);
formData.append('add_image_id', imageId);
function PreviewImage() {
console.log('function called');
var fileInput = document.getElementById("advertise_image");
var file = fileInput.files[0];
if (file) {
var allowedExtensions = ["jpg", "jpeg", "png"];
var fileExtension = file.name.split('.').pop().toLowerCase();
if (!allowedExtensions.includes(fileExtension) || file.size > 200 * 1024) {
toastr.warning('Maximum file size allowed is 200KB.', 'File size exceeds limit.');
fileInput.value = ""; // Clear the file input
document.getElementById("uploadPreview").src = "<?= base_url()."public/assets/images/avatar_2x.png" ?>"; // Remove the preview image
return;
}
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (event) {
var img = new Image();
img.src = event.target.result;
img.onload = function () {
if (img.width !== 1640 || img.height !== 664) {
toastr.warning('Image dimensions must be 1640x664 pixels.', 'Invalid image dimensions.');
fileInput.value = ""; // Clear the file input
document.getElementById("uploadPreview").src = "<?= base_url()."public/assets/images/avatar_2x.png" ?>"; // Remove the preview image
} else {
document.getElementById("uploadPreview").src = img.src;
}
};
};
}
}
var table;
$(document).ready(function() {
$('#client_id').select2();
$('#add_image_id').val('');
$('#client_id').val(null).trigger('change');
$('#advertise_image').val('');
table = $('#tickets-table').DataTable({
// dom: "<'row'<'col-sm-1'f><'col-sm-11 text-right'B>>" + // Filter left, button right
// "<'row'<'col-sm-12'tr>>" +
// "<'row'<'col-sm-5'i><'col-sm-7'p>>",
dom: "<'row'<'col-12 d-flex justify-content-between align-items-center'<'datatable-search dataTables_filter'f><'datatable-buttons dt-buttons'B>>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row align-items-center'<'col-5 text-start'i><'col-7 d-flex justify-content-end align-items-center'<'me-2'l>p>>",
lengthMenu: [[10, 20, 50, 100], [10, 20, 50, 100]],
buttons: [
{
text: '<i class="mdi mdi-plus"></i> <span class="btn-custom">Add</span>',
className: 'btn app-btn-primary',
action: function (e, dt, node, config) {
// ✅ Call your modal logic
callmodal();
}
}
],
language: {
search: `
<div class="datatable-search-wrapper" style="position:relative; display:inline-block;">
_INPUT_
<i class="mdi mdi-magnify datatable-search-icon"
style="position:absolute; right:10px; top:50%; transform:translateY(-50%); color:#666;"></i>
<i class="mdi mdi-close-circle datatable-clear-icon"
style="position:absolute; right:10px; top:50%; transform:translateY(-50%); color:#666; display:none;"></i>
</div>`,
searchPlaceholder: "Search",
emptyTable: '<div class="text-center text-muted">No Data found</div>'
},
paging: true
});
});
// ✅ Define your modal function separately
function callmodal() {
$('#add_image_id').val(0);
$('#client_id').val(null).trigger('change');
$('#advertise_add_edit').html('Add Advertise Image');
$('#uploadPreview').attr('src', '<?= base_url()."public/assets/images/avatar_2x.png" ?>');
$('#bike_model_login-modal').modal('show'); // ✅ this shows the modal
var myModal = new bootstrap.Modal(document.getElementById('bike_make_login-modal'));
myModal.show();
}
function remove_advertise_image(id) {
if (!confirm("Are you sure you want to delete this image?")) return;
$.ajax({
type: 'POST',
url: url,
data: formData,
processData: false,
contentType: false,
dataType: 'json',
success: function(response) {
console.log(response);
if (response.status) {
$('#bike_make_login-modal').modal('hide');
$('#advertise_image').val('');
$('#uploadPreview').attr('src', '<?= base_url('public/assets/images/avatar_2x.png') ?>');
toastr.success('Image uploaded successfully!');
window.location.reload();
} else {
toastr.error(response.message || 'Something went wrong.');
}
url: '<?= base_url("remove_advertise_image"); ?>',
data: { add_image_id: id },
success: function (response) {
toastr.success('Deleted successfully');
location.reload(); // refresh page
},
error: function(xhr, status, error) {
error: function (xhr) {
console.error(xhr.responseText);
console.error('Status:', status);
console.error('Error:', error);
let msg = 'Something went wrong. Please try again later.';
switch (xhr.status) {
case 400:
msg = xhr.responseJSON?.message || 'Bad Request — Invalid input.';
break;
case 401:
msg = 'Unauthorized — Please log in again.';
break;
case 403:
msg = 'Forbidden — You do not have permission.';
break;
case 404:
msg = 'Not Found — Requested URL or resource not found.';
break;
case 500:
console.log('Internal Server Error — Please contact support.');
msg = xhr.responseJSON?.message || xhr.responseText || msg;
break;
default:
msg = xhr.responseJSON?.message || xhr.responseText || msg;
}
}
});
}
function PreviewImage() {
console.log('function called');
var fileInput = document.getElementById("advertise_image");
var file = fileInput.files[0];
if (file) {
var allowedExtensions = ["jpg", "jpeg", "png"];
var fileExtension = file.name.split('.').pop().toLowerCase();
if (!allowedExtensions.includes(fileExtension) || file.size > 200 * 1024) {
toastr.warning('Maximum file size allowed is 200KB.', 'File size exceeds limit.');
fileInput.value = ""; // Clear the file input
document.getElementById("uploadPreview").src = "<?= base_url()."public/assets/images/avatar_2x.png" ?>"; // Remove the preview image
return;
}
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (event) {
var img = new Image();
img.src = event.target.result;
img.onload = function () {
if (img.width !== 1640 || img.height !== 664) {
toastr.warning('Image dimensions must be 1640x664 pixels.', 'Invalid image dimensions.');
fileInput.value = ""; // Clear the file input
document.getElementById("uploadPreview").src = "<?= base_url()."public/assets/images/avatar_2x.png" ?>"; // Remove the preview image
} else {
document.getElementById("uploadPreview").src = img.src;
}
};
};
}
}
var table;
$(document).ready(function() {
table = $('#tickets-table').DataTable({
// dom: "<'row'<'col-sm-1'f><'col-sm-11 text-right'B>>" + // Filter left, button right
// "<'row'<'col-sm-12'tr>>" +
// "<'row'<'col-sm-5'i><'col-sm-7'p>>",
dom: "<'row'<'col-12 d-flex justify-content-between align-items-center'<'datatable-search dataTables_filter'f><'datatable-buttons dt-buttons'B>>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row align-items-center'<'col-5 text-start'i><'col-7 d-flex justify-content-end align-items-center'<'me-2'l>p>>",
lengthMenu: [[10, 20, 50, 100], [10, 20, 50, 100]],
buttons: [
{
text: '<i class="mdi mdi-plus"></i> <span class="btn-custom">Add</span>',
className: 'btn app-btn-primary',
action: function (e, dt, node, config) {
// ✅ Call your modal logic
callmodal();
}
}
],
language: {
search: `
<div class="datatable-search-wrapper" style="position:relative; display:inline-block;">
_INPUT_
<i class="mdi mdi-magnify datatable-search-icon"
style="position:absolute; right:10px; top:50%; transform:translateY(-50%); color:#666;"></i>
<i class="mdi mdi-close-circle datatable-clear-icon"
style="position:absolute; right:10px; top:50%; transform:translateY(-50%); color:#666; display:none;"></i>
</div>`,
searchPlaceholder: "Search",
emptyTable: '<div class="text-center text-muted">No Data found</div>'
},
paging: true
});
});
// ✅ Define your modal function separately
function callmodal() {
$('#add_image_id').val(0);
$('#advertise_add_edit').html('Add Advertise Image');
$('#uploadPreview').attr('src', '<?= base_url()."public/assets/images/avatar_2x.png" ?>');
$('#bike_model_login-modal').modal('show'); // ✅ this shows the modal
var myModal = new bootstrap.Modal(document.getElementById('bike_make_login-modal'));
myModal.show();
}
// $('#btnAdd').click(function () {
// $('#add_image_id').val(0);
// $('#advertise_add_edit').html('Add Advertise Image');
@ -299,28 +392,50 @@ function callmodal() {
// })
// })
$(document).on('click', '.advertise_image_edit', function (e) {
e.preventDefault();
e.preventDefault();
// 1. Clear fields first for a clean state (Good practice)
$('#add_image_id').val('');
$('#client_id').val(null).trigger('change');
$('#advertise_image').val('');
// Reset preview to default before processing to avoid flicker/old image
$('#uploadPreview').attr('src', '<?= base_url("public/assets/images/avatar_2x.png") ?>');
let wholearray = JSON.parse($(this).attr('data-wholearray'));
let ad_name = wholearray.name;
let ad_id = wholearray.id;
let c_id = wholearray.client_id; // This holds the Client ID for the dropdown
// console.log('Whole array:', wholearray);
// console.log('Clicked ID:', ad_id);
// 2. Set the data fields and title
$('#add_image_id').val(ad_id);
$('#advertise_add_edit').html('Edit Advertise Image');
// 🎯 CRITICAL FIX: Set the value of the Client SELECT dropdown
// This pre-selects the client associated with the image.
$('#client_id').val(c_id).trigger('change');
const id = $(this).data('id');
const name = $(this).data('name');
console.log('Clicked ID:', id);
console.log('<?= base_url(); ?>');
// 3. Construct the image URL
// NOTE: If this path fails (404/403), revert to the previous controller path:
const imgUrl = '<?= base_url("showAdvertiseImage/"); ?>' + ad_name;
// const imgUrl = '<?= base_url('public/uploads/add_image_upload/'); ?>' + ad_name;
$('#add_image_id').val(id);
$('#advertise_image').val(name);
$('#advertise_add_edit').html('Edit Advertise Image');
const imgUrl = '<?= base_url("showAdvertiseImage/"); ?>' + name;
// 4. Set the image source AND add robust error handling for default image
$('#uploadPreview').attr('src', imgUrl).on('error', function() {
// Fallback: If the image fails to load, set the source to the default image.
$(this).attr('src', '<?= base_url("public/assets/images/avatar_2x.png") ?>');
});
$('#uploadPreview').attr('src', imgUrl)
.on('error', function() {
$(this).attr('src', '<?= base_url()."public/assets/images/avatar_2x.png" ?>');
// 5. Clear the file input
$('#advertise_image').val('');
// 6. Show the modal
var myModal = new bootstrap.Modal(document.getElementById('bike_make_login-modal'));
myModal.show();
});
});
</script>

View File

@ -0,0 +1,393 @@
<style>
.reload:hover {
cursor: pointer;
}
.table th,
.table td {
padding: 8px;
}
table.dataTable tbody td {
padding: 4px 4px !important;
}
.addbtnStyle{
margin-left: 20px !important;
}
.dataTables_filter {
position: absolute;
}
.dataTables_length label {height: 21px !important;}
</style>
<div class="col-12">
<div class="card">
<div class="card-body">
<table data-custom-table-css="table" class="table table-hover m-0 table-centered dt-responsive w-100" cellspacing="0" id="tickets-table">
<thead class="bg-light">
<tr>
<th class="font-weight-medium">S.No&nbsp;</th>
<th class="font-weight-medium">File name</th>
<th class="font-weight-medium">User/Time</th>
<th class="font-weight-medium">Status</th>
<th class="font-weight-medium">Action</th>
</tr>
</thead>
<tbody class="font-12">
<?php
if (isset($bds_dump_file_data)) {
foreach ($bds_dump_file_data as $key => $file) {
?>
<tr>
<td class="text-center"><b><?php echo ($key + 1) ?></b></td>
<td style="overflow: hidden;" class="reload truncate" data-toggle="tooltip" data-placement="top" title="<?php echo $file['file_name'] ?>">
<?php echo $file['file_name'] ?>
</td>
<td><?php echo change_date_format($file['created_at'], 'Y-m-d H:i:s', 'd M Y h:i A') . ' by <strong>' . $file['user_name'] . '</strong>' ?> </td>
<td>
<?php if ($file['status'] == "failed") { ?>
<span> <?= $file['status'] ?> </span>
<span class='col-xl-3 col-lg-4 col-sm-6'>
<!-- <a href="<?= base_url('util/bds_dump_excel_error/') . $file['file_id'] ?>" target="_blank" class='fe-alert-circle' data-err="<?= $file['file_id'] ?>"></a> -->
<a href="#" class='fe-alert-circle' onclick="fetchFileError(<?= $file['file_id'] ?>)"></a>
</span>
<?php } else if ($file['status'] == "inprogress") { ?>
<a data-id="<?= $file['status'] ?>" class="reload" href="#">
<?= $file['status'] ?>
</a>
<?php } else { ?>
<span> <?= $file['status'] ?> </span>
<?php } ?>
</td>
<td>
<div class="btn-group dropdown">
<a href="javascript: void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm"
data-toggle="dropdown" aria-expanded="false"><i
class="mdi mdi-dots-horizontal"></i></a>
<div class="dropdown-menu dropdown-menu-right">
<a target="_blank" class="dropdown-item" href="<?= base_url("bds_upload/downloadBDSDumpFile/") . $file['file_id']; ?>"><i class="mdi mdi-download mr-2 text-muted font-18 vertical-middle"></i>Download</a>
<!-- <a data-id="<?php echo $file['file_id'] ?>" data-toggle="modal" data-target="#full-width-modal-emp-list" class="dropdown-item view_emp_list" href="#"><i class="mdi mdi-eye mr-2 text-muted font-18 vertical-middle"></i>View</a> -->
</div>
</div>
</td>
</tr>
<?php }
} ?>
</tbody>
</table>
</div>
</div>
</div><!-- end col -->
<!-- Center modal content -->
<div class="modal fade" id="bds-dump-file-err-modal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myCenterModalLabel">File Rejected Reason</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div id="modal_body" class="modal-body">
<div class="spinner-border text-primary" role="status" style="position: relative; left: 200px;"></div>
</div>
</div>
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- Center modal content for upload file-->
<div class="modal fade" id="bds-file-upload-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myCenterModalLabel">BDS Bulk Upload</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<form class="parsley-examples" id="bds-upload-form" enctype="multipart/form-data">
<div class="form-group">
<div class="row">
<div class="form-group float-right-end offset-8 col-4">
<span><a href="<?= base_url("util/download-excel/bds_upload"); ?>" id="download_sample_file" style="font-size: small; color:red !important;">Download sample file</a></span>
</div>
</div>
<div class="form-row" id="file_upload">
<div class="form-group col-md-9">
<label>Upload file</label>
<!-- &nbsp;[ <a href="#" id="excel_download" data-toggle="tooltip" data-placement="top" title="Download Sample Excel">Sample Excel</a> ] -->
<input type="file" name="bds_dump_list" id="bds_dump_list" accept=" application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel,application/vnd.oasis.opendocument.spreadsheet" required>
</div>
<div class="form-group col-md-3" style="margin-top: 40px;">
<button id="bds_form_submit_button" type="submit" class="btn btn-primary waves-effect waves-light justify-content-end">Upload</button>
</div>
</div>
</div>
</form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script>
$(document).ready(function() {
// AJAX Form Submit Function
$('#bds-upload-form').on('submit', function(e) {
e.preventDefault(); // Prevent default form submission
// Get form data
var formData = new FormData(this);
var fileInput = $('#bds_dump_list')[0];
// Validate file type
var allowedTypes = [
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.ms-excel',
'application/vnd.oasis.opendocument.spreadsheet'
];
var selectedFile = fileInput.files[0];
if (!allowedTypes.includes(selectedFile.type)) {
alert('Please upload a valid Excel file (.xlsx, .xls, .ods)');
return false;
}
//form submit url;
let url = `<?php echo base_url('bds_upload/list'); ?>`;
// Show loading state
var submitButton = $('#bds_form_submit_button');
var originalText = submitButton.text();
submitButton.prop('disabled', true).text('Uploading...');
// AJAX request
$.ajax({
url: url, // Your route URL
type: 'POST',
data: formData,
processData: false, // CRITICAL: Don't process the data
contentType: false, // CRITICAL: Don't set content-type header
cache: false,
success: function(response) {
// Handle successful response
console.log('Upload successful:', response);
if (response.status == true) {
toastr.success(response.message, "SUCCESS");
} else {
toastr.error(response.message, "ERROR");
}
// Reset form
$('#bds-upload-form')[0].reset();
$('.close').click();
window.location.reload();
},
error: function(xhr, status, error) {
// Handle error response
console.error('Upload failed:', error);
console.error('Upload failed:', error);
},
complete: function() {
// Reset button state
submitButton.prop('disabled', false).text(originalText);
}
});
});
// File input change event for additional validation
$('#bds_dump_list').on('change', function() {
var fileInput = this;
var file = fileInput.files[0];
if (file) {
// Check file size (optional - set max size as needed, e.g., 10MB)
var maxSize = 10 * 1024 * 1024; // 10MB in bytes
if (file.size > maxSize) {
toastr.warning('File size should not exceed 10MB');
$(this).val(''); // Clear the input
return false;
}
// Display selected file name
var fileName = file.name;
if ($('#selected-file').length === 0) {
$('<div id="selected-file" class="mt-2 text-muted"><small>Selected file: <span id="file-name"></span></small></div>')
.insertAfter('#bds_dump_list');
}
$('#file-name').text(fileName);
}
});
$('body').on('click', '.reload', function() {
status = this.getAttribute('data-id')
console.log(status);
if (status == 'inprogress') {
window.location.reload(true);
}
})
});
// Datatable document ready
$(document).ready(function() {
var ticketsTable = $('#tickets-table');
if (ticketsTable.length) {
ticketsTable.DataTable({
scrollX: true,
// dom: "<'row'<'col-sm-7'f><'col-sm-5 text-right'B>>" + // Filter left, buttons right
// "<'row'<'col-sm-12'tr>>" +
// "<'row'<'col-sm-5'i><'col-sm-7'p>>", // Pagination at the bottom, without page length selector
dom: "<'row'<'col-sm-7'f><'col-sm-5 text-right'B>>" + // Filter left, buttons right
"<'row'<'col-sm-12'tr>>" +
"<'row align-items-center'<'col-5 text-start'i><'col-7 d-flex justify-content-end align-items-center'<'me-2'l>p>>",
lengthMenu: [[10, 20, 50, 100], [10, 20, 50, 100]],
buttons: [
{
text: 'Add',
className: 'buttons-html5 addbtnStyle',
action: function (e, dt, node, config) {
openDumpUploadModal();
}
}
],
language: {
search: `
<div class="datatable-search-wrapper" style="position:relative; display:inline-block;">
_INPUT_
<i class="mdi mdi-magnify datatable-search-icon"
style="position:absolute; right:10px; top:50%; transform:translateY(-50%); color:#666;"></i>
<i class="mdi mdi-close-circle datatable-clear-icon"
style="position:absolute; right:10px; top:50%; transform:translateY(-50%); color:#666; display:none;"></i>
</div>`,
searchPlaceholder: "Search",
emptyTable: '<div class="text-center text-muted">No Data found</div>'
},
paging: true, // Enable pagination
pageLength: 15, // Set default number of rows per page (optional)
});
} else {
console.error("Table not found.");
}
});
function fetchFileError(file_id) {
var url = '<?php echo base_url('bds_upload/getBdsDumpFileErrorData/'); ?>';
let requestData = { file_id: file_id };
var myModal = new bootstrap.Modal(document.getElementById('bds-dump-file-err-modal'));
myModal.show();
sendAjaxRequestForGlobal(url, 'GET', requestData, function(response) {
console.log('Data fetched successfully:', response);
$('#modal_body').empty();
if (response.status === true) {
var file_error_data = (JSON.parse(response.data));
var file_error_html = "";
for (var key in file_error_data['error_summary']) {
var err_id = parseInt(key);
var err_count = file_error_data['error_summary'][key];
switch (err_id) {
case 0:
file_error_html += "<strong>" + file_error_data['error_data'] + "</strong>";
break;
case 1:
file_error_html += "<strong>Mandatory values missing</strong> <span class='badge badge-danger float-right'>" +
err_count + "</span><br>";
break;
case 2:
file_error_html += "<strong>Values not in expected format</strong> <span class='badge badge-danger float-right'>" +
err_count + "</span><br>";
break;
case 3:
file_error_html += "<strong>Field contains not allowed values</strong> <span class='badge badge-danger float-right'>" +
err_count + "</span><br>";
break;
case 4:
file_error_html += "<strong>Rule Conflict</strong> <span class='badge badge-danger float-right'>" +
err_count + "</span><br>";
break;
case 5:
file_error_html += "<strong>" + (file_error_data['error_data'] || 'Error data not available') + "</strong>";
break;
case 6:
file_error_html += "<strong>" + (file_error_data['error_data'] || 'Error data not available') + "</strong>";
break;
case 7:
file_error_html += "<strong>Bds already exist</strong> <span class='badge badge-danger float-right'>" +
err_count + "</span><br>";
break;
case 8:
file_error_html += "<strong>Policy not found</strong> <span class='badge badge-warning float-right'>" +
err_count + "</span><br>";
break;
case 9:
file_error_html += "<strong>Employee not found</strong> <span class='badge badge-danger float-right'>" +
err_count + "</span><br>";
break;
case 10:
file_error_html += "<strong>ACM not found</strong> <span class='badge badge-danger float-right'>" +
err_count + "</span><br>";
break;
default:
file_error_html += "<strong>Unknown error type</strong> <span class='badge badge-secondary float-right'>" +
err_count + "</span><br>";
break;
}
}
if (err_id != 5 && err_id != 6 && err_id != 0) {
file_error_html += (file_error_html != "" ?
"<a href ='<?php echo base_url('bds_upload/getBdsDumpExcelFileErrors/') ?>" + file_id +
"' target=_blank>click here to more details...</a>" : "");
}
// console.log(file_error_html);
$('#modal_body').append(file_error_html);
} else {
console.log('Response status was false');
$('#modal_body').append('<div class="alert alert-warning">No error data available.</div>');
}
}, function(xhr, status, error) {
console.error('Error fetching data:', error);
console.error('Status:', status);
console.error('Response:', xhr.responseText);
// Show error message to user
$('#modal_body').empty().append(
'<div class="alert alert-danger">Failed to fetch error data. Please try again.</div>'
);
});
}
$('.close').click(function(){
$('#modal_body').empty()
let html = `<div class="spinner-border text-primary" role="status" style="position: relative; left: 200px;"></div>`
$('#modal_body').append(html);
});
function openDumpUploadModal() {
var myModal = new bootstrap.Modal(document.getElementById('bds-file-upload-modal'));
myModal.show();
}
</script>

View File

@ -20,12 +20,12 @@ table.dataTable tbody td {
<div class="col-12" id="inception_list">
<div class="card">
<div class="card-body">
<div class="row" style="margin-bottom:1rem;">
<div class="card-body" style="background-color: #F5FFFF !important; border-radius: 10px; box-shadow: 4px 4px 4px 4px #00000040;">
<!-- <div class="row" style="margin-bottom:1rem;">
<div class="col-6" style="align-self: center;">
<h4 style="position: relative;">Renewal Policy List</h4>
</div>
</div>
</div> -->
<div>
<div class="table-responsive">
<table data-custom-table-css="table" id="scroll-horizontal-datatable" class="table w-100 nowrap">

View File

@ -1,9 +1,68 @@
<div class="tab-pane" id="fileupload">
<div id="required_id_docs_div" class="card">
<div class="card-body" style="background-color: #F5FFFF !important; border-radius: 10px; box-shadow: 0px 4px 4px 0px #00000040;">
<div class="form-group">
<!-- Header Row: Title + Switch + Save -->
<div class="row mb-3 align-items-center">
<div class="col-md-6">
<h5 class="mb-0"><strong>IR Documents</strong></h5>
</div>
<div class="col-md-6 text-right">
<div class="d-inline-block mr-3">
<div class="custom-control custom-switch d-inline-block">
<input type="checkbox" class="custom-control-input"
id="action_freeze_switch"
onchange="toggleActionFreeze()">
<label class="custom-control-label" for="action_freeze_switch">
<strong>Freeze User Actions</strong>
</label>
</div>
</div>
<button type="button"
class="btn btn-success waves-effect waves-light"
onclick="saveConfiguration()"> Save
</button>
</div>
</div>
<!-- Document List Container -->
<div class="row mb-3">
<div class="col-md-12">
<!-- Header Row -->
<div class="form-row mb-2">
<div class="col-md-7"><strong>Document Name</strong></div>
<div class="col-md-3"><strong>Status</strong></div>
<div class="col-md-2 text-center"><strong>Action</strong></div>
</div>
<!-- Dynamic Document Rows -->
<div id="document-list-container"></div>
<!-- Add Button -->
<!-- <div class="row mt-3">
<div class="col-md-12 text-right">
<button type="button"
class="btn btn-primary waves-effect waves-light"
onclick="addDocument()">
<i class="mdi mdi-plus"></i> Add Document
</button>
</div>
</div> -->
</div>
</div>
</div>
<!-- Hidden field to store JSON data for form submission -->
<input type="hidden" id="document_config_json" name="document_config">
</div>
</div>
<div class="row">
<div class="col-xl-12">
<div id="accordion" class="mb-3">
<div class="card mb-1">
<div class="card mb-1" style="background-color: #F5FFFF !important; border-radius: 10px; box-shadow: 0px 4px 4px 0px #00000040;">
<h5 class="m-1">
<a id="toggleIcon" class="text-dark float-right" data-toggle="collapse" href="#collapseOne"
aria-expanded="true">
@ -45,7 +104,7 @@
</div>
<div id="file_table" class="card">
<div class="card-body">
<div class="card-body" style="background-color: #F5FFFF !important; border-radius: 10px; box-shadow: 0px 4px 4px 0px #00000040;">
<div class="row" style="padding-bottom: 10px;">
<div class="col-6" style="align-self: center;">
<h4 style="position: relative;">File List</h4>
@ -72,7 +131,6 @@
</div>
</div>
<!-- edit modal -->
<div class="modal fade" id="edit_url_modal" tabindex="-1" role="dialog" aria-labelledby="editUrlModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
@ -108,291 +166,531 @@
</div>
</div>
<script>
$(document).ready(function(){
let ticket_id = $('#ticket_master_id').val();
$('#ticket_id_url').val(ticket_id);
let urlData = getUrlDataByTicketId(ticket_id);
})
$("#drive_file_upload_form").submit(function(event) {
event.preventDefault();
var isValid = $('#drive_file_upload_form').parsley().validate();
if (!isValid) {
console.log('Form is Empty', 'Warning');
return ;
}
form_action = '<?php echo base_url() . 'ticket/upload_url' ?>';
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
var formData = new FormData($('#drive_file_upload_form')[0]);
$.ajax({
data:formData,
url: form_action,
type: "POST",
dataType: 'json',
processData: false,
contentType: false,
success: function(res) {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
if(res.status == true){
toastr.success(res.message, 'Success');
window.location.reload();
}else{
toastr.error(res.message, 'Error');
}
},
error: function (xhr, status, error) {
console.log("error in submission of url data");
console.error(xhr.responseText);
console.error(status, error);
},
complete : function(){
console.log("ajax call is completed for submission of url data..!!");
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
}
});
});
function addHTMLInput() {
const container = document.getElementById('dynamic-form-container');
const newRow = document.createElement('div');
newRow.className = 'form-row dynamic-form-row';
newRow.innerHTML = `
<div class="form-group col-md-5">
<label for="file_name">Document Name<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="docs_name" name="docs_name[]" placeholder="Enter file name" required
value=""
>
</div>
<div class="form-group col-md-5">
<label for="file">URL<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="url_name" name="url[]" required
value=""
>
</div>
<div class="form-group col-md-2" style="position: relative;top: 28px;">
<a class="btn btn-danger waves-effect waves-light" onclick="removeHTMLInput(this)" style="background-color: #BD0707;">
<i class="mdi mdi-delete" ></i>
</a>
</div>
`;
container.appendChild(newRow);
}
function removeHTMLInput(element) {
const container = document.getElementById('dynamic-form-container');
const rows = container.querySelectorAll('.dynamic-form-row');
if (rows.length > 1) {
const row = element.closest('.dynamic-form-row');
row.remove();
}
}
function getUrlDataByTicketId(ticket_id) {
// Show loader
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
$.ajax({
url: "<?= base_url('ticket/getUrlDataByTicketId')?>", // base_url must be defined in JS
type: "POST",
data: { ticket_id: ticket_id },
dataType: 'json',
success: function(response) {
console.log('Form submitted response:', response);
if (response.status === true) {
create_url_list(response.data);
addHTMLInput();
return ;
} else {
addHTMLInput();
console.warn("No Data");
}
},
error: function(xhr, status, error) {
console.log("error in get urldata api");
console.error("AJAX Error:", error);
},
complete: function() {
// Hide loader
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
console.log("Ajax is completed for get url data..!!");
}
});
}
function openEditModal(id, docName, url) {
$('#edit_url_id').val(id);
$('#edit_doc_name').val(docName);
$('#edit_url_link').val(url);
$('#edit_url_modal').modal('show'); // Bootstrap modal
}
function create_url_list(data) {
$('#table_bd').empty(); // clear existing rows
let base_url = "<?php echo base_url() ?>";
if (data && data.length > 0) {
let html = "";
data.forEach((item, index) => {
html += `
<tr>
<td class="text-center">${index + 1}</td>
<td>${item.doc_name}</td>
<td><a href="${item.url}" target="_blank">${item.file_type == 1 ? item.url : item.doc_name}</a></td>
<td>
<a href="javascript:void(0);" class="delete-url"
style="bacolor:black;"
data-href="${base_url}/ticket/remove_url?id=${item.id}">
<i class="mdi mdi-delete mr-1"></i>
</a>
</td>
</tr>
`;
});
$('#table_bd').append(html);
} else {
$('#table_bd').html('<tr><td colspan="4">No Data Found</td></tr>');
}
}
$(document).on('click', '.delete-url', function (e) {
e.preventDefault();
const url = $(this).data('href');
const $row = $(this).closest('tr'); // capture the row before async execution
confirmActionSweertAlert("Do you want to delete?", "Yes, Proceed!", "No, Cancel")
.then((confirmed) => {
if (confirmed) {
$.ajax({
url: url,
type: "GET",
dataType: "json",
beforeSend: function () {
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
},
success: function (response) {
if (response.status === true) {
toastr.success('Removed Successfully');
$row.remove();
} else {
toastr.error(response.message || 'Deletion failed');
}
},
error: function (xhr, status, error) {
console.log("error ");
console.error("AJAX Error:", error);
toastr.error('AJAX request failed');
},
complete: function () {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
console.log("Ajax is completed for get url data..!!");
}
});
}
});
});
function addFileUploadHtml() {
const container = document.getElementById('dynamic-form-container');
const newRow = document.createElement('div');
newRow.className = 'form-row dynamic-form-row';
newRow.innerHTML = `
<div class="form-group col-md-5">
<label for="file_name">Document Name <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="docs_name" name="docs_name[]" placeholder="Enter file name" required>
</div>
<div class="form-group col-md-5">
<label for="file">Choose File <span class="text-danger">*</span></label>
<input type="file" class="form-control" id="file_upload" name="file_upload[]" accept=".pdf,.jpg,.jpeg,.png" required>
</div>
<div class="form-group col-md-2" style="position: relative; top: 28px;">
<a class="btn btn-danger waves-effect waves-light" onclick="removeHTMLInput(this)" style="background-color: #BD0707;">
<i class="mdi mdi-delete"></i>
</a>
</div>
`;
container.appendChild(newRow);
}
function toggleUploadType(btn) {
const $btn = $(btn);
const $addBtn = $('#add_btn_for_claim_file_upload');
console.log('addBtn', $addBtn);
const $container = $('#dynamic-form-container');
const currentType = $btn.text().trim();
console.log('currentType', currentType);
// Remove all existing dynamic rows when mode changes
$container.find('.dynamic-form-row').remove();
if (currentType === 'URL Upload') {
$btn.text('File Upload').removeClass('btn-success').addClass('btn-info');
// Change the Add button action
$addBtn.attr('onclick', 'addHTMLInput(this)');
// Handle switching to file upload mode here
console.log('Switched to File Upload mode');
// call the function
addHTMLInput();
} else {
$btn.text('URL Upload').removeClass('btn-info').addClass('btn-success');
// Change the Add button action
$addBtn.attr('onclick', 'addFileUploadHtml(this)');
// Handle switching to URL upload mode here
console.log('Switched to URL Upload mode');
// call the function
addFileUploadHtml();
}
}
</script>
<script>
$(document).ready(function(){
let documentConfig = {
is_action_freeze: false,
docs: []
};
$(document).ready(function(){
let jsonDocumentConfig = <?= isset($ticket_data['required_docs']) && !empty($ticket_data['required_docs'])
? $ticket_data['required_docs']
: '{"is_action_freeze": false, "docs": [{"document_name":"","document_received":false}]}' ?>;
let ticket_id = $('#ticket_master_id').val();
console.log('loadConfiguration pre', jsonDocumentConfig);
loadConfiguration(jsonDocumentConfig);
})
$('#ticket_id_url').val(ticket_id);
// Initialize the form with JSON data
function initializeForm(jsonData) {
let urlData = getUrlDataByTicketId(ticket_id);
})
$("#drive_file_upload_form").submit(function(event) {
event.preventDefault();
var isValid = $('#drive_file_upload_form').parsley().validate();
if (!isValid) {
console.log('Form is Empty', 'Warning');
return ;
documentConfig = jsonData;
// Set the freeze switch
const freezeSwitch = document.getElementById('action_freeze_switch');
if (freezeSwitch) {
freezeSwitch.checked = documentConfig.is_action_freeze;
}
// Render document list
renderDocumentList();
}
form_action = '<?php echo base_url() . 'ticket/upload_url' ?>';
// Render the document input list
function renderDocumentList() {
const container = document.getElementById('document-list-container');
if (!container) return;
container.innerHTML = '';
documentConfig.docs.forEach((doc, index) => {
const docRow = createDocumentRow(doc, index);
container.appendChild(docRow);
});
}
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
// Create a single document row
function createDocumentRowOld(doc, index) {
const row = document.createElement('div');
row.className = 'form-row align-items-center mb-2';
row.dataset.index = index;
row.innerHTML = `
<div class="col-md-7">
<input type="text" class="form-control"
placeholder="Document Name"
value="${doc.document_name}"
onchange="updateDocumentName(${index}, this.value)"
${documentConfig.is_action_freeze ? 'disabled' : ''}>
</div>
<div class="col-md-3">
<span class="badge ${doc.document_received ? 'badge-success' : 'badge-danger'} text-center d-block"
style="cursor:pointer; font-size:14px; padding:13px 12px; font-weight:600; border-radius:9px;"
onclick="${documentConfig.is_action_freeze ? '' : `updateDocumentReceived(${index}, ${!doc.document_received})`}">
${doc.document_received ? 'Received' : 'Not Received'}
</span>
</div>
<div class="col-md-2">
<button type="button" class="btn btn-sm btn-danger"
onclick="removeDocument(${index})"
${documentConfig.is_action_freeze ? 'disabled' : ''}>
<i class="mdi mdi-delete"></i> Remove
</button>
</div>
`;
return row;
}
var formData = new FormData($('#drive_file_upload_form')[0]);
function createDocumentRow(doc, index) {
const row = document.createElement('div');
row.className = 'form-row align-items-center mb-2';
row.dataset.index = index;
const isLastRow = index === documentConfig.docs.length - 1; // 👉 Check last item
row.innerHTML = `
<div class="col-md-7">
<input type="text" class="form-control"
placeholder="Document Name"
value="${doc.document_name}"
onchange="updateDocumentName(${index}, this.value)"
${documentConfig.is_action_freeze ? 'disabled' : ''}>
</div>
$.ajax({
data:formData,
url: form_action,
type: "POST",
dataType: 'json',
processData: false,
contentType: false,
success: function(res) {
<div class="col-md-3">
<span class="badge ${doc.document_received ? 'badge-success' : 'badge-danger'} text-center d-block"
style="cursor:pointer; font-size:14px; padding:13px 12px; font-weight:600; border-radius:9px;"
onclick="${documentConfig.is_action_freeze ? '' : `updateDocumentReceived(${index}, ${!doc.document_received})`}">
${doc.document_received ? 'Received' : 'Not Received'}
</span>
</div>
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
if(res.status == true){
toastr.success(res.message, 'Success');
window.location.reload();
}else{
toastr.error(res.message, 'Error');
}
<div class="col-md-2 text-center">
<button type="button" class="btn btn-sm btn-danger"
onclick="removeDocument(${index})"
${documentConfig.is_action_freeze ? 'disabled' : ''}>
<i class="mdi mdi-delete"></i>
</button>
},
error: function (xhr, status, error) {
console.log("error in submission of url data");
console.error(xhr.responseText);
console.error(status, error);
},
complete : function(){
console.log("ajax call is completed for submission of url data..!!");
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
${isLastRow && !documentConfig.is_action_freeze ? `
<button type="button" class="btn btn-sm btn-primary ml-1"
onclick="addDocument()">
<i class="mdi mdi-plus"></i>
</button>` : ''}
</div>
`;
return row;
}
// Add new document
function addDocument() {
if (documentConfig.is_action_freeze) {
toastr.warning('Cannot add documents when action is frozen', 'WARNING');
return;
}
});
});
documentConfig.docs.push({
document_name: '',
document_received: false
});
renderDocumentList();
}
function addHTMLInput() {
const container = document.getElementById('dynamic-form-container');
const newRow = document.createElement('div');
newRow.className = 'form-row dynamic-form-row';
newRow.innerHTML = `
<div class="form-group col-md-5">
<label for="file_name">Document Name<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="docs_name" name="docs_name[]" placeholder="Enter file name" required
value=""
>
</div>
<div class="form-group col-md-5">
<label for="file">URL<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="url_name" name="url[]" required
value=""
>
</div>
<div class="form-group col-md-2" style="position: relative;top: 28px;">
<a class="btn btn-danger waves-effect waves-light" onclick="removeHTMLInput(this)" style="background-color: #BD0707;">
<i class="mdi mdi-delete" ></i>
</a>
</div>
`;
container.appendChild(newRow);
// Remove document
function removeDocumentold(index) {
if (documentConfig.is_action_freeze) {
alert('Cannot remove documents when action is frozen');
return;
}
documentConfig.docs.splice(index, 1);
renderDocumentList();
}
}
function removeDocument(index) {
if (documentConfig.is_action_freeze) {
toastr.warning('Cannot remove documents when action is frozen', 'WARNING');
return;
}
function removeHTMLInput(element) {
const container = document.getElementById('dynamic-form-container');
const rows = container.querySelectorAll('.dynamic-form-row');
const doc = documentConfig.docs[index];
if (rows.length > 1) {
const row = element.closest('.dynamic-form-row');
row.remove();
}
}
// ❗ If document is already received, do not remove
if (doc.document_received === true) {
toastr.warning('Cannot remove a received document', 'WARNING');
return;
}
function getUrlDataByTicketId(ticket_id) {
// 👉 First row cannot be removed
if (index === 0) {
documentConfig.docs[0].document_name = '';
documentConfig.docs[0].document_received = false;
renderDocumentList();
return;
}
// Show loader
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
// 👉 Other rows can be removed
documentConfig.docs.splice(index, 1);
renderDocumentList();
}
$.ajax({
url: "<?= base_url('ticket/getUrlDataByTicketId')?>", // base_url must be defined in JS
type: "POST",
data: { ticket_id: ticket_id },
dataType: 'json',
success: function(response) {
console.log('Form submitted response:', response);
// Update document name
function updateDocumentName(index, value) {
documentConfig.docs[index].document_name = value;
}
if (response.status === true) {
create_url_list(response.data);
addHTMLInput();
return ;
// Update document received status
function updateDocumentReceived(index, value) {
documentConfig.docs[index].document_received = value === 'true';
}
// Toggle freeze state
function toggleActionFreeze() {
const freezeSwitch = document.getElementById('action_freeze_switch');
documentConfig.is_action_freeze = freezeSwitch.checked;
// Re-render to update disabled states
renderDocumentList();
}
// Save configuration
function saveConfiguration() {
const hasEmptyNames = documentConfig.docs.some(doc => !doc.document_name.trim());
if (hasEmptyNames) {
toastr.warning('Please fill in all document names', 'WARNING');
return false;
}
let ticket_id = $('#ticket_id_url').val();
let required_docs = JSON.stringify(documentConfig);
console.log('Saving configuration:', JSON.stringify(documentConfig, null, 2));
console.log('ticket_id', ticket_id);
// Data to send in the AJAX request
let requestData = {
ticket_id: ticket_id,
required_docs: required_docs
};
let url = '<?= base_url('ticket/saveIRDocsJson') ?>';
// Send AJAX request
sendAjaxRequestForGlobal(url, 'POST', requestData, function(response) {
console.log('Data fetched successfully:', response);
if (response.status) {
loadConfiguration(response.data);
toastr.success(response.message, 'SUCCESS');
} else {
addHTMLInput();
console.warn("No Data");
toastr.warning(response.message, 'WARNING');
}
},
error: function(xhr, status, error) {
console.log("error in get urldata api");
console.error("AJAX Error:", error);
},
complete: function() {
// Hide loader
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
console.log("Ajax is completed for get url data..!!");
}, function(xhr, status, error) {
console.error('Error fetching data:', error);
console.error(xhr.responseText);
toastr.error('An error occurred while saving docs.', 'ERROR');
});
}
// Get current configuration as JSON
function getConfiguration() {
return documentConfig;
}
// Edit mode - load existing configuration
function loadConfiguration(jsonString) {
try {
const data = typeof jsonString === 'string' ? JSON.parse(jsonString) : jsonString;
initializeForm(data);
} catch (e) {
console.error('Invalid JSON:', e);
}
});
}
function openEditModal(id, docName, url) {
$('#edit_url_id').val(id);
$('#edit_doc_name').val(docName);
$('#edit_url_link').val(url);
$('#edit_url_modal').modal('show'); // Bootstrap modal
}
function create_url_list(data) {
$('#table_bd').empty(); // clear existing rows
let base_url = "<?php echo base_url() ?>";
if (data && data.length > 0) {
let html = "";
data.forEach((item, index) => {
html += `
<tr>
<td class="text-center">${index + 1}</td>
<td>${item.doc_name}</td>
<td><a href="${item.url}" target="_blank">${item.file_type == 1 ? item.url : item.doc_name}</a></td>
<td>
<a href="javascript:void(0);" class="delete-url"
style="bacolor:black;"
data-href="${base_url}/ticket/remove_url?id=${item.id}">
<i class="mdi mdi-delete mr-1"></i>
</a>
</td>
</tr>
`;
});
$('#table_bd').append(html);
} else {
$('#table_bd').html('<tr><td colspan="4">No Data Found</td></tr>');
}
}
$(document).on('click', '.delete-url', function (e) {
e.preventDefault();
const url = $(this).data('href');
const $row = $(this).closest('tr'); // capture the row before async execution
confirmActionSweertAlert("Do you want to delete?", "Yes, Proceed!", "No, Cancel")
.then((confirmed) => {
if (confirmed) {
$.ajax({
url: url,
type: "GET",
dataType: "json",
beforeSend: function () {
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
},
success: function (response) {
if (response.status === true) {
toastr.success('Removed Successfully');
$row.remove();
} else {
toastr.error(response.message || 'Deletion failed');
}
},
error: function (xhr, status, error) {
console.log("error ");
console.error("AJAX Error:", error);
toastr.error('AJAX request failed');
},
complete: function () {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
console.log("Ajax is completed for get url data..!!");
}
});
}
});
});
function addFileUploadHtml() {
const container = document.getElementById('dynamic-form-container');
const newRow = document.createElement('div');
newRow.className = 'form-row dynamic-form-row';
newRow.innerHTML = `
<div class="form-group col-md-5">
<label for="file_name">Document Name <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="docs_name" name="docs_name[]" placeholder="Enter file name" required>
</div>
<div class="form-group col-md-5">
<label for="file">Choose File <span class="text-danger">*</span></label>
<input type="file" class="form-control" id="file_upload" name="file_upload[]" accept=".pdf,.jpg,.jpeg,.png" required>
</div>
<div class="form-group col-md-2" style="position: relative; top: 28px;">
<a class="btn btn-danger waves-effect waves-light" onclick="removeHTMLInput(this)" style="background-color: #BD0707;">
<i class="mdi mdi-delete"></i>
</a>
</div>
`;
container.appendChild(newRow);
}
function toggleUploadType(btn) {
const $btn = $(btn);
const $addBtn = $('#add_btn_for_claim_file_upload');
console.log('addBtn', $addBtn);
const $container = $('#dynamic-form-container');
const currentType = $btn.text().trim();
console.log('currentType', currentType);
// Remove all existing dynamic rows when mode changes
$container.find('.dynamic-form-row').remove();
if (currentType === 'URL Upload') {
$btn.text('File Upload').removeClass('btn-success').addClass('btn-info');
// Change the Add button action
$addBtn.attr('onclick', 'addHTMLInput(this)');
// Handle switching to file upload mode here
console.log('Switched to File Upload mode');
// call the function
addHTMLInput();
} else {
$btn.text('URL Upload').removeClass('btn-info').addClass('btn-success');
// Change the Add button action
$addBtn.attr('onclick', 'addFileUploadHtml(this)');
// Handle switching to URL upload mode here
console.log('Switched to URL Upload mode');
// call the function
addFileUploadHtml();
}
}
</script>

322
app/Views/client_kyc_2.php Executable file
View File

@ -0,0 +1,322 @@
<style> .card-body{ margin-top: 0px !important; } </style>
<div class="tab-pane fade" id="KYC-DOC-tab">
<div id="others">
<div class="col-lg-12 col-sm-12 col-md-12">
<div class="card" style="margin-bottom: unset">
<div class="card-body"
style="margin-top: 0px !important;
margin-bottom: 0px !important;
padding-top: 0px !important;
padding-bottom: 0px !important;">
<h3>Documents</h3>
<form role="form" class="parsley-examples" method="post" id="kyc_form_add"
enctype="multipart/form-data">
<input type="hidden" class="form-control" value="<?= csrf_hash() ?>" name="<?= csrf_token() ?>" />
<input type="hidden" name="PrimaryKey" id="kyc_PrimaryKey" value="<?= isset($client['id']) ? $client['id'] : '' ?>"/>
<input type="hidden" name="client_id" id="client_id_kyc" value="<?= isset($client['id']) ? $client['id'] : '' ?>"/>
<input type="hidden" name="kyc_doc_type_id" value="">
<div class="form-group">
<div class="form-row">
<div class="form-group col-md-3">
<label for="document_select">Document Name<span class="text-danger">*</span></label>
<select class="form-control document-select" id="docs_type_id" name="docs_type_id" required onchange="handleDocumentSelectChange(this)">
<option value="">Select Document</option>
<option value="other">Additional Document</option>
</select>
</div>
<div class="form-group col-md-3 other-docs-name-group" style="display:none;">
<label for="other_docs_name">Enter Document Name<span class="text-danger">*</span></label>
<input type="text" class="form-control other-docs-name-input" name="other_docs_name" placeholder="Enter file name">
</div>
<div class="form-group col-md-3 file-input-group">
<label for="file_input">Browser File<span class="text-danger">*</span></label>
<input type="file" class="form-control file-input" id="kyc_docs_file" name="file_name" required accept=".pdf, .jpeg, .jpg, .png"
style="box-shadow: none !important; outline: none !important; border: none; height: unset !important;padding: 0px !important;background: transparent !important;">
</div>
<div class="form-group col-md-3" style="<?= isset($client['id']) ? 'margin-top: 41px;' : 'margin-top: 30px;' ?>">
<button type="submit" class="btn btn-sm waves-effect waves-light mr-1"id="btnSubmit">Save</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div> <!-- end col-->
</div> <!-- end row -->
<div class="col-lg-12">
<div class="card" id="collapseOne">
<div class="card-body">
<div class="table-responsive">
<table data-custom-table-css="second-table" id="kyc_table" class="table table-sm mb-0">
<thead>
<tr>
<th>S. No</th>
<th>Document Name</th>
<th>File Name</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tbody">
<?= isset($client_kyc_single_table) ? $client_kyc_single_table : "" ?>
</tbody>
</table>
</div> <!-- end table-responsive-->
</div>
</div> <!-- end card -->
</div> <!-- end col -->
</div>
<!-- end -->
<script>
var kycPrimaryKey = $('#client_id_kyc').val();
function handleDocumentSelectChange(selectElement) {
var $row = $(selectElement).closest('.form-row');
var $otherDocsGroup = $row.find('.other-docs-name-group');
var $otherDocsInput = $row.find('.other-docs-name-input');
var $fileInputGroup = $row.find('.file-input-group');
if (selectElement.value === 'other') {
$otherDocsGroup.removeClass('d-none').show();
$otherDocsInput.prop('required', true);
$fileInputGroup.removeClass('col-md-3 col-md-4').addClass('col-md-3');
} else {
$otherDocsGroup.addClass('d-none').hide();
$otherDocsInput.prop('required', false).val('');
$fileInputGroup.removeClass('col-md-3 col-md-4').addClass('col-md-4');
}
}
// Attach the change handler to all dropdowns
$(document).on('change', '.document-select', function() {
handleDocumentSelectChange(this);
});
$(document).ready(function(){
$("#kyc_form_add")[0].reset();
kycPrimaryKey = $('#kyc_PrimaryKey').val();
$('.document-select').each(function() {
handleDocumentSelectChange(this);
});
})
// ADD BUTTON---
$('#kyc_form_add').on('submit', function (e) {
e.preventDefault();
var docSelect = $('#docs_type_id');
var fileInput = $('#kyc_docs_file');
if (docSelect.val() === '' || fileInput[0].files.length === 0) {
toastr.error("Please select a document name and browser a file.");
return;
}
addKycDoc();
});
// ADD Functionality ---
function addKycDoc() {
var form = document.getElementById('kyc_form_add');
var formData = new FormData(form);
var docTypeVal = $('#docs_type_id').val();
// ✅ Correct handling
if (docTypeVal === 'other') {
formData.set('kyc_doc_type_id', '');
formData.set('other_docs_name', $('.other-docs-name-input').val());
} else {
formData.set('kyc_doc_type_id', docTypeVal);
formData.set('other_docs_name', '');
}
formData.set('client_id', $('#client_id_kyc').val());
formData.set('is_active', 1);
var fileInput = $('#kyc_docs_file')[0].files[0];
if (fileInput) {
formData.set('file_name', fileInput);
}
$('.loader').fadeIn();
$.ajax({
url: '<?= base_url("client/kyc/create_2"); ?>',
type: 'POST',
data: formData,
processData: false,
contentType: false,
dataType: 'json',
success: function (res) {
$('.loader').fadeOut();
if (res.status) {
$('#other_docs').html(res.data);
toastr.success('Document added successfully');
$('.other-docs-name-group').addClass('d-none');
$('.other-docs-name-input').val('');
$('#docs_type_id').empty();
$('#docs_type_id').append(res.dropdown);
$('#tbody').empty();
$('#tbody').append(res.html);
$('#kyc_form_add')[0].reset();
} else {
toastr.warning('Failed to add document');
}
},
error: function () {
$('.loader').fadeOut();
toastr.error('Upload error');
}
});
}
$(document).ready(function() {
// EDIT BUTTON---
$(document).on('click', '.btn-edit-kyc', function() {
let id = $(this).data('id');
$(`#data_row_${id}`).addClass('d-none');
$(`#edit_row_${id}`).removeClass('d-none');
});
// CANCEL BUTTON IN EDIT ---
$(document).on('click', '.btn-cancel-kyc', function() {
let id = $(this).data('id');
$(`#edit_row_${id}`).addClass('d-none');
$(`#data_row_${id}`).removeClass('d-none');
$(`#kyc_form_${id}`)[0].reset();
});
// UPDATE CLICK HANDLER ---
$(document).on('click', '.btn-update-kyc', function() {
let id = $(this).data('id');
var client_id = $(this).data('client_id');
var formElement = $(this).closest('form')[0]; // Fails if button isn't inside the form
updateKycDocWithForm(formElement, client_id);
});
});
// UPDATE Functionality ---
function updateKycDocWithForm(formElement, client_id) {
var formData = new FormData(formElement); // Use the element directly
formData.set('client_id', client_id);
let id = formData.get('id');
let fileInput = $(`#kyc_docs_file_${id}`)[0].files[0];
if (!fileInput) { console.log("file input not available here"); }
$('.loader').fadeIn();
$.ajax({
url: '<?= base_url("client/kyc/edit_2"); ?>',
type: 'POST',
data: formData,
processData: false,
contentType: false,
dataType: 'json',
success: function (res) {
$('.loader').fadeOut();
if (res.status) {
$(`#edit_row_${id}`).addClass('d-none');
$(`#data_row_${id}`).removeClass('d-none');
$('#docs_type_id').empty();
$('#docs_type_id').append(res.dropdown);
$('#tbody').empty();
$('#tbody').append(res.html);
toastr.success('Document updated successfully');
} else {
toastr.warning('Update failed: ' + (res.message || 'Server did not return a status message'));
}
},
error: function (xhr, status, error) {
$('.loader').fadeOut();
toastr.error('Server error: Check server logs for details.');
}
});
}
// SOFT DELETE CLICK HANDLER ---
$(document).on('click', '.btn-delete-kyc', function () {
var kyc_id = $(this).attr('data-id');
var client_id = $(this).attr('data-client_id');
Swal.fire({
title: "Are you sure?",
text: "You won't be able to revert this!",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, delete it!"
}).then((result) => {
if (result.isConfirmed) {
deleteKycDoc(kyc_id, client_id);
}
});
});
// SOFT DELETE Functionality ---
function deleteKycDoc(kyc_id,client_id) {
var formData = new FormData();
formData.append('is_active', 0);
formData.append('id', kyc_id);
formData.append('client_id', client_id);
$('.loader').fadeIn();
$.ajax({
url: '<?= base_url("client/kyc/delete_2"); ?>',
type: 'POST',
data: formData,
processData: false,
contentType: false,
dataType: 'json',
success: function (res) {
$('.loader').fadeOut();
if (res.status) {
$('#docs_type_id').empty();
$('#docs_type_id').append(res.dropdown);
$('#tbody').empty();
$('#tbody').append(res.html);
toastr.success('Document deleted successfully');
} else {
toastr.warning('Delete failed: ' + (res.message || 'Server error.'));
}
},
error: function () {
$('.loader').fadeOut();
toastr.error('Server error!');
}
});
}
</script>

View File

@ -0,0 +1,70 @@
<?php if (empty($ckdlist)) : ?>
<tr>
<td colspan="4" class="text-center text-muted">No data found</td>
</tr>
<?php else : ?>
<?php foreach ($ckdlist as $index => $value) :
$sno = $index + 1;
$fileName = !empty($value['file_name']) ? $value['file_name'] : '-';
?>
<tr id="data_row_<?= $value['id'] ?>">
<td><?= $sno ?></td>
<td><?= esc($value['ui_docs_name']) ?></td>
<td><?= esc($fileName) ?></td>
<td>
<a id="download_<?= esc($value['id']); ?>" data-id="<?= esc($value['id']); ?>" data-file="<?= $fileName ?>"
class="mdi mdi-download mr-1 btn-download-kyc" style="font-size:18px;" download></a>
<a class="mdi mdi-pencil mr-1 btn-edit-kyc"
data-id="<?= $value['id'] ?>"
data-client_id="<?= $value['client_id'] ?>"
data-old_file_name="<?= $fileName ?>"
data-kyc_doc_type_id="<?= $value['kyc_doc_type_id'] ?>"
style="font-size:18px;"></a>
<a class="mdi mdi-delete mr-1 btn-delete-kyc"
data-id="<?= $value['id'] ?>"
style="font-size:18px;"></a>
</td>
</tr>
<!-- EDIT ROW -->
<tr id="edit_row_<?= $value['id'] ?>" class="d-none">
<td colspan="4">
<form id="kyc_form_<?= $value['id'] ?>" class="kyc-edit-form">
<input type="hidden" name="id" value="<?= $value['id'] ?>">
<input type="hidden" name="client_id" value="<?= $value['client_id'] ?>">
<input type="hidden" name="old_file_name" value="<?= $fileName ?>">
<div class="row align-items-end">
<div class="col-md-8">
<label>
Change File - <?= esc($value['ui_docs_name']) ?>
(<?= esc($fileName) ?>)
</label>
<input type="file"
name="file_name"
id="kyc_docs_file_<?= $value['id'] ?>"
class="form-control"
style="box-shadow:none!important; outline:none!important; border:none; height:unset!important;padding: 0px !important;background: transparent !important;">
</div>
<div class="col-md-2">
<button type="button" class="btn btn-primary btn-sm btn-update-kyc w-100"
data-id="<?= $value['id'] ?>"
data-client_id="<?= $value['client_id'] ?>">Update</button>
</div>
<div class="col-md-2">
<button type="button"
class="btn btn-secondary btn-sm btn-cancel-kyc w-100"
data-id="<?= $value['id'] ?>">
Cancel
</button>
</div>
</div>
</form>
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>

View File

@ -1988,8 +1988,10 @@ input:checked + .slider_blue::before {
console.log(policy_no + '-' + policy_no.length);
$.ajax({
url: '<?php echo base_url('util/check_policy_no/');?>' + policy_no,
// url: '<?php echo base_url('util/check_policy_no/');?>' + policy_no,
url: '<?php echo base_url('util/get_client_policy_data_using_policy_no');?>',
type: "GET",
data : {policy_no : policy_no},
dataType: 'json',
success: function (res) {
console.log(res);

View File

@ -1071,6 +1071,128 @@ function checkPolicyTermsAndRackRatesHasDefiend(event)
}
function checkWellnessOnboardStatus(event)
{
// console.log(event.target.id);
var policy_id = (event.target.value);
console.log('checkWellnessOnboardStatus called ' + policy_id);
if(policy_id != 0 && policy_id != " " && policy_id != undefined)
{
var apiURL = '<?php echo base_url();?>' + 'checkWellnessOnboardStatus/' + policy_id;
// console.log(apiURL);
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
$.ajax({
url: apiURL,
method: 'GET',
headers: {
"Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest"
},
success: function(response) {
setTimeout(function() {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
}, 300);
console.log('check wellness response', response);
if(response.data && response.data != 0)
{
var btn_txt = 'click here to onboard ('+ response.data +') employees to Visit wellness';
$("#on_board_btn_txt").attr("data-id", response.data);
$('#on_board_btn_txt').text(btn_txt);
$('#onboard_div').show();
}
else
{
console.log('wellness button remains disabled');
$('#onboard_div').hide();
$('#on_board_btn_txt').text("");
}
},
error: function(xhr, status, error) {
setTimeout(function() {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
}, 300);
// toastr.error('Something went wrong! Try Later', 'Error');
console.error('Error fetching data from checkPolicyTermsAndRackRatesHasDefiend API:', error);
return false;
}
});
}
}
function initiateWellnessOnboard(e)
{
var empCount = $("#on_board_btn_txt").data("id");
if (confirm("Are you sure? You are about to onboard " + empCount + " employees to Visit wellness program.")) {
// user clicked OK
console.log("onboard Confirmed");
} else {
// user clicked Cancel
console.log("onboard Cancelled");
return false;
}
// return false;
// console.log(event.target.id);
var policy_id = document.getElementById('policy').value;
console.log('initiateWellnessOnboard called ' + policy_id);
if(policy_id != 0 && policy_id != " " && policy_id != undefined)
{
var apiURL = '<?php echo base_url();?>' + 'initiateWellnessOnboard/' + policy_id;
// console.log(apiURL);
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
$.ajax({
url: apiURL,
method: 'GET',
headers: {
"Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest"
},
success: function(response) {
setTimeout(function() {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
}, 300);
console.log('initiate wellness response', response);
toastr.success(response.message, 'SUCCESS');
$('#onboard_div').hide();
},
error: function(xhr, status, error) {
setTimeout(function() {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
}, 300);
// toastr.error('Something went wrong! Try Later', 'Error');
console.error('Error initiate data from initiateWellnessOnboard API:', error);
toastr.error(error, 'Error');
return false;
}
});
}else{
toastr.error('Please select policy to initiate wellness onboard', 'Error');
return false;
}
}
function checkValues() {

View File

@ -10,6 +10,8 @@
.dataTables_length label {height: 21px !important;}
.column-header { margin-right: 10px; /* Adjust this value as needed */ }
</style>
@ -22,18 +24,19 @@
</div>
</div>
<div class="table-responsive">
<table data-custom-table-css="table" class="table mb-0 nowrap w-100 table-centered" cellspacing="0" id="tickets-table">
<thead class="bg-light">
<tr>
<th class="font-weight-medium">S.No&nbsp;</th>
<th class="font-weight-medium">File name&nbsp;</th>
<th class="font-weight-medium">Client&nbsp;</th>
<th class="font-weight-medium">Client Branch&nbsp;</th>
<th class="font-weight-medium">Policy&nbsp;</th>
<th class="font-weight-medium">Event&nbsp;</th>
<th class="font-weight-medium">User/Time&nbsp;</th>
<th class="font-weight-medium">Status&nbsp;</th>
<th class="font-weight-medium">Action&nbsp;</th>
<th class="font-weight-medium"><div class="column-header">S.No</div></th>
<th class="font-weight-medium"><div class="column-header">File name</div></th>
<th class="font-weight-medium"><div class="column-header">Client</div></th>
<th class="font-weight-medium"><div class="column-header">Client Branch</div></th>
<th class="font-weight-medium"><div class="column-header">Policy</div></th>
<th class="font-weight-medium"><div class="column-header">Event</div></th>
<th class="font-weight-medium"><div class="column-header">User/Time</div></th>
<th class="font-weight-medium"><div class="column-header">Status</div></th>
<th class="font-weight-medium"><div class="column-header">Action</div></th>
</tr>
</thead>
@ -115,6 +118,7 @@
</tbody>
</table>
</div>
</div>
</div>
</div><!-- end col -->

View File

@ -0,0 +1,319 @@
<style>
.dataTables_filter {
position: absolute;
}
.dataTables_length label {height: 21px !important;}
</style>
<!-- End ADD and EDIT Page HTML -->
<div class="row" id="List-page">
<div class="col-12">
<div class="card">
<div class="card-body maincard">
<table data-custom-table-css="table" class="table table-sm m-0 table-centered dt-responsive nowrap w-100" cellspacing="a" id="user-table">
<thead class="bg-light">
<tr>
<!-- `content` `notes` -->
<th class="font-weight-medium">S.No.</th>
<th class="font-weight-medium">Type</th>
<th class="font-weight-medium">Content Section</th>
<th class="font-weight-medium">Heading</th>
<!-- <th class="font-weight-medium">Status</th> -->
<th class="font-weight-medium">Action</th>
</tr>
</thead>
<tbody>
<?php if(isset($test)) { $slno = 1; ?>
<?php foreach($test as $index => $row) { ?>
<tr>
<td class="text-center"><?= $slno++; ?></td>
<td><?= $row['type']; ?></td>
<td><?= $row['content_section']; ?></td>
<td><?= $row['heading']; ?></td>
<!-- <td>
<span class="<?php if($row['is_active'] == 1){ echo 'badge badge-primary'; }else{ echo 'badge badge-danger'; } ?>">
<?php if($row['is_active'] == 1){ echo 'Active'; }else{ echo 'In-Active'; } ?>
</span>
</td> -->
<td>
<div class="btn-group dropdown" style="position: relative !important;left:0px !important;top:0px !important;">
<a href="javascript: void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm" data-toggle="dropdown" aria-expanded="false"><i class="mdi mdi-dots-horizontal"></i></a>
<div class="dropdown-menu dropdown-menu-right" style="cursor: pointer;">
<a class="dropdown-item" data-id="<?= $row['id']; ?>" onclick="handleSaveEditAndDelete('edit', this)">
<i class="mdi mdi-pencil mr-2 text-muted font-18 vertical-middle"></i>Edit
</a>
<?php if ($row['is_active'] == 1): ?>
<a class="dropdown-item" data-id="<?= $row['id']; ?>" onclick="handleSaveEditAndDelete('remove', this)">
<i class="mdi mdi-delete mr-2 text-muted font-18 vertical-middle"></i>Delete
</a>
<?php endif; ?>
</div>
</div>
</td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td colspan="3" class="text-center">No data available</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- modal content -->
<div id="con-close-modal" class="modal fade app-font-family" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;" data-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="modalLabel">Add Front End Content</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body p-4">
<form id="frontEndContentForm" enctype="multipart/form-data">
<input type="hidden" name="pk" id="fe_id"/>
<div class="form-group">
<div class="form-row">
<div class="col-md-4">
<label for="type">Type<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="type" name="type" placeholder="Enter Type" required>
</div>
<div class="col-md-4">
<label for="content_section">Content Section<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="content_section" name="content_section" placeholder="Enter Content Section" required>
</div>
<div class="col-md-4">
<label for="branch_name">Heading<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="heading" name="heading" placeholder="Enter Heading" required>
</div>
</div>
</div>
<button type="button" class="btn app-btn-secondary waves-effect waves-light text-end" onclick="AddContentsAndNotes()">Add Contents And Notes</button>
<table>
</table>
<div class="form-group text-right m-b-0">
<button type="button" class="btn app-btn-secondary waves-effect waves-light" id="btnSubmit" onclick="handleSaveEditAndDelete('submit')">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
var table;
$(document).ready(function () {
var ticketsTable = $('#user-table');
ticketsTable.DataTable({
scrollX: true,
// dom: "<'row'<'col-sm-7'f><'col-sm-5 text-right'B>>" + // Filter left, buttons right
// "<'row'<'col-sm-12'tr>>" +
// "<'row'<'col-sm-5'i><'col-sm-7'p>>", // Pagination at the bottom, without page length selector
dom: "<'row'<'col-sm-7'f><'col-sm-5 text-right'B>>" + // Filter left, buttons right
"<'row'<'col-sm-12'tr>>" +
"<'row align-items-center'<'col-5 text-start'i><'col-7 d-flex justify-content-end align-items-center'<'me-2'l>p>>",
lengthMenu: [[10, 20, 50, 100], [10, 20, 50, 100]],
buttons: [
{
text: 'Add',
className: 'btn app-btn-primary mr-2',
action: function(e, dt, node, config) {
openModal()
}
},
{
extend: 'collection',
text: '<span class=" btn-custom"> Export </span><i class="mdi mdi-menu-down"></i>',
className: 'btn app-btn-secondary ',
buttons: [
{
extend: 'csv',
text: '<i class="mdi mdi-file-delimited " ></i><span class=" btn-custom"> CSV </span>',
title: 'Front End Content',
className: 'app-btn-primary ',
exportOptions: {
columns: ':not(:last-child)'
},
}
]
}
],
language: {
search: `
<div class="datatable-search-wrapper" style="position:relative; display:inline-block;">
_INPUT_
<i class="mdi mdi-magnify datatable-search-icon"
style="position:absolute; right:10px; top:50%; transform:translateY(-50%); color:#666;"></i>
<i class="mdi mdi-close-circle datatable-clear-icon"
style="position:absolute; right:10px; top:50%; transform:translateY(-50%); color:#666; display:none;"></i>
</div>`,
searchPlaceholder: "Search",
emptyTable: '<div class="text-center text-muted">No Data found</div>'
},
paging: true, // Enable pagination
pageLength: 10, // Set default number of rows per page (optional)
// ordering: false,
});
});
$('.close').click(function(){
resetValues()
})
function openModal(){
var myModal = new bootstrap.Modal(document.getElementById('con-close-modal'));
myModal.show();
}
// old Version
// function handleSaveEditAndDelete(type = 'submit', pk = null){
// let url = '<?= base_url('util/nhanceBranchMaster') ?>';
// let method = "POST";
// let requestData = {};
// $('#modalLabel').text('Add Front End Content');
// requestData.pk = pk;
// if(type == 'submit'){
// $("#frontEndContentForm").find("input, select, textarea").each(function () {
// let name = $(this).attr("name");
// let value = $.trim($(this).val());
// if (name) requestData[name] = value;
// });
// }
// if(type == 'remove'){
// method = "DELETE";
// }else if (type == 'edit'){
// method = "GET"
// }
// console.log("type", type)
// console.log("url", url)
// console.log("method", method)
// console.log("requestData", requestData)
// $('.loader').fadeIn();
// $('.loader-mask').fadeIn();
// // Send AJAX request
// sendAjaxRequestForGlobal(url, method, requestData, function(response) {
// console.log('Data fetched successfully:', response);
// if (response.status) {
// if(type == 'edit'){
// $('#modalLabel').text('Edit Front End Content');
// appendEditData(response.data);
// }else{
// toastr.success(response.message, 'SUCCESS');
// }
// } else {
// toastr.warning(response.message, 'WARNING');
// }
// $('.loader').fadeOut();
// $('.loader-mask').delay(350).fadeOut('slow');
// }, function(xhr, status, error) {
// console.error('Error fetching data:', error);
// console.error(xhr.responseText);
// $('.loader').fadeOut();
// $('.loader-mask').delay(350).fadeOut('slow');
// });
// }
function handleSaveEditAndDelete(type = 'submit', el = null) {
let url = '<?= base_url('util/nhanceBranchMaster') ?>';
let method = "POST";
let requestData = {};
let pk = null;
// If element is passed (from edit/remove button), get its data-id
if (el) { pk = $(el).data('id'); }
requestData.pk = pk;
if(type == 'submit'){
$("#frontEndContentForm").find("input, select, textarea").each(function () {
let name = $(this).attr("name");
let value = $.trim($(this).val());
if (name) requestData[name] = value;
});
}
if(type == 'remove'){
method = "DELETE";
} else if (type == 'edit'){
method = "GET";
$('#modalLabel').text('Edit Front End Content');
$('#frontEndContentForm')[0].reset();
}
console.log("type", type)
console.log("url", url)
console.log("method", method)
console.log("requestData", requestData)
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
// Send AJAX request
sendAjaxRequestForGlobal(url, method, requestData, function(response) {
console.log('Data fetched successfully:', response);
if (response.status) {
if(type == 'edit'){
appendEditData(response.data);
} else if(type == 'remove'){
toastr.success(response.message, 'Success');
if(el) $(el).closest('tr').remove();
window.location.reload();
} else if(type == 'submit'){
toastr.success(response.message, 'Success');
var myModal = new bootstrap.Modal(document.getElementById('con-close-modal'));
myModal.hide();
$('#frontEndContentForm')[0].reset();
window.location.reload();
}
} else {
toastr.warning(response.message, 'Warning');
}
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
}, function(xhr, status, error) {
console.error('Error fetching data:', error);
console.error(xhr.responseText);
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
});
}
function resetValues(){
$('#modalLabel').text('Add Front End Content');
$('#frontEndContentForm')[0].reset();
}
function appendEditData(data){
$('#fe_id').val(data[0]['id']);
$('#branch_name').val(data[0]['branch_name']);
openModal()
}
</script>

View File

@ -49,7 +49,7 @@
<div class="form-group col-md-4">
<label>Policy<span class="text-danger" id="policy_danger">*</span></label> <br />
<select name="client_policy_id" class="form-control" id="policy" onchange="checkPolicyTermsAndRackRatesHasDefiend(event)" required>
<select name="client_policy_id" class="form-control" id="policy" onchange="checkPolicyTermsAndRackRatesHasDefiend(event); checkWellnessOnboardStatus(event);" required>
<option value="">Select</option>
</select>
</div>
@ -101,13 +101,13 @@
</div>
</div>
<!-- <div class="form-row policy_issue_date_row" style="display:none;">
<div class="form-row policy_issue_date_row" style="display:none;">
<div class="form-group col-md-4">
<label id="policy_issue_date_label">Policy Issue Date</label> <br />
<input type="text" class="form-control" id="policy_issue_date" name="policy_issue_date"
placeholder="Enter Policy Issue Date">
</div>
</div> -->
</div>
<br>
<div class="form-row" id="import_excel_btn">
@ -129,6 +129,8 @@
</div>
<div class="form-row" id="export_excel_btn">
<div class="d-flex align-items-center justify-content-start" style="margin-top: 18px;">
<div class="form-group col-md-3">
@ -136,6 +138,9 @@
</div>
</div>
</div>
<div class="form-row" id="onboard_div" style="display:none;">
<a href="#"><span id="on_board_btn_txt" onclick="initiateWellnessOnboard(this)"></span></a>
</div>
</div>
</form>
@ -171,10 +176,10 @@
$(document).ready(function() {
// var policy_issue_datePicker = flatpickr("#policy_issue_date", {
// dateFormat: "d/m/Y",
// allowInput: false,
// });
var policy_issue_datePicker = flatpickr("#policy_issue_date", {
dateFormat: "d/m/Y",
allowInput: false,
});
$('#insurer_or_tpa, #action_type').on('change', togglePolicyIssueDate);
});
@ -796,15 +801,15 @@
function togglePolicyIssueDate() {
let insurer = $('#insurer_or_tpa').val();
let action = $('#action_type').val();
// if (insurer === 'insurer' && action === 'import') {
// $('.policy_issue_date_row').show();
// $('#policy_issue_date').attr('required', true);
// $('#policy_issue_date_label').html('Policy Issue Date <span class="text-danger">*</span>');
// } else {
// $('.policy_issue_date_row').hide();
// $('#policy_issue_date').removeAttr('required').val('');
// $('#policy_issue_date_label').text('Policy Issue Date');
// }
if (insurer === 'insurer' && action === 'import') {
$('.policy_issue_date_row').show();
$('#policy_issue_date').attr('required', true);
$('#policy_issue_date_label').html('Policy Issue Date <span class="text-danger">*</span>');
} else {
$('.policy_issue_date_row').hide();
$('#policy_issue_date').removeAttr('required').val('');
$('#policy_issue_date_label').text('Policy Issue Date');
}
}
function fetchTpaIdFromTpa(){

View File

@ -1890,6 +1890,9 @@
<li>
<a href="<?= base_url('/policy_tranction/inception/list') ?>">Policy</a>
</li>
<!-- <li>
<a href="<?= base_url('/policy_tranction/inception/list2') ?>">Policy 2</a>
</li> -->
<li>
<a href="<?= base_url('/policy_tranction/endorsement/list') ?>">Endorsement</a>
</li>
@ -2029,8 +2032,28 @@
<span> Commission</span>
</a>
</li>
<li>
<a href="<?= base_url('/bds_upload/list') ?>">
<i class="ri-car-line"></i>
<span> Motor Policy Bulk Upload</span>
</a>
</li>
<?php } ?>
<?php if (in_array(get_role_id(), [1, 5]) || (in_array(MANAGEMENT_TEAM_ID, user_team()) || in_array(FINANCE_TEAM_ID, user_team()) || in_array(BUSINESS_TEAM_ID, user_team()) || in_array(POS_TEAM_ID, user_team()))) { ?>
<li>
<a href="<?= base_url('/policy_tranction/inception/list2') ?>">
<i class="ri-barcode-line"></i>
<span> Policy 2</span>
</a>
</li>
<li>
<a href="<?= base_url('/policy_tranction/endorsement/list2') ?>">
<i class="ri-file-edit-line"></i>
<span> Endorsement 2</span>
</a>
</li>
<?php } ?>
</ul>
</div>
</li>

303
app/Views/logs/index.php Normal file
View File

@ -0,0 +1,303 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= esc($title) ?></title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
} */
.container {
max-width: 1200px;
margin: 0 auto;
background: white;
border-radius: 10px;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
overflow: hidden;
}
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
text-align: center;
}
.header h1 {
font-size: 2rem;
margin-bottom: 10px;
}
.header p {
opacity: 0.9;
}
.content {
padding: 30px;
}
.alert {
padding: 15px 20px;
margin-bottom: 20px;
border-radius: 5px;
font-weight: 500;
}
.alert-success {
background: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.alert-error {
background: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
.actions {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
padding-bottom: 20px;
border-bottom: 2px solid #e9ecef;
}
.btn {
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 14px;
font-weight: 600;
text-decoration: none;
display: inline-block;
transition: all 0.3s ease;
}
.btn-danger {
background: #dc3545;
color: white;
}
.btn-danger:hover {
background: #c82333;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(220, 53, 69, 0.3);
}
.btn-primary {
background: #667eea;
color: white;
}
.btn-primary:hover {
background: #5568d3;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}
.btn-success {
background: #28a745;
color: white;
}
.btn-success:hover {
background: #218838;
}
.btn-sm {
padding: 6px 12px;
font-size: 12px;
}
.table-wrapper {
overflow-x: auto;
}
table {
width: 100%;
border-collapse: collapse;
background: white;
}
thead {
background: #f8f9fa;
}
th {
padding: 15px;
text-align: left;
font-weight: 600;
color: #495057;
border-bottom: 2px solid #dee2e6;
}
td {
padding: 15px;
border-bottom: 1px solid #dee2e6;
}
tbody tr {
transition: background 0.2s ease;
}
tbody tr:hover {
background: #f8f9fa;
}
.no-logs {
text-align: center;
padding: 60px 20px;
color: #6c757d;
}
.no-logs svg {
width: 100px;
height: 100px;
margin-bottom: 20px;
opacity: 0.5;
}
.action-buttons {
display: flex;
gap: 8px;
}
.file-name {
font-weight: 600;
color: #667eea;
}
.stats {
display: flex;
gap: 20px;
margin-bottom: 20px;
}
.stat-card {
flex: 1;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 20px;
border-radius: 8px;
text-align: center;
}
.stat-card h3 {
font-size: 2rem;
margin-bottom: 5px;
}
.stat-card p {
opacity: 0.9;
font-size: 14px;
}
</style>
</head>
<body>
<div class="container">
<!-- <div class="header">
<h1>📋 Log File Manager</h1>
<p>View and manage your CodeIgniter 4 log files</p>
</div> -->
<div class="content">
<?php if (session()->getFlashdata('success')): ?>
<div class="alert alert-success">
<?= session()->getFlashdata('success') ?>
</div>
<?php endif; ?>
<?php if (session()->getFlashdata('error')): ?>
<div class="alert alert-error">
<?= session()->getFlashdata('error') ?>
</div>
<?php endif; ?>
<!-- <div class="stats">
<div class="stat-card">
<h3><?= count($logFiles) ?></h3>
<p>Total Log Files</p>
</div>
</div> -->
<div class="actions">
<h2 style="color: #495057;">Log Files</h2>
<?php if (!empty($logFiles)): ?>
<!-- <a href="<?= base_url('logs/clearAll') ?>"
class="btn btn-danger"
onclick="return confirm('Are you sure you want to delete all log files?')">
🗑️ Clear All Logs
</a> -->
<?php endif; ?>
</div>
<?php if (empty($logFiles)): ?>
<div class="no-logs">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
<h3>No Log Files Found</h3>
<p>There are no log files to display at the moment.</p>
</div>
<?php else: ?>
<div class="table-wrapper">
<table>
<thead>
<tr>
<th>File Name</th>
<th>Size</th>
<th>Last Modified</th>
<th style="text-align: center;">Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($logFiles as $file): ?>
<tr>
<td>
<span class="file-name">
📄 <?= esc($file['name']) ?>
</span>
</td>
<td><?= esc($file['size']) ?></td>
<td><?= esc($file['modified_date']) ?></td>
<td>
<div class="action-buttons" style="justify-content: center;">
<a href="<?= base_url('logs/view/' . urlencode($file['name'])) ?>"
class="btn btn-primary btn-sm">
View
</a>
<a href="<?= base_url('logs/download/' . urlencode($file['name'])) ?>"
class="btn btn-success btn-sm">
Download
</a>
<!-- <a href="<?= base_url('logs/delete/' . urlencode($file['name'])) ?>"
class="btn btn-danger btn-sm"
onclick="return confirm('Are you sure you want to delete this log file?')">
Delete
</a> -->
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</div>
</div>
</body>
</html>

483
app/Views/logs/view.php Normal file
View File

@ -0,0 +1,483 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= esc($title) ?></title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
} */
.container {
max-width: 1400px;
margin: 0 auto;
background: white;
border-radius: 10px;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
overflow: hidden;
}
.header {
/* background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); */
color: black;
padding: 5px;
}
.header h1 {
font-size: 1.8rem;
margin-bottom: 10px;
display: flex;
align-items: center;
gap: 10px;
}
.file-info {
display: flex;
gap: 30px;
margin-top: 15px;
opacity: 0.9;
}
.file-info-item {
display: flex;
align-items: center;
gap: 8px;
}
.content {
padding: 30px;
}
.controls {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
padding: 15px;
background: #f8f9fa;
border-radius: 8px;
flex-wrap: wrap;
gap: 15px;
}
.filter-group {
display: flex;
gap: 10px;
align-items: center;
flex-wrap: wrap;
}
.filter-btn {
padding: 8px 16px;
border: 2px solid #dee2e6;
background: white;
border-radius: 5px;
cursor: pointer;
font-size: 13px;
font-weight: 600;
transition: all 0.3s ease;
}
.filter-btn:hover {
border-color: #667eea;
color: #667eea;
}
.filter-btn.active {
background: #667eea;
color: white;
border-color: #667eea;
}
.search-box {
padding: 10px 15px;
border: 2px solid #dee2e6;
border-radius: 5px;
font-size: 14px;
width: 300px;
transition: border-color 0.3s ease;
}
.search-box:focus {
outline: none;
border-color: #667eea;
}
.log-entries {
background: #f8f9fa;
border-radius: 8px;
padding: 20px;
max-height: 600px;
overflow-y: auto;
}
.log-entry {
background: white;
border-left: 4px solid #6c757d;
padding: 15px;
margin-bottom: 15px;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
transition: all 0.3s ease;
}
.log-entry:hover {
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
transform: translateX(5px);
}
.log-entry.critical {
border-left-color: #dc3545;
background: #fff5f5;
}
.log-entry.error {
border-left-color: #fd7e14;
background: #fff8f5;
}
.log-entry.warning {
border-left-color: #ffc107;
background: #fffef5;
}
.log-entry.info {
border-left-color: #17a2b8;
background: #f5fcfd;
}
.log-entry.debug {
border-left-color: #6c757d;
background: #f8f9fa;
}
.log-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
padding-bottom: 10px;
border-bottom: 1px solid #e9ecef;
}
.log-level {
padding: 4px 12px;
border-radius: 20px;
font-size: 12px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.level-critical {
background: #dc3545;
color: white;
}
.level-error {
background: #fd7e14;
color: white;
}
.level-warning {
background: #ffc107;
color: #333;
}
.level-info {
background: #17a2b8;
color: white;
}
.level-debug {
background: #6c757d;
color: white;
}
.log-date {
color: #6c757d;
font-size: 13px;
font-family: 'Courier New', monospace;
}
.log-message {
color: #333;
line-height: 1.6;
font-size: 14px;
white-space: pre-wrap;
word-wrap: break-word;
font-family: 'Courier New', monospace;
}
.no-logs {
text-align: center;
padding: 60px 20px;
color: #6c757d;
}
.stats {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 15px;
margin-bottom: 20px;
}
.stat-card {
background-color: #fff;
color: #333;
padding: 0px;
border: 1px solid #007bff;
border-radius: 5px;
text-align: center;
border-width: 1px;
transition: all 0.3s ease;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}
.stat-card:hover {
transform: translateY(-5px);
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
border-color: #0056b3;
}
.stat-card h3 {
font-size: 2rem;
margin-bottom: 5px;
}
.stat-card p {
opacity: 0.9;
font-size: 15px;
}
.hidden {
display: none;
}
@media (max-width: 768px) {
.search-box {
width: 100%;
}
.controls {
flex-direction: column;
align-items: stretch;
}
.filter-group {
justify-content: center;
}
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<div style="display: flex; justify-content: space-between; align-items: center;">
<h1>
📄 <?= esc($filename) ?>
</h1>
<div style="display:flex; gap:10px; margin-bottom:15px;">
<?php if ($prevFile): ?>
<a href="<?= base_url('logs/view/' . $prevFile) ?>" class="btn btn-primary">Previous</a>
<?php else: ?>
<button class="btn btn-secondary" disabled> Previous Day</button>
<?php endif; ?>
<?php if ($nextFile): ?>
<a href="<?= base_url('logs/view/' . $nextFile) ?>" class="btn btn-primary">Next</a>
<?php else: ?>
<button class="btn btn-secondary" disabled>Next Day </button>
<?php endif; ?>
</div>
</div>
<!-- <div class="file-info">
<div class="file-info-item">
<strong>Size:</strong> <?= esc($fileSize) ?>
</div>
<div class="file-info-item">
<strong>Last Modified:</strong> <?= esc($lastModified) ?>
</div>
<div class="file-info-item">
<strong>Total Entries:</strong> <?= count($logEntries) ?>
</div>
</div> -->
</div>
<div class="content">
<div class="stats">
<!--<div class="stat-card">
<h3 id="total-count"><?= count($logEntries) ?></h3>
<p>Total Entries</p>
</div>
<div class="stat-card">
<h3 id="critical-count">
<?= count(array_filter($logEntries, fn($e) => strtoupper($e['level']) === 'CRITICAL')) ?>
</h3>
<p>Critical</p>
</div>
<div class="stat-card">
<h3 id="error-count">
<?= count(array_filter($logEntries, fn($e) => strtoupper($e['level']) === 'ERROR')) ?>
</h3>
<p>Errors</p>
</div>
<div class="stat-card">
<h3 id="warning-count">
<?= count(array_filter($logEntries, fn($e) => strtoupper($e['level']) === 'WARNING')) ?>
</h3>
<p>Warnings</p>
</div> -->
<div class="stat-card">
<h3 id="newtoken-count">
<?= count(array_filter($logEntries, fn($e) => stripos($e['message'], 'TPA CLAIM PUSH SUCCESS') !== false)) ?>
</h3>
<p>Claim success</p>
</div>
<div class="stat-card">
<h3 id="newtoken-count">
<?= count(array_filter($logEntries, fn($e) => stripos($e['message'], 'TPA CLAIM PUSH FAILED') !== false)) ?>
</h3>
<p>Claim failed</p>
</div>
<div class="stat-card">
<h3 id="newtoken-count">
<?= count(array_filter($logEntries, fn($e) => stripos($e['message'], 'TPA ID PULL SUCCESS') !== false)) ?>
</h3>
<p>Tpa no pull success</p>
</div>
<div class="stat-card">
<h3 id="newtoken-count">
<?= count(array_filter($logEntries, fn($e) => stripos($e['message'], 'TPA ID PULL FAILED') !== false)) ?>
</h3>
<p>Tpa no pull Failed</p>
</div>
<div class="stat-card">
<h3 id="newtoken-count">
<?= count(array_filter($logEntries, fn($e) => stripos($e['message'], 'CLAIM STATUS SUCCESS') !== false)) ?>
</h3>
<p>Claim status fetch success</p>
</div>
<div class="stat-card">
<h3 id="newtoken-count">
<?= count(array_filter($logEntries, fn($e) => stripos($e['message'], 'CLAIM STATUS FAILED') !== false)) ?>
</h3>
<p>Claim status fetch failed</p>
</div>
<div class="stat-card">
<h3 id="newtoken-count">
<?= count(array_filter($logEntries, fn($e) => stripos($e['message'], 'Ecard Request PUSH SUCCESS') !== false)) ?>
</h3>
<p>Ecard Request</p>
</div>
</div>
<div class="controls">
<div class="filter-group">
<strong>Filter:</strong>
<button class="filter-btn active" data-level="all">All</button>
<button class="filter-btn" data-level="critical">Critical</button>
<button class="filter-btn" data-level="error">Error</button>
<button class="filter-btn" data-level="warning">Warning</button>
<button class="filter-btn" data-level="info">Info</button>
<button class="filter-btn" data-level="debug">Debug</button>
</div>
<input type="text" class="search-box" id="searchBox" placeholder="🔍 Search log messages...">
</div>
<?php if (empty($logEntries)): ?>
<div class="no-logs">
<h3>No Log Entries Found</h3>
<p>This log file is empty or couldn't be parsed.</p>
</div>
<?php else: ?>
<div class="log-entries" id="logEntries">
<?php foreach ($logEntries as $entry): ?>
<?php
$level = strtolower($entry['level']);
$levelClass = 'level-' . $level;
?>
<div class="log-entry <?= $level ?>" data-level="<?= $level ?>">
<div class="log-header">
<span class="log-level <?= $levelClass ?>">
<?= esc(strtoupper($entry['level'])) ?>
</span>
<span class="log-date"><?= esc($entry['date']) ?></span>
</div>
<div class="log-message"><?= esc($entry['message']) ?></div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
</div>
<script>
// Filter functionality
const filterBtns = document.querySelectorAll('.filter-btn');
const logEntries = document.querySelectorAll('.log-entry');
const searchBox = document.getElementById('searchBox');
let currentFilter = 'all';
filterBtns.forEach(btn => {
btn.addEventListener('click', () => {
filterBtns.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
currentFilter = btn.dataset.level;
applyFilters();
});
});
searchBox.addEventListener('input', applyFilters);
function applyFilters() {
const searchTerm = searchBox.value.toLowerCase();
logEntries.forEach(entry => {
const level = entry.dataset.level;
const message = entry.querySelector('.log-message').textContent.toLowerCase();
const matchesFilter = currentFilter === 'all' || level === currentFilter;
const matchesSearch = message.includes(searchTerm);
if (matchesFilter && matchesSearch) {
entry.classList.remove('hidden');
} else {
entry.classList.add('hidden');
}
});
}
</script>
</body>
</html>

View File

@ -342,7 +342,7 @@
<!-- end -->
<!-- Modal content for the Large example => Common mail -->
<!-- 1 Modal content for the Large example => Common mail -->
<div class="modal fade" id="member_common_mail_modal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel"
aria-hidden="true" aria-modal="true" data-backdrop="static">
<div class="modal-dialog modal-full-width scrollb">
@ -354,7 +354,7 @@
<div class="modal-body">
<div class="text-center" id="no_data"></div>
<form role="form" class="parsley-examples" method="post" id="member_common_mail_form" enctype="multipart/form-data">
<input type="hidden" class="form-control" id="template_name" name="template_name" value="Common Mail" readonly>
@ -391,11 +391,13 @@
<input type="text" id="subject" name="subject" class="form-control" placeholder="Subject">
</div>
<div class="form-group col-md-2 testmail" >
<a class="btn btn-primary waves-effect waves-light mr-1 setid" onclick="testMailSend(this)">Test Mail</a>
<div class="form-group col-md-5 testmail" >
<a class="btn btn-primary waves-effect waves-light mr-1 setid" onclick="testMailSend(this,'send')">Test Mail</a>
<a class="btn btn-primary waves-effect waves-light mr-1 setid" onclick="PreviewTheMail(this,'preview','member_common_mail')">Preview Mail</a>
</div>
</div>
<div class="member_common_mail_section">
<div class="form-row" id="rac_rate_dropdown">
<div class="form-group col-md-12">
<select id="member_common_mail_modal_customButton" class="form-control" style="border:none;right: 6px;width: auto;position: absolute;z-index: 1;top: 17px;height: 32px;float: right;" onchange="copyToClipboard(this)">
@ -421,33 +423,36 @@
<input type="file" id="Question_title_fileInput" style="display: none;">
<table data-custom-table-css="table" id="attachment_table" class="table table-sm mb-0" style="margin-top: 30px;">
<table data-custom-table-css="table" id="attachment_table_common" class="table table-sm mb-0" style="margin-top: 30px;">
<thead>
<tr>
<th>Attachments</th>
<th>Action</th>
</tr>
</thead>
<tbody id="attachment_tbody">
<tbody id="attachment_tbody_common">
</tbody>
</table>
</div>
<div class="form-group text-right m-b-0">
<div class="form-group text-right m-b-0 member_common_mail_action">
<button type="button" class="btn btn-primary waves-effect waves-light mr-1"
onclick="sendCommonMails()" > Send Common Mails </button>
<button type="submit" class="btn btn-primary waves-effect waves-light mr-1"
id="btnGridSubmit_2">Submit</button>
</div>
</div>
<div class="member_common_mail_preview"></div>
</form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- Modal content for the Large example => Welcome mail-->
<!-- 2 Modal content for the Large example => Welcome mail-->
<div class="modal fade" id="member_welcome_mail_modal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel"
aria-hidden="true" aria-modal="true" data-backdrop="static">
<div class="modal-dialog modal-full-width scrollb">
@ -474,11 +479,13 @@
<div class="form-group col-md-5">
<input type="text" id="subject" name="subject" class="form-control" placeholder="Subject">
</div>
<div class="form-group col-md-2 testmail" style="display: none;">
<a class="btn btn-primary waves-effect waves-light mr-1 setid" onclick="testMailSend(this)">Test Mail</a>
<div class="form-group col-md-5 testmail" style="display: none;">
<a class="btn btn-primary waves-effect waves-light mr-1 setid" onclick="testMailSend(this,'send')">Test Mail</a>
<a class="btn btn-primary waves-effect waves-light mr-1 setid" onclick="PreviewTheMail(this,'preview','member_welcome_mail')">Preview Mail</a>
</div>
</div>
<div class="member_welcome_mail_section">
<div class="form-row" id="rac_rate_dropdown">
<div class="form-group col-md-12">
<select id="member_welcome_mailmodal_customButton" class="form-control" style="border:none;right: 6px;width: auto;position: absolute;z-index: 1;top: 17px;height: 32px;float: right;" onchange="copyToClipboard(this)">
@ -516,18 +523,21 @@
</table>
</div>
</div>
<div class="member_welcome_mail_preview"></div>
<div class="form-group text-right m-b-0">
<div class="form-group text-right m-b-0 member_welcome_mail_action">
<button type="submit" class="btn btn-primary waves-effect waves-light mr-1"
id="btnGridSubmit_2">Submit</button>
</div>
</form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- Modal content for the Large example => Remainder mail -->
<!-- 3 Modal content for the Large example => Remainder mail -->
<div class="modal fade" id="member_reminder_mail_modal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="false" aria-modal="true">
<div class="modal-dialog modal-full-width">
<div class="modal-content">
@ -559,8 +569,9 @@
<div class="form-group col-md-5">
<input type="text" id="subject" name="subject" class="form-control" placeholder="Subject">
</div>
<div class="form-group col-md-2 testmail" style="display: none;">
<a class="btn btn-primary waves-effect waves-light mr-1 setid" onclick="testMailSend(this)">Test Mail</a>
<div class="form-group col-md-5 testmail" style="display: none;">
<a class="btn btn-primary waves-effect waves-light mr-1 setid" onclick="testMailSend(this,'send')">Test Mail</a>
<a class="btn btn-primary waves-effect waves-light mr-1 setid" onclick="PreviewTheMail(this,'preview','member_reminder_mail')">Preview Mail</a>
</div>
</div>
@ -575,6 +586,7 @@
</select>
</div>
</div> -->
<div class="member_reminder_mail_section">
<div class="form-row" id="rac_rate_dropdown">
<div class="form-group col-md-12">
<select id="member_reminder_mail_customButton" class="form-control" style="border:none;right: 6px;width: auto;position: absolute;z-index: 1;top: 17px;height: 32px;float: right;" onchange="copyToClipboard(this)">
@ -604,21 +616,35 @@
<input type="file" id="Question_title_fileInput" style="display: none;">
<table data-custom-table-css="table" id="attachment_table_reminder" class="table table-sm mb-0" style="margin-top: 30px;">
<thead>
<tr>
<th>Attachments</th>
<th>Action</th>
</tr>
</thead>
<tbody id="attachment_tbody_reminder">
</tbody>
</table>
</div>
<div class="form-group text-right m-b-0">
<div class="form-group text-right m-b-0 member_reminder_mail_action">
<button class="btn btn-primary waves-effect waves-light mr-1 preview_button"
id="">Preview</button>
<button type="submit" class="btn btn-primary waves-effect waves-light mr-1"
id="btnGridSubmit_2">Submit</button>
</div>
</form>
</div>
<div class="member_reminder_mail_preview"></div>
</form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- Modal content for the Large example => Ecard mail -->
<!-- 4 Modal content for the Large example => Ecard mail -->
<div class="modal fade" id="member_ecard_mail_modal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel"
aria-hidden="true" aria-modal="true" data-backdrop="static">
<div class="modal-dialog modal-full-width">
@ -651,10 +677,12 @@
<div class="form-group col-md-5">
<input type="text" id="subject" name="subject" class="form-control" placeholder="Subject">
</div>
<div class="form-group col-md-2 testmail" style="display: none;">
<a class="btn btn-primary waves-effect waves-light mr-1 setid" onclick="testMailSend(this)">Test Mail</a>
<div class="form-group col-md-5 testmail" style="display: none;">
<a class="btn btn-primary waves-effect waves-light mr-1 setid" onclick="testMailSend(this,'send')">Test Mail</a>
<a class="btn btn-primary waves-effect waves-light mr-1 setid" onclick="PreviewTheMail(this,'preview','member_ecard_mail')">Preview Mail</a>
</div>
</div>
<div class="member_ecard_mail_section">
<div class="form-row" id="rac_rate_dropdown">
<div class="form-group col-md-12">
<select id="member_ecard_mail_customButton" class="form-control" style="border:none;right: 6px;width: auto;position: absolute;z-index: 1;top: 17px;height: 32px;float: right;" onchange="copyToClipboard(this)">
@ -695,8 +723,10 @@
</table>
</div>
</div>
<div class="member_ecard_mail_preview"></div>
<div class="form-group text-right m-b-0">
<div class="form-group text-right m-b-0 member_ecard_mail_action">
<button class="btn btn-primary waves-effect waves-light mr-1 preview_button"
id="">Preview</button>
<button type="submit" class="btn btn-primary waves-effect waves-light mr-1"
@ -708,7 +738,7 @@
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- Modal content for the Large example => Review And Summary mail -->
<!-- 5 Modal content for the Large example => Review And Summary mail -->
<div class="modal fade" id="member_review_and_summary_mail_modal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel"
aria-hidden="true" aria-modal="true" data-backdrop="static">
<div class="modal-dialog modal-full-width">
@ -741,8 +771,9 @@
<div class="form-group col-md-5">
<input type="text" id="subject" name="subject" class="form-control" placeholder="Subject">
</div>
<div class="form-group col-md-2 testmail" style="display: none;">
<a class="btn btn-primary waves-effect waves-light mr-1 setid" onclick="testMailSend(this)">Test Mail</a>
<div class="form-group col-md-5 testmail" style="display: none;">
<a class="btn btn-primary waves-effect waves-light mr-1 setid" onclick="testMailSend(this,'send')">Test Mail</a>
<a class="btn btn-primary waves-effect waves-light mr-1 setid" onclick="PreviewTheMail(this,'preview','member_review_and_summary_mail')">Preview Mail</a>
</div>
</div>
@ -757,6 +788,7 @@
</select>
</div>
</div> -->
<div class="member_review_and_summary_mail_section">
<div class="form-row" id="rac_rate_dropdown">
<div class="form-group col-md-12">
<select id="member_review_and_summary_mail_customButton" class="form-control" style="border:none;right: 6px;width: auto;position: absolute;z-index: 1;top: 17px;height: 32px;float: right;" onchange="copyToClipboard(this)">
@ -785,10 +817,12 @@
<input type="file" id="Question_title_fileInput" style="display: none;">
</div>
<div class="member_review_and_summary_mail_preview"></div>
</div>
<div class="form-group text-right m-b-0">
<div class="form-group text-right m-b-0 member_review_and_summary_mail_action">
<button class="btn btn-primary waves-effect waves-light mr-1 preview_button"
id="">Preview</button>
<button type="submit" class="btn btn-primary waves-effect waves-light mr-1"
@ -800,7 +834,7 @@
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- Modal content for the Large example => Acc Manager Summary mail -->
<!-- 6 Modal content for the Large example => Acc Manager Summary mail -->
<div class="modal fade" id="account_maneger_summary_mail_modal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel"
aria-hidden="true" aria-modal="true" data-backdrop="static">
<div class="modal-dialog modal-full-width">
@ -828,10 +862,12 @@
<div class="form-group col-md-5">
<input type="text" id="subject" name="subject" class="form-control" placeholder="Subject">
</div>
<div class="form-group col-md-2 testmail" style="display: none;">
<a class="btn btn-primary waves-effect waves-light mr-1 setid" onclick="testMailSend(this)">Test Mail</a>
<div class="form-group col-md-5 testmail" style="display: none;">
<a class="btn btn-primary waves-effect waves-light mr-1 setid" onclick="testMailSend(this,'send')">Test Mail</a>
<a class="btn btn-primary waves-effect waves-light mr-1 setid" onclick="PreviewTheMail(this,'preview','account_maneger_summary_mail')">Preview Mail</a>
</div>
</div>
<div class="account_maneger_summary_mail_section">
<div class="form-row" id="rac_rate_dropdown">
<div class="form-group col-md-12">
<select id="account_maneger_summary_mail_modal_customButton" class="form-control" style="border:none;right: 6px;width: auto;position: absolute;z-index: 1;top: 17px;height: 32px;float: right;" onchange="copyToClipboard(this)">
@ -854,7 +890,9 @@
<div id="account_maneger_summary_mail_editor_container" style="height: 600px"></div>
</div>
<!-- </div> -->
<div class="form-group text-right m-b-0">
</div>
<div class="account_maneger_summary_mail_preview"></div>
<div class="form-group text-right m-b-0 account_maneger_summary_mail_action">
<button class="btn btn-primary waves-effect waves-light mr-1 preview_button"
id="">Preview</button>
<button type="submit" class="btn btn-primary waves-effect waves-light mr-1"
@ -867,14 +905,13 @@
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- Modal content for the Large example -->
<!-- 7 Modal content for the Large example => Client HR Summary mail -->
<div class="modal fade" id="client_hr_summary_mail_modal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel"
aria-hidden="true" aria-modal="true" data-backdrop="static">
<div class="modal-dialog modal-full-width">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myLargeModalLabel">Member Review and summary mail <span id="nameOfThePolicy"></span></h4>
<h4 class="modal-title" id="myLargeModalLabel">Member Review and Summary Mail <span id="nameOfThePolicy"></span></h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
@ -882,86 +919,74 @@
<div class="text-center" id="no_data"></div>
<form role="form" class="parsley-examples" method="post" id="client_hr_summary_mail_form" enctype="multipart/form-data">
<div class="form-group">
<div class="form-group">
<div class="form-row" id="rac_rate_dropdown">
<div class="form-group col-md-2">
<label for="template_name">Template Name</label>
</div>
<div class="form-group col-md-5">
<input type="text" id="template_name" name="template_name" value="Client HR Summary Mail" readonly class="form-control" placeholder="Template Name">
</div>
</div>
<div class="form-row" id="rac_rate_dropdown">
<div class="form-group col-md-2">
<label for="emp_code">Template Name</label>
<div class="form-row" id="rac_rate_dropdown">
<div class="form-group col-md-2">
<label for="subject">Subject</label>
</div>
<div class="form-group col-md-5">
<input type="text" id="subject" name="subject" class="form-control" placeholder="Subject">
</div>
<div class="form-group col-md-5 testmail" style="display: none;">
<a class="btn btn-primary waves-effect waves-light mr-1 setid" onclick="testMailSend(this,'send')">Test Mail</a>
<a class="btn btn-primary waves-effect waves-light mr-1 setid" onclick="PreviewTheMail(this,'preview','client_hr_summary_mail')">Preview Mail</a>
</div>
</div>
<div class="form-group col-md-5">
<input type="text" id="template_name" name="template_name" value="Client HR Summary Mail" readonly class="form-control" placeholder="Template Name">
<div class="client_hr_summary_mail_section">
<div class="form-row" id="rac_rate_dropdown">
<div class="form-group col-md-12">
<select id="client_hr_summary_mail_customButton" class="form-control" style="border:none; right:6px; width:auto; position:absolute; z-index:1; top:17px; height:32px; float:right;" onchange="copyToClipboard(this)">
<option value="">PlaceHolders</option>
<?php foreach ($placeHolders as $value): ?>
<?php if (in_array($value, ['member_name','nhance_logo','client_logo','app_link','client_name','member_summary'])): ?>
<?php $valueChange = ucwords(str_replace('_',' ',$value)); ?>
<option value="{{<?php echo $value; ?>}}"><?php echo $valueChange; ?></option>
<?php endif; ?>
<?php endforeach; ?>
</select>
<span id="copy-feedback" style="display: none; position: absolute; top:50px; right:10px; color:green; font-size:12px;">Copied to clipboard!</span>
</div>
</div>
<hr>
<!-- Unlayer editor -->
<div class="form-row" id="rac_rate_dropdown">
<div class="form-group col-md-12">
<div id="client_hr_summary_mail_editor_container" style="height:600px;"></div>
</div>
</div>
<div id="editor"></div>
<input type="file" id="Question_title_fileInput" style="display:none;">
</div>
</div> <!-- /.form-group -->
<div class="form-group text-right m-b-0 client_hr_summary_mail_action">
<button type="button" class="btn btn-primary waves-effect waves-light mr-1 preview_button">Preview</button>
<button type="submit" class="btn btn-primary waves-effect waves-light mr-1" id="btnGridSubmit_2">Submit</button>
</div>
<div class="form-row" id="rac_rate_dropdown">
<div class="form-group col-md-2">
<label for="emp_code">Subject</label>
</div>
<div class="form-group col-md-5">
<input type="text" id="subject" name="subject" class="form-control" placeholder="Subject">
</div>
<div class="form-group col-md-2 testmail" style="display: none;">
<a class="btn btn-primary waves-effect waves-light mr-1 setid" onclick="testMailSend(this)">Test Mail</a>
</div>
</div>
<!-- <div class="form-row" id="rac_rate_dropdown">
<div class="form-group col-md-12">
<select name="" id="" class="form-control" style="z-index: 1;float: right;position: absolute;margin-top: 18px;right: 53px;width: 100px;height: 30px;">
<option value="">1</option>
<option value="">2</option>
<option value="">3</option>
<option value="">4</option>
<option value="">6</option>
</select>
</div>
</div> -->
</div> -->
<div class="form-row" id="rac_rate_dropdown">
<div class="form-group col-md-12">
<select id="client_hr_summary_mail_customButton" class="form-control" style="border:none;right: 6px;width: auto;position: absolute;z-index: 1;top: 17px;height: 32px;float: right;" onchange="copyToClipboard(this)">
<option value="">PlaceHolders</option>
<?php foreach ($placeHolders as $value): ?>
<?php if ($value == 'member_name' || $value == 'nhance_logo' || $value == 'client_logo' || $value == 'app_link' || $value == 'client_name' || $value == 'member_summary') { ?>
<?php $valueChange = str_replace('_', ' ', $value);
$valueChange = ucwords($valueChange); ?>
<option value="{{<?php echo $value; ?>}}"><?php echo $valueChange; ?></option>
<?php } ?>
<?php endforeach; ?>
</select>
<span id="copy-feedback" style="display: none; position: absolute; top: 50px; right: 10px; color: green; font-size: 12px;">Copied to clipboard!</span>
</div>
</div>
<hr>
<!-- Unlayer editor -->
<div class="form-row" id="rac_rate_dropdown">
<div class="form-group col-md-12">
<div id="client_hr_summary_mail_editor_container" style="height: 600px"></div>
</div>
</div>
<div id="editor"></div>
<input type="file" id="Question_title_fileInput" style="display: none;">
</div>
<div class="form-group text-right m-b-0">
<button class="btn btn-primary waves-effect waves-light mr-1 preview_button"
id="">Preview</button>
<button type="submit" class="btn btn-primary waves-effect waves-light mr-1"
id="btnGridSubmit_2">Submit</button>
</div>
</form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
<!-- /.modal -->
<div class="client_hr_summary_mail_preview"></div>
</form>
</div> <!-- /.modal-body -->
</div> <!-- /.modal-content -->
</div> <!-- /.modal-dialog -->
</div> <!-- /.modal -->
<div class="modal fade" id="preview_modal" tabindex="-1" role="dialog" aria-hidden="false" aria-modal="true" data-backdrop="static">
<div class="modal-dialog modal-dialog-centered">
@ -978,6 +1003,7 @@
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- <script>
$(document).ready(function() {
const fileInput = document.getElementById("Question_title_fileInput");
@ -1274,6 +1300,8 @@
// Global editor variable
let editor = null;
let template_name = '';
var activeParentModalId = null;
$(document).ready(function() {
const fileInput = document.getElementById("Question_title_fileInput");
@ -1293,7 +1321,8 @@
})
function testMailSend(input) {
// keep watching
function testMailSend(input,StringFlag) {
let test_mail = prompt("Please enter test mail:");
console.log('mail address:', test_mail);
@ -1306,7 +1335,8 @@
console.log('templte id', template_id);
if (template_id) {
let url = '<?= base_url('util/sentTestMail/') ?>' + template_id + '/' + test_mail;
// let url = '<?= base_url('util/sentTestMail/') ?>' + template_id + '/' + test_mail;
let url = '<?= base_url('util/sentTestMail/') ?>' + template_id + '/' + test_mail + '/'+StringFlag;
console.log('testing mail url:', url);
$('.loader').fadeIn();
@ -1439,13 +1469,19 @@
function addHTMLInput(data = null) {
console.log('addHTMLInput function called');
console.log(template_name);
console.log(`:) addHTMLInput function called for ${template_name}`); // REF : PS
var container = '';
if (template_name == 'member_welcome_mail') {
container = document.getElementById('attachment_tbody');
}
else {
else if (template_name == 'member_common_mail') {
container = document.getElementById('attachment_tbody_common');
}
else if (template_name == 'member_reminder_mail') {
container = document.getElementById('attachment_tbody_reminder');
}
else {
container = document.getElementById('attachment_tbody_ecard');
}
@ -1469,20 +1505,39 @@
const newFormRow = document.createElement('tr');
newFormRow.className = 'dynamic-form-row';
newFormRow.innerHTML = `
<td>
<form class="ajax" onsubmit="submitAttachmentForm(event, this)">
<div class="form-row">
<div class="form-group col-3">
<input type="file" class="file-input__input" name="file" required>
// newFormRow.innerHTML = `
// <td>
// <form class="ajax" onsubmit="submitAttachmentForm(event, this)">
// <div class="form-row">
// <div class="form-group col-3">
// <input type="file" class="file-input__input" name="file" required>
// </div>
// <div class="form-group col-2">
// <button type="submit" class="btn btn-sm btn-primary">Submit</button>
// </div>
// </div>
// </form>
// </td>
// `; // DONT DELETE IT REF : VVJ
newFormRow.innerHTML = `<td>
<form class="ajax" onsubmit="submitAttachmentForm(event, this)">
<div style="display:flex; align-items:center; gap:10px; white-space:nowrap;">
<div>
<input type="file" name="file" required
style="width:100%; min-width:160px;
padding: 0 !important;
background-color: transparent !important;
border-radius: 0 !important;
box-shadow: none !important;
border-color: initial !important; color: white;">
</div>
<div>
<button type="submit" class="btn btn-sm btn-primary">Submit</button>
</div>
</div>
<div class="form-group col-2">
<button type="submit" class="btn btn-sm btn-primary">Submit</button>
</div>
</div>
</form>
</td>
`;
</form>
</td><td></td>`; // REF : PS
container.appendChild(newFormRow);
@ -1490,21 +1545,38 @@
// If no data is passed, create a new empty row
const newRow = document.createElement('tr');
newRow.className = 'dynamic-form-row';
newRow.innerHTML = `<td><form class="ajax" onsubmit="submitAttachmentForm(event, this)">
<div style="display:flex; align-items:center; gap:10px; white-space:nowrap;">
<div>
<input type="file" name="file" required
style="width:100%; min-width:160px;
padding: 0 !important;
background-color: transparent !important;
border-radius: 0 !important;
box-shadow: none !important;
border-color: initial !important; color: white;">
</div>
<div>
<button type="submit" class="btn btn-sm btn-primary">Submit</button>
</div>
</div>
</form>
</td><td></td>`; // REF : PS
newRow.innerHTML = `
<td>
<form class="ajax" onsubmit="submitAttachmentForm(event, this)">
<div class="form-row">
<div class="form-group col-3">
<input type="file" class="file-input__input" name="file" required>
</div>
<div class="form-group col-2">
<button type="submit" class="btn btn-sm btn-primary">Submit</button>
</div>
</div>
</form>
</td>
`;
// newRow.innerHTML = `
// <td>
// <form class="ajax" onsubmit="submitAttachmentForm(event, this)">
// <div class="form-row">
// <div class="form-group col-3">
// <input type="file" class="file-input__input" name="file" required>
// </div>
// <div class="form-group col-2">
// <button type="submit" class="btn btn-sm btn-primary">Submit</button>
// </div>
// </div>
// </form>
// </td>
// `; // DONT DELETE IT REF : VVJ
container.appendChild(newRow);
}
}
@ -1512,7 +1584,14 @@
function removeHTMLInput(element) {
if (template_name == 'member_welcome_mail') {
const container = document.getElementById('attachment_tbody');
} else {
}
else if (template_name == 'member_common_mail') {
container = document.getElementById('attachment_tbody_common');
}
else if (template_name == 'member_reminder_mail') {
container = document.getElementById('attachment_tbody_reminder');
}
else {
const container = document.getElementById('attachment_tbody_ecard');
}
const rows = container.querySelectorAll('.dynamic-form-row');
@ -1530,6 +1609,7 @@
// var template_name = template_name;
var client_id = $('#general_PrimaryKey').val();
// console.log(client_id);
console.log(`:) Submitted for ${template_name}`);
const formData = new FormData(form);
formData.append('template_name', template_name);
@ -1764,7 +1844,7 @@
const validTemplates = [
"account_maneger_summary_mail", "member_reminder_mail","member_common_mail", "member_ecard_mail", "member_welcome_mail", "member_review_and_summary_mail", "client_hr_summary_mail"
];
console.log(`:) getMailTemplateData function called for ${template_name}`); // REF : PS
if (!validTemplates.includes(template_name)) {
console.error("Invalid template name:", template_name);
return;
@ -1782,7 +1862,7 @@
type: "GET",
dataType: 'json',
success: function(res) {
console.log('get Mail Template Data', res);
console.log(':) getMailTemplateData Resp are', res);
if (res) {
// Set subject
@ -1833,6 +1913,8 @@
$('.testmail').toggle(!!res.id);
$('#attachment_table').toggle(!!res.id);
$('#attachment_table_ecard').toggle(!!res.id);
$('#attachment_table_common').toggle(!!res.id);
$('#attachment_table_reminder').toggle(!!res.id);
$('.setid').attr('data-id', res.id || '');
if (template_name == "member_common_mail"){
$('#notification_temp_id').val(res.id);
@ -2436,4 +2518,69 @@
}
});
})
function PreviewTheMail(button, StringFlag,className) {
let $btn = $(button);
let $formSection = $('.' + className + '_section');
let $actionButtons = $('.' + className + '_action');
let $previewSection= $('.' + className + '_preview');
console.log(":/");
console.log($formSection, $actionButtons, $previewSection);
// let $formSection = $('.client_hr_summary_mail_section');
// let $actionButtons = $('.client_hr_summary_mail_action');
// let $previewSection = $('.client_hr_summary_mail_preview');
// 2nd click → Close preview
if ($btn.data('previewing')) {
$formSection.show();
$actionButtons.show();
$previewSection.hide();
$btn.text('Preview Mail');
$btn.data('previewing', false);
return;
}
// 1st click → Open preview
let template_id = $btn.data('id');
let test_mail = "xyz@gmail.com";
if(!template_id){
toastr.warning('Template ID not exist', 'WARNING');
return;
}
let url = '<?= base_url('util/sentTestMail/') ?>' + template_id + '/' + test_mail + '/' + StringFlag;
$('.loader, .loader-mask').fadeIn();
$.ajax({
url: url,
type: "GET",
dataType: 'json',
success: function(res){
$('.loader, .loader-mask').fadeOut();
if(res.status){
let content = res.content || "No Data Found";
$previewSection.html(content.message);
$formSection.hide();
$actionButtons.hide();
$previewSection.show();
$btn.text('Close Preview');
$btn.data('previewing', true);
} else {
toastr.warning('Failed to load content', 'WARNING');
}
},
error: function(xhr){
$('.loader, .loader-mask').fadeOut();
console.error(xhr.responseText);
}
});
}
</script>

View File

@ -109,7 +109,6 @@
margin-top:10px;
}
</style>
<div id="policyGMCTerms" style="display:none">
@ -126,8 +125,8 @@
<div class="form-group">
<div class="row" style="margin-bottom: 10px;">
<!-- <div class="row" style="margin-bottom: 10px;">
REF: VR
<div class="col">
<div class="d-flex align-items-center gap-2">
<label for="sumInsured" class="form-label" >Sum Insured</label>
@ -143,9 +142,9 @@
</div>
</div>
REF: VR
<div id="gmc_si_add_more"></div>
REF: VR
<div class="row" style="margin-bottom:10px;">
<div class="col">
<label for="totalSumInsured" class="form-label me-3">Family Floater</label>
@ -160,6 +159,45 @@
<label class="form-check-label" for="familyFloaterNo">No</label>
</div>
</div>
</div> -->
<div class="row mb-2">
<div class="col-md-4">
<label class="form-label">Sum Insured</label>
</div>
<div class="col-md-6">
<div class="d-flex align-items-center gap-2">
<input class="form-control" type="text" name="sum_insured" id="sum_insured"
style="max-width:200px;"
onkeypress="return onlyNumbers(event)"
onkeyup="formatNumber(this); si_keup_num_to_word(this)">
<button type="button" class="btn btn-primary ml-2 si-add-more"
onclick="appendGMCSIAddMore()"
style="background-color:#e26728;border:1px solid #e26728;">
<i class="mdi mdi-plus"></i>
</button>
</div>
<div id="numberToWordGMC" class="text-danger-2 mt-1"></div>
</div>
</div>
<div id="gmc_si_add_more"></div>
<div class="row mb-2">
<div class="col-md-4">
<label class="form-label">Family Floater</label>
</div>
<div class="col-md-6">
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" id="familyFloaterYes" name="family_floater" value="1">
<label class="form-check-label" for="familyFloaterYes" style="width: 52px !important">Yes</label>
<input class="form-check-input" type="radio" id="familyFloaterNo" name="family_floater" value="0">
<label class="form-check-label" for="familyFloaterNo">No</label>
</div>
</div>
</div>
@ -1183,6 +1221,7 @@
if (Array.isArray(jsonObject[key])) {
jsonObject[key].forEach((value, index) => {
appendGMCSIAddMore(value);
});
} else {
console.log(`${key} is not an array.`);
@ -1269,14 +1308,27 @@
if (element.value === jsonObject[key]) {
element.checked = element.value === jsonObject[key];
if (element.name === "family_floater") {
element.parentElement.nextElementSibling.style
.display = '';
element.parentElement.parentElement
.parentElement.nextElementSibling.style
.display = '';
// alert('family floater');
} else if (element.name ===
// if (element.name === "family_floater") { REF: VR
// element.parentElement.nextElementSibling.style
// .display = '';
// element.parentElement.parentElement
// .parentElement.nextElementSibling.style
// .display = '';
// // alert('family floater');
// }
if (element.name === "family_floater" && element.checked) {
let currentRow = element.closest('.row');
if (currentRow && currentRow.nextElementSibling) {
currentRow.nextElementSibling.style.display = '';
}
if (currentRow && currentRow.nextElementSibling && currentRow.nextElementSibling.nextElementSibling) {
currentRow.nextElementSibling.nextElementSibling.style.display = '';
}
}
else if (element.name ===
"waiverofpreexistingdiseases") {
element.parentElement.parentElement
.nextElementSibling.style.display = '';
@ -1546,6 +1598,52 @@
}
};
$("#sum_insured").on("keyup", function() {
var inputNumber = $(this).val();
console.log('keyup sum insured 2nd');
if (inputNumber) {
var result = convertCommaNumberToWords(inputNumber);
$("#numberToWordSumInsured").text(result);
} else {
$("#numberToWordSumInsured").text("");
}
});
$(".multiple_sum_insured").on("keyup", function() {
console.log('multiple_sum_insured key up')
var inputNumber = $(this).val();
console.log('inputNumber', inputNumber);
if (inputNumber) {
var result = convertCommaNumberToWords(inputNumber);
console.log(result);
$(".numberToWordSumInsured").text(result);
} else {
$(".numberToWordSumInsured").text("");
}
});
function numtowordinkeyup(input) {
console.log('numtowordinkeyup');
var inputNumber = $(input).val().toString().replace(/,/g, '').trim();
var $parentRow = $(input).closest('.row');
var $targetDiv = $parentRow.find('.numberToWordSumInsured');
if (inputNumber) {
var result = convertCommaNumberToWords(inputNumber);
$targetDiv.text(result);
} else {
$targetDiv.text("");
}
}
</script>
<!-- Policy terms Add Special Condition -->
@ -1749,35 +1847,67 @@
}
}
function appendGMCSIAddMore(data = null) {
//REF: VR
// function appendGMCSIAddMore(data = null) {
// console.log('function called')
// var html = `
// <div class="row" style="margin-bottom: 10px;">
// <div class="col">
// <div class="d-flex align-items-center gap-2">
// <label for="sumInsured" class="form-label" >Additional Sum Insured</label>
// <input class="form-control mr-2" style="max-width:200px;"
// value="${data == null || data == undefined || data == "" ? '' : data}" type="text" name="multiple_sum_insured[]"
// class="form-control multiple_sum_insured mr-2" onkeypress="return onlyNumbers(event)"
// onkeyup="formatNumber(this); numtowordinkeyup(this)">
// <button type="button" class="btn btn-primary si-add-more mr-2" onclick="appendGMCSIAddMore()"
// style="background-color: #e26728; border:1px solid #e26728;">
// <i class="mdi mdi-plus"></i>
// </button>
// <button type="button" class="btn btn-danger si-remove-multi mr-2" onclick="removeGMCAdditionalSI(this)"
// style="background-color: #BD0707;border:1px solid #BD0707">
// <i class="mdi mdi-delete"></i>
// </button>
// <div id='numberToWordSumInsured' class="text-danger-2 mr-2"></div>
// </div>
// </div>
// </div> `;
// $('#gmc_si_add_more').append(html);
// }
function appendGMCSIAddMore(data = '') {
console.log('function called')
var html = `
<div class="row" style="margin-bottom: 10px;">
<div class="col">
<div class="d-flex align-items-center gap-2">
<label for="sumInsured" class="form-label" >Additional Sum Insured</label>
<input class="form-control mr-2" style="max-width:200px;"
value="${data == null || data == undefined || data == "" ? '' : data}" type="text" name="multiple_sum_insured[]"
class="form-control multiple_sum_insured mr-2" onkeypress="return onlyNumbers(event)"
onkeyup="formatNumber(this); numtowordinkeyup(this)">
<button type="button" class="btn btn-primary si-add-more mr-2" onclick="appendGMCSIAddMore()"
style="background-color: #e26728; border:1px solid #e26728;">
<i class="mdi mdi-plus"></i>
</button>
<button type="button" class="btn btn-danger si-remove-multi mr-2" onclick="removeGMCAdditionalSI(this)"
style="background-color: #BD0707;border:1px solid #BD0707">
<i class="mdi mdi-delete"></i>
</button>
<div id='numberToWordSumInsured' class="text-danger-2 mr-2"></div>
</div>
<div class="row align-items-start mb-2">
<div class="col-md-4">
<label class="form-label">Additional Sum Insured</label>
</div>
</div>
`;
$('#gmc_si_add_more').append(html);
<div class="col-md-6">
<div class="d-flex align-items-center gap-2">
<input class="form-control" style="max-width:200px;"
value="${data == null || data == undefined || data == "" ? '' : data}" type="text" name="multiple_sum_insured[]"
type="text" name="multiple_sum_insured[]"
onkeypress="return onlyNumbers(event)"
onkeyup="formatNumber(this); numtowordinkeyup(this)">
<button type="button" class="btn btn-primary si-add-more ml-2 "
onclick="appendGMCSIAddMore()"
style="background-color:#e26728;border:1px solid #e26728;">
<i class="mdi mdi-plus"></i>
</button>
<button type="button" class="btn btn-danger si-remove-multi ml-2"
onclick="removeGMCAdditionalSI(this)"
style="background-color:#BD0707;border:1px solid #BD0707;">
<i class="mdi mdi-delete"></i>
</button>
</div>
<div class="text-danger-2 mr-2 numberToWordSumInsured"></div>
</div>
</div>`;
$('#gmc_si_add_more').append(html);
}
function removeGMCAdditionalSI(button) {
@ -2037,5 +2167,4 @@
}
});
</script>

View File

@ -104,8 +104,8 @@
<div class="form-group">
<div class="row" style="margin-bottom: 10px;">
<!-- <div class="row" style="margin-bottom: 10px;">
REF: VR
<div class="col">
<div class="d-flex align-items-center gap-2">
<label for="sumInsured" class="form-label" >Sum Insured</label>
@ -123,7 +123,7 @@
</div>
</div>
REF: VR
<div class="row" style="margin-bottom: 10px;">
<div class="col">
@ -134,8 +134,44 @@
<div id='numberToWordTotalSumInsured' class="text-danger-2 mr-2"></div>
</div>
</div>
</div> -->
<div class="row mb-2">
<div class="col-md-4">
<label for="sumInsured" class="form-label" >Sum Insured</label>
</div>
<div class="col-md-6">
<div class="d-flex align-items-center gap-2">
<input class="form-control mr-2" type="text" name="sumInsured2" id="sumInsured2" style="max-width:200px;"
onkeypress="return onlyNumbers(event)" onkeyup="formatNumber(this)">
<button type="button" class="btn btn-primary si-add-more ml-2" onclick="appendGPASIAddMore()"
style="background-color: #e26728; border:1px solid #e26728;">
<i class="mdi mdi-plus"></i>
</button>
</div>
<div id='numberToWordSumInsured' class="text-danger-2 mr-2"></div>
</div>
</div>
<div id="gpa_si_add_more"></div>
<div class="row mb-2">
<div class="col-md-4">
<label for="totalSumInsured">Total Sum Assured</label>
</div>
<div class="col-md-6">
<div class="d-flex align-items-center gap-2">
<input type="text" style="max-width: 200px !important;" class="form-control mr-2" name="totalSumInsured"
id="totalSumInsured" onkeypress="return onlyNumbers(event)" onkeyup="formatNumber(this)">
</div>
<div id='numberToWordTotalSumInsured' class="text-danger-2 mr-2"></div>
</div>
</div>
<div class="row" style="margin-bottom: 10px;">
<div class="col d-flex align-items-center"
style="background-color: #F5FFFF;border-radius:10px;box-shadow: 0px 2px 2px 0px #00000040;
@ -144,7 +180,7 @@
<input disabled type="checkbox" style="color:black;" name="family_floaters[]"
value="self" id="self" checked>
<span style="margin-right: 40px;color:black;">Self</span>
<span style="margin-right: 40px;color:black; margin-left: 8px;">Self</span>
<div class="self-age" style="margin-right: 20px;">
<span style="margin-right: 20px;color:black;">Min Age:</span>
@ -885,23 +921,40 @@
}
});
// function numtowordinkeyup(input) {
// console.log('testing......')
// console.log(input);
// var inputNumber = $(input).val();
// console.log('inputNumber', inputNumber);
// if (inputNumber) {
// var result = numberToWordsIndian(inputNumber);
// console.log(result);
// var $parentRow = $(input).closest('.row');
// console.log('$parentRow', $parentRow)
// var $targetDiv = $parentRow.find('.numberToWordSumInsured');
// $targetDiv.text(result)
// console.log('$targetDiv', $targetDiv)
// }
// }
function numtowordinkeyup(input) {
console.log('testing......')
console.log(input);
var inputNumber = $(input).val();
console.log('inputNumber', inputNumber);
var inputNumber = $(input).val().toString().replace(/,/g, '').trim();
var $parentRow = $(input).closest('.row');
var $targetDiv = $parentRow.find('.numberToWordSumInsured');
if (inputNumber) {
var result = numberToWordsIndian(inputNumber);
console.log(result);
var $parentRow = $(input).closest('.row');
console.log('$parentRow', $parentRow)
var $targetDiv = $parentRow.find('.numberToWordSumInsured');
$targetDiv.text(result)
console.log('$targetDiv', $targetDiv)
var result = convertCommaNumberToWords(inputNumber);
$targetDiv.text(result);
} else {
$targetDiv.text("");
}
}
$("#totalSumInsured").on("keyup", function() {
@ -914,35 +967,69 @@
}
});
//REF: VR function appendGPASIAddMore(data = null) {
// console.log('appendGPASIAddMore function called')
// console.log('appendGPASIAddMore function data', data)
// var html = `
// <div class="row" style="margin-bottom: 10px;">
// <div class="col">
// <div class="d-flex align-items-center gap-2">
// <label for="sumInsured" class="form-label" >Additional Sum Insured</label>
// <input
// style="max-width:200px;"
// value="${data == null || data == undefined || data == "" ? '' : data}" type="text" name="multiple_sum_insured[]"
// class="form-control multiple_sum_insured mr-2" onkeypress="return onlyNumbers(event)" onkeyup="formatNumber(this); numtowordinkeyup(this)">
// <button type="button" class="btn btn-primary si-add-more mr-2" onclick="appendGPASIAddMore()"
// style="background-color: #e26728; border:1px solid #e26728;" >
// <i class="mdi mdi-plus"></i>
// </button>
// <button type="button" class="btn btn-danger si-remove-multi mr-2" onclick="removeGMCAdditionalSI(this)"
// style="background-color: #BD0707;border:1px solid #BD0707">
// <i class="mdi mdi-delete"></i>
// </button>
// <div id='numberToWordSumInsured' class="text-danger-2 "></div>
// </div>
// </div>
// </div>
// `;
// $('#gpa_si_add_more').append(html);
// }
function appendGPASIAddMore(data = null) {
console.log('appendGPASIAddMore function called')
console.log('appendGPASIAddMore function data', data)
var html = `
<div class="row" style="margin-bottom: 10px;">
<div class="col">
<div class="row align-items-start mb-2">
<div class="col-md-4">
<label for="sumInsured" class="form-label" >Additional Sum Insured</label>
</div>
<div class="col-md-6">
<div class="d-flex align-items-center gap-2">
<label for="sumInsured" class="form-label" >Additional Sum Insured</label>
<input
style="max-width:200px;"
value="${data == null || data == undefined || data == "" ? '' : data}" type="text" name="multiple_sum_insured[]"
class="form-control multiple_sum_insured mr-2" onkeypress="return onlyNumbers(event)" onkeyup="formatNumber(this); numtowordinkeyup(this)">
<button type="button" class="btn btn-primary si-add-more mr-2" onclick="appendGPASIAddMore()"
style="max-width:200px;"
value="${data == null || data == undefined || data == "" ? '' : data}" type="text" name="multiple_sum_insured[]"
class="form-control multiple_sum_insured mr-2" onkeypress="return onlyNumbers(event)" onkeyup="formatNumber(this); numtowordinkeyup(this)">
<button type="button" class="btn btn-primary si-add-more ml-2" onclick="appendGPASIAddMore()"
style="background-color: #e26728; border:1px solid #e26728;" >
<i class="mdi mdi-plus"></i>
</button>
<button type="button" class="btn btn-danger si-remove-multi mr-2" onclick="removeGMCAdditionalSI(this)"
<button type="button" class="btn btn-danger si-remove-multi ml-2" onclick="removeGMCAdditionalSI(this)"
style="background-color: #BD0707;border:1px solid #BD0707">
<i class="mdi mdi-delete"></i>
</button>
<div id='numberToWordSumInsured' class="text-danger-2 "></div>
</div>
</div>
</div>
`;
<div class="text-danger-2 mr-2 numberToWordSumInsured"></div>
</div>
</div>`;
$('#gpa_si_add_more').append(html);
}

View File

@ -63,7 +63,7 @@
aria-hidden="true" aria-modal="true" data-backdrop="static" style="padding-right: 15px">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<!-- <div class="modal-header">
<div class="col-md-6">
<h4 class="modal-title" id="myLargeModalLabel">Rack Rate <span id="PolicyNameForTitle"></span></h4>
</div>
@ -73,6 +73,13 @@
<div class="col-md-1" style="position: relative;top: 10px;">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
</div> -->
<div class="modal-header d-flex align-items-center justify-content-between">
<h4 class="modal-title" id="myLargeModalLabel">Rack Rate <span id="PolicyNameForTitle"></span></h4><!-- Left: Title -->
<div class="d-flex align-items-center">
<div id="add_new_rack_rate_tab_div" class="mr-5"><button class="btn btn-info waves-effect waves-light" id="add_new_rack_rate_tab" onclick="appendNewTab()">Add Rack Rate</button></div><!-- Add Button (show/hide works normally) -->
<button type="button" class="close mr-1" data-dismiss="modal" aria-hidden="true">×</button><!-- Close Button -->
</div><!-- Right: Buttons -->
</div>
<div class="modal-body">

View File

@ -966,7 +966,7 @@
dataType: 'json',
success: function (res) {
console.log(res)
console.log("get_client_policy_data_using_policy_no_and_endo_no Response : ", res);
if(res.status == true){
$('#ct_type').val(1)
}else{
@ -979,6 +979,8 @@
console.error(status, error);
}
});
}else{
console.log('Policy number or Endorsement Number is empty')
}
})
@ -1103,6 +1105,11 @@
$('#table_tr_37').show();
}
if (res.data.policy_type_id == 1 || res.data.policy_type_id == 2 || res.data.policy_type_id == 3 || res.data.policy_type_id == 4 || res.data.policy_type_id == 5 || res.data.policy_type_id == 6 || res.data.policy_type_id == 7 || res.data.client_type == 2) {
$('#table_tr_34').hide();
$('#table_tr_37').hide();
}
// if(res.data.policy_type_id == 1 || res.data.policy_type_id == 2 || res.data.policy_type_id == 3 || res.data.policy_type_id == 4 || res.data.policy_type_id == 5 || res.data.policy_type_id == 6 || res.data.policy_type_id == 7){
// $('#is_cd_reduce_from_bds').prop('disabled',true).prop('checked', false);
// }else{

File diff suppressed because it is too large Load Diff

View File

@ -346,9 +346,11 @@ table.dataTable thead th {
<a class="dropdown-item btnEdit" data-id="<?= $row['id']; ?>" onclick="getPolicyTransactionDataForEndorsementEdit('<?= htmlspecialchars($row['id'], ENT_QUOTES) ?>')">
<i class="mdi mdi-pencil mr-2 text-muted font-18 vertical-middle"></i>Edit
</a>
<a class="dropdown-item delete" data-id="<?= $row['id'];?>" onclick="removePolicyTransaction(this, '<?= htmlspecialchars($row['id'], ENT_QUOTES) ?>', <?= $row['policy_type_id'] ?>)">
<i class="mdi mdi-delete mr-2 text-muted font-18 vertical-middle"></i>Delete
</a>
<?php if(get_role_id() == 5): ?>
<a class="dropdown-item delete" data-id="<?= $row['id'];?>" onclick="removePolicyTransaction(this, '<?= htmlspecialchars($row['id'], ENT_QUOTES) ?>', <?= $row['policy_type_id'] ?>)">
<i class="mdi mdi-delete mr-2 text-muted font-18 vertical-middle"></i>Delete
</a>
<?php endif; ?>
</div>
</div>
</td>

File diff suppressed because it is too large Load Diff

View File

@ -2160,6 +2160,12 @@
$('.loader-mask').delay(350).fadeOut('slow');
}
});
if (res.data.policy_type_id == 1 || res.data.policy_type_id == 2 || res.data.policy_type_id == 3 || res.data.policy_type_id == 4 || res.data.policy_type_id == 5 || res.data.policy_type_id == 6 || res.data.policy_type_id == 7 || res.data.client_type == 2) {
$('#table_tr_34').hide();
$('#table_tr_37').hide();
}
}, 4000)
// Set additional fields

File diff suppressed because it is too large Load Diff

View File

@ -317,7 +317,7 @@ table.dataTable tbody td {
<tr>
<td class="text-center"><?php echo $index+1; ?></td>
<td><?php echo $issuer[$row['issuer']]; ?></td>
<td><?php echo $issuing_type[$row['issue_type']] ?: 'N/A'; ?></td>
<td><?php echo $issuing_type[$row['issue_type']] ?? 'N/A'; ?></td>
<td><?php echo $client_type[$row['client_type']] ?? 'N/A'; ?></td>
<td><?php echo $row['client_type'] == 2 ? $row['client_name'] . " - " . (!empty($row['pan']) ? $row['pan'] : 'N/A') : $row['client_short_name'] . ' - ' . $row['client_branch_name']; ?></td>
<td><?php echo $row['insurer_short_name'] ?: 'N/A'; ?></td>
@ -328,7 +328,7 @@ table.dataTable tbody td {
<td><?php echo empty($row['policy_issue_date']) ? 'N/A' : date('d/m/Y', strtotime($row['policy_end_date'])); ?></td>
<td class="right-align-input"><?php echo $row['emp_count'] ?: '0'; ?></td>
<td class="right-align-input"><?php echo $row['dependent_count'] ?: '0'; ?></td>
<td><?php echo $policy_status[$row['status']] ?: 'N/A'; ?></td>
<td><?php echo $policy_status[$row['status']] ?? 'N/A'; ?></td>
<td><?php echo $row['user_name'] ?: 'N/A'; ?></td>
<td>
<div class="btn-group dropdown">
@ -337,9 +337,12 @@ table.dataTable tbody td {
<a class="dropdown-item btnEdit" data-id="<?= $row['id'];?>" onclick="getPolicyTransactionDataForEdit('<?= htmlspecialchars($row['id'], ENT_QUOTES) ?>')">
<i class="mdi mdi-pencil mr-2 text-muted font-18 vertical-middle"></i>Edit
</a>
<a class="dropdown-item delete" data-id="<?= $row['id'];?>" onclick="removePolicyTransaction(this, '<?= htmlspecialchars($row['id'], ENT_QUOTES) ?>', <?= $row['policy_type_id'] ?>)">
<i class="mdi mdi-delete mr-2 text-muted font-18 vertical-middle"></i>Delete
</a>
<?php if(get_role_id() == 5): ?>
<a class="dropdown-item delete" data-id="<?= $row['id'];?>" onclick="removePolicyTransaction(this, '<?= htmlspecialchars($row['id'], ENT_QUOTES) ?>', <?= $row['policy_type_id'] ?>)">
<i class="mdi mdi-delete mr-2 text-muted font-18 vertical-middle"></i>Delete
</a>
<?php endif; ?>
</div>
</div>
</td>
@ -641,6 +644,7 @@ $(document).ready(function(){
var renewal_date = new Date(policy_end_date);
// renewal_date.setMonth(renewal_date.getMonth() - 1);
renewal_datePicker.setDate(renewal_date); // Set renewal date
renewal_datePicker.set('maxDate', policy_end_date); // set max date
}
});
@ -1768,4 +1772,17 @@ function removePolicyTransaction(input, pt_id, policy_type_id) {
});
}
function showForm(form) {
if (form == 1) {
$('#form1').show();
$('#form2').hide();
}
if (form == 2) {
$('#form1').hide();
$('#form2').show();
}
}
</script>

File diff suppressed because it is too large Load Diff

View File

@ -7,7 +7,7 @@
<button class="scroll-btn left-btn" type="button">&#9664;</button>
</li>
<li class="nav-item">
<a href="#form" data-toggle="tab" aria-expanded="false" class="nav-link px-3 py-2 active" id="general_tab">
<a href="#form" data-toggle="tab" aria-expanded="false" class="nav-link px-3 py-2 active-tab active" id="general_tab">
<span class="mr-1"><i class="mdi mdi-contacts"></i></span>
<span class="d-none d-sm-inline-block">Policy</span>
</a>

View File

@ -0,0 +1,94 @@
<div class="row" id="pt_onboarding2" style="position: relative; bottom: 25px;">
<div class="col-xl-12">
<div class="card-body">
<div class="tab-wrapper position-relative">
<ul class="nav nav-pills navtab-bg" id="myTab">
<li class="nav-item d-flex justify-content-center align-items-center">
<button class="scroll-btn left-btn" type="button">&#9664;</button>
</li>
<li class="nav-item">
<a href="#form" data-toggle="tab" aria-expanded="false" class="nav-link px-3 py-2 active-tab active" id="general_tab">
<span class="mr-1"><i class="mdi mdi-contacts"></i></span>
<span class="d-none d-sm-inline-block">Policy</span>
</a>
</li>
<li class="nav-item">
<a href="#KYC-DOC-tab" data-toggle="tab" aria-expanded="true" class="nav-link px-3 py-2" id="kyc_tab2">
<span class="mr-1"><i class="mdi mdi-file"></i></span>
<span class="d-none d-sm-inline-block">KYC Docs</span>
</a>
</li>
<li class="nav-item" id="hide_file_upload" style="display: none;">
<a href="#fileupload" data-toggle="tab" aria-expanded="true" class="nav-link px-3 py-2" id="kyc_tab">
<span class="mr-1"><i class="mdi mdi-file"></i></span>
<span class="d-none d-sm-inline-block">File Upload</span>
</a>
</li>
<li class="nav-item" id="hide_vehicle_tab" style="display: none;">
<a href="#vehicle-docs-tab" data-toggle="tab" aria-expanded="true" class="nav-link px-3 py-2" id="vehicle_tab">
<span class="mr-1"><i class="mdi mdi-file"></i></span>
<span class="d-none d-sm-inline-block">Vehicle Docs</span>
</a>
</li>
<li class="nav-item d-flex justify-content-center align-items-center">
<!-- Right Arrow -->
<button class="scroll-btn right-btn" type="button">&#9654;</button>
</li>
</ul>
</div>
<div class="tab-content">
<?php include('vehicle_docs.php'); ?>
<?php include('drive_file_upload.php'); ?>
<?php include('client_kyc_2.php'); ?>
<?php include('policy_transaction_inception_form_2.php'); ?>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
// $('#pt_onboarding2').show();
// $('#general_tab').tab('show');
$('#kyc_tab').on('click', function(e) {
var ptId = $('#policy_tranction_primarykey').val();
if (!ptId) { // Check if ptId is empty or null
e.preventDefault(); // Prevent the tab from opening
$('#g_drive_file_upload_sbt_btn').hide()
toastr.warning('Please create Policy before proceeding to File Upload.');
} else {
$('#g_drive_file_upload_sbt_btn').show()
}
});
$('#kyc_tab2').on('click', function(e) {
var ptId = $('#policy_tranction_primarykey').val();
if (!ptId) { // Check if ptId is empty or null
e.preventDefault(); // Prevent the tab from opening
$('#btn_other_docs').hide()
toastr.warning('Please create Policy before proceeding to File Upload.');
} else {
$('#btn_other_docs').show()
}
});
$('#vehicle_tab').on('click', function(e) {
var ptId = $('#policy_tranction_primarykey').val();
if (!ptId) { // Check if ptId is empty or null
e.preventDefault(); // Prevent the tab from opening
$('#vehicle_file_upload_sbt_btn').hide()
toastr.warning('Please create Policy before proceeding to File Upload.');
} else {
$('#vehicle_file_upload_sbt_btn').show()
}
});
});
</script>

View File

@ -1,75 +1,80 @@
<div class="container-fluid-min">
<div class="container-fluid-min" style="margin-left: 30px;">
<div class="col-xl-12">
<div class="card-body">
<div id="accordion" class="mb-3">
<div class="card mb-1">
<h4 class="m-1">
<span>Filter</span>
<a id="toggleIcon" class="text-dark float-right" data-toggle="collapse" href="#collapseOne"
aria-expanded="true">
<i id="icon" class="mdi mdi-chevron-down mr-1 text-primary" style="font-size: 28px;"></i>
</a>
</h4>
<div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion">
<div class="card-body">
<!-- <div class="text-center"> -->
<div class="form-row">
<div class="form-group col-md-3" id="date_div">
<label>Date<span class="text-danger"></span></label>
<!-- <div id="reportrange" class="form-control"
style="background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc; width: 100%">
<i class="mdi mdi-calendar-blank"></i>&nbsp;
<span></span> <i class="mdi mdi-menu-down"></i>
</div> -->
<div class="input-icon">
<input type="text" id="reportrange" class="form-control" readonly style="caret-color: transparent;">
<i class="mdi mdi-calendar-blank-outline additional-icon"></i>
</div>
<input type="hidden" id="startDate" value=<?= $default_start ?>>
<input type="hidden" id="endDate" value=<?= $default_end ?>>
<div id="accordion" class="mb-3">
<div class="card mb-1" style="background-color: #F5FFFF !important; border-radius: 10px; box-shadow: 4px 4px 4px 4px #00000040;">
<h4 class="m-1" style="display: flex;justify-content: space-between;padding: 12px;">
<span>Filter</span>
<a id="toggleIcon" class="text-dark float-right" data-toggle="collapse" href="#collapseOne"
aria-expanded="true">
<i id="icon" class="mdi mdi-chevron-down mr-1 text-primary" style="font-size: 28px;"></i>
</a>
</h4>
<div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion">
<div class="card-body" style="margin-top: -30px;">
<!-- <div class="text-center"> -->
<div class="form-row">
<div class="form-group col-md-3" id="date_div">
<label>Date<span class="text-danger"></span></label>
<!-- <div id="reportrange" class="form-control"
style="background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc; width: 100%">
<i class="mdi mdi-calendar-blank"></i>&nbsp;
<span></span> <i class="mdi mdi-menu-down"></i>
</div> -->
<div class="input-icon">
<input type="text" id="reportrange" class="form-control" readonly style="caret-color: transparent;">
<i class="mdi mdi-calendar-blank-outline additional-icon"></i>
</div>
<input type="hidden" id="startDate" value=<?= $default_start ?>>
<input type="hidden" id="endDate" value=<?= $default_end ?>>
</div>
<div class="form-group col-md-3">
<label for="client_branch">Issuer<span class="text-danger"></span></label>
<select class="form-control" id="issuer" name="issuer">
<option value="">Select Issuer</option>
<?php
if (isset($issuer) && count($issuer)) {
foreach ($issuer as $key => $value) {
echo "<option value=" . $key . ">" . $value . "</option>";
}
<div class="form-group col-md-3">
<label for="client_branch">Nhance Branch<span class="text-danger"></span></label>
<select class="form-control" id="issuer_branch" name="issuer_branch">
<option value="">Select Branch</option>
<?php
if (isset($issuer_branch) && count($issuer_branch)) {
foreach ($issuer_branch as $key => $value) {
echo "<option value=" . $value['id'] . ">" . $value['branch_name'] . "</option>";
}
?>
</select>
</div>
<div class="form-group col-md-3 client_type_div">
<label for="client_type">Client Type<span class="text-danger"></span></label>
<select class="form-control" id="client_type" name="client_type">
<option value="">Select Client type</option>
<option value="1">Group</option>
<option value="2">Individual</option>
</select>
</div>
<div class="form-group col-md-3">
<label for="client_branch">Client<span class="text-danger"></span></label>
<select class="form-control" id="client_id" name="client_id">
<option value="">Select Client</option>
</select>
</div>
}
?>
</select>
</div>
<div class="row justify-content-end">
<div class="col-auto">
<a href="#" class="btn btn-primary waves-effect waves-light" id="get-report-page"
onclick="fetchReportPage(event);">Submit</a>
</div>
<div class="form-group col-md-3 client_type_div">
<label for="client_type">Client Type<span class="text-danger"></span></label>
<select class="form-control" id="client_type" name="client_type">
<option value="">Select Client type</option>
<option value="1">Group</option>
<option value="2">Individual</option>
</select>
</div>
<!-- </div> -->
<div class="form-group col-md-3">
<label for="client_branch">Client<span class="text-danger"></span></label>
<select class="form-control" id="client_id" name="client_id">
<option value="">Select Client</option>
<?php
if (isset($client_list) && count($client_list)) {
foreach ($client_list as $key => $value) {
echo "<option value=" . $value['id'] . ">" . $value['client_name'] . "</option>";
}
}
?>
</select>
</div>
</div>
<div class="row justify-content-end">
<div class="col-auto">
<a href="#" class="btn btn-primary waves-effect waves-light" id="get-report-page"
onclick="fetchReportPage(event);">Submit</a>
</div>
</div>
<!-- </div> -->
</div>
</div>
</div>
@ -85,8 +90,9 @@
let client_list = [];
$(document).ready(function() {
getClientAndBranchAndPolicy();
// getClientAndBranchAndPolicy();
$('#client_id').select2();
$('#issuer_branch').select2();
})
$(function() {
@ -133,13 +139,13 @@
var toDate = $('#endDate').val();
var client_id = $('#client_id').val();
var client_type = $('#client_type').val();
var issuer = $('#issuer').val();
var issuer_branch = $('#issuer_branch').val();
var requestData = {
fromDate: fromDate,
toDate: toDate,
client_id: client_id,
client_type: client_type,
issuer: issuer,
issuer_branch: issuer_branch,
};
console.log(typeof fromDate);
var url = '<?= base_url('/bdsReport/renewal_report') ?>';
@ -173,9 +179,13 @@
//get client , branch, policy data
function getClientAndBranchAndPolicy() {
return_type = 'client';
$.ajax({
url: '<?= base_url("/util/getClientAndBranchAndPolicy") ?>',
type: "GET",
data:{ return_type : return_type},
dataType: 'json',
success: function(res) {

View File

@ -79,7 +79,7 @@ table.dataTable tbody td {
<thead class="bg-light">
<tr>
<th>S. No</th>
<th style="display: none;">User</th>
<th>User</th>
<th>Month</th>
<th style="display: none;">Business Type</th>
<th style="display: none;">Client Type</th>
@ -109,13 +109,19 @@ table.dataTable tbody td {
<th>Agreed Amount</th>
<th>Invoiced Amount</th>
<th>Outstanding Amount</th>
<th style="display: none;">Salse Person</th>
<th style="display: none;">Service Person</th>
<th style="display: none;">Nhance Branch</th>
<th style="display: none;">Installment</th>
<th style="display: none;">Data Received Date</th>
<th style="display: none;">Renewal Date</th>
</tr>
</thead>
<tbody>
<?php if (isset($report_list)) { ?>
<?php foreach($report_list as $index => $row){ ?>
<tr>
<tr data-id="<?= $row['pt_id'] ?>">
<td><?= $index + 1 ?> &nbsp; <a href="<?php
if(strtolower($row['action_type']) == "policy"){
echo base_url('policy_tranction/inception/list') . '?pt_id=' . $row['id'] ;
@ -123,7 +129,7 @@ table.dataTable tbody td {
echo base_url('policy_tranction/endorsement/list') . '?pt_id=' . $row['id'] ;
}
?>" class="mdi mdi-pencil" ></a> </td>
<td style="display: none;"><?php echo $row['user_name'] ?: 'N/A'; ?></td>
<td><?php echo $row['user_name'] ?: 'N/A'; ?></td>
<td><?php echo $row['policy_issue_month'] ?: 'N/A'; ?></td>
<td style="display: none;"><?php echo $row['revenue_type'] ?: 'N/A'; ?></td>
<td style="display: none;"><?php echo $row['client_type'] ?: 'N/A'; ?></td>
@ -142,9 +148,9 @@ table.dataTable tbody td {
<td style="display: none;"><?php echo empty($row['policy_end_date']) ? 'N/A' : date('d/m/Y', strtotime($row['policy_end_date'])); ?></td>
<td style="display: none;"><?php echo $row['ref'] ?: 'N/A'; ?></td>
<td style="display: none;"><?php echo $row['remarks'] ?: 'N/A'; ?></td>
<td class="right-align-input"><?php echo $row['bp_amt'] ?: '0.00'; ?></td>
<td class="right-align-input"><?php echo ($row['total_irda_amt'] != 0.00) ? ($row['bp_amt'] ?: '0.00') : '0.00'; ?></td>
<td class="right-align-input"><?php echo $row['tp_or_ter'] ?: '0.00'; ?></td>
<td class="right-align-input"><?php echo $row['premium_wo_gst']; ?></td>
<td class="right-align-input"><?php echo ($row['total_irda_amt'] != 0.00) ? ($row['premium_wo_gst'] ?: '0.00') : '0.00'; ?></td>
<!-- <td class="right-align-input" style="display: none;"><?php echo $row['gst_amount']; ?></td> -->
<td class="right-align-input" style="display: none;"><?php echo $row['total_premium'] ?: '0.00'; ?></td>
<td class="right-align-input"><?php echo $row['agreed_bp_per'] ?: '0.00'; ?>%</td>
@ -175,9 +181,23 @@ table.dataTable tbody td {
// REF : Velmurugan but he told handle in query
// Date : 6/11/25 12:50
$unbilled_amt = $total_irda_amt - $row['billed_amt'];
if($total_irda_amt == "0.00"){
$unbilled_amt = abs($unbilled_amt);
}
$unbilled_amt = $unbilled_amt == 0 && $row['billed_amt'] == 0 ? $total_irda_amt : $unbilled_amt ;
?>
<td class="right-align-input"><?php echo number_format((float)$unbilled_amt,2, '.', '')?></td>
<td class="right-align-input">
<?php echo
// number_format((float)$unbilled_amt,2, '.', '')
number_format((float)$row['unbilled_amount'],2, '.', '');
?>
</td>
<td style="display: none;"><?php echo $row['salse_person_name'] ?: 'N/A'; ?></td>
<td style="display: none;"><?php echo $row['service_person_name'] ?: 'N/A'; ?></td>
<td style="display: none;"><?php echo $row['nhance_branch'] ?: 'N/A'; ?></td>
<td style="display: none;"><?php echo $row['installment'] ?: 'N/A'; ?></td>
<td style="display: none;"><?php echo empty($row['data_received_date']) ? 'N/A' : date('d/m/Y', strtotime($row['data_received_date'])) ?></td>
<td style="display: none;"><?php echo empty($row['renewal_date']) ? 'N/A' : date('d/m/Y', strtotime($row['renewal_date'])) ?></td>
</tr>
<?php } ?>
<?php } ?>
@ -538,6 +558,33 @@ $(document).ready(function() {
// $('#total_billed').text(totalBilled.toFixed(2));
// $('#total_unbilled').text(totalUnbilled.toFixed(2));
var getUniqueUnbilled = function(colIndex) {
var rows = api.rows({ search: 'applied' }).nodes(); // get filtered nodes
var maxRowPerId = {}; // store only the greatest row
$(rows).each(function() {
var rowId = $(this).data('id'); // read data-id
var rowIndex = $(this).index(); // row index
// Keep only the greatest row index per data-id
if (!maxRowPerId[rowId] || rowIndex > maxRowPerId[rowId]) {
maxRowPerId[rowId] = rowIndex;
}
});
var total = 0;
// Now sum only the selected rows
$.each(maxRowPerId, function(id, rowIndex) {
var value = api.cell(rowIndex, colIndex).data();
value = parseFloat((typeof value === 'string') ? value.replace(/[^0-9.\-]+/g, '') : value) || 0;
total += value;
});
return total;
};
// Helper to sum numeric values safely
var getTotal = function(colIndex) {
return api.column(colIndex, { search: 'applied' }).data()
@ -551,21 +598,20 @@ $(document).ready(function() {
};
// Compute totals by column index
var totalPremium = getTotal(21);
var totalPremium = getTotal(20);
var totalRewards = getTotal(24);
var totalIrda = getTotal(25);
var totalBilled = getTotal(26);
var totalUnbilled = getTotal(27);
// var totalUnbilled = getTotal(27);
// Update the totals section above the table
$('#total_premium').text(totalPremium.toFixed(2));
$('#total_rewards').text(totalRewards.toFixed(2));
$('#total_irda').text(totalIrda.toFixed(2));
$('#total_billed').text(totalBilled.toFixed(2));
// $('#total_unbilled').text(totalUnbilled.toFixed(2));
var totalUnbilled = getUniqueUnbilled(27);
$('#total_unbilled').text(totalUnbilled.toFixed(2));
}
});
} else {
@ -632,5 +678,10 @@ function appendTableData(data) {
});
}
$('table tbody').on('click', 'td', function () {
var colIndex = $(this).index();
var rowIndex = $(this).closest('tr').index();
console.log('Row:', rowIndex, 'Column:', colIndex);
});
</script>

View File

@ -33,19 +33,29 @@
}
</style>
<div class="row">
<div class="col-12">
<div class="card" style="margin-right: 23px;">
<div class="card-body">
<!-- Header Section -->
<div class="row mb-3">
<div class="col-6 d-flex align-items-center">
<div class="row mb-3 align-items-center justify-content-between">
<div class="col-auto">
<h4 class="mb-0">Claims</h4>
</div>
<div class="col-6 text-right">
<div class="col-auto d-flex align-items-center">
<?php if(isset($ticket_data['tpa_claim_push_reference_no']) && !empty($ticket_data['tpa_claim_push_reference_no'])) : ?>
<a href="#" class="btn btn-success mr-2" onclick="fetchTpaClaimStatus()">
Fetch Claim Status
</a>
<?php endif; ?>
<a href="<?= base_url('ticket/list'); ?>" aria-label="Back to ticket list">
<i class="mdi mdi-arrow-left" style="font-size: 17px;"></i>
<i class="mdi mdi-arrow-left" style="font-size: 24px;"></i>
</a>
</div>
</div>
@ -350,4 +360,34 @@
}
});
}
function fetchTpaClaimStatus(){
let ticket_master_id = $('#ticket_master_id').val();
console.log({ticket_master_id});
let requestData = {
claim_id: ticket_master_id,
};
let url = '<?= base_url('ticket/getTpaClaimStatus') ?>';
// Send AJAX request
sendAjaxRequestForGlobal(url, 'GET', requestData, function(response) {
console.log('Data fetched successfully:', response);
if (response.status) {
toastr.success(response.message || 'Status updated successfully', 'SUCCESS');
window.location.reload(true);
} else {
toastr.warning(response.message || 'Failed to update status', 'WARNING');
}
}, function(xhr, status, error) {
console.error('Error fetching data:', error);
console.error(xhr.responseText);
toastr.error('An error occurred while saving docs.', 'ERROR');
});
}
</script>

View File

@ -283,6 +283,45 @@
name="hospital_name" required>
</div>
<div class="form-group col-md-9">
<label class="label-font-size" for="hospital_address">Hospital Address <span class="text-danger">*</span></label>
<textarea class="form-control" id="hospital_address" name="hospital_address" rows="1" placeholder="Enter Hospital Address" required>
<?= isset($ticket_data['hospital_address']) ? $ticket_data['hospital_address'] : '' ?>
</textarea>
</div>
<div class="form-group col-md-3">
<label class="label-font-size" for="hospital_city">Hospital City <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="hospital_city"
placeholder="Enter Hospital City"
value="<?= isset($ticket_data['hospital_city']) ? $ticket_data['hospital_city'] : '' ?>"
name="hospital_city" required>
</div>
<div class="form-group col-md-3">
<label class="label-font-size" for="hospital_state">Hospital State <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="hospital_state"
placeholder="Enter Hospital State"
value="<?= isset($ticket_data['hospital_state']) ? $ticket_data['hospital_state'] : '' ?>"
name="hospital_state" required>
</div>
<div class="form-group col-md-3">
<label class="label-font-size" for="hospital_pin_code">Hospital Pincode <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="hospital_pin_code" maxlength="6"
placeholder="Enter Pincode"
value="<?= isset($ticket_data['hospital_pin_code']) ? $ticket_data['hospital_pin_code'] : '' ?>"
name="hospital_pin_code" required>
</div>
<div class="form-group col-md-3">
<label class="label-font-size" for="hospital_phone_no">Hospital Phone <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="hospital_phone_no" minlength="10" maxlength="10"
placeholder="Enter Phone Number"
value="<?= isset($ticket_data['hospital_phone_no']) ? $ticket_data['hospital_phone_no'] : '' ?>"
name="hospital_phone_no" required>
</div>
<div class="form-group col-md-3">
<label class="label-font-size" for="doa">DOA <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="doa" placeholder="Enter DOA"
@ -300,6 +339,7 @@
<label class="label-font-size" for="claim_amount">Claim Amount <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="claim_amount"
placeholder="Enter Claim Amount"
oninput="this.value = this.value.replace(/[^0-9]/g,'');"
value="<?= isset($ticket_data['claim_amount']) ? $ticket_data['claim_amount'] : '' ?>"
name="claim_amount" required>
</div>
@ -308,6 +348,7 @@
<label class="label-font-size" id="pod_no_label_1" for="pod_no">POD No with Courier Name <span id="pod_no_label_1_span" class="text-danger"></span></label>
<input type="text" class="form-control" id="pod_no" placeholder="Enter POD NO"
value="<?= isset($ticket_data['pod_no']) ? $ticket_data['pod_no'] : '' ?>"
oninput="this.value = this.value.replace(/[^0-9]/g, '');"
name="pod_no">
</div>
@ -374,6 +415,9 @@
<input type="text" class="form-control" id="approved_amount" placeholder="Enter Approved Amount"
value="<?= isset($ticket_data['approved_amount']) ? $ticket_data['approved_amount'] : '' ?>" name="approved_amount"
oninput="this.value = this.value.replace(/[^0-9]/g, '');">
<!-- <small class="text-danger d-none" id="approved_error">
Approved Amount cannot be greater than Claim Amount
</small> -->
</div>
<div class="form-group col-md-3 approved" style="display: none;">
@ -471,7 +515,6 @@
</div>
</div>
<!-- Info Modal -->
<div class="modal fade" id="moreInfoModal" tabindex="-1" role="dialog" aria-labelledby="fullWidthModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl" role="document">
@ -489,7 +532,6 @@
</div>
</div>
<script>
// $(document).ready(function() {
// var calim_status = $('#claim_status_id').val();
@ -507,6 +549,8 @@
var doa;
$(document).ready(function() {
let tpa_id_for_hid_filed = '<?= isset($ticket_data['tpa_id']) ? $ticket_data['tpa_id'] : '' ?>';
$("#emp_client_policy").select2();
var policy_id = $("#emp_client_policy").val();
@ -566,12 +610,12 @@
allowInput: false
});
updateClaimStatusDisplay("<?= isset($ticket_data['claim_status_id']) ? $ticket_data['claim_status_id'] : 0 ?>")
var extraFields = <?= json_encode(isset($extra_fields) ? $extra_fields : []); ?>;
GlobelExtraFields = extraFields;
console.log("extraFields", extraFields);
claimStatusFieldChanges(extraFields);
updateClaimStatusDisplay("<?= isset($ticket_data['claim_status_id']) ? $ticket_data['claim_status_id'] : 0 ?>")
handleTPARequired(tpa_id_for_hid_filed);
})
// function updateClaimStatusDisplay(value) {
@ -1206,8 +1250,12 @@
$('#insurer_name').val(insurer_name);
$('#tpa_id').val(tap_id);
$('#tpa_name').val(tap_name);
handleTPARequired(tap_id);
}
</script>
<script>
$("#infoIcon").click(function() {
var ticket_id = $('#ticket_master_id').val();
@ -1315,4 +1363,66 @@
}
}
}
</script>
function handleTPARequired(tpaId) {
console.log('handleTPARequired function called with tpaid :', tpaId)
const fields = [
"hospital_address",
"hospital_city",
"hospital_state",
"hospital_pin_code",
"hospital_phone_no"
];
fields.forEach(function (id) {
const input = document.getElementById(id);
const label = document.querySelector(`label[for="${id}"]`);
if (!input || !label) return;
if (tpaId == 3) {
input.setAttribute("required", true);
if (!label.querySelector(".text-danger")) {
label.innerHTML += ' <span class="text-danger">*</span>';
}
} else {
input.removeAttribute("required");
const star = label.querySelector("span.text-danger");
if (star) star.remove();
}
});
}
</script>
<!-- <script>
document.getElementById('approved_amount').addEventListener('input', function () {
let claimAmount = parseFloat(document.getElementById('claim_amount').value) || 0;
let approvedAmount = parseFloat(this.value) || 0;
let error = document.getElementById('approved_error');
if (approvedAmount > claimAmount) {
this.value = claimAmount;
error.classList.remove('d-none');
} else {
error.classList.add('d-none');
}
});
</script>
<script>
document.getElementById('policy_form').addEventListener('submit', function (e) {
let claimAmount = parseFloat(document.getElementById('claim_amount').value) || 0;
let approvedAmount = parseFloat(document.getElementById('approved_amount').value) || 0;
if (approvedAmount > claimAmount) {
e.preventDefault();
toastr.warning('Approved Amount cannot be greater than Claim Amount', "Warning");
document.getElementById('approved_amount').focus();
return false;
}
});
</script> -->

View File

@ -1,6 +1,20 @@
<style>
/** CSS changes are not applying on the Client Onboarding screen . so i implement this CSS fixes . */
/* #New_Ticket_modal .modal-dialog {
max-width: 500px !important;
margin: 1.75rem auto !important;
}
@media (min-width: 576px) {
#New_Ticket_modal .modal-dialog {
max-width: 500px !important;
margin: 1.75rem auto !important;
}
} */
</style>
<div class="modal fade" id="New_Ticket_modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-content"> <!-- style="height: 200px !important;" -->
<div class="modal-header">
<h4 class="modal-title" id="myCenterModalLabel"></h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
@ -18,6 +32,12 @@
</select>
</div>
</div>
<!--
<div class="form-row">
<div class="form-group col-md-12 text-right"><!- text-end ->
<button type="button" class="btn btn-primary mt-1" onclick="submitToRedirectTicketNewUrl(this)">Submit</button>
</div>
</div>-->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" onclick="submitToRedirectTicketNewUrl(this)">Submit</button>

View File

@ -97,7 +97,7 @@
// dom: "<'row'<'col-sm-7'f><'col-sm-5 text-right'B>>" + // Filter left, buttons right
// "<'row'<'col-sm-12'tr>>" +
// "<'row'<'col-sm-5'i><'col-sm-7'p>>", // Pagination at the bottom, without page length selector
dom: "<'row'<'col-12 d-flex justify-content-between align-items-center'<'datatable-search dataTables_filter'f><'datatable-buttons dt-buttons'B>>>" +
dom: "<'row'<'col-sm-7'f><'col-sm-5 text-right'B>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row align-items-center'<'col-5 text-start'i><'col-7 d-flex justify-content-end align-items-center'<'me-2'l>p>>",
lengthMenu: [[10, 20, 50, 100], [10, 20, 50, 100]],

View File

@ -903,6 +903,11 @@
<input id="is_cd_switch" type="checkbox" name = "is_cd" value = "1" data-toggle="toggle" data-on="With CD" data-off="Without CD" data-onstyle="info" data-offstyle="primary" data-style="border" data-width="219" <?= isset($lead_data['is_cd']) && $lead_data['is_cd'] != 1 ? '' : 'checked' ?>>
</div>
<div class="form-group col-md-3">
<label for="agreed_percentage">Agreed Percentage (%)</label>
<input type="number" class="form-control" id="agreed_percentage" name="agreed_percentage" placeholder="Enter Agreed Percentage (%)" minlength="0" maxlength="100" step="0.01" value="<?= isset($lead_data['agreed_percentage']) ? $lead_data['agreed_percentage'] : "" ?>">
</div>
<div class="form-group col-md-3">
<label for="premium_amount">Pre Amount include GST</label>
<input type="text" class="form-control" id="premium_amount" name="premium_amount" placeholder="Enter Premium Amount" value="<?= isset($lead_data['premium_amount']) ? $lead_data['premium_amount'] : "" ?>">
@ -4410,6 +4415,7 @@ function constructURL_ForPlacementMailSend(return_type = false) {
let is_cd = $("#is_cd_switch").is(":checked") ? 1 : 0;
let utr_no = $('#utr_no').val();
let premium_amount = $('#premium_amount').val();
let agreed_percentage = $('#agreed_percentage').val();
let total_amount = $('#total_amount').val();
let cd_amount = $('#cd_amount').val();
let subject = $('#placement_subject').val();
@ -4483,8 +4489,9 @@ function constructURL_ForPlacementMailSend(return_type = false) {
formData.append('tpa_id', tpa_id);
formData.append('acm_email', acm_email);
formData.append('acm_pk', acm_pk);
formData.append('agreed_percentage', agreed_percentage);
// Prepare plain key-value object
// Prepare plain key-value object
let dataObj = {
lead_id: lead_id,
file_type: RFQ_or_QCR == 2 ? 'qcr' : 'rfq',
@ -4510,7 +4517,8 @@ function constructURL_ForPlacementMailSend(return_type = false) {
is_installment: is_installment,
tpa_id: tpa_id,
acm_email: acm_email,
acm_pk: acm_pk
acm_pk: acm_pk,
agreed_percentage: agreed_percentage,
};
if(return_type == false){
@ -7645,4 +7653,9 @@ function appendMultiFileData(data) {
}
}
$('#agreed_percentage').on('input', function () {
let v = parseFloat(this.value);
this.value = (v < 0) ? 0 : (v > 100 ? 100 : v);
});
</script>

76
ca.pem Normal file
View File

@ -0,0 +1,76 @@
-----BEGIN CERTIFICATE-----
MIIEADCCAuigAwIBAgIQB/57HSuaqUkLaasdjxUdPjANBgkqhkiG9w0BAQsFADCB
mDELMAkGA1UEBhMCVVMxIjAgBgNVBAoMGUFtYXpvbiBXZWIgU2VydmljZXMsIElu
Yy4xEzARBgNVBAsMCkFtYXpvbiBSRFMxCzAJBgNVBAgMAldBMTEwLwYDVQQDDChB
bWF6b24gUkRTIGFwLXNvdXRoLTEgUm9vdCBDQSBSU0EyMDQ4IEcxMRAwDgYDVQQH
DAdTZWF0dGxlMCAXDTIxMDUxOTE3NDAzNFoYDzIwNjEwNTE5MTg0MDM0WjCBmDEL
MAkGA1UEBhMCVVMxIjAgBgNVBAoMGUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4x
EzARBgNVBAsMCkFtYXpvbiBSRFMxCzAJBgNVBAgMAldBMTEwLwYDVQQDDChBbWF6
b24gUkRTIGFwLXNvdXRoLTEgUm9vdCBDQSBSU0EyMDQ4IEcxMRAwDgYDVQQHDAdT
ZWF0dGxlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtbkaoVsUS76o
TgLFmcnaB8cswBk1M3Bf4IVRcwWT3a1HeJSnaJUqWHCJ+u3ip/zGVOYl0gN1MgBb
MuQRIJiB95zGVcIa6HZtx00VezDTr3jgGWRHmRjNVCCHGmxOZWvJjsIE1xavT/1j
QYV/ph4EZEIZ/qPq7e3rHohJaHDe23Z7QM9kbyqp2hANG2JtU/iUhCxqgqUHNozV
Zd0l5K6KnltZQoBhhekKgyiHqdTrH8fWajYl5seD71bs0Axowb+Oh0rwmrws3Db2
Dh+oc2PwREnjHeca9/1C6J2vhY+V0LGaJmnnIuOANrslx2+bgMlyhf9j0Bv8AwSi
dSWsobOhNQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBQb7vJT
VciLN72yJGhaRKLn6Krn2TAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZIhvcNAQELBQAD
ggEBAAxEj8N9GslReAQnNOBpGl8SLgCMTejQ6AW/bapQvzxrZrfVOZOYwp/5oV0f
9S1jcGysDM+DrmfUJNzWxq2Y586R94WtpH4UpJDGqZp+FuOVJL313te4609kopzO
lDdmd+8z61+0Au93wB1rMiEfnIMkOEyt7D2eTFJfJRKNmnPrd8RjimRDlFgcLWJA
3E8wca67Lz/G0eAeLhRHIXv429y8RRXDtKNNz0wA2RwURWIxyPjn1fHjA9SPDkeW
E1Bq7gZj+tBnrqz+ra3yjZ2blss6Ds3/uRY6NYqseFTZWmQWT7FolZEnT9vMUitW
I0VynUbShVpGf6946e0vgaaKw20=
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIICrjCCAjWgAwIBAgIQGKVv+5VuzEZEBzJ+bVfx2zAKBggqhkjOPQQDAzCBlzEL
MAkGA1UEBhMCVVMxIjAgBgNVBAoMGUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4x
EzARBgNVBAsMCkFtYXpvbiBSRFMxCzAJBgNVBAgMAldBMTAwLgYDVQQDDCdBbWF6
b24gUkRTIGFwLXNvdXRoLTEgUm9vdCBDQSBFQ0MzODQgRzExEDAOBgNVBAcMB1Nl
YXR0bGUwIBcNMjEwNTE5MTc1MDU5WhgPMjEyMTA1MTkxODUwNTlaMIGXMQswCQYD
VQQGEwJVUzEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNlcywgSW5jLjETMBEG
A1UECwwKQW1hem9uIFJEUzELMAkGA1UECAwCV0ExMDAuBgNVBAMMJ0FtYXpvbiBS
RFMgYXAtc291dGgtMSBSb290IENBIEVDQzM4NCBHMTEQMA4GA1UEBwwHU2VhdHRs
ZTB2MBAGByqGSM49AgEGBSuBBAAiA2IABMqdLJ0tZF/DGFZTKZDrGRJZID8ivC2I
JRCYTWweZKCKSCAzoiuGGHzJhr5RlLHQf/QgmFcgXsdmO2n3CggzhA4tOD9Ip7Lk
P05eHd2UPInyPCHRgmGjGb0Z+RdQ6zkitKNCMEAwDwYDVR0TAQH/BAUwAwEB/zAd
BgNVHQ4EFgQUC1yhRgVqU5bR8cGzOUCIxRpl4EYwDgYDVR0PAQH/BAQDAgGGMAoG
CCqGSM49BAMDA2cAMGQCMG0c/zLGECRPzGKJvYCkpFTCUvdP4J74YP0v/dPvKojL
t/BrR1Tg4xlfhaib7hPc7wIwFvgqHes20CubQnZmswbTKLUrgSUW4/lcKFpouFd2
t2/ewfi/0VhkeUW+IiHhOMdU
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIGATCCA+mgAwIBAgIRAKlQ+3JX9yHXyjP/Ja6kZhkwDQYJKoZIhvcNAQEMBQAw
gZgxCzAJBgNVBAYTAlVTMSIwIAYDVQQKDBlBbWF6b24gV2ViIFNlcnZpY2VzLCBJ
bmMuMRMwEQYDVQQLDApBbWF6b24gUkRTMQswCQYDVQQIDAJXQTExMC8GA1UEAwwo
QW1hem9uIFJEUyBhcC1zb3V0aC0xIFJvb3QgQ0EgUlNBNDA5NiBHMTEQMA4GA1UE
BwwHU2VhdHRsZTAgFw0yMTA1MTkxNzQ1MjBaGA8yMTIxMDUxOTE4NDUyMFowgZgx
CzAJBgNVBAYTAlVTMSIwIAYDVQQKDBlBbWF6b24gV2ViIFNlcnZpY2VzLCBJbmMu
MRMwEQYDVQQLDApBbWF6b24gUkRTMQswCQYDVQQIDAJXQTExMC8GA1UEAwwoQW1h
em9uIFJEUyBhcC1zb3V0aC0xIFJvb3QgQ0EgUlNBNDA5NiBHMTEQMA4GA1UEBwwH
U2VhdHRsZTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAKtahBrpUjQ6
H2mni05BAKU6Z5USPZeSKmBBJN3YgD17rJ93ikJxSgzJ+CupGy5rvYQ0xznJyiV0
91QeQN4P+G2MjGQR0RGeUuZcfcZitJro7iAg3UBvw8WIGkcDUg+MGVpRv/B7ry88
7E4OxKb8CPNoa+a9j6ABjOaaxaI22Bb7j3OJ+JyMICs6CU2bgkJaj3VUV9FCNUOc
h9PxD4jzT9yyGYm/sK9BAT1WOTPG8XQUkpcFqy/IerZDfiQkf1koiSd4s5VhBkUn
aQHOdri/stldT7a+HJFVyz2AXDGPDj+UBMOuLq0K6GAT6ThpkXCb2RIf4mdTy7ox
N5BaJ+ih+Ro3ZwPkok60egnt/RN98jgbm+WstgjJWuLqSNInnMUgkuqjyBWwePqX
Kib+wdpyx/LOzhKPEFpeMIvHQ3A0sjlulIjnh+j+itezD+dp0UNxMERlW4Bn/IlS
sYQVNfYutWkRPRLErXOZXtlxxkI98JWQtLjvGzQr+jywxTiw644FSLWdhKa6DtfU
2JWBHqQPJicMElfZpmfaHZjtXuCZNdZQXWg7onZYohe281ZrdFPOqC4rUq7gYamL
T+ZB+2P+YCPOLJ60bj/XSvcB7mesAdg8P0DNddPhHUFWx2dFqOs1HxIVB4FZVA9U
Ppbv4a484yxjTgG7zFZNqXHKTqze6rBBAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMB
Af8wHQYDVR0OBBYEFCEAqjighncv/UnWzBjqu1Ka2Yb4MA4GA1UdDwEB/wQEAwIB
hjANBgkqhkiG9w0BAQwFAAOCAgEAYyvumblckIXlohzi3QiShkZhqFzZultbFIu9
GhA5CDar1IFMhJ9vJpO9nUK/camKs1VQRs8ZsBbXa0GFUM2p8y2cgUfLwFULAiC/
sWETyW5lcX/xc4Pyf6dONhqFJt/ovVBxNZtcmMEWv/1D6Tf0nLeEb0P2i/pnSRR4
Oq99LVFjossXtyvtaq06OSiUUZ1zLPvV6AQINg8dWeBOWRcQYhYcEcC2wQ06KShZ
0ahuu7ar5Gym3vuLK6nH+eQrkUievVomN/LpASrYhK32joQ5ypIJej3sICIgJUEP
UoeswJ+Z16f3ECoL1OSnq4A0riiLj1ZGmVHNhM6m/gotKaHNMxsK9zsbqmuU6IT/
P6cR0S+vdigQG8ZNFf5vEyVNXhl8KcaJn6lMD/gMB2rY0qpaeTg4gPfU5wcg8S4Y
C9V//tw3hv0f2n+8kGNmqZrylOQDQWSSo8j8M2SRSXiwOHDoTASd1fyBEIqBAwzn
LvXVg8wQd1WlmM3b0Vrsbzltyh6y4SuKSkmgufYYvC07NknQO5vqvZcNoYbLNea3
76NkFaMHUekSbwVejZgG5HGwbaYBgNdJEdpbWlA3X4yGRVxknQSUyt4dZRnw/HrX
k8x6/wvtw7wht0/DOqz1li7baSsMazqxx+jDdSr1h9xML416Q4loFCLgqQhil8Jq
Em4Hy3A=
-----END CERTIFICATE-----

Binary file not shown.

View File

@ -1,5 +1,5 @@
Rule Name,Policy Business Type,Policy Name,Premium Type,Vehicle Type,Vehicle Sub Type,Make,Model,CC Min,CC Max,Fuel Type,Vehicle Age Min,Vehicle Age Max,Vehicle Weight Min,Vehicle Weight Max,RTO State,RTO City,Renewal Type,Renewal Sub Type,Commission Type,Commission Value,Commission Params(TP:OD:PA),Notes
Motor sample 1,Retail,,,Two Wheeler,,,,100,100,,,,,,,,,,composite,,10:25:0,"id: rule_68bc096e6d7df; conditions: vehicle_type == Two Wheeler; cubic_capcity == 100; calculation: composite 10% on tp_premium, 25% on od_premium"
Motor sample 2,Retail,,,Four Wheeler,,,,1000,1000,,5,5,,,,,,,percentage,10,,id: rule_68fb5ad42f3c4; conditions: vehicle_type == Four Wheeler; cubic_capcity >= 1000; vehicle_age <= 5; calculation: 10% on premium
Sample 2,Retail,,TP,Four Wheeler,,,,1000,1000,,,,,,,,,,composite,,10:0:0,id: rule_691438a7cb08b; conditions: vehicle_type == Four Wheeler; policy_type == TP; is_new_vehicle == true; cubic_capcity > 1000; calculation: composite 10% on tp_premium
Sample 2 test,Retail,,,"Two Wheeler,Four Wheeler",,,,2500,2500,,,,,,,,,,flat,500,,"id: rule_6916ad2837807; conditions: vehicle_type in [Two Wheeler, Four Wheeler]; cubic_capcity == 2500; calculation: fixed 500 on premium"
S.No,Premium Type,Vehicle Type,Vehicle Sub Type,Make,Model,CC Min,CC Max,Fuel Type,Vehicle Age Min,Vehicle Age Max,Vehicle Weight Min,Vehicle Weight Max,RTO State,RTO Code,Renewal Type,Commission Type,Commission Value,Commission Params (TP),Commission Params (OD),Commission Params (PA)
1,OD,Car,Honda i10,Honda,2014,1000,3000,Petrol,5,10,2000,3000,RJ,41,Online,percentage,15,,,
2,TP,Two Wheeler,Passion Pro,Hero,2019,100,150,Petrol,1,5,100,150,RJ,57,Cash,composite,,18,10,
3,COM,PCV,Toyota,Toyota,2020,2000,8000,Diesel,5,20,3000,5000,GJ,33,Card,percentage,25,,,
4,COM,GCV,Tata,Tata,2023,2000,8000,Diesel,5,20,5000,10000,PB,19,Cash,composite,,,10,

1 Rule Name S.No Policy Business Type Premium Type Policy Name Vehicle Type Vehicle Sub Type Make Model CC Min CC Max Fuel Type Vehicle Age Min Vehicle Age Max Vehicle Weight Min Vehicle Weight Max RTO State RTO Code Renewal Type RTO City Commission Type Commission Value Renewal Sub Type Commission Params (TP) Commission Params (OD) Commission Params (PA) Commission Params(TP:OD:PA) Notes
2 Motor sample 1 1 Retail OD Two Wheeler Car Honda i10 Honda 2014 100 1000 100 3000 Petrol 5 10 2000 3000 RJ 41 Online composite percentage 15 10:25:0 id: rule_68bc096e6d7df; conditions: vehicle_type == Two Wheeler; cubic_capcity == 100; calculation: composite 10% on tp_premium, 25% on od_premium
3 Motor sample 2 2 Retail TP Four Wheeler Two Wheeler Passion Pro Hero 2019 1000 100 1000 150 Petrol 5 1 5 100 150 RJ 57 Cash percentage composite 10 18 10 id: rule_68fb5ad42f3c4; conditions: vehicle_type == Four Wheeler; cubic_capcity >= 1000; vehicle_age <= 5; calculation: 10% on premium
4 Sample 2 3 Retail TP COM Four Wheeler PCV Toyota Toyota 2020 1000 2000 1000 8000 Diesel 5 20 3000 5000 GJ 33 Card composite percentage 25 10:0:0 id: rule_691438a7cb08b; conditions: vehicle_type == Four Wheeler; policy_type == TP; is_new_vehicle == true; cubic_capcity > 1000; calculation: composite 10% on tp_premium
5 Sample 2 test 4 Retail COM Two Wheeler,Four Wheeler GCV Tata Tata 2023 2500 2000 2500 8000 Diesel 5 20 5000 10000 PB 19 Cash flat composite 500 10 id: rule_6916ad2837807; conditions: vehicle_type in [Two Wheeler, Four Wheeler]; cubic_capcity == 2500; calculation: fixed 500 on premium

View File

@ -0,0 +1,5 @@
Rule Name,Policy Business Type,Policy Name,Premium Type,Vehicle Type,Vehicle Sub Type,Make,Model,CC Min,CC Max,Fuel Type,Vehicle Age Min,Vehicle Age Max,Vehicle Weight Min,Vehicle Weight Max,RTO State,RTO City,Renewal Type,Renewal Sub Type,Commission Type,Commission Value,Commission Params(TP:OD:PA),Notes
Motor sample 1,Retail,,,Two Wheeler,,,,100,100,,,,,,,,,,composite,,10:25:0,"id: rule_68bc096e6d7df; conditions: vehicle_type == Two Wheeler; cubic_capcity == 100; calculation: composite 10% on tp_premium, 25% on od_premium"
Motor sample 2,Retail,,,Four Wheeler,,,,1000,1000,,5,5,,,,,,,percentage,10,,id: rule_68fb5ad42f3c4; conditions: vehicle_type == Four Wheeler; cubic_capcity >= 1000; vehicle_age <= 5; calculation: 10% on premium
Sample 2,Retail,,TP,Four Wheeler,,,,1000,1000,,,,,,,,,,composite,,10:0:0,id: rule_691438a7cb08b; conditions: vehicle_type == Four Wheeler; policy_type == TP; is_new_vehicle == true; cubic_capcity > 1000; calculation: composite 10% on tp_premium
Sample 2 test,Retail,,,"Two Wheeler,Four Wheeler",,,,2500,2500,,,,,,,,,,flat,500,,"id: rule_6916ad2837807; conditions: vehicle_type in [Two Wheeler, Four Wheeler]; cubic_capcity == 2500; calculation: fixed 500 on premium"
1 Rule Name Policy Business Type Policy Name Premium Type Vehicle Type Vehicle Sub Type Make Model CC Min CC Max Fuel Type Vehicle Age Min Vehicle Age Max Vehicle Weight Min Vehicle Weight Max RTO State RTO City Renewal Type Renewal Sub Type Commission Type Commission Value Commission Params(TP:OD:PA) Notes
2 Motor sample 1 Retail Two Wheeler 100 100 composite 10:25:0 id: rule_68bc096e6d7df; conditions: vehicle_type == Two Wheeler; cubic_capcity == 100; calculation: composite 10% on tp_premium, 25% on od_premium
3 Motor sample 2 Retail Four Wheeler 1000 1000 5 5 percentage 10 id: rule_68fb5ad42f3c4; conditions: vehicle_type == Four Wheeler; cubic_capcity >= 1000; vehicle_age <= 5; calculation: 10% on premium
4 Sample 2 Retail TP Four Wheeler 1000 1000 composite 10:0:0 id: rule_691438a7cb08b; conditions: vehicle_type == Four Wheeler; policy_type == TP; is_new_vehicle == true; cubic_capcity > 1000; calculation: composite 10% on tp_premium
5 Sample 2 test Retail Two Wheeler,Four Wheeler 2500 2500 flat 500 id: rule_6916ad2837807; conditions: vehicle_type in [Two Wheeler, Four Wheeler]; cubic_capcity == 2500; calculation: fixed 500 on premium