diff --git a/.gitignore b/.gitignore
index a599a01e..e0e9251f 100755
--- a/.gitignore
+++ b/.gitignore
@@ -33,3 +33,5 @@ build/
composer.lock
.env
.phpunit*
+phpqueue.sh
+
diff --git a/README.md b/README.md
index b56458c2..0a4cf0dd 100755
--- a/README.md
+++ b/README.md
@@ -9,3 +9,5 @@ From command propmt run the following cmds
Run speeific method
`php vendor/bin/phpunit tests\unit\PremiumCalculationTest.php --filter testPremiumCalculationWithPrimaryRackRateAndAdditionalRackRate`
+
+Test Comments
\ No newline at end of file
diff --git a/app/Config/Constants.php b/app/Config/Constants.php
index fb86b921..eee4bdcd 100755
--- a/app/Config/Constants.php
+++ b/app/Config/Constants.php
@@ -103,6 +103,8 @@ define('BUSINESS_TEAM_ID', '3');
define('FINANCE_TEAM_ID', '4');
define('SALES_TEAM_ID', '5');
define('MANAGEMENT_TEAM_ID', '6');
+define('BUSINESS_SUPPORT_TEAM_ID', '7');
+define('POS_TEAM_ID', '8');
/**
* @User Teams Constant
diff --git a/app/Config/Database.php b/app/Config/Database.php
index 388b1b03..1a43584f 100755
--- a/app/Config/Database.php
+++ b/app/Config/Database.php
@@ -45,6 +45,9 @@ class Database extends Config
'numberNative' => false,
];
+
+ public array $book_stack = [];
+
/**
* This database connection is used when
* running PHPUnit database tests.
@@ -75,6 +78,29 @@ class Database extends Config
{
parent::__construct();
+ // Initialize book_stack configuration with environment variables
+ $this->book_stack = [
+ 'DSN' => '',
+ 'hostname' => getenv('bookStack_hostname'),
+ 'username' => getenv('bookStack_username'),
+ 'password' => getenv('bookStack_password'),
+ 'database' => getenv('bookStack_database'),
+ 'DBDriver' => 'MySQLi',
+ 'DBPrefix' => '',
+ 'pConnect' => false,
+ 'DBDebug' => true,
+ 'charset' => 'utf8',
+ 'DBCollat' => 'utf8_general_ci',
+ 'swapPre' => '',
+ 'encrypt' => false,
+ 'compress' => false,
+ 'strictOn' => false,
+ 'failover' => [],
+ 'port' => 3306,
+ 'foreignKeys' => true,
+ 'busyTimeout' => 1000,
+ ];
+
// Ensure that we always set the database group to 'tests' if
// we are currently running an automated test suite, so that
// we don't overwrite live data on accident.
@@ -82,4 +108,5 @@ class Database extends Config
$this->defaultGroup = 'tests';
}
}
+
}
diff --git a/app/Config/Filters.php b/app/Config/Filters.php
index 0855ec3e..2cf9a260 100755
--- a/app/Config/Filters.php
+++ b/app/Config/Filters.php
@@ -12,6 +12,7 @@ use CodeIgniter\Filters\SecureHeaders;
use App\Filters\AuthMVC;
use App\Filters\HttpRequestLog;
use App\Filters\CloseDbConnection;
+use App\Filters\AuthClientApi;
use App\Filters\AuthJWT;
@@ -34,6 +35,7 @@ class Filters extends BaseConfig
'authMVC' => AuthMVC::class,
'HttpRequestLog' => HttpRequestLog::class,
'authJWT' => AuthJWT::class,
+ 'AuthClientApi' => AuthClientApi::class,
'CloseDbConnection' => CloseDbConnection::class
];
diff --git a/app/Config/Routes.php b/app/Config/Routes.php
index 0318acfd..b12373ad 100755
--- a/app/Config/Routes.php
+++ b/app/Config/Routes.php
@@ -32,6 +32,7 @@ $routes->get("sendextraparam", "ClientController::sendextraparam");
$routes->get("updateRenewalData", "ClientController::updateRenewalData");
$routes->get("updateRenewalDataNotExistingClient", "ClientController::updateRenewalDataNotExistingClient");
$routes->get("updateRenewalInsurerData", "ClientController::updateRenewalInsurerData");
+$routes->get("sendMutipleToEmails", "MasterController::sendMutipleToEmails");
// $routes->post("iAgreeForAddOn", "EmployeeRestController::iAgreeForAddOn");
// $routes->get("sendCroneRemainderMail", "DashboardController::sendCroneRemainderMail");
// $routes->post("employeeUpload", "EmployeeRestController::employeeUpload");
@@ -52,6 +53,10 @@ $routes->get('/update-emp-policy-status', 'ClientController::updateEmpAndPolicyS
$routes->get('download-e-card/(:any)', 'EmployeeController::generateIDCardForEmployee/$1');
$routes->get('download-kyc-docs/(:segment)', 'ClientController::downloadKYCDocument/$1');
$routes->get('claim-form-download/(:any)', 'TicketController::downloadClaimForm/$1');
+$routes->match (['get','post'],"claims-feedback-form/(:any)/(:any)", "TicketController::viewClaimFeedbackForm/$1/$2");
+$routes->match (['get','post'],"claims-feedback-form/(:any)", "TicketController::viewClaimFeedbackForm/$1");
+
+
$routes->group("/user", ["filter" => "authMVC"], function ($routes) {
$routes->post("create", "UserController::create");
@@ -68,6 +73,7 @@ $routes->group("/dashboard", ["filter" => "authMVC"], function ($routes) {
$routes->get('get-notification', 'DashboardController::getDashboardNotifications');
$routes->get('acknowledge-notification/(:segment)', 'DashboardController::acknowledgeMessage/$1');
$routes->get('get-pending-action', 'PendingActionsController::getPendingActions');
+ $routes->post("prepareClaimSearchData","DashboardController::prepareClaimSearchData");
});
$routes->group("/client", ["filter" => "authMVC"], function ($routes) {
@@ -83,6 +89,8 @@ $routes->group("/client", ["filter" => "authMVC"], function ($routes) {
$routes->get('view_deposit/(:num)', 'ClientController::view_Deposit/$1');
$routes->get('createtransaction', 'ClientController::createtransaction');
$routes->post('save_deposit', 'ClientController::saveDeposit');
+ $routes->post("saveApiData", "ClientController::saveApiData");
+ $routes->get("generateToken","ClientController::sendToken");
// $routes->get('view_Deposit/(:num)/(:num)','ClientController/view_Deposit/$1/$2');
$routes->group("notification", ["filter" => "authMVC"], function ($routes) {
@@ -315,8 +323,8 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) {
$routes->get("test_mail", "MasterController::testGmailAPI");
$routes->post("test_mail", "MasterController::testGmailAPI");
$routes->get("check_policy_no/(:any)", "ClientController::check_policy_no/$1");
- $routes->get("get_client_policy_data_using_policy_no/(:any)", "ClientController::get_client_policy_data_using_policy_no/$1");
- $routes->get("get_client_policy_data_using_policy_no_and_endo_no/(:any)", "ClientController::get_client_policy_data_using_policy_no_and_endo_no/$1");
+ $routes->get("get_client_policy_data_using_policy_no", "ClientController::get_client_policy_data_using_policy_no");
+ $routes->get("get_client_policy_data_using_policy_no_and_endo_no", "ClientController::get_client_policy_data_using_policy_no_and_endo_no");
$routes->get("checkInvoiceStatus/(:any)", "PolicyTransactionController::checkInvoiceStatus/$1");
$routes->get("base_policy_for_policy_inception/(:any)", "PolicyTransactionController::getBasePolicy/$1");
$routes->get("sentTestMail/(:any)", "NotificationController::sentTestMail/$1");
@@ -348,12 +356,20 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) {
$routes->get('getTheEmpDataForClaimSearchByMobile/(:any)', 'ClientController::getTheEmpDataForClaimSearchByMobile/$1');
$routes->get('getLeadNonEB/(:any)', 'LeadsController::getLeadNonEB/$1');
$routes->get('getPolicyTypeFields', 'LeadsController::getPolicyTypeFields');
+ $routes->get('removeMultiFile', 'LeadsController::removeMultiFile');
+ $routes->get('removeInstallments', 'LeadsController::removeInstallments');
});
+$routes->post("policy_tranction/sendInstallmentRemainderMail","PolicyTransactionController::sendInstallmentRemainderMail");
+$routes->cli("cli/sendInstallmentRemainderMail","PolicyTransactionController::sendInstallmentRemainderMail");
+
$routes->group("policy_tranction", ["filter" => "authMVC"], function ($routes) {
+ $routes->post("getMoreInfo","PolicyTransactionController::getMoreInfo");
+ $routes->post("saveInstallment","PolicyTransactionController::saveInstallment");
+
$routes->group("inception", ["filter" => "authMVC"], function ($routes) {
- $routes->get("list", "PolicyTransactionController::viewInception");
+ $routes->match(['get', 'post'], 'list', 'PolicyTransactionController::viewInception');
$routes->post("create", "PolicyTransactionController::createInceptionPolicy");
$routes->get("list/(:any)", "PolicyTransactionController::getInceptionDataForEdit/$1");
$routes->get("remove/(:any)", "PolicyTransactionController::removeCDMaster/$1");
@@ -368,7 +384,7 @@ $routes->group("policy_tranction", ["filter" => "authMVC"], function ($routes) {
});
$routes->group("report", ["filter" => "authMVC"], function ($routes) {
- $routes->get("list", "PolicyTransactionController::reportBDS");
+ $routes->match(['get', 'post'],"list", "PolicyTransactionController::reportBDS");
$routes->get("report-varience-list", "PolicyTransactionController::reportVarience");
$routes->get("report-business-list", "PolicyTransactionController::reportBusinessList");
$routes->get("report-finance-list", "PolicyTransactionController::reportFinanceList");
@@ -404,6 +420,7 @@ $routes->group("leads", ["filter" => "authMVC"], function ($routes) {
$routes->group("rfq", ["filter" => "authMVC"], function ($routes) {
$routes->post("create", "LeadsController::createRFQ");
+ $routes->post("savePolicyInfo", "LeadsController::savePolicyInfo");
$routes->post("createQCR", "LeadsController::createQCR");
$routes->get("list/(:any)", "LeadsController::viewRFQ/$1");
$routes->get("nonEB","LeadsController::rfqNonEB");
@@ -431,6 +448,7 @@ $routes->cli('cli/new_gdrive_token', 'GoogleDriveController::generateNewGoogleDr
//crone job
$routes->cli('cli/enrollOpendAndClose', 'DashboardController::updatePolicyEnrollmentStatus');
$routes->cli("cli/sendCroneRemainderMail", "DashboardController::sendCroneRemainderMail");
+$routes->cli('cli/update-emp-policy-status', 'ClientController::updateEmpAndPolicyStatus');
//Employee login api's
$routes->post("/employeeRest/verifyEmployeeNumber", "RestAuthenticationController::verifyEmployeeWithMobileNumber");
@@ -439,6 +457,9 @@ $routes->post("/employeeRest/verifyMpin", "RestAuthenticationController::verifyM
$routes->post("/employeeRest/checkMpin", "RestAuthenticationController::checkMpin");
$routes->post("/employeeRest/verifyEmployeeEmailId", "RestAuthenticationController::verifyEmployeeWithEmailId");
$routes->post("/employeeRest/updateEmpOTP", "RestAuthenticationController::updateEmpOTP");
+$routes->post("/employeeRest/updateEmpMPIN", "RestAuthenticationController::updateEmpMPIN");
+// $routes->post("/employeeRest/saveMpin", "RestAuthenticationController::saveMpin");
+
//HR login api's
$routes->post("/employeeRest/verifyHrWithMobileNumber", "RestAuthenticationController::verifyHrWithMobileNumber");
@@ -461,6 +482,11 @@ $routes->group("/api", ["filter" => "authJWT"], function ($routes) {
$routes->get('get_ticket_data',"EmployeeRestController::get_ticket_data");
});
+$routes->post("employeeRest/saveMpin", "RestAuthenticationController::saveMpin");
+$routes->post("employeeRest/updateMpin", "RestAuthenticationController::updateMpin");
+
+
+
$routes->get("getEmployeePolicy", "EmployeeRestController::getEmployeePolicy");
$routes->get("getAddOnPolicy", "EmployeeRestController::getAddOnPolicy");
$routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) {
@@ -468,8 +494,7 @@ $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) {
$routes->post("getVerifiedUserData", "RestAuthenticationController::getVerifiedUserData");
$routes->post("storeFireBase", "EmployeeRestController::storeFireBase");
- $routes->post("saveMpin", "RestAuthenticationController::saveMpin");
- $routes->post("updateMpin", "RestAuthenticationController::updateMpin");
+ // $routes->post("updateMpin", "RestAuthenticationController::updateMpin");
$routes->post("getChatResponse", "ChatBotController::getChatResponse");
$routes->get("getEmployeeProfile", "EmployeeRestController::getEmployeeProfile");
@@ -502,6 +527,8 @@ $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) {
$routes->get("getEmployeeActiveOrInactivePolicy", "EmployeeRestController::getEmployeeActiveOrInactivePolicy");
$routes->get("getFEContent", "EmployeeRestController::getFEContent");
$routes->get("getAdvertisementImage", "EmployeeRestController::getAdvertisementImage");
+ $routes->get("getWellnessURL", "EmployeeRestController::getWellnessURL");
+
// $routes->post('postDataForTicket',"EmployeeRestController::postDataForTicket");
});
$routes->get("getEmployeeActiveOrInactivePolicy", "EmployeeRestController::getEmployeeActiveOrInactivePolicy");
@@ -514,19 +541,22 @@ $routes->get("getBackToEnrolledDetails", "EmployeeRestController::getBackToEnrol
// Ticketing System End's
-
+$routes->get("autobookstackLogin", "RestAuthenticationController::bookstackLoginToken");
//BDSReports
$routes->group("/bdsReport", ["filter" => "authMVC"], function ($routes) {
$routes->match( ['get', 'post'], 'irba_report','BDSReportController::irba_report');
$routes->get('insurer_wise_data/(:any)','BDSReportController::Insurer_wise_Data/$1');
$routes->get('bap_wise_data/(:any)','BDSReportController::Bap_Wise_Data/$1');
$routes->match( ['get', 'post'], 'renewal_report','BDSReportController::renewalReport');
-
+ $routes->get('getTATReport','BDSReportController::bdsTATReport');
+ $routes->get("getMultiReport/(:any)", "BDSReportController::getMultiReport/$1");
});
//New Tickets
$routes->group("/ticket", ["filter" => "authMVC"], function ($routes) {
$routes->match( ['get', 'post'], 'list','TicketController::ticketList');
+ $routes->get('feedback-list','TicketController::feedbackList');
+ $routes->get('remove','TicketController::removeTicket');
$routes->get('new/(:any)','TicketController::ticket_form/$1');
$routes->post('create','TicketController::createTicket');
$routes->post('update','TicketController::updateTicket');
@@ -538,6 +568,20 @@ $routes->group("/ticket", ["filter" => "authMVC"], function ($routes) {
$routes->match( ['get', 'post'], 'ticket_reports','TicketController::ticketReports');
$routes->post('getPolicyStartDate','TicketController::getPolicyStartDate');
$routes->post("getPoliciesbyEmpID","TicketController::getPoliciesbyEmpID");
+ $routes->post("getMoreInfo","TicketController::getMoreInfo");
// $routes->post('ticket_messages','TicketController::getTicketMessage');
});
+$routes->group("clientApi",["filter" => "AuthClientApi"], function ($routes){
+
+ $routes->post("getPolicyMaster","ClientAPIController::sendPolicyMaster");
+ $routes->post("getEmployeeMaster","ClientAPIController::sendEmpMaster");
+ $routes->post("getClaimMaster","ClientAPIController::sendClaimMaster");
+ // $routes->post("pushData","ClientWebHooksController::sendSample");
+});
+
+$routes->post("dispatchWebhookData/(:any)/(:any)",'ClientWebHooksController::pushData/$1/$2');
+
+
+$routes->post("retrieveWebhookDataEmp","ClientWebHooksController::pullData_emp");
+$routes->post("retrieveWebhookDataClaim","ClientWebHooksController::pullData_claim");
diff --git a/app/Controllers/BDSReportController.php b/app/Controllers/BDSReportController.php
index 54abf46f..c3005aac 100644
--- a/app/Controllers/BDSReportController.php
+++ b/app/Controllers/BDSReportController.php
@@ -33,6 +33,7 @@ class BDSReportController extends AdminController
protected $PTCOShareDetailsModel;
protected $coShareStmtDetailsModel;
protected $policyTypeModel;
+ protected $policyTatReportType;
public function __construct()
{
@@ -46,6 +47,13 @@ class BDSReportController extends AdminController
$this->PTCOShareDetailsModel = new PTCOShareDetailsModel();
$this->coShareStmtDetailsModel = new COShareStmtDetailsModel();
$this->policyTypeModel = new PolicyTypeModel();
+
+
+ $this->policyTatReportType = [
+ '1' => "TAT Band Wise report",
+ '2' => "Account Manger Status Wise Report",
+ '3' => "Account Manger TAT Wise Report"
+ ];
}
// public function Insurer_wise_Data($insurerCategory, $fromDate, $toDate)
@@ -209,7 +217,7 @@ class BDSReportController extends AdminController
$html = view('bds_report_bap_wise_data', $viewData);
return $this->respond(['status' => true, 'html' => $html], 200);
- } else if($report_type == 'bapInsurer'){
+ } else if ($report_type == 'bapInsurer') {
//Condition for BAP Insurer wise date
$category = $category == 'life' ? 1 : 0;
@@ -217,8 +225,7 @@ class BDSReportController extends AdminController
$html = view('irda_bap_insurer_report_list', $viewData);
return $this->respond(['status' => true, 'html' => $html], 200);
-
- }else if($report_type == 'bapClient'){
+ } else if ($report_type == 'bapClient') {
//Condition for BAP Client wise date
$category = $category == 'life' ? 1 : 0;
@@ -226,8 +233,7 @@ class BDSReportController extends AdminController
$html = view('irda_bap_client_report_list', $viewData);
return $this->respond(['status' => true, 'html' => $html], 200);
-
- }else if($report_type == 'client'){
+ } else if ($report_type == 'client') {
//Condition for Client wise date
$category = $category == 'life' ? 1 : 0;
@@ -517,7 +523,7 @@ class BDSReportController extends AdminController
if (!empty($start_date) && !empty($end_date)) {
$fromDate = change_date_format($start_date);
- $toDate = change_date_format($end_date);
+ $toDate = change_date_format($end_date);
}
$this->myLogger->logme('error', 'From date : {fromDate} - To date {toDate} ', ['fromDate' => $fromDate, 'toDate' => $toDate]);
@@ -597,7 +603,7 @@ class BDSReportController extends AdminController
// $db = db_connect();
// $builder = $db->query("
-
+
// select ins.id, ins.name as insurer_name,
// -- Health Policies
@@ -706,7 +712,7 @@ class BDSReportController extends AdminController
// life_premium DESC,
// marine_cargo_premium DESC,
// marine_hull_premium DESC;
-
+
// ");
// // Get the query
@@ -745,7 +751,7 @@ class BDSReportController extends AdminController
// $db = db_connect();
// $builder = $db->query("
-
+
// SELECT
// c.id AS client_id,
// c.client_name,
@@ -808,7 +814,7 @@ class BDSReportController extends AdminController
// life_premium DESC,
// marine_cargo_premium DESC,
// marine_hull_premium DESC
-
+
// ");
// // Get the query
@@ -847,11 +853,11 @@ class BDSReportController extends AdminController
// $db = db_connect();
// $builder = $db->query("
-
+
// select
// c.id as client_id,
// c.client_name,
-
+
// (
// select
// count(policy_transaction.id)
@@ -862,7 +868,7 @@ class BDSReportController extends AdminController
// and policy_transaction.is_active = 1
// ) as policy_count,
-
+
// COALESCE((
// select
// sum(stmt.actual_bp_amt + stmt.actual_tp_amt + stmt.actual_tep_amt) as premium
@@ -873,9 +879,9 @@ class BDSReportController extends AdminController
// and stmt.is_active = 1
// and ptco.is_active = 1
// and pt.is_active = 1
-
+
// ), 0) as premium
-
+
// from clients c
// join policy_transaction on c.id = policy_transaction.client_id AND policy_transaction.policy_issue_date >= '$fromDate' AND policy_transaction.policy_issue_date <= '$toDate'
// join policy_type on policy_transaction.policy_type_id = policy_type.id and policy_type.policy_category = $category
@@ -910,7 +916,6 @@ class BDSReportController extends AdminController
$data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
$data['page_name'] = "Renewal Report";
return $this->loadLayout('renewal_search', $data);
-
} else {
$fromDate = $this->request->getPost('fromDate');
@@ -927,4 +932,224 @@ class BDSReportController extends AdminController
return $this->respond(['status' => true, 'html' => $html], 200);
}
}
+
+ public function bdsTATReport()
+ {
+ $sql = "
+ SELECT
+ tc.TAT_Category,
+ COALESCE(SUM(CASE WHEN subquery.status = 'under_process' THEN 1 ELSE 0 END), 0) AS `Under Process`,
+ COALESCE(SUM(CASE WHEN subquery.status = 'client_pending' THEN 1 ELSE 0 END), 0) AS `Client Pending`,
+ COALESCE(SUM(CASE WHEN subquery.status = 'insurer_pending' THEN 1 ELSE 0 END), 0) AS `Insurer Pending`,
+ COALESCE(SUM(CASE WHEN subquery.status = 'instalment_pending' THEN 1 ELSE 0 END), 0) AS `Instalment Pending`,
+ COALESCE(SUM(CASE WHEN subquery.status = 'co_insurer_pending' THEN 1 ELSE 0 END), 0) AS `Co-Insurer Pending`,
+ COALESCE(SUM(CASE WHEN subquery.status = 'tpa_pending' THEN 1 ELSE 0 END), 0) AS `TPA Pending`,
+ COALESCE(SUM(CASE WHEN subquery.status = 'validated' THEN 1 ELSE 0 END), 0) AS `Validated`,
+ COALESCE(SUM(CASE WHEN subquery.status = 'cancelled' THEN 1 ELSE 0 END), 0) AS `Cancelled`,
+ COALESCE(SUM(CASE WHEN subquery.status = 'completed' THEN 1 ELSE 0 END), 0) AS `Completed`,
+ COALESCE(SUM(CASE WHEN subquery.status = 'lost' THEN 1 ELSE 0 END), 0) AS `Lost` FROM
+ (
+ SELECT 'Above 12 Days' AS TAT_Category
+ UNION ALL
+ SELECT '9-12 Days'
+ UNION ALL
+ SELECT '5-8 Days'
+ UNION ALL
+ SELECT '0-4 Days'
+ ) AS tc
+ LEFT JOIN (
+ SELECT
+ pt.id AS policy_id,
+ ls.status,
+ CASE
+ WHEN DATEDIFF(CURRENT_DATE, pt.created_at) BETWEEN 0 AND 4 THEN '0-4 Days'
+ WHEN DATEDIFF(CURRENT_DATE, pt.created_at) BETWEEN 5 AND 8 THEN '5-8 Days'
+ WHEN DATEDIFF(CURRENT_DATE, pt.created_at) BETWEEN 9 AND 12 THEN '9-12 Days'
+ ELSE 'Above 12 Days'
+ END AS TAT_Category
+ FROM
+ policy_transaction pt
+ LEFT JOIN (
+ SELECT
+ pts1.*
+ FROM
+ policy_transaction_status pts1
+ INNER JOIN (
+ SELECT
+ policy_tran_id,
+ MAX(created_at) AS max_created_at
+ FROM
+ policy_transaction_status
+ WHERE is_active = 1
+ GROUP BY policy_tran_id
+ ) pts2
+ ON pts1.policy_tran_id = pts2.policy_tran_id
+ AND pts1.created_at = pts2.max_created_at
+ WHERE pts1.is_active = 1
+ ) ls
+ ON pt.id = ls.policy_tran_id
+ WHERE pt.is_active = 1
+ ) AS subquery
+ ON tc.TAT_Category = subquery.TAT_Category
+ GROUP BY
+ tc.TAT_Category
+ ORDER BY
+ FIELD(tc.TAT_Category, '0-4 Days', '5-8 Days' , '9-12 Days' , 'Above 12 Days' )
+ ";
+
+ // Run the query
+ $db = \Config\Database::connect();
+ $query = $db->query($sql);
+
+ // Get the result
+ $result = $query->getResultArray();
+ // dd(db_connect()->getLastQuery(),$result);
+ $data['data'] = $result;
+ // dd($data, get_role_id(), ENROLLMENT_TEAM_ID, user_team());
+ // return $this->loadLayout('bds_tat_wise_report', $data);
+
+ return $result;
+ }
+
+ public function accountMangerStatusBDSReport()
+ {
+ $data['page_name'] = "Account Manager BDS Report";
+
+ $sql = "
+ SELECT
+ COALESCE(ACM_Name, 'Total') AS ACM_Name,
+ COALESCE(SUM(CASE WHEN status = 'instalment_pending' THEN 1 ELSE 0 END), 0) AS `Instalment Pending`,
+ COALESCE(SUM(CASE WHEN status = 'under_process' THEN 1 ELSE 0 END), 0) AS `Under Process`,
+ COALESCE(SUM(CASE WHEN status = 'client_pending' THEN 1 ELSE 0 END), 0) AS `Client Pending`,
+ COALESCE(SUM(CASE WHEN status = 'co_insurer_pending' THEN 1 ELSE 0 END), 0) AS `Co Insurer Pending`,
+ COALESCE(SUM(CASE WHEN status = 'tpa_pending' THEN 1 ELSE 0 END), 0) AS `TPA Pending`,
+ COALESCE(SUM(CASE WHEN status = 'validated' THEN 1 ELSE 0 END), 0) AS `Validated`,
+ COALESCE(SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END), 0) AS `Cancelled`,
+ COALESCE(SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END), 0) AS `Completed`,
+ COALESCE(SUM(CASE WHEN status = 'lost' THEN 1 ELSE 0 END), 0) AS `Lost`,
+ COALESCE(SUM(CASE WHEN status = 'insurer_pending' THEN 1 ELSE 0 END), 0) AS `Insurer Pending`
+
+ FROM (
+ SELECT
+ up.first_name AS ACM_Name,
+ ls.status
+ FROM policy_transaction pt
+ JOIN clients c ON pt.client_id = c.id AND c.is_active = 1
+ JOIN client_rm crm ON crm.client_id = c.id AND crm.is_active = 1 AND crm.level = 3
+ JOIN user_profiles up ON up.id = crm.user_id AND up.is_active = 1
+ LEFT JOIN (
+ SELECT
+ pts1.policy_tran_id,
+ pts1.status,
+ pts1.created_at
+ FROM policy_transaction_status pts1
+ INNER JOIN (
+ SELECT
+ policy_tran_id,
+ MAX(created_at) AS max_created_at
+ FROM policy_transaction_status
+ WHERE is_active = 1
+ GROUP BY policy_tran_id
+ ) pts2
+ ON pts1.policy_tran_id = pts2.policy_tran_id
+ AND pts1.created_at = pts2.max_created_at
+ WHERE pts1.is_active = 1
+ ) ls ON pt.id = ls.policy_tran_id
+ WHERE pt.is_active = 1
+ AND DATEDIFF(CURDATE(), ls.created_at) >= 4
+ ) AS sub
+ GROUP BY ACM_Name;
+ ";
+
+ $db = \Config\Database::connect();
+ $query = $db->query($sql);
+
+ // Get the result
+ $result = $query->getResultArray();
+
+ return $result;
+ }
+
+ public function accountManagerTatBDSReport(){
+
+ $sql = "
+ SELECT
+ COALESCE(ACM_Name, 'Total') AS ACM_Name,
+ COALESCE(SUM(CASE WHEN tat_bucket = '0-4 Days' THEN 1 ELSE 0 END), 0) AS `0-4 Days`,
+ COALESCE(SUM(CASE WHEN tat_bucket = '5-8 Days' THEN 1 ELSE 0 END), 0) AS `5-8 Days`,
+ COALESCE(SUM(CASE WHEN tat_bucket = '9-12 Days' THEN 1 ELSE 0 END), 0) AS `9-12 Days`,
+ COALESCE(SUM(CASE WHEN tat_bucket = 'Above 12 Days' THEN 1 ELSE 0 END), 0) AS `Above 12 Days`
+ FROM (
+ SELECT
+ up.first_name AS ACM_Name,
+ CASE
+ WHEN DATEDIFF(CURDATE(), ls.created_at) BETWEEN 0 AND 4 THEN '0-4 Days'
+ WHEN DATEDIFF(CURDATE(), ls.created_at) BETWEEN 5 AND 8 THEN '5-8 Days'
+ WHEN DATEDIFF(CURDATE(), ls.created_at) BETWEEN 9 AND 12 THEN '9-12 Days'
+ WHEN DATEDIFF(CURDATE(), ls.created_at) > 12 THEN 'Above 12 Days'
+ ELSE 'Unknown'
+ END AS tat_bucket
+ FROM policy_transaction pt
+ JOIN clients c ON pt.client_id = c.id AND c.is_active = 1
+ JOIN client_rm crm ON crm.client_id = c.id AND crm.is_active = 1 AND crm.level = 3
+ JOIN user_profiles up ON up.id = crm.user_id AND up.is_active = 1
+ LEFT JOIN (
+ SELECT
+ pts1.policy_tran_id,
+ pts1.status,
+ pts1.created_at
+ FROM policy_transaction_status pts1
+ INNER JOIN (
+ SELECT
+ policy_tran_id,
+ MAX(created_at) AS max_created_at
+ FROM policy_transaction_status
+ WHERE is_active = 1
+ GROUP BY policy_tran_id
+ ) pts2
+ ON pts1.policy_tran_id = pts2.policy_tran_id
+ AND pts1.created_at = pts2.max_created_at
+ WHERE pts1.is_active = 1
+ ) ls ON pt.id = ls.policy_tran_id
+ WHERE pt.is_active = 1
+ AND ls.created_at IS NOT NULL
+ ) AS sub
+ GROUP BY ACM_Name;
+
+ ";
+
+ $db = \Config\Database::connect();
+ $query = $db->query($sql);
+
+ // Get the result
+ $result = $query->getResultArray();
+
+ return $result;
+
+ }
+
+ public function getMultiReport($report_type){
+
+ $data['page_name'] = "BDS Report";
+
+ if ($report_type == 1){
+
+ $data['page_title'] = "BDS TAT Report";
+ $data['data'] = $this->bdsTATReport();
+ }else if ($report_type == 2){
+
+ $data['page_title'] = "Account Manager Status Report";
+ $data['data'] = $this->accountMangerStatusBDSReport();
+
+ }else{
+
+ $data['page_title'] = "Account Manager TAT Report";
+ $data['data'] = $this->accountManagerTatBDSReport();
+
+ }
+
+ return $this->loadLayout('bds_multi_report', $data);
+
+ }
}
+
diff --git a/app/Controllers/Chatbot/EcardDownloadConversation.php b/app/Controllers/Chatbot/EcardDownloadConversation.php
index b0cb78ae..c38d6977 100644
--- a/app/Controllers/Chatbot/EcardDownloadConversation.php
+++ b/app/Controllers/Chatbot/EcardDownloadConversation.php
@@ -17,10 +17,14 @@ class EcardDownloadConversation extends Conversation
protected function showEcardMenu()
{
+ log_message('error', ('showEcardMenu function called'));
+
$chat_session_info = get_chatbot_session_info();
$policy_list = ChatbotHelper::getListOfPolicies($chat_session_info);
$buttons = [];
$question = 'Choose Policy to Download Ecard:';
+ log_message('error', ('policy_list : ' . json_encode($policy_list)));
+
if(is_array($policy_list) && count($policy_list))
{
foreach($policy_list as $policy)
diff --git a/app/Controllers/Chatbot/MainMenuConversation.php b/app/Controllers/Chatbot/MainMenuConversation.php
index 87d9a4ef..f06fd078 100644
--- a/app/Controllers/Chatbot/MainMenuConversation.php
+++ b/app/Controllers/Chatbot/MainMenuConversation.php
@@ -46,9 +46,16 @@ class MainMenuConversation extends Conversation
$this->bot->reply($message);
}
+ log_message('error', ('user_reponse before: ' . $user_reponse));
+
+
if (!$answer->isInteractiveMessageReply()) {
$user_reponse = null;
}
+
+ log_message('error', ('user_reponse is interactive: ' . $answer->isInteractiveMessageReply()));
+
+
// Get just the existing path array
$path = $this->bot->userStorage()->get('path') ?? [];
@@ -60,25 +67,35 @@ class MainMenuConversation extends Conversation
'path' => $path
]);
+ log_message('error', ('user_reponse after: ' . $user_reponse));
+
+
switch ($user_reponse) {
case "ecard_download":
$this->bot->startConversation(new EcardDownloadConversation());
+ log_message('error', 'ecard_download clicked ');
+
break;
case "network_hospital":
$this->bot->startConversation(new NetworkHospitalConversation());
+ log_message('error', 'network_hospital clicked ');
break;
case "reimbursement_claim":
$this->bot->startConversation(new ReimbursementClaimProcessConversation());
+ log_message('error', 'reimbursement_claim clicked ');
break;
case "reimbursement_status":
$this->bot->startConversation(new ReimbursementClaimStatusConversation());
+ log_message('error', 'reimbursement_status clicked ');
break;
case "new_policy":
case "renew_policy":
$this->bot->startConversation(new policyConversation());
+ log_message('error', 'renew_policy || new_policy clicked ');
break;
default:
+ log_message('error', 'default shown ');
$this->say("Invalid selection. Please choose an option.");
$this->bot->startConversation(new MainMenuConversation());
break;
diff --git a/app/Controllers/Chatbot/NetworkHospitalConversation.php b/app/Controllers/Chatbot/NetworkHospitalConversation.php
index 2e59f896..4a1e991c 100644
--- a/app/Controllers/Chatbot/NetworkHospitalConversation.php
+++ b/app/Controllers/Chatbot/NetworkHospitalConversation.php
@@ -59,7 +59,10 @@ class NetworkHospitalConversation extends Conversation
$this->bot->userStorage()->save([
'path' => $path
]);
+ log_message('error', ('user_reponse : ' . $answer->getValue()));
+
switch ($answer->getValue()) {
+
case is_string($answer->getValue()) && is_array(explode('#',$answer->getValue())) && count((explode('#',$answer->getValue()))) == 2:
$client_poilicy_id = explode('#',$answer->getValue())[1];
diff --git a/app/Controllers/Chatbot/policyConversation.php b/app/Controllers/Chatbot/policyConversation.php
index 04c8d9a5..f2fe91c1 100644
--- a/app/Controllers/Chatbot/policyConversation.php
+++ b/app/Controllers/Chatbot/policyConversation.php
@@ -46,6 +46,9 @@ class policyConversation extends Conversation
if (!$answer->isInteractiveMessageReply()) {
$user_reponse = null;
}
+
+ log_message('error', ('user_reponse : ' . $answer->getValue()));
+
$path = $this->bot->userStorage()->get('path');
array_push($path,
$answer->getValue()
diff --git a/app/Controllers/ChatbotControllerNew.php b/app/Controllers/ChatbotControllerNew.php
index 610f2bda..dc38a3c9 100644
--- a/app/Controllers/ChatbotControllerNew.php
+++ b/app/Controllers/ChatbotControllerNew.php
@@ -84,12 +84,13 @@ class ChatbotControllerNew extends BaseController
public function index()
{
+
if($this->session->get('CHATBOT_RANDOM_USER_ID') == '-' || $this->session->get('CHATBOT_RANDOM_USER_ID') == '')
{
$user = $this->botman->getUser();
$id = $user->getId();
- // $this->myLogger->logme('error', ('TEST' . $id));
+ $this->myLogger->logme('error', ('TEST' . $id));
$this->session->set('CHATBOT_RANDOM_USER_ID', $id);
}
@@ -100,6 +101,7 @@ class ChatbotControllerNew extends BaseController
}
$this->botman->hears('.*', function ($bot) {
+ log_message("error","Inside Bot Type Function");
$bot->types(); // Typing indicator for the first message
sleep(0.5); // Delay
@@ -128,14 +130,14 @@ class ChatbotControllerNew extends BaseController
$this->botman->listen();
}
- private function registerHandlers()
- {
- // Handling Policy and Claims
- $this->botman->hears('group:policy:{option}', [\App\Controllers\Chatbot\PolicyHandler::class, 'handle']);
- $this->botman->hears('group:claim:{option}', [\App\Libraries\Chatbot\ClaimHandler::class, 'handle']);
+ // private function registerHandlers()
+ // {
+ // // Handling Policy and Claims
+ // $this->botman->hears('group:policy:{option}', [\App\Controllers\Chatbot\PolicyHandler::class, 'handle']);
+ // $this->botman->hears('group:claim:{option}', [\App\Libraries\Chatbot\ClaimHandler::class, 'handle']);
- }
+ // }
public function chatbot()
{
diff --git a/app/Controllers/ClientAPIController.php b/app/Controllers/ClientAPIController.php
new file mode 100644
index 00000000..4a6bff4f
--- /dev/null
+++ b/app/Controllers/ClientAPIController.php
@@ -0,0 +1,310 @@
+myLogger = \Config\Services::mylogger();
+
+ //models
+ $this->clientAPI = new ClientApiModel();
+ $this->clientPolicy = new ClientPolicyModel();
+
+ //helper
+ $this->clientQueryHelper = new ClientQueryHelper();
+
+ //controller
+ $this->ticketController = new TicketController();
+
+ //variables
+ $this->operators = [
+
+ "GT" => ">",
+ "LT" => "<",
+ "GTE" => ">=",
+ "LTE" => "<=",
+ "ET" => "=",
+ "NE" => "!=",
+ "LIKE" => "LIKE",
+ "NL" => "NOT LIKE",
+ "BTW" => "BETWEEN",
+ "NB" => "NOT BETWEEN",
+ "IS" => "IS NULL",
+ "ISN" => "IS NOT NULL",
+
+ ];
+ $this->propertyNames = [
+ 'empMaster' => ['name','emp_code','relationship','client_branch_id','emp_status','mobile','email_corporate','change_event','dob','doj','band','gender'],
+ 'claimMaster' => ['emp_name','insured_name',"emp_code",'policy_no','emp_mobile','emp_mail','hospital_name','claim_type','claim_status','claim_no','claim_amount','claim_date','si_amt','raised_date','registration_date','denial_date','denial_reason','approved_amount','utr_details','return_remark','cancel_remark','non_id_reason','head_rejection_reason'],
+ ];
+
+ }
+
+ public function validateToken()
+ {
+
+ try {
+
+ $authHeader = $this->request->getHeaderLine('Authorization');
+
+ // Check if header exists
+ if (empty($authHeader)) {
+ $this->myLogger->log('error', 'Authorization header missing');
+ return $this->respond(['status' => "Failure", 'error' => ['message' => 'Authorization header missing', 'code' => 401]], 401);
+ }
+
+ // Check if Bearer is present
+ if (!str_contains($authHeader, 'Bearer ')) {
+ $this->myLogger->log('error', 'Authorization Bearer missing');
+ return $this->respond(['status' => "Failure", 'error' => ['message' => 'Invalid Authorization header', 'code' => 401]], 401);
+ }
+
+ // Extract the token
+ $token = str_replace('Bearer ', '', $authHeader);
+ if (empty($token)) {
+
+ $this->myLogger->log('error', 'Empty Token');
+ return $this->respond(['status' => "Failure", 'error' => ['message' => 'Invalid Token Format', 'code' => 401]], 401);
+ }
+
+ try {
+
+ // Extract client_id from the token
+ $client_id = ClientTokenHelper::extractClientId($token);
+ } catch (\Exception $e) {
+ $this->myLogger->log('error', 'Invalid Client Token Format');
+
+ return $this->respond(['status' => "Failure", 'error' => 'Invalid Token Format'], 401);
+ }
+
+ // Fetch client details from the database
+ $client = $this->clientAPI->where('client_id', $client_id)->where("is_active", 1)->where("api_access", 1)->first();
+
+ // Client validation
+ if (!$client) {
+ $this->myLogger->log('error', 'Client Not Found or Unauthorized');
+ return $this->respond(['status' => "Failure", 'error' => ['message' => 'Client not found or unauthorized', 'code' => '403']], 403);
+ }
+
+ // Validate the token
+ if (hash_equals($client['client_token'], $token)) {
+ $this->myLogger->log('error', 'Access Granted For Client : ' . $client_id);
+ return true;
+ } else {
+ $this->myLogger->log('error', 'Invalid Token given for client : ' . $client_id);
+ return $this->respond([
+ 'status' => "Failure",
+ 'error' => ['message' => 'Invalid token', 'code' => 401]
+ ], 401);
+ }
+ } catch (\Exception $e) {
+ log_message('error', 'Error in ClientAPIController:validateToken - ' . $e->getMessage());
+ return $this->respond(['status' => "Failure", 'error' => ['message' => 'Internal Server Error', 'code' => 500]], 500);
+ }
+ }
+
+ public function getClientIdfromToken()
+ {
+ $authHeader = $this->request->getHeaderLine('Authorization');
+ $token = str_replace('Bearer ', '', $authHeader);
+ $client_id = ClientTokenHelper::extractClientId($token);
+
+ $this->myLogger->log('error', 'Client ID: ' . $client_id);
+ return [$client_id, $token];
+ }
+
+ public function sendPolicyMaster()
+ {
+
+ $data = $this->getClientIdfromToken();
+ $client_id = $data[0];
+ $keyString = $data[1];
+
+ // Extract only the actual key (after colon)
+ // list($prefix, $hexKey) = explode(':', $keyString, 2);
+
+ // // Convert hex to binary (32 bytes)
+ // $key = hex2bin($hexKey);
+
+
+ $clientPolicy = $this->clientQueryHelper->clientPolicyMaster($client_id);
+
+ $this->myLogger->log('error', 'Client Policy Master: ' . json_encode($clientPolicy));
+
+
+ // $encode_data = ClientTokenHelper::encryptData($clientPolicy, $key);
+ // return $this->respond(['status' => "Success", 'data' => $encode_data], 200);
+
+ return $this->respond(['status' => "Success", 'data' => $clientPolicy], 200);
+ }
+
+
+ public function sendEmpMaster()
+ {
+ $data = $this->getClientIdfromToken();
+ $client_id = $data[0];
+ $keyString = $data[1];
+
+ $received_data = $this->request->getJSON();
+ $filters = $received_data->filters ?? null;
+ $limit = $received_data->limit ?? null;
+ $after = $received_data->after ?? 0;
+
+ if ($limit > getenv('MAX_LIMIT')) {
+
+ $this->myLogger->log('error', "Limit exceeds maximum allowed limit");
+ return $this->respond(['status' => "Failure", 'error' => ['message' => 'Limit exceeds maximum allowed limit', 'code' => 400]], 400);
+ }
+
+ try{
+ if (!empty($filters)) {
+ $whereConditions = $this->prepareWhereConditions($filters,"",'empMaster');
+ $employees = $this->clientQueryHelper->sendEmpMaster($client_id, $whereConditions,!empty($limit) ? $limit : 10,$after);
+ }else{
+ $employees = $this->clientQueryHelper->sendEmpMaster($client_id, [],!empty($limit) ? $limit : 10,$after);
+ }
+ }catch (\InvalidArgumentException $e) {
+ return $this->respond(['status' => "Failure",'error' => ['message' => $e->getMessage(), 'code' => 400]], 400);
+ }
+
+ foreach ($employees as &$employee){
+
+ $employee['policy_details'] = $this->clientQueryHelper->sendEmpPolicies($employee['ref_no']);
+ }
+
+ $next_after = (count($employees) < $limit) ? null : ($after + $limit);
+
+ if (!empty($employees)){
+ return $this->respond(['Status' => "Success","data" => $employees,'next_after'=>$next_after], 200);
+ }else{
+ return $this->respond(['Status' => "Failure","error" => ['message' => 'No Employees Found', 'code' => 404]], 404);
+ }
+ }
+
+ public function sendClaimMaster()
+ {
+ $policy_type = $this->ticketController->ticketType;
+
+ $data = $this->getClientIdfromToken();
+ $client_id = $data[0];
+ $keyString = $data[1];
+
+ $received_data = $this->request->getJSON();
+ $filters = $received_data->filters ?? null;
+ $limit = $received_data->limit ?? null;
+ $after = $received_data->after ?? 0;
+
+ if ($limit > getenv('MAX_LIMIT')) {
+ $this->myLogger->log('error', "Limit exceeds maximum allowed limit");
+ return $this->respond(['status' => "Failure", 'error' => ['message' => 'Limit exceeds maximum allowed limit', 'code' => 400]], 400);
+ }
+
+ try{
+ if (!empty($filters)) {
+ $whereConditions = $this->prepareWhereConditions($filters,"ticket_master",'claimMaster');
+ $claimDetails = $this->clientQueryHelper->sendClaimMaster($client_id,$whereConditions,!empty($limit) ? $limit : 10);
+ }else{
+ $claimDetails = $this->clientQueryHelper->sendClaimMaster($client_id, [],!empty($limit) ? $limit : 10);
+ }
+
+ } catch (\InvalidArgumentException $e) {
+ return $this->respond(['status' => "Failure",'error' => ['message' => $e->getMessage(), 'code' => 400]], 400);
+ }
+
+ foreach ($claimDetails as &$claim){
+
+ $claim['policy_type'] = $policy_type[$claim['policy_type']];
+ }
+ // dd($claimDetails);
+
+ $next_after = (count($claimDetails) < $limit) ? null : ($after + $limit);
+
+
+ if (!empty($claimDetails)){
+ return $this->respond(['Status' => "Success","data" => $claimDetails,'next_after'=>$next_after], 200);
+ }else{
+ return $this->respond(['Status' => "Failure","error" => ['message' => 'No Claims Found', 'code' => 404]], 404);
+ }
+ }
+
+ public function prepareWhereConditions($filters,$tableName = null,$model)
+ {
+ $whereConditions = [];
+
+ foreach ($filters as $filter) {
+
+ $propertyName = $filter->propertyName;
+ $operator = $filter->operator;
+ $this->myLogger->log('error', 'Property Name: ' . $propertyName);
+ if (!in_array($operator, array_keys($this->operators))) {
+ $this->myLogger->log('error', 'Invalid operator: ' . $operator);
+ throw new \InvalidArgumentException('Invalid operator');
+ }
+ if (!in_array($propertyName, $this->propertyNames[$model])) {
+ $this->myLogger->log('error', 'Invalid property name: ' . $propertyName);
+ throw new \InvalidArgumentException('Invalid property name '.$propertyName);
+ }
+ $value = isset($filter->value) ? $filter->value : null;
+ $sqlOperator = $this->operators[$operator];
+
+ $column = !empty($tableName) ? "{$tableName}.{$propertyName}" : $propertyName;
+
+ if ($sqlOperator === '=') {
+ $whereConditions[$column] = $value;
+ } else if($sqlOperator == "LIKE" || $sqlOperator == "NOT LIKE") {
+ $whereConditions["{$column} {$sqlOperator}"] = "%{$value}%";
+
+ } else if ($sqlOperator == 'BETWEEN') {
+ if (is_array($value) && count($value) === 2) {
+ // $whereConditions[] = [$column, $sqlOperator, $value[0]];
+ $whereConditions["{$column} >="] = $value[0];
+ $whereConditions["{$column} <="] = $value[1];
+
+ } else {
+ return $this->respond(['status' => "Failure", 'error' => ['message' => 'Invalid value for BETWEEN operator', 'code' => 400]], 400);
+ }
+ }else if ($sqlOperator == 'NOT BETWEEN') {
+ if (is_array($value) && count($value) === 2) {
+ $whereConditions["{$column} <="] = $value[0];
+ $whereConditions["{$column} >="] = $value[1];
+ } else {
+ return $this->respond(['status' => "Failure", 'error' => ['message' => 'Invalid value for NOT BETWEEN operator', 'code' => 400]], 400);
+ }
+ }else {
+ $whereConditions["{$column} {$sqlOperator}"] = $value;
+ }
+
+ }
+
+ return $whereConditions;
+ }
+
+}
diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php
index ca43f2d2..f256d374 100755
--- a/app/Controllers/ClientController.php
+++ b/app/Controllers/ClientController.php
@@ -4,6 +4,7 @@ namespace App\Controllers;
use App\Helpers\DepositHelper;
use App\Helpers\MailHelper;
+use App\Helpers\ClientTokenHelper;
use App\helpers\JWTToken;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
@@ -39,9 +40,11 @@ use App\Models\PolicyTransactionModel;
use App\Models\PolicyTransactionStatusModel;
use App\Models\VehicleModel;
use App\Models\LeadsModel;
+use App\Models\ClientApiModel;
use App\Controllers\EmpDataServiceController;
use App\Controllers\GoogleDriveController;
+use App\Controllers\PolicyTransactionController;
use App\Helpers\sendMailNotification;
use App\Models\PTCOShareDetailsModel;
@@ -83,7 +86,8 @@ class ClientController extends AdminController
protected $policyTransactionStatusModel;
protected $vehicleModel;
protected $leadsModel;
-
+ protected $clientApi;
+ protected $PTCOShareDetailsModel;
public function __construct()
@@ -119,6 +123,8 @@ class ClientController extends AdminController
$this->policyTransactionStatusModel = new PolicyTransactionStatusModel();
$this->vehicleModel = new VehicleModel();
$this->leadsModel = new LeadsModel();
+ $this->clientApi = new ClientApiModel();
+ $this->PTCOShareDetailsModel = new PTCOShareDetailsModel();
}
//--------------------------------------------------------------------------------------------------------
@@ -266,7 +272,7 @@ class ClientController extends AdminController
if($mail_active == 1){
$mail_send_return = MailHelper::send_email($wholeData[0]);
- $this->myLogger->logme("info", $mail_send_return);
+ $this->myLogger->logme("error", $mail_send_return);
}
// if (isset($wholeData)) {
@@ -594,7 +600,7 @@ class ClientController extends AdminController
$data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
$data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
$data['state'] = $this->stateModel->getAllStates();
- $data['RM'] = $this->userModel->findAll();
+ $data['RM'] = $this->userModel->where('is_active', 1)->findAll();
$data['policyGridData'] = $this->policyGridModel->findAll();
$data['policy_types'] = $this->policyTypeModel->findAll();
$data['policy_type'] = ['1' => 'Base Policy', '2' => 'SI Topup', '3' => 'Dependent Addon'];
@@ -655,10 +661,12 @@ class ClientController extends AdminController
$loggedInUserID = get_session_userid();
// $data['clientData']= $this->clientPolicyModel->getinsurerswithinsurenceid($insurerId);
$clientId = $this->request->getGet('client_id');
+ $cd_ac_pk = $this->request->getGet('cd_ac_pk');
$data['insurerName'] = $this->insurerModel->getInsurerName($insurerId, $clientId);
- $data['depositdata'] = $this->clientPolicyModel->getdepositData($clientId, $insurerId);
+ $data['depositdata'] = $this->clientPolicyModel->getdepositData($clientId, $insurerId, $cd_ac_pk);
$data['clientData'] = $this->clientPolicyModel->getClientById($clientId);
- $data['deposiamount'] = $this->clientPolicyModel->getDepositSummary($clientId, $insurerId);
+ $data['deposiamount'] = $this->clientPolicyModel->getDepositSummary($clientId, $insurerId, $cd_ac_pk);
+ $data['cd_ac_pk'] = $cd_ac_pk;
// dd($data);
@@ -681,10 +689,18 @@ class ClientController extends AdminController
$CD_Account_Number = $this->CDMasterModel
->where('client_id', $client_id)
->where('insurer_id', $insurer_id)
+ ->where('is_active', 1)
->first();
- // Prepare the array with data
- $date = \DateTime::createFromFormat('d/m/Y', $record_date);
- $record_date = $date->format('Y-m-d');
+
+
+ if(!empty($record_date)){
+ // Prepare the array with data
+ $date = \DateTime::createFromFormat('d/m/Y', $record_date);
+ $record_date = $date->format('Y-m-d');
+ }else{
+ $record_date = null;
+ }
+
$data = [
'amount' => $this->request->getPost('amount'),
'sub_type_id' => $this->request->getPost('sub_type_id'),
@@ -717,7 +733,7 @@ class ClientController extends AdminController
$this->myLogger->logme('error', 'Edit Client Onboarding function called');
$headerData['page_name'] = 'Edit Client Onboarding';
- $editData['RM'] = $this->userModel->findAll();
+ $editData['RM'] = $this->userModel->where('is_active', 1)->findAll();
$editData['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
$editData['state'] = $this->stateModel->getAllStates();
$editData['police'] = $this->policesModel->findAll();
@@ -751,7 +767,7 @@ class ClientController extends AdminController
$editData['client_policy']['role'] = get_role_id();
$editData['notification'] = $this->notificationModel->select('template_name,enabled')->where('client_id', $id)->findAll();
$editData['placeHolders'] = ['member_name', 'member_mobile', 'nhance_logo', 'tpa_id', 'ecard_download_link', 'client_logo', 'policy_no', 'member_summary', 'app_link', 'post_enrollment_app_link', 'client_name'];
-
+ $editData['api_data'] = $this->clientApi->where("client_id", $id)->where("is_active",1)->first();
// dd($editData);
echo view('layout/header', $headerData);
echo view('client_onboarding', $editData);
@@ -1239,40 +1255,8 @@ class ClientController extends AdminController
$data['created_by'] = get_session_userid();
- $policy_tranction_data = [
-
- 'issuer' => 2,
- 'client_id' => $this->request->getPost('client_id'),
- 'client_branch_id' => $this->request->getPost('client_branch_id'),
- 'insurer_id' => $insurerId,
- 'insurer_branch_id' => $insurerBranchId,
- 'issue_type' => 1,
- 'policy_no' => $this->request->getPost('policy_no'),
- 'cd_ac_pk' => $this->request->getPost('cd_ac_no'),
- 'policy_issue_date' => date('Y-m-d'),
- 'policy_start_date' => change_date_format($this->request->getPost('policy_start_date'), 'd-m-Y', 'Y-m-d'),
- 'policy_end_date' => change_date_format($this->request->getPost('policy_end_date'), 'd-m-Y', 'Y-m-d'),
- 'action_type' => 'inception',
- 'status' => 'pending',
- 'created_by' => get_session_userid(),
- ];
-
-
$insert = $this->clientPolicyModel->insert($data);
if ($insert) {
-
- $policy_tranction_data['client_policy_id'] = $insert;
- $policy_tranction_data_insert = $this->policyTransactionModel->insert($data);
- if ($policy_tranction_data_insert) {
- $statusData = [
- 'policy_tran_id' => $policy_tranction_data_insert,
- 'status' => 'pending',
- 'created_by' => get_session_userid(),
- ];
- $this->policyTransactionStatusModel->insert($statusData);
- }
-
-
$clientPoliceData = $this->clientPolicyModel->getClientPolicyByClientId($this->request->getPost('client_id'));
$clientPoliceData['role'] = get_role_id();
return $this->respond(['status' => true, 'code' => 200, 'data' => $clientPoliceData, 'method' => 'CERATE', 'post_data' => $data], 200);
@@ -1283,15 +1267,12 @@ class ClientController extends AdminController
public function editClientPolicy()
{
-
- // print_r('test'); die;
$this->myLogger->logme('error', 'Client policy function called');
-
- $id = $this->request->getPost('PrimaryKey');
- $client_id = $this->request->getPost('client_id');
+ $id = $this->request->getPost('PrimaryKey');
+ $client_id = $this->request->getPost('client_id');
$policy_type_id = $this->request->getPost('policy_type_id');
- $base_policy = $this->request->getPost('base_policy');
+ $base_policy = $this->request->getPost('base_policy');
$insurerValue = (string) $this->request->getPost('insurer');
@@ -1301,15 +1282,18 @@ class ClientController extends AdminController
$data['insurer_id'] = $insurerId;
$tpaValue = (string) $this->request->getPost('tpa');
- list($tpaBranchId, $tpaId) = explode('-', $tpaValue);
+ if(!empty($tpaValue) || $tpaValue !== ''){
+ list($tpaBranchId, $tpaId) = explode('-', $tpaValue);
+ }else{
+ $tpaBranchId = null;
+ $tpaId = null;
+ }
$data['tpa_branch_id'] = $tpaBranchId;
$data['client_id'] = $client_id;
$data['tpa_id'] = $tpaId;
$data['policy_type_id'] = $this->request->getPost('policy_type_id');
- $data['policy_no'] = $this->request->getPost('policy_no');
- // $data['policy_start_date'] = change_date_format($this->request->getPost('policy_start_date'), 'd-m-Y', 'Y-m-d');
- // $data['policy_end_date'] = change_date_format($this->request->getPost('policy_end_date'), 'd-m-Y', 'Y-m-d');
+ $data['policy_no'] = $this->request->getPost('policy_no');
$data['insured'] = $this->request->getPost('insured');
$data['no_of_lives'] = $this->request->getPost('no_of_lives');
@@ -1346,19 +1330,6 @@ class ClientController extends AdminController
$data['reminder_date'] = null;
}
- // if($policy_type_id == 1 || $policy_type_id == 2 || $policy_type_id == 3 || $policy_type_id == 6 || $policy_type_id == 7){
-
- // $data['is_addon'] = 1;
-
- // }else if($policy_type_id == 4){
-
- // $data['is_addon'] = 2;
-
- // }else if($policy_type_id == 5){
-
- // $data['is_addon'] = 3;
- // }
-
if ($policy_type_id == 1 || $policy_type_id == 2 || $policy_type_id == 6 || $policy_type_id == 7) {
$data['is_addon'] = 1; // Base Policy
@@ -1376,47 +1347,26 @@ class ClientController extends AdminController
}
}
-
-
$policy_terms = $this->clientPolicyModel->where('id', $this->request->getPost('base_policy'))->first();
- // if ( $this->request->getPost('is_addon') == 2 || $this->request->getPost('is_addon') == 3) {
- // if ($this->request->getPost('is_addon') == 3) {
- // $policyTerm = $policy_terms['policy_terms'];
- // $decoded_policyTerm = json_decode($policyTerm, true);
- // $decoded_policyTerm['family_floater'] =0;
- // $decoded_policyTerm['family_floaters']['self'] =0;
- // $decoded_policyTerm['family_floaters']['spouse'] =0;
- // $decoded_policyTerm['family_floaters']['childrens'] =0;
- // $decoded_policyTerm['family_floaters']['parents'] =0;
- // $decoded_policyTerm['family_floaters']['parents-in-law'] =0;
- // $decoded_policyTerm['family_floaters']['either-parents-pil'] =0;
-
- // $data['policy_terms'] = json_encode($decoded_policyTerm);
- // } else {
- // $data['policy_terms'] = $policy_terms['policy_terms'];
- // }
-
-
- // }
-
- // dd($data);
+ $old_client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $id)->first();
$data['updated_by'] = get_session_userid();
- // print_r(json_encode($data));die;
$insert = $this->clientPolicyModel->update($id, $data);
- $lastQuery = $this->clientPolicyModel->getLastQuery();
-
- // echo '
';
- // print_r($data); die;
if ($insert) {
+
+ $new_client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $id)->first();
+ $policy_transaction_data = $this->policyTransactionModel->where('is_active', 1)->where('client_policy_id', $id)->countAllResults();
$clientPoliceData = $this->clientPolicyModel->getClientPolicyByClientId($client_id);
$clientPoliceData['role'] = get_role_id();
- // foreach ($clientPoliceData as $key => $value) {
- // $clientPoliceData[$key]->policy_start_date = date('d-M-Y', strtotime($value->policy_start_date));
- // $clientPoliceData[$key]->policy_end_date = date('d-M-Y', strtotime($value->policy_end_date));
- // }
+ if($policy_transaction_data > 0){
+ $r = Jobs::addJob(['job_name' => 'updatePolicyTransactionDataWhileClinetPolicyUpdate', 'payload' => [
+ 'old_client_policy_data' => $old_client_policy_data ?? null,
+ 'new_client_policy_data' => $new_client_policy_data ?? null,
+ ]]);
+ }
+
return $this->respond(['status' => true, 'code' => 200, 'data' => $clientPoliceData, 'method' => 'EDIT'], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
@@ -1885,6 +1835,146 @@ class ClientController extends AdminController
}
}
+ public function updatePolicyTransactionDataWhileClinetPolicyUpdate($params)
+ {
+ try {
+ // Basic validation
+ if (empty($params) || !isset($params['old_client_policy_data']) || empty($params['old_client_policy_data'])) {
+ $this->myLogger->logme("error", "Old client policy data is missing or empty: " . json_encode(['params' => $params]));
+ return ['status' => "Failed", 'message' => "Old client policy data is missing or empty", 'data' => $params];
+ }
+
+ if (!isset($params['new_client_policy_data']) || empty($params['new_client_policy_data'])) {
+ $this->myLogger->logme("error", "New client policy data is missing or empty: " . json_encode(['params' => $params]));
+ return ['status' => "Failed", 'message' => "New client policy data is missing or empty", 'data' => $params];
+ }
+
+ $old = $params['old_client_policy_data'];
+ $new = $params['new_client_policy_data'];
+
+ $data = [];
+
+ // Check differences and prepare update data
+ $fields_to_check = [
+ 'client_branch_id', 'policy_type', 'insurer_id', 'insurer_branch_id',
+ 'cd_ac_pk', 'policy_end_date', 'policy_start_date', 'tpa_id', 'tpa_branch_id'
+ ];
+
+ foreach ($fields_to_check as $field) {
+ if (isset($new[$field]) && isset($old[$field]) && $new[$field] != $old[$field]) {
+ $data[$field] = $new[$field];
+ }
+ }
+
+ if (empty($data)) {
+ $this->myLogger->logme("error", "No changes detected in client policy update.");
+ return ['status' => "Failed", 'message' => "No changes detected in policy data."];
+ }
+
+ // Fetch related policy transactions
+ $policy_transactions = $this->policyTransactionModel
+ ->where('is_active', 1)
+ ->where('client_policy_id', $new['id'])
+ ->findAll();
+
+ $updated_pt_ids = [];
+
+ if (!empty($policy_transactions)) {
+
+ // Update each policy transaction and track affected IDs
+ foreach ($policy_transactions as $pt) {
+ $result = $this->policyTransactionModel
+ ->where('id', $pt['id'])
+ ->set($data)
+ ->update();
+
+ if ($this->policyTransactionModel->affectedRows() > 0) {
+ $updated_pt_ids[] = $pt['id'];
+ }
+ }
+
+ if (empty($updated_pt_ids)) {
+ $this->myLogger->logme("error", "No policy_transaction records were updated.");
+ return ['status' => "Failed", 'message' => "No records updated."];
+ }
+
+ // If insurer-related fields are updated, update co-share table as well
+ if (isset($data['insurer_id']) && !empty($data['insurer_id'])) {
+ $co_share_result = $this->updatePTCoShareTableEntry($policy_transactions, $old, $data);
+ $this->myLogger->logme("error", "PT co-share update result: " . json_encode($co_share_result));
+ }
+
+ $this->myLogger->logme("error", "Policy transaction(s) updated successfully. Updated IDs: " . json_encode($updated_pt_ids));
+
+ return [
+ 'status' => "Success",
+ 'message' => "Policy transaction(s) updated.",
+ 'updated_ids' => $updated_pt_ids
+ ];
+
+ } else {
+ $this->myLogger->logme("error", "No active policy_transaction records found for update.");
+ return ['status' => "Failed", 'message' => "No active policy_transaction records found."];
+ }
+
+ } catch (\Throwable $e) {
+ $this->myLogger->logme("error", "Exception during policy_transaction update: " . $e->getMessage());
+ return [
+ 'status' => "Failed",
+ 'message' => "An error occurred during update.",
+ 'error' => $e->getMessage()
+ ];
+ }
+ }
+
+
+ private function updatePTCoShareTableEntry($policy_transaction_data, $old_client_policy_data, $data)
+ {
+ $updated_ids = [];
+ $errors = [];
+
+ foreach ($policy_transaction_data as $value) {
+ $pt_id = $value['id'];
+
+ try {
+ // Find matching rows
+ $rows = $this->PTCOShareDetailsModel
+ ->where('pt_id', $pt_id)
+ ->where('insurer_id', $old_client_policy_data['insurer_id'])
+ ->where('insurer_branch_id', $old_client_policy_data['insurer_branch_id'])
+ ->where('is_active', 1)
+ ->findAll();
+
+ foreach ($rows as $row) {
+ // Update each row individually
+ $result = $this->PTCOShareDetailsModel
+ ->where('id', $row['id'])
+ ->set([
+ 'insurer_id' => $data['insurer_id'],
+ 'insurer_branch_id' => $data['insurer_branch_id'],
+ ])
+ ->update();
+
+ // Check if the update was successful
+ if ($this->PTCOShareDetailsModel->affectedRows() > 0) {
+ $updated_ids[] = $row['id'];
+ } else {
+ $errors[] = "No change or failed update for ID {$row['id']}";
+ }
+ }
+
+ } catch (\Exception $e) {
+ $errors[] = "Error updating pt_id {$pt_id}: " . $e->getMessage();
+ }
+ }
+
+ return [
+ 'updated_ids' => $updated_ids,
+ 'errors' => $errors,
+ ];
+ }
+
+
public function uploadVehicleFile()
@@ -1994,9 +2084,22 @@ class ClientController extends AdminController
if ($id) {
$client_policy_data = $this->clientPolicyModel->where(['id' => $id, 'is_active' => 1])->first();
+
$insurer_id = $client_policy_data['insurer_id'];
$client_id = $client_policy_data['client_id'];
+ if (!empty($client_policy_data['policy_start_date'])) {
+ $client_policy_data['source_policy_start_date'] = change_date_format($client_policy_data['policy_start_date'], 'Y-m-d', 'd/m/Y');
+ } else {
+ $client_policy_data['source_policy_start_date'] = null;
+ }
+
+ if (!empty($client_policy_data['policy_end_date'])) {
+ $client_policy_data['source_policy_end_date'] = change_date_format($client_policy_data['policy_end_date'], 'Y-m-d', 'd/m/Y');
+ } else {
+ $client_policy_data['source_policy_end_date'] = null;
+ }
+
$polices = $this->policesModel
->select('policies.*, policy_type.policy_type')
->join('policy_type', 'policy_type.id = policies.policy_type_id')
@@ -2004,7 +2107,7 @@ class ClientController extends AdminController
->findAll();
$client_policy_list = $this->clientPolicyModel->getPolicyTypeForPolicyBinding($client_id);
- $cd_data = $this->CDMasterModel->where('client_id', $client_id)->where('insurer_id', $insurer_id)->findAll();
+ $cd_data = $this->CDMasterModel->where('client_id', $client_id)->where('insurer_id', $insurer_id)->where('is_active', 1)->findAll();
// $client_policy_data['policy_end_date'] = date('d/m/Y', strtotime($client_policy_data['policy_end_date']));
$fromDate = new \DateTime($client_policy_data['policy_end_date']);
$fromDate->modify('+1 year');
@@ -2022,7 +2125,7 @@ class ClientController extends AdminController
'policy' => $polices,
'client_policy_list' => $client_policy_list,
'end_date' => $newDate,
- 'new_start_date' => date('d/m/Y', strtotime($client_policy_data['policy_end_date']))
+ 'new_start_date' => date('d/m/Y', strtotime($client_policy_data['policy_end_date'] . ' +1 day')),
], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
@@ -2317,52 +2420,109 @@ class ClientController extends AdminController
// print_r($data);die;
- $data['waiverofpreexistingdiseases'] = $this->request->getPost("waiverofpreexistingdiseases");
- $data['waiverof1,2,3&4thyearexclusions'] = $this->request->getPost("waiverof1,2,3&4thyearexclusions");
- $data['waiverof30dayswaitingperiod'] = $this->request->getPost("waiverof30dayswaitingperiod");
- $data['waiver_of_90_days_waiting_period'] = $this->request->getPost("waiver_of_90_days_waiting_period");
- $data['waiver_of_other_waiting_periods'] = $this->request->getPost("waiver_of_other_waiting_periods");
- $data['maternity_benefit'] = $this->request->getPost("maternity_benefit");
- $data['9monthwaitingperiodwaived'] = str_replace(',', '', $this->request->getPost("9monthwaitingperiodwaived"));
- $data['maternitycoverage'] = str_replace(',', '', $this->request->getPost("maternitycoverage"));
- $data['twindelivery'] = str_replace(',', '', $this->request->getPost("twindelivery"));
- $data['well_baby_well_mother_expenses'] = str_replace(',', '', $this->request->getPost("well_baby_well_mother_expenses"));
- $data['preandpostnatal'] = str_replace(',', '', $this->request->getPost("preandpostnatal"));
- $data['infertility_treatment_coverage'] = str_replace(',', '', $this->request->getPost("infertility_treatment_coverage"));
- $data['babyday1cover'] = str_replace(',', '', $this->request->getPost("babyday1cover"));
- $data['coverfromthedateofjoining'] = str_replace(',', '', $this->request->getPost("coverfromthedateofjoining"));
- $data['mid_term_addition_of_new_born_newly_wedded_spouse'] = str_replace(',', '', $this->request->getPost("mid_term_addition_of_new_born_newly_wedded_spouse"));
- $data['prehospitalizationcover'] = str_replace(',', '', $this->request->getPost("prehospitalizationcover"));
- $data['posthospitalizationcover'] =$this->request->getPost("posthospitalizationcover");
- $data['congenitaldiseasesinternal'] = str_replace(',', '', $this->request->getPost("congenitaldiseasesinternal"));
- $data['congenitaldiseasesexternal'] = str_replace(',', '', $this->request->getPost("congenitaldiseasesexternal"));
- $data['copayzonewisecopay'] = $this->request->getPost("copayzonewisecopay");
- $data['roomrentlimit'] = str_replace(',', '', $this->request->getPost("roomrentlimit"));
- $data['icu_limit'] = str_replace(',', '', $this->request->getPost("icu_limit"));
- $data['proportionatedeductionclause'] = str_replace(',', '', $this->request->getPost("proportionatedeductionclause"));
- $data['ailmentcapping'] = $this->request->getPost("ailmentcapping");
- $data['ailment_capping_details'] = str_replace(',', '', $this->request->getPost("ailment_capping_details"));
- $data['corporatebuffer'] = str_replace(',', '', $this->request->getPost("corporatebuffer"));
- $data['non_admissible_contingency_corporate_buffer'] = str_replace(',', '', $this->request->getPost("non_admissible_contingency_corporate_buffer"));
- $data['ambulancecharges'] = str_replace(',', '', $this->request->getPost("ambulancecharges"));
- $data['airambulance'] = str_replace(',', '', $this->request->getPost("airambulance"));
- $data['reasonableandcustomarycharges'] = str_replace(',', '', $this->request->getPost("reasonableandcustomarycharges"));
- $data['daycaretreatment'] = str_replace(',', '', $this->request->getPost("daycaretreatment"));
- $data['lasiksurgery'] = str_replace(',', '', $this->request->getPost("lasiksurgery"));
- $data['ayudhtreatmentcover'] = str_replace(',', '', $this->request->getPost("ayudhtreatmentcover"));
- $data['moderntreatmentsasperirdai'] = str_replace(',', '', $this->request->getPost("moderntreatmentsasperirdai"));
- $data['opd_treatment'] = str_replace(',', '', $this->request->getPost("opd_treatment"));
- $data['days_of_discharge'] = str_replace(',', '', $this->request->getPost("days_of_discharge"));
- $data['days_from_dod'] = str_replace(',', '', $this->request->getPost("days_from_dod"));
- $data['terrorism'] = str_replace(',', '', $this->request->getPost("terrorism"));
- $data['widower_cover'] = str_replace(',', '', $this->request->getPost("widower_cover"));
- $data['breavement_cover'] = str_replace(',', '', $this->request->getPost("breavement_cover"));
+ // $data['waiverofpreexistingdiseases'] = $this->request->getPost("waiverofpreexistingdiseases");
+ // $data['waiverof1,2,3&4thyearexclusions'] = $this->request->getPost("waiverof1,2,3&4thyearexclusions");
+ // $data['waiverof30dayswaitingperiod'] = $this->request->getPost("waiverof30dayswaitingperiod");
+ // $data['waiver_of_90_days_waiting_period'] = $this->request->getPost("waiver_of_90_days_waiting_period");
+ // $data['waiver_of_other_waiting_periods'] = $this->request->getPost("waiver_of_other_waiting_periods");
+ // $data['maternity_benefit'] = $this->request->getPost("maternity_benefit");
+ // $data['9monthwaitingperiodwaived'] = str_replace(',', '', $this->request->getPost("9monthwaitingperiodwaived"));
+ // $data['maternitycoverage'] = str_replace(',', '', $this->request->getPost("maternitycoverage"));
+ // $data['twindelivery'] = str_replace(',', '', $this->request->getPost("twindelivery"));
+ // $data['well_baby_well_mother_expenses'] = str_replace(',', '', $this->request->getPost("well_baby_well_mother_expenses"));
+ // $data['preandpostnatal'] = str_replace(',', '', $this->request->getPost("preandpostnatal"));
+ // $data['infertility_treatment_coverage'] = str_replace(',', '', $this->request->getPost("infertility_treatment_coverage"));
+ // $data['babyday1cover'] = str_replace(',', '', $this->request->getPost("babyday1cover"));
+ // $data['coverfromthedateofjoining'] = str_replace(',', '', $this->request->getPost("coverfromthedateofjoining"));
+ // $data['mid_term_addition_of_new_born_newly_wedded_spouse'] = str_replace(',', '', $this->request->getPost("mid_term_addition_of_new_born_newly_wedded_spouse"));
+ // $data['prehospitalizationcover'] = str_replace(',', '', $this->request->getPost("prehospitalizationcover"));
+ // $data['posthospitalizationcover'] =$this->request->getPost("posthospitalizationcover");
+ // $data['congenitaldiseasesinternal'] = str_replace(',', '', $this->request->getPost("congenitaldiseasesinternal"));
+ // $data['congenitaldiseasesexternal'] = str_replace(',', '', $this->request->getPost("congenitaldiseasesexternal"));
+ // $data['copayzonewisecopay'] = $this->request->getPost("copayzonewisecopay");
+ // $data['roomrentlimit'] = str_replace(',', '', $this->request->getPost("roomrentlimit"));
+ // $data['icu_limit'] = str_replace(',', '', $this->request->getPost("icu_limit"));
+ // $data['proportionatedeductionclause'] = str_replace(',', '', $this->request->getPost("proportionatedeductionclause"));
+ // $data['ailmentcapping'] = $this->request->getPost("ailmentcapping");
+ // $data['ailment_capping_details'] = str_replace(',', '', $this->request->getPost("ailment_capping_details"));
+ // $data['corporatebuffer'] = str_replace(',', '', $this->request->getPost("corporatebuffer"));
+ // $data['non_admissible_contingency_corporate_buffer'] = str_replace(',', '', $this->request->getPost("non_admissible_contingency_corporate_buffer"));
+ // $data['ambulancecharges'] = str_replace(',', '', $this->request->getPost("ambulancecharges"));
+ // $data['airambulance'] = str_replace(',', '', $this->request->getPost("airambulance"));
+ // $data['reasonableandcustomarycharges'] = str_replace(',', '', $this->request->getPost("reasonableandcustomarycharges"));
+ // $data['daycaretreatment'] = str_replace(',', '', $this->request->getPost("daycaretreatment"));
+ // $data['lasiksurgery'] = str_replace(',', '', $this->request->getPost("lasiksurgery"));
+ // $data['ayudhtreatmentcover'] = str_replace(',', '', $this->request->getPost("ayudhtreatmentcover"));
+ // $data['moderntreatmentsasperirdai'] = str_replace(',', '', $this->request->getPost("moderntreatmentsasperirdai"));
+ // $data['opd_treatment'] = str_replace(',', '', $this->request->getPost("opd_treatment"));
+ // $data['days_of_discharge'] = str_replace(',', '', $this->request->getPost("days_of_discharge"));
+ // $data['days_from_dod'] = str_replace(',', '', $this->request->getPost("days_from_dod"));
+ // $data['terrorism'] = str_replace(',', '', $this->request->getPost("terrorism"));
+ // $data['widower_cover'] = str_replace(',', '', $this->request->getPost("widower_cover"));
+ // $data['breavement_cover'] = str_replace(',', '', $this->request->getPost("breavement_cover"));
- $data['suminsuredenhancement'] = str_replace(',', '', $this->request->getPost("suminsuredenhancement"));
+ // $data['suminsuredenhancement'] = str_replace(',', '', $this->request->getPost("suminsuredenhancement"));
- $data['special_condition_label'] = str_replace(',', '', $this->request->getPost("special_condition_label")) ?? [];
- $data['special_condition_input'] = str_replace(',', '', $this->request->getPost("special_condition_input")) ?? [];
- $data['multiple_sum_insured'] = str_replace(',', '', $this->request->getPost("multiple_sum_insured")) ?? [];
+ // $data['special_condition_label'] = str_replace(',', '', $this->request->getPost("special_condition_label")) ?? [];
+ // $data['special_condition_input'] = str_replace(',', '', $this->request->getPost("special_condition_input")) ?? [];
+ // $data['multiple_sum_insured'] = str_replace(',', '', $this->request->getPost("multiple_sum_insured")) ?? [];
+ $fields = [
+ 'waiverofpreexistingdiseases' => false,
+ 'waiverof1,2,3&4thyearexclusions' => false,
+ 'waiverof30dayswaitingperiod' => false,
+ 'waiver_of_90_days_waiting_period' => false,
+ 'waiver_of_other_waiting_periods' => false,
+ 'maternity_benefit' => false,
+ '9monthwaitingperiodwaived' => true,
+ 'maternitycoverage' => true,
+ 'twindelivery' => true,
+ 'well_baby_well_mother_expenses' => true,
+ 'preandpostnatal' => true,
+ 'infertility_treatment_coverage' => true,
+ 'babyday1cover' => true,
+ 'coverfromthedateofjoining' => true,
+ 'mid_term_addition_of_new_born_newly_wedded_spouse' => true,
+ 'prehospitalizationcover' => true,
+ 'posthospitalizationcover' => false,
+ 'congenitaldiseasesinternal' => true,
+ 'congenitaldiseasesexternal' => true,
+ 'copayzonewisecopay' => false,
+ 'roomrentlimit' => true,
+ 'icu_limit' => true,
+ 'proportionatedeductionclause' => true,
+ 'ailmentcapping' => false,
+ 'ailment_capping_details' => true,
+ 'corporatebuffer' => true,
+ 'non_admissible_contingency_corporate_buffer' => true,
+ 'ambulancecharges' => true,
+ 'airambulance' => true,
+ 'reasonableandcustomarycharges' => true,
+ 'daycaretreatment' => true,
+ 'lasiksurgery' => true,
+ 'ayudhtreatmentcover' => true,
+ 'moderntreatmentsasperirdai' => true,
+ 'opd_treatment' => true,
+ 'days_of_discharge' => true,
+ 'days_from_dod' => true,
+ 'terrorism' => true,
+ 'widower_cover' => true,
+ 'breavement_cover' => true,
+ 'suminsuredenhancement' => true,
+ 'special_condition_label' => true,
+ 'special_condition_input' => true,
+ 'multiple_sum_insured' => true,
+ ];
+
+ // $data = [];
+
+ foreach ($fields as $field => $needsCleanup) {
+ $value = $this->request->getPost($field);
+
+ if ($value !== null && $value !== '') {
+ $data[$field] = $needsCleanup ? str_replace(',', '', $value) : $value;
+ }
+ }
+
$data['enrollment_display_key'] = $this->enrollmentGMCDisplayValueTransform();
@@ -2414,6 +2574,10 @@ class ClientController extends AdminController
if ($this->request->getPost("waiverof30dayswaitingperiod_display")) {
$data['Waiver of 30 days waiting period'] = $this->request->getPost("waiverof30dayswaitingperiod");
}
+
+ if ($this->request->getPost("suminsuredenhancement_display")) {
+ $data['Sum Insured Enhancement'] = $this->request->getPost("suminsuredenhancement");
+ }
if ($this->request->getPost("waiver_of_90_days_waiting_period_display")) {
$data['Waiver of 90 Days Waiting Period'] = $this->request->getPost("waiver_of_90_days_waiting_period");
@@ -2631,33 +2795,79 @@ class ClientController extends AdminController
$data['age_ratio']['self']['max'] = $this->request->getPost("self_max_age");
$data['is_payable_employee']['self'] = 0;
- $data['accidentalDeathBenefit'] = str_replace(',', '', $this->request->getPost("accidentalDeathBenefit"));
- $data['permanentTotalDisablement'] = str_replace(',', '', $this->request->getPost("permanentTotalDisablement"));
- $data['permanentPartialDisablement'] = $this->request->getPost("permanentPartialDisablement");
- $data['temporaryTotalDisablementBenefit'] = $this->request->getPost("temporaryTotalDisablementBenefit");
- $data['medical_expenses_medical_extension'] = str_replace(',', '', $this->request->getPost("medical_expenses_medical_extension"));
- $data['opd_treatment_cover'] = str_replace(',', '', $this->request->getPost("opd_treatment_cover"));
- $data['ambulanceCharges'] = str_replace(',', '', $this->request->getPost("ambulanceCharges"));
- $data['repatriation_of_mortal_remains'] = str_replace(',', '', $this->request->getPost("repatriation_of_mortal_remains"));
- $data['childrenEducationWelfareFund'] = str_replace(',', '', $this->request->getPost("childrenEducationWelfareFund"));
- $data['terrorism'] = $this->request->getPost("terrorism");
- $data['worldwideCover'] = $this->request->getPost("worldwideCover");
- $data['family_transportation_benefits'] = $this->request->getPost("family_transportation_benefits");
- $data['fractures_dislocation_burns'] = $this->request->getPost("fractures_dislocation_burns");
- $data['coma'] = $this->request->getPost("coma");
- $data['carriageOfDeadBody'] = $this->request->getPost("carriageOfDeadBody");
- $data['compassionateVisitExpenses'] = $this->request->getPost("compassionateVisitExpenses");
- $data['travel_expenses_for_medical_treatment'] = $this->request->getPost("travel_expenses_for_medical_treatment");
- $data['daily_cash_allowance'] = $this->request->getPost("daily_cash_allowance");
- $data['artifical_limb_and_prosthesis'] = $this->request->getPost("artifical_limb_and_prosthesis");
- $data['animalSnakeInsectBite'] = $this->request->getPost("animalSnakeInsectBite");
- $data['air_ambulance'] = $this->request->getPost("air_ambulance");
+ // $data['accidentalDeathBenefit'] = str_replace(',', '', $this->request->getPost("accidentalDeathBenefit"));
+ // $data['permanentTotalDisablement'] = str_replace(',', '', $this->request->getPost("permanentTotalDisablement"));
+ // $data['permanentPartialDisablement'] = $this->request->getPost("permanentPartialDisablement");
+ // $data['temporaryTotalDisablementBenefit'] = $this->request->getPost("temporaryTotalDisablementBenefit");
+ // $data['medical_expenses_medical_extension'] = str_replace(',', '', $this->request->getPost("medical_expenses_medical_extension"));
+ // $data['opd_treatment_cover'] = str_replace(',', '', $this->request->getPost("opd_treatment_cover"));
+ // $data['ambulanceCharges'] = str_replace(',', '', $this->request->getPost("ambulanceCharges"));
+ // $data['repatriation_of_mortal_remains'] = str_replace(',', '', $this->request->getPost("repatriation_of_mortal_remains"));
+ // $data['childrenEducationWelfareFund'] = str_replace(',', '', $this->request->getPost("childrenEducationWelfareFund"));
+ // $data['terrorism'] = $this->request->getPost("terrorism");
+ // $data['worldwideCover'] = $this->request->getPost("worldwideCover");
+ // $data['family_transportation_benefits'] = $this->request->getPost("family_transportation_benefits");
+ // $data['fractures_dislocation_burns'] = $this->request->getPost("fractures_dislocation_burns");
+ // $data['coma'] = $this->request->getPost("coma");
+ // $data['carriageOfDeadBody'] = $this->request->getPost("carriageOfDeadBody");
+ // $data['compassionateVisitExpenses'] = $this->request->getPost("compassionateVisitExpenses");
+ // $data['travel_expenses_for_medical_treatment'] = $this->request->getPost("travel_expenses_for_medical_treatment");
+ // $data['daily_cash_allowance'] = $this->request->getPost("daily_cash_allowance");
+ // $data['artifical_limb_and_prosthesis'] = $this->request->getPost("artifical_limb_and_prosthesis");
+ // $data['animalSnakeInsectBite'] = $this->request->getPost("animalSnakeInsectBite");
+ // $data['air_ambulance'] = $this->request->getPost("air_ambulance");
- $data['gpa_special_condition_label'] = str_replace(',', '', $this->request->getPost("gpa_special_condition_label")) ?? [];
- $data['gpa_special_condition_input'] = str_replace(',', '', $this->request->getPost("gpa_special_condition_input")) ?? [];
- $data['multiple_sum_insured'] = str_replace(',', '', $this->request->getPost("multiple_sum_insured")) ?? [];
+ // $data['gpa_special_condition_label'] = str_replace(',', '', $this->request->getPost("gpa_special_condition_label")) ?? [];
+ // $data['gpa_special_condition_input'] = str_replace(',', '', $this->request->getPost("gpa_special_condition_input")) ?? [];
+ // $data['multiple_sum_insured'] = str_replace(',', '', $this->request->getPost("multiple_sum_insured")) ?? [];
+ $fieldsWithCommaRemoval = [
+ 'accidentalDeathBenefit',
+ 'permanentTotalDisablement',
+ 'medical_expenses_medical_extension',
+ 'opd_treatment_cover',
+ 'ambulanceCharges',
+ 'repatriation_of_mortal_remains',
+ 'childrenEducationWelfareFund',
+ 'gpa_special_condition_label',
+ 'gpa_special_condition_input',
+ 'multiple_sum_insured',
+ ];
+
+ $fieldsWithoutCommaRemoval = [
+ 'permanentPartialDisablement',
+ 'temporaryTotalDisablementBenefit',
+ 'terrorism',
+ 'worldwideCover',
+ 'family_transportation_benefits',
+ 'fractures_dislocation_burns',
+ 'coma',
+ 'carriageOfDeadBody',
+ 'compassionateVisitExpenses',
+ 'travel_expenses_for_medical_treatment',
+ 'daily_cash_allowance',
+ 'artifical_limb_and_prosthesis',
+ 'animalSnakeInsectBite',
+ 'air_ambulance'
+ ];
+
+ // Remove commas and assign if present
+ foreach ($fieldsWithCommaRemoval as $field) {
+ $value = $this->request->getPost($field);
+ if ($value !== null) {
+ $data[$field] = str_replace(',', '', $value);
+ }
+ }
+
+ // Direct assign if present
+ foreach ($fieldsWithoutCommaRemoval as $field) {
+ $value = $this->request->getPost($field);
+ if ($value !== null) {
+ $data[$field] = $value;
+ }
+ }
+
$data['enrollment_display_key'] = $this->enrollmentGPADisplayValueTransform();
// print_r($data); die;
@@ -3283,11 +3493,29 @@ class ClientController extends AdminController
$client_policy_id = $this->request->getPost("client_policy_id");
$policy_terms = $this->request->getPost("policy_terms");
+ $policy_terms = json_decode($policy_terms, true);
- if (!empty($policy_terms)) {
- $policy_terms = json_decode($policy_terms, true);
+ $data = [];
+
+ foreach ($policy_terms as $key => $value) {
+
+ if (str_ends_with($key, '_display')) {
+
+ $original_key = substr($key, 0, -8);
+
+ $newKey = implode(' ', array_map('ucfirst', explode('_', $original_key)));
+
+ $data['enrollment_display_key'][$newKey] = $policy_terms[$original_key] ?? " ";
+
+ } else {
+
+ $data[$key] = $value;
+ }
+ }
+
+ if (!empty($data)) {
$policy_terms['is_payable_employee']['self'] = 0;
- $policy_terms = json_encode($policy_terms);
+ $policy_terms = json_encode($data);
}
@@ -3675,6 +3903,7 @@ class ClientController extends AdminController
}
}
+ //Function for get all client, branch and policy data
public function getClientAndBranchAndPolicy()
{
// ---------for client-----------------------------------------------------------------------------
@@ -3725,6 +3954,7 @@ class ClientController extends AdminController
policy_type.iep,
policy_type.itp,
policy_type.bap,
+ policy_type.allocg,
DATE_FORMAT(client_policy.policy_start_date, '%d/%m/%Y') as policy_start_date,
DATE_FORMAT(client_policy.policy_end_date, '%d/%m/%Y') as policy_end_date
")
@@ -3792,6 +4022,7 @@ class ClientController extends AdminController
$cdmData = $this->CDMasterModel
->where('client_id', $client)
->where('insurer_id', $insurer)
+ ->where('is_active', 1)
->findAll();
if ($cdmData) {
@@ -3820,13 +4051,13 @@ class ClientController extends AdminController
'dob' => change_date_format($postData['dob'],'d/m/Y','Y-m-d'),
'aadhar' => $postData['aadhar'],
'phone' => $postData['phone'],
- 'email' => $postData['email'],
'entity_type_id' => 7
]);
} else {
$client_data['entity_type_id'] = $postData['entity_type_id'];
}
+ // print_rr($client_data);die();
// Insert client data
$client_insert = $this->clientModel->insert($client_data);
@@ -3836,13 +4067,13 @@ class ClientController extends AdminController
// Additional logic for non-individual clients (client_type != 2)
if ($client_type != 2) {
- $unit = $postData['short_name'] . '-' . $postData['branch_code'];
+ $unit[] = $postData['short_name'] . '-' . $postData['branch_code'];
$branch_data = [
'client_id' => $client_insert,
'branch_name' => $postData['branch_name'],
'branch_code' => $postData['branch_code'],
'gst' => $postData['gst'],
- 'units' => $unit,
+ 'units' => json_encode($unit) ?? null,
];
$branch_insert = $this->clientBranchModel->insert($branch_data);
@@ -3852,6 +4083,8 @@ class ClientController extends AdminController
'contact_type' => 'client',
'name' => $postData['name'],
'mobile' => $postData['mobile'],
+ 'email' => $postData['email'],
+
];
$this->levelContactModel->insert($contact_data);
}
@@ -3981,8 +4214,9 @@ class ClientController extends AdminController
}
}
- public function get_client_policy_data_using_policy_no($policy_no)
- {
+ public function get_client_policy_data_using_policy_no()
+ {
+ $policy_no = $this->request->getGet('policy_no');
$data = $this->clientPolicyModel
->select("
client_policy.*,
@@ -4002,8 +4236,11 @@ class ClientController extends AdminController
}
}
- public function get_client_policy_data_using_policy_no_and_endo_no($policy_no, $endorsement_no)
- {
+ public function get_client_policy_data_using_policy_no_and_endo_no()
+ {
+ $policy_no = $this->request->getGet('policy_no');
+ $endorsement_no = $this->request->getGet('endorsement_no');
+
$data = $this->clientPolicyModel
->select('client_policy.*, endorsement.endorsement_type')
->join('endorsement', 'client_policy.id = endorsement.client_policy_id')
@@ -4027,7 +4264,8 @@ class ClientController extends AdminController
->join('clients', 'client_branch.client_id = clients.id')
->where(['client_branch.id' => $id, 'client_branch.is_active' => 1])
->first();
- $branch_contact_data = $this->levelContactModel->where(['ref_id' => $id, 'contact_type' => 'client', 'is_active' => 1])->orderBy('id','asc')->first();
+ $branch_contact_data = $this->levelContactModel->where(['ref_id' => $id, 'contact_type' => 'client', 'is_active' => 1])->findAll();
+ // print_rr($branch_contact_data);die();
return $this->respond(['status' => true, 'code' => 200, 'data' => $branch_data, 'contact' => $branch_contact_data], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
@@ -4569,6 +4807,11 @@ class ClientController extends AdminController
public function sendextraparam()
{
+ // $data = db_connect()->table('jobs')->where('id', 1677)->get()->getRowArray();
+ // // dd($data);
+ // $return = $this->updatePolicyTransactionDataWhileClinetPolicyUpdate(json_decode($data['payload'], true));
+ // dd($return);
+ // die;
// $employeeController = new EmployeeController();
// $employeeController->truncateFileData('633');
@@ -4581,15 +4824,37 @@ class ClientController extends AdminController
// $employeeRestController->employeesOnboardProcess(['file_id' => 835]);
// $employeeRestController->employeesEnrollmentInsert(['file_id' => 836]);
// $r = Jobs::addJob(['job_name' => 'employeesEnrollmentInsert','payload' => ['file_id' => 721]]);
+ $empServiceController = new EmployeeServiceController();
+ // $res = $empServiceController->excelFileFormatValidation(['file_id' => '865']);
+ // $res = $empServiceController->excelFileDataValidation(['file_id' => '865']);
+ // $res = $empServiceController->employeesSIEnhanceProcess(['file_id' => '978']);
+ // $res = $empServiceController->employeeDisembark(['file_id' => '858']);
+
+ $policyTransactionController = new PolicyTransactionController();
+ // $res = $policyTransactionController->validateInsurerStatement(['file_id' => '17']);
+ // $res = $policyTransactionController->updateInsurerStatement(['file_id' => '22']);
+ // dd('-----', $res);
// ----------EMP DATA SERVICE CONTROLLER--------------------------------------------------------------------------------
// $batch_data = [
- // 'client_id' => 17,
- // 'client_policy_id' => 30,
- // 'client_branch_id' => 18,
- // 'event_type' => "inception",
+ // 'client_id' => 29,
+ // 'client_policy_id' => 17,
+ // 'client_branch_id' => 15,
+ // 'insurer_or_tpa' => "insurer",
+ // 'event_type' => "deletion",
+ // ];
+
+ // $batch_data = [
+ // 'client_id' => 89,
+ // 'client_policy_id' => 328,
+ // 'client_branch_id' => 88,
+ // 'insurer_or_tpa' => "insurer",
+ // // 'insurer_or_tpa' => "tpa",
+ // 'event_type' => "si_enhancement",
+ // 'file_name' => "si_enhancement_test_file.xlsx",
+ // 'actions' => "export",
// ];
// $batch_data['insurer_or_tpa'] = 'insurer';
@@ -4604,11 +4869,18 @@ class ClientController extends AdminController
// $ids = array_column($emp_data, 'id');
// $EmpDataServiceController->sendMailForDownloadingECard($ids);
- // $EmpDataServiceController = new EmpDataServiceController();
+ $EmpDataServiceController = new EmpDataServiceController();
+ // $EmpDataServiceController->generateExcelForSIEnhancement($batch_data); die;
+ // $EmpDataServiceController->importInceptionFileValidation(['file_id' => 1932]); die;
// $EmpDataServiceController->importDeletionValidation(['file_id' => 304]); //for live
+ // $EmpDataServiceController->importSIEnhancementUpdateEndorsementID(['file_id' => 1199]); //for live
+ // $EmpDataServiceController->importSIEnhancementValidation(['file_id' => 1205]); //for live
+ // $EmpDataServiceController->importInceptionUpdateTPAandUHID(['file_id' => 214]); //for live
// $result = $this->employeePolicyModel->getDeletionEmployeeDataForExportExcel($batch_data);
- // print_rr($result); die;
+ // $result = $this->employeePolicyModel->getSIEnhancementEmployeesDataForExportExcel($batch_data, 1);
+ // return $this->downloadInsurerExcelExport($batch_data);
+ // dd($result); die;
// $empServiceController = new EmployeeServiceController();
// $res = $empServiceController->employeesOnboardPreprocess(['file_id' => '741']);
@@ -4617,7 +4889,7 @@ class ClientController extends AdminController
// $res = $PolicyTransactionController->validateInsurerStatement(['file_id' => '36']);
// $empServiceController = new EmployeeServiceController();
- // $res = $empServiceController->excelFileDataValidation(['file_id' => '319']);
+ // $res = $empServiceController->excelFileDataValidation(['file_id' => '1101']);
// dd($res);
// $EmpDataServiceController = new EmpDataServiceController();
@@ -4629,6 +4901,13 @@ class ClientController extends AdminController
// $EmpDataServiceController->importDeletionValidation(['file_id' => 171]);
// $EmpDataServiceController->importDeletionUpdateEndorsementID(['file_id' => 171]);
// $EmpDataServiceController->importCorrectionUpdateEndorsementID(['file_id' => 188]);
+
+ // $params = [
+ // 'client_policy_id' => 6090,
+ // 'action_type' => "inception",
+ // ];
+ // $res = $EmpDataServiceController->makeEntryForBDSPolicyTransaction($params);
+ // dd($res);
// $array = [
// "employeeIds" => ["12800", "12798", "12797", "12799"],
@@ -4650,7 +4929,7 @@ class ClientController extends AdminController
// ------------- LEADS CONTROLLER ----------------------------------------------------------
- // $LeadsController = new LeadsController();
+ $LeadsController = new LeadsController();
// $RFQModel = new RFQModel();
// $data = $RFQModel->where('is_active', 1)->where('lead_id', 40)->first();
@@ -4664,6 +4943,8 @@ class ClientController extends AdminController
// $returndata = $LeadsController->convertQCRJsonToPolicyTerms($jsonArray, $policy_type, $proposel_name, $insurer_name);
// dd($returndata);
+ // $LeadsController->handleMemberDataGPATotalSumInsurerFromExcel(['lead_id' => 169]);
+
// -----------BDS REPORT CONTROLLER---------------------------------------------------------------------------------
// $BDSReportController = new BDSReportController();
@@ -4711,6 +4992,66 @@ class ClientController extends AdminController
// $empmodel = new EmployeeModel();
// $data = $empmodel->getEmployeePolicy(348);
// dd($data);
+
+
+ $LeadsController = new LeadsController();
+ $RFQModel = new RFQModel();
+ // $path = $LeadsController->constructNonEbExcelToSaveTemp(106, 2, "Proposal 2-ICICIPRU-ICICI001");
+ // $filepath = $path['filePath'];
+
+ // if (file_exists($filepath)) {
+ // // Set headers to force download
+ // header('Content-Description: File Transfer');
+ // header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
+ // header('Content-Disposition: attachment; filename="' . basename($filepath) . '"');
+ // header('Content-Length: ' . filesize($filepath));
+ // header('Pragma: public');
+
+ // // Output the file content
+ // readfile($filepath);
+
+ // // Delete the file after download
+ // unlink($filepath);
+
+ // exit;
+ // } else {
+ // echo "File does not exist.";
+ // }
+
+ // $data = $this->leadsModel->where('leads.id', 125)->where('leads.is_active', 1)->first();
+ // $RFQdata = $RFQModel->getRFQTableDataWithLeadIDAndType(145, 2);
+ // $returnData = $LeadsController->getPlacementJson($data);
+ // Kint::dump($returnData);
+ // $policy_terms = $LeadsController->convertNonEbQCRJsonToPolicyTerms(json_decode($returnData, true));
+ // Kint::dump($policy_terms);
+
+ // // $this->clientPolicyModel->where('id', 6050)->set('placement_json', $returnData)->update();
+ // $this->clientPolicyModel->where('id', 6050)->set('policy_terms', $policy_terms)->update();
+ // dd($returnData);
+
+ // Kint::dump($RFQdata['json']);
+ // $inputJson = json_decode($RFQdata['json'], true);
+ // Kint::dump($inputJson);
+ // // print_rr($inputJson['table_data']);
+ // $sortedJson = $this->reorderProposalsByInsurerTotal($inputJson);
+
+ // // If you want to convert back to JSON string
+ // $finalJson = json_encode($sortedJson, JSON_PRETTY_PRINT);
+
+ // // $RFQModel->insert(['lead_id' => 145, 'json' => $finalJson, 'type' => 1]);
+
+ // dd($finalJson);
+
+ // $baseWhere = [
+ // 'client_id' => 159,
+ // 'client_policy_id' => 336,
+ // 'insurer_id' => 1,
+ // 'cd_ac_pk' => 56,
+ // 'event_name' => "addition",
+ // ];
+ // $return_value = check_cd_entry_exist($baseWhere);
+ // dd($return_value);
+
}
// -------------------------------------------------------------------------------------------------------
@@ -4881,8 +5222,10 @@ class ClientController extends AdminController
->where('insurers.is_active', 1)
->where('tpa.is_active', 1)
->where('employees.is_active', 1)
+ ->where('employees.emp_status', "active")
->where('employees.relationship', "Self")
->where('employee_polices.is_active', 1)
+ ->where('employee_polices.status', "active")
->where($field_name, $param);
if (!empty($client_id)) {
@@ -5416,6 +5759,241 @@ class ClientController extends AdminController
$id = $InsurerModel->insert($insurerData);
return $id;
}
+
+ private function reorderProposalsByInsurerTotal(array $data): array {
+
+ Kint::dump($data);
+ if (!isset($data['premium_data']['data'])) return $data;
+ $original = $data['premium_data']['data'];
+ $proposals = [];
+ $others = [];
+ $emptyKeyData = [];
+ foreach ($original as $key => $value) {
+ // Match only keys that look like 'Proposal X'
+ if (preg_match('/^Proposal\s+\d+$/', $key)) {
+ // Get the insurer entry (not 'Quote Asked')
+ foreach ($value as $subKey => $subVal) {
+ if ($subKey !== 'Quote Asked' && isset($subVal['Total'])) {
+ $proposals[$key] = $value;
+ break;
+ }else{
+ $proposals[$key] = $value;
+ }
+ }
+ } else {
+
+ if ($key === '' && isset($value['']) && is_array($value[''])) {
+ // Capture empty key to push it later
+ $emptyKeyData[$key] = $value;
+ }else{
+ $others[$key] = $value;
+
+ }
+ }
+ }
+
+ // dd($proposals, $others, $emptyKeyData);
+ // Sort proposals by their insurer's total
+ uasort($proposals, function($a, $b) {
+ $totalA = 0;
+ $totalB = 0;
+
+ foreach ($a as $key => $val) {
+ if ($key !== 'Quote Asked' && isset($val['Total'])) {
+ $totalA = floatval($val['Total']);
+ break;
+ }
+ }
+
+ foreach ($b as $key => $val) {
+ if ($key !== 'Quote Asked' && isset($val['Total'])) {
+ $totalB = floatval($val['Total']);
+ break;
+ }
+ }
+
+ return $totalA <=> $totalB;
+ });
+
+ // Merge back the sorted proposals into the full structure
+ $data['premium_data']['data'] = array_merge($others, $proposals, $emptyKeyData);
+ $data = $this->reorderProposalDataByPremiumOrder($data);
+ return $data;
+ }
+
+ private function reorderProposalDataByPremiumOrder(array $data): array {
+ if (!isset($data['premium_data']['data'], $data['proposal_data']['over_all_column_data'])) {
+ return $data;
+ }
+
+ $premiumProposals = array_keys($data['premium_data']['data']);
+ $filteredProposals = [];
+
+ // Collect proposal keys that match the pattern "Proposal X"
+ foreach ($premiumProposals as $key) {
+ if (preg_match('/^Proposal\s+\d+$/', $key) && isset($data['proposal_data']['over_all_column_data'][$key])) {
+ $filteredProposals[$key] = $data['proposal_data']['over_all_column_data'][$key];
+ }
+ }
+
+ // dd($premiumProposals, $filteredProposals);
+
+ $data['proposal_data']['over_all_column_data'] = $filteredProposals;
+ $data = $this->reorderProposalInHeaderAndData($data);
+ return $data;
+ }
+
+ private function reorderProposalInHeaderAndData(array $data): array {
+
+ // Kint::dump($data);
+ $tableData = $data['table_data'];
+ $sortedProposalOrder = $data['proposal_data']['over_all_column_data'];
+ $headers = $tableData['headers'] ?? [];
+ $dataRows = $tableData['data'] ?? [];
+
+ // Step 1: Separate static and proposal headers
+ $staticHeaders = [];
+ $proposalHeaders = [];
+ $actionHeader = [];
+ foreach ($headers as $header) {
+ if (in_array($header['parentHeader'], array_keys($sortedProposalOrder))) {
+ $proposalHeaders[$header['parentHeader']] = $header;
+ } else {
+ if($header['parentHeader'] == "Action"){
+ $actionHeader[] = $header;
+ }else{
+ $staticHeaders[] = $header;
+ }
+ }
+ }
+
+ // dd($staticHeaders, $proposalHeaders, $sortedProposalOrder);
+
+ // Step 2: Reorder headers
+ $reorderedHeaders = [];
+ foreach ($sortedProposalOrder as $proposalKey => $proposalValue) {
+ if (isset($proposalHeaders[$proposalKey])) {
+ $reorderedHeaders[] = $proposalHeaders[$proposalKey];
+ }
+ }
+
+ // print_rr($reorderedHeaders); die;
+ foreach ($reorderedHeaders as $key => &$value) {
+ $value['parentHeader'] = 'Proposal ' . ($key + 1);
+ }
+ unset($value);
+
+
+ $reorderedHeaders = array_merge($staticHeaders, $reorderedHeaders, $actionHeader);
+
+
+ // Step 3: Reorder each row's `data` by matching parentth
+ foreach ($dataRows as $dataRowIndex => &$row) {
+ $staticData = [];
+ $proposalData = [];
+ $actionData = [];
+
+ foreach ($row['data'] as $entry) {
+ if (in_array($entry['parentth'], array_keys($sortedProposalOrder))) {
+ $proposalData[$entry['parentth']][] = $entry;
+ } else {
+ if($entry['parentth'] == "Action"){
+ $actionData[] = $entry;
+ }else{
+ $staticData[] = $entry;
+ }
+ }
+ }
+
+ $reorderedProposalData = [];
+ foreach ($sortedProposalOrder as $proposalKey => $proposalValue) {
+ if (isset($proposalData[$proposalKey])) {
+ foreach ($proposalData[$proposalKey] as $entry) {
+ $reorderedProposalData[] = $entry;
+ }
+ }
+ }
+
+ $dubParTh = "";
+ $increament = 0;
+ foreach ($reorderedProposalData as $key => &$value) {
+
+ if($dubParTh == $value['parentth']){
+ $value['parentth'] = 'Proposal ' . ($increament);
+ }else{
+ $dubParTh = $value['parentth'];
+ $increament = $increament + 1;
+ $value['parentth'] = 'Proposal ' . ($increament);
+ }
+ }
+ unset($value);
+
+ $row['data'] = array_merge($staticData, $reorderedProposalData, $actionData);
+ }
+
+ $data['table_data']['headers'] = $reorderedHeaders;
+ $data['table_data']['data'] = $dataRows;
+
+ // dd('-----', $data);
+ $renumberedArray = $this->renumberProposalKeys($data['proposal_data']['over_all_column_data']);
+ $updatedDataSet = $this->renumberProposalKeys($data['premium_data']['data']);
+ $data['proposal_data']['over_all_column_data'] = !empty($renumberedArray) ? $renumberedArray : $data['proposal_data']['over_all_column_data'];
+ $data['premium_data']['data'] = !empty($updatedDataSet) ? $updatedDataSet : $data['premium_data']['data'];
+
+ return $data;
+ }
+
+ private function renumberProposalKeys(array $input): array {
+ $result = [];
+ $counter = 1;
+
+ foreach ($input as $key => $value) {
+ if (strpos($key, 'Proposal') === 0) {
+ $newKey = 'Proposal ' . $counter++;
+ $result[$newKey] = $value;
+ } else {
+ $result[$key] = $value;
+ }
+ }
+
+ return $result;
+ }
+ public function saveApiData(){
+
+ $receivedData = $this->request->getPost();
+
+ if (!empty($receivedData['id'])){
+ $status = $this->clientApi->save($receivedData);
+
+ }else{
+ $status = $this->clientApi->insert($receivedData);
+ }
+
+
+ if ($status){
+ return $this->respond(['status'=>"Sucesss",'message'=>"Submitted Successfully"],200);
+ }else{
+ return $this->respond(['status'=>"Failed",'message'=>"Submission Faild"],500);
+ }
+
+ }
+
+ public function sendToken(){
+
+ $client_id = $this->request->getGet('client_id');
+
+ $token = ClientTokenHelper::generateKey($client_id);
+
+ if ($token){
+ return $this->respond(['status' => 'success', 'token' => $token,'message' => "Token Generated Successfully"],200);
+ }else{
+ return $this->respond(['status' => "Failed","message"=>"Token Generation Failed, Try Again After some time"],500);
+ }
+ }
+
+
}
+
+
diff --git a/app/Controllers/ClientWebHooksController.php b/app/Controllers/ClientWebHooksController.php
new file mode 100644
index 00000000..a54deaf2
--- /dev/null
+++ b/app/Controllers/ClientWebHooksController.php
@@ -0,0 +1,319 @@
+myLogger = \Config\Services::mylogger();
+
+ //models
+ $this->clientAPI = new ClientApiModel();
+ $this->clientPolicy = new ClientPolicyModel();
+
+ // Helpers
+ $this->webHookHelper = new clientWebHookHelper();
+ $this->clientTokenHelper = new ClientTokenHelper();
+ }
+
+ public function pushData($clientID, $type)
+ {
+ if ($type == 1) {
+
+ $webHookType = "emp";
+ } else if ($type == 2) {
+
+ $webHookType = "claim";
+ }
+ log_message('error', 'Client ID: ' . $clientID);
+ log_message('error', 'Webhook Type: ' . $webHookType);
+ // Validate client ID
+ if (empty($clientID)) {
+ return $this->respond(["status" => "Failure", "error" => ["message" => 'Client ID is required.', "code" => 400]], 400);
+ }
+ $webhookData = $this->clientAPI->where('client_id', $clientID)->where('is_active', 1)->first();
+ if (empty($webhookData)) {
+ log_message('error', 'Client Not Found or Unauthorized');
+ return $this->respond(["status" => "Failure", "error" => ["message" => 'Client Not Found or Client Does not have any Active Hooks.', "code" => 404]], 404);
+ }
+ $url = $webhookData[$webHookType . '_url'];
+ if (empty($url)) {
+ log_message('error', 'No active webhook found for the client.');
+ return $this->respond(["status" => "Failure", "error" => ["message" => 'No active webhook found for the client.', "code" => 404]], 404);
+ }
+
+
+ $method = $webhookData[$webHookType . '_method'];
+ $auth_method = $webhookData[$webHookType . '_tkn_type'];
+ $token = $webhookData[$webHookType . '_token'];
+ $objectType = json_decode($webhookData[$webHookType . '_obj']);
+
+ try {
+ $client = \Config\Services::curlrequest();
+ $data = [
+ "name" => "Kavitha",
+ "emp_code" => "EMP001-K4",
+ "emp_status" => "active",
+ "mobile" => "2233448965"
+ ];
+
+ try {
+ $mapped_data = $this->webHookHelper->mapObjectType($data, $objectType);
+ } catch (Exception $e) {
+ $errorMessage = "Object Mapping Failed: " . $e->getMessage();
+ log_message('error', $errorMessage);
+
+ return $this->respond(['status' => 'Failure', 'error' => ['code' => 500, 'message' => "Object Mapping Failed"]], 500);
+ }
+
+ // Create payload
+ $payload = [
+ 'event_type' => 'insert',
+ 'timestamp' => date('c'),
+ 'data' => $mapped_data
+ ];
+
+ log_message("error", "Payload: " . json_encode($payload));
+
+ // Configure request headers
+ $headers = ['Content-Type' => 'application/json'];
+ if ($auth_method && $token) {
+ if (strtolower($auth_method) === 'bearer') {
+ $headers['Authorization'] = 'Bearer ' . $token;
+ } else {
+ $headers[$auth_method] = $token;
+ }
+ }
+
+ // Configure request based on method
+ $options = [
+ 'headers' => $headers,
+ 'timeout' => 10,
+ 'http_errors' => false // Don't throw exceptions for 4xx/5xx responses
+ ];
+
+ if ($method === 'GET') {
+ $options['query'] = $payload;
+ } else {
+ $options['json'] = $payload;
+ }
+
+ // Execute webhook request
+ $response = $client->request($method, $url, $options);
+ $statusCode = $response->getStatusCode();
+ $responseBody = $response->getBody();
+
+ // Log and format response
+ $logMessage = "Webhook to {$url} returned status: {$statusCode}";
+ log_message('error', $logMessage);
+
+ return $this->respond(['status' => 'Success', "response" => $responseBody], $statusCode);
+ } catch (\Throwable $e) {
+ $errorMessage = "Webhook failed: " . $e->getMessage();
+ log_message('error', $errorMessage);
+
+ return $this->respond(['status' => 'Failure', 'error' => ['code' => 500, 'message' => $errorMessage, 'exception' => get_class($e)]], 500);
+ }
+ }
+
+ public function validateToken($type)
+ {
+ $type = $type == 1 ? "pull_emp_token" : "pull_claim_token";
+ try {
+
+ $authHeader = $this->request->getHeaderLine('Authorization');
+
+ // Check if header exists
+ if (empty($authHeader)) {
+ log_message('error', 'Authorization header missing');
+ return $this->respond(['status' => "Failure", 'error' => ['message' => 'Authorization header missing', 'code' => 401]], 401);
+ }
+
+ // Check if Bearer is present
+ if (!str_contains($authHeader, 'Bearer ')) {
+ log_message('error', 'Authorization Bearer missing');
+ return $this->respond(['status' => "Failure", 'error' => ['message' => 'Invalid Authorization header', 'code' => 401]], 401);
+ }
+
+ // Extract the token
+ $token = str_replace('Bearer ', '', $authHeader);
+ if (empty($token)) {
+
+ log_message('error', 'Empty Token');
+ return $this->respond(['status' => "Failure", 'error' => ['message' => 'Invalid Token Format', 'code' => 401]], 401);
+ }
+
+ try {
+
+ // Extract client_id from the token
+ $client_id = ClientTokenHelper::extractClientId($token);
+ } catch (\Exception $e) {
+ log_message('error', 'Invalid Client Token Format');
+
+ return $this->respond(['status' => "Failure", 'error' => 'Invalid Token Format'], 401);
+ }
+
+ // Fetch client details from the database
+ $client = $this->clientAPI->where('client_id', $client_id)->where("is_active", 1)->where("api_access", 1)->first();
+
+ // Client validation
+ if (!$client) {
+ log_message('error', 'Client Not Found or Unauthorized');
+ return $this->respond(['status' => "Failure", 'error' => ['message' => 'Client not found or unauthorized', 'code' => '403']], 403);
+ }
+
+ // Validate the token
+ if (hash_equals($client[$type], $token)) {
+ log_message('error', 'Access Granted For Client : ' . $client_id);
+ return true;
+ } else {
+ log_message('error', 'Invalid Token given for client : ' . $client_id);
+ return $this->respond([
+ 'status' => "Failure",
+ 'error' => ['message' => 'Invalid token', 'code' => 401]
+ ], 401);
+ }
+ } catch (\Exception $e) {
+ log_message('error', 'Error in ClientAPIController:validateToken - ' . $e->getMessage());
+ return $this->respond(['status' => "Failure", 'error' => ['message' => 'Internal Server Error', 'code' => 500]], 500);
+ }
+ }
+
+ public function getClientIdfromToken()
+ {
+ $authHeader = $this->request->getHeaderLine('Authorization');
+ $token = str_replace('Bearer ', '', $authHeader);
+ $client_id = ClientTokenHelper::extractClientId($token);
+
+ log_message('error', 'Client ID: ' . $client_id);
+ return [$client_id, $token];
+ }
+
+ public function pullData_emp()
+ {
+ $validationStatus = $this->validateToken(1);
+
+ $data = $this->getClientIdfromToken();
+ $client_id = $data[0];
+
+ log_message('error', "Pull data emp from Client ID: ". $client_id);
+ $client = $this->clientAPI->where('client_id', $client_id)->where("is_active", 1)->where("api_access", 1)->first();
+ if (empty($client)) {
+ log_message('error', 'Client Not Found or Unauthorized');
+ return $this->respond(['status' => 'Failure', 'error' => ['code' => 404, 'message' => 'Client Not Found or Unauthorized']], 404);
+ }
+
+ $objectType = $client['pull_emp_obj'];
+
+ if ($validationStatus) {
+ $responseBody = $this->request->getBody();
+ $data_to_map = json_decode($responseBody, true);
+ $objectType = json_decode($objectType, true);
+ if (!isset($data_to_map['data']) || !is_array($data_to_map['data'])) {
+
+ log_message('error', "Invalid Response from Endpoint 'data' Key Missing");
+ return $this->respond(['status' => 'Failure', 'error' => ['code' => 500, 'message' => "Invalid Response from Endpoint 'data' Key Missing"]], 500);
+ }
+
+ foreach ($data_to_map['data'] as $index => $item) {
+
+ try {
+ $mapped_data = $this->webHookHelper->mapObjectType($item, $objectType);
+ } catch (Exception $e) {
+ $errorMessage = "Object Mapping Failed: " . $e->getMessage();
+ log_message('error', $errorMessage);
+
+ return $this->respond(['status' => 'Failure', 'error' => ['code' => 500, 'message' => "Object Mapping Failed"]], 500);
+ }
+
+ try {
+ $mapped_data['client_id'] = $client_id;
+ $this->webHookHelper->insertData($mapped_data, 1);
+ } catch (Exception $e) {
+ $errorMessage = "Data Insertion Failed: " . $e->getMessage();
+ log_message('error', $errorMessage);
+
+ return $this->respond(['status' => 'Failure', 'error' => ['code' => 500, 'message' => "Data Insertion Failed"]], 500);
+ }
+ }
+
+ log_message('error', "Data Inserted Successfully for Client ID: " . $client_id);
+ // Return success response
+ return $this->respond(['status' => 'Success', 'message' => "Data Inserted Successfully"], 200);
+ }
+ }
+
+ public function pullData_claim()
+ {
+ $validationStatus = $this->validateToken(2);
+
+ $data = $this->getClientIdfromToken();
+ $client_id = $data[0];
+ log_message('error', "Pull data claim from Client ID: ". $client_id);
+ $client = $this->clientAPI->where('client_id', $client_id)->where("is_active", 1)->where("api_access", 1)->first();
+ if (empty($client)) {
+ log_message('error', 'Client Not Found or Unauthorized');
+ return $this->respond(['status' => 'Failure', 'error' => ['code' => 404, 'message' => 'Client Not Found or Unauthorized']], 404);
+ }
+
+ $objectType = $client['pull_claim_obj'];
+
+ if ($validationStatus) {
+ $responseBody = $this->request->getBody();
+ $data_to_map = json_decode($responseBody, true);
+ $objectType = json_decode($objectType, true);
+ if (!isset($data_to_map['data']) || !is_array($data_to_map['data'])) {
+
+ log_message('error', "Invalid Response from Endpoint 'data' Key Missing");
+ return $this->respond(['status' => 'Failure', 'error' => ['code' => 500, 'message' => "Invalid Response from Endpoint 'data' Key Missing"]], 500);
+ }
+ foreach ($data_to_map['data'] as $index => $item) {
+ try {
+ $mapped_data = $this->webHookHelper->mapObjectType($item, $objectType);
+ } catch (Exception $e) {
+ $errorMessage = "Object Mapping Failed: " . $e->getMessage();
+ log_message('error', $errorMessage);
+
+ return $this->respond(['status' => 'Failure', 'error' => ['code' => 500, 'message' => "Object Mapping Failed"]], 500);
+ }
+
+ try {
+ $mapped_data['client_id'] = $client_id;
+ $this->webHookHelper->insertData($mapped_data, 2);
+ } catch (Exception $e) {
+ $errorMessage = "Data Insertion Failed: " . $e->getMessage();
+ log_message('error', $errorMessage);
+
+ return $this->respond(['status' => 'Failure', 'error' => ['code' => 500, 'message' => "Data Insertion Failed"]], 500);
+ }
+ }
+
+
+ log_message('error', "Data Inserted Successfully for Client ID: " . $client_id);
+ // Return success response
+ return $this->respond(['status' => 'Success', 'message' => "Data Inserted Successfully"], 200);
+ }
+ }
+}
diff --git a/app/Controllers/DashboardController.php b/app/Controllers/DashboardController.php
index d1a48afb..b9ed11a4 100755
--- a/app/Controllers/DashboardController.php
+++ b/app/Controllers/DashboardController.php
@@ -21,6 +21,10 @@ use App\Models\NotificationModel;
use App\Models\EmployeePolicyModel;
use App\Controllers\PendingActionsContrller;
use App\Controllers\EmpDataServiceController;
+use App\Models\TicketMasterModel;
+use App\Models\LeadsModel;
+use App\Models\TicketClaimStatusModel;
+
class DashboardController extends AdminController
{
@@ -33,8 +37,12 @@ class DashboardController extends AdminController
protected $notificationModel;
protected $employeePolicyModel;
protected $policyTransactionModel;
+ protected $leadModel;
+ protected $ticketModel;
+ protected $ticketStatusModel;
protected $policyStatus;
protected $colorShades;
+ protected $claimDashLimit;
protected $myLogger;
@@ -48,9 +56,76 @@ class DashboardController extends AdminController
$this->employeePolicyModel = new EmployeePolicyModel();
$this->clientModel = new ClientModel();
$this->policyTransactionModel = new PolicyTransactionModel();
+ $this->ticketModel = new TicketMasterModel();
+ $this->leadModel = new LeadsModel();
+ $this->ticketStatusModel = new TicketClaimStatusModel();
$this->myLogger = \Config\Services::mylogger();
+ $this->claimDashLimit = [
+ 1 => [
+ 'non_id' => 3,
+ 'id_not_generated' => 3,
+ 'cda' => 3,
+ 'information_required' => 3,
+ 'under_process' => 3,
+ 'rejected' => 3,
+ 'approved' => 3,
+ 'payment_initiated' => 3,
+ 'settled' => 3,
+ 'closed' => 3,
+ 'cancelled' => 3,
+ 'returned' => 3
+ ],
+
+ 2 => [
+ 'claim_intimation' => 3,
+ 'intimation_to_insurer' => 3,
+ 'client_pending' => 3,
+ 'insurer_pending' => 3,
+ 'investigation' => 3,
+ 'approved' => 3,
+ 'closed' => 3,
+ 'not_covered' => 3,
+ 'settled' => 3,
+ 'coverage_check' => 3,
+ 'cancelled' => 3,
+ 'returned' => 3,
+ 'rejected' => 3,
+ 'dv_sent_to_insured' => 3
+ ],
+ 3 => [
+ 'claim_intimation' => 3,
+ 'intimation_to_insurer' => 3,
+ 'client_pending' => 3,
+ 'insurer_pending' => 3,
+ 'investigation' => 3,
+ 'approved' => 3,
+ 'closed' => 3,
+ 'not_covered' => 3,
+ 'settled' => 3,
+ 'coverage_check' => 3,
+ 'cancelled' => 3,
+ 'returned' => 3,
+ 'rejected' => 3
+ ],
+ 4 => [
+ 'claim_intimation' => 3,
+ 'intimation_to_insurer' => 3,
+ 'client_pending' => 3,
+ 'insurer_pending' => 3,
+ 'investigation' => 3,
+ 'approved' => 3,
+ 'closed' => 3,
+ 'not_covered' => 3,
+ 'settled' => 3,
+ 'coverage_check' => 3,
+ 'cancelled' => 3,
+ 'returned' => 3,
+ 'rejected' => 3
+ ]
+ ];
+
$this->policyStatus = [
'under_process' => 'Under Process',
'client_pending' => 'Client Pending',
@@ -92,7 +167,6 @@ class DashboardController extends AdminController
'linear-gradient(45deg, #494f4f, #353d3d)' // SilverChalice shade 6
]
];
-
}
public function dashboard()
@@ -100,8 +174,10 @@ class DashboardController extends AdminController
$data = [];
- $db = db_connect();
- $sql = "SELECT
+ if (in_array(get_role_id(), [1, 2, 3, 5]) || (in_array(MANAGEMENT_TEAM_ID, user_team()) || in_array(FINANCE_TEAM_ID, user_team()) || in_array(BUSINESS_TEAM_ID, user_team()))) {
+
+ $db = db_connect();
+ $sql = "SELECT
clients.id AS client_id,
clients.client_name,
clients.short_name,
@@ -144,38 +220,89 @@ class DashboardController extends AdminController
GROUP BY clients.id, client_branch.id";
- $query = $db->query($sql);
- $results = $query->getResultArray();
+ $query = $db->query($sql);
+ $results = $query->getResultArray();
- $pendingActionsController = new PendingActionsController;
- $pendingActionsData = $pendingActionsController->getPendingActionsForDashBoard();
- $businessTeamData = $this->policyTransactionModel->getBusinessReportList();
- $financeTeamData = $this->policyTransactionModel->getFinanceReportList();
- $businessTeamStatusData = $this->data_construct_for_bds($businessTeamData);
- $financeTeamStatusData = $this->data_construct_for_bds($financeTeamData);
+ $pendingActionsController = new PendingActionsController;
+ $pendingActionsData = $pendingActionsController->getPendingActionsForDashBoard();
+ $businessTeamData = $this->policyTransactionModel->getBusinessReportList();
+ $financeTeamData = $this->policyTransactionModel->getFinanceReportList();
+ $businessTeamStatusData = $this->data_construct_for_bds($businessTeamData);
+ $financeTeamStatusData = $this->data_construct_for_bds($financeTeamData);
- $data['client_branch_emp_list'] = $results;
- $session = \Config\Services::session();
- $session->set('enrollment_data', json_encode($data));
+ $data['client_branch_emp_list'] = $results;
+ $session = \Config\Services::session();
+ $session->set('enrollment_data', json_encode($data));
+
+ // echo "";
+ $data['pendingActionsData'] = $pendingActionsData;
+ $data['businessTeamCount'] = count($businessTeamData) ?? 0;
+ // dd($businessTeamData);
+ $data['financeTeamCount'] = count($financeTeamData) ?? 0;
+ $data['businessTeamStatusData'] = $businessTeamStatusData;
+ $data['financeTeamStatusData'] = $financeTeamStatusData;
+ $data['policyStatus'] = $this->policyStatus;
+ $data['colorShades'] = $this->colorShades;
+ }
+ if ((get_role_id() == STAFF_ROLE_ID && in_array(CLAIMS_TEAM_ID,user_team())) || in_array(get_role_id(),[1,5])){
+ $data['claim_data'] = $this->getClaimData();
+ $data['colorShades'] = $this->colorShades;
+
+ }
+ if ((get_role_id() == STAFF_ROLE_ID && in_array(ENROLLMENT_TEAM_ID,user_team())) || in_array(get_role_id(),[1,5])){
+ $data['lead_data'] = $this->leadModel->getDashData();
+ $data['bds_renewal'] = $this->policyTransactionModel->getBDSRenewalData();
+ $data['colorShades'] = $this->colorShades;
+
+ }
+
+ // dd(get_role_id(),user_team());
+ // dd($data);
- // echo "";
- $data['pendingActionsData'] = $pendingActionsData;
- $data['businessTeamCount'] = count($businessTeamData) ?? 0;
- $data['financeTeamCount'] = count($financeTeamData) ?? 0;
- $data['businessTeamStatusData'] = $businessTeamStatusData;
- $data['financeTeamStatusData'] = $financeTeamStatusData;
- $data['policyStatus'] = $this->policyStatus;
- $data['colorShades'] = $this->colorShades;
- // print_r($data);die;
-
$data['page_name'] = 'Dashboard';
echo view('layout/header', $data);
echo view('DashBoard', $data);
echo view('layout/footer');
}
-
+
+
+ public function getClaimData()
+ {
+
+ $results = $this->ticketStatusModel
+ ->select("ticket_type as ticket_type_id, claim_status")
+ ->where("is_active", 1)
+ ->findAll();
+
+ $claim_status = [];
+
+ foreach ($results as $row) {
+ if (empty($row['ticket_type_id']) || empty($row['claim_status'])) {
+ continue; // Skip if either value is empty
+ }
+ $typeId = $row['ticket_type_id'];
+ $status = $row['claim_status'];
+
+ // Initialize if not set
+ if (!isset($claim_status[$typeId])) {
+ $claim_status[$typeId] = [];
+ }
+
+ $claim_status[$typeId][$status] = true;
+ }
+
+ // Convert set-like structure to plain array
+ foreach ($claim_status as $typeId => $statuses) {
+ $claim_status[$typeId] = array_keys($statuses);
+ }
+ $data = $this->ticketModel->getDashData($claim_status, $this->claimDashLimit);
+
+
+ return $data;
+ }
+
public function getDashboardNotifications()
{
@@ -208,29 +335,29 @@ class DashboardController extends AdminController
{
$clientPolicyModel = new ClientPolicyModel();
$myLogger = \Config\Services::mylogger();
-
+
$client_policy_data = $clientPolicyModel->getPolicyDetailsForEnrollment();
$myLogger->logme('error', 'Fetched client policy data for Enrollment Status update');
-
+
// dd($client_policy_data);
$currentDate = date('d-m-Y');
$openEnrollment = [];
$closeEnrollment = [];
-
+
// Update policy status based on start and end dates
foreach ($client_policy_data as $client_policy) {
$id = $client_policy['id'];
$openDate = date('d-m-Y', strtotime($client_policy['open_date']));
$closeDate = date('d-m-Y', strtotime($client_policy['close_date']));
-
+
if ($currentDate == $openDate) {
$clientPolicyModel->update($id, ['open_for_enrollment' => 1]);
$openEnrollment[] = $id;
$myLogger->logme('error', 'Updated policy ID ' . $id . ' to open for enrollment.');
}
-
+
if ($closeDate < $currentDate) {
$clientPolicyModel->update($id, ['open_for_enrollment' => 0]);
$closeEnrollment[] = $id;
@@ -239,37 +366,36 @@ class DashboardController extends AdminController
}
$myLogger->logme('error', 'enrollment_status function completed');
- $myLogger->logme('error', 'updated Open Enrollment Policy count : "'.count($openEnrollment).'" and Close Enrollment Policy count : "'.count($closeEnrollment).'"');
+ $myLogger->logme('error', 'updated Open Enrollment Policy count : "' . count($openEnrollment) . '" and Close Enrollment Policy count : "' . count($closeEnrollment) . '"');
return $this->respond([
- 'status' => true,
- 'message' => 'updated Open and Close Enrollment successfully',
- 'open_policy_count' => count($openEnrollment),
+ 'status' => true,
+ 'message' => 'updated Open and Close Enrollment successfully',
+ 'open_policy_count' => count($openEnrollment),
'close_policy_count' => count($closeEnrollment),
- 'open_policy_ids' => $openEnrollment,
+ 'open_policy_ids' => $openEnrollment,
'close_policy_ids' => $closeEnrollment,
]);
-
}
-
+
public function sendCroneRemainderMail()
{
$clientPolicyModel = new ClientPolicyModel();
$myLogger = \Config\Services::mylogger();
-
-
+
+
$client_policy_data = $clientPolicyModel->getPolicyDetailsForRemainder();
$myLogger->logme('error', 'Fetched client policy data');
// dd($client_policy_data);
-
+
// Mail send function
$result = $this->sendRemainderMail($client_policy_data, 'crone');
$myLogger->logme('error', 'sendCroneRemainderMail function completed');
-
- if($result){
+
+ if ($result) {
return json_encode(['status' => true, 'message' => 'Mail send successfully']);
- }else{
+ } else {
return json_encode(['status' => false, 'message' => 'There is no data to send']);
}
}
@@ -281,29 +407,22 @@ class DashboardController extends AdminController
$data = [];
- if($type == 'insurer'){
+ if ($type == 'insurer') {
$data = $pendingActionsData['uhid'];
-
- }else if($type == 'TPA'){
+ } else if ($type == 'TPA') {
$data = $pendingActionsData['tpa'];
-
- }else if($type == 'I'){
+ } else if ($type == 'I') {
$data = $pendingActionsData['inception'];
-
- }else if($type == 'D'){
+ } else if ($type == 'D') {
$data = $pendingActionsData['deletion'];
-
- }else if($type == 'C'){
+ } else if ($type == 'C') {
$data = $pendingActionsData['correction'];
-
- }else if($type == 'SI'){
+ } else if ($type == 'SI') {
$data = $pendingActionsData['si_enhancement'];
-
- }else if($type == 'policy'){
+ } else if ($type == 'policy') {
$data = $pendingActionsData['policy'];
-
- }else if($type == 'ticket'){
+ } else if ($type == 'ticket') {
$data = $pendingActionsData['uhid'];
}
@@ -417,7 +536,6 @@ class DashboardController extends AdminController
$reminder_whole_mail[] = $mail_result;
}
}
-
} else { // crone
if (!empty($client_policy['reminder_date'])) {
@@ -507,15 +625,12 @@ class DashboardController extends AdminController
// $this->myLogger->logme('error', 'Mail sent result: ' . json_encode($mail_result));
$reminder_whole_mail[] = $mail_result;
}
-
}
}
-
} else {
$this->myLogger->logme('error', "SEND REMAINDER CRONE --- Remainder date is empty()");
}
}
-
} else {
$this->myLogger->logme('error', 'Notification setup not found or not enabled');
@@ -545,29 +660,28 @@ class DashboardController extends AdminController
public function sendManualReminder($client_id, $client_branch_id, $client_policy_id = null)
{
- $this->myLogger->logme('error','Log Works');
+ $this->myLogger->logme('error', 'Log Works');
$this->myLogger->logme('error', "sendManualRemainder called with client_id: {$client_id}, client_branch_id: {$client_branch_id}");
-
+
$client_policy_data = $this->clientPolicyModel->getPolicyDetailsForRemainder($client_id, $client_branch_id, $client_policy_id);
// print_r($client_policy_data); die;
// print_r($this->clientPolicyModel->getLastQuery()); die;
// $this->myLogger->logme('error', "Policy details fetched: " . json_encode($client_policy_data));
-
+
if ($client_policy_data) {
$result = $this->sendRemainderMail($client_policy_data);
- log_message('error',json_encode($result));
- $this->myLogger->logme('error',$result);
+ log_message('error', json_encode($result));
+ $this->myLogger->logme('error', $result);
$this->myLogger->logme('error', "Manual Remainder Mail sending result: " . ($result ? 'success' : 'failure'));
-
+
if ($result) {
$this->myLogger->logme('error', 'Manual Remainder Mail sent successfully');
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Mail sent successfully'], 200);
} else {
$this->myLogger->logme('error', 'Failed to send manual remainder mail, no data to send');
- return $this->respond(['status' => false, 'code' => 200, 'message' => 'There is no data to send','message2' => 'Failed' ], 200);
+ return $this->respond(['status' => false, 'code' => 200, 'message' => 'There is no data to send', 'message2' => 'Failed'], 200);
}
-
} else {
$this->myLogger->logme('error', 'No policy data found to send');
return $this->respond(['status' => false, 'code' => 200, 'message' => 'There is no data to send', 'message2' => 'No policy data found to send'], 200);
@@ -577,19 +691,17 @@ class DashboardController extends AdminController
public function sendManualEcard($client_id, $client_branch_id, $policy_id)
{
$this->myLogger->logme('error', "sendManualEcard called with client_id: {$client_id}, client_branch_id: {$client_branch_id}, policy id : {$policy_id}");
-
- $notification = $this->notificationModel->where('client_id', $client_id)->where('template_name', 'member_ecard_mail')->first();
- // print_r(($notification)); die;
- if($notification && $notification['enabled'] == 0 && $notification['mail_content'] == '')
- {
- return $this->respond(['status' => false, 'code' => 400, 'message' => 'No template found','message2' => 'Failed' ], 200);
- }
-
+
+ $notification = $this->notificationModel->where('client_id', $client_id)->where('template_name', 'member_ecard_mail')->first();
+ // print_r(($notification)); die;
+ if ($notification && $notification['enabled'] == 0 && $notification['mail_content'] == '') {
+ return $this->respond(['status' => false, 'code' => 400, 'message' => 'No template found', 'message2' => 'Failed'], 200);
+ }
+
$emp_data = $this->employeePolicyModel->getEmployeePolicyForEcard($policy_id);
- if(count($emp_data) == 0)
- {
- return $this->respond(['status' => false, 'code' => 400, 'message' => 'No employees found','message2' => 'Failed' ], 200);
+ if (count($emp_data) == 0) {
+ return $this->respond(['status' => false, 'code' => 400, 'message' => 'No employees found', 'message2' => 'Failed'], 200);
}
$ids = array_column($emp_data, 'id');
// print_r(($ids)); die;
@@ -599,9 +711,8 @@ class DashboardController extends AdminController
// $empEmpDataServiceController = new EmpDataServiceController();
// $empEmpDataServiceController->sendMailForDownloadingECard($ids);
-
+
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Mail Queued'], 200);
-
}
public function data_construct_for_bds($data)
@@ -616,9 +727,8 @@ class DashboardController extends AdminController
'validated' => [],
'cancelled' => [],
'instalment_pending' => [],
- 'completed' => [],
];
-
+
// Loop through results and group them by their status
foreach ($data as $row) {
switch ($row['status']) {
@@ -646,13 +756,32 @@ class DashboardController extends AdminController
case 'instalment_pending':
$groupedData['instalment_pending'][] = $row;
break;
- default:
+ case 'under_process':
$groupedData['under_process'][] = $row;
break;
+ default:
+ break;
}
}
-
return $groupedData;
}
+ public function prepareClaimSearchData()
+ {
+
+ $received_data = $this->request->getPost();
+ $ticketTypeId = $received_data['ticketTypeId'];
+ $status = $received_data['status'];
+
+ $status = strtoupper($status);
+ $status = str_replace('_', ' ', $status);
+
+ $data = $this->ticketModel
+ ->select("tcs.id as claim_status_id")
+ ->join("ticket_claim_status tcs", "tcs.ticket_type = " . (int)$ticketTypeId)
+ ->where("tcs.claim_status", $status)
+ ->first();
+ $data['ticket_type_id'] = $ticketTypeId;
+ return $this->respond(['status' => "success", "data" => $data], 200);
+ }
}
diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php
index 76d44b73..3dbf91d5 100755
--- a/app/Controllers/EmpDataServiceController.php
+++ b/app/Controllers/EmpDataServiceController.php
@@ -28,6 +28,11 @@ use App\Models\CDMasterModel;
use App\Models\InsurerExcelExportTemplateModel;
use App\Models\ClientBranchModel;
use App\Models\EndorsementModel;
+use App\Models\BdsPlacementModel;
+use App\Models\LeadsModel;
+use App\Models\LeadInstallmentPaymentDetails;
+use App\Models\PolicyTransactionModel;
+use App\Models\PTCOShareDetailsModel;
use App\Controllers\Jobs;
use App\Controllers\JobWorker;
@@ -60,6 +65,11 @@ class EmpDataServiceController extends BaseController
protected $excelExportTemplateModel;
protected $clientBranchModel;
protected $endorsementModel;
+ protected $BdsPlacementModel;
+ protected $leadsModel;
+ protected $leadInstallmentPaymentDetailesModel;
+ protected $policyTransactionModel;
+ protected $PTCOShareDetailsModel;
public function __construct()
@@ -83,6 +93,11 @@ class EmpDataServiceController extends BaseController
$this->excelExportTemplateModel = new InsurerExcelExportTemplateModel();
$this->clientBranchModel = new ClientBranchModel();
$this->endorsementModel = new EndorsementModel();
+ $this->BdsPlacementModel = new BdsPlacementModel();
+ $this->leadsModel = new LeadsModel();
+ $this->leadInstallmentPaymentDetailesModel = new LeadInstallmentPaymentDetails();
+ $this->policyTransactionModel = new PolicyTransactionModel();
+ $this->PTCOShareDetailsModel = new PTCOShareDetailsModel();
}
@@ -170,7 +185,7 @@ class EmpDataServiceController extends BaseController
$balance = $this->CDMasterModel
->where('client_id', $export_data['client_id'])
->where('insurer_id', $policy_details['insurer_id'])
- ->where('cd_ac_no', $policy_details['cd_ac_no'])
+ ->where('id', $policy_details['cd_ac_pk'])
->first();
$cash_balance['balance'] = $balance['opening_bal'];
@@ -432,7 +447,7 @@ class EmpDataServiceController extends BaseController
];
//for addition and dependent addition adding a ENDORSEMENT NO column
- if(in_array($export_data['event_type'], ['addition', 'dependent_addition'])){
+ if(in_array($export_data['event_type'], ['addition', 'dependent_addition', 'missed_inception'])){
$excel_header_columns[] = [
'column_index' => 18,
'column_name' => 'ENDORSEMENT NO',
@@ -529,6 +544,7 @@ class EmpDataServiceController extends BaseController
// Close and remove temporary file
fclose($tempFile);
+ exit();
return true; // Excel file successfully generated and exported
@@ -633,6 +649,7 @@ class EmpDataServiceController extends BaseController
// Close and remove the temporary file
fclose($tempFile);
+ exit();
return true;
} else {
@@ -666,7 +683,7 @@ class EmpDataServiceController extends BaseController
$balance = $this->CDMasterModel
->where('client_id', $export_data['client_id'])
->where('insurer_id', $policy_details['insurer_id'])
- ->where('cd_ac_no', $policy_details['cd_ac_no'])
+ ->where('id', $policy_details['cd_ac_pk'])
->first();
$cash_balance['balance'] = $balance['opening_bal'];
@@ -784,6 +801,7 @@ class EmpDataServiceController extends BaseController
// Close and remove the temporary file
fclose($tempFile);
+ exit();
return true;
} else {
@@ -897,6 +915,7 @@ class EmpDataServiceController extends BaseController
// Close and remove the temporary file
fclose($tempFile);
+ exit();
return true;
} else {
@@ -945,6 +964,9 @@ class EmpDataServiceController extends BaseController
$export_data['event_type'] = 'correction';
$correctionData = $this->employeePolicyModel->getCorrectionEmployeesDataForExportExcel($export_data);
+ }else if($value == "missed_inception"){
+ $export_data['event_type'] = 'missed_inception';
+ $additionData = $this->employeePolicyModel->getInceptionEmployeeDataForExportExcel($export_data);
}
}
@@ -1196,6 +1218,7 @@ class EmpDataServiceController extends BaseController
// Close and remove temporary file
fclose($tempFile);
+ exit();
return true; // Excel file successfully generated and exported
@@ -1381,14 +1404,15 @@ class EmpDataServiceController extends BaseController
'TOTAL AMOUNT',
];
- if(in_array($file['event_type'], ['addition', 'dependent_addition'])){
+ if(in_array($file['event_type'], ['addition', 'dependent_addition', 'missed_inception'])){
$inceptionHeader[] = 'ENDORSEMENT NO';
}
// dd($inceptionHeader);
foreach ($inceptionHeader as $key => $value) {
- if($excel_header[$key] != $value){
+ if (!isset($excel_header[$key]) || $excel_header[$key] != $value) {
+
$data = [
'status' => 'failed-5',
];
@@ -1543,6 +1567,17 @@ class EmpDataServiceController extends BaseController
}
}
+ if (in_array($file['event_type'], ['addition', 'dependent_addition', 'missed_inception'])) {
+ if ($excel_data[$key][18] === null) {
+ $missing_id[$key][] = [
+ 'row' => $key,
+ 'column' => 18,
+ 'db_data' => "Endorsement ID is Must",
+ 'excel_data' => $excel_data[$key][18]
+ ];
+ }
+ }
+
if ($emp_value['emp_name'] != $excel_data[$key][1]) {
$errors[$key][] = [
@@ -1877,6 +1912,27 @@ class EmpDataServiceController extends BaseController
$emp_details[] = array('id' => $result['id'], 'tpa_id' => $value[13], 'uhid' => $value[14]);
}
+ if(in_array($file['event_type'], ['missed_inception']) && isset($value[18])){
+ $endorsement_id = $value[18];
+
+ $result_for_employees_policy = $this->employeePolicyModel
+ ->select('employee_polices.*')
+ ->join('employees', 'employees.id = employee_polices.employee_id')
+ ->join('emp_endorsement', 'emp_endorsement.employee_id = employees.id') // assuming this is the correct join
+ ->where('employees.emp_code', $emp_code)
+ ->where('employees.name', $name)
+ ->where('employees.client_id', $client_id)
+ ->where('employees.client_branch_id', $client_branch_id)
+ ->where('employee_polices.client_policy_id', $client_policy_id)
+ ->where('employee_polices.is_active', 1)
+ ->where('employee_polices.status', 'active')
+ ->where('employees.is_active', 1)
+ ->where('employees.emp_status', 'active')
+ ->first();
+
+ $enrollment_file_id = $result_for_employees_policy['file_id'] ?? null;
+ }
+
//for addition and dependent_addition endorsement , endorsement_id update functionality
if(in_array($file['event_type'], ['addition', 'dependent_addition']) && isset($value[18])){
@@ -1906,7 +1962,9 @@ class EmpDataServiceController extends BaseController
->first();
if (!empty($result_for_endorsement) && count($result_for_endorsement)) {
- $enrollment_file_id = $result_for_endorsement['file_id']; //files table primary key
+ if(empty($enrollment_file_id)){
+ $enrollment_file_id = $result_for_endorsement['file_id']; //files table primary key
+ }
$emp_endorsement_table_data[] = array('id' => $result_for_endorsement['id'], 'group_key' => $result_for_endorsement['group_key'], 'endorsement_id' => $value[18], 'status' => 'complete');
}
}
@@ -1922,7 +1980,6 @@ class EmpDataServiceController extends BaseController
if(in_array($file['event_type'], ['addition', 'dependent_addition']) && !empty($emp_endorsement_table_data)){
$this->employeePolicyModel->updateEmpEndorsementAddition($emp_endorsement_table_data);
- $this->storeEndorsementNumber($file_id, $endorsement_id, $enrollment_file_id);
}
// Update batch file status and amount
@@ -1939,6 +1996,11 @@ class EmpDataServiceController extends BaseController
//update CD transaction entry if only insurer
if ($file['insurer_or_tpa'] == 'insurer') {
+ if(in_array($file['event_type'], ['addition', 'dependent_addition', 'missed_inception'])){
+ $this->storeEndorsementNumber($file_id, $endorsement_id, $enrollment_file_id);
+ }
+
+
$this->myLogger->logme('error', 'Inception Update TPA and UHID -- set cashDepositCalculationForInception and sendMailForDownloadingECard in JOB QUEUE');
$policy_name = $this->getPolicyNameUsingClientPolicyId($client_policy_id);
@@ -1968,6 +2030,13 @@ class EmpDataServiceController extends BaseController
'user_id' => $user_id,
]]);
+ $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [
+ 'client_policy_id' => $client_policy_id ?? null,
+ 'endorsement_no' => $endorsement_id ?? null,
+ 'emp_count' => $emp_count ?? null,
+ 'action_type' => $file['event_type'] ?? null,
+ ]]);
+
// $this->cashDepositCalculationForInception($depositeData);
// $this->sendMailForDownloadingECard($emp_policy_ids);
@@ -2358,7 +2427,9 @@ class EmpDataServiceController extends BaseController
if (isset($result['id']) && $result['id'] !== null) {
// return $result;
- $enrollment_file_id = $result['file_id'];
+ if(empty($enrollment_file_id)){
+ $enrollment_file_id = $result['file_id'];
+ }
if($result['field_name'] == 'dob'){
$value[8] = change_date_format($value[8]);
@@ -2392,6 +2463,13 @@ class EmpDataServiceController extends BaseController
$file_data = $this->getDataByFileId($file_id, 'success');
$this->setPullNotification($file_data);
+ $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [
+ 'client_policy_id' => $client_policy_id ?? null,
+ 'endorsement_no' => $endorsement_id[0] ?? null,
+ 'emp_count' => $emp_count ?? null,
+ 'action_type' => $file['event_type'] ?? null,
+ ]]);
+
//import file to upload Google Drive
// if(excelFileGDriveUpload($file_id, 'batch_file')){
@@ -2415,8 +2493,17 @@ class EmpDataServiceController extends BaseController
$client_policy_id = $file['client_policy_id'];
$client_branch_id = $file['client_branch_id'];
$batch_code = $file['batch_code'];
+ $insurer_or_tpa = $file['insurer_or_tpa'];
$user_id = $file['created_by'];
+ $ref_data = [
+ 'client_id' => $client_id,
+ 'client_policy_id' => $client_policy_id,
+ 'client_branch_id' => $client_branch_id,
+ 'insurer_or_tpa' => $insurer_or_tpa,
+ 'event_type' => $file['event_type'],
+ ];
+
$file_name_with_path = WRITEPATH . "/uploads/import_excel/" . $file['file_name'];
@@ -2448,92 +2535,92 @@ class EmpDataServiceController extends BaseController
}
}
+ $endorsement_data = $this->employeePolicyModel->getSIEnhancementEmployeesDataForExportExcel($ref_data, 1);
+ // $db = \Config\Database::connect();
- $db = \Config\Database::connect();
+ // // Raw SQL query
+ // $sql = "
+ // SELECT
+ // a.id as endorsement_primarykey,
+ // a.group_key,
+ // employee_polices.id AS primaryKey,
+ // employees.id AS emp_primary,
+ // employees.name AS emp_name,
+ // employees.emp_code AS emp_code,
+ // employees.dob AS emp_dob,
+ // employees.gender AS emp_gender,
+ // employees.relationship_code AS emp_relationship_code,
+ // 'Has Define' AS emp_type,
+ // employee_polices.uhid AS risk_id,
+ // employee_polices.pre_existing_alignments,
+ // employee_polices.policy_end_date,
+ // employee_polices.basic_cover_si as old_basic_cover_si,
+ // employee_polices.rata_premimum as old_si_premium,
+ // sidata.new_basic_cover_si,
+ // sidata.new_si_premium,
+ // sidata.date_of_coverage,
+ // DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1 AS no_of_days,
+ // sidata.new_si_premium - employee_polices.rata_premimum AS difference_premium,
+ // ROUND((sidata.new_si_premium - employee_polices.rata_premimum) * (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365, 2) AS pro_rata_premimum,
+ // ROUND(((sidata.new_si_premium - employee_polices.rata_premimum) * (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365) * 0.18, 2) AS gst,
+ // ((sidata.new_si_premium - employee_polices.rata_premimum) * (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365) + ROUND(((sidata.new_si_premium - employee_polices.rata_premimum) * (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365) * 0.18, 2) AS total
+ // FROM
+ // emp_endorsement a
+ // LEFT JOIN
+ // employees ON employees.emp_code = a.emp_code
+ // LEFT JOIN
+ // employee_polices ON employees.id = employee_polices.employee_id
+ // LEFT JOIN (
+ // SELECT
+ // aa.emp_code,
+ // aa.new_value as new_basic_cover_si,
+ // bb.new_value as new_si_premium,
+ // cc.new_value as date_of_coverage
+ // FROM (
+ // SELECT
+ // a1.emp_code,
+ // a1.field_name,
+ // a1.new_value
+ // FROM
+ // emp_endorsement as a1
+ // WHERE
+ // a1.field_name = 'basic_cover_si'
+ // ) aa
+ // LEFT JOIN (
+ // SELECT
+ // b1.emp_code,
+ // b1.field_name,
+ // b1.new_value
+ // FROM
+ // emp_endorsement as b1
+ // WHERE
+ // b1.field_name = 'premium'
+ // ) bb ON aa.emp_code = bb.emp_code
+ // LEFT JOIN (
+ // SELECT
+ // c1.emp_code,
+ // c1.field_name,
+ // c1.new_value
+ // FROM
+ // emp_endorsement as c1
+ // WHERE
+ // c1.field_name = 'si_enhancement_date'
+ // ) cc ON aa.emp_code = cc.emp_code
+ // ) as sidata ON a.emp_code = sidata.emp_code
+ // WHERE
+ // employee_polices.client_policy_id = '$client_policy_id'
+ // AND employees.client_branch_id = '$client_branch_id'
+ // AND employee_polices.is_active = '1'
+ // AND (a.endorsement_id IS NULL OR a.endorsement_id = '')
+ // AND a.actions = 'si'
+ // GROUP BY group_key
+ // ";
- // Raw SQL query
- $sql = "
- SELECT
- a.id as endorsement_primarykey,
- a.group_key,
- employee_polices.id AS primaryKey,
- employees.id AS emp_primary,
- employees.name AS emp_name,
- employees.emp_code AS emp_code,
- employees.dob AS emp_dob,
- employees.gender AS emp_gender,
- employees.relationship_code AS emp_relationship_code,
- 'Has Define' AS emp_type,
- employee_polices.uhid AS risk_id,
- employee_polices.pre_existing_alignments,
- employee_polices.policy_end_date,
- employee_polices.basic_cover_si as old_basic_cover_si,
- employee_polices.rata_premimum as old_si_premium,
- sidata.new_basic_cover_si,
- sidata.new_si_premium,
- sidata.date_of_coverage,
- DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1 AS no_of_days,
- sidata.new_si_premium - employee_polices.rata_premimum AS difference_premium,
- ROUND((sidata.new_si_premium - employee_polices.rata_premimum) * (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365, 2) AS pro_rata_premimum,
- ROUND(((sidata.new_si_premium - employee_polices.rata_premimum) * (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365) * 0.18, 2) AS gst,
- ((sidata.new_si_premium - employee_polices.rata_premimum) * (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365) + ROUND(((sidata.new_si_premium - employee_polices.rata_premimum) * (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365) * 0.18, 2) AS total
- FROM
- emp_endorsement a
- LEFT JOIN
- employees ON employees.emp_code = a.emp_code
- LEFT JOIN
- employee_polices ON employees.id = employee_polices.employee_id
- LEFT JOIN (
- SELECT
- aa.emp_code,
- aa.new_value as new_basic_cover_si,
- bb.new_value as new_si_premium,
- cc.new_value as date_of_coverage
- FROM (
- SELECT
- a1.emp_code,
- a1.field_name,
- a1.new_value
- FROM
- emp_endorsement as a1
- WHERE
- a1.field_name = 'basic_cover_si'
- ) aa
- LEFT JOIN (
- SELECT
- b1.emp_code,
- b1.field_name,
- b1.new_value
- FROM
- emp_endorsement as b1
- WHERE
- b1.field_name = 'premium'
- ) bb ON aa.emp_code = bb.emp_code
- LEFT JOIN (
- SELECT
- c1.emp_code,
- c1.field_name,
- c1.new_value
- FROM
- emp_endorsement as c1
- WHERE
- c1.field_name = 'si_enhancement_date'
- ) cc ON aa.emp_code = cc.emp_code
- ) as sidata ON a.emp_code = sidata.emp_code
- WHERE
- employee_polices.client_policy_id = '$client_policy_id'
- AND employees.client_branch_id = '$client_branch_id'
- AND employee_polices.is_active = '1'
- AND (a.endorsement_id IS NULL OR a.endorsement_id = '')
- AND a.actions = 'si'
- GROUP BY group_key
- ";
+ // // Execute the query
+ // $query = $db->query($sql);
- // Execute the query
- $query = $db->query($sql);
-
- // Fetch the results
- $endorsement_data = $query->getResultArray();
+ // // Fetch the results
+ // $endorsement_data = $query->getResultArray();
@@ -2740,11 +2827,11 @@ class EmpDataServiceController extends BaseController
];
}
- if ($endorsement_value['pro_rata_premimum'] != $excel_data[$key][16]) {
+ if ($endorsement_value['pro_rata_premium'] != $excel_data[$key][16]) {
$errors[$key][] = [
'row' => $key,
'column' => 16,
- 'db_data' => $endorsement_value['pro_rata_premimum'],
+ 'db_data' => $endorsement_value['pro_rata_premium'],
'excel_data' => $excel_data[$key][16]
];
}
@@ -2921,7 +3008,10 @@ class EmpDataServiceController extends BaseController
if (isset($result['id']) && $result['id'] !== null) {
- $enrollment_file_id = $result['file_id'];
+ if(empty($enrollment_file_id)){
+ $enrollment_file_id = $result['file_id'];
+ }
+
$emp_policy_ids[] = array('id' => $result['emp_policy_id'], 'is_active' => 0);
$employeeIds[] = $result['emp_policy_id'];
$endorsement_details[] = array('id' => $result['id'], 'group_key' => $result['group_key'], 'endorsement_id' => $value[19], 'status' => 'complete');
@@ -2945,7 +3035,7 @@ class EmpDataServiceController extends BaseController
$empData['basic_cover_si'] = $value[8];
$empData['premium'] = $value[14];
- $empData['si_enhancement_date'] = $value[10];
+ $empData['si_enhancement_date'] = date('Y-m-d', strtotime($value[10])) ?? null;
$empData['rata_premimum'] = $value[16];
$empData['gst'] = $value[17];
$empData['created_by'] = $user_id;
@@ -2957,31 +3047,28 @@ class EmpDataServiceController extends BaseController
// dd($emp_policy_ids, $emp_details, $endorsement_details);
- $this->employeePolicyModel->updateBatch($emp_policy_ids, 'id');
+ if ($file['insurer_or_tpa'] == 'insurer') {
- $db = \Config\Database::connect();
- $db->transStart();
-
- $this->employeePolicyModel->insertBatch($emp_details);
-
- $insertedIds = [];
- $startId = $db->insertID(); // Get the first inserted ID
-
- for ($i = 0; $i < count($emp_details); $i++) {
- $insertedIds[] = $startId + $i;
+ $this->employeePolicyModel->updateBatch($emp_policy_ids, 'id');
+
+ // $this->employeePolicyModel->insertBatch($emp_details);
+ // $insertedIds = [];
+ // $startId = $db->insertID(); // Get the first inserted ID
+
+ // for ($i = 0; $i < count($emp_details); $i++) {
+ // $insertedIds[] = $startId + $i;
+ // }
+
+ $insertedIds = [];
+ foreach ($emp_details as $emp) {
+ $insertedIds[] = $this->employeePolicyModel->insert($emp);
+ }
+
+ // dd($insertedIds);
+
+ $this->employeePolicyModel->bulkUpdateForEndorsement($endorsement_details);
+ $this->storeEndorsementNumber($file_id, $endorsement_id, $enrollment_file_id);
}
-
- $db->transComplete();
-
- // if ($db->transStatus() === FALSE) {
- // // Handle the error, rollback, etc.
- // } else {
- // // Transaction successful
- // print_r($insertedIds); // This will print the array of inserted IDs
- // }
-
- $this->employeePolicyModel->bulkUpdateForEndorsement($endorsement_details);
- $this->storeEndorsementNumber($file_id, $endorsement_id, $enrollment_file_id);
// Update batch file status and amount
@@ -3013,6 +3100,13 @@ class EmpDataServiceController extends BaseController
'user_id' => $user_id,
]]);
+ $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [
+ 'client_policy_id' => $client_policy_id ?? null,
+ 'endorsement_no' => $endorsement_id ?? null,
+ 'emp_count' => $emp_count ?? null,
+ 'action_type' => $file['event_type'] ?? null,
+ ]]);
+
}
$file_data = $this->getDataByFileId($file_id, 'success');
@@ -3425,7 +3519,9 @@ class EmpDataServiceController extends BaseController
if (isset($result['emp_endorsement_primarykey']) && $result['emp_endorsement_primarykey'] !== null) {
- $enrollment_file_id = $result['file_id']; //files table primary key
+ if(empty($enrollment_file_id)){
+ $enrollment_file_id = $result['file_id']; //files table primary key
+ }
$employee_policy_table_primaryKey[] = $result['emp_policy_primarykey']; //for cash deposite
$employee_policy_table_data[] = array('id' => $result['emp_policy_primarykey'], 'date_of_exit' => change_date_format($result['date_of_exit']), 'reason_for_exit' => $result['reason_for_exit'], 'claim_status' => $result['claim_status'], 'status' => $result['status']);
// $employees_table_data[] = array('id' => $result['employees_id'], 'emp_status' => $result['status']);
@@ -3445,20 +3541,29 @@ class EmpDataServiceController extends BaseController
// return ['status' => 'error', 'message' => 'Employees table data is empty or null.'];
// }
- // Check if $employee_policy_table_data is null or empty
- if (empty($employee_policy_table_data)) {
- return ['status' => 'error', 'message' => 'Employee policy table data is empty or null.'];
- }
+ if ($file['insurer_or_tpa'] == 'insurer') {
- // Check if $emp_endorsement_table_data is null or empty
- if (empty($emp_endorsement_table_data)) {
- return ['status' => 'error', 'message' => 'Employee endorsement table data is empty or null.'];
- }
+ // Check if $employee_policy_table_data is null or empty
+ if (empty($employee_policy_table_data)) {
+ $this->batchFileModel->update($file_id, [
+ 'status' => "failed",
+ ]);
+ return ['status' => 'error', 'message' => 'Employee policy table data is empty or null.'];
+ }
- // $this->employeeModel->updateBatch($employees_table_data, 'id');
- $this->employeePolicyModel->updateBatch($employee_policy_table_data, 'id');
- $this->employeePolicyModel->bulkUpdateForEndorsement($emp_endorsement_table_data);
- $this->storeEndorsementNumber($file_id, $endorsement_id, $enrollment_file_id);
+ // Check if $emp_endorsement_table_data is null or empty
+ if (empty($emp_endorsement_table_data)) {
+ $this->batchFileModel->update($file_id, [
+ 'status' => "failed",
+ ]);
+ return ['status' => 'error', 'message' => 'Employee endorsement table data is empty or null.'];
+ }
+
+ // $this->employeeModel->updateBatch($employees_table_data, 'id');
+ $this->employeePolicyModel->updateBatch($employee_policy_table_data, 'id');
+ $this->employeePolicyModel->bulkUpdateForEndorsement($emp_endorsement_table_data);
+ $this->storeEndorsementNumber($file_id, $endorsement_id, $enrollment_file_id);
+ }
// Update batch file status and amount
$this->batchFileModel->update($file_id, [
@@ -3487,6 +3592,13 @@ class EmpDataServiceController extends BaseController
'policy_name' => $policy_name['policy_name'],
'user_id' => $user_id,
]]);
+
+ $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [
+ 'client_policy_id' => $client_policy_id ?? null,
+ 'endorsement_no' => $endorsement_id ?? null,
+ 'emp_count' => $emp_count ?? null,
+ 'action_type' => $file['event_type'] ?? null,
+ ]]);
}
$file_data = $this->getDataByFileId($file_id, 'success');
@@ -4105,6 +4217,9 @@ class EmpDataServiceController extends BaseController
AND emp_endorsement.pk IN (" . implode(',', $arrayData['employeeIds']) . ")
AND employee_polices.claim_status = 0
AND emp_endorsement.field_name = 'date_of_exit'
+ AND emp_endorsement.is_active = 1
+ AND emp_endorsement.actions = 'd'
+ AND emp_endorsement.status != 'truncated';
")->getRow();
// dd(db_connect()->getLastQuery(), $amount);
@@ -4661,6 +4776,316 @@ class EmpDataServiceController extends BaseController
$this->myLogger->logme('error',"storeEndorsementNumber --- Function execution completed for file_id: $file_id");
}
+ // --------------------------------------------------------------------------------------------------------------------------------
+
+ public function makeEntryForBDSPolicyTransaction($params)
+ {
+ try {
+ $this->myLogger->logme("error", "makeEntryForBDSPolicyTransaction() started: " . json_encode(['params' => $params]));
+
+ if (empty($params) || !isset($params['client_policy_id']) || empty($params['client_policy_id'])) {
+ $this->myLogger->logme("error", "Invalid parameters provided: " . json_encode(['params' => $params]));
+ return ['status' => "Failed", 'message' => "Client Policy ID is missing or empty", 'data' => ['params' => $params]];
+ }
+
+ if (!isset($params['action_type']) || empty($params['action_type'])) {
+ $this->myLogger->logme("error", "Invalid action type: " . json_encode(['params' => $params]));
+ return ['status' => "Failed", 'message' => "Action type is missing or empty", 'data' => ['params' => $params]];
+ }
+
+ //Function call for if the old policy transaction entries exisit than active the Policy transaction entries
+ $existing_policy_transaction_entry = $this->retrivePolicyTransactionEntries($params);
+
+ if($existing_policy_transaction_entry != false){
+ return $existing_policy_transaction_entry;
+ }
+
+ //get the policy data
+ $policy_data = $this->clientPolicyModel
+ ->where('id', $params['client_policy_id'])
+ ->where('is_active', 1)
+ ->first();
+
+ if (empty($policy_data)) {
+ $this->myLogger->logme("error", "No policy data found: " . json_encode(['client_policy_id' => $params['client_policy_id']]));
+ return ['status' => "Failed", 'message' => "No policy data found for the given client policy ID", 'data' => ['params' => $params]];
+ }
+
+ //get the leads data
+ $lead_data = $this->leadsModel
+ ->where('is_policy_created', $params['client_policy_id'])
+ ->where('is_active', 1)
+ ->first();
+
+ if (empty($lead_data)) {
+ $this->myLogger->logme("error", "No lead data found: " . json_encode(['client_policy_id' => $params['client_policy_id']]));
+ // return ['status' => "Failed", 'message' => "No lead data found for the given client policy ID", 'data' => ['params' => $params]];
+ }
+
+ $this->myLogger->logme("error", "Constructing policy transaction data: " . json_encode(['policy_data' => $policy_data, 'lead_data' => $lead_data]));
+
+ //Function to construct the policy transaction data to insert
+ $policyTransactionData = $this->constructBDSData($policy_data, $lead_data, $params);
+
+ //insert the policy transaction data to othe table
+ $insert_id = $this->policyTransactionModel->insert($policyTransactionData);
+
+ if (!$insert_id) {
+ $this->myLogger->logme("error", "Failed to insert into policy_transaction: " . json_encode($policyTransactionData));
+ return ['status' => "Failed", 'message' => "Failed to insert policy transaction record", 'data' => ['params' => $params]];
+ }
+
+ $this->myLogger->logme("error", "Policy transaction inserted successfully: " . json_encode(['insert_id' => $insert_id]));
+
+ //do not remove this commented item
+ // $coShareDetails = $this->ConstructPTShareData($policy_data, $insert_id);
+ // $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]));
+
+ // get the lead installment data
+
+ if(!empty($lead_data)){
+ $lead_installment_data = $this->leadInstallmentPaymentDetailesModel
+ ->select('lead_id, installment_amount, payment_date, utr_no')
+ ->where('lead_id', $lead_data['id'])
+ ->where('is_active', 1)
+ ->findAll();
+
+ if (!empty($lead_installment_data) && (isset($params['action_type']) && $params['action_type'] == "inception")) {
+
+ $this->myLogger->logme("error", "Found lead installment data: " . json_encode($lead_installment_data));
+ $installment_ids = $this->constructInstallmentData($lead_installment_data, $insert_id);
+ $this->myLogger->logme("error", "BDS Installment data inserted ids: " . json_encode(['installment_ids' => $installment_ids]));
+ }else{
+ $this->myLogger->logme("error", "Failed to insert Installment data : " . json_encode($params));
+ }
+ }
+
+ return ['status' => "Success", 'message' => "Policy transaction entry created successfully", 'data' => ['params' => $params, 'insert_id' => $insert_id]];
+ } catch (\Throwable $e) {
+ $this->myLogger->logme("error", "Exception occurred in makeEntryForBDSPolicyTransaction(): " . json_encode([
+ 'error' => $e->getMessage(),
+ 'trace' => $e->getTraceAsString()
+ ]));
+
+ return ['status' => "Error", 'message' => "An unexpected error occurred", 'data' => ['error' => $e]];
+ }
+ }
+
+ private function constructBDSData($policy_data, $lead_data, $params)
+ {
+
+ $action_type_string = $params['action_type'];
+ if(in_array($params['action_type'], ['dependent_addition', 'missed_inception'])){
+ $action_type_string = "addition";
+ }
+
+ $policyTransactionData = [
+
+ 'issuer' => 2,
+ 'client_id' => $policy_data['client_id'] ?? null,
+ 'client_branch_id' => $policy_data['client_branch_id'] ?? null,
+ 'insurer_id' => $policy_data['insurer_id'] ?? null,
+ 'insurer_branch_id' => $policy_data['insurer_branch_id'] ?? null,
+ 'tpa_id' => $policy_data['tpa_id'] ?? null,
+ 'tpa_branch_id' => $policy_data['tpa_branch_id'] ?? null,
+ 'policy_type_id' => $policy_data['policy_type_id'] ?? null,
+ 'client_policy_id' => $policy_data['id'] ?? null,
+ 'policy_no' => $policy_data['policy_no'] ?? null,
+ 'cd_ac_no' => $policy_data['cd_ac_no'] ?? null,
+ 'cd_ac_pk' => $policy_data['cd_ac_pk'] ?? null,
+ 'policy_issue_date' => $policy_data['policy_start_date'] ?? null,
+ 'policy_start_date' => $policy_data['policy_start_date'] ?? null,
+ 'policy_end_date' => $policy_data['policy_end_date'] ?? null,
+ 'data_received_date' => $policy_data['data_received_date'] ?? null,
+ 'closure_date' => $policy_data['closure_date'] ?? null,
+ 'emp_count' => $policy_data['emp_count'] ?? null,
+ 'dependent_count' => $policy_data['dependent_count'] ?? null,
+ 'revenue_type' => ($lead_data['lead_type'] == 1 ? "NA" : ($lead_data['lead_type'] == 2 ? "EA" : "EANR") ) ?? null,
+ 'co_share' => $policy_data['co_share'] ?? 0,
+ 'pre_payable_by' => $policy_data['pre_payable_by'] ?? 1,
+ 'renewal_date' => $policy_data['policy_end_date'] ?? null,
+ 'month' => date('Y-m-01', strtotime($policy_data['policy_start_date'])) ?? null,
+ 'ct_type' => 1,
+ 'is_cd_reduce_from_bds' => 0,
+ 'client_type_id' => 0,
+
+ 'status' => "co_insurer_pending",
+ 'action_type' => $action_type_string ?? null,
+ 'endorsement_no' => $params['endorsement_no'] ?? null,
+
+ 'issue_type' => $lead_data['lead_type'] ?? 1,
+ 'source_client_policy_id' => $lead_data['source_policy_id'] ?? null,
+ 'tsi' => generate_tsi_code($lead_data['lead_type'] ?? 1) ?? null,
+ 'installment' => $lead_data['no_of_installment'] ?? null,
+ ];
+
+ $this->myLogger->logme("error", "Constructed policy transaction data: " . json_encode($policyTransactionData));
+
+ return $policyTransactionData;
+ }
+
+ private function ConstructPTShareData($policy_data, $pt_id)
+ {
+ $coShareData = [
+ 'pt_id' => $pt_id,
+ 'insurer_id' => $policy_data['insurer_id'],
+ 'insurer_branch_id' => $policy_data['insurer_branch_id'],
+ 'co_share_type' => 1,
+ ];
+
+ $this->myLogger->logme("error", "Constructed PT co-share data: " . json_encode($coShareData));
+
+
+ return $coShareData;
+ }
+
+ private function constructInstallmentData($data, $pt_id)
+ {
+ if (!empty($data)) {
+ $installment_ids = [];
+ foreach ($data as $key => &$value) {
+ $value['pt_id'] = $pt_id;
+ $installment_ids[] = $this->BdsPlacementModel->insert($value);
+ }
+ unset($value);
+
+ return $installment_ids;
+ }
+ }
+
+ private function retrivePolicyTransactionEntries($params)
+ {
+ $policy_transaction_data = $this->policyTransactionModel
+ ->where('is_active', 0)
+ ->where('client_policy_id', $params['client_policy_id']);
+
+ if ($params['action_type'] != "inception") {
+ $policy_transaction_data = $policy_transaction_data->where('endorsement_no', $params['endorsement_no']);
+ }
+
+ $policy_transaction_data = $policy_transaction_data
+ ->where('action_type', $params['action_type'])
+ ->first();
+
+ if(empty($policy_transaction_data)){
+ $this->myLogger->logme("error", "retrive Policy Transaction Entries data not found : " . json_encode(['params' => $params]));
+ return false;
+ }
+
+ $pt_co_share_data = $this->PTCOShareDetailsModel->where('is_active', 0)->where('pt_id', $policy_transaction_data['id'])->findAll();
+
+ if(empty($pt_co_share_data)){
+ $this->myLogger->logme("error", "PT Co Share Table data not found");
+ }
+
+ $activated_pt_co_share_ids = [];
+ foreach ($pt_co_share_data as $key => $value) {
+ $this->PTCOShareDetailsModel->where('id', $value['id'])->set(['is_active' => 1])->update();
+ $activated_pt_co_share_ids[] = $value['id'];
+ }
+
+ $this->myLogger->logme("error", "Activated pt_co_share_ids : ". json_encode($activated_pt_co_share_ids));
+
+
+ $update_return = $this->policyTransactionModel->where('id', $policy_transaction_data['id'])->set(['is_active' => 1])->update();
+
+ if($update_return){
+ $this->myLogger->logme("error", "Invalid action type: " . json_encode(['params' => $params]));
+ return ['status' => "Success", 'message' => "Policy transaction entry Retrived successfully", 'data' => ['params' => $params, 'updated_id' => $policy_transaction_data['id']]];
+ }else{
+ $this->myLogger->logme("error", "Invalid action type: " . json_encode(['params' => $params]));
+ return ['status' => "Success", 'message' => "Failed to retrive the policy transaction entry", 'data' => ['params' => $params, 'updated_id' => $policy_transaction_data['id']]];
+ }
+
+ }
+
+ public function removeBDSPolicyTransactionEntryFromTruncate($params)
+ {
+ if (empty($params) || !isset($params['client_policy_id']) || empty($params['client_policy_id'])) {
+ $this->myLogger->logme("error", "Invalid parameters provided: " . json_encode(['params' => $params]));
+ return ['status' => "Failed", 'message' => "Client Policy ID is missing or empty", 'data' => ['params' => $params]];
+ }
+
+ if (!isset($params['file_id']) || empty($params['file_id'])) {
+ $this->myLogger->logme("error", "File ID is missing or empty : " . json_encode(['params' => $params]));
+ return ['status' => "Failed", 'message' => "File ID is missing or empty : ", 'data' => ['params' => $params]];
+ }
+
+ if (!isset($params['action_type']) || empty($params['action_type'])) {
+ $this->myLogger->logme("error", "Invalid action type: " . json_encode(['params' => $params]));
+ return ['status' => "Failed", 'message' => "Action type is missing or empty", 'data' => ['params' => $params]];
+ }
+
+
+ if($params['action_type'] != "inception"){
+
+ $endorsement_data = $this->endorsementModel
+ ->where('is_active', 1)
+ ->where('client_policy_id', $params['client_policy_id'])
+ ->where('endorsement_type', $params['action_type'])
+ ->where('file_id', $params['file_id'])
+ ->first();
+
+ if(empty($endorsement_data)){
+ $this->myLogger->logme("error", "Endorsement data not found");
+ return ['status' => "Failed", 'message' => "Endorsement data not found", 'data' => ['params' => $params]];
+ }
+ }
+
+ $action_type_string = $params['action_type'];
+ if(in_array($params['action_type'], ['dependent_addition', 'missed_inception'])){
+ $action_type_string = "addition";
+ }
+
+
+ $policy_transaction_data = $this->policyTransactionModel
+ ->where('is_active', 1)
+ ->where('client_policy_id', $params['client_policy_id']);
+
+ if ($params['action_type'] != "inception") {
+ $policy_transaction_data = $policy_transaction_data->where('endorsement_no', $endorsement_data['endorsement_no']);
+ }
+
+ $policy_transaction_data = $policy_transaction_data
+ ->where('action_type', $action_type_string)
+ ->first();
+
+
+ if(empty($policy_transaction_data)){
+ $this->myLogger->logme("error", "Policy transaction data not found");
+ return ['status' => "Failed", 'message' => "Policy transaction data not found", 'data' => ['params' => $params]];
+ }
+
+
+ $pt_co_share_data = $this->PTCOShareDetailsModel->where('is_active', 1)->where('pt_id', $policy_transaction_data['id'])->findAll();
+
+ if(empty($pt_co_share_data)){
+ $this->myLogger->logme("error", "PT Co Share Table data not found");
+ }
+
+ $de_activated_pt_co_share_ids = [];
+ foreach ($pt_co_share_data as $key => $value) {
+ $this->PTCOShareDetailsModel->where('id', $value['id'])->set(['is_active' => 0])->update();
+ $de_activated_pt_co_share_ids[] = $value['id'];
+ }
+
+ $this->myLogger->logme("error", "De-activated pt_co_share_ids : ". json_encode($de_activated_pt_co_share_ids));
+
+ $update_return = $this->policyTransactionModel->where('id', $policy_transaction_data['id'])->set(['is_active' => 0])->update();
+
+ if($update_return){
+ $this->myLogger->logme("error", "Policy transaction data de-active successfully");
+ return ['status' => "Success", 'message' => "Policy transaction data Truncated successfully", 'data' => ['params' => $params]];
+ }else{
+ $this->myLogger->logme("error", "Failed to de-active policy transaction data");
+ return ['status' => "Success", 'message' => "Failed to truncated the policy transaction data", 'data' => ['params' => $params]];
+ }
+
+ }
+
+
diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php
index 6857487a..6541e011 100755
--- a/app/Controllers/EmployeeController.php
+++ b/app/Controllers/EmployeeController.php
@@ -190,7 +190,7 @@ class EmployeeController extends AdminController
// print_r($this->request->getPost('upload-action-type'));
// die();
// $empServiceController = new EmployeeServiceController();
- // $res = $empServiceController->excelFileFormatValidation(['file_id' => '42']);
+ // $res = $empServiceController->excelFileDataValidation(['file_id' => '933']);
// dd($res);
// $empServiceController = new EmployeeServiceController();
@@ -315,8 +315,10 @@ class EmployeeController extends AdminController
// ->join('clients c', 'files.client_id = c.id and files.client_id = cp.client_id', 'left')
// ->where('files.created_by', get_session_userid())->orderBy('files.created_at', 'desc')->findAll();
// dd($this->fileModel->getLastQuery());
+ $role_id = get_role_id();
+ $user_id = get_session_userid();
- $data['fileList'] = $this->fileModel
+ $query = $this->fileModel
->select([
'files.id','files.file_name','files.created_by','files.created_at','files.is_active','files.status','files.client_id','files.policy_id','files.client_branch_id','files.action','files.uploaded_by',
'up.emp_code',
@@ -334,13 +336,20 @@ class EmployeeController extends AdminController
->join('client_branch cb', 'files.client_branch_id = cb.id', 'left')
->join('policy_type', 'policy_type.id = cp.policy_type_id')
->join('clients c', 'files.client_id = c.id and files.client_id = cp.client_id', 'left')
+ ->join("client_rm cr","cr.client_id = c.id and cr.is_active = 1",'left')
+ ->where('files.is_active', 1);
+ if (in_array($role_id, [2, 3])) {
+
+ // If the user is a Account Manager or Manager, filter by user_id
+ $query->where('cr.user_id', $user_id);
+ }
// ->where('files.created_by', get_session_userid())
- ->orderBy('files.created_at', 'desc')
- ->limit(100)
+ $data['fileList'] = $query->groupBy("c.id")->orderBy('files.created_at', 'desc')
+ ->limit(1500)
->find();
// dd($data['fileList']);
- $data['batch_list'] = $this->batchFileModel->select("
+ $query2 = $this->batchFileModel->select("
batch_files.id,
batch_files.client_id,
@@ -360,12 +369,13 @@ class EmployeeController extends AdminController
batch_files.status,
batch_files.client_branch_id,
- CASE
- WHEN batch_files.status = 'partially success' THEN
- batch_files.error_data
+ CASE
+ WHEN batch_files.status = 'partially success' OR batch_files.status = 'in-progress-partially' THEN
+ batch_files.error_data
ELSE
- error_data = null
- END AS error_data,
+ NULL
+ END AS error_data,
+
clients.short_name as client_short_name,
client_branch.branch_name,
@@ -377,9 +387,18 @@ class EmployeeController extends AdminController
->join('client_branch', 'client_branch.id = batch_files.client_branch_id')
->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
->join('clients', 'clients.id = client_policy.client_id')
- ->orderBy('batch_files.id', 'desc')
- ->limit(1000)
- ->find();
+ ->join("client_rm cr","cr.client_id = clients.id and cr.is_active = 1",'left')
+ ->where('batch_files.is_active', 1);
+ if (in_array($role_id, [2, 3])) {
+
+ // If the user is a Account Manager or Manager, filter by user_id
+ $query2->where('cr.user_id', $user_id);
+ }
+ // ->where('files.created_by', get_session_userid())
+ $data['batch_list'] = $query2->groupBy("clients.id")->orderBy('batch_files.id', 'desc')
+ ->limit(1500)
+ ->find();
+
// dd($data['fileList']);die();
@@ -433,7 +452,7 @@ class EmployeeController extends AdminController
$filePath = ROOTPATH . 'public/sample_excel/sample_correction .xls';
} else if ($actionType == 'si_enhancement') {
$filePath = ROOTPATH . 'public/sample_excel/sample_si_enhancement.xls';
- } else if ($actionType == 'dependent_addtion') {
+ } else if ($actionType == 'dependent_addition') {
$filePath = ROOTPATH . 'public/sample_excel/sample_dependent_addition.xls';
} else if ($actionType == 'addition') {
$filePath = ROOTPATH . 'public/sample_excel/sample_addition.xls';
@@ -443,6 +462,8 @@ class EmployeeController extends AdminController
$filePath = ROOTPATH . 'public/sample_excel/enrollment.xlsx';
}else if ($actionType == 'missed_inception') {
$filePath = ROOTPATH . 'public/sample_excel/sample_inception.xls';
+ }else if ($actionType == 'member_data') {
+ $filePath = ROOTPATH . 'public/sample_excel/Sample_Member_Data.xlsx';
}
// Check if the file exists
@@ -756,8 +777,18 @@ class EmployeeController extends AdminController
public function enrollmentClientList()
{
+ $role_id = get_role_id();
+ $user_id = get_session_userid();
+
$data = [];
- $client_list = $this->clientModel->where('clients.is_active', 1)->findAll();
+ $client_list = $this->clientModel->join("client_rm","client_rm.client_id = clients.id",'left')->where('clients.is_active', 1);
+ if (in_array($role_id, [2, 3])) {
+
+ // If the user is a Account Manager or Manager, filter by user_id
+ $client_list->where('client_rm.user_id', $user_id);
+ }
+
+ $client_list = $client_list->groupBy("clients.id")->findAll();
$branch_list = $this->clientBranchModel->where('client_branch.is_active', 1)->findAll();
$policy_list = $this->clientPolicyModel
->select('client_policy.*, policy_type.policy_type')
@@ -1011,6 +1042,7 @@ class EmployeeController extends AdminController
$data = $this->employeePolicyModel->select('employee_polices.id')
->where('employee_polices.is_active', 1)
+ ->where('employee_polices.status', 'active')
->where('employee_polices.client_policy_id', $id)
->findAll();
@@ -1381,6 +1413,13 @@ class EmployeeController extends AdminController
$this->myLogger->logme('error', 'cash_deposite table updated -- cd transaction');
}
+ //this job for deactive policy transaction and pt co share table entry for BDS Sync
+ $r = Jobs::addJob(['job_name' => 'removeBDSPolicyTransactionEntryFromTruncate', 'payload' => [
+ 'client_policy_id' => $client_policy_id ?? null,
+ 'file_id' => $file_id ?? null,
+ 'action_type' => $file['action'] ?? null,
+ ]]);
+
}else{
$this->myLogger->logme('error', '---- There is no data to truncate ----');
@@ -1531,6 +1570,13 @@ class EmployeeController extends AdminController
}
+ //this job for deactive policy transaction and pt co share table entry for BDS Sync
+ $r = Jobs::addJob(['job_name' => 'removeBDSPolicyTransactionEntryFromTruncate', 'payload' => [
+ 'client_policy_id' => $client_policy_id ?? null,
+ 'file_id' => $file_id ?? null,
+ 'action_type' => $file['action'] ?? null,
+ ]]);
+
$this->myLogger->logme('error', 'SUCCESSFULLY TRUNCATED');
return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => 'success'], 200);
@@ -2358,7 +2404,7 @@ class EmployeeController extends AdminController
} else if ($actionType == 'deletion') {
$filePath = ROOTPATH . 'public/sample_import_excel/sample_import_Deletion.xlsx';
}else if ($actionType == 'missed_inception') {
- $filePath = ROOTPATH . 'public/sample_import_excel/sample_import_Inception.xlsx';
+ $filePath = ROOTPATH . 'public/sample_import_excel/sample_import_Addition.xlsx';
}
// Check if the file exists
diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php
index f46fc522..050fe5b3 100755
--- a/app/Controllers/EmployeeRestController.php
+++ b/app/Controllers/EmployeeRestController.php
@@ -1100,7 +1100,7 @@ class EmployeeRestController extends AdminController
$keysToRemove = ["removable_keys"];
// Retrieve employee policy data by passing the employee primary key
$empPolicy = $this->employeeModel->getEmployeePolicy($id);
-// dd($empPolicy);
+ // dd($empPolicy);
// Retrieve employee and dependents data by passing the employee code
$employeeData = $this->employeeModel->where('emp_code',$emp_code)
->where('client_id',$client_id)
@@ -2501,8 +2501,9 @@ class EmployeeRestController extends AdminController
function getEmployeeActiveOrInactivePolicy()
{
- if($this->request->getGet('type') == 'Active'){ $policy_status = 1; }else{ $policy_status = 0; }
- $ClientPolicyData = $this->clientPolicyModel->select('client_policy.* , policy_type.policy_type as policy_type,insurers.name as insurer_name,tpa.name as tpa_name,tpa.network_hospitals as network_hospitals_url, policy_type.long_name as policy_long_name')
+ if($this->request->getGet('type') == 'Active'){ $policy_status = 1; $policy_status_key = "Active"; }else{ $policy_status = 0; $policy_status_key = "InActive";}
+ $dayInterval = 10;
+ $ClientPolicyData = $this->clientPolicyModel->select("client_policy.* , policy_type.policy_type as policy_type,insurers.name as insurer_name,tpa.name as tpa_name,tpa.network_hospitals as network_hospitals_url, policy_type.long_name as policy_long_name, DATE_ADD(client_policy.policy_end_date, INTERVAL {$dayInterval} DAY) as claims_grace_date")
->join('insurers', 'client_policy.insurer_id = insurers.id', 'left')
->join('tpa', 'client_policy.tpa_id = tpa.id', 'left')
->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left')
@@ -2526,15 +2527,15 @@ class EmployeeRestController extends AdminController
->get()->getRow()->name;
$whereArrayForId = [];
foreach ( $employeeData as $key => $value) { array_push($whereArrayForId, $value['id']); }
-
+
if(count($ClientPolicyData) > 0 && count($employeeData) > 0)
{
$result = [];
foreach ($ClientPolicyData as $key => $ClientPolicyValue) {
-
-
-
+ if (strtotime(date('Y-m-d') > strtotime($ClientPolicyValue['claims_grace_date']))) {
+ continue;
+ }
if($ClientPolicyValue['policy_type_id'] == 1)
{
@@ -2555,11 +2556,7 @@ class EmployeeRestController extends AdminController
}
$terms = json_decode($ClientPolicyValue['policy_terms'] , true);
- $data['policy_terms'] = isset($terms['enrollment_display_key'])
- && !empty($terms['enrollment_display_key'])
- ? $terms['enrollment_display_key']
- : $this->policyTermsFiter($terms, $policyGroup);
- $terms = json_decode($ClientPolicyValue['policy_terms']);
+ $data['policy_terms'] = isset($terms['enrollment_display_key']) && !empty($terms['enrollment_display_key']) ? $terms['enrollment_display_key'] : $this->policyTermsFiter($terms, $policyGroup);
$data['client_id'] = $ClientPolicyValue['client_id'];
@@ -2573,6 +2570,8 @@ class EmployeeRestController extends AdminController
$data['policy_start_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['policy_start_date']);
$data['policy_end_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['policy_end_date']);
$data['heading'] = $ClientPolicyValue['policy_long_name'];
+ $data['claims_grace_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['claims_grace_date']);
+ $data['policy_status'] = $policy_status_key;
// $data['policy_terms'] = $terms;
// if($ClientPolicyValue['policy_type_id'] == 1){ $data['heading'] = 'Group Personal Accident Coverage'; }else
@@ -3120,6 +3119,8 @@ class EmployeeRestController extends AdminController
}
+ // ---------------- TICKET API's ---------------------------------------------------------------------------------------------------
+
//Get Data from post for inserting ticket and message
public function initiateClaim()
{
@@ -3130,6 +3131,18 @@ class EmployeeRestController extends AdminController
$client_policy_id = $received_data['client_policy_id'];
$insured_emp_id = $received_data['insured_emp_id'];
+ if (empty($received_data['doa'])) {
+ $received_data['doa'] = null;
+ } else{
+ $ticket_data['doa'] = change_date_format($received_data['doa']);
+ }
+
+ if (empty($received_data['dod'])) {
+ $received_data['dod'] = null;
+ } else{
+ $ticket_data['dod'] = change_date_format($received_data['dod']);
+ }
+
$sql = "
select
cp.policy_type_id,
@@ -3172,29 +3185,42 @@ class EmployeeRestController extends AdminController
if(!empty($emp_ticket_data)){
$fetchData = $emp_ticket_data[0];
- $fetchData['claim_status_id'] = $this->claimStatusModel
- ->select('id')
- ->where('ticket_type', $fetchData['ticket_type_id'])
- ->orderBy('id', 'asc')
- ->first()['id'];
+
+ $claimStatusQuery = $this->claimStatusModel
+ ->select('id')
+ ->where('ticket_type', $fetchData['ticket_type_id'])
+ ->orderBy('id', 'asc');
+
+ if ($fetchData['ticket_type_id'] == 1 && !empty($fetchData['tpa_no'])) {
+ $results = $claimStatusQuery->findAll(2);
+ $fetchData['claim_status_id'] = $results[1]['id'] ?? $results[0]['id'];
+ } else {
+ $fetchData['claim_status_id'] = $claimStatusQuery->first()['id'];
+ }
+
$fetchData['priority'] = 1;
- $fetchData['mode_of_intimation'] = 1;
+ $fetchData['mode_of_intimation'] = 3;
+ $fetchData['claim_type'] = 1;
$fetchData = array_merge($fetchData, $received_data);
+ $fetchData['relationship'] = strtolower($fetchData['relationship']) ?? $fetchData['relationship'];
// print_r($fetchData); die;
$insert_status = $this->ticketMaster->insert($fetchData);
$ticket_id = $this->ticketMaster->insertID();
if ($insert_status && !empty($ticket_id)) {
+ //insert first history
+ $this->ticketController->putHistoryAfterInsert($fetchData, $ticket_id);
+
$messagesData = [
'ticket_id' => $ticket_id ?? null,
'sender' => 'user',
'claim_status' => $fetchData['claim_status_id'] ?? null,
'emp_mail' => $fetchData['emp_mail'] ?? null,
- 'mail_subject' => $fetchData['subject'] ?? null,
- 'mail_content' => $fetchData['message'] ?? null,
+ 'mail_subject' => $fetchData['subject'] ?? "New Claim",
+ 'mail_content' => $fetchData['message'] ?? "New Claim",
];
if (!empty($messagesData['ticket_id'])) {
@@ -3207,18 +3233,12 @@ class EmployeeRestController extends AdminController
$message = 'Claim Iniated Successfully';
return $this->respond(['status' => true, 'code' => 200, 'message' => $message], 200);
} else {
- $mail_sent_status = json_decode($mail_sent_status);
+ $mail_sent_status_object = json_decode($mail_sent_status);
}
- // dd(gettype($mail_sent_status));
- if ($mail_sent_status->status == 'success') {
- $sent_message_data['ticket_id'] = $ticket_id;
- $sent_message_data['sender'] = 'staff';
- $sent_message_data['emp_mail'] = $mail_sent_status->data->params->mail;
- $sent_message_data['mail_subject'] = $mail_sent_status->data->params->subject;
- $sent_message_data['mail_content'] = $mail_sent_status->data->params->message;
+ if ($mail_sent_status_object->status == 'success') {
- $message_insert_status = $this->ticketMessage->insert($sent_message_data);
+ $message_insert_status = $this->ticketController->autoMessageInsertBasedOnMailResponse($mail_sent_status, $ticket_id);
if ($message_insert_status) {
$message = 'Claim Initiated Successfully';
@@ -3229,11 +3249,11 @@ class EmployeeRestController extends AdminController
return $this->respond(['status' => false, 'code' => 400, 'message' => $message], 200);
}
} else {
-
$message = 'Claim Initiated, Failed to send Mail ';
$this->myLogger->logme('error', "Claim initiated, Failed to send Mail :$ticket_id ");
return $this->respond(['status' => false, 'code' => 400, 'message' => $message], 200);
}
+
} else {
$message = 'Something Went Wrong';
return $this->respond(['status' => false, 'code' => 400, 'message' => $message], 200);
@@ -3310,4 +3330,23 @@ class EmployeeRestController extends AdminController
return $this->response->setJSON(['ticket_data' => $ticket_data])->setStatusCode(200);
}
+ public function getWellnessUrl()
+ {
+ // $url = "https://aam.mohfw.gov.in/home/login";
+ $url = "";
+
+ if (!empty($url)) {
+ return $this->respond([
+ 'status' => 'success',
+ 'data' => $url
+ ], 200);
+ } else {
+ return $this->respond([
+ 'status' => 'failed',
+ 'message' => 'Coming soon........!'
+ ], 200);
+ }
+ }
+
+
}
\ No newline at end of file
diff --git a/app/Controllers/EmployeeServiceController.php b/app/Controllers/EmployeeServiceController.php
index 61e0af4a..5584d67c 100755
--- a/app/Controllers/EmployeeServiceController.php
+++ b/app/Controllers/EmployeeServiceController.php
@@ -28,6 +28,9 @@ use App\Controllers\JobWorker ;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Kint\Kint;
+use App\Helpers\ExcelSanitizeHelper;
+
+
class EmployeeServiceController extends AdminController
{
@@ -150,7 +153,7 @@ class EmployeeServiceController extends AdminController
'is_mandatory' => ['I', 'A', 'DA'],
'data_type' => 'str',
'format' => null,
- 'allowed_values' => null,
+ 'allowed_values' => ['Self', 'Spouse', 'Son', 'Daughter', 'Father', 'Mother', 'Father in Law', 'Mother in Law'],
'custom' => 'check_relationship',
'params' => ['row', 'relationship', 'policy_terms']
],
@@ -468,7 +471,7 @@ class EmployeeServiceController extends AdminController
'format' => null,
'allowed_values' => null,
'custom' => 'check_si',
- 'params' => ['row', 'policy_terms', 'slab_details']
+ 'params' => ['row', 'policy_details', 'slab_details']
],
'date_of_enhancement' => [
'col_idx' => 4,
@@ -725,6 +728,7 @@ class EmployeeServiceController extends AdminController
$allowedHighestColumn = end($columns_to_check);
// dd($allowedHighestColumn);
$excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']);
+ $excel_data = ExcelSanitizeHelper::sanitizeArrayData($excel_data);
// !dd(array_chunk($excel_data,20)[0]);
//check no of columns in excel
@@ -994,7 +998,7 @@ class EmployeeServiceController extends AdminController
$allowedHighestColumn = end($columns_to_check);
$excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']);
- // print_r($keys);die();
+ $excel_data = ExcelSanitizeHelper::sanitizeArrayData($excel_data);
//remove header
unset($excel_data[0]);
@@ -1032,6 +1036,14 @@ class EmployeeServiceController extends AdminController
// kint::dump($family);
$family = data_group_by_family($family)[ $emp_id ];// reason to call this again bring self to first index of the array
}
+ $firstNonTemp = null;
+
+ foreach ($family as $fam) {
+ if (!isset($fam['temp'])) {
+ $firstNonTemp = $fam;
+ break;
+ }
+ }
// kint::dump($family);//die();
//check name dup within a family
@@ -1067,7 +1079,7 @@ class EmployeeServiceController extends AdminController
if(!count($self_details))
{
array_push($result['error_summary'],14); // Self not found
- $result['error_data'][ $family[0][0] ]['sno']['error'][] = "Self not found in Database";
+ $result['error_data'][ $firstNonTemp[0] ]['sno']['error'][] = "Self not found in Database";
}
}
@@ -1075,7 +1087,7 @@ class EmployeeServiceController extends AdminController
if($file['action'] == 'dependent_addition' || $file['action'] == 'addition' || $file['action'] == 'inception'|| $file['action'] == 'missed_inception' || $file['action'] == 'enrollment')
{
$res = check_dependent_conflict($family,$policy_terms,$file['action'],$is_lgbtq);
- // dd($res);
+ // Kint::dump($res);
if(!$res['status'])
{
foreach($res['error_data'] as $key => $value)
@@ -1088,7 +1100,7 @@ class EmployeeServiceController extends AdminController
//check dup with empid and name with db
$res = name_and_empid_check_in_db($family,$file);
- // dd($res);
+ // Kint::dump($res['del']);
// echo ' ';
// print_r($res);
if(count($res['del']))
@@ -1110,7 +1122,7 @@ class EmployeeServiceController extends AdminController
}// end of foreach
}// end of if current action I,DA,A
- // return $result;
+ // return $result;
// die();
if(isset($result['error_summary']) && count($result['error_summary']))
{
@@ -1356,19 +1368,28 @@ class EmployeeServiceController extends AdminController
break;
}
// echo ' START- ' . $row[2];
- $employee = $this->employeeModel->where('emp_code', $row[1])->where('name',$row[2])->where('client_id',$file['client_id'])->where('client_branch_id',$file['client_branch_id'])->first();
+
+ $employee = $this->employeeModel
+ ->where('emp_code', $row[1])
+ ->where('name',$row[2])
+ ->where('client_id',$file['client_id'])
+ ->where('client_branch_id',$file['client_branch_id'])
+ ->where('emp_status !=','truncated')
+ ->where('is_active', 1)
+ ->first();
// $employee = $this->employeeModel->where('emp_code', $row[1])->where('name',$row[2])->where('client_id',$file['client_id'])->first();
// dd($employee);
if(is_array($employee) && count($employee))
{
// dd($employee);
$existing_endorsements = $this->empEndorsementModel->where('actions','d')
- ->where('table_name','employees')
+ ->where('table_name','employee_polices')
->where('endorsement_id is null')
->where('emp_code',$employee['emp_code'])
->where('name',$employee['name'])
- ->where('field_name','emp_status')
+ ->where('field_name','status')
->where('status !=','truncated')
+ ->where('is_active', 1)
->findAll();
// dd($existing_endorsements);
@@ -1527,8 +1548,21 @@ class EmployeeServiceController extends AdminController
break;
}
// echo ' START- ' . $row[2];
- $employee = $this->employeeModel->where('emp_code', $row[1])->where('name',$row[2])->where('client_id',$file['client_id'])->where('client_branch_id',$file['client_branch_id'])->first();
- $employee_policy = $this->employeePolicyModel->where('employee_id',$employee['id'])->where('client_policy_id',$file['policy_id'])->first();
+ $employee = $this->employeeModel
+ ->where('emp_code', $row[1])
+ ->where('name',$row[2])
+ ->where('client_id',$file['client_id'])
+ ->where('client_branch_id',$file['client_branch_id'])
+ ->where('emp_status', 'active')
+ ->where('is_active', 1)
+ ->first();
+ $employee_policy = $this->employeePolicyModel
+ ->where('employee_id',$employee['id'])
+ ->where('client_policy_id',$file['policy_id'])
+ ->where('status', 'active')
+ ->where('is_active', 1)
+ ->first();
+ // dd($employee, $employee_policy);
$existing_endorsements = $this->empEndorsementModel->where('actions','si')
->where('table_name','employee_polices')
@@ -1552,9 +1586,19 @@ class EmployeeServiceController extends AdminController
if($pre_rack_rate_name != $slab_value['rack_rate_name'])
{
$pre_rack_rate_name = $slab_value['rack_rate_name'];
- $rack_rate_json = json_decode($slab_value['additional_relationship']);
- if(in_array(strtolower($employee['relationship']), $rack_rate_json) && $rack_rate_json[ strtolower($employee['relationship']) ] != 0 && $rack_rate_json[ strtolower($employee['relationship']) ] != 'NA')
- {
+ $rack_rate_json = json_decode($slab_value['additional_relationship'], true);
+ $relationship_array_key = strtolower(trim($employee['relationship']));
+
+ if (in_array($relationship_array_key, ['son', 'daughter'])) {
+ $relationship_array_key = 'childrens';
+ } elseif (in_array($relationship_array_key, ['father', 'mother'])) {
+ $relationship_array_key = 'parents';
+ } elseif (in_array($relationship_array_key, ['father in law', 'mother in law', 'father-in-law', 'mother-in-law'])) {
+ $relationship_array_key = 'parents-in-law';
+ }
+
+ if(array_key_exists($relationship_array_key, $rack_rate_json) && $rack_rate_json[$relationship_array_key] != 0 && $rack_rate_json[$relationship_array_key] != 'NA')
+ {
$applicable_rack_rate_name = $slab_value['rack_rate_name'];
$applicable_rack_rate_master = $slab_value['grid_master'];
break;
@@ -1563,11 +1607,13 @@ class EmployeeServiceController extends AdminController
}
//get max age,max count of the familiy
- $max_age_and_max_count_of_current_member = $this->employeeModel->getFamiliyCountAndMaxage($employee['emp_code']);
+ $max_age_and_max_count_of_current_member = $this->employeeModel->getFamiliyCountAndMaxage($employee['emp_code']);
//transform SI excel row data as inception excel OR premium calculateable fomart
$data = transform_si_excel_row_to_calculatable_format(employee: $employee,employee_policy: $employee_policy,maxage_and_maxcount: $max_age_and_max_count_of_current_member,slab_details: $slab_details,applicable_slab_name: $applicable_rack_rate_name,augmented_si: $row[3],grid_master: $applicable_rack_rate_master);
$policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'],$file['policy_id']);
+ $policy_terms = (array) $policy_terms[0];
+ // dd($policy_terms);
//grouping slab details by rack rate name
$temp_slab_rates = group_slab_rates_basedon_name($slab_details);
@@ -1585,6 +1631,7 @@ class EmployeeServiceController extends AdminController
}
+
$this->fileModel->where('id', $file_id)->set(['status' => 'success','reason' => ''])->update();
$this->myLogger->logme("error",'{file_id} uploaded success',['file_id' => $file_id]);
//set success msg to pull notifications
@@ -1658,6 +1705,7 @@ class EmployeeServiceController extends AdminController
// $this->myLogger->logme('error',('Insert - ' . $value['emp_code'] .' - '. $value['name']));
// echo 'update emp';
}
+ $value = ExcelSanitizeHelper::sanitizeArrayData($value);
$this->employeeModel->save($value);
if (isset($value['id'])) {
$emp_id = $value['id'];
@@ -2048,12 +2096,14 @@ public function getFileMetaDataByFileId($file_id, $status = 'success'){
$relation = 'parent';
} else if(strtolower(trim($value['relationship'])) === 'son' || strtolower(trim($value['relationship'])) === 'daughter'){
$relation = 'child';
- }else if(strtolower(trim($value['relationship'])) === 'father in law' || strtolower(trim($value['relationship'])) === 'mother in law'){
+ }else if((strtolower(trim($value['relationship'])) === 'father in law' || strtolower(trim($value['relationship'])) === 'mother in law') || (strtolower(trim($value['relationship'])) === 'father-in-law' || strtolower(trim($value['relationship'])) === 'mother-in-law')){
$relation = 'parent_in_law';
}else if(strtolower(trim($value['relationship'])) === 'spouse'){
$relation = 'spouse';
- }else{
+ }else if(strtolower(trim($value['relationship'])) === 'self'){
$relation = 'self';
+ }else {
+ $relation = '';
}
$value['family_floater_key'] = $relation;
@@ -2081,7 +2131,8 @@ public function getFileMetaDataByFileId($file_id, $status = 'success'){
$value['created_by'] = $file['created_by'];
$log_message = 'Enrollment Insert Employee- '.$value['name'] .'('.$value['emp_code'] .') with PK ';
}
-
+
+ $value = ExcelSanitizeHelper::sanitizeArrayData($value);
$this->employeeModel->save($value);
if (isset($value['id']))
{ $emp_id = $value['id']; }
diff --git a/app/Controllers/JobWorker.php b/app/Controllers/JobWorker.php
index fcaf2096..4cbf5350 100755
--- a/app/Controllers/JobWorker.php
+++ b/app/Controllers/JobWorker.php
@@ -123,6 +123,14 @@ class JobWorker extends AdminController
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmpDataServiceController',
],
+ 'makeEntryForBDSPolicyTransaction' => [
+ 'type' => 'CC', // Handler Category
+ 'handler' => 'App\Controllers\EmpDataServiceController',
+ ],
+ 'removeBDSPolicyTransactionEntryFromTruncate' => [
+ 'type' => 'CC', // Handler Category
+ 'handler' => 'App\Controllers\EmpDataServiceController',
+ ],
'employeesEnrollmentInsert' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmployeeServiceController',
@@ -130,7 +138,11 @@ class JobWorker extends AdminController
'calculateMembersDemography' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\LeadsController',
- ]
+ ],
+ 'updatePolicyTransactionDataWhileClinetPolicyUpdate' => [
+ 'type' => 'CC', // Handler Category
+ 'handler' => 'App\Controllers\ClientController',
+ ],
];
diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php
index 6260124c..67c5c1da 100644
--- a/app/Controllers/LeadsController.php
+++ b/app/Controllers/LeadsController.php
@@ -28,6 +28,9 @@ use App\Models\InsurerBranchModel;
use App\Models\TPABranchModel;
use App\Models\RFQModel;
use App\Models\InsurerModel;
+use App\Models\OccupancyMasterModel;
+use App\Models\LeadFilesModel;
+use App\Models\LeadInstallmentPaymentDetails;
use App\Helpers\MailHelper;
use App\Helpers\ExcelMergeHelper;
@@ -38,6 +41,8 @@ use Kint\Kint;
use App\Controllers\Jobs;
use App\Controllers\JobWorker;
use Google\Service\FactCheckTools\Resource\Claims;
+use GPBMetadata\Google\Type\Datetime;
+use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class LeadsController extends BaseController
{
@@ -60,6 +65,9 @@ class LeadsController extends BaseController
protected $tpaBranchModel;
protected $RFQModel;
protected $insurerModel;
+ protected $occupancyModel;
+ protected $leadFilesModel;
+ protected $leadInstallmentPaymentDetails;
//variables for storing array
protected $issuer;
@@ -68,6 +76,7 @@ class LeadsController extends BaseController
protected $leadsStatus;
protected $claim_type_for_gpa;
protected $cause_of_death;
+ protected $buisnessType;
public function __construct()
@@ -88,19 +97,29 @@ class LeadsController extends BaseController
$this->tpaBranchModel = new TPABranchModel();
$this->RFQModel = new RFQModel();
$this->insurerModel = new InsurerModel();
+ $this->occupancyModel = new OccupancyMasterModel();
+ $this->leadFilesModel = new LeadFilesModel();
+ $this->leadInstallmentPaymentDetails = new LeadInstallmentPaymentDetails();
$this->issuer = [1 => 'JIBS', 2 => 'Nhance'];
$this->clientType = [1 => 'Group', 2 => 'Individual'];
$this->leadType = [1 => 'Fresh', 2 => 'Renewal', 3 => 'Roll Over'];
+ $data = $this->kycEntityTypeModel->where('is_active', 1)->findAll();
+ $this->buisnessType = array_column($data, 'name', 'id');
+ // $this->buisnessType = [1 => 'Public Sector', 2 => 'Private Sector',3=> 'Trust',4 => 'Proprietorship',5 => 'Partnership',6 => 'Private',7 => 'Individual'];
$this->leadsStatus = [
- 'queued' => 'Queued',
- 'qcr_sent' => 'QCR sent',
- 'lost' => 'Lost',
- 'co_insurer_pending' => 'Co-Insurer Pending',
- 'won' => 'Won',
- 'completed_with_corrections' => 'Completed with Corrections',
- 'completed_without_corrections' => 'Completed w/o Corrections',
+ 'queued' => 'In-Queued',
+ 'rfq_created' => 'RFQ Created',
+ 'rfq_sent' => 'RFQ Sent',
+ 'qcr_created' => 'QCR Created',
+ 'qcr_sent' => 'QCR Sent',
+ 'lost' => 'Lost',
+ 'co_insurer_pending' => 'Co-Insurer Pending',
+ 'won' => 'Won',
+ 'completed_with_corrections' => 'Completed with Corrections',
+ 'completed_without_corrections' => 'Completed without Corrections',
];
+
$this->claim_type_for_gpa = [
'accident_death' => 'Accident Death',
'permanent_total_disablement' => 'Permanent Total Disablement',
@@ -113,7 +132,6 @@ class LeadsController extends BaseController
'suicide' => 'Suicide',
'accident' => 'Accident'
];
-
}
public function viewLeadsList()
@@ -133,24 +151,41 @@ class LeadsController extends BaseController
// dd($lastFiveYears);
if ($this->request->is('get')) {
// Fetch leads data
- $data ['lead_data_list'] = $this->leadsModel->getLeadDataForLising();
+ $data['lead_data_list'] = $this->leadsModel->getLeadDataForLising();
// Load layout and pass data
$this->loadLayout('lead_filter', $data);
- }else{
+ } else {
- $search_data = $this->request->getPost();
- // print_r($search_data);
+ $isFromDashboard = $this->request->getPost("is_dashboard");
- $where = [];
- foreach ($search_data as $search_objects => $key) {
- if ($key != null && $key != '' && $key != 0) {
- $where[$search_objects] = $key;
+ if (isset($isFromDashboard) && !empty($isFromDashboard) && $isFromDashboard == 1) {
+ $ids = $this->request->getPost('ids');
+ $ids = array_filter(explode(',', $ids));
+
+ if (!empty($ids)) {
+ $idsStr = implode(',', array_map('intval', $ids)); // sanitize IDs to be integers
+ $where = "leads.id IN ($idsStr)";
+ } else {
+ $where = '1 = 0'; // No valid IDs, return empty result
}
+ // dd($where );
+ $data['lead_data_list'] = $this->leadsModel->getLeadDataForLising($where);
+ $this->loadLayout('lead_filter', $data);
+ } else {
+ $search_data = $this->request->getPost();
+
+ $where = [];
+ foreach ($search_data as $search_objects => $key) {
+ if ($key != null && $key != '' && $key != 0 && $search_objects != 'is_dashboard') {
+ $where[$search_objects] = $key;
+ }
+ }
+
+ $data['lead_data_list'] = $this->leadsModel->getLeadDataForLising($where);
+
+ $html = view('leads_list', $data);
+ return $this->respond(['status' => true, 'html' => $html], 200);
}
-
- $data['lead_data_list'] = $this->leadsModel->getLeadDataForLising($where);
- $html = view('leads_list', $data);
- return $this->respond(['status' => true, 'html' => $html], 200);
}
}
@@ -173,7 +208,7 @@ class LeadsController extends BaseController
{
$data = $this->request->getPost();
- if ($data['lead_type'] == 2) {
+ if ($data['lead_type'] != 1) {
$client_data = $this->clientModel->where('id', $data['client_id'])->where('is_active', 1)->first();
$data['client_name'] = $client_data['client_name'];
$data['client_short_name'] = $client_data['short_name'];
@@ -190,11 +225,12 @@ class LeadsController extends BaseController
$data['client_code'] = generate_client_code('IC');
}
- if(isset($data['lead_form_type'])){
+ if (isset($data['lead_form_type'])) {
$data = $this->prepareSingleLeadData($data);
- }else{
+ } else {
$data = $this->prepareMultipleLeadData($data);
}
+
// print_r($data); die;
return $data;
}
@@ -202,52 +238,56 @@ class LeadsController extends BaseController
private function prepareSingleLeadData($data)
{
// print_r($data); die;
- $uploadFilePath = WRITEPATH . 'uploads/lead_files/';
+ $index_plus_one = 1;
+ $form_file_name = "file_name_" . $index_plus_one;
+ $form_docs_name = "docs_name_" . $index_plus_one;
+ $leads_file_primary_key = $data['leads_file_id'] ?? [];
- // Get all uploaded files for 'file_name[]'
- $files = $this->request->getFileMultiple('file_name');
+ $multi_file_data = [];
+ if (isset($data[$form_docs_name])) {
+ $files = $this->request->getFileMultiple($form_file_name);
+ $multi_file_data = $this->uploadMultiFiles($files, $data[$form_docs_name], $leads_file_primary_key);
+ }
- // print_r($files); die;
-
+ // Separate the insurer and insurer branch, handle missing or invalid data
+ if (isset($data['insurer']) && strpos($data['insurer'], '-') !== false) {
+ list($insurer_branch_id, $insurer_id) = explode('-', $data['insurer']);
+ } else {
+ $insurer_branch_id = 0;
+ $insurer_id = 0;
+ }
- // Separate the insurer and insurer branch, handle missing or invalid data
- if (isset($data['insurer']) && strpos($data['insurer'], '-') !== false) {
- list($insurer_branch_id, $insurer_id) = explode('-', $data['insurer']);
-
- }else{
- $insurer_branch_id = 0;
- $insurer_id = 0;
- }
+ $data['insurer_id'] = $insurer_id;
+ $data['insurer_branch_id'] = $insurer_branch_id;
- $data['insurer_id'] = $insurer_id;
- $data['insurer_branch_id'] = $insurer_branch_id;
+ // Separate the insurer and insurer branch, handle missing or invalid data
+ if (isset($data['tpa']) && strpos($data['tpa'], '-') !== false) {
+ list($tpa_branch_id, $tpa_id) = explode('-', $data['tpa']);
+ } else {
+ $tpa_branch_id = 0;
+ $tpa_id = 0;
+ }
- // Separate the insurer and insurer branch, handle missing or invalid data
- if (isset($data['tpa']) && strpos($data['tpa'], '-') !== false) {
- list($tpa_branch_id, $tpa_id) = explode('-', $data['tpa']);
- } else {
- $tpa_branch_id = 0;
- $tpa_id = 0;
- }
-
- $data['tpa_id'] = $tpa_id;
- $data['tpa_branch_id'] = $tpa_branch_id;
+ $data['tpa_id'] = $tpa_id;
+ $data['tpa_branch_id'] = $tpa_branch_id;
- if (!empty($data['policy_start_date'])) {
- $data['policy_start_date'] = change_date_format($data['policy_start_date']);
- } else {
- $data['policy_start_date'] = null;
- }
+ if (!empty($data['policy_start_date'])) {
+ $data['policy_start_date'] = change_date_format($data['policy_start_date']);
+ } else {
+ $data['policy_start_date'] = null;
+ }
- if (!empty($data['policy_end_date'])) {
- $data['policy_end_date'] = change_date_format($data['policy_end_date']);
- } else {
- $data['policy_end_date'] = null;
- }
+ if (!empty($data['policy_end_date'])) {
+ $data['policy_end_date'] = change_date_format($data['policy_end_date']);
+ } else {
+ $data['policy_end_date'] = null;
+ }
- $data['file_name'] = file_Upload($files, $uploadFilePath);
- $processcedData[] = $data;
+ // $data['file_name'] = file_Upload($files, $uploadFilePath);
+ $data['multi_file_data'] = $multi_file_data ?? null;
+
+ $processcedData[] = $data;
// print_r($data);die();
return $processcedData;
@@ -257,20 +297,20 @@ class LeadsController extends BaseController
{
// print_r($data); die;
$processedData = [];
- $uploadFilePath = WRITEPATH . 'uploads/lead_files/';
- // Get all uploaded files for 'file_name[]'
- $files = $this->request->getFileMultiple('file_name');
+ foreach ($data['policy_type_id'] as $index => $value) {
- // print_r($files); die;
-
- foreach($data['policy_type_id'] as $index => $value){
+ $index_plus_one = $index + 1;
+ $form_file_name = "file_name_" . $index_plus_one;
+ $form_docs_name = "docs_name_" . $index_plus_one;
+ $leads_file_primary_key = $data['leads_file_id'] ?? [];
+ $files = $this->request->getFileMultiple($form_file_name);
+ $multi_file_data = $this->uploadMultiFiles($files, $data[$form_docs_name], $leads_file_primary_key);
// Separate the insurer and insurer branch, handle missing or invalid data
if (isset($data['insurer'][$index]) && strpos($data['insurer'][$index], '-') !== false) {
list($insurer_branch_id, $insurer_id) = explode('-', $data['insurer'][$index]);
-
- }else{
+ } else {
$insurer_branch_id = 0;
$insurer_id = 0;
}
@@ -310,19 +350,31 @@ class LeadsController extends BaseController
$policy_end_date = null;
}
- if(!empty($data['incurred_claim_date'][$index])){
+ if (!empty($data['incurred_claim_date'][$index])) {
$incurred_claims_date = change_date_format($data['incurred_claim_date'][$index], 'd/m/Y', 'Y-m-d');
- }else{
+ } else {
$incurred_claims_date = null;
}
- if(!empty($data['premium_date'][$index])){
- $premium_date = change_date_format($data['premium_date'][$index], 'd/m/Y', 'Y-m-d');
- }else{
- $premium_date = null;
+ // if (!empty($data['premium_date'][$index])) {
+ // $premium_date = change_date_format($data['premium_date'][$index], 'd/m/Y', 'Y-m-d');
+ // } else {
+ // $premium_date = null;
+ // }
+
+ if (!empty($data['source_policy_start_date'])) {
+ $data['source_policy_start_date'] = change_date_format($data['source_policy_start_date'], 'd/m/Y', 'Y-m-d');
+ } else {
+ $data['source_policy_start_date'] = null;
}
- $file_name = file_Upload($files[$index], $uploadFilePath);
+ if (!empty($data['source_policy_end_date'])) {
+ $data['source_policy_end_date'] = change_date_format($data['source_policy_end_date'], 'd/m/Y', 'Y-m-d');
+ } else {
+ $data['source_policy_end_date'] = null;
+ }
+
+ // $file_name = file_Upload($files[$index], $uploadFilePath);
$last_3_years_claims = $data['finyear'];
@@ -376,7 +428,7 @@ class LeadsController extends BaseController
'outstanding_claims' => $data['outstanding_claims'][$index] ?? 0,
'policy_run_days' => $data['policy_run_days'][$index] ?? 0,
'premium_at_inception' => $data['premium_at_inception'][$index] ?? 0,
- 'premium_date' => $premium_date,
+ 'premium_date' => $data['premium_date'][$index] ?? 0,
'earned_premium' => $data['earned_premium'][$index] ?? 0,
'annualised_claims' => $data['annualised_claims'][$index] ?? 0,
'incurred_claims_ratio' => $data['incurred_claims_ratio'][$index] ?? 0,
@@ -385,13 +437,18 @@ class LeadsController extends BaseController
'total_si_at_renewal' => $data['total_si_at_renewal'][$index] ?? 0,
'fin_years_claims' => $last_3_years_claims,
- 'file_name' => $file_name,
+ // 'file_name' => $file_name,
+ 'multi_file_data' => $multi_file_data ?? null,
'status' => $data['status'] ?? null,
'notes' => $data['notes'] ?? null,
'lead_form_type' => $data['lead_form_type'] ?? 1,
'custom_fields' => $data['custom_fields'] ?? null,
+
+ 'source_policy_start_date' => $data['source_policy_start_date'] ?? null,
+ 'source_policy_end_date' => $data['source_policy_end_date'] ?? null,
+ 'claim_history' => $data['claim_history'] ?? 0
];
}
// print_r($processedData);die();
@@ -403,10 +460,15 @@ class LeadsController extends BaseController
$insertCount = [];
foreach ($data as $value) {
$insert = $this->leadsModel->insert($value);
+
+ if ($insert) {
+ $this->insertMultiFilesData($value['multi_file_data'], $insert);
+ }
+
$insertCount[] = $insert;
$this->insertLeadStatus($insert, $value['status'], 3);
- if($value['lead_form_type'] == 1){
+ if ($value['lead_form_type'] == 1) {
//for this push the job to the calculateMembersDemography() function
$job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'calculateMembersDemography', 'payload' => [
@@ -425,13 +487,15 @@ class LeadsController extends BaseController
private function updateOldLead($id, $data)
{
if ($this->leadsModel->where('id', $id)->set($data[0])->update()) {
+
+ $this->insertMultiFilesData($data[0]['multi_file_data'], $id);
$this->insertLeadStatus($id, $data[0]['status'], 3);
return $this->respond(['status' => true, 'lead_id' => $id, 'message' => "Lead updated successfully", 'data' => $data], 200);
}
return $this->respond(['status' => false, 'lead_id' => $id, 'message' => "Failed to update Lead", 'data' => $data], 200);
}
- // Get the Single Lead data for edit
+ // Get the Single Lead data for edit uisng ajax ( do not delete)
public function getLeadDataForEdit($id)
{
@@ -441,9 +505,9 @@ class LeadsController extends BaseController
->first();
$data['lead_edit_data'] = $this->leadsModel
- ->where('leads.id', $id)
- ->where('leads.is_active', 1)
- ->first();
+ ->where('leads.id', $id)
+ ->where('leads.is_active', 1)
+ ->first();
if (!empty($data['policy_start_date'])) {
@@ -464,11 +528,13 @@ class LeadsController extends BaseController
$data['incurred_claims_date'] = null;
}
- if (!empty($data['premium_date'])) {
- $data['premium_date'] = change_date_format($data['premium_date'], 'Y-m-d', 'd/m/Y');
- } else {
- $data['premium_date'] = null;
- }
+ // if (!empty($data['premium_date'])) {
+ // $data['premium_date'] = change_date_format($data['premium_date'], 'Y-m-d', 'd/m/Y');
+ // } else {
+ // $data['premium_date'] = null;
+ // }
+
+ $data['multi_file_data'] = $this->leadFilesModel->where('lead_id', $id)->first() ?? null;
$data['lastFiveYears'] = $this->getLastFiveFinancialYears();
$data['gpaClaimType'] = $this->claim_type_for_gpa;
@@ -483,6 +549,8 @@ class LeadsController extends BaseController
$data['html'] = $this->generateViewPageHtml($data['policy_type_id'], $data) ?? "";
+ // print_r($data); die;
+
if ($data) {
return $this->respond(['status' => true, 'data' => $data], 200);
} else {
@@ -501,26 +569,92 @@ class LeadsController extends BaseController
$this->policyTransactionStatusModel->insert($statusData);
}
+ public function uploadMultiFiles($files, $docs_names, $primaryKey)
+ {
+ $uploadFilePath = WRITEPATH . 'uploads/lead_files/';
+
+ $multi_file_data = [];
+ foreach ($files as $index => $value) {
+ $file_name = file_Upload($value, $uploadFilePath);
+ $multi_file_data[] = [
+ 'file_name' => $file_name,
+ 'docs_name' => $docs_names[$index],
+ 'id' => $primaryKey[$index] ?? "",
+ ];
+ }
+
+ return $multi_file_data;
+ }
+
+ public function insertMultiFilesData($data, $lead_id)
+ {
+ // print_r($data); die;
+
+ if (!empty($data)) {
+ foreach ($data as $key => $value) {
+
+ if (!empty($value['id'])) {
+
+ $lead_file_data = [
+ 'lead_id' => $lead_id,
+ 'docs_name' => $value['docs_name'],
+ ];
+
+ if (!empty($value['file_name'])) {
+ $lead_file_data['file_name'] = $value['file_name'];
+ }
+
+ $this->leadFilesModel->where('id', $value['id'])->set($lead_file_data)->update();
+ } else {
+
+ if (!empty($value['file_name'])) {
+ $lead_file_data = [
+ 'lead_id' => $lead_id,
+ 'docs_name' => $value['docs_name'],
+ 'file_name' => $value['file_name'],
+ ];
+ $this->leadFilesModel->insert($lead_file_data);
+ }
+ }
+
+ if ($key == 0 && !empty($value['file_name'])) {
+ $this->leadsModel->where('id', $lead_id)->set('file_name', $value['file_name'])->update();
+ }
+ }
+ }
+
+ return true;
+ }
+
+ public function removeMultiFile()
+ {
+ $id = $this->request->getGet('lead_file_id');
+ if (!empty($id)) {
+ $this->leadFilesModel->where('id', $id)->set(['is_active' => 0])->update();
+ return $this->respond(['status' => true, 'message' => 'File removed successfully'], 200);
+ } else {
+ return $this->respond(['status' => false, 'message' => 'File could not be removed.'], 200);
+ }
+ }
//--------RFQ-----------------------------------------------------------------------------------------------
-
public function viewRFQ($id, $type = 1)
{
$data['rfq_data'] = $this->RFQModel
- ->where('lead_id', $id)
- // ->where('type', $type)
- ->where('is_active', 1)
- ->orderBy('id', 'desc')
- ->first();
+ ->where('lead_id', $id)
+ // ->where('type', $type)
+ ->where('is_active', 1)
+ ->orderBy('id', 'desc')
+ ->first();
// dd($data);
$data['rfq_count'] = $this->RFQModel
- ->where('lead_id', $id)
- // ->where('type', 1)
- ->where('is_active', 1)
- ->countAllResults();
+ ->where('lead_id', $id)
+ // ->where('type', 1)
+ ->where('is_active', 1)
+ ->countAllResults();
$data['qcr_count'] = $this->RFQModel
->where('lead_id', $id)
@@ -532,92 +666,240 @@ class LeadsController extends BaseController
$data['lead_id'] = $id;
$lead_data = $this->leadsModel
- ->select('
+ ->select('
leads.*,
policy_type.question_json,
policy_type.policy_type,
policy_type.long_name,
user_profiles.email as created_person_email
')
- ->join('policy_type', 'leads.policy_type_id = policy_type.id')
- ->join('user_profiles', 'leads.created_by = user_profiles.id', 'left')
- ->where('leads.id', $id)
- ->where('leads.is_active', 1)
- ->first();
+ ->join('policy_type', 'leads.policy_type_id = policy_type.id')
+ ->join('user_profiles', 'leads.created_by = user_profiles.id', 'left')
+ ->where('leads.id', $id)
+ ->where('leads.is_active', 1)
+ ->first();
// dd($lead_data);
- if ($lead_data['lead_type'] == 2) {
+ if ($lead_data['lead_type'] != 1) {
$client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $lead_data['source_policy_id'])->first();
- $data['policy_terms'] = $client_policy_data['policy_terms'];
+ if (isset($client_policy_data)) {
+ $data['policy_terms'] = $client_policy_data['policy_terms'];
+ }
}
$data['question_json'] = $lead_data['question_json'];
$data['page_name'] = $type == 2 ? 'QCR' : 'RFQ';
$data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
$data['userList'] = $this->userModel->getUserListForRFQ();
+ $data['exclusiveUserList'] = $this->userModel->getexclusiveUserListForRFQ();
$data['lead_data'] = $lead_data;
-
- $mail_content = "
+
+ $mail_content = '
Dear Sir,
Greetings From Nhance India!
Please find attached the {{RFQ_OR_QCR}} for {{POLICY_TYPE}} policy pertaining to {{CLIENT_NAME}} .
Kindly request you to share the competitive quotes at the earliest.
In case of any query, please feel free to contact us.
- Thank You!
- ";
-
+ Thank You!
+ Best regards,
+
+
+
{{LOGGED_USER_NAME}}
+
Mobile: {{LOGGED_USER_MOBILE}}
+
- $subject = "{{CLIENT_NAME}} _ {{POLICY_TYPE}} _ {{RFQ_OR_QCR}} _ {{POLICY_YEAR}}";
+
+ ';
+
+ if ($data['lead_data']['policy_end_date'] != null) {
+ $subject = "{{CLIENT_NAME}} _ {{POLICY_TYPE}} _ {{RFQ_OR_QCR}} _ {{POLICY_YEAR}} {{POLICY_END_DATE}}";
+ } else {
+ $subject = "{{CLIENT_NAME}} _ {{POLICY_TYPE}} _ {{RFQ_OR_QCR}} _ {{POLICY_YEAR}}";
+ }
+
+ if ($lead_data['policy_type_id'] == 1) {
+ $data['totalSumAssured'] = $this->handleMemberDataGPATotalSumInsurerFromExcel(['lead_id' => $id]);
+ } else {
+ $data['totalSumAssured'] = [];
+ }
$data['mail_content'] = $this->transformMailContent($lead_data, $mail_content, $data['page_name']);
$data['subject'] = $this->transformMailContent($lead_data, $subject, $data['page_name']);
+ $data['placement_mail_content'] = $this->transformMailContent($lead_data, $mail_content, 'Placement');
+ $data['placement_subject'] = $this->transformMailContent($lead_data, $subject, 'Placement');
+ $data['multi_file_data'] = $this->leadFilesModel->where('lead_id', $id)->where('is_active', 1)->findAll() ?? null;
+ $installment_data['installments'] = $this->leadInstallmentPaymentDetails->where('lead_id', $id)->where('is_active', 1)->findAll() ?? null;
+ $data['lead_data']['installment_data'] = view('rfq/installment_fields', $installment_data) ?? null;
+ $data['attachment_html'] = view('rfq/attachment_files', $data) ?? "";
+ $data['user_team'] = $this->userModel->select("ut.team_id")->join("user_teams ut", "ut.user_id = user_profiles.id and ut.is_active = 1")->where("user_profiles.is_active", 1)->first()['team_id'];
// dd($data);
- if ($data['lead_data']['lead_form_type'] == 1){
-
- $this->loadLayout('view_rfq.php', $data);
- }else if ($data['lead_data']['lead_form_type'] == 2){
-
- $data['policies'] = json_decode($data['question_json'], true)['policies'];
- $data["child_table_data"] = json_decode($data['question_json'], true)['child_table_data'];
+ if ($data['lead_data']['lead_form_type'] == 1) {
+
+ $this->loadLayout('view_rfq.php', $data);
+ } else if ($data['lead_data']['lead_form_type'] == 2) {
+
+ $data['occupancy'] = $this->occupancyModel->findAll();
+ // dd($data['occupancy']);
+
+ if ($lead_data['lead_type'] != 1 && $data['rfq_count'] == 0) {
+ $client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $lead_data['source_policy_id'])->first();
+ if (isset($client_policy_data)) {
+
+ $data['rfq_data']['json'] = $client_policy_data['placement_json'];
+ }
+ }
+
+ if (!empty($data['question_json'])) {
+ $data['policies'] = json_decode($data['question_json'], true)['policies'];
+ $data["child_table_data"] = json_decode($data['question_json'], true)['child_table_data'];
+ }
+
+ $data['product'] = $this->leadsModel->select("policy_type.policy_type")->join('policy_type', 'leads.policy_type_id = policy_type.id')->where('leads.id', $id)->first()['policy_type'];
// $data['lead_register_data'] = json_decode($data['lead_data']['custom_fields']);
// dd($data['lead_register_data']);
+ // $data['entity_type'] = $this->kycEntityTypeModel->where('is_active', 1)->findAll();
+ $data['buisness_type'] = $this->buisnessType;
+
+ // dd($data);
$data['client_type'] = $this->clientType;
$this->loadLayout('view_rfq_non_eb', $data);
-
}
-
}
+ public function savePolicyInfo()
+ {
+
+ $data = $this->request->getPost();
+
+ $lead_id = $data['lead_id'];
+ $json_data = $data['registration_json'];
+
+ $existingJson = $this->RFQModel->where('is_active', 1)->where("lead_id", $lead_id)->first()['registration_json'] ?? null;
+
+ if (empty($existingJson)) {
+ $this->RFQModel
+ ->where('lead_id', $lead_id)
+ ->where('type', 1)
+ ->where('is_active', 1)
+ ->set('is_active', 0)
+ ->update();
+
+ $insertData['lead_id'] = $lead_id;
+ $insertData['registration_json'] = json_encode($json_data);
+
+
+ $this->RFQModel->insert($insertData);
+
+ return $this->respond(['status' => true, "message" => "Policy Inforamtion saved"]);
+ } else {
+
+ return $this->respond(['status' => true, "message" => "Policy Inforamtion Already saved"]);
+ }
+ }
public function createRFQ()
{
-
- // print_r($this->request->getPost('json')); die();
-
$data = $this->request->getPost();
- $lead_id = $data['lead_id'];
- $data['type'] = 1;
- $this->RFQModel
- ->where('lead_id', $lead_id)
- ->where('type', 1)
- ->where('is_active', 1)
- ->set('is_active', 0)
- ->update();
+ $lead_id = $data['lead_id'] ?? null;
- $result = $this->RFQModel->insert($data);
-
- if ($result) {
-
- $message = "RFQ submitted successfully";
- if($data['submit_type'] == 'QCR'){ $message = "QCR submitted successfully"; }
- return $this->respond(['status' => true, 'id' => $result, 'message' => $message, 'data' => $data], 200);
+ if (!$lead_id) {
+ return $this->respond(['status' => false, 'message' => 'Lead ID is required'], 400);
}
- return $this->respond(['status' => false, 'id' => $result, 'message' => "Failed to create RFQ", 'data' => $data], 200);
+ $rfq_created = $this->RFQModel->where('lead_id', $lead_id)->where('is_active', 1)->countAllResults();
+ $qcr_created = false;
+ $inputJson = json_decode($data['json'], true);
+ if (isset($inputJson['premium_data']) && !empty($inputJson['premium_data'])) {
+ $sortedJson = $this->reorderProposalsByInsurerTotal($inputJson);
+ $data['json'] = json_encode($sortedJson);
+ $qcr_created = true;
+ }
+
+ if (($data['submit_type'] ?? "") == 'QCR') {
+ $inputJson = json_decode($data['json'], true);
+ $proposal_data = array_pop($inputJson);
+ if (isset($proposal_data['proposal_data']['over_all_column_data'])) {
+ $proposel_count = $proposal_data['proposal_data']['over_all_column_data'];
+ foreach ($proposel_count as $key => $value) {
+ if (!empty($value['insurers'])) {
+ $qcr_created = true;
+ }
+ }
+ }
+ }
+
+ $data['type'] = 1;
+
+ // Deactivate existing RFQs for this lead and type
+ if (!isset($data['rfq_primaryKey']) && empty($data['rfq_primaryKey'])) {
+ $this->RFQModel
+ ->where('lead_id', $lead_id)
+ ->where('type', 1)
+ ->where('is_active', 1)
+ ->set('is_active', 0)
+ ->update();
+ }
+
+ // Handle registration_json
+ if (empty($data['registration_json'])) {
+ // Fetch the latest registration_json if not provided
+ $latest = $this->RFQModel
+ ->select('registration_json')
+ ->where('lead_id', $lead_id)
+ ->orderBy('id', 'DESC')
+ ->first();
+
+ if (!empty($latest['registration_json'])) {
+ $data['registration_json'] = $latest['registration_json'];
+ }
+ }
+
+ // print_r($data); die;
+ // $data['json'] = "";
+ if (isset($data['rfq_primaryKey']) && !empty($data['rfq_primaryKey'])) {
+ $this->RFQModel->update($data['rfq_primaryKey'], $data);
+ $insertId = $data['rfq_primaryKey'];
+ $affectedRows = db_connect()->affectedRows();
+ } else {
+ // Insert new RFQ
+ $insertId = $this->RFQModel->insert($data);
+ }
+
+ if ($insertId) {
+
+ if (empty($rfq_created)) {
+ $this->leadsModel->update($lead_id, ['status' => "rfq_created"]);
+ }
+
+ if ($qcr_created == true) {
+ $this->leadsModel
+ ->where('id', $lead_id)
+ ->whereNotIn('status', ['qcr_sent', 'lost', 'co_insurer_pending', 'won', 'completed_with_corrections', 'completed_without_corrections'])
+ ->set(['status' => "qcr_created"])
+ ->update();
+ }
+
+ $message = ($data['submit_type'] ?? '') == 'QCR' ? 'QCR saved successfully' : 'RFQ saved successfully';
+ return $this->respond([
+ 'status' => true,
+ 'id' => $insertId,
+ 'message' => $message,
+ 'data' => $data,
+ 'affectedRows' => $affectedRows ?? null,
+ ], 200);
+ }
+
+ $message = ($data['submit_type'] ?? '') == 'QCR' ? 'Failed to save QCR' : 'Failed to save RFQ';
+ return $this->respond([
+ 'status' => false,
+ 'id' => null,
+ 'message' => $message,
+ 'data' => $data
+ ], 200);
}
public function createQCR()
@@ -644,6 +926,227 @@ class LeadsController extends BaseController
}
+ private function reorderProposalsByInsurerTotal(array $data): array
+ {
+
+ if (!isset($data['premium_data']['data'])) return $data;
+
+ $original = $data['premium_data']['data'];
+ $proposals = [];
+ $others = [];
+ $emptyKeyData = [];
+
+ foreach ($original as $key => $value) {
+ // Match only keys that look like 'Proposal X'
+ if (preg_match('/^Proposal\s+\d+$/', $key)) {
+ // Get the insurer entry (not 'Quote Asked')
+ foreach ($value as $subKey => $subVal) {
+ if ($subKey !== 'Quote Asked' && isset($subVal['Total'])) {
+ $proposals[$key] = $value;
+ break;
+ } else {
+ $proposals[$key] = $value;
+ }
+ }
+ } else {
+
+ if ($key === '' && isset($value['']) && is_array($value[''])) {
+ // Capture empty key to push it later
+ $emptyKeyData[$key] = $value;
+ } else {
+ $others[$key] = $value;
+ }
+ }
+ }
+
+ // Sort proposals by their insurer's total
+ uasort($proposals, function ($a, $b) {
+ $totalA = 0;
+ $totalB = 0;
+
+ foreach ($a as $key => $val) {
+ if ($key !== 'Quote Asked' && isset($val['Total'])) {
+ $totalA = floatval($val['Total']);
+ break;
+ }
+ }
+
+ foreach ($b as $key => $val) {
+ if ($key !== 'Quote Asked' && isset($val['Total'])) {
+ $totalB = floatval($val['Total']);
+ break;
+ }
+ }
+
+ return $totalA <=> $totalB;
+ });
+
+ // Merge back the sorted proposals into the full structure
+ $data['premium_data']['data'] = array_merge($others, $proposals, $emptyKeyData);
+ $data = $this->reorderProposalDataByPremiumOrder($data);
+ return $data;
+ }
+
+ private function reorderProposalDataByPremiumOrder(array $data): array
+ {
+ if (!isset($data['premium_data']['data'], $data['proposal_data']['over_all_column_data'])) {
+ return $data;
+ }
+
+ $premiumProposals = array_keys($data['premium_data']['data']);
+ $filteredProposals = [];
+
+ // Collect proposal keys that match the pattern "Proposal X"
+ foreach ($premiumProposals as $key) {
+ if (preg_match('/^Proposal\s+\d+$/', $key) && isset($data['proposal_data']['over_all_column_data'][$key])) {
+ $filteredProposals[$key] = $data['proposal_data']['over_all_column_data'][$key];
+ }
+ }
+
+ // dd($premiumProposals, $filteredProposals);
+
+ $data['proposal_data']['over_all_column_data'] = $filteredProposals;
+ $data = $this->reorderProposalInHeaderAndData($data);
+ return $data;
+ }
+
+ private function reorderProposalInHeaderAndData(array $data): array
+ {
+ $tableData = $data['table_data'];
+ $sortedProposalOrder = $data['proposal_data']['over_all_column_data'];
+ $headers = $tableData['headers'] ?? [];
+ $dataRows = $tableData['data'] ?? [];
+
+ // Step 1: Separate static and proposal headers
+ $staticHeaders = [];
+ $proposalHeaders = [];
+ $actionHeader = [];
+ foreach ($headers as $header) {
+ if (in_array($header['parentHeader'], array_keys($sortedProposalOrder))) {
+ $proposalHeaders[$header['parentHeader']] = $header;
+ } else {
+ if ($header['parentHeader'] == "Action") {
+ $actionHeader[] = $header;
+ } else {
+ $staticHeaders[] = $header;
+ }
+ }
+ }
+
+ // dd($staticHeaders, $proposalHeaders, $sortedProposalOrder);
+
+ // Step 2: Reorder headers
+ $reorderedHeaders = [];
+ foreach ($sortedProposalOrder as $proposalKey => $proposalValue) {
+ if (isset($proposalHeaders[$proposalKey])) {
+ $reorderedHeaders[] = $proposalHeaders[$proposalKey];
+ }
+ }
+
+ // print_rr($reorderedHeaders); die;
+ foreach ($reorderedHeaders as $key => &$value) {
+ $value['parentHeader'] = 'Proposal ' . ($key + 1);
+ }
+ unset($value);
+
+
+ $reorderedHeaders = array_merge($staticHeaders, $reorderedHeaders, $actionHeader);
+
+
+ // Step 3: Reorder each row's `data` by matching parentth
+ foreach ($dataRows as $dataRowIndex => &$row) {
+ $staticData = [];
+ $proposalData = [];
+ $actionData = [];
+
+ foreach ($row['data'] as $entry) {
+ if (in_array($entry['parentth'], array_keys($sortedProposalOrder))) {
+ $proposalData[$entry['parentth']][] = $entry;
+ } else {
+ if ($entry['parentth'] == "Action") {
+ $actionData[] = $entry;
+ } else {
+ $staticData[] = $entry;
+ }
+ }
+ }
+
+ $reorderedProposalData = [];
+ foreach ($sortedProposalOrder as $proposalKey => $proposalValue) {
+ if (isset($proposalData[$proposalKey])) {
+ foreach ($proposalData[$proposalKey] as $entry) {
+ $reorderedProposalData[] = $entry;
+ }
+ }
+ }
+
+ $dubParTh = "";
+ $increament = 0;
+ foreach ($reorderedProposalData as $key => &$value) {
+
+ if ($dubParTh == $value['parentth']) {
+ $value['parentth'] = 'Proposal ' . ($increament);
+ } else {
+ $dubParTh = $value['parentth'];
+ $increament = $increament + 1;
+ $value['parentth'] = 'Proposal ' . ($increament);
+ }
+ }
+ unset($value);
+
+ $row['data'] = array_merge($staticData, $reorderedProposalData, $actionData);
+ }
+
+ $data['table_data']['headers'] = $reorderedHeaders;
+ $data['table_data']['data'] = $dataRows;
+
+ $renumberedArray = $this->renumberProposalKeys($data['proposal_data']['over_all_column_data']);
+ $updatedDataSet = $this->renumberProposalKeys($data['premium_data']['data']);
+ $data['proposal_data']['over_all_column_data'] = !empty($renumberedArray) ? $renumberedArray : $data['proposal_data']['over_all_column_data'];
+ $data['premium_data']['data'] = !empty($updatedDataSet) ? $updatedDataSet : $data['premium_data']['data'];
+
+ return $data;
+ }
+
+ private function renumberProposalKeys(array $input): array
+ {
+ $result = [];
+ $counter = 1;
+
+ foreach ($input as $key => $value) {
+ if (strpos($key, 'Proposal') === 0) {
+ $newKey = 'Proposal ' . $counter++;
+ $result[$newKey] = $value;
+ } else {
+ $result[$key] = $value;
+ }
+ }
+
+ return $result;
+ }
+
+ public function removeInstallments()
+ {
+ $id = $this->request->getGet('id');
+ // print_r($id); die;
+ if (!empty($id)) {
+ $this->leadInstallmentPaymentDetails->whereIn('id', $id)->set(['is_active' => 0])->update();
+ } else {
+ return $this->respond(['status' => false, 'message' => 'Could not be removed.'], 200);
+ }
+
+ if ($this->request->getGet('lead_id')) {
+ $lead_id = $this->request->getGet('lead_id');
+ $data = [
+ 'no_of_installment' => 0,
+ 'is_installment' => 0
+ ];
+ $this->leadsModel->where('id', $lead_id)->set($data)->update();
+ }
+
+ return $this->respond(['status' => true, 'message' => 'Removed successfully'], 200);
+ }
+
//-----RFQ and QCR EXPORT------------------------------------------------------------------------------------------------
@@ -655,10 +1158,10 @@ class LeadsController extends BaseController
//FOR EXCEL
public function exportExcelForQCRandRFQ($lead_id, $type, $lead_form_type = 1)
- {
- if($lead_form_type == 2){
+ {
+ if ($lead_form_type == 2) {
$filepath = $this->constructNonEbExcelToSaveTemp($lead_id, $type);
- }else{
+ } else {
$filepath = $this->constructExcelToSaveTemp($lead_id, $type);
}
@@ -710,43 +1213,47 @@ class LeadsController extends BaseController
//Construct excel file and save the file to the folder and return file path
public function constructExcelToSaveTemp($lead_id, $type, $propsal_and_insurer = null)
{
+ helper('excel_util_helper');
$rfq_data = $this->RFQModel->getRFQTableDataWithLeadIDAndType($lead_id, $type);
+ $is_placement = false;
+ $length = 0;
// dd($rfq_data, $lead_id, $type, $propsal_and_insurer);
// print_r($propsal_and_insurer); die;
if ($rfq_data['lead_type'] == 1) {
- if ($rfq_data['policy_type_id'] == 2) {
+ if (in_array($rfq_data['policy_type_id'], [2, 3, 4, 5])) {
$lead_data = [
-
'Insured' => $rfq_data['client_name'],
- 'Policy Status' => $rfq_data['status'],
+ 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "",
'No of Employees' => $rfq_data['incept_emp_count'],
'No of Dependents' => $rfq_data['incept_dept_count'],
'Total Lives' => $rfq_data['incept_no_of_lives'],
- 'Period of Insurance ' => date('d/m/Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d/m/Y', strtotime($rfq_data['policy_end_date'])),
- 'Policy Run Days' => $rfq_data['policy_run_days'],
+ 'Period of Insurance ' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided",
+ 'Insurer' => $rfq_data['insurer_name'] ?? " - ",
+ 'TPA' => $rfq_data['tpa_name'] ?? " - ",
+ // 'Policy Run Days' => $rfq_data['policy_run_days'],
];
- } else if ($rfq_data['policy_type_id'] == 1) {
+ } else if (in_array($rfq_data['policy_type_id'], [1, 6, 7])) {
$lead_data = [
'Insured' => $rfq_data['client_name'],
'No of Employees at Inception' => $rfq_data['incept_emp_count'],
'Total Sum Insured at Inception ' => $rfq_data['total_si_at_incept'],
- 'Policy Period' => date('d/m/Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d/m/Y', strtotime($rfq_data['policy_end_date'])),
- 'Policy Status' => $rfq_data['status'],
- 'Existing Insurer' => $rfq_data['insurer_name'],
- 'TPA ' => $rfq_data['tpa_name'],
+ 'Policy Period' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided",
+ 'Insurer' => $rfq_data['insurer_name'] ?? " - ",
+ 'TPA' => $rfq_data['tpa_name'] ?? " - ",
+ 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "",
];
}
} else {
- if ($rfq_data['policy_type_id'] == 2) {
+ if (in_array($rfq_data['policy_type_id'], [2, 3, 4, 5])) {
$lead_data = [
'Insured' => $rfq_data['client_name'],
- 'Policy Status' => $rfq_data['status'],
+ 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "",
'No of Employees at Inception' => $rfq_data['incept_emp_count'],
'No of Dependents at Inception' => $rfq_data['incept_dept_count'],
@@ -760,23 +1267,27 @@ class LeadsController extends BaseController
'No of Dependents at Renewal' => $rfq_data['renewal_dept_count'],
'Total Lives at Renewal ' => $rfq_data['renewal_no_of_lives'],
- 'Period of Insurance ' => date('d/m/Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d/m/Y', strtotime($rfq_data['policy_end_date'])),
+ 'Period of Insurance ' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided",
+ 'Insurer' => $rfq_data['insurer_name'] ?? " - ",
+ 'TPA' => $rfq_data['tpa_name'] ?? " - ",
'Policy Run Days' => $rfq_data['policy_run_days'],
- 'Inception Premium' => $rfq_data['premium_at_inception'],
- 'Premium as on (Date - DD MM YYYY should be entered based on the claims dump report)' => $rfq_data['premium_date'],
+ 'Inception Premium' => formatIndianCurrency($rfq_data['premium_at_inception']),
+ 'Premium as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => formatIndianCurrency($rfq_data['premium_date']),
'Earned Premium' => $rfq_data['earned_premium'],
- 'Incurred Claims as on (Date - DD MM YYYY should be entered based on the claims dump report)' => $rfq_data['incurred_claims_date'],
- 'Annualised Claims' => $rfq_data['annualised_claims'],
- 'Incurred Claims Ratio' => $rfq_data['incurred_claims_ratio'],
- 'Earned Claims Ratio' => $rfq_data['earned_claims_ratio'],
+ 'Incurred Claims as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => formatIndianCurrency($rfq_data['incurred_claims']),
+ 'Annualised Claims' => formatIndianCurrency($rfq_data['annualised_claims']),
+ 'Incurred Claims Ratio' => $rfq_data['incurred_claims_ratio'] . " %",
+ 'Earned Claims Ratio' => $rfq_data['earned_claims_ratio'] . " %",
];
- } else if ($rfq_data['policy_type_id'] == 1) {
+ } else if (in_array($rfq_data['policy_type_id'], [1, 6, 7])) {
$lead_data = [
'Insured' => $rfq_data['client_name'],
'No of Employees at Renewal' => $rfq_data['renewal_emp_count'],
'Total Sum Insured at Renewal ' => $rfq_data['total_si_at_renewal'],
- 'Policy Period' => date('d/m/Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d/m/Y', strtotime($rfq_data['policy_end_date'])),
- 'Policy Status' => $rfq_data['status'],
+ 'Policy Period' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided",
+ 'Insurer' => $rfq_data['insurer_name'] ?? " - ",
+ 'TPA' => $rfq_data['tpa_name'] ?? " - ",
+ 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "",
'Existing Insurer' => $rfq_data['insurer_name'],
'TPA ' => $rfq_data['tpa_name'],
];
@@ -786,25 +1297,32 @@ class LeadsController extends BaseController
$data = json_decode($rfq_data['json'], true);
// dd($data);
+ $sheetName = 'Worksheet';
if ($type == 2) {
+ $sheetName = 'QCR';
$data = $this->convertJsonForQCR($data, $type);
if ($propsal_and_insurer !== null) {
list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2);
$data = $this->transformProposelData($data, $proposal_key, $insurer_key);
+ $is_placement = true;
+ $sheetName = 'Placement';
}
} else if ($type == 1) {
+ $sheetName = 'RFQ';
$data = $this->convertJsonForQCR($data, $type);
// dd($data);
}
+ // dd($data);
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
+ $sheet->setTitle($sheetName);
// Start with lead_data at the top
$rowNumber = 1;
- $mergeRange1 = "A{$rowNumber}:C{$rowNumber}";
+ $mergeRange1 = "A{$rowNumber}:B{$rowNumber}";
$sheet->mergeCells($mergeRange1);
$sheet->setCellValue("A{$rowNumber}", "Nhance India Insurance Broking Pvt Ltd");
$sheet->getStyle("A{$rowNumber}")->applyFromArray([
@@ -818,25 +1336,9 @@ class LeadsController extends BaseController
],
]);
- // Set column width to fit the image properly
- $sheet->getColumnDimension('D')->setWidth(20); // Adjust as needed
- $sheet->getRowDimension($rowNumber)->setRowHeight(40); // Adjust as needed
-
- $drawing = new Drawing();
- $path = ROOTPATH . "public/assets/images/Nhance-Logo-Final.png"; // Use FCPATH for server path
- $drawing->setPath($path);
- $drawing->setCoordinates("D{$rowNumber}"); // Set position in column B
- $drawing->setHeight(35); // Adjust image height
-
- // Center align the image in the cell
- $drawing->setOffsetX(30); // Adjust horizontal offset
- $drawing->setOffsetY(5); // Adjust vertical offset
-
- $drawing->setWorksheet($sheet);
-
// Apply center alignment to the cell
- $sheet->getStyle("D{$rowNumber}")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
- $sheet->getStyle("D{$rowNumber}")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
+ $sheet->getStyle("C{$rowNumber}")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
+ $sheet->getStyle("C{$rowNumber}")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
$rowNumber = $rowNumber + 1;
@@ -849,7 +1351,7 @@ class LeadsController extends BaseController
// Merge A:B for key and C:D for value
$mergeRangeKey = "A{$rowNumber}:B{$rowNumber}";
- $mergeRangeValue = "C{$rowNumber}:D{$rowNumber}";
+ $mergeRangeValue = "C{$rowNumber}";
$sheet->mergeCells($mergeRangeKey);
$sheet->mergeCells($mergeRangeValue);
@@ -880,11 +1382,10 @@ class LeadsController extends BaseController
$rowNumber++;
}
- // Set column width based on max content length (adjusted for padding)
+ // // Set column width based on max content length (adjusted for padding)
$sheet->getColumnDimension('A')->setWidth($maxWidthA * 1.2);
- $sheet->getColumnDimension('B')->setWidth($maxWidthA * 1.2);
- $sheet->getColumnDimension('C')->setWidth($maxWidthB * 1.2);
- $sheet->getColumnDimension('D')->setWidth($maxWidthB * 1.2);
+ $sheet->getColumnDimension('B')->setWidth($maxWidthA * 1.5);
+ $sheet->getColumnDimension('C')->setWidth($maxWidthB * 1.6);
// $rowNumber += 2;
@@ -908,7 +1409,11 @@ class LeadsController extends BaseController
],
]);
$subheader_count = array_sum(array_map(fn($header) => count($header['subHeaders']), $data['table_data']['headers']));
- $subheader_count = $subheader_count - 2;
+
+ if ($is_placement == false) {
+ $subheader_count = $subheader_count - 2;
+ }
+
$headerCount = count($data['table_data']['headers']);
$lastColumn = Coordinate::stringFromColumnIndex($subheader_count);
// dd( $headerCount, $lastColumn);
@@ -926,12 +1431,17 @@ class LeadsController extends BaseController
]);
$sheet->mergeCells($mergeRange);
+ $rowNumber_for_remove_quote_asked = $rowNumber;
$rowNumber = $rowNumber + 1;
-
- $subHeaderRow = $rowNumber + 1;
+ if ($type == 2) {
+ $subHeaderRow = $rowNumber + 1;
+ } else {
+ $subHeaderRow = $rowNumber_for_remove_quote_asked;
+ }
$columnLetter = 'A';
foreach ($headers as $header) {
+ // Kint::dump($header);
if (in_array($header['parentHeader'], ['Item Key', 'Action'])) {
continue;
@@ -943,14 +1453,21 @@ class LeadsController extends BaseController
}
if ($header['parentHeader'] === 'Particulars') {
- $sheet->getColumnDimension('B')->setWidth(40);
+ $sheet->getColumnDimension('B')->setWidth(50);
}
$startColumn = $columnLetter; // Start of the current header range
$subHeaderCount = count($header['subHeaders']); // Number of subheaders for this parent header
-
// Set parent header value
- $sheet->setCellValue("{$startColumn}{$rowNumber}", $header['parentHeader']);
+ if ($is_placement == true && !in_array($header['parentHeader'], ['Particulars', 'S.No.'])) {
+ $sheet->setCellValue("{$startColumn}{$rowNumber}", "Terms");
+ } else {
+ if(in_array($header['parentHeader'], ["Existing Renewal", "Existing Rollover"])){
+ $sheet->setCellValue("{$startColumn}{$rowNumber}", "Terms");
+ }else{
+ $sheet->setCellValue("{$startColumn}{$rowNumber}", $header['parentHeader']);
+ }
+ }
$sheet->getStyle("{$startColumn}{$rowNumber}")->applyFromArray([
'font' => ['bold' => true],
'alignment' => [
@@ -961,7 +1478,7 @@ class LeadsController extends BaseController
// Merge header cells if it spans multiple subheaders
if ($subHeaderCount > 1) {
- $endColumn = chr(ord($startColumn) + $subHeaderCount - 1); // Calculate the end column
+ $endColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($startColumn) + $subHeaderCount - 1);
$sheet->mergeCells("{$startColumn}{$rowNumber}:{$endColumn}{$rowNumber}");
} else {
$endColumn = $startColumn; // No merge needed if only one subheader
@@ -969,27 +1486,37 @@ class LeadsController extends BaseController
// Add subheaders
foreach ($header['subHeaders'] as $subHeader) {
- $sheet->setCellValue("{$columnLetter}{$subHeaderRow}", $subHeader);
- if ($columnLetter != "A" && $columnLetter != "B" && $columnLetter != "C" && $columnLetter != "D") {
+ if ($type == 2 && $is_placement == false) {
+ $sheet->setCellValue("{$columnLetter}{$subHeaderRow}", $subHeader);
+ }
+
+ if ($columnLetter != "A" && $columnLetter != "B" && $columnLetter != "C") {
$sheet->getColumnDimension($columnLetter)->setWidth(35);
} else {
$sheet->getColumnDimension('A')->setWidth(10);
}
- $sheet->getStyle("{$columnLetter}{$subHeaderRow}")->applyFromArray([
- 'font' => ['bold' => true],
- 'alignment' => [
- 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
- 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
- ],
- ]);
+ if ($is_placement == false) {
+ $sheet->getStyle("{$columnLetter}{$subHeaderRow}")->applyFromArray([
+ 'font' => ['bold' => true],
+ 'alignment' => [
+ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ ],
+ ]);
+ }
+
$columnLetter++; // Move to the next column for subheaders
+ // Kint::dump($subHeader);
+ $length++;
}
}
+ // die();
// Apply border to the header range
- $headerRange = "A{$rowNumber}:" . chr(ord($columnLetter) - 1) . "{$subHeaderRow}";
+ $prevColumn1 = $this->getPreviousColumn($columnLetter);
+ $headerRange = "A{$rowNumber}:" . "{$prevColumn1}" . "{$subHeaderRow}";
$sheet->getStyle($headerRange)->applyFromArray([
'borders' => [
'allBorders' => [
@@ -1003,7 +1530,12 @@ class LeadsController extends BaseController
$sheet->getRowDimension($rowNumber)->setRowHeight(25); // Header row height
$sheet->getRowDimension($subHeaderRow)->setRowHeight(20); // Subheader row height
- $rowNumber = $subHeaderRow + 2;
+ if ($is_placement == true) {
+ $rowNumber = $subHeaderRow;
+ } else {
+ $rowNumber = $subHeaderRow + 2;
+ }
+ // dd($rowNumber);
$column_data = $data['table_data']['data'];
$serial_no = 1;
$maxColumnWidths = [];
@@ -1028,7 +1560,8 @@ class LeadsController extends BaseController
$serial_no++;
}
- $dataRange = "A" . ($subHeaderRow + 1) . ":" . chr(ord($columnLetter) - 1) . ($rowNumber - 1);
+ $prevColumn2 = $this->getPreviousColumn($columnLetter);
+ $dataRange = "A" . ($subHeaderRow + 1) . ":" . "{$prevColumn2}" . ($rowNumber - 1);
$sheet->getStyle($dataRange)->applyFromArray([
'borders' => [
'allBorders' => [
@@ -1038,7 +1571,7 @@ class LeadsController extends BaseController
],
]);
-
+ //premium data
if ($type == 2) {
$rowNumber += 2;
@@ -1055,10 +1588,17 @@ class LeadsController extends BaseController
foreach ($premiumData as $proposal => $insurers) {
if ($proposal != 'Particulars') {
foreach ($insurers as $insurer => $values) {
- $premium[] = $values[$labelArray[0]];
- $gst[] = $values[$labelArray[1]];
- $gstAmt[] = $values[$labelArray[2]];
- $total[] = $values[$labelArray[3]];
+ if($insurer == 'Quote Asked'){
+ $premium[] = "";
+ $gst[] = "";
+ $gstAmt[] = "";
+ $total[] = "";
+ }else{
+ $premium[] = formatIndianCurrency($values[$labelArray[0]]);
+ $gst[] = $values[$labelArray[1]];
+ $gstAmt[] = formatIndianCurrency($values[$labelArray[2]]);
+ $total[] = formatIndianCurrency($values[$labelArray[3]]);
+ }
}
}
}
@@ -1075,8 +1615,14 @@ class LeadsController extends BaseController
$rowNumber++;
}
- $premiumRange = "B" . ($rowNumber - 4) . ":" . chr(ord($columnLetter) - 2) . ($rowNumber - 1);
+ if ($is_placement == true) {
+ $prevColumn3 = $this->getPreviousColumn($columnLetter);
+ } else {
+ $prevColumn3 = $this->getPreviousColumn($columnLetter, 2);
+ }
+ $premiumRange = "B" . ($rowNumber - 4) . ":" . "{$prevColumn3}" . ($rowNumber - 1);
// dd($premiumRange);
+
$sheet->getStyle($premiumRange)->applyFromArray([
'borders' => [
'allBorders' => [
@@ -1087,6 +1633,67 @@ class LeadsController extends BaseController
]);
}
+
+ //set imgage and align the row and column
+ // Kint::dump($columnLetter);
+ if ($type == 2) {
+ if ($is_placement == true) {
+ $columnLetter_img = $this->getPreviousColumn($columnLetter);
+ } else {
+ $columnLetter_img = $this->getPreviousColumn($columnLetter, 2);
+ }
+ } else {
+ $columnLetter_img = $this->getPreviousColumn($columnLetter);
+ }
+ // dd($columnLetter_img);
+
+ $company_name = $this->getPreviousColumn($columnLetter_img);
+ $mergeRange1 = "A1:{$company_name}1";
+ $sheet->mergeCells($mergeRange1);
+
+ $rowCount = count($lead_data);
+ for ($i = 2; $i <= $rowCount + 1; $i++) {
+ $mergeRange1 = "C{$i}:{$columnLetter_img}{$i}";
+ $sheet->mergeCells($mergeRange1);
+ $sheet->getStyle($mergeRange1)->applyFromArray([
+ 'borders' => [
+ 'allBorders' => [
+ 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
+ 'color' => ['argb' => 'FF000000'], // Black color
+ ],
+ ],
+ ]);
+ }
+
+ $sheet->getColumnDimension($columnLetter_img)->setWidth(40);
+ $sheet->getRowDimension(1)->setRowHeight(40); // Adjust as needed
+
+ $drawing = new Drawing();
+ $path = ROOTPATH . "public/assets/images/Nhance-Logo-Final.png"; // Use FCPATH for server path
+ $drawing->setPath($path);
+ $drawing->setCoordinates("{$columnLetter_img}1"); // Set position in column B
+ $drawing->setHeight(35); // Adjust image
+ $columnWidth = $sheet->getColumnDimension("C")->getWidth(); // e.g., 20
+ $cellPixelWidth = $columnWidth * 7; // Approximate conversion (1 unit ≈ 7 pixels)
+ $imagePixelWidth = 250; // Approximate width of your image (in pixels)
+
+ $offsetX = max(0, ($cellPixelWidth - $imagePixelWidth) / 2);
+ $offsetX = $offsetX + 97;
+ // dd($length);
+ if ($length >= 4) {
+ $offsetX = 50;
+ } else if ($length == 3) {
+ $offsetX = 65;
+ }
+
+ // Center align the image in the cell
+ $drawing->setOffsetX($offsetX); // Adjust horizontal offset
+ $drawing->setOffsetY(10); // Adjust vertical offset
+ $drawing->setWorksheet($sheet);
+
+ //end
+
+
// Auto-size columns
// foreach ($sheet->getColumnIterator() as $column) {
// $sheet->getColumnDimension($column->getColumnIndex())->setAutoSize(true);
@@ -1124,7 +1731,7 @@ class LeadsController extends BaseController
}
$lastRow = count($lead_data) + 1;
- $leadRange = "A1:D{$lastRow}";
+ $leadRange = "A1:{$columnLetter_img}{$lastRow}";
$sheet->getStyle($leadRange)->applyFromArray([
'borders' => [
@@ -1135,9 +1742,24 @@ class LeadsController extends BaseController
],
]);
+
+
// Set filename
- $string = ($type == 2) ? 'QCR' : 'RFQ';
- $filename = "{$string}_{$rfq_data['client_short_name']}_{$rfq_data['policy_type']}_" . date('YmdHis') . '.xlsx';
+ $string = ($type == 2) ? ($is_placement == true ? 'Placement' : 'QCR') : 'RFQ';
+ $current_year = date('Y');
+ $next_year = $current_year + 1;
+ $policy_year = "$current_year-$next_year";
+
+ if (!empty($rfq_data['policy_end_date'])) {
+
+ $policy_expiry = strtotime($rfq_data['policy_end_date']);
+ $formatted_policy = date("d-m-Y", $policy_expiry);
+ $filename = "{$rfq_data['client_name']}_{$rfq_data['policy_type']}_{$string}_" . $policy_year . '(Due On ' . $formatted_policy . ')' . '.xlsx';
+ } else {
+
+ $filename = "{$rfq_data['client_name']}_{$rfq_data['policy_type']}_{$string}_" . $policy_year . '_' . '.xlsx';
+ }
+
// Save to temporary location
$uploadFilePath = WRITEPATH . 'tmp/' . $filename;
@@ -1189,7 +1811,7 @@ class LeadsController extends BaseController
$highestRowAndColumn = $members_sheet->getHighestRowAndColumn();
// dd($highestRowAndColumn);
$uncleaned_members = $members_sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
- $members = ExcelSanitizeHelper::sanitizeArrayData($uncleaned_members);
+ $members = ExcelSanitizeHelper::sanitizeArrayData($uncleaned_members);
//get age band data
$age_band_sheet = $spreadsheet->getSheet(1);
$highestRowAndColumn = $age_band_sheet->getHighestRowAndColumn();
@@ -1224,21 +1846,21 @@ class LeadsController extends BaseController
$result = $this->generateClassifierSpreadsheet($classifiers, WRITEPATH . 'uploads/lead_files/');
if ($result['success']) {
$this->myLogger->logme('error', "Spreadsheet generated successfully!");
-
+
echo "Location: " . $result['fullpath'] . "\n";
echo "Filename: " . $result['filename'] . "\n";
$filePaths = [
['file_path' => WRITEPATH . 'uploads/lead_files/' . $lead_data['file_name'], 'sheets' => [0, 1]],
- ['file_path' => WRITEPATH.'/uploads/lead_files/' . $result['filename'], 'sheets' => []],
+ ['file_path' => WRITEPATH . '/uploads/lead_files/' . $result['filename'], 'sheets' => []],
];
- $outputPath = WRITEPATH . 'uploads/lead_files/Member_Data.xlsx';
+ $outputPath = WRITEPATH . 'uploads/lead_files/' . $lead_data['file_name'];
$result_merge = ExcelMergeHelper::mergeExcelFiles($filePaths, $outputPath);
if ($result_merge) {
// Call the delete function after the file is successfully created
- $deleteResponse = $this->deleteGeneratedFile($result['fullpath']);
-
- // Add delete message to response
- $response['deleteMessage'] = $deleteResponse['message'];
+ $deleteResponse = $this->deleteGeneratedFile($result['fullpath']);
+
+ // Add delete message to response
+ $response['deleteMessage'] = $deleteResponse['message'];
return ['status' => 'success', 'message' => 'Member_Data Merged Suceesfully'];
}
} else {
@@ -1257,7 +1879,8 @@ class LeadsController extends BaseController
public function getDemographyData($members, $age_band_data, $members_heading, $available_col, $col_index)
{
$first_loop = 0;
- $col_index_si = array_search('si enhancement', array_map('strtolower', $members_heading));
+ // $col_index_si = array_search('si enhancement', array_map('strtolower', $members_heading));
+ $col_index_si = array_search('si', array_map('strtolower', $members_heading));
$col_index_relationship = array_search('relationship', array_map('strtolower', $members_heading));
$relations = [];
$si_amt = ['general']; // Initialize with 'general' as per first loop condition
@@ -1370,17 +1993,17 @@ class LeadsController extends BaseController
throw new Exception("Failed to create directory: $outputDir");
}
}
-
+
// Check if directory is writable
if (!is_writable($outputDir)) {
throw new Exception("Directory is not writable: $outputDir");
}
-
+
// Generate unique filename
$timestamp = date('Y-m-d_His');
$filename = "member_classification_{$timestamp}.xlsx";
$filepath = $outputDir . DIRECTORY_SEPARATOR . $filename;
-
+
// Check if file already exists (shouldn't happen with timestamp, but just in case)
if (file_exists($filepath)) {
$counter = 1;
@@ -1390,31 +2013,31 @@ class LeadsController extends BaseController
$filename = "member_classification_{$timestamp}_{$counter}.xlsx";
$filepath = $outputDir . DIRECTORY_SEPARATOR . $filename;
}
-
+
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Demography_Data');
-
+
// Get all age bands
$age_bands = array_keys(reset($classifiers['general']));
array_pop($age_bands); // Remove 'Grand Total'
$age_bands[] = 'Grand Total'; // Add it back at the end
-
+
$currentRow = 5; // Start from row 5 to match the example
-
+
// Function to write section data
$writeSectionData = function ($data, $sheet, &$currentRow, $si_type) use ($age_bands) {
// Add section header for the SI type
$sheet->setCellValue('B' . $currentRow, strtoupper($si_type));
-
+
// Style section header
$sheet->getStyle('B' . $currentRow)->applyFromArray([
'font' => ['bold' => true, 'size' => 14],
'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER],
]);
-
+
$currentRow++; // Move to the next row after the section header
-
+
// Set headers for the data table
$sheet->setCellValue('B' . $currentRow, 'Relationship');
$col = 'C';
@@ -1422,7 +2045,7 @@ class LeadsController extends BaseController
$sheet->setCellValue($col . $currentRow, $band);
$col++;
}
-
+
// Style headers
$lastCol = chr(ord('B') + count($age_bands));
$headerRange = 'B' . $currentRow . ':' . $lastCol . $currentRow;
@@ -1438,9 +2061,9 @@ class LeadsController extends BaseController
'horizontal' => Alignment::HORIZONTAL_CENTER,
],
]);
-
+
$currentRow++;
-
+
// Write data rows
foreach ($data as $relation => $values) {
if ($relation !== 'Grand Total') {
@@ -1451,7 +2074,7 @@ class LeadsController extends BaseController
$sheet->setCellValue($col . $currentRow, $value);
$col++;
}
-
+
// Style data row
$dataRange = 'B' . $currentRow . ':' . $lastCol . $currentRow;
$sheet->getStyle($dataRange)->applyFromArray([
@@ -1465,11 +2088,11 @@ class LeadsController extends BaseController
'horizontal' => Alignment::HORIZONTAL_CENTER,
],
]);
-
+
$currentRow++;
}
}
-
+
// Add Grand Total row
$sheet->setCellValue('B' . $currentRow, 'Grand Total');
$col = 'C';
@@ -1477,7 +2100,7 @@ class LeadsController extends BaseController
$sheet->setCellValue($col . $currentRow, $data['Grand Total'][$band]);
$col++;
}
-
+
// Style Grand Total row
$totalRange = 'B' . $currentRow . ':' . $lastCol . $currentRow;
$sheet->getStyle($totalRange)->applyFromArray([
@@ -1496,31 +2119,31 @@ class LeadsController extends BaseController
'horizontal' => Alignment::HORIZONTAL_CENTER,
],
]);
-
+
$currentRow += 3; // Add gap after each section
};
-
+
// Write each SI section with gaps
foreach ($classifiers as $si_type => $data) {
$writeSectionData($data, $sheet, $currentRow, $si_type);
}
-
+
// Auto-size columns
foreach (range('B', chr(ord('B') + count($age_bands))) as $col) {
$sheet->getColumnDimension($col)->setAutoSize(true);
}
-
+
// Create Excel file
try {
// Create Excel file
$writer = new Xlsx($spreadsheet);
$writer->save($filepath);
-
+
// Verify file was created successfully
if (!file_exists($filepath)) {
throw new Exception("Failed to create file: $filepath");
}
-
+
// Return the file info after creation
$response = [
'success' => true,
@@ -1530,7 +2153,6 @@ class LeadsController extends BaseController
];
return $response;
-
} catch (Exception $e) {
return [
'success' => false,
@@ -1538,7 +2160,7 @@ class LeadsController extends BaseController
];
}
}
-
+
// Function to delete generated file
public function deleteGeneratedFile($filePath)
{
@@ -1562,7 +2184,7 @@ class LeadsController extends BaseController
];
}
}
-
+
public function getAge($available_col, $member, $col_index)
{
if ($available_col == 'age') {
@@ -1618,6 +2240,14 @@ class LeadsController extends BaseController
$propsal_and_insurer = isset($params['proposal_insurer']) ? $params['proposal_insurer'] : null;
$mail_content = $params['mail_content'];
$mail_subject = $params['subject'];
+ $attachment_file_ids = $params['selected_attachment_files'];
+
+ $from_mail = getenv('email.fromEmail');
+ if (in_array($recipient_type, ['placement', 'insurer', 'internal'])) {
+ $from_mail = "im@nhanceindia.in";
+ } else if (in_array($recipient_type, ['client'])) {
+ $from_mail = "bs@nhanceindia.in";
+ }
$result_data = [];
// dd($recipient_mail);
@@ -1633,17 +2263,19 @@ class LeadsController extends BaseController
->where('leads.id', $lead_id)
->first();
+ // log_message('error', 'Lead Data' . json_encode($lead_data));
// print_r($lead_data ); die;
$cc_mails = [];
$bcc_mails = [];
//get CC Mails
- if ($recipient_type == 'internal' || $recipient_type == 'placement' || $recipient_type == 'insurer' || $recipient_type == 'client') {
+ if ($recipient_type == 'internal' || $recipient_type == 'insurer' || $recipient_type == 'client') {
$cc_data = isset($params['cc']) ? $params['cc'] : "";
$param_cc_mail = json_decode($cc_data, true);
-
+
+
if (isset($param_cc_mail) && is_array($param_cc_mail) && count($param_cc_mail) > 0) {
// Fetch user data where ID is in the param_cc_mail array
$userData = $this->userModel
@@ -1667,6 +2299,8 @@ class LeadsController extends BaseController
// Handle case where param_cc_mail is not valid
// return $this->respond(['status' => 'failed','code' => 400,'data' => '','message' => 'CC mail not found!'], 200);
}
+ } else if ($recipient_type == 'placement') {
+ $cc_mails = isset($params['cc']) ? json_decode($params['cc'], true) : "";
}
//get BCC Mails
@@ -1674,7 +2308,7 @@ class LeadsController extends BaseController
$bcc_data = isset($params['bcc']) ? $params['bcc'] : "";
$param_bcc_mail = json_decode($bcc_data, true);
-
+
if (isset($param_bcc_mail) && is_array($param_bcc_mail) && count($param_bcc_mail) > 0) {
// Fetch user data where ID is in the param_cc_mail array
$userData = $this->userModel
@@ -1709,14 +2343,14 @@ class LeadsController extends BaseController
//get file path to attach
- if($lead_data["lead_form_type"] == 2){
+ if ($lead_data["lead_form_type"] == 2) {
$file_info = $this->constructNonEbExcelToSaveTemp($lead_id, ($file_type == 'rfq' ? 1 : 2), $propsal_and_insurer);
- }else{
+ } else {
$file_info = $this->constructExcelToSaveTemp($lead_id, ($file_type == 'rfq' ? 1 : 2), $propsal_and_insurer);
}
// $file_info = $this->constructExcelToSaveTemp($lead_id, ($file_type == 'rfq' ? 1 : 2), $propsal_and_insurer);
- log_message('error','File Info'.json_encode($file_info));
+ log_message('error', 'File Info' . json_encode($file_info));
if ($lead_data['file_name'] != null && $lead_data['file_name'] != '') {
$temp_file_path = $file_info['filePath'];
$temp_file_name = $file_info['fileName'];
@@ -1726,14 +2360,15 @@ class LeadsController extends BaseController
['file_path' => $temp_file_path, 'sheets' => []],
['file_path' => $lead_file_path, 'sheets' => []]
];
- $outputPath = dirname($temp_file_path) . '/' . 'merged_' . $temp_file_name;
+ $outputPath = dirname($temp_file_path) . '/' . $temp_file_name;
$result = ExcelMergeHelper::mergeExcelFiles($filePaths, $outputPath);
// print_rr($result);
}
- }else{
+ } else {
$result = $file_info['filePath'];
// return $this->respond(['status' => 'fail', 'code' => 200, 'messgae' => 'File Not Found'], 200);
}
+
// print_rr($result); die;
// print_rr($file_info);
// $file_path = WRITEPATH."uploads/excel/sample/correction.xls";
@@ -1742,37 +2377,43 @@ class LeadsController extends BaseController
$file_path = $result;
$file_name = basename($result);
+
+ // Attacments part
$attachments = [['fileName' => $file_name, 'filePath' => $file_path]];
+ $other_attachments = $this->handleMultiFileAttachments($attachment_file_ids, $lead_id);
+ $attachments = array_merge($attachments, $other_attachments);
+ // print_r($attachments); die;
//get recipient address
if ($recipient_type == 'insurer' || $recipient_type == 'placement') {
- // print_r($recipient_mail); die;
-
$recipient_data = $this->levelContactModel
->where(['contact_type' => 'insurer', 'is_active' => 1])
->whereIn('id', $recipient_mail)
->findAll();
-
- // print_r($recipient_data); die;
-
} else if ($recipient_type == 'client') {
- $recipient_data = [['name' => $lead_data['contact_person_name'], 'email' => $lead_data['contact_person_email']]];
+
+ $mailIDS = explode(',', $params['contact_mail']);
+ $recipient_data = [];
+ foreach ($mailIDS as $mail) {
+ $recipient_data[] = ['name' => $lead_data['contact_person_name'], 'email' => $mail];
+ }
} else {
$recipient_data = [['name' => "Team", 'email' => $params['to']]];
}
// print_r($recipient_data); die;
$subject = $file_type == 'rfq' ? 'Request for Quotation from ' . $lead_data['client_name'] . ' for ' . $lead_data['policy_type'] : 'Quotation Comparison Report for ' . $lead_data['policy_type'];
+
$original_message = '
Request for Quotation (RFQ) Dear {{RECIPIENT_NAME}}, We are reaching out to request a quotation for the following insurance coverage. Please review the details below and provide your quote at your earliest convenience.
RFQ Details Client name {{CLIENT_NAME}} Coverage Type {{POLICY_LONG_NAME}} Policy Start Date {{POLICY_START_DATE}} Policy Duration {{DURATION}}
Please note: Additional terms and details are included in the attachment for your reference.
Please feel free to reach out if you require any further information to prepare the quote. We look forward to receiving your proposal.
Best regards,
Nhance India Pvt Ltd
© Nhance India Pvt Ltd. All rights reserved.
';
//for mail content
- if(!empty($mail_content)){
+ if (!empty($mail_content)) {
$original_message = $mail_content;
}
//for mail subject
- if(!empty($mail_subject)){
+ if (!empty($mail_subject)) {
$subject = $mail_subject;
}
@@ -1782,9 +2423,9 @@ class LeadsController extends BaseController
foreach ($recipient_data as $recipient) {
$message = $original_message;
- $message = str_replace("{{RECIPIENT_NAME}}", $recipient['name'], $message);
- $message = str_replace("{{CLIENT_NAME}}", $lead_data['client_name'], $message);
- $message = str_replace("{{POLICY_LONG_NAME}}", $lead_data['long_name'], $message);
+ $message = str_replace("{{RECIPIENT_NAME}}", $recipient['name'] != "" ? $recipient['name'] : " ", $message);
+ $message = str_replace("{{CLIENT_NAME}}", $lead_data['client_name'] != "" ? $lead_data['client_name'] : "", $message);
+ $message = str_replace("{{POLICY_LONG_NAME}}", $lead_data['long_name'] != "" ? $lead_data['long_name'] : "", $message);
$message = str_replace("{{POLICY_START_DATE}}", change_date_format($lead_data['policy_start_date'], 'Y-m-d', 'd-m-Y'), $message);
$message = str_replace("{{DURATION}}", calculate_days_bw_dates($lead_data['policy_end_date'] ?? "", $lead_data['policy_start_date'] ?? "")->days, $message) ?? '--';
@@ -1792,14 +2433,17 @@ class LeadsController extends BaseController
$string = implode(", ", $cc_mails);
$bcc_string = implode(", ", $bcc_mails);
- $res = MailHelper::send_email(['mail' => $recipient['email'], 'cc' => $string, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to, 'bcc' => $bcc_string]);
+ $res = MailHelper::send_email(['from_mail' => $from_mail, 'mail' => $recipient['email'], 'cc' => $string, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to, 'bcc' => $bcc_string]);
// !dd($res);
$result_data[] = ['mail' => $recipient['email'], 'status' => $res];
}
}
+ $is_placement = false;
if ($recipient_type == 'placement') {
+ $is_placement = true;
+
list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2);
$lead_update_data = [
@@ -1811,19 +2455,59 @@ class LeadsController extends BaseController
$data = [
'proposel_data' => json_encode($lead_update_data),
'status' => 'won',
- 'placement_date' => change_date_format($params['placement_date'], 'd/m/Y', 'Y-m-d'),
- 'utr_no' => $params['utr_no'],
- 'premium_amount' => $params['premium_amount'],
- 'total_amount' => $params['total_amount'],
- 'cd_amount' => $params['cd_amount'],
+ 'placement_date' => !empty($params['placement_date']) ? change_date_format($params['placement_date']) : null,
+ 'payment_date' => !empty($params['payment_date']) ? change_date_format($params['payment_date']) : null,
+ 'utr_no' => $params['utr_no'] ?? null,
+ 'is_cd' => $params['is_cd'] ?? null,
+ 'premium_amount' => $params['premium_amount'] ?? null,
+ 'total_amount' => $params['total_amount'] ?? null,
+ 'cd_amount' => $params['cd_amount'] ?? null,
+ 'no_of_installment' => $params['no_of_installment'] ?? null,
+ 'is_installment' => $params['is_installment'] ?? null,
];
$this->leadsModel->where('id', $lead_id)->set($data)->update();
+
+ if (isset($params['installments']) && !empty($params['installments'])) {
+
+ $installment_data = json_decode($params['installments'], true);
+ if (!empty($installment_data)) {
+ foreach ($installment_data as $key => $value) {
+ // print_r($value);die
+ $value['payment_date'] = !empty($value['payment_date']) && strtotime($value['payment_date'])
+ ? date('Y/m/d', strtotime($value['payment_date']))
+ : null;
+ if (isset($value['id']) && !empty($value['id'])) {
+ $this->leadInstallmentPaymentDetails->where('id', $value['id'])->set($value)->update();
+ } else {
+ $this->leadInstallmentPaymentDetails->insert($value);
+ }
+ }
+ }
+ }
+ }
+
+ if ($recipient_type == 'client') {
+
+ $this->leadsModel
+ ->where('id', $lead_id)
+ ->whereNotIn('status', ['lost', 'co_insurer_pending', 'won', 'completed_with_corrections', 'completed_without_corrections'])
+ ->set(['status' => "qcr_sent"])
+ ->update();
+ }
+
+ if ($recipient_type == 'insurer') {
+
+ $this->leadsModel
+ ->where('id', $lead_id)
+ ->whereNotIn('status', ['qcr_created', 'qcr_sent', 'lost', 'co_insurer_pending', 'won', 'completed_with_corrections', 'completed_without_corrections'])
+ ->set(['status' => "rfq_sent"])
+ ->update();
}
//delete attachment file
unlink($file_path);
- return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result_data], 200);
+ return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result_data, 'is_placement' => $is_placement], 200);
}
public function getLevelContects()
@@ -1887,7 +2571,7 @@ class LeadsController extends BaseController
$headerData[] = [
'parentHeader' => $header['parentHeader'],
'subHeaders' => [
- 'Quote Asked', // Default value
+ // 'Quote Asked', // Default value
$subHeader // Matched insurer key
]
];
@@ -1923,15 +2607,16 @@ class LeadsController extends BaseController
];
}
- // Include Proposal with Quote Asked by default
- if ($item['parentth'] === $proposel && $item['subth'] === "Quote Asked") {
- $result['data'][] = [
- "parentth" => $item['parentth'],
- "subth" => $item['subth'],
- "value" => $item['value'],
- "input_value" => $item['input_value']
- ];
- }
+ // Include Proposal with Quote Asked by default
+ /* For proposel do not remove it */
+ // if ($item['parentth'] === $proposel && $item['subth'] === "Quote Asked") {
+ // $result['data'][] = [
+ // "parentth" => $item['parentth'],
+ // "subth" => $item['subth'],
+ // "value" => $item['value'],
+ // "input_value" => $item['input_value']
+ // ];
+ // }
// Example of including matching specific proposals and insurers
if ($item['parentth'] === $proposel && $item['subth'] === $insurer) {
@@ -1952,7 +2637,7 @@ class LeadsController extends BaseController
foreach ($data['premium_data']['data'] as $key => $value) {
if ($key === $proposel) {
- $premiumData[$key]['Quote Asked'] = $value['Quote Asked'];
+ // $premiumData[$key]['Quote Asked'] = $value['Quote Asked'];
$premiumData[$key][$insurer] = $value[$insurer];
}
}
@@ -1963,16 +2648,16 @@ class LeadsController extends BaseController
return $data;
}
-
+
public function convertJsonForQCR($json, $type)
{
if ($json) {
-
+
// Deep copy of JSON
$first_json = json_decode(json_encode($json), true);
// dd($first_json);
-
- if($type == 2){
+
+ if ($type == 2) {
// Column-wise Check: Remove headers and relevant data if qcr == 0
foreach ($json['proposal_data']['over_all_column_data'] as $proposalKey => $proposalData) {
@@ -1995,8 +2680,8 @@ class LeadsController extends BaseController
// Remove proposalKey from over_all_column_data
unset($first_json['proposal_data']['over_all_column_data'][$proposalKey]);
-
- if($type == 2){
+
+ if ($type == 2) {
// Remove proposalKey from premium_data
unset($first_json['premium_data']['data'][$proposalKey]);
}
@@ -2004,7 +2689,7 @@ class LeadsController extends BaseController
// Insurer Check: Remove subHeaders and relevant data for insurers with qcr == 0
foreach ($proposalData['insurers'] as $insurerIndex => $insurer) {
- if (($insurer['qcr'] === 0 || $insurer['qcr'] === false) || ($insurer['stc'] === 0 || $insurer['stc'] === false) ) {
+ if (($insurer['qcr'] === 0 || $insurer['qcr'] === false) || ($insurer['stc'] === 0 || $insurer['stc'] === false)) {
foreach ($first_json['table_data']['headers'] as &$header) {
if (isset($header['subHeaders'])) {
$header['subHeaders'] = array_values(array_filter($header['subHeaders'], function ($sub) use ($insurer) {
@@ -2023,7 +2708,7 @@ class LeadsController extends BaseController
// Remove insurer from proposal's insurers array
unset($first_json['proposal_data']['over_all_column_data'][$proposalKey]['insurers'][$insurerIndex]);
- if($type == 2){
+ if ($type == 2) {
unset($first_json['premium_data']['data'][$proposalKey][$insurer['display_name']]);
}
}
@@ -2047,8 +2732,7 @@ class LeadsController extends BaseController
$proposal['insurers'] = array_values($proposal['insurers']);
return $proposal;
}, $first_json['proposal_data']['over_all_column_data']);
-
- }else{
+ } else {
//remove insurer as Subheaders for RFQ
foreach ($first_json['table_data']['headers'] as &$header) {
@@ -2082,10 +2766,9 @@ class LeadsController extends BaseController
$proposal['insurers'] = [];
}
}
-
+
// Ensure to reset the reference
unset($proposal);
-
}
return $first_json;
@@ -2099,64 +2782,103 @@ class LeadsController extends BaseController
public function featchLeadDataAndInsertClient($lead_id)
{
- $data = $this->leadsModel->where('leads.id', $lead_id)->where('leads.is_active', 1)->first();
+ try {
+ $data = $this->leadsModel->where('leads.id', $lead_id)->where('leads.is_active', 1)->first();
- if (!$data) {
- return $this->respond(['status' => false, 'message' => 'Failed to create Client', 'data' => null], 200);
+ if (!$data) {
+ $this->myLogger->logme('featchLeadDataAndInsertClient', "Lead not found or inactive", ['lead_id' => $lead_id]);
+ return $this->respond(['status' => false, 'message' => 'Failed to create Client', 'data' => null], 200);
+ }
+
+ $result = $this->createClientWithLeadData($data);
+
+ if ($result) {
+ $policy_data = $this->clientPolicyModel->where('client_id', $result)->where('is_active', 1)->first();
+ return $this->respond([
+ 'status' => true,
+ 'message' => 'New Client created successfully',
+ 'client_id' => $result,
+ 'data' => $data,
+ 'client_policy_id' => $policy_data['id'] ?? null,
+ ], 200);
+ }
+
+ $this->myLogger->logme('featchLeadDataAndInsertClient', "Client creation failed after processing", ['lead_id' => $lead_id]);
+ return $this->respond(['status' => false, 'message' => 'Failed to create client', 'data' => $data], 200);
+ } catch (\Throwable $e) {
+ $this->myLogger->logme('error', 'featchLeadDataAndInsertClient failed');
+ return $this->respond(['status' => false, 'message' => 'Internal server error', 'error' => $e->getMessage()], 500);
}
-
- $result = $this->createClientWithLeadData($data);
-
- if ($result) {
-
- $policy_data = $this->clientPolicyModel->where('client_id', $result)->where('is_active', 1)->first();
- return $this->respond(['status' => true, 'message' => 'New Client created successfully', 'client_id' => $result, 'data' => $data, 'client_policy_id' => $policy_data['id']], 200);
- }
-
- return $this->respond(['status' => false, 'message' => 'Failed to create client', 'data' => $data], 200);
}
public function createClientWithLeadData($data)
{
- $client_data = $this->prepareClientData($data);
- $client_id = $this->clientModel->insert($client_data);
+ try {
+ $client_data = $this->prepareClientData($data);
+ $client_id = $this->clientModel->insert($client_data);
- if ($client_id) {
- $this->createClientBranchAndContactWithLeadData($data, $client_id);
- $this->leadsModel->where('id', $data['id'])->set('is_client_created', $client_id)->update();
+ if ($client_id) {
+ $this->createClientBranchAndContactWithLeadData($data, $client_id);
+ $this->leadsModel->where('id', $data['id'])->set('is_client_created', $client_id)->update();
+ }
+
+ return $client_id;
+ } catch (\Throwable $e) {
+ $this->myLogger->logme('error', 'createClientWithLeadData failed');
+ return false;
}
+ }
- return $client_id;
+ public function createClientBranchAndContactWithLeadData($data, $client_id)
+ {
+ try {
+ $branch_data = $this->prepareClientBranchData($data, $client_id);
+ $branch_id = $this->clientBranchModel->insert($branch_data);
+
+ if ($branch_id) {
+ $this->leadsModel->where('id', $data['id'])->set('is_client_created', $client_id)->update();
+ $contact_data = $this->prepareContactData($data, $branch_id);
+ $this->levelContactModel->insert($contact_data);
+ $this->createClientPolicyWithLeadData($data, $client_id, $branch_id);
+ }
+
+ return $branch_id;
+ } catch (\Throwable $e) {
+ $this->myLogger->logme('error', 'createClientBranchAndContactWithLeadData failed');
+ return false;
+ }
+ }
+
+ public function createClientPolicyWithLeadData($data, $client_id, $branch_id)
+ {
+ try {
+ $client_policy_data = $this->prepareClientPolicyData($data, $client_id, $branch_id);
+ $client_policy_id = $this->clientPolicyModel->insert($client_policy_data);
+
+ if ($client_policy_id) {
+ $this->leadsModel->where('id', $data['id'])->set('is_client_created', $client_id)->update();
+ $this->leadsModel->where('id', $data['id'])->set('is_policy_created', $client_policy_id)->update();
+ }
+
+ return $client_policy_id;
+ } catch (\Throwable $e) {
+ $this->myLogger->logme('error', 'createClientPolicyWithLeadData failed');
+ return false;
+ }
}
private function prepareClientData($data)
{
return [
- 'client_type' => $data['client_type'],
- 'entity_type_id' => $data['entity_type_id'],
- 'client_code' => $data['client_code'],
- 'client_name' => $data['client_name'],
- 'short_name' => $data['client_short_name'],
- 'pan' => $data['pan'],
+ 'client_type' => $data['client_type'] ?? null,
+ 'entity_type_id' => $data['entity_type_id'] ?? null,
+ 'client_code' => $data['client_code'] ?? null,
+ 'client_name' => $data['client_name'] ?? null,
+ 'short_name' => $data['client_short_name'] ?? null,
+ 'pan' => $data['pan'] ?? null,
];
}
- public function createClientBranchAndContactWithLeadData($data, $client_id)
- {
- $branch_data = $this->prepareClientBranchData($data, $client_id);
- $branch_id = $this->clientBranchModel->insert($branch_data);
-
- if ($branch_id) {
- $this->leadsModel->where('id', $data['id'])->set('is_client_created', $client_id)->update();
- $contact_data = $this->prepareContactData($data, $branch_id);
- $this->levelContactModel->insert($contact_data);
-
- $this->createClientPolicyWithLeadData($data, $client_id, $branch_id);
- }
-
- return $branch_id;
- }
-
private function prepareClientBranchData($data, $client_id)
{
$default_unit = trim(($data['client_short_name'] ?? '') . '-' . ($data['branch_code'] ?? ''), '-');
@@ -2181,19 +2903,6 @@ class LeadsController extends BaseController
];
}
- public function createClientPolicyWithLeadData($data, $client_id, $branch_id)
- {
- $client_policy_data = $this->prepareClientPolicyData($data, $client_id, $branch_id);
- $client_policy_id = $this->clientPolicyModel->insert($client_policy_data);
-
-
- if ($client_policy_id) {
- $this->leadsModel->where('id', $data['id'])->set('is_client_created', $client_id)->update();
- }
-
- return $client_policy_id;
- }
-
private function prepareClientPolicyData($data, $client_id, $branch_id)
{
$proposel_data = json_decode($data['proposel_data'], true);
@@ -2213,8 +2922,6 @@ class LeadsController extends BaseController
'policy_status' => 1,
];
- $terms = $this->preparePolicyTermsFromRFQ($data);
-
$policy_type_id = $data['policy_type_id'];
if (in_array($policy_type_id, [1, 2, 6, 7])) {
$client_policy_data['is_addon'] = 1; // Base Policy
@@ -2228,8 +2935,16 @@ class LeadsController extends BaseController
// }
}
- $client_policy_data['policy_terms'] = $this->preparePolicyTermsFromRFQ($data);
+ if ($data['lead_form_type'] == 1) {
+ $client_policy_data['policy_terms'] = $this->preparePolicyTermsFromRFQ($data);
+ } else {
+ $placementJson = $this->getPlacementJson($data);
+ if ($placementJson) {
+ $client_policy_data['placement_json'] = $placementJson;
+ $client_policy_data['policy_terms'] = $this->convertNonEbQCRJsonToPolicyTerms(json_decode($placementJson, true));
+ }
+ }
// print_r($client_policy_data); die;
return $client_policy_data;
@@ -2237,93 +2952,23 @@ class LeadsController extends BaseController
private function preparePolicyTermsFromRFQ($data)
{
- $proposel_data = json_decode($data['proposel_data'], true);
+ try {
+ $proposel_data = json_decode($data['proposel_data'], true);
+ $QCRData = $this->RFQModel->where('is_active', 1)->where('lead_id', $data['id'])->first();
- $QCRData = $this->RFQModel->where('is_active', 1)->where('type', 2)->where('lead_id', $data['id'])->first();
-
- $JSON = json_decode($QCRData['json'], true);
-
- $converted_json = $this->transformProposelData($JSON, $proposel_data['proposel_name'], $proposel_data['insurer_name']);
-
- return $this->convertQCRJsonToPolicyTerms($converted_json, $data['policy_type_id'], $proposel_data['proposel_name'], $proposel_data['insurer_name']);
- }
-
- //Function for convert the RFQ and QCR Json to Policy Terms Json
- public function convertQCRJsonToPolicyTerms($data, $policy_type, $proposel_name, $insurer_name)
- {
- //transform the data into the currernt proposel and insurere ( get single proposel )
- $data = $this->transformProposelData($data, $proposel_name, $insurer_name);
-
- // Initialize age_ratio based on policy type
- $age_ratio = $policy_type == 2 ? [
- 'self' => ['min' => '18', 'max' => '60'],
- 'spouse' => ['min' => 0, 'max' => 0],
- 'child' => ['min' => 0, 'max' => '25'],
- 'elders' => ['min' => 0, 'max' => 0],
- ] : [
- 'self' => ['min' => '18', 'max' => '60']
- ];
-
- foreach ($data['table_data']['data'] as $dataRow) {
- $item = $dataRow['items'] ?? '';
-
- foreach ($dataRow['data'] as $cellData) {
- $parentth = $cellData['parentth'] ?? '';
- $subth = $cellData['subth'] ?? '';
- $input_value = $cellData['input_value'] ?? '';
- $value = $cellData['value'] ?? '';
-
- // Skip unwanted keys
- if (in_array($parentth, ['Sno', 'Item Key', 'Particulars', 'Action']) || in_array($subth, ['Quote Asked'])) {
- continue;
- }
-
- switch (true) {
-
- // CASE 1: Handle special conditions
- case str_starts_with($item, 'special_condition') && $parentth === $proposel_name && $subth === $insurer_name:
- $parts = explode('-', $input_value);
- $labelKey = $policy_type == 1 ? 'gpa_special_condition_label' : 'special_condition_label';
- $inputKey = $policy_type == 1 ? 'gpa_special_condition_input' : 'special_condition_input';
-
- $terms_array[$labelKey][] = $parts[0] ?? '';
- $terms_array[$inputKey][] = $parts[1] ?? '';
- break;
-
- // CASE 2: Handle sum insured
- case in_array($item, ['sum_insured', 'sumInsured2']):
- $si_amt = explode(',', $value);
- $terms_array[$item] = $si_amt[0] ?? '';
- $terms_array['multiple_sum_insured'] = array_slice($si_amt, 1);
-
- // Add age_ratio after Sum insured
- if ($policy_type == 1) {
- $terms_array['age_ratio'] = $age_ratio;
- }
-
- break;
-
- // CASE 3: Handle family floaters
- case $item === 'family_composition':
- $terms_array['family_floaters'] = isJsonString($input_value) ? json_decode($input_value, true) : $input_value;
-
- // Add age_ratio after family floaters
- if ($policy_type == 2) {
- $terms_array['age_ratio'] = $age_ratio;
- }
-
- break;
-
- // DEFAULT CASE :
- default:
- // $terms_array[$item] = isJsonString($input_value) ? (json_decode($input_value, true)['key'] ?? '') : $value;
- $terms_array[$item] = $value;
- break;
- }
+ if (!$QCRData) {
+ throw new \Exception('RFQ Data not found');
}
- }
- return json_encode($terms_array);
+ $JSON = json_decode($QCRData['json'], true);
+ $converted_json = $this->transformProposelData($JSON, $proposel_data['proposel_name'], $proposel_data['insurer_name']);
+
+ // log_message('error', 'Converted JSON: ' . json_encode($converted_json));
+ return $this->convertQCRJsonToPolicyTerms($converted_json, $data['policy_type_id'], $proposel_data['proposel_name'], $proposel_data['insurer_name']);
+ } catch (\Throwable $e) {
+ $this->myLogger->logme('error', 'preparePolicyTermsFromRFQ');
+ return null;
+ }
}
public function featchClientPolicyFromLead($client_id, $branch_id, $lead_id)
@@ -2346,17 +2991,217 @@ class LeadsController extends BaseController
return $this->respond(['status' => false, 'message' => 'Failed to create policy', 'data' => $data], 200);
}
+ // ---------------------------------------------------------------------------------------------------------------
+
+ //Function for convert the RFQ and QCR Json to Policy Terms Json
+ public function convertQCRJsonToPolicyTerms($data, $policy_type, $proposel_name, $insurer_name)
+ {
+ //transform the data into the currernt proposel and insurere ( get single proposel )
+ $data = $this->transformProposelData($data, $proposel_name, $insurer_name);
+
+ // Initialize age_ratio based on policy type
+ $age_ratio = $policy_type == 2 ? [
+ 'self' => ['min' => '18', 'max' => '60'],
+ 'spouse' => ['min' => 0, 'max' => 0],
+ 'child' => ['min' => 0, 'max' => '25'],
+ 'elders' => ['min' => 0, 'max' => 0],
+ ] : [
+ 'self' => ['min' => '18', 'max' => '60']
+ ];
+
+ foreach ($data['table_data']['data'] as $dataRow) {
+ $item = $dataRow['items'] ?? '';
+
+ foreach ($dataRow['data'] as $cellData) {
+ $parentth = $cellData['parentth'] ?? '';
+ $subth = $cellData['subth'] ?? '';
+ $input_value = $cellData['input_value'] != "" ? $cellData['input_value'] : ($cellData['value'] ?? '');
+ $value = $cellData['value'] ?? '';
+
+ // Skip unwanted keys
+ if (in_array($parentth, ['Sno', 'Item Key', 'Particulars', 'Action']) || in_array($subth, ['Quote Asked'])) {
+ continue;
+ }
+
+ switch (true) {
+
+ // CASE 1: Handle special conditions
+ case str_starts_with($item, 'special_condition') && $parentth === $proposel_name && $subth === $insurer_name:
+ // log_message("error","INPUT".json_encode($input_value));
+ $parts = explode('-', $input_value);
+
+ $labelKey = $policy_type == 1 ? 'gpa_special_condition_label' : 'special_condition_label';
+ $inputKey = $policy_type == 1 ? 'gpa_special_condition_input' : 'special_condition_input';
+
+ $terms_array[$labelKey][] = $parts[0] ?? '';
+ $terms_array[$inputKey][] = $parts[1] ?? '';
+ break;
+
+ // CASE 2: Handle sum insured
+ case in_array($item, ['sum_insured', 'sumInsured2']):
+ $si_amt = explode(',', $value);
+ $terms_array[$item] = $si_amt[0] ?? '';
+ $terms_array['multiple_sum_insured'] = array_slice($si_amt, 1);
+
+ // Add age_ratio after Sum insured
+ if ($policy_type == 1) {
+ $terms_array['age_ratio'] = $age_ratio;
+ }
+
+ break;
+
+ // CASE 3: Handle family floaters
+ case $item === 'family_composition':
+ $terms_array['family_floaters'] = isJsonString($input_value) ? json_decode($input_value, true) : $input_value;
+
+ // Add age_ratio after family floaters
+ if ($policy_type == 2) {
+ $terms_array['age_ratio'] = $age_ratio;
+ }
+
+ break;
+
+ // DEFAULT CASE :
+ default:
+ // $terms_array[$item] = isJsonString($input_value) ? (json_decode($input_value, true)['key'] ?? '') : $value;
+ $terms_array[$item] = $value;
+ break;
+ }
+ }
+ }
+
+ return json_encode($terms_array);
+ }
+
+ public function convertNonEbQCRJsonToPolicyTerms($allTableData)
+ {
+
+ if (!empty($allTableData)) {
+
+ array_pop($allTableData); // Remove the last item from the array
+ $terms_array = [];
+
+ foreach ($allTableData as $TableIndex => $tableGroup) {
+
+ if ($TableIndex == 0) {
+ continue;
+ }
+
+ foreach ($tableGroup['table_data']['data'] as $dataRow) {
+ $item = $dataRow['items'] ?? '';
+
+ foreach ($dataRow['data'] as $cellData) {
+ $parentth = $cellData['parentth'] ?? '';
+ $subth = $cellData['subth'] ?? '';
+ $value = $cellData['display_content'] ?? '';
+
+ // Skip unwanted keys
+ if (in_array($parentth, ['SNO', 'Particulars', 'Action']) || $subth === 'Sum Insured' || $subth === 'Fidelity Limit') {
+ continue;
+ }
+
+ // Skip if item matches parentth
+ if ($item === $parentth) {
+ continue;
+ }
+
+ // Set the value directly, overwriting with latest encountered
+ if (!empty($item) && !empty($value)) {
+
+ $finalItem = $item;
+
+ if (strpos($tableGroup['tableId'], 'summary') !== false) {
+ $policy_type = explode('_', $tableGroup['tableId'])[0] ?? '';
+ $finalItem = $policy_type . ' - ' . $item;
+ }
+ $terms_array[$finalItem] = $value;
+ }
+ }
+ }
+ }
+
+ return json_encode($terms_array);
+ } else {
+ return null;
+ }
+ }
+
+ public function getPlacementJson(array $data): ?string
+ {
+ $proposel_data = json_decode($data['proposel_data'], true);
+
+ $QCRData = $this->RFQModel
+ ->where('is_active', 1)
+ ->where('lead_id', $data['id'])
+ ->first();
+
+ if (!$QCRData || empty($QCRData['json'])) {
+ return null;
+ }
+
+ $jsonArray = json_decode($QCRData['json'], true);
+ $proposalData = array_pop($jsonArray); // Get last item and remove it from the array
+
+ if (empty($jsonArray)) {
+ return null;
+ }
+
+ $placement_json_data = array_map(function ($jsonData) use ($proposel_data) {
+ return $this->transformNonEbProposelData(
+ $jsonData,
+ $proposel_data['proposel_name'] ?? '',
+ $proposel_data['insurer_name'] ?? '',
+ null,
+ 1
+ );
+ }, $jsonArray);
+
+ if (!empty($proposalData)) {
+ foreach ($proposalData['proposal_data']['over_all_column_data'] as $key => &$proposal) {
+ // Keep only the required proposal
+ if ($key !== $proposel_data['proposel_name']) {
+ unset($proposalData['proposal_data']['over_all_column_data'][$key]);
+ } else {
+ // Within the matched proposal, filter insurers
+ if (!empty($proposal['insurers'])) {
+ $proposal['insurers'] = array_values(array_filter($proposal['insurers'], function ($insurer) use ($proposel_data) {
+ return $insurer['display_name'] === $proposel_data['insurer_name'];
+ }));
+ }
+ }
+ }
+ unset($proposal); // Good practice after foreach by reference
+ }
+
+
+ $placement_json_data[] = $proposalData;
+
+ return json_encode($placement_json_data);
+ }
+
+
//------------------------------------------------------------------------------------------------
public function transformMailContent($lead_data, $mail_content, $page_name)
- {
- $current_year = date('Y');
+ {
+ $current_year = date('Y');
$next_year = $current_year + 1;
$policy_year = "$current_year-$next_year";
+ $page_name = $page_name == "QCR" ? "Quote Comparison Report" : $page_name;
+ $log_path = base_url() . '/public/assets/images/Nhance-Logo-Final.png';
+ // $log_path ='https://venbait.in/nhance/dev/public/assets/images/Nhance-Logo-Final.png';
+ // dd($log_path);
+
+ $policy_expiry = strtotime($lead_data['policy_end_date']);
+
+ $formatted_policy = date("d-m-Y", $policy_expiry);
+ $logged_user_id = get_session_userid();
+
+ $logged_user_data = $this->userModel->where("id", $logged_user_id)->where("is_active", 1)->first();
if ($lead_data) {
-
+
// Replacing placeholders with actual values
$message = $mail_content;
$message = str_replace("{{CLIENT_NAME}}", $lead_data['client_name'] ?? "Valued Client", $message);
@@ -2364,32 +3209,38 @@ class LeadsController extends BaseController
$message = str_replace("{{POLICY_TYPE}}", $lead_data['policy_type'] ?? "Insurance Policy", $message);
$message = str_replace("{{RFQ_OR_QCR}}", $page_name, $message);
$message = str_replace("{{POLICY_YEAR}}", $policy_year, $message);
+ $message = str_replace("{{POLICY_END_DATE}}", " (Due On " . $formatted_policy . ")", $message);
+
+ $message = str_replace("{{LOGGED_USER_NAME}}", ucfirst($logged_user_data['first_name']) . " " . ucfirst($logged_user_data['last_name']), $message);
+ $message = str_replace("{{LOGGED_USER_EMAIL}}", $logged_user_data['email'], $message);
+ $message = str_replace("{{LOGGED_USER_MOBILE}}", $logged_user_data['mobile'], $message);
+ $message = str_replace("{{LOGO_PATH}}", $log_path, $message);
return $message;
-
} else {
return ''; // Return empty if no lead data found
}
}
- function getLastFiveFinancialYears()
+
+ public function getLastFiveFinancialYears()
{
- $currentYear = date('Y');
+ $currentYear = date('Y');
$currentMonth = date('m');
-
+
// In India, the financial year starts from April (04)
if ($currentMonth < 4) {
$currentYear--; // Adjust year if it's Jan-Mar
}
-
+
$financialYears = [];
-
+
for ($i = 0; $i < 5; $i++) {
$startYear = $currentYear - $i - 1;
$endYear = $currentYear - $i;
$financialYears[] = "$startYear-$endYear";
}
-
+
return $financialYears;
}
@@ -2401,76 +3252,7 @@ class LeadsController extends BaseController
$this->loadLayout('view_rfq_non_eb');
}
- // public function getLeadNonEB($type, $id = null)
- // {
- // // Set basic data
- // $data['issuer'] = $this->issuer;
- // $data['client_type'] = $this->clientType;
- // $data['lead_type'] = $this->leadType;
- // $data['lead_status'] = $this->leadsStatus;
-
- // // Fetch policy types and entity data
- // $data['policy_type'] = $this->policyTypeModel->where('is_active', 1)->findAll();
- // $data['entity'] = $this->kycEntityTypeModel->where('is_active', 1)->findAll();
-
- // // Fetch insurer and TPA branch data
- // $data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
- // $data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
- // // print_r($data['tpa']);die();
- // // Fetch sales team members who are active in team 5
- // $data['salse_team'] = $this->userModel
- // ->select('user_profiles.*')
- // ->join('user_teams', 'user_profiles.id = user_teams.user_id')
- // ->where('user_teams.team_id', 5)
- // ->where('user_teams.is_active', 1)
- // ->where('user_profiles.is_active', 1)
- // ->findAll();
-
- // // dd($data);
- // $data['lastFiveYears'] = $this->getLastFiveFinancialYears();
- // $data['gpaClaimType'] = $this->claim_type_for_gpa;
- // $data['causeOfDeath'] = $this->cause_of_death;
- // $data['selected_lead_type'] = $type;
-
- // if(!empty($id)){
-
- // $data['lead_edit_data'] = $this->leadsModel->where('id', $id)->first();
-
- // if (!empty($data['lead_edit_data'])) {
- // $data['lead_edit_data']['policy_start_date'] = !empty($data['lead_edit_data']['policy_start_date'])
- // ? change_date_format($data['lead_edit_data']['policy_start_date'], 'Y-m-d', 'd/m/Y')
- // : null;
-
- // $data['lead_edit_data']['policy_end_date'] = !empty($data['lead_edit_data']['policy_end_date'])
- // ? change_date_format($data['lead_edit_data']['policy_end_date'], 'Y-m-d', 'd/m/Y')
- // : null;
-
- // $data['lead_edit_data']['incurred_claims_date'] = !empty($data['lead_edit_data']['incurred_claims_date'])
- // ? change_date_format($data['lead_edit_data']['incurred_claims_date'], 'Y-m-d', 'd/m/Y')
- // : null;
-
- // $data['lead_edit_data']['premium_date'] = !empty($data['lead_edit_data']['premium_date'])
- // ? change_date_format($data['lead_edit_data']['premium_date'], 'Y-m-d', 'd/m/Y')
- // : null;
- // } else {
- // $data['lead_edit_data'] = [];
- // }
-
- // if (!empty($data['lead_edit_data']['fin_years_claims'])) {
- // $decoded = json_decode($data['lead_edit_data']['fin_years_claims'], true);
- // $data['lead_edit_data']['fin_years_claims_array'] = isset($decoded['finyear']) ? $decoded['finyear'] : [];
- // } else {
- // $data['lead_edit_data']['fin_years_claims_array'] = [];
- // }
-
- // $data['lead_edit_data']['html'] = $this->generateViewPageHtml($data['lead_edit_data']['policy_type_id'], $data) ?? "";
- // }
-
- // // dd($data);
-
- // return $this->loadLayout('leads_form_handler', $data);
- // }
-
+ // get lead data for edit bot EB and NON-EB
public function getLeadNonEB($type, $id = null)
{
// Set basic data
@@ -2496,11 +3278,17 @@ class LeadsController extends BaseController
->where('user_teams.team_id', 5)
->where('user_teams.is_active', 1)
->where('user_profiles.is_active', 1)
- ->findAll();
+ ->findAll();
+
+
if (!empty($id)) {
+
$data['lead_edit_data'] = $this->leadsModel->where('id', $id)->first() ?? [];
+ $data['lead_edit_data']['multi_file_data'] = $this->leadFilesModel->where('lead_id', $id)->where('is_active', 1)->findAll() ?? null;
+ $data['lead_edit_data']['lead_file_count'] = count($data['lead_edit_data']['multi_file_data']);
+
// Decode and merge custom fields if present
$custom_fields_data = !empty($data['lead_edit_data']['custom_fields'])
? json_decode($data['lead_edit_data']['custom_fields'], true)
@@ -2511,7 +3299,7 @@ class LeadsController extends BaseController
}
if (!empty($data['lead_edit_data'])) {
- foreach (['policy_start_date', 'policy_end_date', 'incurred_claims_date', 'premium_date'] as $dateField) {
+ foreach (['policy_start_date', 'policy_end_date', 'source_policy_start_date', 'source_policy_end_date', 'incurred_claims_date'] as $dateField) {
$data['lead_edit_data'][$dateField] = !empty($data['lead_edit_data'][$dateField])
? change_date_format($data['lead_edit_data'][$dateField], 'Y-m-d', 'd/m/Y')
: null;
@@ -2522,55 +3310,71 @@ class LeadsController extends BaseController
: [];
$data['lead_edit_data']['html'] = $this->generateViewPageHtml(
- $data['lead_edit_data']['policy_type_id'] ?? null,
+ $data['lead_edit_data']['policy_type_id'] ?? null,
$data
) ?? "";
+ $html = view('rfq/multi_files', $data);
+ $data['lead_edit_data']['multi_file_html'] = trim($html) !== '' ? $html : null;
}
- if($data['lead_edit_data']['lead_type'] != 1 && $data['lead_edit_data']['lead_form_type'] == 2){
+ if ($data['lead_edit_data']['lead_type'] != 1 && $data['lead_edit_data']['lead_form_type'] == 2) {
$data['lead_edit_data']['claims_details_html'] = view('rfq/claims_details_non_eb', $data['lead_edit_data']);
- }else{
+ } else {
$data['lead_edit_data']['claims_details_html'] = "";
}
}
-
// dd($data);
return $this->loadLayout('leads_form_handler', $data);
}
public function getPolicyTypeFields()
- {
+ {
$policy_type_id = $this->request->getGET('policy_type_id');
$html = $this->generateViewPageHtml($policy_type_id) ?? "";
-
- if(!empty($html)){
+
+ if (!empty($html)) {
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Policy Type FIELDS are found', 'data' => $html], 200);
- }else{
+ } else {
return $this->respond(['status' => false, 'code' => 400, 'message' => 'Fields not found for this policy type'], 200);
}
-
}
public function generateViewPageHtml($policy_type_id, $data = [])
{
$data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
$data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
-
+
$viewMap = [
- 1 => 'rfq/gpa', 6 => 'rfq/gpa', 7 => 'rfq/gpa',
- 2 => 'rfq/gmc', 3 => 'rfq/gmc', 4 => 'rfq/gmc', 5 => 'rfq/gmc',
- 22 => 'rfq/car', 23 => 'rfq/cpm', 24 => 'rfq/cyber_crime',
- 25 => 'rfq/do', 27 => 'rfq/eo', 49 => 'rfq/money',
- 19 => 'rfq/cgl', 59 => 'rfq/sfsp', 63 => 'rfq/wc',
- 15 => 'rfq/blu', 16 => 'rfq/bsu',
- 44 => 'rfq/marine', 45 => 'rfq/marine', 46 => 'rfq/marine', 47 => 'rfq/marine',
+ 1 => 'rfq/gpa',
+ 6 => 'rfq/gpa',
+ 7 => 'rfq/gpa',
+ 2 => 'rfq/gmc',
+ 3 => 'rfq/gmc',
+ 4 => 'rfq/gmc',
+ 5 => 'rfq/gmc',
+ 17 => 'rfq/burglary',
+ 22 => 'rfq/car',
+ 23 => 'rfq/cpm',
+ 24 => 'rfq/cyber_crime',
+ 25 => 'rfq/do',
+ 27 => 'rfq/eo',
+ 49 => 'rfq/money',
+ 19 => 'rfq/cgl',
+ 59 => 'rfq/sfsp',
+ 63 => 'rfq/wc',
+ 15 => 'rfq/blu',
+ 16 => 'rfq/bsu',
+ 44 => 'rfq/marine',
+ 45 => 'rfq/marine',
+ 46 => 'rfq/marine',
+ 47 => 'rfq/marine',
50 => 'rfq/office'
];
-
+
return isset($viewMap[$policy_type_id]) ? view($viewMap[$policy_type_id], $data) : "";
}
@@ -2578,28 +3382,93 @@ class LeadsController extends BaseController
public function constructNonEbExcelToSaveTemp($lead_id, $type, $propsal_and_insurer = null)
{
-
$rfq_data = $this->RFQModel->getRFQTableDataWithLeadIDAndType($lead_id, $type);
-
+ $claim_history = $rfq_data['claim_history'];
+ // dd($claim_history);
$lead_data = json_decode($rfq_data['custom_fields'], true) ?? [];
+ $lead_data['claim_history'] = $claim_history;
+ // dd($lead_data);
if (!is_array($lead_data)) {
$lead_data = [];
}
+
+ if (isset($lead_data['pincode']) && isset($lead_data['address'])) {
+ // Reorder keys: address first, then pincode, then the rest
+ $reordered = ['address' => $lead_data['address'], 'pincode' => $lead_data['pincode']];
+
+ // Remove existing keys
+ unset($lead_data['address'], $lead_data['pincode']);
+
+ // Merge reordered with the rest
+ $lead_data = $reordered + $lead_data;
+ }
$lead_data = array_merge(['Insured' => $rfq_data['client_name']], $lead_data);
- // dd($lead_data);
+
+ $policy_registration_data = [];
+ if (isset($rfq_data['registration_json']) && !empty($rfq_data['registration_json'])) {
+ $policy_registration_data = json_decode($rfq_data['registration_json'], true);
+ }
+
$jsonData = json_decode($rfq_data['json'], true);
$proposalData = end($jsonData);
array_pop($jsonData);
+ $length = 0;
+ // dd($jsonData[0]['table_data']['headers']);
+ foreach ($jsonData as $key => $data) {
+ if ($type == 2) {
+
+ $data = $this->convertNonEbJsonForQCR($data, $type, $proposalData, $key);
+
+ // Kint::dump($data, 'Second');
+
+ if ($propsal_and_insurer !== null) {
+ list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2);
+ $data = $this->transformNonEbProposelData($data, $proposal_key, $insurer_key, $key);
+ }
+ unset($data['proposalData']);
+ } else if ($type == 1) {
+ $data = $this->convertNonEbJsonForQCR($data, $type, $proposalData, $key);
+ unset($data['proposalData']);
+ }
+ }
+ // dd($data);
+ foreach ($data['table_data']['headers'] as $header) {
+ if ($header['parentHeader'] != "Action") {
+ foreach ($header['subHeaders'] as $subHeader) {
+ // Kint::dump($header['parentHeader']);
+ // Kint::dump($subHeader);
+
+ $length++;
+ }
+ }
+ }
+ // dd($length);
+ $columnLetterForTitle = Coordinate::stringFromColumnIndex($length - 1);
+ $columnLetterForImage = Coordinate::stringFromColumnIndex($length);
+
+ // dd($columnLetter);
+ $sheetName = 'Worksheet';
+ if ($type == 2) {
+ $sheetName = 'QCR';
+ if ($propsal_and_insurer !== null) {
+ $sheetName = 'Placement';
+ }
+ } else if ($type == 1) {
+ $sheetName = 'RFQ';
+ }
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
+ $sheet->setTitle($sheetName);
+
+
// Start with lead_data at the top
$rowNumber = 1;
$title = "Nhance India Insurance Broking Pvt Ltd";
- $mergeRange1 = "A{$rowNumber}:B{$rowNumber}";
+ $mergeRange1 = "A{$rowNumber}:{$columnLetterForTitle}{$rowNumber}";
$sheet->mergeCells($mergeRange1);
$sheet->setCellValue("A{$rowNumber}", $title);
$sheet->getStyle("A{$rowNumber}")->applyFromArray([
@@ -2616,40 +3485,57 @@ class LeadsController extends BaseController
// Calculate title width
$maxWidthA = mb_strlen($title);
+ // dd($columnLetterForImage);
// Set column width to fit the image properly
- $sheet->getColumnDimension('C')->setWidth(20); // Adjust as needed
+ $sheet->getColumnDimension($columnLetterForImage)->setWidth(40); // Adjust as needed
$sheet->getRowDimension($rowNumber)->setRowHeight(40); // Adjust as needed
+
$drawing = new Drawing();
$path = ROOTPATH . "public/assets/images/Nhance-Logo-Final.png"; // Use FCPATH for server path
$drawing->setPath($path);
- $drawing->setCoordinates("C{$rowNumber}"); // Set position in column C
+ $drawing->setCoordinates("{$columnLetterForImage}{$rowNumber}"); // Set position in column C
$drawing->setHeight(35); // Adjust image height
- // Center align the image in the cell
- $drawing->setOffsetX(30); // Adjust horizontal offset
- $drawing->setOffsetY(5); // Adjust vertical offset
- $drawing->setWorksheet($sheet);
+
// Apply center alignment to the cell
- $sheet->getStyle("C{$rowNumber}")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
- $sheet->getStyle("C{$rowNumber}")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
+ $sheet->getStyle("{$columnLetterForImage}{$rowNumber}")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
+ $sheet->getStyle("{$columnLetterForImage}{$rowNumber}")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
$rowNumber++;
// Initialize max width tracking variables
$maxWidthB = 0;
+ //Lead Data
foreach ($lead_data as $key => $value) {
+
+ // if ($key == 'risk_location') {
+ // $key == 'risk_details';
+ // }
+ // Kint::dump($key);
+ // Kint::dump($value);
$formattedKey = ucwords(str_replace('_', ' ', $key));
+ $formattedKey = $formattedKey == "Risk Location" ? "Risk Details" : $formattedKey;
+ $formattedKey = $formattedKey == "Address" ? "Communication Address" : $formattedKey;
+ $formattedValue = ucwords(str_replace("_", " ", $value));
+
+ if ($key == "claim_history") {
+
+ $formattedValue = $value == "1" ? "Yes" : "No";
+ $formattedKey = "Claim Experience";
+
+ }
+ // Kint::dump($formattedValue);
// Merge A:B for key
- $mergeRangeKey = "A{$rowNumber}:B{$rowNumber}";
+ $mergeRangeKey = "A{$rowNumber}:{$columnLetterForTitle}{$rowNumber}";
$sheet->mergeCells($mergeRangeKey);
// Set values in merged cells
$sheet->setCellValue("A{$rowNumber}", $formattedKey);
- $sheet->setCellValue("C{$rowNumber}", $value);
+ $sheet->setCellValue("{$columnLetterForImage}{$rowNumber}", $formattedValue);
// Apply styles for alignment and bold text in A:B
$sheet->getStyle($mergeRangeKey)->applyFromArray([
@@ -2670,32 +3556,197 @@ class LeadsController extends BaseController
// Track max width needed for columns
$maxWidthA = max($maxWidthA, mb_strlen($formattedKey)); // Consider title and keys
$maxWidthB = max($maxWidthB, mb_strlen((string) $value));
+ // if (!empty($policy_registration_data)) {
+ // dd($policy_registration_data);
+
+ // }
$rowNumber++;
}
+ // die();
+
// Set column width based on max content length (adjusted for padding)
$sheet->getColumnDimension('A')->setWidth($maxWidthA * 1.2);
- $sheet->getColumnDimension('B')->setWidth($maxWidthA * 1.2);
- $sheet->getColumnDimension('C')->setWidth($maxWidthB * 1.2);
+ // $sheet->getColumnDimension('B')->setWidth($maxWidthA * 1.2);
+ // $sheet->getColumnDimension('C')->setWidth($maxWidthB * 1.2);
- $rowNumber += 2;
+ // $rowNumber += 1;
+ //Policy Registration
+ if (!empty($policy_registration_data)) {
+ foreach ($policy_registration_data as $key => $value) {
+ // kint::dump($value);
+ $startRow = $rowNumber; // Track where the block starts
+ // Title Row
+ $titleMergeRangeKey = "A{$rowNumber}:{$columnLetterForImage}{$rowNumber}";
+ $sheet->mergeCells($titleMergeRangeKey);
+ $sheet->setCellValue("A{$rowNumber}", ucfirst($key) . " Policy Details");
+
+ // Title Style
+ $sheet->getStyle($titleMergeRangeKey)->applyFromArray([
+ 'font' => ['bold' => true],
+ 'alignment' => [
+ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ ],
+ 'fill' => [
+ 'fillType' => Fill::FILL_SOLID,
+ 'startColor' => ['rgb' => 'ADD8E6'],
+ ],
+ ]);
+
+ $rowNumber++; // Move to next row
+
+ // Policy Type
+ if (isset($value['policyType'])) {
+ $sheet->mergeCells("A{$rowNumber}:{$columnLetterForTitle}{$rowNumber}");
+ $sheet->setCellValue("A{$rowNumber}", "Policy Type");
+ $sheet->setCellValue("{$columnLetterForImage}{$rowNumber}", $value['policyType']);
+
+ $sheet->getStyle("A{$rowNumber}:C{$rowNumber}")->applyFromArray([
+ 'font' => ['bold' => true],
+ 'alignment' => [
+ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ ],
+ ]);
+
+ $rowNumber++;
+ } else {
+ $sheet->mergeCells("A{$rowNumber}:{$columnLetterForTitle}{$rowNumber}");
+ $sheet->setCellValue("A{$rowNumber}", "Policy Type");
+ $sheet->setCellValue("{$columnLetterForImage}{$rowNumber}", ucfirst($key) . " Policy");
+
+ $sheet->getStyle("A{$rowNumber}:C{$rowNumber}")->applyFromArray([
+ 'font' => ['bold' => true],
+ 'alignment' => [
+ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ ],
+ ]);
+
+ $rowNumber++;
+ }
+
+ // Type of Business & Nature of Business
+ if (isset($value['productSelection']) && !empty($value['productSelection'])) {
+ // Type of Business
+ $sheet->mergeCells("A{$rowNumber}:{$columnLetterForTitle}{$rowNumber}");
+ $sheet->setCellValue("A{$rowNumber}", "Type of Business");
+ $sheet->setCellValue("{$columnLetterForImage}{$rowNumber}", $this->buisnessType[$value['productSelection']['type_of_buisness']] ?? '');
+
+ $sheet->getStyle("A{$rowNumber}")->applyFromArray([
+ 'font' => ['bold' => true],
+ 'alignment' => [
+ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ ],
+ ]);
+
+ $rowNumber++;
+
+ // Nature of Business
+ $sheet->mergeCells("A{$rowNumber}:{$columnLetterForTitle}{$rowNumber}");
+ $sheet->setCellValue("A{$rowNumber}", "Nature of Business");
+ $sheet->setCellValue("{$columnLetterForImage}{$rowNumber}", $value['productSelection']['buisness_nature'] ?? '');
+
+ $sheet->getStyle("A{$rowNumber}")->applyFromArray([
+ 'font' => ['bold' => true],
+ 'alignment' => [
+ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ ],
+ ]);
+
+ $rowNumber++;
+ }
+
+ if (isset($value['policyDetails']) && !empty($value['policyDetails'])) {
+ // Type of Business
+ $sheet->mergeCells("A{$rowNumber}:{$columnLetterForTitle}{$rowNumber}");
+ $sheet->setCellValue("A{$rowNumber}", "Terrorism");
+ $sheet->setCellValue("{$columnLetterForImage}{$rowNumber}", ucfirst($value['policyDetails']['terrorism'] ?? 'No'));
+
+ $sheet->getStyle("A{$rowNumber}")->applyFromArray([
+ 'font' => ['bold' => true],
+ 'alignment' => [
+ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ ],
+ ]);
+
+ $rowNumber++;
+ }
+ if (!empty($value['locations'])) {
+
+ foreach ($value['locations'] as $index => $location) {
+ // Merge title cell
+ $sheet->mergeCells("A{$rowNumber}:{$columnLetterForTitle}{$rowNumber}");
+ $sheet->setCellValue("A{$rowNumber}", "Risk " . ($location['select_location'] ?? 'Unknown'));
+
+ // Clean and safe address string
+ $address1 = ucfirst($location['policyRisk']['address1'] ?? '');
+ $address2 = ucfirst($location['policyRisk']['address2'] ?? '');
+ $pinCode = $location['policyRisk']['pin_code'] ?? 'No';
+
+ $fullAddress = "{$address1}, {$address2}, {$pinCode}";
+ $sheet->setCellValue("{$columnLetterForImage}{$rowNumber}", $fullAddress);
+
+ // Style the title cell
+ $sheet->getStyle("A{$rowNumber}")->applyFromArray([
+ 'font' => ['bold' => true],
+ 'alignment' => [
+ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ ],
+ ]);
+
+ $rowNumber++;
+ }
+ }
+
+
+ $endRow = $rowNumber; // Block ends at previous row
+
+ // Apply border to the whole block
+ $sheet->getStyle("A{$startRow}:{$columnLetterForImage}{$endRow}")->applyFromArray([
+ 'borders' => [
+ 'allBorders' => [
+ 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
+ 'color' => ['argb' => '000000'],
+ ],
+ ],
+ ]);
+
+ // $rowNumber += 1; // Add space before the next block
+ }
+ $rowNumber--;
+ // die();
+ }
+
+ //Table Data
foreach ($jsonData as $key => $data) {
+ // Kint::dump($data, 'First');
+
if ($type == 2) {
- $data = $this->convertNonEbJsonForQCR($data, $type, $proposalData);
- unset($data['proposalData']);
+
+ $data = $this->convertNonEbJsonForQCR($data, $type, $proposalData, $key);
+
+ // Kint::dump($data, 'Second');
if ($propsal_and_insurer !== null) {
list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2);
- $data = $this->transformProposelData($data, $proposal_key, $insurer_key);
+ $data = $this->transformNonEbProposelData($data, $proposal_key, $insurer_key, $key);
}
+ unset($data['proposalData']);
} else if ($type == 1) {
- $data = $this->convertNonEbJsonForQCR($data, $type, $proposalData);
+ $data = $this->convertNonEbJsonForQCR($data, $type, $proposalData, $key);
unset($data['proposalData']);
}
+ // dd($data);
// Add headers and subheaders
$headers = $data['table_data']['headers'];
// dd($headers);
@@ -2712,9 +3763,10 @@ class LeadsController extends BaseController
}
$sheet->getColumnDimension($columnLetter)->setWidth(60);
+ $sheet->getColumnDimension('C')->setWidth(35);
- if ($header['parentHeader'] == '') {
+ if ($header['parentHeader'] == 'Policy') {
// $header['parentHeader'] = 'S.No.';
$sheet->getColumnDimension('A')->setWidth(10);
}
@@ -2728,10 +3780,10 @@ class LeadsController extends BaseController
$sheet->getColumnDimension('D')->setWidth(35);
}
-
+
$startColumn = $columnLetter; // Start of the current header range
$subHeaderCount = count($header['subHeaders']); // Number of subheaders for this parent header
-
+ // Kint::dump($subHeaderCount);
// Set parent header value
$sheet->setCellValue("{$startColumn}{$rowNumber}", $header['parentHeader']);
$sheet->getStyle("{$startColumn}{$rowNumber}")->applyFromArray([
@@ -2748,12 +3800,13 @@ class LeadsController extends BaseController
// Merge header cells if it spans multiple subheaders
if ($subHeaderCount > 1) {
- $endColumn = chr(ord($startColumn) + $subHeaderCount - 1); // Calculate the end column
+ $endColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($startColumn) + $subHeaderCount - 1);
$sheet->mergeCells("{$startColumn}{$rowNumber}:{$endColumn}{$rowNumber}");
} else {
$endColumn = $startColumn; // No merge needed if only one subheader
}
+ // Kint::dump($header);
// Add subheaders
foreach ($header['subHeaders'] as $subHeader) {
$sheet->setCellValue("{$columnLetter}{$subHeaderRow}", $subHeader);
@@ -2775,8 +3828,20 @@ class LeadsController extends BaseController
}
}
+ // For the subheader row, merge B and C and set the value
+ $sheet->setCellValue("B{$subHeaderRow}", "Sum Insured");
+ $sheet->mergeCells("B{$subHeaderRow}:C{$subHeaderRow}");
+ $sheet->getStyle("B{$subHeaderRow}:C{$subHeaderRow}")->applyFromArray([
+ 'font' => ['bold' => true],
+ 'alignment' => [
+ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ ],
+ ]);
+
// Apply border to the header range
- $headerRange = "A{$rowNumber}:" . chr(ord($columnLetter) - 1) . "{$subHeaderRow}";
+ $prevColumn4 = $this->getPreviousColumn($columnLetter);
+ $headerRange = "A{$rowNumber}:" . "{$prevColumn4}" . "{$subHeaderRow}";
$sheet->getStyle($headerRange)->applyFromArray([
'borders' => [
'allBorders' => [
@@ -2790,15 +3855,21 @@ class LeadsController extends BaseController
$sheet->getRowDimension($rowNumber)->setRowHeight(25); // Header row height
$sheet->getRowDimension($subHeaderRow)->setRowHeight(20); // Subheader row height
- $rowNumber = $subHeaderRow + 2;
+ // $rowNumber = $subHeaderRow + 2;
+ $rowNumber = $subHeaderRow + 1;
+
$column_data = $data['table_data']['data'];
+ // dd($column_data);
$serial_no = 1;
$maxColumnWidths = [];
+ $RowSpanEnable = false;
// Add table data rows
foreach ($column_data as $dataRow) {
$columnLetter = 'A';
+ $hasPolicy = in_array('Policy', array_column($dataRow['data'], 'parentth'));
+ // Kint::dump($hasPolicy);
foreach ($dataRow['data'] as $cellData) {
@@ -2808,7 +3879,7 @@ class LeadsController extends BaseController
if ($cellData['parentth'] == 'SNO') {
$sheet->setCellValue("{$columnLetter}{$rowNumber}", $serial_no);
- } else if ($cellData['parentth'] == '') {
+ } else if ($cellData['parentth'] == 'Policy') {
$mergeStart = $rowNumber; // Start row for merging
$mergeEnd = $rowNumber + ($cellData['rowspan'] - 1); // End row for merging
@@ -2817,16 +3888,30 @@ class LeadsController extends BaseController
$sheet->getStyle("{$columnLetter}{$mergeStart}:{$columnLetter}{$mergeEnd}")
->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
} else {
- $sheet->setCellValue("{$columnLetter}{$rowNumber}", $cellData['display_value']);
+ if (!$hasPolicy && $key == 0) {
+ $RowSpanEnable = true;
+ $columnLetter++;
+ $sheet->setCellValue("{$columnLetter}{$rowNumber}", $cellData['display_content']);
+ } else {
+ $sheet->setCellValue("{$columnLetter}{$rowNumber}", $cellData['display_content']);
+ }
}
- $columnLetter++;
+ if (!($key === 0 && !$hasPolicy)) {
+ $columnLetter++;
+ }
}
$rowNumber++;
$serial_no++;
}
- $dataRange = "A" . ($subHeaderRow + 1) . ":" . chr(ord($columnLetter) - 1) . ($rowNumber - 1);
+ if ($key == 0 && $RowSpanEnable == true) {
+ $columnLetter++;
+ }
+
+ // dd($columnLetter);
+ $prevColumn5 = $this->getPreviousColumn($columnLetter);
+ $dataRange = "A" . ($subHeaderRow + 1) . ":" . "{$prevColumn5}" . ($rowNumber - 1);
$sheet->getStyle($dataRange)->applyFromArray([
'borders' => [
'allBorders' => [
@@ -2873,7 +3958,7 @@ class LeadsController extends BaseController
}
$lastRow = count($lead_data) + 1;
- $leadRange = "A1:C{$lastRow}";
+ $leadRange = "A1:{$columnLetterForImage}{$lastRow}";
$sheet->getStyle($leadRange)->applyFromArray([
'borders' => [
@@ -2885,6 +3970,93 @@ class LeadsController extends BaseController
]);
}
+ $columnWidth = $sheet->getColumnDimension("C")->getWidth(); // e.g., 20
+ $cellPixelWidth = $columnWidth * 7; // Approximate conversion (1 unit ≈ 7 pixels)
+ $imagePixelWidth = 250; // Approximate width of your image (in pixels)
+
+ $offsetX = max(0, ($cellPixelWidth - $imagePixelWidth) / 2);
+ $offsetX = $offsetX + 97;
+ if ($length >= 4) {
+ $offsetX = 50;
+ } else if ($length == 3) {
+ $offsetX = 140;
+ }
+
+ // dd($offsetX, $cellPixelWidth, $imagePixelWidth);
+ $drawing->setOffsetX($offsetX); // Dynamically center
+ $drawing->setOffsetY(10); // Dynamically center
+
+ $drawing->setWorksheet($sheet);
+
+ $sheet->getStyle('C1')->getAlignment()
+ ->setHorizontal(Alignment::HORIZONTAL_CENTER)
+ ->setVertical(Alignment::VERTICAL_CENTER);
+
+ if (!empty($rfq_data['fin_years_claims']) && $claim_history == 1) {
+
+ $claim_details = json_decode($rfq_data['fin_years_claims'], true) ?? [];
+
+ if (!empty($claim_details['finyear'])) {
+
+ // Get headers dynamically
+ $headers = array_map(function ($key) {
+ return ucwords(str_replace('_', ' ', $key));
+ }, array_keys($claim_details['finyear'][0]));
+
+ $newSheet = new Worksheet($spreadsheet, 'Claims Experience');
+ $spreadsheet->addSheet($newSheet);
+ $spreadsheet->setActiveSheetIndexByName('Claims Experience');
+ $sheet = $spreadsheet->getActiveSheet();
+
+ // Set headers
+ $sheet->fromArray($headers, NULL, 'A1');
+
+ // Apply background color and bold style to headers
+ $headerCellRange = 'A1:' . chr(64 + count($headers)) . '1'; // e.g., A1:G1
+
+ $sheet->getStyle($headerCellRange)->getFont()->setBold(true);
+ $sheet->getStyle($headerCellRange)->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('ADD8E6');
+
+ // Add border to header
+ $sheet->getStyle($headerCellRange)->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN);
+
+ // Fill data and apply borders
+ $row = 2;
+ foreach ($claim_details['finyear'] as $record) {
+ $col = 'A';
+ foreach ($record as $value) {
+ $sheet->setCellValue($col . $row, $value);
+ $col++;
+ }
+
+ // Apply border to each data row
+ $sheet->getStyle('A' . $row . ':' . chr(64 + count($headers)) . $row)
+ ->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN);
+
+ $row++;
+ }
+ // Auto-size all columns based on header count
+ for ($i = 0; $i < count($headers); $i++) {
+ $colLetter = chr(65 + $i); // 'A', 'B', etc.
+ $sheet->getColumnDimension($colLetter)->setAutoSize(true);
+ }
+
+ // Enable wrap text for all cells
+ $maxColLetter = chr(64 + count($headers)); // Last column letter
+ $sheet->getStyle("A2:{$maxColLetter}{$row}")->getAlignment()->setWrapText(true);
+
+ // Optional: center vertically for neatness
+ $sheet->getStyle("A2:{$maxColLetter}{$row}")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
+
+ // Optional: Make row height auto (helps when wrap text is on)
+ for ($i = 2; $i < $row; $i++) {
+ $sheet->getRowDimension($i)->setRowHeight(-1);
+ }
+
+ }
+ }
+
+ // dd($rowNumber);
// Set filename
$string = ($type == 2) ? 'QCR' : 'RFQ';
$filename = "{$string}_{$rfq_data['client_short_name']}_{$rfq_data['policy_type']}_" . date('YmdHis') . '.xlsx';
@@ -2900,241 +4072,446 @@ class LeadsController extends BaseController
];
}
- public function convertNonEbJsonForQCR($jsonArr, $type, $proposeldata)
+ public function convertNonEbJsonForQCR($jsonArr, $type, $proposeldata, $indexOfTheTable)
{
-
- $first_json = $jsonArr;
- $first_json = array_merge($first_json, $proposeldata);
-
- if($type == 2){
- // Column-wise Check: Remove headers and relevant data if qcr == 0
- foreach ($first_json['proposal_data']['over_all_column_data'] as $proposalKey => $proposalData) {
+ $first_json = $jsonArr;
+ $first_json = array_merge($first_json, $proposeldata);
- if (($proposalData['qcr'] == 0 || $proposalData['qcr'] === false) || ($proposalData['stc'] == 0 || $proposalData['stc'] === false)) {
+ if ($type == 2) {
- // Remove matching parentHeader in headers
- foreach ($first_json['table_data']['headers'] as $index => $header) {
- if ($header['parentHeader'] === $proposalKey) {
- unset($first_json['table_data']['headers'][$index]);
+ // Column-wise Check: Remove headers and relevant data if qcr == 0
+ foreach ($first_json['proposal_data']['over_all_column_data'] as $proposalKey => $proposalData) {
+
+ if ((isset($proposalData['qcr']) && isset($proposalData['stc'])) && ($proposalData['qcr'] == 0 || $proposalData['qcr'] === false) || ($proposalData['stc'] == 0 || $proposalData['stc'] === false)) {
+
+ // Remove matching parentHeader in headers
+ foreach ($first_json['table_data']['headers'] as $index => $header) {
+ if ($header['parentHeader'] === $proposalKey) {
+ unset($first_json['table_data']['headers'][$index]);
+ }
+ }
+
+ // Remove data entries with matching parentth
+ foreach ($first_json['table_data']['data'] as &$item) {
+ $item['data'] = array_values(array_filter($item['data'], function ($entry) use ($proposalKey) {
+ return $entry['parentth'] !== $proposalKey;
+ }));
+ }
+
+ // Remove proposalKey from over_all_column_data
+ unset($first_json['proposal_data']['over_all_column_data'][$proposalKey]);
+
+ if ($type == 2) {
+ // Remove proposalKey from premium_data
+ unset($first_json['premium_data']['data'][$proposalKey]);
+ }
+ }
+
+ // Insurer Check: Remove subHeaders and relevant data for insurers with qcr == 0
+ foreach ($proposalData['insurers'] as $insurerIndex => $insurer) {
+
+ $qcr = $insurer['qcr'] ?? null;
+ $stc = $insurer['stc'] ?? null;
+
+ if (($qcr === 0 || $qcr === false) || ($stc === 0 || $stc === false)) {
+
+ foreach ($first_json['table_data']['headers'] as &$header) {
+ if (isset($header['subHeaders'])) {
+ $header['subHeaders'] = array_values(array_filter($header['subHeaders'], function ($sub) use ($insurer) {
+ return $sub !== $insurer['display_name'];
+ }));
}
}
- // Remove data entries with matching parentth
+
foreach ($first_json['table_data']['data'] as &$item) {
- $item['data'] = array_values(array_filter($item['data'], function ($entry) use ($proposalKey) {
- return $entry['parentth'] !== $proposalKey;
+ $item['data'] = array_values(array_filter($item['data'], function ($entry) use ($insurer) {
+ return $entry['subth'] !== $insurer['display_name'];
}));
}
- // Remove proposalKey from over_all_column_data
- unset($first_json['proposal_data']['over_all_column_data'][$proposalKey]);
-
- if($type == 2){
- // Remove proposalKey from premium_data
- unset($first_json['premium_data']['data'][$proposalKey]);
- }
- }
+ // Remove insurer from proposal's insurers array
+ unset($first_json['proposal_data']['over_all_column_data'][$proposalKey]['insurers'][$insurerIndex]);
- // Insurer Check: Remove subHeaders and relevant data for insurers with qcr == 0
- foreach ($proposalData['insurers'] as $insurerIndex => $insurer) {
- if (($insurer['qcr'] === 0 || $insurer['qcr'] === false) || ($insurer['stc'] === 0 || $insurer['stc'] === false) ) {
- foreach ($first_json['table_data']['headers'] as &$header) {
- if (isset($header['subHeaders'])) {
- $header['subHeaders'] = array_values(array_filter($header['subHeaders'], function ($sub) use ($insurer) {
- return $sub !== $insurer['display_name'];
- }));
- }
- }
-
-
- foreach ($first_json['table_data']['data'] as &$item) {
- $item['data'] = array_values(array_filter($item['data'], function ($entry) use ($insurer) {
- return $entry['subth'] !== $insurer['display_name'];
- }));
- }
-
- // Remove insurer from proposal's insurers array
- unset($first_json['proposal_data']['over_all_column_data'][$proposalKey]['insurers'][$insurerIndex]);
-
- if($type == 2){
- unset($first_json['premium_data']['data'][$proposalKey][$insurer['display_name']]);
- }
+ if ($type == 2) {
+ unset($first_json['premium_data']['data'][$proposalKey][$insurer['display_name']]);
}
}
}
-
- // Row-wise Check: Remove rows if qcr == 0 for actions
- foreach ($first_json['table_data']['data'] as $rowKey => $rowData) {
- foreach ($rowData['data'] as $data) {
- if (
- isset($data['parentth']) && $data['parentth'] === "Action" &&
- (
- (isset($data['input_value']['qcr']) && $data['input_value']['qcr'] == 0) ||
- (isset($data['input_value']['stc']) && $data['input_value']['stc'] == 0)
- )
- ) {
-
- unset($first_json['table_data']['data'][$rowKey]);
- break; // Stop checking other columns for this row
- }
- }
- }
-
- // Reindex arrays to maintain proper structure
- $first_json['table_data']['headers'] = array_values($first_json['table_data']['headers']);
- $first_json['table_data']['data'] = array_values($first_json['table_data']['data']);
- $first_json['proposal_data']['over_all_column_data'] = array_map(function ($proposal) {
- $proposal['insurers'] = array_values($proposal['insurers']);
- return $proposal;
- }, $first_json['proposal_data']['over_all_column_data']);
-
- }else{
-
- //remove insurer as Subheaders for RFQ
- foreach ($first_json['table_data']['headers'] as &$header) {
- // Ensure 'subHeaders' exists and is an array before filtering
- if (isset($header['subHeaders']) && is_array($header['subHeaders'])) {
- $header['subHeaders'] = array_filter($header['subHeaders'], function ($subHeader) {
- return in_array($subHeader, ['Quote asked', '-'], true);
- });
- }
- }
-
- //Remove insurer Row wise data for RFQ
- foreach ($first_json['table_data']['data'] as &$row) {
-
- // Filter the inner data array
- $row['data'] = array_filter(
- $row['data'],
- function ($item) {
- return in_array($item['subth'], ['Quote asked', '-']);
- }
- );
-
- $row['data'] = array_values($row['data']);
- }
-
- // Ensure to unset the reference after the loop
- unset($row);
-
- // Remove insurers from Proposal Data key for RFQ
- foreach ($proposeldata['proposal_data']['over_all_column_data'] as $key => &$proposal) {
- if (isset($proposal['insurers'])) {
- // Set the insurers array to empty
- $proposal['insurers'] = [];
- }
- }
-
- // Ensure to reset the reference
- unset($proposal);
-
}
- return $first_json;
+ // Row-wise Check: Remove rows if qcr == 0 for actions
+ $groupedRows = [];
+ foreach ($first_json['table_data']['data'] as $rowKey => $rowData) {
+
+ $groupedRows[$rowData['row_id']][] = $rowData;
+
+ foreach ($rowData['data'] as $keyIndex => $data) {
+
+ if ($indexOfTheTable == 0) {
+
+ if ($data['parentth'] == "Policy" && $data['input_value'] != "Checked") {
+ unset($first_json['table_data']['data'][$rowKey]);
+ break;
+ }
+ } else {
+ if (
+ isset($data['parentth'], $data['input_value']['qcr'], $data['input_value']['stc']) &&
+ $data['parentth'] === "Action" &&
+ ($data['input_value']['qcr'] == 0 || $data['input_value']['stc'] == 0)
+ ) {
+ unset($first_json['table_data']['data'][$rowKey]);
+ break;
+ }
+ }
+ }
+ }
+
+ $finalRows = [];
+
+ if (!empty($groupedRows)) {
+
+ // Loop through each row_id group and check for Policy status
+ foreach ($groupedRows as $rowId => $rows) {
+ $hasPolicy = false;
+ $isChecked = false;
+
+ foreach ($rows as $row) {
+ foreach ($row['data'] as $cell) {
+ if ($cell['parentth'] === 'Policy') {
+ $hasPolicy = true;
+ if (trim(strtolower($cell['input_value'])) === 'checked') {
+ $isChecked = true;
+ }
+ break 2; // Found Policy, no need to continue further
+ }
+ }
+ }
+
+ // Step 3: If parent Policy is "Checked", retain the entire group
+ if (!$hasPolicy || $isChecked) {
+ foreach ($rows as $r) {
+ $finalRows[] = $r;
+ }
+ }
+ }
+
+ if (!empty($finalRows)) {
+ // Update the original data
+ $first_json['table_data']['data'] = array_values($finalRows);
+ }
+ }
+
+
+ // Reindex arrays to maintain proper structure
+ $first_json['table_data']['headers'] = array_values($first_json['table_data']['headers']);
+ $first_json['table_data']['data'] = array_values($first_json['table_data']['data']);
+ $first_json['proposal_data']['over_all_column_data'] = array_map(function ($proposal) {
+ $proposal['insurers'] = array_values($proposal['insurers']);
+ return $proposal;
+ }, $first_json['proposal_data']['over_all_column_data']);
+ } else {
+
+ //remove insurer as Subheaders for RFQ
+ foreach ($first_json['table_data']['headers'] as &$header) {
+ // Ensure 'subHeaders' exists and is an array before filtering
+ if (isset($header['subHeaders']) && is_array($header['subHeaders'])) {
+ $header['subHeaders'] = array_filter($header['subHeaders'], function ($subHeader) {
+ return in_array($subHeader, ['Sum Insured', '-'], true);
+ });
+ }
+ }
+ // Kint::dump($header);
+ //Remove insurer Row wise data for RFQ
+ $groupedRows = [];
+ foreach ($first_json['table_data']['data'] as &$row) {
+
+ // Filter the inner data array
+ $row['data'] = array_filter(
+ $row['data'],
+ function ($item) {
+ return in_array($item['subth'], ['Sum Insured', '-', "Liability Limit"]);
+ }
+ );
+
+ $row['data'] = array_values($row['data']);
+
+ $groupedRows[$row['row_id']][] = $row;
+ }
+ // Ensure to unset the reference after the loop
+ unset($row);
+
+
+ $finalRows = [];
+
+ if (!empty($groupedRows)) {
+
+ // Loop through each row_id group and check for Policy status
+ foreach ($groupedRows as $rowId => $rows) {
+ $hasPolicy = false;
+ $isChecked = false;
+
+ foreach ($rows as $row) {
+ foreach ($row['data'] as $cell) {
+ if ($cell['parentth'] === 'Policy') {
+ $hasPolicy = true;
+ if (trim(strtolower($cell['input_value'])) === 'checked') {
+ $isChecked = true;
+ }
+ break 2; // Found Policy, no need to continue further
+ }
+ }
+ }
+
+ // Step 3: If parent Policy is "Checked", retain the entire group
+ if (!$hasPolicy || $isChecked) {
+ foreach ($rows as $r) {
+ $finalRows[] = $r;
+ }
+ }
+ }
+
+ if (!empty($finalRows)) {
+ // Update the original data
+ $first_json['table_data']['data'] = array_values($finalRows);
+ }
+ }
+
+ // Remove insurers from Proposal Data key for RFQ
+ foreach ($proposeldata['proposal_data']['over_all_column_data'] as $key => &$proposal) {
+ if (isset($proposal['insurers'])) {
+ // Set the insurers array to empty
+ $proposal['insurers'] = [];
+ }
+ }
+
+ // Ensure to reset the reference
+ unset($proposal);
+ }
+
+ return $first_json;
return null;
}
- public function transformNonEbProposelData($data, $proposel, $insurer)
+ public function transformNonEbProposelData(&$data, $proposal, $insurer, $tableCount = null, $actionColumn = null)
{
+ // Kint::dump($data, $proposal, $insurer, $tableCount);
- // print_r($data['premium_data']['data']); die;
-
+ // Initialize headers with defaults
$headerData = [];
- // Default headers: S. No and Particulars
- $defaultHeaders = [
- [
- 'parentHeader' => 'Sno',
- 'subHeaders' => ['-']
- ],
- [
- 'parentHeader' => 'Particulars',
- 'subHeaders' => ['-']
- ]
+ // Add the first two default headers only once
+ $headerData[] = [
+ 'parentHeader' => $data['table_data']['headers'][0]['parentHeader'],
+ 'subHeaders' => ['-']
+ ];
+ $headerData[] = [
+ 'parentHeader' => $data['table_data']['headers'][1]['parentHeader'],
+ 'subHeaders' => ['-']
];
- // Add default headers to the result
- $headerData = array_merge($headerData, $defaultHeaders);
+ $second_table_name = $data['table_data']['headers'][1]['parentHeader'] ?? "";
+ // Loop through the headers to find matching proposal and insurer
foreach ($data['table_data']['headers'] as $header) {
- // Check if the parentHeader matches the target proposal
- if ($header['parentHeader'] === $proposel) {
- // Check if subHeaders contain the target insurer key
+ if ($header['parentHeader'] === $proposal) {
foreach ($header['subHeaders'] as $subHeader) {
if ($subHeader === $insurer) {
$headerData[] = [
'parentHeader' => $header['parentHeader'],
- 'subHeaders' => [
- 'Quote asked', // Default value
- $subHeader // Matched insurer key
- ]
+ 'subHeaders' => ['Sum Insured', $subHeader]
];
- break;
+ break 2; // Exit both loops after match is found
}
}
}
}
- $columnData = [];
+ // Update the original data's headers
+ $data['table_data']['headers'] = $headerData;
- foreach ($data['table_data']['data'] as $entry) {
+ if (!empty($actionColumn)) {
+ $data['table_data']['headers'][] = [
+ 'parentHeader' => "Action",
+ 'subHeaders' => ['-']
+ ];
+ }
+
+ foreach ($data['table_data']['data'] as &$entry) {
$sno = $entry['SNO'];
$items = $entry['items'];
$row_id = $entry['row_id'];
- $dataEntry = $entry['data'];
- $result = [
- "SNO" => $sno,
- "items" => $items,
- "items" => $row_id,
- "data" => []
- ];
+ $filteredData = [];
- foreach ($dataEntry as $item) {
+ foreach ($entry['data'] as $item) {
- // Include Sno and Particulars by default
- if (in_array($item['parentth'], ['Sno', 'Particulars'])) {
- $result['data'][] = [
- "parentth" => $item['parentth'],
- "subth" => $item['subth'],
- "value" => $item['value'],
- "input_value" => $item['input_value'],
- "display_value" => $item['display_value'],
- "rowspan" => $item['rowspan'],
- ];
+ // Always include SNO and Particulars
+ if (in_array($item['parentth'], ['S.NO', "Policy", "", 'Particulars', $second_table_name])) {
+ $filteredData[] = $item;
}
- // Include Proposal with Quote Asked by default
- if ($item['parentth'] === $proposel && $item['subth'] === "Quote asked") {
- $result['data'][] = [
- "parentth" => $item['parentth'],
- "subth" => $item['subth'],
- "value" => $item['value'],
- "input_value" => $item['input_value'],
- "display_value" => $item['display_value'],
- "rowspan" => $item['rowspan'],
- ];
+ // Include Proposal with Sum Insured
+ if ($item['parentth'] === $proposal && ($item['subth'] === "Sum Insured" || $item['subth'] === "Liability Limit")) {
+ $filteredData[] = $item;
}
- // Example of including matching specific proposals and insurers
- if ($item['parentth'] === $proposel && $item['subth'] === $insurer) {
- $result['data'][] = [
- "parentth" => $item['parentth'],
- "subth" => $item['subth'],
- "value" => $item['value'],
- "input_value" => $item['input_value'],
- "display_value" => $item['display_value'],
- "rowspan" => $item['rowspan'],
- ];
+ // Include specific proposal and insurer
+ if ($item['parentth'] === $proposal && $item['subth'] === $insurer) {
+ $filteredData[] = $item;
+ }
+
+ if (!empty($actionColumn)) {
+ if ($item['parentth'] === "Action") {
+ $filteredData[] = $item;
+ }
}
}
- // Add to the final result
- $columnData[] = $result;
+ // Update the entry with filtered data
+ $entry['SNO'] = $sno;
+ $entry['items'] = $items;
+ $entry['row_id'] = $row_id;
+ $entry['data'] = $filteredData;
}
+ unset($entry);
+ // kint::dump($data);
return $data;
}
+
+ public function getPreviousColumn($columnLetter, $decrement = 1)
+ {
+ $colIndex = Coordinate::columnIndexFromString($columnLetter);
+ $colIndex = max(1, $colIndex - $decrement); // ensure column index doesn't go below 1
+ return Coordinate::stringFromColumnIndex($colIndex);
+ }
+
+ public function handleMultiFileAttachments($json_string, $lead_id)
+ {
+ log_message('error', 'handleMultiFileAttachments called with lead_id: ' . $lead_id);
+
+ $attachments = [];
+
+ if (!empty($json_string)) {
+ log_message('error', 'json_string is not empty');
+
+ $fileIds = json_decode($json_string, true);
+ log_message('error', 'Decoded fileIds: ' . print_r($fileIds, true));
+
+ $lead_file_path = WRITEPATH . 'uploads/lead_files/';
+ log_message('error', 'Lead file path: ' . $lead_file_path);
+
+ foreach ($fileIds as $id) {
+ log_message('error', 'Processing file ID: ' . $id);
+
+ $lead_file = $this->leadFilesModel
+ ->where('lead_id', $lead_id)
+ ->where('id', $id)
+ ->where('is_active', 1)
+ ->first();
+
+ if ($lead_file) {
+ log_message('error', 'Found lead file: ' . print_r($lead_file, true));
+
+ $fullPath = $lead_file_path . $lead_file['file_name'];
+ log_message('error', 'Full file path: ' . $fullPath);
+
+ if (file_exists($fullPath)) {
+ log_message('error', 'File exists at path: ' . $fullPath);
+
+ if (!empty($lead_file['file_name'])) {
+ log_message('error', 'File name is not empty: ' . $lead_file['file_name']);
+
+ $attachments[] = [
+ 'fileName' => $lead_file['file_name'],
+ 'filePath' => $fullPath
+ ];
+ } else {
+ log_message('warning', 'File name is empty for ID: ' . $id);
+ }
+ } else {
+ log_message('warning', 'File does not exist at path: ' . $fullPath);
+ }
+ } else {
+ log_message('warning', 'No active lead file found for ID: ' . $id . ' and lead_id: ' . $lead_id);
+ }
+ }
+ } else {
+ log_message('error', 'json_string is empty');
+ }
+
+ log_message('error', 'Attachments prepared: ' . print_r($attachments, true));
+ return $attachments;
+ }
+
+
+ public function handleMemberDataGPATotalSumInsurerFromExcel($params)
+ {
+ $lead_id = $params['lead_id'];
+ $lead_data = $this->leadsModel->find($lead_id);
+ // dd($lead_data);
+ $file_name_with_path = WRITEPATH . "/uploads/lead_files/" . $lead_data['file_name'];
+ // dd($file_name_with_path);
+
+ if (!$lead_data) {
+ return ['status' => 'failed', 'message' => 'Lead data not found'];
+ }
+
+ if ($lead_data['file_name']) {
+
+ //check physical file
+ if (!file_exists($file_name_with_path)) {
+
+ $message = "Lead Physcial file not found";
+ $this->myLogger->logme('error', ($message . ' for file ' . $file_name_with_path));
+ return ['status' => 'failed', 'message' => 'no physical file'];
+ }
+
+ $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
+
+ //get members data
+ $members_sheet = $spreadsheet->getSheet(0);
+ $highestRowAndColumn = $members_sheet->getHighestRowAndColumn();
+ // dd($highestRowAndColumn);
+
+ $uncleaned_members = $members_sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
+ // dd($uncleaned_members);
+
+ $members = ExcelSanitizeHelper::sanitizeArrayData($uncleaned_members);
+ // dd($members);
+
+
+ // Check column headings
+ $members_heading = $members[0];
+ $available_col = [];
+
+ $lower_headers = array_map('strtolower', $members_heading);
+ foreach ($lower_headers as $index => $header) {
+ if (preg_match('/^sa\s*-\s*option\s*\d*$/i', $header)) {
+ $column_name = $members_heading[$index];
+ $sum = 0;
+
+ for ($i = 1; $i < count($members); $i++) {
+ $cell_raw = $members[$i][$index] ?? '';
+ $cell_clean = preg_replace('/[^0-9.\-]/', '', $cell_raw); // remove non-numeric chars
+
+ if ($cell_clean !== '' && is_numeric($cell_clean)) {
+ $sum += (float) $cell_clean;
+ }
+ }
+
+ $available_col[] = $sum;
+ }
+ }
+
+
+ // dd($available_col);
+ return $available_col;
+ }
+
+ return [];
+ }
}
diff --git a/app/Controllers/LoginController.php b/app/Controllers/LoginController.php
index f5f31844..bf7f116c 100755
--- a/app/Controllers/LoginController.php
+++ b/app/Controllers/LoginController.php
@@ -94,7 +94,7 @@ class LoginController extends BaseController
// setcookie('session_data', '', time() - 3600, $path);
$path = getenv('cookie.Path');
$domain = getenv('cookie.Domain');
- $https = getenv('ccokie.secure');
+ $https = getenv('cookie.secure');
setcookie('session_data',null, time() -3600, $path, $domain, $https, true);
return redirect()->to(base_url('login'));
}
diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php
index 4e1271f8..0a3c357d 100755
--- a/app/Controllers/MasterController.php
+++ b/app/Controllers/MasterController.php
@@ -1422,11 +1422,12 @@ class MasterController extends AdminController
if ($insert) {
//for CD Tranction Table
+ $cd_tranction_data['cd_ac_pk'] = $this->CDMasterModel->insertID();
$response = DepositHelper::saveDeposit($cd_tranction_data, $loggedInUserID);
$cd_data = $this->CDMasterModel->where('client_id', $data['client_id'])->where('insurer_id', $data['insurer_id'])->findAll();
- return $this->respond(['status' => true, 'data' => $cd_data, 'cd_ac_no'=>$data['cd_ac_no'], 'message' => 'CD Account number created successfully'], 200);
+ return $this->respond(['status' => true, 'data' => $cd_data, 'cd_ac_no'=>$data['cd_ac_no'], 'message' => 'CD Account number created successfully', "FOR BDS PURPOSE"], 200);
}else{
return $this->respond(['status' => false, 'message' => 'Failed to created CD Account number'], 200);
}
@@ -1679,7 +1680,7 @@ class MasterController extends AdminController
["filePath" => ROOTPATH."public/sample_excel/sample_inception.xls","fileName" => "sample_inception.xls"],
["filePath" => ROOTPATH."public/assets/images/login_bg.jpg","fileName" => "login_bg.jpg"]
];
- $email_id = 'srinivas.saravanan@venbainfotech.com';
+ $email_id = ['srinivas.saravanan@venbainfotech.com','srinivassaravanan2002@gmail.com'];
$params = ['mail'=>$email_id];
$common = ['mail_type'=>'test_mail_cli'];
// $bcc = "vijayalakshmi@nhanceindia.in,vitvelz@gmail.com,velmurugan.s@venbainfotech.com,hariharan@nhanceindia.in,hariharan@jubiliant.in,srinivas.saravanan@venbainfotech.com";
@@ -1828,4 +1829,22 @@ class MasterController extends AdminController
echo "################################################################\n\n";
}
+ public function sendMutipleToEmails()
+ {
+
+ $message = 'Dear {{RECIPIENT_NAME}}, We are reaching out to request a quotation for the following insurance coverage. Please review the details below and provide your quote at your earliest convenience.
RFQ Details Client name {{CLIENT_NAME}} Coverage Type {{POLICY_LONG_NAME}} Policy Start Date {{POLICY_START_DATE}} Policy Duration {{DURATION}}
Please note: Additional terms and details are included in the attachment for your reference.
Please feel free to reach out if you require any further information to prepare the quote. We look forward to receiving your proposal.
Best regards,
Nhance India Pvt Ltd
';
+ $attachments = [
+ ["filePath" => ROOTPATH."public/sample_excel/sample_addition.xls","fileName" => "sample_addition.xls"],
+ ["filePath" => ROOTPATH."public/sample_excel/sample_inception.xls","fileName" => "sample_inception.xls"],
+ ["filePath" => ROOTPATH."public/assets/images/login_bg.jpg","fileName" => "login_bg.jpg"]
+ ];
+ $email_id = 'venkateshraman786@gmail.com';
+ $params = ['mail'=>$email_id];
+ $multi_mails = ['venkateshraman786@gmail.com', 'gowtham.manavalan.la@gmail.com', 'venkatesh.r@venbainfotech.com'];
+ $common = ['mail_type'=>'test_mail_cli'];
+ $bcc = "vitvelz@gmail.com,velmurugan.s@venbainfotech.com,srinivas.saravanan@venbainfotech.com";
+ $result = MailHelper::send_email(['mail' => $multi_mails, 'bcc'=>$bcc, 'params'=>$params,'subject' => 'Send Multiple " To " emails','message' => $message,'attachments' => $attachments,'common'=>$common]);
+ dd($result);
+ }
+
}
\ No newline at end of file
diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php
index 4a2a59d6..6622d0fa 100644
--- a/app/Controllers/PolicyTransactionController.php
+++ b/app/Controllers/PolicyTransactionController.php
@@ -32,10 +32,13 @@ use App\Models\InvPaymentDetailsModel;
use App\Models\BatchFileModel;
use App\Models\FileModel;
use App\Models\COShareStmtDetailsModel;
-use Kint;
+use App\Models\BdsPlacementModel;
+use Kint\Kint;
+use App\Helpers\MailHelper;
+use Exception;
class PolicyTransactionController extends BaseController
-{
+{
use ResponseTrait;
protected $myLogger;
@@ -64,7 +67,8 @@ class PolicyTransactionController extends BaseController
protected $batchFileModel;
protected $filesModel;
protected $coShareStmtDetailsModel;
-
+ protected $BdsPlacementModel;
+
public function __construct()
{
set_session_context('Policy Tranction');
@@ -94,6 +98,7 @@ class PolicyTransactionController extends BaseController
$this->batchFileModel = new BatchFileModel();
$this->filesModel = new FileModel();
$this->coShareStmtDetailsModel = new COShareStmtDetailsModel();
+ $this->BdsPlacementModel = new BdsPlacementModel();
$this->invoiceStatus = [
'pending' => 'Pending',
'generated' => 'Generated',
@@ -106,7 +111,7 @@ class PolicyTransactionController extends BaseController
public function viewInception()
{
$data['page_name'] = 'Policy';
-
+
// Static arrays for dropdowns
$data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
$data['client_type'] = [1 => 'Group', 2 => 'Individual'];
@@ -148,7 +153,7 @@ class PolicyTransactionController extends BaseController
'policy_start_date' => 'Policy Start Date',
'policy_end_date' => 'Policy End Date',
];
-
+
// Filter data
$start_date = $this->request->getGet('start_date');
$end_date = $this->request->getGet('end_date');
@@ -158,7 +163,7 @@ class PolicyTransactionController extends BaseController
$date_type = $this->request->getGet('date_type');
$issuer = $this->request->getGet('issuer');
$status = $this->request->getGet('status');
-
+
// Handle null or empty values
$start_date = empty($start_date) ? 0 : $start_date;
$end_date = empty($end_date) ? 0 : $end_date;
@@ -168,19 +173,39 @@ class PolicyTransactionController extends BaseController
$date_type = empty($date_type) ? 0 : $date_type;
$issuer = empty($issuer) ? 0 : $issuer;
$status = empty($status) ? 0 : $status; // Corrected from `$issuer`
-
- // Fetch inception data list
- $data['inception_data_list'] = $this->policyTransactionModel->getInceptionTranctionListData(
- $start_date,
- $end_date,
- $client_id,
- $insurer_id,
- $policy_type_id,
- $date_type,
- $issuer,
- $status
- );
-
+
+ if ($this->request->is('get')) {
+
+ // Fetch inception data list
+ $data['inception_data_list'] = $this->policyTransactionModel->getInceptionTranctionListData(
+ $start_date,
+ $end_date,
+ $client_id,
+ $insurer_id,
+ $policy_type_id,
+ $date_type,
+ $issuer,
+ $status
+ );
+ } else {
+
+ $ids = $this->request->getPost('ids');
+ $ids = array_filter(explode(',', $ids));
+ $data['inception_data_list'] = $this->policyTransactionModel->getInceptionTranctionListData(
+ $start_date = 0,
+ $end_date = 0,
+ $client_id = 0,
+ $insurer_id = 0,
+ $policy_type_id = 0,
+ $date_type = 0,
+ $issuer = 0,
+ $status = 0,
+ $ids
+ );
+ }
+
+
+
// Fetch additional data
$data['client'] = $this->clientModel->where('is_active', 1)->findAll();
$data['client_branch'] = $this->clientBranchModel->where('is_active', 1)->findAll();
@@ -190,7 +215,7 @@ class PolicyTransactionController extends BaseController
$data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll();
$data['insurer_branch'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
$data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
-
+
// Fetch PP Teams Data
$data['ppTeamsData'] = $this->userModel
->where('is_active', 1)
@@ -204,22 +229,21 @@ class PolicyTransactionController extends BaseController
->where('user_teams.is_active', 1)
->where('user_profiles.is_active', 1)
->findAll();
-
+
// Fetch ACM
$data['ACM'] = $this->userModel
->where('role', 3) // Assuming `role` is in `user_profiles`
->where('is_active', 1)
->findAll();
-
- // echo '';
+ // echo '';
// print_r($data['ppTeamsData']); die;
-
+
// dd($data);
-
+
// Load view
$this->loadLayout('policy_transaction_inception_list', $data);
}
-
+
// policy Transaction Create function start
public function createInceptionPolicy()
{
@@ -229,56 +253,56 @@ class PolicyTransactionController extends BaseController
$data['cd_ac_pk'] = $this->request->getPost('cd_ac_no');
// print_r($this->request->getPost()); die;
-
+
if (!$id) {
return $this->insertInceptionPolicy($data);
} else {
return $this->updateInceptionPolicy($id, $data);
}
}
-
+
private function preparePolicyData()
{
$data = $this->request->getPost();
-
+
// print_r($data); die;
// var_dump($data); die;
- if(empty($data['policy_issue_date'])){
+ if (empty($data['policy_issue_date'])) {
$data['policy_issue_date'] = null;
}
- if(empty($data['policy_start_date'])){
- $data['policy_start_date'] = null;
+ if (empty($data['policy_start_date'])) {
+ $data['policy_start_date'] = null;
}
- if(empty($data['policy_end_date'])){
- $data['policy_end_date'] = null;
+ if (empty($data['policy_end_date'])) {
+ $data['policy_end_date'] = null;
}
- if(empty($data['renewal_date'])){
- $data['renewal_date'] = null;
+ if (empty($data['renewal_date'])) {
+ $data['renewal_date'] = null;
}
- if(empty($data['rollover_date'])){
- $data['rollover_date'] = null;
+ if (empty($data['rollover_date'])) {
+ $data['rollover_date'] = null;
}
- if(empty($data['last_action_date'])){
+ if (empty($data['last_action_date'])) {
$data['last_action_date'] = null;
- }else{
+ } else {
$data['last_action_date'] = change_date_format($data['last_action_date']);
}
// Separate Insurer and TPA Branch IDs and IDs
- if(isset($data['insurer_id']) && !empty($data['insurer_id'])){
+ if (isset($data['insurer_id']) && !empty($data['insurer_id'])) {
list($data['insurer_branch_id'], $data['insurer_id']) = explode('-', $data['insurer_id']);
if (isset($data['tpa']) && !empty($data['tpa'])) {
list($data['tpa_branch_id'], $data['tpa_id']) = explode('-', $data['tpa']);
}
}
-
+
$data['tsi'] = generate_tsi_code($data['issue_type']);
$data['action_type'] = 'inception';
@@ -287,13 +311,13 @@ class PolicyTransactionController extends BaseController
} elseif ($data['co_share']) {
$data['co_share'] = 1;
}
-
+
if (!isset($data['bro_payable_by'])) {
$data['bro_payable_by'] = 0;
} elseif ($data['bro_payable_by']) {
$data['bro_payable_by'] = 1;
}
-
+
if (!isset($data['same_as_proposer'])) {
$data['same_as_proposer'] = 0;
} elseif ($data['same_as_proposer']) {
@@ -306,127 +330,143 @@ class PolicyTransactionController extends BaseController
$data['policy_with_corr'] = 1;
}
- if($data['ct_type'] == ""){
+ if (!isset($data['is_cd_reduce_from_bds'])) {
+ $data['is_cd_reduce_from_bds'] = 0;
+ } elseif ($data['is_cd_reduce_from_bds']) {
+ $data['is_cd_reduce_from_bds'] = 1;
+ }
+
+ if ($data['ct_type'] == "") {
$data['ct_type'] = 1;
}
// $month = '01-'.(string)$this->request->getPost('month');
// $data['month'] = empty($data['month']) ? null : date('Y-m-d', strtotime($month));
-
+
// Determine $is_addon value
- $data['is_addon'] = in_array($data['policy_type_id'], [1, 2, 6, 7]) ? 1 :
- (in_array($data['policy_type_id'], [4, 5]) ? 2 : ($data['policy_type_id'] == 3 && isset($data['base_policy']) ? 3 : 1));
-
+ $data['is_addon'] = in_array($data['policy_type_id'], [1, 2, 6, 7]) ? 1 : (in_array($data['policy_type_id'], [4, 5]) ? 2 : ($data['policy_type_id'] == 3 && isset($data['base_policy']) ? 3 : 1));
+
// print_r($data); die;
return $data;
}
-
+
private function insertInceptionPolicy($data)
- {
+ {
// print_r($data); die;
$insert = $this->policyTransactionModel->insert($data);
+
if ($insert) {
+
$this->insertTransactionStatus($insert, $data, 1);
$emp_data = $this->processInsertIndividualMemberInEmpTable($data);
- if(isset($data['follow_insurer_id']) && !empty($data['follow_insurer_id'][0])){
+ if (isset($data['follow_insurer_id']) && !empty($data['follow_insurer_id'][0])) {
$pt_co_share_details = $this->insertOrUpdateCoShareDetails($data, $insert);
if ($data['ct_type'] == 2) {
-
$client_policy_insert_data = $this->prepareClientPolicyInsertData($data);
$client_policy_id = $this->clientPolicyModel->insert($client_policy_insert_data);
$this->policyTransactionModel->update($insert, ['client_policy_id' => $client_policy_id]);
$emp_policy_insert = $this->InsertIndividualEmpPolicyTable($emp_data, $client_policy_id);
-
- if ($data['client_type'] == 1 && $data['status'] == 'completed') {
- $this->processCompletedStatus($data, $client_policy_id, $data['insurer_id']);
- }
}
-
- $data['pt_co_share_details'] = $this->PTCOShareDetailsModel->where('pt_id', $insert)->where('is_active', 1)->findAll();
+ if ($data['client_type'] == 1 && $data['status'] == 'completed' && $data['is_cd_reduce_from_bds'] == 1) {
+ $this->processCompletedStatus($data, $client_policy_id, $data['insurer_id']);
+ }
}
-
+
$client_data = $this->clientModel->where('id', $data['client_id'])->first();
$data['client_kyc'] = $this->clientKYCDocsModel->where('client_id', $data['client_id'])->findAll();
$data['entity_type_id'] = $client_data['entity_type_id'];
return $this->respondSuccess($insert, "Policy transaction created successfully", $data);
}
+
return $this->respondError("Failed to create policy transaction");
}
-
+
private function updateInceptionPolicy($id, $data)
- {
+ {
+ // print_r($data); die;
if ($this->policyTransactionModel->update($id, $data)) {
-
+
$this->insertTransactionStatus($id, $data, 1);
$emp_data = $this->processInsertIndividualMemberInEmpTable($data);
-
+
if (isset($data['follow_insurer_id']) && !empty($data['follow_insurer_id'][0])) {
-
+
$this->insertOrUpdateCoShareDetails($data, $id);
if ($data['ct_type'] == 1) {
- $this->policyTransactionModel->update($id, ['client_policy_id' => $data['client_policy_id']]);
+ $this->policyTransactionModel->update($id, ['client_policy_id' => $data['client_policy_id']]);
}
-
+
if (empty($data['client_policy_id']) || $data['client_policy_id'] == 0) {
-
+
if ($data['ct_type'] == 2) {
$client_policy_insert_data = $this->prepareClientPolicyInsertData($data);
$client_policy_id = $this->clientPolicyModel->insert($client_policy_insert_data);
- $this->policyTransactionModel->update($id, ['client_policy_id' => $client_policy_id]);
+ $this->policyTransactionModel->update($id, ['client_policy_id' => $client_policy_id]);
$this->InsertIndividualEmpPolicyTable($emp_data, $client_policy_id);
}
-
} else {
if (isset($data['emp_policy_id']) && !empty($data['emp_policy_id'][0])) {
$this->InsertIndividualEmpPolicyTable($emp_data, $data['client_policy_id']);
}
}
-
+
if ($data['status'] == 'completed' && $data['ct_type'] == 2) {
- if($data['client_type'] == 1){
+ if ($data['client_type'] == 1 && $data['is_cd_reduce_from_bds'] == 1) {
$this->processCompletedStatus($data, $data['client_policy_id'], $data['insurer_id']);
}
}
-
+
$data['pt_co_share_details'] = $this->PTCOShareDetailsModel->where('pt_id', $id)->where('is_active', 1)->findAll();
}
-
+
$client_data = $this->clientModel->where('id', $data['client_id'])->first();
$data['client_kyc'] = $this->clientKYCDocsModel->where('client_id', $data['client_id'])->findAll();
$data['entity_type_id'] = $client_data['entity_type_id'];
return $this->respondSuccess($id, "Policy transaction updated successfully", $data);
}
-
+
return $this->respondError("Failed to update policy transaction");
}
-
+
private function insertOrUpdateCoShareDetails($data, $pt_id)
- {
+ {
// Prepare data for insertion and updating
$coShareDetails = [];
-
+
// print_r($data); die;
// die;
- if(isset($data['co_share_id']) && !empty($data['co_share_id'])){
- $this->removePtCoShareRecords($data['co_share_id']);
+ if (isset($data['co_share_id']) && !empty($data['co_share_id'])) {
+ $this->removePtCoShareRecords($data['co_share_id'], $pt_id);
}
- if(isset($data['follow_insurer_id'])){
+ if (isset($data['follow_insurer_id'])) {
foreach ($data['follow_insurer_id'] as $index => $insurer) {
-
+
// Separate the insurer and insurer branch
- list($insurer_branch_id, $insurer_id) = explode('-', $insurer);
+ if (isset($insurer) && !empty($insurer)) {
+ list($insurer_branch_id, $insurer_id) = explode('-', $insurer);
+ } else {
+ $insurer_branch_id = null;
+ $insurer_id = null;
+ }
+
+ if ($data['bro_payable_by'] == 1) {
+ $cop_amt = isset($data['co_premium'][$index]) && ($data['co_premium'][$index] != "0.00" && !empty($data['co_premium'][$index])) ? $data['co_premium'][$index] : ($data['base_premium'][$index] ?? 0);
+ // print_r($cop_amt);die();
+ } else {
+ $cop_amt = $data['co_premium'][$index] ?? 0;
+ }
// Prepare each co-share detail entry
$coShareDetails[] = [
@@ -460,56 +500,55 @@ class PolicyTransactionController extends BaseController
'actual_bp_brokerage_amt' => $data['actual_bp_brokerage_amt'][$index] ?? 0,
'actual_tp_brokerage_amt' => $data['actual_tp_brokerage_amt'][$index] ?? 0,
'actual_tep_brokerage_amt' => $data['actual_tep_brokerage_amt'][$index] ?? 0,
- 'exp_amt' => $data['exp_amt'][$index] ?? 0,
+ 'exp_amt' => isset($data['exp_amt'][$index]) && !empty($data['exp_amt'][$index]) ? $data['exp_amt'][$index] : expected_amount_calc($data, $index),
'amount' => $data['total'][$index] ?? 0,
'stamp_duty' => $data['stamp_duty'][$index] ?? 0,
- 'cop_amt' => $data['co_premium'][$index] ?? 0,
+ 'cop_amt' => $cop_amt,
'variance' => $data['variance'][$index] ?? 0,
'reward' => $data['reward'][$index] ?? null,
'created_by' => get_session_userid() ?? null,
'updated_by' => get_session_userid() ?? null,
'id' => $data['co_share_id'][$index] ?? null, // Assuming this is the ID to identify existing records
- 'follower_policy_no' => $data['follower_policy_no'][$index] ?? null,
- 'non_comm_per_amt' => $data['non_comm_per_amt'][$index] ?? null,
+ 'follower_policy_no' => $data['follower_policy_no'][$index] ?? null,
+ 'non_comm_per_amt' => $data['non_comm_per_amt'][$index] ?? null,
];
}
// print_r($pt_id);
// print_r($coShareDetails);
// die;
-
+
// Separate data into insert and update batches
- $insertData = array_filter($coShareDetails, function($detail) {
+ $insertData = array_filter($coShareDetails, function ($detail) {
return empty($detail['id']); // Only insert new records
});
-
- $updateData = array_filter($coShareDetails, function($detail) {
+
+ $updateData = array_filter($coShareDetails, function ($detail) {
return !empty($detail['id']); // Only update existing records
});
-
+
// Insert new records
if (!empty($insertData)) {
$this->PTCOShareDetailsModel->insertBatch($insertData);
}
-
+
// Update existing records
if (!empty($updateData)) {
$this->PTCOShareDetailsModel->updateBatch($updateData, 'id'); // Assuming 'id' is the unique identifier
}
-
+
// print_r($this->PTCOShareDetailsModel->getLastQuery()); die;
// print_r($coShareDetails);
// die;
return true;
-
}
-
+
// print_r($data);
// die;
}
-
+
private function prepareClientPolicyInsertData($data)
{
return [
@@ -520,7 +559,7 @@ class PolicyTransactionController extends BaseController
'tpa_branch_id' => $data['tpa_branch_id'] ?? null,
'policy_type_id' => $data['policy_type_id'] ?? null,
'policy_start_date' => $data['policy_start_date'] ?? null,
- 'policy_end_date' => $data['policy_end_date'] ?? null ,
+ 'policy_end_date' => $data['policy_end_date'] ?? null,
'policy_status' => 1,
'is_addon' => $data['is_addon'] ?? null,
'base_policy' => $data['base_policy'] ?? 0,
@@ -531,7 +570,7 @@ class PolicyTransactionController extends BaseController
'gst' => 18,
];
}
-
+
private function insertTransactionStatus($policyTranId, $data, $statusType)
{
$statusData = [
@@ -543,12 +582,12 @@ class PolicyTransactionController extends BaseController
];
$this->policyTransactionStatusModel->insert($statusData);
}
-
+
private function processCompletedStatus($data, $client_policy_id, $insurer_id)
{
$totalAmount = (int)$data['total'][0] ?? 0;
- $description = 'The following amount of Rs. ' . $totalAmount . '/- has been debited for the ' . $data['emp_count'] . ' employees at Inception.';
-
+ $description = 'The following amount of Rs. ' . $totalAmount . '/- has been debited for the ' . $data['emp_count'] . ' employees at Inception (BDS).';
+
$cdTransactionData = [
'amount' => $totalAmount,
'sub_type_id' => 4,
@@ -562,38 +601,39 @@ class PolicyTransactionController extends BaseController
'updated_by' => get_session_userid(),
'event_name' => 'inception',
'is_active' => 1,
+ 'cd_ac_pk' => $data['cd_ac_pk']
];
-
+
DepositHelper::saveDeposit($cdTransactionData, get_session_userid());
}
private function processInsertIndividualMemberInEmpTable($data)
- {
+ {
// print_r($data);
- if(isset($data['family_name']) && !empty($data['family_name'])){
+ if (isset($data['family_name']) && !empty($data['family_name'])) {
$emp_data = [];
$emp_ids = [];
$random_code = generateRandomCode(); // Generate random code once
-
+
foreach ($data['family_name'] as $index => $val) {
-
+
// Determine the gender based on the relationship
$relationship = $data['relationship'][$index] ?? '';
$gender = 'M'; // Default to Male
-
+
// Set gender based on relationship
if (in_array($relationship, ['Mother', 'Daughter', 'Mother in law', 'Spouse'])) {
$gender = 'F';
}
-
+
$emp_data[] = [
'client_id' => $data['client_id'] ?? 0,
'client_branch_id' => $data['client_branch_id'] ?? 0,
'name' => $val,
'relationship' => $relationship,
- 'gender' => $gender,
- 'emp_status' => 'active',
+ 'gender' => $gender,
+ 'emp_status' => 'active',
'created_by' => get_session_userid(),
'emp_code' => $random_code, // Use the same random code for all
'id' => $data['emp_id'][$index] ?? null
@@ -601,52 +641,51 @@ class PolicyTransactionController extends BaseController
$emp_ids[] = $data['emp_id'][$index] ?? 0;
}
-
-
+
+
// print_r($emp_data); die;
-
+
// Separate data into insert and update batches
- $insertData = array_filter($emp_data, function($detail) {
+ $insertData = array_filter($emp_data, function ($detail) {
return empty($detail['id']); // Only insert new records
});
-
- $updateData = array_filter($emp_data, function($detail) {
+
+ $updateData = array_filter($emp_data, function ($detail) {
return !empty($detail['id']); // Only update existing records
});
-
+
// Insert new records
if (!empty($insertData)) {
$this->employeeModel->insertBatch($insertData);
}
-
+
// Update existing records
if (!empty($updateData)) {
$this->employeeModel->updateBatch($updateData, 'id'); // Assuming 'id' is the unique identifier
}
-
- return $emp_ids;
+ return $emp_ids;
}
}
private function InsertIndividualEmpPolicyTable($emp_ids, $client_policy_id)
- {
- if(!empty($emp_ids)){
+ {
+ if (!empty($emp_ids)) {
$emp_policy_data = [];
-
+
foreach ($emp_ids as $index => $emp_id) {
$emp_policy_data[] = [
'employee_id' => $emp_id ?? 0,
'client_policy_id' => $client_policy_id ?? 0,
'created_by' => get_session_userid(),
- 'status' => 'active',
+ 'status' => 'active',
];
}
-
+
// print_r($emp_policy_data); die;
-
+
// Insert new records
if (!empty($emp_policy_data)) {
$this->employeePolicyModel->insertBatch($emp_policy_data);
@@ -654,15 +693,14 @@ class PolicyTransactionController extends BaseController
return true;
-
}
}
-
+
private function respondSuccess($id, $message, $data)
{
- return $this->respond(['status' => true, 'pt_id' => $id, 'message' => $message, 'data' =>$data], 200);
+ return $this->respond(['status' => true, 'pt_id' => $id, 'message' => $message, 'data' => $data], 200);
}
-
+
private function respondError($message)
{
return $this->respond(['status' => false, 'message' => $message], 200);
@@ -673,7 +711,7 @@ class PolicyTransactionController extends BaseController
public function getInceptionDataForEdit($id)
{
$data = $this->policyTransactionModel
- ->select('
+ ->select('
policy_transaction.*,
clients.short_name as client_short_name,
clients.client_type,
@@ -694,83 +732,83 @@ class PolicyTransactionController extends BaseController
) as last_action_date
')
- ->join('clients', 'clients.id = policy_transaction.client_id')
- ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
- ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left')
- ->where('policy_transaction.id', $id)
- ->where('policy_transaction.is_active', 1)
- ->first();
+ ->join('clients', 'clients.id = policy_transaction.client_id')
+ ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
+ ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left')
+ ->where('policy_transaction.id', $id)
+ ->where('policy_transaction.is_active', 1)
+ ->first();
- // $data['policy_issue_date'] = (isset($data['policy_issue_date']) && $data['policy_issue_date'] !== null && $data['policy_issue_date'] !== '')
- // ? date('d/m/Y', strtotime($data['policy_issue_date']))
- // : null;
-
- // $data['policy_start_date'] = (isset($data['policy_start_date']) && $data['policy_start_date'] !== null && $data['policy_start_date'] !== '')
- // ? date('d/m/Y', strtotime($data['policy_start_date']))
- // : null;
-
- // $data['policy_end_date'] = (isset($data['policy_end_date']) && $data['policy_end_date'] !== null && $data['policy_end_date'] !== '')
- // ? date('d/m/Y', strtotime($data['policy_end_date']))
- // : null;
-
- // $data['renewal_date'] = (isset($data['renewal_date']) && $data['renewal_date'] !== null && $data['renewal_date'] !== '')
- // ? date('d/m/Y', strtotime($data['renewal_date']))
- // : null;
-
- // $data['rollover_date'] = (isset($data['rollover_date']) && $data['rollover_date'] !== null && $data['rollover_date'] !== '')
- // ? date('d/m/Y', strtotime($data['rollover_date']))
- // : null;
-
- // $data['month'] = (isset($data['month']) && $data['month'] !== null && $data['month'] !== '')
- // ? date('M/Y', strtotime($data['month']))
- // : null;
+ // $data['policy_issue_date'] = (isset($data['policy_issue_date']) && $data['policy_issue_date'] !== null && $data['policy_issue_date'] !== '')
+ // ? date('d/m/Y', strtotime($data['policy_issue_date']))
+ // : null;
-
- $data['created_at'] = (isset($data['created_at']) && $data['created_at'] !== null && $data['created_at'] !== '')
- ? date('d/m/Y h:i:s A', strtotime($data['created_at']))
- : null;
-
- $data['updated_at'] = (isset($data['updated_at']) && $data['updated_at'] !== null && $data['updated_at'] !== '')
- ? date('d/m/Y h:i:s A', strtotime($data['updated_at']))
- : null;
-
+ // $data['policy_start_date'] = (isset($data['policy_start_date']) && $data['policy_start_date'] !== null && $data['policy_start_date'] !== '')
+ // ? date('d/m/Y', strtotime($data['policy_start_date']))
+ // : null;
+
+ // $data['policy_end_date'] = (isset($data['policy_end_date']) && $data['policy_end_date'] !== null && $data['policy_end_date'] !== '')
+ // ? date('d/m/Y', strtotime($data['policy_end_date']))
+ // : null;
+
+ // $data['renewal_date'] = (isset($data['renewal_date']) && $data['renewal_date'] !== null && $data['renewal_date'] !== '')
+ // ? date('d/m/Y', strtotime($data['renewal_date']))
+ // : null;
+
+ // $data['rollover_date'] = (isset($data['rollover_date']) && $data['rollover_date'] !== null && $data['rollover_date'] !== '')
+ // ? date('d/m/Y', strtotime($data['rollover_date']))
+ // : null;
+
+ // $data['month'] = (isset($data['month']) && $data['month'] !== null && $data['month'] !== '')
+ // ? date('M/Y', strtotime($data['month']))
+ // : null;
+
+
+ $data['created_at'] = (isset($data['created_at']) && $data['created_at'] !== null && $data['created_at'] !== '')
+ ? date('d/m/Y h:i:s A', strtotime($data['created_at']))
+ : null;
+
+ $data['updated_at'] = (isset($data['updated_at']) && $data['updated_at'] !== null && $data['updated_at'] !== '')
+ ? date('d/m/Y h:i:s A', strtotime($data['updated_at']))
+ : null;
+
+
+ if (!empty($data['policy_issue_date'])) {
+ $data['policy_issue_date'] = change_date_format($data['policy_issue_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['policy_start_date'])) {
+ $data['policy_start_date'] = change_date_format($data['policy_start_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['policy_end_date'])) {
+ $data['policy_end_date'] = change_date_format($data['policy_end_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['renewal_date'])) {
+ $data['renewal_date'] = change_date_format($data['renewal_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['rollover_date'])) {
+ $data['rollover_date'] = change_date_format($data['rollover_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['endorse_eff_date'])) {
+ $data['endorse_eff_date'] = change_date_format($data['endorse_eff_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['last_action_date'])) {
+ $data['last_action_date'] = change_date_format($data['last_action_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['month'])) {
+ $data['month'] = change_date_format($data['month'], 'Y-m-d', 'M/Y');
+ } else {
+ $data['month'] = null;
+ }
- if(!empty($data['policy_issue_date'])){
- $data['policy_issue_date'] = change_date_format($data['policy_issue_date'], 'Y-m-d', 'd/m/Y');
- }
- if(!empty($data['policy_start_date'])){
- $data['policy_start_date'] = change_date_format($data['policy_start_date'], 'Y-m-d', 'd/m/Y');
- }
-
- if(!empty($data['policy_end_date'])){
- $data['policy_end_date'] = change_date_format($data['policy_end_date'], 'Y-m-d', 'd/m/Y');
- }
-
- if(!empty($data['renewal_date'])){
- $data['renewal_date'] = change_date_format($data['renewal_date'], 'Y-m-d', 'd/m/Y');
- }
-
- if(!empty($data['rollover_date'])){
- $data['rollover_date'] = change_date_format($data['rollover_date'], 'Y-m-d', 'd/m/Y');
- }
-
- if(!empty($data['endorse_eff_date'])){
- $data['endorse_eff_date'] = change_date_format($data['endorse_eff_date'], 'Y-m-d', 'd/m/Y');
- }
- if(!empty($data['last_action_date'])){
- $data['last_action_date'] = change_date_format($data['last_action_date'], 'Y-m-d', 'd/m/Y');
- }
-
- if(!empty($data['month'])){
- $data['month'] = change_date_format($data['month'], 'Y-m-d', 'M/Y');
- }else{
- $data['month'] = null;
- }
-
-
-
// print_r($data); die;
$data['renewal_policy'] = $this->clientPolicyModel
@@ -781,24 +819,35 @@ class PolicyTransactionController extends BaseController
->where('client_policy.is_active', 1)
->findAll();
-
+
$data['base_policy_data'] = $this->clientPolicyModel
- ->select('client_policy.*, policy_type.policy_type')
- ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
- ->where('client_policy.client_id', $data['client_id'])
- ->where('client_policy.client_branch_id', $data['client_branch_id'])
- ->whereIn('client_policy.policy_type_id', [2, 3])
- ->where('client_policy.is_active', 1)
- ->findAll();
-
- $data['pt_files'] = $this->PTFileModel
- ->join('policy_transaction', 'pt_files.pt_id = policy_transaction.id')
- ->where('pt_files.pt_id', $id)
- ->where('pt_files.is_active', 1)
- ->findAll();
-
+ ->select('client_policy.*, policy_type.policy_type')
+ ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
+ ->where('client_policy.client_id', $data['client_id'])
+ ->where('client_policy.client_branch_id', $data['client_branch_id'])
+ ->whereIn('client_policy.policy_type_id', [2, 3])
+ ->where('client_policy.is_active', 1)
+ ->findAll();
+
+
+ $ptFileQuery = $this->PTFileModel
+ ->join('policy_transaction', 'pt_files.pt_id = policy_transaction.id')
+ ->where('pt_files.pt_id', $id)
+ ->where('pt_files.is_active', 1);
+
+ if (!in_array(get_role_id(), [1, 5]) && empty(array_intersect(user_team(), [MANAGEMENT_TEAM_ID, FINANCE_TEAM_ID, BUSINESS_TEAM_ID]))) {
+
+ if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
+ $ptFileQuery->where('pt_files.created_by', get_session_userid());
+ }
+ }
+
+ $data['pt_files'] = $ptFileQuery->findAll();
+
+
+
$data['pt_co_share_details'] = $this->PTCOShareDetailsModel
- ->select("
+ ->select("
pt_co_share_details.*,
(
@@ -914,41 +963,39 @@ class PolicyTransactionController extends BaseController
) AS actual_tep_brokerage_amount
")
- ->where('pt_id', $id)
- ->where('is_active', 1)
- ->orderBy('id', 'asc')
- ->findAll();
-
+ ->where('pt_id', $id)
+ ->where('is_active', 1)
+ ->orderBy('id', 'asc')
+ ->findAll();
+
$data['emp_data'] = $this->employeeModel
- ->select('employees.*, employee_polices.id as emp_policy_id')
- ->join('employee_polices', 'employees.id = employee_polices.employee_id', 'left')
- ->where('employees.client_id', $data['client_id'])
- ->where('employees.is_active', 1)->findAll();
+ ->select('employees.*, employee_polices.id as emp_policy_id')
+ ->join('employee_polices', 'employees.id = employee_polices.employee_id', 'left')
+ ->where('employees.client_id', $data['client_id'])
+ ->where('employees.is_active', 1)->findAll();
$data['client_kyc'] = $this->clientKYCDocsModel->where('client_id', $data['client_id'])->findAll();
$data['vehicle_docs'] = $this->clientKYCDocsModel
- ->where('client_id', $data['client_id'])
- ->where('vehicle_id', $data['vehicle_id'])
- ->findAll();
+ ->where('client_id', $data['client_id'])
+ ->where('vehicle_id', $data['vehicle_id'])
+ ->findAll();
// print_r( $data['pt_co_share_details']); die;
- if($data){
+ if ($data) {
return $this->respond(['status' => true, 'data' => $data], 200);
- }else{
+ } else {
return $this->respond(['status' => false], 200);
}
-
}
public function removePolicyTransaction($id)
{
if ($id) {
-
+
$data['is_active'] = 0;
$this->policyTransactionModel->where('id', $id)->set($data)->update();
$this->PTCOShareDetailsModel->where('pt_id', $id)->set($data)->update();
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Policy Transaction removed successfully'], 200);
-
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to remove policy transaction'], 200);
@@ -956,27 +1003,31 @@ class PolicyTransactionController extends BaseController
}
//function for soft delete for pt_co_share_details records
- public function removePtCoShareRecords($primaryKeys)
+ public function removePtCoShareRecords($primaryKeys, $pt_id)
{
- // print_r($primaryKeys); die;
if (empty($primaryKeys)) {
- return false;
+ return false;
}
-
- // Convert array to a comma-separated string for query binding
+
+ // Convert array to a comma-separated string of placeholders for query binding
$placeholders = implode(',', array_fill(0, count($primaryKeys), '?'));
-
- $sql = "UPDATE pt_co_share_details SET is_active = 0 WHERE id NOT IN ($placeholders)";
-
- return db_connect()->query($sql, $primaryKeys);
+
+ // Prepare the query with proper binding
+ $sql = "UPDATE pt_co_share_details SET is_active = 0 WHERE pt_id = ? AND id NOT IN ($placeholders)";
+
+ // Merge pt_id with primary keys for binding
+ $params = array_merge([$pt_id], $primaryKeys);
+
+ // Execute the query with bound parameters
+ return db_connect()->query($sql, $params);
}
-
+
//------------------------------------------------------------------------------------------------
// Policy Transaction Endorsement
public function viewEndorsement()
- {
+ {
// echo '';
// !dd($this->getEndorsementDataForEdit(17));
@@ -1034,27 +1085,33 @@ class PolicyTransactionController extends BaseController
$date_type = $this->request->getGet('date_type');
$issuer = $this->request->getGet('issuer');
$status = $this->request->getGet('status');
-
+
$start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date;
$end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date;
-
+
$client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
- $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
- $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;
- $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;
- $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;
- $status = (!isset($issuer) || $status === '' || $status === null) ? 0 : $status;
+ $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
+ $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;
+ $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;
+ $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;
+ $status = (!isset($issuer) || $status === '' || $status === null) ? 0 : $status;
$data['endorsement_data_list'] = $this->policyTransactionModel->getEndorsementTranctionListData($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status);
$data['client'] = $this->clientModel->where('is_active', 1)->findAll();
- $data['policy_type'] = $this->policyTypeModel->where('is_active', 1)->findAll();
+ $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll();
$data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll();
// $data['tpa'] = $this->tpaModel->where('is_active', 1)->findAll();
- $data['insurer_branch'] = $this->insurerBranchModel ->getInsurerBranchesWithInsurerNames();
- $data['tpa'] = $this->tpaBranchModel ->getTpaBranchesWithTpaNames();
+ $data['insurer_branch'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
+ $data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
+ list($policyList, $policyListByClient) = $this->getPolicyForEndorsment();
+ $data['endorsementPolicies'] = $policyList;
+ $data['endorsementPolicyListByClient'] = $policyListByClient;
+
+ // dd($data);
+ // print_r($data['endorsementPolicies']);die();
$this->loadLayout('policy_transaction_endorsement_list', $data);
}
@@ -1064,7 +1121,7 @@ class PolicyTransactionController extends BaseController
$id = $this->request->getPost('id');
$data = $this->preparePolicyTransactionData();
// print_r($data); die;
-
+
if (!$id) {
return $this->insertEndorsementTransaction($data);
} else {
@@ -1086,47 +1143,51 @@ class PolicyTransactionController extends BaseController
$data['policy_with_corr'] = 1;
}
- if(empty($data['data_received_date'])){
+ if (!isset($data['is_cd_reduce_from_bds'])) {
+ $data['is_cd_reduce_from_bds'] = 0;
+ } elseif ($data['is_cd_reduce_from_bds']) {
+ $data['is_cd_reduce_from_bds'] = 1;
+ }
+
+ if (empty($data['data_received_date'])) {
$data['data_received_date'] = null;
- }else{
+ } else {
$data['data_received_date'] = change_date_format($data['data_received_date'], 'd/m/Y', 'Y-m-d');
}
- if(empty($data['policy_issue_date'])){
+ if (empty($data['policy_issue_date'])) {
$data['policy_issue_date'] = null;
- }else{
+ } else {
$data['policy_issue_date'] = change_date_format($data['policy_issue_date'], 'd/m/Y', 'Y-m-d');
}
- if(empty($data['endorse_eff_date'])){
+ if (empty($data['endorse_eff_date'])) {
$data['endorse_eff_date'] = null;
- }else{
+ } else {
$data['endorse_eff_date'] = change_date_format($data['endorse_eff_date'], 'd/m/Y', 'Y-m-d');
-
}
- if(empty($data['install_due_date'])){
+ if (empty($data['install_due_date'])) {
$data['install_due_date'] = null;
- }else{
+ } else {
$data['install_due_date'] = change_date_format($data['install_due_date'], 'd/m/Y', 'Y-m-d');
-
}
- if(!empty($data['month'])){
- $month = '01/'.$data['month'];
+ if (!empty($data['month'])) {
+ $month = '01/' . $data['month'];
$data['month'] = change_date_format($month, 'd/M/Y', 'Y-m-d');
}
- if(empty($data['last_action_date'])){
+ if (empty($data['last_action_date'])) {
$data['last_action_date'] = null;
- }else{
+ } else {
$data['last_action_date'] = change_date_format($data['last_action_date']);
}
// print_r($data); die;
// Separate Insurer and TPA Branch IDs and IDs
- if(isset($data['insurer_id']) && !empty($data['insurer_id'])){
+ if (isset($data['insurer_id']) && !empty($data['insurer_id'])) {
list($data['insurer_branch_id'], $data['insurer_id']) = explode('-', $data['insurer_id']);
if (isset($data['tpa']) && !empty($data['tpa'])) {
list($data['tpa_branch_id'], $data['tpa_id']) = explode('-', $data['tpa']);
@@ -1134,20 +1195,20 @@ class PolicyTransactionController extends BaseController
}
$issue_type = $this->policyTransactionModel
- ->where('action_type', 'inception')
- ->where('client_id', $this->request->getPost('client_id'))
- ->where('client_policy_id', $this->request->getPost('client_policy_id'))
- ->where('policy_transaction.is_active', 1)
- ->first();
+ ->where('action_type', 'inception')
+ ->where('client_id', $this->request->getPost('client_id'))
+ ->where('client_policy_id', $this->request->getPost('client_policy_id'))
+ ->where('policy_transaction.is_active', 1)
+ ->first();
$data['tsi'] = generate_tsi_code($issue_type['issue_type'] ?? 1);
$client_branch_id = $data['client_branch_id'];
- if($data['client_branch_id'] == ""){
+ if ($data['client_branch_id'] == "") {
$client_branch_id = $issue_type['client_branch_id'];
}
- if(!$data['id']){
+ if (!$data['id']) {
$data += [
'issuer' => $issue_type['issuer'] ?? null,
@@ -1155,8 +1216,8 @@ class PolicyTransactionController extends BaseController
'policy_type_id' => $issue_type['policy_type_id'] ?? null,
'issue_type' => $issue_type['issue_type'] ?? null,
'source_client_policy_id' => $issue_type['source_client_policy_id'] ?? null,
- 'cd_ac_no' => $issue_type['cd_ac_no'] ?? null,
- 'cd_ac_pk' => $issue_type['cd_ac_pk'] ?? null,
+ 'cd_ac_no' => isset($data['cd_ac_no']) && !empty($data['cd_ac_no']) ? $data['cd_ac_no'] : $issue_type['cd_ac_no'] ?? null,
+ 'cd_ac_pk' => isset($data['cd_ac_pk']) && !empty($data['cd_ac_pk']) ? $data['cd_ac_pk'] : $issue_type['cd_ac_pk'] ?? null,
// 'policy_issue_date' => $issue_type['policy_issue_date'] ?? null,
'policy_start_date' => $issue_type['policy_start_date'] ?? null,
'policy_end_date' => $issue_type['policy_end_date'] ?? null,
@@ -1166,7 +1227,7 @@ class PolicyTransactionController extends BaseController
'installment' => $issue_type['installment'] ?? null,
'installment_data' => $issue_type['installment_data'] ?? null,
'location' => $issue_type['location'] ?? null,
- 'links' => $issue_type['links'] ??null,
+ 'links' => $issue_type['links'] ?? null,
'stage' => $issue_type['stage'] ?? null,
'etat' => $issue_type['etat'] ?? null,
'etat_band' => $issue_type['etat_band'] ?? null,
@@ -1215,6 +1276,7 @@ class PolicyTransactionController extends BaseController
$update = $this->policyTransactionModel->where('id', $id)->set($data)->update();
if ($update) {
+
$this->insertTransactionStatus($id, $data, 1);
$this->handleCompletedStatus($data, $id);
$this->insertOrUpdateCoShareDetails($data, $id);
@@ -1228,12 +1290,12 @@ class PolicyTransactionController extends BaseController
private function handleCompletedStatus($data, $policy_tran_id)
{
- if ($data['status'] == 'completed' && $data['ct_type'] == 2) {
+ if ($data['client_type'] == 1 && $data['status'] == 'completed' && $data['is_cd_reduce_from_bds'] == 1) {
$tolamt = $data['total'][0] ?? 0;
- $description = 'The following amount of Rs. ' . round($tolamt, 2) . '/- has been' .
- ($data['action_type'] == 'deletion' ? ' Credit ' : ' Debit ') . 'from the policy transaction';
+ $description = 'The following amount of Rs. ' . round($tolamt, 2) . '/- has been' .
+ ($data['action_type'] == 'deletion' ? ' Credit ' : ' Debit ') . 'from the policy transaction (BDS)';
$cd_tranction_data = [
'amount' => $tolamt,
@@ -1248,6 +1310,7 @@ class PolicyTransactionController extends BaseController
'updated_by' => get_session_userid(),
'event_name' => $data['action_type'],
'is_active' => 1,
+ 'cd_ac_pk' => $data['cd_ac_pk'] ?? null,
];
DepositHelper::saveDeposit($cd_tranction_data, get_session_userid());
@@ -1450,13 +1513,13 @@ class PolicyTransactionController extends BaseController
//file upload function
public function uploadFile()
- {
+ {
$GoogleDriveController = new GoogleDriveController();
$files = $this->request->getFiles();
- $doc_name = $this->request->getPost('doc_name[]');
- $pt_id = $this->request->getPost('pt_id');
- $client_policy_id = $this->request->getPost('client_policy_id');
- $data = $this->request->getPost();
+ $doc_name = $this->request->getPost('doc_name[]');
+ $pt_id = $this->request->getPost('pt_id');
+ $client_policy_id = $this->request->getPost('client_policy_id');
+ $data = $this->request->getPost();
$uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';
@@ -1489,7 +1552,7 @@ class PolicyTransactionController extends BaseController
$insert = $this->PTFileModel->insert($docData);
if ($insert) {
- $uploadData[] = $docData;
+ $uploadData[] = $docData;
}
}
}
@@ -1498,15 +1561,23 @@ class PolicyTransactionController extends BaseController
// print_r($uploadData); die;
// $uploadData = uploadFilesToGoogleDrive($files['file'], $doc_name, $pt_id);
-
+
if (!empty($uploadData)) {
- $data['pt_files'] = $this->PTFileModel
+ $ptFileQuery = $this->PTFileModel
->join('policy_transaction', 'pt_files.pt_id = policy_transaction.id')
->where('pt_files.pt_id', $pt_id)
- ->where('pt_files.is_active', 1)
- ->findAll();
-
+ ->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();
+
return $this->respond(['status' => true, 'message' => 'File uploaded successfully in G-Drive', 'data' => $data]);
} else {
return $this->respond(['status' => false, 'message' => 'Failed to upload file in G-Drive']);
@@ -1522,7 +1593,7 @@ class PolicyTransactionController extends BaseController
// var_dump($ids); die;
$data['invoice_status'] = $this->request->getPost('invoice_status');
- if($this->request->getPost('invoice_status') == 'generated'){
+ if ($this->request->getPost('invoice_status') == 'generated') {
$data['invoice_no'] = $this->request->getPost('invoice_no');
}
@@ -1531,8 +1602,8 @@ class PolicyTransactionController extends BaseController
->whereIn('id', $ids)
->set($data)
->update();
-
-
+
+
if ($update) {
return $this->respond(['status' => true, 'data' => $ids, 'message' => 'Invoice status updated successfully'], 200);
@@ -1549,7 +1620,7 @@ class PolicyTransactionController extends BaseController
'updated_by' => get_session_userid(),
'is_active' => 0
];
-
+
$update = $this->PTCOShareDetailsModel->where('id', $id)->set($data)->update();
if ($update) {
@@ -1565,6 +1636,7 @@ class PolicyTransactionController extends BaseController
->select("
pt_co_share_details.*,
policy_transaction.bro_payable_by,
+ policy_transaction.cd_ac_pk,
(
select cd_ac_no
from cd_master
@@ -1583,6 +1655,7 @@ class PolicyTransactionController extends BaseController
->where('policy_transaction.client_id', $client_id)
->where('policy_transaction.client_policy_id', $client_policy_id)
->where('policy_transaction.action_type', 'inception')
+ ->where('policy_transaction.is_active', 1)
->findAll();
$is_copay_yes = $this->policyTransactionModel
@@ -1591,13 +1664,15 @@ class PolicyTransactionController extends BaseController
->where('action_type', 'inception')
->where('is_active', 1)
->first();
-
- if ($totalCount) {
- return $this->respond(['status' => true, 'code' => 200, 'data' => $totalCount, 'is_copay_yes' => $is_copay_yes], 200);
- } else {
- return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to get data'], 200);
- }
+ $cd_ac_no = db_connect()->table('cd_master')->where('id', $is_copay_yes['cd_ac_pk'] ?? null)->get()->getRowArray();
+
+ if ($totalCount) {
+ return $this->respond(['status' => true, 'code' => 200, 'data' => $totalCount, 'is_copay_yes' => $is_copay_yes, "cd_master_data" => $cd_ac_no], 200);
+ } else {
+ $insurer_data = $this->clientPolicyModel->where('id', $client_policy_id)->where('is_active', 1)->first();
+ return $this->respond(['status' => false, 'code' => 404, 'message' => 'There is no policy inception data.'], 200);
+ }
}
public function checkInvoiceStatus($pt_id)
@@ -1612,28 +1687,28 @@ class PolicyTransactionController extends BaseController
->where('insurer_statements.invoice_no IS NOT NULL')
->countAllResults();
- if($data){
- return $this->respond(['status' => true, 'count'=> $data, 'code' => 200], 200);
- }else{
- return $this->respond(['status' => false, 'count'=> 0, 'message' => 'No Data Found', 'code' => 404], 200);
+ if ($data) {
+ return $this->respond(['status' => true, 'count' => $data, 'code' => 200], 200);
+ } else {
+ return $this->respond(['status' => false, 'count' => 0, 'message' => 'No Data Found', 'code' => 404], 200);
}
}
public function getBasePolicy($client_id, $client_branch_id)
{
$data = $this->clientPolicyModel
- ->select('client_policy.*, policy_type.policy_type')
- ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
- ->where('client_policy.client_id', $client_id)
- ->where('client_policy.client_branch_id', $client_branch_id)
- ->whereIn('client_policy.policy_type_id', [2, 3])
- ->where('client_policy.is_active', 1)
- ->findAll();
+ ->select('client_policy.*, policy_type.policy_type')
+ ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
+ ->where('client_policy.client_id', $client_id)
+ ->where('client_policy.client_branch_id', $client_branch_id)
+ ->whereIn('client_policy.policy_type_id', [2, 3])
+ ->where('client_policy.is_active', 1)
+ ->findAll();
- if($data){
- return $this->respond(['status' => true, 'data'=> $data, 'code' => 200], 200);
- }else{
- return $this->respond(['status' => false, 'count'=> 0, 'message' => 'No Data Found', 'code' => 404], 200);
+ if ($data) {
+ return $this->respond(['status' => true, 'data' => $data, 'code' => 200], 200);
+ } else {
+ return $this->respond(['status' => false, 'count' => 0, 'message' => 'No Data Found', 'code' => 404], 200);
}
}
@@ -1641,7 +1716,7 @@ class PolicyTransactionController extends BaseController
//get BDS Reports data old function
public function reportBDSOld()
- {
+ {
$data['page_name'] = 'BDS Report';
@@ -1655,7 +1730,7 @@ class PolicyTransactionController extends BaseController
'exported_to_tpa' => 'Exported to TPA',
'imported_from_tpa' => 'Imported from TPA',
'completed' => 'Completed'
- ];
+ ];
$data['invoice_status_array'] = [
'yet_to_generate' => 'Yet to Generate',
'generated' => 'Generated',
@@ -1682,27 +1757,27 @@ class PolicyTransactionController extends BaseController
$policy_type_id = $this->request->getGet('policy_type_id');
$date_type = $this->request->getGet('date_type');
$issuer = $this->request->getGet('issuer');
-
+
$start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date;
$end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date;
-
+
$client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
- $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
- $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;
- $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;
- $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;
-
-
+ $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
+ $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;
+ $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;
+ $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;
+
+
//Actual data for the list
$data['report_list'] = $this->policyTransactionModel->getBDSReportList($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer);
// dd($data);
-
- $this->loadLayout('report_bds_filter', $data);
+
+ $this->loadLayout('report_bds_filter', $data);
}
//get BDS Reports data New Function
public function reportBDS()
- {
+ {
$data['page_name'] = 'BDS Report';
@@ -1716,7 +1791,7 @@ class PolicyTransactionController extends BaseController
'exported_to_tpa' => 'Exported to TPA',
'imported_from_tpa' => 'Imported from TPA',
'completed' => 'Completed'
- ];
+ ];
$data['invoice_status_array'] = [
'yet_to_generate' => 'Yet to Generate',
'generated' => 'Generated',
@@ -1736,6 +1811,7 @@ class PolicyTransactionController extends BaseController
$data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll();
$data['clients'] = $this->clientModel->where('is_active', 1)->findAll();
+
//filter datas
$start_date = $this->request->getGet('start_date');
$end_date = $this->request->getGet('end_date');
@@ -1748,35 +1824,50 @@ class PolicyTransactionController extends BaseController
$insurer_branch_id = $this->request->getGet('insurer_branch_id');
$client_policy_id = $this->request->getGet('client_policy_id');
- if($date_type == 'statement_month'){
+ if ($date_type == 'statement_month') {
$start_date = (string)date('Y-m-01', strtotime($start_date));
$end_date = (string)date('Y-m-31', strtotime($end_date));
}
// dd($start_date, $end_date, $date_type);
-
+
$start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date;
$end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date;
-
+
$client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
- $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
- $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;
- $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;
- $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;
- $client_branch_id = (!isset($client_branch_id) || $client_branch_id === '' || $client_branch_id === null) ? 0 : $client_branch_id;
- $insurer_branch_id = (!isset($insurer_branch_id) || $insurer_branch_id === '' || $insurer_branch_id === null) ? 0 : $insurer_branch_id;
- $client_policy_id = (!isset($client_policy_id) || $client_policy_id === '' || $client_policy_id === null) ? 0 : $client_policy_id;
-
-
+ $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
+ $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;
+ $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;
+ $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;
+ $client_branch_id = (!isset($client_branch_id) || $client_branch_id === '' || $client_branch_id === null) ? 0 : $client_branch_id;
+ $insurer_branch_id = (!isset($insurer_branch_id) || $insurer_branch_id === '' || $insurer_branch_id === null) ? 0 : $insurer_branch_id;
+ $client_policy_id = (!isset($client_policy_id) || $client_policy_id === '' || $client_policy_id === null) ? 0 : $client_policy_id;
+ if ($this->request->is('post')) {
+ $isFromDashboard = $this->request->getPost("is_dashboard");
+
+ if (isset($isFromDashboard) && !empty($isFromDashboard) && $isFromDashboard == 1) {
+ $ids = $this->request->getPost('ids');
+
+ $ids = array_filter(explode(',', $ids));
+
+ if (!empty($ids)) {
+ $idsStr = implode(',', array_map('intval', $ids)); // sanitize IDs to be integers
+ $where = "policy_transaction.id IN ($idsStr)";
+ } else {
+ $where = []; // No valid IDs, return empty result
+ }
+ }
+ // dd($ids);
+ }
//Actual data for the list
- $data['report_list'] = $this->policyTransactionModel->getBDSReportList($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $client_branch_id, $insurer_branch_id, $client_policy_id);
+ $data['report_list'] = $this->policyTransactionModel->getBDSReportList($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $client_branch_id, $insurer_branch_id, $client_policy_id, isset($where) ? $where : '');
//!dd($data['report_list']);
-
- $this->loadLayout('report_bds_filter', $data);
+
+ $this->loadLayout('report_bds_filter', $data);
}
public function reportVarience()
- {
+ {
$data['page_name'] = 'Variance Report';
$data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
@@ -1803,30 +1894,29 @@ class PolicyTransactionController extends BaseController
$insurer_branch_id = $this->request->getGet('insurer_branch_id');
$client_policy_id = $this->request->getGet('client_policy_id');
-
+
$start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date;
$end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date;
-
- $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
- $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
- $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;
- $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;
- $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;
- $client_branch_id = (!isset($client_branch_id) || $client_branch_id === '' || $client_branch_id === null) ? 0 : $client_branch_id;
- $insurer_branch_id = (!isset($insurer_branch_id) || $insurer_branch_id === '' || $insurer_branch_id === null) ? 0 : $insurer_branch_id;
- $client_policy_id = (!isset($client_policy_id) || $client_policy_id === '' || $client_policy_id === null) ? 0 : $client_policy_id;
+ $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
+ $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
+ $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;
+ $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;
+ $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;
+
+ $client_branch_id = (!isset($client_branch_id) || $client_branch_id === '' || $client_branch_id === null) ? 0 : $client_branch_id;
+ $insurer_branch_id = (!isset($insurer_branch_id) || $insurer_branch_id === '' || $insurer_branch_id === null) ? 0 : $insurer_branch_id;
+ $client_policy_id = (!isset($client_policy_id) || $client_policy_id === '' || $client_policy_id === null) ? 0 : $client_policy_id;
$data['varience_list'] = $this->policyTransactionModel->getVarienceReportLIst($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $client_branch_id, $insurer_branch_id, $client_policy_id);
// !dd($data['varience_list']);
- $this->loadLayout('variance_report_list', $data);
-
+ $this->loadLayout('variance_report_list', $data);
}
public function reportBusinessList()
- {
+ {
$data['page_name'] = 'Business Report';
$data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
@@ -1849,24 +1939,24 @@ class PolicyTransactionController extends BaseController
$policy_type_id = $this->request->getGet('policy_type_id');
$date_type = $this->request->getGet('date_type');
$issuer = $this->request->getGet('issuer');
-
+
$start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date;
$end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date;
-
+
$client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
- $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
- $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;
- $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;
- $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;
+ $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
+ $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;
+ $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;
+ $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;
$data['business_list'] = $this->policyTransactionModel->getBusinessReportList($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer);
- $this->loadLayout('business_team_list', $data);
+ $this->loadLayout('business_team_list', $data);
}
public function reportFinanceList()
- {
+ {
$data['page_name'] = 'Finance Report';
$data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
@@ -1889,24 +1979,24 @@ class PolicyTransactionController extends BaseController
$policy_type_id = $this->request->getGet('policy_type_id');
$date_type = $this->request->getGet('date_type');
$issuer = $this->request->getGet('issuer');
-
+
$start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date;
$end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date;
-
+
$client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
- $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
- $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;
- $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;
- $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;
+ $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
+ $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;
+ $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;
+ $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;
$data['finance_list'] = $this->policyTransactionModel->getFinanceReportList($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer);
- $this->loadLayout('finance_team_list', $data);
+ $this->loadLayout('finance_team_list', $data);
}
public function reportOutstanding()
- {
+ {
$data['page_name'] = 'Outstanding Report';
$data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
@@ -1927,20 +2017,19 @@ class PolicyTransactionController extends BaseController
$client_id = $this->request->getGet('client_id');
$insurer_id = $this->request->getGet('insurer_id');
$insurer_branch_id = $this->request->getGet('insurer_branch_id');
-
- $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : change_date_format($start_date,'d-m-Y','Y-m-01');
- $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : change_date_format($end_date,'d-m-Y','Y-m-31');
- // dd([$start_date,$end_date]);
-
-
- $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
- $insurer_branch_id = (!isset($insurer_branch_id) || $insurer_branch_id === '' || $insurer_branch_id === null) ? 0 : $insurer_branch_id;
- $data['outstanting_list'] = $this->policyTransactionModel->getOutstandingReportLIst($start_date, $end_date,$insurer_id, $insurer_branch_id);
+ $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : change_date_format($start_date, 'd-m-Y', 'Y-m-01');
+ $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : change_date_format($end_date, 'd-m-Y', 'Y-m-31');
+ // dd([$start_date,$end_date]);
+
+
+ $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
+ $insurer_branch_id = (!isset($insurer_branch_id) || $insurer_branch_id === '' || $insurer_branch_id === null) ? 0 : $insurer_branch_id;
+
+ $data['outstanting_list'] = $this->policyTransactionModel->getOutstandingReportLIst($start_date, $end_date, $insurer_id, $insurer_branch_id);
// dd($this->policyTransactionModel->getLastQuery());
// dd($data);
- $this->loadLayout('outstanding_report_list', $data);
-
+ $this->loadLayout('outstanding_report_list', $data);
}
//---------------------------------------------------------------------------------------------------
@@ -1949,16 +2038,17 @@ class PolicyTransactionController extends BaseController
public function statementList()
{
// dd($this->validateInsurerStatement(['file_id' => 30]));
- // $data['insurers'] = $this->insurerModel->where('is_active',1)->findAll();
+ // $data['insurers'] = $this->insurerModel->where('is_active',1)->findAll();
$today = date('Y-m-d');
$fromday = $from_date = date('Y-m-d', strtotime('-180 days', strtotime($today)));
// echo $fromday;die();
- $data['invoice_status_array'] = $this->invoiceStatus;
- $data['insurers'] = $this->insurerBranchModel ->getInsurerBranchesWithInsurerNames();
+ $data['invoice_status_array'] = $this->invoiceStatus;
+ $data['insurers'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
- // dd( $data['insurers']);
- $data['insurer_statement_list'] = $this->insurerStatements
- ->select('insurer_statements.*,
+ // dd( $data['insurers']);
+ $data['insurer_statement_list'] = $this->insurerStatements
+ ->select(
+ 'insurer_statements.*,
insurers.name AS insurer_name,
insurers.short_name,
user_profiles.first_name,
@@ -1973,18 +2063,18 @@ class PolicyTransactionController extends BaseController
WHERE inv_payment_details.is_active = 1
AND inv_payment_details.statement_id = insurer_statements.id
) AS received_inv_amt'
- )
- ->join('insurers', 'insurer_statements.insurer_id = insurers.id')
- ->join('insurer_branch', 'insurer_statements.branch_id = insurer_branch.id')
- ->join('user_profiles', 'insurer_statements.created_by = user_profiles.id')
- ->where('insurer_statements.is_active', 1)
- // ->where('insurer_statements.file_status','success')
- ->where('date(insurer_statements.created_at) >= ', $from_date)
- ->where('date(insurer_statements.created_at) <= ', $today)
- ->orderBy('insurer_statements.id', 'DESC')
- ->findAll();
+ )
+ ->join('insurers', 'insurer_statements.insurer_id = insurers.id')
+ ->join('insurer_branch', 'insurer_statements.branch_id = insurer_branch.id')
+ ->join('user_profiles', 'insurer_statements.created_by = user_profiles.id')
+ ->where('insurer_statements.is_active', 1)
+ // ->where('insurer_statements.file_status','success')
+ ->where('date(insurer_statements.created_at) >= ', $from_date)
+ ->where('date(insurer_statements.created_at) <= ', $today)
+ ->orderBy('insurer_statements.id', 'DESC')
+ ->findAll();
- // dd( $this->insurerStatements->getLastQuery());
+ // dd( $this->insurerStatements->getLastQuery());
$data['page_name'] = 'Statement Upload';
$this->loadLayout('insurer_statement_list', $data);
@@ -2035,80 +2125,77 @@ class PolicyTransactionController extends BaseController
public function uploadInsurerStatement()
{
- //validate uploaded file
- $filename = '';
- $validated = $this->validate([
- 'statement' => [
- 'uploaded[statement]',
- 'mime_in[statement,application/vnd.ms-excel,application/vnd,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.oasis.opendocument.spreadsheet]',
- 'max_size[statement,16384]',
- ],
- ]);
- // $this->createStatementFolder();
- if ($validated)
- {
- $avatar = $this->request->getFile('statement');
- if (!$avatar) {
- $this->myLogger->logme("error", 'Statement File not found');
- return $this->respond(['dataStatus' => false, 'code' => 400, 'message' => 'File not found'], 400);
- }
+ //validate uploaded file
+ $filename = '';
+ $validated = $this->validate([
+ 'statement' => [
+ 'uploaded[statement]',
+ 'mime_in[statement,application/vnd.ms-excel,application/vnd,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.oasis.opendocument.spreadsheet]',
+ 'max_size[statement,16384]',
+ ],
+ ]);
+ // $this->createStatementFolder();
+ if ($validated) {
+ $avatar = $this->request->getFile('statement');
+ if (!$avatar) {
+ $this->myLogger->logme("error", 'Statement File not found');
+ return $this->respond(['dataStatus' => false, 'code' => 400, 'message' => 'File not found'], 400);
+ }
- $is_moved = $avatar->move(WRITEPATH . 'uploads/statements/');
- if ($is_moved) {
- $filename = $avatar->getName();
- // Handle successful upload, e.g., log success or further processing
- $this->myLogger->logme("error", 'Statement File moved successful');
-
- } else {
- $this->myLogger->logme("error", 'Statement File move failed');
- return $this->respond(['dataStatus' => false, 'code' => 500, 'message' => 'File move failed'], 500);
- }
+ $is_moved = $avatar->move(WRITEPATH . 'uploads/statements/');
+ if ($is_moved) {
+ $filename = $avatar->getName();
+ // Handle successful upload, e.g., log success or further processing
+ $this->myLogger->logme("error", 'Statement File moved successful');
} else {
- $this->myLogger->logme("error", 'Statement Upload failed Invalid file');
- return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'Invalid file'], 404);
+ $this->myLogger->logme("error", 'Statement File move failed');
+ return $this->respond(['dataStatus' => false, 'code' => 500, 'message' => 'File move failed'], 500);
}
+ } else {
+ $this->myLogger->logme("error", 'Statement Upload failed Invalid file');
+ return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'Invalid file'], 404);
+ }
- //process post variable entry in file table
- $loggedInUserID = get_session_userid();
- // dd($loggedInUserID);
- // $loggedInUserID = 8;
+ //process post variable entry in file table
+ $loggedInUserID = get_session_userid();
+ // dd($loggedInUserID);
+ // $loggedInUserID = 8;
- $insurer = $this->request->getPost('insurer');
+ $insurer = $this->request->getPost('insurer');
- $insurer_id = explode('-', $insurer)[0];
- $branch_id = explode('-', $insurer)[1];
- // print_r($insurer_id);
- // print_r($branch_id);
- // die();
- $month = $this->request->getPost('statement_month');
- $month = $month.'-01';
- // print_r($month);die;
- $month = change_date_format($month,'Y-M-d','Y-m-d');
- $stmt_sno = $this->request->getPost('statement_no');
- // print_r($month);die;
+ $insurer_id = explode('-', $insurer)[0];
+ $branch_id = explode('-', $insurer)[1];
+ // print_r($insurer_id);
+ // print_r($branch_id);
+ // die();
+ $month = $this->request->getPost('statement_month');
+ $month = $month . '-01';
+ // print_r($month);die;
+ $month = change_date_format($month, 'Y-M-d', 'Y-m-d');
+ $stmt_sno = $this->request->getPost('statement_no');
+ // print_r($month);die;
- $file_id = $this->insurerStatements->insert(['insurer_id' => $insurer_id, 'branch_id' => $branch_id, 'file_name' => $filename,'month' => $month, 'created_by' => $loggedInUserID,'stmt_sno' => $stmt_sno]); //here field policy_id have client_policy_id and not policy id from policy master
- $this->myLogger->logme("error", '{file_id} statement uploaded success', ['file_id' => $file_id]);
+ $file_id = $this->insurerStatements->insert(['insurer_id' => $insurer_id, 'branch_id' => $branch_id, 'file_name' => $filename, 'month' => $month, 'created_by' => $loggedInUserID, 'stmt_sno' => $stmt_sno]); //here field policy_id have client_policy_id and not policy id from policy master
+ $this->myLogger->logme("error", '{file_id} statement uploaded success', ['file_id' => $file_id]);
- //validate file
- $validation_result = $this->validateInsurerStatement(['file_id' => $file_id]);
- //update file content to DB
- if($validation_result['status'] )
- {
- $this->updateInsurerStatement(['file_id' => $file_id]);
- }
-
- if (!isset($file_id) || !$validation_result['status']) {
- return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'file not uploaded', 'error_data' => $validation_result['error_data'],'error_code' => $validation_result['error_code']], 200);
- }
+ //validate file
+ $validation_result = $this->validateInsurerStatement(['file_id' => $file_id]);
+ //update file content to DB
+ if ($validation_result['status']) {
+ $this->updateInsurerStatement(['file_id' => $file_id]);
+ }
- if (isset($file_id) || $validation_result['status']) {
- $this->insurerStatements->where('id', $file_id)->set(['invoice_status' => 'pending'])->update();
- }
+ if (!isset($file_id) || !$validation_result['status']) {
+ return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'file not uploaded', 'error_data' => $validation_result['error_data'], 'error_code' => $validation_result['error_code']], 200);
+ }
+
+ if (isset($file_id) || $validation_result['status']) {
+ $this->insurerStatements->where('id', $file_id)->set(['invoice_status' => 'pending'])->update();
+ }
- return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => 'file upload success'], 200);
+ return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => 'file upload success'], 200);
}
public function createStatementFolder()
@@ -2116,23 +2203,20 @@ class PolicyTransactionController extends BaseController
$folderPath = WRITEPATH . 'uploads/statements/';
// Check if the folder doesn't exist
- if (!file_exists($folderPath))
- {
+ if (!file_exists($folderPath)) {
// Create the folder
if (mkdir($folderPath, 0777, true)) {
- $this->myLogger->logme('error','statement upload folder created successfully');
-
+ $this->myLogger->logme('error', 'statement upload folder created successfully');
+
// Set permissions to a+rwx (read, write, execute for all)
chmod($folderPath, 0777);
- $this->myLogger->logme('error','Permissions set to a+rwx.');
+ $this->myLogger->logme('error', 'Permissions set to a+rwx.');
} else {
// echo "Failed to create folder.";
- $this->myLogger->logme('error','Failed to create statement upload folder.');
+ $this->myLogger->logme('error', 'Failed to create statement upload folder.');
}
- }
- else
- {
- $this->myLogger->logme('error','upload folder exists.');
+ } else {
+ $this->myLogger->logme('error', 'upload folder exists.');
}
}
@@ -2144,37 +2228,35 @@ class PolicyTransactionController extends BaseController
$file = $this->insurerStatements->find($file_id);
// dd($file);
$date = new \DateTime($file['month']);
-
- $month = $date->format('m');
+
+ $month = $date->format('m');
$year = $date->format('Y');
- $error_data = ['error_code' => '','error_data' => []];
+ $error_data = ['error_code' => '', 'error_data' => []];
$status = 'success';
$ret_status = true;
// dd($month.'-'.$year);
$return = [];
- if(!isset($file))
- {
+ if (!isset($file)) {
//file not found in DB
return array('status' => false, 'msg' => 'statement file not found in DB');
}
- $file_name_with_path = WRITEPATH."/uploads/statements/".$file['file_name'];
-
+ $file_name_with_path = WRITEPATH . "/uploads/statements/" . $file['file_name'];
+
//check physical file
- if(!file_exists($file_name_with_path))
- {
+ if (!file_exists($file_name_with_path)) {
//file not found update status and reason
$message = "Physcial file not found";
// echo $message;
- $this->myLogger->logme('error',($message . ' for statement file id ' . $file_id));
- $this->insurerStatements->where('id', $file_id)->set(['file_status' => 'failed','reason' => json_encode(['error_code' => 0,'error_data' => $message])])->update();
+ $this->myLogger->logme('error', ($message . ' for statement file id ' . $file_id));
+ $this->insurerStatements->where('id', $file_id)->set(['file_status' => 'failed', 'reason' => json_encode(['error_code' => 0, 'error_data' => $message])])->update();
return array('status' => false, 'error_code' => 0); //0 - Physcial file not found
}
//get excel data to php array
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
$sheet = $spreadsheet->getActiveSheet();
-
+
$highestRowAndColumn = $sheet->getHighestRowAndColumn();
// dd($highestRowAndColumn);
$excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
@@ -2183,33 +2265,29 @@ class PolicyTransactionController extends BaseController
//get no of line items and update in DB
$line_items = 0;
// get uploaded month transactions data
- $source_data = $this->PTCOShareDetailsModel->getNonReconcileredPolicyTransactions(insurer_id:$file['insurer_id'],insurer_branch_id:$file['branch_id']);
+ $source_data = $this->PTCOShareDetailsModel->getNonReconcileredPolicyTransactions(insurer_id: $file['insurer_id'], insurer_branch_id: $file['branch_id']);
// var_dump($source_data);die();
// Kint::dump($source_data);//die();
-
+
// check policy no,insurer and etc in DB for this month
// if all good return true, otherwise return false with messssage
- foreach ($excel_data as $excel_key => $excel_row)
- {
+ foreach ($excel_data as $excel_key => $excel_row) {
$is_row_empty = check_row_is_empty_or_null($excel_row);
- if(!$is_row_empty)
- {
+ if (!$is_row_empty) {
// $excel_row = ExcelSanitizeHelper::sanitizeArrayData($excel_row);
$is_source_found = 0;
- $policy_start_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[4]);//policy_start_date from excel
- $policy_end_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[5]);//policy_end_date from excel
- $policy_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[1]);//policy_end_date from excel
- $policy_no = preg_replace('/[\x{200C}\x{200B}]/u', '', $excel_row[1]);//policy_end_date from excel
- $client_name = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[3]);//clientname from excel
- $endorsement_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[2]);//policy_end_date from excel
+ $policy_start_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[4]); //policy_start_date from excel
+ $policy_end_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[5]); //policy_end_date from excel
+ $policy_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[1]); //policy_end_date from excel
+ $policy_no = preg_replace('/[\x{200C}\x{200B}]/u', '', $excel_row[1]); //policy_end_date from excel
+ $client_name = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[3]); //clientname from excel
+ $endorsement_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[2]); //policy_end_date from excel
// Kint::dump($policy_no);
- foreach ($source_data as $source_key => $source_row)
- {
+ foreach ($source_data as $source_key => $source_row) {
$source_endorsement_no = $source_row['endorsement_no'] !== null ? $source_row['endorsement_no'] : null;
// Kint::dump($source_endorsement_no);
- if( ($policy_no == $source_row['policy_no']) && $endorsement_no == $source_endorsement_no && change_date_format($policy_start_date,'d-m-Y','Y-m-d') == $source_row['policy_start_date'] && change_date_format($policy_end_date,'d-m-Y','Y-m-d') == $source_row['policy_end_date'] && $client_name == $source_row['client_name'])
- {
+ if (($policy_no == $source_row['policy_no']) && $endorsement_no == $source_endorsement_no && change_date_format($policy_start_date, 'd-m-Y', 'Y-m-d') == $source_row['policy_start_date'] && change_date_format($policy_end_date, 'd-m-Y', 'Y-m-d') == $source_row['policy_end_date'] && $client_name == $source_row['client_name']) {
$is_source_found = 1;
$line_items = $line_items + 1;
unset($source_data[$source_key]);
@@ -2217,27 +2295,24 @@ class PolicyTransactionController extends BaseController
}
}
- if($is_source_found == 0)
- {
+ if ($is_source_found == 0) {
// echo $excel_key.'-'.$excel_row[1] . '- not found ';
- $error_data['error_code'] = 1;//match not found
+ $error_data['error_code'] = 1; //match not found
// $error_data['error_data'] = ($error_data['error_data'] ?? []);
- $error_data['error_data'] = array_merge($error_data['error_data'],[$excel_row[0]]);//match not found
+ $error_data['error_data'] = array_merge($error_data['error_data'], [$excel_row[0]]); //match not found
}
-
}
}
// dd($error_data);
- if($error_data['error_code'])
- {
- $status = 'failed';
- $ret_status = false;
+ if ($error_data['error_code']) {
+ $status = 'failed';
+ $ret_status = false;
}
- //update in DB
- $this->insurerStatements->where('id', $file_id)->set(['line_items' => $line_items,'file_status' => $status,'reason' => json_encode($error_data)])->update();
- return array('status' => $ret_status, 'error_code' => $error_data['error_code'],'error_data' => $error_data['error_data']);
+ //update in DB
+ $this->insurerStatements->where('id', $file_id)->set(['line_items' => $line_items, 'file_status' => $status, 'reason' => json_encode($error_data)])->update();
+ return array('status' => $ret_status, 'error_code' => $error_data['error_code'], 'error_data' => $error_data['error_data']);
}
@@ -2249,37 +2324,35 @@ class PolicyTransactionController extends BaseController
$file = $this->insurerStatements->find($file_id);
// dd($file);
$date = new \DateTime($file['month']);
-
- $month = $date->format('m');
+
+ $month = $date->format('m');
$year = $date->format('Y');
- $error_data = ['error_code' => '','error_data' => []];
+ $error_data = ['error_code' => '', 'error_data' => []];
$status = 'success';
$ret_status = true;
// dd($month.'-'.$year);
$return = [];
- if(!isset($file))
- {
+ if (!isset($file)) {
//file not found in DB
return array('status' => false, 'msg' => 'statement file not found in DB');
}
- $file_name_with_path = WRITEPATH."/uploads/statements/".$file['file_name'];
-
+ $file_name_with_path = WRITEPATH . "/uploads/statements/" . $file['file_name'];
+
//check physical file
- if(!file_exists($file_name_with_path))
- {
+ if (!file_exists($file_name_with_path)) {
//file not found update status and reason
$message = "Physcial file not found";
// echo $message;
- $this->myLogger->logme('error',($message . ' for statement file id ' . $file_id));
- $this->insurerStatements->where('id', $file_id)->set(['file_status' => 'failed','reason' => json_encode(['error_code' => 0,'error_data' => $message])])->update();
+ $this->myLogger->logme('error', ($message . ' for statement file id ' . $file_id));
+ $this->insurerStatements->where('id', $file_id)->set(['file_status' => 'failed', 'reason' => json_encode(['error_code' => 0, 'error_data' => $message])])->update();
return array('status' => false, 'error_code' => 0); //0 - Physcial file not found
}
//get excel data to php array
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
$sheet = $spreadsheet->getActiveSheet();
-
+
$highestRowAndColumn = $sheet->getHighestRowAndColumn();
// dd($highestRowAndColumn);
$excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
@@ -2288,33 +2361,29 @@ class PolicyTransactionController extends BaseController
//get no of line items and update in DB
$line_items = count($excel_data);
// get uploaded month transactions data
- $source_data = $this->PTCOShareDetailsModel->getNonReconcileredPolicyTransactions(insurer_id:$file['insurer_id'],insurer_branch_id:$file['branch_id']);
+ $source_data = $this->PTCOShareDetailsModel->getNonReconcileredPolicyTransactions(insurer_id: $file['insurer_id'], insurer_branch_id: $file['branch_id']);
// Kint::dump($source_data);//die;
// Kint::dump($excel_data);
// die;
// check policy no,insurer and etc in DB for this month
// if all good return true, otherwise return false with messssage
$data_to_update = [];
- foreach ($excel_data as $excel_key => $excel_row)
- {
+ foreach ($excel_data as $excel_key => $excel_row) {
$is_row_empty = check_row_is_empty_or_null($excel_row);
- if(!$is_row_empty)
- {
-
+ if (!$is_row_empty) {
+
$is_source_found = 0;
- $policy_start_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[4]);//policy_start_date from excel
- $policy_end_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[5]);//policy_end_date from excel
- $policy_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[1]);//policy_end_date from excel
- $policy_no = preg_replace('/[\x{200C}\x{200B}]/u', '', $excel_row[1]);//
- $client_name = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[3]);//clientname from excel
- $endorsement_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[2]);//policy_end_date from excel
-
- foreach ($source_data as $source_key => $source_row)
- {
+ $policy_start_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[4]); //policy_start_date from excel
+ $policy_end_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[5]); //policy_end_date from excel
+ $policy_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[1]); //policy_end_date from excel
+ $policy_no = preg_replace('/[\x{200C}\x{200B}]/u', '', $excel_row[1]); //
+ $client_name = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[3]); //clientname from excel
+ $endorsement_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[2]); //policy_end_date from excel
+
+ foreach ($source_data as $source_key => $source_row) {
// Kint::dump(change_date_format($excel_row[3],'d-m-Y','Y-m-d'));
$source_endorsement_no = $source_row['endorsement_no'] !== null ? $source_row['endorsement_no'] : null;
- if( ($policy_no == $source_row['policy_no']) && $endorsement_no == $source_endorsement_no && change_date_format($policy_start_date,'d-m-Y','Y-m-d') == $source_row['policy_start_date'] && change_date_format($policy_end_date,'d-m-Y','Y-m-d') == $source_row['policy_end_date'] && $client_name == $source_row['client_name'])
- {
+ if (($policy_no == $source_row['policy_no']) && $endorsement_no == $source_endorsement_no && change_date_format($policy_start_date, 'd-m-Y', 'Y-m-d') == $source_row['policy_start_date'] && change_date_format($policy_end_date, 'd-m-Y', 'Y-m-d') == $source_row['policy_end_date'] && $client_name == $source_row['client_name']) {
$is_source_found = 1;
//calculate percentage first
@@ -2324,18 +2393,13 @@ class PolicyTransactionController extends BaseController
$actual_bp_brokerage = trim($excel_row[12]);
$actual_bp_amt = trim($excel_row[6]);
- if(($actual_bp_brokerage && $actual_bp_brokerage != 0 && $actual_bp_brokerage != ""))
- {
+ if (($actual_bp_brokerage && $actual_bp_brokerage != 0 && $actual_bp_brokerage != "")) {
$total_amt += $actual_bp_brokerage;
//percentage reverse calculation
- if($actual_bp_per == 0 || $actual_bp_per == "")
- {
- $actual_bp_per = round(($actual_bp_brokerage / $actual_bp_amt) * 100,2);
+ if (($actual_bp_per == 0 || $actual_bp_per == 0) && !empty($actual_bp_amt)) {
+ $actual_bp_per = round(($actual_bp_brokerage / $actual_bp_amt) * 100, 2);
}
-
- }
- else
- {
+ } else {
$actual_bp_brokerage = $actual_bp_amt * ($actual_bp_per / 100);
$total_amt += $actual_bp_brokerage;
}
@@ -2344,17 +2408,13 @@ class PolicyTransactionController extends BaseController
$actual_tp_brokerage = trim($excel_row[13]);
$actual_tp_amt = trim($excel_row[7]);
- if($actual_tp_brokerage && $actual_tp_brokerage != 0 && $actual_tp_brokerage != "")
- {
+ if ($actual_tp_brokerage && $actual_tp_brokerage != 0 && $actual_tp_brokerage != "") {
$total_amt += $actual_tp_brokerage;
//percentage reverse calculation
- if($actual_tp_per == 0 || $actual_tp_per == "")
- {
+ if (($actual_tp_per == 0 || $actual_tp_per == "") && !empty($actual_tp_amt)) {
$actual_tp_per = ($actual_tp_brokerage / $actual_tp_amt) * 100;
}
- }
- else
- {
+ } else {
$actual_tp_brokerage = $actual_tp_amt * ($actual_tp_per / 100);
$total_amt += $actual_tp_brokerage;
}
@@ -2363,17 +2423,13 @@ class PolicyTransactionController extends BaseController
$actual_tep_brokerage = trim($excel_row[14]);
$actual_tep_amt = trim($excel_row[8]);
- if($actual_tep_brokerage && $actual_tep_brokerage != 0 && $actual_tep_brokerage != "")
- {
+ if ($actual_tep_brokerage && $actual_tep_brokerage != 0 && $actual_tep_brokerage != "") {
$total_amt += $actual_tep_brokerage;
//percentage reverse calculation
- if($actual_tep_per == 0 || $actual_tep_per == "")
- {
+ if (($actual_tep_per == 0 || $actual_tep_per == "") && !empty($actual_tep_amt)) {
$actual_tep_per = ($actual_tep_brokerage / $actual_tep_amt) * 100;
}
- }
- else
- {
+ } else {
$actual_tep_brokerage = $actual_tep_amt * ($actual_tep_per / 100);
$total_amt += $actual_tep_brokerage;
}
@@ -2381,13 +2437,12 @@ class PolicyTransactionController extends BaseController
//find variance
$variance_amt = $source_row['exp_amt'] - $total_amt;
- $data_to_update[] = ['co_share_id' => $source_row['id'],'actual_bp_amt' => $actual_bp_amt,'actual_tp_amt' => $actual_tp_amt,'actual_tep_amt' => $actual_tep_amt,'actual_bp_per' => $actual_bp_per,'actual_tp_per' => $actual_tp_per,'actual_tep_per' => $actual_tep_per,'variance' => $variance_amt,'actual_tep_brokerage_amt' => $actual_tep_brokerage,'actual_tp_brokerage_amt' => $actual_tp_brokerage,'actual_bp_brokerage_amt' => $actual_bp_brokerage,'reward' => trim($excel_row[15]),'statement_id' => $file_id];
+ $data_to_update[] = ['co_share_id' => $source_row['id'], 'actual_bp_amt' => $actual_bp_amt, 'actual_tp_amt' => $actual_tp_amt, 'actual_tep_amt' => $actual_tep_amt, 'actual_bp_per' => $actual_bp_per, 'actual_tp_per' => $actual_tp_per, 'actual_tep_per' => $actual_tep_per, 'variance' => $variance_amt, 'actual_tep_brokerage_amt' => $actual_tep_brokerage, 'actual_tp_brokerage_amt' => $actual_tp_brokerage, 'actual_bp_brokerage_amt' => $actual_bp_brokerage, 'reward' => trim($excel_row[15]), 'statement_id' => $file_id];
unset($source_data[$source_key]);
continue 2;
}
}
-
}
}
// dd($data_to_update);
@@ -2398,59 +2453,57 @@ class PolicyTransactionController extends BaseController
// $status = 'failed';
// $ret_status = false;
// }
- //update in DB
- $this->insurerStatements->where('id', $file_id)->set(['file_status' => $status,'reason' => json_encode($error_data),'invoice_status' =>'pending'])->update();
- return array('status' => $ret_status, 'error_code' => $error_data['error_code'],'error_data' => $error_data['error_data']);
+ //update in DB
+ $this->insurerStatements->where('id', $file_id)->set(['file_status' => $status, 'reason' => json_encode($error_data), 'invoice_status' => 'pending'])->update();
+ return array('status' => $ret_status, 'error_code' => $error_data['error_code'], 'error_data' => $error_data['error_data']);
}
public function getInvoicePaymentDetails()
{
- $statement_id = $this->request->getUri()->getSegment(4);
-
- $inv_details = $this->insurerStatements->find($statement_id);
- $inv_payment_details = $this->invPaymentDetailsModel
- ->where('statement_id',$statement_id)
- ->where('is_active',1)
- ->get()
- ->getResultArray();
- if(!$inv_details['invoice_value'])
- {
+ $statement_id = $this->request->getUri()->getSegment(4);
+
+ $inv_details = $this->insurerStatements->find($statement_id);
+ $inv_payment_details = $this->invPaymentDetailsModel
+ ->where('statement_id', $statement_id)
+ ->where('is_active', 1)
+ ->get()
+ ->getResultArray();
+ if (!$inv_details['invoice_value']) {
$stmt_level_value = $this->coShareStmtDetailsModel->select('sum(actual_tep_brokerage_amt) + sum(actual_tp_brokerage_amt) + sum(actual_bp_brokerage_amt) + sum(reward) as invoice_value')
- ->where('statement_id',$statement_id)
- ->groupBy('statement_id')
- ->get()
- ->getResultArray();
- // print_r($stmt_level_value);
- if($stmt_level_value && count($stmt_level_value) && isset($stmt_level_value[0]))
- {
+ ->where('statement_id', $statement_id)
+ ->groupBy('statement_id')
+ ->get()
+ ->getResultArray();
+ // print_r($stmt_level_value);
+ if ($stmt_level_value && count($stmt_level_value) && isset($stmt_level_value[0])) {
$inv_details['invoice_value'] = $stmt_level_value[0]['invoice_value'];
}
}
- // ~dd($inv_details);
- $data = [ 'invoice_status' => $inv_details['invoice_status'],
- 'gst_per' => isset($inv_details['gst_per']) ? $inv_details['gst_per'] : 18 ,
- 'invoice_value' => $inv_details['invoice_value'],
- 'gst_value' => $inv_details['gst_value'],
- 'invoice_no' => $inv_details['invoice_no'],
- 'invoice_amount' => $inv_details['invoice_amount'],
- 'invoice_date' => isset($inv_details['invoice_date']) ? change_date_format($inv_details['invoice_date'],'Y-m-d','d/m/Y') : null ];
+ // ~dd($inv_details);
+ $data = [
+ 'invoice_status' => $inv_details['invoice_status'],
+ 'gst_per' => isset($inv_details['gst_per']) ? $inv_details['gst_per'] : 18,
+ 'invoice_value' => $inv_details['invoice_value'],
+ 'gst_value' => $inv_details['gst_value'],
+ 'invoice_no' => $inv_details['invoice_no'],
+ 'invoice_amount' => $inv_details['invoice_amount'],
+ 'invoice_date' => isset($inv_details['invoice_date']) ? change_date_format($inv_details['invoice_date'], 'Y-m-d', 'd/m/Y') : null
+ ];
$data['payments'] = $inv_payment_details;
return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $data], 200);
-
-
}
public function saveInvoicePaymentDetails()
{
- $jsonData = $this->request->getJSON();
- $jsonData = (array)$jsonData;
- // echo 'Hi';
- // print_r($jsonData);die();
+ $jsonData = $this->request->getJSON();
+ $jsonData = (array)$jsonData;
+ // echo 'Hi';
+ // print_r($jsonData);die();
$invoiceStatus = $jsonData['invoice_status'];
$hiddenStatementId = $jsonData['hidden_statement_id'];
$invoiceNo = $jsonData['invoice_no'];
- $invoiceDate = change_date_format($jsonData['invoice_date'],'d/m/Y','Y-m-d');
+ $invoiceDate = change_date_format($jsonData['invoice_date'], 'd/m/Y', 'Y-m-d');
$invoice_amount = $jsonData['invoice_amount'];
$invoice_value = $jsonData['invoice_value'];
$gst_per = $jsonData['invoice_gst_per'];
@@ -2468,10 +2521,10 @@ class PolicyTransactionController extends BaseController
'updated_by' => get_session_userid()
];
-
+
$this->insurerStatements->update($hiddenStatementId, $parentData);
-
+
// Process child data
$receivedAmounts = $jsonData['received_amount'];
$utrNos = $jsonData['utr_no'];
@@ -2493,19 +2546,20 @@ class PolicyTransactionController extends BaseController
'utr_no' => $utrNo,
'tds' => $tds,
'gst' => $gst,
- 'received_date' => change_date_format($paymentDate,'d/m/Y','Y-m-d'),
+ 'received_date' => change_date_format($paymentDate, 'd/m/Y', 'Y-m-d'),
'statement_id' => $hiddenStatementId
];
- if($pk){
- $childData['updated_by'] = get_session_userid();
- $childData['id'] = (int)$pk;
+ if ($pk) {
+ $childData['updated_by'] = get_session_userid();
+ $childData['id'] = (int)$pk;
+ } else {
+ $childData['created_by'] = get_session_userid();
}
- else { $childData['created_by'] = get_session_userid(); }
// print_r($childData);
// Insert or update
$this->invPaymentDetailsModel->save($childData);
// print_r($this->invPaymentDetailsModel->errors());
-
+
}
return $this->respond(['dataStatus' => true, 'code' => 200], 200);
@@ -2522,7 +2576,7 @@ class PolicyTransactionController extends BaseController
public function downloadSampleInsurerStatement()
{
-
+
$filePath = ROOTPATH . 'public/sample_excel/insurer_stament_sample.xlsx';
// Check if the file exists
if (file_exists($filePath)) {
@@ -2542,14 +2596,13 @@ class PolicyTransactionController extends BaseController
{
$file_id = $this->request->getUri()->getSegment(4);
$file = $this->insurerStatements->find($file_id);
- return $this->respond(['dataStatus' => true, 'code' => 200,'data' => $file['reason']], 200);
+ return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $file['reason']], 200);
}
public function dmsSearch()
{
- // echo 'scbsc';die();
- if ($this->request->getMethod() == 'post')
- {
+ // echo 'scbsc';die();
+ if ($this->request->is('post')) {
// $jsonData = (array)$this->request->getJSON();
$customer_id = $this->request->getPost('customer_id');
$policy_id = $this->request->getPost('policy_id');
@@ -2560,37 +2613,33 @@ class PolicyTransactionController extends BaseController
$batch_files = [];
$files = [];
// print_r($jsonData);die();
- if($policy_id != "")
- {
+ if ($policy_id != "") {
//get policy docs from policy transation related tables
- $pt_files = $this->PTFileModel->getPolicyDriveFilesIndex($policy_id,$policy_doc_name);
- $batch_files = $this->batchFileModel->getBatchFilesDataForDocumentSearch($policy_id,$policy_doc_name);
- $files = $this->filesModel->getFilesDataForDocumentSearch($policy_id,$policy_doc_name);
+ $pt_files = $this->PTFileModel->getPolicyDriveFilesIndex($policy_id, $policy_doc_name);
+ $batch_files = $this->batchFileModel->getBatchFilesDataForDocumentSearch($policy_id, $policy_doc_name);
+ $files = $this->filesModel->getFilesDataForDocumentSearch($policy_id, $policy_doc_name);
// dd($files);
// dd($this->PTFileModel->getLastQuery());
// ~dd($pt_files);
}
- if($customer_id != "")
- {
- $kyc_files = $this->clientKYCDocsModel->getClientKYCDriveFilesIndex($customer_id,$cus_doc_name);
+ if ($customer_id != "") {
+ $kyc_files = $this->clientKYCDocsModel->getClientKYCDriveFilesIndex($customer_id, $cus_doc_name);
// dd($this->clientKYCDocsModel->getLastQuery());
// !dd($kyc_files);
}
- $data['files'] = array_merge($pt_files,$kyc_files,$batch_files,$files);
- // dd($data['files']);
+ $data['files'] = array_merge($pt_files, $kyc_files, $batch_files, $files);
+ // dd($data['files']);
}
$data['page_name'] = 'Documents Search';
- $data['customers'] = $this->clientModel->select('id,client_name,short_name as display_value')->where('is_active',1)->get()->getResultarray();
+ $data['customers'] = $this->clientModel->select('id,client_name,short_name as display_value')->where('is_active', 1)->get()->getResultarray();
$data['policies'] = $this->clientPolicyModel->select("client_policy.id,client_policy.policy_no,policy_type.policy_type,concat(policy_type.policy_type,' - ',client_policy.policy_no) as display_value")
- ->join('policy_type','client_policy.policy_type_id = policy_type.id')
- ->where('client_policy.is_active',1)->get()->getResultarray();
- // dd($data);
+ ->join('policy_type', 'client_policy.policy_type_id = policy_type.id')
+ ->where('client_policy.is_active', 1)->get()->getResultarray();
+ // dd($data);
$this->loadLayout('dms_search', $data);
-
-
}
//---------------------------------------------------------------------------------------------------
@@ -2650,7 +2699,7 @@ class PolicyTransactionController extends BaseController
], 200);
}
}
-
+
public function getClientPolicyDataBasedOnClientAndInsuer()
{
@@ -2661,14 +2710,14 @@ class PolicyTransactionController extends BaseController
$policy_type_id = $this->request->getGet('policy_type_id') ?? 0;
$builder = db_connect()->table("client_policy")
- ->select("
+ ->select("
client_policy.*,
policy_type.policy_type,
")
- ->join('policy_type', 'client_policy.policy_type_id = policy_type.id')
- ->where([
- 'client_policy.is_active' => 1,
- ]);
+ ->join('policy_type', 'client_policy.policy_type_id = policy_type.id')
+ ->where([
+ 'client_policy.is_active' => 1,
+ ]);
if (!empty($client_id)) {
$builder->where('client_policy.client_id', $client_id);
@@ -2689,22 +2738,22 @@ class PolicyTransactionController extends BaseController
$result = $builder->get()->getResultArray();
if ($result) {
- return $this->respond(['status' => true,'code' => 200,'data' => $result, 'getData' => $this->request->getGet()], 200);
+ return $this->respond(['status' => true, 'code' => 200, 'data' => $result, 'getData' => $this->request->getGet()], 200);
} else {
- return $this->respond(['status' => false,'code' => 400,'message' => 'No data found'], 200);
+ return $this->respond(['status' => false, 'code' => 400, 'message' => 'No data found'], 200);
}
}
-
+
public function checkCDAmountForBasePremium()
{
$base_premium = $this->request->getGet('base_premium') ?? 0;
$cd_ac_no = $this->request->getGet('cd_ac_no') ?? 0;
-
+
// Validate inputs
if (empty($cd_ac_no)) {
return $this->respond(['status' => false, 'code' => 400, 'message' => 'CD Account Number is required'], 200);
}
-
+
// Build query
$db = db_connect();
$builder = $db->table("cash_deposit")
@@ -2712,13 +2761,13 @@ class PolicyTransactionController extends BaseController
->where('is_active', 1)
->orderBy('id', 'desc')
->limit(1);
-
+
$result = $builder->get()->getRowArray();
-
+
if ($result) {
// Check if base premium exceeds balance
$base_premium_greater_than_balance = $base_premium > $result['balance'];
-
+
return $this->respond([
'status' => true,
'code' => 200,
@@ -2728,48 +2777,234 @@ class PolicyTransactionController extends BaseController
'base_premium_greater_than_balance' => $base_premium_greater_than_balance,
], 200);
}
-
+
return $this->respond(['status' => false, 'code' => 400, 'message' => 'No data found for this CD'], 200);
}
- public function getInsurerStatementMonth()
+ public function getInsurerStatementMonth()
{
$insurer_id = $this->request->getGet('insurer_id');
$month = $this->request->getGet('month');
// echo $month;
- $insurer_branch_id = explode('-',$insurer_id)[1];
- $insurer_id = explode('-',$insurer_id)[0];
- $month = $month.'-01';
- $month = change_date_format($month,'Y-M-d','Y-m-d');
+ $insurer_branch_id = explode('-', $insurer_id)[1];
+ $insurer_id = explode('-', $insurer_id)[0];
+ $month = $month . '-01';
+ $month = change_date_format($month, 'Y-M-d', 'Y-m-d');
// echo $month;
$res_data = $this->insurerStatements
- ->where('insurer_id',$insurer_id)
- ->where('branch_id',$insurer_branch_id)
- ->where('month', $month)
- ->where('is_active', 1)
- ->where('file_status', 'success')
- ->findAll();
-
- return $this->respond(['dataStatus' => true, 'code' => 200,'data' => $res_data], 200);
-
+ ->where('insurer_id', $insurer_id)
+ ->where('branch_id', $insurer_branch_id)
+ ->where('month', $month)
+ ->where('is_active', 1)
+ ->where('file_status', 'success')
+ ->findAll();
+ return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $res_data], 200);
}
public function deleteStatement($id)
{
// echo $id;die();
- $this->coShareStmtDetailsModel->where('statement_id',$id)
- ->set(['is_active' => 0])
- ->update();
- $this->invPaymentDetailsModel->where('statement_id',$id)
- ->set(['is_active' => 0])
- ->update();
- $this->insurerStatements->where('id',$id)
- ->set(['is_active' => 0])
- ->update();
+ $this->coShareStmtDetailsModel->where('statement_id', $id)
+ ->set(['is_active' => 0])
+ ->update();
+ $this->invPaymentDetailsModel->where('statement_id', $id)
+ ->set(['is_active' => 0])
+ ->update();
+ $this->insurerStatements->where('id', $id)
+ ->set(['is_active' => 0])
+ ->update();
return $this->respond(['dataStatus' => true, 'code' => 200], 200);
}
-
-
-}
\ No newline at end of file
+
+ public function sendInstallmentRemainderMail()
+ {
+
+ $this->myLogger->logme("error", "Cron Job For Send Installment Remainder Mail Started");
+
+ try {
+
+ try {
+
+ $bdsInstallmentData = $this->BdsPlacementModel->getClientInstallmentDetails();
+ } catch (Exception $e) {
+
+ $this->myLogger->logme('error', 'Exception: ' . $e->getMessage() . 'Page: ' . $e->getFile() . ' Line: ' . $e->getLine());
+ }
+ $this->myLogger->logme("error", "Data for BDS Installment " . json_encode($bdsInstallmentData));
+ // dd($bdsInstallmentData);
+
+ if (empty($bdsInstallmentData)) {
+
+ $this->myLogger->logme("error", "No Client Installment is Due in the 15th Day");
+
+ return false;
+ }
+
+ foreach ($bdsInstallmentData as $installmentData) {
+
+ $mailData = $this->PrepareBDSMailData($installmentData);
+ $to_mail = $mailData['to_mail'];
+ $message = $mailData['message'];
+ $subject = $mailData['subject'];
+
+ $this->myLogger->logme("error", "Installment Pending for" . $subject);
+
+ $common = ['mail_type' => 'installment_amount_due_remainder_mail'];
+
+ $res = MailHelper::send_email(['mail' => $to_mail, 'subject' => $subject, 'message' => $message, 'common' => $common]);
+
+ $res = json_decode($res);
+ $this->myLogger->logme('error', 'res: ' . json_encode($res));
+
+ if ($res->status == 'success') {
+ return true;
+ } else {
+ return false;
+ }
+ }
+ } catch (Exception $e) {
+
+ $this->myLogger->logme('error', 'Exception: ' . $e->getMessage() . 'Page: ' . $e->getFile() . ' Line: ' . $e->getLine());
+ }
+ }
+
+ protected function PrepareBDSMailData($data)
+ {
+
+ try {
+
+ $installment_amount = $data['installment_amount'];
+ $payment_date = date('d-m-Y', strtotime($data['payment_date']));
+ $client = $data['client_name'];
+ $branch = $data['branch_name'];
+ $sales_person_mail = $data['sales_person'];
+ $heads = $data['heads'];
+ $admins = $data['admins'];
+ $buisness_team = $data['buisness_team'];
+ $policy_no = $data['policy_no'];
+ $client_short_name = isset($data['short_name']) && $data['short_name'] != null ? $data['short_name'] : $data['client_name'];
+
+ $subject = "Installment Amount Due For Client - {$client_short_name} - Policy NO({$policy_no}) is Due On - {$payment_date}";
+
+ $message = "Policy Installment for Client - {$client}, Branch - {$branch} is Due on {$payment_date}
+ with amount of {$installment_amount}.
+ Policy No : {$policy_no}";
+
+
+ $to_mail = array_merge(
+ array_column($heads, 'email'),
+ array_column($admins, 'email'),
+ array_column($buisness_team, 'email'),
+ [$sales_person_mail]
+ );
+
+ $to_mail = array_unique($to_mail);
+
+ $this->myLogger->logme("error", "Selected To Address : " . json_encode($to_mail));
+
+ // dd($to_mail);
+ return [
+ 'to_mail' => $to_mail,
+ 'message' => $message,
+ 'subject' => $subject
+ ];
+ } catch (Exception $e) {
+
+ $this->myLogger->logme('error', 'Exception: ' . $e->getMessage() . 'Page: ' . $e->getFile() . ' Line: ' . $e->getLine());
+ }
+ }
+
+ public function getMoreInfo()
+ {
+
+ $pt_id = $this->request->getPost("pt_id");
+ $data_to_send['bds_data'] = $this->BdsPlacementModel->where("is_active", 1)->where("pt_id", $pt_id)->findAll();
+
+ foreach ($data_to_send['bds_data'] as &$data) {
+
+ $data['payment_date'] = (new \DateTime($data['payment_date']))->format('d-m-Y');
+ }
+
+ if (!empty($data_to_send)) {
+
+ return $this->respond(['status' => true, "data" => $data_to_send], 200);
+ } else {
+
+ return $this->respond(['status' => false, "No Data Found For the Policy Transaction"], 404);
+ }
+ }
+
+ public function saveInstallment()
+ {
+
+ $installments = $this->request->getPost('installments');
+
+ if (!$installments || !is_array($installments)) {
+ return $this->respond(['status' => false, 'message' => 'No data received'], 400);
+ }
+
+ $this->myLogger->logme("error", json_encode($installments));
+ // die();
+
+ foreach ($installments as &$row) {
+ // Convert date from d-m-Y to Y-m-d
+ if (!empty($row['payment_date'])) {
+ $date = \DateTime::createFromFormat('d-m-Y', $row['payment_date']);
+ if ($date) {
+ $row['payment_date'] = $date->format('Y-m-d');
+ }
+ }
+ $this->BdsPlacementModel->save($row);
+ }
+
+ return $this->respond(['status' => true, 'message' => 'Data saved successfully'], 200);
+ }
+
+ protected function getPolicyForEndorsment()
+ {
+
+ $policyList = [];
+ $policyListByClient = [];
+
+
+ $clients = $this->clientModel
+ ->select("*, DATE_FORMAT(dob, '%d-%m-%Y') as dob")
+ ->where('is_active', 1)
+ ->findAll();
+
+ $clientIds = array_column($clients, 'id');
+
+ $policies = $this->clientPolicyModel
+ ->select("
+ client_policy.*,
+ policy_type.policy_type,
+ policy_type.ebp,
+ policy_type.etp,
+ policy_type.iep,
+ policy_type.itp,
+ policy_type.bap,
+ policy_type.allocg,
+ DATE_FORMAT(client_policy.policy_start_date, '%d/%m/%Y') as policy_start_date,
+ DATE_FORMAT(client_policy.policy_end_date, '%d/%m/%Y') as policy_end_date
+ ")
+ ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
+ ->join('policy_transaction pt', 'pt.client_policy_id = client_policy.id and pt.action_type = "inception" and pt.is_active = 1 and pt.client_policy_id is not null')
+ ->whereIn('client_policy.client_id', $clientIds)
+ ->where('client_policy.is_active', 1)
+ ->findAll();
+
+ foreach ($policies as $policy) {
+ $policyList[$policy['client_branch_id']][] = $policy;
+ $policyListByClient[$policy['client_id']][] = $policy;
+ if (isset($policyCount[$policy['client_id']])) {
+ $policyCount[$policy['client_id']]++;
+ } else {
+ $policyCount[$policy['client_id']] = 1;
+ }
+ }
+
+ return [$policyList, $policyListByClient];
+ }
+}
diff --git a/app/Controllers/RestAuthenticationController.php b/app/Controllers/RestAuthenticationController.php
index e82548c9..a31dabe7 100755
--- a/app/Controllers/RestAuthenticationController.php
+++ b/app/Controllers/RestAuthenticationController.php
@@ -84,7 +84,7 @@ class RestAuthenticationController extends AdminController
->where('employees.emp_status !=', 'truncated')
->where('employees.mobile', $mobile_number)
->where('EP.is_active', 1)
- ->whereIn('EP.status', ['active'])
+ ->whereIn('EP.status', ['active', 'expired'])
->first();
@@ -124,7 +124,7 @@ class RestAuthenticationController extends AdminController
->where('employees.emp_status !=', 'truncated')
->where('employees.email_corporate', $email)
->where('EP.is_active', 1)
- ->whereIn('EP.status', ['draft', 'enrolled'])
+ ->whereIn('EP.status', ['active', 'expired'])
->first();
if (isset($employeeData['employee_id'])) {
@@ -184,6 +184,47 @@ class RestAuthenticationController extends AdminController
}
+ public function updateEmpMPIN()
+ {
+ $requestData = $this->request->getJSON();
+ $mobile_number = $requestData->mobile_number ?? null;
+ $email_id = $requestData->email_id ?? null;
+ $new_mpin = $requestData->new_mpin ?? $requestData->mpin ?? null;
+ $old_mpin = $requestData->old_mpin ?? null;
+
+ if (!$new_mpin) {
+ return $this->response->setJSON(['status' => false, 'message' => 'MPIN is required.']);
+ }
+
+ $query = $this->employeeModel->where('relationship', 'self');
+
+ if ($mobile_number) {
+ $query->where('mobile', $mobile_number);
+ } elseif ($email_id) {
+ $query->where('email_corporate', $email_id);
+ } else {
+ return $this->response->setJSON(['status' => false, 'message' => 'Mobile number or Email ID is required.']);
+ }
+
+ if (!empty($old_mpin)) {
+ $query->where('mpin', $old_mpin);
+ }
+
+ // Fetch employee data
+ $employeeData = $query->first();
+
+ if (!$employeeData) {
+ return $this->response->setJSON(['status' => false, 'message' => 'Employee not found or invalid MPIN.']);
+ }
+
+ // Update MPIN
+ $updated = $this->employeeModel->update($employeeData['id'], ['mpin' => $new_mpin]);
+
+ return true;
+ }
+
+
+
public function getVerifiedUserData()
{
try {
@@ -521,15 +562,14 @@ class RestAuthenticationController extends AdminController
$mobile_number = isset($this->request->getJSON()->mobile_number) ? $this->request->getJSON()->mobile_number : null;
$email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null;
$mpin = $this->request->getJSON()->mpin;
-
if (isset($mobile_number))
{
$employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->first();
}else{
$employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('relationship', 'self')->first();
}
-
if ($employeeData && $mpin == $employeeData["mpin"]) {
+
$auth = HttpRequestHelper::getRequestInfo();
if ($auth) {
$data = [
@@ -547,6 +587,7 @@ class RestAuthenticationController extends AdminController
$result = JWTToken::encode($employeeData);
+ // $result = $employeeData;
return $this->respond(['status' => 'success','code' => 200,'data' => $result],200);
} else {
return $this->respond(['status' => 'failed','code' => 404,'data' => "Invalid OTP"],200);
@@ -561,7 +602,7 @@ class RestAuthenticationController extends AdminController
try {
$mobile_number = isset($this->request->getJSON()->mobile_number) ? $this->request->getJSON()->mobile_number : null;
$email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null;
- $mpin = $this->request->getJSON()->mpin;
+ // $mpin = $this->request->getJSON()->mpin;
if (isset($mobile_number))
{
@@ -585,5 +626,32 @@ class RestAuthenticationController extends AdminController
}
+ // TokenController.php
+ public function bookstackLoginToken()
+ {
+ $session = \Config\Services::session();
+ $user_data = session()->get('userData');
+ $user = $user_data->email;
+ $secret = getenv('bookstack.token');
+ // $user = 'staff@staff.com';
+ $name = $user_data->first_name ?? 'User';
+
+ $payload = [
+ 'email' => $user,
+ 'name' => $name,
+ 'exp' => time() + (60 * 60 * 24) // expires in 1 day
+ ];
+
+ // dd($payload);
+ $token = base64_encode(json_encode($payload));
+ $signature = hash_hmac('sha256', $token, $secret);
+ $bookStackUrl = getenv('bookstack.baseURL');
+
+ $url = $bookStackUrl . urlencode($token) . '&sig=' . $signature;
+ return redirect()->to($url);
+ }
+
+
+
}
\ No newline at end of file
diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php
index a7392860..1fafa208 100644
--- a/app/Controllers/TicketController.php
+++ b/app/Controllers/TicketController.php
@@ -54,6 +54,8 @@ class TicketController extends BaseController
public function __construct()
{
$this->myLogger = \Config\Services::mylogger();
+ set_session_context('Ticket Master Controller');
+
$this->ticketMasterModel = new TicketMasterModel();
@@ -120,6 +122,10 @@ class TicketController extends BaseController
'((POLICY_TYPE))' => 'policy_type',
'((AUTO_QUERY_CONTENT))' => 'auto_query_content',
'((CLAIM_FORM_LINK))' => 'claim_form_link',
+ '((CLAIM_FEEDBACK_FORM))' => 'claim_feedback_form',
+ '((SETTLED_LETTER))' => 'settle_letter',
+ '((APPROVED_LETTER))' => 'approved_letter',
+ '((APPROVED_DESCRIBTION))' => 'approved_description',
];
$this->extraFields = [
1 => ['non_id_reason'],
@@ -129,13 +135,13 @@ class TicketController extends BaseController
5 => ['claim_number', 'registration_date'],
7 => ['query_received_date'],
8 => ['denial_reason','denial_date'],
- 9 => ['approved_amount','approved_date', 'approved_letter'],
+ 9 => ['approved_amount','approved_date', 'approved_letter', "approved_description"],
11 => ['utr_details', 'settled_date', 'settle_letter'],
- 40 => ['approved_amount','approved_date', 'approved_letter'],
+ 40 => ['approved_amount','approved_date', 'approved_letter', "approved_description"],
44 => ['utr_details', 'settled_date', 'settle_letter'],
- 30 => ['approved_amount','approved_date', 'approved_letter'],
+ 30 => ['approved_amount','approved_date', 'approved_letter', "approved_description"],
34 => ['utr_details', 'settled_date', 'settle_letter'],
- 20 => ['approved_amount','approved_date', 'approved_letter'],
+ 20 => ['approved_amount','approved_date', 'approved_letter', "approved_description"],
24 => ['utr_details', 'settled_date', 'settle_letter'],
14 => ['return_remark', 'awb_no_courier_name'],
48 => ['return_remark', 'awb_no_courier_name'],
@@ -170,6 +176,9 @@ class TicketController extends BaseController
public function ticketList()
{
$data['ticket_type'] = $this->ticketType;
+ $data['modeOFIntimate'] = $this->modeOFIntimate;
+ $data['priorityType'] = $this->priorityType;
+ $data['claimType'] = $this->claimType;
if ($this->request->is('get')) {
$data['page_name'] = "Claims";
$data['claim_status'] = $this->claimStatus->select('id,ticket_type,claim_status')->where('is_active', 1)->findAll();
@@ -178,49 +187,76 @@ class TicketController extends BaseController
return $this->loadLayout('ticket_search', $data);
} else {
- $data['ticket_data'] = $this->ticketSearch();
- $html = view('ticket_list', $data);
- return $this->respond(['status' => true, 'html' => $html], 200);
+ $isFromDashboard = $this->request->getPost("is_dashboard");
+ log_message('error', 'Is From Dashboard: ' . $isFromDashboard);
+
+ if (isset($isFromDashboard) && !empty($isFromDashboard)){
+ $data['page_name'] = "Claims";
+ if ($isFromDashboard == 1) {
+
+ $data['ticket_data'] = $this->ticketSearch(3);
+
+ }else if ($isFromDashboard == 2){
+ $data['ticket_data'] = $this->ticketSearch(4);
+
+ }else if ($isFromDashboard == 3){
+ $data['ticket_data'] = $this->ticketSearch(2);
+
+ }else if ($isFromDashboard == 4){
+ $data['ticket_data'] = $this->ticketSearch(5);
+
+ }
+ $data['claim_status'] = $this->claimStatus->select('id,ticket_type,claim_status')->where('is_active', 1)->findAll();
+ $data['client_list'] = $this->clientModel->select('id,client_name')->where('is_active', 1)->findAll();
+ // dd($data);
+ return $this->loadLayout('ticket_search', $data);
+
+ }
+ else{
+ $data['ticket_data'] = $this->ticketSearch();
+ $html = view('ticket_list', $data);
+ return $this->respond(['status' => true, 'html' => $html], 200);
+ }
+
}
}
public function ticketSearch($action = null)
- {
+ {
$db = db_connect();
-
- $subquery = $db->table('ticket_history th')
+ // log_message('error', 'Ticket Search Action: ' . $action);
+ $subquery = $db->table('ticket_master tm')
->select([
- 'th.ticket_id',
+ 'tm.id AS ticket_id',
"CASE
- WHEN DATEDIFF(
- th.created_at,
- COALESCE(
- (SELECT MIN(created_at) FROM ticket_history th2 WHERE th2.ticket_id = th.ticket_id),
- tm.created_at
- )
- ) BETWEEN 0 AND 6 THEN '0-6 Days'
- WHEN DATEDIFF(
- th.created_at,
- COALESCE(
- (SELECT MIN(created_at) FROM ticket_history th2 WHERE th2.ticket_id = th.ticket_id),
- tm.created_at
- )
- ) BETWEEN 7 AND 12 THEN '7-12 Days'
- WHEN DATEDIFF(
- th.created_at,
- COALESCE(
- (SELECT MIN(created_at) FROM ticket_history th2 WHERE th2.ticket_id = th.ticket_id),
- tm.created_at
- )
- ) BETWEEN 13 AND 20 THEN '13-20 Days'
- ELSE 'Above 20 Days'
- END AS tat"
+ WHEN DATEDIFF(
+ CURDATE(),
+ COALESCE(latest_history.created_at, tm.created_at)
+ ) BETWEEN 0 AND 6 THEN '0-6 Days'
+ WHEN DATEDIFF(
+ CURDATE(),
+ COALESCE(latest_history.created_at, tm.created_at)
+ ) BETWEEN 7 AND 12 THEN '7-12 Days'
+ WHEN DATEDIFF(
+ CURDATE(),
+ COALESCE(latest_history.created_at, tm.created_at)
+ ) BETWEEN 13 AND 20 THEN '13-20 Days'
+ ELSE 'Above 20 Days'
+ END AS tat"
])
- ->join('ticket_master tm', 'tm.id = th.ticket_id', 'right')
+ ->join(
+ '(SELECT th.ticket_id, MAX(th.created_at) AS created_at
+ FROM ticket_history th
+ WHERE th.field_name = "claim_status_id"
+ GROUP BY th.ticket_id) AS latest_history',
+ 'latest_history.ticket_id = tm.id',
+ 'left'
+ )
->where('tm.is_active', 1)
- ->groupBy('th.ticket_id, tm.created_at');
+ ->groupBy('tm.id, tm.created_at, latest_history.created_at');
- //action 1 get last 100 rows, action 2 filter and get all rows related to that
+
+ //action 1 get last 100 rows, action 2 filter and get all rows related to that, action 3 gets according to dashboard, action 4 gets according to ACM, action 5 tat
if ($action == 1) {
$query = $db->table('ticket_master tm')
@@ -232,13 +268,66 @@ class TicketController extends BaseController
'tcs.claim_status AS status',
'tm.claim_number AS claim_no',
'tm.tpa_id',
+ 'tm.tpa_no',
'tm.emp_name',
+ 'tm.emp_code',
+ 'tm.relationship',
'i.name AS insurer_name',
'c.client_name',
'tm.insured_name',
'c.short_name',
'DATE_FORMAT(tm.created_at, "%d-%m-%Y") AS ticket_created_date',
- 'COALESCE(tat_category.tat, "0-6 Days") AS tat'
+ 'COALESCE(tat_category.tat, "0-6 Days") AS tat',
+
+ 'tm.claim_status_id',
+
+ '(SELECT first_name FROM user_profiles WHERE user_profiles.id = tm.acm_id) AS acm_name',
+ '(SELECT name FROM insurers WHERE insurers.id = tm.insurer_id) AS insurer_name',
+ '(SELECT name FROM tpa WHERE tpa.id = tm.tpa_id) AS tpa_name',
+
+ 'tm.acm_id',
+ 'tm.insurer_id',
+ 'tm.tpa_id',
+ 'tm.client_policy_id',
+
+ 'tm.policy_no',
+ 'tm.priority',
+ 'tm.relationship',
+ 'tm.emp_mobile',
+ 'tm.emp_mail',
+ 'tm.emp_personal_mail',
+ 'tm.mode_of_intimation',
+ 'tm.claim_type',
+ 'tm.hospital_name',
+ 'tm.doa',
+ 'tm.dod',
+ 'tm.claim_amount',
+ 'tm.pod_no',
+ 'tm.date_of_join',
+ 'tm.date_of_incep',
+ 'tm.dob',
+ 'tm.date_of_accident',
+ 'tm.date_of_death',
+ 'tm.date_of_intimat',
+ 'tm.si_amt',
+ 'tm.raised_date',
+ 'tm.registration_date',
+ 'tm.query_received_date',
+ 'tm.denial_date',
+ 'tm.approved_date',
+ 'tm.settled_date',
+ 'tm.denial_reason',
+ 'tm.approved_letter',
+ 'tm.approved_amount',
+ 'tm.utr_details',
+ 'tm.settle_letter',
+ 'tm.return_remark',
+ 'tm.cancel_remark',
+ 'tm.awb_no_courier_name',
+ 'tm.non_id_reason',
+ 'tm.pay_initiate_date',
+ 'tm.approved_description'
+
])
->join('insurers i', 'i.id = tm.insurer_id AND i.is_active = 1', 'left')
->join('clients c', 'c.id = tm.client_id AND c.is_active = 1', 'left')
@@ -247,54 +336,142 @@ class TicketController extends BaseController
->where('tm.is_active', 1)
->orderBy('tm.id', 'DESC');
- $data = $query->get()->getResultArray();
+ $data = $query->get()->getResultArray();
// dd(db_connect()->getLastQuery());
return $data;
+ } else if ($action == 3) {
+ $ids = $this->request->getPost('ids');
+ $ids = array_filter(explode(',', $ids));
+
+ if (!empty($ids)) {
+ $idsStr = implode(',', array_map('intval', $ids)); // sanitize IDs to be integers
+ $where = "tm.id IN ($idsStr)";
+ } else {
+ $where = '1 = 0'; // No valid IDs, return empty result
+ }
+ // dd($where);
+
+ } else if ($action == 4){
+ $acm_id = $this->request->getPost('ids');
+
+ // dd($acm_id);
+ if (!empty($acm_id)) {
+ $where = "tm.acm_id = $acm_id";
+ } else {
+ $where = '1 = 0'; // No valid IDs, return empty result
+ }
+
+ }else if ($action == 5) {
+ $search_data = $this->request->getPost();
+ $where = "tm.created_at >= '" . $search_data['from_date'] . "' AND tm.created_at <= '" . $search_data['to_date'] . "'" ."and ticket_type_id = ".$search_data['ticket_type_id'];
} else {
$search_data = $this->request->getPost();
- // print_r($search_data);
+ // print_r($search_data); die()
$where = [];
foreach ($search_data as $search_objects => $key) {
- if ($key != null && $key != '' && $key != 0) {
+ if ($key != null && $key != '' && $key != 0 && $search_objects != 'is_dashboard') {
$where[$search_objects] = $key;
}
}
// print_rr($where);
- $query = $db->table('ticket_master tm')
- ->select([
- 'tm.id',
- 'tm.ticket_type_id',
- 'tcs.claim_status AS status',
- 'tm.claim_number AS claim_no',
- 'tm.claim_status_id',
- 'tm.is_head_approved',
- 'tm.tpa_id',
- 'tm.emp_name',
- 'i.name AS insurer_name',
- 'c.client_name',
- 'tm.insured_name',
- 'c.short_name',
- 'DATE_FORMAT(tm.created_at, "%d-%m-%Y") AS ticket_created_date',
- 'COALESCE(tat_category.tat, "0-6 Days") AS tat'
- ])
- ->join('insurers i', 'i.id = tm.insurer_id AND i.is_active = 1', 'left')
- ->join('clients c', 'c.id = tm.client_id AND c.is_active = 1', 'left')
- ->join('ticket_claim_status tcs', 'tcs.id = tm.claim_status_id AND tcs.is_active = 1', 'left')
- ->join("({$subquery->getCompiledSelect()}) tat_category", 'tm.id = tat_category.ticket_id', 'left')
- ->where('tm.is_active', 1)
- ->where($where)
- ->orderBy('tm.id', 'DESC');
- $data = $query->get()->getResultArray();
- // print_rr($data);
- // log_message('error',' Claims Master Data '.json_encode($data));die();
- // print_rr($data);die();
-
- return $data;
}
+ $query = $db->table('ticket_master tm')
+ ->select([
+ 'tm.id',
+ 'tm.ticket_type_id',
+ 'tcs.claim_status AS status',
+ 'tm.claim_number AS claim_no',
+ 'tm.claim_status_id',
+ 'tm.is_head_approved',
+ 'tm.tpa_id',
+ 'tm.tpa_no',
+ 'tm.emp_name',
+ 'tm.emp_code',
+ 'tm.relationship',
+ 'i.name AS insurer_name',
+ 'c.client_name',
+ 'tm.insured_name',
+ 'c.short_name',
+ 'DATE_FORMAT(tm.created_at, "%d-%m-%Y") AS ticket_created_date',
+ 'COALESCE(tat_category.tat, "0-6 Days") AS tat',
+
+ '(SELECT first_name FROM user_profiles WHERE user_profiles.id = tm.acm_id) AS acm_name',
+ '(SELECT name FROM insurers WHERE insurers.id = tm.insurer_id) AS insurer_name',
+ '(SELECT name FROM tpa WHERE tpa.id = tm.tpa_id) AS tpa_name',
+
+ 'tm.claim_status_id',
+ 'tm.acm_id',
+ 'tm.insurer_id',
+ 'tm.tpa_id',
+ 'tm.client_policy_id',
+ 'tm.policy_no',
+ 'tm.priority',
+ 'tm.relationship',
+ 'tm.emp_mobile',
+ 'tm.emp_mail',
+ 'tm.emp_personal_mail',
+ 'tm.mode_of_intimation',
+ 'tm.claim_type',
+ 'tm.hospital_name',
+ 'tm.doa',
+ 'tm.dod',
+ 'tm.claim_amount',
+ 'tm.pod_no',
+ 'tm.date_of_join',
+ 'tm.date_of_incep',
+ 'tm.dob',
+ 'tm.date_of_accident',
+ 'tm.date_of_death',
+ 'tm.date_of_intimat',
+ 'tm.si_amt',
+ 'tm.raised_date',
+ 'tm.registration_date',
+ 'tm.query_received_date',
+ 'tm.denial_date',
+ 'tm.approved_date',
+ 'tm.settled_date',
+ 'tm.denial_reason',
+ 'tm.approved_letter',
+ 'tm.approved_amount',
+ 'tm.utr_details',
+ 'tm.settle_letter',
+ 'tm.return_remark',
+ 'tm.cancel_remark',
+ 'tm.awb_no_courier_name',
+ 'tm.non_id_reason',
+ 'tm.pay_initiate_date',
+ 'tm.approved_description'
+
+ ])
+ ->join('insurers i', 'i.id = tm.insurer_id AND i.is_active = 1', 'left')
+ ->join('clients c', 'c.id = tm.client_id AND c.is_active = 1', 'left')
+ ->join('ticket_claim_status tcs', 'tcs.id = tm.claim_status_id AND tcs.is_active = 1', 'left')
+ ->join("({$subquery->getCompiledSelect()}) tat_category", 'tm.id = tat_category.ticket_id', 'left')
+ ->where('tm.is_active', 1)
+ ->where($where)
+ ->orderBy('tm.id', 'DESC');
+
+ $data = $query->get()->getResultArray();
+ // dd($db->getLastQuery()->getQuery());
+ // dd($data);
+ if ($action == 5){
+
+ $tat = $this->request->getPost("tat_category");
+
+ $data = array_values(array_filter($data, function($dat) use ($tat) {
+ return $dat['tat'] == $tat;
+ }));
+
+ }
+ // print_rr($data);
+ // log_message('error',' Claims Master Data '.json_encode($data));die();
+ // print_rr($data);die();
+
+ return $data;
}
public function ticket_form($ticket_type)
@@ -456,7 +633,18 @@ class TicketController extends BaseController
$data['placeHolders'] = $this->placeHolders;
$data['message_data'] = $this->getTicketMessage($ticket_id);
$data['view_ticket_page'] = [];
- $data['member_data'] = $this->employeeModel->getEmployeeByEmployeeCode($ticket_data['emp_code']);
+
+ if($ticket_data['ticket_type_id'] == 1){
+ $data['member_data'] = $this->employeeModel->getEmployeeByEmployeeCode($ticket_data['emp_code']);
+ }else{
+ $data['member_data'] = array_filter(
+ $this->employeeModel->getEmployeeByEmployeeCode($ticket_data['emp_code']),
+ function ($member) {
+ return isset($member['emp_relationship']) && $member['emp_relationship'] == 'Self';
+ }
+ );
+ }
+
$data['ticket_history'] = $this->ticketHistory($ticket_id);
$data['ticket_check_list'] = db_connect()->table('ticket_check_list')->where('is_active', 1)->where('ticket_type_id', $ticket_data['ticket_type_id'])->get()->getResultArray();
if (!empty($ticket_data['client_policy_id'])){
@@ -578,7 +766,9 @@ class TicketController extends BaseController
$return_value = $this->ticketMasterModel->insert($ticket_data);
if ($return_value) {
//mail trigger part
+ $this->putHistoryAfterInsert($ticket_data, $return_value);
$mail_responce = $this->sendAutoMailTrigger($return_value);
+ $this->autoMessageInsertBasedOnMailResponse($mail_responce, $return_value);
return $this->respond(['status' => true, 'ticket_id' => $return_value, 'code' => 200, 'data' => $ticket_data, "message" => "Claim created successfully", 'mail_responce' => $mail_responce], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to create claim'], 200);
@@ -601,8 +791,12 @@ class TicketController extends BaseController
$return_value = $this->ticketMasterModel->where('id', $ticket_id)->set($ticket_data)->update();
if ($return_value) {
- //mail trigger part
- $mail_responce = $this->sendAutoMailTrigger($ticket_id);
+ $mail_responce = null;
+ if($old_ticket_data['claim_status_id'] != $ticket_data['claim_status_id']){
+ //mail trigger part
+ $mail_responce = $this->sendAutoMailTrigger($ticket_id);
+ $this->autoMessageInsertBasedOnMailResponse($mail_responce, $ticket_id);
+ }
//send mail to the head for rejected ticket approvel
if($ticket_data['claim_status_id'] == 8 && $ticket_data['is_head_approved'] == 0){
@@ -751,13 +945,20 @@ class TicketController extends BaseController
{
// log_message('error','Function called');die();
// $ticket_master_id = $this->request->getPost('id');
- $user_id = get_session_userid();
- $logged_user = $this->userModel->select('first_name,last_name,profile')->where('id', $user_id)->first();
$dataToSend = [];
- $dataToSend['user_name'] = $logged_user['first_name'] . ' ' . $logged_user['last_name'];
- $dataToSend['messages'] = $this->ticketMessageModel->where('is_active', 1)
- ->where('ticket_id', $ticket_master_id)->orderBy('created_at', 'DESC')
+
+ $user_id = get_session_userid();
+ // $logged_user = $this->userModel->select('first_name,last_name,profile')->where('id', $user_id)->first();
+ // $dataToSend['user_name'] = $logged_user['first_name'] . ' ' . $logged_user['last_name'];
+
+ $dataToSend['messages'] = $this->ticketMessageModel
+ ->select('ticket_messages.*,up.first_name as user_name')
+ ->join('user_profiles up', 'up.id = ticket_messages.created_by', 'left')
+ ->where('ticket_messages.is_active', 1)
+ ->where('ticket_messages.ticket_id', $ticket_master_id)
+ ->orderBy('ticket_messages.created_at', 'DESC')
->findAll();
+
foreach ($dataToSend['messages'] as $message) {
$mail_content_converted = $this->convertHtmlToText($message['mail_content']);
$message['mail_content'] = $mail_content_converted;
@@ -775,10 +976,27 @@ class TicketController extends BaseController
}
public function convertHtmlToText($html)
+ {
+ if(!empty($html)){
+ $dom = new DOMDocument();
+ @$dom->loadHTML($html);
+ return strip_tags($dom->saveHTML());
+ }else{
+ return '';
+ }
+ }
+
+ public function removeTicket()
{
- $dom = new DOMDocument();
- @$dom->loadHTML($html);
- return strip_tags($dom->saveHTML());
+ $ticket_id = $this->request->getGet('ticket_id');
+ if(!empty($ticket_id)){
+ $data['is_active'] = 0;
+ $this->ticketMasterModel->where('id', $ticket_id)->set($data)->update();
+ return $this->respond(['status' => true, 'code' => 200, 'message' => 'Claim removed successfully'], 200);
+ }else{
+ return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to remove Claim'], 200);
+ }
+
}
//---- Email Trigger Part----------------------------------------------------------------------------------------------
@@ -838,13 +1056,24 @@ class TicketController extends BaseController
// Construct Mail Data
$mailData = [
- 'mail' => $ticket_data['emp_mail'],
+ 'mail' => [$ticket_data['emp_mail'], $ticket_data['emp_personal_mail'] ?? ""],
'subject' => $subject,
'message' => $message,
'cc' => $ticket_data['common_mails'] ?? '',
'attachments' => []
];
+ // // if the employee personal mail is not empty then send the mail to the employee personal mail
+ // if(!empty($ticket_data['emp_personal_mail'])){
+ // $mailData[] = [
+ // 'mail' => [$ticket_data['emp_mail'], $ticket_data['emp_personal_mail'] ?? ""],
+ // 'subject' => $subject,
+ // 'message' => $message,
+ // 'cc' => $ticket_data['common_mails'] ?? '',
+ // 'attachments' => []
+ // ];
+ // }
+
// print_r($mailData); die;
$this->myLogger->logme('error', "Final Email Data");
@@ -861,6 +1090,10 @@ class TicketController extends BaseController
$this->myLogger->logme('error', "Replacing placeholders in content");
if (!empty($ticket_data) && !empty($content)) {
+ // print_rr($ticket_data);die();
+ if (!isset($ticket_data['id'])) { $ticket_data['id'] = $ticket_data['ticket_master_id'];}
+ if (!isset($ticket_data['ticket_master_id'])) {$ticket_data['ticket_master_id'] = $ticket_data['id'];}
+
foreach ($this->placeHolders as $key => $value) {
if ($value == "emp_code") {
@@ -869,6 +1102,12 @@ class TicketController extends BaseController
$replaceData = str_replace("Claim-", "", $this->ticketType[$ticket_data['ticket_type_id']] ?? "");
} else if ($value == "claim_form_link"){
$replaceData = 'Click here to download Claim Form ';
+ } else if ($value == "claim_feedback_form" && $ticket_data['ticket_type_id'] == 1){
+ $replaceData = 'Click to open Claim Feedback Form ';
+ } else if ($value == "settle_letter"){
+ $replaceData = ' View Settlement Letter ';
+ }else if ($value == "approved_letter"){
+ $replaceData = ' View Approved Letter ';
}else {
$replaceData = isset($ticket_data[$value]) ? $ticket_data[$value] : '';
}
@@ -927,8 +1166,29 @@ class TicketController extends BaseController
$this->myLogger->logme('error', "Fetched ACM emails");
+
+ // if(!empty($ticket_data['emp_personal_mail'])){
+
+ // $this->myLogger->logme('error', "Send employee personal mail start");
+
+ // $emailPersonalData = [
+ // 'mail' => $ticket_data['emp_personal_mail'],
+ // 'subject' => $mail_data['mail_subject'],
+ // 'message' => $mail_data['mail_content'],
+ // 'common' => [],
+ // 'cc' => $acm_mails['common_mails'],
+ // 'attachments' => []
+ // ];
+
+ // $this->sendTrigger($emailPersonalData);
+
+ // $this->myLogger->logme('error', "Send employee personal mail successfully");
+ // }else{
+ // $this->myLogger->logme('error', "Send employee personal mail is empty");
+ // }
+
$emailData = [
- 'mail' => $mail_data['emp_mail'],
+ 'mail' => [$mail_data['emp_mail'], $ticket_data['emp_personal_mail'] ?? ""],
'subject' => $mail_data['mail_subject'],
'message' => $mail_data['mail_content'],
'common' => [],
@@ -950,7 +1210,11 @@ class TicketController extends BaseController
if (!empty($auto_mail_enable) && $auto_mail_enable['is_auto_mail'] == 1) {
$mail_content = $this->constructMailContent($ticket_id);
// print_r($mail_content); die;
- $mail_responce = $this->sendTrigger($mail_content);
+ // foreach ($mail_content as $key => $value) {
+ $mail_responce = $this->sendTrigger($mail_content);
+ // $this->myLogger->logme('error', '{data} - Auto Mail Sent, Successfully', ['data' => $key + 1]);
+ $this->myLogger->logme('error', 'Auto Mail Sent, Successfully');
+ // }
} elseif (!empty($auto_mail_enable) && $auto_mail_enable['is_auto_mail'] == 0) {
$this->myLogger->logme('error', 'Auto Mail Not Sent, Reason: Automail Not Enabled');
} else {
@@ -972,7 +1236,7 @@ class TicketController extends BaseController
th.old_value,
th.new_value,
th.created_at,
- CONCAT(creator.first_name, ' ', creator.last_name) as modified_by,
+ CONCAT_WS(' ', creator.first_name, creator.last_name) AS modified_by,
-- Claim Status
old_status.claim_status as old_status_value,
new_status.claim_status as new_status_value,
@@ -1032,6 +1296,7 @@ class TicketController extends BaseController
ORDER BY
th.created_at DESC";
$data = $this->ticketHistoryModel->query($sql)->getResultArray();
+ // dd(db_connect()->getLastQuery());
$priorityType = $this->priorityType;
$relationshipType = $this->relationshipType;
$modeOFIntimate = $this->modeOFIntimate;
@@ -1162,11 +1427,12 @@ class TicketController extends BaseController
if ($received_data['report_type'] == "acc_manager_wise_status"){
$viewData['policy_type'] = $received_data['policy_type'];
$viewData['account_manager_wise_data'] = $this->ticketMasterModel->accountManagerWiseReport($policy_type,$fromDate,$toDate);
- // print_rr($viewData);
+
+ // print_rr($viewData);die();
if ($policy_type == 1){
$viewData['column_order'] = [
'ACM_NAME', 'ID NOT GENERATED', 'NON ID', 'CDA', 'INFORMATION REQUIRED',
- 'UNDER PROCESS - CLAIM NO. UPDATION', 'UNDER PROCESS - INVESTIGATION STATUS',
+ 'UNDER PROCESS - CLAIM NO. UPDATION',
'UNDER PROCESS - QUERY DOCUMENT RECEIVED', 'APPROVED', 'PAYMENT INITIATED',
'TOTAL'
];
@@ -1180,12 +1446,13 @@ class TicketController extends BaseController
$ordered_data[] = $temp;
}
$viewData['tpa_wise_data'] = $ordered_data;
+ // print_rr($viewData);die();
$html = view('claims_report_acc_manager_wise', $viewData);
return $this->respond(['status' => true, 'html' => $html], 200);
}else{
$viewData['column_order'] = [
'ACM_NAME', 'CLAIM INTIMATION', 'INTIMATION TO INSURER', 'CLIENT PENDING',
- 'INSURER PENDING','INVESTIGATION','APPROVED','ON HOLD','TOTAL', 'NOT COVERED',
+ 'INSURER PENDING','INVESTIGATION','APPROVED','TOTAL', 'NOT COVERED',
'CLOSED', 'SETTLED', 'CLEARED_TOTAL'
];
$ordered_data = [];
@@ -1198,6 +1465,7 @@ class TicketController extends BaseController
$ordered_data[] = $temp;
}
$viewData['tpa_wise_data'] = $ordered_data;
+ // print_rr($viewData);die();
$html = view('claims_report_acc_manager_wise', $viewData);
return $this->respond(['status' => true, 'html' => $html], 200);
}
@@ -1207,9 +1475,9 @@ class TicketController extends BaseController
$viewData['column_order'] = [
'TPA_NAME', 'NON ID', 'ID NOT GENERATED', 'CDA', 'INFORMATION REQUIRED',
- 'UNDER PROCESS - CLAIM NO. UPDATION', 'UNDER PROCESS - INVESTIGATION STATUS',
+ 'UNDER PROCESS - CLAIM NO. UPDATION',
'UNDER PROCESS - QUERY DOCUMENT RECEIVED', 'APPROVED', 'PAYMENT INITIATED',
- 'TOTAL', 'SETTLED', 'CLOSED', 'CANCELLED', 'RETURNED', 'CLEARED_TOTAL'
+ 'TOTAL', 'SETTLED', 'CLOSED', 'CANCELLED', 'RETURNED', 'CLEARED_TOTAL','TPA_ID'
];
// Reorder data based on column order
@@ -1223,6 +1491,7 @@ class TicketController extends BaseController
$ordered_data[] = $temp;
}
$viewData['tpa_wise_data'] = $ordered_data;
+ // print_r($ordered_data);die();
// $html = view('claims_report_tpa_wise', $viewData);
$html = view('claims_report_tpa_wise',$viewData);
@@ -1230,6 +1499,9 @@ class TicketController extends BaseController
} else if ($received_data['report_type'] == 'tat_band_wise') {
$viewData['data'] = $this->ticketMasterModel->getTATReport($policy_type, $fromDate, $toDate);
+ $viewData['policyType'] = $policy_type;
+ $viewData['fromDate'] = $fromDate;
+ $viewData['toDate'] = $toDate;
$html = view('tat_report_band_wise_list', $viewData);
return $this->respond(['status' => true, 'html' => $html], 200);
}
@@ -1304,14 +1576,21 @@ class TicketController extends BaseController
$statusMapping = json_decode($incoming_form_values['extra_fields_array_for_validate']);
foreach ($statusMapping as $status => $requiredFields) {
+
// Ensure requiredFields is an array
if (!is_array($requiredFields)) {
$requiredFields = [$requiredFields];
+
}
// Check if all required fields exist and are not empty in the incoming form values
$allFieldsMatched = true;
foreach ($requiredFields as $field) {
+
+ if(in_array($field, ['approved_description'])){
+ continue;
+ }
+
if (!isset($incoming_form_values[$field]) || empty($incoming_form_values[$field])) {
$allFieldsMatched = false;
break;
@@ -1371,7 +1650,8 @@ class TicketController extends BaseController
}
}
- public function getPoliciesbyEmpID() {
+ public function getPoliciesbyEmpID()
+ {
$received_data = $this->request->getPost();
$emp_id = $received_data['emp_id'];
@@ -1379,6 +1659,8 @@ class TicketController extends BaseController
$policies = $this->employeePolicyModel
->select('client_policy_id')
->where('employee_id', $emp_id)
+ ->where('is_active', 1)
+ ->where('status', 'active')
->findAll();
if (empty($policies)) {
@@ -1390,8 +1672,20 @@ class TicketController extends BaseController
// Fetch all policy names and IDs in one query
$policyNameandID = $this->clientPolicyModel
- ->select('CONCAT(policy_type.policy_type, "-", client_policy.policy_no) as client_policy_name, client_policy.id as client_policy_value,client_policy.policy_type_id,client_policy.policy_no')
+ ->select('
+ CONCAT(policy_type.policy_type, "-", client_policy.policy_no) as client_policy_name,
+ client_policy.id as client_policy_value,
+ client_policy.policy_type_id,
+ client_policy.policy_no,
+ insurers.id as insurer_id,
+ insurers.name as insurer_name,
+ tpa.name as tpa_name,
+ tpa.id as tpa_id,
+ ')
->join('policy_type', 'policy_type.id = client_policy.policy_type_id AND policy_type.is_active = 1')
+ ->join('insurers', 'insurers.id = client_policy.insurer_id AND insurers.is_active = 1', 'left')
+ ->join('tpa', 'tpa.id = client_policy.tpa_id AND tpa.is_active = 1', 'left')
+ ->where('client_policy.policy_status', 1)
->whereIn('client_policy.id', $policy_ids)
->findAll();
@@ -1443,5 +1737,202 @@ class TicketController extends BaseController
return $this->response->setStatusCode(500)->setBody('An error occurred while downloading the file.');
}
}
+
+ // -------------------------------------------------------------------------------------------------------------------------
+
+ public function autoMessageInsertBasedOnMailResponse($mail_sent_status, $ticket_id)
+ {
+ if (gettype($mail_sent_status) == 'array') {
+ $this->myLogger->logme('error', "auto Message Insert Based On Mail Response Failed because is array :$ticket_id ");
+ } else {
+ $mail_sent_status = json_decode($mail_sent_status);
+ $this->myLogger->logme('error', "mail_sent_status is object :$ticket_id ");
+ }
+
+ if (!empty($mail_sent_status) && isset($mail_sent_status->status) && $mail_sent_status->status == 'success') {
+
+ $sent_message_data['ticket_id'] = $ticket_id;
+ $sent_message_data['sender'] = 'staff';
+ $sent_message_data['emp_mail'] = isset($mail_sent_status->data->params->mail[0]) ? $mail_sent_status->data->params->mail[0] ?? null : $mail_sent_status->data->params->mail ?? null;
+ $sent_message_data['mail_subject'] = $mail_sent_status->data->params->subject;
+ $sent_message_data['mail_content'] = $mail_sent_status->data->params->message;
+
+ $message_insert_status = $this->ticketMessageModel->insert($sent_message_data);
+
+ if ($message_insert_status) {
+ $this->myLogger->logme('error', "Claim initiated, Mail sent Successfully, successfully store message:$ticket_id ");
+ } else {
+ $this->myLogger->logme('error', "Claim initiated, Mail sent Successfully, Failed to store message:$ticket_id ");
+ }
+
+ return true;
+ } else {
+
+ $this->myLogger->logme('error', "Failed to send Mail :$ticket_id ");
+ return false;
+ }
+ }
+
+ public function putHistoryAfterInsert($ticket_data, $ticket_id)
+ {
+ $this->myLogger->logme('error', "Put History After Insert function called : $ticket_id");
+
+ if(!empty($ticket_data)){
+
+ $history_data = [
+ 'ticket_id' => $ticket_id,
+ 'field_name' => 'claim_status_id',
+ 'display_name' => 'Ticket Created',
+ 'old_value' => null,
+ 'new_value' => $ticket_data['claim_status_id'],
+ 'created_by' => get_session_userid(),
+ 'is_active' => 1
+ ];
+
+ $this->myLogger->logme('error', "Put History After Insert function called : " . json_encode($history_data));
+
+
+ $history_insert = $this->ticketHistoryModel->insert($history_data);
+
+ if($history_insert){
+ $this->myLogger->logme('error', "Put History After Insert Ticket Data Successfully");
+ }else{
+ $this->myLogger->logme('error', "Put History After Insert Ticket Data Failed");
+ }
+
+ }else{
+ $this->myLogger->logme('error', "Put History After Insert Ticket Data is empty");
+ }
+
+ return true;
+
+ }
+
+ public function viewClaimFeedbackForm($md5_ticket_id,$empView = null)
+ {
+
+ if ($this->request->is("get")){
+
+ $data['ticket_id'] = $md5_ticket_id;
+ $data['ticket_data'] = $this->ticketMasterModel->select('ticket_master.*,clients.client_name')->join('clients','clients.id = ticket_master.client_id')->where('MD5(ticket_master.id)',$md5_ticket_id)->where('ticket_master.is_active',1)->first();
+ $data['form_submitted'] = !empty($data['ticket_data']['feedback_json'])? 1 : 0;
+
+
+ $data['viewer'] = !empty($empView) ? $empView : 0;
+ // dd($data);
+ return view('ticket_feedback_form', $data);
+ }else{
+
+ $formDataJson = json_encode($this->request->getPost());
+ // log_message("error","Form data : ".$formDataJson);
+
+
+ $data_to_store = [
+
+ 'feedback_json' => $formDataJson
+ ];
+
+ if (!empty($formDataJson)){
+ // $this->ticketMasterModel->save($data_to_store);
+ $this->ticketMasterModel->where('MD5(id)', $md5_ticket_id)->set($data_to_store)->update();
+
+ return $this->respond(['status' => true,'id'=> $md5_ticket_id,'received_data' => $formDataJson], 200);
+
+ }else{
+ return $this->respond(['status' => false,'id'=> $md5_ticket_id,'received_data' => $formDataJson], 200);
+ }
+
+ }
+
+ }
+
+ public function feedbackList(){
+
+ $data['feedback_data'] = $this->ticketMasterModel->select("ticket_master.*,clients.client_name")->join("clients","clients.id = ticket_master.client_id")->where("ticket_master.is_active",1)->where("ticket_master.feedback_json IS NOT NULL", null, false)->where("ticket_master.feedback_json !=", "")->findAll();
+
+ // dd($data);
+ $this->loadLayout("ticket_feedback_list",$data);
+ }
+
+ public function getMoreInfo() {
+ $ticket_id = $this->request->getPost('ticket_id');
+ $this->myLogger->logme("error", "Ticket ID : " . $ticket_id);
+
+ $fields = $this->extraFields;
+ $data_to_send = [];
+ // Get ticket data
+ $ticket_data = $this->ticketMasterModel->where("id", $ticket_id)->where("is_active", 1)->first();
+
+ // Query previous status
+ $ticket_previous_status = $this->ticketMasterModel
+ ->select("th.old_value, tcs.claim_status")
+ ->join("ticket_history th", "th.ticket_id = ticket_master.id AND th.field_name = 'claim_status_id' AND th.is_active = 1")
+ ->join("ticket_claim_status tcs", "tcs.id = th.old_value AND tcs.is_active = 1")
+ ->where("ticket_master.is_active", 1)
+ ->where("ticket_master.id", $ticket_id)
+ ->groupBy("th.old_value, tcs.claim_status")
+ ->get()
+ ->getResultArray();
+
+ // Loop through previous status and gather the required data
+ foreach ($ticket_previous_status as $status) {
+ $this->myLogger->logme("error", "Status : " . json_encode($status));
+
+ if (isset($fields[$status['old_value']])) {
+ $field = $fields[$status['old_value']];
+
+ // Ensure claim_status is a scalar value (string or int)
+ $claim_status = (string)$status['claim_status']; // Cast to string to avoid issues
+
+ // Initialize claim_status if it doesn't exist in the array
+ if (!isset($data_to_send[$claim_status])) {
+ $data_to_send[$claim_status] = [];
+ }
+
+ // Handle case where $field is an array
+ if (is_array($field)) {
+ foreach ($field as $f) {
+ // Check if the field exists in the ticket data
+ $data_to_send[$claim_status][$f] = isset($ticket_data[$f]) ? $ticket_data[$f] : null;
+
+ // Check if the field contains a date and format it
+ if ($this->isDate($data_to_send[$claim_status][$f])) {
+ $data_to_send[$claim_status][$f] = date('d-m-Y', strtotime($data_to_send[$claim_status][$f]));
+ }
+
+ $this->myLogger->logme("error", "Data for field {$f}: " . json_encode($data_to_send[$claim_status][$f]));
+ }
+ } else {
+ // If field is not an array, handle it as a single field
+ $data_to_send[$claim_status][$field] = isset($ticket_data[$field]) ? $ticket_data[$field] : null;
+
+ // Check if the field contains a date and format it
+ if ($this->isDate($data_to_send[$claim_status][$field])) {
+ $data_to_send[$claim_status][$field] = date('d-m-Y', strtotime($data_to_send[$claim_status][$field]));
+ }
+
+ $this->myLogger->logme("error", "Data for field {$field}: " . json_encode($data_to_send[$claim_status][$field]));
+ }
+ }
+ }
+
+ $this->myLogger->logme('error', "Total data: " . json_encode($data_to_send));
+
+ // Send response based on data availability
+ if (!empty($data_to_send)) {
+ return $this->respond(['status' => true, 'data' => $data_to_send], 200);
+ } else {
+ return $this->respond(['status' => false], 200);
+ }
+ }
+
+ private function isDate($value, $format = 'Y-m-d') {
+ // Check if the value is a valid date string (basic validation)
+ $date = \DateTime::createFromFormat($format, $value);
+ return $date && $date->format($format) === $value;
+ }
+
+
+
}
diff --git a/app/Controllers/UserController.php b/app/Controllers/UserController.php
index b9f5c34e..cc23a148 100755
--- a/app/Controllers/UserController.php
+++ b/app/Controllers/UserController.php
@@ -12,6 +12,7 @@ use App\Models\UserModel;
use App\Models\RoleModel;
use App\Models\TeamModel;
use App\Models\UserTeamsModel;
+use App\Helpers\BookStackUserHelper;
class UserController extends AdminController
@@ -21,6 +22,7 @@ class UserController extends AdminController
protected $roleModel;
protected $teamModel;
protected $userTeamsModel;
+ protected $bookStack;
public function __construct()
{
@@ -31,6 +33,7 @@ class UserController extends AdminController
$this->roleModel = new RoleModel();
$this->teamModel = new TeamModel();
$this->userTeamsModel = new UserTeamsModel();
+ $this->bookStack = new BookStackUserHelper();
}
public function list()
@@ -60,10 +63,17 @@ class UserController extends AdminController
$userData['created_by'] = get_session_userid();
$temp_team = $userData['team'];
unset($userData['team']);
+
$insert = $this->userModel->insert($userData);
- if ($insert) {
+ $bookStackData = [
+ 'name' => $userData['first_name'],
+ 'email' => $userData['email'],
+
+ ];
+ $this->bookStack->createEditUser($bookStackData);
+ if ($insert) {
$teamData['user_id'] = $insert;
foreach ($teams as $value) {
$teamData['team_id'] = $value;
@@ -137,10 +147,20 @@ class UserController extends AdminController
unset($userData['csrf_test_name']);
unset($userData['PrimaryKey']);
+ $existingData = $this->userModel->where('id',$id)->first();;
+
// Update data in the 'users' table based on the $id
$userData['updated_by'] = get_session_userid();
$update = $this->userModel->where('id', $id)->set($userData)->update();
+ $bookStackData = [
+ 'name' => $userData['first_name'],
+ 'email' => $userData['email'],
+ ];
+
+ $this->bookStack->createEditUser($bookStackData,$existingData);
+
+
if ($update) {
if ($teams) {
@@ -211,7 +231,11 @@ class UserController extends AdminController
public function deactive($id = null)
{
$model = new UserModel();
+
+ $emailToDelete = $model->where('id', $id)->first();
$deactive = $model->where('id', $id)->set(['is_active' => 0])->update();
+
+ $this->bookStack->deleteUser($emailToDelete);
if($deactive)
{
// $db = \Config\Database::connect();
diff --git a/app/Filters/AuthClientApi.php b/app/Filters/AuthClientApi.php
new file mode 100644
index 00000000..2b3eb46e
--- /dev/null
+++ b/app/Filters/AuthClientApi.php
@@ -0,0 +1,87 @@
+clientAPI = new ClientApiModel();
+ $this->myLogger = \Config\Services::mylogger();
+
+ }
+ public function before(RequestInterface $request, $arguments = null)
+ {
+ $response = service('response');
+ try {
+
+ $authHeader = $request->getHeaderLine('Authorization');
+
+ // Check if header exists
+ if (empty($authHeader)) {
+ $this->myLogger->log('error', 'Authorization header missing');
+ return $response->setJson(['status' => "Failure", 'error' => ['message'=>'Authorization header missing','code'=> 401]], 401);
+ }
+
+ if(!str_contains($authHeader, 'Bearer ')){
+ $this->myLogger->log('error', 'Authorization Bearer missing');
+ return $response->setJson(['status' => "Failure", 'error' => ['message'=>'Invalid Authorization header','code'=>401]], 401);
+ }
+
+ $token = str_replace('Bearer ', '', $authHeader);
+ if (empty($token)) {
+
+ $this->myLogger->log('error', 'Empty Token');
+ return $response->setJson(['status' => "Failure", 'error' => ['message'=>'Invalid Token Format','code'=> 401]], 401);
+ }
+
+ try{
+
+ $client_id = ClientTokenHelper::extractClientId($token);
+
+ }catch(\Exception $e){
+
+ $this->myLogger->log('error', 'Invalid Client Token Format');
+
+ return $response->setJson(['status' => "Failure", 'error' => 'Invalid Token Format'], 401);
+ }
+ $client = $this->clientAPI->where('client_id', $client_id)->where("is_active", 1)->where("api_access", 1)->first();
+
+ // Client validation
+ if (!$client) {
+ $this->myLogger->log('error', 'Client Not Found or Unauthorized');
+ return $response->setJson(['status' => "Failure", 'error' => ['message' => 'Client not found or unauthorized','code'=>'403']], 403);
+ }
+
+ if (hash_equals($client['client_token'], $token)) {
+ $this->myLogger->log('error', 'Access Granted For Client : '.$client_id);
+ return true;
+ } else {
+ $this->myLogger->log('error', 'Invalid Token given for client : '.$client_id);
+ return $response->setJson(['status' => "Failure", 'error' => ['message' => 'Invalid token','code'=>401]
+ ], 401);
+ }
+ } catch (\Exception $e) {
+ log_message('error', 'Error in ClientAPIController:validateToken - ' . $e->getMessage());
+ return $response->setJson(['status' => "Failure", 'error' => ['message'=>'Internal Server Error','code'=> 500]], 500);
+ }
+
+ }
+
+ public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
+ {
+ // Do something here
+ }
+}
+
diff --git a/app/Helpers/BookStackUserHelper.php b/app/Helpers/BookStackUserHelper.php
new file mode 100644
index 00000000..c27386b2
--- /dev/null
+++ b/app/Helpers/BookStackUserHelper.php
@@ -0,0 +1,77 @@
+userModel = new BookStackUserModel();
+ $this->roleModel = new BookStackRoleModel();
+ }
+
+ public function createEditUser($data,$preData = null) {
+ // This function will handle the creation or editing of a user
+ // It will check if the user already exists and update or create accordingly
+ // The $data parameter should contain all necessary user information
+ // For example: ['name' => 'johndoe', 'email' => 'johndoe@doe.com']
+
+ if (!empty($preData)) {
+
+ $isExistingUser = $this->userModel->where('email', $preData['email'])->first();
+
+ if ($isExistingUser) {
+ $id = $isExistingUser['id'];
+ $update = $this->userModel->where('id', $id)->set($data)->update();
+ return $update;
+ }
+ }
+
+ $password = 'password';
+ $hashedPassword = ['password' => password_hash($password, PASSWORD_DEFAULT)];
+
+ $slug = ['slug' => $this->createSlug($data['name'])];
+
+ // array_push($data,$hashedPassword,$slug);
+
+ $data['password'] = $hashedPassword['password'];
+ $data['slug'] = $slug['slug'];
+
+ // dd($data);
+ $this->userModel->insert($data);
+ $userId = $this->userModel->insertID();
+
+ if (!empty($userId)) {
+
+ $roleData = [
+ 'user_id' => $userId,
+ 'role_id' => 3 // 3 is the default role ID for viewers
+ ];
+
+ $this->roleModel->insert($roleData);
+ }
+
+
+ }
+
+ protected function createSlug($string) {
+ return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $string)));
+ }
+
+ public function deleteUser($data) {
+
+ $isExistingUser = $this->userModel->where('email', $data['email'])->first();
+ if ($isExistingUser) {
+ $id = $isExistingUser['id'];
+ $delete = $this->userModel->where('id', $id)->delete();
+ $this->roleModel->where('user_id', $id)->delete();
+ return $delete;
+ }
+
+ }
+}
\ No newline at end of file
diff --git a/app/Helpers/ClientQueryHelper.php b/app/Helpers/ClientQueryHelper.php
new file mode 100644
index 00000000..6d58de19
--- /dev/null
+++ b/app/Helpers/ClientQueryHelper.php
@@ -0,0 +1,100 @@
+clientPolicy = new ClientPolicyModel();
+ $this->empModel = new EmployeeModel();
+ $this->empPolicyModel = new EmployeePolicyModel();
+ $this->claimModel = new TicketMasterModel();
+ }
+
+ public function clientPolicyMaster($client_id){
+
+ return $this->clientPolicy->select("client_policy.id as policy_ref_no,client_policy.client_branch_id as branch_ref_no,client_branch.branch_code,
+ client_policy.insurer_id as insurer_ref_no,insurers.name as insurer,client_policy.policy_type_id,policy_type.policy_type,
+ client_policy.tpa_id as tpa_ref_no,client_policy.policy_start_date,client_policy.policy_end_date,client_policy.policy_no,client_policy.policy_status")
+ ->join('insurers', 'client_policy.insurer_id = insurers.id and insurers.is_active = 1')
+ ->join('policy_type', 'client_policy.policy_type_id = policy_type.id and policy_type.is_active = 1')
+ ->join('client_branch', 'client_policy.client_branch_id = client_branch.id and client_branch.is_active = 1')
+ ->where('client_policy.is_active', 1)
+ ->where('client_policy.client_id', $client_id)
+ ->get()
+ ->getResultArray();
+ }
+
+ public function sendEmpMaster($client_id,$where,$limit,$offset = 0)
+ {
+
+ return $this->empModel->select("id as ref_no,name,emp_code,
+ relationship,emp_status,mobile,email_corporate,
+ change_event,dob,doj,band,gender")
+ ->where("is_active",1)
+ ->where("client_id", $client_id)
+ ->where($where)
+ ->whereNotIn('emp_status', ['truncated'],)
+ ->orderBy("id")
+ ->limit($limit,$offset)
+ ->get()
+ ->getResultArray();
+
+ }
+
+ public function sendEmpPolicies($emp_id)
+ {
+ return $this->empPolicyModel->select("id as ref_no,client_policy_id as policy_ref_no,
+ tpa_id as tpa_ref_no,uhid as policy_no,pre_existing_alignments,age_band,basic_cover_si,date_coverage,
+ policy_end_date,days,premium,rata_premimum,date_of_exit,reason_for_exit,payable_employee")
+ ->where("employee_id", $emp_id)
+ ->where("is_active", 1)
+ ->whereNotIn("status", ['truncated'])
+ ->orderBy("id")
+ ->get()
+ ->getResultArray();
+ }
+
+ public function sendClaimMaster($client_id,$where,$limit,$offset = 0)
+ {
+
+ return $this->claimModel->select("i.name as insurer,tpa.name as tpa,concat(up.first_name,' ',up.last_name) as acm_name,
+ cs.claim_status,ticket_master.emp_name,ticket_master.insured_name,
+ ticket_master.emp_code,ticket_master.policy_no,ticket_master.ticket_type_id as policy_type,
+ ticket_master.emp_mobile,ticket_master.emp_mail,ticket_master.hospital_name,ticket_master.doa,
+ ticket_master.dod,ticket_master.claim_amount,ticket_master.date_of_join,ticket_master.date_of_incep,
+ ticket_master.date_of_accident,ticket_master.date_of_death,
+ ticket_master.date_of_intimat,ticket_master.claim_number,ticket_master.si_amt,
+ ticket_master.raised_date,ticket_master.registration_date,ticket_master.denial_date,
+ ticket_master.settled_date,ticket_master.denial_reason,ticket_master.approved_amount,
+ ticket_master.utr_details,ticket_master.return_remark,ticket_master.cancel_remark,
+ ticket_master.non_id_reason,ticket_master.head_rejection_reason")
+ ->join("tpa","tpa.id = ticket_master.tpa_id and tpa.is_active = 1")
+ ->join("user_profiles up", "ticket_master.acm_id = up.id and up.is_active = 1")
+ ->join('insurers i', 'ticket_master.insurer_id = i.id and i.is_active = 1')
+ ->join('ticket_claim_status cs', 'ticket_master.claim_status_id = cs.id and cs.is_active = 1')
+ ->where("ticket_master.client_id", $client_id)
+ ->where("ticket_master.is_active", 1)
+ ->where($where)
+ ->orderBy("ticket_master.id")
+ ->limit($limit,$offset)
+ ->get()
+ ->getResultArray();
+
+ }
+
+
+}
\ No newline at end of file
diff --git a/app/Helpers/ClientTokenHelper.php b/app/Helpers/ClientTokenHelper.php
new file mode 100644
index 00000000..50c73f23
--- /dev/null
+++ b/app/Helpers/ClientTokenHelper.php
@@ -0,0 +1,54 @@
+query($getLastBalanceQuery, $getLastBalanceParams)->getRow()->balance ?? 0;
diff --git a/app/Helpers/ExcelMergeHelper.php b/app/Helpers/ExcelMergeHelper.php
index 36306692..60a8255e 100644
--- a/app/Helpers/ExcelMergeHelper.php
+++ b/app/Helpers/ExcelMergeHelper.php
@@ -17,10 +17,13 @@ class ExcelMergeHelper {
{
try {
log_message('debug', 'Attempting merge with original file order');
+ // echo "Attempting merge with original file order\n";
return self::processFiles($filePaths, $outputPath);
} catch (Exception $e) {
log_message('error', 'First attempt failed: ' . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine());
+ // echo "First attempt failed: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() . "\n";
log_message('debug', 'Retrying with reversed file order');
+ // echo "Retrying with reversed file order\n";
// Reverse the file order and try again
$reversedFiles = array_reverse($filePaths);
@@ -29,6 +32,7 @@ class ExcelMergeHelper {
return self::processFiles($reversedFiles, $outputPath);
} catch (Exception $e2) {
log_message('error', 'Both attempts failed. Last error: ' . $e2->getMessage() . ' in ' . $e2->getFile() . ' on line ' . $e2->getLine());
+ // echo "Both attempts failed. Last error: " . $e2->getMessage() . ' in ' . $e2->getFile() . ' on line ' . $e2->getLine() . "\n";
return null;
}
}
@@ -45,7 +49,9 @@ class ExcelMergeHelper {
private static function processFiles(array $filePaths, string $outputPath): string
{
log_message('debug', 'Starting Excel merge process');
+ // echo "Starting Excel merge process\n";
log_message('debug', 'Files to process: ' . json_encode($filePaths));
+ // echo "Files to process: " . json_encode($filePaths) . "\n";
if (empty($filePaths)) {
throw new Exception("No files provided to merge");
@@ -66,6 +72,7 @@ class ExcelMergeHelper {
// Save the merged file
log_message('debug', "Saving merged file to: {$outputPath}");
+ // echo "Saving merged file to: {$outputPath}\n";
$writer = IOFactory::createWriter($mergedSpreadsheet, 'Xlsx');
$writer->setPreCalculateFormulas(false);
$writer->save($outputPath);
@@ -76,6 +83,7 @@ class ExcelMergeHelper {
gc_collect_cycles();
log_message('debug', 'Excel merge process completed successfully');
+ // echo "Excel merge process completed successfully\n";
return $outputPath;
}
@@ -87,15 +95,17 @@ class ExcelMergeHelper {
* @param int|null $index
* @throws Exception
*/
- private static function processSingleFile(array $fileInfo, Spreadsheet $mergedSpreadsheet, int $index = null)
+ private static function processSingleFile(array $fileInfo, Spreadsheet $mergedSpreadsheet, ?int $index = null)
{
if (!isset($fileInfo['file_path']) || !file_exists($fileInfo['file_path'])) {
$path = $fileInfo['file_path'] ?? 'undefined';
log_message('error', "File " . ($index ?? 'base') . ": Invalid or missing file path: {$path}");
+ // echo "File " . ($index ?? 'base') . ": Invalid or missing file path: {$path}\n";
return;
}
log_message('debug', "Processing file " . ($index ?? 'base') . ": " . $fileInfo['file_path']);
+ // echo "Processing file " . ($index ?? 'base') . ": " . $fileInfo['file_path'] . "\n";
try {
// Load the source spreadsheet
@@ -105,6 +115,7 @@ class ExcelMergeHelper {
$worksheets = $sourceSpreadsheet->getAllSheets();
$totalSheets = count($worksheets);
log_message('debug', "Total sheets in file: " . $totalSheets);
+ // echo "Total sheets in file: " . $totalSheets . "\n";
$sheetsToMerge = $fileInfo['sheets'] ?? [];
@@ -114,26 +125,36 @@ class ExcelMergeHelper {
try {
$sheetName = $worksheet->getTitle();
log_message('debug', "Processing sheet: {$sheetName}");
+ // echo "Processing sheet: {$sheetName}\n";
// Generate unique sheet name before cloning
$newName = $sheetName;
$counter = 1;
- while (in_array($newName, $mergedSpreadsheet->getSheetNames())) {
- $newName = $sheetName . "_" . $counter++;
- log_message('debug', "Sheet name already exists. Trying new name: {$newName}");
+ // while (in_array($newName, $mergedSpreadsheet->getSheetNames())) {
+ // // $newName = $sheetName . "_" . $counter++;
+ // log_message('debug', "Sheet name already exists. Trying new name: {$newName}");
+ // // echo "Sheet name already exists. Trying new name: {$newName}\n";
+ // }
+
+ if (in_array($newName, $mergedSpreadsheet->getSheetNames())) {
+ $newName = $sheetName . '_' . $counter++;
+ $worksheet->setTitle($newName);
+
}
// Clone the worksheet and set the new name
- $clonedSheet = clone $worksheet;
- $clonedSheet->setTitle($newName);
+ // $clonedSheet = clone $worksheet;
+ // $clonedSheet->setTitle($newName);
// Add as external sheet
- $mergedSpreadsheet->addExternalSheet($clonedSheet);
+ $mergedSpreadsheet->addExternalSheet($worksheet);
log_message('debug', "Successfully added sheet: {$newName}");
+ // echo "Successfully added sheet: {$newName}\n";
} catch (Exception $e) {
log_message('error', "Error processing sheet {$sheetName} as new name {$newName}: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine());
+ // echo "Error processing sheet {$sheetName} as new name {$newName}: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() . "\n";
}
}
}
@@ -145,6 +166,7 @@ class ExcelMergeHelper {
} catch (Exception $e) {
log_message('error', "Error processing file {$fileInfo['file_path']}: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine());
+ // echo "Error processing file {$fileInfo['file_path']}: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() . "\n";
}
}
}
\ No newline at end of file
diff --git a/app/Helpers/ExcelSanitizeHelper.php b/app/Helpers/ExcelSanitizeHelper.php
index 5c2836a7..f4591bfa 100644
--- a/app/Helpers/ExcelSanitizeHelper.php
+++ b/app/Helpers/ExcelSanitizeHelper.php
@@ -29,6 +29,7 @@ class ExcelSanitizeHelper
$cleanData[$key] = self::sanitizeArrayData($value); // Recursive call for nested arrays
} elseif (is_string($value)) {
// Remove non-printable characters and trim whitespace from strings
+ $value = str_replace("\u00a0", " ", $value);
$cleanData[$key] = trim(preg_replace(self::$nonPrintablePattern, '', $value));
} else {
$cleanData[$key] = $value; // Keep non-string/non-array data as is
diff --git a/app/Helpers/GmailResponseHandler.php b/app/Helpers/GmailResponseHandler.php
index 8ff0ed35..beb731a7 100644
--- a/app/Helpers/GmailResponseHandler.php
+++ b/app/Helpers/GmailResponseHandler.php
@@ -74,7 +74,11 @@ class GmailResponseHandler{
if(in_array($key,$arr)){
$data[$key] = isset($value)?json_encode($value):null;
}else{
- $data[$key] = isset($value)?$value:null;
+ if($key == "mail" && is_array($value)){
+ $data[$key] = isset($value)?json_encode($value):null;
+ }else{
+ $data[$key] = isset($value)?$value:null;
+ }
}
}
}
diff --git a/app/Helpers/MailHelper.php b/app/Helpers/MailHelper.php
index 8fc4884b..cce74a9a 100755
--- a/app/Helpers/MailHelper.php
+++ b/app/Helpers/MailHelper.php
@@ -292,154 +292,164 @@ class MailHelper
}
}
- public static function send_email($params)
-{
- $myLogger = \Config\Services::mylogger();
-
- $emaill = $params['mail'];
- $subject = $params['subject'];
- $message = $params['message'];
- $attachments = isset($params['attachments']) ? $params['attachments'] : [];
- $common = isset($params['common']) ? $params['common'] : '';
- $bcc = isset($params['bcc']) ? $params['bcc'] : '';
- $cc = isset($params['cc']) ? $params['cc'] : '';
-
- $from_address = isset($params['from_mail']) && !empty($params['from_mail']) ? $params['from_mail'] : getenv('email.fromEmail');
- // $from_address = "claims@nhanceindia.in";
- try {
- $curl = curl_init();
-
- $postData = [
- 'from' => [
- 'address' => $from_address
- ],
- 'to' => [
- [
+ public static function send_email($params)
+ {
+ $myLogger = \Config\Services::mylogger();
+ if (is_array($params['mail'])) {
+ $emails = [];
+
+ foreach ($params['mail'] as $key => $emaill) {
+ $emails[] = [
'email_address' => [
'address' => $emaill
]
+ ];
+ }
+ } else {
+ $emails[] = [
+ 'email_address' => [
+ 'address' => $params['mail']
]
- ],
- 'subject' => $subject,
- 'htmlbody' => $message
- ];
-
- // Add CC recipients if provided
- if (!empty($cc)) {
- $ccList = explode(',', $cc);
- $ccList = array_map('trim', $ccList);
- $postData['cc'] = array_map(function($email) {
- return [
- 'email_address' => [
- 'address' => $email
- ]
- ];
- }, $ccList);
- }
- // Add BCC if present
- if (!empty($bcc)) {
- $bccList = explode(',', $bcc);
- $bccList = array_map('trim', $bccList);
- $postData['bcc'] = array_map(function($email) {
- return [
- 'email_address' => [
- 'address' => $email
- ]
- ];
- }, $bccList);
+ ];
}
- // Add BCC recipients if provided
- // if (!empty($bcc)) {
- // $postData['bcc'] = [];
- // // Handle both string and array inputs for BCC
- // $bccEmails = is_array($bcc) ? $bcc : [$bcc];
- // foreach ($bccEmails as $bccEmail) {
- // $postData['bcc'][] = [
- // 'email_address' => [
- // 'address' => $bccEmail
- // ]
- // ];
- // }
- // }
+ $subject = $params['subject'];
+ $message = $params['message'];
+ $attachments = isset($params['attachments']) ? $params['attachments'] : [];
+ $common = isset($params['common']) ? $params['common'] : '';
+ $bcc = isset($params['bcc']) ? $params['bcc'] : '';
+ $cc = isset($params['cc']) ? $params['cc'] : '';
- // Handle attachments
- if (!empty($attachments)) {
- $postData['attachments'] = [];
- foreach ($attachments as $attachment) {
- if (isset($attachment['filePath']) && file_exists($attachment['filePath'])) {
- // Determine MIME type dynamically
- $fileMimeType = mime_content_type($attachment['filePath']);
-
- $postData['attachments'][] = [
- 'content' => base64_encode(file_get_contents($attachment['filePath'])),
- 'name' => $attachment['fileName'],
- 'mime_type' => $fileMimeType,
+ $from_address = isset($params['from_mail']) && !empty($params['from_mail']) ? $params['from_mail'] : getenv('email.fromEmail');
+ // $from_address = "claims@nhanceindia.in";
+ try {
+ $curl = curl_init();
+
+ $postData = [
+ 'from' => [
+ 'address' => $from_address
+ ],
+ 'to' => $emails,
+ 'subject' => $subject,
+ 'htmlbody' => $message
+ ];
+
+ // Add CC recipients if provided
+ if (!empty($cc)) {
+ $ccList = explode(',', $cc);
+ $ccList = array_map('trim', $ccList);
+ $postData['cc'] = array_map(function ($email) {
+ return [
+ 'email_address' => [
+ 'address' => $email
+ ]
];
+ }, $ccList);
+ }
+ // Add BCC if present
+ if (!empty($bcc)) {
+ $bccList = explode(',', $bcc);
+ $bccList = array_map('trim', $bccList);
+ $postData['bcc'] = array_map(function ($email) {
+ return [
+ 'email_address' => [
+ 'address' => $email
+ ]
+ ];
+ }, $bccList);
+ }
+
+ // Add BCC recipients if provided
+ // if (!empty($bcc)) {
+ // $postData['bcc'] = [];
+ // // Handle both string and array inputs for BCC
+ // $bccEmails = is_array($bcc) ? $bcc : [$bcc];
+ // foreach ($bccEmails as $bccEmail) {
+ // $postData['bcc'][] = [
+ // 'email_address' => [
+ // 'address' => $bccEmail
+ // ]
+ // ];
+ // }
+ // }
+
+ // Handle attachments
+ if (!empty($attachments)) {
+ $postData['attachments'] = [];
+ foreach ($attachments as $attachment) {
+ if (isset($attachment['filePath']) && file_exists($attachment['filePath'])) {
+ // Determine MIME type dynamically
+ $fileMimeType = mime_content_type($attachment['filePath']);
+
+ $postData['attachments'][] = [
+ 'content' => base64_encode(file_get_contents($attachment['filePath'])),
+ 'name' => $attachment['fileName'],
+ 'mime_type' => $fileMimeType,
+ ];
+ }
}
}
- }
- curl_setopt_array($curl, [
- CURLOPT_URL => "https://api.zeptomail.in/v1.1/email",
- CURLOPT_RETURNTRANSFER => true,
- CURLOPT_ENCODING => "",
- CURLOPT_MAXREDIRS => 10,
- CURLOPT_TIMEOUT => 30,
- CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
- CURLOPT_CUSTOMREQUEST => "POST",
- CURLOPT_POSTFIELDS => json_encode($postData),
- CURLOPT_HTTPHEADER => [
- "accept: application/json",
- "authorization: Zoho-enczapikey " . getenv('ZEPTO_API_KEY'),
- "cache-control: no-cache",
- "content-type: application/json",
- ],
- ]);
+ curl_setopt_array($curl, [
+ CURLOPT_URL => "https://api.zeptomail.in/v1.1/email",
+ CURLOPT_RETURNTRANSFER => true,
+ CURLOPT_ENCODING => "",
+ CURLOPT_MAXREDIRS => 10,
+ CURLOPT_TIMEOUT => 30,
+ CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
+ CURLOPT_CUSTOMREQUEST => "POST",
+ CURLOPT_POSTFIELDS => json_encode($postData),
+ CURLOPT_HTTPHEADER => [
+ "accept: application/json",
+ "authorization: Zoho-enczapikey " . getenv('ZEPTO_API_KEY'),
+ "cache-control: no-cache",
+ "content-type: application/json",
+ ],
+ ]);
- $mail_result = curl_exec($curl);
- $err = curl_error($curl);
- curl_close($curl);
+ $mail_result = curl_exec($curl);
+ $err = curl_error($curl);
+ curl_close($curl);
- $res['params'] = $params;
- $MailDataHelper = new GmailResponseHandler();
- $apiResponse = json_decode($mail_result, true);
- $res['zepto_api'] = $apiResponse;
-
- if (isset($apiResponse['error'])) {
+ $res['params'] = $params;
+ $MailDataHelper = new GmailResponseHandler();
+ $apiResponse = json_decode($mail_result, true);
+ $res['zepto_api'] = $apiResponse;
+
+ if (isset($apiResponse['error'])) {
+ $response = $res;
+ $MailDataHelper->receive_and_distribute_param_to_functions($response);
+ return json_encode([
+ 'status' => 'failed',
+ 'code' => 404,
+ 'message' => 'Email Sent Failed...' . json_encode($params['mail']),
+ 'data' => $res
+ ], 404);
+ }
+
+ if (isset($apiResponse['data'])) {
+ $response = $res;
+ $MailDataHelper->receive_and_distribute_param_to_functions($response);
+ return json_encode([
+ 'status' => 'success',
+ 'code' => 200,
+ 'message' => 'Email Sent Successfully...' . json_encode($params['mail']),
+ 'data' => $res
+ ], 200);
+ }
+ } catch (\Exception $e) {
+ $msg['error'] = $e->getMessage();
+ $msg['params'] = $params;
$response = $res;
$MailDataHelper->receive_and_distribute_param_to_functions($response);
return json_encode([
'status' => 'failed',
- 'code' => 404,
- 'message' => 'Email Sent Failed...' . $emaill,
- 'data' => $res
- ], 404);
+ 'code' => 500,
+ 'data' => $msg
+ ], 500);
}
-
- if (isset($apiResponse['data'])) {
- $response = $res;
- $MailDataHelper->receive_and_distribute_param_to_functions($response);
- return json_encode([
- 'status' => 'success',
- 'code' => 200,
- 'message' => 'Email Sent Successfully...' . $emaill,
- 'data' => $res
- ], 200);
- }
-
- } catch (\Exception $e) {
- $msg['error'] = $e->getMessage();
- $msg['params'] = $params;
- $response = $res;
- $MailDataHelper->receive_and_distribute_param_to_functions($response);
- return json_encode([
- 'status' => 'failed',
- 'code' => 500,
- 'data' => $msg
- ], 500);
}
-}
+
public static function bulk_mail(array $mails = [])
{
$model = new JobModel();
diff --git a/app/Helpers/clientWebHookHelper.php b/app/Helpers/clientWebHookHelper.php
new file mode 100644
index 00000000..ba55eb18
--- /dev/null
+++ b/app/Helpers/clientWebHookHelper.php
@@ -0,0 +1,39 @@
+empModel = new EmployeeModel();
+ $this->empPolicyModel = new EmployeePolicyModel();
+ $this->claimModel = new TicketMasterModel();
+
+ }
+
+ public function mapObjectType($data_to_map, $objectType)
+ {
+ $mapped_data = [];
+ foreach ($objectType as $key => $value){
+ $mapped_data[$key] = $data_to_map[$value];
+ }
+
+ return $mapped_data;
+ }
+
+ public function insertData($mapped_data, $type){
+
+ $model = $type == 1 ? "empModel" : "claimModel";
+ $this->$model->insert($mapped_data);
+ }
+}
diff --git a/app/Helpers/excel_util_helper.php b/app/Helpers/excel_util_helper.php
index c90eebb3..141fe725 100755
--- a/app/Helpers/excel_util_helper.php
+++ b/app/Helpers/excel_util_helper.php
@@ -5,29 +5,35 @@ use App\Models\InsurerModel;
use Kint\Kint;
-if(!function_exists('calculate_days_bw_dates'))
-{
- function calculate_days_bw_dates(string $from_date = "", string $to_date ="",bool $include_start_date = true)
+if (!function_exists('calculate_days_bw_dates')) {
+ function calculate_days_bw_dates(string $from_date = "", string $to_date = "", bool $include_start_date = true)
{
- if($to_date == ""){ $currentDateTime = new DateTime(); }
- else{ $to_date = convert_string_to_date($to_date); $currentDateTime = new DateTime($to_date); }
+ if ($to_date == "") {
+ $currentDateTime = new DateTime();
+ } else {
+ $to_date = convert_string_to_date($to_date);
+ $currentDateTime = new DateTime($to_date);
+ }
- if($from_date == ""){ $passedDateTime = new DateTime(); }
- else{ $from_date = convert_string_to_date($from_date); $passedDateTime = new DateTime($from_date); }
-
- $interval = $currentDateTime->diff($passedDateTime);
- // $totalDays = $interval->days;
- // if ($include_start_date) {
- // $totalDays += 1;
- // }
- //$interval->totalDays = $totalDays;
- return $interval;
+ if ($from_date == "") {
+ $passedDateTime = new DateTime();
+ } else {
+ $from_date = convert_string_to_date($from_date);
+ $passedDateTime = new DateTime($from_date);
+ }
+ $interval = $currentDateTime->diff($passedDateTime);
+ // $totalDays = $interval->days;
+ // if ($include_start_date) {
+ // $totalDays += 1;
+ // }
+ //$interval->totalDays = $totalDays;
+ return $interval;
}
}
if (!function_exists('check_columns_name')) {
- function check_columns_name($definedColumns,$excelColumns)
+ function check_columns_name($definedColumns, $excelColumns)
{
$mismatchedColumns = [];
@@ -36,7 +42,7 @@ if (!function_exists('check_columns_name')) {
$definedColName = $definedCol['col_name'];
if (strtolower(strip_tags(trim($excelColumns[$definedColIdx]))) !== strtolower($definedColName)) {
- $mismatchedColumns[] = "Column order conflict. Column order no ".($definedColIdx + 1)." expected : ".$definedColName." and received : ".$excelColumns[$definedColIdx]." ";
+ $mismatchedColumns[] = "Column order conflict. Column order no " . ($definedColIdx + 1) . " expected : " . $definedColName . " and received : " . $excelColumns[$definedColIdx] . " ";
}
}
@@ -47,8 +53,9 @@ if (!function_exists('check_columns_name')) {
if (!function_exists('check_row_is_empty_or_null')) {
- function check_row_is_empty_or_null($arr) {
- unset($arr[0]);// unset SNO in the array, becoz we need to check only datapoints are empty not SNo, it may added by accidentally
+ function check_row_is_empty_or_null($arr)
+ {
+ unset($arr[0]); // unset SNO in the array, becoz we need to check only datapoints are empty not SNo, it may added by accidentally
foreach ($arr as $item) {
if ($item !== null && !empty($item)) {
return false; // If any item is not empty or not null, return false
@@ -60,263 +67,234 @@ if (!function_exists('check_row_is_empty_or_null')) {
if (!function_exists('check_excel_date_format')) {
- function check_excel_date_format($dateString,$format)
+ function check_excel_date_format($dateString, $format)
{
-
- if($dateString == ""){ return array('status' => true); }
+
+ if ($dateString == "") {
+ return array('status' => true);
+ }
$date = DateTime::createFromFormat('d-M-Y', $dateString);
-
+
if ($date && $date->format('d-M-Y') == $dateString) {
- return array('status' => true);
+ return array('status' => true);
} else {
- $res = convert_string_to_date($dateString);
- if(!$res)
- {
- return array('status' => false,'error' => "wrong date format: Expected 'd-M-Y' and received $dateString");
- }
- else
- {
- return array('status' => true);
- }
+ $res = convert_string_to_date($dateString);
+ if (!$res) {
+ return array('status' => false, 'error' => "wrong date format: Expected 'd-M-Y' and received $dateString");
+ } else {
+ return array('status' => true);
+ }
}
}
}
-if(!function_exists('check_relationship'))
-{
- function check_relationship($row,$relationship,$policy_terms)
+if (!function_exists('check_relationship')) {
+ function check_relationship($row, $relationship, $policy_terms)
{
// print_r($relationship);
// echo ' ';
- if($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I','A','DA','MI']))// check rule only of action column data available
+ if ($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I', 'A', 'DA', 'MI'])) // check rule only of action column data available
{
- if($row[5] != null && $row[4] != null)//$row[5] = relationship $row[4] = Gender
+ if ($row[5] != null && $row[4] != null) //$row[5] = relationship $row[4] = Gender
{
$slug = \Config\Services::slug();
$col = $slug->slugify($row[5]);
- // echo $col;//die();
- if($col != 'self' && $col != 'spouse')
- {
- if(!isset($relationship[ $col ]))
- {
- return array('status' => false,'error' => 'Rule Conflict: Unknown Relationship');
+ // echo $col;//die();
+ if ($col != 'self' && $col != 'spouse') {
+ if (!isset($relationship[$col])) {
+ return array('status' => false, 'error' => 'Rule Conflict: Unknown Relationship');
}
$family_floaters = isset($policy_terms['family_floaters']);
- if($family_floaters)
- {
- if(isset($relationship[ $col ]) && $relationship[ $col ]['gender'] != $row[4])
- {
- $error = "Gender relationship conflict: Expected ".$relationship[ $col ]['gender'].", received $row[4]";
- return array('status' => false,'error' => $error);
+ if ($family_floaters) {
+ if (isset($relationship[$col]) && $relationship[$col]['gender'] != $row[4]) {
+ $error = "Gender relationship conflict: Expected " . $relationship[$col]['gender'] . ", received $row[4]";
+ return array('status' => false, 'error' => $error);
}
- }
- else // if family_floaters not set the its GPA, reject all other dependents
+ } else // if family_floaters not set the its GPA, reject all other dependents
{
- if($col != 'self')
- {
+ if ($col != 'self') {
$error = "Dependent(s) are not allowed";
- return array('status' => false,'error' => $error);
+ return array('status' => false, 'error' => $error);
}
}
-
-
}
return array('status' => true);
+ } else {
+ return array('status' => false, 'error' => 'Rule Conflict: Both Relationship and Gender required for check relationship conflict');
}
- else
- {
- return array('status' => false,'error' => 'Rule Conflict: Both Relationship and Gender required for check relationship conflict');
- }
- }
- else { return array('status' => true); } // in else condition no need to check rule, just return true
+ } else {
+ return array('status' => true);
+ } // in else condition no need to check rule, just return true
}
}
-if(!function_exists('check_doj'))
-{
+if (!function_exists('check_doj')) {
function check_doj($row)
{
- if($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I','A','DA','MI']))// check rule only of action column data available
+ if ($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I', 'A', 'DA', 'MI'])) // check rule only of action column data available
{
$slug = \Config\Services::slug();
$relationship = $slug->slugify($row[5]);
// echo $relationship;echo $row[7];
- if($relationship == 'self' && $row[8] == "") { return array('status' => false,'error' => "DOJ mandantory for self"); }
+ if ($relationship == 'self' && $row[8] == "") {
+ return array('status' => false, 'error' => "DOJ mandantory for self");
+ }
return array('status' => true);
- }
- else { return array('status' => true); } // in else condition no need to check rule, just return true
+ } else {
+ return array('status' => true);
+ } // in else condition no need to check rule, just return true
}
}
-if(!function_exists('check_doc'))
-{
+if (!function_exists('check_doc')) {
- function check_doc($row,$policy_details)
+ function check_doc($row, $policy_details)
{
- if($row['current_action'] != null && $row[7] != null && $row[7] != '' && in_array(strtoupper($row['current_action']), ['A','DA']))// check rule only of action column data available
+ if ($row['current_action'] != null && $row[7] != null && $row[7] != '' && in_array(strtoupper($row['current_action']), ['A', 'DA'])) // check rule only of action column data available
{
// dd($policy_details);
$dateString = convert_string_to_date($row[7]);
- if($dateString)
- {
+ if ($dateString) {
$date = new DateTime($dateString);
$startDate = new DateTime($policy_details[0]->policy_start_date);
$endDate = new DateTime($policy_details[0]->policy_end_date);
if ($date >= $startDate && $date <= $endDate) {
- return array('status' => true);
+ return array('status' => true);
} else {
- return array('status' => false,'error' => 'the given date of coverage is not between policy start/end date');
+ return array('status' => false, 'error' => 'the given date of coverage is not between policy start/end date');
}
+ } else {
+ return array('status' => false, 'error' => 'date format error');
}
- else
- {
- return array('status' => false,'error' => 'date format error');
- }
- }
- else { return array('status' => true); } // in else condition no need to check rule, just return true
+ } else {
+ return array('status' => true);
+ } // in else condition no need to check rule, just return true
}
}
-if(!function_exists('check_employee_band'))
-{
- function check_employee_band($row,$policy_terms,$slab_details)
+if (!function_exists('check_employee_band')) {
+ function check_employee_band($row, $policy_terms, $slab_details)
{
- if($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I','A','DA','MI']))// check rule only of action column data available
+ if ($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I', 'A', 'DA', 'MI'])) // check rule only of action column data available
{
$is_emp_band_needed = $slab_details['grid_master']['emp_band'];
// $is_emp_band_needed = true;
- if($slab_details['grid_master']['ui_type'] == 1) //gpa rack rate 1
+ if ($slab_details['grid_master']['ui_type'] == 1) //gpa rack rate 1
{
- if($slab_details['slab_rates'][0]['si_or_bp'] == 3)
- {
+ if ($slab_details['slab_rates'][0]['si_or_bp'] == 3) {
$is_emp_band_needed = true;
}
}
$slug = \Config\Services::slug();
$relationship = $slug->slugify($row[5]);
// echo $relationship;echo $row[7];
- if($is_emp_band_needed && $relationship == 'self' && $row[10] == "") { return array('status' => false,'error' => "Band mandantory for self"); }
- else if($is_emp_band_needed && $relationship == 'self' && $row[10] != "")
- {
- $received_grade = $row[10];
- $found = false;
- foreach ($slab_details['slab_rates'] as $skey => $slab_value)
- {
- if($slab_value['grade'] == $received_grade)
- {
+ if ($is_emp_band_needed && $relationship == 'self' && $row[10] == "") {
+ return array('status' => false, 'error' => "Band mandantory for self");
+ } else if ($is_emp_band_needed && $relationship == 'self' && $row[10] != "") {
+ $received_grade = $row[10];
+ $found = false;
+ foreach ($slab_details['slab_rates'] as $skey => $slab_value) {
+ if ($slab_value['grade'] == $received_grade) {
$found = true;
break;
}
}
- if(!$found) { return array('status' => false,'error' => "Emp band/Grade not found"); }
+ if (!$found) {
+ return array('status' => false, 'error' => "Emp band/Grade not found");
+ }
}
return array('status' => true);
- }else { return array('status' => true); } // in else condition no need to check rule, just return true
+ } else {
+ return array('status' => true);
+ } // in else condition no need to check rule, just return true
}
}
-if(!function_exists('check_si'))
-{
- function check_si($row,$policy_details,$slab_details)
+if (!function_exists('check_si')) {
+ function check_si($row, $policy_details, $slab_details)
{
// Kint::dump($policy_details);
$policy_details = (array)$policy_details[0];
// dd($policy_details);
- $return_array = array('status' => true,'error' => '');
+ $return_array = array('status' => true, 'error' => '');
$is_si_found = false;
$is_age_slab_found = false;
- if(($policy_details['policy_type_id'] == 1 || $policy_details['policy_type_id'] == 6 || $policy_details['policy_type_id'] == 7) && $slab_details['slab_rates'][0]['policy_grid_id'] == 1 && $slab_details['slab_rates'][0]['si_or_bp'] == 2) // GPA && grid type 1 for GPA && sub type is basic pay
+ if (($policy_details['policy_type_id'] == 1 || $policy_details['policy_type_id'] == 6 || $policy_details['policy_type_id'] == 7) && $slab_details['slab_rates'][0]['policy_grid_id'] == 1 && $slab_details['slab_rates'][0]['si_or_bp'] == 2) // GPA && grid type 1 for GPA && sub type is basic pay
{
- $is_si_found = true;
- $is_age_slab_found = true;
- $return_array = array('status' => true,'error' => '');
+ $is_si_found = true;
+ $is_age_slab_found = true;
+ $return_array = array('status' => true, 'error' => '');
}
- if($policy_details['policy_type_id'] == 3 && strtolower($row['5']) == 'self') // if GMC parent and current relation is self then skip this . so set all true;
+ if ($policy_details['policy_type_id'] == 3 && strtolower($row['5']) == 'self') // if GMC parent and current relation is self then skip this . so set all true;
{
- $is_si_found = true;
- $is_age_slab_found = true;
- $return_array = array('status' => true,'error' => '');
+ $is_si_found = true;
+ $is_age_slab_found = true;
+ $return_array = array('status' => true, 'error' => '');
}
- if($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I','A','DA','SI','MI']))// check rule only of action column data available
+ if ($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I', 'A', 'DA', 'SI', 'MI'])) // check rule only of action column data available
{
$received_si = $row['current_action'] == 'SI' ? $row[3] : $row[6];
- foreach ($slab_details['slab_rates'] as $skey => $slab_value)
+ foreach ($slab_details['slab_rates'] as $skey => $slab_value) {
+ if ($is_si_found && $is_age_slab_found) {
+ break;
+ }
+
+ if (!$is_si_found && $slab_value['si'] == $received_si) //match si amount
{
- if($is_si_found && $is_age_slab_found)
- {
- break;
- }
+ // echo 'found';
+ $is_si_found = true;
+ }
- if(!$is_si_found && $slab_value['si'] == $received_si) //match si amount
+ // check age slab
+ if (in_array(strtoupper($row['current_action']), ['I', 'A', 'DA', 'MI']) && (($slab_value['premium_type'] == 1 && strtolower($row['5']) == 'self') || ($slab_value['premium_type'] == 2))) {
+ if ($row[3] != '' && $row[3] != null) // dob
{
- // echo 'found';
- $is_si_found = true;
- }
-
- // check age slab
- if(in_array(strtoupper($row['current_action']), ['I','A','DA','MI']) && (($slab_value['premium_type'] == 1 && strtolower($row['5']) == 'self' ) || ($slab_value['premium_type'] == 2) ) )
- {
- if($row[3] != '' && $row[3] != null)// dob
- {
- $dob = convert_string_to_date($row[3]);
- if($dob !== false)
- {
- // echo $row[3].' - '.$dob;echo ' ';
- $currentDateTime = new DateTime();//die();
- $passedDateTime = new DateTime($dob);
- $interval = $currentDateTime->diff($passedDateTime);
- if(!$is_age_slab_found)
- {
- if(isset($slab_value['age_from']) && isset($slab_value['age_to']))
- {
- if($slab_value['age_from'] !== null && $slab_value['age_to'] !== null && $slab_value['age_from'] <= $interval->y && $slab_value['age_to'] >= $interval->y && $slab_value['si'] == $received_si)
- {
- $is_age_slab_found = true;// send true if age slab found
- }
- }
- else
- {
- $is_age_slab_found = true;// send true if age conditin is not applicable
- }
-
+ $dob = convert_string_to_date($row[3]);
+ if ($dob !== false) {
+ // echo $row[3].' - '.$dob;echo ' ';
+ $currentDateTime = new DateTime(); //die();
+ $passedDateTime = new DateTime($dob);
+ $interval = $currentDateTime->diff($passedDateTime);
+ if (!$is_age_slab_found) {
+ if (isset($slab_value['age_from']) && isset($slab_value['age_to'])) {
+ if ($slab_value['age_from'] !== null && $slab_value['age_to'] !== null && $slab_value['age_from'] <= $interval->y && $slab_value['age_to'] >= $interval->y && $slab_value['si'] == $received_si) {
+ $is_age_slab_found = true; // send true if age slab found
}
+ } else {
+ $is_age_slab_found = true; // send true if age conditin is not applicable
}
+ }
}
-
}
- else
- {
- $is_age_slab_found = true;// send true if age conditin is not applicable
- $is_si_found = true;
- }//end of check age slab
- }// end of for loop
+ } else {
+ $is_age_slab_found = true; // send true if age conditin is not applicable
+ $is_si_found = true;
+ } //end of check age slab
+ } // end of for loop
}
-
- if(!$is_si_found)
- {
+
+ if (!$is_si_found) {
$return_array['status'] = false;
$return_array['error'] = "Sum insured not found";
}
- if(!$is_age_slab_found)
- {
+ if (!$is_age_slab_found) {
$return_array['status'] = false;
- $return_array['error'] = !empty($return_array['error']) ? ($return_array['error'].', '.'Sum insured not configured for this age slab') : 'Sum insured not configured for this age slab';
+ $return_array['error'] = !empty($return_array['error']) ? ($return_array['error'] . ', ' . 'Sum insured not configured for this age slab') : 'Sum insured not configured for this age slab';
}
- if(empty($received_si))
- {
+ if (empty($received_si)) {
$return_array['status'] = false;
$return_array['error'] = "Sum insured value mandantory";
}
@@ -325,222 +303,215 @@ if(!function_exists('check_si'))
}
}
-if(!function_exists('check_basic_pay'))
-{
- function check_basic_pay($row,$policy_terms,$slab_details)
+if (!function_exists('check_basic_pay')) {
+ function check_basic_pay($row, $policy_terms, $slab_details)
{
- if($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I','A','DA','MI']))// check rule only of action column data available
+ if ($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I', 'A', 'DA', 'MI'])) // check rule only of action column data available
{
$is_basic_pay_needed = $slab_details['grid_master']['basicpay'];
// $is_basic_pay_needed = true;
$slug = \Config\Services::slug();
$relationship = $slug->slugify($row[5]);
// echo $relationship;echo $row[7];
- if($is_basic_pay_needed && $relationship == 'self' && $row[9] == "") { return array('status' => false,'error' => "Basic pay mandantory for self"); }
+ if ($is_basic_pay_needed && $relationship == 'self' && $row[9] == "") {
+ return array('status' => false, 'error' => "Basic pay mandantory for self");
+ }
return array('status' => true);
- }else { return array('status' => true); } // in else condition no need to check rule, just return true
+ } else {
+ return array('status' => true);
+ } // in else condition no need to check rule, just return true
}
}
-if (!function_exists('check_dob_diff'))
-{
- function check_dob_diff($row,$relationships,$default_age_ratio,$policy_details) {
- if($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I','A','DA','MI']))// check rule only of action column data available
+if (!function_exists('check_dob_diff')) {
+ function check_dob_diff($row, $relationships, $default_age_ratio, $policy_details)
+ {
+ if ($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I', 'A', 'DA', 'MI'])) // check rule only of action column data available
{
- if($row[3] != null && $row[5] != null)
- {
- $dateString = convert_string_to_date($row[3]);
- if ($dateString === false)
- {
- return array('status' => false,'error' => 'Not a valid Date');
- }
- // return array('status' => true);
- $dob = $dateString;
- //$currentDateTime = new DateTime();//previously dob calculated from current date time
- $temp_date = ($row[7] != null && $row[7] != "") ? convert_string_to_date($row[7]) : $policy_details[0]->policy_start_date; //pick date of coverage from row if not then use policy start date as from to calculate DOB
- $currentDateTime = new DateTime($temp_date);//later DOB calculated from date of coverage or policy_start_date
- // die();
- $passedDateTime = new DateTime($dob);
- $interval = $currentDateTime->diff($passedDateTime);
- //remap default age ratio data into relationship array
- if(count($default_age_ratio))
- {
- $relationships = remap_default_age_ratio_into_relationship($relationships,$default_age_ratio);
- }
- $slug = \Config\Services::slug();
- $relationship = $slug->slugify($row[5]);
- $age_min = isset($relationships[$relationship]['age_min']) ? $relationships[$relationship]['age_min'] : NULL;
- $age_max = isset($relationships[$relationship]['age_max']) ? $relationships[$relationship]['age_max'] : NULL;
- if($age_min !== null && $age_min > $interval->y)
- {
- return array('status' => false,'error' => "Age conflict : minimum $age_min yrs allowed, received $interval->y");
- }
- if($age_max !== null && $age_max < $interval->y)
- {
- return array('status' => false,'error' => "Age conflict : maximum $age_max yrs allowed, received $interval->y");
- }
- return array('status' => true);
+ if ($row[3] != null && $row[5] != null) {
+ $dateString = convert_string_to_date($row[3]);
+ if ($dateString === false) {
+ return array('status' => false, 'error' => 'Not a valid Date');
}
- else
- {
- return array('status' => false,'error' => 'Rule Conflict: Both DOB and Relationship required for age check');
+ // return array('status' => true);
+ $dob = $dateString;
+ //$currentDateTime = new DateTime();//previously dob calculated from current date time
+ $temp_date = ($row[7] != null && $row[7] != "") ? convert_string_to_date($row[7]) : $policy_details[0]->policy_start_date; //pick date of coverage from row if not then use policy start date as from to calculate DOB
+ $currentDateTime = new DateTime($temp_date); //later DOB calculated from date of coverage or policy_start_date
+ // die();
+ $passedDateTime = new DateTime($dob);
+ $interval = $currentDateTime->diff($passedDateTime);
+ //remap default age ratio data into relationship array
+ if (count($default_age_ratio)) {
+ $relationships = remap_default_age_ratio_into_relationship($relationships, $default_age_ratio);
}
- }else { return array('status' => true); } // in else condition no need to check rule, just return true
+ $slug = \Config\Services::slug();
+ $relationship = $slug->slugify($row[5]);
+ $age_min = isset($relationships[$relationship]['age_min']) ? $relationships[$relationship]['age_min'] : NULL;
+ $age_max = isset($relationships[$relationship]['age_max']) ? $relationships[$relationship]['age_max'] : NULL;
+ if ($age_min !== null && $age_min > $interval->y) {
+ return array('status' => false, 'error' => "Age conflict : minimum $age_min yrs allowed, received $interval->y");
+ }
+ if ($age_max !== null && $age_max < $interval->y) {
+ return array('status' => false, 'error' => "Age conflict : maximum $age_max yrs allowed, received $interval->y");
+ }
+ return array('status' => true);
+ } else {
+ return array('status' => false, 'error' => 'Rule Conflict: Both DOB and Relationship required for age check');
+ }
+ } else {
+ return array('status' => true);
+ } // in else condition no need to check rule, just return true
}
}
-if (!function_exists('data_group_by_family'))
-{
- function data_group_by_family($emp_data,$data_source = 'excel',$action = '')
+if (!function_exists('data_group_by_family')) {
+ function data_group_by_family($emp_data, $data_source = 'excel', $action = '')
{
$result = [];
// Kint::dump($emp_data);
- foreach ($emp_data as $rkey => $row)
- {
- if($data_source == 'excel')
- {
- if(!check_row_is_empty_or_null($row))
- {
- if($action == 'enrollment') //if action is enrollment transform current row into inception row, becoz we treat enrollment as inception
+ foreach ($emp_data as $rkey => $row) {
+ if ($data_source == 'excel') {
+ if (!check_row_is_empty_or_null($row)) {
+ if ($action == 'enrollment') //if action is enrollment transform current row into inception row, becoz we treat enrollment as inception
{
$row = transform_enrollment_row_to_inception_row($row);
}
- if(strtolower($row[5]) == 'self' && isset($result[$row[1]]))
- {
- array_unshift($result[$row[1]],$row);
- }else
- {
- $result[$row[1]][] = $row;
+ if (isset($row[5]) && strtolower($row[5]) == 'self' && isset($result[$row[1]])) {
+ array_unshift($result[$row[1]], $row);
+ } else {
+ $result[$row[1]][] = $row;
}
}
- }else if($data_source = 'db')
- {
- if(strtolower($row['relationship']) == 'self' && isset($result[$row['emp_code']]))
- {
- array_unshift($result[$row['emp_code']],$row);
- }else
- {
- $result[$row['emp_code']][] = $row;
- }
+ } else if ($data_source = 'db') {
+ if (strtolower($row['relationship']) == 'self' && isset($result[$row['emp_code']])) {
+ array_unshift($result[$row['emp_code']], $row);
+ } else {
+ $result[$row['emp_code']][] = $row;
+ }
}
-
}
return $result;
}
}
-if (!function_exists('name_dup_check_within_family'))
-{
+if (!function_exists('name_dup_check_within_family')) {
function name_dup_check_within_family($family_data)
{
$result = [];
$temp = [];
- foreach ($family_data as $rkey => $row)
- {
- if(in_array($row[2],$temp))
- {
- array_push($result,$row[0]);
- }
- else
- {
+ foreach ($family_data as $rkey => $row) {
+ if (in_array($row[2], $temp)) {
+ // Kint::dump($row);
+ $emp_code = $row[1];
+ $tempFam = null;
+ foreach ($family_data as $family) {
+ if ($family[1] == $emp_code && !isset($family['temp'])) {
+ $tempFam = $family;
+ break; // Stop at the first match
+ }
+ }
+ // Kint::dump($tempFam);
+ // die();
+
+ array_push($result, $tempFam[0]);
+ } else {
array_push($temp, $row[2]);
}
-
}
-
+ // dd($result);
return $result;
}
}
-if (!function_exists('check_self_available_in_family'))
-{
+if (!function_exists('check_self_available_in_family')) {
function check_self_available_in_family($family_data)
{
-
+
$is_self_found = false;
-
- $row_id_from_excel = array_filter($family_data,function($item){ return !isset($item['temp']);});
+
+ $row_id_from_excel = array_filter($family_data, function ($item) {
+ return !isset($item['temp']);
+ });
// Kint::dump($row_id_from_excel);
$row_id_from_excel = current($row_id_from_excel); // get excel sno/rowid of employee amoung familiy array where this array has both data from excel and db
$row_id_from_excel = $row_id_from_excel[0];
- foreach ($family_data as $rkey => $row)
- {
- if($row[5] != null && strtolower($row[5]) == 'self')//$row[5] = relationship $row[4] = Gender
+ foreach ($family_data as $rkey => $row) {
+ if ($row[5] != null && strtolower($row[5]) == 'self') //$row[5] = relationship $row[4] = Gender
{
$is_self_found = true;
break;
}
-
}
- return ['is_self_found' => $is_self_found,'emp_code' => $family_data[0][1],'row_id' => $row_id_from_excel];
+ return ['is_self_found' => $is_self_found, 'emp_code' => $family_data[0][1], 'row_id' => $row_id_from_excel];
}
}
-if (!function_exists('name_and_empid_check_in_db'))
-{
- function name_and_empid_check_in_db($family_data,$actionArr)
+if (!function_exists('name_and_empid_check_in_db')) {
+ function name_and_empid_check_in_db($family_data, $actionArr)
{
$employeeModel = new EmployeeModel();
- $result = ['del' => [],'i' => []];
+ $result = ['del' => [], 'i' => []];
$client_id = $actionArr['client_id'];
$policy_id = $actionArr['policy_id'];
$client_branch_id = $actionArr['client_branch_id'];
$current_action = $actionArr['action'];
- foreach ($family_data as $rkey => $row)
- {
- if($current_action != 'dependent_addition' || (isset($row['temp']) && $row['temp']['source'] != 'db'))
- {
+ foreach ($family_data as $rkey => $row) {
+ if ($current_action != 'dependent_addition' || (isset($row['temp']) && $row['temp']['source'] != 'db')) {
$res = $employeeModel
- ->join('client_policy cp',"employees.client_id = cp.client_id")
- ->join('employee_polices ep',"cp.id = ep.client_policy_id AND employees.id = ep.employee_id")
- ->where("cp.id",$policy_id)
- ->where("employees.client_id",$client_id)
- ->where("employees.client_branch_id",$client_branch_id)
- ->where("employees.is_active",1)
- ->where("employees.emp_status",'active')
- ->where("ep.is_active",1)
- ->where("ep.status",'active')
- // ->where("ep.client_id",$client_id)
- ->where('name',trim($row[2]))->where('emp_code',trim($row[1]))
- ->findAll();
-
- // kint::dump($employeeModel->getLastQuery()->getQuery());
-
-
- if(($current_action == 'deletion' || $current_action == 'correction' || $current_action == 'si_enhancement') && !count($res))
- {
- array_push($result['del'],$row[0]);
+ ->join('client_policy cp', "employees.client_id = cp.client_id")
+ ->join('employee_polices ep', "cp.id = ep.client_policy_id AND employees.id = ep.employee_id")
+ ->where("cp.id", $policy_id)
+ ->where("employees.client_id", $client_id)
+ ->where("employees.client_branch_id", $client_branch_id)
+ ->where("employees.is_active", 1)
+ ->where("employees.emp_status", 'active')
+ ->where("ep.is_active", 1)
+ ->where("ep.status", 'active')
+ // ->where("ep.client_id",$client_id)
+ ->where('name', trim($row[2]))->where('emp_code', trim($row[1]))
+ ->findAll();
+
+ // kint::dump($employeeModel->getLastQuery()->getQuery());
+
+
+ if (($current_action == 'deletion' || $current_action == 'correction' || $current_action == 'si_enhancement') && !count($res)) {
+ array_push($result['del'], $row[0]);
+ }
+ if (($current_action == 'inception' || $current_action == 'dependent_addition' || $current_action == 'addition' || $current_action == 'enrollment') && count($res)) {
+ $emp_code = $row[1];
+ $tempFam = null;
+ foreach ($family_data as $family) {
+ if ($family[1] == $emp_code && !isset($family['temp'])) {
+ $tempFam = $family;
+ break; // Stop at the first match
+ }
}
- if(($current_action == 'inception' || $current_action == 'dependent_addition' || $current_action == 'addition' || $current_action == 'enrollment') && count($res))
- {
- array_push($result['i'],$row[0]);
- }
- }
-
-
+ array_push($result['i'], $tempFam[0]);
+ }
+ }
}
return $result;
}
}
-if (!function_exists('check_dependent_conflict'))
-{
- function check_dependent_conflict($family_data,$policy_terms,$actionArr,$is_lgbtq)
- {
+if (!function_exists('check_dependent_conflict')) {
+ function check_dependent_conflict($family_data, $policy_terms, $actionArr, $is_lgbtq)
+ {
// dd($family_data,$policy_terms,$actionArr,$is_lgbtq);
$result = ['status' => true];
-
+
$self_gender = null;
$spouse_gender = null;
-
+
$allowed_spouse_count = 0;
$received_spouse_count = 0;
$allowed_child_count = 0;
@@ -551,11 +522,10 @@ if (!function_exists('check_dependent_conflict'))
$received_parent_in_laws_count = 0;
$overall_famility_relationships = [];
$self_emp_row_id = null;
- $temp_counts = [2,3,4,5,6,7,8,9,10]; //temp variable for check relation repetaed count
+ $temp_counts = [2, 3, 4, 5, 6, 7, 8, 9, 10]; //temp variable for check relation repetaed count
$slug = \Config\Services::slug();
- // dd($policy_terms);
- if(isset($policy_terms['family_floater']) && !empty($policy_terms['family_floaters']))
- {
+ // dd($policy_terms);
+ if (isset($policy_terms['family_floater']) && !empty($policy_terms['family_floaters'])) {
// $temp_string = implode(" ",$policy_terms['family_floaters']);
$temp = $policy_terms['family_floaters'];
@@ -566,131 +536,118 @@ if (!function_exists('check_dependent_conflict'))
$allowed_parents_count = $temp['either-parents-pil'] == 0 ? $temp['parents'] : 0;
$allowed_parent_in_laws_count = $temp['either-parents-pil'] == 0 ? $temp['parents-in-law'] : 0;
// dd($allowed_adults == 0);
- foreach ($family_data as $key => $row)
- {
+ $firstNonTemp = null;
+
+ foreach ($family_data as $family) {
+ if (!isset($family['temp'])) {
+ $firstNonTemp = $family;
+ break;
+ }
+ }
+ // Kint::dump($firstNonTemp);
+ foreach ($family_data as $key => $row) {
// dd($family_data[0][0]);
$relationship = $slug->slugify($row[5]);
- if($actionArr != 'deletion' && $relationship != 'son' && $relationship != 'daughter')
- {
+ if ($actionArr != 'deletion' && $relationship != 'son' && $relationship != 'daughter') {
array_push($overall_famility_relationships, $relationship);
}
- if($relationship == 'self')
- {
+ if ($relationship == 'self') {
$self_gender = $row[4];
- $self_emp_row_id = $row[0];
+ $self_emp_row_id = isset($row['temp']) ? null : $row[0];
}
- if($relationship == 'spouse')
- {
+ if ($relationship == 'spouse') {
$spouse_gender = $row[4];
$received_spouse_count = $received_spouse_count + 1;
}
- if($relationship == 'son' || $relationship == 'daughter')
- {
+ if ($relationship == 'son' || $relationship == 'daughter') {
$received_child_count = $received_child_count + 1;
}
- if($relationship == 'father' || $relationship == 'mother')
- {
+ if ($relationship == 'father' || $relationship == 'mother') {
$received_parents_count = $received_parents_count + 1;
}
- if($relationship == 'father-in-law' || $relationship == 'mother-in-law')
- {
+ if ($relationship == 'father-in-law' || $relationship == 'mother-in-law') {
$received_parent_in_laws_count = $received_parent_in_laws_count + 1;
}
-
}
-
+
// print_r($overall_famility_relationships);
// echo ' ';
- if($actionArr != 'deletion')
- {
+ if ($actionArr != 'deletion') {
$repeated_relationships_count = array_count_values($overall_famility_relationships);
- // print_r($repeated_relationships_count);
- // echo ' ';
- $repeated_count = array_intersect($repeated_relationships_count,$temp_counts);
- if(is_array($repeated_count) && count($repeated_count))
- {
+ // print_r($repeated_relationships_count);
+ // echo ' ';
+ $repeated_count = array_intersect($repeated_relationships_count, $temp_counts);
+ if (is_array($repeated_count) && count($repeated_count)) {
+ // Kint::dump($firstNonTemp);die();
$result['status'] = false;
- $result['error_data'][] = ['code' => 13,'col_name' => 'relationship','msg' => 'Rule conflict: Twofold relationship found within family','row_id' => $family_data[0][0]];
+ $result['error_data'][] = ['code' => 13, 'col_name' => 'relationship', 'msg' => 'Rule conflict: Twofold relationship found within family', 'row_id' => $firstNonTemp[0]];
}
}
// print_r($repeated_count);
// echo "===============";
// echo " ";
-
+
// print_r(array_values(array_count_values($overall_famility_relationships)));
// print_r(in_array(2,array_values(array_count_values($overall_famility_relationships))));
//check if this policy is allowed LGBTQ
- if($is_lgbtq == 0)
- {
- if($self_gender && $spouse_gender && $self_gender == $spouse_gender)
- {
+ if ($is_lgbtq == 0) {
+ if ($self_gender && $spouse_gender && $self_gender == $spouse_gender) {
$result['status'] = false;
- $result['error_data'][] = ['code' => 4,'col_name' => 'gender','msg' => 'Rule conflict: Self and Spouse cannot be same gender','row_id' => (isset($self_emp_row_id) ? $self_emp_row_id : $family_data[0][0])];
+ $result['error_data'][] = ['code' => 4, 'col_name' => 'gender', 'msg' => 'Rule conflict: Self and Spouse cannot be same gender', 'row_id' => (isset($self_emp_row_id) ? $self_emp_row_id : $firstNonTemp[0])];
}
}
- if(($allowed_spouse_count < $received_spouse_count) || ($allowed_child_count < $received_child_count) )
- {
+ if (($allowed_spouse_count < $received_spouse_count) || ($allowed_child_count < $received_child_count)) {
$result['status'] = false;
- $result['error_data'][] = ['code' => 12,'col_name' => 'sno','msg' => 'Rule conflict: As per policy, count of dependents has exceeded configured count','row_id' => (isset($self_emp_row_id) ? $self_emp_row_id : $family_data[0][0])];//dependent count mismatch
+ $result['error_data'][] = ['code' => 12, 'col_name' => 'sno', 'msg' => 'Rule conflict: As per policy, count of dependents has exceeded configured count', 'row_id' => (isset($self_emp_row_id) ? $self_emp_row_id : $firstNonTemp[0])]; //dependent count mismatch
}
// || ($allowed_parents_count < $received_parents_count) || ($allowed_parent_in_laws_count < $received_parent_in_laws_count)
- if($allowed_adults == 1 && $received_parents_count && $received_parent_in_laws_count )
- {
+ if ($allowed_adults == 1 && $received_parents_count && $received_parent_in_laws_count) {
$result['status'] = false;
- $result['error_data'][] = ['code' => 12,'col_name' => 'sno','msg' => 'Rule conflict: Parents and Parents in law both not allowed','row_id' => (isset($self_emp_row_id) ? $self_emp_row_id : $family_data[0][0])];
+ $result['error_data'][] = ['code' => 12, 'col_name' => 'sno', 'msg' => 'Rule conflict: Parents and Parents in law both not allowed', 'row_id' => (isset($self_emp_row_id) ? $self_emp_row_id : $firstNonTemp[0])];
- if((2 < $received_parents_count) || (2 < $received_parent_in_laws_count))
- {
+ if ((2 < $received_parents_count) || (2 < $received_parent_in_laws_count)) {
$result['status'] = false;
- $result['error_data'][] = ['code' => 12,'col_name' => 'sno','msg' => 'Rule conflict: As per policy, count of dependents has exceeded configured count','row_id' => (isset($self_emp_row_id) ? $self_emp_row_id : $family_data[0][0])];//dependent count mismatch
+ $result['error_data'][] = ['code' => 12, 'col_name' => 'sno', 'msg' => 'Rule conflict: As per policy, count of dependents has exceeded configured count', 'row_id' => (isset($self_emp_row_id) ? $self_emp_row_id : $firstNonTemp[0])]; //dependent count mismatch
}
}
//check for any cross parents but not more than two
- if($allowed_adults == 2 && (2 < ($received_parents_count + $received_parent_in_laws_count)))
- {
- // dd($allowed_adults);
- $result['status'] = false;
- $result['error_data'][] = ['code' => 12,'col_name' => 'sno','msg' => 'Rule conflict:As per policy, count of dependents has exceeded configured count','row_id' => (isset($self_emp_row_id) ? $self_emp_row_id : $family_data[0][0])];//dependent count mismatch
+ if ($allowed_adults == 2 && (2 < ($received_parents_count + $received_parent_in_laws_count))) {
+ // dd($allowed_adults);
+ $result['status'] = false;
+ $result['error_data'][] = ['code' => 12, 'col_name' => 'sno', 'msg' => 'Rule conflict:As per policy, count of dependents has exceeded configured count', 'row_id' => (isset($self_emp_row_id) ? $self_emp_row_id : $firstNonTemp[0])]; //dependent count mismatch
}
-
-
+ } else {
+ $result['status'] = true;
}
- else
- {
- $result['status'] = true;
- }
-
-
- return $result;
+
+ return $result;
}
}
-if (!function_exists('generate_relationship_code'))
-{
+if (!function_exists('generate_relationship_code')) {
function generate_relationship_code($arr)
{
- $gender = ['M' => 1,'F' => 2];
- $relationship = ['self' => 1,'spouse' => 2,'son' => 3,'daughter' => 4,'father' => 5,'mother' => 6,'father-in-law' => 7,'mother-in-law' => 8];
+ $gender = ['M' => 1, 'F' => 2];
+ $relationship = ['self' => 1, 'spouse' => 2, 'son' => 3, 'daughter' => 4, 'father' => 5, 'mother' => 6, 'father-in-law' => 7, 'mother-in-law' => 8];
$slug = \Config\Services::slug();
$relationship_code = $slug->slugify($arr['relationship']);
$emp_type_code = ($relationship_code == 'self' ? 'EMP_TYP_01' : 'EMP_TYP_03');
- $relationship_code = $gender[ trim($arr['gender']) ] . $relationship[ trim($relationship_code) ];
- return ['relationship_code' => $relationship_code,'emp_type_code' => $emp_type_code];
+ $relationship_code = $gender[trim($arr['gender'])] . $relationship[trim($relationship_code)];
+ return ['relationship_code' => $relationship_code, 'emp_type_code' => $emp_type_code];
}
}
-if (!function_exists('calculate_premium'))
-{
+if (!function_exists('calculate_premium')) {
// function calculate_premimum($family_data,$policy_terms,$slab_details,$fileArr,$default_si = null)
- function calculate_premium(array $family_data,array $policy_terms,array $slab_details,array $fileArr,string $default_si = null,array $existing_units = [])
+ function calculate_premium(array $family_data, array $policy_terms, array $slab_details, array $fileArr, string $default_si = null, array $existing_units = [])
{
// dd($family_data);
$slug = \Config\Services::slug();
@@ -700,232 +657,205 @@ if (!function_exists('calculate_premium'))
//gather detailes for additional rack info
$additional_grid_type = isset($slab_details['additional_slab_info']['grid_master']['ui_type']) ? $slab_details['additional_slab_info']['grid_master']['ui_type'] : null;
// dd(isset($slab_details['additional_slab_info']['grid_master']['ui_type']));
- $policy_terms_json = ($policy_terms['policy_terms']);
- $policy_terms_json = (array) json_decode($policy_terms_json);
+ $policy_terms_json = ($policy_terms['policy_terms']);
+ $policy_terms_json = (array) json_decode($policy_terms_json);
// dd($policy_terms);
$primary_rack_rate_applicable_familiy_members = ['self'];
- if(isset($policy_terms_json['family_floaters']))
- {
+ if (isset($policy_terms_json['family_floaters'])) {
$primary_rack_rate_applicable_familiy_members = generate_family_relationship_array((array)$policy_terms_json['family_floaters']);
}
-
+
$additional_grid_type_applicable_familiy_members = [];
- if($additional_grid_type != null)
- {
+ if ($additional_grid_type != null) {
$additional_grid_type_applicable_familiy_members = (array)json_decode($slab_details['additional_slab_info']['slab_rates'][0]['additional_relationship']);
$additional_grid_type_applicable_familiy_members = generate_family_relationship_array($additional_grid_type_applicable_familiy_members);
}
- // Kint::dump($primary_rack_rate_applicable_familiy_members);
- // Kint::dump($additional_grid_type_applicable_familiy_members);
+ // Kint::dump($primary_rack_rate_applicable_familiy_members);
+ // Kint::dump($additional_grid_type_applicable_familiy_members);
//remove common family members in primary array
- $primary_rack_rate_applicable_familiy_members = array_diff($primary_rack_rate_applicable_familiy_members,$additional_grid_type_applicable_familiy_members);
+ $primary_rack_rate_applicable_familiy_members = array_diff($primary_rack_rate_applicable_familiy_members, $additional_grid_type_applicable_familiy_members);
// dd($primary_rack_rate_applicable_familiy_members);
-
+
//this variable for store emp id and their band for emp band level premium calculation for all famility members (especially for grid type 9) also store max age and max count of a familiy for grid type 10,11
$emp_details_with_empband_max_age_max_count = [];
//find max age and max count of family members for both primary and additional grid type
- $max_age_and_count = (array_reduce($family_data,function($max_age,$family_member) use ($primary_rack_rate_applicable_familiy_members,$slug) {
-
- if( in_array($slug->slugify($family_member[5]), $primary_rack_rate_applicable_familiy_members))
- {
- $max_age['primary_rack_rate_max_age'][] = calculate_days_bw_dates(from_date: $family_member[3])->y;
- $max_age['primary_rack_rate_max_count'] = $max_age['primary_rack_rate_max_count'] + 1;
- }
- else
- {
- $max_age['additional_rack_rate_max_age'][] = calculate_days_bw_dates(from_date: $family_member[3])->y;
- $max_age['additional_rack_rate_max_count'] = $max_age['additional_rack_rate_max_count'] + 1;
- }
- return $max_age;
- }, ['primary_rack_rate_max_age' => [], 'additional_rack_rate_max_age' => [],'primary_rack_rate_max_count' => 0,'additional_rack_rate_max_count' => 0]));
+ $max_age_and_count = (array_reduce($family_data, function ($max_age, $family_member) use ($primary_rack_rate_applicable_familiy_members, $slug) {
+
+ if (in_array($slug->slugify($family_member[5]), $primary_rack_rate_applicable_familiy_members)) {
+ $max_age['primary_rack_rate_max_age'][] = calculate_days_bw_dates(from_date: $family_member[3])->y;
+ $max_age['primary_rack_rate_max_count'] = $max_age['primary_rack_rate_max_count'] + 1;
+ } else {
+ $max_age['additional_rack_rate_max_age'][] = calculate_days_bw_dates(from_date: $family_member[3])->y;
+ $max_age['additional_rack_rate_max_count'] = $max_age['additional_rack_rate_max_count'] + 1;
+ }
+ return $max_age;
+ }, ['primary_rack_rate_max_age' => [], 'additional_rack_rate_max_age' => [], 'primary_rack_rate_max_count' => 0, 'additional_rack_rate_max_count' => 0]));
- $get_max_age_or_count = function($relationship,$flag) use ($slug, $primary_rack_rate_applicable_familiy_members, $max_age_and_count)
- {
- if(in_array($slug->slugify($relationship),$primary_rack_rate_applicable_familiy_members))
- {
- return $flag == 'age' ? max($max_age_and_count['primary_rack_rate_max_age']) : $max_age_and_count['primary_rack_rate_max_count'];
- }
- return $flag == 'age' ? max($max_age_and_count['additional_rack_rate_max_age']) : $max_age_and_count['additional_rack_rate_max_count'];
- };
+ $get_max_age_or_count = function ($relationship, $flag) use ($slug, $primary_rack_rate_applicable_familiy_members, $max_age_and_count) {
+ if (in_array($slug->slugify($relationship), $primary_rack_rate_applicable_familiy_members)) {
+ return $flag == 'age' ? max($max_age_and_count['primary_rack_rate_max_age']) : $max_age_and_count['primary_rack_rate_max_count'];
+ }
+ return $flag == 'age' ? max($max_age_and_count['additional_rack_rate_max_age']) : $max_age_and_count['additional_rack_rate_max_count'];
+ };
- $get_current_member_grid_type = function($relationship) use ($slug, $primary_rack_rate_applicable_familiy_members,$primary_grid_type,$additional_grid_type)
- {
- if(in_array($slug->slugify($relationship),$primary_rack_rate_applicable_familiy_members))
- {
- return ['type' => 'primary','grid_id' => $primary_grid_type];
- }
- return ['type' => 'additional','grid_id' => $additional_grid_type];
- };
+ $get_current_member_grid_type = function ($relationship) use ($slug, $primary_rack_rate_applicable_familiy_members, $primary_grid_type, $additional_grid_type) {
+ if (in_array($slug->slugify($relationship), $primary_rack_rate_applicable_familiy_members)) {
+ return ['type' => 'primary', 'grid_id' => $primary_grid_type];
+ }
+ return ['type' => 'additional', 'grid_id' => $additional_grid_type];
+ };
// Kint::dump($max_age_and_count);dd();
- foreach($family_data as $fkey => $member)
- {
- //get grid type either primary or additional based on current member relationship available in primary_rack_rate_applicable_familiy_members or not. if yes then primaty grid type else additional grid type
- $current_grid_info = $get_current_member_grid_type($member[5]);
- $fileArr['grid_info'] = $current_grid_info;
- //transform as db row column
- $transformed_familiy_member_data = transform_excel_data_to_db($member,$fileArr);
- // dd($transformed_familiy_member_data);
-
- //store emp id and emp band and attach it to their familiy members where band is always empty
+ foreach ($family_data as $fkey => $member) {
+ //get grid type either primary or additional based on current member relationship available in primary_rack_rate_applicable_familiy_members or not. if yes then primaty grid type else additional grid type
+ $current_grid_info = $get_current_member_grid_type($member[5]);
+ $fileArr['grid_info'] = $current_grid_info;
+ //transform as db row column
+ $transformed_familiy_member_data = transform_excel_data_to_db($member, $fileArr);
+ // dd($transformed_familiy_member_data);
- $emp_details_with_empband_max_age_max_count[ $transformed_familiy_member_data['emp_code'] ]['band'] = isset($emp_details_with_empband_max_age_max_count[ $transformed_familiy_member_data['emp_code'] ]['band']) ? $emp_details_with_empband_max_age_max_count[ $transformed_familiy_member_data['emp_code'] ]['band'] : NULL;
+ //store emp id and emp band and attach it to their familiy members where band is always empty
- $emp_details_with_empband_max_age_max_count[ $transformed_familiy_member_data['emp_code'] ]['si'] = isset($emp_details_with_empband_max_age_max_count[ $transformed_familiy_member_data['emp_code'] ]['si']) ? $emp_details_with_empband_max_age_max_count[ $transformed_familiy_member_data['emp_code'] ]['si'] : NULL;
- //get emp band and si from self and make it available for whole family
- if(strtolower($transformed_familiy_member_data['relationship']) == 'self')
+ $emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['band'] = isset($emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['band']) ? $emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['band'] : NULL;
+
+ $emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['si'] = isset($emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['si']) ? $emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['si'] : NULL;
+ //get emp band and si from self and make it available for whole family
+ if (strtolower($transformed_familiy_member_data['relationship']) == 'self') {
+ $emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['band'] = $transformed_familiy_member_data['band'];
+ $emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['si'] = $transformed_familiy_member_data['policy_details']['basic_cover_si'];
+ }
+
+ //end of store emp id and emp band and attach it to their familiy members where band is always empty
+ $emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['maxcount'] = $get_max_age_or_count($transformed_familiy_member_data['relationship'], 'count');
+
+ $emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['maxage'] = $get_max_age_or_count($transformed_familiy_member_data['relationship'], 'age');
+
+ //set additional_rack_rate_acting_self in emp_details_with_empband_max_age_max_count array
+ $transformed_familiy_member_data['temp']['additional_rack_rate_acting_self'] = false;
+ if (!isset($emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['additional_rack_rate_acting_self']) && $current_grid_info['type'] == 'additional') {
+
+ if ($transformed_familiy_member_data['temp']['action'] != 'DA') {
+ $transformed_familiy_member_data['temp']['additional_rack_rate_acting_self'] = true;
+ $emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['additional_rack_rate_acting_self'] = true;
+ } else // if dependent addition then set employee from db is an acting self
{
- $emp_details_with_empband_max_age_max_count[ $transformed_familiy_member_data['emp_code'] ]['band'] = $transformed_familiy_member_data['band'];
- $emp_details_with_empband_max_age_max_count[ $transformed_familiy_member_data['emp_code'] ]['si'] = $transformed_familiy_member_data['policy_details']['basic_cover_si'];
- }
-
- //end of store emp id and emp band and attach it to their familiy members where band is always empty
- $emp_details_with_empband_max_age_max_count[ $transformed_familiy_member_data['emp_code'] ]['maxcount'] = $get_max_age_or_count($transformed_familiy_member_data['relationship'],'count');
-
- $emp_details_with_empband_max_age_max_count[ $transformed_familiy_member_data['emp_code'] ]['maxage'] = $get_max_age_or_count($transformed_familiy_member_data['relationship'],'age');
- //set additional_rack_rate_acting_self in emp_details_with_empband_max_age_max_count array
- $transformed_familiy_member_data['temp']['additional_rack_rate_acting_self'] = false;
- if(!isset($emp_details_with_empband_max_age_max_count[ $transformed_familiy_member_data['emp_code'] ]['additional_rack_rate_acting_self']) && $current_grid_info['type'] == 'additional')
- {
-
- if($transformed_familiy_member_data['temp']['action'] != 'DA')
- {
+ if ($transformed_familiy_member_data['temp']['source'] == 'db' && $transformed_familiy_member_data['temp']['rata_premimum']) {
+ // echo 'SETTING';
$transformed_familiy_member_data['temp']['additional_rack_rate_acting_self'] = true;
- $emp_details_with_empband_max_age_max_count[ $transformed_familiy_member_data['emp_code'] ]['additional_rack_rate_acting_self'] = true;
- }
- else// if dependent addition then set employee from db is an acting self
- {
-
- if($transformed_familiy_member_data['temp']['source'] == 'db' && $transformed_familiy_member_data['temp']['rata_premimum'])
- {
- // echo 'SETTING';
- $transformed_familiy_member_data['temp']['additional_rack_rate_acting_self'] = true;
- $emp_details_with_empband_max_age_max_count[ $transformed_familiy_member_data['emp_code'] ]['additional_rack_rate_acting_self'] = true;
- }
- }
- }
-
- //set primary_rack_rate_acting_self in emp_details_with_empband_max_age_max_count array for policies where self not available and premium type is 1 (i.e.) GMC parents as dep addon policy
- $transformed_familiy_member_data['temp']['primary_rack_rate_acting_self'] = false;
- if(!isset($emp_details_with_empband_max_age_max_count[ $transformed_familiy_member_data['emp_code'] ]['primary_rack_rate_acting_self']) && $current_grid_info['type'] == 'primary')
- {
- if(strtolower($transformed_familiy_member_data['relationship']) == 'self')
- {
- $transformed_familiy_member_data['temp']['primary_rack_rate_acting_self'] = true;
- $emp_details_with_empband_max_age_max_count[ $transformed_familiy_member_data['emp_code'] ]['primary_rack_rate_acting_self'] = true;
- }
- else
- {
- $transformed_familiy_member_data['temp']['primary_rack_rate_acting_self'] = true;
- $emp_details_with_empband_max_age_max_count[ $transformed_familiy_member_data['emp_code'] ]['primary_rack_rate_acting_self'] = true;
- }
- }
-
- //generate relationship code
- if($transformed_familiy_member_data['temp']['action'] != 'D' && $transformed_familiy_member_data['temp']['action'] != 'C' && $transformed_familiy_member_data['temp']['action'] != 'SI')
- {
- $temp_res = generate_relationship_code($transformed_familiy_member_data);
- $transformed_familiy_member_data['relationship_code'] = $temp_res['relationship_code'];
- $transformed_familiy_member_data['emp_type'] = $temp_res['emp_type_code'];
- }
-
- //calculate primimum based on grid type
- if($transformed_familiy_member_data['temp']['action'] != 'D' && $transformed_familiy_member_data['temp']['action'] != 'C' && $transformed_familiy_member_data['temp']['action'] != 'SI')
- {
-
- //before call premium_calculation_manager attach band,max age and max count into the array temporarly for grid 9,10 and 11
- $transformed_familiy_member_data['temp']['band'] = $emp_details_with_empband_max_age_max_count[ $transformed_familiy_member_data['emp_code'] ]['band'];
- $transformed_familiy_member_data['temp']['maxage'] = $emp_details_with_empband_max_age_max_count[ $transformed_familiy_member_data['emp_code'] ]['maxage'];
- $transformed_familiy_member_data['temp']['maxcount'] = $emp_details_with_empband_max_age_max_count[ $transformed_familiy_member_data['emp_code'] ]['maxcount'];
-
- //set self si to all familiy members, except they've come from DB
- // if(isset($emp_details_with_empband_max_age_max_count[ $transformed_familiy_member_data['emp_code'] ]['si']))
- // {
- if($transformed_familiy_member_data['temp']['source'] != 'db')
- {
- $transformed_familiy_member_data['policy_details']['basic_cover_si'] = isset($emp_details_with_empband_max_age_max_count[ $transformed_familiy_member_data['emp_code'] ]['si']) ? $emp_details_with_empband_max_age_max_count[ $transformed_familiy_member_data['emp_code'] ]['si'] : $transformed_familiy_member_data['policy_details']['basic_cover_si'];
- }
- // }
-
-
- // this array hold conditions to allow calculate premium amt
- $conditions = [
- 'isEmployeeSourceEnrollment' => $fileArr['id'] == null,
- 'isEmployeeSourceExcelFile' => $transformed_familiy_member_data['temp']['source'] == 'excel',
- 'isCurrentActionDependentAddition' => $fileArr['action'] == 'dependent_addition',
- 'isPrimaryGridType' => $transformed_familiy_member_data['temp']['grid_type'] == 'primary',
- 'isAdditionalGridType' => $transformed_familiy_member_data['temp']['grid_type'] == 'additional',
- 'isPrimaryGridPremiumTypeSingle' => $slab_details['slab_rates'][0]['premium_type'] == 1,
- 'isAdditionalPremiumTypeSingle' => isset($slab_details['additional_slab_info']['slab_rates'][0]['premium_type']) ? ( $slab_details['additional_slab_info']['slab_rates'][0]['premium_type'] == 1) : 0,
- 'isCurrentRelationshipSelf' => strtolower($transformed_familiy_member_data['relationship']) == 'self',
- 'isBasicCoverCalculatedToCurrentEmployee' => ($transformed_familiy_member_data['policy_details']['basic_cover_si'] != null && $transformed_familiy_member_data['policy_details']['basic_cover_si'] != 0)
- ];
- // Kint::dump($transformed_familiy_member_data['policy_details']);
- // echo ($transformed_familiy_member_data['policy_details']['basic_cover_si'] != null && $transformed_familiy_member_data['policy_details']['basic_cover_si'] != 0);
- // echo ($conditions['isBasicCoverCalculatedToCurrentEmployee']);
- // echo " ";
- // same logic for both primay and additional grid type
- $primaryGridTypeCondition = $conditions['isCurrentActionDependentAddition'] && $conditions['isPrimaryGridType'] && $conditions['isPrimaryGridPremiumTypeSingle'] && $conditions['isCurrentRelationshipSelf'];
- $additionalGridTypeCondition = $conditions['isCurrentActionDependentAddition'] && $conditions['isAdditionalGridType'] && $conditions['isAdditionalPremiumTypeSingle'] && $conditions['isBasicCoverCalculatedToCurrentEmployee'];
-
- // Final combined condition
- if ($conditions['isEmployeeSourceEnrollment'] || $conditions['isEmployeeSourceExcelFile'] || $primaryGridTypeCondition || $additionalGridTypeCondition) {
-
- $transformed_familiy_member_data = premium_calculation_manager($transformed_familiy_member_data,$policy_terms,$slab_details,$default_si);
-
- $result[] = $transformed_familiy_member_data;
+ $emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['additional_rack_rate_acting_self'] = true;
}
}
}
- // Kint::dump($emp_details_with_empband_max_age_max_count);
+
+ //set primary_rack_rate_acting_self in emp_details_with_empband_max_age_max_count array for policies where self not available and premium type is 1 (i.e.) GMC parents as dep addon policy
+ $transformed_familiy_member_data['temp']['primary_rack_rate_acting_self'] = false;
+ if (!isset($emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['primary_rack_rate_acting_self']) && $current_grid_info['type'] == 'primary') {
+ if (strtolower($transformed_familiy_member_data['relationship']) == 'self') {
+ $transformed_familiy_member_data['temp']['primary_rack_rate_acting_self'] = true;
+ $emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['primary_rack_rate_acting_self'] = true;
+ } else {
+ $transformed_familiy_member_data['temp']['primary_rack_rate_acting_self'] = true;
+ $emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['primary_rack_rate_acting_self'] = true;
+ }
+ }
+
+ //generate relationship code
+ if ($transformed_familiy_member_data['temp']['action'] != 'D' && $transformed_familiy_member_data['temp']['action'] != 'C' && $transformed_familiy_member_data['temp']['action'] != 'SI') {
+ $temp_res = generate_relationship_code($transformed_familiy_member_data);
+ $transformed_familiy_member_data['relationship_code'] = $temp_res['relationship_code'];
+ $transformed_familiy_member_data['emp_type'] = $temp_res['emp_type_code'];
+ }
+
+ //calculate primimum based on grid type
+ if ($transformed_familiy_member_data['temp']['action'] != 'D' && $transformed_familiy_member_data['temp']['action'] != 'C' && $transformed_familiy_member_data['temp']['action'] != 'SI') {
+
+ //before call premium_calculation_manager attach band,max age and max count into the array temporarly for grid 9,10 and 11
+ $transformed_familiy_member_data['temp']['band'] = $emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['band'];
+ $transformed_familiy_member_data['temp']['maxage'] = $emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['maxage'];
+ $transformed_familiy_member_data['temp']['maxcount'] = $emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['maxcount'];
+
+ //set self si to all familiy members, except they've come from DB
+ // if(isset($emp_details_with_empband_max_age_max_count[ $transformed_familiy_member_data['emp_code'] ]['si']))
+ // {
+ if ($transformed_familiy_member_data['temp']['source'] != 'db') {
+ $transformed_familiy_member_data['policy_details']['basic_cover_si'] = isset($emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['si']) ? $emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['si'] : $transformed_familiy_member_data['policy_details']['basic_cover_si'];
+ }
+ // }
+
+
+ // this array hold conditions to allow calculate premium amt
+ $conditions = [
+ 'isEmployeeSourceEnrollment' => $fileArr['id'] == null,
+ 'isEmployeeSourceExcelFile' => $transformed_familiy_member_data['temp']['source'] == 'excel',
+ 'isCurrentActionDependentAddition' => $fileArr['action'] == 'dependent_addition',
+ 'isPrimaryGridType' => $transformed_familiy_member_data['temp']['grid_type'] == 'primary',
+ 'isAdditionalGridType' => $transformed_familiy_member_data['temp']['grid_type'] == 'additional',
+ 'isPrimaryGridPremiumTypeSingle' => $slab_details['slab_rates'][0]['premium_type'] == 1,
+ 'isAdditionalPremiumTypeSingle' => isset($slab_details['additional_slab_info']['slab_rates'][0]['premium_type']) ? ($slab_details['additional_slab_info']['slab_rates'][0]['premium_type'] == 1) : 0,
+ 'isCurrentRelationshipSelf' => strtolower($transformed_familiy_member_data['relationship']) == 'self',
+ 'isBasicCoverCalculatedToCurrentEmployee' => ($transformed_familiy_member_data['policy_details']['basic_cover_si'] != null && $transformed_familiy_member_data['policy_details']['basic_cover_si'] != 0)
+ ];
+ // Kint::dump($transformed_familiy_member_data['policy_details']);
+ // echo ($transformed_familiy_member_data['policy_details']['basic_cover_si'] != null && $transformed_familiy_member_data['policy_details']['basic_cover_si'] != 0);
+ // echo ($conditions['isBasicCoverCalculatedToCurrentEmployee']);
+ // echo " ";
+ // same logic for both primay and additional grid type
+ $primaryGridTypeCondition = $conditions['isCurrentActionDependentAddition'] && $conditions['isPrimaryGridType'] && $conditions['isPrimaryGridPremiumTypeSingle'] && $conditions['isCurrentRelationshipSelf'];
+ $additionalGridTypeCondition = $conditions['isCurrentActionDependentAddition'] && $conditions['isAdditionalGridType'] && $conditions['isAdditionalPremiumTypeSingle'] && $conditions['isBasicCoverCalculatedToCurrentEmployee'];
+
+ // Final combined condition
+ if ($conditions['isEmployeeSourceEnrollment'] || $conditions['isEmployeeSourceExcelFile'] || $primaryGridTypeCondition || $additionalGridTypeCondition) {
+
+ $transformed_familiy_member_data = premium_calculation_manager($transformed_familiy_member_data, $policy_terms, $slab_details, $default_si);
+
+ $result[] = $transformed_familiy_member_data;
+ }
+ }
+ }
+ // Kint::dump($emp_details_with_empband_max_age_max_count);
return $result;
}
}
-if (!function_exists('calculate_premium_new'))
-{
- function calculate_premium_new(array $family_data,array $policy_terms,array $slab_details,array $fileArr,array $existing_units,string $default_si = null,)
+if (!function_exists('calculate_premium_new')) {
+ function calculate_premium_new(array $family_data, array $policy_terms, array $slab_details, array $fileArr, array $existing_units, string $default_si = null,)
{
//grouping slab details by rack rate name
$temp_slab_rates = group_slab_rates_basedon_name($slab_details);
// dd($temp_slab_rates);
/* 1. construct available/incoming family members composition & count */
- $incoming_familiy_composition = get_familiy_composition($family_data);
- // dd($incoming_familiy_composition);
+ $incoming_familiy_composition = get_familiy_composition($family_data);
+ // dd($incoming_familiy_composition);
//2 .get applicable familiy members composition & count from slab details & constrcut an array
- //3 in for another loop compare slab level applicable familiy composition with available family composition
- $result = [];
- foreach($temp_slab_rates as $key => $slab)
- {
+ //3 in for another loop compare slab level applicable familiy composition with available family composition
+ $result = [];
+ foreach ($temp_slab_rates as $key => $slab) {
// dd($slab);
- $res = compare_incoming_family_slab_with_configured_slab($slab,$incoming_familiy_composition);
+ $res = compare_incoming_family_slab_with_configured_slab($slab, $incoming_familiy_composition);
// kint::dump($key);
// kint::dump($res);
- if($res['is_applicable'])
- {
+ if ($res['is_applicable']) {
$temp_slab_rates[$key]['is_applicable'] = true;
$temp_slab_rates[$key]['members'] = $res['applicable_members'];
//get applicable members for current rack rate from over all familiy members and calculate max age and max count,self/acting self and grid type and set it in individual familiy member level
- $applicable_members_from_familiy = get_applicable_familiy_members($family_data,$res['applicable_members']);
+ $applicable_members_from_familiy = get_applicable_familiy_members($family_data, $res['applicable_members']);
// dd( $applicable_members_from_familiy);
$is_self_acting_self_set = false;
- foreach($applicable_members_from_familiy['index'] as $val)
- {
+ foreach ($applicable_members_from_familiy['index'] as $val) {
$acting_self = false;
- if(!$is_self_acting_self_set)
- {
- if(strtolower($family_data[$val][5]) == 'self' || !$is_self_acting_self_set) $acting_self = true;
+ if (!$is_self_acting_self_set) {
+ if (strtolower($family_data[$val][5]) == 'self' || !$is_self_acting_self_set) $acting_self = true;
$is_self_acting_self_set = true;
}
-
+
//$family_data[$val]['temp'] = ['max_age' => max($applicable_members_from_familiy['max_age']),'max_count' => $applicable_members_from_familiy['max_count'],'grid_name' => $key,'grid_master' => $slab['grid_master'],'acting_self' => $acting_self,'premium_type' => $slab['slab_rates'][0]['premium_type']];
$family_data[$val]['temp'] = array_merge(
$family_data[$val]['temp'] ?? [], // existing 'temp' data or an empty array if it doesn't exist
@@ -938,113 +868,116 @@ if (!function_exists('calculate_premium_new'))
'premium_type' => $slab['slab_rates'][0]['premium_type']
]
);
-
}
- }
- else
- {
+ } else {
$temp_slab_rates[$key]['is_applicable'] = false;
}
- }
- // dd();
-
+ }
+ // dd();
+
//4. if macthed then the current rack rate is applicable and find common variables link max age,max count,grade, basic pay,SI, self/acting self for current rack rate
- foreach($family_data as $fkey => $member)
- {
- // dd($member);
- //get grid type either primary or additional based on current member relationship available in primary_rack_rate_applicable_familiy_members or not. if yes then primaty grid type else additional grid type
-
- $fileArr['grid_info'] = ['type' => isset($member['temp']['grid_name']) ? $member['temp']['grid_name'] : NULL , 'grid_id' => isset($member['temp']['grid_master']['ui_type']) ? $member['temp']['grid_master']['ui_type'] : NULL];
+ foreach ($family_data as $fkey => $member) {
+ // dd($member);
+ //get grid type either primary or additional based on current member relationship available in primary_rack_rate_applicable_familiy_members or not. if yes then primaty grid type else additional grid type
-
-
- //set self (first index of familiy) SI and grade to rest of the familiy
- $member[6] = $family_data[0][6];
- $member[10] = $family_data[0][10];
- $member[18] = $family_data[0][18];
- //set default unit if unit is not available in self/members level
- if(empty($member[18])){ $member[18] = $existing_units[0]; }
- //transform as db row column
- $transformed_familiy_member_data = transform_excel_data_to_db($member,$fileArr);
- //generate relationship code
- if($transformed_familiy_member_data['temp']['action'] != 'D' && $transformed_familiy_member_data['temp']['action'] != 'C' && $transformed_familiy_member_data['temp']['action'] != 'SI')
- {
- $temp_res = generate_relationship_code($transformed_familiy_member_data);
- $transformed_familiy_member_data['relationship_code'] = $temp_res['relationship_code'];
- $transformed_familiy_member_data['emp_type'] = $temp_res['emp_type_code'];
- }
-
- // // this array hold conditions to allow calculate premium amt
- $conditions = [
- 'isEmployeeSourceEnrollment' => $fileArr['id'] == null,
- 'isEmployeeSourceExcelFile' => $transformed_familiy_member_data['temp']['source'] == 'excel',
- 'isCurrentActionDependentAddition' => $fileArr['action'] == 'dependent_addition',
- 'isPrimaryGridPremiumTypeSingle' => isset($transformed_familiy_member_data['temp']['premium_type']) ? $transformed_familiy_member_data['temp']['premium_type'] == 1 : 0,
- 'isCurrentRelationshipSelf' => (strtolower($transformed_familiy_member_data['relationship']) == 'self' || (isset($transformed_familiy_member_data['temp']['acting_self']) && $transformed_familiy_member_data['temp']['acting_self'] === true)),
- 'isBasicCoverCalculatedToCurrentEmployee' => ($transformed_familiy_member_data['policy_details']['basic_cover_si'] != null && $transformed_familiy_member_data['policy_details']['basic_cover_si'] != 0)
- ];
-
- $primaryGridTypeCondition = $conditions['isCurrentActionDependentAddition'] && $conditions['isPrimaryGridPremiumTypeSingle'] && $conditions['isCurrentRelationshipSelf'] && $conditions['isBasicCoverCalculatedToCurrentEmployee'];
-
- // // Final combined condition
- if ($conditions['isEmployeeSourceEnrollment'] || $conditions['isEmployeeSourceExcelFile'] || $primaryGridTypeCondition ) {
- // dd($transformed_familiy_member_data);
- $transformed_familiy_member_data = premium_calculation_manager($transformed_familiy_member_data,$policy_terms,$temp_slab_rates,$default_si);
- // dd($transformed_familiy_member_data);
- $result[] = $transformed_familiy_member_data;
- }
+ $fileArr['grid_info'] = ['type' => isset($member['temp']['grid_name']) ? $member['temp']['grid_name'] : NULL, 'grid_id' => isset($member['temp']['grid_master']['ui_type']) ? $member['temp']['grid_master']['ui_type'] : NULL];
- // $result[] = $transformed_familiy_member_data;
+
+ //set self (first index of familiy) SI and grade to rest of the familiy
+ $member[6] = $family_data[0][6];
+ $member[10] = $family_data[0][10];
+ $member[18] = $family_data[0][18];
+ //set default unit if unit is not available in self/members level
+ if (empty($member[18])) {
+ $member[18] = $existing_units[0];
+ }
+ //transform as db row column
+ $transformed_familiy_member_data = transform_excel_data_to_db($member, $fileArr);
+ //generate relationship code
+ if ($transformed_familiy_member_data['temp']['action'] != 'D' && $transformed_familiy_member_data['temp']['action'] != 'C' && $transformed_familiy_member_data['temp']['action'] != 'SI') {
+ $temp_res = generate_relationship_code($transformed_familiy_member_data);
+ $transformed_familiy_member_data['relationship_code'] = $temp_res['relationship_code'];
+ $transformed_familiy_member_data['emp_type'] = $temp_res['emp_type_code'];
}
- // dd($result);
- return ($result);
- //
-
-
+ // // this array hold conditions to allow calculate premium amt
+ $conditions = [
+ 'isEmployeeSourceEnrollment' => $fileArr['id'] == null,
+ 'isEmployeeSourceExcelFile' => $transformed_familiy_member_data['temp']['source'] == 'excel',
+ 'isCurrentActionDependentAddition' => $fileArr['action'] == 'dependent_addition',
+ 'isPrimaryGridPremiumTypeSingle' => isset($transformed_familiy_member_data['temp']['premium_type']) ? $transformed_familiy_member_data['temp']['premium_type'] == 1 : 0,
+ 'isCurrentRelationshipSelf' => (strtolower($transformed_familiy_member_data['relationship']) == 'self' || (isset($transformed_familiy_member_data['temp']['acting_self']) && $transformed_familiy_member_data['temp']['acting_self'] === true)),
+ 'isBasicCoverCalculatedToCurrentEmployee' => ($transformed_familiy_member_data['policy_details']['basic_cover_si'] != null && $transformed_familiy_member_data['policy_details']['basic_cover_si'] != 0)
+ ];
+
+ $primaryGridTypeCondition = $conditions['isCurrentActionDependentAddition'] && $conditions['isPrimaryGridPremiumTypeSingle'] && $conditions['isCurrentRelationshipSelf'] && $conditions['isBasicCoverCalculatedToCurrentEmployee'];
+
+ // // Final combined condition
+ if ($conditions['isEmployeeSourceEnrollment'] || $conditions['isEmployeeSourceExcelFile'] || $primaryGridTypeCondition) {
+ // dd($transformed_familiy_member_data);
+ $transformed_familiy_member_data = premium_calculation_manager($transformed_familiy_member_data, $policy_terms, $temp_slab_rates, $default_si);
+ // dd($transformed_familiy_member_data);
+ $result[] = $transformed_familiy_member_data;
+ }
+
+
+ // $result[] = $transformed_familiy_member_data;
+ }
+
+ // dd($result);
+ return ($result);
+ //
+
+
}
}
-if (!function_exists('transform_excel_data_to_db'))
-{
- function transform_excel_data_to_db($memArr,$actionArr)
+if (!function_exists('transform_excel_data_to_db')) {
+ function transform_excel_data_to_db($memArr, $actionArr)
{
- $current_column_action = null;
- if($actionArr['action'] == 'inception'){ $current_column_action = 'I'; }
- else if($actionArr['action'] == 'addition'){ $current_column_action = 'A'; }
- else if($actionArr['action'] == 'dependent_addition'){ $current_column_action = 'DA'; }
- else if($actionArr['action'] == 'deletion'){ $current_column_action = 'D'; }
- else if($actionArr['action'] == 'correction'){ $current_column_action = 'C'; }
- else if($actionArr['action'] == 'si_enhancement'){ $current_column_action = 'SI'; }
- else if($actionArr['action'] == 'missed_inception'){ $current_column_action = 'MI'; }
+ $current_column_action = null;
+ if ($actionArr['action'] == 'inception') {
+ $current_column_action = 'I';
+ } else if ($actionArr['action'] == 'addition') {
+ $current_column_action = 'A';
+ } else if ($actionArr['action'] == 'dependent_addition') {
+ $current_column_action = 'DA';
+ } else if ($actionArr['action'] == 'deletion') {
+ $current_column_action = 'D';
+ } else if ($actionArr['action'] == 'correction') {
+ $current_column_action = 'C';
+ } else if ($actionArr['action'] == 'si_enhancement') {
+ $current_column_action = 'SI';
+ } else if ($actionArr['action'] == 'missed_inception') {
+ $current_column_action = 'MI';
+ }
+
+ if ($actionArr['action'] == 'inception' || $actionArr['action'] == 'missed_inception' || $actionArr['action'] == 'addition' || $actionArr['action'] == 'dependent_addition') {
- if($actionArr['action'] == 'inception' || $actionArr['action'] == 'missed_inception' || $actionArr['action'] == 'addition' || $actionArr['action'] == 'dependent_addition')
- {
-
$policy['basic_cover_si'] = $memArr[6];
$policy['pre_existing_alignments'] = $memArr[14];
// $policy['date_of_exit'] = isset($memArr[16]) ? change_date_format($memArr[16],'d-M-Y','Y-m-d') : NULL;
// $policy['reason_for_exit'] = $memArr[17];
-
+
$policy['client_policy_id'] = $actionArr['policy_id'];
- $policy['date_coverage'] = isset($memArr[7]) && $memArr[7] != '' ? convert_string_to_date($memArr[7],'Y-m-d') : NULL;
+ $policy['date_coverage'] = isset($memArr[7]) && $memArr[7] != '' ? convert_string_to_date($memArr[7], 'Y-m-d') : NULL;
$policy['policy_end_date'] = null;
$policy['days'] = null;
$policy['premium'] = null;
$policy['rata_premimum'] = null;
$policy['gst'] = null;
-
+
$result['emp_code'] = $memArr[1];
$result['name'] = $memArr[2];
- $result['dob'] = isset($memArr[3]) ? convert_string_to_date($memArr[3],'Y-m-d') : NULL;
+ $result['dob'] = isset($memArr[3]) ? convert_string_to_date($memArr[3], 'Y-m-d') : NULL;
$result['gender'] = $memArr[4];
$result['relationship'] = $memArr[5];
$result['relationship_code'] = $memArr[5];
- $result['doj'] = isset($memArr[8]) ? convert_string_to_date($memArr[8],'Y-m-d') : NULL;
+ $result['doj'] = isset($memArr[8]) ? convert_string_to_date($memArr[8], 'Y-m-d') : NULL;
$result['basic_pay'] = $memArr[9];
$result['band'] = $memArr[10];
$result['designation'] = $memArr[11];
@@ -1055,7 +988,7 @@ if (!function_exists('transform_excel_data_to_db'))
$result['change_event'] = $memArr[15];
$result['unit'] = $memArr[18];
$result['temp'] = [];
- if(isset($memArr['temp'])) $result['temp'] = array_merge($result['temp'],$memArr['temp']);
+ if (isset($memArr['temp'])) $result['temp'] = array_merge($result['temp'], $memArr['temp']);
$result['temp']['grid_type'] = $actionArr['grid_info']['type'];
$result['temp']['band'] = $result['band'];
$result['temp']['grid_id'] = $actionArr['grid_info']['grid_id'];
@@ -1069,16 +1002,14 @@ if (!function_exists('transform_excel_data_to_db'))
$result['policy_details'] = $policy;
return $result;
-
}
}
}
-if (!function_exists('premium_calculation_manager'))
-{
- function premium_calculation_manager($emp_data,$policy_terms,$slab_details,$default_si = null)
- {
+if (!function_exists('premium_calculation_manager')) {
+ function premium_calculation_manager($emp_data, $policy_terms, $slab_details, $default_si = null)
+ {
// dd($emp_data,$policy_terms,$slab_details,$default_si);
$myLogger = \Config\Services::mylogger();
@@ -1087,57 +1018,52 @@ if (!function_exists('premium_calculation_manager'))
// Kint::dump($emp_data);
//check if the data comes from enrollment (DB) and status is draft then fetch original data of employee from
- //audit history table then initiate calculation with it. so this data again get updated in emp table
+ //audit history table then initiate calculation with it. so this data again get updated in emp table
- //check emp records
- if($emp_data['file_id'] == null && $emp_data['temp']['emp_status'] == 'draft' && $emp_data['temp']['policy_status'] == 'draft')
- {
- // $original_emp_records = get_emp_records_from_audit_history($emp_data['temp']['emp_id']);
- // if(is_array($original_emp_records))
- // {
- // // Kint::dump($original_emp_records);
- // // $emp_data = replace_original_data(original_data:$original_emp_records,current_data:$emp_data);
- // // Kint::dump($value);
- // }
- }
+ //check emp records
+ if ($emp_data['file_id'] == null && $emp_data['temp']['emp_status'] == 'draft' && $emp_data['temp']['policy_status'] == 'draft') {
+ // $original_emp_records = get_emp_records_from_audit_history($emp_data['temp']['emp_id']);
+ // if(is_array($original_emp_records))
+ // {
+ // // Kint::dump($original_emp_records);
+ // // $emp_data = replace_original_data(original_data:$original_emp_records,current_data:$emp_data);
+ // // Kint::dump($value);
+ // }
+ }
+
+ //check emp policy records
+ if ($emp_data['file_id'] == null && $emp_data['temp']['emp_status'] == 'draft' && $emp_data['temp']['policy_status'] == 'draft') {
+ // $original_emp_policy_records = get_emp_policy_records_from_audit_history($emp_data['temp']['emp_policy_id']);
+ // if(is_array($original_emp_policy_records))
+ // {
+ // // Kint::dump($original_emp_records);
+ // $emp_data['policy_details'] = replace_original_data(original_data:$original_emp_policy_records,current_data:$emp_data['policy_details']);
+ // // Kint::dump($policy_data);
+ // }
+
+ } //end of fetching data from audit history table
- //check emp policy records
- if($emp_data['file_id'] == null && $emp_data['temp']['emp_status'] == 'draft' && $emp_data['temp']['policy_status'] == 'draft')
- {
- // $original_emp_policy_records = get_emp_policy_records_from_audit_history($emp_data['temp']['emp_policy_id']);
- // if(is_array($original_emp_policy_records))
- // {
- // // Kint::dump($original_emp_records);
- // $emp_data['policy_details'] = replace_original_data(original_data:$original_emp_policy_records,current_data:$emp_data['policy_details']);
- // // Kint::dump($policy_data);
- // }
-
- }//end of fetching data from audit history table
-
//gird and calculation start
$slug = \Config\Services::slug();
$grid_type = $emp_data['temp']['grid_id'];
$slab_index = isset($emp_data['temp']['grid_name']) ? $emp_data['temp']['grid_name'] : false;
// echo $emp_data['name'];
// kint::dump($slab_index);
- if ($slab_index === false)
- {
- // echo 'not set';
- return false;
- }
- $temp_slab_rates = $slab_details[ $slab_index ]['slab_rates'];
-
+ if ($slab_index === false) {
+ // echo 'not set';
+ return false;
+ }
+ $temp_slab_rates = $slab_details[$slab_index]['slab_rates'];
+
//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 = ($insurer->find($policy_terms['insurer_id']));
- if($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'] = isset($emp_data['policy_details']['date_coverage']) && $emp_data['policy_details']['date_coverage'] != '' && $emp_data['policy_details']['date_coverage'] != null ?
- (new DateTime($emp_data['policy_details']['date_coverage']))->modify('+1 day')->format('Y-m-d') : null ;
+ $emp_data['policy_details']['date_coverage'] = isset($emp_data['policy_details']['date_coverage']) && $emp_data['policy_details']['date_coverage'] != '' && $emp_data['policy_details']['date_coverage'] != null ?
+ (new DateTime($emp_data['policy_details']['date_coverage']))->modify('+1 day')->format('Y-m-d') : null;
}
}
// dd($emp_data);
@@ -1148,58 +1074,51 @@ if (!function_exists('premium_calculation_manager'))
//GPA - Sum Insured (SI) * Multiplier
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
$employee_received_band = $emp_data['temp']['band'];
- foreach ($temp_slab_rates as $skey => $slab_value)
- {
- if(($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit']) || ($slab_value['grade'] != null && $slab_value['grade'] == $employee_received_band && $slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit']))
- {
+ foreach ($temp_slab_rates as $skey => $slab_value) {
+ if (($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit']) || ($slab_value['grade'] != null && $slab_value['grade'] == $employee_received_band && $slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'])) {
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
- $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
+ $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
- $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1);
+ $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
- $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1));
- $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.','');
+ $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
+ $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$is_match_found = true;
break;
}
}
//auto calculate of SI and premium for basic pay type
- if(!$is_match_found)
- {
- if($temp_slab_rates[0]['si_or_bp'] == 2)
- {
+ if (!$is_match_found) {
+ if ($temp_slab_rates[0]['si_or_bp'] == 2) {
$temp_si = $emp_data['basic_pay'] * $temp_slab_rates[0]['basic_multiplier'];
$temp_premium = ($temp_si * $temp_slab_rates[0]['multiplier']) / 1000;
- $emp_data['policy_details']['basic_cover_si'] = $temp_si;
- $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
+ $emp_data['policy_details']['basic_cover_si'] = $temp_si;
+ $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
- $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1);
+ $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $temp_premium;
- $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1));
- $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.','');
+ $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
+ $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$is_match_found = true;
- $log_message = 'Pre defined SI not found. auto calc SI & premium for -' . $emp_data['emp_code'].' - '. $emp_data['name'].' - '. $temp_si.' - '. $temp_premium;
- $myLogger->logme('error',$log_message);
-
+ $log_message = 'Pre defined SI not found. auto calc SI & premium for -' . $emp_data['emp_code'] . ' - ' . $emp_data['name'] . ' - ' . $temp_si . ' - ' . $temp_premium;
+ $myLogger->logme('error', $log_message);
}
}
break;
case "2":
- //GPA - Flat Rate for all SI
- $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
- foreach ($temp_slab_rates as $skey => $slab_value)
- {
- if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'])
- {
+ //GPA - Flat Rate for all SI
+ $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
+ foreach ($temp_slab_rates as $skey => $slab_value) {
+ if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit']) {
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
- $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
+ $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
- $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1);
+ $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
- $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1));
- $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.','');
+ $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
+ $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$is_match_found = true;
break;
}
@@ -1208,17 +1127,15 @@ if (!function_exists('premium_calculation_manager'))
case "3":
//GMC - SI
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
- foreach ($temp_slab_rates as $skey => $slab_value)
- {
- if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3 ) ))
- {
+ foreach ($temp_slab_rates as $skey => $slab_value) {
+ if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && (($slab_value['premium_type'] == 1 && (strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'])) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3))) {
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
- $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
+ $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
- $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1);
+ $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
- $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1));
- $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.','');
+ $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
+ $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$is_match_found = true;
break;
}
@@ -1226,27 +1143,25 @@ if (!function_exists('premium_calculation_manager'))
break;
case "4":
-
+
//GMC - Employees Age band
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
// dd($employee_received_si);
$temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
- $age = calculate_days_bw_dates(from_date: $emp_data['dob'],to_date: $temp_date)->y;
-
- foreach ($temp_slab_rates as $skey => $slab_value)
- {
-
- if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) ))
- {
+ $age = calculate_days_bw_dates(from_date: $emp_data['dob'], to_date: $temp_date)->y;
+
+ foreach ($temp_slab_rates as $skey => $slab_value) {
+
+ if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && (strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'])) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3))) {
// dd($slab_value);
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
- $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
+ $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
- $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1);
+ $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
- $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1));
- $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.','');
- $emp_data['policy_details']['age_band'] = $slab_value['age_from'].'-'.$slab_value['age_to'];
+ $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
+ $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
+ $emp_data['policy_details']['age_band'] = $slab_value['age_from'] . '-' . $slab_value['age_to'];
$is_match_found = true;
break;
}
@@ -1256,21 +1171,19 @@ if (!function_exists('premium_calculation_manager'))
//GMC - Employees Age + SI
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
$temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
- $age = calculate_days_bw_dates(from_date: $emp_data['dob'],to_date: $temp_date)->y;
+ $age = calculate_days_bw_dates(from_date: $emp_data['dob'], to_date: $temp_date)->y;
// kint::dump($age);
- foreach ($temp_slab_rates as $skey => $slab_value)
- {
- // dd($slab_value);
- if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3 ) ))
- {
- $emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
- $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
+ foreach ($temp_slab_rates as $skey => $slab_value) {
+ // dd($slab_value);
+ if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && (strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'])) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3))) {
+ $emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
+ $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
- $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1);
+ $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
- $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1));
- $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.','');
- $emp_data['policy_details']['age_band'] = $slab_value['age_from'].'-'.$slab_value['age_to'];
+ $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
+ $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
+ $emp_data['policy_details']['age_band'] = $slab_value['age_from'] . '-' . $slab_value['age_to'];
$is_match_found = true;
break;
}
@@ -1279,46 +1192,41 @@ if (!function_exists('premium_calculation_manager'))
case "6":
//GMC - Employees + Dependent Age band
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
- $temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
- $age = calculate_days_bw_dates(from_date: $emp_data['dob'],to_date: $temp_date)->y;
- foreach ($temp_slab_rates as $skey => $slab_value)
- {
-
- if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) ))
- {
+ $temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
+ $age = calculate_days_bw_dates(from_date: $emp_data['dob'], to_date: $temp_date)->y;
+ foreach ($temp_slab_rates as $skey => $slab_value) {
+
+ if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && (strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'])) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3))) {
// echo $emp_data['name']; die;
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
- $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
+ $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
- $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1);
+ $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
- $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1));
- $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.','');
- $emp_data['policy_details']['age_band'] = $slab_value['age_from'].'-'.$slab_value['age_to'];
+ $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
+ $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
+ $emp_data['policy_details']['age_band'] = $slab_value['age_from'] . '-' . $slab_value['age_to'];
$is_match_found = true;
break;
}
-
}
break;
case "7":
//GMC - Employees + Dependent Age + SI
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
- $temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
- $age = calculate_days_bw_dates(from_date: $emp_data['dob'],to_date: $temp_date)->y;
- foreach ($temp_slab_rates as $skey => $slab_value)
- {
-
- if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) ))
- {
+ $temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
+ $age = calculate_days_bw_dates(from_date: $emp_data['dob'], to_date: $temp_date)->y;
+ foreach ($temp_slab_rates as $skey => $slab_value) {
+
+ if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && (strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'])) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3))) {
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
- $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
+ $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
- $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1);
+ $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
- $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1));
- $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.','');
- $emp_data['policy_details']['age_band'] = $slab_value['age_from'].'-'.$slab_value['age_to'];
+ $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
+ $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
+ $emp_data['policy_details']['age_band'] = $slab_value['age_from'] . '-' . $slab_value['age_to'];
$is_match_found = true;
break;
@@ -1329,19 +1237,17 @@ if (!function_exists('premium_calculation_manager'))
//GMC - SI as per Grade or Band
$employee_received_band = $emp_data['temp']['band'];
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
- foreach ($temp_slab_rates as $skey => $slab_value)
- {
-
- if($slab_value['grade'] == $employee_received_band && $slab_value['unit'] == $emp_data['unit'] && $slab_value['si'] == $employee_received_si && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) ))
- {
+ foreach ($temp_slab_rates as $skey => $slab_value) {
+
+ if ($slab_value['grade'] == $employee_received_band && $slab_value['unit'] == $emp_data['unit'] && $slab_value['si'] == $employee_received_si && (($slab_value['premium_type'] == 1 && (strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'])) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3))) {
// $emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
- $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
+ $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
- $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1);
+ $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
- $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1));
- $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.','');
+ $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
+ $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$is_match_found = true;
break;
}
@@ -1351,18 +1257,16 @@ if (!function_exists('premium_calculation_manager'))
//GMC - Flat Rate for all
$employee_received_band = $emp_data['temp']['band'];
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
- foreach ($temp_slab_rates as $skey => $slab_value)
- {
-
- if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] )) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) ))
- {
+ foreach ($temp_slab_rates as $skey => $slab_value) {
+
+ if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && (($slab_value['premium_type'] == 1 && (strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'])) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3))) {
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
- $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
+ $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
- $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1);
+ $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
- $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1));
- $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.','');
+ $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
+ $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$is_match_found = true;
break;
}
@@ -1375,22 +1279,22 @@ if (!function_exists('premium_calculation_manager'))
// echo $emp_data['name'].'-'.$employee_received_si.' ';
// echo $emp_data['temp']['grid_type'].' ';
$emp_data['policy_details']['basic_cover_si'] = null;
- foreach ($temp_slab_rates as $skey => $slab_value)
- {
+ foreach ($temp_slab_rates as $skey => $slab_value) {
// echo $slab_value['si'].'-'.$slab_value['age_from'].'-'.$slab_value['age_to'].'-'.$max_age.' ';
- if( $slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] &&
- ($slab_value['age_from'] <= $max_age && $slab_value['age_to'] >= $max_age) &&
- (($slab_value['premium_type'] == 1 &&
- ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] )) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) ) )
- {
+ if (
+ $slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] &&
+ ($slab_value['age_from'] <= $max_age && $slab_value['age_to'] >= $max_age) &&
+ (($slab_value['premium_type'] == 1 &&
+ (strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'])) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3))
+ ) {
$emp_data['policy_details']['basic_cover_si'] = $employee_received_si;
$emp_data['policy_details']['date_coverage'] = isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date'];
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
- $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1);
+ $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
- $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1));
- $emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.',''));
- $emp_data['policy_details']['age_band'] = $slab_value['age_from'].'-'.$slab_value['age_to'];
+ $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
+ $emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', ''));
+ $emp_data['policy_details']['age_band'] = $slab_value['age_from'] . '-' . $slab_value['age_to'];
$is_match_found = true;
break;
@@ -1398,18 +1302,16 @@ if (!function_exists('premium_calculation_manager'))
}
break;
case "11":
- //GMC - Maximum count per Family
+ //GMC - Maximum count per Family
$max_count = $emp_data['temp']['max_count'];
$employee_received_band = $emp_data['band'];
// echo $employee_received_band;
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
$emp_data['policy_details']['basic_cover_si'] = null;
- foreach ($temp_slab_rates as $skey => $slab_value)
- {
-
- if($slab_value['si'] == $employee_received_si && $slab_value['grade'] == $employee_received_band && $slab_value['unit'] == $emp_data['unit'] && (($slab_value['premium_type'] == 1 &&
- ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] )) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) ))
- {
+ foreach ($temp_slab_rates as $skey => $slab_value) {
+
+ if ($slab_value['si'] == $employee_received_si && $slab_value['grade'] == $employee_received_band && $slab_value['unit'] == $emp_data['unit'] && (($slab_value['premium_type'] == 1 &&
+ (strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'])) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3))) {
//calculate premium based on count
// echo $emp_data['name'];
$familiy_si_covered = $employee_received_si * $max_count;
@@ -1418,10 +1320,10 @@ if (!function_exists('premium_calculation_manager'))
$emp_data['policy_details']['basic_cover_si'] = $familiy_si_covered;
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
- $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1);
- $emp_data['policy_details']['premium'] = get_premium_for_si(slab_details: $temp_slab_rates,si_amount: $familiy_si_covered,band: $employee_received_band,unit:$emp_data['unit']);
- $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1));
- $emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.',''));
+ $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
+ $emp_data['policy_details']['premium'] = get_premium_for_si(slab_details: $temp_slab_rates, si_amount: $familiy_si_covered, band: $employee_received_band, unit: $emp_data['unit']);
+ $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
+ $emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', ''));
$is_match_found = true;
break;
}
@@ -1429,24 +1331,22 @@ if (!function_exists('premium_calculation_manager'))
break;
case "12":
- //GMC - Employee + relationship
-
+ //GMC - Employee + relationship
+
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
$employee_relationship = $slug->slugify($emp_data['relationship']);
$employee_relationship = ($employee_relationship == 'daughter' || $employee_relationship == 'son' ? $employee_relationship = 'child' : $employee_relationship);
$emp_data['policy_details']['basic_cover_si'] = null;
- foreach ($temp_slab_rates as $skey => $slab_value)
- {
- if( $slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ((($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) && $slab_value['relationship'] == $employee_relationship) || ($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) )) )
- {
+ foreach ($temp_slab_rates as $skey => $slab_value) {
+ if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ((($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) && $slab_value['relationship'] == $employee_relationship) || ($slab_value['premium_type'] == 1 && (strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'])))) {
$emp_data['policy_details']['basic_cover_si'] = $employee_received_si;
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
- $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1);
+ $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
- $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1));
- $emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.',''));
+ $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
+ $emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', ''));
$is_match_found = true;
break;
}
@@ -1454,26 +1354,24 @@ if (!function_exists('premium_calculation_manager'))
break;
case "13":
- //GMC - Employee + relationship + age
+ //GMC - Employee + relationship + age
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
$employee_relationship = $slug->slugify($emp_data['relationship']);
$employee_relationship = ($employee_relationship == 'daughter' || $employee_relationship == 'son' ? $employee_relationship = 'child' : $employee_relationship);
$emp_data['policy_details']['basic_cover_si'] = null;
$temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
- $age = calculate_days_bw_dates(from_date: $emp_data['dob'],to_date: $temp_date)->y;
- foreach ($temp_slab_rates as $skey => $slab_value)
- {
- if( $slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && ((($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) && $slab_value['relationship'] == $employee_relationship) || ($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) )) )
- {
+ $age = calculate_days_bw_dates(from_date: $emp_data['dob'], to_date: $temp_date)->y;
+ foreach ($temp_slab_rates as $skey => $slab_value) {
+ if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && ((($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) && $slab_value['relationship'] == $employee_relationship) || ($slab_value['premium_type'] == 1 && (strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'])))) {
$emp_data['policy_details']['basic_cover_si'] = $employee_received_si;
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
- $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1);
+ $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
- $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days);
- $emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.',''));
- $emp_data['policy_details']['age_band'] = $slab_value['age_from'].'-'.$slab_value['age_to'];
+ $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days);
+ $emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', ''));
+ $emp_data['policy_details']['age_band'] = $slab_value['age_from'] . '-' . $slab_value['age_to'];
$is_match_found = true;
break;
}
@@ -1483,53 +1381,48 @@ if (!function_exists('premium_calculation_manager'))
default:
- $myLogger->logme('error',($emp_data['emp_code'].'-'.$emp_data['name'].' - grid type not found'));
- }
+ $myLogger->logme('error', ($emp_data['emp_code'] . '-' . $emp_data['name'] . ' - grid type not found'));
+ }
//this if condition for premium calculated & premium type 3 (familiy floater but premium calculated every individual implemented later) then remove si amount only for dependents (not self)
- if($is_match_found && strtolower($emp_data['relationship']) != 'self' && $temp_slab_rates[0]['premium_type'] == 3)
- {
+ if ($is_match_found && strtolower($emp_data['relationship']) != 'self' && $temp_slab_rates[0]['premium_type'] == 3 && $policy_terms['is_addon'] != 3) {
//set dependent si to 0
- $emp_data['policy_details']['basic_cover_si'] = 0;
+ $emp_data['policy_details']['basic_cover_si'] = 0;
}
- if(!$is_match_found)
- {
+ if (!$is_match_found) {
$temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
- $age = calculate_days_bw_dates(from_date: $emp_data['dob'],to_date: $temp_date)->y;
- $log_message = '[ client_policy_id : ' .$emp_data['policy_details']['client_policy_id'].' - '. $emp_data['emp_code'].' - '.$emp_data['name'] .' - '. $emp_data['policy_details']['basic_cover_si'] . ', Age : '. $age.' ]';
- if($temp_slab_rates[0]['premium_type'] == 1)
- {
- $log_message .= ' - skipping, calculating only self..!';
- //reset emp si and others policy level data if premium only for self
- // $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
- $emp_data['policy_details']['basic_cover_si'] = 0;
- $emp_data['policy_details']['premium'] = 0;
- $emp_data['policy_details']['rata_premimum'] = 0;
- $emp_data['policy_details']['gst'] = 0;
- $emp_data['policy_details']['days'] = 0;
- $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
- }
- else { $log_message .= '- skipping, slab rate not found'; }
- $myLogger->logme('error',$log_message);
+ $age = calculate_days_bw_dates(from_date: $emp_data['dob'], to_date: $temp_date)->y;
+ $log_message = '[ client_policy_id : ' . $emp_data['policy_details']['client_policy_id'] . ' - ' . $emp_data['emp_code'] . ' - ' . $emp_data['name'] . ' - ' . $emp_data['policy_details']['basic_cover_si'] . ', Age : ' . $age . ' ]';
+ if ($temp_slab_rates[0]['premium_type'] == 1) {
+ $log_message .= ' - skipping, calculating only self..!';
+ //reset emp si and others policy level data if premium only for self
+ // $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
+ $emp_data['policy_details']['basic_cover_si'] = 0;
+ $emp_data['policy_details']['premium'] = 0;
+ $emp_data['policy_details']['rata_premimum'] = 0;
+ $emp_data['policy_details']['gst'] = 0;
+ $emp_data['policy_details']['days'] = 0;
+ $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
+ } else {
+ $log_message .= '- skipping, slab rate not found';
+ }
+ $myLogger->logme('error', $log_message);
// echo $log_message;
-
+
}
return $emp_data;
-
}
}
-if (!function_exists('calculate_pro_rata_premimum'))
-{
- function calculate_pro_rata_premimum($premium,$employee_policy_coverage_days,$policy_coverage_days)
+if (!function_exists('calculate_pro_rata_premimum')) {
+ function calculate_pro_rata_premimum($premium, $employee_policy_coverage_days, $policy_coverage_days)
{
- return (float) number_format(($premium / ($policy_coverage_days) ) * $employee_policy_coverage_days,2,'.','');
+ return (float) number_format(($premium / ($policy_coverage_days)) * $employee_policy_coverage_days, 2, '.', '');
}
}
-if (!function_exists('no_of_days_in_current_fin_year'))
-{
+if (!function_exists('no_of_days_in_current_fin_year')) {
function no_of_days_in_current_fin_year()
{
return true;
@@ -1537,66 +1430,64 @@ if (!function_exists('no_of_days_in_current_fin_year'))
}
//transform db columns into excel rows with indexs
-if (!function_exists('transform_db_data_to_excel'))
-{
- function transform_db_data_to_excel($familiyArr,$actionArr = [])
+if (!function_exists('transform_db_data_to_excel')) {
+ function transform_db_data_to_excel($familiyArr, $actionArr = [])
{
// if($actionArr['action'] == 'dependent_addition')
// {
- $return_data = [];
+ $return_data = [];
- foreach ($familiyArr as $key => $value)
- {
- // dd($value);
- $row = [];
- $row[0] = ($key + 1);
- $row[6] = $value['basic_cover_si'];
- $row[14] = $value['pre_existing_alignments'];
- $row[16] = isset($value['date_of_exit']) ? change_date_format($value['date_of_exit'], 'Y-m-d', 'd-M-Y') : NULL;
- $row[17] = $value['reason_for_exit'];
- $row[18] = $value['unit'];
+ foreach ($familiyArr as $key => $value) {
+ // dd($value);
+ $row = [];
+ $row[0] = ($key + 1);
+ $row[6] = $value['basic_cover_si'];
+ $row[14] = $value['pre_existing_alignments'];
+ $row[16] = isset($value['date_of_exit']) ? change_date_format($value['date_of_exit'], 'Y-m-d', 'd-M-Y') : NULL;
+ $row[17] = $value['reason_for_exit'];
+ $row[18] = $value['unit'];
-
- $row[7] = isset($value['date_coverage']) ? change_date_format($value['date_coverage'], 'Y-m-d', 'd-M-Y') : NULL;
- $row[1] = $value['emp_code'];
- $row[2] = $value['name'];
- $row[3] = isset($value['dob']) ? change_date_format($value['dob'], 'Y-m-d', 'd-M-Y') : NULL;
- $row[4] = $value['gender'];
- $row[5] = $value['relationship'];
-
- $row[8] = isset($value['doj']) ? change_date_format($value['doj'], 'Y-m-d', 'd-M-Y') : NULL;
- $row[9] = $value['basic_pay'];
- $row[10] = $value['band'];
- $row[11] = $value['designation'];
- $row[12] = $value['mobile'];
- $row[13] = $value['email_corporate'];
- // $actionArr['id'] = $value['file_id'];
- // $actionArr['client_id'] = $value['client_id'];
- $row[15] = $value['change_event'];
- $row['current_action'] = 'DA';
- $row['temp']['source'] = 'db';
- $row['temp']['emp_id'] = $value['emp_id'];
- $row['temp']['emp_policy_id'] = $value['emp_policy_id'];
- $row['temp']['emp_status'] = $value['emp_status'];
- $row['temp']['policy_status'] = $value['status'];
- $row['temp']['rata_premimum'] = $value['rata_premimum'];
- $row['temp']['file_id'] = $value['file_id'];
+ $row[7] = isset($value['date_coverage']) ? change_date_format($value['date_coverage'], 'Y-m-d', 'd-M-Y') : NULL;
- array_push($return_data, ($row));
- }
+ $row[1] = $value['emp_code'];
+ $row[2] = $value['name'];
+ $row[3] = isset($value['dob']) ? change_date_format($value['dob'], 'Y-m-d', 'd-M-Y') : NULL;
+ $row[4] = $value['gender'];
+ $row[5] = $value['relationship'];
- return $return_data;
+ $row[8] = isset($value['doj']) ? change_date_format($value['doj'], 'Y-m-d', 'd-M-Y') : NULL;
+ $row[9] = $value['basic_pay'];
+ $row[10] = $value['band'];
+ $row[11] = $value['designation'];
+ $row[12] = $value['mobile'];
+ $row[13] = $value['email_corporate'];
+ // $actionArr['id'] = $value['file_id'];
+ // $actionArr['client_id'] = $value['client_id'];
+ $row[15] = $value['change_event'];
+ $row['current_action'] = 'DA';
+ $row['temp']['source'] = 'db';
+ $row['temp']['emp_id'] = $value['emp_id'];
+ $row['temp']['emp_policy_id'] = $value['emp_policy_id'];
+ $row['temp']['emp_status'] = $value['emp_status'];
+ $row['temp']['policy_status'] = $value['status'];
+ $row['temp']['rata_premimum'] = $value['rata_premimum'];
+ $row['temp']['file_id'] = $value['file_id'];
+
+ array_push($return_data, ($row));
+ }
+
+ return $return_data;
// }
-
+
}
}
//comparre excel cell names and return range of chars between them
-if (!function_exists('compare_excel_cell_range'))
-{
- function compare_excel_cell_range($highestColumnAllowed, $highestColumnReceivedInExcel) {
+if (!function_exists('compare_excel_cell_range')) {
+ function compare_excel_cell_range($highestColumnAllowed, $highestColumnReceivedInExcel)
+ {
$highestColumnAllowed = strtoupper($highestColumnAllowed);
$highestColumnReceivedInExcel = strtoupper($highestColumnReceivedInExcel);
@@ -1608,8 +1499,7 @@ if (!function_exists('compare_excel_cell_range'))
}
}
-if(!function_exists('get_emp_records_from_audit_history'))
-{
+if (!function_exists('get_emp_records_from_audit_history')) {
function get_emp_records_from_audit_history($employee_id)
{
$db = db_connect();
@@ -1617,21 +1507,18 @@ if(!function_exists('get_emp_records_from_audit_history'))
$res = $db->query($query);
// echo $db->getLastQuery();
$res = $res->getResultArray();
- if(count($res))
- { $temp = [];
- foreach($res as $row)
- {
- $temp[ $row['field_name'] ] = $row['old_value'];
+ if (count($res)) {
+ $temp = [];
+ foreach ($res as $row) {
+ $temp[$row['field_name']] = $row['old_value'];
}
return $temp;
}
return false;
-
}
}
-if(!function_exists('get_emp_policy_records_from_audit_history'))
-{
+if (!function_exists('get_emp_policy_records_from_audit_history')) {
function get_emp_policy_records_from_audit_history($emp_policy_id)
{
$db = db_connect();
@@ -1639,44 +1526,36 @@ if(!function_exists('get_emp_policy_records_from_audit_history'))
$res = $db->query($query);
// echo $db->getLastQuery();
$res = $res->getResultArray();
- if(count($res))
- { $temp = [];
- foreach($res as $row)
- {
- $temp[ $row['field_name'] ] = $row['old_value'];
+ if (count($res)) {
+ $temp = [];
+ foreach ($res as $row) {
+ $temp[$row['field_name']] = $row['old_value'];
}
return $temp;
}
return false;
-
}
}
-if(!function_exists('replace_original_data'))
-{
- function replace_original_data(array $original_data,array $current_data)
+if (!function_exists('replace_original_data')) {
+ function replace_original_data(array $original_data, array $current_data)
{
- foreach($original_data as $key => $data)
- {
- if(array_key_exists($key, $current_data))
- {
- $current_data [$key] = $data;
+ foreach ($original_data as $key => $data) {
+ if (array_key_exists($key, $current_data)) {
+ $current_data[$key] = $data;
}
}
return $current_data;
}
}
-if(!function_exists('get_premium_for_si'))
-{
- function get_premium_for_si(array $slab_details,string $si_amount,string $band,string $unit)
+if (!function_exists('get_premium_for_si')) {
+ function get_premium_for_si(array $slab_details, string $si_amount, string $band, string $unit)
{
// dd($slab_details);
- foreach ($slab_details as $skey => $slab_value)
- {
- if($slab_value['si'] == $si_amount && $slab_value['grade'] == $band && $slab_value['unit'] == $unit)
- {
+ foreach ($slab_details as $skey => $slab_value) {
+ if ($slab_value['si'] == $si_amount && $slab_value['grade'] == $band && $slab_value['unit'] == $unit) {
return $slab_value['premium'];
}
}
@@ -1684,12 +1563,10 @@ if(!function_exists('get_premium_for_si'))
}
}
-if(!function_exists('remap_default_age_ratio_into_relationship'))
-{
- function remap_default_age_ratio_into_relationship(array $general_relationships,array $default_age_ratio)
+if (!function_exists('remap_default_age_ratio_into_relationship')) {
+ function remap_default_age_ratio_into_relationship(array $general_relationships, array $default_age_ratio)
{
- foreach ($default_age_ratio as $relationship => $age_ratio)
- {
+ foreach ($default_age_ratio as $relationship => $age_ratio) {
switch ($relationship) {
case 'child':
if (isset($general_relationships['son'])) {
@@ -1725,7 +1602,7 @@ if(!function_exists('remap_default_age_ratio_into_relationship'))
$general_relationships[$relationship]['age_max'] = $age_ratio['max'];
}
break;
- }
+ }
}
return $general_relationships;
@@ -1733,14 +1610,12 @@ if(!function_exists('remap_default_age_ratio_into_relationship'))
}
-if(!function_exists('check_dup_mobileno'))
-{
- function check_dup_mobileno(array $row,array $existing_mobilenos)
+if (!function_exists('check_dup_mobileno')) {
+ function check_dup_mobileno(array $row, array $existing_mobilenos)
{
- foreach($existing_mobilenos as $k => $value)
- {
- if ($row['12'] == $value['mobile']) {
- return array('status' => false,'error' => "Duplicate Mobile No");
+ foreach ($existing_mobilenos as $k => $value) {
+ if (strtolower($row['5']) == 'self' && $row['12'] == $value['mobile']) {
+ return array('status' => false, 'error' => "Duplicate Mobile No");
// break;
}
}
@@ -1748,14 +1623,12 @@ if(!function_exists('check_dup_mobileno'))
}
}
-if(!function_exists('check_dup_email'))
-{
- function check_dup_email(array $row,array $existing_mobilenos)
+if (!function_exists('check_dup_email')) {
+ function check_dup_email(array $row, array $existing_mobilenos)
{
- foreach($existing_mobilenos as $k => $value)
- {
- if ($row['13'] == $value['email_corporate']) {
- return array('status' => false,'error' => "Duplicate Email");
+ foreach ($existing_mobilenos as $k => $value) {
+ if (strtolower($row['5']) == 'self' && $row['13'] == $value['email_corporate']) {
+ return array('status' => false, 'error' => "Duplicate Email");
// break;
}
}
@@ -1763,52 +1636,51 @@ if(!function_exists('check_dup_email'))
}
}
-if(!function_exists('generate_family_relationship_array'))
-{
- function generate_family_relationship_array($family_structure_from_policy_terms) {
- $family_relationships = [];
+if (!function_exists('generate_family_relationship_array')) {
+ function generate_family_relationship_array($family_structure_from_policy_terms)
+ {
+ $family_relationships = [];
- // Add self and spouse
- if ($family_structure_from_policy_terms['self'] > 0) {
- $family_relationships[] = 'self';
- }
- if ($family_structure_from_policy_terms['spouse'] > 0) {
- $family_relationships[] = 'spouse';
- }
+ // Add self and spouse
+ if ($family_structure_from_policy_terms['self'] > 0) {
+ $family_relationships[] = 'self';
+ }
+ if ($family_structure_from_policy_terms['spouse'] > 0) {
+ $family_relationships[] = 'spouse';
+ }
- // Add children
- if ($family_structure_from_policy_terms['childrens'] > 0) {
- $family_relationships[] = 'son';
- $family_relationships[] = 'daughter';
- }
+ // Add children
+ if ($family_structure_from_policy_terms['childrens'] > 0) {
+ $family_relationships[] = 'son';
+ $family_relationships[] = 'daughter';
+ }
- // Add parents
- if ($family_structure_from_policy_terms['parents'] > 0) {
- $family_relationships[] = 'father';
- $family_relationships[] = 'mother';
- }
+ // Add parents
+ if ($family_structure_from_policy_terms['parents'] > 0) {
+ $family_relationships[] = 'father';
+ $family_relationships[] = 'mother';
+ }
- // Add parents-in-law
- if ($family_structure_from_policy_terms['parents-in-law'] > 0) {
- $family_relationships[] = 'father-in-law';
- $family_relationships[] = 'mother-in-law';
- }
+ // Add parents-in-law
+ if ($family_structure_from_policy_terms['parents-in-law'] > 0) {
+ $family_relationships[] = 'father-in-law';
+ $family_relationships[] = 'mother-in-law';
+ }
- // Add either parents or parents-in-law
- if ($family_structure_from_policy_terms['either-parents-pil'] > 0) {
- $family_relationships[] = 'father';
- $family_relationships[] = 'mother';
- $family_relationships[] = 'father-in-law';
- $family_relationships[] = 'mother-in-law';
- }
+ // Add either parents or parents-in-law
+ if ($family_structure_from_policy_terms['either-parents-pil'] > 0) {
+ $family_relationships[] = 'father';
+ $family_relationships[] = 'mother';
+ $family_relationships[] = 'father-in-law';
+ $family_relationships[] = 'mother-in-law';
+ }
- return $family_relationships;
-}
+ return $family_relationships;
+ }
}
-if(!function_exists('convert_string_to_date'))
-{
- function convert_string_to_date($dateString,$defaultFormat = 'd-M-Y')
+if (!function_exists('convert_string_to_date')) {
+ function convert_string_to_date($dateString, $defaultFormat = 'd-M-Y')
{
$formats = [
'd-M-Y', // 03-APr-2024
@@ -1832,99 +1704,79 @@ if(!function_exists('convert_string_to_date'))
}
-if(!function_exists('transform_enrollment_row_to_inception_row'))
-{
+if (!function_exists('transform_enrollment_row_to_inception_row')) {
function transform_enrollment_row_to_inception_row($row)
{
- $res = [];
- $res[0] = $row[0]; // inception: sno (S.No) -> enrollment: sno (Sno)
- $res[1] = $row[1]; // inception: emp_id (EMP ID) -> enrollment: emp_code (Emp_Code)
- $res[2] = $row[2]; // inception: name_of_emp_dep (NAME OF EMP/DEP) -> enrollment: name (NAME OF EMP/DEP)
- $res[3] = $row[6]; // inception: dob (DOB) -> enrollment: dob (DOB)
- $res[4] = $row[4]; // inception: gender (Gender) -> enrollment: gender (Gender)
- $res[5] = $row[5]; // inception: relationship (RELATIONSHIP) -> enrollment: relationship (Relation)
- $res[6] = $row[9]; // inception: basic_cover_si (BASIC COVER SI) -> enrollment: basic_cover_si (SI)
- $res[7] = $row[13]; // inception: doc (Date of Coverage) -> No match in enrollment
- $res[8] = $row[3]; // inception: doj (DOJ) -> enrollment: doj (DOJ)
- $res[9] = $row[11]; // inception: basic_pay (Basic Pay) -> enrollment: basic_pay (Basic Pay)
- $res[10] = $row[10]; // inception: band_grade (Band/Grade) -> enrollment: band_grade (Grade)
- $res[11] = null; // inception: designation (Designation) -> No match in enrollment
- $res[12] = $row[8]; // inception: phone (Phone) -> enrollment: phone (Mobile)
- $res[13] = $row[7]; // inception: email (Email) -> enrollment: email (Email)
- $res[14] = 1; // inception: pre_existing_ailments (PRE EXISTING AILMENTS) -> No match in enrollment
- $res[15] = null; // inception: change_event (Change event) -> No match in enrollment
- $res[16] = null; // inception: date_of_exit (Date of exit) -> No match in enrollment
- $res[17] = null; // inception: reason_for_exit (Reason for exit) -> No match in enrollment
- return $res;
+ $res = [];
+ $res[0] = $row[0]; // inception: sno (S.No) -> enrollment: sno (Sno)
+ $res[1] = $row[1]; // inception: emp_id (EMP ID) -> enrollment: emp_code (Emp_Code)
+ $res[2] = $row[2]; // inception: name_of_emp_dep (NAME OF EMP/DEP) -> enrollment: name (NAME OF EMP/DEP)
+ $res[3] = $row[6]; // inception: dob (DOB) -> enrollment: dob (DOB)
+ $res[4] = $row[4]; // inception: gender (Gender) -> enrollment: gender (Gender)
+ $res[5] = $row[5]; // inception: relationship (RELATIONSHIP) -> enrollment: relationship (Relation)
+ $res[6] = $row[9]; // inception: basic_cover_si (BASIC COVER SI) -> enrollment: basic_cover_si (SI)
+ $res[7] = $row[13]; // inception: doc (Date of Coverage) -> No match in enrollment
+ $res[8] = $row[3]; // inception: doj (DOJ) -> enrollment: doj (DOJ)
+ $res[9] = $row[11]; // inception: basic_pay (Basic Pay) -> enrollment: basic_pay (Basic Pay)
+ $res[10] = $row[10]; // inception: band_grade (Band/Grade) -> enrollment: band_grade (Grade)
+ $res[11] = null; // inception: designation (Designation) -> No match in enrollment
+ $res[12] = $row[8]; // inception: phone (Phone) -> enrollment: phone (Mobile)
+ $res[13] = $row[7]; // inception: email (Email) -> enrollment: email (Email)
+ $res[14] = 1; // inception: pre_existing_ailments (PRE EXISTING AILMENTS) -> No match in enrollment
+ $res[15] = null; // inception: change_event (Change event) -> No match in enrollment
+ $res[16] = null; // inception: date_of_exit (Date of exit) -> No match in enrollment
+ $res[17] = null; // inception: reason_for_exit (Reason for exit) -> No match in enrollment
+ return $res;
}
}
-if(!function_exists('get_familiy_composition'))
-{
+if (!function_exists('get_familiy_composition')) {
function get_familiy_composition($family_data)
{
// dd($family_data);
$family_composition = [];
$slug = \Config\Services::slug();
- foreach ($family_data as $key => $row)
- {
- // Kint::dump($row);
- $relationship = $slug->slugify($row[5]);
- // echo $relationship;
- if($relationship == 'self')
- {
- $family_composition['self'] = 1;
- }
- else if(!array_key_exists('self', $family_composition))
- {
- $family_composition['self'] = 0;
- }
-
- if($relationship == 'spouse')
- {
- $family_composition['spouse'] = 1;
- }
- else if(!array_key_exists('spouse', $family_composition))
- {
- $family_composition['spouse'] = 0;
- }
-
- if($relationship == 'son' || $relationship == 'daughter')
- {
- $family_composition['childrens'] = (isset($family_composition['childrens']) ? $family_composition['childrens'] + 1 : 1);
- }
- else if(!array_key_exists('childrens', $family_composition))
- {
- $family_composition['childrens'] = 0;
- }
-
- if($relationship == 'father' || $relationship == 'mother')
- {
- $family_composition['parents'] = (isset($family_composition['parents']) ? $family_composition['parents'] + 1 : 1);
- }
- else if(!array_key_exists('parents', $family_composition))
- {
- $family_composition['parents'] = 0;
- }
-
- if($relationship == 'father-in-law' || $relationship == 'mother-in-law')
- {
- $family_composition['parents-in-law'] = (isset($family_composition['parents-in-law']) ? $family_composition['parents-in-law'] + 1 : 1);
- }
- else if(!array_key_exists('parents-in-law', $family_composition))
- {
- $family_composition['parents-in-law'] = 0;
- }
-
+ foreach ($family_data as $key => $row) {
+ // Kint::dump($row);
+ $relationship = $slug->slugify($row[5]);
+ // echo $relationship;
+ if ($relationship == 'self') {
+ $family_composition['self'] = 1;
+ } else if (!array_key_exists('self', $family_composition)) {
+ $family_composition['self'] = 0;
}
- return ($family_composition);
+ if ($relationship == 'spouse') {
+ $family_composition['spouse'] = 1;
+ } else if (!array_key_exists('spouse', $family_composition)) {
+ $family_composition['spouse'] = 0;
+ }
+
+ if ($relationship == 'son' || $relationship == 'daughter') {
+ $family_composition['childrens'] = (isset($family_composition['childrens']) ? $family_composition['childrens'] + 1 : 1);
+ } else if (!array_key_exists('childrens', $family_composition)) {
+ $family_composition['childrens'] = 0;
+ }
+
+ if ($relationship == 'father' || $relationship == 'mother') {
+ $family_composition['parents'] = (isset($family_composition['parents']) ? $family_composition['parents'] + 1 : 1);
+ } else if (!array_key_exists('parents', $family_composition)) {
+ $family_composition['parents'] = 0;
+ }
+
+ if ($relationship == 'father-in-law' || $relationship == 'mother-in-law') {
+ $family_composition['parents-in-law'] = (isset($family_composition['parents-in-law']) ? $family_composition['parents-in-law'] + 1 : 1);
+ } else if (!array_key_exists('parents-in-law', $family_composition)) {
+ $family_composition['parents-in-law'] = 0;
+ }
+ }
+
+ return ($family_composition);
}
}
-if(!function_exists('compare_incoming_family_slab_with_configured_slab'))
-{
+if (!function_exists('compare_incoming_family_slab_with_configured_slab')) {
// function compare_incoming_family_slab_with_configured_slab($slab,$incoming_familiy_composition)
// {
// $relationship_mapping = [
@@ -1974,75 +1826,70 @@ if(!function_exists('compare_incoming_family_slab_with_configured_slab'))
// return $result;
// }
- function compare_incoming_family_slab_with_configured_slab($slab, $incoming_familiy_composition)
-{
- $relationship_mapping = [
- "self" => ["self"],
- "spouse" => ["spouse"],
- "childrens" => ["son", "daughter"],
- "parents" => ["father", "mother"],
- "parents-in-law" => ["father-in-law", "mother-in-law"],
- "either-parents-pil" => ["either-parents-pil"]
- ];
+ function compare_incoming_family_slab_with_configured_slab($slab, $incoming_familiy_composition)
+ {
+ $relationship_mapping = [
+ "self" => ["self"],
+ "spouse" => ["spouse"],
+ "childrens" => ["son", "daughter"],
+ "parents" => ["father", "mother"],
+ "parents-in-law" => ["father-in-law", "mother-in-law"],
+ "either-parents-pil" => ["either-parents-pil"]
+ ];
- $result = ['is_applicable' => false, 'applicable_members' => []];
- $configured_familiy_composition = json_decode($slab['slab_rates'][0]['additional_relationship'], true);
+ $result = ['is_applicable' => false, 'applicable_members' => []];
+ $configured_familiy_composition = json_decode($slab['slab_rates'][0]['additional_relationship'], true);
- // Remove unnecessary keys
- // kint::dump($incoming_familiy_composition);
- // kint::dump($configured_familiy_composition);
- unset($configured_familiy_composition['either-parents-pil']);
- unset($configured_familiy_composition['elders_count']);
+ // Remove unnecessary keys
+ // kint::dump($incoming_familiy_composition);
+ // kint::dump($configured_familiy_composition);
+ unset($configured_familiy_composition['either-parents-pil']);
+ unset($configured_familiy_composition['elders_count']);
- // foreach ($configured_familiy_composition as $key => $value) {
- // if ($value === 0) {
- // // If any relationship is zero, make the rack rate not applicable
- // return $result;
- // }
- // }
+ // foreach ($configured_familiy_composition as $key => $value) {
+ // if ($value === 0) {
+ // // If any relationship is zero, make the rack rate not applicable
+ // return $result;
+ // }
+ // }
- if (count($configured_familiy_composition)) {
- foreach ($configured_familiy_composition as $key => $value) {
- if ( $value != 'NA') {
- if (isset($incoming_familiy_composition[$key])) {
- if ($incoming_familiy_composition[$key] == $value || $value == 'any') {
- $result['is_applicable'] = true;
- $result['applicable_members'] = array_merge($result['applicable_members'], $relationship_mapping[$key]);
+ if (count($configured_familiy_composition)) {
+ foreach ($configured_familiy_composition as $key => $value) {
+ if ($value != 'NA') {
+ if (isset($incoming_familiy_composition[$key])) {
+ if ($incoming_familiy_composition[$key] == $value || $value == 'any') {
+ $result['is_applicable'] = true;
+ $result['applicable_members'] = array_merge($result['applicable_members'], $relationship_mapping[$key]);
+ } else {
+ $result['is_applicable'] = false;
+ $result['applicable_members'] = [];
+ break;
+ }
} else {
$result['is_applicable'] = false;
$result['applicable_members'] = [];
break;
}
- } else {
- $result['is_applicable'] = false;
- $result['applicable_members'] = [];
- break;
}
}
+ } else {
+ $result['is_applicable'] = false;
+ $result['applicable_members'] = [];
}
- } else {
- $result['is_applicable'] = false;
- $result['applicable_members'] = [];
+ // dd($result);
+ return $result;
}
- // dd($result);
- return $result;
}
-
-}
-
-if(!function_exists('get_applicable_familiy_members'))
-{
- function get_applicable_familiy_members($family_data,$applicable_members)
+if (!function_exists('get_applicable_familiy_members')) {
+ function get_applicable_familiy_members($family_data, $applicable_members)
{
$slug = \Config\Services::slug();
- $result = ['index' => [],'max_age'=> [],'max_count' => 0];
- foreach ($family_data as $index => $family_member)
- {
- if(in_array($slug->slugify($family_member[5]),$applicable_members))
- {
- $result['index'] = array_merge($result['index'],[$index]);
- $result['max_age'] = array_merge($result['max_age'],[calculate_days_bw_dates(from_date: $family_member[3])->y]);
+ $result = ['index' => [], 'max_age' => [], 'max_count' => 0];
+ foreach ($family_data as $index => $family_member) {
+ if (in_array($slug->slugify($family_member[5]), $applicable_members)) {
+ $result['index'] = array_merge($result['index'], [$index]);
+ $result['max_age'] = array_merge($result['max_age'], [calculate_days_bw_dates(from_date: $family_member[3])->y]);
}
}
$result['max_count'] = count($result['index']);
@@ -2050,76 +1897,51 @@ if(!function_exists('get_applicable_familiy_members'))
}
}
-if(!function_exists('check_unit'))
-{
- function check_unit($row,$existing_units)
+if (!function_exists('check_unit')) {
+ function check_unit($row, $existing_units)
{
$temp = $row[18];
$temp = empty($row[18]) ? $row[18] : trim($row[18]);
-
- if(in_array($row['current_action'], ['I','A','MI']) )
- {
- if(count($existing_units) == 1)
- {
- if(empty($temp))
- {
+
+ if (in_array($row['current_action'], ['I', 'A', 'MI'])) {
+ if (count($existing_units) == 1) {
+ if (empty($temp)) {
return array('status' => true);
+ } else if ($temp != $existing_units[0]) {
+ return array('status' => false, 'error' => 'wrong unit name');
}
- else if($temp != $existing_units[0])
- {
- return array('status' => false,'error' => 'wrong unit name');
- }
-
-
}
- if(strtolower($row[5]) == 'self')
- {
- if(in_array($temp,$existing_units)) //18 is unit name
+ if (strtolower($row[5]) == 'self') {
+ if (in_array($temp, $existing_units)) //18 is unit name
{
return array('status' => true);
+ } else if (!empty($temp)) {
+ return array('status' => false, 'error' => 'wrong unit name');
+ } else {
+ return array('status' => false, 'error' => 'name of the unit is mandantory');
}
- else if(!empty($temp))
- {
- return array('status' => false,'error' => 'wrong unit name');
- }
- else
- {
- return array('status' => false,'error' => 'name of the unit is mandantory');
- }
- }
- else
- {
- if(empty($temp))
- {
+ } else {
+ if (empty($temp)) {
return array('status' => true);
- }
- else
- {
- if(in_array($temp,$existing_units)) //18 is unit name
+ } else {
+ if (in_array($temp, $existing_units)) //18 is unit name
{
return array('status' => true);
- }
- else
- {
- return array('status' => false,'error' => 'wrong unit name');
+ } else {
+ return array('status' => false, 'error' => 'wrong unit name');
}
}
}
-
-
- }
- else
- {
+ } else {
return array('status' => true);
}
}
}
-if(!function_exists('transform_si_excel_row_to_calculatable_format'))
-{
- function transform_si_excel_row_to_calculatable_format(array $employee,array$employee_policy,array $maxage_and_maxcount,array $slab_details,string $applicable_slab_name,string $augmented_si,array $grid_master)
+if (!function_exists('transform_si_excel_row_to_calculatable_format')) {
+ function transform_si_excel_row_to_calculatable_format(array $employee, array $employee_policy, array $maxage_and_maxcount, array $slab_details, string $applicable_slab_name, string $augmented_si, array $grid_master)
{
$employee['temp'] = [];
$employee['temp']['max_age'] = $maxage_and_maxcount[0]['max_age'];
@@ -2127,7 +1949,7 @@ if(!function_exists('transform_si_excel_row_to_calculatable_format'))
$employee['temp']['grid_name'] = $applicable_slab_name;
$employee['temp']['grid_master'] = $grid_master;
$employee['temp']['acting_self'] = true;
- $employee['temp']['premium_type'] = $grid_master['premium_type'];
+ $employee['temp']['premium_type'] = $slab_details['slab_rates'][0]['premium_type'];
$employee['temp']['grid_type'] = $applicable_slab_name;
$employee['temp']['grid_id'] = $grid_master['ui_type'];
$employee['temp']['action'] = 'SI';
@@ -2137,16 +1959,12 @@ if(!function_exists('transform_si_excel_row_to_calculatable_format'))
$employee['temp']['policy_status'] = null;
$employee['temp']['emp_status'] = null;
$employee['temp']['rata_premimum'] = null;
-
+ $employee['policy_details'] = $employee_policy;
return $employee;
-
-
-
}
}
-if(!function_exists('group_slab_rates_basedon_name'))
-{
+if (!function_exists('group_slab_rates_basedon_name')) {
function group_slab_rates_basedon_name($slab_details)
{
// dd($slab_details);
@@ -2154,17 +1972,15 @@ if(!function_exists('group_slab_rates_basedon_name'))
$temp_slab_rates = [];
$pre_name = '';
$pre_grid_master = [];
- foreach ($slab_details['slab_rates'] as $key => $value)
- {
+ foreach ($slab_details['slab_rates'] as $key => $value) {
$pre_grid_master = $value['grid_master'];
unset($value['grid_master']);
- if($value['rack_rate_name'] != $pre_name)
- {
+ if ($value['rack_rate_name'] != $pre_name) {
$pre_name = $value['rack_rate_name'];
- $temp_slab_rates[ $value['rack_rate_name'] ]['slab_rates'][] = $value;
+ $temp_slab_rates[$value['rack_rate_name']]['slab_rates'][] = $value;
}
- $temp_slab_rates[ $value['rack_rate_name'] ]['slab_rates'][] = $value;
- $temp_slab_rates[ $value['rack_rate_name'] ]['grid_master'] = $pre_grid_master;
+ $temp_slab_rates[$value['rack_rate_name']]['slab_rates'][] = $value;
+ $temp_slab_rates[$value['rack_rate_name']]['grid_master'] = $pre_grid_master;
}
return $temp_slab_rates;
@@ -2180,14 +1996,42 @@ if (!function_exists('generate_family_floater_key')) {
$relation = 'parent';
} else if (strtolower(trim($relationship)) === 'son' || strtolower(trim($relationship)) === 'daughter') {
$relation = 'child';
- } else if (strtolower(trim($relationship)) === 'father in Law' || strtolower(trim($relationship)) === 'mother in Law') {
+ } else if ((strtolower(trim($relationship)) === 'father in Law' || strtolower(trim($relationship)) === 'mother in Law') || (strtolower(trim($relationship)) === 'father-in-Law' || strtolower(trim($relationship)) === 'mother-in-Law')) {
$relation = 'parent_in_law';
} else if (strtolower(trim($relationship)) === 'spouse') {
$relation = 'spouse';
- } else {
+ } else if (strtolower(trim($relationship)) === 'self') {
$relation = 'self';
+ } else {
+ $relation = '';
}
return $relation;
}
-}
\ No newline at end of file
+}
+
+if (!function_exists('formatIndianCurrency')) {
+ function formatIndianCurrency($amount)
+ {
+ $amount = (string) $amount;
+ $decimal = '';
+
+ // Split decimal part if exists
+ if (strpos($amount, '.') !== false) {
+ list($amount, $decimal) = explode('.', $amount);
+ $decimal = '.' . substr($decimal, 0, 2); // Limit to 2 decimal places
+ }
+
+ $lastThree = substr($amount, -3);
+ $rest = substr($amount, 0, -3);
+
+ if ($rest != '') {
+ $rest = preg_replace("/\B(?=(\d{2})+(?!\d))/", ",", $rest);
+ $formatted = $rest . ',' . $lastThree;
+ } else {
+ $formatted = $lastThree;
+ }
+
+ return $formatted . $decimal;
+ }
+}
diff --git a/app/Helpers/utility_helper.php b/app/Helpers/utility_helper.php
index 2e932ab7..eae819ea 100755
--- a/app/Helpers/utility_helper.php
+++ b/app/Helpers/utility_helper.php
@@ -55,8 +55,8 @@ if (!function_exists('file_Upload')) {
function file_Upload($fileToUpload, $filepath)
{
if ($fileToUpload !== null && $fileToUpload->isValid() && !$fileToUpload->hasMoved()) {
+ $fileToUpload->move($filepath);
$fileName = $fileToUpload->getName();
- $fileToUpload->move($filepath, $fileName);
return $fileName;
} else {
return "";
@@ -665,3 +665,123 @@ if (!function_exists('check_pay_by_employee_or_company')) {
}
+if (!function_exists('is_json_string')) {
+ function is_json_string($string)
+ {
+ if (!is_string($string)) {
+ return false;
+ }
+
+ $decoded = json_decode($string, true);
+ return (json_last_error() === JSON_ERROR_NONE && is_array($decoded));
+ }
+}
+
+if (!function_exists('check_cd_entry_exist')) {
+ function check_cd_entry_exist($params)
+ {
+ $db = db_connect();
+
+ $client_id = $params['client_id'];
+ $client_policy_id = $params['client_policy_id'];
+ $insurer_id = $params['insurer_id'];
+ $cd_ac_pk = $params['cd_ac_pk'];
+ $event_name = $params['event_name'];
+
+ // Check if truncated entry (sub_type = 8) exists
+ $has_truncated = $db->table('cash_deposit')
+ ->where('client_id', $client_id)
+ ->where('insurer_id', $insurer_id)
+ ->where('cd_ac_pk', $cd_ac_pk)
+ ->where('client_policy_id', $client_policy_id)
+ ->where('event_name', $event_name)
+ ->where('sub_type', 8)
+ ->where('is_active', 1)
+ ->countAllResults();
+
+ if ($has_truncated) {
+
+ echo "has_truncated";
+ // Get all entries with same details (including truncated)
+ $entries = $db->table('cash_deposit')
+ ->where('client_id', $client_id)
+ ->where('insurer_id', $insurer_id)
+ ->where('cd_ac_pk', $cd_ac_pk)
+ ->where('client_policy_id', $client_policy_id)
+ ->where('event_name', $event_name)
+ ->where('is_active', 1)
+ ->where('sub_type !=', 8)
+ ->get()
+ ->getResultArray();
+
+ if (count($entries) > 1) {
+ // Only one entry found (truncated)
+ return true;
+ }else{
+ return false;
+ }
+ } else {
+ // Check if any other entry exists
+ $entry = $db->table('cash_deposit')
+ ->where('client_id', $client_id)
+ ->where('insurer_id', $insurer_id)
+ ->where('cd_ac_pk', $cd_ac_pk)
+ ->where('client_policy_id', $client_policy_id)
+ ->where('event_name', $event_name)
+ ->where('is_active', 1)
+ ->get()
+ ->getRowArray();
+
+ if (!empty($entry)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+}
+
+if (!function_exists('expected_amount_calc')) {
+ function expected_amount_calc($data, $index)
+ {
+ $agreed_amount = (float) ($data['agreed_amount'][$index] ?? 0);
+ $agreed_bp_per = (float) ($data['agreed_bp'][$index] ?? 0);
+ $agreed_tp_per = (float) ($data['agreed_tp'][$index] ?? 0);
+ $agreed_tep_per = (float) ($data['agreed_ter'][$index] ?? 0);
+
+ $standard_bp_per = (float) ($data['standard_bp'][$index] ?? 0);
+ $standard_tp_per = (float) ($data['standard_tp'][$index] ?? 0);
+ $standard_tep_per = (float) ($data['standard_ter'][$index] ?? 0);
+
+
+ if($data['bro_payable_by'] == 0){
+ $base_premium = (float) ($data['co_premium'][$index] ?? 0);
+ $third_part_premium = (float) ($data['co_tp_premium'][$index] ?? 0);
+ $terrisom_premium = (float) ($data['co_ter_premium'][$index] ?? 0);
+ }else{
+ $base_premium = (float) ($data['base_premium'][$index] ?? 0);
+ $third_part_premium = (float) ($data['tp_premium'][$index] ?? 0);
+ $terrisom_premium = (float) ($data['ter_premium'][$index] ?? 0);
+ }
+
+ $sum_of_agreed_premium = $agreed_bp_per + $agreed_tp_per + $agreed_tep_per;
+
+ $expectedAmount = 0;
+
+ if ($agreed_amount > 0) {
+ $expectedAmount = $agreed_amount;
+ } elseif ($sum_of_agreed_premium > 0) {
+ $expectedAmount =
+ ($base_premium * $agreed_bp_per / 100) +
+ ($third_part_premium * $agreed_tp_per / 100) +
+ ($terrisom_premium * $agreed_tep_per / 100);
+ } else {
+ $expectedAmount =
+ ($base_premium * $standard_bp_per / 100) +
+ ($third_part_premium * $standard_tp_per / 100) +
+ ($terrisom_premium * $standard_tep_per / 100);
+ }
+
+ return round($expectedAmount, 2); // Optional: round to 2 decimal places
+ }
+}
diff --git a/app/Models/BdsPlacementModel.php b/app/Models/BdsPlacementModel.php
new file mode 100644
index 00000000..82edfce5
--- /dev/null
+++ b/app/Models/BdsPlacementModel.php
@@ -0,0 +1,126 @@
+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
+ 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', $sales_person_id)
+ ->get()
+ ->getRowArray();
+
+ $row['sales_person'] = $user['email'] ?? 'N/A';
+ } else {
+ $row['sales_person'] = 'Not Assigned';
+ }
+
+ $head = $this->db->table('user_profiles')
+ ->select('email') // or whatever field
+ ->where('role', 5)
+ ->where('is_active',1)
+ ->get()
+ ->getResultArray();
+
+
+ $row['heads'] = $head;
+
+ $admin = $this->db->table('user_profiles')
+ ->select('email')
+ ->where("is_active",1)
+ ->where("role",1)
+ ->get()
+ ->getResultArray();
+
+ $row['admins'] = $admin;
+
+ $buisenessTeam = $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)
+ ->where("ut.is_active",1)
+ ->get()
+ ->getResultArray();
+
+ $row['buisness_team'] = $buisenessTeam;
+
+
+ }
+
+
+ return $data;
+ }
+}
diff --git a/app/Models/BookStackRoleModel.php b/app/Models/BookStackRoleModel.php
new file mode 100644
index 00000000..a57256a9
--- /dev/null
+++ b/app/Models/BookStackRoleModel.php
@@ -0,0 +1,19 @@
+select($columns)
- ->where('is_active',1)
+ ->where('clients.is_active',1)
->findAll();
- // if($role_id == 2 || $role_id == 3){
+ if($role_id == 2 || $role_id == 3){
- // $clients = $this->select($columns)
- // ->join('client_rm', 'client_rm.client_id = clients.id')
- // ->where('client_rm.user_id', $user_id)
- // ->where('clients.is_active',1)
- // ->findAll();
- // }
+ $clients = $this->select($columns)
+ ->join('client_rm', 'client_rm.client_id = clients.id')
+ ->where('client_rm.user_id', $user_id)
+ ->where('clients.is_active',1)
+ ->findAll();
+ }
+
+ // $clients->findAll();
@@ -107,11 +109,24 @@ class ClientModel extends Model
public function getCreatedByUserName(){
- return $this->db->table('clients')
+ $role_id = get_role_id();
+ $user_id = get_session_userid();
+
+ $query = $this->db->table('clients')
->select('clients.*')
- ->where('is_active', 1)
- ->get()
- ->getResult();
+ ->join('client_rm', 'client_rm.client_id = clients.id','left')
+ ->where('clients.is_active', 1);
+
+ if (in_array($role_id, [2, 3])) {
+
+ // If the user is a Account Manager or Manager, filter by user_id
+ $query->where('client_rm.user_id', $user_id);
+ }
+
+ $data = $query->groupBy("clients.id")->get()->getResult();
+ // dd($data);
+
+ return $data;
}
diff --git a/app/Models/ClientPolicyModel.php b/app/Models/ClientPolicyModel.php
index c8fcb855..59f05958 100755
--- a/app/Models/ClientPolicyModel.php
+++ b/app/Models/ClientPolicyModel.php
@@ -54,6 +54,7 @@ class ClientPolicyModel extends Model
"is_member_modify_allowed",
"cd_ac_pk",
"is_lgbtq",
+ "placement_json",
];
// Callbacks
@@ -70,7 +71,7 @@ class ClientPolicyModel extends Model
protected function checkAndADDCreatedByValue(array $data)
{
// Check if 'updated_by' value is null or empty
- if (empty($data['data']['created_by'])) {
+ if (empty($data['data']['created_by'])) {
// Set 'updated_by' value to the current session user ID
$data['data']['created_by'] = get_session_userid();
}
@@ -81,7 +82,7 @@ class ClientPolicyModel extends Model
protected function checkAndUpdateUpdatedByValue(array $data)
{
// Check if 'updated_by' value is null or empty
- if (empty($data['data']['updated_by'])) {
+ if (empty($data['data']['updated_by'])) {
// Set 'updated_by' value to the current session user ID
$data['data']['updated_by'] = get_session_userid();
}
@@ -89,100 +90,102 @@ class ClientPolicyModel extends Model
return $data;
}
- public function getClientPolicyById($id){
+ public function getClientPolicyById($id)
+ {
return $this->db->table('client_policy')
- ->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('policies.name as policy_name')
- ->select('insurer_branch.branch_name as insurer_branch_name, insurer_branch.branch_code as insurer_branch_code')
- ->select('tpa_branch.branch_name as tpa_branch_name, tpa_branch.branch_code as tpa_branch_code')
- ->join('insurers', 'insurers.id = client_policy.insurer_id')
- ->join('insurer_branch', 'client_policy.insurer_branch_id = insurer_branch.id')
- ->join('tpa', 'tpa.id = client_policy.tpa_id')
- ->join('tpa_branch', 'client_policy.tpa_branch_id = tpa_branch.id')
- ->join('policies', 'policies.id = client_policy.policy_id')
- ->where('client_policy.id', $id)
- ->get()
- ->getResult();
-
+ ->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('policies.name as policy_name')
+ ->select('insurer_branch.branch_name as insurer_branch_name, insurer_branch.branch_code as insurer_branch_code')
+ ->select('tpa_branch.branch_name as tpa_branch_name, tpa_branch.branch_code as tpa_branch_code')
+ ->join('insurers', 'insurers.id = client_policy.insurer_id')
+ ->join('insurer_branch', 'client_policy.insurer_branch_id = insurer_branch.id')
+ ->join('tpa', 'tpa.id = client_policy.tpa_id')
+ ->join('tpa_branch', 'client_policy.tpa_branch_id = tpa_branch.id')
+ ->join('policies', 'policies.id = client_policy.policy_id')
+ ->where('client_policy.id', $id)
+ ->get()
+ ->getResult();
}
- public function getClientPolicyByClientId($client_id){
-
+ public function getClientPolicyByClientId($client_id)
+ {
+
return $this->db->table('client_policy')
- ->select('client_policy.*')
- ->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('policy_type.policy_type as policy_type_name')
- ->select('insurer_branch.branch_name as insurer_branch_name, insurer_branch.branch_code as insurer_branch_code')
- ->select('tpa_branch.branch_name as tpa_branch_name, tpa_branch.branch_code as tpa_branch_code')
- ->select('policy_type.policy_type as policy_type_name')
- ->select('client_branch.branch_name as branch_name')
- ->join('insurers', 'insurers.id = client_policy.insurer_id')
- ->join('insurer_branch', 'client_policy.insurer_branch_id = insurer_branch.id')
- ->join('tpa', 'tpa.id = client_policy.tpa_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('client_branch', 'client_branch.id = client_policy.client_branch_id')
- ->where('client_policy.client_id', $client_id)
- ->where('client_policy.policy_status', 1)
- ->where('client_policy.is_active', 1)
- ->get()
- ->getResult();
-
-
-
+ ->select('client_policy.*')
+ ->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('policy_type.policy_type as policy_type_name')
+ ->select('insurer_branch.branch_name as insurer_branch_name, insurer_branch.branch_code as insurer_branch_code')
+ ->select('tpa_branch.branch_name as tpa_branch_name, tpa_branch.branch_code as tpa_branch_code')
+ ->select('policy_type.policy_type as policy_type_name')
+ ->select('client_branch.branch_name as branch_name')
+ ->join('insurers', 'insurers.id = client_policy.insurer_id')
+ ->join('insurer_branch', 'client_policy.insurer_branch_id = insurer_branch.id')
+ ->join('tpa', 'tpa.id = client_policy.tpa_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('client_branch', 'client_branch.id = client_policy.client_branch_id')
+ ->where('client_policy.client_id', $client_id)
+ ->where('client_policy.policy_status', 1)
+ ->where('client_policy.is_active', 1)
+ ->get()
+ ->getResult();
}
- public function getPolicyPremium($policy_id){
+ public function getPolicyPremium($policy_id)
+ {
return $this->db->table('policies')
- ->select('policy_type.*')
- ->join('policy_type', 'policy_type.id = policies.policy_type_id')
- ->where('policies.id', $policy_id)
- ->get()
- ->getResult();
+ ->select('policy_type.*')
+ ->join('policy_type', 'policy_type.id = policies.policy_type_id')
+ ->where('policies.id', $policy_id)
+ ->get()
+ ->getResult();
}
- public function getPolicyPremiumPolicyTypeId($policy_type_id){
+ public function getPolicyPremiumPolicyTypeId($policy_type_id)
+ {
return $this->db->table('policies')
- ->select('policy_type.*')
- ->join('policy_type', 'policy_type.id = policies.policy_type_id')
- ->where('policies.id', $policy_type_id)
- ->get()
- ->getResult();
+ ->select('policy_type.*')
+ ->join('policy_type', 'policy_type.id = policies.policy_type_id')
+ ->where('policies.id', $policy_type_id)
+ ->get()
+ ->getResult();
}
- public function getPolicyDetails($client_id,$policy_id)
+ public function getPolicyDetails($client_id, $policy_id)
{
return $this->select('*')
- ->where('client_id',$client_id)
- ->where('id',$policy_id)
- ->get()
- ->getResult();
-
+ ->where('client_id', $client_id)
+ ->where('id', $policy_id)
+ ->get()
+ ->getResult();
}
- public function getinsurerswithclientid($id){
+ public function getinsurerswithclientid($id)
+ {
return $this->db->table('client_policy')
- ->select('client_policy.*, cd_master.cd_ac_no as cd_master_account_no')
- ->select('insurers.name as insurer_name, insurers.short_name as insurer_short')
- ->select('clients.client_name as client_name')
- ->join('clients','clients.id=client_policy.client_id')
- ->join('insurers', 'insurers.id = client_policy.insurer_id')
- ->join('cd_master', 'cd_master.insurer_id = insurers.id AND cd_master.client_id = client_policy.client_id')
- ->where('client_policy.client_id', $id)
- ->where('cd_master.id = client_policy.cd_ac_pk')
- ->groupBy('client_policy.insurer_id')
- ->groupBy('client_policy.client_id', $id) // Group by insurer_id
- ->get()
- ->getResult();
+ ->select('client_policy.*, cd_master.cd_ac_no as cd_master_account_no')
+ ->select('insurers.name as insurer_name, insurers.short_name as insurer_short')
+ ->select('clients.client_name as client_name')
+ ->join('clients', 'clients.id=client_policy.client_id')
+ ->join('insurers', 'insurers.id = client_policy.insurer_id')
+ ->join('cd_master', 'cd_master.insurer_id = insurers.id AND cd_master.client_id = client_policy.client_id')
+ ->where('client_policy.client_id', $id)
+ ->where('cd_master.id = client_policy.cd_ac_pk')
+ ->where('cd_master.is_active', 1)
+ ->groupBy('client_policy.client_id', $id) // Group by insurer_id
+ ->groupBy('client_policy.insurer_id')
+ ->groupBy('client_policy.cd_ac_pk')
+ ->get()
+ ->getResult();
// return $this->db->table('client_policy')
// ->select('insurers.name as insurer_name, insurers.short_name as insurer_short')
@@ -197,34 +200,36 @@ class ClientPolicyModel extends Model
// ->getResult();
}
-
- public function getinsurerswithinsurenceid($insurerId){
+
+ public function getinsurerswithinsurenceid($insurerId)
+ {
return $this->db->table('client_policy')
- ->select('client_policy.*')
- ->select('insurers.name as insurer_name, insurers.short_name as insurer_short')
- ->select('clients.client_name as clientname, clients.short_name as clientshort')
- ->join('insurers', 'insurers.id = client_policy.insurer_id')
- ->join('clients', 'clients.id = client_policy.client_id')
- ->where('client_policy.insurer_id', $insurerId)
- ->groupBy('client_policy.client_id') // Group by insurer_id
- ->get()
- ->getResult();
+ ->select('client_policy.*')
+ ->select('insurers.name as insurer_name, insurers.short_name as insurer_short')
+ ->select('clients.client_name as clientname, clients.short_name as clientshort')
+ ->join('insurers', 'insurers.id = client_policy.insurer_id')
+ ->join('clients', 'clients.id = client_policy.client_id')
+ ->where('client_policy.insurer_id', $insurerId)
+ ->groupBy('client_policy.client_id') // Group by insurer_id
+ ->get()
+ ->getResult();
}
- public function getClientById($id) {
+ public function getClientById($id)
+ {
$query = $this->db->table('clients')->getWhere(['id' => $id]);
- // Debug statement
+ // Debug statement
return $query->getRow();
}
- public function getDepositData($clientId, $insurerId)
+ public function getDepositData($clientId, $insurerId, $cd_ac_pk = null)
{
- // Fetch the deposit data based on client and insurer IDs
- return $this->db->table('cash_deposit')
+ // Fetch the deposit data based on client and insurer IDs
+ $query = $this->db->table('cash_deposit')
->select('cash_deposit.*')
->select('insurers.name as insurer_name, insurers.short_name as insurer_short')
->select('clients.client_name as clientname, clients.short_name as clientshort, client_policy.policy_no')
@@ -241,184 +246,193 @@ class ClientPolicyModel extends Model
->join('policy_type', 'policy_type.id = client_policy.policy_type_id', 'left')
->where('cash_deposit.client_id', $clientId)
->where('cash_deposit.insurer_id', $insurerId)
- ->where('cash_deposit.is_active', 1)
+ ->where('cash_deposit.is_active', 1);
// ->where('cash_deposit.cd_ac_pk = cd_master.id')
- ->orderBy('cash_deposit.id', 'DESC')
+ if(!empty($cd_ac_pk)){
+ $query->where('cash_deposit.cd_ac_pk', $cd_ac_pk);
+ }
+ $query->orderBy('cash_deposit.id', 'DESC');
+
+ return $query->get()->getResult();
+ }
+
+
+ public function getDepositSummary($clientId, $insurerId, $cd_ac_pk)
+ {
+ // Fetch the sum of credit and debit transactions and calculate the balance
+ return $this->db->table('cash_deposit')
+ ->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();
+ }
+ // Inside your clientPolicyModel
+ // Inside your clientPolicyModel
+ // public function getDepositDataWithBalance($clientId, $insurerId)
+ // {
+ // // Fetch deposit data with balance information
+ // $builder = $this->db->table('cash_deposit');
+ // $builder->select('id, created_at, description, sub_type, amount, transaction_type');
+
+ // $builder->where('client_id', $clientId);
+ // $builder->where('insurer_id', $insurerId);
+ // $builder->orderBy('created_at', 'asc');
+
+ // $depositData = $builder->get()->getResult();
+
+ // $currentBalance = 0;
+
+ // foreach ($depositData as $transaction) {
+ // if ($transaction->transaction_type == 'Credit') {
+ // $currentBalance += $transaction->amount;
+ // } elseif ($transaction->transaction_type == 'Debit') {
+ // $currentBalance -= $transaction->amount;
+ // }
+
+ // $transaction->balance = $currentBalance;
+ // }
+
+ // return $depositData;
+ // }
+
+
+
+
+ public function getBalances($clientId)
+ {
+ $depositsummary = $this->getDepositlistsummary($clientId);
+ $balances = [];
+
+ foreach ($depositsummary as $summary) {
+ $insurerId = $summary->insurer_id;
+ $balances[$insurerId] = $summary;
+ }
+
+ return $balances;
+ }
+
+ public function getDepositlistsummary($id)
+ {
+ return $this->db->table('cash_deposit')
+ ->select('insurer_id, cd_ac_pk')
+ ->select('SUM(CASE WHEN transaction_type = "Credit" THEN amount ELSE -amount END) AS balance')
+ ->where('client_id', $id)
+ ->where('is_active', 1)
+ ->groupBy('insurer_id')
+ // ->groupBy('cd_ac_pk')
->get()
->getResult();
}
-
-
- public function getDepositSummary($clientId, $insurerId)
-{
- // Fetch the sum of credit and debit transactions and calculate the balance
- return $this->db->table('cash_deposit')
- ->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('cash_deposit.is_active', 1)
- ->get()
- ->getRow();
-}
-// Inside your clientPolicyModel
-// Inside your clientPolicyModel
-// public function getDepositDataWithBalance($clientId, $insurerId)
-// {
-// // Fetch deposit data with balance information
-// $builder = $this->db->table('cash_deposit');
-// $builder->select('id, created_at, description, sub_type, amount, transaction_type');
-
-// $builder->where('client_id', $clientId);
-// $builder->where('insurer_id', $insurerId);
-// $builder->orderBy('created_at', 'asc');
-
-// $depositData = $builder->get()->getResult();
-
-// $currentBalance = 0;
-
-// foreach ($depositData as $transaction) {
-// if ($transaction->transaction_type == 'Credit') {
-// $currentBalance += $transaction->amount;
-// } elseif ($transaction->transaction_type == 'Debit') {
-// $currentBalance -= $transaction->amount;
-// }
-
-// $transaction->balance = $currentBalance;
-// }
-
-// return $depositData;
-// }
+ public function updateStatus()
+ {
+ // Update client_policy table
+ $client = $this->db->query("UPDATE client_policy SET policy_status = 0 WHERE policy_end_date < CURDATE()");
+ $client_count = $this->db->affectedRows();
+ // Update employee_polices table
+ $employee = $this->db->query("UPDATE employee_polices SET status = 'expired' WHERE policy_end_date < CURDATE()");
+ $emp_count = $this->db->affectedRows();
-public function getBalances($clientId)
-{
- $depositsummary = $this->getDepositlistsummary($clientId);
- $balances = [];
+ // Log the result
+ log_message('info', "Client policies updated: {$client_count}");
+ log_message('info', "Employee policies updated: {$emp_count}");
- foreach ($depositsummary as $summary) {
- $insurerId = $summary->insurer_id;
- $balances[$insurerId] = $summary;
+ return ['client' => $client_count, 'emp' => $emp_count];
}
- return $balances;
-}
+ public function getpolicyWithPattern($client_id)
+ {
-public function getDepositlistsummary($id)
-{
- return $this->db->table('cash_deposit')
- ->select('insurer_id')
- ->select('SUM(CASE WHEN transaction_type = "Credit" THEN amount ELSE -amount END) AS balance')
- ->where('client_id', $id)
- ->groupBy('insurer_id')
- ->get()
- ->getResult();
-}
+ $query = $this->db->table('client_policy')
+ ->select('client_policy.*, policies.name, policies.policy_type_id, policy_type.policy_type')
+ ->join('policies', 'policies.id = client_policy.policy_id')
+ ->join('policy_type', 'policy_type.id = policies.policy_type_id')
+ // ->where('policy_type.policy_type', 'GMC')
+ ->whereIn('policy_type.id', [2, 3])
+ ->where('client_policy.client_id', $client_id)
+ ->get()
+ ->getResult();
-public function updateStatus(){
-
- // Update client_policy table
- $client = $this->db->query("UPDATE client_policy SET policy_status = 0 WHERE policy_end_date < CURDATE()");
- $client_count = $this->db->affectedRows();
- // Update employee_polices table
- $employee = $this->db->query("UPDATE employee_polices SET status = 'expired' WHERE policy_end_date < CURDATE()");
- $emp_count = $this->db->affectedRows();
-
- return ['client'=>$client_count, 'emp' => $emp_count];
-
-
-}
-
-public function getpolicyWithPattern($client_id){
-
- $query = $this->db->table('client_policy')
- ->select('client_policy.*, policies.name, policies.policy_type_id, policy_type.policy_type')
- ->join('policies', 'policies.id = client_policy.policy_id')
- ->join('policy_type', 'policy_type.id = policies.policy_type_id')
- // ->where('policy_type.policy_type', 'GMC')
- ->whereIn('policy_type.id', [2, 3])
- ->where('client_policy.client_id', $client_id)
- ->get()
- ->getResult();
-
-
- return $query;
-}
-
-public function getTopUpPolicy($client_id, $type){
-
- $query = "
- SELECT client_policy.*, policies.name, policies.policy_type_id
- FROM client_policy
- JOIN policies ON policies.id = client_policy.policy_id
- JOIN policy_type ON policy_type.id = policies.policy_type_id
- WHERE policy_type.policy_type = '{$type}'
- AND client_policy.client_id = {$client_id}";
-
- $result = $this->db->query($query)->getResult();
-
- return $result;
-
-}
-
-
-public function getClientPolicyByPolicyType($client_id, $type){
-
-
- $query = $this->db->table('client_policy')
- ->select('client_policy.*, insurers.name as insurer_name, insurers.short_name as insurer_short')
- ->select('tpa.name as tpa_name, tpa.short_name as tpa_short')
- ->select('policies.name as policy_name, policies.policy_type_id')
- ->select('policy_type.policy_type as policy_type_name')
- ->select('insurer_branch.branch_name as insurer_branch_name, insurer_branch.branch_code as insurer_branch_code')
- ->select('tpa_branch.branch_name as tpa_branch_name, tpa_branch.branch_code as tpa_branch_code')
- ->join('insurers', 'insurers.id = client_policy.insurer_id')
- ->join('insurer_branch', 'client_policy.insurer_branch_id = insurer_branch.id')
- ->join('tpa', 'tpa.id = client_policy.tpa_id')
- ->join('tpa_branch', 'client_policy.tpa_branch_id = tpa_branch.id')
- ->join('policies', 'policies.id = client_policy.policy_id')
- ->join('policy_type', 'policy_type.id = policies.policy_type_id')
- ->where('client_policy.client_id', $client_id)
- ->where('client_policy.policy_status', 1);
-
- if ($type == 2) {
- $query->where('policy_type.policy_type', 'GMC - Top-up');
- } else if ($type == 3) {
- $query->whereIn('policy_type.policy_type', ['GMC - Parents', 'GMC - Top-up(Parents)']);
+ return $query;
}
- $result = $query->get()->getResult();
+ public function getTopUpPolicy($client_id, $type)
+ {
- return $result;
+ $query = "
+ SELECT client_policy.*, policies.name, policies.policy_type_id
+ FROM client_policy
+ JOIN policies ON policies.id = client_policy.policy_id
+ JOIN policy_type ON policy_type.id = policies.policy_type_id
+ WHERE policy_type.policy_type = '{$type}'
+ AND client_policy.client_id = {$client_id}";
+
+ $result = $this->db->query($query)->getResult();
+
+ return $result;
+ }
-}
+ public function getClientPolicyByPolicyType($client_id, $type)
+ {
-public function getPolicyTypeForPolicyBinding($client_id){
+ $query = $this->db->table('client_policy')
+ ->select('client_policy.*, insurers.name as insurer_name, insurers.short_name as insurer_short')
+ ->select('tpa.name as tpa_name, tpa.short_name as tpa_short')
+ ->select('policies.name as policy_name, policies.policy_type_id')
+ ->select('policy_type.policy_type as policy_type_name')
+ ->select('insurer_branch.branch_name as insurer_branch_name, insurer_branch.branch_code as insurer_branch_code')
+ ->select('tpa_branch.branch_name as tpa_branch_name, tpa_branch.branch_code as tpa_branch_code')
+ ->join('insurers', 'insurers.id = client_policy.insurer_id')
+ ->join('insurer_branch', 'client_policy.insurer_branch_id = insurer_branch.id')
+ ->join('tpa', 'tpa.id = client_policy.tpa_id')
+ ->join('tpa_branch', 'client_policy.tpa_branch_id = tpa_branch.id')
+ ->join('policies', 'policies.id = client_policy.policy_id')
+ ->join('policy_type', 'policy_type.id = policies.policy_type_id')
+ ->where('client_policy.client_id', $client_id)
+ ->where('client_policy.policy_status', 1);
- $result = $this->table('client_policy')
- ->select('policy_type.*, client_policy.id as client_policy_id, client_policy.policy_no')
- ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
- ->where('client_policy.client_id', $client_id)
- ->where('client_policy.is_active', 1)
- ->whereIn('policy_type.id', [2,3])
- ->findAll();
+ if ($type == 2) {
+ $query->where('policy_type.policy_type', 'GMC - Top-up');
+ } else if ($type == 3) {
+ $query->whereIn('policy_type.policy_type', ['GMC - Parents', 'GMC - Top-up(Parents)']);
+ }
- return $result;
+ $result = $query->get()->getResult();
+
+ return $result;
+ }
-}
+ public function getPolicyTypeForPolicyBinding($client_id)
+ {
+
+ $result = $this->table('client_policy')
+ ->select('policy_type.*, client_policy.id as client_policy_id, client_policy.policy_no')
+ ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
+ ->where('client_policy.client_id', $client_id)
+ ->where('client_policy.is_active', 1)
+ ->whereIn('policy_type.id', [2, 3])
+ ->findAll();
+
+ return $result;
+ }
-public function getCliendDataForExcelFileName($client_policy_id){
+ public function getCliendDataForExcelFileName($client_policy_id)
+ {
- return $this->table('client_policy')
+ return $this->table('client_policy')
->select('clients.short_name, policy_type.policy_type, client_branch.branch_code')
->join('clients', 'clients.id = client_policy.client_id')
->join('client_branch', 'client_branch.id = client_policy.client_branch_id')
@@ -426,49 +440,48 @@ public function getCliendDataForExcelFileName($client_policy_id){
->where('client_policy.id', $client_policy_id)
->where('client_policy.is_active', 1)
->first();
-
-}
-
-//for this using in CRONE JOB
-public function getPolicyDetailsForRemainder($client_id = null, $branch_id = null, $policy_id = null)
-{
- $builder = $this->table('client_policy')
- ->where('client_policy.is_active', 1)
- ->where('client_policy.policy_status', 1)
- // ->where('client_policy.is_addon', 1)
- // ->where('client_policy.inception_type', 2)
- ->where('client_policy.open_for_enrollment', 1);
-
- if ($client_id && $branch_id) {
- $builder->where('client_policy.client_id', $client_id)
- ->where('client_policy.client_branch_id', $branch_id);
}
- if(empty($policy_id)){
- $builder->whereIn('client_policy.policy_type_id', [2, 3, 4, 5]);
- }else{
- $builder->where('client_policy.id', $policy_id);
+ //for this using in CRONE JOB
+ public function getPolicyDetailsForRemainder($client_id = null, $branch_id = null, $policy_id = null)
+ {
+ $builder = $this->table('client_policy')
+ ->where('client_policy.is_active', 1)
+ ->where('client_policy.policy_status', 1)
+ // ->where('client_policy.is_addon', 1)
+ // ->where('client_policy.inception_type', 2)
+ ->where('client_policy.open_for_enrollment', 1);
+
+ if ($client_id && $branch_id) {
+ $builder->where('client_policy.client_id', $client_id)
+ ->where('client_policy.client_branch_id', $branch_id);
+ }
+
+ if (empty($policy_id)) {
+ $builder->whereIn('client_policy.policy_type_id', [2, 3, 4, 5]);
+ } else {
+ $builder->where('client_policy.id', $policy_id);
+ }
+
+ return $builder->get()->getResultArray();
}
- return $builder->get()->getResultArray();
-}
+ //for this using in CRONE JOB
+ public function getPolicyDetailsForEnrollment($client_id = null, $branch_id = null)
+ {
+ $builder = $this->table('client_policy')
+ ->where('client_policy.is_active', 1)
+ ->where('client_policy.policy_status', 1)
+ ->where('client_policy.open_date IS NOT NULL')
+ ->where('client_policy.close_date IS NOT NULL');
-//for this using in CRONE JOB
-public function getPolicyDetailsForEnrollment($client_id = null, $branch_id = null)
-{
- $builder = $this->table('client_policy')
- ->where('client_policy.is_active', 1)
- ->where('client_policy.policy_status', 1)
- ->where('client_policy.open_date IS NOT NULL')
- ->where('client_policy.close_date IS NOT NULL');
+ if ($client_id && $branch_id) {
+ $builder->where('client_policy.client_id', $client_id)
+ ->where('client_policy.client_branch_id', $branch_id);
+ }
- if ($client_id && $branch_id) {
- $builder->where('client_policy.client_id', $client_id)
- ->where('client_policy.client_branch_id', $branch_id);
+ return $builder->get()->getResultArray();
}
- return $builder->get()->getResultArray();
+
}
-
-}
-
diff --git a/app/Models/EmployeeModel.php b/app/Models/EmployeeModel.php
index 524eb18b..6f4af68b 100755
--- a/app/Models/EmployeeModel.php
+++ b/app/Models/EmployeeModel.php
@@ -222,7 +222,7 @@ class EmployeeModel extends Model
) AS family_stats
ORDER BY family_member_count DESC, max_age DESC
LIMIT 1;";
- $results = $this->db->query($query)->getResult();
+ $results = $this->db->query($query)->getResultArray();
return $results;
}
diff --git a/app/Models/EmployeePolicyModel.php b/app/Models/EmployeePolicyModel.php
index 960f37d0..f6ff81ed 100755
--- a/app/Models/EmployeePolicyModel.php
+++ b/app/Models/EmployeePolicyModel.php
@@ -81,6 +81,146 @@ class EmployeePolicyModel extends Model
}
// ----------------------------------------------------------------------------------------------------------
+ // public function getEmployeePolicy($client_id = 0, $policy_id = 0, $status = [], $branch_id = 0, $emp_code = "", $emp_name = "")
+ // {
+ // // dd($status);
+
+ // $result = $this->select([
+ // 'employee_polices.*',
+ // 'policy_type.policy_type as policy_name',
+ // 'im.short_name as insurer_short_name',
+ // 'ib.branch_name as insurer_branch_name',
+ // 'ib.branch_code as insurer_branch_code',
+ // 'tpam.name as tpa_name',
+ // 'tpam.short_name as tpa_short_name',
+ // 'tpab.branch_code as tpa_branch_code',
+ // 'cm.client_name',
+ // 'cm.short_name as client_short_name',
+ // // 'emp.id as employee_primary_id',
+ // 'emp.relationship',
+ // 'emp.relationship_code',
+ // 'emp.change_event',
+ // 'emp.emp_code',
+ // 'emp.name',
+ // 'emp.email_corporate',
+ // 'emp.dob',
+ // 'DATE_FORMAT(emp.dob, "%d/%m/%Y") AS formatted_dob',
+ // 'emp.gender',
+ // 'emp.emp_status',
+ // 'emp.is_active as emp_is_active',
+ // 'emp.mobile as mobile',
+ // 'emp.doj',
+ // 'emp.basic_pay',
+ // 'emp.band as grade',
+ // 'policy_type.policy_type',
+ // 'client_branch.branch_name as client_branch_name',
+ // 'client_branch.branch_code as client_branch_code',
+ // 'cp.policy_no',
+ // 'cp.policy_type_id',
+
+ // // Name audit trail
+ // '(SELECT old_value FROM auditing_history WHERE pk = emp.id AND field_name = "name" AND table_name = "employees" ORDER BY id ASC LIMIT 1) AS name_first_old',
+ // '(SELECT new_value FROM auditing_history WHERE pk = emp.id AND field_name = "name" AND table_name = "employees" ORDER BY id DESC LIMIT 1) AS name_last_new',
+
+ // // DOB audit trail
+ // '(SELECT old_value FROM auditing_history WHERE pk = emp.id AND field_name = "dob" AND table_name = "employees" ORDER BY id ASC LIMIT 1) AS dob_first_old',
+ // '(SELECT new_value FROM auditing_history WHERE pk = emp.id AND field_name = "dob" AND table_name = "employees" ORDER BY id DESC LIMIT 1) AS dob_last_new',
+
+ // // Gender audit trail
+ // '(SELECT old_value FROM auditing_history WHERE pk = emp.id AND field_name = "gender" AND table_name = "employees" ORDER BY id ASC LIMIT 1) AS gender_first_old',
+ // '(SELECT new_value FROM auditing_history WHERE pk = emp.id AND field_name = "gender" AND table_name = "employees" ORDER BY id DESC LIMIT 1) AS gender_last_new',
+
+ // '(CASE
+ // WHEN emp.relationship = "Self"
+ // THEN (SELECT COUNT(id) FROM employees WHERE emp_code = emp.emp_code AND is_active = 0 AND emp_status != "truncated")
+ // ELSE NULL
+ // END) AS removed_count',
+
+ // '(CASE
+ // WHEN emp.relationship != "Self" AND emp.created_at != (
+ // SELECT created_at
+ // FROM employees
+ // WHERE emp_code = emp.emp_code AND relationship = "Self" AND is_active = 1
+ // LIMIT 1
+ // )
+ // THEN "Newly Added"
+ // ELSE NULL
+ // END) AS newly_added',
+
+ // ])
+ // ->join('employees emp', 'employee_polices.employee_id = emp.id')
+ // ->join('client_policy cp', 'employee_polices.client_policy_id = cp.id') //cp - client policy
+ // ->join('policies pm', 'cp.policy_id = pm.id', 'left') //pm - policy master
+ // ->join('policy_type', 'policy_type.id = cp.policy_type_id')
+ // ->join('insurers im', 'cp.insurer_id = im.id') //im - insurer master
+ // ->join('insurer_branch ib', 'cp.insurer_branch_id = ib.id') //ib - insurer branch
+ // ->join('tpa tpam', 'cp.tpa_id = tpam.id', 'left') //tpam - tpa master
+ // ->join('tpa_branch tpab', 'cp.tpa_branch_id = tpab.id', 'left') //tpab - tpa branch
+ // ->join('clients cm', 'cp.client_id = cm.id') //cm - client master
+ // ->join('client_branch', 'emp.client_branch_id = client_branch.id') //cm - client master
+ // ->orderBy('emp.emp_code', 'ASC')
+ // ->orderBy('employee_polices.employee_id', 'ASC');
+
+
+ // // Conditionally add where clauses
+ // if ($client_id != 0 && !empty($client_id)) {
+ // $result->where('emp.client_id', $client_id);
+ // }
+ // if ($branch_id != 0 && !empty($branch_id)) {
+ // $result->where('emp.client_branch_id', $branch_id);
+ // }
+ // if ($policy_id != 0 && !empty($policy_id)) {
+ // $result->where('employee_polices.client_policy_id', $policy_id);
+ // }
+
+ // if (is_array($status) && count($status) > 0) {
+
+ // $result->where('employee_polices.status !=', 'expired');
+
+ // if (in_array("active", $status)) {
+
+ // $result->where('employee_polices.tpa_id IS NOT NULL');
+ // $result->where('employee_polices.uhid IS NOT NULL');
+ // $result->whereIn('employee_polices.status', $status);
+ // } elseif (in_array("pending", $status)) {
+
+ // $result->where('employee_polices.tpa_id IS NULL');
+ // $result->where('employee_polices.uhid IS NULL');
+ // $result->whereIn('employee_polices.status', array_merge($status, ['active']));
+ // } else {
+
+ // $result->whereIn('employee_polices.status', $status);
+ // }
+
+ // // if($status == 'active'){
+ // // $result->where('employee_polices.tpa_id IS NOT NULL');
+ // // $result->where('employee_polices.uhid IS NOT NULL');
+ // // }else if($status == 'pending'){
+ // // $status = 'active';
+ // // $result->where('employee_polices.status', $status);
+ // // }else{
+ // // $result->where('employee_polices.status', $status);
+ // // }
+ // }
+
+ // if (!empty($emp_code)) {
+ // $result->where('emp.emp_code', $emp_code);
+ // }
+ // if (!empty($emp_name)) {
+ // $result->like('emp.name', $emp_name);
+ // }
+
+ // // Always check these conditions
+ // $result->where('employee_polices.is_active', 1)
+ // ->where('emp.is_active', 1);
+
+ // $res = $result->findAll();
+
+ // // dd($this->db->getLastQuery());
+
+ // return $res;
+ // } // remarks do not remove
+
public function getEmployeePolicy($client_id = 0, $policy_id = 0, $status = [], $branch_id = 0, $emp_code = "", $emp_name = "")
{
// dd($status);
@@ -179,9 +319,11 @@ class EmployeePolicyModel extends Model
}
// Always check these conditions
- $result->where('employee_polices.is_active', 1)
- ->where('emp.is_active', 1);
-
+ $result
+ ->where('employee_polices.is_active', 1)
+ ->where('emp.is_active', 1)
+ ->where('employee_polices.status !=', 'inactive');
+
$res = $result->findAll();
// dd($this->db->getLastQuery());
@@ -274,7 +416,7 @@ class EmployeePolicyModel extends Model
employees.designation AS emp_designation,
employees.basic_pay AS emp_basic_pay,
- TIMESTAMPDIFF(YEAR, employees.dob, CURDATE()) AS emp_age,
+ TIMESTAMPDIFF(YEAR, employees.dob, employee_polices.date_coverage) AS emp_age,
employees.emp_type as emp_type,
@@ -452,20 +594,20 @@ class EmployeePolicyModel extends Model
}
- public function getSIEnhancementEmployeesDataForExportExcel($ref_data)
+ public function getSIEnhancementEmployeesDataForExportExcel($ref_data, $return_type = 0)
{
- $client_id = $ref_data['client_id'];
- $client_policy_id = $ref_data['client_policy_id'];
- $client_branch_id = $ref_data['client_branch_id'];
- $insurer_or_tpa = $ref_data['insurer_or_tpa'];
+ $client_id = $ref_data['client_id'];
+ $client_policy_id = $ref_data['client_policy_id'];
+ $client_branch_id = $ref_data['client_branch_id'];
+ $insurer_or_tpa = $ref_data['insurer_or_tpa'];
- $endorsement_condition = "{$insurer_or_tpa}" === 'tpa' ? "AND (a.endorsement_id IS NOT NULL OR a.endorsement_id != '')" : "AND (a.endorsement_id IS NULL OR a.endorsement_id = '')";
+ $endorsement_condition = "{$insurer_or_tpa}" === 'tpa' ? "AND (a.endorsement_id IS NOT NULL OR a.endorsement_id != '')" : "AND (a.endorsement_id IS NULL OR a.endorsement_id = '')";
- $query = $this->db->query("
- SELECT
- a.id as endorsement_primarykey,
+ $query = $this->db->query("
+ SELECT
+ a.id AS endorsement_primarykey,
a.group_key,
employee_polices.id AS primaryKey,
employees.name AS emp_name,
@@ -474,10 +616,8 @@ class EmployeePolicyModel extends Model
employees.gender AS emp_gender,
employees.relationship_code AS emp_relationship_code,
employees.relationship AS emp_relationship,
- employees.emp_type as emp_type,
- 'SI' as event_type_data,
-
-
+ employees.emp_type AS emp_type,
+ 'SI' AS event_type_data,
employees.doj AS emp_doj,
employees.mobile AS emp_mobile,
employees.email_corporate AS emp_email_c,
@@ -485,97 +625,59 @@ class EmployeePolicyModel extends Model
employees.band AS emp_grade,
employees.designation AS emp_designation,
employees.basic_pay AS emp_basic_pay,
-
employee_polices.uhid AS uhid,
employee_polices.pre_existing_alignments,
employee_polices.policy_end_date,
- employee_polices.basic_cover_si as old_basic_cover_si,
- employee_polices.rata_premimum as old_si_premium,
+ employee_polices.basic_cover_si AS old_basic_cover_si,
+ employee_polices.premium AS old_si_premium,
+ employee_polices.rata_premimum AS old_rata_premium,
employee_polices.age_band,
-
- batch_data.emp_policy_id,
- batch_data.bl AS batch_list_batch_code,
- batch_data.bf AS batch_files_batch_code,
-
- sidata.new_basic_cover_si,
+ sidata.new_basic_cover_si,
sidata.new_si_premium,
+ sidata.old_si_premium,
sidata.date_of_coverage,
-
DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1 AS no_of_days,
-
- sidata.new_si_premium - employee_polices.rata_premimum AS difference_premium,
-
- ROUND((sidata.new_si_premium - employee_polices.rata_premimum) * (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365, 2) AS pro_rata_premium,
-
- ROUND(((sidata.new_si_premium - employee_polices.rata_premimum) * (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365) * 0.18, 2) AS gst,
-
+ ROUND(sidata.new_si_premium - sidata.old_si_premium, 2) AS difference_premium,
ROUND(
- ((sidata.new_si_premium - employee_polices.rata_premimum) *
- (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365) +
+ (sidata.new_si_premium - sidata.old_si_premium) *
+ (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365,
+ 2
+ ) AS pro_rata_premium,
+ ROUND(
+ (
+ (sidata.new_si_premium - sidata.old_si_premium) *
+ (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365
+ ) * 0.18,
+ 2
+ ) AS gst,
+ ROUND(
+ (
+ (sidata.new_si_premium - sidata.old_si_premium) *
+ (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365
+ ) +
ROUND(
- ((sidata.new_si_premium - employee_polices.rata_premimum) *
- (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365) * 0.18, 2
- ), 2
+ (
+ (sidata.new_si_premium - sidata.old_si_premium) *
+ (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365
+ ) * 0.18,
+ 2
+ ),
+ 2
) AS total
-
- FROM
+ FROM
emp_endorsement a
- LEFT JOIN
- employees ON employees.emp_code = a.emp_code
- LEFT JOIN
- employee_polices ON employees.id = employee_polices.employee_id
+ LEFT JOIN employees ON employees.emp_code = a.emp_code
+ LEFT JOIN employee_polices ON employees.id = employee_polices.employee_id
LEFT JOIN (
- SELECT
- aa.emp_code,
- aa.new_value as 'new_basic_cover_si',
- bb.new_value as 'new_si_premium',
- cc.new_value as 'date_of_coverage'
- FROM (
- SELECT
- a1.emp_code,
- a1.field_name,
- a1.new_value
- FROM
- emp_endorsement as a1
- WHERE
- a1.field_name = 'basic_cover_si'
- ) aa
- LEFT JOIN (
- SELECT
- b1.emp_code,
- b1.field_name,
- b1.new_value
- FROM
- emp_endorsement as b1
- WHERE
- b1.field_name = 'premium'
- ) bb ON aa.emp_code = bb.emp_code
- LEFT JOIN (
- SELECT
- c1.emp_code,
- c1.field_name,
- c1.new_value
- FROM
- emp_endorsement as c1
- WHERE
- c1.field_name = 'si_enhancement_date'
- ) cc ON aa.emp_code = cc.emp_code
- ) as sidata ON a.emp_code = sidata.emp_code
- LEFT JOIN (
- SELECT DISTINCT
- batch_list.emp_policy_id,
- batch_list.batch_code AS bl,
- batch_files.batch_code AS bf
- FROM
- batch_files
- LEFT JOIN
- batch_list ON batch_files.batch_code = batch_list.batch_code
- WHERE
- batch_files.event_type = 'si_enhancement'
- AND batch_files.actions = 'export'
- AND batch_files.insurer_or_tpa = '{$insurer_or_tpa}'
- ) AS batch_data ON employee_polices.id = batch_data.emp_policy_id
-
+ SELECT
+ emp_code,
+ CAST(MAX(CASE WHEN field_name = 'basic_cover_si' THEN new_value END) AS UNSIGNED) AS new_basic_cover_si,
+ CAST(MAX(CASE WHEN field_name = 'premium' THEN new_value END) AS DECIMAL(10,2)) AS new_si_premium,
+ CAST(MAX(CASE WHEN field_name = 'premium' THEN old_value END) AS DECIMAL(10,2)) AS old_si_premium,
+ MAX(CASE WHEN field_name = 'si_enhancement_date' THEN new_value END) AS date_of_coverage
+ FROM emp_endorsement
+ GROUP BY emp_code
+ ) AS sidata ON a.emp_code = sidata.emp_code
WHERE employee_polices.client_policy_id = '{$client_policy_id}'
AND employees.client_branch_id = '{$client_branch_id}'
$endorsement_condition
@@ -588,13 +690,177 @@ class EmployeePolicyModel extends Model
group by group_key
");
- // Get the result set
- $results = $query->getResult();
- // dd($this->db->getLastQuery(), $results);
- return $results;
+ // Get the result set
+ $results = $query->getResult();
+ if ($return_type == 1) {
+ $results = $query->getResultArray();
+ } else {
+ $results = $query->getResult();
+ }
+
+ // dd($this->db->getLastQuery());
+ return $results;
}
+ // DO NOT DELETE this SI ENHANCEMENT QUERY FUNCTION
+
+ // public function getSIEnhancementEmployeesDataForExportExcel($ref_data, $return_type = 0)
+ // {
+
+ // $client_id = $ref_data['client_id'];
+ // $client_policy_id = $ref_data['client_policy_id'];
+ // $client_branch_id = $ref_data['client_branch_id'];
+ // $insurer_or_tpa = $ref_data['insurer_or_tpa'];
+
+ // $endorsement_condition = "{$insurer_or_tpa}" === 'tpa' ? "AND (a.endorsement_id IS NOT NULL OR a.endorsement_id != '')" : "AND (a.endorsement_id IS NULL OR a.endorsement_id = '')";
+
+
+ // $query = $this->db->query("
+ // SELECT
+ // a.id as endorsement_primarykey,
+ // a.group_key,
+ // employee_polices.id AS primaryKey,
+ // employees.name AS emp_name,
+ // employees.emp_code AS emp_code,
+ // employees.dob AS emp_dob,
+ // employees.gender AS emp_gender,
+ // employees.relationship_code AS emp_relationship_code,
+ // employees.relationship AS emp_relationship,
+ // employees.emp_type as emp_type,
+ // 'SI' as event_type_data,
+
+
+ // employees.doj AS emp_doj,
+ // employees.mobile AS emp_mobile,
+ // employees.email_corporate AS emp_email_c,
+ // employees.email_personal AS emp_email_p,
+ // employees.band AS emp_grade,
+ // employees.designation AS emp_designation,
+ // employees.basic_pay AS emp_basic_pay,
+
+ // employee_polices.uhid AS uhid,
+ // employee_polices.pre_existing_alignments,
+ // employee_polices.policy_end_date,
+ // employee_polices.basic_cover_si as old_basic_cover_si,
+ // employee_polices.premium as old_si_premium,
+ // employee_polices.rata_premimum as old_rata_premium,
+ // employee_polices.age_band,
+
+ // batch_data.emp_policy_id,
+ // batch_data.bl AS batch_list_batch_code,
+ // batch_data.bf AS batch_files_batch_code,
+
+ // sidata.new_basic_cover_si,
+ // sidata.new_si_premium,
+ // sidata.old_si_premium,
+ // sidata.date_of_coverage,
+
+ // DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1 AS no_of_days,
+
+ // ROUND(sidata.new_si_premium - sidata.old_si_premium, 2) AS difference_premium,
+
+ // ROUND((sidata.new_si_premium - sidata.old_si_premium) * (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365, 2) AS pro_rata_premium,
+
+ // ROUND(((sidata.new_si_premium - sidata.old_si_premium) * (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365) * 0.18, 2) AS gst,
+
+ // ROUND(
+ // ((sidata.new_si_premium - sidata.old_si_premium) *
+ // (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365) +
+ // ROUND(
+ // ((sidata.new_si_premium - sidata.old_si_premium) *
+ // (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365) * 0.18, 2
+ // ), 2
+ // ) AS total
+
+ // FROM
+ // emp_endorsement a
+ // LEFT JOIN
+ // employees ON employees.emp_code = a.emp_code
+ // LEFT JOIN
+ // employee_polices ON employees.id = employee_polices.employee_id
+ // LEFT JOIN (
+ // SELECT
+ // aa.emp_code,
+ // aa.new_value as 'new_basic_cover_si',
+ // bb.new_value as 'new_si_premium',
+ // bb.old_value as 'old_si_premium',
+ // cc.new_value as 'date_of_coverage'
+ // FROM (
+ // SELECT
+ // a1.emp_code,
+ // a1.field_name,
+ // a1.new_value,
+ // a1.old_value
+ // FROM
+ // emp_endorsement as a1
+ // WHERE
+ // a1.field_name = 'basic_cover_si'
+ // ) aa
+ // LEFT JOIN (
+ // SELECT
+ // b1.emp_code,
+ // b1.field_name,
+ // b1.new_value,
+ // b1.old_value
+ // FROM
+ // emp_endorsement as b1
+ // WHERE
+ // b1.field_name = 'premium'
+ // ) bb ON aa.emp_code = bb.emp_code
+ // LEFT JOIN (
+ // SELECT
+ // c1.emp_code,
+ // c1.field_name,
+ // c1.new_value,
+ // c1.old_value
+ // FROM
+ // emp_endorsement as c1
+ // WHERE
+ // c1.field_name = 'si_enhancement_date'
+ // ) cc ON aa.emp_code = cc.emp_code
+ // ) as sidata ON a.emp_code = sidata.emp_code
+ // LEFT JOIN (
+ // SELECT DISTINCT
+ // batch_list.emp_policy_id,
+ // batch_list.batch_code AS bl,
+ // batch_files.batch_code AS bf
+ // FROM
+ // batch_files
+ // LEFT JOIN
+ // batch_list ON batch_files.batch_code = batch_list.batch_code
+ // WHERE
+ // batch_files.event_type = 'si_enhancement'
+ // AND batch_files.actions = 'export'
+ // AND batch_files.insurer_or_tpa = '{$insurer_or_tpa}'
+ // ) AS batch_data ON employee_polices.id = batch_data.emp_policy_id
+
+ // WHERE employee_polices.client_policy_id = '{$client_policy_id}'
+ // AND employees.client_branch_id = '{$client_branch_id}'
+ // $endorsement_condition
+ // AND a.actions = 'si'
+ // AND a.status != 'truncated'
+ // AND employee_polices.is_active = 1
+ // AND employee_polices.status = 'active'
+ // AND employees.is_active = 1
+ // AND employees.emp_status = 'active'
+ // group by group_key
+ // ");
+
+ // // Get the result set
+ // $results = $query->getResult();
+
+ // if($return_type == 1){
+ // $results = $query->getResultArray();
+ // }else{
+ // $results = $query->getResult();
+ // }
+
+ // // dd($this->db->getLastQuery());
+ // return $results;
+
+ // }
+
// DO NOT DELETE this DELETION QUERY FUNCTION
// public function getDeletionEmployeeDataForExportExcel($ref_data, $return_type = 0)
@@ -795,10 +1061,10 @@ class EmployeePolicyModel extends Model
}
$status_condition = "{$insurer_or_tpa}" === 'tpa'
- ? "employee_polices.status = 'active' AND employees.emp_status = 'active'"
+ ? "employee_polices.status = 'inactive' AND employees.emp_status = 'active'"
: "employee_polices.status = 'active' AND employees.emp_status = 'active'";
- $endorsement_condition = "{$insurer_or_tpa}" === 'tpa' ? "AND (a.endorsement_id IS NULL OR a.endorsement_id = '')" : "AND (a.endorsement_id IS NULL OR a.endorsement_id = '')";
+ $endorsement_condition = "{$insurer_or_tpa}" === 'tpa' ? "AND (a.endorsement_id IS NOT NULL OR a.endorsement_id != '')" : "AND (a.endorsement_id IS NULL OR a.endorsement_id = '')";
$query = $this->db->query("
SELECT DISTINCT
@@ -823,7 +1089,8 @@ class EmployeePolicyModel extends Model
employee_polices.basic_cover_si,
employee_polices.uhid as uhid,
- employee_polices.rata_premimum as premium,
+ employee_polices.rata_premimum,
+ ROUND(employee_polices.premium,2) as premium,
employee_polices.claim_status,
employee_polices.age_band,
employee_polices.tpa_id,
@@ -849,22 +1116,22 @@ class EmployeePolicyModel extends Model
CASE
WHEN deletiondata.claimstatus = 0 OR deletiondata.claimstatus IS NULL THEN
- ROUND((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365, 2)
+ ROUND((employee_polices.premium * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365, 2)
ELSE
0
END AS pro_rata_premium,
CASE
WHEN deletiondata.claimstatus = 0 OR deletiondata.claimstatus IS NULL THEN
- ROUND(((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) * 0.18, 2)
+ ROUND(((employee_polices.premium * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) * 0.18, 2)
ELSE
0
END AS gst,
CASE
WHEN deletiondata.claimstatus = 0 OR deletiondata.claimstatus IS NULL THEN
- ROUND(((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) +
- (((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) * 0.18), 2)
+ ROUND(((employee_polices.premium * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) +
+ (((employee_polices.premium * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) * 0.18), 2)
ELSE
0
END AS total,
@@ -1386,73 +1653,120 @@ class EmployeePolicyModel extends Model
}
- public function bulkUpdateForEndorsement($endorsement_details)
+ // public function bulkUpdateForEndorsement($endorsement_details)
+ // {
+ // // dd($endorsement_details, '---');
+ // // Extract IDs, endorsement_ids, and statuses
+ // $ids = array_column($endorsement_details, 'group_key');
+ // $endorsement_ids = array_column($endorsement_details, 'endorsement_id');
+ // $statuses = array_column($endorsement_details, 'status');
+
+ // // Escape values for SQL
+ // $escapedIds = array_map([$this->db, 'escape'], $ids);
+ // $escapedEndorsementIds = array_map([$this->db, 'escape'], $endorsement_ids);
+ // $escapedStatuses = array_map([$this->db, 'escape'], $statuses);
+
+ // // Construct the CASE statements
+ // $caseEndorsementId = array_map(function ($id, $endorsement_id) {
+ // return "WHEN group_key = $id THEN $endorsement_id";
+ // }, $escapedIds, $escapedEndorsementIds);
+
+ // // $caseStatus = array_map(function ($id, $status) {
+ // // return "WHEN status = $id THEN $status";
+ // // }, $escapedIds, $escapedStatuses);
+
+ // // Convert cases to a string
+ // $caseEndorsementIdString = implode(' ', $caseEndorsementId);
+ // // $caseStatusString = implode(' ', $caseStatus);
+
+ // // Convert ids to a string
+ // $idsString = implode(', ', $escapedIds);
+
+ // // Construct the SQL query
+ // $sql = "
+ // UPDATE emp_endorsement
+ // SET
+ // endorsement_id = CASE {$caseEndorsementIdString} END,
+ // status = 'complete'
+ // WHERE group_key IN ({$idsString})
+ // ";
+
+
+ // // dd($sql);
+ // // Begin a transaction
+ // $this->db->transBegin();
+
+ // try {
+ // // Start the transaction
+ // $this->db->transBegin();
+
+ // // Execute the query
+ // $this->db->query($sql);
+
+ // // Check transaction status
+ // if ($this->db->transStatus() === false) {
+ // $error = $this->db->error(); // Get the last database error
+ // $this->db->transRollback();
+
+ // // Optionally log the error
+ // log_message('error', 'Bulk update failed. Error: ' . json_encode($error));
+
+ // throw new \Exception('Bulk update failed. Error: ' . $error['message']);
+ // }
+
+ // // Commit if everything is fine
+ // $this->db->transCommit();
+
+ // return $this->db->getLastQuery(); // Optional: return last executed query for debugging
+ // } catch (\Exception $e) {
+ // $this->db->transRollback();
+
+ // // Optionally log the exception
+ // log_message('error', 'Exception during bulk update: ' . $e->getMessage());
+
+ // // Re-throw with detailed context
+ // throw new \RuntimeException('Exception during bulk update: ' . $e->getMessage(), $e->getCode(), $e);
+ // }
+
+ // }
+
+ public function bulkUpdateForEndorsement(array $endorsement_details)
{
-
- // Extract IDs, endorsement_ids, and statuses
- $ids = array_column($endorsement_details, 'group_key');
- $endorsement_ids = array_column($endorsement_details, 'endorsement_id');
- $statuses = array_column($endorsement_details, 'status');
-
- // Escape values for SQL
- $escapedIds = array_map([$this->db, 'escape'], $ids);
- $escapedEndorsementIds = array_map([$this->db, 'escape'], $endorsement_ids);
- $escapedStatuses = array_map([$this->db, 'escape'], $statuses);
-
- // Construct the CASE statements
- $caseEndorsementId = array_map(function ($id, $endorsement_id) {
- return "WHEN group_key = $id THEN $endorsement_id";
- }, $escapedIds, $escapedEndorsementIds);
-
- // $caseStatus = array_map(function ($id, $status) {
- // return "WHEN status = $id THEN $status";
- // }, $escapedIds, $escapedStatuses);
-
- // Convert cases to a string
- $caseEndorsementIdString = implode(' ', $caseEndorsementId);
- // $caseStatusString = implode(' ', $caseStatus);
-
- // Convert ids to a string
- $idsString = implode(', ', $escapedIds);
-
- // Construct the SQL query
+ if (empty($endorsement_details)) {
+ throw new \InvalidArgumentException("No endorsement details provided.");
+ }
+
+ $caseParts = [];
+ $groupKeys = [];
+
+ foreach ($endorsement_details as $row) {
+ $groupKey = $this->db->escape($row['group_key']);
+ $endorsementId = $this->db->escape($row['endorsement_id']);
+ $caseParts[] = "WHEN group_key = {$groupKey} THEN {$endorsementId}";
+ $groupKeys[] = $groupKey;
+ }
+
$sql = "
UPDATE emp_endorsement
SET
- endorsement_id = CASE {$caseEndorsementIdString} END,
+ endorsement_id = CASE " . implode(' ', $caseParts) . " END,
status = 'complete'
- WHERE group_key IN ({$idsString})
+ WHERE group_key IN (" . implode(', ', $groupKeys) . ")
";
-
-
- // dd($sql);
- // Begin a transaction
- $this->db->transBegin();
-
- try {
- // Execute the query
- $this->db->query($sql);
-
- // Commit the transaction
- if ($this->db->transStatus() === FALSE) {
- // If something went wrong, rollback
- $this->db->transRollback();
- throw new \Exception('Bulk update failed.');
- } else {
- // Otherwise, commit
- $this->db->transCommit();
- }
- // $this->storeEndorsementNumber($file_id, $endorsement_id, $enrollment_file_id);
-
- return $this->db->getLastQuery();
- } catch (\Exception $e) {
- // Rollback the transaction on error
- $this->db->transRollback();
- throw $e;
+
+ $this->db->query($sql);
+
+ // Check if query was successful
+ if ($this->db->affectedRows() === 0) {
+ throw new \RuntimeException('No rows were updated.');
}
+
+ return true;
}
+
+
public function bulkUpdateForCorrection($emp_details){
foreach ($emp_details as $employee) {
diff --git a/app/Models/EndorsementModel.php b/app/Models/EndorsementModel.php
index 22bcec72..60b675cb 100644
--- a/app/Models/EndorsementModel.php
+++ b/app/Models/EndorsementModel.php
@@ -24,6 +24,7 @@ class EndorsementModel extends Model
'created_at',
'updated_by',
'updated_at',
+ 'file_id',
'is_active'
];
diff --git a/app/Models/LeadFilesModel.php b/app/Models/LeadFilesModel.php
new file mode 100644
index 00000000..37db8e16
--- /dev/null
+++ b/app/Models/LeadFilesModel.php
@@ -0,0 +1,55 @@
+join('kyc_entity_type', 'leads.entity_type_id = kyc_entity_type.id', 'left')
- ->join('user_profiles', 'leads.salse_person_id = user_profiles.id', 'left')
- ->join('policy_type', 'leads.policy_type_id = policy_type.id', 'left')
- ->where('leads.is_active', 1);
+ ->join('kyc_entity_type', 'leads.entity_type_id = kyc_entity_type.id', 'left')
+ ->join('user_profiles', 'leads.salse_person_id = user_profiles.id', 'left')
+ ->join('policy_type', 'leads.policy_type_id = policy_type.id', 'left')
+ ->where('leads.is_active', 1);
if (!empty($where)) {
$data->where($where);
@@ -162,12 +173,13 @@ class LeadsModel extends Model
public function getLeadForInsertClientList($type = null, $client_id = null)
{
$query = $this->db->table('leads')
- ->select('leads.*, user_profiles.first_name as user_name')
- ->join('user_profiles', 'leads.created_by = user_profiles.id')
- ->where('leads.is_active', 1)
- ->where('leads.status', 'won')
- ->where("leads.proposel_data IS NOT NULL AND leads.proposel_data <> ''")
- ->where("(leads.is_client_created = '' OR leads.is_client_created IS NULL)");
+ ->select('leads.*, user_profiles.first_name as user_name')
+ ->join('user_profiles', 'leads.created_by = user_profiles.id')
+ ->where('leads.is_active', 1)
+ ->where('leads.status', 'won')
+ ->where("leads.proposel_data IS NOT NULL AND leads.proposel_data <> ''")
+ ->where("(leads.is_client_created = '' OR leads.is_client_created IS NULL)")
+ ->where("(leads.is_policy_created = '' OR leads.is_policy_created IS NULL)");
@@ -177,11 +189,83 @@ class LeadsModel extends Model
if ($client_id) {
$query->where('leads.client_id', $client_id);
}
-
+
$result = $query->get()->getResultArray();
return $result;
-
+ }
+
+ public function getDashData()
+ {
+ $statuses = $this->db->table('leads')
+ ->select('status')
+ ->where("is_active", 1)
+ ->groupBy('status')
+ ->get()
+ ->getResultArray();
+
+ $selectParts = [];
+
+ foreach ($statuses as $status) {
+ $s = $status['status'];
+ $alias = strtolower(str_replace(' ', '_', $s));
+
+ // Count alias
+ $selectParts[] = "SUM(CASE WHEN status = '{$s}' THEN 1 ELSE 0 END) AS `{$alias}`";
+
+ // IDs alias
+ $selectParts[] = "GROUP_CONCAT(CASE WHEN status = '{$s}' THEN leads.id ELSE NULL END) AS `{$alias}_ids`";
+ }
+
+ $select = implode(", ", $selectParts);
+
+ // Start query builder
+ $builder = $this->db->table('leads');
+
+ $builder->select($select);
+
+ // Auditing subquery
+ $subquery = "(SELECT pk, MAX(created_at) AS last_claim_status_change
+ FROM auditing_history
+ WHERE table_name = 'leads' AND field_name = 'status'
+ GROUP BY pk)";
+
+ $builder->join("{$subquery} AS th", 'leads.id = th.pk', 'left');
+
+ // Date filtering for last status change
+ $dateLimit = 3;
+ $dateThreshold = date('Y-m-d H:i:s', strtotime("-{$dateLimit} days"));
+
+ $builder->groupStart()
+ ->where('th.last_claim_status_change <=', $dateThreshold)
+ ->orWhere('th.last_claim_status_change IS NULL')
+ ->groupEnd();
+
+ // Add only active
+ $builder->where("leads.is_active", 1);
+
+ $lead_data = $builder->get()->getResultArray();
+
+ // Fallback for empty results
+ if (empty($lead_data)) {
+ $lead_data[0] = ['total' => 0];
+ foreach ($statuses as $status) {
+ $alias = strtolower(str_replace(' ', '_', $status['status']));
+ $lead_data[0][$alias] = 0;
+ $lead_data[0]["{$alias}_ids"] = '';
+ }
+ }
+
+ // Calculate total
+ $total = 0;
+ foreach ($lead_data[0] as $key => $value) {
+ if (!str_ends_with($key, '_ids') && $key != "won") {
+ $total += (int) $value;
+ }
+ }
+ $lead_data[0]['total'] = $total;
+
+ // dd($lead_data[0]);
+ return $lead_data[0];
}
-
}
diff --git a/app/Models/OccupancyMasterModel.php b/app/Models/OccupancyMasterModel.php
new file mode 100644
index 00000000..2db89bfa
--- /dev/null
+++ b/app/Models/OccupancyMasterModel.php
@@ -0,0 +1,22 @@
+join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left')
->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left')
->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left')
- ->where('policy_transaction.is_active', 1);
-
+ ->where('policy_transaction.is_active', 1);
+
// Check if the start date and end date are provided
if ($start_date != 0 && $end_date != 0 && $date_type != 0) {
$startDate = date('Y-m-d 00:00:00', strtotime($start_date));
$endDate = date('Y-m-d 23:59:59', strtotime($end_date));
- $builder->where('policy_transaction.'.$date_type.'>=', $startDate)
- ->where('policy_transaction.'.$date_type.'<=', $endDate);
- }else{
+ $builder->where('policy_transaction.' . $date_type . '>=', $startDate)
+ ->where('policy_transaction.' . $date_type . '<=', $endDate);
+ } else {
// $fromDate = date('Y-m-d', strtotime('-30 days'));
// $toDate = date('Y-m-d 23:59:59');
-
+
// $builder->where('policy_transaction.created_at >=', $fromDate)
// ->where('policy_transaction.created_at <=', $toDate);
}
@@ -288,31 +289,30 @@ class PolicyTransactionModel extends Model
if ($client_id != 0) {
$builder->where('policy_transaction.client_id', $client_id);
}
-
+
if ($insurer_id != 0) {
$builder->where('policy_transaction.insurer_id', $insurer_id);
}
-
+
if ($policy_type_id != 0) {
$builder->where('client_policy.policy_type_id', $policy_type_id);
}
-
+
if ($issuer != 0) {
$builder->where('policy_transaction.issuer', $issuer);
}
- if($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0){
+ if ($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0) {
$fromDate = date('Y-m-d', strtotime('-30 days'));
$toDate = date('Y-m-d 23:59:59');
-
- $builder->where('policy_transaction.created_at >=', $fromDate)
- ->where('policy_transaction.created_at <=', $toDate);
+ $builder->where('policy_transaction.created_at >=', $fromDate)
+ ->where('policy_transaction.created_at <=', $toDate);
}
$builder->orderBy('policy_transaction.id', 'desc');
-
+
return $builder->get()->getResultArray();
}
@@ -445,7 +445,7 @@ class PolicyTransactionModel extends Model
// AND insurer_statements.is_active = 1
// AND insurer_statements.invoice_status IS NOT NULL
// $date_condition
-
+
// ),
// 2
// ) AS billed_amt,
@@ -510,7 +510,7 @@ class PolicyTransactionModel extends Model
// ->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left')
// ->where('policy_transaction.is_active', 1)
// ->where('pt_co_share_details.is_active', 1);
-
+
// // Check if the start date and end date are provided
// if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') {
@@ -546,7 +546,7 @@ class PolicyTransactionModel extends Model
// if ($client_id != 0) {
// $builder->where('policy_transaction.client_id', $client_id);
// }
-
+
// if ($insurer_id != 0) {
// $builder->where('policy_transaction.insurer_id', $insurer_id);
// }
@@ -554,7 +554,7 @@ class PolicyTransactionModel extends Model
// if ($client_branch_id != 0) {
// $builder->where('policy_transaction.client_branch_id', $client_branch_id);
// }
-
+
// if ($insurer_branch_id != 0) {
// $builder->where('policy_transaction.insurer_branch_id', $insurer_branch_id);
// }
@@ -564,11 +564,11 @@ class PolicyTransactionModel extends Model
// }
-
+
// if ($policy_type_id != 0) {
// $builder->where('client_policy.policy_type_id', $policy_type_id);
// }
-
+
// if ($issuer != 0) {
// $builder->where('policy_transaction.issuer', $issuer);
// }
@@ -577,7 +577,7 @@ class PolicyTransactionModel extends Model
// $fromDate = date('Y-m-d', strtotime('-30 days'));
// $toDate = date('Y-m-d 23:59:59');
-
+
// $builder->where('policy_transaction.created_at >=', $fromDate)
// ->where('policy_transaction.created_at <=', $toDate);
@@ -588,18 +588,18 @@ class PolicyTransactionModel extends Model
// $result = $builder->get()->getResultArray();
// // dd($this->db->getLastQuery());
-
+
// return $result;
// }
- 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)
- {
+ 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, $where = [])
+ {
$date_condition = '';
- if($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) {
+ if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) {
$date_condition = "
- AND insurer_statements.month >= '".$start_date ."'
- AND insurer_statements.month <= '".$end_date ."'
+ AND insurer_statements.month >= '" . $start_date . "'
+ AND insurer_statements.month <= '" . $end_date . "'
";
}
@@ -781,18 +781,33 @@ class PolicyTransactionModel extends Model
->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left')
->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left')
->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left')
- ->where('policy_transaction.is_active', 1)
+ ->where('policy_transaction.is_active', 1)
->where('pt_co_share_details.is_active', 1);
-
+
+ if (
+ (!in_array(get_role_id(), [1, 5])) &&
+ !(
+ in_array(MANAGEMENT_TEAM_ID, user_team()) ||
+ in_array(FINANCE_TEAM_ID, user_team()) ||
+ in_array(BUSINESS_TEAM_ID, user_team())
+ )
+ ) {
+ if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
+ $builder->where('policy_transaction.created_by', get_session_userid());
+ }
+ }
+ if (!empty($where)) {
+ log_message('info', 'Where condition: ' . json_encode($where));
+ $builder->where($where);
+ }
// Check if the start date and end date are provided
if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') {
$startDate = date('Y-m-d 00:00:00', strtotime($start_date));
$endDate = date('Y-m-d 23:59:59', strtotime($end_date));
- $builder->where('policy_transaction.'.$date_type.'>=', $startDate)
- ->where('policy_transaction.'.$date_type.'<=', $endDate);
-
+ $builder->where('policy_transaction.' . $date_type . '>=', $startDate)
+ ->where('policy_transaction.' . $date_type . '<=', $endDate);
}
// if($date_type == 'statement_month' && $start_date != 0 && $end_date != 0){
@@ -809,17 +824,17 @@ class PolicyTransactionModel extends Model
$endDate = date('Y-m-d', strtotime($end_date));
$builder->join('co_share_stmt_details', 'pt_co_share_details.id = co_share_stmt_details.co_share_id', 'left')
- ->join('insurer_statements', 'co_share_stmt_details.statement_id = insurer_statements.id','left')
- ->where('insurer_statements.is_active', 1)
- ->where('insurer_statements.month >=', $startDate)
- ->where('insurer_statements.month <=', $endDate)
- ->groupBy('co_share_stmt_details.co_share_id');
+ ->join('insurer_statements', 'co_share_stmt_details.statement_id = insurer_statements.id', 'left')
+ ->where('insurer_statements.is_active', 1)
+ ->where('insurer_statements.month >=', $startDate)
+ ->where('insurer_statements.month <=', $endDate)
+ ->groupBy('co_share_stmt_details.co_share_id');
}
if ($client_id != 0) {
$builder->where('policy_transaction.client_id', $client_id);
}
-
+
if ($insurer_id != 0) {
$builder->where('policy_transaction.insurer_id', $insurer_id);
}
@@ -827,7 +842,7 @@ class PolicyTransactionModel extends Model
if ($client_branch_id != 0) {
$builder->where('policy_transaction.client_branch_id', $client_branch_id);
}
-
+
if ($insurer_branch_id != 0) {
$builder->where('policy_transaction.insurer_branch_id', $insurer_branch_id);
}
@@ -837,23 +852,24 @@ class PolicyTransactionModel extends Model
}
-
+
if ($policy_type_id != 0) {
$builder->where('client_policy.policy_type_id', $policy_type_id);
}
-
+
if ($issuer != 0) {
$builder->where('policy_transaction.issuer', $issuer);
}
- if($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0){
+ if ($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0) {
- $fromDate = date('Y-m-d', strtotime('-30 days'));
+ $fromDate = date('Y-m-d', strtotime('-60 days'));
$toDate = date('Y-m-d 23:59:59');
-
- $builder->where('policy_transaction.created_at >=', $fromDate)
- ->where('policy_transaction.created_at <=', $toDate);
+ if (empty($where)) {
+ $builder->where('policy_transaction.created_at >=', $fromDate)
+ ->where('policy_transaction.created_at <=', $toDate);
+ }
}
$builder->orderBy('policy_transaction.id', 'desc');
@@ -861,10 +877,10 @@ class PolicyTransactionModel extends Model
$result = $builder->get()->getResultArray();
// dd($this->db->getLastQuery());
-
+
return $result;
}
-
+
// public function getInceptionTranctionListData($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0)
// {
// // dd($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status);
@@ -903,7 +919,7 @@ class PolicyTransactionModel extends Model
// // $fromDate = date('Y-m-d', strtotime('-30 days'));
// // $toDate = date('Y-m-d 23:59:59');
-
+
// // $builder->where('policy_transaction.created_at >=', $fromDate)
// // ->where('policy_transaction.created_at <=', $toDate);
// }
@@ -911,15 +927,15 @@ class PolicyTransactionModel extends Model
// if ($client_id != 0) {
// $builder->where('policy_transaction.client_id', $client_id);
// }
-
+
// if ($insurer_id != 0) {
// $builder->where('policy_transaction.insurer_id', $insurer_id);
// }
-
+
// if ($policy_type_id != 0) {
// $builder->where('client_policy.policy_type_id', $policy_type_id);
// }
-
+
// if ($issuer != 0) {
// $builder->where('policy_transaction.issuer', $issuer);
// }
@@ -931,12 +947,12 @@ class PolicyTransactionModel extends Model
// $fromDate = date('Y-m-d', strtotime('-30 days'));
// $toDate = date('Y-m-d 23:59:59');
-
+
// $builder->where('policy_transaction.created_at >=', $fromDate)
// ->where('policy_transaction.created_at <=', $toDate);
// }
-
+
// $builder->orderBy('policy_transaction.id', 'desc')->limit(10);
// $result = $builder->get()->getResultArray();
@@ -946,7 +962,7 @@ class PolicyTransactionModel extends Model
// return $result;
// }
- public function getInceptionTranctionListData($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0)
+ public function getInceptionTranctionListData($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0, $where = null)
{
$builder = $this->db->table('policy_transaction')
->select('
@@ -973,10 +989,23 @@ class PolicyTransactionModel extends Model
->where('policy_transaction.is_active', 1)
->where('policy_transaction.action_type', 'inception');
+ if (
+ (!in_array(get_role_id(), [1, 5])) &&
+ !(
+ in_array(MANAGEMENT_TEAM_ID, user_team()) ||
+ in_array(FINANCE_TEAM_ID, user_team()) ||
+ in_array(BUSINESS_TEAM_ID, user_team())
+ )
+ ) {
+ if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
+ $builder->where('policy_transaction.created_by', get_session_userid());
+ }
+ }
+
// Optimize Date Filtering
if (!empty($start_date) && !empty($end_date) && !empty($date_type)) {
$builder->where("policy_transaction.$date_type >=", date('Y-m-d 00:00:00', strtotime($start_date)))
- ->where("policy_transaction.$date_type <=", date('Y-m-d 23:59:59', strtotime($end_date)));
+ ->where("policy_transaction.$date_type <=", date('Y-m-d 23:59:59', strtotime($end_date)));
}
// Apply Filters Only When Necessary
@@ -997,12 +1026,16 @@ class PolicyTransactionModel extends Model
}
// Default to Last 30 Days if No Filters Are Applied
- if (empty($client_id) && empty($insurer_id) && empty($policy_type_id) && empty($date_type) && empty($issuer)) {
- $fromDate = date('Y-m-d', strtotime('-30 days'));
+ if (empty($client_id) && empty($insurer_id) && empty($policy_type_id) && empty($date_type) && empty($issuer) && empty($where)) {
+ $fromDate = date('Y-m-d', strtotime('-60 days'));
$toDate = date('Y-m-d 23:59:59');
$builder->where('policy_transaction.created_at >=', $fromDate)
- ->where('policy_transaction.created_at <=', $toDate);
+ ->where('policy_transaction.created_at <=', $toDate);
+ }
+
+ if (!empty($where)) {
+ $builder->whereIn('policy_transaction.id', $where);
}
// Optimize Query Execution
@@ -1011,7 +1044,7 @@ class PolicyTransactionModel extends Model
return $builder->get()->getResultArray();
}
-
+
public function getEndorsementTranctionListData($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0)
{
// dd($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status);
@@ -1028,25 +1061,38 @@ class PolicyTransactionModel extends Model
->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
->join('clients', 'policy_transaction.client_id = clients.id', 'left')
->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left')
- ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id','left')
+ ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left')
->where('policy_transaction.is_active', 1)
->where('policy_transaction.action_type !=', 'inception');
+ if (
+ (!in_array(get_role_id(), [1, 5])) &&
+ !(
+ in_array(MANAGEMENT_TEAM_ID, user_team()) ||
+ in_array(FINANCE_TEAM_ID, user_team()) ||
+ in_array(BUSINESS_TEAM_ID, user_team())
+ )
+ ) {
+ if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
+ $builder->where('policy_transaction.created_by', get_session_userid());
+ }
+ }
+
if ($start_date != 0 && $end_date != 0 && $date_type != 0) {
$startDate = date('Y-m-d 00:00:00', strtotime($start_date));
$endDate = date('Y-m-d 23:59:59', strtotime($end_date));
- $builder->where('policy_transaction.'.$date_type.'>=', $startDate)
- ->where('policy_transaction.'.$date_type.'<=', $endDate);
- }else{
+ $builder->where('policy_transaction.' . $date_type . '>=', $startDate)
+ ->where('policy_transaction.' . $date_type . '<=', $endDate);
+ } else {
// $fromDate = date('Y-m-d', strtotime('-30 days'));
// $toDate = date('Y-m-d 23:59:59');
-
+
// $builder->where('policy_transaction.created_at >=', $fromDate)
// ->where('policy_transaction.created_at <=', $toDate);
}
@@ -1054,15 +1100,15 @@ class PolicyTransactionModel extends Model
if ($client_id != 0) {
$builder->where('policy_transaction.client_id', $client_id);
}
-
+
if ($insurer_id != 0) {
$builder->where('policy_transaction.insurer_id', $insurer_id);
}
-
+
if ($policy_type_id != 0) {
$builder->where('client_policy.policy_type_id', $policy_type_id);
}
-
+
if ($issuer != 0) {
$builder->where('policy_transaction.issuer', $issuer);
}
@@ -1070,16 +1116,15 @@ class PolicyTransactionModel extends Model
$builder->where('policy_transaction.status', $status);
}
- if($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0){
+ if ($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0) {
$fromDate = date('Y-m-d', strtotime('-30 days'));
$toDate = date('Y-m-d 23:59:59');
-
- $builder->where('policy_transaction.created_at >=', $fromDate)
- ->where('policy_transaction.created_at <=', $toDate);
+ $builder->where('policy_transaction.created_at >=', $fromDate)
+ ->where('policy_transaction.created_at <=', $toDate);
}
-
+
$builder->orderBy('policy_transaction.id', 'desc');
return $builder->get()->getResultArray();
@@ -1195,14 +1240,14 @@ class PolicyTransactionModel extends Model
// ->having('premium_variance_amt !=',0);
// ->group_start()
- ->having('variance_amt IS NOT NULL')
- ->orHaving('variance_amt !=', 0)
- ->having('premium_variance_amt IS NOT NULL')
- ->orHaving('premium_variance_amt !=', 0);
- // ->group_end();
- // ->where('pt_co_share_details.actual_bp_brokerage_amt IS NOT NULL AND pt_co_share_details.actual_bp_brokerage_amt != 0');
- // ->where('pt_co_share_details.variance IS NOT NULL')
- // ->where('pt_co_share_details.variance !=', 0);
+ ->having('variance_amt IS NOT NULL')
+ ->orHaving('variance_amt !=', 0)
+ ->having('premium_variance_amt IS NOT NULL')
+ ->orHaving('premium_variance_amt !=', 0);
+ // ->group_end();
+ // ->where('pt_co_share_details.actual_bp_brokerage_amt IS NOT NULL AND pt_co_share_details.actual_bp_brokerage_amt != 0');
+ // ->where('pt_co_share_details.variance IS NOT NULL')
+ // ->where('pt_co_share_details.variance !=', 0);
if ($start_date != 0 && $end_date != 0 && $date_type != 0) {
@@ -1239,7 +1284,7 @@ class PolicyTransactionModel extends Model
if ($client_branch_id != 0) {
$builder->where('policy_transaction.client_branch_id', $client_branch_id);
}
-
+
if ($insurer_branch_id != 0) {
$builder->where('policy_transaction.insurer_branch_id', $insurer_branch_id);
}
@@ -1256,6 +1301,7 @@ class PolicyTransactionModel extends Model
public function getBusinessReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0)
{
+ $dateThreshold = date('Y-m-d H:i:s', strtotime("- 3 days"));
$builder = $this->db->table('policy_transaction')
->select([
'policy_transaction.id AS policy_trns_id',
@@ -1279,9 +1325,21 @@ class PolicyTransactionModel extends Model
->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
+ ->join(
+ '(SELECT policy_tran_id, MAX(created_at) AS last_policy_status_change,is_active
+ FROM policy_transaction_status
+ WHERE is_active = 1
+ GROUP BY policy_tran_id) th',
+ 'policy_transaction.id = th.policy_tran_id'
+
+ )
+ ->where("th.last_policy_status_change <= '{$dateThreshold}'", null, false)
->where('policy_transaction.is_active', 1)
+ ->where("policy_transaction.status is not null", null, false)
+ ->whereNotIn("policy_transaction.status", ['completed'])
// ->where('policy_transaction.status', 'completed')
- ->where('pt_co_share_details.bp_amt IS NULL OR pt_co_share_details.bp_amt = 0');
+ ->where('(pt_co_share_details.bp_amt IS NULL OR pt_co_share_details.bp_amt = 0)', null, false);
+
if ($start_date != 0 && $end_date != 0 && $date_type != 0) {
@@ -1320,12 +1378,21 @@ class PolicyTransactionModel extends Model
}
$builder->orderBy('policy_transaction.id', 'desc');
+ // echo $builder->getCompiledSelect();
+ // exit;
- return $builder->get()->getResultArray();
+ $returnData = $builder->get()->getResultArray();
+
+
+
+ // dd($returnData);
+ return $returnData;
}
public function getFinanceReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0)
{
+ $dateThreshold = date('Y-m-d H:i:s', strtotime("- 3 days"));
+
$builder = $this->db->table('policy_transaction')
->select("
policy_transaction.id,
@@ -1348,12 +1415,22 @@ class PolicyTransactionModel extends Model
->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
+ ->join(
+ '(SELECT policy_tran_id, MAX(created_at) AS last_policy_status_change,is_active
+ FROM policy_transaction_status
+ WHERE is_active = 1
+ GROUP BY policy_tran_id) th',
+ 'policy_transaction.id = th.policy_tran_id'
+
+ )
+ ->where("th.last_policy_status_change <= '{$dateThreshold}'", null, false)
->where('policy_transaction.is_active', 1)
// ->where('policy_transaction.status', 'completed')
->where('COALESCE(pt_co_share_details.agreed_bp_per, 0) + COALESCE(pt_co_share_details.agreed_tp_per, 0) + COALESCE(pt_co_share_details.agreed_tep_per, 0) = 0')
->where('COALESCE(pt_co_share_details.actual_bp_amt, 0) + COALESCE(pt_co_share_details.actual_tp_amt, 0) + COALESCE(pt_co_share_details.actual_tep_amt, 0) = 0')
- ->where('COALESCE(pt_co_share_details.actual_bp_brokerage_amt, 0) + COALESCE(pt_co_share_details.actual_tp_brokerage_amt, 0) + COALESCE(pt_co_share_details.actual_tep_brokerage_amt, 0) = 0');
-
+ ->where('COALESCE(pt_co_share_details.actual_bp_brokerage_amt, 0) + COALESCE(pt_co_share_details.actual_tp_brokerage_amt, 0) + COALESCE(pt_co_share_details.actual_tep_brokerage_amt, 0) = 0')
+ ->where("policy_transaction.status is not null", null, false)
+ ->whereNotIn("policy_transaction.status", ['completed']);
if ($start_date != 0 && $end_date != 0 && $date_type != 0) {
@@ -1449,55 +1526,55 @@ class PolicyTransactionModel extends Model
->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
->where('policy_transaction.is_active', 1);
-
+
// Date range filtering
if ($start_date != 0 && $end_date != 0 && $date_type != 0) {
$startDate = date('Y-m-d 00:00:00', strtotime($start_date));
$endDate = date('Y-m-d 23:59:59', strtotime($end_date));
-
+
$builder->where('policy_transaction.' . $date_type . '>=', $startDate)
->where('policy_transaction.' . $date_type . '<=', $endDate);
} else {
$fromDate = date('Y-m-d', strtotime('-30 days'));
$toDate = date('Y-m-d 23:59:59');
-
+
$builder->where('policy_transaction.created_at >=', $fromDate)
->where('policy_transaction.created_at <=', $toDate);
}
-
+
// Additional filters
if ($client_id != 0) {
$builder->where('policy_transaction.client_id', $client_id);
}
-
+
if ($insurer_id != 0) {
$builder->where('policy_transaction.insurer_id', $insurer_id);
}
-
+
if ($policy_type_id != 0) {
$builder->where('client_policy.policy_type_id', $policy_type_id);
}
-
+
if ($issuer != 0) {
$builder->where('policy_transaction.issuer', $issuer);
}
-
+
if ($status != 0) {
$builder->where('policy_transaction.status', $status);
}
-
+
// Filter where outstanding_amount is not null
$builder->having('outstanding_amount IS NOT NULL');
-
+
$builder->orderBy('policy_transaction.id', 'desc');
-
+
return $builder->get()->getResultArray();
}
- public function getOutstandingReportList($start_date = 0, $end_date = 0, $insurer_id = 0,$insurer_branch_id = 0)
+ public function getOutstandingReportList($start_date = 0, $end_date = 0, $insurer_id = 0, $insurer_branch_id = 0)
{
$builder = $this->db->table('insurer_statements s')
- ->select('
+ ->select('
s.id,
s.insurer_id,
s.branch_id,
@@ -1513,32 +1590,32 @@ class PolicyTransactionModel extends Model
COALESCE(SUM(p.inv_amt) + SUM(p.tds) + SUM(p.gst), 0) AS total_paid,
(s.invoice_amount - COALESCE(SUM(p.inv_amt) + SUM(p.tds) + SUM(p.gst), 0)) AS outstanding_amount
')
- ->join('inv_payment_details p', 's.id = p.statement_id', 'left')
- ->join('insurers ins', 's.insurer_id = ins.id')
- ->join('insurer_branch ib', 's.branch_id = ib.id')
- ->where('s.is_active', 1)
- ->where('p.is_active', 1)
- ->groupBy('s.id, s.invoice_no, s.invoice_date, s.invoice_amount')
- ->having('outstanding_amount >', 0);
- // ->get();
+ ->join('inv_payment_details p', 's.id = p.statement_id', 'left')
+ ->join('insurers ins', 's.insurer_id = ins.id')
+ ->join('insurer_branch ib', 's.branch_id = ib.id')
+ ->where('s.is_active', 1)
+ ->where('p.is_active', 1)
+ ->groupBy('s.id, s.invoice_no, s.invoice_date, s.invoice_amount')
+ ->having('outstanding_amount >', 0);
+ // ->get();
+
-
// Date range filtering
if ($start_date != 0 && $end_date != 0) {
-
+
$builder->where('s.month >=', $start_date)
->where('s.month <=', $end_date);
- }
-
+ }
+
if ($insurer_id != 0) {
$builder->where('s.insurer_id', $insurer_id);
}
- if ($insurer_branch_id != 0) {
+ if ($insurer_branch_id != 0) {
$builder->where('s.branch_id', $insurer_branch_id);
}
$builder->orderBy('s.id', 'desc');
-
+
return $builder->get()->getResultArray();
}
@@ -1548,12 +1625,12 @@ class PolicyTransactionModel extends Model
{
$fromDate = date('Y-m-d', strtotime('-60 days'));
$toDate = date('Y-m-d 23:59:59');
-
+
if (!empty($start_date) && !empty($end_date)) {
$fromDate = change_date_format($start_date);
$toDate = change_date_format($end_date);
}
-
+
$query = $this->db->table('policy_transaction pt')
->select('
pt.*,
@@ -1578,7 +1655,7 @@ class PolicyTransactionModel extends Model
->where('pt.is_active', 1)
->where('pt_co.is_active', 1)
->where('pt.action_type', "inception");
-
+
// Apply filters if parameters are provided
if (!empty($client_type)) {
$query->where('c.client_type', $client_type);
@@ -1589,7 +1666,7 @@ class PolicyTransactionModel extends Model
if (!empty($issuer)) { // Corrected condition to check $issuer
$query->where('pt.issuer', $issuer);
}
-
+
$query->groupBy('pt.id');
$query->orderBy('pt.id', 'DESC');
// Fetch and return results
@@ -1597,6 +1674,47 @@ class PolicyTransactionModel extends Model
// print($this->db->getLastQuery()); die;
return $results;
}
-
-
+
+ public function getBDSRenewalData()
+ {
+ // Increase GROUP_CONCAT limit
+ $this->db->query("SET SESSION group_concat_max_len = 1000000;");
+
+ $builder = $this->db->table('policy_transaction pt');
+
+ $builder->select([
+ 'SUM(CASE WHEN pt.policy_end_date < CURDATE() THEN 1 ELSE 0 END) AS Expired',
+ 'SUM(CASE WHEN pt.policy_end_date BETWEEN CURDATE() AND (CURDATE() + INTERVAL 1 MONTH) THEN 1 ELSE 0 END) AS `Renewal Pending`',
+ 'GROUP_CONCAT(CASE WHEN pt.policy_end_date < CURDATE() THEN pt.id ELSE NULL END) AS Expired_ids',
+ 'GROUP_CONCAT(CASE WHEN pt.policy_end_date BETWEEN CURDATE() AND (CURDATE() + INTERVAL 1 MONTH) THEN pt.id ELSE NULL END) AS Renewal_Pending_ids'
+ ]);
+ $builder->where("pt.policy_end_date IS NOT NULL", null, false);
+ $builder->where('pt.is_active', 1);
+
+ // Self join to check if a policy has been renewed
+ $builder->join('policy_transaction renewed', 'renewed.source_client_policy_id = pt.client_policy_id and renewed.client_id = pt.client_id and renewed.client_branch_id = pt.client_branch_id', 'left');
+
+ // Filter for expired or expiring policies
+ $builder->where("(pt.policy_end_date < CURDATE() OR pt.policy_end_date BETWEEN CURDATE() AND (CURDATE() + INTERVAL 1 MONTH))", null, false);
+
+ $builder->where('renewed.id IS NULL', null, false);
+ $query = $builder->get();
+ $result = $query->getResultArray();
+
+ $total = 0;
+ foreach ($result[0] as $key => $value) {
+ if ($key !== 'Expired_ids' && $key !== 'Renewal_Pending_ids') {
+ $total += $value;
+ }
+ }
+
+ // Ensure ID fields are arrays (not null)
+ $result[0]['Expired_ids'] = $result[0]['Expired_ids'] ? $result[0]['Expired_ids'] : [];
+ $result[0]['Renewal Pending_ids'] = $result[0]['Renewal_Pending_ids'] ? $result[0]['Renewal_Pending_ids'] : [];
+
+ // Add total count
+ $result[0]['total'] = $total;
+
+ return $result[0];
+ }
}
diff --git a/app/Models/RFQModel.php b/app/Models/RFQModel.php
index 2e51f2aa..4ffbf9d4 100644
--- a/app/Models/RFQModel.php
+++ b/app/Models/RFQModel.php
@@ -17,6 +17,7 @@ class RFQModel extends Model
'type',
'lead_id',
'json',
+ "registration_json",
'created_at',
'created_by',
'updated_at',
@@ -67,6 +68,7 @@ class RFQModel extends Model
tpa_branch.branch_name as tpa_branch_name,
policy_type.policy_type,
rfq.json,
+ rfq.registration_json
')
->join('leads', 'rfq.lead_id = leads.id')
->join('policy_type', 'leads.policy_type_id = policy_type.id')
diff --git a/app/Models/TicketHistoryModel.php b/app/Models/TicketHistoryModel.php
index 6d7eb0f5..92041c8c 100644
--- a/app/Models/TicketHistoryModel.php
+++ b/app/Models/TicketHistoryModel.php
@@ -12,7 +12,7 @@ class TicketHistoryModel extends Model
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $protectFields = true;
- protected $allowedFields = ['id','field_name','display_name','old_value',
+ protected $allowedFields = ['id', "ticket_id", 'field_name','display_name','old_value',
'new_value','created_by','created_at','updated_by','updated_at','is_active'];
// Callbacks
diff --git a/app/Models/TicketMasterModel.php b/app/Models/TicketMasterModel.php
index f75cf2a6..b85dad62 100644
--- a/app/Models/TicketMasterModel.php
+++ b/app/Models/TicketMasterModel.php
@@ -15,6 +15,7 @@ class TicketMasterModel extends Model
protected $allowedFields = [
'id',
'ticket_type_id',
+ 'feedback_json',
'claim_status_id',
'acm_id',
'insurer_id',
@@ -73,11 +74,13 @@ class TicketMasterModel extends Model
'head_rejection_reason',
'pay_initiate_date',
'emp_personal_mail',
- 'client_policy_id'
-
- ];
-
-
+ 'client_policy_id',
+
+ 'approved_description'
+
+ ];
+
+
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = ["checkAndADDCreatedByValue"];
@@ -92,7 +95,7 @@ class TicketMasterModel extends Model
protected function checkAndADDCreatedByValue(array $data)
{
// Check if 'updated_by' value is null or empty
- if (empty($data['data']['created_by'])) {
+ if (empty($data['data']['created_by'])) {
// Set 'updated_by' value to the current session user ID
$data['data']['created_by'] = get_session_userid();
}
@@ -103,7 +106,7 @@ class TicketMasterModel extends Model
protected function checkAndUpdateUpdatedByValue(array $data)
{
// Check if 'updated_by' value is null or empty
- if (empty($data['data']['updated_by'])) {
+ if (empty($data['data']['updated_by'])) {
// Set 'updated_by' value to the current session user ID
$data['data']['updated_by'] = get_session_userid();
}
@@ -129,21 +132,21 @@ class TicketMasterModel extends Model
public function getTemplateDataByTicketID($ticket_id)
{
$template_data = $this
- ->select("ticket_mail_template.*, CASE
+ ->select("ticket_mail_template.*, CASE
WHEN employees.email_corporate IS NULL OR employees.email_corporate = ''
THEN ticket_master.emp_mail
ELSE employees.email_corporate
END as emp_mail, ,ticket_master.claim_status_id")
- ->join('ticket_claim_status', 'ticket_master.claim_status_id = ticket_claim_status.id and ticket_claim_status.is_active = 1')
- ->join('ticket_mail_template', '
+ ->join('ticket_claim_status', 'ticket_master.claim_status_id = ticket_claim_status.id and ticket_claim_status.is_active = 1')
+ ->join('ticket_mail_template', '
ticket_claim_status.trigger_type = ticket_mail_template.trigger_type
and ticket_claim_status.ticket_type = ticket_mail_template.ticket_type
and ticket_mail_template.is_active = 1')
- ->join('employees','employees.id = ticket_master.emp_id','left')
- ->where('ticket_master.id', $ticket_id)
- ->where('ticket_master.is_active', 1)
- ->where('ticket_claim_status.is_active', 1)
- ->first();
+ ->join('employees', 'employees.id = ticket_master.emp_id', 'left')
+ ->where('ticket_master.id', $ticket_id)
+ ->where('ticket_master.is_active', 1)
+ ->where('ticket_claim_status.is_active', 1)
+ ->first();
return $template_data;
}
@@ -172,16 +175,16 @@ class TicketMasterModel extends Model
->join('clients', 'ticket_master.client_id = clients.id', 'left')
->join('insurers', 'ticket_master.insurer_id = insurers.id', 'left')
->join('tpa', 'ticket_master.tpa_id = tpa.id', 'left')
- ->join('ticket_notes', 'ticket_master.id = ticket_notes.ticket_id and ticket_notes.is_active = 1 and ticket_notes.is_auto_query = 1','left')
+ ->join('ticket_notes', 'ticket_master.id = ticket_notes.ticket_id and ticket_notes.is_active = 1 and ticket_notes.is_auto_query = 1', 'left')
->join('user_profiles', 'ticket_master.acm_id = user_profiles.id', 'left')
- ->join('employees','employees.id = ticket_master.emp_id','left')
+ ->join('employees', 'employees.id = ticket_master.emp_id', 'left')
->where('ticket_master.id', $ticket_id)
->where('ticket_master.is_active', 1)
->first();
return $ticket_data;
}
-
+
//get TAT report BAND wise Data
// public function getTATReport($ticket_type = null, $start_date = null, $end_date = null)
// {
@@ -209,7 +212,7 @@ class TicketMasterModel extends Model
// ";
// $statusResult = $this->db->query($statusQuery)->getResultArray();
// // dd($statusResult);
-
+
// // Initialize dynamic query parts
// $dynamicSelect = '';
@@ -247,12 +250,12 @@ class TicketMasterModel extends Model
// 0
// ) AS `$columnName`, ";
// }
-
+
// // Remove the trailing comma from the SELECT part
// $dynamicSelect = rtrim($dynamicSelect, ', ');
// // dd($dynamicSelect);
-
+
// // Construct the full SQL query
// $sql = "
// SELECT
@@ -316,7 +319,7 @@ class TicketMasterModel extends Model
// ORDER BY
// FIELD(tc.TAT_Category, 'Above 20 Days', '13-20 Days', '7-12 Days', '0-6 Days');
// ";
-
+
// // Execute the query and return the result
// $data = $this->db->query($sql)->getResultArray();
// // print_rr($this->db->getLastQuery(), $data); die;
@@ -328,167 +331,249 @@ class TicketMasterModel extends Model
// // $tableData['headers'] = $headers;
// // $tableData['body'] = $data;
// // }
-
+
// return $data;
// }
+ // public function getTATReport($ticket_type = null, $start_date = null, $end_date = null)
+ // {
+ // //set default last 3 months data date
+ // $fromDate = date('Y-m-d', strtotime('-90 days'));
+ // $toDate = date('Y-m-d 23:59:59');
+
+ // if (!empty($start_date) && !empty($end_date)) {
+ // $fromDate = change_date_format($start_date);
+ // $toDate = change_date_format($end_date);
+ // }
+ // $ticket_type_data_1 = "";
+ // $ticket_type_data_2 = "";
+ // if (!empty($ticket_type)) {
+ // $ticket_type_data_1 = "AND ticket_type = $ticket_type";
+ // $ticket_type_data_2 = "WHERE tm.ticket_type_id = $ticket_type";
+ // }
+
+ // // Fetch claim statuses from the `ticket_claim_status` table
+ // $statusQuery = " SELECT
+ // id, claim_status, ticket_type
+ // FROM ticket_claim_status
+ // Where is_active = 1
+ // $ticket_type_data_1
+ // ";
+ // $statusResult = $this->db->query($statusQuery)->getResultArray();
+ // // dd($statusResult);
+
+ // // Initialize dynamic query parts
+ // $dynamicSelect = '';
+
+ // // Loop through each claim status and generate the COALESCE and CASE statements for the SELECT
+ // foreach ($statusResult as $status) {
+
+ // $columnName = $status['claim_status']; // Default column name
+
+ // if (empty($ticket_type)) {
+ // // Append the insurance type prefix based on `ticket_type`
+ // switch ($status['ticket_type']) {
+ // case 1:
+ // $columnName = "GMC - {$status['claim_status']}";
+ // break;
+ // case 2:
+ // $columnName = "GPA - {$status['claim_status']}";
+ // break;
+ // case 3:
+ // $columnName = "EDLI - {$status['claim_status']}";
+ // break;
+ // case 4:
+ // $columnName = "GTLI - {$status['claim_status']}";
+ // break;
+ // }
+ // }
+
+ // $dynamicSelect .= "
+ // COALESCE(
+ // SUM(
+ // CASE
+ // WHEN subquery.status_id = {$status['id']} THEN 1
+ // ELSE 0
+ // END
+ // ),
+ // 0
+ // ) AS `$columnName`, ";
+ // }
+
+ // // Remove the trailing comma from the SELECT part
+ // $dynamicSelect = rtrim($dynamicSelect, ', ');
+ // // dd($dynamicSelect);
+
+
+ // // Construct the full SQL query
+ // $sql = "
+ // SELECT
+ // tc.TAT_Category,
+ // $dynamicSelect
+ // FROM
+ // (
+ // SELECT 'Above 20 Days' AS TAT_Category
+ // UNION ALL
+ // SELECT '13-20 Days'
+ // UNION ALL
+ // SELECT '7-12 Days'
+ // UNION ALL
+ // SELECT '0-6 Days'
+ // ) AS tc
+ // LEFT JOIN (
+ // SELECT
+ // tm.id AS ticket_id,
+ // latest_status.claim_status_id AS status_id,
+ // CASE
+ // WHEN DATEDIFF(CURDATE(), COALESCE(latest_status.change_date, tm.created_at)) BETWEEN 0 AND 6 THEN '0-6 Days'
+ // WHEN DATEDIFF(CURDATE(), COALESCE(latest_status.change_date, tm.created_at)) BETWEEN 7 AND 12 THEN '7-12 Days'
+ // WHEN DATEDIFF(CURDATE(), COALESCE(latest_status.change_date, tm.created_at)) BETWEEN 13 AND 20 THEN '13-20 Days'
+ // ELSE 'Above 20 Days'
+ // END AS TAT_Category
+ // FROM
+ // ticket_master tm
+ // LEFT JOIN (
+ // SELECT
+ // th.ticket_id,
+ // th.new_value AS claim_status_id,
+ // MAX(th.created_at) AS change_date
+ // FROM
+ // ticket_history th
+ // WHERE
+ // th.field_name = 'claim_status_id'
+ // AND th.is_active = 1
+ // GROUP BY
+ // th.ticket_id, th.new_value
+ // ) AS latest_status ON latest_status.ticket_id = tm.id
+ // WHERE tm.is_active = 1
+ // AND tm.created_at >= '$fromDate'
+ // AND tm.created_at <= '$toDate'
+ // " . (!empty($ticket_type) ? " AND tm.ticket_type_id = $ticket_type" : "") . "
+ // GROUP BY tm.id, latest_status.claim_status_id, latest_status.change_date, tm.created_at
+ // ) AS subquery ON tc.TAT_Category = subquery.TAT_Category
+ // GROUP BY
+ // tc.TAT_Category
+ // ORDER BY
+ // FIELD(
+ // tc.TAT_Category,
+ // 'Above 20 Days',
+ // '13-20 Days',
+ // '7-12 Days',
+ // '0-6 Days'
+ // );
+ // ";
+
+ // // Execute the query and return the result
+ // $data = $this->db->query($sql)->getResultArray();
+ // // dd($data);
+ // print_rr($data);die();
+ // // print_rr($this->db->getLastQuery()->getQuery()); die;
+
+ // return $data;
+ // }
public function getTATReport($ticket_type = null, $start_date = null, $end_date = null)
- {
- //set default last 3 months data date
+ {
+ // Set default date range (last 90 days)
$fromDate = date('Y-m-d', strtotime('-90 days'));
$toDate = date('Y-m-d 23:59:59');
-
+
if (!empty($start_date) && !empty($end_date)) {
$fromDate = change_date_format($start_date);
$toDate = change_date_format($end_date);
}
- $ticket_type_data_1 = "";
- $ticket_type_data_2 = "";
- if(!empty($ticket_type)){
- $ticket_type_data_1 = "AND ticket_type = $ticket_type";
- $ticket_type_data_2 = "WHERE tm.ticket_type_id = $ticket_type";
- }
-
- // Fetch claim statuses from the `ticket_claim_status` table
- $statusQuery = " SELECT
- id, claim_status, ticket_type
- FROM ticket_claim_status
- Where is_active = 1
- $ticket_type_data_1
- ";
- $statusResult = $this->db->query($statusQuery)->getResultArray();
- // dd($statusResult);
- // Initialize dynamic query parts
- $dynamicSelect = '';
-
- // Loop through each claim status and generate the COALESCE and CASE statements for the SELECT
- foreach ($statusResult as $status) {
-
- $columnName = $status['claim_status']; // Default column name
-
- if (empty($ticket_type)) {
- // Append the insurance type prefix based on `ticket_type`
- switch ($status['ticket_type']) {
- case 1:
- $columnName = "GMC - {$status['claim_status']}";
- break;
- case 2:
- $columnName = "GPA - {$status['claim_status']}";
- break;
- case 3:
- $columnName = "EDLI - {$status['claim_status']}";
- break;
- case 4:
- $columnName = "GTLI - {$status['claim_status']}";
- break;
+ // Get all active claim statuses
+ $statusQuery = $this->db->table('ticket_claim_status')
+ ->select('id, claim_status')
+ ->where('is_active', 1)
+ ->orderBy('id', 'ASC');
+
+ if (!empty($ticket_type)) {
+ $statusQuery->where('ticket_type', $ticket_type);
+ }
+
+ $statusResult = $statusQuery->get()->getResultArray();
+
+ // Create a list of all TAT categories we want in the output
+ $tatCategories = [
+ 'Above 20 Days',
+ '13-20 Days',
+ '7-12 Days',
+ '0-6 Days'
+ ];
+
+ // Initialize the result array with all TAT categories
+ $result = [];
+ foreach ($tatCategories as $category) {
+ $row = ['TAT_Category' => $category];
+ foreach ($statusResult as $status) {
+ $row[$status['claim_status']] = 0;
+ }
+ $result[] = $row;
+ }
+
+ // Get the base query for ticket counts by status and TAT category
+ $query = $this->db->table('ticket_master tm')
+ ->select([
+ 'tcs.claim_status',
+ 'CASE
+ WHEN DATEDIFF(CURDATE(), COALESCE(
+ (SELECT MAX(th.created_at)
+ FROM ticket_history th
+ WHERE th.ticket_id = tm.id
+ AND th.field_name = "claim_status_id"
+ AND th.is_active = 1),
+ tm.created_at
+ )) BETWEEN 0 AND 6 THEN "0-6 Days"
+ WHEN DATEDIFF(CURDATE(), COALESCE(
+ (SELECT MAX(th.created_at)
+ FROM ticket_history th
+ WHERE th.ticket_id = tm.id
+ AND th.field_name = "claim_status_id"
+ AND th.is_active = 1),
+ tm.created_at
+ )) BETWEEN 7 AND 12 THEN "7-12 Days"
+ WHEN DATEDIFF(CURDATE(), COALESCE(
+ (SELECT MAX(th.created_at)
+ FROM ticket_history th
+ WHERE th.ticket_id = tm.id
+ AND th.field_name = "claim_status_id"
+ AND th.is_active = 1),
+ tm.created_at
+ )) BETWEEN 13 AND 20 THEN "13-20 Days"
+ ELSE "Above 20 Days"
+ END AS tat_category',
+ 'COUNT(*) AS count'
+ ])
+ ->join('ticket_claim_status tcs', 'tcs.id = tm.claim_status_id AND tcs.is_active = 1')
+ ->where('tm.is_active', 1)
+ ->where('tm.created_at >=', $fromDate)
+ ->where('tm.created_at <=', $toDate)
+ ->groupBy('tcs.claim_status, tat_category')
+ ->orderBy('FIELD(tat_category, "Above 20 Days", "13-20 Days", "7-12 Days", "0-6 Days")');
+
+ if (!empty($ticket_type)) {
+ $query->where('tm.ticket_type_id', $ticket_type);
+ }
+
+ $countResults = $query->get()->getResultArray();
+
+ // Populate the result array with actual counts
+ foreach ($countResults as $row) {
+ foreach ($result as &$categoryRow) {
+ if ($categoryRow['TAT_Category'] === $row['tat_category']) {
+ $categoryRow[$row['claim_status']] = (int)$row['count'];
+ break;
}
}
-
- $dynamicSelect .= "
- COALESCE(
- SUM(
- CASE
- WHEN subquery.status_id = {$status['id']} THEN 1
- ELSE 0
- END
- ),
- 0
- ) AS `$columnName`, ";
}
- // Remove the trailing comma from the SELECT part
- $dynamicSelect = rtrim($dynamicSelect, ', ');
- // dd($dynamicSelect);
-
-
- // Construct the full SQL query
- $sql = "
- SELECT
- tc.TAT_Category,
- $dynamicSelect
- FROM
- (
- SELECT 'Above 20 Days' AS TAT_Category
- UNION ALL
- SELECT '13-20 Days'
- UNION ALL
- SELECT '7-12 Days'
- UNION ALL
- SELECT '0-6 Days'
- ) AS tc
- LEFT JOIN (
-
- SELECT
- th.ticket_id,
- tcs.claim_status,
- tcs.id AS status_id,
- CASE
- WHEN DATEDIFF(
- th.created_at,
- COALESCE(
- (SELECT MIN(created_at) FROM ticket_history th2 WHERE th2.ticket_id = th.ticket_id),
- tm.created_at
- )
- ) BETWEEN 0 AND 6 THEN '0-6 Days'
- WHEN DATEDIFF(
- th.created_at,
- COALESCE(
- (SELECT MIN(created_at) FROM ticket_history th2 WHERE th2.ticket_id = th.ticket_id),
- tm.created_at
- )
- ) BETWEEN 7 AND 12 THEN '7-12 Days'
- WHEN DATEDIFF(
- th.created_at,
- COALESCE(
- (SELECT MIN(created_at) FROM ticket_history th2 WHERE th2.ticket_id = th.ticket_id),
- tm.created_at
- )
- ) BETWEEN 13 AND 20 THEN '13-20 Days'
- ELSE 'Above 20 Days'
- END AS TAT_Category
-
- FROM
- ticket_master tm
- JOIN ticket_history th ON tm.id = th.ticket_id
- JOIN ticket_claim_status tcs ON th.field_name = 'claim_status_id' AND th.new_value = tcs.id
- $ticket_type_data_2
- AND tm.created_at >= '$fromDate'
- AND tm.created_at <= '$toDate'
- AND tm.is_active = 1
- AND th.is_active = 1
- AND tcs.is_active = 1
-
- ) AS subquery ON tc.TAT_Category = subquery.TAT_Category
- GROUP BY
- tc.TAT_Category
- ORDER BY
- FIELD(
- tc.TAT_Category,
- 'Above 20 Days',
- '13-20 Days',
- '7-12 Days',
- '0-6 Days'
- );
- ";
-
- // Execute the query and return the result
- $data = $this->db->query($sql)->getResultArray();
- // print_rr($this->db->getLastQuery(), $data); die;
-
- // $tableData = [];
- // if (!empty($data)) {
- // // Extract table headers from the first row keys
- // $headers = array_keys($data[0]);
- // $tableData['headers'] = $headers;
- // $tableData['body'] = $data;
- // }
-
- return $data;
+ return $result;
}
- public function tpaWiseReport($policy_type = null ,$start_date = null, $end_date = null){
- $ticket_type_data_1 = "";
+ public function tpaWiseReport($policy_type = null, $start_date = null, $end_date = null)
+ {
+ $ticket_type_data_1 = "";
$ticket_type_data_2 = "";
if (!empty($policy_type)) {
@@ -510,8 +595,17 @@ class TicketMasterModel extends Model
$dynamicSelect .= "
COUNT(CASE WHEN master.claim_status_id = {$status['id']} THEN master.id END) AS `{$status['claim_status']}`, ";
- if (in_array($status['claim_status'], ['ID NOT GENERATED', 'NON ID', 'CDA', 'INFORMATION REQUIRED','UNDER PROCESS - CLAIM NO. UPDATION',
- 'UNDER PROCESS - INVESTIGATION STATUS','UNDER PROCESS - QUERY DOCUMENT RECEIVED','APPROVED','PAYMENT INITIATED'])) {
+ if (in_array($status['claim_status'], [
+ 'ID NOT GENERATED',
+ 'NON ID',
+ 'CDA',
+ 'INFORMATION REQUIRED',
+ 'UNDER PROCESS - CLAIM NO. UPDATION',
+ 'UNDER PROCESS - INVESTIGATION STATUS',
+ 'UNDER PROCESS - QUERY DOCUMENT RECEIVED',
+ 'APPROVED',
+ 'PAYMENT INITIATED'
+ ])) {
$dynamicTotal .= "COUNT(CASE WHEN master.claim_status_id = {$status['id']} THEN master.id END) + ";
}
// Include in total count
@@ -531,6 +625,7 @@ class TicketMasterModel extends Model
// Construct the final SQL query
$sql = "
SELECT
+ tpa.id as TPA_ID,
tpa.name AS TPA_NAME,
$dynamicSelect,
($dynamicTotal) AS TOTAL,
@@ -552,48 +647,49 @@ class TicketMasterModel extends Model
// print_rr($result);die();
return $result;
-
}
- public function accountManagerWiseReport($policy_type = null ,$start_date = null, $end_date = null){
+ public function accountManagerWiseReport($policy_type = null, $start_date = null, $end_date = null)
+ {
if ($policy_type == 1) {
$ticket_type_data_1 = "";
- $ticket_type_data_2 = "";
+ $ticket_type_data_2 = "";
- if (!empty($policy_type)) {
- $ticket_type_data_1 = "AND ticket_type = $policy_type";
- $ticket_type_data_2 = "AND master.ticket_type_id = $policy_type";
- }
+ if (!empty($policy_type)) {
+ $ticket_type_data_1 = "AND ticket_type = $policy_type";
+ $ticket_type_data_2 = "AND master.ticket_type_id = $policy_type";
+ }
- // Fetch claim statuses dynamically
- $statusQuery = "SELECT id, claim_status FROM ticket_claim_status WHERE is_active = 1 $ticket_type_data_1";
- $statusResult = $this->db->query($statusQuery)->getResultArray();
+ // Fetch claim statuses dynamically
+ $statusQuery = "SELECT id, claim_status FROM ticket_claim_status WHERE is_active = 1 $ticket_type_data_1";
+ $statusResult = $this->db->query($statusQuery)->getResultArray();
- // Initialize dynamic query parts
- $dynamicSelect = '';
- $dynamicTotal = '';
+ // Initialize dynamic query parts
+ $dynamicSelect = '';
+ $dynamicTotal = '';
- // Loop through each claim status and generate the CASE statements
- foreach ($statusResult as $status) {
- $dynamicSelect .= "
+ // Loop through each claim status and generate the CASE statements
+ foreach ($statusResult as $status) {
+ $dynamicSelect .= "
COUNT(CASE WHEN master.claim_status_id = {$status['id']} THEN master.id END) AS `{$status['claim_status']}`, ";
- // Include in total count
- $dynamicTotal .= "COUNT(CASE WHEN master.claim_status_id = {$status['id']} THEN master.id END) + ";
+ // Include in total count
+ $dynamicTotal .= "COUNT(CASE WHEN master.claim_status_id = {$status['id']} THEN master.id END) + ";
- // Include only closed-related statuses in total2 count
+ // Include only closed-related statuses in total2 count
- }
+ }
- // Remove the trailing commas and `+` signs
- $dynamicSelect = rtrim($dynamicSelect, ', ');
- $dynamicTotal = rtrim($dynamicTotal, ' +');
- // print_rr($dynamicSelect);
- // Construct the final SQL query
- $sql = "
+ // Remove the trailing commas and `+` signs
+ $dynamicSelect = rtrim($dynamicSelect, ', ');
+ $dynamicTotal = rtrim($dynamicTotal, ' +');
+ // print_rr($dynamicSelect);
+ // Construct the final SQL query
+ $sql = "
SELECT
+ user_profiles.id as ACM_ID,
user_profiles.first_name AS ACM_NAME,
$dynamicSelect,
($dynamicTotal) AS TOTAL
@@ -610,47 +706,51 @@ class TicketMasterModel extends Model
";
$result = $this->db->query($sql)->getResultArray();
- // dd($result);
return $result;
-
-
- }else{
+ } else {
$ticket_type_data_1 = "";
$ticket_type_data_2 = "";
-
+
if (!empty($policy_type)) {
$ticket_type_data_1 = "AND ticket_type = $policy_type";
$ticket_type_data_2 = "AND master.ticket_type_id = $policy_type";
}
-
+
// Fetch claim statuses dynamically
$statusQuery = "SELECT id, claim_status FROM ticket_claim_status WHERE is_active = 1 $ticket_type_data_1";
$statusResult = $this->db->query($statusQuery)->getResultArray();
-
+
// Initialize dynamic query parts
$dynamicSelect = '';
$dynamicTotal = '';
$dynamicClosedTotal = '';
-
+
// Loop through each claim status and generate the CASE statements
foreach ($statusResult as $status) {
$dynamicSelect .= "
COUNT(CASE WHEN master.claim_status_id = {$status['id']} THEN master.id END) AS `{$status['claim_status']}`, ";
-
- if (in_array($status['claim_status'], ['CLAIM INTIMATION', 'INTIMATION TO INSURER', 'CLIENT PENDING', 'INSURER PENDING','INVESTIGATION',
- 'APPROVED','ON HOLD'])) {
+
+ if (in_array($status['claim_status'], [
+ 'CLAIM INTIMATION',
+ 'INTIMATION TO INSURER',
+ 'CLIENT PENDING',
+ 'INSURER PENDING',
+ 'INVESTIGATION',
+ 'APPROVED',
+ 'ON HOLD'
+ ])) {
$dynamicTotal .= "COUNT(CASE WHEN master.claim_status_id = {$status['id']} THEN master.id END) + ";
}
// Include in total count
// $dynamicTotal .= "COUNT(CASE WHEN master.claim_status_id = {$status['id']} THEN master.id END) + ";
-
+
// Include only closed-related statuses in total2 count
if (in_array($status['claim_status'], ['CLOSED', 'SETTLED', 'NOT COVERED'])) {
$dynamicClosedTotal .= "COUNT(CASE WHEN master.claim_status_id = {$status['id']} THEN master.id END) + ";
}
}
-
+
// Remove the trailing commas and `+` signs
$dynamicSelect = rtrim($dynamicSelect, ', ');
$dynamicTotal = rtrim($dynamicTotal, ' +');
@@ -659,6 +759,7 @@ class TicketMasterModel extends Model
// Construct the final SQL query
$sql = "
SELECT
+ user_profiles.id as ACM_ID,
user_profiles.first_name AS ACM_NAME,
$dynamicSelect,
($dynamicTotal) AS TOTAL,
@@ -674,12 +775,13 @@ class TicketMasterModel extends Model
GROUP BY
user_profiles.id;
";
-
+
// Execute the query
$result = $this->db->query($sql)->getResultArray();
-
- // print_rr($result);die();
+
return $result;
+
+
}
}
@@ -689,6 +791,7 @@ class TicketMasterModel extends Model
$query = $this->select('ticket_master.*, tms.mail_subject as subject')
->join('ticket_messages tms', 'ticket_master.id = tms.ticket_id', 'left')
->where('ticket_master.is_active', 1)
+ ->where('tms.sender', "user")
->where('ticket_master.emp_id', $emp_id);
if (!empty($ticket_id)) {
@@ -703,6 +806,151 @@ class TicketMasterModel extends Model
// dd($data, db_connect()->getLastQuery());
return $data;
}
-
-
+
+ public function getDashData($claim_statuses, $limit)
+ {
+ $finalResults = [];
+
+ foreach ($claim_statuses as $typeId => $statuses) {
+ // Get all active, non-null claim status tickets for this type
+ $builder = $this->db->table('ticket_master tm')
+ ->select('tm.id, tm.ticket_type_id, tcs.claim_status, th.last_claim_status_change')
+ ->join('ticket_claim_status tcs', 'tm.claim_status_id = tcs.id', 'left')
+ ->join(
+ '(SELECT ticket_id, MAX(created_at) AS last_claim_status_change
+ FROM ticket_history
+ WHERE field_name = \'claim_status_id\'
+ GROUP BY ticket_id) th',
+ 'tm.id = th.ticket_id',
+ 'left'
+ )
+ ->where('tm.ticket_type_id', $typeId)
+ ->where('tm.is_active', 1)
+ ->where('tm.claim_status_id IS NOT NULL');
+
+ $results = $builder->get()->getResultArray();
+
+ $summary = [
+ 'ticket_type_id' => $typeId,
+ ];
+
+ $total = 0;
+ foreach ($statuses as $status) {
+ $alias = strtolower(str_replace(' ', '_', $status));
+ $summary[$alias] = 0;
+ $summary[$alias . '_ids'] = '';
+
+ $dateLimit = $limit[$typeId][$status] ?? 3;
+ $threshold = date('Y-m-d H:i:s', strtotime("-{$dateLimit} days"));
+
+ $ticketIds = [];
+ // dd($results);
+ foreach ($results as $row) {
+ if (
+ $row['claim_status'] === $status &&
+ (
+ !$row['last_claim_status_change'] ||
+ $row['last_claim_status_change'] <= $threshold
+ )
+ ) {
+ $summary[$alias]++;
+ $ticketIds[] = $row['id'];
+ if ($status == "APPROVED"|| $status == "SETTLED"|| $status == "CLOSED" ){
+ continue;
+ }
+
+ $total++;
+
+
+ }
+ }
+
+ // Convert ticket IDs array to a comma-separated string
+ $summary[$alias . '_ids'] = implode(',', $ticketIds);
+ }
+
+ $summary['total'] = $total;
+
+ // Add approved but not settled IDs and count
+ $approvedNotSettled = $this->getNotSettledbutApprovedCount($typeId);
+ $summary['approved_not_settled'] = $approvedNotSettled['count'];
+ $summary['approved_not_settled_ids'] = $approvedNotSettled['ticket_ids'];
+
+ $finalResults[$typeId] = $summary;
+ }
+
+ // dd($finalResults);
+ return $finalResults;
+ }
+
+
+
+ public function getNotSettledbutApprovedCount($ticket_type)
+ {
+ // Fetch the approved and settled claim_status IDs
+ $builder = $this->db->table("ticket_claim_status approved")
+ ->select("approved.id AS approved_id, settled.id AS settled_id")
+ ->join("ticket_claim_status settled", "approved.ticket_type = settled.ticket_type")
+ ->where("approved.claim_status", "APPROVED")
+ ->where("settled.claim_status", "SETTLED")
+ ->where("approved.ticket_type", $ticket_type)
+ ->where("approved.is_active", 1)
+ ->where("settled.is_active", 1);
+
+ $ids = $builder->get()->getRowArray();
+
+ // If no matching status IDs are found, return empty
+ if (!$ids) {
+ return ['count' => 0, 'ticket_ids' => ''];
+ }
+
+ // Extract approved and settled status IDs
+ $approved_id = $ids['approved_id'];
+ $settled_id = $ids['settled_id'];
+
+ // Subquery to get the latest approval time for each ticket
+ $subquery = $this->db->table('ticket_history')
+ ->select('ticket_id, MAX(created_at) AS approved_time')
+ ->where('field_name', 'claim_status_id')
+ ->where('new_value', $approved_id)
+ ->groupBy('ticket_id');
+
+ // Main query to find tickets that are approved but not settled
+ $builder = $this->db->table('ticket_master tm');
+
+ $builder->join("({$subquery->getCompiledSelect()}) latest_approval", 'tm.id = latest_approval.ticket_id', 'inner');
+
+ // Left join to find if there is a settled status for each ticket after approval
+ $builder->join(
+ 'ticket_history th_settled',
+ "th_settled.ticket_id = tm.id
+ AND th_settled.field_name = 'claim_status_id'
+ AND th_settled.new_value = {$settled_id}
+ AND th_settled.created_at > latest_approval.approved_time",
+ 'left',
+ false // Important for raw ON condition
+ );
+
+ // Filtering conditions: not settled and approved time older than 12 days
+ $builder->where('tm.claim_status_id !=', $settled_id);
+ $builder->where('tm.is_active', 1);
+ $builder->where("latest_approval.approved_time <= DATE_SUB(NOW(), INTERVAL 12 DAY)", null, false);
+ $builder->where('th_settled.id IS NULL', null, false);
+
+ // Final select to get ticket IDs of approved but not settled tickets
+ $builder->select('tm.id');
+
+ // Execute the query
+ $query = $builder->get();
+ $ticketIds = array_column($query->getResultArray(), 'id'); // Extract the IDs
+
+ // Convert ticket IDs array to a comma-separated string
+ $ticketIdsString = implode(',', $ticketIds);
+
+ // Return the count and comma-separated ticket IDs
+ return [
+ 'count' => count($ticketIds),
+ 'ticket_ids' => $ticketIdsString
+ ];
+ }
}
diff --git a/app/Models/UserModel.php b/app/Models/UserModel.php
index 49b84400..ed5a8ace 100755
--- a/app/Models/UserModel.php
+++ b/app/Models/UserModel.php
@@ -134,5 +134,20 @@ class UserModel extends Model
->getResultArray();
}
+ public function getexclusiveUserListForRFQ(){
+ $data = $this->db->table('user_profiles')
+ ->select('user_profiles.*,user_teams.team_id')
+ ->select('roles.role as user_role')
+ ->join('roles', 'roles.id = user_profiles.role')
+ ->join('user_teams', 'user_teams.user_id = user_profiles.id')
+ ->get()
+ ->getResultArray();
+
+
+ // dd($data);
+
+ return $data;
+ }
+
}
?>
\ No newline at end of file
diff --git a/app/Views/DashBoard.php b/app/Views/DashBoard.php
index 4da6b9c0..08e08855 100755
--- a/app/Views/DashBoard.php
+++ b/app/Views/DashBoard.php
@@ -139,40 +139,41 @@
+
@@ -188,21 +189,25 @@ body {
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/Views/batch_list.php b/app/Views/batch_list.php
index 4d85d018..f1a623fe 100755
--- a/app/Views/batch_list.php
+++ b/app/Views/batch_list.php
@@ -90,6 +90,17 @@
+
+
+
+
+
+
+
+
+
+
failed Re-Upload
-
+
Download
diff --git a/app/Views/bds_dash.php b/app/Views/bds_dash.php
index 89a92413..0544e646 100644
--- a/app/Views/bds_dash.php
+++ b/app/Views/bds_dash.php
@@ -125,12 +125,20 @@ body{
}
-
+
+
+
-
-
show all pending Tile
+
+
+
-
@@ -219,6 +227,10 @@ body{
\ No newline at end of file
diff --git a/app/Views/bds_multi_report.php b/app/Views/bds_multi_report.php
new file mode 100644
index 00000000..05b38e6c
--- /dev/null
+++ b/app/Views/bds_multi_report.php
@@ -0,0 +1,122 @@
+
+
+
+
+
+
diff --git a/app/Views/bds_tat_wise_report.php b/app/Views/bds_tat_wise_report.php
new file mode 100644
index 00000000..e3c428f4
--- /dev/null
+++ b/app/Views/bds_tat_wise_report.php
@@ -0,0 +1,122 @@
+
+
+
+
+
+
+
+
+
+
BDS TAT Band Wise Report
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/Views/chatbot.php b/app/Views/chatbot.php
index 94373196..95bf5cde 100644
--- a/app/Views/chatbot.php
+++ b/app/Views/chatbot.php
@@ -41,7 +41,7 @@
origin: "mobile", // origin
emp_code:"HTL-007",
client_id:159,
- client_branch_id:125
+ client_branch_id:126
}
};
diff --git a/app/Views/claims_dash.php b/app/Views/claims_dash.php
new file mode 100644
index 00000000..c62af2ab
--- /dev/null
+++ b/app/Views/claims_dash.php
@@ -0,0 +1,330 @@
+
+
+
+
+
+
+
+
GMC
+
= isset($claim_data[1]['total']) ? $claim_data[1]['total'] : '0' ?>
+
+
+
+
+
+
+
+
+
+
GPA
+
= isset($claim_data[2]['total']) ? $claim_data[2]['total'] : '0' ?>
+
+
+
+
+
+
+
+
+
+
EDLI
+
= isset($claim_data[3]['total']) ? $claim_data[3]['total'] : '0' ?>
+
+
+
+
+
+
+
+
+
+
GTLI
+
= isset($claim_data[4]['total']) ? $claim_data[4]['total'] : '0' ?>
+
+
+
+
+
+
+
+
+
+
+
+ $statuses) : ?>
+
+
+ $count) : ?>
+
+ 20 ? substr($formattedStatus, 0, 15) . '...' : $formattedStatus;
+ $showTooltip = strlen($formattedStatus) > 20;
+ ?>
+
+
+
= $count ?>
+ >
+ = $truncatedStatus ?>
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/Views/claims_report_acc_manager_wise.php b/app/Views/claims_report_acc_manager_wise.php
index a629a01c..3816a419 100644
--- a/app/Views/claims_report_acc_manager_wise.php
+++ b/app/Views/claims_report_acc_manager_wise.php
@@ -18,6 +18,10 @@
.right-align-input {
text-align: right;
}
+
+ #scroll-horizontal-datatable tbody tr:hover {
+ background-color: #e0e0e0;
+ }
@@ -47,7 +51,7 @@
- = $row[$col_name] ?>
+ = $row[$col_name] ?>
@@ -101,3 +105,37 @@
}
});
+
+
+
\ No newline at end of file
diff --git a/app/Views/claims_report_tpa_wise.php b/app/Views/claims_report_tpa_wise.php
index 0a3fc65a..d473d717 100644
--- a/app/Views/claims_report_tpa_wise.php
+++ b/app/Views/claims_report_tpa_wise.php
@@ -37,16 +37,18 @@
- = str_replace('_', ' ', $col_name) ?>
-
+
+ = str_replace('_', ' ', $col_name) ?>
+
- = $row[$col_name] ?>
-
+
+ = $row[$col_name] ?>
+
@@ -62,7 +64,7 @@
}
foreach ($column_order as $col_name) {
- if ($col_name !== 'TPA_NAME') {
+ if ($col_name !== 'TPA_NAME' && $col_name != "TPA_ID") {
echo "
{$totals[$col_name]} ";
}
}
@@ -98,4 +100,35 @@
console.error("Table not found.");
}
});
-
+
+ function redirectTPAToClaimList(tpa_id){
+
+ // alert(tpa_id);
+ data = {
+ 'tpa_id' : tpa_id,
+ 'is_dashboard':3
+ }
+
+ redirectWithPost("= base_url("ticket/list") ?>", data);
+
+ }
+
+ function redirectWithPost(url, data = {}) {
+ const form = document.createElement('form');
+ form.method = 'POST';
+ form.action = url;
+
+ for (const key in data) {
+ if (data.hasOwnProperty(key)) {
+ const input = document.createElement('input');
+ input.type = 'hidden';
+ input.name = key;
+ input.value = data[key];
+ form.appendChild(input);
+ }
+ }
+
+ document.body.appendChild(form);
+ form.submit();
+ }
+
\ No newline at end of file
diff --git a/app/Views/client_api.php b/app/Views/client_api.php
new file mode 100644
index 00000000..8fe995d5
--- /dev/null
+++ b/app/Views/client_api.php
@@ -0,0 +1,453 @@
+
+
+
+
+
+
+ Enable API Access
+
+ id="is_api" type="checkbox" name="is_api">
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/Views/client_basic_info.php b/app/Views/client_basic_info.php
index 9e41c616..220164b8 100755
--- a/app/Views/client_basic_info.php
+++ b/app/Views/client_basic_info.php
@@ -125,13 +125,13 @@ input:checked + .slider:before {
-
+
diff --git a/app/Views/client_deposit_list.php b/app/Views/client_deposit_list.php
index d19d0ec6..ab076ebb 100755
--- a/app/Views/client_deposit_list.php
+++ b/app/Views/client_deposit_list.php
@@ -49,7 +49,7 @@
insurer_id}?client_id={$value->client_id}"); ?>">
+ href="= base_url("client/view_deposit/{$value->insurer_id}?client_id={$value->client_id}&cd_ac_pk={$value->cd_ac_pk}"); ?>">
View Deposit
diff --git a/app/Views/client_list.php b/app/Views/client_list.php
index 592031dc..673c5eaf 100755
--- a/app/Views/client_list.php
+++ b/app/Views/client_list.php
@@ -17,6 +17,10 @@ table.dataTable thead th {
max-width: 98% !important;
}
+.btn-filter{
+ margin-left: 20px !important;
+}
+
.custom-dropdown-menu {
display: none;
position: absolute;
@@ -53,12 +57,12 @@ table.dataTable thead th {
Client List
-
+
@@ -269,18 +273,40 @@ table.dataTable thead th {
$(document).ready(function()
{
$('#tickets-table').DataTable({
- dom: "<'row'<'col-sm-0'f><'col-sm-7 text-right'B>>" +
+ dom: "<'row'<'col-sm-2'f><'col-sm-10 text-right'B>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>",
- buttons: [{
- extend: 'csv',
- text: 'CSV',
- title: 'ClientList',
- className: 'my_class',
- exportOptions: {
- columns: ':not(:last-child)'
+ buttons: [
+ {
+ extend: 'csv',
+ text: 'CSV',
+ title: 'ClientList',
+ className: 'my_class',
+ exportOptions: {
+ columns: ':not(:last-child)'
+ },
+ },
+ {
+ text: 'Add From Lead',
+ className: 'btn-filter', // custom class
+ action: function(e, dt, node, config) {
+ showModal();
+ }
},
- }],
+ {
+ text: 'Add',
+ className: 'btn-filter', // custom class
+ action: function(e, dt, node, config) {
+ addClient();
+ }
+ }
+ ],
+
+ initComplete: function() {
+ $('.btn-filter')
+ .removeClass('btn-secondary')
+ .addClass('btn btn-primary');
+ },
language: {
search: "_INPUT_",
searchPlaceholder: "Search..."
@@ -440,4 +466,9 @@ function featchClient(){
});
}
+function addClient(){
+ let url = "= base_url("client/create"); ?>";
+ window.location.href = url;
+}
+
\ No newline at end of file
diff --git a/app/Views/client_onboarding.php b/app/Views/client_onboarding.php
index 814a97cd..5327b58b 100755
--- a/app/Views/client_onboarding.php
+++ b/app/Views/client_onboarding.php
@@ -88,15 +88,22 @@ body {
Policies
-
+
+
-
+
+
@@ -172,10 +179,9 @@ body {
}
function client_policies() {
- var check_client_id = $('#general_PrimaryKey');
+ var check_client_id = $('#general_PrimaryKey').val();
-
- if(check_client_id[0].value == '' || check_client_id[0].value == null || check_client_id[0].value == 0){
+ if(check_client_id == '' || check_client_id == null || check_client_id == 0){
$('#BtnAdd').hide();
toastr.warning('Please Add the Client!', 'warning',{timeOut: 2000});
}else{
@@ -246,7 +252,7 @@ body {
event.preventDefault();
client_notification();
});
-
+
diff --git a/app/Views/client_policy.php b/app/Views/client_policy.php
index cbe4f817..b16dae44 100755
--- a/app/Views/client_policy.php
+++ b/app/Views/client_policy.php
@@ -16,7 +16,7 @@
Client Branch
TPA
Date
- Enrolment Status
+
Status
Action
@@ -136,7 +136,7 @@
-
@@ -326,10 +326,10 @@ label {
- Waiver of Pre-existing Diseases
+ Waiver of Pre-existing Diseases
-
+
@@ -405,10 +405,10 @@ label {
id="9monthwaitingperiodwaived_display" class="unchecked" checked>
- 9-month waiting Period –waived
+ 9-month waiting Period –waived
-
+
@@ -418,7 +418,7 @@ label {
id="maternitycoverage_display" class="unchecked" checked>
- Maternity Coverage
+ Maternity Coverage
@@ -431,7 +431,7 @@ label {
id="twindelivery_display" class="unchecked" checked>
- Twin Delivery
+ Twin Delivery
@@ -457,7 +457,7 @@ label {
id="preandpostnatal_display" class="unchecked" checked>
- Pre and Post natal
+ Pre and Post natal
@@ -483,7 +483,7 @@ label {
id="babyday1cover_display" class="unchecked" checked>
- Baby Day 1 Cover
+ Baby Day 1 Cover
@@ -496,7 +496,7 @@ label {
id="coverfromthedateofjoining_display" class="unchecked" checked>
- Cover from the date of Joining
+ Cover from the date of Joining
- Pre Hospitalization Cover
+ Pre Hospitalization Cover
- Post Hospitalization Cover
+ Post Hospitalization Cover
- Congenital Diseases - Internal
+ Congenital Diseases - Internal
@@ -564,7 +564,7 @@ label {
id="congenitaldiseasesexternal_display" class="unchecked" checked>
- Congenital Diseases - External
+ Congenital Diseases - External
- Room Rent Limit
+ Room Rent Limit
@@ -617,7 +617,7 @@ label {
id="proportionatedeductionclause_display" class="unchecked" checked>
- Proportionate Deduction Clause
+ Proportionate Deduction Clause
@@ -643,7 +643,7 @@ label {
id="ailment_capping_details_display" class="unchecked" checked>
- Ailment capping Details
+ Ailment capping Details
@@ -656,7 +656,7 @@ label {
id="corporatebuffer_display" class="unchecked" checked>
- Corporate Buffer
+ Corporate Buffer
@@ -683,7 +683,7 @@ label {
id="ambulancecharges_display" class="unchecked" checked>
- Ambulance Charges
+ Ambulance Charges
@@ -696,7 +696,7 @@ label {
id="airambulance_display" class="unchecked" checked>
- Air Ambulance
+ Air Ambulance
@@ -735,7 +735,7 @@ label {
id="lasiksurgery_display" class="unchecked" checked>
- Lasik Surgery
+ Lasik Surgery
@@ -751,7 +751,7 @@ label {
AYUSH treatment cover
-
+
@@ -761,7 +761,7 @@ label {
id="moderntreatmentsasperirdai_display" class="unchecked" checked>
- Modern treatments as per IRDAI
+ Modern treatments as per IRDAI
- Claim Intimation Clause
+ Claim Intimation Clause
@@ -801,7 +801,7 @@ label {
id="days_from_dod_display" class="unchecked" checked>
- Claim Submission
+ Claim Submission
@@ -817,7 +817,7 @@ label {
Terrorism
-
+
@@ -849,7 +849,7 @@ label {
-
+
Sum Insured enhancement
@@ -880,584 +880,191 @@ label {
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/Views/policy_gpa_terms.php b/app/Views/policy_gpa_terms.php
index 3ad9d2be..3dee9703 100755
--- a/app/Views/policy_gpa_terms.php
+++ b/app/Views/policy_gpa_terms.php
@@ -475,75 +475,75 @@ $('.close').click(function() {
});
-$('input[name="burnExpenses"]').change(function() {
+// $('input[name="burnExpenses"]').change(function() {
- console.log($(this).val());
+// console.log($(this).val());
- if ($(this).val() == '1') {
- var element = $(this).parent().parent().next()[0];
- $(element).css("display", "");
+// if ($(this).val() == '1') {
+// var element = $(this).parent().parent().next()[0];
+// $(element).css("display", "");
- } else {
- var element = $(this).parent().parent().next()[0];
- $(element).css("display", "none");
- }
-});
+// } else {
+// var element = $(this).parent().parent().next()[0];
+// $(element).css("display", "none");
+// }
+// });
-$('input[name="compassionateVisitExpenses"]').change(function() {
+// $('input[name="compassionateVisitExpenses"]').change(function() {
- console.log($(this).val());
+// console.log($(this).val());
- if ($(this).val() == '1') {
- var element = $(this).parent().parent().next()[0];
- $(element).css("display", "");
+// if ($(this).val() == '1') {
+// var element = $(this).parent().parent().next()[0];
+// $(element).css("display", "");
- } else {
- var element = $(this).parent().parent().next()[0];
- $(element).css("display", "none");
- }
-});
+// } else {
+// var element = $(this).parent().parent().next()[0];
+// $(element).css("display", "none");
+// }
+// });
-$('input[name="carriageOfDeadBody"]').change(function() {
+// $('input[name="carriageOfDeadBody"]').change(function() {
- console.log($(this).val());
+// console.log($(this).val());
- if ($(this).val() == '1') {
- var element = $(this).parent().parent().next()[0];
- $(element).css("display", "");
+// if ($(this).val() == '1') {
+// var element = $(this).parent().parent().next()[0];
+// $(element).css("display", "");
- } else {
- var element = $(this).parent().parent().next()[0];
- $(element).css("display", "none");
- }
-});
+// } else {
+// var element = $(this).parent().parent().next()[0];
+// $(element).css("display", "none");
+// }
+// });
-$('input[name="ambulanceCharges"]').change(function() {
+// $('input[name="ambulanceCharges"]').change(function() {
- console.log($(this).val());
+// console.log($(this).val());
- if ($(this).val() == '1') {
- var element = $(this).parent().parent().next()[0];
- $(element).css("display", "");
+// if ($(this).val() == '1') {
+// var element = $(this).parent().parent().next()[0];
+// $(element).css("display", "");
- } else {
- var element = $(this).parent().parent().next()[0];
- $(element).css("display", "none");
- }
-});
+// } else {
+// var element = $(this).parent().parent().next()[0];
+// $(element).css("display", "none");
+// }
+// });
-$('input[name="brokenBoneExpenses"]').change(function() {
+// $('input[name="brokenBoneExpenses"]').change(function() {
- console.log($(this).val());
+// console.log($(this).val());
- if ($(this).val() == '1') {
- var element = $(this).parent().parent().next()[0];
- $(element).css("display", "");
+// if ($(this).val() == '1') {
+// var element = $(this).parent().parent().next()[0];
+// $(element).css("display", "");
- } else {
- var element = $(this).parent().parent().next()[0];
- $(element).css("display", "none");
- }
-});
+// } else {
+// var element = $(this).parent().parent().next()[0];
+// $(element).css("display", "none");
+// }
+// });
$("#policyGPATerms").submit(function(event) {
@@ -784,6 +784,7 @@ $('body').on('click', '.btnPolicyMaster', function() {
.next()[0];
$(element).css("display", "");
}
+ disableUnwantedTermsforGPA(jsonObject);
Object.keys(jsonObject).forEach(function(key) {
@@ -853,6 +854,34 @@ $('body').on('click', '.btnPolicyMaster', function() {
\ No newline at end of file
diff --git a/app/Views/policy_grid.php b/app/Views/policy_grid.php
index 69e8e3db..06c945c6 100755
--- a/app/Views/policy_grid.php
+++ b/app/Views/policy_grid.php
@@ -108,6 +108,7 @@
onchange="addGridHTML(this)" required>
+