MERGE_LIVE_SQL_INJECTION_COMPLETED

This commit is contained in:
Ubuntu 2026-02-12 14:08:51 +05:30
commit 3c94f96443
211 changed files with 22943 additions and 3511 deletions

View File

@ -33,11 +33,11 @@ database.default.DBDriver =
# session.driver = 'CodeIgniter\Session\Handlers\FileHandler' # session.driver = 'CodeIgniter\Session\Handlers\FileHandler'
# session.cookieName = 'ci_session' # session.cookieName = 'ci_session'
#session.expiration = 28800 session.expiration =
# session.savePath = null # session.savePath = null
# session.matchIP = false # session.matchIP = false
# session.timeToUpdate = 300 session.timeToUpdate = 300
# session.regenerateDestroy = false session.regenerateDestroy = false
#-------------------------------------------------------------------- #--------------------------------------------------------------------
# LOGGER # LOGGER
@ -81,16 +81,6 @@ cookie.secure = 'true';// if https set as true or if http set as false
unlayer.projectID = unlayer.projectID =
email.enquiryMail = email.enquiryMail =
database.postDB.hostname =
database.postDB.database =
database.postDB.username =
database.postDB.password =
database.postDB.DBDriver =
database.postDB.DBPrefix =
database.postDB.port =
POST_ENROLLMENT_BASEURL =
#SMS #SMS
SMS_API_KEY = SMS_API_KEY =
SMS_SENDER_ID = SMS_SENDER_ID =
@ -108,3 +98,26 @@ CORS_MAX_AGE=7200
CORS_DEBUG=true CORS_DEBUG=true
APP_SIGNATURE = APP_SIGNATURE =
TOKENTIMEOUT =
JWT_SECRET =
ICICI_PRIMARY_KEY_CONSTANT =
ABHI_PRIMARY_KEY_CONSTANT =
R_CARE_PRIMARY_KEY_CONSTANT =
FHPL_PRIMARY_KEY_CONSTANT =
VIDAL_PRIMARY_KEY_CONSTANT =
MEDI_ASSIST_PRIMARY_KEY_CONSTANT =
FHPL_TOKEN_URL =
FHPL_BASE_URL =
FHPL_USER_NAME =
FHPL_PASSWORD =
FHPL_GRANT_TYPE =
METABASE_SECRET_KEY=

170
app/Config/Acl.php Normal file
View File

@ -0,0 +1,170 @@
<?php
namespace Config;
class Acl
{
public array $rules = [
// ===================== PUBLIC / AUTH =====================
'#^/login#' => ['public' => true],
'#^/downloadCdSplitUpFile#' => ['public' => true],
'#^/logout#' => ['public' => true],
'#^/auth#' => ['public' => true],
'#^/oauth2callback#' => ['public' => true],
'#^/loginPos#' => ['public' => true],
'#^/getVerifyPosMobileNo#' => ['public' => true],
'#^/getVerifiedPosUserData#' => ['public' => true],
'#^/swagger#' => ['roles' => [ADMIN_ROLE_ID]],
'#^/fedeploy#' => ['roles' => [ADMIN_ROLE_ID]],
'#^/visitOffBoardCheck#' => ['roles' => [ADMIN_ROLE_ID]],
'#^/logs#' => ['roles' => [ADMIN_ROLE_ID]],
'#^/util/log_list#' => ['roles' => [ADMIN_ROLE_ID]],
'#^/util/view_log#' => ['roles' => [ADMIN_ROLE_ID]],
'#^/util/download_log#' => ['roles' => [ADMIN_ROLE_ID]],
'#^/metaDashboardDemo#' => ['roles' => [ADMIN_ROLE_ID, HEAD_ROLE_ID]],
// ===================== PUBLIC DOWNLOADS / FORMS =====================
'#^/download-#' => ['public' => true],
'#^/claim-form-download#' => ['public' => true],
'#^/claims-feedback-form#' => ['public' => true],
'#^/autobookstackLogin#' => ['public' => true],
// ===================== DASHBOARD =====================
'#^/dashboard#' => [
'roles' => [ ADMIN_ROLE_ID,HEAD_ROLE_ID, MANAGER_ROLE_ID, STAFF_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => []
],
// ===================== VIEW INCEPTION PAGE =====================
'#^/hrFileList#' => [
'roles' => [ ADMIN_ROLE_ID,HEAD_ROLE_ID, MANAGER_ROLE_ID, STAFF_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => []
],
// ===================== USER MANAGEMENT =====================
'#^/user#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID],
'teams' => []
],
// ===================== CLIENT =====================
'#^/client#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => []
],
// ===================== EMPLOYEE / ENROLLMENT =====================
'#^/employee#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => [ENROLLMENT_TEAM_ID]
],
// ===================== MASTERS =====================
'#^/master#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => []
],
'#^/util#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID,STAFF_ROLE_ID],
'teams' => []
],
// ===================== POLICY TRANSACTION / BDS =====================
'#^/policy_tranction#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => [FINANCE_TEAM_ID,POS_TEAM_ID]
],
'#^/bds_upload#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => [FINANCE_TEAM_ID,POS_TEAM_ID]
],
// ===================== REPORTS =====================
'#^/bdsReport#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => [FINANCE_TEAM_ID,POS_TEAM_ID]
],
// ===================== PAYOUT / COMMISSION =====================
'#^/payout#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => [FINANCE_TEAM_ID,POS_TEAM_ID]
],
'#^/commission#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => [FINANCE_TEAM_ID,POS_TEAM_ID]
],
// ===================== CLAIMS / TICKETS =====================
'#^/ticket#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => [CLAIMS_TEAM_ID]
],
'#^/claim_mis#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => [CLAIMS_TEAM_ID]
],
// ===================== LEADS / SALES =====================
'#^/leads#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => [BUSINESS_SUPPORT_TEAM_ID, SALES_TEAM_ID]
],
'#^/rfq#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => [SALES_TEAM_ID]
],
'#^/sales#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID],
'teams' => [SALES_TEAM_ID]
],
// ===================== CMS / CONTENT =====================
'#^/add_image_index#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID,STAFF_ROLE_ID],
'teams' => []
],
'#^/frontend_content#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID,STAFF_ROLE_ID],
'teams' => []
],
'#^/FAQ#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID,STAFF_ROLE_ID],
'teams' => []
],
// ===================== LOGS =====================
'#^/logs#' => [
'roles' => [ADMIN_ROLE_ID],
'teams' => []
],
// ===================== INTERNAL TEST =====================
'#^/test#' => [
'roles' => [ADMIN_ROLE_ID],
'teams' => []
],
// ===================== API (JWT / SIGNED) =====================
'#^/api#' => ['public' => true],
'#^/employeeRest#' => ['public' => true],
'#^/clientApi#' => ['public' => true],
// ===================== WEBHOOKS / 3RD PARTY =====================
'#^/dispatchWebhookData#' => ['public' => true],
'#^/retrieveWebhookData#' => ['public' => true],
// '#^/ICICI#' => ['public' => true],
// '#^/Vidal#' => ['public' => true],
// '#^/MediAssist#' => ['public' => true],
// ===================== CLI =====================
'#^/cli/#' => ['public' => true],
// ===================== DEFAULT DENY (ZERO TRUST) =====================
'#^/#' => [
'roles' => [ADMIN_ROLE_ID],
'teams' => []
],
];
}

View File

@ -101,6 +101,6 @@ class Autoload extends AutoloadConfig
* @phpstan-var list<string> * @phpstan-var list<string>
*/ */
public $helpers = ['uuid','session','utility', 'form', 'url', 'oauth', 'fileupload', public $helpers = ['uuid','session','utility', 'form', 'url', 'oauth', 'fileupload',
'excel_import_export', 'file', 'drive','ExcelSanitizeHelper', 'api_helper','exception','sms_helper' 'excel_import_export', 'file', 'drive','ExcelSanitizeHelper', 'api_helper','exception','sms_helper','sanitizeInputArrayAdvanced'
]; ];
} }

View File

@ -16,6 +16,10 @@ use App\Filters\AuthClientApi;
use App\Filters\CommissionApiFilter; use App\Filters\CommissionApiFilter;
use App\Filters\VerifyAppSignature; use App\Filters\VerifyAppSignature;
use App\Filters\Cors; use App\Filters\Cors;
use App\Filters\SecurityInputFilter;
use App\Filters\GlobalPostFileUploadGuard;
use App\Filters\AclFilter;
use App\Filters\RateLimitFilter;
use App\Filters\AuthJWT; use App\Filters\AuthJWT;
@ -43,6 +47,11 @@ class Filters extends BaseConfig
'CommissionApiFilter'=> CommissionApiFilter::class, 'CommissionApiFilter'=> CommissionApiFilter::class,
'appSignature' => VerifyAppSignature::class, 'appSignature' => VerifyAppSignature::class,
'Cors' => Cors::class, 'Cors' => Cors::class,
'SecurityInputFilter' => SecurityInputFilter::class,
'GlobalPostFileUploadGuard' => GlobalPostFileUploadGuard::class,
'AclFilter' => AclFilter::class,
'ratelimit' => RateLimitFilter::class,
]; ];
/** /**
@ -56,6 +65,9 @@ class Filters extends BaseConfig
'before' => [ 'before' => [
'HttpRequestLog' => ['except' => 'cli/*'], 'HttpRequestLog' => ['except' => 'cli/*'],
'Cors', 'Cors',
'AclFilter' => ['except' => ['login', 'logout', 'auth/*', 'oauth2callback','claim-form-download', 'claims-feedback-form', 'autobookstackLogin','employeeRest/*','processjob','getCommission']],
'SecurityInputFilter' => ['except' => ['/client/notification/create','/ticket/crud_mail_template/*','test_mail','leads/sendMail'] ],
'GlobalPostFileUploadGuard'
// 'csrf', // 'csrf',
// 'invalidchars', // 'invalidchars',
], ],
@ -86,5 +98,5 @@ class Filters extends BaseConfig
* Example: * Example:
* 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']] * 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']]
*/ */
public array $filters = []; // public array $filters = [ 'Cors' => ['before' => ['employeeRest/*']]];
} }

View File

@ -21,6 +21,8 @@ $routes->get('/chatbot', 'ChatbotControllerNew::chatbot');
$routes->get('/swagger', 'SwaggerController::index', ['filter' => 'authMVC']); $routes->get('/swagger', 'SwaggerController::index', ['filter' => 'authMVC']);
$routes->get('/fedeploy', 'DeployController::fedeploy_view', ['filter' => 'authMVC']); $routes->get('/fedeploy', 'DeployController::fedeploy_view', ['filter' => 'authMVC']);
$routes->post('/fedeploy', 'DeployController::fedeploy', ['filter' => 'authMVC']); $routes->post('/fedeploy', 'DeployController::fedeploy', ['filter' => 'authMVC']);
$routes->get('/visitOffBoardCheck', 'EmployeeController::visitOffBoardCheck');
$routes->get('/metaDashboardDemo', 'TestingController::metaDashboardDemo');
// Reminder Mail Notification // Reminder Mail Notification
@ -35,7 +37,6 @@ $routes->get("view", "EmployeeController::viewECard/$1");
$routes->get("checkWellnessOnboardStatus/(:any)", "EmployeeController::checkWellnessOnboardStatus/$1"); $routes->get("checkWellnessOnboardStatus/(:any)", "EmployeeController::checkWellnessOnboardStatus/$1");
$routes->get("initiateWellnessOnboard/(:any)", "EmployeeController::initiateWellnessOnboard/$1"); $routes->get("initiateWellnessOnboard/(:any)", "EmployeeController::initiateWellnessOnboard/$1");
$routes->get("exportQCRandRFQ/(:any)", "LeadsController::exportQCRandRFQ/$1"); $routes->get("exportQCRandRFQ/(:any)", "LeadsController::exportQCRandRFQ/$1");
$routes->get("smapletest", "ClientController::smapletest");
$routes->get("testMailAttachments", "ClientController::testMailAttachments"); $routes->get("testMailAttachments", "ClientController::testMailAttachments");
$routes->get("updatePolicyTermsKey", "ClientController::updatePolicyTermsKey"); $routes->get("updatePolicyTermsKey", "ClientController::updatePolicyTermsKey");
$routes->get("updateRemainderDate", "ClientController::updateRemainderDate"); $routes->get("updateRemainderDate", "ClientController::updateRemainderDate");
@ -215,6 +216,9 @@ $routes->group("/employee", ["filter" => "authMVC"], function ($routes) {
$routes->post("retail-endorsement-save", "EmployeeController::retailendorsementsave"); $routes->post("retail-endorsement-save", "EmployeeController::retailendorsementsave");
$routes->get("getTPADataVariationReport/(:num)", "EmployeeController::getTPADataVariationReport/$1"); $routes->get("getTPADataVariationReport/(:num)", "EmployeeController::getTPADataVariationReport/$1");
$routes->get("bulkGenerateEcardAndStoreinS3", "EmployeeController::bulkGenerateEcardAndStoreinS3"); $routes->get("bulkGenerateEcardAndStoreinS3", "EmployeeController::bulkGenerateEcardAndStoreinS3");
$routes->get('clearCdSession', 'EmployeeController::clearCdSession');
$routes->get('checkSessionStatus', 'EmployeeController::checkSessionStatus');
}); });
@ -427,6 +431,8 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) {
$routes->get('checkDuplicateCdAccount', 'MasterController::checkDuplicateCdAccount'); $routes->get('checkDuplicateCdAccount', 'MasterController::checkDuplicateCdAccount');
$routes->get('proceedExcelFileDataValidation', 'EmployeeController::proceedExcelFileDataValidation'); $routes->get('proceedExcelFileDataValidation', 'EmployeeController::proceedExcelFileDataValidation');
$routes->get('checkTpaApiEnable', 'EmployeeRestController::checkTpaApiEnable'); $routes->get('checkTpaApiEnable', 'EmployeeRestController::checkTpaApiEnable');
$routes->get('generateDemographyDataTable', 'LeadsController::generateDemographyDataTable');
$routes->post('insufficientCdBalanceHrMailSend', 'EmployeeController::insufficientCdBalanceHrMailSend');
}); });
$routes->post("policy_tranction/sendInstallmentRemainderMail","PolicyTransactionController::sendInstallmentRemainderMail"); $routes->post("policy_tranction/sendInstallmentRemainderMail","PolicyTransactionController::sendInstallmentRemainderMail");
@ -525,7 +531,6 @@ $routes->cli('cli/check_env', 'MasterController::checkEnv');
$routes->cli('cli/enrollOpendAndClose', 'DashboardController::updatePolicyEnrollmentStatus'); $routes->cli('cli/enrollOpendAndClose', 'DashboardController::updatePolicyEnrollmentStatus');
$routes->cli("cli/sendCroneRemainderMail", "DashboardController::sendCroneRemainderMail"); $routes->cli("cli/sendCroneRemainderMail", "DashboardController::sendCroneRemainderMail");
$routes->cli('cli/update-emp-policy-status', 'ClientController::updateEmpAndPolicyStatus'); $routes->cli('cli/update-emp-policy-status', 'ClientController::updateEmpAndPolicyStatus');
$routes->cli('cli/update-emp-policy-status', 'ClientController::updateEmpAndPolicyStatus');
$routes->cli('cli/insurerRFQRemainder', 'LeadsController::remainderForQcr'); $routes->cli('cli/insurerRFQRemainder', 'LeadsController::remainderForQcr');
$routes->cli('cli/sendMailWithAutoQuery','TicketController::sendMailWithAutoQuery'); $routes->cli('cli/sendMailWithAutoQuery','TicketController::sendMailWithAutoQuery');
$routes->cli('cli/MediAssit-ClaimStatusUpdate','MediAssistApiController::ClaimStatusUpdate'); $routes->cli('cli/MediAssit-ClaimStatusUpdate','MediAssistApiController::ClaimStatusUpdate');
@ -544,7 +549,7 @@ $routes->get('get_ticket_data',"EmployeeRestController::get_ticket_data");
//api //api
$routes->group("/api", ["filter" => "authJWT"], function ($routes) { $routes->group("/api", ["filter" => [ 'ratelimit' , 'authJWT']], function ($routes) {
$routes->get('get_ticket_type',"EmployeeRestController::get_ticket_type"); $routes->get('get_ticket_type',"EmployeeRestController::get_ticket_type");
$routes->post("logined", "RestAuthenticationController::logined"); $routes->post("logined", "RestAuthenticationController::logined");
$routes->post("getId", "RestAuthenticationController::getUserIdFromToken"); $routes->post("getId", "RestAuthenticationController::getUserIdFromToken");
@ -554,8 +559,12 @@ $routes->group("/api", ["filter" => "authJWT"], function ($routes) {
$routes->get("getSSORedirectUrl", "ApiServiceController::getSSORedirectUrl"); $routes->get("getSSORedirectUrl", "ApiServiceController::getSSORedirectUrl");
$routes->get("getEmployeePolicy", "EmployeeRestController::getEmployeePolicy"); $routes->get("getEmployeePolicy", "EmployeeRestController::getEmployeePolicy");
$routes->get("downloadCdSplitUpFile", "EmployeeRestController::downloadCdSplitUpFile");
$routes->get("downloadFileTableFile/(:any)", "EmployeeController::downloadFileList/$1");
$routes->group("employeeRest", ['filter' => ['appSignature'] ], function ($routes) {
$routes->group("employeeRest", ['filter' => ['ratelimit' , 'appSignature'] ], function ($routes) {
//Employee login api's //Employee login api's
$routes->post("verifyEmployeeNumber", "RestAuthenticationController::verifyEmployeeWithMobileNumber"); $routes->post("verifyEmployeeNumber", "RestAuthenticationController::verifyEmployeeWithMobileNumber");
@ -598,7 +607,9 @@ $routes->group("employeeRest", ['filter' => ['appSignature'] ], function ($route
}); });
$routes->group("employeeRest", ["filter" => ['appSignature' , 'authJWT']], function ($routes) { $routes->group("employeeRest", ["filter" => ['GlobalPostFileUploadGuard', 'ratelimit' , 'appSignature', 'authJWT']], function ($routes) {
$routes->post('logout', 'RestAuthenticationController::logout');
$routes->post("ecardRequest", "ApiServiceController::ecardRequest"); $routes->post("ecardRequest", "ApiServiceController::ecardRequest");
$routes->get("getWellnessURL", "ApiServiceController::getWellnessURL"); $routes->get("getWellnessURL", "ApiServiceController::getWellnessURL");
@ -648,6 +659,7 @@ $routes->group("employeeRest", ["filter" => ['appSignature' , 'authJWT']], funct
$routes->get("hrFileDownload", "EmployeeRestController::hrFileDownload"); $routes->get("hrFileDownload", "EmployeeRestController::hrFileDownload");
$routes->post("hrFileUpload", "EmployeeRestController::hrFileUpload"); $routes->post("hrFileUpload", "EmployeeRestController::hrFileUpload");
$routes->post("updateHrFileUploadData", "EmployeeRestController::updateHrFileUploadData"); $routes->post("updateHrFileUploadData", "EmployeeRestController::updateHrFileUploadData");
$routes->post("getHrDashboad", "EmployeeRestController::getHrDashboad");
//thz_master's //thz_master's
@ -659,7 +671,7 @@ $routes->group("employeeRest", ["filter" => ['appSignature' , 'authJWT']], funct
$routes->match(['get','post','put'], 'ticketType', 'ThzController::ticketType'); $routes->match(['get','post','put'], 'ticketType', 'ThzController::ticketType');
//this route for nhance website contact form (sales/service) //this route for nhance website contact form (sales/service)
$routes->group("employeeRest", ['filter' => ['appSignature'] ], function ($routes) { $routes->group("employeeRest", ['filter' => ['ratelimit' , 'appSignature'] ], function ($routes) {
$routes->post("ticketSave", "ThzController::ticketSave"); $routes->post("ticketSave", "ThzController::ticketSave");
}); });
@ -678,7 +690,10 @@ $routes->group("employeeRest", ["filter" => ['appSignature' , 'authJWT']], funct
// get insurer and policy type // get insurer and policy type
$routes->get("getPolicyTypeAndInsurer", "EmployeeRestController::getPolicyTypeAndInsurer"); $routes->get("getPolicyTypeAndInsurer", "EmployeeRestController::getPolicyTypeAndInsurer");
$routes->get("getExcelFileErrors/(:any)", "EmployeeController::getExcelFileErrors/$1");
$routes->get("getPolicyAndEndorsementFiles", "EmployeeRestController::getPolicyAndEndorsementFiles");
$routes->get("downloadPolicyFiles", "EmployeeRestController::downloadPolicyFiles");
$routes->post("bulkEcardDownloadAsZip", "EmployeeRestController::bulkEcardDownloadAsZip");
}); });
$routes->get("hrFileDownload", "EmployeeRestController::hrFileDownload"); $routes->get("hrFileDownload", "EmployeeRestController::hrFileDownload");
@ -736,6 +751,12 @@ $routes->group("/ticket", ["filter" => "authMVC"], function ($routes) {
$routes->get('getTpaClaimStatus',"ApiServiceController::getClaimStatus"); $routes->get('getTpaClaimStatus',"ApiServiceController::getClaimStatus");
}); });
$routes->group("/claim_mis", ["filter" => "authMVC"], function ($routes) {
$routes->get('list','TicketController::claimMisFileList');
$routes->get('download','TicketController::downloadClaimMisFile');
$routes->post('upload','TicketController::uploadClaimMisFile');
});
$routes->group("clientApi",["filter" => "AuthClientApi"], function ($routes){ $routes->group("clientApi",["filter" => "AuthClientApi"], function ($routes){
$routes->post("getPolicyMaster","ClientAPIController::sendPolicyMaster"); $routes->post("getPolicyMaster","ClientAPIController::sendPolicyMaster");
@ -753,7 +774,6 @@ $routes->post("retrieveWebhookDataClaim","ClientWebHooksController::pullData_cla
//Third party ICICILombard Api Call //Third party ICICILombard Api Call
$routes->get('generateAuthToken','ICICILombardController::generateAuthToken'); $routes->get('generateAuthToken','ICICILombardController::generateAuthToken');
$routes->get('createEnrollmentBatch','ICICILombardController::createEnrollmentBatch'); $routes->get('createEnrollmentBatch','ICICILombardController::createEnrollmentBatch');
$routes->get('getEnrollmentBatchStatus','ICICILombardController::getEnrollmentBatchStatus'); $routes->get('getEnrollmentBatchStatus','ICICILombardController::getEnrollmentBatchStatus');
@ -762,16 +782,17 @@ $routes->get('fetchUHIDDetails','ICICILombardController::fetchUHIDDetails');
//Third party - testing route //Third party - testing route
$routes->get('FhplGetBenefDetails','FhplApiController::FhplGetBenefDetails');
$routes->get('EcardRequest','VidalApiController::EcardRequest'); $routes->get('EcardRequest','FhplApiController::EcardRequest');
$routes->get('HospitalNetwork','MediAssistApiController::HospitalNetwork'); $routes->get('HospitalNetwork','MediAssistApiController::HospitalNetwork');
$routes->get('VidalGetBenefDetails','VidalApiController::VidalGetBenefDetails'); $routes->get('VidalGetBenefDetails','VidalApiController::VidalGetBenefDetails');
$routes->get('ClaimDetail','VidalApiController::ClaimDetail'); $routes->get('ClaimDetail','FhplApiController::ClaimDetail');
$routes->get('SubmitClaim','MediAssistApiController::SubmitClaim'); $routes->get('SubmitClaim','HealthIndiaApiController::SubmitClaim');
$routes->get('IntimateClaim','MediAssistApiController::IntimateClaim'); $routes->get('IntimateClaim','MediAssistApiController::IntimateClaim');
$routes->get('IRSubmission','MediAssistApiController::IRSubmission'); $routes->get('IRSubmission','MediAssistApiController::IRSubmission');
$routes->get('ClaimStatusUpdate','MediAssistApiController::ClaimStatusUpdate'); $routes->get('ClaimStatusUpdate','MediAssistApiController::ClaimStatusUpdate');
$routes->get('syncTpaClaimToNhance','MediAssistApiController::syncTpaClaimToNhance'); $routes->get('syncTpaClaimToNhance','MediAssistApiController::syncTpaClaimToNhance');
$routes->get('HealthIndiaGetBenefDetails','HealthIndiaApiController::HealthIndiaGetBenefDetails');
// API service (Don't delete) // API service (Don't delete)

View File

@ -12,6 +12,7 @@ use App\Controllers\BaseController;
use App\Controllers\VidalApiController; use App\Controllers\VidalApiController;
use App\Controllers\ICICILombardController; use App\Controllers\ICICILombardController;
use App\Controllers\MediAssistApiController; use App\Controllers\MediAssistApiController;
use App\Controllers\FhplApiController;
use App\Models\BatchFileModel; use App\Models\BatchFileModel;
use App\Models\FileModel; use App\Models\FileModel;
use App\Helpers\TPADataCompareHelper; use App\Helpers\TPADataCompareHelper;
@ -26,6 +27,8 @@ class ApiServiceController extends BaseController
protected $medi_assist_primary_key; protected $medi_assist_primary_key;
protected $vidal_primary_key; protected $vidal_primary_key;
protected $icici_primary_key; protected $icici_primary_key;
protected $fhpl_primary_key;
protected $health_india_primary_key;
public function __construct() public function __construct()
{ {
@ -34,6 +37,8 @@ class ApiServiceController extends BaseController
$this->medi_assist_primary_key = getenv('MEDI_ASSIST_PRIMARY_KEY_CONSTANT'); $this->medi_assist_primary_key = getenv('MEDI_ASSIST_PRIMARY_KEY_CONSTANT');
$this->vidal_primary_key = getenv('VIDAL_PRIMARY_KEY_CONSTANT'); $this->vidal_primary_key = getenv('VIDAL_PRIMARY_KEY_CONSTANT');
$this->icici_primary_key = getenv('ICICI_PRIMARY_KEY_CONSTANT'); $this->icici_primary_key = getenv('ICICI_PRIMARY_KEY_CONSTANT');
$this->fhpl_primary_key = getenv('FHPL_PRIMARY_KEY_CONSTANT');
$this->health_india_primary_key = getenv('HEALTH_INDIA_PRIMARY_KEY_CONSTANT');
} }
// Push Claims // Push Claims
@ -55,6 +60,10 @@ class ApiServiceController extends BaseController
{ // Vidal { // Vidal
$vidalApiController = new VidalApiController; $vidalApiController = new VidalApiController;
return $vidalApiController->SubmitClaim($claimId); return $vidalApiController->SubmitClaim($claimId);
}else if ($tpaID == $this->fhpl_primary_key)
{ // fhpl
$fhplApiController = new FhplApiController;
return $fhplApiController->SubmitClaim($claimId);
}else{ }else{
log_message('error', "This ticket id ( {$claimId} ) TPA has no API service enabled. TPA ID : {$tpaID}"); log_message('error', "This ticket id ( {$claimId} ) TPA has no API service enabled. TPA ID : {$tpaID}");
} }
@ -106,10 +115,11 @@ class ApiServiceController extends BaseController
->join('client_policy', 'employee_polices.client_policy_id = client_policy.id', 'left') ->join('client_policy', 'employee_polices.client_policy_id = client_policy.id', 'left')
->where('employees.emp_code', $emp_code) ->where('employees.emp_code', $emp_code)
->where('employee_polices.client_policy_id', $client_policy_id) ->where('employee_polices.client_policy_id', $client_policy_id)
->where('employees.id', $id)
->where('employee_polices.is_active', 1) ->where('employee_polices.is_active', 1)
->where('employees.is_active', 1) ->where('employees.is_active', 1)
->where('employee_polices.status', 'active') ->whereIn('employee_polices.status', ['active', 'expired'])
->where('employees.emp_status', 'active') ->whereIn('employees.emp_status', ['active', 'expired'])
->findAll(); ->findAll();
@ -129,6 +139,12 @@ class ApiServiceController extends BaseController
$vidalApiController = new VidalApiController; $vidalApiController = new VidalApiController;
$data['eCardDownload'] = $vidalApiController->EcardRequest( $emp_code, $policy_no , $employee_policy[0]['tpa_id'] ); $data['eCardDownload'] = $vidalApiController->EcardRequest( $emp_code, $policy_no , $employee_policy[0]['tpa_id'] );
}else if($employee_policy[0]['tpa_primary_id'] == $this->fhpl_primary_key)// Fhpl
{
$fhplApiController = new FhplApiController;
$data['eCardDownload'] = $fhplApiController->EcardRequest( $emp_code, $policy_no , $employee_policy[0]['tpa_id'] );
}else{ }else{
if($type == "download"){ if($type == "download"){
@ -265,6 +281,17 @@ class ApiServiceController extends BaseController
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Action Triggered','data' => [] ]); return $this->respond(['status' => true, 'code' => 200, 'message' => 'Action Triggered','data' => [] ]);
}else if ($tpa_id == $this->fhpl_primary_key) // Fhpl
{
$file_id = $fileModel->insert($data);
log_message('error', "Files table inserted successfully, File id : {$file_id}");
// $fhplApiController = new FhplApiController;
// $fhplApiController->FhplGetBenefDetails( [ 'polict_no' => $policy_no, 'file_id' =>$file_id ] );
$r = Jobs::addJob(['job_name' => 'FhplGetBenefDetails', 'payload' => ['policy_no' => $policy_no, 'file_id' => $file_id, 'client_policy_id' => $policy_id, 'return_type' => 'job']]);
log_message('error', "FhplGetBenefDetails job pushed successfully.");
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Action Triggered','data' => [] ]);
}else{ }else{
return $this->respond(['status' => false, 'code' => 200,'message' => 'TPA not found ','data' => [] ]); return $this->respond(['status' => false, 'code' => 200,'message' => 'TPA not found ','data' => [] ]);
} }
@ -286,12 +313,20 @@ class ApiServiceController extends BaseController
if ($tpaID == $this->medi_assist_primary_key) { // MediAssist if ($tpaID == $this->medi_assist_primary_key) { // MediAssist
$mediAssistController = new MediAssistApiController(); $mediAssistController = new MediAssistApiController();
return $mediAssistController->ClaimDetail($claimId); $res = $mediAssistController->ClaimDetail($claimId);
return $this->response->setJSON(['status' => $res['status'],'message' => $res['message'] ]);
}else if ($tpaID == $this->vidal_primary_key) { // vidal }else if ($tpaID == $this->vidal_primary_key) { // vidal
$vidalApiController = new VidalApiController; $vidalApiController = new VidalApiController;
return $vidalApiController->ClaimDetail($claimId); $res = $vidalApiController->ClaimDetail($claimId);
return $this->response->setJSON(['status' => $res['status'],'message' => $res['message'] ]);
}else if ($tpaID == $this->fhpl_primary_key) { // Fhpl
$fhplApiController = new FhplApiController;
$res = $fhplApiController->ClaimDetail($claimId);
return $this->response->setJSON(['status' => $res['status'],'message' => $res['message'] ]);
}else{ }else{
log_message('error', "This ticket id ( {$claimId} ) TPA has no API service enabled. TPA ID : {$tpaID}"); log_message('error', "This ticket id ( {$claimId} ) TPA has no API service enabled. TPA ID : {$tpaID}");

View File

@ -59,8 +59,48 @@ class AppContentManagementController extends AdminController
// add and edit // add and edit
public function add_advertise_image() { public function add_advertise_image() {
try { try {
$data = $this->request->getPost();
$sanitized_post_data = sanitizeInputArrayAdvanced($data);
$id = ((int) $sanitized_post_data['add_image_id']) ?? null;
$rules = [
'client_id' => [
'rules' => 'required|integer',
'errors' => [
'required' => 'Client is required',
'integer' => 'Invalid client selected'
]
],
];
$rules['advertise_image'] = [
'rules' => ($id === 0 ? 'uploaded[advertise_image]|' : '') // required only for ADD
. 'is_image[advertise_image]'
. '|mime_in[advertise_image,image/jpg,image/jpeg,image/png]'
. '|max_size[advertise_image,200]'
. '|min_dims[advertise_image,1640,664]'
. '|max_dims[advertise_image,1640,664]',
'errors' => [
'uploaded' => 'Image is required',
'is_image' => 'File must be an image',
'mime_in' => 'Only JPG, JPEG, PNG allowed',
'max_size' => 'Image size must not exceed 200 KB',
'min_dims' => 'Image dimensions must be exactly 1640x664 pixels',
'max_dims' => 'Image dimensions must be exactly 1640x664 pixels',
]
];
if (!$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Input validation failed',
'code' => 400,
'errors' => $this->validator->getErrors()
]);
}
$file = $this->request->getFile('advertise_image'); $file = $this->request->getFile('advertise_image');
$client_id = $this->request->getPost('client_id'); $client_id = $sanitized_post_data['client_id'] ?? null;
//1) original file name for vaildations //1) original file name for vaildations
$fileName = $file->getClientName(); //original file name for vaildations $fileName = $file->getClientName(); //original file name for vaildations
$existing = $this->addImgModel->where('name', $fileName)->where('client_id', $fileName)->where('is_active', 1)->first(); $existing = $this->addImgModel->where('name', $fileName)->where('client_id', $fileName)->where('is_active', 1)->first();
@ -80,13 +120,13 @@ class AppContentManagementController extends AdminController
$file->move($uploadPath, $fileName); $file->move($uploadPath, $fileName);
$id = $this->request->getPost('add_image_id'); $id = $sanitized_post_data['add_image_id'] ?? null;
$data = ['name' => $fileName,'client_id'=>$client_id]; $details = ['name' => $fileName,'client_id'=>$client_id];
if ($id == 0) { if ($id == 0) {
$this->addImgModel->insert($data); $this->addImgModel->insert($details);
} else { } else {
$this->addImgModel->update($id, $data); $this->addImgModel->update($id, $details);
} }
return $this->respond(['status' => true, 'message' => 'Image saved successfully.']); return $this->respond(['status' => true, 'message' => 'Image saved successfully.']);
@ -143,8 +183,56 @@ class AppContentManagementController extends AdminController
if ($this->request->getMethod() === 'post') { if ($this->request->getMethod() === 'post') {
$id = $this->request->getPost('fe_id'); $rules = [
$data = $this->request->getPost(); 'type' => [
'rules' => 'required|max_length[255]',
'errors' => [
'required' => 'Type is required',
'max_length' => 'Type cannot exceed 255 characters'
]
],
'content_section' => [
'rules' => 'required|max_length[255]',
'errors' => [
'required' => 'Content Section is required',
'max_length' => 'Content Section cannot exceed 255 characters'
]
],
'heading' => [
'rules' => 'required|max_length[255]',
'errors' => [
'required' => 'Heading is required',
'max_length' => 'Heading cannot exceed 255 characters'
]
],
'content' => [
'rules' => 'required|max_length[5000]',
'errors' => [
'required' => 'Content is required',
'max_length' => 'Content cannot exceed 5000 characters'
]
],
'notes' => [
'rules' => 'required|max_length[1500]',
'errors' => [
'required' => 'Notes are required',
'max_length' => 'Notes cannot exceed 1500 characters'
]
]
];
if (!$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Input validation failed',
'code' => 400,
'errors' => $this->validator->getErrors()
]);
}
$request_post_data = $this->request->getPost();
$data = sanitizeInputArrayAdvanced($request_post_data);
$id = $data['fe_id'];
unset($data['fe_id']); unset($data['fe_id']);
@ -231,8 +319,30 @@ class AppContentManagementController extends AdminController
try { try {
// --- 1. POST: CREATE OR UPDATE --- // --- 1. POST: CREATE OR UPDATE ---
if ($method === 'post') { if ($method === 'post') {
$id = $this->request->getPost('faq_id'); $rules = [
$data = array_filter($this->request->getPost(), fn($v) => $v !== '' && $v !== null); 'category' => [
'rules' => 'required',
'errors' => [
'required' => 'Category is required'
]
],
'question' => [
'rules' => 'required',
'errors' => [
'required' => 'Question is required'
]
],
'answer' => [
'rules' => 'required',
'errors' => [
'required' => 'Answer is required'
]
]
];
$request_post_data = $this->request->getPost();
$sanitized_post_data = sanitizeInputArrayAdvanced($request_post_data);
$data = array_filter($sanitized_post_data, fn($v) => $v !== '' && $v !== null);
$id = $data['faq_id'];
if (empty($id)) { if (empty($id)) {
$status = $this->faqModel->insert($data); $status = $this->faqModel->insert($data);
@ -264,9 +374,9 @@ class AppContentManagementController extends AdminController
if (!empty($id)) { if (!empty($id)) {
if($returnType === 'web'){ if($returnType === 'web'){
$row = $this->faqModel->find($id); $row = $this->faqModel->find((int)$id);
}else{ }else{
$row = $this->faqModel->where('is_active', 1)->find($id); $row = $this->faqModel->where('is_active', 1)->find((int)$id);
} }
$data['faq_list'] = $row ? [$row] : []; $data['faq_list'] = $row ? [$row] : [];

View File

@ -101,10 +101,10 @@ class BDSReportController extends AdminController
SELECT SELECT
ins.id, ins.id,
ins.name AS insurers, ins.name AS insurers,
COALESCE(SUM(CASE WHEN pt.action_type = 'inception' AND pt.insurer_id = ins.id AND ptp.policy_category = $insurerCategory THEN 1 ELSE 0 END), 0) AS Policies, COALESCE(SUM(CASE WHEN pt.action_type = 'inception' AND pt.insurer_id = ins.id AND ptp.policy_category = :insurerCategory: THEN 1 ELSE 0 END), 0) AS Policies,
COALESCE(SUM(CASE WHEN ptp.policy_category = $insurerCategory AND pt_co.insurer_id = ins.id THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS Premium, COALESCE(SUM(CASE WHEN ptp.policy_category = :insurerCategory: AND pt_co.insurer_id = ins.id THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS Premium,
COALESCE(SUM(CASE WHEN stmt.co_share_id = pt_co.id AND ptp.policy_category = $insurerCategory AND pt_co.insurer_id = ins.id THEN stmt.reward + stmt.actual_bp_brokerage_amt + stmt.actual_tep_brokerage_amt + stmt.actual_tp_brokerage_amt ELSE 0 END), 0) AS Revenue, COALESCE(SUM(CASE WHEN stmt.co_share_id = pt_co.id AND ptp.policy_category = :insurerCategory: AND pt_co.insurer_id = ins.id THEN stmt.reward + stmt.actual_bp_brokerage_amt + stmt.actual_tep_brokerage_amt + stmt.actual_tp_brokerage_amt ELSE 0 END), 0) AS Revenue,
COALESCE(SUM(CASE WHEN ptp.policy_category = $insurerCategory AND pt_co.insurer_id = ins.id THEN pt_co.exp_amt ELSE 0 END), 0) AS Expected_amt COALESCE(SUM(CASE WHEN ptp.policy_category = :insurerCategory: AND pt_co.insurer_id = ins.id THEN pt_co.exp_amt ELSE 0 END), 0) AS Expected_amt
FROM FROM
insurers ins insurers ins
LEFT JOIN LEFT JOIN
@ -112,16 +112,17 @@ class BDSReportController extends AdminController
LEFT JOIN LEFT JOIN
co_share_stmt_details stmt ON pt_co.id = stmt.co_share_id AND stmt.is_active = 1 co_share_stmt_details stmt ON pt_co.id = stmt.co_share_id AND stmt.is_active = 1
LEFT JOIN LEFT JOIN
policy_transaction pt ON pt_co.pt_id = pt.id AND pt.is_active = 1 AND pt.policy_issue_date >= '$fromDate' AND pt.policy_issue_date <= '$toDate' policy_transaction pt ON pt_co.pt_id = pt.id AND pt.is_active = 1 AND pt.policy_issue_date >= :fromDate: AND pt.policy_issue_date <= :toDate:
LEFT JOIN LEFT JOIN
policy_type ptp ON pt.policy_type_id = ptp.id AND ptp.policy_category = $insurerCategory AND ptp.is_active = 1 policy_type ptp ON pt.policy_type_id = ptp.id AND ptp.policy_category = :insurerCategory: AND ptp.is_active = 1
WHERE WHERE
ins.is_active = 1 AND (ptp.policy_category = $insurerCategory OR ptp.policy_category IS NULL) ins.is_active = 1 AND (ptp.policy_category = :insurerCategory: OR ptp.policy_category IS NULL)
GROUP BY GROUP BY
ins.id; ins.id;
"; ";
$data['insurer_wise_data'] = $this->insurerModel->query($sql)->getResultArray(); $binds = ['insurerCategory'=>$insurerCategory,'fromDate'=>$fromDate,'toDate'=>$toDate];
$data['insurer_wise_data'] = $this->insurerModel->query($sql,$binds)->getResultArray();
// log_message('error',$this->insurerModel->getLastQuery()); // log_message('error',$this->insurerModel->getLastQuery());
// log_message('error',json_encode($data)); // log_message('error',json_encode($data));
} catch (\Exception $e) { } catch (\Exception $e) {
@ -146,15 +147,16 @@ class BDSReportController extends AdminController
COALESCE(SUM(co.reward + co.actual_bp_brokerage_amt + co.actual_tep_brokerage_amt + co.actual_tp_brokerage_amt), 0) AS Revenue, COALESCE(SUM(co.reward + co.actual_bp_brokerage_amt + co.actual_tep_brokerage_amt + co.actual_tp_brokerage_amt), 0) AS Revenue,
COALESCE(SUM(pt_co.exp_amt), 0) AS Expected_amt COALESCE(SUM(pt_co.exp_amt), 0) AS Expected_amt
FROM policy_type AS pot FROM policy_type AS pot
LEFT JOIN policy_transaction AS pt ON pot.id = pt.policy_type_id AND pt.is_active = 1 AND pt.action_type = 'inception' and pt.policy_issue_date >= '$fromDate' and pt.policy_issue_date <= '$toDate' LEFT JOIN policy_transaction AS pt ON pot.id = pt.policy_type_id AND pt.is_active = 1 AND pt.action_type = 'inception' and pt.policy_issue_date >= :fromDate: and pt.policy_issue_date <= :toDate:
LEFT JOIN pt_co_share_details AS pt_co ON pt.id = pt_co.pt_id AND pt_co.is_active = 1 LEFT JOIN pt_co_share_details AS pt_co ON pt.id = pt_co.pt_id AND pt_co.is_active = 1
LEFT JOIN co_share_stmt_details AS co ON pt_co.id = co.co_share_id AND co.is_active = 1 LEFT JOIN co_share_stmt_details AS co ON pt_co.id = co.co_share_id AND co.is_active = 1
WHERE pot.is_active = 1 WHERE pot.is_active = 1
AND pot.policy_category = $insurerCategory AND pot.policy_category = :insurerCategory:
GROUP BY pot.bap; GROUP BY pot.bap;
"; ";
$data['bap_wise_data'] = $this->policyTypeModel->query($sql)->getResultArray(); $binds = ['insurerCategory'=>$insurerCategory,'fromDate'=>$fromDate,'toDate'=>$toDate];
$data['bap_wise_data'] = $this->policyTypeModel->query($sql,$binds)->getResultArray();
} catch (\Exception $e) { } catch (\Exception $e) {
$data['message'] = 'No Data Found'; $data['message'] = 'No Data Found';
$this->myLogger->logme('error', $e->getMessage()); $this->myLogger->logme('error', $e->getMessage());
@ -189,10 +191,13 @@ class BDSReportController extends AdminController
return $this->loadLayout('irba_report', $data); return $this->loadLayout('irba_report', $data);
} else { } else {
$fromDate = $this->request->getPost('fromDate'); $request_post_data = $this->request->getPost();
$toDate = $this->request->getPost('toDate'); $sanitized_post_data = sanitizeInputArrayAdvanced($request_post_data);
$category = $this->request->getPost('category');
$report_type = $this->request->getPost('report_type'); $fromDate = $sanitized_post_data['fromDate'] ?? null;
$toDate = $sanitized_post_data['toDate'] ?? null;
$category = $sanitized_post_data['category'] ?? null;
$report_type = $sanitized_post_data['report_type'] ?? null;
// log_message('error',json_encode($_POST));die(); // log_message('error',json_encode($_POST));die();
if ($report_type == 'insurer') { if ($report_type == 'insurer') {
$life = $category == 'life' ? 1 : 0; $life = $category == 'life' ? 1 : 0;
@ -265,6 +270,7 @@ class BDSReportController extends AdminController
//Function for get BAP INSURE wise data for premium , policy count , revenue only //Function for get BAP INSURE wise data for premium , policy count , revenue only
public function getBAPInsurerData($category = 0, $start_date = null, $end_date = null) public function getBAPInsurerData($category = 0, $start_date = null, $end_date = null)
{ {
$category = (int)$category;
try { try {
$this->myLogger->logme('error', 'getBAPInsurerData function called'); $this->myLogger->logme('error', 'getBAPInsurerData function called');
$this->myLogger->logme('error', 'category : {data}', ['data' => $category]); $this->myLogger->logme('error', 'category : {data}', ['data' => $category]);
@ -424,7 +430,7 @@ class BDSReportController extends AdminController
//Function for get BAP CLIENT wise data for premium , policy count , revenue only //Function for get BAP CLIENT wise data for premium , policy count , revenue only
public function getBAPClientData($category = 0, $start_date = null, $end_date = null) public function getBAPClientData($category = 0, $start_date = null, $end_date = null)
{ {
$category = (int)$category;
try { try {
$this->myLogger->logme('error', 'getBAPClientData function called'); $this->myLogger->logme('error', 'getBAPClientData function called');
$this->myLogger->logme('error', 'category : {data}', ['data' => $category]); $this->myLogger->logme('error', 'category : {data}', ['data' => $category]);
@ -525,7 +531,7 @@ class BDSReportController extends AdminController
//Function for get CLIENT wise data for premium and policy count only //Function for get CLIENT wise data for premium and policy count only
public function getClientData($category = 0, $start_date = null, $end_date = null) public function getClientData($category = 0, $start_date = null, $end_date = null)
{ {
$category = (int)$category;
try { try {
$this->myLogger->logme('error', 'getClientData function called'); $this->myLogger->logme('error', 'getClientData function called');
@ -935,11 +941,13 @@ class BDSReportController extends AdminController
return $this->loadLayout('renewal_search', $data); return $this->loadLayout('renewal_search', $data);
} else { } else {
$fromDate = $this->request->getPost('fromDate'); $request_post_data = $this->request->getPost();
$toDate = $this->request->getPost('toDate'); $sanitized_post_data = sanitizeInputArrayAdvanced($request_post_data);
$client_id = $this->request->getPost('client_id'); $fromDate = $sanitized_post_data['fromDate'] ?? null;
$client_type = $this->request->getPost('client_type'); $toDate = $sanitized_post_data['toDate'] ?? null;
$issuer_branch = $this->request->getPost('issuer_branch'); $client_id = $sanitized_post_data['client_id'] ?? null;
$client_type = $sanitized_post_data['client_type'] ?? null;
$issuer_branch = $sanitized_post_data['issuer_branch'] ?? null;
$data['issuer_branch'] = $this->nhanceBranchModel->where('is_active', 1)->findAll(); $data['issuer_branch'] = $this->nhanceBranchModel->where('is_active', 1)->findAll();
$data['client_type'] = [1 => 'Group', 2 => 'Individual']; $data['client_type'] = [1 => 'Group', 2 => 'Individual'];

View File

@ -0,0 +1,48 @@
<?php
namespace App\Controllers;
use CodeIgniter\API\ResponseTrait;
use App\Controllers\BaseController;
class ClaimsUploadController extends BaseController
{
use ResponseTrait;
protected $db;
public function __construct()
{
$this->db = \Config\Database::connect();
}
public function uploadDump()
{
$file = $this->request->getFile('file');
if (!$file || !$file->isValid()) {
return $this->respond([
'status' => 'failed',
'message' => 'Invalid file'
], 400);
}
$data = [
'client_id' => $this->request->getPost('client_id'),
'tpa_id' => $this->request->getPost('tpa_id'),
'client_policy_id' => $this->request->getPost('client_policy_id'),
'from_date' => $this->request->getPost('from_date'),
'to_date' => $this->request->getPost('to_date'),
'upload_file' => $file->getRandomName(),
// 'uploaded_by' => user_id()
];
$file->move(WRITEPATH . 'uploads/claims_dump', $data['upload_file']);
$this->db->table('claims_dump_uploads')->insert($data);
return $this->respond([
'status' => 'success',
'message' => 'Claims dump uploaded'
]);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -443,7 +443,7 @@ class DashboardController extends AdminController
foreach ($client_policy_data as $client_policy) { foreach ($client_policy_data as $client_policy) {
// Fetch client data // Fetch client data
$client_data = $this->clientModel->find($client_policy['client_id']); $client_data = $this->clientModel->find((int)$client_policy['client_id']);
// Fetch notification settings // Fetch notification settings
$notification_data = $this->notificationModel $notification_data = $this->notificationModel

View File

@ -33,6 +33,8 @@ use App\Models\LeadsModel;
use App\Models\LeadInstallmentPaymentDetails; use App\Models\LeadInstallmentPaymentDetails;
use App\Models\PolicyTransactionModel; use App\Models\PolicyTransactionModel;
use App\Models\PTCOShareDetailsModel; use App\Models\PTCOShareDetailsModel;
use App\Models\LevelContactModel;
use App\Controllers\Jobs; use App\Controllers\Jobs;
use App\Controllers\JobWorker; use App\Controllers\JobWorker;
@ -71,6 +73,8 @@ class EmpDataServiceController extends BaseController
protected $leadInstallmentPaymentDetailesModel; protected $leadInstallmentPaymentDetailesModel;
protected $policyTransactionModel; protected $policyTransactionModel;
protected $PTCOShareDetailsModel; protected $PTCOShareDetailsModel;
protected $LevelContactModel;
public function __construct() public function __construct()
@ -99,6 +103,7 @@ class EmpDataServiceController extends BaseController
$this->leadInstallmentPaymentDetailesModel = new LeadInstallmentPaymentDetails(); $this->leadInstallmentPaymentDetailesModel = new LeadInstallmentPaymentDetails();
$this->policyTransactionModel = new PolicyTransactionModel(); $this->policyTransactionModel = new PolicyTransactionModel();
$this->PTCOShareDetailsModel = new PTCOShareDetailsModel(); $this->PTCOShareDetailsModel = new PTCOShareDetailsModel();
$this->LevelContactModel = new LevelContactModel();
} }
@ -199,24 +204,28 @@ class EmpDataServiceController extends BaseController
$totals = $totals + $item->total; $totals = $totals + $item->total;
} }
$totals = round($totals, 2); $totals = round($totals);
//check CD amt insufficient only insurer, not tpa // DO NOT REMOVE THIS //check CD amt insufficient only insurer, not tpa // DO NOT REMOVE THIS
if($export_data['insurer_or_tpa'] == 'insurer') if($export_data['insurer_or_tpa'] == 'insurer')
{ {
if (!empty($cash_balance)) {
if ((int) $cash_balance['balance'] < (int) $totals) { if ((int) $cash_balance['balance'] < (int) $totals) {
$this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount.'); clear_cd_balance_session(); // Clear old junk first
$this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount. CASH BALANCE : {balance} and TOTAL AMOUNT : {total}', ['balance' => $cash_balance['balance'], 'total' => $totals]);
session()->set('cd_balance', false);
session()->set('cd_amount', $cash_balance['balance']);
session()->set('excel_file_amt', $totals);
}else{
session()->set('cd_balance', true);
session()->set('cd_amount', $cash_balance['balance']);
session()->set('excel_file_amt', $totals);
} $cd_session_data = json_encode([
'cd_balance' => false,
'cd_amount' => $cash_balance['balance'],
'excel_file_amt' => $totals
]);
session()->set('cd_balance_info', $cd_session_data);
session()->set('cd_balance', 'insufficient'); // Use a string status for clarity
$hr_data = $this->getHrdataForInsufficientMailSend($export_data['client_branch_id']);
session()->set('hr_data', json_encode(['client_id' => $export_data['client_id'], 'hr_data' => $hr_data]));
}else{
session()->set('cd_balance', 'sufficient'); // Use a string status for clarity
session()->set('cd_balance_info', null);
} }
} }
@ -487,13 +496,18 @@ class EmpDataServiceController extends BaseController
WHEN `client_policy`.`policy_type_id` IN (2, 3, 4, 5) THEN 2 WHEN `client_policy`.`policy_type_id` IN (2, 3, 4, 5) THEN 2
ELSE `client_policy`.`policy_type_id` ELSE `client_policy`.`policy_type_id`
END END
WHERE `client_policy`.`id` = '".$export_data['client_policy_id']."' WHERE `client_policy`.`id` = :client_policy_id:
AND `insurer_excel_export_template`.`event_name` = '".$export_data['event_type']."' AND `insurer_excel_export_template`.`event_name` = :event_name:
AND `insurer_excel_export_template`.`is_active` = 1 AND `insurer_excel_export_template`.`is_active` = 1
AND `insurer_excel_export_template`.`type_name` = '".$export_data['actions']."' AND `insurer_excel_export_template`.`type_name` = :type_name:
LIMIT 1"; LIMIT 1";
$query = db_connect()->query($sql); $binds = [
'client_policy_id' => (int)$export_data['client_policy_id'],
'event_name' => $export_data['event_type'],
'type_name' => $export_data['actions'],
];
$query = db_connect()->query($sql,$binds);
$template_json = $query->getRowArray(); $template_json = $query->getRowArray();
// dd(db_connect()->getLastQuery()); // dd(db_connect()->getLastQuery());
@ -720,17 +734,23 @@ class EmpDataServiceController extends BaseController
if($export_data['insurer_or_tpa'] == 'insurer') if($export_data['insurer_or_tpa'] == 'insurer')
{ {
if (!empty($cash_balance)) { if (!empty($cash_balance)) {
if ((int) $cash_balance['balance'] < (int) $rounded_totals) { if ((int) $cash_balance['balance'] < (int) $totals) {
$this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount.'); clear_cd_balance_session(); // Clear old junk first
$this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount. CASH BALANCE : {balance} and TOTAL AMOUNT : {total}', ['balance' => $cash_balance['balance'], 'total' => $totals]);
session()->set('cd_balance', false);
session()->set('cd_amount', $cash_balance['balance']);
session()->set('excel_file_amt', $rounded_totals);
}else{
session()->set('cd_balance', true);
session()->set('cd_amount', $cash_balance['balance']);
session()->set('excel_file_amt', $rounded_totals);
$cd_session_data = json_encode([
'cd_balance' => false,
'cd_amount' => $cash_balance['balance'],
'excel_file_amt' => $totals
]);
session()->set('cd_balance_info', $cd_session_data);
session()->set('cd_balance', 'insufficient'); // Use a string status for clarity
$hr_data = $this->getHrdataForInsufficientMailSend($export_data['client_branch_id']);
session()->set('hr_data', json_encode(['client_id' => $export_data['client_id'], 'hr_data' => $hr_data]));
}else{
session()->set('cd_balance', 'sufficient'); // Use a string status for clarity
session()->set('cd_balance_info', null);
} }
} }
} }
@ -1052,16 +1072,22 @@ class EmpDataServiceController extends BaseController
{ {
if (!empty($cash_balance)) { if (!empty($cash_balance)) {
if ((int) $cash_balance['balance'] < (int) $totals) { if ((int) $cash_balance['balance'] < (int) $totals) {
$this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount.'); clear_cd_balance_session(); // Clear old junk first
$this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount. CASH BALANCE : {balance} and TOTAL AMOUNT : {total}', ['balance' => $cash_balance['balance'], 'total' => $totals]);
session()->set('cd_balance', false);
session()->set('cd_amount', $cash_balance['balance']);
session()->set('excel_file_amt', $totals);
}else{
session()->set('cd_balance', true);
session()->set('cd_amount', $cash_balance['balance']);
session()->set('excel_file_amt', $totals);
$cd_session_data = json_encode([
'cd_balance' => false,
'cd_amount' => $cash_balance['balance'],
'excel_file_amt' => $totals
]);
session()->set('cd_balance_info', $cd_session_data);
session()->set('cd_balance', 'insufficient'); // Use a string status for clarity
$hr_data = $this->getHrdataForInsufficientMailSend($export_data['client_branch_id']);
session()->set('hr_data', json_encode(['client_id' => $export_data['client_id'], 'hr_data' => $hr_data]));
}else{
session()->set('cd_balance', 'sufficient'); // Use a string status for clarity
session()->set('cd_balance_info', null);
} }
} }
} }
@ -1095,13 +1121,15 @@ class EmpDataServiceController extends BaseController
WHEN `client_policy`.`policy_type_id` IN (2, 3, 4, 5) THEN 2 WHEN `client_policy`.`policy_type_id` IN (2, 3, 4, 5) THEN 2
ELSE `client_policy`.`policy_type_id` ELSE `client_policy`.`policy_type_id`
END END
WHERE `client_policy`.`id` = '".$export_data['client_policy_id']."' WHERE `client_policy`.`id` = :client_policy_id:
AND `insurer_excel_export_template`.`event_name` = 'all' AND `insurer_excel_export_template`.`event_name` = 'all'
AND `insurer_excel_export_template`.`is_active` = 1 AND `insurer_excel_export_template`.`is_active` = 1
AND `insurer_excel_export_template`.`type_name` = '".$export_data['actions']."' AND `insurer_excel_export_template`.`type_name` = :type_name:
LIMIT 1"; LIMIT 1";
$query = db_connect()->query($sql); $binds = ['client_policy_id' => (int)$export_data['client_policy_id'],
'type_name' => $export_data['actions']];
$query = db_connect()->query($sql,$binds);
$template_json = $query->getRowArray(); $template_json = $query->getRowArray();
@ -1931,7 +1959,7 @@ class EmpDataServiceController extends BaseController
$this->myLogger->logme('error', 'Inception Update TPA and UHID -- Function called'); $this->myLogger->logme('error', 'Inception Update TPA and UHID -- Function called');
$file_id = $params['file_id']; $file_id = $params['file_id'];
$file = $this->batchFileModel->find($file_id); $file = $this->batchFileModel->find((int)$file_id);
// dd($file); // dd($file);
if (!$file) { if (!$file) {
@ -1940,10 +1968,10 @@ class EmpDataServiceController extends BaseController
'status' => 'failed-4', 'status' => 'failed-4',
]; ];
$this->batchFileModel->where('id', $file_id)->set($data)->update(); $this->batchFileModel->where('id', (int)$file_id)->set($data)->update();
$this->myLogger->logme('error', 'Inception Update TPA and UHID -- The Physical file not found -- File id : {data}', ['data' => $file_id]); $this->myLogger->logme('error', 'Inception Update TPA and UHID -- The Physical file not found -- File id : {data}', ['data' => $file_id]);
$file_data = $this->getDataByFileId($file_id, 'failure'); $file_data = $this->getDataByFileId((int)$file_id, 'failure');
$this->setPullNotification($file_data); $this->setPullNotification($file_data);
return ['status' => 'error', 'message' => 'Inception Update TPA and UHID -- The Physical file not found']; // Return error code if file not found return ['status' => 'error', 'message' => 'Inception Update TPA and UHID -- The Physical file not found']; // Return error code if file not found
@ -1958,17 +1986,17 @@ class EmpDataServiceController extends BaseController
$user_id = $file['created_by']; $user_id = $file['created_by'];
$policy_issue_date = $file['policy_issue_date']; $policy_issue_date = $file['policy_issue_date'];
$insurer_id = $this->clientPolicyModel->where('id', $client_policy_id)->first(); $insurer_id = $this->clientPolicyModel->where('id', (int)$client_policy_id)->first();
$CD_Account_Number = $this->CDMasterModel $CD_Account_Number = $this->CDMasterModel
->where('client_id', $client_id) ->where('client_id', (int)$client_id)
->where('insurer_id', $insurer_id['insurer_id']) ->where('insurer_id', (int)$insurer_id['insurer_id'])
->first(); ->first();
$get_policy_type = $this->clientPolicyModel $get_policy_type = $this->clientPolicyModel
->select('client_policy.*, policy_type.policy_type') ->select('client_policy.*, policy_type.policy_type')
->join('policy_type', 'policy_type.id = client_policy.policy_type_id', 'left') ->join('policy_type', 'policy_type.id = client_policy.policy_type_id', 'left')
->where('client_policy.id', $client_policy_id) ->where('client_policy.id', (int)$client_policy_id)
->first(); ->first();
// dd($get_policy_type); // dd($get_policy_type);
@ -2178,6 +2206,7 @@ class EmpDataServiceController extends BaseController
'event_name' => $file['event_type'], 'event_name' => $file['event_type'],
'policy_name' => $policy_name['policy_name'], 'policy_name' => $policy_name['policy_name'],
'user_id' => $user_id, 'user_id' => $user_id,
'file_id' => $file_id,
]]); ]]);
$r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [ $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [
@ -2201,7 +2230,7 @@ class EmpDataServiceController extends BaseController
//send ecard mail if the event is tpa only //send ecard mail if the event is tpa only
if ($file['insurer_or_tpa'] == 'tpa') { if ($file['insurer_or_tpa'] == 'tpa') {
if ($get_policy_type['policy_type_id'] != 1) { if (in_array($get_policy_type['policy_type_id'], [2, 3])) {
// generate e-card and store S3 // generate e-card and store S3
$r = Jobs::addJob(['job_name' => 'bulkGenerateEcardAndStoreinS3', 'payload' => ['client_policy_id' => $client_policy_id]]); $r = Jobs::addJob(['job_name' => 'bulkGenerateEcardAndStoreinS3', 'payload' => ['client_policy_id' => $client_policy_id]]);
@ -2500,7 +2529,7 @@ class EmpDataServiceController extends BaseController
$this->myLogger->logme('error', 'importCorrectionUpdateEndorsementID called'); $this->myLogger->logme('error', 'importCorrectionUpdateEndorsementID called');
$file_id = $params['file_id']; $file_id = (int)$params['file_id'];
$file = $this->batchFileModel->find($file_id); $file = $this->batchFileModel->find($file_id);
if (!$file) { if (!$file) {
@ -2617,7 +2646,7 @@ class EmpDataServiceController extends BaseController
'status' => $status_val, 'status' => $status_val,
]); ]);
if($client_policy_data['policy_type_id'] != 1){ if(in_array($client_policy_data['policy_type_id'], [2, 3])){
// re-generate e-card and store S3 // re-generate e-card and store S3
$r = Jobs::addJob(['job_name' => 'bulkGenerateEcardAndStoreinS3', 'payload' => ['client_policy_id' => $client_policy_id]]); $r = Jobs::addJob(['job_name' => 'bulkGenerateEcardAndStoreinS3', 'payload' => ['client_policy_id' => $client_policy_id]]);
} }
@ -3135,7 +3164,7 @@ class EmpDataServiceController extends BaseController
$this->myLogger->logme('error', 'SI Enhancement Update Endorsement ID -- Function called'); $this->myLogger->logme('error', 'SI Enhancement Update Endorsement ID -- Function called');
$file_id = $params['file_id']; $file_id = (int)$params['file_id'];
$file = $this->batchFileModel->find($file_id); $file = $this->batchFileModel->find($file_id);
if (!$file) { if (!$file) {
@ -3361,6 +3390,7 @@ class EmpDataServiceController extends BaseController
'event_name' => $file['event_type'], 'event_name' => $file['event_type'],
'policy_name' => $policy_name['policy_name'], 'policy_name' => $policy_name['policy_name'],
'user_id' => $user_id, 'user_id' => $user_id,
'file_id' => $file_id,
]]); ]]);
$r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [ $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [
@ -3709,7 +3739,7 @@ class EmpDataServiceController extends BaseController
$this->myLogger->logme('error', 'Deletion Update Endorsement ID -- Function called'); $this->myLogger->logme('error', 'Deletion Update Endorsement ID -- Function called');
$file_id = $params['file_id']; $file_id = (int)$params['file_id'];
$file = $this->batchFileModel->find($file_id); $file = $this->batchFileModel->find($file_id);
if (!$file) { if (!$file) {
@ -3872,6 +3902,7 @@ class EmpDataServiceController extends BaseController
'event_name' => $file['event_type'], 'event_name' => $file['event_type'],
'policy_name' => $policy_name['policy_name'], 'policy_name' => $policy_name['policy_name'],
'user_id' => $user_id, 'user_id' => $user_id,
'file_id' => $file_id,
]]); ]]);
$r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [ $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [
@ -4193,7 +4224,7 @@ class EmpDataServiceController extends BaseController
$this->myLogger->logme('error', 'importCorrectionUpdateEndorsementID called'); $this->myLogger->logme('error', 'importCorrectionUpdateEndorsementID called');
$file_id = $params['file_id']; $file_id = (int)$params['file_id'];
$file = $this->batchFileModel->find($file_id); $file = $this->batchFileModel->find($file_id);
if (!$file) { if (!$file) {
@ -4356,7 +4387,8 @@ class EmpDataServiceController extends BaseController
'updated_by' => $arrayData['user_id'], 'updated_by' => $arrayData['user_id'],
'event_name' => $arrayData['event_name'], 'event_name' => $arrayData['event_name'],
'is_active' => 1, 'is_active' => 1,
'cd_ac_pk' => $cd_ac_pk['cd_ac_pk'] 'cd_ac_pk' => $cd_ac_pk['cd_ac_pk'],
'file_id' => $arrayData['file_id'],
]; ];
$response = DepositHelper::saveDeposit($data, $arrayData['user_id']); $response = DepositHelper::saveDeposit($data, $arrayData['user_id']);
@ -4454,11 +4486,12 @@ class EmpDataServiceController extends BaseController
SELECT SUM(rata_premimum + gst) AS total_sum SELECT SUM(rata_premimum + gst) AS total_sum
FROM employee_polices FROM employee_polices
JOIN employees ON employees.id = employee_polices.employee_id JOIN employees ON employees.id = employee_polices.employee_id
WHERE employees.unit = '{$unit}' WHERE employees.unit = :unit:
AND employee_polices.id = '{$pk}' AND employee_polices.id = :pk:
"; ";
$amount = $this->employeePolicyModel->query($query)->getRow(); $binds = ['unit' => $unit,'pk' => $pk];
$amount = $this->employeePolicyModel->query($query,$binds)->getRow();
if ($amount && $amount->total_sum > 0) { if ($amount && $amount->total_sum > 0) {
if ($si_adjustment == 2) { if ($si_adjustment == 2) {
@ -4492,7 +4525,8 @@ class EmpDataServiceController extends BaseController
'updated_by' => $arrayData['user_id'], 'updated_by' => $arrayData['user_id'],
'event_name' => $arrayData['event_name'], 'event_name' => $arrayData['event_name'],
'is_active' => 1, 'is_active' => 1,
'cd_ac_pk' => $policy_data['cd_ac_pk'] 'cd_ac_pk' => $policy_data['cd_ac_pk'],
'file_id' => $arrayData['file_id'],
]; ];
DepositHelper::saveDeposit($data, $arrayData['user_id']); DepositHelper::saveDeposit($data, $arrayData['user_id']);
@ -4522,7 +4556,8 @@ class EmpDataServiceController extends BaseController
'updated_by' => $arrayData['user_id'], 'updated_by' => $arrayData['user_id'],
'event_name' => $arrayData['event_name'], 'event_name' => $arrayData['event_name'],
'is_active' => 1, 'is_active' => 1,
'cd_ac_pk' => $policy_data['cd_ac_pk'] 'cd_ac_pk' => $policy_data['cd_ac_pk'],
'file_id' => $arrayData['file_id'],
]; ];
DepositHelper::saveDeposit($data, $arrayData['user_id']); DepositHelper::saveDeposit($data, $arrayData['user_id']);
@ -4634,7 +4669,8 @@ class EmpDataServiceController extends BaseController
'updated_by' => $arrayData['user_id'], 'updated_by' => $arrayData['user_id'],
'event_name' => $arrayData['event_name'], 'event_name' => $arrayData['event_name'],
'is_active' => 1, 'is_active' => 1,
'cd_ac_pk' => $insurer_id['cd_ac_pk'] 'cd_ac_pk' => $insurer_id['cd_ac_pk'],
'file_id' => $arrayData['file_id'],
]; ];
$response = DepositHelper::saveDeposit($data, $arrayData['user_id']); $response = DepositHelper::saveDeposit($data, $arrayData['user_id']);
@ -5400,7 +5436,7 @@ class EmpDataServiceController extends BaseController
$this->myLogger->logme("error", "Policy transaction inserted successfully: " . json_encode(['insert_id' => $insert_id])); $this->myLogger->logme("error", "Policy transaction inserted successfully: " . json_encode(['insert_id' => $insert_id]));
//do not remove this commented item //do not remove this commented item
$coShareDetails = $this->ConstructPTShareData($policy_data, $insert_id, $params, $lead_data); $coShareDetails = $this->ConstructPTShareData($policy_data, $insert_id, $params, $lead_data, $params['action_type']);
$pt_co_share_id = $this->PTCOShareDetailsModel->insert($coShareDetails); $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]));
@ -5532,7 +5568,46 @@ class EmpDataServiceController extends BaseController
return $policyTransactionData; return $policyTransactionData;
} }
private function ConstructPTShareData($policy_data, $pt_id, $params, $lead_data) private function ConstructPTShareData($policy_data, $pt_id, $params, $lead_data, $action_type)
{
$policyTypeModel = new PolicyTypeModel();
$policy_type_data = $policyTypeModel->where('is_active', 1)->where('id', $policy_data['policy_type_id'])->first();
// Determine if we should negate the values
$multiplier = (strtolower($action_type) === 'deletion') ? -1 : 1;
$coShareData = [
'pt_id' => $pt_id,
'insurer_id' => $policy_data['insurer_id'],
'insurer_branch_id' => $policy_data['insurer_branch_id'],
'bp_amt' => ($params['base_premium'] ?? 0) * $multiplier,
'cop_amt' => ($params['base_premium'] ?? 0) * $multiplier,
'bp_gst_amt' => ($params['gst'] ?? 0) * $multiplier,
'bp_sgst' => 9, // Usually tax percentages remain positive, but multiply if this is an amount
'bp_cgst' => 9,
'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)) * $multiplier,
];
if(isset($policy_data['gst']) && $policy_data['gst'] != null){
$coShareData['bp_igst'] = $policy_data['gst'] ?? 0;
$coShareData['bp_sgst'] = 0;
$coShareData['bp_cgst'] = 0;
}
// Calculate exp_amt logic
$agreed_per = $lead_data['agreed_percentage'] ?? $policy_type_data['ebp'] ?? 0;
$coShareData['exp_amt'] = ((($params['base_premium'] ?? 0) * $agreed_per) / 100) * $multiplier;
$this->myLogger->logme("error", "Constructed PT co-share data: " . json_encode($coShareData));
return $coShareData;
}
private function ConstructPTShareDataOld($policy_data, $pt_id, $params, $lead_data, $action_type = null)
{ {
$policyTypeModel = new PolicyTypeModel(); $policyTypeModel = new PolicyTypeModel();
$policy_type_data = $policyTypeModel->where('is_active', 1)->where('id', $policy_data['policy_type_id'])->first(); $policy_type_data = $policyTypeModel->where('is_active', 1)->where('id', $policy_data['policy_type_id'])->first();
@ -5850,4 +5925,16 @@ class EmpDataServiceController extends BaseController
'gst' => round($amount['gst'] ?? 0, 2) 'gst' => round($amount['gst'] ?? 0, 2)
]; ];
} }
public function getHrdataForInsufficientMailSend($ref_id)
{
$data = $this->LevelContactModel
->select('id, name, email')
->where('ref_id', $ref_id)
->where('is_active', 1)
->where('contact_type', 'client')
->findAll();
return $data;
}
} }

File diff suppressed because it is too large Load Diff

View File

@ -1018,7 +1018,7 @@ class EmployeeMultiEventServiceController extends BaseController
$this->myLogger->logme('error', 'Excel Multievent File Formate Validation function START: ' . json_encode(['params' => $params])); $this->myLogger->logme('error', 'Excel Multievent File Formate Validation function START: ' . json_encode(['params' => $params]));
helper('excel_util_helper'); helper('excel_util_helper');
$file_id = $params['file_id']; $file_id = $params['file_id'];
$file = $this->fileModel->find($file_id); $file = $this->fileModel->find((int)$file_id);
if (!isset($file)) { if (!isset($file)) {
//file not found in DB //file not found in DB
@ -1182,7 +1182,7 @@ class EmployeeMultiEventServiceController extends BaseController
helper('excel_util_helper'); helper('excel_util_helper');
$file_id = $params['file_id']; $file_id = $params['file_id'];
$file = $this->fileModel->find($file_id); $file = $this->fileModel->find((int)$file_id);
if (!isset($file)) { if (!isset($file)) {
//file not found in DB //file not found in DB
@ -1291,7 +1291,7 @@ class EmployeeMultiEventServiceController extends BaseController
helper('excel_util_helper'); helper('excel_util_helper');
$file_id = $params['file_id']; $file_id = $params['file_id'];
$file = $this->fileModel->find($file_id); $file = $this->fileModel->find((int)$file_id);
if (!isset($file)) { if (!isset($file)) {
//file not found in DB //file not found in DB
@ -1387,7 +1387,7 @@ class EmployeeMultiEventServiceController extends BaseController
// dd($params); // dd($params);
//get file name //get file name
$file_id = $params['file_id']; $file_id = $params['file_id'];
$file = $this->fileModel->find($file_id); $file = $this->fileModel->find((int)$file_id);
$file['action'] = $params['action']; $file['action'] = $params['action'];
// dd($file); // dd($file);
@ -1604,7 +1604,7 @@ class EmployeeMultiEventServiceController extends BaseController
//get file name //get file name
$file_id = $params['file_id']; $file_id = $params['file_id'];
$file = $this->fileModel->find($file_id); $file = $this->fileModel->find((int)$file_id);
$file['action'] = $params['action']; $file['action'] = $params['action'];
// Kint::dump($file); // Kint::dump($file);
@ -1805,7 +1805,7 @@ class EmployeeMultiEventServiceController extends BaseController
{ {
//get file name //get file name
$file_id = $params['file_id']; $file_id = $params['file_id'];
$file = $this->fileModel->find($file_id); $file = $this->fileModel->find((int)$file_id);
$file['action'] = $params['action']; $file['action'] = $params['action'];
// dd($file); // dd($file);
$return = []; $return = [];
@ -1910,7 +1910,7 @@ class EmployeeMultiEventServiceController extends BaseController
// $this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'success')); // $this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'success'));
} else if (isset($params['client_policy_id'])) //handle data from enrollment to inception } else if (isset($params['client_policy_id'])) //handle data from enrollment to inception
{ {
$client_policy_id = $params['client_policy_id']; $client_policy_id = (int)$params['client_policy_id'];
//get client id //get client id
$client_id = ($this->clientPolicyModel->select('client_id')->find($client_policy_id))['client_id']; $client_id = ($this->clientPolicyModel->select('client_id')->find($client_policy_id))['client_id'];
// dd($client_id); // dd($client_id);
@ -1956,7 +1956,7 @@ class EmployeeMultiEventServiceController extends BaseController
//get file name //get file name
$file_id = $params['file_id']; $file_id = $params['file_id'];
$file = $this->fileModel->find($file_id); $file = $this->fileModel->find((int)$file_id);
$file['action'] = $params['action']; $file['action'] = $params['action'];
// dd($file); // dd($file);
@ -1975,7 +1975,7 @@ class EmployeeMultiEventServiceController extends BaseController
$endorsement_data = []; $endorsement_data = [];
$policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'], $file['policy_id']); $policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'], $file['policy_id']);
$insurer = new InsurerModel(); $insurer = new InsurerModel();
$insurer = ($insurer->find($policy_terms[0]->insurer_id)); $insurer = ($insurer->find((int)$policy_terms[0]->insurer_id));
// kint::dump($insurer); // kint::dump($insurer);
//make closure funciton which is going to use only by this method //make closure funciton which is going to use only by this method
@ -2095,7 +2095,7 @@ class EmployeeMultiEventServiceController extends BaseController
helper('excel_util_helper'); helper('excel_util_helper');
//get file name //get file name
$file_id = $params['file_id']; $file_id = $params['file_id'];
$file = $this->fileModel->find($file_id); $file = $this->fileModel->find((int)$file_id);
$file['action'] = $params['action']; $file['action'] = $params['action'];
@ -2173,7 +2173,7 @@ class EmployeeMultiEventServiceController extends BaseController
helper('excel_util_helper'); helper('excel_util_helper');
//get file name //get file name
$file_id = $params['file_id']; $file_id = $params['file_id'];
$file = $this->fileModel->find($file_id); $file = $this->fileModel->find((int)$file_id);
$file['action'] = $params['action']; $file['action'] = $params['action'];
// $file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name']; // $file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name'];
@ -2470,7 +2470,7 @@ class EmployeeMultiEventServiceController extends BaseController
{ {
try { try {
$file = $this->fileModel->find($file_id); $file = $this->fileModel->find((int)$file_id);
// $error_data = json_decode($file['reason'], true); // $error_data = json_decode($file['reason'], true);
$error_data = $res; $error_data = $res;
// dd($error_data); // dd($error_data);
@ -2632,7 +2632,7 @@ class EmployeeMultiEventServiceController extends BaseController
// dd($this->request); // dd($this->request);
helper('excel_util_helper'); helper('excel_util_helper');
//get file name //get file name
$file_id = $params['file_id']; $file_id = (int)$params['file_id'];
$file = $this->fileModel->find($file_id); $file = $this->fileModel->find($file_id);
// dd($file); // dd($file);
$return = []; $return = [];

File diff suppressed because it is too large Load Diff

View File

@ -784,7 +784,7 @@ class EmployeeServiceController extends AdminController
//get file name //get file name
// check_dob_diff('4-APr-1990');die(); // check_dob_diff('4-APr-1990');die();
$file_id = $params['file_id']; $file_id = $params['file_id'];
$file = $this->fileModel->find($file_id); $file = $this->fileModel->find((int)$file_id);
// dd($file); // dd($file);
$return = []; $return = [];
if(!isset($file)) if(!isset($file))
@ -866,6 +866,14 @@ class EmployeeServiceController extends AdminController
// get policy and rack details // get policy and rack details
$policy_details = $this->clientPolicyModel->getPolicyDetails($file['client_id'],$file['policy_id']); $policy_details = $this->clientPolicyModel->getPolicyDetails($file['client_id'],$file['policy_id']);
if(empty($policy_details)){
$message = "Policy configuration is incomplete. Cannot proceed.";
$this->myLogger->logme('error',($message . ' for file id ' . $file_id));
$this->fileModel->where('id', $file_id)->set(['status' => 'failed','reason' => json_encode(['error_summary' => array_count_values([5]),'error_data' => $message])])->update();
return array('error_summary' => [5], 'error_data' => $message);
}
$policy_terms = json_decode($policy_details[0]->policy_terms); $policy_terms = json_decode($policy_details[0]->policy_terms);
$policy_terms = (array) $policy_terms;// convert obj to array $policy_terms = (array) $policy_terms;// convert obj to array
$default_age_ratio = isset($policy_terms['age_ratio']) ? json_decode(json_encode($policy_terms['age_ratio']),true) : []; $default_age_ratio = isset($policy_terms['age_ratio']) ? json_decode(json_encode($policy_terms['age_ratio']),true) : [];
@ -876,6 +884,13 @@ class EmployeeServiceController extends AdminController
$slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($file['policy_id'],$file['client_id']); $slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($file['policy_id'],$file['client_id']);
// dd($slab_details); // dd($slab_details);
if(empty($slab_details) || (isset($slab_details['slab_rates']) && empty($slab_details['slab_rates']))){
$message = "Policy configuration is incomplete. Cannot proceed.";
$this->myLogger->logme('error',($message . ' for file id ' . $file_id));
$this->fileModel->where('id', $file_id)->set(['status' => 'failed','reason' => json_encode(['error_summary' => array_count_values([5]),'error_data' => $message])])->update();
return array('error_summary' => [5], 'error_data' => $message);
}
//remove header //remove header
unset($excel_data[0]); unset($excel_data[0]);
$relationship = $this->general_relationships; $relationship = $this->general_relationships;
@ -1062,7 +1077,7 @@ class EmployeeServiceController extends AdminController
helper('excel_util_helper'); helper('excel_util_helper');
//get file name //get file name
$file_id = $params['file_id']; $file_id = $params['file_id'];
$file = $this->fileModel->find($file_id); $file = $this->fileModel->find((int)$file_id);
// dd($file); // dd($file);
$return = []; $return = [];
if(!isset($file)) if(!isset($file))
@ -1322,7 +1337,7 @@ class EmployeeServiceController extends AdminController
{ {
//get file name //get file name
$file_id = $params['file_id']; $file_id = $params['file_id'];
$file = $this->fileModel->find($file_id); $file = $this->fileModel->find((int)$file_id);
// dd($file); // dd($file);
$return = []; $return = [];
if(!isset($file)) if(!isset($file))
@ -1387,6 +1402,8 @@ class EmployeeServiceController extends AdminController
$employee_data_group_by_family = data_group_by_family($excel_data, 'excel', '', $current_column_action); $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);
$employee_insert_count = 0;
foreach ($employee_data_group_by_family as $emp_id => $family) foreach ($employee_data_group_by_family as $emp_id => $family)
{ {
@ -1410,11 +1427,25 @@ class EmployeeServiceController extends AdminController
$data = calculate_premium_new(family_data:$family,policy_terms: $policy_terms,slab_details : $slab_details,fileArr: $file, existing_units:$existing_units); $data = calculate_premium_new(family_data:$family,policy_terms: $policy_terms,slab_details : $slab_details,fileArr: $file, existing_units:$existing_units);
// dd($data); // dd($data);
$employee_data_group_by_family[$emp_id] = $data; $employee_data_group_by_family[$emp_id] = $data;
$this->employeesOnboardProcess(['familiy_data' => $data,'file' => $file]); $res = $this->employeesOnboardProcess(['familiy_data' => $data,'file' => $file]);
if($res > 0){
$employee_insert_count++;
}
} }
if($employee_insert_count > 0){
$this->fileModel->where('id', $file_id)->set(['status' => 'success','reason' => ''])->update(); $this->fileModel->where('id', $file_id)->set(['status' => 'success','reason' => ''])->update();
$this->myLogger->logme("error",'{file_id} uploaded success',['file_id' => $file_id]); $this->myLogger->logme("error",'{file_id} uploaded success',['file_id' => $file_id]);
}else{
$reason = json_encode([
'error_summary' => [5 => 1],
'error_data' => "Rack rate configuration issue: Please check the slab rates configuration"
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$this->fileModel->where('id', $file_id)->set(['status' => 'failed','reason' => $reason])->update();
$this->myLogger->logme("error",'{file_id} uploaded failed with reason: Rack rate configuration issue: Please check the slab rates configuration',['file_id' => $file_id]);
}
$this->setPullNotification($this->getFileMetaDataByFileId($file_id,'success')); $this->setPullNotification($this->getFileMetaDataByFileId($file_id,'success'));
@ -1424,7 +1455,7 @@ class EmployeeServiceController extends AdminController
{ {
$client_policy_id = $params['client_policy_id']; $client_policy_id = $params['client_policy_id'];
//get client id //get client id
$client_id = ($this->clientPolicyModel->select('client_id')->find($client_policy_id))['client_id']; $client_id = ($this->clientPolicyModel->select('client_id')->find((int)$client_policy_id))['client_id'];
// dd($client_id); // dd($client_id);
// get policy and rack details // get policy and rack details
@ -1470,7 +1501,7 @@ class EmployeeServiceController extends AdminController
helper('excel_util_helper'); helper('excel_util_helper');
//get file name //get file name
$file_id = $params['file_id']; $file_id = $params['file_id'];
$file = $this->fileModel->find($file_id); $file = $this->fileModel->find((int)$file_id);
// dd($file); // dd($file);
$file_name_with_path = WRITEPATH."/uploads/excel/".$file['file_name']; $file_name_with_path = WRITEPATH."/uploads/excel/".$file['file_name'];
@ -1489,7 +1520,7 @@ class EmployeeServiceController extends AdminController
$endorsement_data = []; $endorsement_data = [];
$policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'],$file['policy_id']); $policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'],$file['policy_id']);
$insurer = new InsurerModel(); $insurer = new InsurerModel();
$insurer = ($insurer->find($policy_terms[0]->insurer_id)); $insurer = ($insurer->find((int)$policy_terms[0]->insurer_id));
// kint::dump($insurer); // kint::dump($insurer);
//make closure funciton which is going to use only by this method //make closure funciton which is going to use only by this method
$endorsement = function($data,$file,$row) use ($insurer){ $endorsement = function($data,$file,$row) use ($insurer){
@ -1621,7 +1652,7 @@ class EmployeeServiceController extends AdminController
helper('excel_util_helper'); helper('excel_util_helper');
//get file name //get file name
$file_id = $params['file_id']; $file_id = $params['file_id'];
$file = $this->fileModel->find($file_id); $file = $this->fileModel->find((int)$file_id);
// dd($file); // dd($file);
$file_name_with_path = WRITEPATH."/uploads/excel/".$file['file_name']; $file_name_with_path = WRITEPATH."/uploads/excel/".$file['file_name'];
@ -1700,7 +1731,7 @@ class EmployeeServiceController extends AdminController
helper('excel_util_helper'); helper('excel_util_helper');
//get file name //get file name
$file_id = $params['file_id']; $file_id = $params['file_id'];
$file = $this->fileModel->find($file_id); $file = $this->fileModel->find((int)$file_id);
// dd($file); // dd($file);
$file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name']; $file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name'];
@ -1827,6 +1858,7 @@ class EmployeeServiceController extends AdminController
$policy_details = $this->clientPolicyModel->where('id', $file['policy_id'])->first(); $policy_details = $this->clientPolicyModel->where('id', $file['policy_id'])->first();
// dd($policy_details); // dd($policy_details);
$employee_insert_count = 0;
foreach($familiy_data as $fkey => $value) foreach($familiy_data as $fkey => $value)
{ {
if(is_array($value)) if(is_array($value))
@ -1959,6 +1991,7 @@ class EmployeeServiceController extends AdminController
// else{ $emp_policy_id = $employee_policy[0]['id']; } // else{ $emp_policy_id = $employee_policy[0]['id']; }
$this->myLogger->logme('error',$log_message); $this->myLogger->logme('error',$log_message);
$employee_insert_count++;
}// if end }// if end
}// is array check end }// is array check end
@ -1967,6 +2000,8 @@ class EmployeeServiceController extends AdminController
$this->myLogger->logme('error','######Incoming value is not an array'); $this->myLogger->logme('error','######Incoming value is not an array');
} }
}// for end }// for end
return $employee_insert_count;
}//function end }//function end
@ -2028,7 +2063,7 @@ class EmployeeServiceController extends AdminController
{ {
try { try {
$file = $this->fileModel->find($file_id); $file = $this->fileModel->find((int)$file_id);
$error_data = json_decode($file['reason']); $error_data = json_decode($file['reason']);
// dd($error_data); // dd($error_data);
// return $error_data; // return $error_data;
@ -2187,7 +2222,7 @@ class EmployeeServiceController extends AdminController
helper('excel_util_helper'); helper('excel_util_helper');
//get file name //get file name
$file_id = $params['file_id']; $file_id = $params['file_id'];
$file = $this->fileModel->find($file_id); $file = $this->fileModel->find((int)$file_id);
// dd($file); // dd($file);
$return = []; $return = [];
if(!isset($file)) if(!isset($file))

View File

@ -0,0 +1,790 @@
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use App\Models\BatchFileModel;
use App\Models\EmployeePolicyModel;
use App\Models\TpaApiDataModel;
use App\Models\ClientPolicyModel;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\API\ResponseTrait;
use App\Controllers\Jobs;
class FhplApiController extends BaseController
{
use ResponseTrait;
protected $db;
protected $fhplTpaId;
public function __construct()
{
$this->db = \Config\Database::connect();
$this->fhplTpaId = getenv('FHPL_PRIMARY_KEY_CONSTANT');
}
public function generateAuthToken()
{
$url = env('FHPL_TOKEN_URL');
// x-www-form-urlencoded body
$postData = http_build_query([
'UserName' => env('FHPL_USER_NAME'),
'Password' => env('FHPL_PASSWORD'),
'grant_type' => env('FHPL_GRANT_TYPE'),
]);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'GET', // SAME AS POSTMAN
CURLOPT_POSTFIELDS => $postData,
CURLOPT_HTTPHEADER => [
'Content-Type: application/x-www-form-urlencoded',
'Accept: application/json',
],
CURLOPT_TIMEOUT => 30,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
return $this->response->setJSON([
'status' => false,
'error' => curl_error($ch),
]);
}
curl_close($ch);
return $this->response->setJSON([
'status' => $httpCode === 200,
'http_code' => $httpCode,
'data' => json_decode($response, true),
]);
}
public function SubmitClaim($claimId = null) // 515
{
helper('api');
$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.claim_amount as requestedAmount,
tm.tpa_no as dependentUniqueId,
cp.policy_no as policyNo,
e.emp_code as memberId,
tn.note as disease,
cf.url as filePath
')
->join('employees e', 'e.id = tm.emp_id', 'left')
->join('client_policy cp', 'tm.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();
if (count($data) && $data['filePath'] == null) {
log_message('error', "TPA CLAIM PUSH FAILED FHPL | claimId: '.$claimId.' - Claim or File Missing");
return;
}
// Build absolute file path
$filename = basename($data['filePath']);
$pdfPath = WRITEPATH . 'uploads/claim_files/' . $filename;
if (!file_exists($pdfPath)) {
log_message('error', "TPA CLAIM PUSH FAILED FHPL | claimId: '.$claimId.' - PDF not found on server");
return;
}
// Convert PDF to Base64
$fileContent = base64_encode(file_get_contents($pdfPath));
// Generate FHPL Token
$tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
if (empty($tokenResponse['data']['access_token'])) {
log_message('error', "TPA CLAIM PUSH FAILED FHPL | claimId: '.$claimId.' - FHPL Token generation failed");
return;
}
$token = $tokenResponse['data']['access_token'];
// Build FHPL Request
$body = [
"IssueID" => $data['dependentUniqueId'], // this key added after seeing the error in responce have to click with fhpl team
"Userid" => getenv('FHPL_USER_NAME'),
"PolicyNo" => $data['policyNo'], // "111700-TATAMTORS",
"UhidNo" => $data['dependentUniqueId'], // "OIC40830846",
"ClaimID" => (string) $data['id'],
"DOA" => date('Y-m-d', strtotime($data['admissionDate'])), //"2025-10-11",
"DateofDischarge"=> $data['dischargeDate'] ? date('Y-m-d', strtotime($data['dischargeDate'])) : null,
"ClaimedAmount" => (float) $data['requestedAmount'],
"DocumentType" => 20, // Fresh Claim
"PayeeName" => $data['memberId'],
"HospitalName" => $data['hospitalName'],
"MobileNo" => $data['mobileNo'],
"Documents" => [
[
"documentName" => $filename,
"documentCategory" => "IRR",
"filecontent" => $fileContent
]
]
];
$url = getenv('FHPL_BASE_URL') . "/api/ClaimSubmission";
$headers = [
"Authorization: Bearer " . $token,
"Content-Type: application/json"
];
log_message('error', 'TPA CLAIM PUSH FHPL | claimId: '.$claimId.' | payload: '.json_encode($body));
$response = call_third_party_api($url, 'POST', $headers, $body);
log_message('error', 'TPA CLAIM PUSH FHPL RESPONSE | ' . json_encode($response));
if($response['status'] != true){
log_message('error', 'TPA CLAIM PUSH FAILED FHPL | claimId: '.$claimId.' | response: '.json_encode($response));
$this->db->table('ticket_master')
->where('id',$claimId)
->update([ 'tpa_push_response' => json_encode($response) ]);
return;
}
if ($response['status'] === true && !empty($response['data'][0]['ClaimsInfo']))
{
$claimsInfo = json_decode($response['data'][0]['ClaimsInfo'], true);
if (!empty($claimsInfo[0]['ClaimID'])) {
$fhplClaimNo = $claimsInfo[0]['ClaimID'];
$this->db->table('ticket_master')
->where('id', $claimId)
->update([
'claim_number' => $fhplClaimNo,
'tpa_claim_id' => $fhplClaimNo,
'tpa_claim_push_reference_no' => $fhplClaimNo,
'updated_at' => date('Y-m-d H:i:s')
]);
log_message('error', 'TPA CLAIM PUSH SUCCESS FHPL | claimId: '.$claimId.' | claimNO: '.$fhplClaimNo);
}else {
log_message('error', 'TPA CLAIM PUSH API SUCCESS BUT claimsInfo EMPTY | response: '.json_encode($response));
return;
}
}
return;
// return $this->response->setJSON($response);
}
public function ClaimDetail($claimId = null) //515
{
helper('api');
$ticket = $this->db->table('ticket_master tm')
->select("tm.id, tm.tpa_claim_id as claimNo, cp.policy_no , cp.policy_start_date , cp.policy_end_date")
->join('client_policy cp','tm.client_policy_id=cp.id')
->where('tm.id',$claimId)
->get()->getRowArray();
if(!$ticket) return ['status'=>false,'message'=>'Invalid claim'];
// Generate FHPL Token
$tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
if (empty($tokenResponse['data']['access_token'])) {
return ['status' => false,'message' => 'FHPL Token generation failed'];
}
$token = $tokenResponse['data']['access_token'];
$url = getenv('FHPL_BASE_URL')."/api/GetTPA_ClaimsDetails";
$body = [
"UserName" => getenv('FHPL_USER_NAME'),
"Password" => getenv('FHPL_PASSWORD'),
"PolicyNumber" => $ticket['policy_no'], //"GHI-81-25-00087313-000",
"Fromdate" => $ticket['policy_start_date'],//"2025-04-26",
"Todate" => $ticket['policy_end_date'],//"2025-04-27",
];
$headers = ["Authorization: Bearer ".$token,"Content-Type: application/json"];
$response = call_third_party_api($url,'POST',$headers,$body);
// dd($response);
if (empty($response['data'][0])) {
log_message('error', 'CLAIM STATUS FAILED | for ticket ID: ' . $claimId.' | response: '.json_encode($response));
return ['status' => false,'message' => 'API call failed.','data' => $response ];
}
$status = null;
// find this claim
foreach($response['data'] as $row){
if($row['CLAIM_ID']==$ticket['claimNo']){
$status = $row['CLAIM_STATUS'];
}
}
$map = [
"In-Progress" => 5,
"Under Process" => 5,
"Query" => 4,
"Paid" => 11,
"Rejected" => 8,
"Approved" => 8,
"Required Information" => 4,
];
if( $status != null && isset($map[$status]))
{
$this->db->table('ticket_master')->where('id',$claimId)->update(['claim_status_id'=>$map[$status],'tpa_claim_status'=>$status]);
log_message('error', "CLAIM STATUS SUCCESS | Updated ticket ID $claimId with claim status: $status");
}
return ['status' => true,'message' => 'Claim status updated.','updated_status' => $status,'api_response' => $response];
}
public function ClaimStatusUpdate()
{
helper('api');
$tickets = $this->db->table('ticket_master tm')
->select("tm.id,tm.tpa_claim_id,cp.policy_no")
->join('client_policy cp','tm.client_policy_id=cp.id')
->where('tm.tpa_claim_id IS NOT NULL')
->get()->getResultArray();
$count=0;
foreach($tickets as $t){
$this->ClaimDetail($t['id']);
$count++;
}
return $this->response->setJSON(['status'=>true,'updated'=>$count]);
}
public function EcardRequest($employeeId = null,$policyNo = null,$uhid = null)
{
helper('api');
// Generate FHPL Token
$tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
if (empty($tokenResponse['data']['access_token'])) {
log_message('error', 'Ecard Request FAILED | employeeId: '.$employeeId.' | policyNo: '.$policyNo.' | Message: FHPL Token generation failed');
return null;
}
$token = $tokenResponse['data']['access_token'];
$url = getenv('FHPL_BASE_URL')."/api/GetEcard";
$body = [
"UserName" => getenv('FHPL_USER_NAME'),
"Password" => getenv('FHPL_PASSWORD'),
"PolicyNumber" => $policyNo, //'10/12/2025/16/17',
"EmployeeID" => $employeeId, //'101225',
];
$headers = ["Authorization: Bearer ".$token,"Content-Type: application/json"];
$response = call_third_party_api($url,'POST',$headers,$body);
// dd($response);
if (($response['status'] ?? false) !== true) {
log_message('error', 'Ecard Request FAILED | response: ' . json_encode($response));
return null;
}
if (empty($response['data'][0])) {
log_message('error', 'Ecard Request FAILED | Empty data | response: ' . json_encode($response));
return null;
}
$apiData = $response['data'][0];
if (($apiData['STATUS'] ?? '') === 'SUCCESS') {
$ecardUrl = $apiData['E_Card'] ?? '';
if (!empty($ecardUrl)) {
log_message(
'info',
'Ecard Request PUSH SUCCESS | employeeId: ' . $employeeId .
' | policyNo: ' . $policyNo .
' | ecardUrl: ' . $ecardUrl
);
return $ecardUrl;
}
}
log_message('error', 'Ecard Request FAILED | response: ' . json_encode($response));
return null;
}
public function FhplGetBenefDetails($requestData = null)
{
$function_calling_type = $requestData['return_type'] ?? 'job';
try {
helper('api');
$policyNo = $requestData['policy_no'] ?? null;
$client_policy_id = $requestData['client_policy_id'] ?? null;
if (empty($policyNo)) {
log_message('error', 'TPA ID PULL | policy_no missing in request');
if($function_calling_type == "job"){
return ['status' => false, 'message' => 'policy_no required'];
}else{
return $this->respond(['status' => false, 'message' => 'policy_no required']);
}
}
if (empty($client_policy_id)) {
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{
return $this->respond(['status' => false, 'message' => 'client_policy_id required']);
}
}
log_message('error', "TPA ID PULL | called for policy_no: {$policyNo} , client_policy_id: {$client_policy_id}");
// Fetch file download dates
$batchFiles = $this->db->table('batch_files f')
->select("f.created_at")
->where('f.client_policy_id', $client_policy_id)
->where('f.insurer_or_tpa', 'tpa')
->where('f.actions', 'export')
->get()
->getResultArray();
if (empty($batchFiles)) {
log_message('error', 'TPA ID PULL FAILED | batchFiles is empty for this tpa id pull request');
if($function_calling_type == "job"){
return ['status' => false, 'message' => 'batchFiles not found'];
}else{
return $this->respond(['status' => false, 'message' => 'batchFiles not found']);
}
}
// Generate FHPL Token
$tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
if (empty($tokenResponse['data']['access_token'])) {
log_message('error', 'TPA ID PULL | FHPL Token generation failed');
if($function_calling_type == "job"){
return ['status' => false, 'message' => 'FHPL Token generation failed'];
}else{
return $this->respond(['status' => false, 'message' => 'FHPL Token generation failed']);
}
}
$token = $tokenResponse['data']['access_token'];
$url = getenv('FHPL_BASE_URL') . "/api/GetEnrollmentDetailsPolicy";
$headers = [
"Authorization: Bearer " . $token,
"Content-Type: application/json"
];
$startIndex = 0;
$range = 100;
$allMembers = [];
while (true) {
$body = [
"UserName" => getenv('FHPL_USER_NAME'),
"Password" => getenv('FHPL_PASSWORD'),
"PolicyNumber" => $policyNo,
"StartIndex" => $startIndex,
"Range" => $range
];
log_message('error', "TPA ID PULL | API parems " . json_encode([$url, 'POST', $headers, $body]));
$response = call_third_party_api($url, 'POST', $headers, $body);
if (($response['status'] ?? false) !== true) {
log_message('error', 'FHPL API FAILED | response: ' . json_encode($response));
break;
}
if (
!isset($response['data']) ||
!is_array($response['data']) ||
count($response['data']) === 0 ||
!array_is_list($response['data']) // PHP 8+ safe check
) {
// STOP when data is not a valid list
break;
}
$allMembers = array_merge($allMembers, $response['data']);
// Move to next page
$startIndex += $range;
}
if(empty($allMembers))
{
// update file table status after the tpa id failed to update
if (isset($requestData['file_id']) && !empty($requestData['file_id'])) {
$file_model = new BatchFileModel();
$file_model->where('id', $requestData['file_id'])->set('status', 'failed-8')->update();
log_message('error', "Files table status updated for the file id : {$requestData['file_id']}");
} else {
log_message('error', "Failed to update file table status.");
}
log_message('error', 'TPA ID PULL API FAILED | API failed: Empty menber data for this pull request');
if($function_calling_type == "job"){
return ['status' => false, 'message' => 'API call failed', 'data' => 'Empty menber data for this pull request'];
}else{
return $this->respond(['status' => false, 'message' => 'API call failed', 'data' => 'Empty menber data for this pull request']);
}
}
// dd($allMembers);
//save API data as JSON for analysis
$json = json_encode($allMembers, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
// $filename = time() . '.json';
$filePath = WRITEPATH . 'tmp/'.time().'_'.$requestData['file_id'].'.json';
file_put_contents($filePath, $json);
//call a job for dump JSON data to DB
$job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'saveFhplAPIData', 'payload' => [ 'file_id' => $requestData['file_id'],'json_file_path' => $filePath ]]);
// ================= MATCHING LOGIC =================
$employeePolicyModel = new EmployeePolicyModel();
$employeePolicyData = $employeePolicyModel
->join('employees', 'employees.id = employee_polices.employee_id')
->where('employee_polices.client_policy_id', $client_policy_id)
->where('employee_polices.tpa_id IS NULL')
->findAll();
$updated = 0;
foreach ($employeePolicyData as $policy) {
$hasMatchForThisPolicy = false;
foreach ($allMembers as $m) {
if (
strtolower(trim($policy['name'])) === strtolower(trim($m['EMPLOYEE_NAME'] ?? '')) &&
($policy['emp_code'] ?? '') == ($m['EMPLOYEE_ID'] ?? '') &&
strtolower($policy['relationship']) === strtolower($m['RELATION'] ?? '')
) {
$hasMatchForThisPolicy = true;
$sql = "UPDATE employee_polices SET tpa_id = ? WHERE id = ?";
$this->db->query($sql, [$m['TPA_TPADETAIL_ID'], $policy['emp_policy_id']]);
// for e-card send
if(strtolower(trim($policy['relationship'])) == 'self'){
$employee_policy_ids[] = $policy['emp_policy_id'];
}
if ($this->db->affectedRows() > 0) {
$updated++;
log_message('error', "✅ Updated tpa_id={$m['TPA_TPADETAIL_ID']} for emp_policy_id={$policy['emp_policy_id']} policy={$policyNo}");
} else {
log_message('error', "⚠️ No update (already set or not matched) for emp_policy_id={$policy['emp_policy_id']} policy={$policyNo}");
}
}
}
}
// 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,
];
$batch_file_success = 'partially success';
log_message(
'error',
"❌ No match for Nhance = " . json_encode($nhanceSideData)
);
}
// send e-card
if(!empty($employee_policy_ids)){
log_message('error', "sendMailForDownloadingECard JOB PUSHED.");
Jobs::addJob(['job_name' => 'sendMailForDownloadingECard', 'payload' => ['ids' => $employee_policy_ids, 'client_policy_id' => $client_policy_id]]);
}
// update file table status after the tpa id successfully updated
if (isset($requestData['file_id']) && !empty($requestData['file_id'])) {
$file_model = new BatchFileModel();
$file_model->where('id', $requestData['file_id'])->set('status', $batch_file_success)->update();
log_message('error', "Files table status updated for the file id : {$requestData['file_id']}");
} else {
log_message('error', "Failed to update file table status.");
}
$totalCount = count($allMembers);
log_message('error', "TPA ID PULL SUCCESS | completed. Total fetched={$totalCount}, updated={$updated}");
if($function_calling_type == "job"){
return [
'status' => true,
'message' => 'Updated successfully',
'total_fetched' => $totalCount,
'total_updated' => $updated
];
}else{
return $this->respond([
'status' => true,
'message' => 'Updated successfully',
'total_fetched' => $totalCount,
'total_updated' => $updated
]);
}
} catch (\Throwable $th) {
// update file table status after the tpa id failed to update
if (isset($requestData['file_id']) && !empty($requestData['file_id'])) {
$file_model = new BatchFileModel();
$file_model->where('id', $requestData['file_id'])->set('status', 'failed-8')->update();
log_message('error', "Files table status updated for the file id : {$requestData['file_id']}");
} else {
log_message('error', "Failed to update file table status.");
}
$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,
];
log_message('error', 'Exception thrown while calling GetBenefDetails API: ' . json_encode($errorData));
if($function_calling_type == "job"){
return ['status' => false, 'message' => 'API call failed', 'data' => $errorData];
}else{
return $this->respond(['status' => false, 'message' => 'API call failed', 'data' => $errorData]);
}
}
}
// public function FhplGetBenefDetails($requestData = null)
// {
// helper('api');
// $policyNo = $requestData['policy_no'] ?? "10/12/2025/16/17";
// $client_policy_id = $requestData['client_policy_id'] ?? 0;
// // Generate FHPL Token
// $tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
// if (empty($tokenResponse['data']['access_token'])) {
// return $this->response->setJSON(['status' => false,'message' => 'FHPL Token generation failed']);
// }
// $token = $tokenResponse['data']['access_token'];
// $url = getenv('FHPL_BASE_URL')."/api/GetEnrollmentDetailsPolicy";
// $headers = [
// "Authorization: Bearer ".$token,
// "Content-Type: application/json"
// ];
// $startIndex = 0;
// $range = 100;
// $allMembers = [];
// do {
// $body = [
// "UserName" => getenv('FHPL_USER_NAME'),
// "Password" => getenv('FHPL_PASSWORD'),
// "PolicyNumber" => $policyNo,
// "StartIndex" => $startIndex,
// "Range" => $range
// ];
// $response = call_third_party_api($url,'POST',$headers,$body);
// dd($response);
// if(empty($response['data']['Members'])){
// break;
// }
// $allMembers = array_merge($allMembers,$response['data']['Members']);
// $startIndex += $range;
// } while($startIndex < ($response['data']['Total'] ?? 0));
// dd($allMembers);
// // Now same matching logic you already have
// $employeePolicyModel = new EmployeePolicyModel();
// $employeePolicyData = $employeePolicyModel
// ->join('employees','employees.id=employee_polices.employee_id')
// ->where('employee_polices.client_policy_id',$client_policy_id)
// ->where('employee_polices.tpa_id IS NULL')
// ->findAll();
// $updated = 0;
// foreach($employeePolicyData as $policy){
// foreach($allMembers as $m){
// if(
// strtolower(trim($policy['name']))==strtolower(trim($m['Name'])) &&
// $policy['emp_code']==$m['MemberID'] &&
// strtolower($policy['relationship'])==strtolower($m['Relation'])
// ){
// $this->db->table('employee_polices')
// ->where('id',$policy['emp_policy_id'])
// ->update(['tpa_id'=>$m['UHID']]);
// $updated++;
// }
// }
// }
// return [
// 'status'=>true,
// 'total_fetched'=>count($allMembers),
// 'updated'=>$updated
// ];
// }
public function syncFhplClaimsToNhance()
{
helper('api');
// Generate FHPL Token
$tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
if (empty($tokenResponse['data']['access_token'])) {
return $this->response->setJSON(['status' => false,'message' => 'FHPL Token generation failed']);
}
$token = $tokenResponse['data']['access_token'];
$url = getenv('FHPL_BASE_URL')."/api/GetTPA_ClaimsDetails";
$headers = [
"Authorization: Bearer ".$token,
"Content-Type: application/json"
];
$policies = $this->db->table('client_policy')
->where('tpa_id',$this->fhplTpaId)
->get()->getResultArray();
$finalResult=[];
foreach($policies as $policy){
$body = [
"UserName" => getenv('FHPL_USER_NAME'),
"Password" => getenv('FHPL_PASSWORD'),
"PolicyNumber" => $policy['policy_no'],
"Fromdate" => $policy['policy_start_date'],
"Todate" => $policy['policy_end_date']
];
$response = call_third_party_api($url,'POST',$headers,$body);
if(!empty($response['data'])){
$finalResult = array_merge($finalResult,$response['data']);
}
}
// Insert / update ticket_master same way you already do for MediAssist
foreach($finalResult as $row){
$status = $row['CLAIM_STATUS'];
$map = [
"Under Process"=>5,
"Paid"=>11,
"Rejected"=>8,
"Approved"=>8
];
$claimStatus = $map[$status] ?? 1;
$this->db->table('ticket_master')->insert([
'policy_no'=>$row['POLICY_NO'],
'claim_number'=>$row['CLAIM_ID'],
'tpa_claim_id'=>$row['CLAIM_ID'],
'emp_code'=>$row['EMPLOYEE_NO'],
'insured_name'=>$row['PATIENT_NAME'],
'claim_amount'=>$row['CLAIM_AMOUNT'],
'hospital_name'=>$row['HOSPITAL_NAME'],
'doa'=>$row['DATE_OF_ADMISSION'],
'dod'=>$row['DATE_OF_DISCHARGE'],
'claim_status_id'=>$claimStatus,
'tpa_id'=>$this->fhplTpaId
]);
}
return ['status'=>true,'total'=>count($finalResult)];
}
}

View File

@ -116,7 +116,7 @@ class GoogleDriveController extends BaseController
} }
//if not in cache then get it from grdrive //if not in cache then get it from grdrive
$client = $this->clientModel->find($client_id); $client = $this->clientModel->find((int)$client_id);
$clientShortName = $client['short_name']; // Assuming short_name is the column for client's short name $clientShortName = $client['short_name']; // Assuming short_name is the column for client's short name
} }
else if($client_policy_id) else if($client_policy_id)

View File

@ -0,0 +1,785 @@
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use App\Models\BatchFileModel;
use App\Models\EmployeePolicyModel;
use App\Models\TpaApiDataModel;
use App\Models\ClientPolicyModel;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\API\ResponseTrait;
use App\Controllers\Jobs;
class HealthIndiaApiController extends BaseController
{
use ResponseTrait;
protected $db;
protected $healthIndiaTpaId;
public function __construct()
{
$this->db = \Config\Database::connect();
$this->healthIndiaTpaId = getenv('HEALTH_INDIA_PRIMARY_KEY_CONSTANT');
}
public function generateAuthToken()
{
$url = getenv('HEALTH_INDIA_TOKEN_URL'); // https://software.healthindiatpa.com/HIITPABROKERAPI/JWT/GenerateJWTAuth
// Basic Authentication credentials
$username = getenv('HEALTH_INDIA_USERNAME'); // /MU4gwfBYC71M1QnczasegH0vPM5IMbESO4iy4wbUrQ=
$password = getenv('HEALTH_INDIA_PASSWORD'); // KoVi+w2WGA+ET6fHN3kdBamHNsDKbA+kUtuF++4jWcg=
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_USERPWD => $username . ':' . $password,
CURLOPT_POSTFIELDS => '{}',
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Accept: application/json',
],
CURLOPT_TIMEOUT => 30,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
log_message('error', 'HEALTH_INDIA TOKEN GENERATION FAILED | Error: ' . curl_error($ch));
curl_close($ch);
return $this->response->setJSON([
'status' => false,
'error' => curl_error($ch),
]);
}
curl_close($ch);
$responseData = json_decode($response, true);
if ($httpCode === 200 && isset($responseData['status']) && $responseData['status'] === true) {
log_message('error', 'HEALTH_INDIA TOKEN GENERATION SUCCESS | Token: ' . ($responseData['result'][0]['access_token'] ?? 'N/A'));
} else {
log_message('error', 'HEALTH_INDIA TOKEN GENERATION FAILED | Response: ' . $response);
}
return $this->response->setJSON([
'status' => $httpCode === 200,
'http_code' => $httpCode,
'data' => $responseData,
]);
}
public function SubmitClaim($claimId = 515)
{
helper('api');
log_message('error', 'TPA CLAIM PUSH HEALTH_INDIA | Started for claimId: ' . $claimId);
$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_pin_code as hospitalCode,
tm.hospital_name as hospitalName,
tm.hospital_address as hospitalAddress,
tm.hospital_phone_no as hospitalNumber,
tm.claim_amount as claimedAmount,
tm.tpa_no as memberId,
tm.claim_description as ailmentDescription,
cp.policy_no as policyNumber,
e.emp_code as employeeCode,
tn.note as disease,
cf.url as filePath,
tm.claim_type as claimType,
tm.claim_type as benefitType
')
->join('employees e', 'e.id = tm.emp_id', 'left')
->join('client_policy cp', 'tm.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();
// dd($data);
if (!$data) {
log_message('error', "TPA CLAIM PUSH FAILED HEALTH_INDIA | claimId: {$claimId} - Claim not found");
return;
}
if ($data['filePath'] == null) {
log_message('error', "TPA CLAIM PUSH FAILED HEALTH_INDIA | claimId: {$claimId} - File Missing");
return;
}
// Build absolute file path
$filename = basename($data['filePath']);
$pdfPath = WRITEPATH . 'uploads/claim_files/' . $filename;
if (!file_exists($pdfPath)) {
log_message('error', "TPA CLAIM PUSH FAILED HEALTH_INDIA | claimId: {$claimId} - PDF not found on server at path: {$pdfPath}");
return;
}
// Convert PDF to Base64
$fileContent = base64_encode(file_get_contents($pdfPath));
// Generate Health India Token
$tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
if (empty($tokenResponse['data']['result'][0]['access_token'])) {
log_message('error', "TPA CLAIM PUSH FAILED HEALTH_INDIA | claimId: {$claimId} - Token generation failed");
return;
}
$token = $tokenResponse['data']['result'][0]['access_token'];
// Map claim type: Reimbursement or Cashless
$claimTypeMap = [
'reimbursement' => 'Reimbursement',
'cashless' => 'Cashless',
];
$mappedClaimType = $claimTypeMap[strtolower($data['claimType'] ?? 'reimbursement')] ?? 'Reimbursement';
// Map benefit type: IPD or OPD
$benefitTypeMap = [
'ipd' => 'IPD',
'opd' => 'OPD',
];
$mappedBenefitType = $benefitTypeMap[strtolower($data['benefitType'] ?? 'ipd')] ?? 'IPD';
// Build Health India Claim Submission Request (API Section 5)
$body = [
"policY_NUMBER" => $data['policyNumber'],
"employeE_CODE" => $data['employeeCode'],
"membeR_ID" => $data['memberId'],
"claiM_TYPE" => $mappedClaimType,
"benefiT_TYPE" => $mappedBenefitType,
"claimeD_AMOUNT" => (string) $data['claimedAmount'],
"datE_OF_ADMISSION" => date('Y-m-d', strtotime($data['admissionDate'])),
"ailmenT_DESCRIPTION" => $data['ailmentDescription'] ?? 'NA',
"hospitaL_CODE" => $data['hospitalCode'] ?? '',
"hospitaL_NAME" => $data['hospitalName'] ?? '',
"hospitaL_ADDRESS" => $data['hospitalAddress'] ?? '',
"hospitaL_NUMBER" => $data['hospitalNumber'] ?? '',
"pdF_BYTES" => [$fileContent]
];
// $body = [
// 'policY_NUMBER' => '141600_POLICY_AWAITED',
// 'employeE_CODE' => 'DECP000',
// 'membeR_ID' => '10662420SE',
// 'claiM_TYPE' => 'Reimbursement',
// 'benefiT_TYPE' => 'IPD',
// 'claimeD_AMOUNT' => '102',
// 'datE_OF_ADMISSION' => '2026-01-19',
// 'ailmenT_DESCRIPTION' => 'Fever',
// 'hospitaL_CODE' => '100900',
// 'hospitaL_NAME' => 'Test',
// 'hospitaL_ADDRESS' => 'YEst',
// 'hospitaL_NUMBER' => '2233445566',
// "pdF_BYTES" => [$fileContent]
// ];
$url = getenv('HEALTH_INDIA_BASE_URL') . "/Intimation/GetClaimIntimation";
$headers = [
"Authorization: Bearer " . $token,
"Content-Type: application/json"
];
log_message('error', 'TPA CLAIM PUSH HEALTH_INDIA | claimId: ' . $claimId . ' | URL: ' . $url );
$response = call_third_party_api($url, 'POST', $headers, $body);
dd($response);
log_message('error', 'TPA CLAIM PUSH HEALTH_INDIA RESPONSE | claimId: ' . $claimId . ' | response: ' . json_encode($response));
if ($response['status'] != true) {
log_message('error', 'TPA CLAIM PUSH FAILED HEALTH_INDIA | claimId: ' . $claimId . ' | response: ' . json_encode($response));
$this->db->table('ticket_master')
->where('id', $claimId)
->update(['tpa_push_response' => json_encode($response)]);
return;
}
if ($response['status'] === true && !empty($response['data']['result'][0]['ccn'])) {
$ccn = $response['data']['result'][0]['ccn'];
$ccnExt = $response['data']['result'][0]['ccN_EXT'] ?? '0';
$this->db->table('ticket_master')
->where('id', $claimId)
->update([
'claim_number' => $ccn,
'tpa_claim_id' => $ccn,
'tpa_claim_push_reference_no' => $ccn . '(' . $ccnExt . ')',
'updated_at' => date('Y-m-d H:i:s')
]);
log_message('error', 'TPA CLAIM PUSH SUCCESS HEALTH_INDIA | claimId: ' . $claimId . ' | CCN: ' . $ccn . ' | CCN_EXT: ' . $ccnExt);
} else {
log_message('error', 'TPA CLAIM PUSH HEALTH_INDIA API SUCCESS BUT CCN EMPTY | claimId: ' . $claimId . ' | response: ' . json_encode($response));
return;
}
return;
}
public function ClaimDetail($claimId = null)
{
helper('api');
log_message('error', 'CLAIM STATUS HEALTH_INDIA | Started for claimId: ' . $claimId);
$ticket = $this->db->table('ticket_master tm')
->select("tm.id, tm.tpa_claim_id as ccn, cp.policy_no, cp.policy_start_date, cp.policy_end_date, tm.emp_code")
->join('client_policy cp', 'tm.client_policy_id=cp.id')
->where('tm.id', $claimId)
->get()->getRowArray();
if (!$ticket) {
log_message('error', 'CLAIM STATUS FAILED HEALTH_INDIA | claimId: ' . $claimId . ' - Invalid claim');
return ['status' => false, 'message' => 'Invalid claim'];
}
// Generate Health India Token
$tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
if (empty($tokenResponse['data']['result'][0]['access_token'])) {
log_message('error', 'CLAIM STATUS FAILED HEALTH_INDIA | claimId: ' . $claimId . ' - Token generation failed');
return ['status' => false, 'message' => 'Token generation failed'];
}
$token = $tokenResponse['data']['result'][0]['access_token'];
$url = getenv('HEALTH_INDIA_BASE_URL') . "/Claims/GetClaims";
// Using claim number wise approach (Section 7.3 - option 3)
$body = [
"policY_NUMBER" => $ticket['policy_no'],
"CCN" => $ticket['ccn'],
"CCN_EXT" => "0"
];
$headers = [
"Authorization: Bearer " . $token,
"Content-Type: application/json"
];
log_message('error', 'CLAIM STATUS HEALTH_INDIA | claimId: ' . $claimId . ' | Request: ' . json_encode($body));
$response = call_third_party_api($url, 'POST', $headers, $body);
log_message('error', 'CLAIM STATUS HEALTH_INDIA | claimId: ' . $claimId . ' | Response: ' . json_encode($response));
if (empty($response['data']['result'][0])) {
log_message('error', 'CLAIM STATUS FAILED HEALTH_INDIA | claimId: ' . $claimId . ' | Empty response data');
return ['status' => false, 'message' => 'API call failed.', 'data' => $response];
}
$claimData = $response['data']['result'][0];
$status = $claimData['claiM_STATUS'] ?? null;
// Status mapping based on API documentation
$map = [
"Under Process" => 5,
"Pending for Bill Entry" => 5,
"Query" => 4,
"Paid" => 11,
"Rejected" => 8,
"Approved" => 8,
"Outstanding" => 5,
];
if ($status != null && isset($map[$status])) {
$this->db->table('ticket_master')
->where('id', $claimId)
->update([
'claim_status_id' => $map[$status],
'tpa_claim_status' => $status
]);
log_message('error', "CLAIM STATUS SUCCESS HEALTH_INDIA | Updated claimId: {$claimId} with status: {$status}");
} else {
log_message('error', "CLAIM STATUS HEALTH_INDIA | claimId: {$claimId} | Unknown status: {$status}");
}
return [
'status' => true,
'message' => 'Claim status updated.',
'updated_status' => $status,
'api_response' => $response
];
}
public function ClaimStatusUpdate()
{
helper('api');
log_message('error', 'CLAIM STATUS UPDATE BULK HEALTH_INDIA | Started');
$tickets = $this->db->table('ticket_master tm')
->select("tm.id, tm.tpa_claim_id, cp.policy_no")
->join('client_policy cp', 'tm.client_policy_id=cp.id')
->where('tm.tpa_claim_id IS NOT NULL')
->where('cp.tpa_id', $this->healthIndiaTpaId)
->get()->getResultArray();
$count = 0;
foreach ($tickets as $t) {
$this->ClaimDetail($t['id']);
$count++;
}
log_message('error', 'CLAIM STATUS UPDATE BULK HEALTH_INDIA | Completed | Updated: ' . $count);
return $this->response->setJSON(['status' => true, 'updated' => $count]);
}
public function EcardRequest($employeeId = null, $policyNo = null, $memberId = null)
{
helper('api');
log_message('error', "ECARD REQUEST HEALTH_INDIA | Started | employeeId: {$employeeId} | policyNo: {$policyNo} | memberId: {$memberId}");
// Generate Health India Token
$tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
if (empty($tokenResponse['data']['result'][0]['access_token'])) {
log_message('error', "ECARD REQUEST FAILED HEALTH_INDIA | employeeId: {$employeeId} | policyNo: {$policyNo} | Message: Token generation failed");
return null;
}
$token = $tokenResponse['data']['result'][0]['access_token'];
// API Section 3.3 - Individual member e-card
$url = getenv('HEALTH_INDIA_BASE_URL') . "/Member/GetMemberEcard";
$body = [
"policY_NUMBER" => $policyNo,
"employeE_CODE" => $employeeId,
"membeR_ID" => $memberId
];
$headers = [
"Authorization: Bearer " . $token,
"Content-Type: application/json"
];
log_message('error', 'ECARD REQUEST HEALTH_INDIA | Request: ' . json_encode($body));
$response = call_third_party_api($url, 'POST', $headers, $body);
log_message('error', 'ECARD REQUEST HEALTH_INDIA | Response: ' . json_encode($response));
if (($response['status'] ?? false) !== true) {
log_message('error', 'ECARD REQUEST FAILED HEALTH_INDIA | response: ' . json_encode($response));
return null;
}
if (empty($response['data']['result'][0])) {
log_message('error', 'ECARD REQUEST FAILED HEALTH_INDIA | Empty data | response: ' . json_encode($response));
return null;
}
$apiData = $response['data']['result'][0];
if (($apiData['message'] ?? '') === 'SUCCESS') {
$ecardUrl = $apiData['membeR_ECARD'] ?? '';
if (!empty($ecardUrl)) {
log_message('error', "ECARD REQUEST SUCCESS HEALTH_INDIA | employeeId: {$employeeId} | policyNo: {$policyNo} | memberId: {$memberId} | ecardUrl: {$ecardUrl}");
return $ecardUrl;
}
}
log_message('error', 'ECARD REQUEST FAILED HEALTH_INDIA | response: ' . json_encode($response));
return null;
}
public function HealthIndiaGetBenefDetails($requestData = null)
{
$function_calling_type = $requestData['return_type'] ?? 'job';
try {
helper('api');
$policyNo = $requestData['policy_no'] ?? '141600_POLICY_AWAITED';
$client_policy_id = $requestData['client_policy_id'] ?? 6473;
if (empty($policyNo)) {
log_message('error', 'TPA ID PULL HEALTH_INDIA | policy_no missing in request');
if ($function_calling_type == "job") {
return ['status' => false, 'message' => 'policy_no required'];
} else {
return $this->respond(['status' => false, 'message' => 'policy_no required']);
}
}
if (empty($client_policy_id)) {
log_message('error', 'TPA ID PULL HEALTH_INDIA | client_policy_id missing in request');
if ($function_calling_type == "job") {
return ['status' => false, 'message' => 'client_policy_id required'];
} else {
return $this->respond(['status' => false, 'message' => 'client_policy_id required']);
}
}
log_message('error', "TPA ID PULL HEALTH_INDIA | called for policy_no: {$policyNo}, client_policy_id: {$client_policy_id}");
// Fetch file download dates
// $batchFiles = $this->db->table('batch_files f')
// ->select("f.created_at")
// ->where('f.client_policy_id', $client_policy_id)
// ->where('f.insurer_or_tpa', 'tpa')
// ->where('f.actions', 'export')
// ->get()
// ->getResultArray();
// if (empty($batchFiles)) {
// log_message('error', 'TPA ID PULL FAILED HEALTH_INDIA | batchFiles is empty for this tpa id pull request');
// if ($function_calling_type == "job") {
// return ['status' => false, 'message' => 'batchFiles not found'];
// } else {
// return $this->respond(['status' => false, 'message' => 'batchFiles not found']);
// }
// }
// Generate Health India Token
$tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
if (empty($tokenResponse['data']['result'][0]['access_token'])) {
log_message('error', 'TPA ID PULL HEALTH_INDIA | Token generation failed');
if ($function_calling_type == "job") {
return ['status' => false, 'message' => 'Token generation failed'];
} else {
return $this->respond(['status' => false, 'message' => 'Token generation failed']);
}
}
$token = $tokenResponse['data']['result'][0]['access_token'];
// API Section 2.3 - Bulk Enrolment data Fetch
$url = getenv('HEALTH_INDIA_BASE_URL') . "/Enrollment/GetEnrollmentData";
$headers = [
"Authorization: Bearer " . $token,
"Content-Type: application/json"
];
$body = [
"policY_NUMBER" => $policyNo
];
log_message('error', "TPA ID PULL HEALTH_INDIA | API params: " . json_encode(['url' => $url, 'method' => 'POST', 'body' => $body]));
$response = call_third_party_api($url, 'POST', $headers, $body);
dd($response);
log_message('error', "TPA ID PULL HEALTH_INDIA | API Response: " . json_encode($response));
if (($response['status'] ?? false) !== true) {
log_message('error', 'HEALTH_INDIA API FAILED | response: ' . json_encode($response));
// update file table status after the tpa id failed to update
if (isset($requestData['file_id']) && !empty($requestData['file_id'])) {
$file_model = new BatchFileModel();
$file_model->where('id', $requestData['file_id'])->set('status', 'failed-8')->update();
log_message('error', "Files table status updated for the file id: {$requestData['file_id']}");
} else {
log_message('error', "Failed to update file table status.");
}
if ($function_calling_type == "job") {
return ['status' => false, 'message' => 'API call failed', 'data' => $response];
} else {
return $this->respond(['status' => false, 'message' => 'API call failed', 'data' => $response]);
}
}
if (
!isset($response['data']['result']) ||
!is_array($response['data']['result']) ||
count($response['data']['result']) === 0
) {
log_message('error', 'TPA ID PULL API FAILED HEALTH_INDIA | Empty member data for this pull request');
// update file table status after the tpa id failed to update
if (isset($requestData['file_id']) && !empty($requestData['file_id'])) {
$file_model = new BatchFileModel();
$file_model->where('id', $requestData['file_id'])->set('status', 'failed-8')->update();
log_message('error', "Files table status updated for the file id: {$requestData['file_id']}");
} else {
log_message('error', "Failed to update file table status.");
}
if ($function_calling_type == "job") {
return ['status' => false, 'message' => 'API call failed', 'data' => 'Empty member data for this pull request'];
} else {
return $this->respond(['status' => false, 'message' => 'API call failed', 'data' => 'Empty member data for this pull request']);
}
}
$allMembers = $response['data']['result'];
// Save API data as JSON for analysis
$json = json_encode($allMembers, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
$filePath = WRITEPATH . 'tmp/' . time() . '_' . $requestData['file_id'] . '.json';
file_put_contents($filePath, $json);
log_message('error', "TPA ID PULL HEALTH_INDIA | Saved JSON to: {$filePath}");
// Call a job for dump JSON data to DB
$job_details = new Jobs();
$r = Jobs::addJob([
'job_name' => 'saveHealthIndiaAPIData',
'payload' => [
'file_id' => $requestData['file_id'],
'json_file_path' => $filePath
]
]);
log_message('error', "TPA ID PULL HEALTH_INDIA | Job added for saving API data");
// ================= MATCHING LOGIC =================
$employeePolicyModel = new EmployeePolicyModel();
$employeePolicyData = $employeePolicyModel
->join('employees', 'employees.id = employee_polices.employee_id')
->where('employee_polices.client_policy_id', $client_policy_id)
->where('employee_polices.tpa_id IS NULL')
->findAll();
$updated = 0;
$batch_file_success = 'success';
$employee_policy_ids = [];
foreach ($employeePolicyData as $policy) {
$hasMatchForThisPolicy = false;
foreach ($allMembers as $m) {
// Match based on: employee name, employee code, and relation
if (
strtolower(trim($policy['name'])) === strtolower(trim($m['insured_Name'] ?? '')) &&
($policy['emp_code'] ?? '') == ($m['employeeCode'] ?? '') &&
strtolower($policy['relationship']) === strtolower($m['relation'] ?? '')
) {
$hasMatchForThisPolicy = true;
$sql = "UPDATE employee_polices SET tpa_id = ? WHERE id = ?";
$this->db->query($sql, [$m['memberId'], $policy['emp_policy_id']]);
// For e-card send
if (strtolower(trim($policy['relationship'])) == 'self') {
$employee_policy_ids[] = $policy['emp_policy_id'];
}
if ($this->db->affectedRows() > 0) {
$updated++;
log_message('error', "✅ HEALTH_INDIA | Updated tpa_id={$m['memberId']} for emp_policy_id={$policy['emp_policy_id']} policy={$policyNo}");
} else {
log_message('error', "⚠️ HEALTH_INDIA | No update (already set or not matched) for emp_policy_id={$policy['emp_policy_id']} policy={$policyNo}");
}
}
}
// Handle NO MATCH for this policy
if (!$hasMatchForThisPolicy) {
$nhanceSideData = [
'name' => $policy['name'] ?? null,
'emp_code' => $policy['emp_code'] ?? null,
'relationship' => $policy['relationship'] ?? null,
'gender' => $policy['gender'] ?? null,
'dob' => $policy['dob'] ?? null,
];
$batch_file_success = 'partially success';
log_message('error', "❌ HEALTH_INDIA | No match for Nhance = " . json_encode($nhanceSideData));
}
}
// Send e-card
if (!empty($employee_policy_ids)) {
log_message('error', "HEALTH_INDIA | sendMailForDownloadingECard JOB PUSHED.");
Jobs::addJob([
'job_name' => 'sendMailForDownloadingECard',
'payload' => [
'ids' => $employee_policy_ids,
'client_policy_id' => $client_policy_id
]
]);
}
// Update file table status after the tpa id successfully updated
if (isset($requestData['file_id']) && !empty($requestData['file_id'])) {
$file_model = new BatchFileModel();
$file_model->where('id', $requestData['file_id'])->set('status', $batch_file_success)->update();
log_message('error', "Files table status updated for the file id: {$requestData['file_id']} with status: {$batch_file_success}");
} else {
log_message('error', "Failed to update file table status.");
}
$totalCount = count($allMembers);
log_message('error', "TPA ID PULL SUCCESS HEALTH_INDIA | completed. Total fetched={$totalCount}, updated={$updated}");
if ($function_calling_type == "job") {
return [
'status' => true,
'message' => 'Updated successfully',
'total_fetched' => $totalCount,
'total_updated' => $updated
];
} else {
return $this->respond([
'status' => true,
'message' => 'Updated successfully',
'total_fetched' => $totalCount,
'total_updated' => $updated
]);
}
} catch (\Throwable $th) {
// Update file table status after the tpa id failed to update
if (isset($requestData['file_id']) && !empty($requestData['file_id'])) {
$file_model = new BatchFileModel();
$file_model->where('id', $requestData['file_id'])->set('status', 'failed-8')->update();
log_message('error', "Files table status updated for the file id: {$requestData['file_id']}");
} else {
log_message('error', "Failed to update file table status.");
}
$errorData = [
'message' => $th->getMessage(),
'file' => $th->getFile(),
'line' => $th->getLine(),
'code' => $th->getCode(),
'trace' => $th->getTraceAsString(),
'trace_array' => $th->getTrace(),
'function' => $th->getTrace()[0]['function'] ?? null,
'class' => $th->getTrace()[0]['class'] ?? null,
];
log_message('error', 'Exception thrown while calling HealthIndiaGetBenefDetails API: ' . json_encode($errorData));
if ($function_calling_type == "job") {
return ['status' => false, 'message' => 'API call failed', 'data' => $errorData];
} else {
return $this->respond(['status' => false, 'message' => 'API call failed', 'data' => $errorData]);
}
}
}
public function syncHealthIndiaClaimsToNhance()
{
helper('api');
log_message('error', 'SYNC CLAIMS HEALTH_INDIA | Started');
// Generate Health India Token
$tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
if (empty($tokenResponse['data']['result'][0]['access_token'])) {
log_message('error', 'SYNC CLAIMS FAILED HEALTH_INDIA | Token generation failed');
return $this->response->setJSON(['status' => false, 'message' => 'Token generation failed']);
}
$token = $tokenResponse['data']['result'][0]['access_token'];
$url = getenv('HEALTH_INDIA_BASE_URL') . "/ClaimsMIS/GetClaimsMIS";
$headers = [
"Authorization: Bearer " . $token,
"Content-Type: application/json"
];
$policies = $this->db->table('client_policy')
->where('tpa_id', $this->healthIndiaTpaId)
->get()->getResultArray();
$finalResult = [];
foreach ($policies as $policy) {
$body = [
"policY_NUMBER" => $policy['policy_no']
];
log_message('error', 'SYNC CLAIMS HEALTH_INDIA | Fetching for policy: ' . $policy['policy_no']);
$response = call_third_party_api($url, 'POST', $headers, $body);
if (!empty($response['data']['result'])) {
$finalResult = array_merge($finalResult, $response['data']['result']);
log_message('error', 'SYNC CLAIMS HEALTH_INDIA | Fetched ' . count($response['data']['result']) . ' claims for policy: ' . $policy['policy_no']);
}
}
log_message('error', 'SYNC CLAIMS HEALTH_INDIA | Total claims fetched: ' . count($finalResult));
// Insert / update ticket_master
$insertedCount = 0;
foreach ($finalResult as $row) {
$status = $row['Claim_Status'] ?? 'Under Process';
$map = [
"Under Process" => 5,
"Pending for Bill Entry" => 5,
"Paid" => 11,
"Rejected" => 8,
"Approved" => 8,
"Outstanding" => 5,
];
$claimStatus = $map[$status] ?? 1;
// Check if claim already exists
$existing = $this->db->table('ticket_master')
->where('tpa_claim_id', $row['CLAIM_NUMBER'])
->get()->getRowArray();
if (!$existing) {
$this->db->table('ticket_master')->insert([
'policy_no' => $row['Policy_No'] ?? '',
'claim_number' => $row['CLAIM_NUMBER'] ?? '',
'tpa_claim_id' => $row['CLAIM_NUMBER'] ?? '',
'emp_code' => $row['Employee_Code'] ?? '',
'insured_name' => $row['PATIENT_NAME'] ?? '',
'claim_amount' => $row['INTIMATED_AMOUNT'] ?? 0,
'hospital_name' => $row['HOSPITAL_NAME'] ?? '',
'doa' => !empty($row['DATEOF_ADMISSION']) ? date('Y-m-d', strtotime($row['DATEOF_ADMISSION'])) : null,
'dod' => !empty($row['DATEOF_DISCHARGE']) ? date('Y-m-d', strtotime($row['DATEOF_DISCHARGE'])) : null,
'claim_status_id' => $claimStatus,
'tpa_id' => $this->healthIndiaTpaId,
'created_at' => date('Y-m-d H:i:s')
]);
$insertedCount++;
log_message('error', 'SYNC CLAIMS HEALTH_INDIA | Inserted claim: ' . ($row['CLAIM_NUMBER'] ?? 'N/A'));
} else {
log_message('error', 'SYNC CLAIMS HEALTH_INDIA | Skipped existing claim: ' . ($row['CLAIM_NUMBER'] ?? 'N/A'));
}
}
log_message('error', 'SYNC CLAIMS HEALTH_INDIA | Completed | Total: ' . count($finalResult) . ' | Inserted: ' . $insertedCount);
return $this->response->setJSON([
'status' => true,
'total' => count($finalResult),
'inserted' => $insertedCount
]);
}
}

View File

@ -86,33 +86,64 @@ class ICICILombardController extends AdminController
// dd($body); // dd($body);
// $body = [
// "PolicyNumber" => "4016/PPN/A/O/53167743/00/000",
// "CDBGAccountNumber" => "CD-MUM-0026",
// "CorrelationId" => "550e8400-e29b-41d4-a716-446655440016",
// "MemberDetails" => [
// [
// "MemberEmpId" => "EMPID3625562",
// "DOJ" => "21-MAR-2019",
// "InsuredName" => "Jeeva",
// "DOB" => "7-JUL-1993",
// "Relationship" => "SELF",
// "Gender" => "MALE",
// "DOC" => '28-Oct-2025',
// "SumInsured" => "500000",
// "EmailId" => "Jeeva@GMAIL.COM",
// "FlagStatus" => "A"
// ],
// [
// "MemberEmpId" => "EMPID3625562",
// "DOJ" => "21-MAR-2019",
// "InsuredName" => "Muthu",
// "DOB" => "8-AUG-1970",
// "Relationship" => "MOTHER",
// "Gender" => "FEMALE",
// "DOC" => '28-Oct-2025',
// "EmailId" => "Muthu@GMAIL.COM",
// "FlagStatus" => "A"
// ],
// ]
// ];
$body = [ $body = [
"PolicyNumber" => "4016/PPN/A/O/53167743/00/000", "PolicyNumber" => "4016/PPN/A/O/53185987/00/000",
"CDBGAccountNumber" => "CD-MUM-0026", "CDBGAccountNumber" => "CD-MUM-0026",
"CorrelationId" => "550e8400-e29b-41d4-a716-446655440012", "CorrelationId" => "550e8400-e29b-41d4-a716-446655440021",
"MemberDetails" => [ "MemberDetails" => [
[ [
"MemberEmpId" => "EMPID3625559", "MemberEmpId" => "EMPID3625564",
"DOJ" => "21-MAR-2019", "DOJ" => "21-MAR-2019",
"InsuredName" => "Gowtham", "InsuredName" => "Jeeva",
"DOB" => "7-JUL-1993", "DOB" => "7-JUL-1993",
"Relationship" => "SELF", "Relationship" => "SELF",
"Gender" => "MALE", "Gender" => "MALE",
"DOC" => '2025-10-27', "DOC" => '18-Nov-2025',
"SumInsured" => "400000", "SumInsured" => "500000",
"EmailId" => "Gowtham@GMAIL.COM", "EmailId" => "Jeeva@GMAIL.COM",
"FlagStatus" => "A" "FlagStatus" => "A"
], ],
[ [
"MemberEmpId" => "EMPID3625559", "MemberEmpId" => "EMPID3625564",
"DOJ" => "21-MAR-2019", "DOJ" => "21-MAR-2019",
"InsuredName" => "Lavanya", "InsuredName" => "Muthu",
"DOB" => "8-AUG-1970", "DOB" => "8-AUG-1970",
"Relationship" => "MOTHER", "Relationship" => "MOTHER",
"Gender" => "FEMALE", "Gender" => "FEMALE",
"DOC" => '2025-10-27', "DOC" => '18-Nov-2025',
"SumInsured" => "400000", "EmailId" => "Muthu@GMAIL.COM",
"EmailId" => "Lavanya@GMAIL.COM",
"FlagStatus" => "A" "FlagStatus" => "A"
], ],
] ]
@ -148,9 +179,9 @@ class ICICILombardController extends AdminController
// dd($headers); // dd($headers);
$body = [ $body = [
"PolicyNumber" => "4016/PPN/A/O/53167743/00/000", "PolicyNumber" => "4016/PPN/A/O/53185987/00/000",
"BatchId" => "3672146", "BatchId" => "3727144",
"CorrelationId" => "550e8400-e29b-41d4-a716-446655440012" "CorrelationId" => "550e8400-e29b-41d4-a716-446655440021"
]; ];
$response = call_third_party_api($url, 'POST', $headers, $body, true); $response = call_third_party_api($url, 'POST', $headers, $body, true);
@ -182,9 +213,9 @@ class ICICILombardController extends AdminController
]; ];
$body = [ $body = [
"PolicyNumber" => "4016/PPN/A/O/53167743/00/000", "PolicyNumber" => "4016/PPN/A/O/53185987/00/000",
"IMID" => "3672145", "IMID" => "201580517901",
"CorrelationId" => "550e8400-e29b-41d4-a716-446655440011" "CorrelationId" => "550e8400-e29b-41d4-a716-446655440020"
]; ];
$response = call_third_party_api($url, 'POST', $headers, $body, true); $response = call_third_party_api($url, 'POST', $headers, $body, true);

View File

@ -155,6 +155,14 @@ class JobWorker extends AdminController
'type' => 'CC', // Handler Category 'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\TicketServiceController', 'handler' => 'App\Controllers\TicketServiceController',
], ],
'tpaClaimDumpImporter' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\TicketServiceController',
],
'tpaClaimDumpToTicketMasterImporters' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\TicketServiceController',
],
'excelMultieventFileFormateValidation' => [ 'excelMultieventFileFormateValidation' => [
'type' => 'CC', // Handler Category 'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmployeeMultiEventServiceController', 'handler' => 'App\Controllers\EmployeeMultiEventServiceController',
@ -183,6 +191,10 @@ class JobWorker extends AdminController
'type' => 'CC', // Handler Category 'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\VidalApiController', 'handler' => 'App\Controllers\VidalApiController',
], ],
'FhplGetBenefDetails' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\FhplApiController',
],
'bdsDumpExcelFileFormatValidation' => [ 'bdsDumpExcelFileFormatValidation' => [
'type' => 'CC', // Handler Category 'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\PolicyTransactionController', 'handler' => 'App\Controllers\PolicyTransactionController',
@ -201,6 +213,14 @@ class JobWorker extends AdminController
'bulkGenerateEcardAndStoreinS3' => [ 'bulkGenerateEcardAndStoreinS3' => [
'type' => 'CC', // Handler Category 'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmployeeController', 'handler' => 'App\Controllers\EmployeeController',
],
'bulkEcardDownloadAsZipFromS3' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmployeeController',
],
'getEmployeeEcardFromTmpFolderAndZipToS3' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmployeeController',
] ]
]; ];

View File

@ -378,7 +378,154 @@ class LeadsController extends BaseController
private function prepareLeadData() private function prepareLeadData()
{ {
$data = $this->request->getPost(); $rules = [
'lead_type' => [
'rules' => 'integer',
'errors' => ['required' => 'Lead Type is required']
],
'issuer' => [
'rules' => 'required',
'errors' => ['required' => 'Issuer is required']
],
'entity_type_id' => [
'rules' => 'required',
'errors' => ['required' => 'Entity Type is required']
],
'client_name' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9_ -]+$/]',
'errors' => [
'required' => 'Client Name is required',
'regex_match' => 'Client Name only letters, numbers and characters _ - and space are allowed'
]
],
'client_short_name' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9_-]+$/]',
'errors' => ['required' => 'Client Short Name is required','regex_match' => 'Client Short Name only letters, numbers and characters _ and - are allowed']
],
'gst' => [
'rules' => 'required',
'errors' => ['required' => 'GST Number is required']
],
'gst' => [
'rules' => 'required|regex_match[/^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/]',
'errors' => [
'required' => 'GST Number is required.',
'regex_match' => 'Invalid GST format. Example: 22AAAAA0000A1Z5'
]
],
'branch_name' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9\s_-]+$/]|min_length[3]',
'errors' => [
'required' => 'Branch Name is required.',
'regex_match' => 'Branch Name can only contain letters, numbers, spaces, - and _.',
'min_length' => 'Branch Name must be at least 3 characters long.'
]
],
'branch_code' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9_-]+$/]',
'errors' => [
'required' => 'Branch Code is required.',
'regex_match' => 'Branch Code can only contain letters, numbers, - and _.'
]
],
'contact_person_name' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9_ -]+$/]',
'errors' => [
'required' => 'Contact Person Name is required',
'regex_match' => 'Contact person name only letters, numbers and spaces, - and _.'
]
],
'contact_person_mobile' => [
'rules' => 'required',
'rules' => 'required|regex_match[/^[0-9]+$/]',
'errors' => ['required' => 'Contact Person Mobile is required' ,
'regex_match' => 'Contact Person Mobile Only numbers'
]
],
'contact_person_email' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/]',
'errors' => [
'required' => 'Contact Person Email address is required.',
'regex_match' => 'Please enter a valid email format (e.g., name@domain.com).'
]
// 'rules' => 'required|valid_email|regex_match[/^[a-zA-Z0-9_-]+$/]',
// 'regex_match' => 'Contact Person Email Only letters, numbers and characters _ - @ . are allowed'
],
'salse_person_id' => [
'rules' => 'required',
'errors' => ['required' => 'Sales Person is required']
],
'status' => [
'rules' => 'required',
'errors' => ['required' => 'Status is required']
]
];
$request_data = $this->request->getPost();
$data = sanitizeInputArrayAdvanced($request_data);
if (isset($data['lead_form_type']) && (int)$data['lead_form_type'] === 2) {
$rules['client_type'] = [
'rules' => 'required',
'errors' => ['required' => 'Client Type is required']
];
$rules['policy_type_id'] = [
'rules' => 'required',
'errors' => ['required' => 'Policy Type is required']
];
$rules['policy_start_date'] = [
'rules' => 'required',
'errors' => ['required' => 'Date of Commencement is required']
];
$rules['policy_end_date'] = [
'rules' => 'required',
'errors' => ['required' => 'Date of Expiry is required']
];
}
// 1. MANUALLY VALIDATE FILES BEFORE PROCESSING
// $allFiles = $this->request->getFiles();
// foreach ($allFiles as $inputName => $files) {
// // If it's a single file, wrap it in an array to use the same logic
// $fileArray = is_array($files) ? $files : [$files];
// foreach ($fileArray as $index => $file) {
// if ($file->isValid() && !$file->hasMoved()) {
// $extension = strtolower($file->getExtension());
// // Logic: index 0 is Excel only, others are mixed
// if ($index === 0) {
// $allowed = ['xls', 'xlsx'];
// } else {
// $allowed = ['xls', 'xlsx', 'pdf', 'jpg', 'jpeg', 'png'];
// }
// if (!in_array($extension, $allowed)) {
// // Return 400 Error immediately
// return $this->response->setStatusCode(400)->setJSON([
// 'status' => false,
// 'message' => 'Input validation failed',
// 'code' => 400,
// 'errors' => [
// $inputName => "File " . ($index + 1) . " has an invalid extension ($extension). Allowed: " . implode(',', $allowed)
// ]
// ]);
// }
// }
// }
// }
if (!$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Input validation failed',
'code' => 400,
'errors' => $this->validator->getErrors()
]);
}
$data['client_type'] = 1; $data['client_type'] = 1;
$data['pan'] = ""; $data['pan'] = "";
@ -1136,7 +1283,7 @@ class LeadsController extends BaseController
// 12. Conditional rendering based on lead_form_type // 12. Conditional rendering based on lead_form_type
if ($lead_data['lead_form_type'] == 1) { if ($lead_data['lead_form_type'] == 1) {
$data['demogrphy_html_data'] = $this->generateDemographyDataTable(['lead_id' => $id]); // $data['demogrphy_html_data'] = $this->generateDemographyDataTable(['lead_id' => $id]);
$this->loadLayout('view_rfq.php', $data); $this->loadLayout('view_rfq.php', $data);
} else if ($lead_data['lead_form_type'] == 2) { } else if ($lead_data['lead_form_type'] == 2) {
$data['occupancy'] = $this->occupancyModel->findAll(); $data['occupancy'] = $this->occupancyModel->findAll();
@ -2538,7 +2685,7 @@ class LeadsController extends BaseController
public function calculateMembersDemography($params, $returnType = null) public function calculateMembersDemography($params, $returnType = null)
{ {
$lead_id = $params['lead_id']; $lead_id = $params['lead_id'];
$lead_data = $this->leadsModel->find($lead_id); $lead_data = $this->leadsModel->find((int)$lead_id);
$file_name_with_path = WRITEPATH . "/uploads/lead_files/" . $lead_data['file_name']; $file_name_with_path = WRITEPATH . "/uploads/lead_files/" . $lead_data['file_name'];
if (!$lead_data) { if (!$lead_data) {
@ -2999,7 +3146,7 @@ class LeadsController extends BaseController
// print_r($params); die; // print_r($params); die;
$lead_id = $params['lead_id']; $lead_id = (int)$params['lead_id'];
$file_type = $params['file_type']; //rfq or qcr $file_type = $params['file_type']; //rfq or qcr
$recipient_type = $params['recipient_type']; //insurer or client or internal or placement $recipient_type = $params['recipient_type']; //insurer or client or internal or placement
$recipient_mail = $params['recipient_mail']; // - only primary key of contacts $recipient_mail = $params['recipient_mail']; // - only primary key of contacts
@ -3033,7 +3180,7 @@ class LeadsController extends BaseController
if ($recipient_type === 'placement') { if ($recipient_type === 'placement') {
$lead_data = $this->leadsModel->find($lead_id); $lead_data = $this->leadsModel->find((int)$lead_id);
$data = []; $data = [];
@ -5320,7 +5467,7 @@ class LeadsController extends BaseController
public function handleMemberDataGPATotalSumInsurerFromExcel($params) public function handleMemberDataGPATotalSumInsurerFromExcel($params)
{ {
$lead_id = $params['lead_id']; $lead_id = $params['lead_id'];
$lead_data = $this->leadsModel->find($lead_id); $lead_data = $this->leadsModel->find((int)$lead_id);
// dd($lead_data); // dd($lead_data);
$file_name_with_path = WRITEPATH . "/uploads/lead_files/" . $lead_data['file_name']; $file_name_with_path = WRITEPATH . "/uploads/lead_files/" . $lead_data['file_name'];
// dd($file_name_with_path); // dd($file_name_with_path);
@ -5384,8 +5531,13 @@ class LeadsController extends BaseController
return []; return [];
} }
public function generateDemographyDataTable($param) public function generateDemographyDataTable($param = [])
{ {
if ($this->request !== null) {
$param['lead_id'] = $this->request->getGet('lead_id');
}
$returnData = $this->calculateMembersDemography($param, "internal"); $returnData = $this->calculateMembersDemography($param, "internal");
$html = ""; $html = "";
@ -5431,6 +5583,14 @@ class LeadsController extends BaseController
} }
} }
if ($this->request !== null) {
if(!empty($html)){
return $this->respond(['status' => true, 'data' => $html], 200);
}else{
return $this->respond(['status' => false, 'data' => $html], 200);
}
}
return $html; return $html;
} }
@ -5726,7 +5886,7 @@ class LeadsController extends BaseController
$first_file_name = $isFirstField ? 'Member List' : ''; $first_file_name = $isFirstField ? 'Member List' : '';
$member_data_link = $isFirstField ? $sample_dwn_link : ''; $member_data_link = $isFirstField ? $sample_dwn_link : '';
$read_only = $isFirstField ? 'readonly' : ''; $read_only = $isFirstField ? 'readonly' : '';
$accept = $isFirstField ? '.xls,.xlsx' : ''; $accept = $isFirstField ? '.xls,.xlsx' : '.xls,.xlsx,.pdf,.jpg,.jpeg,.png';
$displayIndex = $index + 1; $displayIndex = $index + 1;
$html .= ' $html .= '

View File

@ -11,6 +11,8 @@ use CodeIgniter\API\ResponseTrait;
use App\Models\UserModel; use App\Models\UserModel;
use App\Models\AuthHistoryModel; use App\Models\AuthHistoryModel;
use App\Libraries\AuthLogout;
class LoginController extends BaseController class LoginController extends BaseController
{ {
use ResponseTrait; use ResponseTrait;
@ -45,7 +47,7 @@ class LoginController extends BaseController
$user_team = $UserModel->getUserTeamsByUserID($user->id); $user_team = $UserModel->getUserTeamsByUserID($user->id);
// dd($user_team); // dd($user_team);
session()->regenerate(true);
$session_data = [ $session_data = [
'isLoggedIn' => True , 'isLoggedIn' => True ,
'userid' => $user->id, 'userid' => $user->id,
@ -56,9 +58,12 @@ class LoginController extends BaseController
$path = getenv('cookie.Path'); $path = getenv('cookie.Path');
$domain = getenv('cookie.Domain'); $domain = getenv('cookie.Domain');
$https = getenv('ccokie.secure'); $https = getenv('ccokie.secure');
setcookie('session_data', json_encode($session_data), time() + 12 * 60 * 60, $path, $domain, $https, true); // setcookie('session_data', json_encode($session_data), time() + 12 * 60 * 60, $path, $domain, $https, true);
set_session_data($session_data); set_session_data($session_data);
// Bind session to device
set_session_data(['fingerprint' => generateFingerprint()]);
log_message('error', 'Set The UserId : `'. $user->id .'` in Session'); log_message('error', 'Set The UserId : `'. $user->id .'` in Session');
log_message('error', 'User Login Sucessfully'); log_message('error', 'User Login Sucessfully');
@ -91,14 +96,23 @@ class LoginController extends BaseController
public function logout() public function logout()
{ {
$path = getenv('cookie.Path'); // $path = getenv('cookie.Path');
session()->destroy(); // session()->regenerate(true);
// setcookie('session_data', '', time() - 3600, $path); // session()->destroy();
$path = getenv('cookie.Path');
$domain = getenv('cookie.Domain'); // $path = getenv('cookie.Path');
$https = getenv('cookie.secure'); // $domain = getenv('cookie.Domain');
setcookie('session_data',null, time() -3600, $path, $domain, $https, true); // $https = getenv('cookie.secure');
return redirect()->to(base_url('login'));
// setcookie('session_data',null, time() - 42000, $path, $domain, $https, true);
// // return redirect()->to(base_url('login'));
// return redirect()->to(base_url('login'))
// ->setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
// ->setHeader('Pragma', 'no-cache')
// ->setHeader('Expires', 'Sat, 26 Jul 1997 05:00:00 GMT');
return AuthLogout::logout();
} }
public function getUserDeviceInfo($userId, $type_of_user) public function getUserDeviceInfo($userId, $type_of_user)

File diff suppressed because it is too large Load Diff

View File

@ -138,6 +138,9 @@ class MediAssistApiController extends BaseController
if($response['status'] != true){ if($response['status'] != true){
log_message('error', 'TPA CLAIM PUSH FAILED | claimId: '.$claimId.' | response: '.json_encode($response)); log_message('error', 'TPA CLAIM PUSH FAILED | claimId: '.$claimId.' | response: '.json_encode($response));
$this->db->table('ticket_master')
->where('id',$claimId)
->update([ 'tpa_push_response' => json_encode($response) ]);
return; return;
} }
@ -515,7 +518,7 @@ class MediAssistApiController extends BaseController
->getRowArray(); ->getRowArray();
if (!$ticket) { if (!$ticket) {
return $this->response->setJSON(['status' => false,'message' => 'Invalid Claim ID' ]); return ['status' => false,'message' => 'Invalid Claim ID' ];
} }
// REQUEST BODY // REQUEST BODY
@ -545,8 +548,6 @@ class MediAssistApiController extends BaseController
} }
// $body = [ // $body = [
// "policyNo" => "97000063250400000031", // "policyNo" => "97000063250400000031",
// "startDate" => "01/11/2025", // "startDate" => "01/11/2025",
@ -565,11 +566,7 @@ class MediAssistApiController extends BaseController
if ($response['status'] != true || empty($response['data']['claimsData'][0])) { if ($response['status'] != true || empty($response['data']['claimsData'][0])) {
log_message('error', 'CLAIM STATUS FAILED | for ticket ID: ' . $claimId.' | response: '.json_encode($response)); log_message('error', 'CLAIM STATUS FAILED | for ticket ID: ' . $claimId.' | response: '.json_encode($response));
return $this->response->setJSON([ return ['status' => false,'message' => 'API call failed.','data' => $response ];
'status' => false,
'message' => 'API call failed.',
'data' => $response
]);
} }
// Extract claim status // Extract claim status
@ -631,12 +628,7 @@ class MediAssistApiController extends BaseController
// LOG UPDATE // LOG UPDATE
log_message('error', "CLAIM STATUS SUCCESS | Updated ticket ID $claimId with claim status: $currentStatus"); log_message('error', "CLAIM STATUS SUCCESS | Updated ticket ID $claimId with claim status: $currentStatus");
return $this->response->setJSON([ return ['status' => true,'message' => 'Claim status updated.','updated_status' => $currentStatus,'api_response' => $response];
'status' => true,
'message' => 'Claim status updated.',
'updated_status' => $currentStatus,
'api_response' => $response
]);
} }
public function IRSubmission($claimId = null) // 585 this id for test public function IRSubmission($claimId = null) // 585 this id for test
@ -1106,7 +1098,9 @@ class MediAssistApiController extends BaseController
$ticket = $this->db->table('ticket_master tm')->select("tm.id") $ticket = $this->db->table('ticket_master tm')->select("tm.id")
->where('tm.policy_no', $value['policY_NUMBER']) ->where('tm.policy_no', $value['policY_NUMBER'])
->where('tm.emp_code', $value['employeE_NO']) ->where('tm.emp_code', $value['employeE_NO'])
->where('tm.claim_number', $value['tpA_CLAIM_NO']) ->where('tm.claim_amount', $value['estimateD_CLAIM_AMOUNT'])
->where('tm.doa', $this->mediDate($value['datE_OF_ADMISSION'] ?? null))
// ->where('tm.claim_number', $value['tpA_CLAIM_NO'])
->get() ->get()
->getRowArray(); ->getRowArray();
@ -1173,6 +1167,7 @@ class MediAssistApiController extends BaseController
") ")
->join('client_rm', 'client_rm.client_id = cp.client_id AND client_rm.level = 3', 'left') ->join('client_rm', 'client_rm.client_id = cp.client_id AND client_rm.level = 3', 'left')
->where('cp.policy_no', $value['policY_NUMBER']) ->where('cp.policy_no', $value['policY_NUMBER'])
->orderBy('client_rm.id','DESC')
->get() ->get()
->getRowArray(); ->getRowArray();
@ -1181,12 +1176,14 @@ class MediAssistApiController extends BaseController
e.id as emp_id, e.id as emp_id,
e.emp_code , e.emp_code ,
e2.id as insured_emp_id, e2.id as insured_emp_id,
ep.tpa_id as tpa_no,
") ")
->join( ->join(
'employees e2', 'employees e2',
"e2.emp_code = e.emp_code AND e2.relationship = ".$this->db->escape($relationship), "e2.emp_code = e.emp_code AND e2.relationship = ".$this->db->escape($relationship),
'left' 'left'
) )
->join( 'employee_polices ep', "ep.employee_id = e2.id ", 'left' )
->where('e.emp_code', $value['employeE_NO']) ->where('e.emp_code', $value['employeE_NO'])
->where('e.relationship', 'self') ->where('e.relationship', 'self')
->get() ->get()
@ -1212,6 +1209,7 @@ class MediAssistApiController extends BaseController
// Employee / Insured // Employee / Insured
'emp_id' => $employee['emp_id'] ?? null, 'emp_id' => $employee['emp_id'] ?? null,
'insured_emp_id' => $employee['insured_emp_id'] ?? null, 'insured_emp_id' => $employee['insured_emp_id'] ?? null,
'tpa_no' => $employee['tpa_no'] ?? null,
'emp_code' => $value['employeE_NO'] ?? null, 'emp_code' => $value['employeE_NO'] ?? null,
'emp_name' => $value['employeE_NAME'] ?? null, 'emp_name' => $value['employeE_NAME'] ?? null,
'insured_name' => $value['beneficiarY_NAME'] ?? null, 'insured_name' => $value['beneficiarY_NAME'] ?? null,
@ -1250,9 +1248,8 @@ class MediAssistApiController extends BaseController
$this->db->table('ticket_master')->insert($claimData); $this->db->table('ticket_master')->insert($claimData);
log_message( log_message(
'info', 'error',
'New claim created | Policy: '.$claimData['policy_no']. 'New claim created | Policy: '.$claimData['policy_no'].' | Claim: '.$claimData['claim_number']
' | Claim: '.$claimData['claim_number']
); );
} }

View File

@ -52,6 +52,7 @@ class NotificationController extends AdminController
// Create Or Update the Notification // Create Or Update the Notification
public function createNotification() public function createNotification()
{ {
$form_data['template_name'] = $this->camelCaseToSnakeCase($this->request->getPost('template_name')); $form_data['template_name'] = $this->camelCaseToSnakeCase($this->request->getPost('template_name'));
$form_data['subject'] = $this->request->getPost('subject'); $form_data['subject'] = $this->request->getPost('subject');
$form_data['mail_content'] = $this->request->getPost('mailContent'); $form_data['mail_content'] = $this->request->getPost('mailContent');
@ -93,7 +94,8 @@ class NotificationController extends AdminController
'member_ecard_mail_btn', 'member_ecard_mail_btn',
'member_review_and_summary_mail_btn', 'member_review_and_summary_mail_btn',
'account_maneger_summary_mail_btn', 'account_maneger_summary_mail_btn',
'client_hr_summary_mail_btn' 'client_hr_summary_mail_btn',
'hr_cd_insufficient_balance_mail_btn',
]; ];
$data = []; $data = [];
$emptyTemplate = []; $emptyTemplate = [];

View File

@ -147,7 +147,7 @@ class PayoutController extends BaseController
$summary_data = $this->invoiceModel->utrSummary($invoice_id); $summary_data = $this->invoiceModel->utrSummary($invoice_id);
if($summary_data['invoice_amount'] == $summary_data['total_utr_amount']){ if($summary_data['invoice_amount'] == $summary_data['total_utr_amount']){
$sql = "UPDATE partner_invoice SET payout_status = 2 WHERE id = ?"; $sql = "UPDATE partner_invoice SET payout_status = 2 WHERE id = ?";
db_connect()->query($sql, [$invoice_id]); db_connect()->query($sql, [(int)$invoice_id]);
} }
return $this->respond(['status' => true, 'code' => 200, 'data' => $payout_edit_data, "message" => "UTR successfully updated"], 200); return $this->respond(['status' => true, 'code' => 200, 'data' => $payout_edit_data, "message" => "UTR successfully updated"], 200);
@ -166,7 +166,7 @@ class PayoutController extends BaseController
$summary_data = $this->invoiceModel->utrSummary($invoice_id); $summary_data = $this->invoiceModel->utrSummary($invoice_id);
if($summary_data['invoice_amount'] == $summary_data['total_utr_amount']){ if($summary_data['invoice_amount'] == $summary_data['total_utr_amount']){
$sql = "UPDATE partner_invoice SET payout_status = 2 WHERE id = ?"; $sql = "UPDATE partner_invoice SET payout_status = 2 WHERE id = ?";
db_connect()->query($sql, [$invoice_id]); db_connect()->query($sql, [(int)$invoice_id]);
} }
return $this->respond(['status' => true, 'code' => 200, 'data' => $payout_data, "message" => "UTR added successfully"], 200); return $this->respond(['status' => true, 'code' => 200, 'data' => $payout_data, "message" => "UTR added successfully"], 200);
@ -281,13 +281,17 @@ class PayoutController extends BaseController
//... Payout-invoice Mapping - Save/update/soft Delete/Hard Delete Data //... Payout-invoice Mapping - Save/update/soft Delete/Hard Delete Data
public function saveInvoice() public function saveInvoice()
{ {
$json = $this->request->getJSON(true); $raw_json = $this->request->getJSON(true);
// print_rr($json);die();
if (!$json) { // 1. Check if the JSON was actually valid/parsed before sanitizing
if (is_null($raw_json)) {
return $this->response->setJSON(['error' => 'Invalid JSON','message' => 'Invalid JSON received.'])->setStatusCode(400); return $this->response->setJSON(['error' => 'Invalid JSON','message' => 'Invalid JSON received.'])->setStatusCode(400);
} }
// 2. Sanitize the data
$json = sanitizeInputArrayAdvanced($raw_json);
// 3. Now you can safely use $json (even if it is an empty array)
$id = $json['invoice_id'] ?? null; $id = $json['invoice_id'] ?? null;
try { try {
@ -335,7 +339,7 @@ class PayoutController extends BaseController
$invoiceData = [ $invoiceData = [
'invoice_no' => $json['invoice_no'], 'invoice_no' => $json['invoice_no'],
'agent_id' => $json['agent_id'], // 'agent_id' => $json['agent_id'] ?? null,
'invoice_date' => $json['invoice_date'], 'invoice_date' => $json['invoice_date'],
'invoice_amount' => $json['invoice_amount'], 'invoice_amount' => $json['invoice_amount'],
]; ];

View File

@ -309,7 +309,7 @@
'format' => null, 'format' => null,
'allowed_values' => null, 'allowed_values' => null,
'custom' => 'check_agent_exist', 'custom' => 'check_agent_exist',
'params' => ['row', 'agent_data'] 'params' => ['row', 'pos_data']
], ],
'base_premium' => [ 'base_premium' => [
@ -917,12 +917,152 @@
// policy Transaction Create function start // policy Transaction Create function start
public function createInceptionPolicy() public function createInceptionPolicy()
{ {
$post_data = $this->request->getPost() ?? []; $post_data = $this->request->getPost();
$rules = [
// ==========================================
// 1. CLIENT SECTION (5 Fields)
// ==========================================
'client_id' => ['label' => 'Client','rules' => 'required','errors' => ['required' => 'Please select a Client.']],
'client_type' => ['label' => 'Client Type','rules' => 'required','errors' => ['required' => 'Client Type must be selected.']],
'industry_type' => ['label' => 'Industry','rules' => 'permit_empty','errors' => []], // No errors needed for permit_empty unless adding other rules
'gst_no' => ['label' => 'GST Number','rules' => 'permit_empty|regex_match[/^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/]','errors' => ['alpha_numeric' => 'GST Number should only contain letters and numbers.','regex_match' => 'Invalid GST format. (Example: 22AAAAA0000A1Z5)']],
'pan_no' => ['label' => 'PAN Number','rules' => 'permit_empty|regex_match[/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/]','errors' => ['alpha_numeric' => 'PAN Number should only contain letters and numbers.','regex_match' => 'Invalid PAN format. (Example: ABCDE1234F)']],
// ==========================================
// 2. PRE-SALES SECTION (3 Fields)
// ==========================================
'lead_source' => ['label' => 'Lead Source', 'rules' => 'permit_empty', 'errors' => []],
'opportunity_id' => ['label' => 'Opportunity', 'rules' => 'permit_empty', 'errors' => []],
'quotation_ref' => ['label' => 'Quotation Ref', 'rules' => 'permit_empty', 'errors' => []],
// ==========================================
// 3. POLICY DOCUMENT (2 Fields)
// ==========================================
'policy_copy' => ['label' => 'Policy Copy', 'rules' => 'permit_empty', 'errors' => []],
'proposal_form' => ['label' => 'Proposal Form', 'rules' => 'permit_empty', 'errors' => []],
// ==========================================
// 4. VEHICLE DOCUMENT (2 Fields)
// ==========================================
'rc_copy' => ['label' => 'RC Copy', 'rules' => 'permit_empty', 'errors' => []],
'inspection_report' => ['label' => 'Inspection Report', 'rules' => 'permit_empty', 'errors' => []],
// ==========================================
// 5. SALES SECTION (12 Fields)
// ==========================================
'base_policy' => ['label' => 'Base Policy', 'rules' => 'permit_empty','errors' => []],
'policy_no' => ['label' => 'Policy Number', 'rules' => 'required|regex_match[/^[a-zA-Z0-9\/_-]+$/]',
'errors' => [
'required' => 'Policy Number is Must.',
'regex_match' => 'Policy Number can only contain letters, numbers, and symbols like / - or _'
]],
'policy_issue_date' => ['label' => 'Issue Date', 'rules' => 'required|valid_date[Y-m-d]|regex_match[/^\d{4}-\d{2}-\d{2}$/]',
'errors' => [
'required' => 'Policy Issue Date is required.',
'valid_date' => 'Please provide a valid Policy Issue Date.',
'regex_match' => 'The Policy Issue Date format is incorrect. '
]],
'month' => ['label' => 'Issue Month', 'rules' => 'required','errors' => [
'required' => 'Please select or enter the Policy Issue Month.'
]],
'policy_start_date' => ['label' => 'D.O.C',
'rules' => 'required|valid_date[Y-m-d]|regex_match[/^\d{4}-\d{2}-\d{2}$/]',
'errors' => [
'required' => 'D.O.C (Start Date) is required.',
'valid_date' => 'Please provide a valid D.O.C date.',
'regex_match' => 'The D.O.C date format is incorrect. '
]],
'policy_end_date' => ['label' => 'D.O.E', 'rules' => 'required|valid_date[Y-m-d]|regex_match[/^\d{4}-\d{2}-\d{2}$/]','errors' => [
'required' => 'D.O.E (Expiry Date) is required.',
'valid_date' => 'Please provide a valid D.O.E date.',
'regex_match' => 'The D.O.E date format is incorrect. '
]],
'emp_count' => ['label' => 'No of Insured', 'rules' => 'permit_empty|numeric','errors' => [
'numeric' => 'No of Insured must contain only numbers.'
]],
'dependent_count' => ['label' => 'No of Dependents', 'rules' => 'permit_empty|numeric','errors' => [
'numeric' => 'No of Dependents must contain only numbers.'
]],
'installment' => ['label' => 'Installment', 'rules' => 'permit_empty','errors' => []],
'installment_data' => ['label' => 'Installment Data', 'rules' => 'permit_empty','errors' => []],
'co_share' => ['label' => 'CoP Yes', 'rules' => 'permit_empty','errors' => []],
'bro_payable_by' => ['label' => 'Remuneration Pay By', 'rules' => 'permit_empty','errors' => []],
'renewal_date' => ['label' => 'Renewal Date', 'rules' => 'required|valid_date[Y-m-d]|regex_match[/^\d{4}-\d{2}-\d{2}$/]','errors' => [
'required' => 'Renewal Date is required.',
'valid_date' => 'Please provide a valid Renewal Date.',
'regex_match' => 'The Renewal Date format is incorrect. '
]],
'sales_generated_by' => ['label' => 'Sales Generated By', 'rules' => 'permit_empty','errors' => [
// 'required' => 'Please select the person who generated this sale.'
]],
'serviced_by' => ['label' => 'Serviced By', 'rules' => 'permit_empty','errors' => [
// 'required' => 'Please select the service person for this policy.'
]],
'pos_id' => ['label' => 'POS', 'rules' => 'permit_empty','errors' => []],
// ==========================================
// 6. PREMIUM DETAILS (Array Fields - 25 Fields)
// Use .* because these come from the dynamic table
// ==========================================
'follow_insurer_id.*' => ['label' => 'Insurer', 'rules' => 'required','errors' => ['required' => 'Please select an Insurer.']],
'co_share_type.*' => ['label' => 'Is Leader', 'rules' => 'permit_empty','errors' => []],
'cd_ac_no_for_child.*' => ['label' => 'CD Acc No', 'rules' => 'permit_empty','errors' => []],
'cd_current_balance.*' => ['label' => 'CD Amount', 'rules' => 'permit_empty','errors' => []],
'follower_policy_no.*' => ['label' => 'Follower Policy No', 'rules' => 'permit_empty','errors' => []],
'calc_policy_issue_date.*' => ['label' => 'Policy Issue Date', 'rules' => 'required','errors' => [ 'required' => 'Policy Issue Date is required' ]],
'co_share_per.*' => ['label' => 'Co-Share %', 'rules' => 'permit_empty|decimal','errors' => ['decimal' => 'Co-Share % must be a valid decimal.']],
'non_comm_per_amt.*' => ['label' => 'Non-Comm Premium', 'rules' => 'permit_empty|decimal','errors' => ['decimal' => 'Amount must be numeric.']],
'base_premium.*' => ['label' => 'Base Premium', 'rules' => 'permit_empty|regex_match[/^-?\d+(\.\d+)?$/]|differs[0]',
'errors' => [
'regex_match' => 'Base Premium must be a valid positive or negative number.',
'differs' => 'Base Premium cannot be zero.'
]],
'tp_premium.*' => ['label' => 'TP Premium', 'rules' => 'permit_empty|decimal','errors' => ['decimal' => 'TP Premium must be numeric.']],
'ter_premium.*' => ['label' => 'TEP Premium', 'rules' => 'permit_empty|decimal','errors' => ['decimal' => 'TEP Premium must be numeric.']],
'co_premium.*' => ['label' => 'Co-Premium', 'rules' => 'permit_empty|decimal','errors'=> ['decimal' => 'Co-Premium must be numeric.']],
'co_tp_premium.*' => ['label' => 'Co-TP Premium', 'rules' => 'permit_empty|decimal','errors' => ['decimal' => 'Co-TP Premium must be numeric.']],
'co_ter_premium.*' => ['label' => 'Co-TEP Premium', 'rules' => 'permit_empty|decimal','errors' => ['decimal' => 'Co-TEP Premium must be numeric.']],
'cgst.*' => ['label' => 'CGST', 'rules' => 'permit_empty|decimal','errors' => ['decimal' => 'CGST must be numeric.']],
'sgst.*' => ['label' => 'SGST', 'rules' => 'permit_empty|decimal','errors' => ['decimal' => 'SGST must be numeric.']],
'igst.*' => ['label' => 'IGST', 'rules' => 'permit_empty|decimal','errors' => ['decimal' => 'IGST must be numeric.']],
'gst_amount.*' => ['label' => 'GST Amount', 'rules' => 'permit_empty|decimal|greater_than[0]','errors' => [
'decimal' => 'GST Amount must be a valid numeric value.',
'greater_than' => 'GST Amount cannot be zero; please enter a value greater than 0.'
]],
'stamp_duty.*' => ['label' => 'Stamp Duty', 'rules' => 'permit_empty|decimal','errors' => ['decimal' => 'Stamp Duty must be numeric.']],
'total.*' => ['label' => 'Total', 'rules' => 'permit_empty|decimal','errors' => ['decimal' => 'Total must be a numeric value.']],
'agreed_bp.*' => ['label' => 'Agreed BP %', 'rules' => 'permit_empty|decimal','errors' => ['decimal' => 'Agreed BP % must be numeric.']],
'agreed_tp.*' => ['label' => 'Agreed TP %', 'rules' => 'permit_empty|decimal','errors' => ['decimal' => 'Agreed TP % must be numeric.']],
'agreed_ter.*' => ['label' => 'Agreed TEP %', 'rules' => 'permit_empty|decimal','errors' => ['decimal' => 'Agreed TEP % must be numeric.']],
'agreed_amount.*' => ['label' => 'Agreed Amount', 'rules' => 'permit_empty|decimal','errors' => ['decimal' => 'Agreed Amount must be numeric.']],
'actual_bp_amt.*' => ['label' => 'Actual BP Amount', 'rules' => 'permit_empty|decimal','errors' => ['decimal' => 'Actual BP Amount must be numeric.']],
'actual_tp_amt.*' => ['label' => 'Actual TP Amount', 'rules' => 'permit_empty|decimal','errors' => ['decimal' => 'Actual TP Amount must be numeric.']],
'actual_tep_amt.*' => ['label' => 'Actual TEP Amount', 'rules' => 'permit_empty|decimal','errors' => ['decimal' => 'Actual TEP Amount must be numeric.']],
'actual_bp_per.*' => ['label' => 'Actual BP %', 'rules' => 'permit_empty|decimal','errors' => ['decimal' => 'Actual BP % must be numeric.']],
'actual_tp_per.*' => ['label' => 'Actual TP %', 'rules' => 'permit_empty|decimal','errors' => ['decimal' => 'Actual TP % must be numeric.']],
'actual_tep_per.*' => ['label' => 'Actual TEP %', 'rules' => 'permit_empty|decimal','errors' => ['decimal' => 'Actual TEP % must be numeric.']],
'actual_bp_brokerage_amt.*'=> ['label' => 'BP Remuneration', 'rules' => 'permit_empty|decimal','errors' => ['decimal' => 'BP Remuneration must be numeric.']],
'actual_tp_brokerage_amt.*'=> ['label' => 'TP Remuneration', 'rules' => 'permit_empty|decimal','errors' => ['decimal' => 'TP Remuneration must be numeric.']],
'actual_tep_brokerage_amt.*'=>['label' => 'TEP Remuneration', 'rules' => 'permit_empty|decimal','errors' => ['decimal' => 'TEP Remuneration must be numeric.']],
'exp_amt.*' => ['label' => 'Expected Amount', 'rules' => 'permit_empty|decimal','errors' => ['decimal'=> 'The Expected Amount field must contain a valid number.']]
];
if (!$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Input validation failed',
'code' => 400,
'errors' => $this->validator->getErrors()
]);
}
$post_data = $post_data ? sanitizeInputArrayAdvanced($post_data) : [];
$this->myLogger->logme('error', 'Policy Trancaction form data : '. json_encode($post_data)); $this->myLogger->logme('error', 'Policy Trancaction form data : '. json_encode($post_data));
$id = $this->request->getPost('id'); $id = $post_data['id'] ?? null;
$data = $this->preparePolicyData(); $data = $this->preparePolicyData();
$data['cd_ac_pk'] = $this->request->getPost('cd_ac_no'); $data['cd_ac_pk'] = $post_data['cd_ac_no'];
$data['issuer'] = 2; $data['issuer'] = 2;
$data['status'] = 'completed'; $data['status'] = 'completed';
$this->myLogger->logme('error', 'Policy Trancaction modified form data ( insert data ) : '. json_encode($data)); $this->myLogger->logme('error', 'Policy Trancaction modified form data ( insert data ) : '. json_encode($data));
@ -937,7 +1077,8 @@
private function preparePolicyData() private function preparePolicyData()
{ {
$data = $this->request->getPost(); $request_data = $this->request->getPost();
$data = sanitizeInputArrayAdvanced($request_data);
$file_data = $this->request->getFiles() ?? null; $file_data = $this->request->getFiles() ?? null;
$data['file_data'] = $file_data ?? null; $data['file_data'] = $file_data ?? null;
@ -1094,6 +1235,7 @@
private function updateInceptionPolicy($id, $data) private function updateInceptionPolicy($id, $data)
{ {
// print_r($data); die; // print_r($data); die;
$data['updated_by'] = get_session_userid();
$old_pt_data = $this->policyTransactionModel->where('is_active', 1)->where("id", $id)->first(); $old_pt_data = $this->policyTransactionModel->where('is_active', 1)->where("id", $id)->first();
$old_pt_co_share_data = $this->PTCOShareDetailsModel->where('is_active', 1)->where("id", $id)->first(); $old_pt_co_share_data = $this->PTCOShareDetailsModel->where('is_active', 1)->where("id", $id)->first();
if ($this->policyTransactionModel->update($id, $data)) { if ($this->policyTransactionModel->update($id, $data)) {
@ -2007,6 +2149,7 @@
{ {
if ($id) { if ($id) {
$data['is_active'] = 0; $data['is_active'] = 0;
$data['updated_by'] = get_session_userid();
$policy_transaction_data = $this->policyTransactionModel->where('id', $id)->first(); $policy_transaction_data = $this->policyTransactionModel->where('id', $id)->first();
if($policy_transaction_data['policy_type_id'] > 7 && $type == 0){ if($policy_transaction_data['policy_type_id'] > 7 && $type == 0){
@ -2247,26 +2390,277 @@
public function createEndorsementPolicy() public function createEndorsementPolicy()
{ {
$id = $this->request->getPost('id'); // $id = $this->request->getPost('id');
$rules = [
// ==========================================
// 1. CLIENT SECTION
// ==========================================
'client_id' => [
'label' => 'Client',
'rules' => 'required',
'errors' => ['required' => 'Client selection is mandatory.']
],
'client_policy_id' => [
'label' => 'Policy',
'rules' => 'required',
'errors' => ['required' => 'Please select the policy to endorse.']
],
'client_type' => ['rules' => 'permit_empty','errors' => []],
'client_branch_id' => ['rules' => 'permit_empty','errors' => []],
// ==========================================
// 2. ENDORSEMENT SECTION
// ==========================================
'action_type' => [
'label' => 'Endorsement Type',
'rules' => 'required',
'errors' => ['required' => 'Select an Endorsement Type.']
],
'endorsement_no' => ['label' => 'Endorsement No','rules' => 'permit_empty|regex_match[/^[a-zA-Z0-9\/_-]+$/]',
'errors' => [ 'regex_match' => 'Endorsement No can only contain letters, numbers, and symbols like / - or _' ]],
'data_received_date' => [
'label' => 'Data Received Date',
'rules' => 'required|valid_date[d/m/Y]',
'errors' => ['required' => 'Data Received Date is required.', 'valid_date' => 'Please provide a valid Data Received Date.']
],
'policy_issue_date' => [
'label' => 'Endorsement Issue Date',
'rules' => 'required|valid_date[d/m/Y]',
'errors' => ['required' => 'Endorsement Issue Date is required.', 'valid_date' => 'Please provide a valid Endorsement Issue Date.']
],
// ==========================================
// ENDORSEMENT SECTION
// ==========================================
'month' => [
'label' => 'Endorsement Issue Month',
'rules' => 'required',
'errors' => ['required' => 'Endorsement Issue Month (MM/YYYY) is required.']
],
'endorse_eff_date' => [
'label' => 'Endorsement Effective Date',
'rules' => 'permit_empty|valid_date[d/m/Y]',
'errors' => ['valid_date' => 'Please provide a valid Endorsement Effective Date.']
],
'emp_count' => [
'label' => 'No of Insured',
'rules' => 'permit_empty|numeric',
'errors' => ['numeric' => 'No of Insured must be a number.']
],
'dependent_count' => [
'label' => 'No of Dependents',
'rules' => 'permit_empty|numeric',
'errors' => ['numeric' => 'No of Dependents must be a number.']
],
'last_action_date' => [
'label' => 'Latest Action Date',
'rules' => 'permit_empty|valid_date[d/m/Y]',
'errors' => ['valid_date' => 'Please provide a valid Latest Action Date.']
],
'install_due_date' => [
'label' => 'Installment Due Date',
'rules' => 'permit_empty|valid_date[d/m/Y]',
'errors' => ['valid_date' => 'Please provide a valid Installment Due Date.']
],
// ==========================================
// PREMIUM DETAILS (ARRAY FIELDS .*)
// ==========================================
'follow_insurer_id.*' => [
'label' => 'Insurer',
'rules' => 'required',
'errors' => ['required' => 'Please select an Insurer.']
],
'calc_policy_issue_date.*' => [
'label' => 'Premium Endorsement Issue Date',
'rules' => 'required',
'errors' => ['required' => 'Endorsement Issue Date is required.']
],
'co_share_per.*' => [
'label' => 'Co-Share %',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'Co-Share % must be a valid decimal.']
],
'base_premium.*' => [
'label' => 'Base Premium',
'rules' => 'permit_empty|regex_match[/^-?\d+(\.\d+)?$/]|differs[0]',
'errors' => [
'regex_match' => 'Base Premium must be a valid positive or negative number.',
'differs' => 'Base Premium cannot be zero.'
]
],
'total.*' => [
'label' => 'Total Premium',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'Total Premium must be a valid amount.'],
],
// Decimal validation with Labels
'non_comm_per_amt.*' => [
'label' => 'Non-Comm Premium',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'Non-Comm Premium must be numeric.']
],
'tp_premium.*' => [
'label' => 'TP Premium',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'TP Premium must be numeric.']
],
'ter_premium.*' => [
'label' => 'TEP Premium',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'TEP Premium must be numeric.']
],
'co_premium.*' => [
'label' => 'Co-Premium',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'Co-Premium must be numeric.']
],
'co_tp_premium.*' => [
'label' => 'Co-TP Premium',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'Co-TP Premium must be numeric.']
],
'co_ter_premium.*' => [
'label' => 'Co-TEP Premium',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'Co-TEP Premium must be numeric.']
],
'cgst.*' => [
'label' => 'CGST',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'CGST must be numeric.']
],
'sgst.*' => [
'label' => 'SGST',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'SGST must be numeric.']
],
'igst.*' => [
'label' => 'IGST',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'IGST must be numeric.']
],
'gst_amount.*' => [
'label' => 'GST Amount',
'rules' => 'permit_empty|decimal|greater_than[0]',
'errors' => ['decimal' => 'GST Amount must be numeric.','greater_than' => 'GST Amount cannot be zero; please enter a value greater than 0.']
],
'stamp_duty.*' => [
'label' => 'Stamp Duty',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'Stamp Duty must be numeric.']
],
'agreed_bp.*' => [
'label' => 'Agreed BP %',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'Agreed BP % must be numeric.']
],
'agreed_tp.*' => [
'label' => 'Agreed TP %',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'Agreed TP % must be numeric.']
],
'agreed_ter.*' => [
'label' => 'Agreed TEP %',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'Agreed TEP % must be numeric.']
],
'agreed_amount.*' => [
'label' => 'Agreed Amount',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'Agreed Amount must be numeric.']
],
// Finance/Management Specific Labels
'actual_bp_amt.*' => [
'label' => 'Actual BP Amount',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'Actual BP Amount must be numeric.']
],
'actual_tp_amt.*' => [
'label' => 'Actual TP Amount',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'Actual TP Amount must be numeric.']
],
'actual_tep_amt.*' => [
'label' => 'Actual TEP Amount',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'Actual TEP Amount must be numeric.']
],
'actual_bp_per.*' => [
'label' => 'Actual BP %',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'Actual BP % must be numeric.']
],
'actual_tp_per.*' => [
'label' => 'Actual TP %',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'Actual TP % must be numeric.']
],
'actual_tep_per.*' => [
'label' => 'Actual TEP %',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'Actual TEP % must be numeric.']
],
'actual_bp_brokerage_amt.*' => [
'label' => 'BP Remuneration',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'BP Remuneration must be numeric.']
],
'actual_tp_brokerage_amt.*' => [
'label' => 'TP Remuneration',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'TP Remuneration must be numeric.']
],
'actual_tep_brokerage_amt.*' => [
'label' => 'TEP Remuneration',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'TEP Remuneration must be numeric.']
],
'exp_amt.*' => [
'label' => 'Expected Amount',
'rules' => 'permit_empty|decimal',
'errors' => ['decimal' => 'Expected Amount must be numeric.']
],
'co_share_type.*' => ['label' => 'Is Leader', 'rules' => 'permit_empty','errors' => []],
'follower_policy_no.*' => ['label' => 'Follower Policy No', 'rules' => 'permit_empty','errors' => []],
'co_share_id.*' => ['label' => 'Record ID', 'rules' => 'permit_empty','errors' => []],
];
if (!$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Input validation failed',
'code' => 400,
'errors' => $this->validator->getErrors()
]);
}
$data = $this->preparePolicyTransactionData(); $data = $this->preparePolicyTransactionData();
$id = (isset($data['id']) && !empty($data['id'])) ? $data['id'] : null;
$data['status'] = 'completed'; $data['status'] = 'completed';
// print_r($data); die;
if (!$id) { if (!$id) {
return $this->insertEndorsementTransaction($data); return $this->insertEndorsementTransaction($data);
} else { } else {
return $this->updateEndorsementTransaction($id, $data); return $this->updateEndorsementTransaction($id, $data);
} }
} }
private function preparePolicyTransactionData() private function preparePolicyTransactionData()
{ {
$data = $this->request->getPost(); $request_post_data = $this->request->getPost();
$data = sanitizeInputArrayAdvanced($request_post_data);
// echo '<pre>'; // echo '<pre>';
// print_r($data); // print_r($data);
// die; // die;
$file_data = $this->request->getFiles() ?? null;
$data['file_data'] = $file_data ?? null;
if (!isset($data['policy_with_corr'])) { if (!isset($data['policy_with_corr'])) {
$data['policy_with_corr'] = 0; $data['policy_with_corr'] = 0;
} elseif ($data['policy_with_corr']) { } elseif ($data['policy_with_corr']) {
@ -2410,6 +2804,11 @@
$this->handleCompletedStatus($data, $insert); $this->handleCompletedStatus($data, $insert);
$this->insertOrUpdateCoShareDetails($data, $insert); $this->insertOrUpdateCoShareDetails($data, $insert);
// policy file upload
if(isset($data['doc_name']) && isset($data['file_data']) && !empty($data['doc_name']) && !empty($data['file_data'])){
$this->uploadFile($data['doc_name'], $data['file_data'], $insert);
}
return $this->respond(['status' => true, 'message' => 'Endorsement transaction created successfully'], 200); return $this->respond(['status' => true, 'message' => 'Endorsement transaction created successfully'], 200);
} }
@ -2418,6 +2817,7 @@
private function updateEndorsementTransaction($id, $data) private function updateEndorsementTransaction($id, $data)
{ {
$data['updated_by'] = get_session_userid();
$old_endorse_data = $this->policyTransactionModel->where('id', $id)->where('is_active', 1)->first(); $old_endorse_data = $this->policyTransactionModel->where('id', $id)->where('is_active', 1)->first();
$update = $this->policyTransactionModel->where('id', $id)->set($data)->update(); $update = $this->policyTransactionModel->where('id', $id)->set($data)->update();
@ -2681,6 +3081,20 @@
// dd(db_connect()->getLastQuery() ,$pt_bp_amt); // dd(db_connect()->getLastQuery() ,$pt_bp_amt);
$data['base_cd_amount'] = $pt_bp_amt['amount'] ?? null; $data['base_cd_amount'] = $pt_bp_amt['amount'] ?? null;
$ptFileQuery = $this->PTFileModel
->join('policy_transaction', 'pt_files.pt_id = policy_transaction.id')
->where('pt_files.pt_id', $id)
->where('pt_files.is_active', 1);
if (!in_array(get_role_id(), [1, 5]) && empty(array_intersect(user_team(), [MANAGEMENT_TEAM_ID, FINANCE_TEAM_ID, BUSINESS_TEAM_ID]))) {
if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
$ptFileQuery->where('pt_files.created_by', get_session_userid());
}
}
$data['pt_files'] = $ptFileQuery->findAll();
if ($data) { if ($data) {
return $this->respond(['status' => true, 'data' => $data, 'pt_id' => $pt_id], 200); return $this->respond(['status' => true, 'data' => $data, 'pt_id' => $pt_id], 200);
} else { } else {
@ -3250,10 +3664,12 @@
$client_policy_id = (!isset($client_policy_id) || $client_policy_id === '' || $client_policy_id === null) ? 0 : $client_policy_id; $client_policy_id = (!isset($client_policy_id) || $client_policy_id === '' || $client_policy_id === null) ? 0 : $client_policy_id;
$user_id = (!isset($user_id) || $user_id === '' || $user_id === null) ? 0 : $user_id; $user_id = (!isset($user_id) || $user_id === '' || $user_id === null) ? 0 : $user_id;
if ($this->request->is('post')) { if ($this->request->is('post')) {
$isFromDashboard = $this->request->getPost("is_dashboard"); $request_post_data = $this->request->getPost();
$sanitized_post_data = sanitizeInputArrayAdvanced($request_post_data);
$isFromDashboard = $sanitized_post_data["is_dashboard"];
if (isset($isFromDashboard) && !empty($isFromDashboard) && $isFromDashboard == 1) { if (isset($isFromDashboard) && !empty($isFromDashboard) && $isFromDashboard == 1) {
$ids = $this->request->getPost('ids'); $ids = $sanitized_post_data['ids'];
$ids = array_filter(explode(',', $ids)); $ids = array_filter(explode(',', $ids));
@ -3639,7 +4055,7 @@
helper('excel_util_helper'); helper('excel_util_helper');
//get file info //get file info
$file_id = $params['file_id']; $file_id = $params['file_id'];
$file = $this->insurerStatements->find($file_id); $file = $this->insurerStatements->find((int)$file_id);
// dd($file); // dd($file);
$date = new \DateTime($file['month']); $date = new \DateTime($file['month']);
@ -3757,7 +4173,7 @@
try { try {
//get file info //get file info
$file = $this->insurerStatements->find($file_id); $file = $this->insurerStatements->find((int)$file_id);
// dd($file); // dd($file);
$date = new \DateTime($file['month']); $date = new \DateTime($file['month']);
@ -3910,7 +4326,7 @@
helper('excel_util_helper'); helper('excel_util_helper');
//get file info //get file info
$file_id = $params['file_id']; $file_id = $params['file_id'];
$file = $this->insurerStatements->find($file_id); $file = $this->insurerStatements->find((int)$file_id);
// dd($file); // dd($file);
$date = new \DateTime($file['month']); $date = new \DateTime($file['month']);
@ -4075,7 +4491,7 @@
{ {
$statement_id = $this->request->getUri()->getSegment(4); $statement_id = $this->request->getUri()->getSegment(4);
$inv_details = $this->insurerStatements->find($statement_id); $inv_details = $this->insurerStatements->find((int)$statement_id);
$inv_payment_details = $this->invPaymentDetailsModel $inv_payment_details = $this->invPaymentDetailsModel
->where('statement_id', $statement_id) ->where('statement_id', $statement_id)
->where('is_active', 1) ->where('is_active', 1)
@ -4212,7 +4628,7 @@
public function getFileErr() public function getFileErr()
{ {
$file_id = $this->request->getUri()->getSegment(4); $file_id = $this->request->getUri()->getSegment(4);
$file = $this->insurerStatements->find($file_id); $file = $this->insurerStatements->find((int)$file_id);
return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $file['reason']], 200); return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $file['reason']], 200);
} }
@ -4221,10 +4637,12 @@
// echo 'scbsc';die(); // echo 'scbsc';die();
if ($this->request->is('post')) { if ($this->request->is('post')) {
// $jsonData = (array)$this->request->getJSON(); // $jsonData = (array)$this->request->getJSON();
$customer_id = $this->request->getPost('customer_id'); $request_data = $this->request->getPost();
$policy_id = $this->request->getPost('policy_id'); $data = sanitizeInputArrayAdvanced($request_data);
$cus_doc_name = $this->request->getPost('cus_doc_name'); $customer_id = $data['customer_id'];
$policy_doc_name = $this->request->getPost('policy_doc_name'); $policy_id = $data['policy_id'];
$cus_doc_name = $data['cus_doc_name'];
$policy_doc_name = $data['policy_doc_name'];
$pt_files = []; $pt_files = [];
$kyc_files = []; $kyc_files = [];
$batch_files = []; $batch_files = [];
@ -4933,6 +5351,7 @@
$pt_data = $this->policyTransactionModel->where('is_active', 1)->findAll(); $pt_data = $this->policyTransactionModel->where('is_active', 1)->findAll();
$user_data = $this->userModel->where('is_active', 1)->findAll(); $user_data = $this->userModel->where('is_active', 1)->findAll();
$agent_data = db_connect()->table('partner_agent')->where('is_active', 1)->get()->getResultArray(); $agent_data = db_connect()->table('partner_agent')->where('is_active', 1)->get()->getResultArray();
$pos_data = db_connect()->table('partner_pos')->where('is_active', 1)->get()->getResultArray();
$rto_master = db_connect()->table('rto_master')->where('is_active', 1)->get()->getResultArray(); $rto_master = db_connect()->table('rto_master')->where('is_active', 1)->get()->getResultArray();
$vehicle_type = db_connect()->table('vehicle_type')->where('is_active', 1)->get()->getResultArray(); $vehicle_type = db_connect()->table('vehicle_type')->where('is_active', 1)->get()->getResultArray();
$nhance_branch_data = db_connect()->table('nhance_branch')->where('is_active', 1)->get()->getResultArray(); $nhance_branch_data = db_connect()->table('nhance_branch')->where('is_active', 1)->get()->getResultArray();
@ -5098,6 +5517,7 @@
$vehicle_data = $this->vehicleModel->where('is_active', 1)->findAll(); $vehicle_data = $this->vehicleModel->where('is_active', 1)->findAll();
$user_data = $this->userModel->where('is_active', 1)->findAll(); $user_data = $this->userModel->where('is_active', 1)->findAll();
$agent_data = db_connect()->table('partner_agent')->where('is_active', 1)->get()->getResultArray(); $agent_data = db_connect()->table('partner_agent')->where('is_active', 1)->get()->getResultArray();
$pos_data = db_connect()->table('partner_pos')->where('is_active', 1)->get()->getResultArray();
$rto_master = db_connect()->table('rto_master')->where('is_active', 1)->get()->getResultArray(); $rto_master = db_connect()->table('rto_master')->where('is_active', 1)->get()->getResultArray();
$vehicle_type_data = db_connect()->table('vehicle_type')->where('is_active', 1)->get()->getResultArray(); $vehicle_type_data = db_connect()->table('vehicle_type')->where('is_active', 1)->get()->getResultArray();
$nhance_branch_data = db_connect()->table('nhance_branch')->where('is_active', 1)->get()->getResultArray(); $nhance_branch_data = db_connect()->table('nhance_branch')->where('is_active', 1)->get()->getResultArray();
@ -5180,7 +5600,8 @@
$current_insurer_branch_data = check_insurer_branch_exist($row, $insurer_branch_data, $current_insurer_data)['branch'] ?? null; $current_insurer_branch_data = check_insurer_branch_exist($row, $insurer_branch_data, $current_insurer_data)['branch'] ?? null;
$current_nhance_branch = check_nhance_branch($row, $nhance_branch_data)['branch'] ?? null; $current_nhance_branch = check_nhance_branch($row, $nhance_branch_data)['branch'] ?? null;
$current_agent_data = check_agent_exist($row, $agent_data)['agent'] ?? null; // $current_agent_data = check_agent_exist($row, $agent_data)['agent'] ?? null;
$current_agent_data = check_agent_exist($row, $pos_data)['agent'] ?? null;
$salse = check_user_exist($row, 13, $user_data)['user'] ?? null; $salse = check_user_exist($row, 13, $user_data)['user'] ?? null;
$service = check_user_exist($row, 14, $user_data)['user'] ?? null; $service = check_user_exist($row, 14, $user_data)['user'] ?? null;
@ -5218,8 +5639,9 @@
'salse_person_manager_id' => $salse['rm_id'] ?? null, 'salse_person_manager_id' => $salse['rm_id'] ?? null,
'service_person_manager_id' => $service['rm_id'] ?? null, 'service_person_manager_id' => $service['rm_id'] ?? null,
'service_person_branch_id' => $service['nhance_branch_id'] ?? null, 'service_person_branch_id' => $service['nhance_branch_id'] ?? null,
'agent_id' => $current_agent_data['id'] ?? null, // 'agent_id' => $current_agent_data['id'] ?? null,
'agent_code' => $current_agent_data['agent_code'] ?? null, // 'agent_code' => $current_agent_data['agent_code'] ?? null,
'pos_id' => $current_agent_data['id'] ?? null,
'file_id' => $params['file_id'], 'file_id' => $params['file_id'],
'endorsement_no' => null, 'endorsement_no' => null,
'client_branch_id' => null, 'client_branch_id' => null,

View File

@ -110,6 +110,14 @@ class RestAuthenticationController extends AdminController
if (isset($employeeData['employee_id'])) if (isset($employeeData['employee_id']))
{ {
//check the resend otp (with in 60 seconds don't allow another otp to send)
$check = canSendOtp($employeeData);
if (!$check['allowed']) {
return $this->respond(['status' => false,'message' => 'OTP already sent. Please wait before retrying.','retry_after_seconds' => $check['retry_after']], 429); // Too Many Requests
}
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithMobileNumber: Employee verified with ID = " . $employeeData['employee_id']); $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithMobileNumber: Employee verified with ID = " . $employeeData['employee_id']);
log_message('error', ' '); log_message('error', ' ');
log_message('error', '************************ POST END ********************************'); log_message('error', '************************ POST END ********************************');
@ -217,6 +225,12 @@ class RestAuthenticationController extends AdminController
if (isset($employeeData['employee_id'])) { if (isset($employeeData['employee_id'])) {
//check the resend otp (with in 60 seconds don't allow another otp to send)
$check = canSendOtp($employeeData);
if (!$check['allowed']) {
return $this->respond(['status' => false,'message' => 'OTP already sent. Please wait before retrying.','retry_after_seconds' => $check['retry_after']], 429); // Too Many Requests
}
$builder = $this->employeeModel $builder = $this->employeeModel
->where('email_corporate', $email) ->where('email_corporate', $email)
@ -519,6 +533,12 @@ class RestAuthenticationController extends AdminController
if ($HrData) { if ($HrData) {
//check the resend otp (with in 60 seconds don't allow another otp to send)
$check = canSendOtp($HrData);
if (!$check['allowed']) {
return $this->respond(['status' => false,'message' => 'OTP already sent. Please wait before retrying.','retry_after_seconds' => $check['retry_after']], 429); // Too Many Requests
}
$sql = "UPDATE level_contacts SET otp = ? WHERE mobile = ? AND contact_type = 'client' AND is_active = 1"; $sql = "UPDATE level_contacts SET otp = ? WHERE mobile = ? AND contact_type = 'client' AND is_active = 1";
$db = db_connect(); $db = db_connect();
@ -569,6 +589,12 @@ class RestAuthenticationController extends AdminController
if ($HrData) { if ($HrData) {
//check the resend otp (with in 60 seconds don't allow another otp to send)
$check = canSendOtp($HrData);
if (!$check['allowed']) {
return $this->respond(['status' => false,'message' => 'OTP already sent. Please wait before retrying.','retry_after_seconds' => $check['retry_after']], 429); // Too Many Requests
}
$sql = " $sql = "
UPDATE level_contacts UPDATE level_contacts
SET otp = ? SET otp = ?
@ -734,6 +760,8 @@ class RestAuthenticationController extends AdminController
$decoded = json_decode($HRAccessData['allowed_modules'], true); $decoded = json_decode($HRAccessData['allowed_modules'], true);
$getAllhrData[$key]['allowed_modules'] = $decoded; $getAllhrData[$key]['allowed_modules'] = $decoded;
$HRAccessData['pre_client_id'] = md5($HRAccessData['pre_client_id']);
$HRAccessData['post_client_id'] = md5($HRAccessData['post_client_id']);
$token = JWTToken::encode($HRAccessData); $token = JWTToken::encode($HRAccessData);
$getAllhrData[$key]['token'] = $token; $getAllhrData[$key]['token'] = $token;
@ -749,7 +777,7 @@ class RestAuthenticationController extends AdminController
}else { }else {
return $this->respond(['status' => 'failed','code' => 404,'data' => "" , 'message' => 'User not found' ],200); return $this->respond(['status' => 'failed','code' => 404,'data' => "" , 'message' => 'Invalid OTP' ],200);
} }
@ -759,7 +787,7 @@ class RestAuthenticationController extends AdminController
} else { } else {
return $this->respond(['status' => 'failed','code' => 404,'data' => "" , 'message' => 'User not found' ],200); return $this->respond(['status' => 'failed','code' => 404,'data' => "" , 'message' => 'Invalid OTP' ],200);
} }
} catch (\Exception $e) { } catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()],500); return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()],500);
@ -919,6 +947,12 @@ class RestAuthenticationController extends AdminController
$mpin = $this->request->getJSON()->new_mpin; $mpin = $this->request->getJSON()->new_mpin;
$client_id = $this->request->getJSON()->client_id ?? null; $client_id = $this->request->getJSON()->client_id ?? null;
if($old_mpin == $mpin)
{
$result = ['mpin_verification' => false , 'message' => "New MPIN must be different from the old MPIN"];
return $this->respond(['status' => 'failed','code' => 404,'data' => $result],200);
}
// if (isset($mobile_number)) // if (isset($mobile_number))
// { // {
// $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('mpin', $old_mpin)->where('relationship', 'self')->first(); // $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('mpin', $old_mpin)->where('relationship', 'self')->first();
@ -990,11 +1024,11 @@ class RestAuthenticationController extends AdminController
} else { } else {
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - updateMpin: Employee not found in the POST. Wrong MPIN"); $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - updateMpin: Employee not found in the POST. Old MPIN is incorrect");
log_message('error', ' '); log_message('error', ' ');
log_message('error', ' ************************************* POST END **************************************** '); log_message('error', ' ************************************* POST END **************************************** ');
log_message('error', ' '); log_message('error', ' ');
$result = ['mpin_verification' => false , 'message' => "Wrong Mpin"]; $result = ['mpin_verification' => false , 'message' => "Old MPIN is incorrect"];
return $this->respond(['status' => 'failed','code' => 404,'data' => $result],200); return $this->respond(['status' => 'failed','code' => 404,'data' => $result],200);
} }
@ -1237,7 +1271,7 @@ class RestAuthenticationController extends AdminController
log_message('error', ' '); log_message('error', ' ');
log_message('error', ' ************************************* POST END **************************************** '); log_message('error', ' ************************************* POST END **************************************** ');
log_message('error', ' '); log_message('error', ' ');
return $this->respond(['status' => 'success','code' => 200,'data' => "", 'message' => "Mpin - exist" , 'Mpin' =>$employeeData["mpin"], 'is_mpin_skipped' => $employeeData['is_mpin_skipped'], 'is_biometric_enabled' => $employeeData['is_biometric_enabled']],200); return $this->respond(['status' => 'success','code' => 200,'data' => "", 'message' => "Mpin - exist" , 'Mpin' =>$employeeData["mpin"], 'is_mpin_skipped' => $employeeData['is_mpin_skipped'] ?? 0, 'is_biometric_enabled' => $employeeData['is_biometric_enabled'] ?? 0],200);
} else { } else {
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - checkMpin: Mpin - not found"); $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - checkMpin: Mpin - not found");
log_message('error', ' '); log_message('error', ' ');
@ -2289,4 +2323,53 @@ class RestAuthenticationController extends AdminController
} }
} }
public function logout()
{
$authHeader = $this->request->getHeaderLine('Authorization');
if (!$authHeader) {
return $this->respond([
'status' => false,
'message' => 'Authorization token missing'
], 401);
}
// Validate JWT (your hardened function)
$result = JWTToken::validateJWT($authHeader);
if ($result['status'] !== true) {
return $this->respond([
'status' => false,
'message' => 'Invalid or expired token'
], 401);
}
$decoded = $result['decoded'];
$userId = $decoded['id'] ?? null;
if (!$userId) {
return $this->respond([
'status' => false,
'message' => 'Invalid token payload'
], 401);
}
// Identify user type
if (isset($decoded['emp_code'])) {
$model = new EmployeeModel();
} else {
$model = new LevelContactModel();
}
// Invalidate token server-side
$model->update($userId, [
'token_time_out' => null
]);
return $this->respond([
'status' => true,
'message' => 'Logged out successfully'
], 200);
}
} }

View File

@ -128,7 +128,7 @@ class SalesController extends BaseController
public function updateLead($id) public function updateLead($id)
{ {
try { try {
if (!$this->leadModel->find($id)) { if (!$this->leadModel->find((int)$id)) {
return $this->failNotFound('Lead not found'); return $this->failNotFound('Lead not found');
} }
@ -158,7 +158,7 @@ class SalesController extends BaseController
public function deleteLead($id) public function deleteLead($id)
{ {
try { try {
if (!$this->leadModel->find($id)) { if (!$this->leadModel->find((int)$id)) {
return $this->failNotFound('Lead not found'); return $this->failNotFound('Lead not found');
} }
@ -228,7 +228,7 @@ class SalesController extends BaseController
} }
$contactId = $this->contactModel->getInsertID(); $contactId = $this->contactModel->getInsertID();
$contact = $this->contactModel->find($contactId); $contact = $this->contactModel->find((int)$contactId);
return $this->respondCreated([ return $this->respondCreated([
'status' => 'success', 'status' => 'success',
@ -247,18 +247,18 @@ class SalesController extends BaseController
public function updateContact($id) public function updateContact($id)
{ {
try { try {
if (!$this->contactModel->find($id)) { if (!$this->contactModel->find((int)$id)) {
return $this->failNotFound('Contact not found'); return $this->failNotFound('Contact not found');
} }
$data = $this->request->getJSON(true); $data = $this->request->getJSON(true);
$data['updated_by'] = $this->getUserId(); $data['updated_by'] = $this->getUserId();
if (!$this->contactModel->update($id, $data)) { if (!$this->contactModel->update((int)$id, $data)) {
return $this->fail($this->contactModel->errors(), ResponseInterface::HTTP_BAD_REQUEST); return $this->fail($this->contactModel->errors(), ResponseInterface::HTTP_BAD_REQUEST);
} }
$contact = $this->contactModel->find($id); $contact = $this->contactModel->find((int)$id);
return $this->respond([ return $this->respond([
'status' => 'success', 'status' => 'success',
@ -277,11 +277,11 @@ class SalesController extends BaseController
public function deleteContact($id) public function deleteContact($id)
{ {
try { try {
if (!$this->contactModel->find($id)) { if (!$this->contactModel->find((int)$id)) {
return $this->failNotFound('Contact not found'); return $this->failNotFound('Contact not found');
} }
$this->contactModel->delete($id); $this->contactModel->delete((int)$id);
return $this->respondDeleted([ return $this->respondDeleted([
'status' => 'success', 'status' => 'success',
@ -299,7 +299,7 @@ class SalesController extends BaseController
public function setPrimaryContact($id) public function setPrimaryContact($id)
{ {
try { try {
$contact = $this->contactModel->find($id); $contact = $this->contactModel->find((int)$id);
if (!$contact) { if (!$contact) {
return $this->failNotFound('Contact not found'); return $this->failNotFound('Contact not found');
@ -425,7 +425,7 @@ class SalesController extends BaseController
} }
$activityId = $this->activityModel->getInsertID(); $activityId = $this->activityModel->getInsertID();
$activity = $this->activityModel->find($activityId); $activity = $this->activityModel->find((int)$activityId);
return $this->respondCreated([ return $this->respondCreated([
'status' => 'success', 'status' => 'success',
@ -444,7 +444,7 @@ class SalesController extends BaseController
public function updateActivity($id) public function updateActivity($id)
{ {
try { try {
if (!$this->activityModel->find($id)) { if (!$this->activityModel->find((int)$id)) {
return $this->failNotFound('Activity not found'); return $this->failNotFound('Activity not found');
} }
@ -455,7 +455,7 @@ class SalesController extends BaseController
return $this->fail($this->activityModel->errors(), ResponseInterface::HTTP_BAD_REQUEST); return $this->fail($this->activityModel->errors(), ResponseInterface::HTTP_BAD_REQUEST);
} }
$activity = $this->activityModel->find($id); $activity = $this->activityModel->find((int)$id);
return $this->respond([ return $this->respond([
'status' => 'success', 'status' => 'success',
@ -474,7 +474,7 @@ class SalesController extends BaseController
public function completeActivity($id) public function completeActivity($id)
{ {
try { try {
$activity = $this->activityModel->find($id); $activity = $this->activityModel->find((int)$id);
if (!$activity) { if (!$activity) {
return $this->failNotFound('Activity not found'); return $this->failNotFound('Activity not found');
@ -487,7 +487,7 @@ class SalesController extends BaseController
$data = $this->request->getJSON(true); $data = $this->request->getJSON(true);
$data['updated_by'] = $this->getUserId(); $data['updated_by'] = $this->getUserId();
$this->activityModel->completeActivity($id, $data); $this->activityModel->completeActivity((int)$id, $data);
// Create follow-up activity if requested // Create follow-up activity if requested
if (!empty($data['create_followup']) && $data['create_followup'] === true) { if (!empty($data['create_followup']) && $data['create_followup'] === true) {
@ -505,7 +505,7 @@ class SalesController extends BaseController
$this->activityModel->insert($followupData); $this->activityModel->insert($followupData);
} }
$updatedActivity = $this->activityModel->find($id); $updatedActivity = $this->activityModel->find((int)$id);
return $this->respond([ return $this->respond([
'status' => 'success', 'status' => 'success',
@ -524,11 +524,11 @@ class SalesController extends BaseController
public function deleteActivity($id) public function deleteActivity($id)
{ {
try { try {
if (!$this->activityModel->find($id)) { if (!$this->activityModel->find((int)$id)) {
return $this->failNotFound('Activity not found'); return $this->failNotFound('Activity not found');
} }
$this->activityModel->delete($id); $this->activityModel->delete((int)$id);
return $this->respondDeleted([ return $this->respondDeleted([
'status' => 'success', 'status' => 'success',
@ -595,7 +595,7 @@ class SalesController extends BaseController
} }
$noteId = $this->noteModel->getInsertID(); $noteId = $this->noteModel->getInsertID();
$note = $this->noteModel->find($noteId); $note = $this->noteModel->find((int)$noteId);
return $this->respondCreated([ return $this->respondCreated([
'status' => 'success', 'status' => 'success',
@ -614,7 +614,7 @@ class SalesController extends BaseController
public function updateNote($id) public function updateNote($id)
{ {
try { try {
$note = $this->noteModel->find($id); $note = $this->noteModel->find((int)$id);
if (!$note) { if (!$note) {
return $this->failNotFound('Note not found'); return $this->failNotFound('Note not found');
@ -632,7 +632,7 @@ class SalesController extends BaseController
return $this->fail($this->noteModel->errors(), ResponseInterface::HTTP_BAD_REQUEST); return $this->fail($this->noteModel->errors(), ResponseInterface::HTTP_BAD_REQUEST);
} }
$updatedNote = $this->noteModel->find($id); $updatedNote = $this->noteModel->find((int)$id);
return $this->respond([ return $this->respond([
'status' => 'success', 'status' => 'success',
@ -651,7 +651,7 @@ class SalesController extends BaseController
public function deleteNote($id) public function deleteNote($id)
{ {
try { try {
$note = $this->noteModel->find($id); $note = $this->noteModel->find((int)$id);
if (!$note) { if (!$note) {
return $this->failNotFound('Note not found'); return $this->failNotFound('Note not found');
@ -662,7 +662,7 @@ class SalesController extends BaseController
return $this->failUnauthorized('You are not authorized to delete this note'); return $this->failUnauthorized('You are not authorized to delete this note');
} }
$this->noteModel->delete($id); $this->noteModel->delete((int)$id);
return $this->respondDeleted([ return $this->respondDeleted([
'status' => 'success', 'status' => 'success',

View File

@ -17,6 +17,8 @@ use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill; use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Border;
use Firebase\JWT\JWT;
class TestingController extends BaseController class TestingController extends BaseController
{ {
use ResponseTrait; use ResponseTrait;
@ -983,5 +985,46 @@ class TestingController extends BaseController
} }
public function metaDashboardDemo()
{
// 🔐 Move this to .env in real projects
$METABASE_SECRET_KEY = getenv('METABASE_SECRET_KEY');
$policy_id = $this->request->getGet('client_policy');
$policy_id = $policy_id ? $policy_id : 4687;
$payload = [
'resource' => [
// 'dashboard' => 1
'dashboard' => 2
],
'params' => (object)['client_policy' => $policy_id], // MUST be object for Metabase
'exp' => time() + (10 * 60) // 10 minutes
];
// dd($payload);
$token = JWT::encode($payload, $METABASE_SECRET_KEY, 'HS256');
// // You can either return token only
// return $this->response->setJSON([
// 'token' => $token,
// 'iframe_url' => "https://your-metabase-domain/embed/dashboard/{$token}#bordered=true&titled=true"
// ]);
if($this->request->getGet('api') == 1)
{
return $this->respond([
'status' => 'success',
'message' => 'Form data received successfully!',
'data' => [
'metabaseToken' => $token,
'metabaseUrl' => 'https://nsights.nhanceindia.in']
]);
}
return view('meta_dashboard_demo_one', [
'metabaseToken' => $token,
'metabaseUrl' => 'https://nsights.nhanceindia.in',
]);
}
} }

View File

@ -62,8 +62,108 @@ class ThzController extends BaseController
public function ticketSave() public function ticketSave()
{ {
$rules = [
'client_id' => [
'rules' => 'permit_empty|integer',
'errors' => [
'integer' => 'Invalid client selected'
]
],
'mobile' => [
'rules' => 'required|regex_match[/^[0-9]{10}$/]',
'errors' => [
'required' => 'Mobile number is required',
'regex_match' => 'Mobile number must be exactly 10 digits'
]
],
'name' => [
'rules' => 'required|min_length[3]|max_length[100]|alpha_space',
'errors' => [
'required' => 'Name is required',
'min_length' => 'Name must be at least 3 characters',
'alpha_space'=> 'Name can contain only letters and spaces'
]
],
'email' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/]',
'errors' => [
'required' => 'Email address is required.',
'regex_match' => 'Please enter a valid email format (e.g., name@company.com).'
]
],
'empcode' => [
'rules' => 'permit_empty|alpha_numeric_punct|max_length[50]',
'errors' => [
'alpha_numeric_punct' => 'Employee code contains invalid characters.',
'max_length' => 'Employee code is too long'
]
],
'ticket_type' => [
'rules' => 'required',
'errors' => [
'required' => 'Please select a Ticket Type.'
]
],
'ticket_type' => [
'rules' => 'required',
'errors' => [
'required' => 'Ticket Type is required',
]
],
'assign_to' => [
'rules' => 'permit_empty|integer',
'errors' => [
'integer' => 'Invalid assignee selected'
]
],
'subject' => [
'rules' => 'required|min_length[3]|max_length[150]|regex_match[/^[a-zA-Z0-9 .,\-_()&\/\?]+$/]',
'errors' => [
'required' => 'Subject is required.',
'min_length' => 'Subject must be at least 3 characters long.',
'max_length' => 'Subject cannot exceed 150 characters',
'regex_match' => 'Subject contains invalid characters (Avoid quotes and special symbols).'
]
],
'message' => [
'rules' => 'required|min_length[10]|max_length[1500]',
'errors' => [
'required' => 'Message is required',
'min_length' => 'Message must be at least 10 characters',
'max_length' => 'Message cannot exceed 1500 characters'
]
],
'status' => [
'rules' => 'permit_empty|in_list[Open,In Progress,Resolved,Closed]',
'errors' => [
'in_list' => 'Invalid ticket status'
]
],
];
if (!$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Input validation failed',
'code' => 400,
'errors' => $this->validator->getErrors()
]);
}
try { try {
$data = $this->request->getPost();
$request_post_data = $this->request->getPost();
$data = sanitizeInputArrayAdvanced($request_post_data);
$references = ""; $references = "";
if (!empty($data['thz_id'])) { if (!empty($data['thz_id'])) {
@ -157,7 +257,30 @@ class ThzController extends BaseController
{ {
try { try {
$data = $this->request->getPost();
$rules = [
'notes' => [
'rules' => 'required|string|min_length[1]|max_length[1500]',
'errors' => [
'required' => 'Notes is required',
'string' => 'Notes must be valid text',
'min_length' => 'Notes cannot be empty',
'max_length' => 'Notes cannot exceed 1500 characters'
]
],
];
if (!$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Input validation failed',
'code' => 400,
'errors' => $this->validator->getErrors()
]);
}
$request_post_data = $this->request->getPost();
$data = sanitizeInputArrayAdvanced($request_post_data);
$data['notes_type'] = $data['notes_type'] ?? 'External'; $data['notes_type'] = $data['notes_type'] ?? 'External';
@ -238,7 +361,7 @@ class ThzController extends BaseController
$accManagerId = $this->getAcmIdUsingClientId($clientId ?? null); $accManagerId = $this->getAcmIdUsingClientId($clientId ?? null);
$accManager = $this->userModel->find($accManagerId); $accManager = $this->userModel->find((int)$accManagerId);
if (!empty($result['master'])) { if (!empty($result['master'])) {
$notes = $this->thzMasterNotesModel->ticketConversationList($thz_id, $returnType); $notes = $this->thzMasterNotesModel->ticketConversationList($thz_id, $returnType);

File diff suppressed because it is too large Load Diff

View File

@ -7,6 +7,14 @@ use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\API\ResponseTrait; use CodeIgniter\API\ResponseTrait;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use Kint\Kint; use Kint\Kint;
use App\Libraries\TpaClaimsImportFactory;
use App\Libraries\TPAClaimsImportServices\FhplClaimImportService;
use App\Libraries\TPAClaimsImportServices\MediAssistClaimImportService;
use App\Libraries\TPAClaimsImportServices\AbhiClaimImportService;
use App\Libraries\TPAClaimsImportServices\RcareClaimImportService;
use App\Libraries\TPAClaimsImportServices\VidalClaimImportService;
use App\Libraries\TPAClaimsImportServices\IciciClaimImportService;
use App\Libraries\TPAClaimsImportServices\BaseTpaClaimImportService;
use App\Models\ClaimDumpFileModel; use App\Models\ClaimDumpFileModel;
use App\Models\EmployeeModel; use App\Models\EmployeeModel;
@ -15,10 +23,14 @@ use App\Models\TPAModel;
use App\Models\ClientModel; use App\Models\ClientModel;
use App\Models\TicketClaimStatusModel; use App\Models\TicketClaimStatusModel;
use App\Models\ClientPolicyModel; use App\Models\ClientPolicyModel;
use App\Models\ClaimsDumpFhplModel;
use App\Helpers\ExcelSanitizeHelper; use App\Helpers\ExcelSanitizeHelper;
use App\Models\TicketMasterModel; use App\Models\TicketMasterModel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class TicketServiceController extends BaseController class TicketServiceController extends BaseController
{ {
use ResponseTrait; use ResponseTrait;
@ -35,6 +47,10 @@ class TicketServiceController extends BaseController
protected $ticketClaimStatusModel; protected $ticketClaimStatusModel;
protected $clientPolicyModel; protected $clientPolicyModel;
protected $medi_assist_primary_key;
protected $vidal_primary_key;
protected $icici_primary_key;
public function __construct() public function __construct()
{ {
@ -50,6 +66,11 @@ class TicketServiceController extends BaseController
$this->ticketClaimStatusModel = new TicketClaimStatusModel(); $this->ticketClaimStatusModel = new TicketClaimStatusModel();
$this->clientPolicyModel = new ClientPolicyModel(); $this->clientPolicyModel = new ClientPolicyModel();
$this->medi_assist_primary_key = getenv('MEDI_ASSIST_PRIMARY_KEY_CONSTANT');
$this->vidal_primary_key = getenv('VIDAL_PRIMARY_KEY_CONSTANT');
$this->icici_primary_key = getenv('ICICI_PRIMARY_KEY_CONSTANT');
$this->claim_dump_excel_columns = [ $this->claim_dump_excel_columns = [
// Mandatory Fields // Mandatory Fields
@ -1144,7 +1165,7 @@ class TicketServiceController extends BaseController
{ {
//get file name //get file name
$file_id = $params['file_id']; $file_id = $params['file_id'];
$file = $this->claimDumpFileModel->find($file_id); $file = $this->claimDumpFileModel->find((int)$file_id);
$this->myLogger->logme('error', "Start the claim dump File Data Validataion with the file id : " . $file_id); $this->myLogger->logme('error', "Start the claim dump File Data Validataion with the file id : " . $file_id);
// dd($file); // dd($file);
@ -1329,7 +1350,7 @@ class TicketServiceController extends BaseController
{ {
//get file name //get file name
$file_id = $params['file_id']; $file_id = $params['file_id'];
$file = $this->claimDumpFileModel->find($file_id); $file = $this->claimDumpFileModel->find((int)$file_id);
$this->myLogger->logme('error', "Start the claim dump OnBoard Process with the file id : " . $file_id); $this->myLogger->logme('error', "Start the claim dump OnBoard Process with the file id : " . $file_id);
// dd($file); // dd($file);
@ -1820,4 +1841,175 @@ class TicketServiceController extends BaseController
} }
// --------------------------------------------------------------------------------------------------------------------------------
public function tpaClaimDumpImporter($params)
{
$file_id = $params['file_id'] ?? null; // Move outside try to ensure catch can see it
try {
$file_path = WRITEPATH . 'uploads' . DIRECTORY_SEPARATOR . 'claim_dump_excel' . DIRECTORY_SEPARATOR;
if (!$file_id) {
return ['status' => false, 'message' => 'File ID is missing'];
}
$fileData = $this->claimDumpFileModel->find((int)$file_id);
if (!$fileData) {
return ['status' => false, 'message' => 'Invalid file ID. No file data found'];
}
$file_full_path = $file_path . $fileData['file_name'];
if (!is_file($file_full_path)) {
return ['status' => false, 'message' => 'Claim dump file not found'];
}
$handler = TpaClaimsImportFactory::make($fileData['tpa_id'] ?? 0);
$result = $handler->runTpaClaimDumpInsert($file_full_path, $file_id);
if (!empty($result['status']) && $result['status'] === true) {
Jobs::addJob(['job_name' => 'tpaClaimDumpToTicketMasterImporters', 'payload' => ['file_id' => $file_id]]);
} else {
// FORCE FAIL LOGIC
$this->markAsFailed($file_id, $result['message'] ?? 'System error contact admin', $fileData['created_by'] ?? null);
}
return $result;
} catch (\Throwable $th) {
$this->myLogger->logme("error", 'TPA_CLAIM_IMPORTER_JOB : ' . $th->getMessage());
if (!empty($file_id)) {
$this->markAsFailed($file_id, 'System error contact admin');
}
return [
'status' => false,
'message' => 'TPA Claim dump import failed',
'error_data' => $th->getMessage()
];
}
}
private function markAsFailed($file_id, $message, $user_id = null)
{
$reason = json_encode([
'error_summary' => [5 => 1],
'error_data' => $message
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$data = [
'status' => 'failed',
'reason' => $reason,
'updated_by' => $user_id
];
// Using the direct update(id, data) method is often more reliable inside try/catch
return $this->claimDumpFileModel->update($file_id, $data);
}
public function tpaClaimDumpToTicketMasterImporters($params)
{
$file_id = $params['file_id'] ?? null;
$fileData = null;
try {
if (!$file_id) {
return ['status' => false, 'message' => 'File ID is missing'];
}
$fileData = $this->claimDumpFileModel->where('id', $file_id)->first();
if (!$fileData) {
return ['status' => false, 'message' => 'Invalid file ID. No file data found to import'];
}
$handler = TpaClaimsImportFactory::make($fileData['tpa_id'] ?? 0);
$result = $handler->runTicketMasterInsert($params);
if (!empty($result['status']) && $result['status'] === true) {
// Success: Update the status to success
$this->claimDumpFileModel->update($file_id, [
'status' => 'success',
'reason' => null
]);
} else {
// Logic failure: The runTicketMasterInsert returned status false
$this->markAsFailed(
$file_id,
$result['message'] ?? 'System error contact admin',
$fileData['created_by'] ?? null
);
}
return $result;
} catch (\Throwable $th) {
// Log the full error
$this->myLogger->logme("error", 'TICKET_MASTER_CLAIM_IMPORTER_JOB :' . $th->getMessage() . ' at line ' . $th->getLine());
// CRITICAL: Even if the code crashes, try to mark the file as failed
if ($file_id) {
$this->markAsFailed($file_id, 'Fatal Crash: ' . $th->getMessage(), $fileData['created_by'] ?? null);
}
return [
'status' => false,
'message' => $th->getMessage(),
'error_data' => [
'line' => $th->getLine(),
'file' => $th->getFile()
]
];
}
}
public function readExcelBySheetName(string $filePath, string $sheetName): array
{
if (!file_exists($filePath)) {
return [];
}
$spreadsheet = IOFactory::load($filePath);
// Get sheet by name
$sheet = $spreadsheet->getSheetByName($sheetName);
if ($sheet === null) {
return [];
}
$rows = $sheet->toArray(null, true, true, true);
// Need at least header + one row
if (count($rows) < 2) {
return [];
}
// First row = headers
$headers = array_shift($rows);
$headers = array_map('trim', $headers);
$data = [];
foreach ($rows as $row) {
// Skip completely empty rows
if (!array_filter($row)) {
continue;
}
$item = [];
foreach ($headers as $key => $headerName) {
if ($headerName !== '') {
$item[$headerName] = $row[$key] ?? null;
}
}
$data[] = $item;
}
return $data;
}
} }

View File

@ -83,7 +83,110 @@ class UserController extends AdminController
return redirect()->to(base_url('/user/list')); return redirect()->to(base_url('/user/list'));
} else { } else {
$userData = $this->request->getPost(); // $userData = $this->request->getPost();
$data = $this->request->getPost();
$userData = sanitizeInputArrayAdvanced($data);
$rules = [
// ======================
// Nhance Branch
// ======================
'nhance_branch_id' => [
'rules' => 'required|integer',
'errors' => [
'required' => 'Nhance Branch is required',
'integer' => 'Invalid Nhance Branch selected'
]
],
// ======================
// Reporting Manager
// ======================
'rm_id' => [
'rules' => 'required|integer',
'errors' => [
'required' => 'Reporting Manager is required',
'integer' => 'Invalid Reporting Manager selected'
]
],
// ======================
// Employee Code
// ======================
'emp_code' => [
'rules' => 'required|min_length[3]|max_length[15]',
'errors' => [
'required' => 'Employee Code is required',
'min_length' => 'Employee Code must be at least 3 characters',
'max_length' => 'Employee Code cannot exceed 15 characters',
]
],
// ======================
// First Name
// ======================
'first_name' => [
'rules' => 'required|alpha_space|min_length[2]|max_length[100]',
'errors' => [
'required' => 'Name is required',
'alpha_space' => 'Name can contain only letters and spaces',
'min_length' => 'Name must be at least 2 characters',
'max_length' => 'Name cannot exceed 100 characters'
]
],
// ======================
// Email
// ======================
'email' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/]',
'errors' => [
'required' => 'Email address is required.',
'regex_match' => 'Please enter a valid email format (e.g., name@company.com).'
]
],
// ======================
// Mobile
// ======================
'mobile' => [
'rules' => 'required|regex_match[/^[6-9][0-9]{9}$/]',
'errors' => [
'required' => 'Mobile number is required',
'regex_match' => 'Enter a valid 10-digit mobile number starting with 6, 7, 8, or 9',
]
],
// ======================
// Role
// ======================
'role' => [
'rules' => 'required|integer',
'errors' => [
'required' => 'User Role is required',
'integer' => 'Invalid User Role selected'
]
],
// ======================
// Team (Multiple select)
// ======================
'team' => [
'rules' => 'required',
'errors' => [
'required' => 'At least one User Team must be selected'
]
],
];
if (!$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Input validation failed',
'code' => 400,
'errors' => $this->validator->getErrors()
]);
}
$userData['created_by'] = get_session_userid(); $userData['created_by'] = get_session_userid();
$temp_team = $userData['team']; $temp_team = $userData['team'];
unset($userData['team']); unset($userData['team']);
@ -167,9 +270,112 @@ class UserController extends AdminController
return redirect()->to(base_url('/user/list')); return redirect()->to(base_url('/user/list'));
} else { } else {
// echo ":/ in 163"; // echo ":/ in 163";
$id = $this->request->getPost('PrimaryKey'); $rules = [
$teams = $this->request->getPost('team');
$userData = $this->request->getPost(); // ======================
// Nhance Branch
// ======================
'nhance_branch_id' => [
'rules' => 'required|integer',
'errors' => [
'required' => 'Nhance Branch is required',
'integer' => 'Invalid Nhance Branch selected'
]
],
// ======================
// Reporting Manager
// ======================
'rm_id' => [
'rules' => 'required|integer',
'errors' => [
'required' => 'Reporting Manager is required',
'integer' => 'Invalid Reporting Manager selected'
]
],
// ======================
// Employee Code
// ======================
'emp_code' => [
'rules' => 'required|min_length[3]|max_length[15]',
'errors' => [
'required' => 'Employee Code is required',
'min_length' => 'Employee Code must be at least 3 characters',
'max_length' => 'Employee Code cannot exceed 15 characters',
]
],
// ======================
// First Name
// ======================
'first_name' => [
'rules' => 'required|alpha_space|min_length[2]|max_length[100]',
'errors' => [
'required' => 'Name is required',
'alpha_space' => 'Name can contain only letters and spaces',
'min_length' => 'Name must be at least 2 characters',
'max_length' => 'Name cannot exceed 100 characters'
]
],
// ======================
// Email
// ======================
'email' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/]',
'errors' => [
'required' => 'Email address is required.',
'regex_match' => 'Please enter a valid email format (e.g., name@company.com).'
]
],
// ======================
// Mobile
// ======================
'mobile' => [
'rules' => 'required|regex_match[/^[6-9][0-9]{9}$/]',
'errors' => [
'required' => 'Mobile number is required',
'regex_match' => 'Enter a valid 10-digit mobile number starting with 6, 7, 8, or 9',
]
],
// ======================
// Role
// ======================
'role' => [
'rules' => 'required|integer',
'errors' => [
'required' => 'User Role is required',
'integer' => 'Invalid User Role selected'
]
],
// ======================
// Team (Multiple select)
// ======================
'team' => [
'rules' => 'required',
'errors' => [
'required' => 'At least one User Team must be selected'
]
],
];
if (!$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Input validation failed',
'code' => 400,
'errors' => $this->validator->getErrors()
]);
}
$data = $this->request->getPost();
$userData = sanitizeInputArrayAdvanced($data);
$id = $userData['PrimaryKey'];
$teams = $userData['team'];
unset($userData['csrf_test_name']); unset($userData['csrf_test_name']);
unset($userData['PrimaryKey']); unset($userData['PrimaryKey']);
@ -594,29 +800,100 @@ class UserController extends AdminController
// add/update // add/update
if ($method === 'post') { if ($method === 'post') {
$rules = [
// ======================
// Partner Name
// ======================
'name' => [
'rules' => 'required|alpha_space|min_length[2]|max_length[100]',
'errors' => [
'required' => 'Partner name is required',
'alpha_space' => 'Partner name can contain only letters and spaces',
'min_length' => 'Partner name must be at least 2 characters',
'max_length' => 'Partner name cannot exceed 100 characters'
]
],
// ======================
// Mobile Number
// ======================
'mobile' => [
'rules' => 'required|regex_match[/^[6-9][0-9]{9}$/]',
'errors' => [
'required' => 'Mobile number is required',
'regex_match' => 'Enter a valid 10-digit mobile number starting with 6, 7, 8, or 9',
]
],
// ======================
// Email
// ======================
'email' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/]',
'errors' => [
'required' => 'Email address is required.',
'regex_match' => 'Please enter a valid email format (e.g., name@company.com).'
]
],
// ======================
// Retention Rate
// ======================
'retention_rate' => [
'rules' => [
'required',
'regex_match[/^(100(\.0{1,2})?|([0-9]{1,2})(\.[0-9]{1,2})?)$/]'
],
'errors' => [
'required' => 'Retention Rate is required',
'regex_match' => 'Retention Rate must be between 0 and 100 with up to 2 decimal places'
]
],
// ======================
// Nhance Branch
// ======================
'nhance_branch_id' => [
'rules' => 'required|integer',
'errors' => [
'required' => 'Nhance Branch is required',
'integer' => 'Invalid Nhance Branch selected'
]
],
];
if (! $this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Input validation failed',
'code' => 400,
'errors' => $this->validator->getErrors()
]);
}
$data = $this->request->getPost(); $data = $this->request->getPost();
$id = !empty($data['PrimaryKey']) ? $data['PrimaryKey'] : null; $sanitized_post_data = sanitizeInputArrayAdvanced($data);
$id = !empty($sanitized_post_data['PrimaryKey']) ? $sanitized_post_data['PrimaryKey'] : null;
unset($sanitized_post_data['pk']);
// don't forgot same means just unset the key because partner_staff some UNIQUE KEY sets in table thats why // don't forgot same means just unset the key because partner_staff some UNIQUE KEY sets in table thats why
if ($id) { if ($id) {
$existing = $this->partnerStaffModel->find($id); $existing = $this->partnerStaffModel->find((int)$id);
if ($existing) { if ($existing) {
if ($data['email'] === $existing['email']) { unset($data['email']); } if ($sanitized_post_data['email'] === $existing['email']) { unset($sanitized_post_data['email']); }
if ($data['mobile'] === $existing['mobile']) { unset($data['mobile']); } if ($sanitized_post_data['mobile'] === $existing['mobile']) { unset($sanitized_post_data['mobile']); }
} }
} }
$errors = []; $errors = [];
// Check Email Duplicate (if it wasn't unset) // Check Email Duplicate (if it wasn't unset)
if (isset($data['email'])) { if (isset($sanitized_post_data['email'])) {
$count = $this->partnerStaffModel->where('email', $data['email'])->countAllResults(); $count = $this->partnerStaffModel->where('email', $sanitized_post_data['email'])->countAllResults();
if ($count > 0) $errors['email'] = "This email is already taken by another user."; if ($count > 0) $errors['email'] = "This email is already taken by another user.";
} }
// Check Mobile Duplicate (if it wasn't unset) // Check Mobile Duplicate (if it wasn't unset)
if (isset($data['mobile'])) { if (isset($sanitized_post_data['mobile'])) {
$count = $this->partnerStaffModel->where('mobile', $data['mobile'])->countAllResults(); $count = $this->partnerStaffModel->where('mobile', $sanitized_post_data['mobile'])->countAllResults();
if ($count > 0) $errors['mobile'] = "This mobile is already taken by another user."; if ($count > 0) $errors['mobile'] = "This mobile is already taken by another user.";
} }
@ -632,14 +909,14 @@ class UserController extends AdminController
// --- Save/Update --- // --- Save/Update ---
if ($id) { if ($id) {
$text = "update"; $text = "update";
$data['updated_by'] = get_session_userid(); $sanitized_post_data['updated_by'] = get_session_userid();
$result = $this->partnerStaffModel->update($id, $data); $result = $this->partnerStaffModel->update($id, $sanitized_post_data);
} else { } else {
$text = "create"; $text = "create";
$data['role_id'] = 1; $sanitized_post_data['role_id'] = 1;
$data['created_by'] = get_session_userid(); $sanitized_post_data['created_by'] = get_session_userid();
$id = $this->partnerStaffModel->insert($data); $id = $this->partnerStaffModel->insert($sanitized_post_data);
if($id){ if($id){
$details['manager_id'] = $id; $details['manager_id'] = $id;
$details['updated_by'] = get_session_userid(); $details['updated_by'] = get_session_userid();
@ -667,7 +944,7 @@ class UserController extends AdminController
return $this->response->setJSON(['status' => 'error', 'message' => 'ID is required'])->setStatusCode(400); return $this->response->setJSON(['status' => 'error', 'message' => 'ID is required'])->setStatusCode(400);
} }
$staff = $this->partnerStaffModel->find($id); $staff = $this->partnerStaffModel->find((int)$id);
if (!$staff) { if (!$staff) {
return $this->response->setJSON(['status' => 'error','message' => 'Staff not found'])->setStatusCode(404); return $this->response->setJSON(['status' => 'error','message' => 'Staff not found'])->setStatusCode(404);
} }
@ -783,7 +1060,7 @@ class UserController extends AdminController
return $this->response->setJSON(['status' => 'error', 'message' => 'ID is required'])->setStatusCode(400); return $this->response->setJSON(['status' => 'error', 'message' => 'ID is required'])->setStatusCode(400);
} }
$files = $this->partnerManagerIncentiveFileModel->find($id); $files = $this->partnerManagerIncentiveFileModel->find((int)$id);
if (!$files) { if (!$files) {
return $this->response->setJSON(['status' => 'error','message' => 'No Records found'])->setStatusCode(404); return $this->response->setJSON(['status' => 'error','message' => 'No Records found'])->setStatusCode(404);
} }

View File

@ -29,7 +29,7 @@ class VidalApiController extends BaseController
$apiUrl = getenv('VIDAL_API_BASE_URL').'/files/upload-url'; $apiUrl = getenv('VIDAL_API_BASE_URL').'/files/upload-url';
$subscriptionKey = getenv('VIDAL_API_SUBSCRIPTION_KEY'); $subscriptionKey = getenv('VIDAL_API_SUBSCRIPTION_KEY');
log_message('error', "Starting file upload process for filename: $filename | Path: $filePath"); log_message('error', "TPA CLAIM PUSH | Starting file upload process for filename: $filename | Path: $filePath");
// Step 1: Get signed URL from Vidal API // Step 1: Get signed URL from Vidal API
// $filePath = '/opt/lampp/htdocs/nhance/writable/uploads/claim_files/1760013019_73d94af7b96ddc2e3d51.png'; // $filePath = '/opt/lampp/htdocs/nhance/writable/uploads/claim_files/1760013019_73d94af7b96ddc2e3d51.png';
@ -39,7 +39,7 @@ class VidalApiController extends BaseController
"Ocp-Apim-Subscription-Key: $subscriptionKey" "Ocp-Apim-Subscription-Key: $subscriptionKey"
]; ];
log_message('error', "Requesting signed URL from Vidal API: $apiUrl | Payload: $payload"); log_message('error', "TPA CLAIM PUSH | Requesting signed URL from Vidal API: $apiUrl | Payload: $payload");
$ch = curl_init($apiUrl); $ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
@ -57,7 +57,7 @@ class VidalApiController extends BaseController
$responseData = json_decode($response, true); $responseData = json_decode($response, true);
if (!isset($responseData['data']['signedUrl']) || !isset($responseData['data']['fileId'])) { if (!isset($responseData['data']['signedUrl']) || !isset($responseData['data']['fileId'])) {
log_message('error', "Invalid signed URL response received: " . json_encode($responseData)); log_message('error', "TPA CLAIM PUSH | Invalid signed URL response received: " . json_encode($responseData));
return ["status" => false, "message" => "Invalid signed URL response", "response" => $responseData]; return ["status" => false, "message" => "Invalid signed URL response", "response" => $responseData];
} }
@ -88,12 +88,12 @@ class VidalApiController extends BaseController
curl_close($ch2); curl_close($ch2);
if ($curlErr) { if ($curlErr) {
log_message('error', "Curl error during file upload: $curlErr"); log_message('error', "TPA CLAIM PUSH | Curl error during file upload: $curlErr");
return ["status" => false, "message" => "File upload failed", "data" => $curlErr]; return ["status" => false, "message" => "File upload failed", "data" => $curlErr];
} }
if ($httpCode !== 200 && $httpCode !== 201) { if ($httpCode !== 200 && $httpCode !== 201) {
log_message('error', "File upload failed with HTTP Code: $httpCode | Response: $uploadResponse"); log_message('error', "TPA CLAIM PUSH | File upload failed with HTTP Code: $httpCode | Response: $uploadResponse");
return [ return [
"status" => false, "status" => false,
"message" => "File upload failed", "message" => "File upload failed",
@ -112,7 +112,7 @@ class VidalApiController extends BaseController
]; ];
} }
public function SubmitClaim ($claimId = 515) public function SubmitClaim ($claimId = null) //515
{ {
helper('api'); helper('api');
@ -153,7 +153,7 @@ class VidalApiController extends BaseController
->getRowArray(); // single record ->getRowArray(); // single record
if (count($data) && $data['filePath'] == null) { if (count($data) && $data['filePath'] == null) {
log_message('error', "Submit claim failed - Claim or File Missing"); log_message('error', "TPA CLAIM PUSH | Submit claim failed - Claim or File Missing");
return $this->response->setJSON(['status' => false,'message' => 'Claim or File Missing', ]); return $this->response->setJSON(['status' => false,'message' => 'Claim or File Missing', ]);
} }
@ -166,7 +166,7 @@ class VidalApiController extends BaseController
$upload = $this->uploadFileToVidal($filePath,$filename); $upload = $this->uploadFileToVidal($filePath,$filename);
if ($upload['status'] !== true) { if ($upload['status'] !== true) {
log_message('error', "Submit claim failed - File upload failed"); log_message('error', "TPA CLAIM PUSH | Submit claim failed - File upload failed");
return $this->response->setJSON([ return $this->response->setJSON([
'status' => false, 'status' => false,
'message' => 'File upload failed', 'message' => 'File upload failed',
@ -244,6 +244,9 @@ class VidalApiController extends BaseController
if($response['status'] != true){ if($response['status'] != true){
log_message('error', 'TPA CLAIM PUSH FAILED | claimId: '.$claimId.' | response: '.json_encode($response)); log_message('error', 'TPA CLAIM PUSH FAILED | claimId: '.$claimId.' | response: '.json_encode($response));
$this->db->table('ticket_master')
->where('id',$claimId)
->update([ 'tpa_push_response' => json_encode($response) ]);
return; return;
} }
@ -251,8 +254,8 @@ class VidalApiController extends BaseController
if($response['data']['status'] == 'SUCCESS') if($response['data']['status'] == 'SUCCESS')
{ {
$claimNO = $response['data']['data']['claimNO'] ?? null; $claimNO = $response['data']['data']['claimNo'] ?? null;
$claimInwardNO = $response['data']['data']['claimInwardNO'] ?? null; $claimInwardNO = $response['data']['data']['claimInwardNo'] ?? null;
if(!empty($claimNO) && !empty($claimInwardNO)){ if(!empty($claimNO) && !empty($claimInwardNO)){
@ -260,7 +263,7 @@ class VidalApiController extends BaseController
$this->db->table('ticket_master') $this->db->table('ticket_master')
->where('id',$claimId) ->where('id',$claimId)
->update([ 'tpa_claim_push_reference_no' => $claimInwardNO , 'tpa_claim_id' => $claimNO ]); ->update([ 'tpa_claim_push_reference_no' => $claimInwardNO , 'tpa_claim_id' => $claimNO , 'claim_number' => $claimNO ]);
return; return;
@ -439,7 +442,7 @@ class VidalApiController extends BaseController
->getRowArray(); ->getRowArray();
if (!$ticket) { if (!$ticket) {
return $this->response->setJSON(['status' => false,'message' => 'Invalid Claim ID' ]); return ['status' => false,'message' => 'Invalid Claim ID' ];
} }
$body = []; $body = [];
@ -464,11 +467,7 @@ class VidalApiController extends BaseController
if ($response['status'] != true || empty($response['data']['data']['claims'][0])) { if ($response['status'] != true || empty($response['data']['data']['claims'][0])) {
log_message('error', 'CLAIM STATUS FAILED | for ticket ID: ' . $claimId.' | response: '.json_encode($response)); log_message('error', 'CLAIM STATUS FAILED | for ticket ID: ' . $claimId.' | response: '.json_encode($response));
return $this->response->setJSON([ return ['status' => false, 'message' => 'API call failed.','data' => $response];
'status' => false,
'message' => 'API call failed.',
'data' => $response
]);
} }
// Extract claim status // Extract claim status
@ -501,12 +500,7 @@ class VidalApiController extends BaseController
// LOG UPDATE // LOG UPDATE
log_message('error', "CLAIM STATUS SUCCESS | Updated ticket ID $claimId with claim status: $currentStatus"); log_message('error', "CLAIM STATUS SUCCESS | Updated ticket ID $claimId with claim status: $currentStatus");
return $this->response->setJSON([ return ['status' => true,'message' => 'Claim status updated.','updated_status' => $currentStatus,'api_response' => $response];
'status' => true,
'message' => 'Claim status updated.',
'updated_status' => $currentStatus,
'api_response' => $response
]);
} }
public function ClaimStatusUpdate() public function ClaimStatusUpdate()
@ -801,7 +795,7 @@ class VidalApiController extends BaseController
//call a job for dump JSON data to DB //call a job for dump JSON data to DB
$job_details = new Jobs(); $job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'saveMediAssitAPIData', 'payload' => [ 'file_id' => $requestData['file_id'],'json_file_path' => $filePath ]]); $r = Jobs::addJob(['job_name' => 'saveVidalAPIData', 'payload' => [ 'file_id' => $requestData['file_id'],'json_file_path' => $filePath ]]);
// now update DB // now update DB
@ -842,9 +836,9 @@ class VidalApiController extends BaseController
// log_message('error', "✅ Match found: emp_code={$row['empNo']} policy={$row['policyNumber']}"); // log_message('error', "✅ Match found: emp_code={$row['empNo']} policy={$row['policyNumber']}");
$sql = "UPDATE employee_polices $sql = "UPDATE employee_polices
SET tpa_id = ? SET tpa_id = :tpa_id:,
WHERE id = ?"; WHERE id = :emp_policy_id:";
$this->db->query($sql, [$row['enrollmentId'], $policy_data['emp_policy_id']]); $this->db->query($sql, ["tpa_id"=>$row['enrollmentId'], "emp_policy_id"=>$policy_data['emp_policy_id']]);
// for e-card send // for e-card send
if(strtolower(trim($policy_data['relationship'])) == 'self'){ if(strtolower(trim($policy_data['relationship'])) == 'self'){

156
app/Filters/AclFilter.php Normal file
View File

@ -0,0 +1,156 @@
<?php
namespace App\Filters;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
use Config\Acl;
use App\Libraries\AuthLogout;
class AclFilter implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
// ===================== CLI BYPASS =====================
if (is_cli()) {
return;
}
// ===================== PATH NORMALIZATION =====================
$uri = service('uri');
// Raw path: /PHP828APPS/ruc/nhance/index.php/dashboard/view
$fullPath = '/' . ltrim($uri->getPath(), '/');
// Base path: /PHP828APPS/ruc/nhance
$basePath = rtrim(parse_url(base_url(), PHP_URL_PATH), '/');
// Remove base path
if ($basePath && str_starts_with($fullPath, $basePath)) {
$path = substr($fullPath, strlen($basePath));
} else {
$path = $fullPath;
}
// Remove index.php if present
if (str_starts_with($path, '/index.php')) {
$path = substr($path, strlen('/index.php'));
}
// Normalize
$path = '/' . ltrim($path, '/');
// Fallback
if ($path === '') {
$path = '/';
}
// echo'<br>BASH PATH: ' . base_url();
// echo'<br>ACL RAW PATH: ' . $fullPath;
// echo'<br>ACL BASE PATH: ' . $basePath;
// echo'<br>ACL FINAL PATH: ' . $path;
// ===================== LOAD ACL =====================
$acl = new Acl();
$rules = $acl->rules;
// print_rr($rules);die;
// ===================== MATCH RULE =====================
$matchedRule = null;
foreach ($rules as $pattern => $rule) {
// echo "$pattern".'---------<br>';
if (preg_match($pattern, $path)) {
// echo "matched - $pattern";
$matchedRule = $rule;
break; // FIRST MATCH WINS
}
}
// print_r($matchedRule);//die;
// ===================== NO RULE = DENY =====================
if ($matchedRule === null) {
return $this->deny($path, 'No ACL rule matched');
}
// ===================== PUBLIC ROUTE =====================
if (!empty($matchedRule['public'])) {
return; // ALLOW
}
// ===================== AUTH CHECK =====================
if (!check_session()) {
// For API requests return 401 JSON
if ($request->isAJAX() || str_starts_with($path, '/api') || str_starts_with($path, '/employeeRest')) {
return service('response')
->setStatusCode(401)
->setJSON(['error' => 'Unauthorized Resource Access']);
}
// For web redirect to login
return AuthLogout::logout();
}
// ===================== GET USER CONTEXT =====================
$userRole = check_role(); //
$userTeams = user_team(); // must return array of TEAM IDs
$allowedRoles = $matchedRule['roles'] ?? [];
$allowedTeams = $matchedRule['teams'] ?? [];
// ===================== ROLE FIRST =====================
if (!empty($allowedRoles) && in_array((int)$userRole, $allowedRoles, true)) {
return; // ALLOW
}
// ===================== TEAM FALLBACK =====================
if (!empty($allowedTeams) && is_array($userTeams)) {
foreach ($userTeams as $teamId) {
if (in_array($teamId, $allowedTeams, true)) {
return; // ALLOW
}
}
}
// ===================== DENY =====================
return $this->deny($path, 'Role/Team not permitted');
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// nothing
}
// ===================== DENY HANDLER =====================
protected function deny(string $path, string $reason)
{
log_message('error', 'ACL BLOCKED: {user} {path} - {reason}', [
'user' => session()->get('userid') ?? 'guest',
'path' => $path,
'reason' => $reason,
]);
// API / AJAX → JSON
$request = service('request');
if ($request->isAJAX() || str_starts_with($path, '/api') || str_starts_with($path, '/employeeRest')) {
return service('response')
->setStatusCode(403)
->setJSON([
'error' => 'Forbidden',
'message' => 'You do not have permission to access this resource'
]);
}
$response = service('response');
$response->setStatusCode(403);
$response->setBody(view('errors/404', [
'message' => '403 Access denied - You do not have permission to access this resource'
]));
return $response;
// Web → nice 403 page or simple text
return service('response')
->setStatusCode(403)
->setBody('403 Forbidden - Access denied - You do not have permission to access this resource');
}
}

View File

@ -18,66 +18,119 @@ use App\Models\LevelContactModel;
class AuthJWT implements FilterInterface class AuthJWT implements FilterInterface
{ {
// public function before(RequestInterface $request, $arguments = null)
// {
// $jwt = $request->getHeader('Authorization');
// if ($jwt) {
// if (JWTToken::validateJWT($jwt)) {
// $data = JWTToken::validateJWT($jwt);
// $data = json_decode($data);
// $id = $data->decoded->id;
// if(isset($data->decoded->emp_code)){
// $model = new EmployeeModel();
// $user_data = $model->where('id', $id)->first();
// if($user_data['token_time_out'] > time()){
// $data =["token_time_out" => time() + getenv('TOKENTIMEOUT') ];
// $model->update($id, $data);
// return true;
// }else{
// // if($user_data['token_time_out'] != "" && $user_data['token_time_out'] != NULL)
// $data =["token_time_out" => ''];
// $model->update($id, $data);
// header('Content-Type: application/json');
// http_response_code(401);
// // $error = json_encode(["status" => 401, "message" => $data->message]);
// $error = json_encode(["status" => 401, "message" => "Token is Invalid"]);
// echo $error;
// exit;
// }
// }else{
// $model = new LevelContactModel();
// $hr_data = $model->where('id', $id)->first();
// if($hr_data['token_time_out'] > time()){
// $data =["token_time_out" => time() + getenv('TOKENTIMEOUT') ];
// $model->update($id, $data);
// return true;
// }else{
// $data =["token_time_out" => ''];
// $model->update($id, $data);
// header('Content-Type: application/json');
// http_response_code(401);
// // $error = json_encode(["status" => 401, "message" => $data->message]);
// $error = json_encode(["status" => 401, "message" => "Token is Invalid"]);
// echo $error;
// exit;
// }
// }
// }
// } else {
// header('Content-Type: application/json');
// http_response_code(403);
// $error = json_encode(["status" => 403, "message" => "Access Forbidden!"]);
// echo $error;
// exit();
// }
// }
public function before(RequestInterface $request, $arguments = null) public function before(RequestInterface $request, $arguments = null)
{ {
$jwt = $request->getHeader('Authorization'); $authHeader = $request->getHeaderLine('Authorization');
if ($jwt) { if (!$authHeader) {
if (JWTToken::validateJWT($jwt)) { return $this->reject(403, 'Access Forbidden');
$data = JWTToken::validateJWT($jwt);
$data = json_decode($data);
$id = $data->decoded->id;
if(isset($data->decoded->emp_code)){
$model = new EmployeeModel();
$user_data = $model->where('id', $id)->first();
if($user_data['token_time_out'] > time()){
$data =["token_time_out" => time() + getenv('TOKENTIMEOUT') ];
$model->update($id, $data);
return true;
}else{
// if($user_data['token_time_out'] != "" && $user_data['token_time_out'] != NULL)
$data =["token_time_out" => ''];
$model->update($id, $data);
header('Content-Type: application/json');
http_response_code(401);
// $error = json_encode(["status" => 401, "message" => $data->message]);
$error = json_encode(["status" => 401, "message" => "Token is Invalid"]);
echo $error;
exit;
} }
$result = JWTToken::validateJWT($authHeader);
if ($result['status'] !== true) {
return $this->reject(401, $result['message']);
}
$decoded = $result['decoded'];
$id = $decoded['id'] ?? null;
if (!$id) {
return $this->reject(401, 'Invalid token payload');
}
if (isset($decoded['emp_code'])) {
$model = new EmployeeModel();
} else { } else {
$model = new LevelContactModel(); $model = new LevelContactModel();
$hr_data = $model->where('id', $id)->first(); $id = $decoded['post_hr_id'] ?? null;
}
$user = $model->find($id);
if (!$user || $user['token_time_out'] <= time()) {
$model->update($id, ['token_time_out' => null]);
return $this->reject(401, 'Token expired');
}
// Refresh sliding expiration
$model->update($id, [
'token_time_out' => time() + getenv('TOKENTIMEOUT')
]);
if($hr_data['token_time_out'] > time()){
$data =["token_time_out" => time() + getenv('TOKENTIMEOUT') ];
$model->update($id, $data);
return true; return true;
}else{
$data =["token_time_out" => ''];
$model->update($id, $data);
header('Content-Type: application/json');
http_response_code(401);
// $error = json_encode(["status" => 401, "message" => $data->message]);
$error = json_encode(["status" => 401, "message" => "Token is Invalid"]);
echo $error;
exit;
}
} }
private function reject(int $code, string $message)
{
return service('response')
->setStatusCode($code)
->setJSON(['status' => $code, 'message' => $message])
->send();
} }
} else {
header('Content-Type: application/json');
http_response_code(403);
$error = json_encode(["status" => 403, "message" => "Access Forbidden!"]);
echo $error;
exit();
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{ {

View File

@ -5,13 +5,28 @@ use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\HTTP\ResponseInterface;
use App\Libraries\AuthLogout;
class AuthMVC implements FilterInterface class AuthMVC implements FilterInterface
{ {
public function before(RequestInterface $request, $arguments = null) public function before(RequestInterface $request, $arguments = null)
{ {
if (!check_session() && !check_cookie()) {
return redirect()->to(base_url('/login')); if (!check_session())
{
return AuthLogout::logout();
}
// if (!check_cookie())
// {
// return AuthLogout::logout();
// }
// Fingerprint validation
$fp = generateFingerprint();
// log_message('error',$fp);
if (session()->get('fingerprint') !== $fp) {
return AuthLogout::logout();
} }
} }

View File

@ -38,7 +38,7 @@ class Cors implements FilterInterface
* *
* @var string * @var string
*/ */
protected string $allowedMethods = 'GET,POST,PUT,PATCH,DELETE,OPTIONS'; protected string $allowedMethods = 'GET,POST,OPTIONS';
/** /**
* HTTP headers allowed in CORS requests * HTTP headers allowed in CORS requests
@ -143,7 +143,7 @@ class Cors implements FilterInterface
// If wildcard present in configuration, allow any origin // If wildcard present in configuration, allow any origin
if (in_array('*', $this->allowedOrigins, true)) { if (in_array('*', $this->allowedOrigins, true)) {
$this->log('Origin allowed: wildcard match', ['origin' => $origin]); // $this->log('Origin allowed: wildcard match', ['origin' => $origin]);
return true; return true;
} }
@ -159,10 +159,10 @@ class Cors implements FilterInterface
// 1. Exact match (including scheme and port) // 1. Exact match (including scheme and port)
// Example: https://example.com matches https://example.com // Example: https://example.com matches https://example.com
if (strcasecmp($allowed, $origin) === 0) { if (strcasecmp($allowed, $origin) === 0) {
$this->log('Origin allowed: exact match', [ // $this->log('Origin allowed: exact match', [
'origin' => $origin, // 'origin' => $origin,
'matched_rule' => $allowed // 'matched_rule' => $allowed
]); // ]);
return true; return true;
} }
@ -178,11 +178,11 @@ class Cors implements FilterInterface
// Check if origin host ends with the allowed root domain // Check if origin host ends with the allowed root domain
if ($originHost === $allowedRoot || str_ends_with($originHost, '.' . $allowedRoot)) { if ($originHost === $allowedRoot || str_ends_with($originHost, '.' . $allowedRoot)) {
$this->log('Origin allowed: wildcard subdomain match', [ // $this->log('Origin allowed: wildcard subdomain match', [
'origin' => $origin, // 'origin' => $origin,
'matched_rule' => $allowed, // 'matched_rule' => $allowed,
'origin_host' => $originHost // 'origin_host' => $originHost
]); // ]);
return true; return true;
} }
} }
@ -191,11 +191,11 @@ class Cors implements FilterInterface
// Example: example.com matches both http://example.com and https://example.com // Example: example.com matches both http://example.com and https://example.com
else { else {
if (strcasecmp($allowed, $originHost) === 0) { if (strcasecmp($allowed, $originHost) === 0) {
$this->log('Origin allowed: host match (scheme-less)', [ // $this->log('Origin allowed: host match (scheme-less)', [
'origin' => $origin, // 'origin' => $origin,
'matched_rule' => $allowed, // 'matched_rule' => $allowed,
'origin_host' => $originHost // 'origin_host' => $originHost
]); // ]);
return true; return true;
} }
} }
@ -274,6 +274,7 @@ class Cors implements FilterInterface
// Handle allowed headers // Handle allowed headers
if ($isPreflight) { if ($isPreflight) {
$response->setHeader('Access-Control-Allow-Methods', ['OPTIONS']);
// For preflight: respect what the browser is asking for // For preflight: respect what the browser is asking for
// The browser sends Access-Control-Request-Headers to ask permission // The browser sends Access-Control-Request-Headers to ask permission
$requestedHeaders = $request->getHeaderLine('Access-Control-Request-Headers'); $requestedHeaders = $request->getHeaderLine('Access-Control-Request-Headers');
@ -320,11 +321,11 @@ class Cors implements FilterInterface
// Preflight is sent by browsers before actual cross-origin requests // Preflight is sent by browsers before actual cross-origin requests
// to check if the actual request is safe to send // to check if the actual request is safe to send
if ($method === 'OPTIONS') { if ($method === 'OPTIONS') {
$this->log('Preflight request received', [ // $this->log('Preflight request received', [
'origin' => $origin, // 'origin' => $origin,
'method' => $method, // 'method' => $method,
'uri' => (string) $request->getUri() // 'uri' => (string) $request->getUri()
]); // ]);
// Validate origin - reject if not allowed // Validate origin - reject if not allowed
if (empty($origin) || !$this->isOriginAllowed($origin)) { if (empty($origin) || !$this->isOriginAllowed($origin)) {
@ -346,10 +347,10 @@ class Cors implements FilterInterface
$response->setStatusCode(204); $response->setStatusCode(204);
$response->setBody(''); $response->setBody('');
$this->log('Preflight approved', [ // $this->log('Preflight approved', [
'origin' => $origin, // 'origin' => $origin,
'allowed_methods' => $this->allowedMethods // 'allowed_methods' => $this->allowedMethods
]); // ]);
return $response; return $response;
} }
@ -392,10 +393,10 @@ class Cors implements FilterInterface
// Add CORS headers to the response // Add CORS headers to the response
$this->addCorsHeaders($response, $request, $origin, false); $this->addCorsHeaders($response, $request, $origin, false);
$this->log('CORS headers added to response', [ // $this->log('CORS headers added to response', [
'origin' => $origin, // 'origin' => $origin,
'status' => $response->getStatusCode() // 'status' => $response->getStatusCode()
]); // ]);
} }
/** /**

View File

@ -0,0 +1,147 @@
<?php
namespace App\Filters;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
use Config\Services;
use finfo;
class GlobalPostFileUploadGuard implements FilterInterface
{
/**
* Max file size (in bytes) → 25MB
*/
protected int $maxFileSize = 25 * 1024 * 1024;
/**
* Allowed MIME types mapped to extensions
*/
protected array $allowedMimeMap = [
'image/jpeg' => ['jpg', 'jpeg'],
'image/png' => ['png'],
'image/gif' => ['gif'],
'image/webp' => ['webp'],
'image/svg+xml' => ['svg'],
'application/pdf' => ['pdf'],
'application/msword' => ['doc'],
'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => ['docx'],
'application/vnd.oasis.opendocument.text' => ['odt'],
'text/rtf' => ['rtf'],
'application/rtf' => ['rtf'],
'application/vnd.ms-excel' => ['xls'],
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => ['xlsx'],
'application/vnd.oasis.opendocument.spreadsheet' => ['ods'],
'text/csv' => ['csv'],
'application/csv' => ['csv'],
'text/plain' => ['txt', 'csv'],
];
protected array $blockedExtensions = [
'php', 'phtml', 'html', 'pht', 'phar', 'php3', 'php4', 'php5', 'php7', 'php8', 'phps',
'cgi', 'fcgi', 'pl', 'py', 'rb', 'lua', 'tcl', 'go', 'rs', 'jar', 'class',
'exe', 'dll', 'com', 'bat', 'cmd', 'msi', 'vbs', 'ps1', 'scr',
'sh', 'bash', 'zsh', 'apk', 'app', 'deb', 'rpm', 'bin', 'run',
'js', 'mjs', 'jsp', 'asp', 'aspx', 'cer', 'swf',
'env', 'ini', 'user.ini', 'htaccess', 'htpasswd', 'conf', 'config', 'log', 'sql',
'zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'xz', 'iso',
'lnk', 'url', 'reg', 'sys', 'drv', 'vxd', 'tmp', 'bak', 'old', 'backup', 'key', 'pem'
];
public function before(RequestInterface $request, $arguments = null)
{
if ($request->getMethod() !== 'post') {
return;
}
$files = $request->getFiles();
if (empty($files)) {
return;
}
foreach ($files as $inputName => $fileData) {
$this->validateFileInput($fileData, $inputName);
}
}
private function validateFileInput($fileData, string $inputName): void
{
if (is_array($fileData)) {
foreach ($fileData as $file) {
$this->validateSingleFile($file, $inputName);
}
} else {
$this->validateSingleFile($fileData, $inputName);
}
}
private function validateSingleFile($file, string $inputName): void
{
$request = Services::request();
$clientIp = $request->getIPAddress();
$uri = $request->getUri()->getPath();
if (!$file->isValid()) {
if ($file->getError() === UPLOAD_ERR_INI_SIZE || $file->getError() === UPLOAD_ERR_FORM_SIZE) {
$this->block("File exceeds server-side size limit", $clientIp, $uri, $inputName, $file->getClientName(), 'unknown', 'unknown', 0);
}
return;
}
$originalName = $file->getClientName();
$extension = strtolower($file->getExtension());
$mime = $file->getMimeType();
$size = $file->getSize();
// --- 1. Fixed Null Byte & Path Traversal Check ---
if (preg_match('/\0|[\/\\\]/', $originalName)) {
$this->block("Malicious filename characters", $clientIp, $uri, $inputName, $originalName, $mime, $extension, $size);
}
// --- 2. Double Extension Attack Check ---
if (preg_match('/\.(php|html|phtml|phar|exe|sh|bat|cmd|js|jsp|asp|aspx|py|pl)\./i', $originalName)) {
$this->block("Double extension attack", $clientIp, $uri, $inputName, $originalName, $mime, $extension, $size);
}
// --- 3. Forbidden Extension ---
if (in_array($extension, $this->blockedExtensions, true)) {
$this->block("Forbidden extension", $clientIp, $uri, $inputName, $originalName, $mime, $extension, $size);
}
// --- 4. File Size Limit ---
if ($size > $this->maxFileSize) {
$this->block("File too large", $clientIp, $uri, $inputName, $originalName, $mime, $extension, $size);
}
// --- 5. MIME Allow-list Check ---
if (!array_key_exists($mime, $this->allowedMimeMap)) {
$this->block("MIME type not allowed ($mime)", $clientIp, $uri, $inputName, $originalName, $mime, $extension, $size);
}
// --- 6. MIME-Extension Consistency ---
if (!in_array($extension, $this->allowedMimeMap[$mime], true)) {
$this->block("MIME-extension mismatch", $clientIp, $uri, $inputName, $originalName, $mime, $extension, $size);
}
}
private function block(string $reason, string $ip, string $uri, string $field, string $filename, string $mime, string $ext, int $size): void
{
log_message('critical',
'[UPLOAD_BLOCKED] {reason} | IP: {ip} | URI: {uri} | Field: {field} | File: {file} | MIME: {mime} | EXT: {ext} | SIZE: {size}',
['reason'=>$reason, 'ip'=>$ip, 'uri'=>$uri, 'field'=>$field, 'file'=>$filename, 'mime'=>$mime, 'ext'=>$ext, 'size'=>$size]
);
$response = Services::response();
$response->setStatusCode(403)
->setJSON([
'status' => 'error',
'message' => 'File upload rejected: Security policy violation.',
'debug' => (ENVIRONMENT === 'development') ? $reason : null
])
->send();
exit;
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) {}
}

View File

@ -0,0 +1,34 @@
<?php
namespace App\Filters;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
class RateLimitFilter implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
$throttler = service('throttler');
// sanitize IP for cache
$key = preg_replace('/[^a-zA-Z0-9_]/', '_', $request->getIPAddress());
if ($throttler->check($key, 25, MINUTE) === false) {
return service('response')
->setStatusCode(429)
->setJSON([
'status' => 'error',
'message' => 'Too many requests. Try again later.'
]);
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// nothing
}
}

View File

@ -0,0 +1,130 @@
<?php
namespace App\Filters;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Services;
class SecurityInputFilter implements FilterInterface
{
/**
* High-confidence XSS patterns only
* (low false-positive set)
**/
protected array $xssPatterns = [
// Script execution
'/<\s*script\b/i',
'/<\/\s*script\s*>/i',
// JavaScript execution vectors
'/javascript\s*:/i',
'/vbscript\s*:/i',
'/data\s*:\s*text\/html/i',
// Inline event handlers (strong signal)
'/on\w+\s*=\s*["\']?/i',
// Dangerous HTML tags
'/<\s*iframe\b/i',
'/<\s*object\b/i',
'/<\s*embed\b/i',
'/<\s*applet\b/i',
'/<\s*img\b/i',
// Image-based execution
'/<\s*img\b[^>]*on\w+/i',
// SVG-based execution (modern bypass)
'/<\s*svg\b/i',
'/<\s*math\b/i',
// Meta refresh redirect
'/<\s*meta\b[^>]*http-equiv\s*=\s*["\']?refresh/i',
// HTML injection via src/href
'/<\s*\w+\b[^>]*(src|href)\s*=\s*["\']?\s*(javascript|data)\s*:/i'
];
public function before(RequestInterface $request, $arguments = null)
{
$logger = Services::mylogger();
$response = Services::response();
// Collect all user-controlled input
$inputs = array_merge(
$request->getGet(),
$request->getPost()
);
if (empty($inputs)) {
return;
}
foreach ($inputs as $field => $value) {
if (is_array($value)) {
$value = json_encode($value);
}
// Step 1: Canonicalization (VERY IMPORTANT)
$canonical = $this->canonicalize($value);
// Step 2: Trim (hygiene)
$canonical = trim($canonical);
// Step 3: Detection (signal-only)
if ($this->detectXss($canonical)) {
// 🔐 Log intent, not data
$logger->logme('critical','SECURITY_BLOCKED_REQUEST - '. json_encode([
'ip' => $request->getIPAddress(),
'method' => $request->getMethod(),
'uri' => current_url(),
'field' => $field,
'attack' => 'XSS_PATTERN',
'length' => strlen($canonical),
'hash' => hash('sha256', $canonical),
]));
// ⛔ Block request
return $response
->setStatusCode(403)
->setJSON([
'status' => 403,
'error' => 'Forbidden',
'message' => 'Malicious input detected'
]);
}
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// no-op
}
/**
* Canonicalization prevents encoded bypass
*/
private function canonicalize(string $value): string
{
$value = urldecode($value);
$value = html_entity_decode($value, ENT_QUOTES | ENT_HTML5, 'UTF-8');
// Remove invisible control characters
return preg_replace('/[\x00-\x1F\x7F]/u', '', $value);
}
private function detectXss(string $value): bool
{
foreach ($this->xssPatterns as $pattern) {
if (preg_match($pattern, $value)) {
return true;
}
}
return false;
}
}

View File

@ -59,7 +59,7 @@ class ChatbotHelper
// $policy_id = 0; // $policy_id = 0;
// $relationship ='Father'; // $relationship ='Father';
$EmployeeModel = new EmployeeModel(); $EmployeeModel = new EmployeeModel();
$data = $EmployeeModel->find($emp_id); $data = $EmployeeModel->find((int)$emp_id);
if(isset($data) && isset($data['email_corporate'])) if(isset($data) && isset($data['email_corporate']))
{ {
$message = SELF::ReimbursementProcessMailTemplate(); $message = SELF::ReimbursementProcessMailTemplate();

View File

@ -67,7 +67,8 @@ class DepositHelper
'balance' => $newBalance, // Include the new balance in the data array 'balance' => $newBalance, // Include the new balance in the data array
'cd_ac_pk'=> isset($data['cd_ac_pk'])?$data['cd_ac_pk']:null, 'cd_ac_pk'=> isset($data['cd_ac_pk'])?$data['cd_ac_pk']:null,
'record_date' => $data['record_date'] ?? null, 'record_date' => $data['record_date'] ?? null,
'policy_transaction_id' => $data['pt_id'] ?? null 'policy_transaction_id' => $data['pt_id'] ?? null,
'file_id' => $data['file_id'] ?? null,
]; ];
// Insert data and get the insert ID // Insert data and get the insert ID

View File

@ -4,24 +4,175 @@ namespace App\Helpers;
class HttpRequestHelper class HttpRequestHelper
{ {
public static function getRequestInfo() public static function getRequestInfo(): array
{ {
$request = service('request'); $request = service('request');
$uaString = $request->getHeaderLine('User-Agent');
// Detect platform & browser using robust fallback logic
[$platform, $browser] = self::detectFromUserAgent($uaString);
$data = [ $data = [
'ip' => $request->getIPAddress(), 'ip' => $request->getIPAddress(),
'platform' => $request->getUserAgent()->getPlatform(), 'platform' => $platform,
'browser' => ($request->getUserAgent()->getBrowser().' '.$request->getUserAgent()->getVersion()), 'browser' => $browser,
'method' => $request->getMethod(), 'method' => strtoupper($request->getMethod()),
'endpoint' => $request->uri->getPath(), 'endpoint' => $request->uri->getPath(),
'getparams' => $request->uri->getSegments(), 'getparams' => json_encode($request->uri->getSegments(), JSON_UNESCAPED_UNICODE),
'postparams' => $request->getPost() 'postparams' => self::sanitizePostForLog($request->getPost()),
]; ];
$data['method'] = (isset($data['method']) ? strtoupper($data['method']) : $data['method']);
$data['getparams'] = is_array($data['getparams']) ? json_encode($data['getparams']) : $data['getparams'];
$data['postparams'] = is_array($data['postparams']) ? json_encode($data['postparams']) : $data['postparams'];
return $data; return $data;
} }
public static function add($payload)
{return $payload['a'] + $payload['b'];} /**
* Detect platform & browser from UA string (reliable fallback)
*/
private static function detectFromUserAgent(string $ua): array
{
$uaLower = strtolower($ua);
// =========================
// PLATFORM DETECTION
// =========================
$platform = 'Unknown';
if (str_contains($uaLower, 'windows nt 11') || str_contains($uaLower, 'windows 11')) {
$platform = 'Windows 11';
} elseif (str_contains($uaLower, 'windows nt 10')) {
$platform = 'Windows 10';
} elseif (str_contains($uaLower, 'windows nt 6.3')) {
$platform = 'Windows 8.1';
} elseif (str_contains($uaLower, 'windows nt 6.2')) {
$platform = 'Windows 8';
} elseif (str_contains($uaLower, 'windows nt 6.1')) {
$platform = 'Windows 7';
} elseif (str_contains($uaLower, 'windows nt 6.0')) {
$platform = 'Windows Vista';
} elseif (str_contains($uaLower, 'windows nt 5.1') || str_contains($uaLower, 'windows xp')) {
$platform = 'Windows XP';
} elseif (str_contains($uaLower, 'android')) {
$platform = 'Android';
} elseif (str_contains($uaLower, 'iphone')) {
$platform = 'iOS (iPhone)';
} elseif (str_contains($uaLower, 'ipad')) {
$platform = 'iOS (iPad)';
} elseif (str_contains($uaLower, 'ipod')) {
$platform = 'iOS (iPod)';
} elseif (str_contains($uaLower, 'mac os') || str_contains($uaLower, 'macintosh')) {
$platform = 'Mac OS';
} elseif (str_contains($uaLower, 'cros')) {
$platform = 'Chrome OS';
} elseif (str_contains($uaLower, 'linux')) {
$platform = 'Linux';
} elseif (str_contains($uaLower, 'freebsd')) {
$platform = 'FreeBSD';
} elseif (str_contains($uaLower, 'openbsd')) {
$platform = 'OpenBSD';
} elseif (str_contains($uaLower, 'netbsd')) {
$platform = 'NetBSD';
} elseif (str_contains($uaLower, 'unix')) {
$platform = 'Unix';
} elseif (str_contains($uaLower, 'symbian')) {
$platform = 'Symbian';
} elseif (str_contains($uaLower, 'blackberry')) {
$platform = 'BlackBerry';
} elseif (str_contains($uaLower, 'tizen')) {
$platform = 'Tizen';
} elseif (str_contains($uaLower, 'webos')) {
$platform = 'WebOS';
} elseif (str_contains($uaLower, 'kaios')) {
$platform = 'KaiOS';
} elseif (str_contains($uaLower, 'harmonyos')) {
$platform = 'HarmonyOS';
} elseif (str_contains($uaLower, 'watchos')) {
$platform = 'watchOS';
} elseif (str_contains($uaLower, 'tv os') || str_contains($uaLower, 'tvos')) {
$platform = 'tvOS';
}
// =========================
// BROWSER / CLIENT DETECTION
// =========================
$browser = 'Unknown';
// Bots & tools first
if (preg_match('/googlebot|bingbot|slurp|duckduckbot|baiduspider|yandexbot|sogou|exabot|facebot|ia_archiver/i', $ua)) {
$browser = 'Search Bot';
} elseif (preg_match('/postman/i', $ua)) {
$browser = 'Postman';
} elseif (preg_match('/insomnia/i', $ua)) {
$browser = 'Insomnia';
} elseif (preg_match('/curl/i', $ua)) {
$browser = 'curl';
} elseif (preg_match('/wget/i', $ua)) {
$browser = 'wget';
}
// Real browsers
elseif (preg_match('/edg\/([\d\.]+)/i', $ua, $m)) {
$browser = 'Edge ' . $m[1];
} elseif (preg_match('/opr\/([\d\.]+)/i', $ua, $m)) {
$browser = 'Opera ' . $m[1];
} elseif (preg_match('/vivaldi\/([\d\.]+)/i', $ua, $m)) {
$browser = 'Vivaldi ' . $m[1];
} elseif (preg_match('/brave\/([\d\.]+)/i', $ua, $m)) {
$browser = 'Brave ' . $m[1];
} elseif (preg_match('/chrome\/([\d\.]+)/i', $ua, $m)) {
$browser = 'Chrome ' . $m[1];
} elseif (preg_match('/firefox\/([\d\.]+)/i', $ua, $m)) {
$browser = 'Firefox ' . $m[1];
} elseif (preg_match('/safari\/([\d\.]+)/i', $ua, $m)) {
$browser = 'Safari ' . $m[1];
} elseif (preg_match('/msie\s([\d\.]+)/i', $ua, $m) || preg_match('/trident\/.*rv:([\d\.]+)/i', $ua, $m)) {
$browser = 'Internet Explorer ' . $m[1];
}
// In-app browsers
elseif (preg_match('/fbav|fban/i', $ua)) {
$browser = 'Facebook In-App Browser';
} elseif (preg_match('/instagram/i', $ua)) {
$browser = 'Instagram In-App Browser';
} elseif (preg_match('/linkedinapp/i', $ua)) {
$browser = 'LinkedIn In-App Browser';
} elseif (preg_match('/twitter/i', $ua)) {
$browser = 'Twitter/X In-App Browser';
}
return [$platform, $browser];
}
/**
* Remove sensitive fields before logging POST
*/
private static function sanitizePostForLog(array $post): string
{
if (empty($post)) {
return json_encode([]);
}
$sensitiveKeys = [
'password', 'pass', 'pwd',
'token', 'access_token', 'refresh_token',
'secret', 'api_key', 'authorization',
'otp', 'pin'
];
foreach ($post as $k => $v) {
foreach ($sensitiveKeys as $sk) {
if (stripos($k, $sk) !== false) {
$post[$k] = '***MASKED***';
}
}
}
return json_encode($post, JSON_UNESCAPED_UNICODE);
}
public static function add($payload)
{
return $payload['a'] + $payload['b'];
}
} }

View File

@ -18,24 +18,28 @@ use App\Models\LevelContactModel;
class JWTToken class JWTToken
{ {
private const ALLOWED_ALG = 'HS512';
public static function encode($data =null) public static function encode($data =null)
{ {
$secret_Key ="secret"; $secret_Key = env('JWT_SECRET');
$request_data = (array)$data; $request_data = (array)$data;
try{ try{
$token = JWT::encode($request_data ,$secret_Key,'HS512'); $token = JWT::encode($request_data ,$secret_Key,'HS512');
$id = $request_data['id']; $id = $request_data['id'];
$data["token_time_out"] = time() + getenv('TOKENTIMEOUT'); $update["token_time_out"] = time() + getenv('TOKENTIMEOUT');
if(isset($data['emp_code'])){ if(isset($data['emp_code'])){
$model = new EmployeeModel(); $model = new EmployeeModel();
$model->update($id, $data); $model->update($id, $update);
}else{ }else{
$models = new LevelContactModel(); $models = new LevelContactModel();
$models->update($id, $data); $id = $request_data['post_hr_id'];
$models->update($id, $update);
} }
@ -47,30 +51,79 @@ class JWTToken
} }
} }
public static function validateJWT($jwt) // public static function validateJWT($jwt)
// {
// $jwtParts = explode(' ', $jwt);
// // print_r($jwtParts);
// if (count($jwtParts) != 2 || $jwtParts[0] == 'Bearer') {
// return false;
// }
// $token = $jwtParts[1];
// try {
// $decoded = JWT::decode($token, new Key(env('JWT_SECRET'), 'HS512'));
// return json_encode(['status' => true, 'message' => 'Token is valid', 'decoded' => (array) $decoded]);
// } catch (ExpiredException $e) {
// return json_encode(['status' => false, 'message' => 'Token has expired']);
// } catch (BeforeValidException $e) {
// return json_encode(['status' => false, 'message' => 'Token is not yet valid']);
// } catch (SignatureInvalidException $e) {
// return json_encode(['status' => false, 'message' => 'Token signature is invalid']);
// } catch (\Exception $e) {
// return json_encode(['status' => false, 'message' => 'An error occurred while decoding the token']);
// }
// }
public static function validateJWT(string $authHeader)
{ {
$jwtParts = explode(' ', $jwt); // 1️⃣ Validate Authorization header
if (!preg_match('/^Bearer\s(\S+)$/', $authHeader, $matches)) {
// print_r($jwtParts); return ['status' => false, 'message' => 'Invalid Authorization header'];
if (count($jwtParts) != 2 || $jwtParts[0] == 'Bearer') {
return false;
} }
$token = $jwtParts[1]; $token = $matches[1];
// 2️⃣ Decode JWT header manually
$jwtParts = explode('.', $token);
if (count($jwtParts) !== 3) {
return ['status' => false, 'message' => 'Malformed JWT'];
}
$header = json_decode(base64_decode(strtr($jwtParts[0], '-_', '+/')), true);
// 3️⃣ Reject missing or NONE algorithm
if (
empty($header['alg']) ||
$header['alg'] === 'none' ||
$header['alg'] !== self::ALLOWED_ALG
) {
return ['status' => false, 'message' => 'Invalid or unsupported JWT algorithm'];
}
// 4️⃣ Enforce signature validation
try { try {
$decoded = JWT::decode($token, new Key("secret", 'HS512')); $decoded = JWT::decode(
return json_encode(['status' => true, 'message' => 'Token is valid', 'decoded' => (array) $decoded]); $token,
} catch (ExpiredException $e) { new Key(env('JWT_SECRET'), self::ALLOWED_ALG)
return json_encode(['status' => false, 'message' => 'Token has expired']); );
} catch (BeforeValidException $e) {
return json_encode(['status' => false, 'message' => 'Token is not yet valid']);
} catch (SignatureInvalidException $e) {
return json_encode(['status' => false, 'message' => 'Token signature is invalid']);
} catch (\Exception $e) {
return json_encode(['status' => false, 'message' => 'An error occurred while decoding the token']);
}
return [
'status' => true,
'decoded' => (array) $decoded
];
} catch (ExpiredException $e) {
return ['status' => false, 'message' => 'Token expired'];
} catch (BeforeValidException $e) {
return ['status' => false, 'message' => 'Token not yet valid'];
} catch (SignatureInvalidException $e) {
return ['status' => false, 'message' => 'Invalid token signature'];
} catch (\Exception $e) {
return ['status' => false, 'message' => 'Token validation failed'];
}
} }

View File

@ -1128,7 +1128,7 @@ if (!function_exists('premium_calculation_manager_old')) {
//if curent action is dependent addition OR addition then pull insurer master to set whether add one day from employee date of coverage //if curent action is dependent addition OR addition then pull insurer master to set whether add one day from employee date of coverage
if ($emp_data['temp']['action'] == 'DA' || $emp_data['temp']['action'] == 'A') { if ($emp_data['temp']['action'] == 'DA' || $emp_data['temp']['action'] == 'A') {
$insurer = new InsurerModel(); $insurer = new InsurerModel();
$insurer = ($insurer->find($policy_terms['insurer_id'])); $insurer = ($insurer->find((int)$policy_terms['insurer_id']));
if (isset($insurer['addition_add_day']) && $insurer['addition_add_day'] == true) { if (isset($insurer['addition_add_day']) && $insurer['addition_add_day'] == true) {
// $emp_data['policy_details']['date_coverage'] = (new DateTime($emp_data['policy_details']['date_coverage']))->modify('+1 day')->format('Y-m-d'); // $emp_data['policy_details']['date_coverage'] = (new DateTime($emp_data['policy_details']['date_coverage']))->modify('+1 day')->format('Y-m-d');
@ -1535,7 +1535,7 @@ if (!function_exists('premium_calculation_manager')) {
//if curent action is dependent addition OR addition then pull insurer master to set whether add one day from employee date of coverage //if curent action is dependent addition OR addition then pull insurer master to set whether add one day from employee date of coverage
if ($emp_data['temp']['action'] == 'DA' || $emp_data['temp']['action'] == 'A') { if ($emp_data['temp']['action'] == 'DA' || $emp_data['temp']['action'] == 'A') {
$insurer = new InsurerModel(); $insurer = new InsurerModel();
$insurer = ($insurer->find($policy_terms['insurer_id'])); $insurer = ($insurer->find((int)$policy_terms['insurer_id']));
if (isset($insurer['addition_add_day']) && $insurer['addition_add_day'] == true) { if (isset($insurer['addition_add_day']) && $insurer['addition_add_day'] == true) {
// $emp_data['policy_details']['date_coverage'] = (new DateTime($emp_data['policy_details']['date_coverage']))->modify('+1 day')->format('Y-m-d'); // $emp_data['policy_details']['date_coverage'] = (new DateTime($emp_data['policy_details']['date_coverage']))->modify('+1 day')->format('Y-m-d');
@ -1884,7 +1884,7 @@ if (!function_exists('premium_calculation_manager')) {
} }
// if the family floater case first self add first the process completed, after spouse or any dependent add the rata premium not added this change will handle this // if the family floater case first self add first the process completed, after spouse or any dependent add the rata premium not added this change will handle this
if (strtolower($emp_data['relationship']) != 'self' && $temp_slab_rates[0]['premium_type'] == 1 && $emp_data['temp']['action'] == 'DA') { if (strtolower($emp_data['relationship']) != 'self' && empty($emp_data['temp']['acting_self']) && $temp_slab_rates[0]['premium_type'] == 1 && $emp_data['temp']['action'] == 'DA') {
//set dependent si to 0 //set dependent si to 0
$emp_data['policy_details']['basic_cover_si'] = 0; $emp_data['policy_details']['basic_cover_si'] = 0;
$emp_data['policy_details']['premium'] = 0; $emp_data['policy_details']['premium'] = 0;
@ -1897,7 +1897,7 @@ if (!function_exists('premium_calculation_manager')) {
$emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', ''); $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
} }
}else if(strtolower($emp_data['relationship']) != 'self' && $temp_slab_rates[0]['premium_type'] == 1 && ($emp_data['temp']['action'] == 'I' || $emp_data['temp']['action'] == 'A' || $emp_data['temp']['action'] == 'MI')){ }else if(strtolower($emp_data['relationship']) != 'self' && empty($emp_data['temp']['acting_self']) && $temp_slab_rates[0]['premium_type'] == 1 && ($emp_data['temp']['action'] == 'I' || $emp_data['temp']['action'] == 'A' || $emp_data['temp']['action'] == 'MI')){
$emp_data['policy_details']['basic_cover_si'] = 0; $emp_data['policy_details']['basic_cover_si'] = 0;
$emp_data['policy_details']['premium'] = 0; $emp_data['policy_details']['premium'] = 0;
@ -2000,8 +2000,9 @@ if (!function_exists('get_emp_records_from_audit_history')) {
function get_emp_records_from_audit_history($employee_id) function get_emp_records_from_audit_history($employee_id)
{ {
$db = db_connect(); $db = db_connect();
$query = "SELECT min(id) as id,pk,table_name,field_name,old_value FROM auditing_history where pk = $employee_id and table_name = 'employees' and field_name in ('name','dob','gender','mobile','email_corporate','relationship') group by field_name order by id asc"; $query = "SELECT min(id) as id,pk,table_name,field_name,old_value FROM auditing_history where pk = :employee_id: and table_name = 'employees' and field_name in ('name','dob','gender','mobile','email_corporate','relationship') group by field_name order by id asc";
$res = $db->query($query); $binds = ['employee_id'=>(int)$employee_id];
$res = $db->query($query,$binds);
// echo $db->getLastQuery(); // echo $db->getLastQuery();
$res = $res->getResultArray(); $res = $res->getResultArray();
if (count($res)) { if (count($res)) {
@ -2019,8 +2020,9 @@ if (!function_exists('get_emp_policy_records_from_audit_history')) {
function get_emp_policy_records_from_audit_history($emp_policy_id) function get_emp_policy_records_from_audit_history($emp_policy_id)
{ {
$db = db_connect(); $db = db_connect();
$query = "SELECT min(id) as id,pk,table_name,field_name,old_value FROM auditing_history where pk = $emp_policy_id and table_name = 'employee_polices' and field_name in ('basic_cover_si','premium','gst') group by field_name order by id asc"; $query = "SELECT min(id) as id,pk,table_name,field_name,old_value FROM auditing_history where pk = :emp_policy_id: and table_name = 'employee_polices' and field_name in ('basic_cover_si','premium','gst') group by field_name order by id asc";
$res = $db->query($query); $binds = ['emp_policy_id'=>(int)$emp_policy_id];
$res = $db->query($query,$binds);
// echo $db->getLastQuery(); // echo $db->getLastQuery();
$res = $res->getResultArray(); $res = $res->getResultArray();
if (count($res)) { if (count($res)) {
@ -3147,7 +3149,7 @@ if (!function_exists('check_agent_exist')) {
// Loop agent data from DB // Loop agent data from DB
foreach ($agent_data as $agent) { foreach ($agent_data as $agent) {
// Assuming DB keys: agent_code // Assuming DB keys: agent_code
if (isset($agent['agent_code']) && $agent['agent_code'] == $agent_code) { if (isset($agent['pos_code']) && (strtolower($agent['pos_code']) == strtolower($agent_code))) {
return [ return [
'status' => true, 'status' => true,
'error' => null, 'error' => null,
@ -3171,6 +3173,24 @@ if (!function_exists('check_rto_data')) {
$vehicle_no = strtoupper(trim($row[2])); // Example: TN10AB1234 $vehicle_no = strtoupper(trim($row[2])); // Example: TN10AB1234
$new_vehicle = strtolower(trim($row[2])); $new_vehicle = strtolower(trim($row[2]));
if(!validate_indian_vehicle_number($vehicle_no)['status']){
return [
'status' => false,
'error' => 'Invalid Vehicle Number. Format should be like TN82AX2024 (no spaces or special characters).'
];
};
// BH Series: 22BH1234AA
$bhPattern = '/^[0-9]{2}BH[0-9]{4}[A-Z]{2}$/';
if (preg_match($bhPattern, $vehicle_no)) {
return [
'status' => true,
'error' => null,
'rto_data' => []
];
}
if($new_vehicle == "new"){ if($new_vehicle == "new"){
return [ return [
'status' => true, 'status' => true,

View File

@ -0,0 +1,84 @@
<?php
// use Normalizer;
/**
* High security sanitizer
* - Normalizes unicode
* - Removes control chars
* - Removes null bytes
* - Removes invisible unicode tricks
* - Strips dangerous HTML
* - Prevents polyglot payloads
*/
function sanitizeInputArrayAdvanced(array $data, array $htmlAllowedFields = []): array
{
foreach ($data as $k => $v) {
if (is_array($v)) {
$data[$k] = sanitizeInputArrayAdvanced($v, $htmlAllowedFields);
continue;
}
if (!is_string($v)) {
continue;
}
// 1. Unicode normalization (prevents homoglyph attacks)
if (class_exists('Normalizer')) {
$v = \Normalizer::normalize($v, \Normalizer::FORM_C);
}
// 2. Remove NULL bytes & control chars
$v = preg_replace('/[\x00-\x1F\x7F]/u', '', $v);
// 3. Remove invisible unicode chars (zero width, etc)
$v = preg_replace('/[\x{200B}-\x{200F}\x{202A}-\x{202E}\x{2060}-\x{206F}]/u', '', $v);
// 4. Decode HTML entities (so hidden payloads are exposed)
$v = html_entity_decode($v, ENT_QUOTES | ENT_HTML5, 'UTF-8');
// 5. Trim
$v = trim($v);
// 6. If this field is NOT allowed to contain HTML → strip aggressively
if (!in_array($k, $htmlAllowedFields, true)) {
// Remove all tags
$v = strip_tags($v);
// Kill any leftover JS protocol
$v = preg_replace('/(javascript:|data:|vbscript:)/i', '', $v);
} else {
// This is HTML-allowed field → run HTML sanitizer
$v = sanitizeTrustedHtml($v);
}
$data[$k] = $v;
}
return $data;
}
function sanitizeTrustedHtml(string $html): string
{
// Allowed tags for email templates
$allowedTags = '<p><br><b><strong><i><u><em><ul><ol><li><table><thead><tbody><tr><td><th><a><img><div><span><h1><h2><h3><h4><h5><h6>';
// Strip all other tags
$html = strip_tags($html, $allowedTags);
// Remove event handlers like onclick, onerror, etc
$html = preg_replace('/\son\w+="[^"]*"/i', '', $html);
$html = preg_replace("/\son\w+='[^']*'/i", '', $html);
// Remove javascript: and data:
$html = preg_replace('/(javascript:|vbscript:|data:)/i', '', $html);
// Remove iframe, object, embed even if sneaked in
$html = preg_replace('/<(iframe|object|embed|script|style)[^>]*>.*?<\/\1>/is', '', $html);
return $html;
}

View File

@ -116,6 +116,21 @@ class sendMailNotification
$tpa_id = $params['tpa_id']; $tpa_id = $params['tpa_id'];
$common = $params['common']; $common = $params['common'];
$mailAttachmentModel = new MailAttachmentModel();
$attachment_data = $mailAttachmentModel
->select('file_path, file_name')
->where('notification_id', $notification['id'])
->where('is_active', 1)
->findAll();
$attachments = [];
foreach ($attachment_data as $data) {
$attachments[] = [
"filePath" => WRITEPATH . $data['file_path'],
"fileName" => $data['file_name']
];
}
$mail_content = $notification['mail_content']; $mail_content = $notification['mail_content'];
$mail = $get_emp_email_and_other_details['email_corporate']; $mail = $get_emp_email_and_other_details['email_corporate'];
@ -160,7 +175,7 @@ class sendMailNotification
$mail_content = view('mail_template', $data); $mail_content = view('mail_template', $data);
$wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content,'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to'], 'common' => $common]; $wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content,'bcc'=> $client_data['common_mails'],'attachments' => $attachments, 'reply_to' => $client_data['reply_to'], 'common' => $common];
return $wholeData; return $wholeData;

View File

@ -21,7 +21,7 @@ if(!function_exists('check_cookie')){
'userProfile' => $value['userProfile'], 'userProfile' => $value['userProfile'],
'user_team' => $user_team, 'user_team' => $user_team,
]; ];
set_session_data($session_data); // set_session_data($session_data);
// $this->getUserDeviceInfo($user->id, 'NhanceUser'); // $this->getUserDeviceInfo($user->id, 'NhanceUser');
// return redirect()->to(base_url('/dashboard/view')); // return redirect()->to(base_url('/dashboard/view'));
return true; return true;
@ -34,13 +34,14 @@ if(!function_exists('check_cookie')){
return false; return false;
} }
} }
}
if (!function_exists('check_session')) { if (!function_exists('check_session')) {
function check_session() function check_session()
{ {
// $ci =& get_instance(); // $ci =& get_instance();
$session = \Config\Services::session(); $session = \Config\Services::session();
return $session->get('isLoggedIn'); return $session->get('isLoggedIn') === true;
} }
} }
@ -117,7 +118,8 @@ if (!function_exists('check_role')) {
{ {
// $ci =& get_instance(); // $ci =& get_instance();
$session = \Config\Services::session(); $session = \Config\Services::session();
return $session->get('role'); return $role_id = isset(get_session_userdata()->role) ? get_session_userdata()->role : null;
} }
} }
@ -201,7 +203,6 @@ if (!function_exists('get_chatbot_session_info')) {
} }
}

View File

@ -6,6 +6,7 @@ use App\Models\BatchFileModelFileModel;
use App\Controllers\GoogleDriveController; use App\Controllers\GoogleDriveController;
use App\Models\BatchFileModel; use App\Models\BatchFileModel;
use App\Controllers\ApiServiceController; use App\Controllers\ApiServiceController;
use App\Models\TicketMasterModel;
// File: app/Helpers/Uuid_helper.php // File: app/Helpers/Uuid_helper.php
@ -639,6 +640,8 @@ if (!function_exists('change_date_format')) {
'd/m/Y', // 01/01/2025 'd/m/Y', // 01/01/2025
'd-m-Y', // 01-01-2025 'd-m-Y', // 01-01-2025
'm/d/Y h:i:s A', // 01-01-2025
'm/d/Y', // 25-05-2025
]; ];
@ -648,7 +651,7 @@ if (!function_exists('change_date_format')) {
$date = DateTime::createFromFormat($source_format, $date_str); $date = DateTime::createFromFormat($source_format, $date_str);
if (!$date) { if (!$date) {
// throw new Exception("Invalid date string for source format: $source_format"); // throw new Exception("Invalid date string for source format: $source_format");
log_message('error', "❌ Date format error : Invalid date string | Params => date_str: {$date_str}, source_format: {$source_format}, output_format: {$output_format}"); // log_message('error', "❌ Date format error : Invalid date string | Params => date_str: {$date_str}, source_format: {$source_format}, output_format: {$output_format}");
return null; return null;
} }
return $date->format($output_format); return $date->format($output_format);
@ -659,7 +662,7 @@ if (!function_exists('change_date_format')) {
$date = DateTime::createFromFormat($source_format, $date_str); $date = DateTime::createFromFormat($source_format, $date_str);
if (!$date) { if (!$date) {
// throw new Exception("Invalid date string for source format: $source_format"); // throw new Exception("Invalid date string for source format: $source_format");
log_message('error', "❌ Date format error : Invalid date string | Params => date_str: {$date_str}, source_format: {$source_format}, output_format: {$output_format}"); // log_message('error', "❌ Date format error : Invalid date string | Params => date_str: {$date_str}, source_format: {$source_format}, output_format: {$output_format}");
return null; return null;
} }
return $date->format('Y-m-d'); // MySQL default format return $date->format('Y-m-d'); // MySQL default format
@ -676,15 +679,15 @@ if (!function_exists('change_date_format')) {
// If no format matches, throw an exception // If no format matches, throw an exception
$allowed_placeholders = implode(', ', $allowed_formats); $allowed_placeholders = implode(', ', $allowed_formats);
// throw new Exception("Invalid date string format. Allowed formats: $allowed_placeholders"); // throw new Exception("Invalid date string format. Allowed formats: $allowed_placeholders");
log_message( // log_message(
'error', // 'error',
"❌ Date format error: Invalid date string. Allowed formats: {$allowed_placeholders} | Params => date_str: {$date_str}, source_format: {$source_format}, output_format: {$output_format}" // "❌ Date format error: Invalid date string. Allowed formats: {$allowed_placeholders} | Params => date_str: {$date_str}, source_format: {$source_format}, output_format: {$output_format}"
); // );
return null; return null;
} }
} catch (Exception $e) { } catch (Exception $e) {
// return "Error: " . $e->getMessage(); // return "Error: " . $e->getMessage();
log_message('error', "❌ Date format error: {$e->getMessage()} | Params => date_str: {$date_str}, source_format: {$source_format}, output_format: {$output_format}"); // log_message('error', "❌ Date format error: {$e->getMessage()} | Params => date_str: {$date_str}, source_format: {$source_format}, output_format: {$output_format}");
return null; return null;
} }
@ -940,6 +943,44 @@ if (!function_exists('getMimeTypeByFileName')) {
} }
} }
if (!function_exists('validateExcelFile')) {
function validateExcelFile($file)
{
// 1. Check if the file was uploaded without errors
if (! $file->isValid() || $file->hasMoved()) {
return false;
}
// 2. Size check (16MB)
if ($file->getSizeByUnit('mb') > 16) {
return false;
}
// 3. Define allowed types
$allowedMimes = [
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.oasis.opendocument.spreadsheet',
'application/zip',
'application/octet-stream'
];
$allowedExtensions = ['xls', 'xlsx', 'ods', 'xlsm'];
// Get the actual values using CI4 methods
$mime = $file->getClientMimeType();
$extension = $file->getExtension(); // This is the CI4 method
// 4. Validate
if (in_array($mime, $allowedMimes) || in_array($extension, $allowedExtensions)) {
return true;
}
return false;
}
}
if (!function_exists('generate_ecard_download_link_based_on_tpa')) { if (!function_exists('generate_ecard_download_link_based_on_tpa')) {
function generate_ecard_download_link_based_on_tpa($params) { function generate_ecard_download_link_based_on_tpa($params) {
@ -956,3 +997,154 @@ if (!function_exists('generate_ecard_download_link_based_on_tpa')) {
} }
} }
if (!function_exists('canSendOtp')) {
function canSendOtp(array $row, int $limitSeconds = 60): array
{
// If OTP does not exist → allow
if (empty($row['otp']) || empty($row['updated_at'])) {
return ['allowed' => true];
}
$lastUpdated = strtotime($row['updated_at']);
$currentTime = time();
// Calculate expiry time
$allowedAfter = $lastUpdated + $limitSeconds;
// If still within limit → block
if ($currentTime < $allowedAfter) {
return [
'allowed' => false,
'retry_after' => $allowedAfter - $currentTime
];
}
return ['allowed' => true];
}
}
if (!function_exists('checkDuplicateClaim')) {
function checkDuplicateClaim(array $params): bool
{
$ticketMaster = new TicketMasterModel();
$query = $ticketMaster->where('is_active', 1);
if(empty($params['doa']) && empty($params['claim_amount'])){
return false;
}
$hasValidCondition = false;
foreach ($params as $key => $value) {
if ($value !== null && $value !== '') {
$query->where($key, $value);
$hasValidCondition = true;
}
}
if (!$hasValidCondition) {
return false;
}
$result = $query->countAllResults();
// print_r($ticketMaster->getLastQuery()->getQuery()); die;
if($result > 0){ return true; }else{ return false; }
}
}
function getRealClientIP()
{
$request = service('request');
if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
return $_SERVER['HTTP_CF_CONNECTING_IP'];
}
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
return explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
}
return $request->getIPAddress();
}
function generateFingerprint()
{
$request = service('request');
$ua = $request->getUserAgent()->getAgentString();
$ip = getRealClientIP();
// Use only subnet (first 3 blocks) to tolerate IP change
$ipParts = explode('.', $ip);
$ipSubnet = $ipParts[0] . '.' . $ipParts[1] . '.' . $ipParts[2];
// $secret = env('app.sessionFingerprintSalt');
// return hash('sha256', $ua . '|' . $ipSubnet . '|' . $secret);
return hash('sha256', $ua . '|' . $ipSubnet );
}
if (!function_exists('convertGoogleDriveToDownloadLink')) {
function convertGoogleDriveToDownloadLink(?string $url): ?string
{
if (empty($url)) {
return null;
}
// Trim spaces
$url = trim($url);
// Pattern to extract Google Drive file ID
$patterns = [
'#https?://drive\.google\.com/file/d/([^/]+)/?#',
'#https?://drive\.google\.com/open\?id=([^&]+)#',
'#https?://drive\.google\.com/uc\?id=([^&]+)#'
];
foreach ($patterns as $pattern) {
if (preg_match($pattern, $url, $matches)) {
$fileId = $matches[1];
// Return direct download link
return 'https://drive.google.com/uc?export=download&id=' . $fileId;
}
}
// Not a Google Drive link → return original
return $url;
}
}
if (!function_exists('get_cd_balance')) {
function get_cd_balance(): array
{
$session = session();
return [
'has_cd_balance' => $session->has('cd_balance'),
'cd_balance' => $session->get('cd_balance') ?? null,
'hr_data' => $session->get('hr_data') ?? [],
'cd_balance_info' => $session->get('cd_balance_info') ?? [],
];
}
}
if (!function_exists('clear_cd_balance_session')) {
function clear_cd_balance_session(): void
{
$session = session();
$session->remove('cd_balance');
$session->remove('hr_data');
$session->remove('cd_balance_info');
log_message('error', 'clear_cd_balance_session clered');
}
}

View File

@ -0,0 +1,42 @@
<?php
namespace App\Libraries;
use CodeIgniter\HTTP\RedirectResponse;
class AuthLogout
{
public static function logout(): RedirectResponse
{
$session = session();
// Regenerate session ID (kills fixation)
$session->regenerate(true);
// Destroy CI session
$session->destroy();
// Kill PHP session cookie safely
if (ini_get('session.use_cookies')) {
$params = session_get_cookie_params();
setcookie(
session_name(), // DO NOT hardcode cookie name
null,
time() - 42000,
$params['path'],
$params['domain'],
$params['secure'],
$params['httponly']
);
}
session_write_close();
// Redirect with anti-cache headers
return redirect()->to(base_url('login'))
->setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
->setHeader('Pragma', 'no-cache')
->setHeader('Expires', 'Sat, 26 Jul 1997 05:00:00 GMT');
}
}

View File

@ -0,0 +1,448 @@
<?php
namespace App\Libraries\TPAClaimsImportServices;
use App\Models\TicketMasterModel;
use App\Models\ClientPolicyModel;
use App\Models\ClientRMModel;
use App\Models\EmployeeModel;
use App\Models\ClaimDumpFileModel;
class AbhiClaimImportService extends BaseTpaClaimImportService
{
/**
* MAPPING ARRAYs
*/
protected $mapping = [
["excel_column" => ["col_name" => "ABHI Claim No", "col_index" => 0], "db_column" => "abhi_claim_no"],
["excel_column" => ["col_name" => "New ABHI Claim No With Extension", "col_index" => 1], "db_column" => "new_abhi_claim_no_with_extension"],
["excel_column" => ["col_name" => "Unique Count", "col_index" => 2], "db_column" => "unique_count"],
["excel_column" => ["col_name" => "Proposer Name", "col_index" => 3], "db_column" => "proposer_name"],
["excel_column" => ["col_name" => "Patient Name", "col_index" => 4], "db_column" => "patient_name"],
["excel_column" => ["col_name" => "Family ID", "col_index" => 5], "db_column" => "family_id"],
["excel_column" => ["col_name" => "Member Code", "col_index" => 6], "db_column" => "member_code"],
["excel_column" => ["col_name" => "Patient Age", "col_index" => 7], "db_column" => "patient_age"],
["excel_column" => ["col_name" => "Relation", "col_index" => 8], "db_column" => "relation"],
["excel_column" => ["col_name" => "Gender", "col_index" => 9], "db_column" => "gender"],
["excel_column" => ["col_name" => "Certificate No", "col_index" => 10], "db_column" => "certificate_no"],
["excel_column" => ["col_name" => "Master Policy No", "col_index" => 11], "db_column" => "master_policy_no"],
["excel_column" => ["col_name" => "Policy Number", "col_index" => 12], "db_column" => "policy_number"],
["excel_column" => ["col_name" => "Policy From", "col_index" => 13], "db_column" => "policy_from"],
["excel_column" => ["col_name" => "Policy Upto", "col_index" => 14], "db_column" => "policy_upto"],
["excel_column" => ["col_name" => "Product Name", "col_index" => 15], "db_column" => "product_name"],
["excel_column" => ["col_name" => "Product Name 1", "col_index" => 16], "db_column" => "product_name_1"],
["excel_column" => ["col_name" => "Sub - Product", "col_index" => 17], "db_column" => "sub_product"],
["excel_column" => ["col_name" => "Policy Category", "col_index" => 18], "db_column" => "policy_category"],
["excel_column" => ["col_name" => "Policy Category (Carry Forward till Q3 18-19)+(New Q4 18-19 Onward)", "col_index" => 19], "db_column" => "policy_category_cf_q3_q4"],
["excel_column" => ["col_name" => "Sum Insured", "col_index" => 20], "db_column" => "sum_insured"],
["excel_column" => ["col_name" => "Bonus", "col_index" => 21], "db_column" => "bonus"],
["excel_column" => ["col_name" => "Intimation Date", "col_index" => 22], "db_column" => "intimation_date"],
["excel_column" => ["col_name" => "Date Of Doc Rec", "col_index" => 23], "db_column" => "date_of_doc_rec"],
["excel_column" => ["col_name" => "Intimation Final Month", "col_index" => 24], "db_column" => "intimation_final_month"],
["excel_column" => ["col_name" => "Reported Year", "col_index" => 25], "db_column" => "reported_year"],
["excel_column" => ["col_name" => "Reported Qurter", "col_index" => 26], "db_column" => "reported_quarter"],
["excel_column" => ["col_name" => "Hospital Name", "col_index" => 27], "db_column" => "hospital_name"],
["excel_column" => ["col_name" => "Hospital City", "col_index" => 28], "db_column" => "hospital_city"],
["excel_column" => ["col_name" => "Hospital State", "col_index" => 29], "db_column" => "hospital_state"],
["excel_column" => ["col_name" => "Diagnosis", "col_index" => 30], "db_column" => "diagnosis"],
["excel_column" => ["col_name" => "ICD Chapter", "col_index" => 31], "db_column" => "icd_chapter"],
["excel_column" => ["col_name" => "ICD Block", "col_index" => 32], "db_column" => "icd_block"],
["excel_column" => ["col_name" => "ICD Level1", "col_index" => 33], "db_column" => "icd_level1"],
["excel_column" => ["col_name" => "ICD Level2", "col_index" => 34], "db_column" => "icd_level2"],
["excel_column" => ["col_name" => "Procedure Description", "col_index" => 35], "db_column" => "procedure_description"],
["excel_column" => ["col_name" => "PCS Description", "col_index" => 36], "db_column" => "pcs_description"],
["excel_column" => ["col_name" => "DOA", "col_index" => 37], "db_column" => "doa"],
["excel_column" => ["col_name" => "DOD", "col_index" => 38], "db_column" => "dod"],
["excel_column" => ["col_name" => "Claim Type", "col_index" => 39], "db_column" => "claim_type"],
["excel_column" => ["col_name" => "Claim Category", "col_index" => 40], "db_column" => "claim_category"],
["excel_column" => ["col_name" => "Disc Datails", "col_index" => 41], "db_column" => "disc_details"],
["excel_column" => ["col_name" => "Disc Date", "col_index" => 42], "db_column" => "disc_date"],
["excel_column" => ["col_name" => "Hospital Code", "col_index" => 43], "db_column" => "hospital_code"],
["excel_column" => ["col_name" => "Claim Status", "col_index" => 44], "db_column" => "claim_status"],
["excel_column" => ["col_name" => "Final ABHI Status-Current Month", "col_index" => 45], "db_column" => "final_abhi_status_current_month"],
["excel_column" => ["col_name" => "Claimed Amount", "col_index" => 46], "db_column" => "claimed_amount"],
["excel_column" => ["col_name" => "ABHI Amount Less Coins - Current Month", "col_index" => 47], "db_column" => "abhi_amount_less_coins_current_month"],
["excel_column" => ["col_name" => "Repudiation Date", "col_index" => 48], "db_column" => "repudiation_date"],
["excel_column" => ["col_name" => "Settled Date", "col_index" => 49], "db_column" => "settled_date"],
["excel_column" => ["col_name" => "Settled Month", "col_index" => 50], "db_column" => "settled_month"],
["excel_column" => ["col_name" => "Settled Year", "col_index" => 51], "db_column" => "settled_year"],
["excel_column" => ["col_name" => "Settled Quarter", "col_index" => 52], "db_column" => "settled_quarter"],
["excel_column" => ["col_name" => "Rejection Category", "col_index" => 53], "db_column" => "rejection_category"],
["excel_column" => ["col_name" => "Rejection Category - Level 1", "col_index" => 54], "db_column" => "rejection_category_level_1"],
["excel_column" => ["col_name" => "Rejection Category - Level 2", "col_index" => 55], "db_column" => "rejection_category_level_2"],
["excel_column" => ["col_name" => "COVID tagging - Current Month", "col_index" => 56], "db_column" => "covid_tagging_current_month"],
["excel_column" => ["col_name" => "EXPECTED DOA", "col_index" => 57], "db_column" => "expected_doa"],
["excel_column" => ["col_name" => "EXPECTED DOD", "col_index" => 58], "db_column" => "expected_dod"],
["excel_column" => ["col_name" => "AGENT/BROKER CODE", "col_index" => 59], "db_column" => "agent_broker_code"],
["excel_column" => ["col_name" => "AGENT/BROKER NAME", "col_index" => 60], "db_column" => "agent_broker_name"],
["excel_column" => ["col_name" => "HEALTHCARD_ID", "col_index" => 61], "db_column" => "healthcard_id"],
["excel_column" => ["col_name" => "ABHI_NETWORK_NON_NETWORK", "col_index" => 62], "db_column" => "abhi_network_non_network"],
["excel_column" => ["col_name" => "CORPORATE_EMPLOYEE_CODE", "col_index" => 63], "db_column" => "corporate_employee_code"],
];
protected $ticketMasterMapping = [
// Employee / Member details
'member_code' => 'emp_code',
'abhi_claim_no' => 'claim_number',
// Dates
'doa' => 'doa',
'dod' => 'dod',
'intimation_date' => 'date_of_intimat',
// Claim info
'claim_status' => 'tpa_claim_status',
'claimed_amount' => 'claim_amount',
// Hospital details
'hospital_name' => 'hospital_name',
'hospital_city' => 'hospital_city',
'hospital_state' => 'hospital_state',
// Settlement / decision
'repudiation_date' => 'denial_date',
'settled_date' => 'settled_date',
'rejection_category' => 'denial_reason',
// Misc
'diagnosis' => 'claim_description',
'healthcard_id' => 'tpa_no',
'claim_type' => 'tpa_claim_type',
'diagnosis' => 'tpa_ailments',
];
protected $statusMapping = [
'Settled' => 11,
'Rejected' => 8,
'Cancelled' => 13,
];
protected $dateColumns = [
'policy_from',
'policy_upto',
'intimation_date',
'date_of_doc_rec',
'doa',
'dod',
'repudiation_date',
'settled_date',
'expected_doa',
'expected_dod',
];
/**
* ABSTRACT FUNCTIONs
*/
public function bulkInsertTPATable(array $data): bool
{
if (empty($data)) {
return false;
}
$builder = $this->db->table('claims_dump_abhi');
return $builder->insertBatch($data);
}
public function importClaimMaster(array $data): bool
{
if (empty($data)) {
return false;
}
$ticketMasterModel = new TicketMasterModel();
return $ticketMasterModel->insertBatch($data);
}
public function updateTicketIdInTPATable(): bool
{
if (empty($data)) {
return false;
}
$builder = $this->db->table('claims_dump_abhi');
return $builder->updateBatch($data, 'id');
}
public function updateTicketMasterRejectedReasonInTPATable($data): bool
{
if (empty($data)) {
return false;
}
$builder = $this->db->table('claims_dump_abhi');
return $builder->updateBatch($data, 'id');
}
/**
* MAPPING FUNCTIONs
*/
public function mapTPAData(array $rows, $file_id): array
{
$ClientPolicyModel = new ClaimDumpFileModel();
$file_data = $ClientPolicyModel->where('id', $file_id)->first();
$mapped = [];
foreach ($rows as $row) {
$item = [];
foreach ($this->mapping as $map) {
$excelColumn = $map['excel_column']['col_name'];
$dbColumn = $map['db_column'];
$value = $row[$excelColumn] ?? null;
$item[$dbColumn] = trim($value);
}
foreach ($this->dateColumns as $key => $value) {
$item[$value] = change_date_format($item[$value] ?? null, 'm/d/Y h:i:s A', 'Y-m-d');
}
$params = [
'doa' => $item['doa'] ?? null,
'member_code' => $item['member_code'] ?? null,
'claimed_amount' => $item['claimed_amount'] ?? null,
'healthcard_id' => $item['healthcard_id'] ?? null
];
$is_duplicate = $this->checkDuplicateTpaClaim('claims_dump_abhi', $params);
if ($is_duplicate) {
$item = [];
continue;
}
$item['file_id'] = $file_id ?? null;
$item['client_id'] = $file_data['client_id'] ?? null;
$item['client_policy_id'] = $file_data['client_policy_id'] ?? null;
$item['created_by'] = $file_data['created_by'] ?? null;
$mapped[] = $item;
}
return $mapped;
}
public function mapClaimMasterData($file_id): array
{
$ClientPolicyModel = new ClaimDumpFileModel();
$file_data = $ClientPolicyModel->where('id', $file_id)->first();
$tpaClaimDumpData = $this->getTpaClaimDumpData('claims_dump_abhi', ['file_id' => $file_id]);
if (empty($tpaClaimDumpData)) {
return ['status' => false, 'message' => "No data to insert in TICKET MASTER"];
}
$ClientPolicyModel = new ClientPolicyModel();
$client_policy_data = $ClientPolicyModel
->select("
client_policy.*,
(
SELECT id
FROM client_rm
WHERE is_active = 1
AND level = 3
AND client_id = client_policy.client_id
ORDER BY id ASC
LIMIT 1
) AS acm_id
")
->where('client_policy.id', $file_data['client_policy_id'])
->where('client_policy.is_active', 1)
->first();
try {
$mapped = [];
$rejecetd_reason = [];
foreach ($tpaClaimDumpData as $row) {
$params = [
'doa' => change_date_format($row['doa'] ?? '') ?? null,
'emp_code' => $row['member_code'] ?? null,
'claim_amount' => $row['claimed_amount'] ?? null,
'tpa_no' => $row['healthcard_id'] ?? null
];
$isduplicate = $this->checkDublicateTicketMasterClaim($params);
if ($isduplicate) {
$reason = "This claim already exists in our system.";
$rejecetd_reason[] = ["id" => $row['id'], "master_reject_reason" => $reason];
continue;
}
$item = [];
$item['client_id'] = $client_policy_data['client_id'] ?? null;
$item['client_policy_id'] = $client_policy_data['id'] ?? null;
$item['insurer_id'] = $client_policy_data['insurer_id'] ?? null;
$item['tpa_id'] = $client_policy_data['tpa_id'] ?? null;
$item['acm_id'] = $client_policy_data['acm_id'] ?? null;
$item['policy_no'] = $client_policy_data['policy_no'] ?? null;
$item['relationship'] = $this->convertRelation($row['relation'] ?? null);
$employee_data = $this->getEmployeeDetails($file_data['client_id'], $file_data['client_policy_id'], $row['member_code'], $item['relationship']);
if (!empty($employee_data)) {
$item['emp_id'] = $employee_data['id'] ?? null;
$item['emp_name'] = $employee_data['name'] ?? null;
$item['emp_code'] = $employee_data['emp_code'] ?? null;
$item['emp_mail'] = $employee_data['email_corporate'] ?? null;
$item['emp_mobile'] = $employee_data['mobile'] ?? null;
if (!empty($employee_data['insured_emp_id'])) {
$item['insured_emp_id'] = $employee_data['insured_emp_id'] ?? null;
$item['insured_name'] = $employee_data['insured_name'] ?? null;
}else{
$reason = 'This Dependent employee not exist in our system.';
$rejecetd_reason[] = ["id" => $row['id'], "master_reject_reason" => $reason];
continue;
}
} else {
$reason = 'This employee not exist in our system.';
$rejecetd_reason[] = ["id" => $row['id'], "master_reject_reason" => $reason];
continue;
}
foreach ($this->ticketMasterMapping as $tpaKey => $ticketMasterKey) {
$item[$ticketMasterKey] = array_key_exists($tpaKey, $row) ? $row[$tpaKey] : null;
}
// Meta fields
$item['claim_status_id'] = $statusMapping[$row['claim_status']] ?? 61;
$item['file_id'] = $file_id;
$item['claim_dump_ref_id'] = $row['id'];
$item['created_by'] = $file_data['created_by'] ?? null;
$item['claim_type'] = isset($row['mainclaim_prepost_type']) && !empty($row['mainclaim_prepost_type']) && strtolower($row['mainclaim_prepost_type']) == 'normal' ? 1 : 3;
$item['priority'] = 1;
$item['mode_of_intimation'] = 5;
$item['ticket_type_id'] = 1;
$mapped[] = $item;
}
return ['status' => true, 'mapped_array' => $mapped, 'rejected_reason_array' => $rejecetd_reason];
} 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,
];
return ['status' => false, "message" => $errorData['message'], 'error_data' => $errorData];
}
}
/**
* HELPER FUNCTIONs
*/
public function isDateValue($value): bool
{
if (empty($value)) {
return false;
}
// Excel numeric date
if (is_numeric($value) && $value > 30000) {
return true;
}
return strtotime(str_replace('/', '-', $value)) !== false;
}
public function normalizeDate($value): ?string
{
try {
if (empty($value)) {
return null;
}
// Excel numeric date
if (is_numeric($value)) {
return date(
'Y-m-d',
\PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($value)
);
}
$value = trim((string) $value);
// Replace / with - for strtotime compatibility
$value = str_replace('/', '-', $value);
$timestamp = strtotime($value);
if ($timestamp === false) {
return null;
}
return date('Y-m-d', $timestamp);
} catch (\Throwable $e) {
return null;
}
}
public function convertRelation(?string $relation): ?string
{
if (empty($relation)) {
return null;
}
// trim removes whitespace, strtolower handles case sensitivity
$relation = strtolower(trim($relation));
// Mapping specific keywords to standardized outputs
// ORDER MATTERS: Specific phrases (in-law) must come before general ones (father)
$map = [
'father-in-law' => ['father in law', 'father-in-law', 'fil'],
'mother-in-law' => ['mother in law', 'mother-in-law', 'mil'],
'father' => ['father', 'papa', 'dad'],
'mother' => ['mother', 'mom', 'mummy'],
'spouse' => ['spouse', 'wife', 'husband', 'hubby'],
'daughter' => ['daughter', 'daug'],
'son' => ['son'],
'self' => ['self', 'employee', 'main'],
];
foreach ($map as $standard => $keywords) {
foreach ($keywords as $keyword) {
if (str_contains($relation, $keyword)) {
return $standard;
}
}
}
return null;
}
}

View File

@ -0,0 +1,360 @@
<?php
namespace App\Libraries\TPAClaimsImportServices;
use CodeIgniter\Database\BaseConnection;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use App\Models\TicketMasterModel;
use App\Models\EmployeeModel;
use App\Models\ClaimDumpFileModel;
use App\Models\ClaimsDumpFhplModel;
use RuntimeException;
abstract class BaseTpaClaimImportService
{
protected BaseConnection $db;
protected $claimDumpFileModel;
public function __construct()
{
$this->db = db_connect();
$this->claimDumpFileModel = new ClaimDumpFileModel();
}
/**
* First JOB for insert TPA wise Bulk Upload
*/
public function runTpaClaimDumpInsert(string $filePath, int $fileId): array
{
// 1. Start Transaction
$this->db->transBegin();
try {
$fileData = $this->claimDumpFileModel->where('id', $fileId)->first();
// Determine sheet name logic...
if (env('FHPL_PRIMARY_KEY_CONSTANT') == $fileData['tpa_id']) {
$rows = $this->readExcelBySheetName($filePath, 'Claims&Preauth');
} else if (env('R_CARE_PRIMARY_KEY_CONSTANT') == $fileData['tpa_id']) {
$rows = $this->readExcelBySheetName($filePath, 'CL');
} else {
$rows = $this->readExcel($filePath);
}
if (empty($rows)) {
$this->db->transRollback(); // ROLLBACK BEFORE RETURN
return ['status' => false, 'message' => 'Excel file contains no data or wrong file upload'];
}
$tpaInsertData = $this->mapTPAData($rows, $fileId);
if (empty($tpaInsertData)) {
$this->db->transRollback(); // ROLLBACK BEFORE RETURN
return ['status' => false, 'message' => 'These records already exist in the system.'];
}
$return_res = $this->bulkInsertTPATable($tpaInsertData);
if ($return_res !== true) {
$this->db->transRollback(); // ROLLBACK BEFORE RETURN
return ['status' => false, 'message' => 'TPA Import bulk insert failed'];
}
// 2. Commit if everything is fine
$this->db->transCommit();
return ['status' => true, 'message' => 'File uploaded successfully', 'record_count' => count($tpaInsertData)];
} catch (\Throwable $e) {
// 3. Rollback on any crash/exception
$this->db->transRollback();
return ['status' => false, 'message' => 'System error : ' . $e->getMessage()];
}
}
/**
* Second JOB for insert Ticket Master table after insert the TPA bulk upload success
*/
public function runTicketMasterInsert(array $params): array
{
// 1. Start manual transaction
$this->db->transBegin();
try {
$file_id = $params['file_id'];
$ticketMasterData = $this->mapClaimMasterData($file_id);
// Check if mapping failed
if (!$ticketMasterData['status']) {
$this->db->transRollback(); // ALWAYS rollback before early return
return $ticketMasterData;
}
$message = '';
$hasExecutedTask = false;
$status = true;
// Process Mapped Data
if (!empty($ticketMasterData['mapped_array'])) {
$insert_res = $this->importClaimMaster($ticketMasterData['mapped_array']);
if (!$insert_res) {
$this->db->transRollback();
return ['status' => false, 'message' => 'Ticket Master Claim bulk insert failed'];
}
$message .= 'Ticket Master Claim bulk insert success. ';
$hasExecutedTask = true;
}else{
$status = false;
}
// Process Rejected Reasons
if (!empty($ticketMasterData['rejected_reason_array'])) {
$update_res = $this->updateTicketMasterRejectedReasonInTPATable($ticketMasterData['rejected_reason_array']);
if (!$update_res) {
$this->db->transRollback();
return ['status' => false, 'message' => 'Updating rejected reasons failed'];
}
$message .= empty($ticketMasterData['mapped_array'])
? 'Those employee or dependent not in our system. '
: 'Ticket Master Claim rejected reason updated successfully. ';
$hasExecutedTask = true;
}
// If nothing was processed but no error occurred
if (!$hasExecutedTask) {
$this->db->transRollback();
return ['status' => false, 'message' => 'No data found to process.'];
}
// 2. Commit the transaction
$this->db->transCommit();
return ['status' => $status, 'message' => trim($message)];
} catch (\Throwable $th) {
// 3. Rollback on crash
$this->db->transRollback();
return [
'status' => false,
'message' => 'System error during Ticket Master Insert: ' . $th->getMessage()
];
}
}
/**
* Read Excel and return associative rows (header based)
*/
protected function readExcel(string $filePath): array
{
helper('excel_util_helper');
if (!file_exists($filePath)) {
throw new RuntimeException("File not found: {$filePath}");
}
$spreadsheet = IOFactory::load($filePath);
$sheet = $spreadsheet->getActiveSheet();
$rows = $sheet->toArray(null, true, true, true);
// dd($rows);
if (count($rows) < 2) {
return [];
}
// First row is header
$headers = array_shift($rows);
$headers = array_map('trim', $headers);
$data = [];
foreach ($rows as $row) {
if(check_row_is_empty_or_null($row)){
break;
}
$item = [];
foreach ($headers as $key => $headerName) {
if ($headerName !== '') {
$item[$headerName] = $row[$key] ?? null;
}
}
$data[] = $item;
}
return $data;
}
/**
* Read Excel By Sheet name and return associative rows (header based)
*/
protected function readExcelBySheetName(string $filePath, string $sheetName): array
{
if (!file_exists($filePath)) {
throw new RuntimeException("File not found: {$filePath}");
}
$spreadsheet = IOFactory::load($filePath);
// Get sheet by name
$sheet = $spreadsheet->getSheetByName($sheetName);
if ($sheet === null) {
throw new RuntimeException("Sheet '{$sheetName}' not found in Excel file");
}
$rows = $sheet->toArray(null, true, true, true);
// Need at least header + one row
if (count($rows) < 2) {
return [];
}
// First row = headers
$headers = array_shift($rows);
$headers = array_map('trim', $headers);
$data = [];
foreach ($rows as $row) {
// Skip completely empty rows
if (!array_filter($row)) {
continue;
}
$item = [];
foreach ($headers as $key => $headerName) {
if ($headerName !== '') {
$item[$headerName] = $row[$key] ?? null;
}
}
$data[] = $item;
}
return $data;
}
/**
* Dublicate check in the ticket_master table records
*/
protected function checkDublicateTicketMasterClaim(array $param): bool
{
$ticketMaster = new TicketMasterModel();
$ticket_master_data = $ticketMaster
->where('doa', $param['doa'])
->where('tpa_no', $param['tpa_no'])
->where('claim_amount', $param['claim_amount'])
->where('emp_code', $param['emp_code'])
->where('is_active', 1)
->findAll();
if(count($ticket_master_data) > 0){
return true;
}
return false;
}
/**
* Dublicate check in the TPA specific table records
*/
protected function checkDuplicateTpaClaim(string $table, array $params): bool
{
return $this->db->table($table)
->where($params)
->where('is_active', 1)
->countAllResults() > 0;
}
/**
* Dublicate check in the TPA specific table records
*/
protected function getTpaClaimDumpData(string $table, array $params): array
{
return $this->db
->table($table)
->where('is_active', 1)
->where('file_id', $params['file_id'])
->where('ticket_id IS NULL')
->where('master_reject_reason IS NULL')
->get()
->getResultArray();
}
/**
* Dublicate check in the TPA specific table records
*/
public function getEmployeeDetails(int $client_id, int $client_policy_id, string $emp_code, string $relation): array
{
$EmployeeModel = new EmployeeModel();
$employeeData = $EmployeeModel
->select([
'employees.id AS id',
'employees.email_corporate AS emp_mail',
'employees.mobile AS emp_mobile',
'employees.name AS name',
'employees.emp_code AS emp_code',
// insured employee
'insured.id AS insured_emp_id',
'insured.name AS insured_name'
])
->join(
'employee_polices',
'employees.id = employee_polices.employee_id'
)
->join(
'employees AS insured',
"insured.emp_code = employees.emp_code
AND insured.client_id = employees.client_id
AND LOWER(insured.relationship) = " . $EmployeeModel->db->escape(strtolower($relation)),
'left'
)
->where('employees.is_active', 1)
->where('employee_polices.is_active', 1)
->where('employee_polices.client_policy_id', $client_policy_id)
->where('employees.client_id', $client_id)
->where('employees.emp_code', $emp_code)
->where('LOWER(employees.relationship)', 'self')
->first();
return $employeeData ?? [];
}
/**
* Map Excel rows to TPA table structure
*/
abstract protected function mapTPAData(array $rows, $fileId): array;
/**
* Map DB rows to Ticket Master table structure
*/
abstract protected function mapClaimMasterData($fileId): array;
/**
* Insert into TPA-specific table (bulk)
*/
abstract protected function bulkInsertTPATable(array $data): bool;
/**
* Insert into Ticket-Master-specific table (bulk)
*/
abstract protected function importClaimMaster(array $data): bool;
/**
* Update TPA table with ticket_master primary key
*/
abstract protected function updateTicketIdInTPATable(): bool;
/**
* Update TPA table with ticket_master insert rejected reason
*/
abstract protected function updateTicketMasterRejectedReasonInTPATable(array $data): bool;
}

View File

@ -0,0 +1,484 @@
<?php
namespace App\Libraries\TPAClaimsImportServices;
use App\Models\TicketMasterModel;
use App\Models\ClientPolicyModel;
use App\Models\ClaimDumpFileModel;
use App\Models\ClaimsDumpFhplModel;
class FhplClaimImportService extends BaseTpaClaimImportService
{
/**
* MAPPING ARRAYs
*/
protected $mapping = [
["excel_column"=>["col_name"=>"Requesttype","col_index"=>0],"db_column"=>"request_type"],
["excel_column"=>["col_name"=>"Intimation ID","col_index"=>1],"db_column"=>"intimation_id"],
["excel_column"=>["col_name"=>"Intimation Date","col_index"=>2],"db_column"=>"intimation_date"],
["excel_column"=>["col_name"=>"claimid","col_index"=>3],"db_column"=>"claim_id"],
["excel_column"=>["col_name"=>"slno","col_index"=>4],"db_column"=>"sl_no"],
["excel_column"=>["col_name"=>"UHIDNO","col_index"=>5],"db_column"=>"uhid_no"],
["excel_column"=>["col_name"=>"Membername","col_index"=>6],"db_column"=>"member_name"],
["excel_column"=>["col_name"=>"Main Memuhidno","col_index"=>7],"db_column"=>"main_member_uhid_no"],
["excel_column"=>["col_name"=>"Main Memname","col_index"=>8],"db_column"=>"main_member_name"],
["excel_column"=>["col_name"=>"Gender","col_index"=>9],"db_column"=>"gender"],
["excel_column"=>["col_name"=>"DOB","col_index"=>10],"db_column"=>"dob"],
["excel_column"=>["col_name"=>"Yrs","col_index"=>11],"db_column"=>"years"],
["excel_column"=>["col_name"=>"relationship","col_index"=>12],"db_column"=>"relationship"],
["excel_column"=>["col_name"=>"employeeid","col_index"=>13],"db_column"=>"employee_id"],
["excel_column"=>["col_name"=>"Mobile","col_index"=>14],"db_column"=>"mobile"],
["excel_column"=>["col_name"=>"Email","col_index"=>15],"db_column"=>"email"],
["excel_column"=>["col_name"=>"Policy No","col_index"=>16],"db_column"=>"policy_no"],
["excel_column"=>["col_name"=>"Policy Start Date","col_index"=>17],"db_column"=>"policy_start_date"],
["excel_column"=>["col_name"=>"Policy Commencing Date","col_index"=>18],"db_column"=>"policy_commencing_date"],
["excel_column"=>["col_name"=>"Policy Expiry Date","col_index"=>19],"db_column"=>"policy_expiry_date"],
["excel_column"=>["col_name"=>"Organisationname","col_index"=>20],"db_column"=>"organisation_name"],
["excel_column"=>["col_name"=>"Claimreceiveddate","col_index"=>21],"db_column"=>"claim_received_date"],
["excel_column"=>["col_name"=>"Admdate","col_index"=>22],"db_column"=>"admission_date"],
["excel_column"=>["col_name"=>"Dis Date","col_index"=>23],"db_column"=>"discharge_date"],
["excel_column"=>["col_name"=>"Diagnosis","col_index"=>24],"db_column"=>"diagnosis"],
["excel_column"=>["col_name"=>"Service Type","col_index"=>25],"db_column"=>"service_type"],
["excel_column"=>["col_name"=>"Service Sub Type","col_index"=>26],"db_column"=>"service_sub_type"],
["excel_column"=>["col_name"=>"icdcode First Level","col_index"=>27],"db_column"=>"icd_code_first_level"],
["excel_column"=>["col_name"=>"icdcode Second Level","col_index"=>28],"db_column"=>"icd_code_second_level"],
["excel_column"=>["col_name"=>"icdcode Third Level","col_index"=>29],"db_column"=>"icd_code_third_level"],
["excel_column"=>["col_name"=>"Claim Type","col_index"=>30],"db_column"=>"claim_type"],
["excel_column"=>["col_name"=>"Providername","col_index"=>31],"db_column"=>"provider_name"],
["excel_column"=>["col_name"=>"provideraddress","col_index"=>32],"db_column"=>"provider_address"],
["excel_column"=>["col_name"=>"providerplace","col_index"=>33],"db_column"=>"provider_place"],
["excel_column"=>["col_name"=>"providerstate","col_index"=>34],"db_column"=>"provider_state"],
["excel_column"=>["col_name"=>"Provider Pincode","col_index"=>35],"db_column"=>"provider_pincode"],
["excel_column"=>["col_name"=>"PROVIDERTYPE","col_index"=>36],"db_column"=>"provider_type"],
["excel_column"=>["col_name"=>"Provider Identification","col_index"=>37],"db_column"=>"provider_identification"],
["excel_column"=>["col_name"=>"coverageamount","col_index"=>38],"db_column"=>"coverage_amount"],
["excel_column"=>["col_name"=>"claimamount","col_index"=>39],"db_column"=>"claim_amount"],
["excel_column"=>["col_name"=>"billedamount","col_index"=>40],"db_column"=>"billed_amount"],
["excel_column"=>["col_name"=>"Disallowed Amount","col_index"=>41],"db_column"=>"disallowed_amount"],
["excel_column"=>["col_name"=>"Dis Allowence Reason1","col_index"=>42],"db_column"=>"dis_allowance_reason_1"],
["excel_column"=>["col_name"=>"Dis Allowence Reason2","col_index"=>43],"db_column"=>"dis_allowance_reason_2"],
["excel_column"=>["col_name"=>"settledamt","col_index"=>44],"db_column"=>"settled_amount"],
["excel_column"=>["col_name"=>"Incurred Amount","col_index"=>45],"db_column"=>"incurred_amount"],
["excel_column"=>["col_name"=>"Discountamount","col_index"=>46],"db_column"=>"discount_amount"],
["excel_column"=>["col_name"=>"TDSAmount","col_index"=>47],"db_column"=>"tds_amount"],
["excel_column"=>["col_name"=>"Net Amount Paid","col_index"=>48],"db_column"=>"net_amount_paid"],
["excel_column"=>["col_name"=>"Co Payment","col_index"=>49],"db_column"=>"co_payment"],
["excel_column"=>["col_name"=>"Current Claim Status","col_index"=>50],"db_column"=>"current_claim_status"],
["excel_column"=>["col_name"=>"Balance Suminsured","col_index"=>51],"db_column"=>"balance_sum_insured"],
["excel_column"=>["col_name"=>"Chequeno","col_index"=>52],"db_column"=>"cheque_no"],
["excel_column"=>["col_name"=>"chequedate","col_index"=>53],"db_column"=>"cheque_date"],
["excel_column"=>["col_name"=>"Claim Passed Date","col_index"=>54],"db_column"=>"claim_passed_date"],
["excel_column"=>["col_name"=>"Settled Date","col_index"=>55],"db_column"=>"settled_date"],
["excel_column"=>["col_name"=>"Pending Remarks","col_index"=>56],"db_column"=>"pending_remarks"],
["excel_column"=>["col_name"=>"Ir Investigation","col_index"=>57],"db_column"=>"ir_investigation"],
["excel_column"=>["col_name"=>"Date of IR","col_index"=>58],"db_column"=>"ir_date"],
["excel_column"=>["col_name"=>"Date of IRretrieval Date","col_index"=>59],"db_column"=>"ir_retrieval_date"],
["excel_column"=>["col_name"=>"first Reminder","col_index"=>60],"db_column"=>"first_reminder"],
["excel_column"=>["col_name"=>"Second Reminder","col_index"=>61],"db_column"=>"second_reminder"],
["excel_column"=>["col_name"=>"Rejection Remarks","col_index"=>62],"db_column"=>"rejection_remarks"],
["excel_column"=>["col_name"=>"Payee name","col_index"=>63],"db_column"=>"payee_name"],
["excel_column"=>["col_name"=>"Treatment Type","col_index"=>64],"db_column"=>"treatment_type"],
["excel_column"=>["col_name"=>"roomdays","col_index"=>65],"db_column"=>"room_days"],
["excel_column"=>["col_name"=>"icudays","col_index"=>66],"db_column"=>"icu_days"],
["excel_column"=>["col_name"=>"totalstay","col_index"=>67],"db_column"=>"total_stay"],
["excel_column"=>["col_name"=>"Room Rent Claimed","col_index"=>68],"db_column"=>"room_rent_claimed"],
["excel_column"=>["col_name"=>"ICU Claimed","col_index"=>69],"db_column"=>"icu_claimed"],
["excel_column"=>["col_name"=>"ICU Related","col_index"=>70],"db_column"=>"icu_related"],
["excel_column"=>["col_name"=>"Nursing Claimed","col_index"=>71],"db_column"=>"nursing_claimed"],
["excel_column"=>["col_name"=>"Nursing Charges","col_index"=>72],"db_column"=>"nursing_charges"],
["excel_column"=>["col_name"=>"Room Rent Related","col_index"=>73],"db_column"=>"room_rent_related"],
["excel_column"=>["col_name"=>"Professional Charges","col_index"=>74],"db_column"=>"professional_charges"],
["excel_column"=>["col_name"=>"Drugs Medication Consumables Investigationsetc","col_index"=>75],"db_column"=>"drugs_medication_consumables"],
["excel_column"=>["col_name"=>"Investigations Procedures IP","col_index"=>76],"db_column"=>"investigations_procedures_ip"],
["excel_column"=>["col_name"=>"Domicillary Hospitalization","col_index"=>77],"db_column"=>"domicillary_hospitalization"],
["excel_column"=>["col_name"=>"Maternity","col_index"=>78],"db_column"=>"maternity"],
["excel_column"=>["col_name"=>"Day Care","col_index"=>79],"db_column"=>"day_care"],
["excel_column"=>["col_name"=>"Operation Theatre","col_index"=>80],"db_column"=>"operation_theatre"],
["excel_column"=>["col_name"=>"Organ Donar","col_index"=>81],"db_column"=>"organ_donor"],
["excel_column"=>["col_name"=>"Ancilliary Services","col_index"=>82],"db_column"=>"ancillary_services"],
["excel_column"=>["col_name"=>"Dental","col_index"=>83],"db_column"=>"dental"],
["excel_column"=>["col_name"=>"Out Patient Coverage","col_index"=>84],"db_column"=>"out_patient_coverage"],
["excel_column"=>["col_name"=>"Personal Accident","col_index"=>85],"db_column"=>"personal_accident"],
["excel_column"=>["col_name"=>"Critical Illness","col_index"=>86],"db_column"=>"critical_illness"],
["excel_column"=>["col_name"=>"Health Check Up","col_index"=>87],"db_column"=>"health_check_up"],
["excel_column"=>["col_name"=>"Spectacles Contact Lenses Hearing Aid","col_index"=>88],"db_column"=>"spectacles_contact_lenses_hearing_aid"],
["excel_column"=>["col_name"=>"Notes","col_index"=>89],"db_column"=>"notes"],
["excel_column"=>["col_name"=>"Buffer Amount","col_index"=>90],"db_column"=>"buffer_amount"],
["excel_column"=>["col_name"=>"tertiaryamount","col_index"=>91],"db_column"=>"tertiary_amount"],
["excel_column"=>["col_name"=>"insurancename","col_index"=>92],"db_column"=>"insurance_name"],
["excel_column"=>["col_name"=>"Roname","col_index"=>93],"db_column"=>"ro_name"],
["excel_column"=>["col_name"=>"Class Of Accommodation","col_index"=>94],"db_column"=>"class_of_accommodation"],
["excel_column"=>["col_name"=>"claimcreateddatetime","col_index"=>95],"db_column"=>"claim_created_datetime"],
["excel_column"=>["col_name"=>"Insurer Claim ID","col_index"=>96],"db_column"=>"insurer_claim_id"],
["excel_column"=>["col_name"=>"Gipsa","col_index"=>97],"db_column"=>"gipsa"],
["excel_column"=>["col_name"=>"Date Of Joining","col_index"=>98],"db_column"=>"date_of_joining"],
["excel_column"=>["col_name"=>"GIPSAHospital","col_index"=>99],"db_column"=>"gipsa_hospital"],
["excel_column"=>["col_name"=>"Package","col_index"=>100],"db_column"=>"package"],
["excel_column"=>["col_name"=>"Is NIDB","col_index"=>101],"db_column"=>"is_nidb"],
["excel_column"=>["col_name"=>"NIDB Removed Date","col_index"=>102],"db_column"=>"nidb_removed_date"],
["excel_column"=>["col_name"=>"Investigationdate","col_index"=>103],"db_column"=>"investigation_date"],
["excel_column"=>["col_name"=>"Investigation Retrieval Date","col_index"=>104],"db_column"=>"investigation_retrieval_date"],
["excel_column"=>["col_name"=>"Reopeneddate","col_index"=>105],"db_column"=>"reopened_date"],
["excel_column"=>["col_name"=>"Referto Insurer Date","col_index"=>106],"db_column"=>"refer_to_insurer_date"],
["excel_column"=>["col_name"=>"Receiveddatefrom Insurer","col_index"=>107],"db_column"=>"received_date_from_insurer"],
["excel_column"=>["col_name"=>"Rejection Category","col_index"=>108],"db_column"=>"rejection_category"],
["excel_column"=>["col_name"=>"Referto Insurer Reasons","col_index"=>109],"db_column"=>"refer_to_insurer_reasons"],
["excel_column"=>["col_name"=>"Is VIP","col_index"=>110],"db_column"=>"is_vip"],
["excel_column"=>["col_name"=>"Main Claim Status","col_index"=>111],"db_column"=>"main_claim_status"],
["excel_column"=>["col_name"=>"Main Claimtype","col_index"=>112],"db_column"=>"main_claim_type"],
["excel_column"=>["col_name"=>"icd Third Level Code","col_index"=>113],"db_column"=>"icd_third_level_code"],
["excel_column"=>["col_name"=>"Benefit Plan Name","col_index"=>114],"db_column"=>"benefit_plan_name"],
["excel_column"=>["col_name"=>"zone","col_index"=>115],"db_column"=>"zone"],
["excel_column"=>["col_name"=>"Grade","col_index"=>116],"db_column"=>"grade"],
["excel_column"=>["col_name"=>"Last Modified Date","col_index"=>117],"db_column"=>"last_modified_date"],
["excel_column"=>["col_name"=>"Temp MOU","col_index"=>118],"db_column"=>"temp_mou"],
];
protected $ticketMasterMapping = [
// Claim / Reference
'claim_id' => 'claim_number',
// Employee / Member
'employee_id' => 'emp_code',
// Claim Dates
'admission_date' => 'doa',
'discharge_date' => 'dod',
'claim_received_date' => 'date_of_intimat',
'claim_passed_date' => 'approved_date',
'settled_date' => 'settled_date',
'current_claim_status' => 'tpa_claim_status',
// Amounts
'claim_amount' => 'claim_amount',
'settled_amount' => 'settled_amount',
'disallowed_amount' => 'denial_reason',
'coverage_amount' => 'si_amt',
// Hospital
'provider_name' => 'hospital_name',
'provider_address' => 'hospital_address',
'provider_state' => 'hospital_state',
'provider_place' => 'hospital_city',
'provider_pincode' => 'hospital_pin_code',
// Remarks / Description
'diagnosis' => 'claim_description',
'rejection_remarks' => 'return_remark',
// Payment
'cheque_no' => 'utr_details',
'uhid_no' => 'tpa_no',
'claim_type' => 'tpa_claim_type',
'diagnosis' => 'tpa_ailments',
];
protected $statusMapping = [
'Settled' => 11,
'Rejected' => 8,
];
protected $dateColumns = [
'intimation_date',
'policy_start_date',
'policy_commencing_date',
'policy_expiry_date',
'claim_received_date',
'admission_date',
'discharge_date',
'cheque_date',
'claim_passed_date',
'settled_date',
'ir_date',
'ir_retrieval_date',
'first_reminder',
'second_reminder',
'date_of_joining',
'nidb_removed_date',
'investigation_date',
'investigation_retrieval_date',
'reopened_date',
'refer_to_insurer_date',
'received_date_from_insurer',
'claim_created_datetime',
'last_modified_date'
];
/**
* ABSTRACT FUNCTIONs
*/
public function bulkInsertTPATable(array $data): bool
{
if (empty($data)) {
return false;
}
$builder = $this->db->table('claims_dump_fhpl');
return $builder->insertBatch($data);
}
public function importClaimMaster(array $data): bool
{
if (empty($data)) {
return false;
}
$ticketMasterModel = new TicketMasterModel();
return $ticketMasterModel->insertBatch($data);
}
public function updateTicketIdInTPATable(): bool
{
if (empty($data)) {
return false;
}
$builder = $this->db->table('claims_dump_fhpl');
return $builder->updateBatch($data, 'id');
}
public function updateTicketMasterRejectedReasonInTPATable($data): bool
{
if (empty($data)) {
return false;
}
$builder = $this->db->table('claims_dump_fhpl');
return $builder->updateBatch($data, 'id');
}
/**
* MAPPING FUNCTIONs
*/
public function mapTPAData(array $rows, $file_id): array
{
$ClientPolicyModel = new ClaimDumpFileModel();
$file_data = $ClientPolicyModel->where('id', $file_id)->first();
$mapped = [];
foreach ($rows as $row) {
$item = [];
foreach ($this->mapping as $map) {
$excelColumn = $map['excel_column']['col_name'];
$dbColumn = $map['db_column'];
$value = $row[$excelColumn] ?? null;
$item[$dbColumn] = trim($value);
}
foreach ($this->dateColumns as $key => $value) {
$item[$value] = change_date_format($item[$value] ?? null, 'd-M-y', 'Y-m-d');
}
$params = [
'admission_date' => $item['admission_date'] ?? null,
'employee_id' => $item['employee_id'] ?? null,
'claim_amount' => $item['claim_amount'] ?? null,
'uhid_no' => $item['uhid_no'] ?? null
];
$is_duplicate = $this->checkDuplicateTpaClaim('claims_dump_fhpl', $params);
if ($is_duplicate) {
$item = [];
continue;
}
$item['file_id'] = $file_id ?? null;
$item['client_id'] = $file_data['client_id'] ?? null;
$item['client_policy_id'] = $file_data['client_policy_id'] ?? null;
$item['created_by'] = $file_data['created_by'] ?? null;
$mapped[] = $item;
}
return $mapped;
}
public function mapClaimMasterData($file_id): array
{
$ClientPolicyModel = new ClaimDumpFileModel();
$file_data = $ClientPolicyModel->where('id', $file_id)->first();
$tpaClaimDumpData = $this->getTpaClaimDumpData('claims_dump_fhpl', ['file_id' => $file_id]);
if (empty($tpaClaimDumpData)) {
return ['status' => false, 'message' => "No data to insert in TICKET MASTER"];
}
$ClientPolicyModel = new ClientPolicyModel();
$client_policy_data = $ClientPolicyModel
->select("
client_policy.*,
(
SELECT id
FROM client_rm
WHERE is_active = 1
AND level = 3
AND client_id = client_policy.client_id
ORDER BY id ASC
LIMIT 1
) AS acm_id
")
->where('client_policy.id', $file_data['client_policy_id'])
->where('client_policy.is_active', 1)
->first();
try {
$mapped = [];
$rejecetd_reason = [];
foreach ($tpaClaimDumpData as $row) {
$params = [
'doa' => change_date_format($row['admission_date'] ?? '') ?? null,
'emp_code' => $row['employee_id'] ?? null,
'claim_amount' => $row['claim_amount'] ?? null,
'tpa_no' => $row['uhid_no'] ?? null
];
$isduplicate = $this->checkDublicateTicketMasterClaim($params);
if ($isduplicate) {
$reason = "This claim already exists in our system.";
$rejecetd_reason[] = ["id" => $row['id'], "master_reject_reason" => $reason];
continue;
}
$item = [];
$item['client_id'] = $client_policy_data['client_id'] ?? null;
$item['client_policy_id'] = $client_policy_data['id'] ?? null;
$item['insurer_id'] = $client_policy_data['insurer_id'] ?? null;
$item['tpa_id'] = $client_policy_data['tpa_id'] ?? null;
$item['acm_id'] = $client_policy_data['acm_id'] ?? null;
$item['policy_no'] = $client_policy_data['policy_no'] ?? null;
$item['relationship'] = $this->convertRelation($row['relationship'] ?? null);
$employee_data = $this->getEmployeeDetails($file_data['client_id'], $file_data['client_policy_id'], $row['employee_id'], $item['relationship']);
if (!empty($employee_data)) {
$item['emp_id'] = $employee_data['id'] ?? null;
$item['emp_name'] = $employee_data['name'] ?? null;
$item['emp_code'] = $employee_data['emp_code'] ?? null;
$item['emp_mail'] = $employee_data['email_corporate'] ?? null;
$item['emp_mobile'] = $employee_data['mobile'] ?? null;
if (!empty($employee_data['insured_emp_id'])) {
$item['insured_emp_id'] = $employee_data['insured_emp_id'] ?? null;
$item['insured_name'] = $employee_data['insured_name'] ?? null;
}else{
$reason = 'This Dependent employee not exist in our system.';
$rejecetd_reason[] = ["id" => $row['id'], "master_reject_reason" => $reason];
continue;
}
} else {
$reason = 'This employee not exist in our system.';
$rejecetd_reason[] = ["id" => $row['id'], "master_reject_reason" => $reason];
continue;
}
foreach ($this->ticketMasterMapping as $tpaKey => $ticketMasterKey) {
$item[$ticketMasterKey] = array_key_exists($tpaKey, $row) ? $row[$tpaKey] : null;
}
// Meta fields
$item['claim_status_id'] = $statusMapping[$row['current_claim_status']] ?? 61;
$item['file_id'] = $file_id;
$item['claim_dump_ref_id'] = $row['id'];
$item['created_by'] = $file_data['created_by'] ?? null;
$item['claim_type'] = 1;
$item['priority'] = 1;
$item['mode_of_intimation'] = 5;
$item['ticket_type_id'] = 1;
$mapped[] = $item;
}
return ['status' => true, 'mapped_array' => $mapped, 'rejected_reason_array' => $rejecetd_reason];
} 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,
];
return ['status' => false, "message" => $errorData['message'], 'error_data' => $errorData];
}
}
/**
* HELPER FUNCTIONs
*/
public function convertRelation(?string $relation): ?string
{
if (empty($relation)) {
return null;
}
$relation = strtolower($relation);
if (str_contains($relation, 'self')) {
return 'self';
}
if (str_contains($relation, 'spouse') || str_contains($relation, 'wife') || str_contains($relation, 'husband')) {
return 'spouse';
}
if (str_contains($relation, 'daughter')) {
return 'daughter';
}
if (str_contains($relation, 'son')) {
return 'son';
}
if (str_contains($relation, 'father in law') || str_contains($relation, 'father-in-law')) {
return 'father-in-law';
}
if (str_contains($relation, 'mother in law') || str_contains($relation, 'mother-in-law')) {
return 'mother-in-law';
}
if (str_contains($relation, 'father')) {
return 'father';
}
if (str_contains($relation, 'mother')) {
return 'mother';
}
return null; // unmatched case
}
}

View File

@ -0,0 +1,402 @@
<?php
namespace App\Libraries\TPAClaimsImportServices;
use App\Models\TicketMasterModel;
use App\Models\ClientPolicyModel;
use App\Models\ClientRMModel;
use App\Models\EmployeeModel;
use App\Models\ClaimDumpFileModel;
use App\Models\ClaimsDumpFhplModel;
class IciciClaimImportService extends BaseTpaClaimImportService
{
/**
* MAPPING ARRAYs
*/
protected $mapping = [
["excel_column" => ["col_name" => "POLICY_NAME", "col_index" => 0], "db_column" => "policy_name"],
["excel_column" => ["col_name" => "POLICY_NO", "col_index" => 1], "db_column" => "policy_no"],
["excel_column" => ["col_name" => "UHID", "col_index" => 2], "db_column" => "uhid"],
["excel_column" => ["col_name" => "INSURED_NAME", "col_index" => 3], "db_column" => "insured_name"],
["excel_column" => ["col_name" => "MAIN_MEMBER_NAME", "col_index" => 4], "db_column" => "main_member_name"],
["excel_column" => ["col_name" => "EMPLOYEE_MEMBER_ID", "col_index" => 5], "db_column" => "employee_member_id"],
["excel_column" => ["col_name" => "GRADE", "col_index" => 6], "db_column" => "grade"],
["excel_column" => ["col_name" => "RELATION", "col_index" => 7], "db_column" => "relation"],
["excel_column" => ["col_name" => "AGE", "col_index" => 8], "db_column" => "age"],
["excel_column" => ["col_name" => "GENDER", "col_index" => 9], "db_column" => "gender"],
["excel_column" => ["col_name" => "DIAGNOSIS", "col_index" => 10], "db_column" => "diagnosis"],
["excel_column" => ["col_name" => "CLAIMED_AMOUNT", "col_index" => 11], "db_column" => "claimed_amount"],
["excel_column" => ["col_name" => "NET_SANCT_AMT", "col_index" => 12], "db_column" => "net_sanct_amt"],
["excel_column" => ["col_name" => "COPAYMENT_AMT", "col_index" => 13], "db_column" => "copayment_amt"],
["excel_column" => ["col_name" => "DISALLOWED_AMOUNT", "col_index" => 14], "db_column" => "disallowed_amount"],
["excel_column" => ["col_name" => "REASON_FOR_DISALLOWANCE", "col_index" => 15], "db_column" => "reason_for_disallowance"],
["excel_column" => ["col_name" => "PAYMENT_AMOUNT", "col_index" => 16], "db_column" => "payment_amount"],
["excel_column" => ["col_name" => "SUM_INSURED", "col_index" => 17], "db_column" => "sum_insured"],
["excel_column" => ["col_name" => "BAL_SUM_INSURED", "col_index" => 18], "db_column" => "bal_sum_insured"],
["excel_column" => ["col_name" => "TYPE_OF_CLAIM", "col_index" => 19], "db_column" => "type_of_claim"],
["excel_column" => ["col_name" => "Claim_r_Os_Amt", "col_index" => 20], "db_column" => "claim_r_os_amt"],
["excel_column" => ["col_name" => "Updated_status", "col_index" => 21], "db_column" => "updated_status"],
["excel_column" => ["col_name" => "Disease_Category", "col_index" => 22], "db_column" => "disease_category"],
["excel_column" => ["col_name" => "POLICY_START_DATE", "col_index" => 23], "db_column" => "policy_start_date"],
["excel_column" => ["col_name" => "POLICY_END_DATE", "col_index" => 24], "db_column" => "policy_end_date"],
["excel_column" => ["col_name" => "CLAIM_NUMBER", "col_index" => 25], "db_column" => "claim_number"],
["excel_column" => ["col_name" => "AL_NO", "col_index" => 26], "db_column" => "al_no"],
["excel_column" => ["col_name" => "HOSPITAL_CODE", "col_index" => 27], "db_column" => "hospital_code"],
["excel_column" => ["col_name" => "HOSPITAL_ID", "col_index" => 28], "db_column" => "hospital_id"],
["excel_column" => ["col_name" => "HOSPITAL_NAME", "col_index" => 29], "db_column" => "hospital_name"],
["excel_column" => ["col_name" => "TREATMENT_TAKEN", "col_index" => 30], "db_column" => "treatment_taken"],
["excel_column" => ["col_name" => "CF_Utilised_Amounnt", "col_index" => 31], "db_column" => "cf_utilised_amount"],
["excel_column" => ["col_name" => "DT_OF_DEFICIENCIES_SENT", "col_index" => 32], "db_column" => "dt_of_deficiencies_sent"],
["excel_column" => ["col_name" => "DT_OF_DEFICIENCIES_RECIEVED", "col_index" => 33], "db_column" => "dt_of_deficiencies_received"],
["excel_column" => ["col_name" => "PAYMENT_DATE", "col_index" => 34], "db_column" => "payment_date"],
["excel_column" => ["col_name" => "PAYEE_NAME", "col_index" => 35], "db_column" => "payee_name"],
["excel_column" => ["col_name" => "PAYMENT_MODE", "col_index" => 36], "db_column" => "payment_mode"],
["excel_column" => ["col_name" => "CHEQUE_NUMBER", "col_index" => 37], "db_column" => "cheque_number"],
["excel_column" => ["col_name" => "DOA", "col_index" => 38], "db_column" => "doa"],
["excel_column" => ["col_name" => "DOD", "col_index" => 39], "db_column" => "dod"],
["excel_column" => ["col_name" => "HOSPITAL_CITY", "col_index" => 40], "db_column" => "hospital_city"],
["excel_column" => ["col_name" => "HOSPITAL_STATE", "col_index" => 41], "db_column" => "hospital_state"],
["excel_column" => ["col_name" => "REJECTED_QUERY_REASON", "col_index" => 42], "db_column" => "rejected_query_reason"],
["excel_column" => ["col_name" => "REJECTED_QUERY_DESC", "col_index" => 43], "db_column" => "rejected_query_desc"],
["excel_column" => ["col_name" => "REJECTED_QUERY_CLOSED_DATE", "col_index" => 44], "db_column" => "rejected_query_closed_date"],
["excel_column" => ["col_name" => "REJREOPEN_CLOSURE_DATE", "col_index" => 45], "db_column" => "rejreopen_closure_date"],
["excel_column" => ["col_name" => "CLAIM_CLASSIFICATION", "col_index" => 46], "db_column" => "claim_classification"],
["excel_column" => ["col_name" => "TAGGED_INWARD_NO", "col_index" => 47], "db_column" => "tagged_inward_no"],
["excel_column" => ["col_name" => "INWARD_DATE", "col_index" => 48], "db_column" => "inward_date"],
["excel_column" => ["col_name" => "ICD_ID_L3", "col_index" => 49], "db_column" => "icd_id_l3"],
["excel_column" => ["col_name" => "Incidence_Count", "col_index" => 50], "db_column" => "incidence_count"],
["excel_column" => ["col_name" => "FLEXI_OPTION", "col_index" => 51], "db_column" => "flexi_option"],
["excel_column" => ["col_name" => "Base_TopUp_Option", "col_index" => 52], "db_column" => "base_topup_option"],
["excel_column" => ["col_name" => "POLICY_GROUP_NAME", "col_index" => 53], "db_column" => "policy_group_name"],
["excel_column" => ["col_name" => "Relation_Group", "col_index" => 54], "db_column" => "relation_group"],
["excel_column" => ["col_name" => "Age_Band", "col_index" => 55], "db_column" => "age_band"],
["excel_column" => ["col_name" => "Work_Location", "col_index" => 56], "db_column" => "work_location"],
["excel_column" => ["col_name" => "ILTC_TAG", "col_index" => 57], "db_column" => "iltc_tag"],
];
protected $ticketMasterMapping = [
// Employee / Member
'employee_member_id' => 'emp_code',
// Claim
'claim_number' => 'claim_number',
'claimed_amount' => 'claim_amount',
'claim_status' => 'tpa_claim_status',
// Dates
'doa' => 'doa',
'dod' => 'dod',
'payment_date' => 'settled_date',
// Hospital
'hospital_name' => 'hospital_name',
'hospital_city' => 'hospital_city',
'hospital_state' => 'hospital_state',
'cheque_number' => 'utr_details',
'uhid' => 'tpa_no',
'rejected_query_desc' => 'claim_description',
'type_of_claim' => 'tpa_claim_type',
'diagnosis' => 'tpa_ailments',
];
protected $statusMapping = [
'PAID' => 11,
'REJECTED' => 8,
];
protected $dateColumns = [
'policy_start_date',
'policy_end_date',
'dt_of_deficiencies_sent',
'dt_of_deficiencies_received',
'payment_date',
'doa',
'dod',
'rejected_query_closed_date',
'rejreopen_closure_date',
];
/**
* ABSTRACT FUNCTIONs
*/
public function bulkInsertTPATable(array $data): bool
{
if (empty($data)) {
return false;
}
$builder = $this->db->table('claims_dump_icici');
return $builder->insertBatch($data);
}
public function importClaimMaster(array $data): bool
{
if (empty($data)) {
return false;
}
$ticketMasterModel = new TicketMasterModel();
return $ticketMasterModel->insertBatch($data);
}
public function updateTicketIdInTPATable(): bool
{
if (empty($data)) {
return false;
}
$builder = $this->db->table('claims_dump_icici');
return $builder->upsertBatch($data, 'id');
}
public function updateTicketMasterRejectedReasonInTPATable($data): bool
{
if (empty($data)) {
return false;
}
$builder = $this->db->table('claims_dump_icici');
return $builder->updateBatch($data, 'id');
}
/**
* MAPPING FUNCTIONs
*/
public function mapTPAData(array $rows, $file_id): array
{
$ClientPolicyModel = new ClaimDumpFileModel();
$file_data = $ClientPolicyModel->where('id', $file_id)->first();
$mapped = [];
foreach ($rows as $row) {
$item = [];
foreach ($this->mapping as $map) {
$excelColumn = $map['excel_column']['col_name'];
$dbColumn = $map['db_column'];
$value = $row[$excelColumn] ?? null;
$item[$dbColumn] = $value;
}
foreach ($this->dateColumns as $key => $value) {
$item[$value] = change_date_format($item[$value] ?? null);
}
$params = [
'doa' => change_date_format($item['doa'] ?? '') ?? null,
'employee_member_id' => $item['employee_member_id'] ?? null,
'claimed_amount' => $item['claimed_amount'] ?? null,
'uhid' => $item['uhid'] ?? null
];
$is_duplicate = $this->checkDuplicateTpaClaim('claims_dump_icici', $params);
if ($is_duplicate) {
$item = [];
continue;
}
$item['file_id'] = $file_id ?? null;
$item['client_id'] = $file_data['client_id'] ?? null;
$item['client_policy_id'] = $file_data['client_policy_id'] ?? null;
$item['created_by'] = $file_data['created_by'] ?? null;
$mapped[] = $item;
}
return $mapped;
}
public function mapClaimMasterData($file_id): array
{
$ClientPolicyModel = new ClaimDumpFileModel();
$file_data = $ClientPolicyModel->where('id', $file_id)->first();
$tpaClaimDumpData = $this->getTpaClaimDumpData('claims_dump_icici', ['file_id' => $file_id]);
if (empty($tpaClaimDumpData)) {
return ['status' => false, 'message' => "No data to insert in TICKET MASTER"];
}
$ClientPolicyModel = new ClientPolicyModel();
$client_policy_data = $ClientPolicyModel
->select("
client_policy.*,
(
SELECT id
FROM client_rm
WHERE is_active = 1
AND level = 3
AND client_id = client_policy.client_id
ORDER BY id ASC
LIMIT 1
) AS acm_id
")
->where('client_policy.id', $file_data['client_policy_id'])
->where('client_policy.is_active', 1)
->first();
try {
$mapped = [];
$rejecetd_reason = [];
foreach ($tpaClaimDumpData as $row) {
$params = [
'doa' => change_date_format($row['doa'] ?? '') ?? null,
'emp_code' => $row['employee_member_id'] ?? null,
'claim_amount' => $row['claim_amount'] ?? null,
'tpa_no' => $row['uhid'] ?? null
];
$isduplicate = $this->checkDublicateTicketMasterClaim($params);
if ($isduplicate) {
$reason = "This claim already exists in our system.";
$rejecetd_reason[] = ["id" => $row['id'], "master_reject_reason" => $reason];
continue;
}
$item = [];
$item['client_id'] = $client_policy_data['client_id'] ?? null;
$item['client_policy_id'] = $client_policy_data['id'] ?? null;
$item['insurer_id'] = $client_policy_data['insurer_id'] ?? null;
$item['tpa_id'] = $client_policy_data['tpa_id'] ?? null;
$item['acm_id'] = $client_policy_data['acm_id'] ?? null;
$item['policy_no'] = $client_policy_data['policy_no'] ?? null;
$item['relationship'] = $this->convertRelation($row['relation_group'] ?? '');
$employee_data = $this->getEmployeeDetails($file_data['client_id'], $file_data['client_policy_id'], $row['employee_member_id'], $item['relationship']);
if (!empty($employee_data)) {
$item['emp_id'] = $employee_data['id'] ?? null;
$item['emp_name'] = $employee_data['name'] ?? null;
$item['emp_code'] = $employee_data['emp_code'] ?? null;
$item['emp_mail'] = $employee_data['email_corporate'] ?? null;
$item['emp_mobile'] = $employee_data['mobile'] ?? null;
if (!empty($employee_data['insured_emp_id'])) {
$item['insured_emp_id'] = $employee_data['insured_emp_id'] ?? null;
$item['insured_name'] = $employee_data['insured_name'] ?? null;
}else{
$reason = 'This Dependent employee not exist in our system.';
$rejecetd_reason[] = ["id" => $row['id'], "master_reject_reason" => $reason];
continue;
}
} else {
$reason = 'This employee not exist in our system.';
$rejecetd_reason[] = ["id" => $row['id'], "master_reject_reason" => $reason];
continue;
}
foreach ($this->ticketMasterMapping as $tpaKey => $ticketMasterKey) {
$item[$ticketMasterKey] = array_key_exists($tpaKey, $row) ? $row[$tpaKey] : null;
}
// Meta fields
$item['claim_status_id'] = $statusMapping[$row['updated_status']] ?? 61;
$item['claim_dump_ref_id'] = $row['id'];
$item['file_id'] = $file_id;
$item['created_by'] = $file_data['created_by'] ?? null;
$item['claim_type'] = 1;
$item['priority'] = 1;
$item['mode_of_intimation'] = 5;
$item['ticket_type_id'] = 1;
$mapped[] = $item;
}
return ['status' => true, 'mapped_array' => $mapped, 'rejected_reason_array' => $rejecetd_reason];
} 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,
];
return ['status' => false, "message" => $errorData['message'], 'error_data' => $errorData];
}
}
/**
* HELPER FUNCTIONs
*/
public function convertRelation(?string $relation): ?string
{
if (empty($relation)) {
return null;
}
$relation = strtolower($relation);
if (str_contains($relation, 'self')) {
return 'self';
}
if (str_contains($relation, 'spouse') || str_contains($relation, 'wife') || str_contains($relation, 'husband')) {
return 'spouse';
}
if (str_contains($relation, 'daughter')) {
return 'daughter';
}
if (str_contains($relation, 'son')) {
return 'son';
}
if (str_contains($relation, 'father in law') || str_contains($relation, 'father-in-law')) {
return 'father-in-law';
}
if (str_contains($relation, 'mother in law') || str_contains($relation, 'mother-in-law')) {
return 'mother-in-law';
}
if (str_contains($relation, 'father')) {
return 'father';
}
if (str_contains($relation, 'mother')) {
return 'mother';
}
return null; // unmatched case
}
}

View File

@ -0,0 +1,438 @@
<?php
namespace App\Libraries\TPAClaimsImportServices;
use App\Models\TicketMasterModel;
use App\Models\ClientPolicyModel;
use App\Models\ClientRMModel;
use App\Models\EmployeeModel;
use App\Models\ClaimDumpFileModel;
class MediAssistClaimImportService extends BaseTpaClaimImportService
{
/**
* MAPPING ARRAYs
*/
protected $mapping = [
["excel_column" => ["col_name" => "insurance_company", "col_index" => 0], "db_column" => "insurance_company"],
["excel_column" => ["col_name" => "insurer_region_name", "col_index" => 1], "db_column" => "insurer_region_name"],
["excel_column" => ["col_name" => "insurer_ro_code", "col_index" => 2], "db_column" => "insurer_ro_code"],
["excel_column" => ["col_name" => "insurer_do_code", "col_index" => 3], "db_column" => "insurer_do_code"],
["excel_column" => ["col_name" => "insurer_bo_code", "col_index" => 4], "db_column" => "insurer_bo_code"],
["excel_column" => ["col_name" => "event_id", "col_index" => 5], "db_column" => "event_id"],
["excel_column" => ["col_name" => "claim_id", "col_index" => 6], "db_column" => "claim_id"],
["excel_column" => ["col_name" => "insurer_claim_ref_no", "col_index" => 7], "db_column" => "insurer_claim_ref_no"],
["excel_column" => ["col_name" => "claim_pre_auths", "col_index" => 8], "db_column" => "claim_pre_auths"],
["excel_column" => ["col_name" => "ma_policy_id", "col_index" => 9], "db_column" => "ma_policy_id"],
["excel_column" => ["col_name" => "policy_no", "col_index" => 10], "db_column" => "policy_no"],
["excel_column" => ["col_name" => "policy_holder_name", "col_index" => 11], "db_column" => "policy_holder_name"],
["excel_column" => ["col_name" => "policy_type", "col_index" => 12], "db_column" => "policy_type"],
["excel_column" => ["col_name" => "policy_subtype_desc", "col_index" => 13], "db_column" => "policy_subtype_desc"],
["excel_column" => ["col_name" => "policy_start_date", "col_index" => 14], "db_column" => "policy_start_date"],
["excel_column" => ["col_name" => "policy_end_date", "col_index" => 15], "db_column" => "policy_end_date"],
["excel_column" => ["col_name" => "devlopment_officer", "col_index" => 16], "db_column" => "devlopment_officer"],
["excel_column" => ["col_name" => "agent", "col_index" => 17], "db_column" => "agent"],
["excel_column" => ["col_name" => "broker", "col_index" => 18], "db_column" => "broker"],
["excel_column" => ["col_name" => "pribenef_employee_code", "col_index" => 19], "db_column" => "pribenef_employee_code"],
["excel_column" => ["col_name" => "pribenef_name", "col_index" => 20], "db_column" => "pribenef_name"],
["excel_column" => ["col_name" => "pribenef_floater_sum", "col_index" => 21], "db_column" => "pribenef_floater_sum"],
["excel_column" => ["col_name" => "benef_maid", "col_index" => 22], "db_column" => "benef_maid"],
["excel_column" => ["col_name" => "benef_insurer_id", "col_index" => 23], "db_column" => "benef_insurer_id"],
["excel_column" => ["col_name" => "benef_name", "col_index" => 24], "db_column" => "benef_name"],
["excel_column" => ["col_name" => "benef_gender", "col_index" => 25], "db_column" => "benef_gender"],
["excel_column" => ["col_name" => "benef_relation", "col_index" => 26], "db_column" => "benef_relation"],
["excel_column" => ["col_name" => "benef_age", "col_index" => 27], "db_column" => "benef_age"],
["excel_column" => ["col_name" => "benef_sum_insured", "col_index" => 28], "db_column" => "benef_sum_insured"],
["excel_column" => ["col_name" => "balance_sum_insured", "col_index" => 29], "db_column" => "balance_sum_insured"],
["excel_column" => ["col_name" => "intimation_id", "col_index" => 30], "db_column" => "intimation_id"],
["excel_column" => ["col_name" => "intimation_date", "col_index" => 31], "db_column" => "intimation_date"],
["excel_column" => ["col_name" => "settled_date", "col_index" => 32], "db_column" => "settled_date"],
["excel_column" => ["col_name" => "ClaimSource", "col_index" => 33], "db_column" => "ClaimSource"],
["excel_column" => ["col_name" => "claim_mode_of_rcpt", "col_index" => 34], "db_column" => "claim_mode_of_rcpt"],
["excel_column" => ["col_name" => "claim_type", "col_index" => 35], "db_column" => "claim_type"],
["excel_column" => ["col_name" => "claim_sub_type", "col_index" => 36], "db_column" => "claim_sub_type"],
["excel_column" => ["col_name" => "claim_stage", "col_index" => 37], "db_column" => "claim_stage"],
["excel_column" => ["col_name" => "claim_status", "col_index" => 38], "db_column" => "claim_status"],
["excel_column" => ["col_name" => "is_cashlessanywhere", "col_index" => 39], "db_column" => "is_cashlessanywhere"],
["excel_column" => ["col_name" => "date_of_admission", "col_index" => 40], "db_column" => "date_of_admission"],
["excel_column" => ["col_name" => "date_of_discharge", "col_index" => 41], "db_column" => "date_of_discharge"],
["excel_column" => ["col_name" => "claim_amount", "col_index" => 42], "db_column" => "claim_amount"],
["excel_column" => ["col_name" => "claim_approved_amount", "col_index" => 43], "db_column" => "claim_approved_amount"],
["excel_column" => ["col_name" => "incurred_amount", "col_index" => 44], "db_column" => "incurred_amount"],
["excel_column" => ["col_name" => "primary_icd_group", "col_index" => 45], "db_column" => "primary_icd_group"],
["excel_column" => ["col_name" => "primary_ailment_name", "col_index" => 46], "db_column" => "primary_ailment_name"],
["excel_column" => ["col_name" => "primary_ailment_code", "col_index" => 47], "db_column" => "primary_ailment_code"],
["excel_column" => ["col_name" => "treatment_type", "col_index" => 48], "db_column" => "treatment_type"],
["excel_column" => ["col_name" => "treatment_name", "col_index" => 49], "db_column" => "treatment_name"],
["excel_column" => ["col_name" => "hospital_id", "col_index" => 50], "db_column" => "hospital_id"],
["excel_column" => ["col_name" => "hospital_name", "col_index" => 51], "db_column" => "hospital_name"],
["excel_column" => ["col_name" => "hospital_city", "col_index" => 52], "db_column" => "hospital_city"],
["excel_column" => ["col_name" => "hospital_state", "col_index" => 53], "db_column" => "hospital_state"],
["excel_column" => ["col_name" => "hospital_pincode", "col_index" => 54], "db_column" => "hospital_pincode"],
["excel_column" => ["col_name" => "hospital_address", "col_index" => 55], "db_column" => "hospital_address"],
["excel_column" => ["col_name" => "Clinic_DoctorName_Hospital", "col_index" => 56], "db_column" => "Clinic_DoctorName_Hospital"],
["excel_column" => ["col_name" => "OPD_pincode", "col_index" => 57], "db_column" => "OPD_pincode"],
["excel_column" => ["col_name" => "payable_amount_OPD_Consultation", "col_index" => 58], "db_column" => "payable_amount_OPD_Consultation"],
["excel_column" => ["col_name" => "payable_amount_Dental", "col_index" => 59], "db_column" => "payable_amount_Dental"],
["excel_column" => ["col_name" => "payable_amount_Diagnostics", "col_index" => 60], "db_column" => "payable_amount_Diagnostics"],
["excel_column" => ["col_name" => "payable_amount_Other", "col_index" => 61], "db_column" => "payable_amount_Other"],
["excel_column" => ["col_name" => "payable_amount_Pharmacy", "col_index" => 62], "db_column" => "payable_amount_Pharmacy"],
["excel_column" => ["col_name" => "payable_amount_Vaccination", "col_index" => 63], "db_column" => "payable_amount_Vaccination"],
["excel_column" => ["col_name" => "payable_amount_Miscellaneous_Charges", "col_index" => 64], "db_column" => "payable_amount_Miscellaneous_Charges"],
["excel_column" => ["col_name" => "payable_amount_Health_Checkup", "col_index" => 65], "db_column" => "payable_amount_Health_Checkup"],
["excel_column" => ["col_name" => "deduction_amount_copay", "col_index" => 66], "db_column" => "deduction_amount_copay"],
["excel_column" => ["col_name" => "deduction_amount_excess_ailment", "col_index" => 67], "db_column" => "deduction_amount_excess_ailment"],
["excel_column" => ["col_name" => "deduction_amount_excess_policy", "col_index" => 68], "db_column" => "deduction_amount_excess_policy"],
["excel_column" => ["col_name" => "deduction_amount_prorata", "col_index" => 69], "db_column" => "deduction_amount_prorata"],
["excel_column" => ["col_name" => "deduction_amount_hospital_discount", "col_index" => 70], "db_column" => "deduction_amount_hospital_discount"],
["excel_column" => ["col_name" => "deduction_amount_paid_by_patient", "col_index" => 71], "db_column" => "deduction_amount_paid_by_patient"],
["excel_column" => ["col_name" => "deduction_amount_issurer_approved", "col_index" => 72], "db_column" => "deduction_amount_issurer_approved"],
["excel_column" => ["col_name" => "deduction_amount_deductible", "col_index" => 73], "db_column" => "deduction_amount_deductible"],
["excel_column" => ["col_name" => "deduction_amount_intimation_penalty", "col_index" => 74], "db_column" => "deduction_amount_intimation_penalty"],
["excel_column" => ["col_name" => "claim_payable_to_name", "col_index" => 75], "db_column" => "claim_payable_to_name"],
["excel_column" => ["col_name" => "utr_no", "col_index" => 76], "db_column" => "utr_no"],
["excel_column" => ["col_name" => "utr_date", "col_index" => 77], "db_column" => "utr_date"],
["excel_column" => ["col_name" => "denial_short_description", "col_index" => 78], "db_column" => "denial_short_description"],
["excel_column" => ["col_name" => "claim_received_date", "col_index" => 79], "db_column" => "claim_received_date"],
["excel_column" => ["col_name" => "last_necessary_doc_rec_date", "col_index" => 80], "db_column" => "last_necessary_doc_rec_date"],
["excel_column" => ["col_name" => "processed_date", "col_index" => 81], "db_column" => "processed_date"],
["excel_column" => ["col_name" => "first_document_attached_date", "col_index" => 82], "db_column" => "first_document_attached_date"],
["excel_column" => ["col_name" => "claim_processing_tat_days", "col_index" => 83], "db_column" => "claim_processing_tat_days"],
["excel_column" => ["col_name" => "ready_for_payment_date", "col_index" => 84], "db_column" => "ready_for_payment_date"],
["excel_column" => ["col_name" => "payment_date", "col_index" => 85], "db_column" => "payment_date"],
["excel_column" => ["col_name" => "claim_payment_tat_days", "col_index" => 86], "db_column" => "claim_payment_tat_days"],
["excel_column" => ["col_name" => "denial_description", "col_index" => 87], "db_column" => "denial_description"],
["excel_column" => ["col_name" => "error_group", "col_index" => 88], "db_column" => "error_group"],
["excel_column" => ["col_name" => "tpa_name", "col_index" => 89], "db_column" => "tpa_name"],
["excel_column" => ["col_name" => "new_short_error_group", "col_index" => 90], "db_column" => "new_short_error_group"],
["excel_column" => ["col_name" => "death_claim", "col_index" => 91], "db_column" => "death_claim"],
["excel_column" => ["col_name" => "vip_claim", "col_index" => 92], "db_column" => "vip_claim"],
["excel_column" => ["col_name" => "balance_sum_insured_exhausted", "col_index" => 93], "db_column" => "balance_sum_insured_exhausted"],
];
protected $ticketMasterMapping = [
// Employee / Beneficiary details
'pribenef_employee_code' => 'emp_code',
// Policy / Claim identifiers
'claim_id' => 'claim_number',
'event_id' => 'tpa_no',
'claim_pre_auths' => 'tpa_claim_push_reference_no',
// Claim type & status
'claim_status' => 'tpa_claim_status',
// Dates
'date_of_admission' => 'doa',
'date_of_discharge' => 'dod',
'intimation_date' => 'date_of_intimat',
'settled_date' => 'settled_date',
'claim_received_date' => 'registration_date',
'processed_date' => 'approved_date',
// Amounts
'claim_amount' => 'claim_amount',
'claim_approved_amount' => 'approved_amount',
// Hospital details
'hospital_name' => 'hospital_name',
'hospital_address' => 'hospital_address',
'hospital_city' => 'hospital_city',
'hospital_state' => 'hospital_state',
'hospital_pincode' => 'hospital_pin_code',
'hospital_phone_no' => 'hospital_phone_no',
// Denial / approval
'denial_description' => 'denial_reason',
'approved_description' => 'approved_description',
// Payment
'utr_no' => 'utr_details',
'claim_type' => 'tpa_claim_type',
'primary_ailment_name' => 'tpa_ailments',
];
protected $statusMapping = [
'Settled' => 11,
'Rejected' => 8,
'Denied' => 8,
'Cancelled' => 13,
'Processed' => 61,
'Information Awaited' => 4,
'Denied Letter Sent' => 66,
'Cashless Document Awaited' => 3,
];
/**
* ABSTRACT FUNCTIONs
*/
public function bulkInsertTPATable(array $data): bool
{
if (empty($data)) {
return false;
}
$builder = $this->db->table('claims_dump_medi_assist');
return $builder->insertBatch($data);
}
public function importClaimMaster(array $data): bool
{
if (empty($data)) {
return false;
}
$ticketMasterModel = new TicketMasterModel();
return $ticketMasterModel->insertBatch($data);
}
public function updateTicketIdInTPATable(): bool
{
if (empty($data)) {
return false;
}
$builder = $this->db->table('claims_dump_medi_assist');
$builder->insertBatch($data);
return true;
}
public function updateTicketMasterRejectedReasonInTPATable($data): bool
{
if (empty($data)) {
return false;
}
$builder = $this->db->table('claims_dump_medi_assist');
return $builder->updateBatch($data, 'id');
}
/**
* MAPPING FUNCTIONs
*/
public function mapTPAData(array $rows, $file_id): array
{
$ClientPolicyModel = new ClaimDumpFileModel();
$file_data = $ClientPolicyModel->where('id', $file_id)->first();
$mapped = [];
foreach ($rows as $row) {
$item = [];
foreach ($this->mapping as $map) {
$excelColumn = $map['excel_column']['col_name'];
$dbColumn = $map['db_column'];
$value = $row[$excelColumn] ?? null;
$item[$dbColumn] = $value;
}
$params = [
'date_of_admission' => change_date_format($item['date_of_admission'] ?? '') ?? null,
'pribenef_employee_code' => $item['pribenef_employee_code'] ?? null,
'claim_amount' => $item['claim_amount'] ?? null,
'event_id' => $item['event_id'] ?? null
];
$is_duplicate = $this->checkDuplicateTpaClaim('claims_dump_medi_assist', $params);
if ($is_duplicate) {
$item = [];
continue;
}
$item['file_id'] = $file_id ?? null;
$item['client_id'] = $file_data['client_id'] ?? null;
$item['client_policy_id'] = $file_data['client_policy_id'] ?? null;
$item['created_by'] = $file_data['created_by'] ?? null;
$mapped[] = $item;
}
return $mapped;
}
public function mapClaimMasterData($file_id): array
{
$ClientPolicyModel = new ClaimDumpFileModel();
$file_data = $ClientPolicyModel->where('id', $file_id)->first();
$tpaClaimDumpData = $this->getTpaClaimDumpData('claims_dump_medi_assist', ['file_id' => $file_id]);
if (empty($tpaClaimDumpData)) {
return ['status' => false, 'message' => "No data to insert in TICKET MASTER"];
}
$ClientPolicyModel = new ClientPolicyModel();
$client_policy_data = $ClientPolicyModel
->select("
client_policy.*,
(
SELECT id
FROM client_rm
WHERE is_active = 1
AND level = 3
AND client_id = client_policy.client_id
ORDER BY id ASC
LIMIT 1
) AS acm_id
")
->where('client_policy.id', $file_data['client_policy_id'])
->where('client_policy.is_active', 1)
->first();
try {
$mapped = [];
$rejecetd_reason = [];
foreach ($tpaClaimDumpData as $row) {
$params = [
'doa' => change_date_format($row['date_of_admission'] ?? '') ?? null,
'emp_code' => $row['pribenef_employee_code'] ?? null,
'claim_amount' => $row['claim_amount'] ?? null,
'tpa_no' => $row['event_id'] ?? null
];
$isduplicate = $this->checkDublicateTicketMasterClaim($params);
if ($isduplicate) {
$reason = "This claim already exists in our system.";
$rejecetd_reason[] = ["id" => $row['id'], "master_reject_reason" => $reason];
continue;
}
$item = [];
$item['client_id'] = $client_policy_data['client_id'] ?? null;
$item['client_policy_id'] = $client_policy_data['id'] ?? null;
$item['insurer_id'] = $client_policy_data['insurer_id'] ?? null;
$item['tpa_id'] = $client_policy_data['tpa_id'] ?? null;
$item['acm_id'] = $client_policy_data['acm_id'] ?? null;
$item['policy_no'] = $client_policy_data['policy_no'] ?? null;
$item['relationship'] = $this->convertRelation($row['benef_relation'] ?? null);
$employee_data = $this->getEmployeeDetails($file_data['client_id'], $file_data['client_policy_id'], $row['pribenef_employee_code'], $item['relationship']);
if (!empty($employee_data)) {
$item['emp_id'] = $employee_data['id'] ?? null;
$item['emp_name'] = $employee_data['name'] ?? null;
$item['emp_code'] = $employee_data['emp_code'] ?? null;
$item['emp_mail'] = $employee_data['email_corporate'] ?? null;
$item['emp_mobile'] = $employee_data['mobile'] ?? null;
if (!empty($employee_data['insured_emp_id'])) {
$item['insured_emp_id'] = $employee_data['insured_emp_id'] ?? null;
$item['insured_name'] = $employee_data['insured_name'] ?? null;
}else{
$reason = 'This Dependent employee not exist in our system.';
$rejecetd_reason[] = ["id" => $row['id'], "master_reject_reason" => $reason];
continue;
}
} else {
$reason = 'This employee not exist in our system.';
$rejecetd_reason[] = ["id" => $row['id'], "master_reject_reason" => $reason];
continue;
}
foreach ($this->ticketMasterMapping as $tpaKey => $ticketMasterKey) {
$item[$ticketMasterKey] = array_key_exists($tpaKey, $row) ? $row[$tpaKey] : null;
}
// Meta fields
$item['claim_dump_ref_id'] = $row['id'];
$item['file_id'] = $file_id;
$item['claim_status_id'] = $statusMapping[$row['claim_status']] ?? 61;
$item['created_by'] = $file_data['created_by'] ?? null;
$item['claim_type'] = 1;
$item['priority'] = 1;
$item['mode_of_intimation'] = 5;
$item['ticket_type_id'] = 1;
$mapped[] = $item;
}
return ['status' => true, 'mapped_array' => $mapped, 'rejected_reason_array' => $rejecetd_reason];
} 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,
];
return ['status' => false, "message" => $errorData['message'], 'error_data' => $errorData];
}
}
/**
* HELPER FUNCTIONs
*/
public function convertRelation(?string $relation): ?string
{
if (empty($relation)) {
return null;
}
$relation = strtolower($relation);
if (str_contains($relation, 'self')) {
return 'self';
}
if (str_contains($relation, 'spouse') || str_contains($relation, 'wife') || str_contains($relation, 'husband')) {
return 'spouse';
}
if (str_contains($relation, 'daughter')) {
return 'daughter';
}
if (str_contains($relation, 'son')) {
return 'son';
}
if (str_contains($relation, 'father in law') || str_contains($relation, 'father-in-law')) {
return 'father-in-law';
}
if (str_contains($relation, 'mother in law') || str_contains($relation, 'mother-in-law')) {
return 'mother-in-law';
}
if (str_contains($relation, 'father')) {
return 'father';
}
if (str_contains($relation, 'mother')) {
return 'mother';
}
return null; // unmatched case
}
}

View File

@ -0,0 +1,392 @@
<?php
namespace App\Libraries\TPAClaimsImportServices;
use App\Models\TicketMasterModel;
use App\Models\ClientPolicyModel;
use App\Models\ClientRMModel;
use App\Models\EmployeeModel;
use App\Models\ClaimDumpFileModel;
use App\Models\ClaimsDumpFhplModel;
class RcareClaimImportService extends BaseTpaClaimImportService
{
/**
* MAPPING ARRAYs
*/
protected $mapping = [
["excel_column" => ["col_name" => "CLInwardNo", "col_index" => 0], "db_column" => "cl_inward_no"],
["excel_column" => ["col_name" => "Inward Date", "col_index" => 1], "db_column" => "inward_date"],
["excel_column" => ["col_name" => "Claim Classification", "col_index" => 2], "db_column" => "claim_classification"],
["excel_column" => ["col_name" => "Policy Name", "col_index" => 3], "db_column" => "policy_name"],
["excel_column" => ["col_name" => "Policy Number", "col_index" => 4], "db_column" => "policy_number"],
["excel_column" => ["col_name" => "Policy Start Date", "col_index" => 5], "db_column" => "policy_start_date"],
["excel_column" => ["col_name" => "Policy End Date", "col_index" => 6], "db_column" => "policy_end_date"],
["excel_column" => ["col_name" => "UHID", "col_index" => 7], "db_column" => "uhid"],
["excel_column" => ["col_name" => "Insured Name", "col_index" => 8], "db_column" => "insured_name"],
["excel_column" => ["col_name" => "Patient Name", "col_index" => 9], "db_column" => "patient_name"],
["excel_column" => ["col_name" => "Employee/Member Id", "col_index" => 10], "db_column" => "employee_member_id"],
["excel_column" => ["col_name" => "Grade", "col_index" => 11], "db_column" => "grade"],
["excel_column" => ["col_name" => "Relation", "col_index" => 12], "db_column" => "relation"],
["excel_column" => ["col_name" => "Age", "col_index" => 13], "db_column" => "age"],
["excel_column" => ["col_name" => "Gender", "col_index" => 14], "db_column" => "gender"],
["excel_column" => ["col_name" => "DF/DNF idenitifcation", "col_index" => 15], "db_column" => "df_dnf_identification"],
["excel_column" => ["col_name" => "Sum Insured", "col_index" => 16], "db_column" => "sum_insured"],
["excel_column" => ["col_name" => "DOA/OPD Treatment From", "col_index" => 17], "db_column" => "doa_opd_treatment_from"],
["excel_column" => ["col_name" => "DOD/OPD Treatment To", "col_index" => 18], "db_column" => "dod_opd_treatment_to"],
["excel_column" => ["col_name" => "Hospital Name", "col_index" => 19], "db_column" => "hospital_name"],
["excel_column" => ["col_name" => "Hospital District", "col_index" => 20], "db_column" => "hospital_district"],
["excel_column" => ["col_name" => "Hospital State", "col_index" => 21], "db_column" => "hospital_state"],
["excel_column" => ["col_name" => "ICDCode", "col_index" => 22], "db_column" => "icd_code"],
["excel_column" => ["col_name" => "Disease Category", "col_index" => 23], "db_column" => "disease_category"],
["excel_column" => ["col_name" => "Final Status", "col_index" => 24], "db_column" => "final_status"],
["excel_column" => ["col_name" => "Approved Date", "col_index" => 25], "db_column" => "approved_date"],
["excel_column" => ["col_name" => "Claimed Amount", "col_index" => 26], "db_column" => "claimed_amount"],
["excel_column" => ["col_name" => "Disallowed Amount", "col_index" => 27], "db_column" => "disallowed_amount"],
["excel_column" => ["col_name" => "Net Sanct Amt", "col_index" => 28], "db_column" => "net_sanction_amount"],
["excel_column" => ["col_name" => "Reason For Disallowance", "col_index" => 29], "db_column" => "reason_for_disallowance"],
["excel_column" => ["col_name" => "External Query Remarks", "col_index" => 30], "db_column" => "external_query_remarks"],
["excel_column" => ["col_name" => "Rejection Remarks", "col_index" => 31], "db_column" => "rejection_remarks"],
["excel_column" => ["col_name" => "Cheque/NEFT Number", "col_index" => 32], "db_column" => "cheque_neft_number"],
["excel_column" => ["col_name" => "Cheque/NEFT Date", "col_index" => 33], "db_column" => "cheque_neft_date"],
["excel_column" => ["col_name" => "Diagnosis", "col_index" => 34], "db_column" => "diagnosis"],
["excel_column" => ["col_name" => "Treatment Detail", "col_index" => 35], "db_column" => "treatment_detail"],
["excel_column" => ["col_name" => "Member Reimbursement CL Type", "col_index" => 36], "db_column" => "member_reimbursement_cl_type"],
];
protected $ticketMasterMapping = [
// Employee / Member
'employee_member_id' => 'emp_code',
// Policy
'policy_start_date' => 'date_of_incep',
// Claim Dates
'doa_opd_treatment_from' => 'doa',
'dod_opd_treatment_to' => 'dod',
'approved_date' => 'approved_date',
// Claim Amounts
'claimed_amount' => 'claim_amount',
'net_sanction_amount' => 'approved_amount',
// Status / Remarks
'final_status' => 'tpa_claim_status',
'reason_for_disallowance' => 'denial_reason',
'rejection_remarks' => 'return_remark',
// Hospital
'hospital_name' => 'hospital_name',
'hospital_state' => 'hospital_state',
'hospital_district' => 'hospital_city',
'diagnosis' => 'claim_description',
'diagnosis' => 'tpa_ailments',
// Payment
'cheque_neft_number' => 'utr_details',
'cheque_neft_date' => 'settled_date',
// References
'cl_inward_no' => 'claim_number',
];
protected $statusMapping = [
'Settled' => 11,
'Rejected' => 8,
'Denied' => 8,
'Cancelled' => 13,
'Processed' => 61,
'Information Awaited' => 4,
'Denied Letter Sent' => 66,
'Cashless Document Awaited' => 3,
];
protected $dateColumns = [
'inward_date',
'policy_start_date',
'policy_end_date',
'doa_opd_treatment_from',
'dod_opd_treatment_to',
'approved_date',
'cheque_neft_date'
];
/**
* ABSTRACT FUNCTIONs
*/
public function bulkInsertTPATable(array $data): bool
{
if (empty($data)) {
return false;
}
$builder = $this->db->table('claims_dump_reliance');
return $builder->insertBatch($data);
}
public function importClaimMaster(array $data): bool
{
if (empty($data)) {
return false;
}
$ticketMasterModel = new TicketMasterModel();
return $ticketMasterModel->insertBatch($data);
}
public function updateTicketIdInTPATable(): bool
{
if (empty($data)) {
return false;
}
$builder = $this->db->table('claims_dump_reliance');
return $builder->updateBatch($data, 'id');
}
public function updateTicketMasterRejectedReasonInTPATable($data): bool
{
if (empty($data)) {
return false;
}
$builder = $this->db->table('claims_dump_reliance');
return $builder->updateBatch($data, 'id');
}
/**
* MAPPING FUNCTIONs
*/
public function mapTPAData(array $rows, $file_id): array
{
$ClientPolicyModel = new ClaimDumpFileModel();
$file_data = $ClientPolicyModel->where('id', $file_id)->first();
$mapped = [];
foreach ($rows as $row) {
$item = [];
foreach ($this->mapping as $map) {
$excelColumn = $map['excel_column']['col_name'];
$dbColumn = $map['db_column'];
$value = $row[$excelColumn] ?? null;
$item[$dbColumn] = $value;
}
foreach ($this->dateColumns as $key => $value) {
$item[$value] = change_date_format($item[$value] ?? null, 'd-M-y', 'Y-m-d');
}
$params = [
'doa_opd_treatment_from' => $item['doa_opd_treatment_from'] ?? null,
'employee_member_id' => $item['employee_member_id'] ?? null,
'claimed_amount' => $item['claimed_amount'] ?? null,
'uhid' => $item['uhid'] ?? null
];
$is_duplicate = $this->checkDuplicateTpaClaim('claims_dump_reliance', $params);
if ($is_duplicate) {
$item = [];
continue;
}
$item['file_id'] = $file_id ?? null;
$item['client_id'] = $file_data['client_id'] ?? null;
$item['client_policy_id'] = $file_data['client_policy_id'] ?? null;
$item['created_by'] = $file_data['created_by'] ?? null;
$mapped[] = $item;
}
return $mapped;
}
public function mapClaimMasterData($file_id): array
{
$ClientPolicyModel = new ClaimDumpFileModel();
$file_data = $ClientPolicyModel->where('id', $file_id)->first();
$tpaClaimDumpData = $this->getTpaClaimDumpData('claims_dump_reliance', ['file_id' => $file_id]);
if (empty($tpaClaimDumpData)) {
return ['status' => false, 'message' => "No data to insert in TICKET MASTER"];
}
$ClientPolicyModel = new ClientPolicyModel();
$client_policy_data = $ClientPolicyModel
->select("
client_policy.*,
(
SELECT id
FROM client_rm
WHERE is_active = 1
AND level = 3
AND client_id = client_policy.client_id
ORDER BY id ASC
LIMIT 1
) AS acm_id
")
->where('client_policy.id', $file_data['client_policy_id'])
->where('client_policy.is_active', 1)
->first();
try {
$mapped = [];
$rejecetd_reason = [];
foreach ($tpaClaimDumpData as $row) {
$params = [
'doa' => change_date_format($row['doa_opd_treatment_from'] ?? '') ?? null,
'emp_code' => $row['employee_member_id'] ?? null,
'claim_amount' => $row['claimed_amount'] ?? null,
'tpa_no' => $row['uhid'] ?? null
];
$isduplicate = $this->checkDublicateTicketMasterClaim($params);
if ($isduplicate) {
$reason = "This claim already exists in our system.";
$rejecetd_reason[] = ["id" => $row['id'], "master_reject_reason" => $reason];
continue;
}
$item = [];
$item['client_id'] = $client_policy_data['client_id'] ?? null;
$item['client_policy_id'] = $client_policy_data['id'] ?? null;
$item['insurer_id'] = $client_policy_data['insurer_id'] ?? null;
$item['tpa_id'] = $client_policy_data['tpa_id'] ?? null;
$item['acm_id'] = $client_policy_data['acm_id'] ?? null;
$item['policy_no'] = $client_policy_data['policy_no'] ?? null;
$item['relationship'] = $this->convertRelation($row['relation'] ?? null);
$employee_data = $this->getEmployeeDetails($file_data['client_id'], $file_data['client_policy_id'], $row['employee_member_id'], $item['relationship']);
if (!empty($employee_data)) {
$item['emp_id'] = $employee_data['id'] ?? null;
$item['emp_name'] = $employee_data['name'] ?? null;
$item['emp_code'] = $employee_data['emp_code'] ?? null;
$item['emp_mail'] = $employee_data['email_corporate'] ?? null;
$item['emp_mobile'] = $employee_data['mobile'] ?? null;
if (!empty($employee_data['insured_emp_id'])) {
$item['insured_emp_id'] = $employee_data['insured_emp_id'] ?? null;
$item['insured_name'] = $employee_data['insured_name'] ?? null;
}else{
$reason = 'This Dependent employee not exist in our system.';
$rejecetd_reason[] = ["id" => $row['id'], "master_reject_reason" => $reason];
continue;
}
} else {
$reason = 'This employee not exist in our system.';
$rejecetd_reason[] = ["id" => $row['id'], "master_reject_reason" => $reason];
continue;
}
foreach ($this->ticketMasterMapping as $tpaKey => $ticketMasterKey) {
$item[$ticketMasterKey] = array_key_exists($tpaKey, $row) ? $row[$tpaKey] : null;
}
// Meta fields
$item['claim_status_id'] = $statusMapping[$row['final_status']] ?? 61;
$item['file_id'] = $file_id;
$item['created_by'] = $file_data['created_by'] ?? null;
$item['claim_dump_ref_id'] = $row['id'];
$item['claim_type'] = 1;
$item['priority'] = 1;
$item['mode_of_intimation'] = 5;
$item['ticket_type_id'] = 1;
$mapped[] = $item;
}
return ['status' => true, 'mapped_array' => $mapped, 'rejected_reason_array' => $rejecetd_reason];
} 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,
];
return ['status' => false, "message" => $errorData['message'], 'error_data' => $errorData];
}
}
/**
* HELPER FUNCTIONs
*/
public function convertRelation(?string $relation): ?string
{
if (empty($relation)) {
return null;
}
$relation = strtolower($relation);
if (str_contains($relation, 'self')) {
return 'self';
}
if (str_contains($relation, 'spouse') || str_contains($relation, 'wife') || str_contains($relation, 'husband')) {
return 'spouse';
}
if (str_contains($relation, 'daughter')) {
return 'daughter';
}
if (str_contains($relation, 'son')) {
return 'son';
}
if (str_contains($relation, 'father in law') || str_contains($relation, 'father-in-law')) {
return 'father-in-law';
}
if (str_contains($relation, 'mother in law') || str_contains($relation, 'mother-in-law')) {
return 'mother-in-law';
}
if (str_contains($relation, 'father')) {
return 'father';
}
if (str_contains($relation, 'mother')) {
return 'mother';
}
return null; // unmatched case
}
}

View File

@ -0,0 +1,801 @@
<?php
namespace App\Libraries\TPAClaimsImportServices;
use App\Models\TicketMasterModel;
use App\Models\ClientPolicyModel;
use App\Models\ClientRMModel;
use App\Models\EmployeeModel;
use App\Models\ClaimDumpFileModel;
class VidalClaimImportService extends BaseTpaClaimImportService
{
/**
* MAPPING ARRAYs
*/
protected $mapping_old = [
["excel_column" => "TPA Policy Number", "db_column" => "tpa_policy_number"],
["excel_column" => "Insurer Policy Number", "db_column" => "insurer_policy_number"],
["excel_column" => "Corporate Name", "db_column" => "corporate_name"],
["excel_column" => "Proposer Name", "db_column" => "proposer_name"],
["excel_column" => "Corporate Group ID", "db_column" => "corporate_group_id"],
["excel_column" => "Policy Start Date", "db_column" => "policy_start_date"],
["excel_column" => "Policy End date", "db_column" => "policy_end_date"],
["excel_column" => "Insurance Company Name", "db_column" => "insurance_company_name"],
["excel_column" => "Employee Number", "db_column" => "employee_number"],
["excel_column" => "Employee Location", "db_column" => "employee_location"],
["excel_column" => "Primary Policy Holder Name", "db_column" => "primary_policy_holder_name"],
["excel_column" => "Primary Policy Holder Card ID", "db_column" => "primary_policy_holder_card_id"],
["excel_column" => "Employee Grade", "db_column" => "employee_grade"],
["excel_column" => "Patient Health Card ID", "db_column" => "patient_health_card_id"],
["excel_column" => "Patient Name", "db_column" => "patient_name"],
["excel_column" => "Date of Birth", "db_column" => "date_of_birth"],
["excel_column" => "Age", "db_column" => "age"],
["excel_column" => "Gender", "db_column" => "gender"],
["excel_column" => "Relation", "db_column" => "relation"],
["excel_column" => "Sum Insured", "db_column" => "sum_insured"],
["excel_column" => "Balance Sum Insured", "db_column" => "balance_sum_insured"],
["excel_column" => "Top Up Sum Insured", "db_column" => "top_up_sum_insured"],
["excel_column" => "Enrollment status", "db_column" => "enrollment_status"],
["excel_column" => "Policy Inception date", "db_column" => "policy_inception_date"],
["excel_column" => "Policy Exit Date", "db_column" => "policy_exit_date"],
["excel_column" => "Insurer Risk ID", "db_column" => "insurer_risk_id"],
["excel_column" => "Claim Preauth Identifier", "db_column" => "claim_preauth_identifier"],
["excel_column" => "TPA Claim Number", "db_column" => "tpa_claim_number"],
["excel_column" => "Preauth Number", "db_column" => "preauth_number"],
["excel_column" => "Insurer Claim Number", "db_column" => "insurer_claim_number"],
["excel_column" => "Claim Received date", "db_column" => "claim_received_date"],
["excel_column" => "Date of Admission", "db_column" => "date_of_admission"],
["excel_column" => "Date of Discharge", "db_column" => "date_of_discharge"],
["excel_column" => "Hospital Name", "db_column" => "hospital_name"],
["excel_column" => "Hospital ID", "db_column" => "hospital_id"],
["excel_column" => "Hospital Address", "db_column" => "hospital_address"],
["excel_column" => "Hospital City", "db_column" => "hospital_city"],
["excel_column" => "Hospital State", "db_column" => "hospital_state"],
["excel_column" => "Hospital Pincode", "db_column" => "hospital_pincode"],
["excel_column" => "Hospital Network status", "db_column" => "hospital_network_status"],
["excel_column" => "PPN Hospital Status", "db_column" => "ppn_hospital_status"],
["excel_column" => "Room Category", "db_column" => "room_category"],
["excel_column" => "Room Days", "db_column" => "room_days"],
["excel_column" => "ICU Days", "db_column" => "icu_days"],
["excel_column" => "Medical Surgical Identifier", "db_column" => "medical_surgical_identifier"],
["excel_column" => "Treatment Type of AYUSH", "db_column" => "treatment_type_of_ayush"],
["excel_column" => "Package", "db_column" => "package"],
["excel_column" => "Diagnosis", "db_column" => "diagnosis"],
["excel_column" => "Illness Details", "db_column" => "illness_details"],
["excel_column" => "Ailment Grouping", "db_column" => "ailment_grouping"],
["excel_column" => "Primary ICD Code", "db_column" => "primary_icd_code"],
["excel_column" => "Secondary ICD Code", "db_column" => "secondary_icd_code"],
["excel_column" => "Procedure Code", "db_column" => "procedure_code"],
["excel_column" => "Procedure Description", "db_column" => "procedure_description"],
["excel_column" => "Procedure Grouping", "db_column" => "procedure_grouping"],
["excel_column" => "Claim Submission mode", "db_column" => "claim_submission_mode"],
["excel_column" => "Admission Category", "db_column" => "admission_category"],
["excel_column" => "Type of Claim", "db_column" => "type_of_claim"],
["excel_column" => "MainClaim_Prepost type", "db_column" => "mainclaim_prepost_type"],
["excel_column" => "Type of Hospitalization", "db_column" => "type_of_hospitalization"],
["excel_column" => "Death Status", "db_column" => "death_status"],
["excel_column" => "Treatement Given", "db_column" => "treatment_given"],
["excel_column" => "Claim Amount", "db_column" => "claim_amount"],
["excel_column" => "Total Billed Amount", "db_column" => "total_billed_amount"],
["excel_column" => "Claim Consultation Charges", "db_column" => "claim_consultation_charges"],
["excel_column" => "Claim Investigation Charges", "db_column" => "claim_investigation_charges"],
["excel_column" => "Claim Medicines", "db_column" => "claim_medicines"],
["excel_column" => "Claim Nursing", "db_column" => "claim_nursing"],
["excel_column" => "Claim Room Charges", "db_column" => "claim_room_charges"],
["excel_column" => "Claim Icu Charges", "db_column" => "claim_icu_charges"],
["excel_column" => "Claim Stay Charges", "db_column" => "claim_stay_charges"],
["excel_column" => "Claim Surgeon Charges", "db_column" => "claim_surgeon_charges"],
["excel_column" => "Claim Surgery Charges", "db_column" => "claim_surgery_charges"],
["excel_column" => "Claim Miscellaneous Charges", "db_column" => "claim_miscellaneous_charges"],
["excel_column" => "Claim Other Charges", "db_column" => "claim_other_charges"],
["excel_column" => "Approved Consultation Charges", "db_column" => "approved_consultation_charges"],
["excel_column" => "Approved Investigation Charges", "db_column" => "approved_investigation_charges"],
["excel_column" => "Approved Medicines", "db_column" => "approved_medicines"],
["excel_column" => "Approved Nursing", "db_column" => "approved_nursing"],
["excel_column" => "Approved Room Charges", "db_column" => "approved_room_charges"],
["excel_column" => "Approved Icu Charges", "db_column" => "approved_icu_charges"],
["excel_column" => "Approved Stay Charges", "db_column" => "approved_stay_charges"],
["excel_column" => "Approved Surgeon Charges", "db_column" => "approved_surgeon_charges"],
["excel_column" => "Approved Surgery Charges", "db_column" => "approved_surgery_charges"],
["excel_column" => "Approved Miscellaneous Charges", "db_column" => "approved_miscellaneous_charges"],
["excel_column" => "Approved Others Charges", "db_column" => "approved_others_charges"],
["excel_column" => "Total Disallowed Amount", "db_column" => "total_disallowed_amount"],
["excel_column" => "Copayment Amount", "db_column" => "copayment_amount"],
["excel_column" => "Deposit Amount", "db_column" => "deposit_amount"],
["excel_column" => "Exceeds Policy Limit", "db_column" => "exceeds_policy_limit"],
["excel_column" => "Copay Buffer", "db_column" => "copay_buffer"],
["excel_column" => "Hospital Discount Amount", "db_column" => "hospital_discount_amount"],
["excel_column" => "Deductible Amount", "db_column" => "deductible_amount"],
["excel_column" => "Approved Amount", "db_column" => "approved_amount"],
["excel_column" => "Total Incurred Amount", "db_column" => "total_incurred_amount"],
["excel_column" => "Total Buffer Approved", "db_column" => "total_buffer_approved"],
["excel_column" => "Total Buffer Utlilized", "db_column" => "total_buffer_utilized"],
["excel_column" => "TDS Amount", "db_column" => "tds_amount"],
["excel_column" => "Net Amount", "db_column" => "net_amount"],
["excel_column" => "Claim Decision date", "db_column" => "claim_decision_date"],
["excel_column" => "Payment Reference Number", "db_column" => "payment_reference_number"],
["excel_column" => "Payment Reference Date", "db_column" => "payment_reference_date"],
["excel_column" => "Claim Status", "db_column" => "claim_status"],
["excel_column" => "Deduction Remarks", "db_column" => "deduction_remarks"],
["excel_column" => "Rejection Reasons", "db_column" => "rejection_reasons"],
["excel_column" => "Claim Query Reasons", "db_column" => "claim_query_reasons"],
["excel_column" => "Insurer Request Sent date", "db_column" => "insurer_request_sent_date"],
["excel_column" => "Insurer Conf. Received date", "db_column" => "insurer_conf_received_date"],
["excel_column" => "Claim Reopen Date", "db_column" => "claim_reopen_date"],
["excel_column" => "First Query Raised date", "db_column" => "first_query_raised_date"],
["excel_column" => "First Query response date", "db_column" => "first_query_response_date"],
["excel_column" => "Last Query Raised date", "db_column" => "last_query_raised_date"],
["excel_column" => "Last Query response date", "db_column" => "last_query_response_date"],
["excel_column" => "Last Document Received date", "db_column" => "last_document_received_date"],
];
protected $mapping = [
["excel_column" => ["col_name" => "TPA Policy Number", "col_index" => 0], "db_column" => "tpa_policy_number"],
["excel_column" => ["col_name" => "Insurer Policy Number", "col_index" => 1], "db_column" => "insurer_policy_number"],
["excel_column" => ["col_name" => "Corporate Name", "col_index" => 2], "db_column" => "corporate_name"],
["excel_column" => ["col_name" => "Proposer Name", "col_index" => 3], "db_column" => "proposer_name"],
["excel_column" => ["col_name" => "Corporate Group ID", "col_index" => 4], "db_column" => "corporate_group_id"],
["excel_column" => ["col_name" => "Policy Start Date", "col_index" => 5], "db_column" => "policy_start_date"],
["excel_column" => ["col_name" => "Policy End date", "col_index" => 6], "db_column" => "policy_end_date"],
["excel_column" => ["col_name" => "Insurance Company Name", "col_index" => 7], "db_column" => "insurance_company_name"],
["excel_column" => ["col_name" => "Employee Number", "col_index" => 8], "db_column" => "employee_number"],
["excel_column" => ["col_name" => "Employee Location", "col_index" => 9], "db_column" => "employee_location"],
["excel_column" => ["col_name" => "Primary Policy Holder Name", "col_index" => 10], "db_column" => "primary_policy_holder_name"],
["excel_column" => ["col_name" => "Primary Policy Holder Card ID", "col_index" => 11], "db_column" => "primary_policy_holder_card_id"],
["excel_column" => ["col_name" => "Employee Grade", "col_index" => 12], "db_column" => "employee_grade"],
["excel_column" => ["col_name" => "Patient Health Card ID", "col_index" => 13], "db_column" => "patient_health_card_id"],
["excel_column" => ["col_name" => "Patient Name", "col_index" => 14], "db_column" => "patient_name"],
["excel_column" => ["col_name" => "Date of Birth", "col_index" => 15], "db_column" => "date_of_birth"],
["excel_column" => ["col_name" => "Age", "col_index" => 16], "db_column" => "age"],
["excel_column" => ["col_name" => "Gender", "col_index" => 17], "db_column" => "gender"],
["excel_column" => ["col_name" => "Relation", "col_index" => 18], "db_column" => "relation"],
["excel_column" => ["col_name" => "Sum Insured", "col_index" => 19], "db_column" => "sum_insured"],
["excel_column" => ["col_name" => "Balance Sum Insured", "col_index" => 20], "db_column" => "balance_sum_insured"],
["excel_column" => ["col_name" => "Top Up Sum Insured", "col_index" => 21], "db_column" => "top_up_sum_insured"],
["excel_column" => ["col_name" => "Enrollment status", "col_index" => 22], "db_column" => "enrollment_status"],
["excel_column" => ["col_name" => "Policy Inception date", "col_index" => 23], "db_column" => "policy_inception_date"],
["excel_column" => ["col_name" => "Policy Exit Date", "col_index" => 24], "db_column" => "policy_exit_date"],
["excel_column" => ["col_name" => "Insurer Risk ID", "col_index" => 25], "db_column" => "insurer_risk_id"],
["excel_column" => ["col_name" => "Claim Preauth Identifier", "col_index" => 26], "db_column" => "claim_preauth_identifier"],
["excel_column" => ["col_name" => "TPA Claim Number", "col_index" => 27], "db_column" => "tpa_claim_number"],
["excel_column" => ["col_name" => "Preauth Number", "col_index" => 28], "db_column" => "preauth_number"],
["excel_column" => ["col_name" => "Insurer Claim Number", "col_index" => 29], "db_column" => "insurer_claim_number"],
["excel_column" => ["col_name" => "Claim Received date", "col_index" => 30], "db_column" => "claim_received_date"],
["excel_column" => ["col_name" => "Date of Admission", "col_index" => 31], "db_column" => "date_of_admission"],
["excel_column" => ["col_name" => "Date of Discharge", "col_index" => 32], "db_column" => "date_of_discharge"],
["excel_column" => ["col_name" => "Hospital Name", "col_index" => 33], "db_column" => "hospital_name"],
["excel_column" => ["col_name" => "Hospital ID", "col_index" => 34], "db_column" => "hospital_id"],
["excel_column" => ["col_name" => "Hospital Address", "col_index" => 35], "db_column" => "hospital_address"],
["excel_column" => ["col_name" => "Hospital City", "col_index" => 36], "db_column" => "hospital_city"],
["excel_column" => ["col_name" => "Hospital State", "col_index" => 37], "db_column" => "hospital_state"],
["excel_column" => ["col_name" => "Hospital Pincode", "col_index" => 38], "db_column" => "hospital_pincode"],
["excel_column" => ["col_name" => "Hospital Network status", "col_index" => 39], "db_column" => "hospital_network_status"],
["excel_column" => ["col_name" => "PPN Hospital Status", "col_index" => 40], "db_column" => "ppn_hospital_status"],
["excel_column" => ["col_name" => "Room Category", "col_index" => 41], "db_column" => "room_category"],
["excel_column" => ["col_name" => "Room Days", "col_index" => 42], "db_column" => "room_days"],
["excel_column" => ["col_name" => "ICU Days", "col_index" => 43], "db_column" => "icu_days"],
["excel_column" => ["col_name" => "Medical Surgical Identifier", "col_index" => 44], "db_column" => "medical_surgical_identifier"],
["excel_column" => ["col_name" => "Treatment Type of AYUSH", "col_index" => 45], "db_column" => "treatment_type_of_ayush"],
["excel_column" => ["col_name" => "Package", "col_index" => 46], "db_column" => "package"],
["excel_column" => ["col_name" => "Diagnosis", "col_index" => 47], "db_column" => "diagnosis"],
["excel_column" => ["col_name" => "Illness Details", "col_index" => 48], "db_column" => "illness_details"],
["excel_column" => ["col_name" => "Ailment Grouping", "col_index" => 49], "db_column" => "ailment_grouping"],
["excel_column" => ["col_name" => "Primary ICD Code", "col_index" => 50], "db_column" => "primary_icd_code"],
["excel_column" => ["col_name" => "Secondary ICD Code", "col_index" => 51], "db_column" => "secondary_icd_code"],
["excel_column" => ["col_name" => "Procedure Code", "col_index" => 52], "db_column" => "procedure_code"],
["excel_column" => ["col_name" => "Procedure Description", "col_index" => 53], "db_column" => "procedure_description"],
["excel_column" => ["col_name" => "Procedure Grouping", "col_index" => 54], "db_column" => "procedure_grouping"],
["excel_column" => ["col_name" => "Claim Submission mode", "col_index" => 55], "db_column" => "claim_submission_mode"],
["excel_column" => ["col_name" => "Admission Category", "col_index" => 56], "db_column" => "admission_category"],
["excel_column" => ["col_name" => "Type of Claim", "col_index" => 57], "db_column" => "type_of_claim"],
["excel_column" => ["col_name" => "MainClaim_Prepost type", "col_index" => 58], "db_column" => "mainclaim_prepost_type"],
["excel_column" => ["col_name" => "Type of Hospitalization", "col_index" => 59], "db_column" => "type_of_hospitalization"],
["excel_column" => ["col_name" => "Death Status", "col_index" => 60], "db_column" => "death_status"],
["excel_column" => ["col_name" => "Treatement Given", "col_index" => 61], "db_column" => "treatment_given"],
["excel_column" => ["col_name" => "Claim Amount", "col_index" => 62], "db_column" => "claim_amount"],
["excel_column" => ["col_name" => "Total Billed Amount", "col_index" => 63], "db_column" => "total_billed_amount"],
["excel_column" => ["col_name" => "Claim Consultation Charges", "col_index" => 64], "db_column" => "claim_consultation_charges"],
["excel_column" => ["col_name" => "Claim Investigation Charges", "col_index" => 65], "db_column" => "claim_investigation_charges"],
["excel_column" => ["col_name" => "Claim Medicines", "col_index" => 66], "db_column" => "claim_medicines"],
["excel_column" => ["col_name" => "Claim Nursing", "col_index" => 67], "db_column" => "claim_nursing"],
["excel_column" => ["col_name" => "Claim Room Charges", "col_index" => 68], "db_column" => "claim_room_charges"],
["excel_column" => ["col_name" => "Claim Icu Charges", "col_index" => 69], "db_column" => "claim_icu_charges"],
["excel_column" => ["col_name" => "Claim Stay Charges", "col_index" => 70], "db_column" => "claim_stay_charges"],
["excel_column" => ["col_name" => "Claim Surgeon Charges", "col_index" => 71], "db_column" => "claim_surgeon_charges"],
["excel_column" => ["col_name" => "Claim Surgery Charges", "col_index" => 72], "db_column" => "claim_surgery_charges"],
["excel_column" => ["col_name" => "Claim Miscellaneous Charges", "col_index" => 73], "db_column" => "claim_miscellaneous_charges"],
["excel_column" => ["col_name" => "Claim Other Charges", "col_index" => 74], "db_column" => "claim_other_charges"],
["excel_column" => ["col_name" => "Approved Consultation Charges", "col_index" => 75], "db_column" => "approved_consultation_charges"],
["excel_column" => ["col_name" => "Approved Investigation Charges", "col_index" => 76], "db_column" => "approved_investigation_charges"],
["excel_column" => ["col_name" => "Approved Medicines", "col_index" => 77], "db_column" => "approved_medicines"],
["excel_column" => ["col_name" => "Approved Nursing", "col_index" => 78], "db_column" => "approved_nursing"],
["excel_column" => ["col_name" => "Approved Room Charges", "col_index" => 79], "db_column" => "approved_room_charges"],
["excel_column" => ["col_name" => "Approved Icu Charges", "col_index" => 80], "db_column" => "approved_icu_charges"],
["excel_column" => ["col_name" => "Approved Stay Charges", "col_index" => 81], "db_column" => "approved_stay_charges"],
["excel_column" => ["col_name" => "Approved Surgeon Charges", "col_index" => 82], "db_column" => "approved_surgeon_charges"],
["excel_column" => ["col_name" => "Approved Surgery Charges", "col_index" => 83], "db_column" => "approved_surgery_charges"],
["excel_column" => ["col_name" => "Approved Miscellaneous Charges", "col_index" => 84], "db_column" => "approved_miscellaneous_charges"],
["excel_column" => ["col_name" => "Approved Others Charges", "col_index" => 85], "db_column" => "approved_others_charges"],
["excel_column" => ["col_name" => "Total Disallowed Amount", "col_index" => 86], "db_column" => "total_disallowed_amount"],
["excel_column" => ["col_name" => "Copayment Amount", "col_index" => 87], "db_column" => "copayment_amount"],
["excel_column" => ["col_name" => "Deposit Amount", "col_index" => 88], "db_column" => "deposit_amount"],
["excel_column" => ["col_name" => "Exceeds Policy Limit", "col_index" => 89], "db_column" => "exceeds_policy_limit"],
["excel_column" => ["col_name" => "Copay Buffer", "col_index" => 90], "db_column" => "copay_buffer"],
["excel_column" => ["col_name" => "Hospital Discount Amount", "col_index" => 91], "db_column" => "hospital_discount_amount"],
["excel_column" => ["col_name" => "Deductible Amount", "col_index" => 92], "db_column" => "deductible_amount"],
["excel_column" => ["col_name" => "Approved Amount", "col_index" => 93], "db_column" => "approved_amount"],
["excel_column" => ["col_name" => "Total Incurred Amount", "col_index" => 94], "db_column" => "total_incurred_amount"],
["excel_column" => ["col_name" => "Total Buffer Approved", "col_index" => 95], "db_column" => "total_buffer_approved"],
["excel_column" => ["col_name" => "Total Buffer Utlilized", "col_index" => 96], "db_column" => "total_buffer_utilized"],
["excel_column" => ["col_name" => "TDS Amount", "col_index" => 97], "db_column" => "tds_amount"],
["excel_column" => ["col_name" => "Net Amount", "col_index" => 98], "db_column" => "net_amount"],
["excel_column" => ["col_name" => "Claim Decision date", "col_index" => 99], "db_column" => "claim_decision_date"],
["excel_column" => ["col_name" => "Payment Reference Number", "col_index" => 100], "db_column" => "payment_reference_number"],
["excel_column" => ["col_name" => "Payment Reference Date", "col_index" => 101], "db_column" => "payment_reference_date"],
["excel_column" => ["col_name" => "Claim Status", "col_index" => 102], "db_column" => "claim_status"],
["excel_column" => ["col_name" => "Deduction Remarks", "col_index" => 103], "db_column" => "deduction_remarks"],
["excel_column" => ["col_name" => "Rejection Reasons", "col_index" => 104], "db_column" => "rejection_reasons"],
["excel_column" => ["col_name" => "Claim Query Reasons", "col_index" => 105], "db_column" => "claim_query_reasons"],
["excel_column" => ["col_name" => "Insurer Request Sent date", "col_index" => 106], "db_column" => "insurer_request_sent_date"],
["excel_column" => ["col_name" => "Insurer Conf. Received date", "col_index" => 107], "db_column" => "insurer_conf_received_date"],
["excel_column" => ["col_name" => "Claim Reopen Date", "col_index" => 108], "db_column" => "claim_reopen_date"],
["excel_column" => ["col_name" => "First Query Raised date", "col_index" => 109], "db_column" => "first_query_raised_date"],
["excel_column" => ["col_name" => "First Query response date", "col_index" => 110], "db_column" => "first_query_response_date"],
["excel_column" => ["col_name" => "Last Query Raised date", "col_index" => 111], "db_column" => "last_query_raised_date"],
["excel_column" => ["col_name" => "Last Query response date", "col_index" => 112], "db_column" => "last_query_response_date"],
["excel_column" => ["col_name" => "Last Document Received date", "col_index" => 113], "db_column" => "last_document_received_date"],
];
protected $ticketMasterMapping = [
// Policy / Claim identifiers
'insurer_claim_number' => 'claim_number',
'tpa_claim_number' => 'tpa_claim_id',
// Employee / Insured details
'employee_number' => 'emp_code',
'primary_policy_holder_name' => 'emp_name',
'patient_name' => 'insured_name',
// Dates
'date_of_admission' => 'doa',
'date_of_discharge' => 'dod',
'date_of_birth' => 'dob',
'claim_received_date' => 'registration_date',
// Claim details
'claim_amount' => 'claim_amount',
'approved_amount' => 'approved_amount',
'sum_insured' => 'si_amt',
'claim_status' => 'tpa_claim_status',
// Hospital details
'hospital_name' => 'hospital_name',
'hospital_address' => 'hospital_address',
'hospital_city' => 'hospital_city',
'hospital_state' => 'hospital_state',
'hospital_pincode' => 'hospital_pin_code',
// Meta
'file_id' => 'file_id',
'type_of_claim' => 'tpa_claim_type',
'diagnosis' => 'tpa_ailments',
];
protected $statusMapping = [
'CL Paid with Settlement Letter' => 11,
'CL Rejected' => 8,
'CL Approved' => 9,
'AL Closed' => 12,
];
/**
* ABSTRACT FUNCTIONs
*/
public function bulkInsertTPATable(array $data): bool
{
if (empty($data)) {
return false;
}
$builder = $this->db->table('claims_dump_vidal');
return $builder->insertBatch($data);
}
public function importClaimMaster(array $data): bool
{
if (empty($data)) {
return false;
}
$ticketMasterModel = new TicketMasterModel();
return $ticketMasterModel->insertBatch($data);
}
public function updateTicketIdInTPATable(): bool
{
if (empty($data)) {
return false;
}
$builder = $this->db->table('claims_dump_vidal');
return $builder->updateBatch($data, 'id');
}
public function updateTicketMasterRejectedReasonInTPATable($data): bool
{
if (empty($data)) {
return false;
}
$builder = $this->db->table('claims_dump_vidal');
return $builder->updateBatch($data, 'id');
}
/**
* MAPPING FUNCTIONs
*/
public function mapTPAData(array $rows, $file_id): array
{
$ClientPolicyModel = new ClaimDumpFileModel();
$file_data = $ClientPolicyModel->where('id', $file_id)->first();
$mapped = [];
foreach ($rows as $row) {
$item = [];
foreach ($this->mapping as $map) {
$excelColumn = $map['excel_column']['col_name'];
$dbColumn = $map['db_column'];
$value = $row[$excelColumn] ?? null;
if ($this->isDateValue($value)) {
$value = $this->normalizeDate($value);
}
$item[$dbColumn] = $value;
}
$params = [
'date_of_admission' => change_date_format($item['date_of_admission'] ?? '') ?? null,
'employee_number' => $item['employee_number'] ?? null,
'claim_amount' => $item['claim_amount'] ?? null,
'primary_policy_holder_card_id' => $item['primary_policy_holder_card_id'] ?? null
];
$is_duplicate = $this->checkDuplicateTpaClaim('claims_dump_vidal', $params);
if ($is_duplicate) {
$item = [];
continue;
}
$item['file_id'] = $file_id ?? null;
$item['client_id'] = $file_data['client_id'] ?? null;
$item['client_policy_id'] = $file_data['client_policy_id'] ?? null;
$item['created_by'] = $file_data['created_by'] ?? null;
$mapped[] = $item;
}
return $mapped;
}
public function mapClaimMasterData($file_id): array
{
$ClientPolicyModel = new ClaimDumpFileModel();
$file_data = $ClientPolicyModel->where('id', $file_id)->first();
$tpaClaimDumpData = $this->getTpaClaimDumpData('claims_dump_vidal', ['file_id' => $file_id]);
if (empty($tpaClaimDumpData)) {
return ['status' => false, 'message' => "No data to insert in TICKET MASTER"];
}
$ClientPolicyModel = new ClientPolicyModel();
$client_policy_data = $ClientPolicyModel
->select("
client_policy.*,
(
SELECT id
FROM client_rm
WHERE is_active = 1
AND level = 3
AND client_id = client_policy.client_id
ORDER BY id ASC
LIMIT 1
) AS acm_id
")
->where('client_policy.id', $file_data['client_policy_id'])
->where('client_policy.is_active', 1)
->first();
try {
$mapped = [];
$rejecetd_reason = [];
foreach ($tpaClaimDumpData as $row) {
$params = [
'doa' => change_date_format($row['date_of_admission'] ?? '') ?? null,
'emp_code' => $row['employee_number'] ?? null,
'claim_amount' => $row['claim_amount'] ?? null,
'tpa_no' => $row['primary_policy_holder_card_id'] ?? null
];
$isduplicate = $this->checkDublicateTicketMasterClaim($params);
if ($isduplicate) {
$reason = "This claim already exists in our system.";
$rejecetd_reason[] = ["id" => $row['id'], "master_reject_reason" => $reason];
continue;
}
$item = [];
$item['client_id'] = $client_policy_data['client_id'] ?? null;
$item['client_policy_id'] = $client_policy_data['id'] ?? null;
$item['insurer_id'] = $client_policy_data['insurer_id'] ?? null;
$item['tpa_id'] = $client_policy_data['tpa_id'] ?? null;
$item['acm_id'] = $client_policy_data['acm_id'] ?? null;
$item['policy_no'] = $client_policy_data['policy_no'] ?? null;
$item['relationship'] = $this->convertRelation($row['relation'] ?? null, $row['gender'] ?? null);
$employee_data = $this->getEmployeeDetails($file_data['client_id'], $file_data['client_policy_id'], $row['employee_number'], $item['relationship']);
if (!empty($employee_data)) {
$item['emp_id'] = $employee_data['id'] ?? null;
$item['emp_name'] = $employee_data['name'] ?? null;
$item['emp_mail'] = $employee_data['email_corporate'] ?? null;
$item['emp_code'] = $employee_data['emp_code'] ?? null;
$item['emp_mobile'] = $employee_data['mobile'] ?? null;
$item['insured_emp_id'] = $employee_data['insured_emp_id'] ?? null;
$item['insured_name'] = $employee_data['insured_name'] ?? null;
} else {
$reason = 'This employee not exist in our system.';
$rejecetd_reason[] = ["id" => $row['id'], "master_reject_reason" => $reason];
continue;
}
foreach ($this->ticketMasterMapping as $tpaKey => $ticketMasterKey) {
$item[$ticketMasterKey] = array_key_exists($tpaKey, $row) ? $row[$tpaKey] : null;
}
// Meta fields
$item['claim_status_id'] = $statusMapping[$row['claim_status']] ?? 61;
$item['file_id'] = $file_id;
$item['claim_dump_ref_id'] = $row['id'];
$item['created_by'] = $file_data['created_by'] ?? null;
$item['claim_type'] = isset($row['mainclaim_prepost_type']) && !empty($row['mainclaim_prepost_type']) && strtolower($row['mainclaim_prepost_type']) == 'normal' ? 1 : 3;
$item['priority'] = 1;
$item['mode_of_intimation'] = 5;
$item['ticket_type_id'] = 1;
$mapped[] = $item;
}
return ['status' => true, 'mapped_array' => $mapped, 'rejected_reason_array' => $rejecetd_reason];
} 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,
];
return ['status' => false, "message" => $errorData['message'], 'error_data' => $errorData];
}
}
public function mapClaimMasterDataOld($file_id): array
{
$tpaClaimDumpData = $this->db
->table('claims_dump_vidal')
->where('is_active', 1)
->where('file_id', $file_id)
->where('ticket_id IS NULL')
->get()
->getResultArray();
if (empty($tpaClaimDumpData)) {
return [];
}
$ClientPolicyModel = new ClientPolicyModel();
$client_policy_data = $ClientPolicyModel->where('is_active', 1)->findAll();
$mapped = [];
$rejecetd_reason = [];
foreach ($tpaClaimDumpData as $row) {
$item = [];
if(isset($row['insurer_policy_number']) && !empty($row['insurer_policy_number'])){
$basic_claim_data = $this->getClientPolicyDataBypolicyNo($client_policy_data, $row['insurer_policy_number']);
if(empty($basic_claim_data)){
$reason = " This policy no ( " . $row['insurer_policy_number'] ." ) does not exist in our system";
$rejecetd_reason[$row['id']] = ["ticket_master_insert_reject_reason" => $reason];
continue;
}
$item['client_id'] = $basic_claim_data['client_id'] ?? null;
$item['client_policy_id'] = $basic_claim_data['id'] ?? null;
$item['insurer_id'] = $basic_claim_data['insurer_id'] ?? null;
$item['tpa_id'] = $basic_claim_data['tpa_id'] ?? null;
$item['acm_id'] = $basic_claim_data['acm_id'] ?? null;
$item['policy_no'] = $basic_claim_data['policy_no'] ?? null;
$item['relationship'] = $this->convertRelation($row['relation'] ?? null, $row['gender'] ?? null);
$employee_data = $this->getEmployeeDetails($item['client_id'], $item['client_policy_id'], $row['employee_number'], $item['relationship']);
if(!empty($employee_data)){
$item['emp_id'] = $employee_data['client_id'] ?? null;
$item['emp_name'] = $employee_data['id'] ?? null;
$item['emp_mail'] = $employee_data['insurer_id'] ?? null;
$item['emp_mobile'] = $employee_data['tpa_id'] ?? null;
if (!empty($employee_data['insured_emp_id'])) {
$item['insured_emp_id'] = $employee_data['insured_emp_id'] ?? null;
$item['insured_name'] = $employee_data['insured_name'] ?? null;
}else{
$reason = 'This Dependent employee not exist in our system.';
$rejecetd_reason[] = ["id" => $row['id'], "master_reject_reason" => $reason];
continue;
}
}else{
$reason = " This policy no ( " . $row['insurer_policy_number'] ." ) does not exist in our system";
$rejecetd_reason[$row['id']] = ["ticket_master_insert_reject_reason" => $reason];
continue;
}
}else{
$reason = " Policy Number is empty";
$rejecetd_reason[$row['id']] = ["ticket_master_insert_reject_reason" => $reason];
continue;
}
foreach ($this->ticketMasterMapping as $tpaKey => $ticketMasterKey) {
$item[$ticketMasterKey] = array_key_exists($tpaKey, $row)
? $row[$tpaKey]
: null;
}
$isduplicate = checkDuplicateClaim([
'doa' => change_date_format($item['doa'] ?? '') ?? null,
'emp_code' => $item['emp_code'] ?? null,
'claim_amount' => $item['claim_amount'] ?? null,
'policy_no' => $item['policy_no'] ?? null
]);
if($isduplicate){
$reason = " This claim ( " . $row['insurer_policy_number'] ." ) does not exist in our system";
$rejecetd_reason[$row['id']] = ["ticket_master_insert_reject_reason" => $reason];
continue;
}
// Meta fields
$item['file_id'] = $file_id;
$item['created_by'] = get_session_userid() ?? null;
$item['claim_type'] = isset($row['mainclaim_prepost_type']) && !empty($row['mainclaim_prepost_type']) && strtolower($row['mainclaim_prepost_type']) == 'normal' ? 1 : 3;
$mapped[] = $item;
}
return ['mapped_array' => $mapped, 'rejected_reason_array' => $rejecetd_reason];
}
/**
* HELPER FUNCTIONs
*/
public function isDateValue($value): bool
{
if (empty($value)) {
return false;
}
// Excel numeric date (e.g. 44927)
if (is_numeric($value) && $value > 30000) {
return true;
}
// Common date formats
return preg_match(
'/^\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}$|^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/',
(string) $value
) === 1;
}
public function normalizeDate($value): ?string
{
try {
// Excel numeric date
if (is_numeric($value)) {
return date('Y-m-d', \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($value));
}
// String date
return date('Y-m-d', strtotime(str_replace('/', '-', $value)));
} catch (\Throwable $e) {
return null;
}
}
public function looksLikeDate($value): bool
{
if (empty($value)) {
return false;
}
// Excel numeric date
if (is_numeric($value) && $value > 30000) {
return true;
}
return preg_match(
'/\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}|
\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}|
\d{1,2}\s?[A-Za-z]{3,}\s?\d{2,4}|
\d{8}/x',
(string) $value
) === 1;
}
public function convertRelation(string $relation, string $gender): ?string
{
if (empty($relation)) {
return null;
}
$relation = strtolower($relation);
$gender = strtolower($gender);
if ($relation == 'self') {
return $relation;
}
if ($relation == 'spouse') {
return $relation;
}
if ($relation == 'child' && $gender == 'male') {
return 'son';
}
if ($relation == 'child' && $gender == 'female') {
return 'daughter';
}
if ($relation == 'parents' && $gender == 'male') {
return 'father';
}
if ($relation == 'parents' && $gender == 'female') {
return 'mother';
}
if ($relation == 'parents-in-law' && $gender == 'male') {
return 'father-in-law';
}
if ($relation == 'parents-in-law' && $gender == 'female') {
return 'mother-in-law';
}
return null;
}
public function getClientPolicyDataBypolicyNo(array $client_policy_data, string $policy_number): array
{
$matched_data = [];
foreach ($client_policy_data as $key => $value) {
if(trim($value) == trim($policy_number)){
$matched_data = $value;
}
}
if(!empty($matched_data)){
$ClientRMModel = new ClientRMModel();
$acm_data = $ClientRMModel->where('is_active', 1)->where('level', 3)->where('client_id', $matched_data['client_id'])->orderBy('id', 'asc')->first();
if(!empty($acm_data)){
$matched_data['acm_id'] = $acm_data['id'] ?? null;
}
}
return $matched_data;
}
}

View File

@ -0,0 +1,37 @@
<?php
namespace App\Libraries;
use App\Libraries\TPAClaimsImportServices\BaseTpaClaimImportService;
use App\Libraries\TPAClaimsImportServices\VidalClaimImportService;
use App\Libraries\TPAClaimsImportServices\AbhiClaimImportService;
use App\Libraries\TPAClaimsImportServices\FhplClaimImportService;
use App\Libraries\TPAClaimsImportServices\MediAssistClaimImportService;
use App\Libraries\TPAClaimsImportServices\RcareClaimImportService;
use App\Libraries\TPAClaimsImportServices\IciciClaimImportService;
use InvalidArgumentException;
class TpaClaimsImportFactory
{
/**
* Resolve TPA Import Service based on TPA ID
*
* @param int $tpaId
* @return BaseTpaClaimImportService
*/
public static function make(int $tpaId): BaseTpaClaimImportService
{
return match ($tpaId) {
(int) env('VIDAL_PRIMARY_KEY_CONSTANT') => new VidalClaimImportService(),
(int) env('ABHI_PRIMARY_KEY_CONSTANT') => new AbhiClaimImportService(),
(int) env('MEDI_ASSIST_PRIMARY_KEY_CONSTANT') => new MediAssistClaimImportService(),
(int) env('FHPL_PRIMARY_KEY_CONSTANT') => new FhplClaimImportService(),
(int) env('R_CARE_PRIMARY_KEY_CONSTANT') => new RcareClaimImportService(),
(int) env('ICICI_PRIMARY_KEY_CONSTANT') => new IciciClaimImportService(),
default => throw new InvalidArgumentException(
"Unsupported TPA ID: {$tpaId}"
),
};
}
}

View File

@ -0,0 +1,179 @@
<?php
namespace App\Libraries;
use ZipArchive;
class ZipService
{
protected $s3Service;
public function __construct()
{
$this->s3Service = new S3Service();
}
/**
* Zips a local folder and uploads it to S3
*/
public function zipAndUploadS3(string $localFolderPath, string $s3Folder = '', string $zipName = ''): array
{
// dd($localFolderPath, $s3Folder, $zipName);
if (!is_dir($localFolderPath)) {
return ['status' => false, 'message' => 'Local directory does not exist'];
}
// 1. Prepare naming
$folderName = basename($localFolderPath);
$zipName = $zipName ?: $folderName . '_' . time() . '.zip';
$tempZipPath = FCPATH . 'tmp/' . $zipName;
// 2. Create the Local Zip
$zipResult = $this->createLocalZip($localFolderPath, $tempZipPath);
if (!$zipResult['status']) {
return $zipResult;
}
try {
// 3. Upload to S3
$uploadResult = $this->s3Service->upload($tempZipPath, $s3Folder, $zipName);
// dd($uploadResult);
// 4. Cleanup
if (file_exists($tempZipPath)) {
unlink($tempZipPath);
}
$get_presinged_url = $this->s3Service->getPresignedUrl($uploadResult['key'], 2,880);
// To delete the original temprory folder after zipping and uploading
// $this->deleteDirectory($localFolderPath);
return ['status' => true, 'data' => $uploadResult, 'presigned_url' => $get_presinged_url];
} catch (\Exception $e) {
log_message('error', 'Zip/Upload Error: ' . $e->getMessage());
return ['status' => false, 'message' => $e->getMessage()];
}
}
/**
* Zips a local folder using native ZipArchive
*/
public function createLocalZip(string $localFolderPath, string $destinationPath): array
{
// 1. Validate Source Directory
if (!is_dir($localFolderPath)) {
return ['status' => false, 'message' => 'Source directory does not exist'];
}
// 2. Check if folder is empty (ignoring hidden files)
$filesInFolder = array_diff(scandir($localFolderPath), array('.', '..'));
if (empty($filesInFolder)) {
return ['status' => false, 'message' => 'No records found to compress'];
}
// 3. Ensure the destination directory exists and is writable
$destDir = dirname($destinationPath);
if (!is_dir($destDir)) {
mkdir($destDir, 0777, true);
}
$zip = new ZipArchive();
// 4. Open the zip file
$openZip = $zip->open($destinationPath, ZipArchive::CREATE | ZipArchive::OVERWRITE);
if ($openZip !== true) {
return ['status' => false, 'message' => "Could not open Zip. Error code: " . $openZip];
}
try {
$files = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($localFolderPath, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::LEAVES_ONLY
);
$fileCount = 0;
$sourcePath = realpath($localFolderPath);
foreach ($files as $file) {
if (!$file->isDir()) {
$filePath = $file->getRealPath();
// Calculate relative path correctly
$relativePath = ltrim(substr($filePath, strlen($sourcePath)), DIRECTORY_SEPARATOR);
// Add to zip
if ($zip->addFile($filePath, $relativePath)) {
$fileCount++;
}
}
}
// 5. Finalize
if ($fileCount > 0) {
if (!$zip->close()) {
return ['status' => false, 'message' => 'Failed to write ZIP file to disk (Check permissions/space)'];
}
} else {
$zip->close();
return ['status' => false, 'message' => 'No files were added to the archive'];
}
return [
'status' => true,
'path' => $destinationPath,
'count' => $fileCount,
'message' => 'Zip created successfully'
];
} catch (\Exception $e) {
// Only attempt to close if the zip object was successfully opened
if (isset($zip->status) && $zip->status !== ZipArchive::ER_OK) {
@$zip->close();
}
log_message('error', 'Local Zip Error: ' . $e->getMessage());
return ['status' => false, 'message' => 'from catch Exception: ' . $e->getMessage()];
}
}
private function deleteDirectory($dir)
{
if (!file_exists($dir)) {
return true;
}
if (!is_dir($dir)) {
// Use @ to suppress warnings if the file is already gone or locked
// return @unlink($dir);
return unlink($dir);
}
// scandir can return false if the directory isn't readable
$items = scandir($dir);
if ($items === false) {
return false;
}
foreach ($items as $item) {
if ($item == '.' || $item == '..') {
continue;
}
// Recursively call the function
if (!$this->deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
// If a child cannot be deleted, attempt to change its permissions and try once more
@chmod($dir . DIRECTORY_SEPARATOR . $item, 0777);
if (!$this->deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
return false;
}
}
}
// Finally, remove the empty directory
return @rmdir($dir);
}
}

View File

@ -57,6 +57,64 @@ class BdsPlacementModel extends Model
public function getClientInstallmentDetails() public function getClientInstallmentDetails()
{
// 1. Fetch common data ONCE (Heads, Admins, Business Team)
// This saves hundreds of redundant queries
$heads = $this->db->table('user_profiles')
->select('email')->where(['role' => 5, 'is_active' => 1])
->get()->getResultArray();
$admins = $this->db->table('user_profiles')
->select('email')->where(['role' => 1, 'is_active' => 1])
->get()->getResultArray();
$businessTeam = $this->db->table("user_teams ut")
->select("up.email")
->join('user_profiles up', 'up.id = ut.user_id AND up.is_active = 1')
->where(["ut.team_id" => 7, "ut.is_active" => 1])
->get()->getResultArray();
// 2. Main Query
$builder = $this->db->table("bds_installment_payment_details bipd")
->select("bipd.*, ct.client_name, ct.short_name, cb.branch_name, leads.salse_person_id, cp.policy_no")
->join("policy_transaction pt", "pt.id = bipd.pt_id")
->join("clients ct", "ct.id = pt.client_id")
->join("client_branch cb", "cb.id = pt.client_branch_id")
->join("leads", "leads.id = bipd.lead_id")
->join("client_policy cp", "cp.id = pt.client_policy_id")
->where("bipd.is_active", 1)
->where("bipd.payment_date", date('Y-m-d', strtotime('+15 days')));
$data = $builder->get()->getResultArray();
// Loop through to extract sales person details
// 3. Simple Loop for Sales Person (Since it relies on a JSON ID)
foreach ($data as &$row) {
$sales_person_ids = json_decode($row['salse_person_id'], true);
$sales_person_id = $sales_person_ids[0] ?? null;
if ($sales_person_id) {
$user = $this->db->table('user_profiles')
->select('email') // or whatever field
->where('id', (int)$sales_person_id) // Cast to int for extra safety
->get()
->getRowArray();
$row['sales_person'] = $user['email'] ?? 'N/A';
} else {
$row['sales_person'] = 'Not Assigned';
}
// Assign the pre-fetched data
$row['heads'] = $heads;
$row['admins'] = $admins;
$row['buisness_team'] = $businessTeam;
}
return $data;
}
public function getClientInstallmentDetails_olds()
{ {
$builder = $this->db->table("bds_installment_payment_details bipd") $builder = $this->db->table("bds_installment_payment_details bipd")

View File

@ -10,6 +10,9 @@ class ClaimDumpFileModel extends Model
protected $primaryKey = 'id'; protected $primaryKey = 'id';
protected $allowedFields = [ protected $allowedFields = [
"id", "id",
"client_id",
"client_policy_id",
"tpa_id",
"file_name", "file_name",
"status", "status",
"reason", "reason",

View File

@ -0,0 +1,57 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class ClaimMisFileModel extends Model
{
protected $table = 'claims_mis_files';
protected $primaryKey = 'id';
protected $allowedFields = [
'id',
'client_id',
'tpa_id',
'client_policy_id',
'from_date',
'to_date',
'file_name',
'created_by',
'updated_by',
'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

@ -0,0 +1,141 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class ClaimsDumpFhplModel extends Model
{
protected $table = 'claims_dump_fhpl';
protected $primaryKey = 'id';
protected $allowedFields = [
'id',
'client_id',
'client_policy_id',
'ticket_id',
'file_id',
'created_by',
'updated_by',
'is_active',
'request_type',
'intimation_id',
'intimation_date',
'claim_id',
'sl_no',
'uhid_no',
'member_name',
'main_member_uhid_no',
'main_member_name',
'gender',
'dob',
'years',
'relationship',
'employee_id',
'mobile',
'email',
'policy_no',
'policy_start_date',
'policy_commencing_date',
'policy_expiry_date',
'organisation_name',
'claim_received_date',
'admission_date',
'discharge_date',
'diagnosis',
'service_type',
'service_sub_type',
'icd_code_first_level',
'icd_code_second_level',
'icd_code_third_level',
'claim_type',
'provider_name',
'provider_address',
'provider_place',
'provider_state',
'provider_pincode',
'provider_type',
'provider_identification',
'coverage_amount',
'claim_amount',
'billed_amount',
'disallowed_amount',
'dis_allowance_reason_1',
'dis_allowance_reason_2',
'settled_amount',
'incurred_amount',
'discount_amount',
'tds_amount',
'net_amount_paid',
'co_payment',
'current_claim_status',
'balance_sum_insured',
'cheque_no',
'cheque_date',
'claim_passed_date',
'settled_date',
'pending_remarks',
'ir_investigation',
'ir_date',
'ir_retrieval_date',
'first_reminder',
'second_reminder',
'rejection_remarks',
'payee_name',
'treatment_type',
'room_days',
'icu_days',
'total_stay',
'room_rent_claimed',
'icu_claimed',
'icu_related',
'nursing_claimed',
'nursing_charges',
'room_rent_related',
'professional_charges',
'drugs_medication_consumables',
'investigations_procedures_ip',
'domicillary_hospitalization',
'maternity',
'day_care',
'operation_theatre',
'organ_donor',
'ancillary_services',
'dental',
'out_patient_coverage',
'personal_accident',
'critical_illness',
'health_check_up',
'spectacles_contact_lenses_hearing_aid',
'notes',
'buffer_amount',
'tertiary_amount',
'insurance_name',
'ro_name',
'class_of_accommodation',
'claim_created_datetime',
'insurer_claim_id',
'gipsa',
'date_of_joining',
'gipsa_hospital',
'package',
'is_nidb',
'nidb_removed_date',
'investigation_date',
'investigation_retrieval_date',
'reopened_date',
'refer_to_insurer_date',
'received_date_from_insurer',
'rejection_category',
'refer_to_insurer_reasons',
'is_vip',
'main_claim_status',
'main_claim_type',
'icd_third_level_code',
'benefit_plan_name',
'zone',
'grade',
'last_modified_date',
'temp_mou'
];
}

View File

@ -30,6 +30,7 @@ class ClientDepositModel extends Model
"cd_ac_pk", "cd_ac_pk",
"record_date", "record_date",
"policy_transaction_id", "policy_transaction_id",
"file_id",
]; ];

View File

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

View File

@ -118,7 +118,16 @@ class ClientPolicyModel extends Model
return $this->db->table('client_policy') return $this->db->table('client_policy')
->select('client_policy.*') ->select('
client_policy.*,
CASE
WHEN client_policy.policy_entry_from = 3
AND client_policy.cd_ac_pk IS NULL
THEN leads.cd_amount
ELSE NULL
END AS lead_cd_amount
', false)
->select('insurers.name as insurer_name, insurers.short_name as insurer_short') ->select('insurers.name as insurer_name, insurers.short_name as insurer_short')
->select('tpa.name as tpa_name, tpa.short_name as tpa_short') ->select('tpa.name as tpa_name, tpa.short_name as tpa_short')
->select('policy_type.policy_type as policy_type_name') ->select('policy_type.policy_type as policy_type_name')
@ -132,6 +141,7 @@ class ClientPolicyModel extends Model
->join('tpa_branch', 'client_policy.tpa_branch_id = tpa_branch.id', 'left') ->join('tpa_branch', 'client_policy.tpa_branch_id = tpa_branch.id', 'left')
->join('policy_type', 'policy_type.id = client_policy.policy_type_id') ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
->join('client_branch', 'client_branch.id = client_policy.client_branch_id') ->join('client_branch', 'client_branch.id = client_policy.client_branch_id')
->join('leads', 'client_policy.is_from_lead = leads.id', 'left')
->where('client_policy.client_id', $client_id) ->where('client_policy.client_id', $client_id)
// ->where('client_policy.policy_status', 1) // ->where('client_policy.policy_status', 1)
->where('client_policy.is_active', 1) ->where('client_policy.is_active', 1)
@ -183,9 +193,14 @@ class ClientPolicyModel extends Model
->join('clients', 'clients.id = client_policy.client_id') ->join('clients', 'clients.id = client_policy.client_id')
->join('insurers', 'insurers.id = client_policy.insurer_id') ->join('insurers', 'insurers.id = client_policy.insurer_id')
->join('insurer_branch', 'client_policy.insurer_branch_id = insurer_branch.id', 'left') ->join('insurer_branch', 'client_policy.insurer_branch_id = insurer_branch.id', 'left')
->join('cd_master', 'cd_master.insurer_id = insurers.id AND cd_master.client_id = client_policy.client_id') ->join('cd_master', 'cd_master.insurer_id = insurers.id AND cd_master.client_id = client_policy.client_id');
->where('client_policy.client_id', $id) // ->where('client_policy.client_id', $id)
->where('cd_master.id = client_policy.cd_ac_pk') if (is_string($id) && preg_match('/^[a-f0-9]{32}$/i', $id)) {
$builder->where('MD5(client_policy.client_id)', $id);
} else {
$builder->where('client_policy.client_id', $id);
}
$builder->where('cd_master.id = client_policy.cd_ac_pk')
->where('cd_master.is_active', 1) ->where('cd_master.is_active', 1)
->groupBy('client_policy.client_id') ->groupBy('client_policy.client_id')
->groupBy('client_policy.insurer_id') ->groupBy('client_policy.insurer_id')
@ -248,13 +263,32 @@ class ClientPolicyModel extends Model
} }
public function getClientById($id) // public function getClientById($id)
// {
// $query = $this->db->table('clients')->getWhere(['id' => $id]);
// // Debug statement
// return $query->getRow();
// }
public function getClientById($client_id)
{ {
$query = $this->db->table('clients')->getWhere(['id' => $id]); if (empty($client_id)) {
// Debug statement return null;
return $query->getRow();
} }
$builder = $this->db->table('clients');
// MD5 vs normal ID check
if (is_string($client_id) && preg_match('/^[a-f0-9]{32}$/i', $client_id)) {
$builder->where('MD5(id)', $client_id);
} else {
$builder->where('id', $client_id);
}
return $builder->get()->getRow();
}
public function getDepositData($clientId, $insurerId, $cd_ac_pk = null, $subTypeOptions = null) public function getDepositData($clientId, $insurerId, $cd_ac_pk = null, $subTypeOptions = null)
{ {
@ -269,6 +303,8 @@ class ClientPolicyModel extends Model
$caseSql = ""; $caseSql = "";
} }
$url = base_url('downloadCdSplitUpFile?id=');
// Fetch the deposit data based on client and insurer IDs // Fetch the deposit data based on client and insurer IDs
$query = $this->db->table('cash_deposit') $query = $this->db->table('cash_deposit')
->select('cash_deposit.*') ->select('cash_deposit.*')
@ -278,6 +314,12 @@ class ClientPolicyModel extends Model
// ->select('policies.name as policy_name') // ->select('policies.name as policy_name')
->select('policy_type.policy_type') ->select('policy_type.policy_type')
->select('user_profiles.first_name as username') ->select('user_profiles.first_name as username')
->select("CASE
WHEN cash_deposit.file_id IS NOT NULL AND cash_deposit.file_id != ''
THEN CONCAT(" . $this->db->escape($url) . ", MD5(cash_deposit.file_id))
ELSE NULL
END AS split_up_url",
false)
->select($caseSql) ->select($caseSql)
->join('user_profiles', 'user_profiles.id = cash_deposit.created_by', 'left') ->join('user_profiles', 'user_profiles.id = cash_deposit.created_by', 'left')
->join('insurers', 'insurers.id = cash_deposit.insurer_id', 'left') ->join('insurers', 'insurers.id = cash_deposit.insurer_id', 'left')
@ -285,9 +327,16 @@ class ClientPolicyModel extends Model
->join('client_policy', 'client_policy.id = cash_deposit.client_policy_id', 'left') ->join('client_policy', 'client_policy.id = cash_deposit.client_policy_id', 'left')
->join('cd_master', 'cd_master.id = cash_deposit.cd_ac_pk', 'left') ->join('cd_master', 'cd_master.id = cash_deposit.cd_ac_pk', 'left')
// ->join('policies', 'policies.id = client_policy.policy_id', 'left') // ->join('policies', 'policies.id = client_policy.policy_id', 'left')
->join('policy_type', 'policy_type.id = client_policy.policy_type_id', 'left') ->join('policy_type', 'policy_type.id = client_policy.policy_type_id', 'left');
->where('cash_deposit.client_id', $clientId) // ->where('cash_deposit.client_id', $clientId)
->where('cash_deposit.insurer_id', $insurerId) if (!empty($clientId)) {
if (is_string($clientId) && preg_match('/^[a-f0-9]{32}$/i', $clientId)) {
$query->where('MD5(cash_deposit.client_id)', $clientId);
} else {
$query->where('cash_deposit.client_id', $clientId);
}
}
$query->where('cash_deposit.insurer_id', $insurerId)
->where('cash_deposit.is_active', 1) ->where('cash_deposit.is_active', 1)
->where('cd_master.is_active', 1); ->where('cd_master.is_active', 1);
// ->where('cash_deposit.cd_ac_pk = cd_master.id') // ->where('cash_deposit.cd_ac_pk = cd_master.id')
@ -296,16 +345,62 @@ class ClientPolicyModel extends Model
} }
$query->orderBy('cash_deposit.id', 'DESC'); $query->orderBy('cash_deposit.id', 'DESC');
return $query->get()->getResult(); $data = $query->get()->getResult();
return $data;
} }
// public function getDepositSummary($clientId, $insurerId, $cd_ac_pk)
// {
// $subQuery = $this->db->table('cash_deposit')
// ->select('balance')
// ->where('client_id', $clientId)
// ->where('insurer_id', $insurerId)
// ->where('cd_ac_pk', $cd_ac_pk)
// ->where('is_active', 1)
// ->orderBy('id', 'DESC')
// ->limit(1)
// ->getCompiledSelect();
// // Fetch the sum of credit and debit transactions and calculate the balance
// $data = $this->db->table('cash_deposit')
// ->select("($subQuery) AS balance", false)
// ->select('SUM(CASE WHEN transaction_type = "Credit" THEN amount ELSE 0 END) AS total_credit')
// ->select('SUM(CASE WHEN transaction_type = "Debit" THEN amount ELSE 0 END) AS total_withdraw')
// // ->select('SUM(CASE WHEN transaction_type = "Credit" THEN amount ELSE -amount END) AS balance')
// ->select('SUM(CASE WHEN sub_type = 3 THEN amount ELSE 0 END) AS total_refund')
// ->where('client_id', $clientId)
// ->where('insurer_id', $insurerId)
// ->where('cd_ac_pk', $cd_ac_pk)
// ->where('cash_deposit.is_active', 1)
// ->get()
// ->getRow();
// // dd($this->db->getLastQuery());
// return $data;
// }
public function getDepositSummary($clientId, $insurerId, $cd_ac_pk) public function getDepositSummary($clientId, $insurerId, $cd_ac_pk)
{ {
if (empty($clientId)) {
return null;
}
// Build SAFE client condition (NO BINDS!)
if (is_string($clientId) && preg_match('/^[a-f0-9]{32}$/i', $clientId)) {
$clientCondition = 'MD5(client_id) = ' . $this->db->escape($clientId);
} else {
$clientCondition = 'client_id = ' . $this->db->escape($clientId);
}
/* -------------------------------------------------
Subquery: latest balance
------------------------------------------------- */
$subQuery = $this->db->table('cash_deposit') $subQuery = $this->db->table('cash_deposit')
->select('balance') ->select('balance')
->where('client_id', $clientId) ->where($clientCondition, null, false)
->where('insurer_id', $insurerId) ->where('insurer_id', $insurerId)
->where('cd_ac_pk', $cd_ac_pk) ->where('cd_ac_pk', $cd_ac_pk)
->where('is_active', 1) ->where('is_active', 1)
@ -313,14 +408,15 @@ class ClientPolicyModel extends Model
->limit(1) ->limit(1)
->getCompiledSelect(); ->getCompiledSelect();
// Fetch the sum of credit and debit transactions and calculate the balance /* -------------------------------------------------
Main query: totals
------------------------------------------------- */
$data = $this->db->table('cash_deposit') $data = $this->db->table('cash_deposit')
->select("($subQuery) AS balance", false) ->select("($subQuery) AS balance", false)
->select('SUM(CASE WHEN transaction_type = "Credit" THEN amount ELSE 0 END) AS total_credit') ->select('SUM(CASE WHEN transaction_type = "Credit" THEN amount ELSE 0 END) AS total_credit')
->select('SUM(CASE WHEN transaction_type = "Debit" THEN amount ELSE 0 END) AS total_withdraw') ->select('SUM(CASE WHEN transaction_type = "Debit" THEN amount ELSE 0 END) AS total_withdraw')
// ->select('SUM(CASE WHEN transaction_type = "Credit" THEN amount ELSE -amount END) AS balance')
->select('SUM(CASE WHEN sub_type = 3 THEN amount ELSE 0 END) AS total_refund') ->select('SUM(CASE WHEN sub_type = 3 THEN amount ELSE 0 END) AS total_refund')
->where('client_id', $clientId) ->where($clientCondition, null, false)
->where('insurer_id', $insurerId) ->where('insurer_id', $insurerId)
->where('cd_ac_pk', $cd_ac_pk) ->where('cd_ac_pk', $cd_ac_pk)
->where('cash_deposit.is_active', 1) ->where('cash_deposit.is_active', 1)
@ -330,6 +426,8 @@ class ClientPolicyModel extends Model
// dd($this->db->getLastQuery()); // dd($this->db->getLastQuery());
return $data; return $data;
} }
// Inside your clientPolicyModel // Inside your clientPolicyModel
// Inside your clientPolicyModel // Inside your clientPolicyModel
// public function getDepositDataWithBalance($clientId, $insurerId) // public function getDepositDataWithBalance($clientId, $insurerId)
@ -402,6 +500,35 @@ class ClientPolicyModel extends Model
// ORDER BY cd.id DESC // ORDER BY cd.id DESC
// "; // ";
// $sql = "
// SELECT cd.insurer_id, cd.cd_ac_pk, cd.balance
// FROM cash_deposit cd
// JOIN cd_master cdm ON cdm.id = cd.cd_ac_pk
// JOIN (
// SELECT MAX(id) AS max_id
// FROM cash_deposit
// WHERE is_active = 1 AND client_id = :id:
// GROUP BY insurer_id, cd_ac_pk
// ) latest ON latest.max_id = cd.id
// JOIN insurers on cd.insurer_id = insurers.id
// WHERE cd.is_active = 1 AND cd.client_id = :id: AND cdm.is_active = 1
// ORDER BY cd.insurer_id;
// ";
// $binds = ['id'=>(int)$id];
// return $this->db->query($sql,$binds)->getResult();
$whereClient = 'cd.client_id = :id:';
$subWhereClient = 'client_id = :id:';
$binds = ['id' => $id];
// 🔐 MD5 handling
if (is_string($id) && preg_match('/^[a-f0-9]{32}$/i', $id)) {
$whereClient = 'MD5(cd.client_id) = :id:';
$subWhereClient = 'MD5(client_id) = :id:';
}
$sql = " $sql = "
SELECT cd.insurer_id, cd.cd_ac_pk, cd.balance SELECT cd.insurer_id, cd.cd_ac_pk, cd.balance
FROM cash_deposit cd FROM cash_deposit cd
@ -409,15 +536,17 @@ class ClientPolicyModel extends Model
JOIN ( JOIN (
SELECT MAX(id) AS max_id SELECT MAX(id) AS max_id
FROM cash_deposit FROM cash_deposit
WHERE is_active = 1 AND client_id = $id WHERE is_active = 1 AND {$subWhereClient}
GROUP BY insurer_id, cd_ac_pk GROUP BY insurer_id, cd_ac_pk
) latest ON latest.max_id = cd.id ) latest ON latest.max_id = cd.id
JOIN insurers on cd.insurer_id = insurers.id JOIN insurers ON cd.insurer_id = insurers.id
WHERE cd.is_active = 1 AND cd.client_id = $id AND cdm.is_active = 1 WHERE cd.is_active = 1
ORDER BY cd.insurer_id; AND {$whereClient}
AND cdm.is_active = 1
ORDER BY cd.insurer_id
"; ";
return $this->db->query($sql)->getResult(); return $this->db->query($sql, $binds)->getResult();
} }
@ -464,10 +593,12 @@ class ClientPolicyModel extends Model
FROM client_policy FROM client_policy
JOIN policies ON policies.id = client_policy.policy_id JOIN policies ON policies.id = client_policy.policy_id
JOIN policy_type ON policy_type.id = policies.policy_type_id JOIN policy_type ON policy_type.id = policies.policy_type_id
WHERE policy_type.policy_type = '{$type}' WHERE policy_type.policy_type = :type:
AND client_policy.client_id = {$client_id}"; AND client_policy.client_id = :client_id:";
$result = $this->db->query($query)->getResult(); $binds = ['type' =>$type,'client_id'=>(int)$client_id];
$result = $this->db->query($query,$binds)->getResult();
return $result; return $result;
} }

View File

@ -94,10 +94,11 @@ class EmpEndorsementModel extends Model
FROM emp_endorsement FROM emp_endorsement
JOIN employee_polices ON employee_polices.id = emp_endorsement.pk JOIN employee_polices ON employee_polices.id = emp_endorsement.pk
JOIN client_policy ON client_policy.id = employee_polices.client_policy_id JOIN client_policy ON client_policy.id = employee_polices.client_policy_id
WHERE group_key = '{$group_key}' WHERE group_key = :group_key:
"; ";
$results = $this->db->query($query)->getResult(); $binds['group_key'] = $group_key;
$results = $this->db->query($query,$binds)->getResult();
return $results; return $results;
} }
@ -191,10 +192,10 @@ class EmpEndorsementModel extends Model
e1.field_name = 'status' e1.field_name = 'status'
) ee ON aa.emp_code = ee.emp_code ) ee ON aa.emp_code = ee.emp_code
) AS deletiondata ON a.emp_code = deletiondata.emp_code ) AS deletiondata ON a.emp_code = deletiondata.emp_code
WHERE group_key = '{$group_key}'; WHERE group_key = :group_key: ;
"; ";
$binds['group_key'] = $group_key;
$results = $this->db->query($query)->getResult(); $results = $this->db->query($query,$binds)->getResult();
return $results; return $results;
} }

View File

@ -223,12 +223,13 @@ class EmployeeModel extends Model
emp_code, emp_code,
COUNT(*) AS family_member_count, COUNT(*) AS family_member_count,
MAX(TIMESTAMPDIFF(YEAR, dob, CURDATE())) AS max_age MAX(TIMESTAMPDIFF(YEAR, dob, CURDATE())) AS max_age
FROM employees where emp_code = '{$emp_code}' FROM employees where emp_code = :emp_code:
GROUP BY emp_code GROUP BY emp_code
) AS family_stats ) AS family_stats
ORDER BY family_member_count DESC, max_age DESC ORDER BY family_member_count DESC, max_age DESC
LIMIT 1;"; LIMIT 1;";
$results = $this->db->query($query)->getResultArray(); $binds['emp_code'] = $emp_code;
$results = $this->db->query($query,$binds)->getResultArray();
return $results; return $results;
} }

View File

@ -222,7 +222,7 @@ class EmployeePolicyModel extends Model
// return $res; // return $res;
// } // remarks do not remove // } // remarks do not remove
public function getEmployeePolicy($client_id = 0, $policy_id = 0, $status = [], $branch_id = 0, $emp_code = "", $emp_name = "") public function getEmployeePolicy($client_id = 0, $policy_id = 0, $status = [], $branch_id = 0, $emp_code = "", $emp_name = "", $status_type = '')
{ {
// dd($status); // dd($status);
$ecard_download_link = " $ecard_download_link = "
@ -280,6 +280,14 @@ class EmployeePolicyModel extends Model
'cp.policy_no', 'cp.policy_no',
'cp.policy_type_id', 'cp.policy_type_id',
'cp.is_addon', 'cp.is_addon',
'(
select id from employees
where emp_code = emp.emp_code
and client_id = emp.client_id
and lower(relationship) = "self"
and is_active = 1
limit 1
) as self_employee_id',
$ecard_download_link $ecard_download_link
]) ])
->join('employees emp', 'employee_polices.employee_id = emp.id') ->join('employees emp', 'employee_polices.employee_id = emp.id')
@ -295,7 +303,10 @@ class EmployeePolicyModel extends Model
->orderBy('emp.emp_code', 'ASC') ->orderBy('emp.emp_code', 'ASC')
->orderBy('employee_polices.employee_id', 'ASC'); ->orderBy('employee_polices.employee_id', 'ASC');
// Conditionally add where clauses // Conditionally add where clauses
if ($client_id != 0 && !empty($client_id)) { if (is_string($client_id) && preg_match('/^[a-f0-9]{32}$/i', $client_id)) {
// MD5 hash → compare using md5()
$result->where('md5(emp.client_id)', $client_id);
}else if ($client_id != 0 && !empty($client_id)) {
$result->where('emp.client_id', $client_id); $result->where('emp.client_id', $client_id);
} }
if ($branch_id != 0 && !empty($branch_id)) { if ($branch_id != 0 && !empty($branch_id)) {
@ -345,8 +356,13 @@ class EmployeePolicyModel extends Model
// Always check these conditions // Always check these conditions
$result $result
->where('employee_polices.is_active', 1) ->where('employee_polices.is_active', 1)
->where('emp.is_active', 1) ->where('emp.is_active', 1);
->where('employee_polices.status !=', 'inactive');
if($status_type == 'inactive'){
$result->whereIn('employee_polices.status', ['active', 'inactive']);
}else{
$result->where('employee_polices.status !=', 'inactive');
}
$res = $result->findAll(); $res = $result->findAll();
@ -388,8 +404,8 @@ class EmployeePolicyModel extends Model
->where('is_active',1) ->where('is_active',1)
->find(); ->find();
} }
//-------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------
public function getInceptionEmployeeDataForExportExcel($ref_data, $return_type = 0) public function getInceptionEmployeeDataForExportExcel($ref_data, $return_type = 0)
{ {
@ -430,7 +446,7 @@ class EmployeePolicyModel extends Model
employees.gender AS emp_gender, employees.gender AS emp_gender,
employees.relationship AS emp_relationship, employees.relationship AS emp_relationship,
employees.relationship_code AS emp_relationship_code, employees.relationship_code AS emp_relationship_code,
'$datas' as event_type_data, :datas: as event_type_data,
employees.change_event AS change_event, employees.change_event AS change_event,
@ -483,24 +499,37 @@ class EmployeePolicyModel extends Model
batch_files.batch_code as bf batch_files.batch_code as bf
FROM batch_files FROM batch_files
LEFT JOIN batch_list ON batch_files.batch_code = batch_list.batch_code LEFT JOIN batch_list ON batch_files.batch_code = batch_list.batch_code
WHERE batch_files.event_type = '{$event}' WHERE batch_files.event_type = :event:
AND batch_files.actions = 'export' AND batch_files.actions = 'export'
AND batch_files.insurer_or_tpa = '{$insurer_or_tpa}' AND batch_files.insurer_or_tpa = :insurer_or_tpa:
AND batch_files.client_policy_id = '{$client_policy_id}' AND batch_files.client_policy_id = :client_policy_id:
AND batch_files.client_policy_id = '{$client_id}' AND batch_files.client_policy_id = :client_id:
) as batch_data ON employee_polices.id = batch_data.emp_policy_id ) as batch_data ON employee_polices.id = batch_data.emp_policy_id
WHERE employee_polices.client_policy_id = '{$client_policy_id}' WHERE employee_polices.client_policy_id = :client_policy_id:
AND (employee_polices.{$id} IS NULL OR employee_polices.{$id} = '') AND employees.client_branch_id = :client_branch_id:
AND employees.client_branch_id = '{$client_branch_id}'
AND employee_polices.is_active = 1 AND employee_polices.is_active = 1
AND employee_polices.status = 'active' AND employee_polices.status = 'active'
AND employees.is_active = 1 AND employees.is_active = 1
AND employees.emp_status = 'active' AND employees.emp_status = 'active'
"; ";
if($insurer_or_tpa == 'insurer'){
$sql .= "AND (employee_polices.uhid IS NULL OR employee_polices.uhid <> '')";
}
if($insurer_or_tpa == 'tpa'){
$sql .= "AND (employee_polices.tpa_id IS NULL OR employee_polices.tpa_id <> '')";
}
$binds = ["datas" => $datas,"event" => $event
,"insurer_or_tpa" => $insurer_or_tpa
,"client_policy_id" => $client_policy_id
,"client_branch_id" => $client_branch_id
,"client_id" => $client_id,"id" => $id];
// Get the result set // Get the result set
$query = $this->db->query($sql); $query = $this->db->query($sql,$binds);
if($return_type == 1){ if($return_type == 1){
$results = $query->getResultArray(); $results = $query->getResultArray();
@ -573,9 +602,9 @@ class EmployeePolicyModel extends Model
employees ON employees.id = emp_endorsement.pk employees ON employees.id = emp_endorsement.pk
LEFT JOIN LEFT JOIN
employee_polices ON employees.id = employee_polices.employee_id employee_polices ON employees.id = employee_polices.employee_id
WHERE employees.client_id = '{$client_id}' WHERE employees.client_id = :client_id:
AND employee_polices.client_policy_id = '{$client_policy_id}' AND employee_polices.client_policy_id = :client_policy_id:
AND employees.client_branch_id = '{$client_branch_id}' AND employees.client_branch_id = :client_branch_id:
AND emp_endorsement.actions = 'c' AND emp_endorsement.actions = 'c'
AND emp_endorsement.status != 'truncated' AND emp_endorsement.status != 'truncated'
AND emp_endorsement.is_active = 1 AND emp_endorsement.is_active = 1
@ -585,8 +614,10 @@ class EmployeePolicyModel extends Model
AND employees.emp_status = 'active' AND employees.emp_status = 'active'
$endorsement_condition"; $endorsement_condition";
$binds = ["client_policy_id" => $client_policy_id,"client_branch_id" => $client_branch_id,"client_id" => $client_id];
// Execute the raw query // Execute the raw query
$query = $this->db->query($sql); $query = $this->db->query($sql,$binds);
// Get the result set // Get the result set
if($return_type == 1){ if($return_type == 1){
@ -1083,9 +1114,9 @@ class EmployeePolicyModel extends Model
public function getDeletionEmployeeDataForExportExcel($ref_data, $return_type = 0) public function getDeletionEmployeeDataForExportExcel($ref_data, $return_type = 0)
{ {
$client_id = $ref_data['client_id']; $client_id = (string) "'".$ref_data['client_id']."'";
$client_policy_id = $ref_data['client_policy_id']; $client_policy_id = (string) "'".$ref_data['client_policy_id']."'";
$client_branch_id = $ref_data['client_branch_id']; $client_branch_id = (string) "'".$ref_data['client_branch_id']."'";
$insurer_or_tpa = $ref_data['insurer_or_tpa']; $insurer_or_tpa = $ref_data['insurer_or_tpa'];
$get_insurer_id_from_client_policy = $this->db->table('client_policy') $get_insurer_id_from_client_policy = $this->db->table('client_policy')
@ -1284,12 +1315,12 @@ class EmployeePolicyModel extends Model
( (
SELECT employees.id SELECT employees.id
FROM employees FROM employees
WHERE client_id = '$client_id' WHERE client_id = :client_id:
AND client_branch_id = '$client_branch_id' AND client_branch_id = :client_branch_id:
AND is_active = 1 AND is_active = 1
AND emp_status = 'active' AND emp_status = 'active'
AND emp_code = '$emp_code' AND emp_code = :emp_code:
AND name = '$emp_name' AND name = :emp_name:
LIMIT 1 LIMIT 1
) AS employees_id, ) AS employees_id,
@ -1318,10 +1349,10 @@ class EmployeePolicyModel extends Model
JOIN employee_polices AS ep ON ep.id = ee.pk JOIN employee_polices AS ep ON ep.id = ee.pk
JOIN employees AS e ON e.emp_code = ee.emp_code JOIN employees AS e ON e.emp_code = ee.emp_code
WHERE WHERE
ee.emp_code = '$emp_code' ee.emp_code = :emp_code:
AND ep.client_policy_id = '$client_policy_id' AND ep.client_policy_id = :client_policy_id:
AND e.client_branch_id = '$client_branch_id' AND e.client_branch_id = :client_branch_id:
AND ee.name = '$emp_name' AND ee.name = :emp_name:
AND ee.field_name IN ('date_of_exit', 'reason_for_exit', 'status', 'claim_status') AND ee.field_name IN ('date_of_exit', 'reason_for_exit', 'status', 'claim_status')
AND ep.is_active = 1 AND ep.is_active = 1
AND ep.status = 'active' AND ep.status = 'active'
@ -1331,10 +1362,15 @@ class EmployeePolicyModel extends Model
ee.group_key ee.group_key
"; ";
$binds = ['client_policy_id' => $client_policy_id,
'client_branch_id' => $client_branch_id,
'client_id' => $client_id,
'emp_name' => $emp_name,
'emp_code' => $emp_code];
// dd($sql); // dd($sql);
// Execute the raw SQL query // Execute the raw SQL query
$query = $this->db->query($sql); $query = $this->db->query($sql,$binds);
// Fetch and return results // Fetch and return results
$row = $query->getRowArray(); $row = $query->getRowArray();
@ -1358,12 +1394,12 @@ class EmployeePolicyModel extends Model
$query = "UPDATE employee_polices $query = "UPDATE employee_polices
SET employee_polices.basic_cover_si = '{$basic_cover_si}' SET employee_polices.basic_cover_si = :basic_cover_si:
, employee_polices.premium = '{$premium}' , employee_polices.premium = :premium:
WHERE employee_polices.employee_id = '{$employee_id}' WHERE employee_polices.employee_id = :employee_id:
AND employee_polices.client_policy_id = '{$client_policy_id}'"; AND employee_polices.client_policy_id = :client_policy_id:";
$binds = ["client_policy_id"=>$client_policy_id, "employee_id"=>$employee_id,"basic_cover_si"=>$basic_cover_si,"premium"=>$premium];
$this->query($query); $this->query($query,$binds);
} }
@ -1545,9 +1581,9 @@ class EmployeePolicyModel extends Model
->join('insurer_branch', 'insurer_branch.id = cp.insurer_branch_id') ->join('insurer_branch', 'insurer_branch.id = cp.insurer_branch_id')
->join('tpa', 'tpa.id = cp.tpa_id') ->join('tpa', 'tpa.id = cp.tpa_id')
->where("ep.tpa_id IS NOT NULL AND ep.tpa_id <> ''") ->where("ep.tpa_id IS NOT NULL AND ep.tpa_id <> ''")
->where('e.emp_status', 'active')
->where('e.is_active', '1') ->where('e.is_active', '1')
->where('ep.status', 'active') ->whereIn('ep.status', ['active', 'expired'])
->whereIn('e.emp_status', ['active', 'expired'])
->where('ep.is_active', '1') ->where('ep.is_active', '1')
->where('e.emp_code', $emp_code) ->where('e.emp_code', $emp_code)
->where('ep.client_policy_id', $client_policy_id) ->where('ep.client_policy_id', $client_policy_id)
@ -1618,9 +1654,9 @@ class EmployeePolicyModel extends Model
->join('insurer_branch', 'insurer_branch.id = cp.insurer_branch_id') ->join('insurer_branch', 'insurer_branch.id = cp.insurer_branch_id')
->join('tpa', 'tpa.id = cp.tpa_id') ->join('tpa', 'tpa.id = cp.tpa_id')
->where("ep.tpa_id IS NOT NULL AND ep.tpa_id <> ''") ->where("ep.tpa_id IS NOT NULL AND ep.tpa_id <> ''")
->where('e.emp_status', 'active')
->where('e.is_active', '1') ->where('e.is_active', '1')
->where('ep.status', 'active') ->whereIn('ep.status', ['active', 'expired'])
->whereIn('e.emp_status', ['active', 'expired'])
->where('ep.is_active', '1') ->where('ep.is_active', '1')
->where('ep.rand_string', $rand_string) ->where('ep.rand_string', $rand_string)
->get() ->get()
@ -1893,6 +1929,8 @@ class EmployeePolicyModel extends Model
public function getDeletionDataForTruncated($file_id) public function getDeletionDataForTruncated($file_id)
{ {
$file_id = (int)$file_id;
// Fetch the necessary details in a single query using JOINs // Fetch the necessary details in a single query using JOINs
$result = $this->db->table('files f') $result = $this->db->table('files f')
->select('i.deletion_add_day') ->select('i.deletion_add_day')
@ -2028,6 +2066,8 @@ class EmployeePolicyModel extends Model
$action = "da"; $action = "da";
} }
$file_id = (int)$file_id;
$query = $this->db->query(" $query = $this->db->query("
SELECT SELECT
@ -2050,6 +2090,7 @@ class EmployeePolicyModel extends Model
// dd($this->db->getLastQuery(), $result); // dd($this->db->getLastQuery(), $result);
// dd($result); // dd($result);
return $result[0]; return $result[0];
} }
@ -2060,6 +2101,8 @@ class EmployeePolicyModel extends Model
log_message('error', 'updateEmployeePolicyTruncateReverse model function called'); log_message('error', 'updateEmployeePolicyTruncateReverse model function called');
log_message('error', 'FILE ID : {data}', ['data' => $file_id]); log_message('error', 'FILE ID : {data}', ['data' => $file_id]);
$file_id = (int)$file_id;
$this->db->query(" $this->db->query("
UPDATE employee_polices UPDATE employee_polices
SET SET
@ -2101,6 +2144,9 @@ class EmployeePolicyModel extends Model
//calculate the CD Transaction sum of the amount for the inception, addition, dependent addition, missed inception //calculate the CD Transaction sum of the amount for the inception, addition, dependent addition, missed inception
public function calculateCdTranctionAmount($file_id) public function calculateCdTranctionAmount($file_id)
{ {
$file_id = (int)$file_id;
$query = $this->db->query(" $query = $this->db->query("
SELECT SELECT
@ -2195,5 +2241,70 @@ class EmployeePolicyModel extends Model
// return $result; // return $result;
} }
// for this function using bulk e-card download as a zip
public function getEmployeeDataWithPolicyUsingClientPolicyIdOrEmployeePolicyIds($params, $limit = 100, $last_id = 0)
{
$client_policy_id = $params['client_policy_id'] ?? null;
$emp_policy_ids = $params['emp_policy_ids'] ?? null;
if (empty($client_policy_id) && empty($emp_policy_ids)) {
return [];
}
$builder = $this->db->table('employee_polices');
$builder->select('
employee_polices.id as emp_policy_id,
employee_polices.client_policy_id,
employees.name,
employees.emp_code,
employees.id as emp_id,
tpa.short_name,
employee_polices.tpa_id,
client_policy.policy_no
')
->join('client_policy', 'client_policy.id = employee_polices.client_policy_id')
->join('employees', 'employees.id = employee_polices.employee_id')
->join('tpa', 'tpa.id = client_policy.tpa_id')
->where([
'employees.emp_status' => 'active',
'employees.is_active' => '1',
'employee_polices.status' => 'active',
'employee_polices.is_active' => '1',
])
->where("employee_polices.tpa_id IS NOT NULL AND employee_polices.tpa_id <> ''");
// BATCHING LOGIC: Only get records greater than the last processed ID
if ($last_id > 0) {
$builder->where('employee_polices.id >', $last_id);
}
if ($client_policy_id) $builder->where('employee_polices.client_policy_id', $client_policy_id);
if ($emp_policy_ids) $builder->whereIn('employee_polices.id', $emp_policy_ids);
$builder->orderBy('employee_polices.id', 'ASC'); // Critical for keyset pagination
$builder->limit($limit);
return $builder->get()->getResultArray();
}
public function getClientPolicyDetailsByClientPolicyIdOrEmployeePolicyId($params)
{
$client_policy_id = $params['client_policy_id'] ?? null;
$emp_policy_id = $params['emp_policy_id'] ?? null;
if (empty($client_policy_id) && empty($emp_policy_id)) {
return [];
}
$builder = $this->db->table('client_policy');
$builder->select('client_policy.*')
->join('employee_polices ep', 'ep.client_policy_id = client_policy.id', 'left');
if ($client_policy_id) $builder->where('employee_polices.client_policy_id', $client_policy_id);
if ($emp_policy_id) $builder->where('employee_polices.id', $emp_policy_id);
return $builder->get()->getResultArray();
}
} }

View File

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

View File

@ -37,27 +37,68 @@ class InsurerModel extends Model
->getResult(); ->getResult();
} }
// public function getInsurerName($insurerId, $client_id)
// {
// // Fetch the insurer name based on the insurer ID
// $query = $this->db->table('client_policy')
// ->select('insurers.id, insurers.name, cd_master.cd_ac_no as cd_master_account_no')
// ->join('insurers', 'insurers.id = client_policy.insurer_id')
// ->join('cd_master', 'cd_master.insurer_id = insurers.id AND cd_master.client_id = client_policy.client_id')
// ->where('client_policy.insurer_id', $insurerId)
// ->where('client_policy.client_id', $client_id)
// ->where('cd_master.id = client_policy.cd_ac_pk')
// ->where('cd_master.is_active', 1)
// ->get();
// if ($query->resultID->num_rows > 0) {
// $result = $query->getRow();
// return $result;
// }
// return null; // or handle accordingly if the insurer is not found
// }
public function getInsurerName($insurerId, $client_id) public function getInsurerName($insurerId, $client_id)
{ {
// Fetch the insurer name based on the insurer ID $builder = $this->db->table('client_policy')
$query = $this->db->table('client_policy') ->select('
->select('insurers.id, insurers.name, cd_master.cd_ac_no as cd_master_account_no') insurers.id,
insurers.name,
insurers.short_name,
cd_master.cd_ac_no AS cd_master_account_no
')
->join('insurers', 'insurers.id = client_policy.insurer_id') ->join('insurers', 'insurers.id = client_policy.insurer_id')
->join('cd_master', 'cd_master.insurer_id = insurers.id AND cd_master.client_id = client_policy.client_id') ->join(
->where('client_policy.insurer_id', $insurerId) 'cd_master',
->where('client_policy.client_id', $client_id) 'cd_master.insurer_id = insurers.id
->where('cd_master.id = client_policy.cd_ac_pk') AND cd_master.client_id = client_policy.client_id
->where('cd_master.is_active', 1) AND cd_master.id = client_policy.cd_ac_pk
->get(); AND cd_master.is_active = 1'
)
->where('client_policy.insurer_id', $insurerId);
if ($query->resultID->num_rows > 0) { // Handle raw client_id vs MD5
$result = $query->getRow(); if (!empty($client_id)) {
return $result; if (is_string($client_id) && preg_match('/^[a-f0-9]{32}$/i', $client_id)) {
$builder->where('MD5(client_policy.client_id)', $client_id);
} else {
$builder->where('client_policy.client_id', $client_id);
}
} }
return null; // or handle accordingly if the insurer is not found $result = $builder
->groupBy([
'insurers.id',
'cd_master.cd_ac_no'
])
->limit(1)
->get()
->getRow();
return $result ?? null;
} }
public function getInsurerTemplateByInsurerID($insurer_id) public function getInsurerTemplateByInsurerID($insurer_id)
{ {
$insurer_data = $this->db->table('insurer_excel_export_template') $insurer_data = $this->db->table('insurer_excel_export_template')

View File

@ -206,9 +206,8 @@ class InvoiceModel extends Model
WHEN payout_status = 2 THEN 'Completed' WHEN payout_status = 2 THEN 'Completed'
END AS status_text, END AS status_text,
partner_agent.name as agent_name
") ")
->join('partner_agent', 'partner_invoice.agent_id = partner_agent.id') // ->join('partner_agent', 'partner_invoice.agent_id = partner_agent.id')
->where('partner_invoice.is_active', 1) ->where('partner_invoice.is_active', 1)
->where('partner_invoice.id', $invoice_id) ->where('partner_invoice.id', $invoice_id)
->first(); ->first();

View File

@ -73,6 +73,6 @@ class MessageModel extends Model
$query = $builder->get(); $query = $builder->get();
return $query->getResult(); return $query->getResult();
dd($this->db->getLastQuery()); // dd($this->db->getLastQuery());
} }
} }

View File

@ -67,7 +67,7 @@ class PolicesModel extends Model
{ {
$grid_id = $value['policy_grid_id']; $grid_id = $value['policy_grid_id'];
$policyGridModel = new PolicyGridModel(); $policyGridModel = new PolicyGridModel();
$grid_type = $policyGridModel->find($grid_id); $grid_type = $policyGridModel->find((int)$grid_id);
$premium_slab_data[$key]['grid_master'] = $grid_type; $premium_slab_data[$key]['grid_master'] = $grid_type;
} }
$premium_slab_data[$key]['grid_master'] = $grid_type; $premium_slab_data[$key]['grid_master'] = $grid_type;
@ -78,7 +78,7 @@ class PolicesModel extends Model
{ {
$additional_grid_id = $additional_premium_slab_data[0]['policy_grid_id']; $additional_grid_id = $additional_premium_slab_data[0]['policy_grid_id'];
$policyGridModel = new PolicyGridModel(); $policyGridModel = new PolicyGridModel();
$additional_grid_type = $policyGridModel->find($additional_grid_id); $additional_grid_type = $policyGridModel->find((int)$additional_grid_id);
} }

View File

@ -2421,16 +2421,20 @@
$sql1 = $builder2->getCompiledSelect(); $sql1 = $builder2->getCompiledSelect();
$sql2 = $builder->getCompiledSelect(); $sql2 = $builder->getCompiledSelect();
$finalSql = "($sql1) UNION ALL ($sql2) $finalSql = "(:sql1:) UNION ALL (:sql2:)
ORDER BY policy_no DESC, insurer_branch_name ASC, statement_uploaded ASC, ORDER BY policy_no DESC, insurer_branch_name ASC, statement_uploaded ASC,
STR_TO_DATE(policy_issue_month, '%b %Y') ASC"; STR_TO_DATE(policy_issue_month, '%b %Y') ASC";
$result = $this->db->query($finalSql)->getResultArray(); $binds = ['sql1'=>$sql1,'sql2'=>$sql1];
$result = $this->db->query($finalSql,$binds)->getResultArray();
// dd($this->db->getLastQuery()); // dd($this->db->getLastQuery());
return $result; return $result;
} }
//not in use function due to complexity of query and union, so writing raw query with bindings to avoid sql injection
public function getBDSReportListSingleUnion($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0, $user_id = 0, $where = []) public function getBDSReportListSingleUnion($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0, $user_id = 0, $where = [])
{ {
@ -2539,6 +2543,9 @@
pt.ref, pt.ref,
pt.data_received_date, pt.data_received_date,
pt.endorse_eff_date,
pt.policy_start_date,
pt.policy_end_date,
pt.renewal_date, pt.renewal_date,
pt.installment, pt.installment,
nhance_branch.branch_name as nhance_branch, nhance_branch.branch_name as nhance_branch,
@ -2568,8 +2575,10 @@
pt.action_type as action_type_string, pt.action_type as action_type_string,
c.client_name, c.client_name,
c.id as client_id,
c.short_name AS client_short_name, c.short_name AS client_short_name,
cb.branch_name AS client_branch_name, cb.branch_name AS client_branch_name,
cb.id AS client_branch_id,
cb.address1 AS client_address, cb.address1 AS client_address,
ptype.policy_type, ptype.policy_type,
ptype.bap, ptype.bap,
@ -2577,6 +2586,7 @@
ins.name AS insurer_name, ins.name AS insurer_name,
ins.short_name AS insurer_short_name, ins.short_name AS insurer_short_name,
ib.branch_name AS insurer_branch_name, ib.branch_name AS insurer_branch_name,
ib.id AS insurer_branch_id,
ib.branch_code AS insurer_branch_code, ib.branch_code AS insurer_branch_code,
created_user.first_name AS user_name, created_user.first_name AS user_name,
@ -2695,6 +2705,9 @@
pt.ref, pt.ref,
pt.data_received_date, pt.data_received_date,
pt.endorse_eff_date,
pt.policy_start_date,
pt.policy_end_date,
pt.renewal_date, pt.renewal_date,
pt.installment, pt.installment,
nhance_branch.branch_name as nhance_branch, nhance_branch.branch_name as nhance_branch,
@ -2734,8 +2747,10 @@
pt.action_type as action_type_string, pt.action_type as action_type_string,
c.client_name, c.client_name,
c.id as client_id,
c.short_name AS client_short_name, c.short_name AS client_short_name,
cb.branch_name AS client_branch_name, cb.branch_name AS client_branch_name,
cb.id AS client_branch_id,
cb.address1 AS client_address, cb.address1 AS client_address,
ptype.policy_type, ptype.policy_type,
ptype.bap, ptype.bap,
@ -2743,6 +2758,7 @@
ins.name AS insurer_name, ins.name AS insurer_name,
ins.short_name AS insurer_short_name, ins.short_name AS insurer_short_name,
ib.branch_name AS insurer_branch_name, ib.branch_name AS insurer_branch_name,
ib.id AS insurer_branch_id,
ib.branch_code AS insurer_branch_code, ib.branch_code AS insurer_branch_code,
created_user.first_name as user_name, created_user.first_name as user_name,
@ -3002,13 +3018,23 @@
public function getBDSReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0, $user_id = 0, $where = []) public function getBDSReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0, $user_id = 0, $where = [])
{ {
$client_id = (int)$client_id;
$insurer_id = (int)$insurer_id;
$policy_type_id = (int)$policy_type_id;
$client_branch_id = (int)$client_branch_id;
$insurer_branch_id = (int)$insurer_branch_id;
$client_policy_id = (int)$client_policy_id;
$user_id = (int)$user_id;
$issuer = (int)$issuer;
$whereAdded = false;
$statement_month_condition = ''; $statement_month_condition = '';
if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) { if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) {
$statement_month_condition = " $statement_month_condition = "
WHERE statement_month >= '" . $start_date . "' WHERE statement_month >= '" . $start_date . "'
AND statement_month <= '" . $end_date . "' AND statement_month <= '" . $end_date . "'
"; ";
$whereAdded = true;
} }
$default_date_filter = ''; $default_date_filter = '';
@ -3071,7 +3097,7 @@
} }
if ($insurer_id != 0) { if ($insurer_id != 0) {
$conditions .= " AND pt.insurer_id = $insurer_id "; $conditions .= " AND pcsd.insurer_id = $insurer_id ";
} }
if ($client_branch_id != 0) { if ($client_branch_id != 0) {
@ -3079,7 +3105,7 @@
} }
if ($insurer_branch_id != 0) { if ($insurer_branch_id != 0) {
$conditions .= " AND pt.insurer_branch_id = $insurer_branch_id "; $conditions .= " AND pcsd.insurer_branch_id = $insurer_branch_id ";
} }
if ($client_policy_id != 0) { if ($client_policy_id != 0) {
@ -3098,6 +3124,33 @@
$conditions .= " AND pt.issuer = $issuer "; $conditions .= " AND pt.issuer = $issuer ";
} }
$main_conditions = '';
function addCondition(&$main_conditions, &$whereAdded, $condition)
{
if (!$whereAdded) {
$main_conditions .= " WHERE $condition ";
$whereAdded = true;
} else {
$main_conditions .= " AND $condition ";
}
}
// 4. Common filters
if ($client_id != 0) {
addCondition($main_conditions, $whereAdded, "client_id = $client_id");
}
if ($insurer_id != 0) {
addCondition($main_conditions, $whereAdded, "insurer_id = $insurer_id");
}
if ($client_branch_id != 0) {
addCondition($main_conditions, $whereAdded, "client_branch_id = $client_branch_id");
}
if ($insurer_branch_id != 0) {
addCondition($main_conditions, $whereAdded, "insurer_branch_id = $insurer_branch_id");
}
$sql = " $sql = "
SELECT * FROM ( SELECT * FROM (
@ -3108,6 +3161,9 @@
pt.ref, pt.ref,
pt.data_received_date, pt.data_received_date,
pt.endorse_eff_date,
pt.policy_start_date,
pt.policy_end_date,
pt.renewal_date, pt.renewal_date,
pt.installment, pt.installment,
nhance_branch.branch_name as nhance_branch, nhance_branch.branch_name as nhance_branch,
@ -3137,8 +3193,10 @@
pt.action_type as action_type_string, pt.action_type as action_type_string,
c.client_name, c.client_name,
c.id as client_id,
c.short_name AS client_short_name, c.short_name AS client_short_name,
cb.branch_name AS client_branch_name, cb.branch_name AS client_branch_name,
cb.id AS client_branch_id,
cb.address1 AS client_address, cb.address1 AS client_address,
ptype.policy_type, ptype.policy_type,
ptype.bap, ptype.bap,
@ -3146,6 +3204,7 @@
ins.name AS insurer_name, ins.name AS insurer_name,
ins.short_name AS insurer_short_name, ins.short_name AS insurer_short_name,
ib.branch_name AS insurer_branch_name, ib.branch_name AS insurer_branch_name,
ib.id AS insurer_branch_id,
ib.branch_code AS insurer_branch_code, ib.branch_code AS insurer_branch_code,
created_user.first_name AS user_name, created_user.first_name AS user_name,
@ -3265,6 +3324,9 @@
pt.ref, pt.ref,
pt.data_received_date, pt.data_received_date,
pt.endorse_eff_date,
pt.policy_start_date,
pt.policy_end_date,
pt.renewal_date, pt.renewal_date,
pt.installment, pt.installment,
nhance_branch.branch_name as nhance_branch, nhance_branch.branch_name as nhance_branch,
@ -3294,8 +3356,10 @@
pt.action_type as action_type_string, pt.action_type as action_type_string,
c.client_name, c.client_name,
c.id as client_id,
c.short_name AS client_short_name, c.short_name AS client_short_name,
cb.branch_name AS client_branch_name, cb.branch_name AS client_branch_name,
cb.id AS client_branch_id,
cb.address1 AS client_address, cb.address1 AS client_address,
ptype.policy_type, ptype.policy_type,
ptype.bap, ptype.bap,
@ -3303,6 +3367,7 @@
ins.name AS insurer_name, ins.name AS insurer_name,
ins.short_name AS insurer_short_name, ins.short_name AS insurer_short_name,
ib.branch_name AS insurer_branch_name, ib.branch_name AS insurer_branch_name,
ib.id AS insurer_branch_id,
ib.branch_code AS insurer_branch_code, ib.branch_code AS insurer_branch_code,
created_user.first_name as user_name, created_user.first_name as user_name,
@ -3449,6 +3514,9 @@
pt.ref, pt.ref,
pt.data_received_date, pt.data_received_date,
pt.endorse_eff_date,
pt.policy_start_date,
pt.policy_end_date,
pt.renewal_date, pt.renewal_date,
pt.installment, pt.installment,
nhance_branch.branch_name as nhance_branch, nhance_branch.branch_name as nhance_branch,
@ -3479,8 +3547,10 @@
pt.action_type as action_type_string, pt.action_type as action_type_string,
c.client_name, c.client_name,
c.id as client_id,
c.short_name AS client_short_name, c.short_name AS client_short_name,
cb.branch_name AS client_branch_name, cb.branch_name AS client_branch_name,
cb.id AS client_branch_id,
cb.address1 AS client_address, cb.address1 AS client_address,
ptype.policy_type, ptype.policy_type,
ptype.bap, ptype.bap,
@ -3488,6 +3558,7 @@
ins.name AS insurer_name, ins.name AS insurer_name,
ins.short_name AS insurer_short_name, ins.short_name AS insurer_short_name,
ib.branch_name AS insurer_branch_name, ib.branch_name AS insurer_branch_name,
ib.id AS insurer_branch_id,
ib.branch_code AS insurer_branch_code, ib.branch_code AS insurer_branch_code,
created_user.first_name as user_name, created_user.first_name as user_name,
@ -3616,6 +3687,7 @@
) AS final_result ) AS final_result
$statement_month_condition $statement_month_condition
$main_conditions
-- GROUP BY statement_month, insurer_name, policy_no -- GROUP BY statement_month, insurer_name, policy_no
-- WHERE id = 6143 -- WHERE id = 6143
@ -3629,9 +3701,11 @@
"; ";
$query = $this->db->query($sql); $query = $this->db->query($sql);
$result = $query->getResultArray(); $result = $query->getResultArray();
// $countofalldata = count($result); // $countofalldata = count($result);
// dd($result); // dd($result);
// dd($this->db->getLastQuery()); // dd($this->db->getLastQuery()->getQuery());
$keys = []; $keys = [];
$filtered = []; $filtered = [];

View File

@ -85,7 +85,6 @@ class ThzMasterNotesModel extends Model
$ticketTypeFilter = "AND thz_master_notes.notes_type = 'External' "; $ticketTypeFilter = "AND thz_master_notes.notes_type = 'External' ";
} }
$integer_ticket_id = (int)$thz_id;
$notes_sql = "SELECT $notes_sql = "SELECT
thz_master_notes.*, thz_master_notes.*,
@ -103,11 +102,12 @@ class ThzMasterNotesModel extends Model
LEFT JOIN thz_master LEFT JOIN thz_master
ON thz_master.thz_id = thz_master_notes.thz_id ON thz_master.thz_id = thz_master_notes.thz_id
AND LOWER(thz_master_notes.notes_by) = 'user' AND LOWER(thz_master_notes.notes_by) = 'user'
WHERE thz_master_notes.thz_id = ". $integer_ticket_id ." WHERE thz_master_notes.thz_id = :integerTicketId:
$ticketTypeFilter $ticketTypeFilter
ORDER BY thz_master_notes.created_at DESC"; ORDER BY thz_master_notes.created_at DESC";
$result = $this->db->query($notes_sql)->getResultArray(); $binds = ["integerTicketId" => (int)$thz_id];
$result = $this->db->query($notes_sql,$binds)->getResultArray();
return $result; return $result;
} }

View File

@ -92,6 +92,10 @@ class TicketMasterModel extends Model
'claim_description', 'claim_description',
'required_docs', 'required_docs',
'policy_transaction_id', 'policy_transaction_id',
'tpa_claim_type',
'tpa_ailments',
'claim_dump_ref_id',
]; ];
@ -589,15 +593,17 @@ class TicketMasterModel extends Model
{ {
$ticket_type_data_1 = ""; $ticket_type_data_1 = "";
$ticket_type_data_2 = ""; $ticket_type_data_2 = "";
$statusBinds = [];
if (!empty($policy_type)) { if (!empty($policy_type)) {
$ticket_type_data_1 = "AND ticket_type = $policy_type"; $ticket_type_data_1 = "AND ticket_type = :policy_type:";
$ticket_type_data_2 = "AND master.ticket_type_id = $policy_type"; $ticket_type_data_2 = "AND master.ticket_type_id = :policy_type:";
$statusBinds['policy_type'] = $policy_type;
} }
// Fetch claim statuses dynamically // Fetch claim statuses dynamically
$statusQuery = "SELECT id, claim_status FROM ticket_claim_status WHERE is_active = 1 $ticket_type_data_1"; $statusQuery = "SELECT id, claim_status FROM ticket_claim_status WHERE is_active = 1 $ticket_type_data_1";
$statusResult = $this->db->query($statusQuery)->getResultArray(); $statusResult = $this->db->query($statusQuery, $statusBinds)->getResultArray();
// Initialize dynamic query parts // Initialize dynamic query parts
$dynamicSelect = ''; $dynamicSelect = '';
@ -649,7 +655,7 @@ class TicketMasterModel extends Model
JOIN JOIN
tpa ON master.tpa_id = tpa.id AND tpa.is_active = 1 tpa ON master.tpa_id = tpa.id AND tpa.is_active = 1
WHERE WHERE
master.created_at BETWEEN '$start_date' AND '$end_date' master.created_at BETWEEN :start_date: AND :end_date:
AND master.is_active = 1 AND master.is_active = 1
$ticket_type_data_2 $ticket_type_data_2
GROUP BY GROUP BY
@ -657,9 +663,14 @@ class TicketMasterModel extends Model
"; ";
// Execute the query // Execute the query
$result = $this->db->query($sql)->getResultArray(); $binds = ["start_date"=>$start_date,"end_date"=>$end_date];
// Merge policy_type binds if present
// print_rr($result);die(); if (!empty($statusBinds)) {
$binds = array_merge($binds, $statusBinds);
}
$result = $this->db->query($sql, $binds)->getResultArray();
// print_rr(count(($result)));
// print_rr($this->db->lastQuery);die();
return $result; return $result;
} }
@ -669,15 +680,17 @@ class TicketMasterModel extends Model
if ($policy_type == 1) { if ($policy_type == 1) {
$ticket_type_data_1 = ""; $ticket_type_data_1 = "";
$ticket_type_data_2 = ""; $ticket_type_data_2 = "";
$statusBinds = [];
if (!empty($policy_type)) { if (!empty($policy_type)) {
$ticket_type_data_1 = "AND ticket_type = $policy_type"; $ticket_type_data_1 = "AND ticket_type = :policy_type:";
$ticket_type_data_2 = "AND master.ticket_type_id = $policy_type"; $ticket_type_data_2 = "AND master.ticket_type_id = :policy_type:";
$statusBinds['policy_type'] = $policy_type;
} }
// Fetch claim statuses dynamically // Fetch claim statuses dynamically
$statusQuery = "SELECT id, claim_status FROM ticket_claim_status WHERE is_active = 1 $ticket_type_data_1"; $statusQuery = "SELECT id, claim_status FROM ticket_claim_status WHERE is_active = 1 $ticket_type_data_1";
$statusResult = $this->db->query($statusQuery)->getResultArray(); $statusResult = $this->db->query($statusQuery,$statusBinds)->getResultArray();
// Initialize dynamic query parts // Initialize dynamic query parts
$dynamicSelect = ''; $dynamicSelect = '';
@ -712,28 +725,36 @@ class TicketMasterModel extends Model
JOIN JOIN
user_profiles ON master.acm_id = user_profiles.id AND user_profiles.is_active = 1 user_profiles ON master.acm_id = user_profiles.id AND user_profiles.is_active = 1
WHERE WHERE
master.created_at BETWEEN '$start_date' AND '$end_date' master.created_at BETWEEN :start_date: AND :end_date:
AND master.is_active = 1 AND master.is_active = 1
$ticket_type_data_2 $ticket_type_data_2
GROUP BY GROUP BY
user_profiles.id; user_profiles.id;
"; ";
$result = $this->db->query($sql)->getResultArray(); $binds = ["start_date"=>$start_date,"end_date"=>$end_date];
// Merge policy_type binds if present
if (!empty($statusBinds)) {
$binds = array_merge($binds, $statusBinds);
}
$result = $this->db->query($sql,$binds)->getResultArray();
// print_rr(count(($result)));
// print_rr($this->db->lastQuery);die();
return $result; return $result;
} else { } else {
$ticket_type_data_1 = ""; $ticket_type_data_1 = "";
$ticket_type_data_2 = ""; $ticket_type_data_2 = "";
$statusBinds = [];
if (!empty($policy_type)) { if (!empty($policy_type)) {
$ticket_type_data_1 = "AND ticket_type = $policy_type"; $ticket_type_data_1 = "AND ticket_type = :policy_type:";
$ticket_type_data_2 = "AND master.ticket_type_id = $policy_type"; $ticket_type_data_2 = "AND master.ticket_type_id = :policy_type:";
$statusBinds['policy_type'] = $policy_type;
} }
// Fetch claim statuses dynamically // Fetch claim statuses dynamically
$statusQuery = "SELECT id, claim_status FROM ticket_claim_status WHERE is_active = 1 $ticket_type_data_1"; $statusQuery = "SELECT id, claim_status FROM ticket_claim_status WHERE is_active = 1 $ticket_type_data_1";
$statusResult = $this->db->query($statusQuery)->getResultArray(); $statusResult = $this->db->query($statusQuery,$statusBinds)->getResultArray();
// Initialize dynamic query parts // Initialize dynamic query parts
$dynamicSelect = ''; $dynamicSelect = '';
@ -783,16 +804,22 @@ class TicketMasterModel extends Model
JOIN JOIN
user_profiles ON master.acm_id = user_profiles.id AND user_profiles.is_active = 1 user_profiles ON master.acm_id = user_profiles.id AND user_profiles.is_active = 1
WHERE WHERE
master.created_at BETWEEN '$start_date' AND '$end_date' master.created_at BETWEEN :start_date: AND :end_date:
AND master.is_active = 1 AND master.is_active = 1
$ticket_type_data_2 $ticket_type_data_2
GROUP BY GROUP BY
user_profiles.id; user_profiles.id;
"; ";
$binds = ["start_date"=>$start_date,"end_date"=>$end_date];
// Execute the query // Execute the query
$result = $this->db->query($sql)->getResultArray(); // Merge policy_type binds if present
if (!empty($statusBinds)) {
$binds = array_merge($binds, $statusBinds);
}
$result = $this->db->query($sql,$binds)->getResultArray();
// print_rr($this->db->lastQuery);die();
return $result; return $result;
@ -992,12 +1019,12 @@ class TicketMasterModel extends Model
$sql = " SELECT cp.policy_terms $sql = " SELECT cp.policy_terms
FROM ticket_master tm FROM ticket_master tm
JOIN client_policy cp ON cp.id = tm.client_policy_id JOIN client_policy cp ON cp.id = tm.client_policy_id
WHERE tm.id = ? WHERE tm.id = :ticket_id:
AND tm.is_active = 1 AND tm.is_active = 1
AND cp.is_active = 1 AND cp.is_active = 1
"; ";
$binds = [$ticket_id]; $binds = ["ticket_id"=>$ticket_id];
$query = $this->db->query($sql,$binds); $query = $this->db->query($sql,$binds);
if ($query && $query->getNumRows() > 0) { if ($query && $query->getNumRows() > 0) {

View File

@ -581,7 +581,7 @@ table.dataTable tbody td {
<div class="form-group text-right m-b-0"> <div class="form-group text-right m-b-0">
<button class="btn app-btn-outline-secondary mr-2 " type="button" data-dismiss="modal" aria-hidden="true">Cancel</button> <button class="btn app-btn-outline-secondary mr-2 " type="button" data-dismiss="modal" aria-hidden="true">Cancel</button>
<button class="btn app-btn-secondary waves-effect waves-light" id="btnSubmit">Submit</button> <button type="submit" class="btn app-btn-secondary waves-effect waves-light" id="btnSubmit">Submit</button>
<!-- <button type="button" class="btn btn-secondry waves-effect waves-light mr-1" data-dismiss="modal" aria-hidden="true">Close</button> --> <!-- <button type="button" class="btn btn-secondry waves-effect waves-light mr-1" data-dismiss="modal" aria-hidden="true">Close</button> -->
</div> </div>
</form> </form>
@ -684,7 +684,7 @@ table.dataTable tbody td {
<div class="form-group col-md-5"> <div class="form-group col-md-5">
<label for="incentive_file_name">Upload File</label> <label for="incentive_file_name">Upload File</label>
<div class="input-icon"> <div class="input-icon">
<input type="file" class="form-control" name="incentive_file_name" id="incentive_file_name" required> <input type="file" class="form-control" name="incentive_file_name" id="incentive_file_name" required accept=".jpg,.jpeg,.png">
<i class="mdi mdi-upload additional-icon"></i> <i class="mdi mdi-upload additional-icon"></i>
</div> </div>
</div> </div>
@ -884,7 +884,20 @@ table.dataTable tbody td {
</table> </table>
</div> </div>
</div> </div>
<?php if (session()->getFlashdata('error')) : ?>
<?php foreach (session()->getFlashdata('error') as $error) : ?>
<script>
toastr.error("<?= esc($error) ?>", "Validation Error");
</script>
<?php endforeach; ?>
<script>
var errorModal = new bootstrap.Modal(
document.getElementById('con-close-modal')
);
errorModal.show();
</script>
<?php endif; ?>
<script> <script>
var table; var table;
$(document).ready(function () { $(document).ready(function () {
@ -1134,6 +1147,29 @@ table.dataTable tbody td {
console.error("Response Headers:", xhr.getAllResponseHeaders()); console.error("Response Headers:", xhr.getAllResponseHeaders());
console.error("Error Thrown:", error); console.error("Error Thrown:", error);
console.error("Status:", status); console.error("Status:", status);
if (xhr.status === 400) {
let response = JSON.parse(xhr.responseText);
let errorMessages = "";
let seenMessages = []; // Array to store unique messages
if (response.errors) {
$.each(response.errors, function (field, message) {
if (!seenMessages.includes(message)) {
errorMessages += `• ${message}<br>`;
seenMessages.push(message); // Mark this message as "seen"
}
});
toastr.error(errorMessages, 'Validation Error', { "allowHtml": true });
} else {
toastr.warning(response.message || 'Validation failed', 'Warning');
}
} else if (xhr.status === 403) {
let response = JSON.parse(xhr.responseText);
toastr.error(response.message, 'Security Policy');
} else if (xhr.status === 500) {
toastr.error('Something went wrong . Please try again later.', 'Server Error');
} else {
toastr.error('An unexpected error occurred. Please try again later.', 'Error');
}
} }
}); });
@ -1154,7 +1190,7 @@ table.dataTable tbody td {
var student_id = $(this).attr('data-id'); var student_id = $(this).attr('data-id');
$.get('<?php echo base_url('user/deactive/');?>'+student_id, function (data) { $.get('<?php echo base_url('user/deactive/');?>'+student_id, function (data) {
console.log(data); console.log(data);
toastr.success('User removed successfully', 'success'); toastr.success('User removed successfully', 'Success');
window.location.reload() window.location.reload()
}) })
} }
@ -1333,7 +1369,32 @@ table.dataTable tbody td {
}, },
error: function(xhr) { error: function(xhr) {
console.log("Error: " + xhr.statusText); console.log("Error: " + xhr.statusText);
toastr.error('Server error occurred.', 'Error'); if (xhr.status === 400) {
let response = JSON.parse(xhr.responseText);
let errorMessages = "";
let seenMessages = []; // Array to store unique messages
if (response.errors) {
$.each(response.errors, function (field, message) {
if (!seenMessages.includes(message)) {
errorMessages += `• ${message}<br>`;
seenMessages.push(message); // Mark this message as "seen"
}
});
toastr.error(errorMessages, 'Validation Error', { "allowHtml": true });
} else {
toastr.warning(response.message || 'Validation failed', 'Warning');
}
}else if (xhr.status === 403) {
let response = JSON.parse(xhr.responseText);
toastr.error(response.message, 'Security Policy');
} else if (xhr.status === 500) {
toastr.error('Something went wrong . Please try again later.', 'Server Error');
} else {
toastr.error('An unexpected error occurred. Please try again later.', 'Error');
}
console.error('Unexpected error:', xhr.responseText);
}, },
complete: function() { complete: function() {
btn.disabled = false; btn.disabled = false;
@ -1394,7 +1455,31 @@ table.dataTable tbody td {
}, },
error: function(xhr) { error: function(xhr) {
console.log("Error: " + xhr.statusText); console.log("Error: " + xhr.statusText);
toastr.error('Server error occurred.', 'Error'); console.error(xhr.responseText);
if (xhr.status === 400) {
let response = JSON.parse(xhr.responseText);
let errorMessages = "";
let seenMessages = []; // Array to store unique messages
if (response.errors) {
$.each(response.errors, function (field, message) {
if (!seenMessages.includes(message)) {
errorMessages += `• ${message}<br>`;
seenMessages.push(message); // Mark this message as "seen"
}
});
toastr.error(errorMessages, 'Validation Error', { "allowHtml": true });
} else {
toastr.warning(response.message || 'Validation failed', 'Warning');
}
} else if (xhr.status === 403) {
let response = JSON.parse(xhr.responseText);
toastr.error(response.message, 'Security Policy');
} else if (xhr.status === 500) {
toastr.error('Something went wrong . Please try again later.', 'Server Error');
} else {
toastr.error('An unexpected error occurred. Please try again later.', 'Error');
}
}, },
complete: function() { complete: function() {
btn.disabled = false; btn.disabled = false;
@ -1871,18 +1956,35 @@ table.dataTable tbody td {
<script> <script>
$(document).on('click', '#btnAdd', function() { $(document).on('click', '#btnAdd', function() {
$('#first_name').val(''); // Reset the form
$('#last_name').val(''); $('#UserForm')[0].reset();
$('#email').val(''); $('#UserId').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
// Specifically reset Select2 if you are using it
$('#nhance_branch_id').val('').trigger('change');
$('#rm_id').val('').trigger('change');
// Update Modal Title and Action
$('.modal-title').text('Add User');
$('#btnSubmit').text('Submit');
$('#UserForm').attr('action', '<?php echo base_url('/user/create');?>');
var myModal = new bootstrap.Modal(document.getElementById('con-close-modal'));
myModal.show();
}); });
// $(document).on('click', '#btnAdd', function(){
// $('#first_name').val('');
// $('#last_name').val('');
// $('#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
// });
$(document).on('click', '#btnNhancePartnerAdd', function(){ $(document).on('click', '#btnNhancePartnerAdd', function(){
$('#partner_name').val(''); $('#partner_name').val('');
$('#email_addr').val(''); $('#email_addr').val('');
@ -1910,7 +2012,7 @@ table.dataTable tbody td {
checkDuplicateTableFieldValue(table, field, value, function(isDuplicate) { checkDuplicateTableFieldValue(table, field, value, function(isDuplicate) {
if (isDuplicate) { if (isDuplicate) {
toastr.warning(message, 'WARNING'); toastr.warning(message, 'Warning');
// $(input).val('') // $(input).val('')
$('#' + submitButId).prop('disabled', true); $('#' + submitButId).prop('disabled', true);
} else{ } else{

View File

@ -126,7 +126,7 @@ table.dataTable thead th {
<div class="form-group"> <div class="form-group">
<label for="branchname">Upload Image</label> <label for="branchname">Upload Image</label>
<div class="input-icon"> <div class="input-icon">
<input type="file" class="form-control" name="advertise_image" id="advertise_image" accept="image/*" onchange="PreviewImage();" required> <input type="file" class="form-control" name="advertise_image" id="advertise_image" accept=".jpg,.jpeg,.png" onchange="PreviewImage();" required>
<i class="mdi mdi-upload additional-icon"></i> <i class="mdi mdi-upload additional-icon"></i>
</div> </div>
</div> </div>
@ -219,31 +219,42 @@ table.dataTable thead th {
} }
}, },
error: function(xhr, status, error) { error: function(xhr, status, error) {
console.error(xhr.responseText); // Get the current domain
console.error('Status:', status); const hostname = window.location.hostname;
console.error('Error:', error); if (hostname === 'localhost' || hostname === '127.0.0.1') {
// DEVELOPER MODE: Show everything in a nice group
console.group("%c Debug: Server Error ", "background: #222; color: #bada55; padding: 2px;");
console.error("Status:", xhr.status);
console.error("Type:", error);
console.error("Full Response:", xhr.responseText);
console.groupEnd();
} else {
// LIVE MODE: Only log a simple, non-revealing error
console.error("Server Error: Action could not be completed. Reference Code: " + xhr.responseText);
}
let msg = 'Something went wrong. Please try again later.'; if (xhr.status === 400) {
let response = JSON.parse(xhr.responseText);
switch (xhr.status) { let errorMessages = "";
case 400: let seenMessages = []; // Array to store unique messages
msg = xhr.responseJSON?.message || 'Bad Request — Invalid input.'; if (response.errors) {
break; $.each(response.errors, function (field, message) {
case 401: if (!seenMessages.includes(message)) {
msg = 'Unauthorized — Please log in again.'; errorMessages += `• ${message}<br>`;
break; seenMessages.push(message); // Mark this message as "seen"
case 403: }
msg = 'Forbidden — You do not have permission.'; });
break; toastr.error(errorMessages, 'Validation Error', { "allowHtml": true });
case 404: } else {
msg = 'Not Found — Requested URL or resource not found.'; toastr.warning(response.message || 'Validation failed', 'Warning');
break; }
case 500: } else if (xhr.status === 403) {
console.log('Internal Server Error — Please contact support.'); let response = JSON.parse(xhr.responseText);
msg = xhr.responseJSON?.message || xhr.responseText || msg; toastr.error(response.message, 'Security Policy');
break; } else if (xhr.status === 500) {
default: toastr.error('Something went wrong . Please try again later.', 'Server Error');
msg = xhr.responseJSON?.message || xhr.responseText || msg; } else {
toastr.error('An unexpected error occurred. Please try again later.', 'Error');
} }
} }

View File

@ -168,6 +168,7 @@
data-event_type="<?= $file['event_type'] ?>" data-event_type="<?= $file['event_type'] ?>"
data-actions="<?= $file['actions'] ?>" data-actions="<?= $file['actions'] ?>"
data-client_branch_id="<?= $file['client_branch_id'] ?>" data-client_branch_id="<?= $file['client_branch_id'] ?>"
data-issue_date="<?= $file['policy_issue_date'] ?>"
onclick="getBatchFileData(this)" class="dropdown-item upload_button" ><i class="mdi mdi-upload mr-2 text-muted font-18 vertical-middle"></i>Re-Upload</a> onclick="getBatchFileData(this)" class="dropdown-item upload_button" ><i class="mdi mdi-upload mr-2 text-muted font-18 vertical-middle"></i>Re-Upload</a>
<?php } ?> <?php } ?>
@ -215,6 +216,7 @@
<input type="hidden" id="batch_file_insurer_or_tpa" name="insurer_or_tpa"> <input type="hidden" id="batch_file_insurer_or_tpa" name="insurer_or_tpa">
<input type="hidden" id="batch_file_action_type" name="action_type"> <input type="hidden" id="batch_file_action_type" name="action_type">
<input type="hidden" id="batch_file_event_type" name="event_type"> <input type="hidden" id="batch_file_event_type" name="event_type">
<input type="hidden" id="batch_file_issue_date" name="policy_issue_date">
<input type="file" id="import_file_data" name="import_file_data" required <input type="file" id="import_file_data" name="import_file_data" required
accept=" application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel,application/vnd.oasis.opendocument.spreadsheet"> accept=" application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel,application/vnd.oasis.opendocument.spreadsheet">
@ -329,6 +331,7 @@
let insurer_or_tpa = $(input).data('insurer_or_tpa') let insurer_or_tpa = $(input).data('insurer_or_tpa')
let event_type = $(input).data('event_type') let event_type = $(input).data('event_type')
let actions = $(input).data('actions') let actions = $(input).data('actions')
let issue_date = $(input).data('issue_date')
console.log('client_id', client_id); console.log('client_id', client_id);
console.log('client_policy_id', client_policy_id); console.log('client_policy_id', client_policy_id);
@ -336,6 +339,7 @@
console.log('insurer_or_tpa', insurer_or_tpa); console.log('insurer_or_tpa', insurer_or_tpa);
console.log('event_type', event_type); console.log('event_type', event_type);
console.log('actions', actions); console.log('actions', actions);
console.log('issue_date', issue_date);
$('#batch_file_client_id').val(client_id); $('#batch_file_client_id').val(client_id);
$('#batch_file_policy_id').val(client_policy_id); $('#batch_file_policy_id').val(client_policy_id);
@ -343,6 +347,7 @@
$('#batch_file_insurer_or_tpa').val(insurer_or_tpa); $('#batch_file_insurer_or_tpa').val(insurer_or_tpa);
$('#batch_file_action_type').val(actions); $('#batch_file_action_type').val(actions);
$('#batch_file_event_type').val(event_type); $('#batch_file_event_type').val(event_type);
$('#batch_file_issue_date').val(issue_date);
var myModal = new bootstrap.Modal(document.getElementById('batch_file_upload_modal')); var myModal = new bootstrap.Modal(document.getElementById('batch_file_upload_modal'));

View File

@ -182,9 +182,9 @@
console.log('Upload successful:', response); console.log('Upload successful:', response);
if (response.status == true) { if (response.status == true) {
toastr.success(response.message, "SUCCESS"); toastr.success(response.message, "Success");
} else { } else {
toastr.error(response.message, "ERROR"); toastr.error(response.message, "Error");
} }
// Reset form // Reset form
@ -196,7 +196,30 @@
error: function(xhr, status, error) { error: function(xhr, status, error) {
// Handle error response // Handle error response
console.error('Upload failed:', error); console.error('Upload failed:', error);
console.error('Upload failed:', error); console.error('Unexpected error:', xhr.responseText);
if (xhr.status === 400) {
let response = JSON.parse(xhr.responseText);
let errorMessages = "";
let seenMessages = []; // Array to store unique messages
if (response.errors) {
$.each(response.errors, function (field, message) {
if (!seenMessages.includes(message)) {
errorMessages += `• ${message}<br>`;
seenMessages.push(message); // Mark this message as "seen"
}
});
toastr.error(errorMessages, 'Validation Error', { "allowHtml": true });
} else {
toastr.warning(response.message || 'Validation failed', 'Warning');
}
} else if (xhr.status === 403) {
let response = JSON.parse(xhr.responseText);
toastr.error(response.message, 'Security Policy');
} else if (xhr.status === 500) {
toastr.error('Something went wrong . Please try again later.', 'Server Error');
} else {
toastr.error('An unexpected error occurred. Please try again later.', 'Error');
}
}, },
complete: function() { complete: function() {
// Reset button state // Reset button state
@ -214,7 +237,7 @@
// Check file size (optional - set max size as needed, e.g., 10MB) // Check file size (optional - set max size as needed, e.g., 10MB)
var maxSize = 10 * 1024 * 1024; // 10MB in bytes var maxSize = 10 * 1024 * 1024; // 10MB in bytes
if (file.size > maxSize) { if (file.size > maxSize) {
toastr.warning('File size should not exceed 10MB'); toastr.warning('File size should not exceed 10MB', 'Warning');
$(this).val(''); // Clear the input $(this).val(''); // Clear the input
return false; return false;
} }

View File

@ -187,7 +187,7 @@
} }
} else { } else {
toastr.warning(res.message, 'WARNING'); toastr.warning(res.message, 'Warning');
} }
//this function for reset the form values after submitting the form or closing the form //this function for reset the form values after submitting the form or closing the form
@ -204,7 +204,30 @@
console.error(status, error); console.error(status, error);
$('.loader').fadeOut(); $('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow'); $('.loader-mask').delay(350).fadeOut('slow');
toastr.error('An error occurred while adding the CD account number.', 'ERROR'); if (xhr.status === 400) {
let response = JSON.parse(xhr.responseText);
let errorMessages = "";
let seenMessages = []; // Array to store unique messages
if (response.errors) {
$.each(response.errors, function (field, message) {
if (!seenMessages.includes(message)) {
errorMessages += `• ${message}<br>`;
seenMessages.push(message); // Mark this message as "seen"
}
});
toastr.error(errorMessages, 'Validation Error', { "allowHtml": true });
} else {
toastr.warning(response.message || 'Validation failed', 'Warning');
}
} else if (xhr.status === 403) {
let response = JSON.parse(xhr.responseText);
toastr.error(response.message, 'Security Policy');
} else if (xhr.status === 500) {
toastr.error('Something went wrong . Please try again later.', 'Server Error');
} else {
toastr.error('An unexpected error occurred. Please try again later.', 'Error');
}
toastr.error('An error occurred while adding the CD account number.', 'Error');
} }
}); });
}); });
@ -279,7 +302,6 @@
$('#opening_date').val(''); $('#opening_date').val('');
$('#cd_ac_no_for_cd_master').val(''); $('#cd_ac_no_for_cd_master').val('');
$('#opening_bal').val('');
// $('#CDMasterForm').attr('action', '<?php echo base_url('master/cash_deposite/create');?>'); // $('#CDMasterForm').attr('action', '<?php echo base_url('master/cash_deposite/create');?>');
$('#title').html('Add Opening Amount'); $('#title').html('Add Opening Amount');
$('#cd_master_btn_Submit').html('Submit'); $('#cd_master_btn_Submit').html('Submit');
@ -329,13 +351,13 @@
$('#cd_client_id').val('').select2(); $('#cd_client_id').val('').select2();
$('#insurer_id_for_cd').val('').select2(); $('#insurer_id_for_cd').val('').select2();
$('#insurer_branch_id').val('').select2(); $('#insurer_branch_id').val('').select2();
toastr.warning(response.message, 'WARNING'); toastr.warning(response.message, 'Warning');
} }
}, function(xhr, status, error) { }, function(xhr, status, error) {
console.error('Error fetching data:', error); console.error('Error fetching data:', error);
console.error(xhr.responseText); console.error(xhr.responseText);
toastr.error('An error occurred while checking the CD amount.', 'ERROR'); toastr.error('An error occurred while checking the CD amount.', 'Error');
}); });
} }
} }

View File

@ -312,7 +312,7 @@ table.dataTable thead th {
<?php endif; ?> <?php endif; ?>
<?php if (session()->has('success')) : ?> <?php if (session()->has('success')) : ?>
toastr.success('<?= session()->getFlashdata('success') ?>', 'success'); toastr.success('<?= session()->getFlashdata('success') ?>', 'Success');
<?php endif; ?> <?php endif; ?>
}) })
@ -381,10 +381,10 @@ table.dataTable thead th {
// console.log(res.status == true); // console.log(res.status == true);
if(res){ if(res){
if (res.status == true) { if (res.status == true) {
toastr.success('CD removed successfully.', 'success'); toastr.success('CD removed successfully.', 'Success');
location.reload(); location.reload();
} else { } else {
toastr.warning('Failed to remove CD.', 'warning'); toastr.warning('Failed to remove CD.', 'Warning');
} }
} }
}, },

View File

@ -22,6 +22,8 @@
} }
.dataTables_length label {height: 21px !important;} .dataTables_length label {height: 21px !important;}
.readonly-select { background-color: #f3f3f3 !important; cursor: not-allowed; pointer-events: none; }
</style> </style>
<!-- <div class="row"> <!-- <div class="row">
@ -155,10 +157,35 @@
<div class="modal-body"> <div class="modal-body">
<form class="parsley-examples" id="claim-upload-form" enctype="multipart/form-data"> <form class="parsley-examples" id="claim-upload-form" enctype="multipart/form-data">
<div class="form-group"> <div class="form-group">
<div class="form-row">
<div class="form-group col-md-12">
<label>Client<span id="tpa_danger" class="text-danger"></span></label>
<select name="client_id" class="form-control" id="client_id">
<option value="">Select</option>
</select>
</div>
<div class="form-group col-md-12">
<label>Policy <span id="tpa_danger" class="text-danger"></span></label>
<select name="client_policy_id" class="form-control" id="client_policy_id">
<option value="">Select</option>
</select>
</div>
<div class="form-group col-md-12">
<label for="tpa">TPA<span id="tpa_danger" class="text-danger"></span></label>
<select class="form-control readonly-select" id="tpa_id" name="tpa_id">
<option value="">Select TPA</option>
<?php foreach ($tpa_list as $value) { ?>
<option value="<?= $value['id'] ?>"><?= $value['short_name'] ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-row" id="file_upload"> <div class="form-row" id="file_upload">
<div class="form-group col-md-9"> <div class="form-group col-md-9">
<label>Upload file</label> <label>Upload file</label>
<!-- &nbsp;[ <a href="#" id="excel_download" data-toggle="tooltip" data-placement="top" title="Download Sample Excel">Sample Excel</a> ] --> &nbsp;[ <a href="<?= base_url("util/download-excel/claim_dump_upload"); ?>" id="download_sample_file" style="font-size: small; color:red !important;">Download sample file</a> ]
<input type="file" name="claim_dump_list" id="claim_dump_list" accept=" application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel,application/vnd.oasis.opendocument.spreadsheet" required> <input type="file" name="claim_dump_list" id="claim_dump_list" accept=" application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel,application/vnd.oasis.opendocument.spreadsheet" required>
</div> </div>
<div class="form-group col-md-3" style="margin-top: 40px;"> <div class="form-group col-md-3" style="margin-top: 40px;">
@ -172,14 +199,47 @@
</div><!-- /.modal-dialog --> </div><!-- /.modal-dialog -->
</div><!-- /.modal --> </div><!-- /.modal -->
<div id="full-width-modal-emp-list" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="fullWidthModalLabel"
aria-hidden="true">
<div class="modal-dialog modal-full-width">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="fullWidthModalLabel">View Uploaded File<span
id="title_header_name"></span></h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body" id="emp_data_success">
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script> <script>
let policyListByClient = null;
let client_list = null;
$(document).ready(function() { $(document).ready(function() {
getClientAndBranchAndPolicy();
$('#client_id').select2();
$('#client_policy_id').select2();
// AJAX Form Submit Function // AJAX Form Submit Function
$('#claim-upload-form').on('submit', function(e) { $('#claim-upload-form').on('submit', function(e) {
e.preventDefault(); // Prevent default form submission e.preventDefault(); // Prevent default form submission
let client_id = $('#client_id').val() ?? null;
let client_policy_id = $('#client_policy_id').val() ?? null;
if(client_id){
if(!client_policy_id){
toastr.warning('Please select the client policy', 'Warning');
return;
}
}
// Get form data // Get form data
var formData = new FormData(this); var formData = new FormData(this);
var fileInput = $('#claim_dump_list')[0]; var fileInput = $('#claim_dump_list')[0];
@ -220,9 +280,9 @@
console.log('Upload successful:', response); console.log('Upload successful:', response);
if (response.status == true) { if (response.status == true) {
toastr.success(response.message, "SUCCESS"); toastr.success(response.message, "Success");
} else { } else {
toastr.error(response.message, "ERROR"); toastr.error(response.message, "Error");
} }
// Reset form // Reset form
@ -275,6 +335,28 @@
} }
}) })
$('#client_id').on('change', function(){
let client_id = $(this).val();
if(policyListByClient != '') {
console.log(policyListByClient[client_id]);
let data = policyListByClient[client_id];
appendPolicies(data);
}
})
$('#client_policy_id').on('change', function(){
let tpa_id = $(this).find(':selected').data('tpaid');
console.log('tpa_id', tpa_id);
if(tpa_id){
$('#tpa_id').val(tpa_id);
}else{
$('#tpa_id').val('');
}
})
}); });
// Datatable document ready // Datatable document ready
@ -390,6 +472,7 @@
} }
} }
if (err_id != 5 && err_id != 6 && err_id != 0) { if (err_id != 5 && err_id != 6 && err_id != 0) {
file_error_html += (file_error_html != "" ? file_error_html += (file_error_html != "" ?
"<a href ='<?php echo base_url('util/claim_dump_excel_error/') ?>" + file_id + "<a href ='<?php echo base_url('util/claim_dump_excel_error/') ?>" + file_id +
@ -429,4 +512,138 @@
myModal.show(); myModal.show();
} }
function getClientAndBranchAndPolicy() {
$.ajax({
url: '<?= base_url("/util/getClientAndBranchAndPolicy") ?>',
type: "GET",
dataType: 'json',
success: function(res) {
console.log('getClientAndBranchAndPolicy', res);
if (res.status == true) {
policyListByClient = res.policyListByClient;
client_list = res.client_data;
appendClients(res.client_data);
} else {
console.log('No data found');
}
},
error: function(xhr, status, error) {
console.error(xhr.responseText);
console.error(status, error);
}
});
}
function appendClients(data) {
$('#client_id').empty();
$('#client_id').append($('<option>', {
value: '',
text: 'Select Client'
}));
$.each(data, function(index, item) {
if (item.client_policy_count > 0) {
var option = $('<option>', {
value: item.id,
text: item.client_name
});
$('#client_id').append(option);
}
});
}
function appendPolicies(data) {
$('#client_policy_id').empty();
$('#client_policy_id').append($('<option>', {
value: '',
text: 'Select Policy',
}));
$.each(data, function(index, item) {
var option = $('<option>', {
value: item.id,
text: item.policy_type + '-' + item.policy_no,
'data-tpaid': item.tpa_id,
});
$('#client_policy_id').append(option);
});
}
$('body').on('click', '.view_emp_list', function() {
$('#emp_data_success').empty();
var file_id = $(this).attr('data-id');
console.log(file_id);
var queryParams = {
file_id: file_id,
};
console.log('queryParams', queryParams)
const queryString = objectToQueryString(queryParams);
console.log('queryString', queryString)
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
var uri = '<?= base_url('util/view-success-emp-list') ?>?' + queryString
console.log(uri)
$.ajax({
url: uri,
data: {
file_id: file_id,
},
type: "GET",
dataType: 'json',
processData: false,
contentType: false,
success: function(res) {
console.log(res);
if (res) {
setTimeout(function() {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
}, 1000);
}
var title = " - ";
if (res.file_data) {
title += (res.file_data.file_name || "") + " - ";
title += (res.file_data.short_name || "") + " - ";
title += (res.file_data.policy_name || "") + " - ";
title += (res.file_data.action || "") + " - ";
title += (res.file_data.status || "");
}
$('#title_header_name').html(title);
$('#emp_data_success').html(res.data);
},
error: function(xhr, status, error) {
console.error(xhr.responseText);
console.error(status, error);
setTimeout(function() {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
toastr.warning('Something went wrong', 'Warning');
}, 1000);
}
});
})
</script> </script>

View File

@ -217,6 +217,29 @@
console.log("error in submission of url data"); console.log("error in submission of url data");
console.error(xhr.responseText); console.error(xhr.responseText);
console.error(status, error); console.error(status, error);
if (xhr.status === 400) {
let response = JSON.parse(xhr.responseText);
let errorMessages = "";
let seenMessages = []; // Array to store unique messages
if (response.errors) {
$.each(response.errors, function (field, message) {
if (!seenMessages.includes(message)) {
errorMessages += `• ${message}<br>`;
seenMessages.push(message); // Mark this message as "seen"
}
});
toastr.error(errorMessages, 'Validation Error', { "allowHtml": true });
} else {
toastr.warning(response.message || 'Validation failed', 'Warning');
}
} else if (xhr.status === 403) {
let response = JSON.parse(xhr.responseText);
toastr.error(response.message, 'Security Policy');
} else if (xhr.status === 500) {
toastr.error('Something went wrong . Please try again later.', 'Server Error');
} else {
toastr.error('An unexpected error occurred. Please try again later.', 'Error');
}
}, },
complete : function(){ complete : function(){
@ -566,7 +589,7 @@
function addDocument() { function addDocument() {
if (documentConfig.is_action_freeze) { if (documentConfig.is_action_freeze) {
toastr.warning('Cannot add documents when action is frozen', 'WARNING'); toastr.warning('Cannot add documents when action is frozen', 'Warning');
return; return;
} }
@ -591,7 +614,7 @@
function removeDocument(index) { function removeDocument(index) {
if (documentConfig.is_action_freeze) { if (documentConfig.is_action_freeze) {
toastr.warning('Cannot remove documents when action is frozen', 'WARNING'); toastr.warning('Cannot remove documents when action is frozen', 'Warning');
return; return;
} }
@ -599,7 +622,7 @@
// ❗ If document is already received, do not remove // ❗ If document is already received, do not remove
if (doc.document_received === true) { if (doc.document_received === true) {
toastr.warning('Cannot remove a received document', 'WARNING'); toastr.warning('Cannot remove a received document', 'Warning');
return; return;
} }
@ -640,7 +663,7 @@
const hasEmptyNames = documentConfig.docs.some(doc => !doc.document_name.trim()); const hasEmptyNames = documentConfig.docs.some(doc => !doc.document_name.trim());
if (hasEmptyNames) { if (hasEmptyNames) {
toastr.warning('Please fill in all document names', 'WARNING'); toastr.warning('Please fill in all document names', 'Warning');
return false; return false;
} }
@ -665,15 +688,38 @@
if (response.status) { if (response.status) {
loadConfiguration(response.data); loadConfiguration(response.data);
toastr.success(response.message, 'SUCCESS'); toastr.success(response.message, 'Success');
} else { } else {
toastr.warning(response.message, 'WARNING'); toastr.warning(response.message, 'Warning');
} }
}, function(xhr, status, error) { }, function(xhr, status, error) {
console.error('Error fetching data:', error); console.error('Error fetching data:', error);
console.error(xhr.responseText); console.error(xhr.responseText);
toastr.error('An error occurred while saving docs.', 'ERROR'); if (xhr.status === 400) {
let response = JSON.parse(xhr.responseText);
let errorMessages = "";
let seenMessages = []; // Array to store unique messages
if (response.errors) {
$.each(response.errors, function (field, message) {
if (!seenMessages.includes(message)) {
errorMessages += `• ${message}<br>`;
seenMessages.push(message); // Mark this message as "seen"
}
});
toastr.error(errorMessages, 'Validation Error', { "allowHtml": true });
} else {
toastr.warning(response.message || 'Validation failed', 'Warning');
}
} else if (xhr.status === 403) {
let response = JSON.parse(xhr.responseText);
toastr.error(response.message, 'Security Policy');
} else if (xhr.status === 500) {
toastr.error('Something went wrong . Please try again later.', 'Server Error');
} else {
toastr.error('An unexpected error occurred. Please try again later.', 'Error');
}
}); });
} }

View File

@ -0,0 +1,411 @@
<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;}
.readonly-select { background-color: #f3f3f3 !important; cursor: not-allowed; pointer-events: none; }
</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">Action</th>
</tr>
</thead>
<tbody class="font-12">
<?php
if (isset($claim_mis_file_list)) {
foreach ($claim_mis_file_list as $key => $file) {
?>
<tr>
<td class="text-center"><b><?php echo ($key + 1) ?></b></td>
<td class="text-center"><?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>
<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("claim_mis/download?id=") . $file['id']; ?>"><i class="mdi mdi-download mr-2 text-muted font-18 vertical-middle"></i>Download</a>
</div>
</div>
</td>
</tr>
<?php }
} ?>
</tbody>
</table>
</div>
</div>
</div><!-- end col -->
<!-- Center modal content for upload file-->
<div class="modal fade" id="claim-mis-file-upload-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myCenterModalLabel">Cliam MIS File upload</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<form class="parsley-examples" id="claim-mis-upload-form" enctype="multipart/form-data">
<div class="form-group">
<div class="form-row">
<div class="form-group col-md-4">
<label>Client<span id="tpa_danger" class="text-danger">*</span></label>
<select name="client_id" class="form-control" id="client_id" required>
<option value="">Select</option>
</select>
</div>
<div class="form-group col-md-4">
<label>Policy <span id="tpa_danger" class="text-danger">*</span></label>
<select name="client_policy_id" class="form-control" id="client_policy_id" required>
<option value="">Select</option>
</select>
</div>
<div class="form-group col-md-4">
<label for="tpa">TPA<span id="tpa_danger" class="text-danger">*</span></label>
<select class="form-control readonly-select" id="tpa_id" name="tpa_id" required>
<option value="">Select TPA</option>
<?php foreach ($tpa_list as $value) { ?>
<option value="<?= $value['id'] ?>"><?= $value['short_name'] ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<label>From Date<span id="tpa_danger" class="text-danger">*</span></label>
<input class="form-control" type="text" name="from_date" id="from_date" required>
</div>
<div class="form-group col-md-4">
<label>To Date<span id="tpa_danger" class="text-danger">*</span></label>
<input class="form-control" type="text" name="to_date" id="to_date" required>
</div>
</div>
<div class="form-row" id="file_upload">
<div class="form-group col-md-4">
<label>Upload file</label>
<input type="file" name="file" id="file" accept=".pdf,.xls,.xlsx,application/pdf,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" required>
</div>
<div class="form-group col-md-3" style="margin-top: 40px;margin-left: 170px;">
<button id="claim_mis_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>
let policyListByClient = null;
let client_list = null;
$(document).ready(function() {
getClientAndBranchAndPolicy();
$('#client_id').select2();
$('#client_policy_id').select2();
var from_date = flatpickr("#from_date", {
dateFormat: "d/m/Y",
allowInput: false
});
var to_date = flatpickr("#to_date", {
dateFormat: "d/m/Y",
allowInput: false
});
// AJAX Form Submit Function
$('#claim-mis-upload-form').on('submit', function(e) {
e.preventDefault(); // Prevent default form submission
// Get form data
var formData = new FormData(this);
var fileInput = $('#file')[0];
// Validate file type
var allowedTypes = [
'application/pdf',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.oasis.opendocument.spreadsheet'
];
if (!fileInput.files || !fileInput.files.length) {
toastr.warning('Please select a file', 'Warning');
return false;
}
var selectedFile = fileInput.files[0];
// Some browsers return empty type → fallback to extension
var allowedExtensions = ['pdf', 'xls', 'xlsx', 'ods'];
var fileExtension = selectedFile.name.split('.').pop().toLowerCase();
if (
(!allowedTypes.includes(selectedFile.type)) &&
(!allowedExtensions.includes(fileExtension))
) {
toastr.warning(
'Please upload a valid file (PDF / Excel: .pdf, .xls, .xlsx, .ods)',
'Warning'
);
return false;
}
//form submit url;
let url = `<?php echo base_url('claim_mis/upload'); ?>`;
// Show loading state
var submitButton = $('#claim_mis_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
$('#claim-mis-upload-form')[0].reset();
$('.close').click();
window.location.reload();
},
error: function(xhr, status, error) {
// Handle error response
console.error('Upload failed:', error);
console.error('Unexpected error:', xhr.responseText);
if (xhr.status === 400) {
let response = JSON.parse(xhr.responseText);
let errorMessages = "";
let seenMessages = []; // Array to store unique messages
if (response.errors) {
$.each(response.errors, function (field, message) {
if (!seenMessages.includes(message)) {
errorMessages += `• ${message}<br>`;
seenMessages.push(message); // Mark this message as "seen"
}
});
toastr.error(errorMessages, 'Validation Error', { "allowHtml": true });
} else {
toastr.warning(response.message || 'Validation failed', 'Warning');
}
} else if (xhr.status === 403) {
let response = JSON.parse(xhr.responseText);
toastr.error(response.message, 'Security Policy');
} else if (xhr.status === 500) {
toastr.error('Something went wrong . Please try again later.', 'Server Error');
} else {
toastr.error('An unexpected error occurred. Please try again later.', 'Error');
}
},
complete: function() {
// Reset button state
submitButton.prop('disabled', false).text(originalText);
}
});
});
$('#client_id').on('change', function(){
let client_id = $(this).val();
if(policyListByClient != '') {
console.log(policyListByClient[client_id]);
let data = policyListByClient[client_id];
appendPolicies(data);
}
})
$('#client_policy_id').on('change', function(){
let tpa_id = $(this).find(':selected').data('tpaid');
console.log('tpa_id', tpa_id);
if(tpa_id){
$('#tpa_id').val(tpa_id);
}else{
$('#tpa_id').val('');
}
})
});
// 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 openDumpUploadModal() {
var myModal = new bootstrap.Modal(document.getElementById('claim-mis-file-upload-modal'));
myModal.show();
}
function getClientAndBranchAndPolicy() {
$.ajax({
url: '<?= base_url("/util/getClientAndBranchAndPolicy") ?>',
type: "GET",
dataType: 'json',
success: function(res) {
console.log('getClientAndBranchAndPolicy', res);
if (res.status == true) {
policyListByClient = res.policyListByClient;
client_list = res.client_data;
appendClients(res.client_data);
} else {
console.log('No data found');
}
},
error: function(xhr, status, error) {
console.error(xhr.responseText);
console.error(status, error);
}
});
}
function appendClients(data) {
$('#client_id').empty();
$('#client_id').append($('<option>', {
value: '',
text: 'Select Client'
}));
$.each(data, function(index, item) {
if (item.client_policy_count > 0) {
var option = $('<option>', {
value: item.id,
text: item.client_name
});
$('#client_id').append(option);
}
});
}
function appendPolicies(data) {
$('#client_policy_id').empty();
$('#client_policy_id').append($('<option>', {
value: '',
text: 'Select Policy',
}));
$.each(data, function(index, item) {
var option = $('<option>', {
value: item.id,
text: item.policy_type + '-' + item.policy_no,
'data-tpaid': item.id,
});
$('#client_policy_id').append(option);
});
}
</script>

View File

@ -57,7 +57,7 @@
<td>Get Branch Wise Employee Data</td> <td>Get Branch Wise Employee Data</td>
<td><?= base_url("getClientBranchEmpData") ?></td> <td><?= base_url("getClientBranchEmpData") ?></td>
</tr> </tr>
</table> </table>-->
<!-- Enter Token Section --> <!-- Enter Token Section -->

View File

@ -81,7 +81,7 @@ input:checked + .slider:before {
style="border-radius:25px; border:1px solid #00999E;padding:10px;color:#00999E;" style="border-radius:25px; border:1px solid #00999E;padding:10px;color:#00999E;"
alt="avatar"/> alt="avatar"/>
<span style="margin-bottom:5px;"> <span style="margin-bottom:5px;">
<input type="file" name="client_logo" id="client_logo" accept="image/*" onchange="PreviewImage();"><br> <input type="file" name="client_logo" id="client_logo" accept=".jpg,.jpeg,.png" onchange="PreviewImage();"><br>
<i class="text">( Image dimensions 100 x 100 pixels and size of 200KB. )</i> <i class="text">( Image dimensions 100 x 100 pixels and size of 200KB. )</i>
</span> </span>
<br> <br>
@ -142,6 +142,32 @@ input:checked + .slider:before {
</select> </select>
</div> </div>
<div class="form-group col-md-4">
<label>HR File Processed By <span class="text-danger">*</span></label>
<div class="d-flex align-items-center">
<div class="form-check form-check-inline mb-0" style="margin-right: -356px;">
<input class="form-check-input"
type="radio"
name="hr_file_processed_by"
id="hr_processed"
value="1" <?php echo(isset($client['hr_file_processed_by']) && $client['hr_file_processed_by'] == 1) ? 'checked' : '' ?>>
<label class="form-check-label" for="hr_processed">HR</label>
</div>
<div class="form-check form-check-inline mb-0">
<input class="form-check-input"
type="radio"
name="hr_file_processed_by"
id="account_manager_processed"
value="2"
<?php echo(isset($client['hr_file_processed_by']) && $client['hr_file_processed_by'] == 2) ? 'checked' : '' ?>>
<label class="form-check-label" for="account_manager_processed">Account Manager</label>
</div>
</div>
</div>
</div> </div>
<hr> <hr>
</div> </div>
@ -298,7 +324,7 @@ input:checked + .slider:before {
$.each(res.data, function (index, item) { $.each(res.data, function (index, item) {
var row = `<tr> var row = `<tr>
<td> ${item.file_name}</td> <td> ${item.file_name}</td>
<td id="form_${item.id}" style=""><form class="ajax" ><input class="file-input__input" type="file" name="file_name"> <td id="form_${item.id}" style=""><form class="ajax" ><input class="file-input__input" type="file" name="file_name" accept=".jpg,.jpeg,.png">
<input type="hidden" class="form-control" value="<?= csrf_hash() ?>" name="<?= csrf_token() ?>" /> <input type="hidden" class="form-control" value="<?= csrf_hash() ?>" name="<?= csrf_token() ?>" />
<input type="hidden" class="form-control" value="${item.id}" name="kyc_doc_type_id" /> <input type="hidden" class="form-control" value="${item.id}" name="kyc_doc_type_id" />
<input type="hidden" name="client_id" id="id_for_kyc_file" value="${client_id_for_file}"/> <input type="hidden" name="client_id" id="id_for_kyc_file" value="${client_id_for_file}"/>
@ -323,12 +349,30 @@ input:checked + .slider:before {
$('.loader').fadeOut(); $('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow'); $('.loader-mask').delay(350).fadeOut('slow');
$submitButton.prop('disabled', false); $submitButton.prop('disabled', false);
if (xhr.status === 404) { if (xhr.status === 400) {
let response = JSON.parse(xhr.responseText);
let errorMessages = "";
let seenMessages = []; // Array to store unique messages
if (response.errors) {
$.each(response.errors, function (field, message) {
if (!seenMessages.includes(message)) {
errorMessages += `• ${message}<br>`;
seenMessages.push(message); // Mark this message as "seen"
}
});
toastr.error(errorMessages, 'Validation Error', { "allowHtml": true });
} else {
toastr.warning(response.message || 'Validation failed', 'Warning');
}
} else if (xhr.status === 403) {
let response = JSON.parse(xhr.responseText);
toastr.error(response.message, 'Security Policy');
} else if (xhr.status === 404) {
toastr.warning('Resource not found', 'Warning'); toastr.warning('Resource not found', 'Warning');
} else if (xhr.status === 500) { } else if (xhr.status === 500) {
toastr.warning('Internal server error', 'Warning'); toastr.error('Something went wrong . Please try again later.', 'Server Error');
} else { } else {
toastr.warning('Unknown error occurred', 'Warning'); toastr.error('An unexpected error occurred. Please try again later.', 'Error');
} }
}, 1000); }, 1000);
} }

View File

@ -44,6 +44,69 @@
cursor: pointer; cursor: pointer;
} }
</style> </style>
<style>
.switch-branch-contact {
position: relative;
display: inline-block;
width: 54px;
height: 34px;
}
.switch-branch-contact input {
opacity: 0;
width: 0;
height: 0;
}
.slider-branch-contact {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider-branch-contact:before {
position: absolute;
content: "";
height: 19px;
width: 19px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider-branch-contact {
background-color: #00999E;
}
input:focus + .slider-branch-contact {
box-shadow: 0 0 1px #00999E;
}
input:checked + .slider-branch-contact:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */
.slider-branch-contact.round-branch-contact {
border-radius: 34px;
}
.slider-branch-contact.round-branch-contact:before {
border-radius: 50%;
}
</style>
<div class="tab-pane fade" id="branch-tab"> <div class="tab-pane fade" id="branch-tab">
<input type="hidden" id="client_id_for_client_branch" value="<?= isset($client['id']) ? $client['id'] : '' ?>" /> <input type="hidden" id="client_id_for_client_branch" value="<?= isset($client['id']) ? $client['id'] : '' ?>" />
@ -162,12 +225,12 @@
</select> </select>
</div> </div>
<div class="form-group col-md-4"> <div class="form-group col-md-4">
<label class="switch" style="position: relative;top: 43px;left: 20px;"> <label class="switch-branch-contact" style="position: relative;top: 43px;left: 20px;">
<input id="sez" type="checkbox" name="sez"> <input id="sez" type="checkbox" name="sez">
<span class="slider round" style="height: 27px;"></span> <span class="slider-branch-contact round-branch-contact" style="height: 27px;"></span>
</label> </label>
<label for="inception_type" style="position: relative;bottom: 5px;left: 85px;">Enable SEZ</label> <label for="sez" style="position: relative;bottom: 5px;left: 85px;">Enable SEZ</label>
</div> </div>
</div> </div>
@ -495,6 +558,31 @@ $("#branch_form").submit(function(event) {
if(xhr.status === 409){ if(xhr.status === 409){
alert('The Current Branch is Already Existing..!!'); alert('The Current Branch is Already Existing..!!');
} }
else if (xhr.status === 400) {
let response = JSON.parse(xhr.responseText);
let errorMessages = "";
let seenMessages = []; // Array to store unique messages
if (response.errors) {
$.each(response.errors, function (field, message) {
// Only add the message if it hasn't been seen before
if (!seenMessages.includes(message)) {
errorMessages += `• ${message}<br>`;
seenMessages.push(message); // Mark this message as "seen"
}
});
toastr.error(errorMessages, 'Validation Error', { "allowHtml": true });
} else {
toastr.warning(response.message || 'Validation failed', 'Warning');
}
} else if (xhr.status === 403) {
let response = JSON.parse(xhr.responseText);
toastr.error(response.message, 'Security Policy');
} else if (xhr.status === 500) {
toastr.error('Something went wrong . Please try again later.', 'Server Error');
} else {
toastr.error('An unexpected error occurred. Please try again later.', 'Error');
}
}, 300); }, 300);
}, },
complete: function() { complete: function() {
@ -967,7 +1055,7 @@ function validateInput(input, table, field, submitButId){
checkDuplicateTableFieldValue(table, field, value, function(isDuplicate) { checkDuplicateTableFieldValue(table, field, value, function(isDuplicate) {
if (isDuplicate) { if (isDuplicate) {
toastr.warning(message, 'WARNING'); toastr.warning(message, 'Warning');
// $(input).val('') // $(input).val('')
$('#' + submitButId).prop('disabled', true); $('#' + submitButId).prop('disabled', true);
} else{ } else{
@ -1003,7 +1091,7 @@ function validateDuplicateByClientBranch(input, field, submitButId) {
if (isLocalDuplicate) { if (isLocalDuplicate) {
console.log(`r u n Local`); console.log(`r u n Local`);
console.log(`duplicate found for ${field}`); console.log(`duplicate found for ${field}`);
toastr.warning(message, 'WARNING'); toastr.warning(message, 'Warning');
$('#' + submitButId).prop('disabled', true); $('#' + submitButId).prop('disabled', true);
return; return;
} }
@ -1030,7 +1118,7 @@ function validateDuplicateByClientBranch(input, field, submitButId) {
if (response.isDuplicate) { if (response.isDuplicate) {
console.log(`r u n Server`); console.log(`r u n Server`);
console.log(`duplicate found for ${field}`); console.log(`duplicate found for ${field}`);
toastr.warning(message, 'WARNING'); toastr.warning(message, 'Warning');
$('#' + submitButId).prop('disabled', true); $('#' + submitButId).prop('disabled', true);
} else { } else {
console.log(`No duplicate for ${field}`); console.log(`No duplicate for ${field}`);
@ -1075,13 +1163,13 @@ function checkAllFieldsValid(submitButId) {
$('#' + submitButId).prop('disabled', true); $('#' + submitButId).prop('disabled', true);
// show correct message based on what’s duplicated // show correct message based on what’s duplicated
if (emailDuplicates && mobileDuplicates) { if (emailDuplicates && mobileDuplicates) {
toastr.warning("Email and Mobile values are duplicate!", "WARNING"); toastr.warning("Email and Mobile values are duplicate!", "Warning");
console.log('Both Email and Mobile duplicates'); console.log('Both Email and Mobile duplicates');
} else if (emailDuplicates) { } else if (emailDuplicates) {
toastr.warning("Email duplicate!", "WARNING"); toastr.warning("Email duplicate!", "Warning");
console.log('Cross Check Email duplicates'); console.log('Cross Check Email duplicates');
} else if (mobileDuplicates) { } else if (mobileDuplicates) {
toastr.warning("Mobile duplicate!", "WARNING"); toastr.warning("Mobile duplicate!", "Warning");
console.log('Cross Check Mobile duplicates'); console.log('Cross Check Mobile duplicates');
} }
console.log(`btn Dis - true`); console.log(`btn Dis - true`);
@ -1127,9 +1215,9 @@ function removeLevelContacts(id){
console.log('Data fetched successfully:', response); console.log('Data fetched successfully:', response);
if (response.status == true) { if (response.status == true) {
toastr.success(response.message, 'SUCCESS'); toastr.success(response.message, 'Success');
} else { } else {
toastr.warning(response.message, 'WARNING'); toastr.warning(response.message, 'Warning');
} }
}, function(xhr, status, error) { }, function(xhr, status, error) {

View File

@ -157,7 +157,7 @@
$('#tbody').append(res.data); $('#tbody').append(res.data);
toastr.success('File uploaded successfully', 'Success'); toastr.success('File uploaded successfully', 'Success');
}else{ }else{
toastr.warning('File uploaded failed', 'WARNING'); toastr.warning('File uploaded failed', 'Warning');
} }
}, },
error: function (xhr, status, error) { error: function (xhr, status, error) {
@ -165,7 +165,32 @@
console.error(status, error); console.error(status, error);
$('.loader').fadeOut(); $('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow'); $('.loader-mask').delay(350).fadeOut('slow');
toastr.warning('Something Wrong!', 'warning'); if (xhr.status === 400) {
let response = JSON.parse(xhr.responseText);
let errorMessages = "";
let seenMessages = []; // Array to store unique messages
if (response.errors) {
$.each(response.errors, function (field, message) {
if (!seenMessages.includes(message)) {
errorMessages += `• ${message}<br>`;
seenMessages.push(message); // Mark this message as "seen"
}
});
toastr.error(errorMessages, 'Validation Error', { "allowHtml": true });
} else {
toastr.warning(response.message || 'Validation failed', 'Warning');
}
} else if (xhr.status === 403) {
let response = JSON.parse(xhr.responseText);
toastr.error(response.message, 'Security Policy');
} else if (xhr.status === 404) {
toastr.warning('Resource not found', 'Warning');
} else if (xhr.status === 500) {
toastr.error('Something went wrong . Please try again later.', 'Server Error');
} else {
toastr.error('An unexpected error occurred. Please try again later.', 'Error');
}
} }
}); });
}); });
@ -211,7 +236,7 @@
$('#other_docs').append(res.data); $('#other_docs').append(res.data);
toastr.success('File uploaded successfully', 'Success'); toastr.success('File uploaded successfully', 'Success');
}else{ }else{
toastr.warning('File uploaded failed', 'WARNING'); toastr.warning('File uploaded failed', 'Warning');
} }
$('#kyc_form').trigger('reset'); $('#kyc_form').trigger('reset');
@ -221,7 +246,31 @@
console.error(status, error); console.error(status, error);
$('.loader').fadeOut(); $('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow'); $('.loader-mask').delay(350).fadeOut('slow');
toastr.warning('Something Wrong!', 'warning'); if (xhr.status === 400) {
let response = JSON.parse(xhr.responseText);
let errorMessages = "";
let seenMessages = []; // Array to store unique messages
if (response.errors) {
$.each(response.errors, function (field, message) {
if (!seenMessages.includes(message)) {
errorMessages += `• ${message}<br>`;
seenMessages.push(message); // Mark this message as "seen"
}
});
toastr.error(errorMessages, 'Validation Error', { "allowHtml": true });
} else {
toastr.warning(response.message || 'Validation failed', 'Warning');
}
} else if (xhr.status === 403) {
let response = JSON.parse(xhr.responseText);
toastr.error(response.message, 'Security Policy');
} else if (xhr.status === 404) {
toastr.warning('Resource not found', 'Warning');
} else if (xhr.status === 500) {
toastr.error('Something went wrong . Please try again later.', 'Server Error');
} else {
toastr.error('An unexpected error occurred. Please try again later.', 'Error');
}
} }
}); });
@ -304,7 +353,8 @@
<td>${item.file_name}</td> <td>${item.file_name}</td>
<td id="form_${item.id}"> <td id="form_${item.id}">
<form class="ajax"> <form class="ajax">
<input class="file-input__input" type="file" name="file_name"> <input class="file-input__input" type="file" name="file_name"
accept=".pdf,.jpg,.jpeg,.png">
<input type="hidden" class="form-control" value="<?= csrf_hash() ?>" name="<?= csrf_token() ?>"> <input type="hidden" class="form-control" value="<?= csrf_hash() ?>" name="<?= csrf_token() ?>">
<input type="hidden" class="form-control" value="${item.id}" name="kyc_doc_type_id"> <input type="hidden" class="form-control" value="${item.id}" name="kyc_doc_type_id">
<input type="hidden" name="client_id" value="${client_id}"> <input type="hidden" name="client_id" value="${client_id}">

View File

@ -36,6 +36,7 @@
<div class="form-group col-md-3 file-input-group"> <div class="form-group col-md-3 file-input-group">
<label for="file_input">Browser File<span class="text-danger">*</span></label> <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 <input type="file" class="form-control file-input" id="kyc_docs_file" name="file_name" required
accept=".pdf,.jpg,.jpeg,.png"
style="box-shadow: none !important; outline: none !important; border: none; height: unset !important;padding: 0px !important;background: transparent !important;"> style="box-shadow: none !important; outline: none !important; border: none; height: unset !important;padding: 0px !important;background: transparent !important;">
</div> </div>
@ -345,7 +346,7 @@
} }
// Invalid format // Invalid format
toastr.warning('Invalid file format. Only PDF or Image files are allowed.', 'WARNING!'); toastr.warning('Invalid file format. Only PDF or Image files are allowed.', 'Warning');
$(fileInput).val(''); // clear file $(fileInput).val(''); // clear file
return false; // Invalid return false; // Invalid
} }

View File

@ -4,7 +4,7 @@
<!-- <td><?= $index + 1; ?></td> --> <!-- <td><?= $index + 1; ?></td> -->
<td><?= esc($item['file_name']); ?></td> <td><?= esc($item['file_name']); ?></td>
<td><?= esc($item['other_docs_name']); ?></td> <td><?= esc($item['other_docs_name']); ?></td>
<td><a id="download_<?= esc($item['id']); ?>" data-id="<?= esc($item['id']); ?>" class="mdi mdi-download" style="font-size:18px;" download></a></td> <td><a id="download_<?= esc($item['id']); ?>" data-id="<?= esc($item['id']); ?>" class="mdi mdi-download" style="font-size:18px;" download title="Download file"></a></td>
</tr> </tr>
<?php endforeach; ?> <?php endforeach; ?>
<?php else: ?> <?php else: ?>

View File

@ -7,7 +7,7 @@
<?php if(empty($item['upload_doc_name'])) { ?> <?php if(empty($item['upload_doc_name'])) { ?>
<td id="form_<?= esc($item['id']); ?>"> <td id="form_<?= esc($item['id']); ?>">
<form class="ajax" enctype="multipart/form-data" method="post"> <form class="ajax" enctype="multipart/form-data" method="post">
<input class="file-input__input" type="file" name="file_name"> <input class="file-input__input" type="file" name="file_name" accept=".pdf,.jpg,.jpeg,.png">
<input type="hidden" class="form-control" value="<?= csrf_hash() ?>" name="<?= csrf_token() ?>"> <input type="hidden" class="form-control" value="<?= csrf_hash() ?>" name="<?= csrf_token() ?>">
<input type="hidden" class="form-control" value="<?= esc($item['id']); ?>" name="kyc_doc_type_id"> <input type="hidden" class="form-control" value="<?= esc($item['id']); ?>" name="kyc_doc_type_id">
<input type="hidden" name="client_id" value="<?= esc($client_id); ?>"> <input type="hidden" name="client_id" value="<?= esc($client_id); ?>">

View File

@ -48,6 +48,7 @@
name="file_name" name="file_name"
id="kyc_docs_file_<?= $value['id'] ?>" id="kyc_docs_file_<?= $value['id'] ?>"
class="form-control edit-file-input" class="form-control edit-file-input"
accept=".pdf,.jpg,.jpeg,.png"
style="box-shadow:none!important; outline:none!important; border:none; height:unset!important;padding: 0px !important;background: transparent !important;"> style="box-shadow:none!important; outline:none!important; border:none; height:unset!important;padding: 0px !important;background: transparent !important;">
</div> </div>

View File

@ -102,7 +102,7 @@ table.dataTable thead th {
<tr > <tr >
<td class="text-center"><?=$index+1?></td> <td class="text-center"><?=$index+1?></td>
<td class="client_info" data-id="<?php echo $row->id; ?>"><?php echo $row->client_name; ?> ( <?php echo $row->short_name; ?> ) </td> <td class="client_info" data-id="<?php echo $row->id; ?>"><?php echo $row->client_name; ?> ( <?php echo $row->short_name; ?> ) </td>
<td> <!-- <td>
<?php $account_managers = ''; ?> <?php $account_managers = ''; ?>
<?php foreach ($client_rm as $client): ?> <?php foreach ($client_rm as $client): ?>
<?php if ($client->client_id == $row->id): ?> <?php if ($client->client_id == $row->id): ?>
@ -112,6 +112,9 @@ table.dataTable thead th {
<?php <?php
$account_managers = rtrim($account_managers, ', '); $account_managers = rtrim($account_managers, ', ');
echo $account_managers !== '' ? $account_managers : 'N/A'; ?> echo $account_managers !== '' ? $account_managers : 'N/A'; ?>
</td> -->
<td>
<?= $row->account_managers ?>
</td> </td>
<td> <td>
<div class="btn-group dropdown"> <div class="btn-group dropdown">
@ -375,26 +378,28 @@ $(document).ready(function()
</span> </span>
</span> </span>
`); `);
$('#toggleButtons').on('change', function() { $('#toggleButtons').on('change', function() {
let type = $(this).is(':checked') ? 1 : 2; let type = $(this).is(':checked') ? 1 : 2;
// $('div.col-6 h4').text(
// $(this).is(':checked')
// ? "GC Client List"
// : "RC Client List"
// );
let url = '<?= base_url('client/typeList/') ?>' + type; let url = '<?= base_url('client/typeList/') ?>' + type;
$('.loader').fadeIn(); // Show loader during AJAX
$.ajax({ $.ajax({
url: url, url: url,
method: 'GET', method: 'GET',
success: function(response) { success: function(response) {
if (response.status === "success" && Array.isArray(response.data)) { $('.loader').fadeOut();
// Pass response.data directly to the function
if (response.status === "success") {
renderRows(response.data); renderRows(response.data);
} else { } else {
renderRows([]); // If the structure is slightly different, pass the whole object
renderRows(response);
} }
}, },
error: function(xhr, status, error) { error: function(xhr, status, error) {
$('.loader').fadeOut();
console.error("Error loading:", error); console.error("Error loading:", error);
renderRows([]); renderRows([]);
} }
@ -403,25 +408,25 @@ $(document).ready(function()
}) })
function renderRows(data) { function renderRows(incomingData) {
table.clear();
if (Array.isArray(data) && data.length) {
data.forEach((row, index) => {
let clientrm = <?= json_encode($client_rm) ?>;
let account_managers = "";
clientrm.forEach(client => { let actualList = [];
if (client.client_id == row.id) { if (incomingData && incomingData.clientList) {
account_managers += client.account_manager + ", "; actualList = incomingData.clientList;
} else if (Array.isArray(incomingData)) {
actualList = incomingData;
} }
});
account_managers = account_managers.replace(/,\s*$/, "");
if (account_managers === "") account_managers = "N/A"; table.clear();
if (actualList.length > 0) {
actualList.forEach((row, index) => {
let rowData = [ let rowData = [
index + 1, index + 1,
`<span class="client_info" data-id="${row.id}">${row.client_name} (${row.short_name})</span>`, `<span class="client_info" data-id="${row.id}">${row.client_name} (${row.short_name})</span>`,
account_managers, row.account_managers || "N/A",
`<div class="btn-group dropdown"> `<div class="btn-group dropdown">
<a href="javascript:void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm" data-toggle="dropdown"> <a href="javascript:void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm" data-toggle="dropdown">
<i class="mdi mdi-dots-horizontal"></i> <i class="mdi mdi-dots-horizontal"></i>
@ -484,7 +489,7 @@ $(document).ready(function()
// if(res){ // if(res){
// if (res.status == true) { // if (res.status == true) {
// toastr.success('Client removed successfully.', 'success'); // toastr.success('Client removed successfully.', 'Success');
// location.reload(); // location.reload();
// } else { // } else {
// Swal.fire({ // Swal.fire({
@ -492,7 +497,7 @@ $(document).ready(function()
// text: res.message, // text: res.message,
// icon: "warning" // icon: "warning"
// }); // });
// // toastr.warning(res.message, 'warning'); // // toastr.warning(res.message, 'Warning');
// } // }
// } // }
// }, // },
@ -549,15 +554,15 @@ function removeClient(element)
$('.loader-mask').delay(350).fadeOut('slow'); $('.loader-mask').delay(350).fadeOut('slow');
if (res.status == true) { if (res.status == true) {
toastr.success(res.message, 'success'); toastr.success(res.message, 'Success');
location.reload(); location.reload();
} else { } else {
Swal.fire({ Swal.fire({
title: "warning!", title: "Warning!",
text: res.message, text: res.message,
icon: "warning" icon: "warning"
}); });
// toastr.warning(res.message, 'warning'); // toastr.warning(res.message, 'Warning');
} }
}, },
error: function (xhr, status, error) { error: function (xhr, status, error) {
@ -645,11 +650,15 @@ function featchClient(){
$('.loader-mask').delay(350).fadeOut('slow'); $('.loader-mask').delay(350).fadeOut('slow');
if(res.status == true){ if(res.status == true){
let client_url = '<?= base_url('client/list/') ?>' + res.client_id + '?client_policy_id=' + res.client_policy_id+'#police-tab'; let client_url = '<?= base_url('client/list/') ?>'
toastr.success(res.message, 'SUCCESS') + res.client_id
+ '?cd_amt=' + (res.cd_amount ?? 0)
+ '&client_policy_id=' + res.client_policy_id
+ '#police-tab';
toastr.success(res.message, 'Success')
window.location.href = client_url window.location.href = client_url
}else{ }else{
toastr.success(res.message, 'WARNING') toastr.warning(res.message, 'Warning')
} }
$('.close').click() $('.close').click()

View File

@ -464,7 +464,7 @@
if (check_client_id[0].value == '' || check_client_id[0].value == null || check_client_id[0].value == 0) { if (check_client_id[0].value == '' || check_client_id[0].value == null || check_client_id[0].value == 0) {
$('#btnBranchAdd').hide(); $('#btnBranchAdd').hide();
toastr.warning('Please Add the Client!', 'warning', { toastr.warning('Please Add the Client!', 'Warning', {
timeOut: 2000 timeOut: 2000
}); });
} else { } else {
@ -481,7 +481,7 @@
if (check_client_id[0].value == '' || check_client_id[0].value == null || check_client_id[0].value == 0) { if (check_client_id[0].value == '' || check_client_id[0].value == null || check_client_id[0].value == 0) {
$('#relation_form').hide(); $('#relation_form').hide();
toastr.warning('Please Add the Client!', 'warning', { toastr.warning('Please Add the Client!', 'Warning', {
timeOut: 2000 timeOut: 2000
}); });
} else { } else {
@ -495,7 +495,7 @@
if (check_client_id == '' || check_client_id == null || check_client_id == 0) { if (check_client_id == '' || check_client_id == null || check_client_id == 0) {
$('#BtnAdd').hide(); $('#BtnAdd').hide();
toastr.warning('Please Add the Client!', 'warning', { toastr.warning('Please Add the Client!', 'Warning', {
timeOut: 2000 timeOut: 2000
}); });
} else { } else {
@ -512,7 +512,7 @@
if (check_client_id[0].value == '' || check_client_id[0].value == null || check_client_id[0].value == 0) { if (check_client_id[0].value == '' || check_client_id[0].value == null || check_client_id[0].value == 0) {
$('#btnBranchAdd').hide(); $('#btnBranchAdd').hide();
toastr.warning('Please Add the Client!', 'warning', { toastr.warning('Please Add the Client!', 'Warning', {
timeOut: 2000 timeOut: 2000
}); });
} else { } else {
@ -529,7 +529,7 @@
if (check_client_id[0].value == '' || check_client_id[0].value == null || check_client_id[0].value == 0) { if (check_client_id[0].value == '' || check_client_id[0].value == null || check_client_id[0].value == 0) {
$('#notification-tab').hide(); $('#notification-tab').hide();
toastr.warning('Please Add the Client!', 'warning', { toastr.warning('Please Add the Client!', 'Warning', {
timeOut: 2000 timeOut: 2000
}); });
} else { } else {
@ -719,9 +719,9 @@
console.log('Data fetched successfully:', response); console.log('Data fetched successfully:', response);
if (response.status === true) { if (response.status === true) {
toastr.success(response.message, 'SUCCESS'); toastr.success(response.message, 'Success');
} else { } else {
console.error(response.message, 'WARNING'); console.error(response.message, 'Warning');
} }
}, function(xhr, status, error) { }, function(xhr, status, error) {
console.error('--- AJAX Error Details ---'); console.error('--- AJAX Error Details ---');
@ -813,7 +813,7 @@
if (response.status === true) { if (response.status === true) {
$('#hr_access_append_area').empty(); $('#hr_access_append_area').empty();
$('#hr_access_append_area').append(response.data) $('#hr_access_append_area').append(response.data)
toastr.success(response.message, 'SUCCESS'); toastr.success(response.message, 'Success');
} else { } else {
console.error(response.message, 'WARNING'); console.error(response.message, 'WARNING');
} }

View File

@ -59,9 +59,9 @@ $(document).ready(function() {
$('.loader').fadeOut(); $('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow'); $('.loader-mask').delay(350).fadeOut('slow');
if (res.status == true) { if (res.status == true) {
toastr.success(res.message, 'SUCCESS'); toastr.success(res.message, 'Success');
} else { } else {
toastr.warning(res.message, 'WARNING'); toastr.warning(res.message, 'Warning');
} }
}, },

Some files were not shown because too many files have changed in this diff Show More