MERGE_TEST_DASHBOARD_API

This commit is contained in:
Ubuntu 2026-06-02 14:32:55 +05:30
commit 06f5844fd6
32 changed files with 1051964 additions and 101 deletions

View File

@ -35,6 +35,7 @@ $routes->get('/fedeploy', 'DeployController::fedeploy_view', ['filter' => 'authM
$routes->post('/fedeploy', 'DeployController::fedeploy', ['filter' => 'authMVC']);
$routes->get('/visitOffBoardCheck', 'EmployeeController::visitOffBoardCheck');
$routes->get('/metaDashboardDemo', 'TestingController::metaDashboardDemo');
$routes->get('/apacheSuperSetDemo', 'TestingController::apacheSuperSetDemo');
$routes->get('/metaTpaDashboardDemo', 'TestingController::metaTpaDashboardDemo');
// Reminder Mail Notification
@ -460,6 +461,15 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) {
$routes->get('insertSampleTpaApiData/(:any)', 'TestingController::insertSampleTpaApiData/$1');
$routes->get('listEmployeeCountByClientPolicy', 'TestingController::listEmployeeCountByClientPolicy');
$routes->get('testMediAssistWellness','TestingController::testMediAssistWellness');
$routes->group('claims-collection-v2', static function ($routes) {
$routes->get('preview', 'ClaimsCollectionV2DashboardController::preview');
$routes->get('preview/(:num)', 'ClaimsCollectionV2DashboardController::preview/$1');
$routes->get('kpi/(:segment)', 'ClaimsCollectionV2DashboardController::kpi/$1');
$routes->get('all', 'ClaimsCollectionV2DashboardController::all');
$routes->get('debug', 'ClaimsCollectionV2DashboardController::debug');
$routes->get('debug/(:num)', 'ClaimsCollectionV2DashboardController::debug/$1');
});
});
$routes->post("policy_tranction/sendInstallmentRemainderMail","PolicyTransactionController::sendInstallmentRemainderMail");
@ -767,6 +777,15 @@ $routes->group("employeeRest", ["filter" => ['GlobalPostFileUploadGuard', 'ratel
$routes->get("downloadPolicyFiles", "EmployeeRestController::downloadPolicyFiles");
$routes->post("bulkEcardDownloadAsZip", "EmployeeRestController::bulkEcardDownloadAsZip");
$routes->get("downloadSampleExcel/(:any)", "EmployeeController::downloadSampleExcelFile/$1");
$routes->group('claims-collection-v2', static function ($routes) {
$routes->get('preview', 'ClaimsCollectionV2DashboardController::preview');
$routes->get('preview/(:num)', 'ClaimsCollectionV2DashboardController::preview/$1');
$routes->get('kpi/(:segment)', 'ClaimsCollectionV2DashboardController::kpi/$1');
$routes->get('all', 'ClaimsCollectionV2DashboardController::all');
$routes->get('debug', 'ClaimsCollectionV2DashboardController::debug');
$routes->get('debug/(:num)', 'ClaimsCollectionV2DashboardController::debug/$1');
});
});
$routes->post("bulkEcardDownloadAsZip", "EmployeeRestController::bulkEcardDownloadAsZip");

View File

@ -0,0 +1,166 @@
<?php
namespace App\Controllers;
use App\Models\ClaimsCollectionV2DashboardModel;
use CodeIgniter\API\ResponseTrait;
/**
* Claims Collection V2 KPI API (Metabase SQL as model methods).
*/
class ClaimsCollectionV2DashboardController extends BaseController
{
use ResponseTrait;
/**
* Resolve policy id from request; optional $fallback (e.g. route default for debug only).
*/
protected function resolvePolicyId(?int $fallback = null): int
{
$id = (int) (
$this->request->getGet('client_policy')
?? $this->request->getGet('client_policy_id')
?? $this->request->getPost('client_policy')
?? $this->request->getPost('client_policy_id')
?? 0
);
if ($id > 0) {
return $id;
}
if ($fallback !== null && $fallback > 0) {
return $fallback;
}
return 0;
}
/**
* Resolve KPI by Metabase numeric id or method slug.
*/
protected function resolveKpiMethod(string $kpiKey): ?string
{
$kpiKey = trim($kpiKey);
if ($kpiKey === '') {
return null;
}
if (in_array($kpiKey, ClaimsCollectionV2DashboardModel::KPI_MAP, true)) {
return $kpiKey;
}
if (ctype_digit($kpiKey)) {
$id = (int) $kpiKey;
return ClaimsCollectionV2DashboardModel::KPI_MAP[$id] ?? null;
}
return null;
}
/**
* JSON: single KPI by slug (e.g. incurred_ratio) or Metabase id (e.g. 207).
* Requires client_policy or client_policy_id.
*/
public function kpi(string $kpiMethod = '')
{
$policyId = $this->resolvePolicyId();
if ($policyId <= 0) {
return $this->respond([
'status' => false,
'message' => 'client_policy or client_policy_id is required.',
], 422);
}
$kpiMethod = $this->resolveKpiMethod($kpiMethod);
if ($kpiMethod === null) {
return $this->respond([
'status' => false,
'message' => 'Unknown KPI. Pass Metabase id or method slug.',
'allowed' => ClaimsCollectionV2DashboardModel::KPI_MAP,
], 404);
}
$model = new ClaimsCollectionV2DashboardModel();
$metabaseId = array_search($kpiMethod, ClaimsCollectionV2DashboardModel::KPI_MAP, true);
return $this->respond([
'status' => true,
'policy_id' => $policyId,
'kpi_id' => $metabaseId !== false ? (int) $metabaseId : null,
'kpi' => $kpiMethod,
'label' => ClaimsCollectionV2DashboardModel::KPI_LABELS[$kpiMethod] ?? $kpiMethod,
'rows' => $model->getKpi($kpiMethod, $policyId),
]);
}
/**
* JSON: all KPIs. Requires client_policy or client_policy_id.
*/
public function all()
{
$policyId = $this->resolvePolicyId();
if ($policyId <= 0) {
return $this->respond([
'status' => false,
'message' => 'client_policy or client_policy_id is required.',
], 422);
}
$model = new ClaimsCollectionV2DashboardModel();
return $this->respond([
'status' => true,
'policy_id' => $policyId,
'data' => $model->getAllKpis($policyId),
]);
}
/**
* Admin preview UI (authMVC only) KPI grid for manual testing.
* Default policy id only in method signature; override via query or /preview/{id}.
*/
public function preview(int $policyId = 4687)
{
$policyId = $this->resolvePolicyId($policyId);
$path = $this->request->getUri()->getPath();
$isJwt = stripos($path, 'employeeRest') !== false;
$prefix = $isJwt ? 'employeeRest/claims-collection-v2' : 'util/claims-collection-v2';
return view('claims_collection_v2_dashboard', [
'policy_id' => $policyId,
'kpi_map' => ClaimsCollectionV2DashboardModel::KPI_MAP,
'kpi_labels' => ClaimsCollectionV2DashboardModel::KPI_LABELS,
'api_all_url' => base_url($prefix . '/all'),
'api_kpi_url' => base_url($prefix . '/kpi'),
]);
}
/**
* Admin check only: raw JSON on screen (no dashboard UI).
* Default policy id only here; override via ?client_policy= or /debug/{id}.
*/
public function debug(int $policyId = 4687)
{
$policyId = $this->resolvePolicyId($policyId);
if ($policyId <= 0) {
return $this->response
->setStatusCode(422)
->setBody('client_policy or client_policy_id is required.');
}
$model = new ClaimsCollectionV2DashboardModel();
$body = json_encode([
'status' => true,
'policy_id' => $policyId,
'data' => $model->getAllKpis($policyId),
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
return $this->response
->setHeader('Content-Type', 'application/json; charset=UTF-8')
->setBody($body);
}
}

View File

@ -6652,7 +6652,7 @@ class ClientController extends AdminController
// Check in Enrollment (client_policy)
$client_policy_data = $this->clientPolicyModel
->where('is_active', 1)
->where('policy_status', 1)
// ->where('policy_status', 1)
->where('TRIM(policy_no)', $policy_no)
->first();

View File

@ -1143,11 +1143,54 @@ class TestingController extends BaseController
'metabaseUrl' => 'https://nsights.nhanceindia.in',
]);
}
public function apacheSuperSetDemo()
{
public function testingquerys1(){
// echo 'Dta';die;
// 🔐 Move this to .env in real projects
$METABASE_SECRET_KEY = getenv('METABASE_SECRET_KEY');
$database_id = (int)$this->request->getGet('database_id') ?? 2;
$policy_id = $this->request->getGet('client_policy') ?? null;
$tpa_url = 'https://nsights.nhanceindia.in/public/dashboard/4babf324-6c1e-4c5a-adbb-1c80a0f545b1';
$policy_id = $policy_id ? $policy_id : 4687;
$payload = [
'resource' => [
// 'dashboard' => 1
'dashboard' => 2
],
'exp' => time() + (10 * 60), // 10 minutes
];
if(!empty($policy_id)){
$payload['params'] = (object)['client_policy' => $policy_id]; // MUST be object for Metabase
}else{
$payload['params'] = (object)[]; // MUST be object for Metabase
}
// dd($payload);
$token = JWT::encode($payload, $METABASE_SECRET_KEY, 'HS256');
// // You can either return token only
// return $this->response->setJSON([
// 'token' => $token,
// 'iframe_url' => "https://your-metabase-domain/embed/dashboard/{$token}#bordered=true&titled=true"
// ]);
if($this->request->getGet('api') == 1)
{
return $this->respond([
'status' => 'success',
'message' => 'Form data received successfully!',
'data' => [
'metabaseToken' => $token,
'metabaseUrl' => 'https://nsights.nhanceindia.in']
]);
}
return view('apache_dashboard_demo_one', [
'metabaseToken' => $token,
'metabaseUrl' => 'https://nsights.nhanceindia.in',
]);
}
public function testingquerys()
{
$calendar = new \App\Libraries\GoogleCalendarService();

View File

@ -183,12 +183,24 @@ use App\Models\JobModel;
class MailHelper
{
private const SYSTEM_EMAIL_FOOTER = '<div style="
text-align:center;
font-size:9px;
color:#999999;
border-top:1px solid #eeeeee;
margin-top:2px;
padding-top:1px;
line-height:1;
">
This is a system-generated email. Please do not reply.
</div>';
public static function send_email_smtp($params)
{
$myLogger = \Config\Services::mylogger();
$emaill = $params['mail'];
$subject = $params['subject'];
$message = $params['message'];
$message .= self::SYSTEM_EMAIL_FOOTER;
if (isset($params['bcc'])) {
$bcc = $params['bcc'];
} else {
@ -206,7 +218,8 @@ class MailHelper
$curl = curl_init();
$postData = [
'from' => [
'address' => $from_address
'address' => $from_address,
'name' => 'Nhance India Insurance'
],
'to' => [
[
@ -315,6 +328,9 @@ class MailHelper
$subject = $params['subject'];
$message = $params['message'];
$message .= self::SYSTEM_EMAIL_FOOTER;
// echo $message;die;
$attachments = isset($params['attachments']) ? $params['attachments'] : [];
$common = isset($params['common']) ? $params['common'] : '';
$bcc = isset($params['bcc']) ? $params['bcc'] : '';
@ -328,7 +344,8 @@ class MailHelper
$postData = [
'from' => [
'address' => $from_address
'address' => $from_address,
'name' => "Nhance India Insurance"
],
'to' => $emails,
'subject' => $subject,

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,113 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Claims Overview</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: sans-serif; background: #f5f5f5; }
#dashboard-container {
width: 100%;
height: 100vh;
}
#dashboard-container iframe {
width: 100%;
height: 100%;
border: none;
}
#error-msg {
display: none;
padding: 2rem;
color: #c0392b;
font-size: 14px;
text-align: center;
}
</style>
</head>
<body>
<div id="dashboard-container"></div>
<iframe src="https://venbait.in/chartBoard/public/share/8e130e4faa821740183feaa805f3ba0c7935841a64c5461ba6ed255f5b419f93?embed=1" width="1200" height="800" style="border:0;" loading="lazy" title="Chart-Board"></iframe>
<div id="error-msg"></div>
<script src="https://unpkg.com/@superset-ui/embedded-sdk"></script>
<script>
const SUPERSET_DOMAIN = "https://demo.venbait.in";
const DASHBOARD_ID = "aaff42c8-1d7a-4e28-8beb-f6a7b9e08661";
const USERNAME = "admin";
const PASSWORD = "$tr0n9pa55w0rd ";
async function getGuestToken() {
// Step 1: Login to get access token
const loginRes = await fetch(SUPERSET_DOMAIN + "/api/v1/security/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
username: USERNAME,
password: PASSWORD,
provider: "db",
refresh: true
})
});
if (!loginRes.ok) throw new Error("Login failed: " + loginRes.status);
const { access_token } = await loginRes.json();
// Step 2: Get CSRF token
const csrfRes = await fetch(SUPERSET_DOMAIN + "/api/v1/security/csrf_token/", {
method: "GET",
headers: { "Authorization": "Bearer " + access_token }
});
if (!csrfRes.ok) throw new Error("CSRF fetch failed: " + csrfRes.status);
const { result: csrf_token } = await csrfRes.json();
// Step 3: Get guest token
const guestRes = await fetch(SUPERSET_DOMAIN + "/api/v1/security/guest_token/", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + access_token,
"X-CSRFToken": csrf_token
},
body: JSON.stringify({
resources: [{ type: "dashboard", id: DASHBOARD_ID }],
rls: [],
user: { username: "guest", first_name: "Guest", last_name: "User" }
})
});
if (!guestRes.ok) throw new Error("Guest token failed: " + guestRes.status);
const { token } = await guestRes.json();
return token;
}
async function init() {
alert();
return true;
try {
await supersetEmbeddedSdk.embedDashboard({
id: DASHBOARD_ID,
supersetDomain: SUPERSET_DOMAIN,
mountPoint: document.getElementById("dashboard-container"),
fetchGuestToken: () => getGuestToken(),
dashboardUiConfig: {
hideTitle: true,
filters: { expanded: true }
}
});
} catch (err) {
const el = document.getElementById("error-msg");
el.style.display = "block";
el.textContent = "Error loading dashboard: " + err.message;
console.error(err);
}
}
init();
</script>
</body>
</html>

View File

@ -34,7 +34,7 @@ if (!empty($batch_list) && is_array($batch_list)) {
$countStr = ($file['count'] ?? null) === null ? '-' : (string) $file['count'];
$batch_col_max_len[9] = max($batch_col_max_len[9], mb_strlen($countStr));
$batch_col_max_len[10] = max($batch_col_max_len[10], mb_strlen((string) format_indian_number($file['amount'])));
$userTime = change_date_format($file['created_at'] ?? '', 'Y-m-d H:i:s', 'd M Y h:i a')
$userTime = change_date_format($file['created_at'] ?? '', 'Y-m-d H:i:s', 'd/m/Y h:i a')
. ' by '
. get_username($file['created_by'] ?? '');
$batch_col_max_len[11] = max($batch_col_max_len[11], mb_strlen($userTime));
@ -350,7 +350,7 @@ for ($i = 0; $i < $batch_col_count; $i++) {
<td><?php echo format_indian_number($file['amount'])?></td>
<td class="reload">
<?php echo change_date_format($file['created_at'],'Y-m-d H:i:s', 'd M Y h:i a') ?> by <?php echo get_username($file['created_by']) ?>
<?php echo change_date_format($file['created_at'],'Y-m-d H:i:s', 'd/m/Y h:i a') ?> by <?php echo get_username($file['created_by']) ?>
</td>

View File

@ -49,7 +49,7 @@
<td style="overflow: hidden;" class="reload truncate" data-toggle="tooltip" data-placement="top" title="<?php echo $file['file_name'] ?>">
<?php echo $file['file_name'] ?>
</td>
<td><?php echo change_date_format($file['created_at'], 'Y-m-d H:i:s', 'd M Y h:i A') . ' by <strong>' . $file['user_name'] . '</strong>' ?> </td>
<td><?php echo change_date_format($file['created_at'], 'Y-m-d H:i:s', 'd/m/Y h:i A') . ' by <strong>' . $file['user_name'] . '</strong>' ?> </td>
<td>
<?php if ($file['status'] == "failed") { ?>
<span> <?= $file['status'] ?> </span>

View File

@ -107,13 +107,50 @@
var isCdMasterPage = <?php echo isset($CD_Master_Data) ? 'true' : 'false'; ?>;
console.log("isCdMasterPage", isCdMasterPage);
function formatCdOpeningDateForInput(inputDate) {
if (!inputDate || String(inputDate).trim() === '') {
return '';
}
var str = String(inputDate).trim();
var iso = str.match(/^(\d{4})-(\d{2})-(\d{2})/);
if (iso) {
return iso[3] + '/' + iso[2] + '/' + iso[1];
}
var dmy = str.match(/^(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})$/);
if (dmy) {
var day = ('0' + dmy[1]).slice(-2);
var month = ('0' + dmy[2]).slice(-2);
return day + '/' + month + '/' + dmy[3];
}
return str;
}
function cdOpeningDateForSubmit(inputDate) {
var formatted = formatCdOpeningDateForInput(inputDate);
if (!formatted) {
return inputDate || '';
}
var parts = formatted.split('/');
return parts[0] + '-' + parts[1] + '-' + parts[2];
}
var openingDatePicker;
$(document).ready(function(){
var openingDatePicker = flatpickr("#opening_date", {
dateFormat: "d-m-Y",
openingDatePicker = flatpickr("#opening_date", {
dateFormat: "d/m/Y",
allowInput: false
});
$('#con-close-modal').on('shown.bs.modal', function() {
var val = $('#opening_date').val();
if (val) {
var formatted = formatCdOpeningDateForInput(val);
openingDatePicker.setDate(formatted, false);
}
});
if(isCdMasterPage == true){
$('#cd_client_id').select2();
$('#insurer_id_for_cd').select2();
@ -172,6 +209,10 @@
}
let formData = new FormData($('#CDMasterForm')[0]);
var openingDate = formData.get('opening_date');
if (openingDate) {
formData.set('opening_date', cdOpeningDateForSubmit(openingDate));
}
console.log("formData", formData);
let url = '<?= base_url('master/cash_deposite/create') ?>';

View File

@ -15,12 +15,12 @@ foreach ($CD_Master_Data as $index => $row) {
$cdm_col_max_len[1] = max($cdm_col_max_len[1], mb_strlen($clientCell));
$cdm_col_max_len[2] = max($cdm_col_max_len[2], mb_strlen((string) ($row['insurer_name'] ?? '')));
$cdm_col_max_len[3] = max($cdm_col_max_len[3], mb_strlen((string) ($row['insurer_branch_name'] ?? '')));
$od = ! empty($row['opening_date']) ? date('d-m-Y', strtotime((string) $row['opening_date'])) : '';
$od = ! empty($row['opening_date']) ? date('d/m/Y', strtotime((string) $row['opening_date'])) : '';
$cdm_col_max_len[4] = max($cdm_col_max_len[4], mb_strlen($od));
$cdm_col_max_len[5] = max($cdm_col_max_len[5], mb_strlen((string) ($row['cd_ac_no'] ?? '')));
$cdm_col_max_len[6] = max($cdm_col_max_len[6], mb_strlen((string) ($row['opening_bal'] ?? '')));
$du = ! empty($row['created_at'])
? (date('d-M-Y h:i A', strtotime((string) $row['created_at'])) . ' by ' . ($row['user_name'] ?? ''))
? (date('d/m/Y h:i A', strtotime((string) $row['created_at'])) . ' by ' . ($row['user_name'] ?? ''))
: '';
$cdm_col_max_len[7] = max($cdm_col_max_len[7], mb_strlen($du));
$cdm_col_max_len[8] = max($cdm_col_max_len[8], 4);
@ -118,10 +118,10 @@ $cdm_col_width_px = nhance_dt_column_widths_px($cdm_header_labels, $cdm_col_max_
<td><?php echo $row['client_name']; ?>( <?= $row['short_name'] ?> )</td>
<td><?php echo $row['insurer_name']; ?></td>
<td><?php echo $row['insurer_branch_name']; ?></td>
<td><?php echo date('d-m-Y', strtotime($row['opening_date'])); ?></td>
<td><?php echo date('d/m/Y', strtotime($row['opening_date'])); ?></td>
<td><?php echo $row['cd_ac_no']; ?></td>
<td><?php echo $row['opening_bal']; ?></td>
<td><?php echo date('d-M-Y h:i A', strtotime($row['created_at'])) ?> <br>by <?php echo $row['user_name']; ?></td>
<td><?php echo date('d/m/Y h:i A', strtotime($row['created_at'])) ?> <br>by <?php echo $row['user_name']; ?></td>
<td class="text-center table-action-cell">
<div class="btn-group dropdown">
<a href="javascript: void(0);"class="dropdown-toggle arrow-none btn btn-light btn-sm" data-toggle="dropdown" aria-expanded="false"><i class="mdi mdi-dots-horizontal"></i></a>

View File

@ -161,7 +161,7 @@
<td style="overflow: hidden;" class="reload truncate" data-toggle="tooltip" data-placement="top" title="<?php echo $file['file_name'] ?>">
<?php echo $file['file_name'] ?>
</td>
<td><?php echo change_date_format($file['created_at'], 'Y-m-d H:i:s', 'd M Y h:i A') . ' by <strong>' . $file['user_name'] . '</strong>' ?> </td>
<td><?php echo change_date_format($file['created_at'], 'Y-m-d H:i:s', 'd/m/Y h:i A') . ' by <strong>' . $file['user_name'] . '</strong>' ?> </td>
<td>
<?php if ($file['status'] == "failed") { ?>
<span style="color : #BD0707 ;"> <?= $file['status'] ?> </span>
@ -262,7 +262,7 @@
<label for="tpa">TPA<span id="tpa_danger" class="text-danger"></span></label>
<select class="form-control readonly-select" id="tpa_id" name="tpa_id">
<option value="">Select TPA</option>
<?php foreach ($tpa_list as $value) { ?>
<?php foreach ($tpa_list ?? [] as $value) { ?>
<option value="<?= $value['id'] ?>"><?= $value['short_name'] ?></option>
<?php } ?>
</select>

View File

@ -0,0 +1,103 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Claims Collection V2 Dashboard</title>
<style>
* { box-sizing: border-box; }
body { font-family: system-ui, sans-serif; margin: 0; padding: 1.5rem; background: #f0f2f5; color: #1a1a1a; }
h1 { font-size: 1.35rem; margin: 0 0 1rem; }
.toolbar { display: flex; flex-wrap: wrap; gap: 0.75rem; align-items: center; margin-bottom: 1.25rem; }
.toolbar input { padding: 0.45rem 0.6rem; border: 1px solid #ccc; border-radius: 6px; width: 140px; }
.toolbar button { padding: 0.5rem 1rem; border: none; border-radius: 6px; background: #2563eb; color: #fff; cursor: pointer; }
.toolbar button.secondary { background: #64748b; }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 1rem; }
.card { background: #fff; border-radius: 8px; padding: 1rem; box-shadow: 0 1px 3px rgba(0,0,0,.08); }
.card h2 { font-size: 0.85rem; margin: 0 0 0.5rem; color: #475569; font-weight: 600; }
.card pre { font-size: 0.72rem; margin: 0; max-height: 200px; overflow: auto; background: #f8fafc; padding: 0.5rem; border-radius: 4px; white-space: pre-wrap; word-break: break-word; }
.card .status { font-size: 0.75rem; color: #94a3b8; margin-bottom: 0.35rem; }
.card.loading pre { color: #94a3b8; }
.card.error pre { color: #b91c1c; }
</style>
</head>
<body>
<h1>Claims Collection V2</h1>
<div class="toolbar">
<label>Policy ID <input type="number" id="policy-id" value="<?= (int) $policy_id ?>" min="1"></label>
<button type="button" id="btn-load-all">Load all KPIs</button>
<button type="button" class="secondary" id="btn-clear">Clear</button>
</div>
<div class="grid" id="kpi-grid">
<?php foreach ($kpi_map as $metabaseId => $method): ?>
<div class="card" id="card-<?= esc($method) ?>" data-kpi="<?= esc($method) ?>">
<div class="status">#<?= (int) $metabaseId ?> · <?= esc($kpi_labels[$method] ?? $method) ?></div>
<h2><?= esc($method) ?></h2>
<pre>Click “Load all KPIs” or open single KPI API.</pre>
</div>
<?php endforeach; ?>
</div>
<script>
(function () {
const baseUrl = <?= json_encode(rtrim(base_url(), '/')) ?>;
const policyInput = document.getElementById('policy-id');
const grid = document.getElementById('kpi-grid');
function setCardState(method, state, text) {
const card = document.getElementById('card-' + method);
if (!card) return;
card.classList.remove('loading', 'error');
if (state) card.classList.add(state);
card.querySelector('pre').textContent = text;
}
async function loadAll() {
const policyId = policyInput.value;
if (!policyId) {
alert('Enter a policy ID');
return;
}
grid.querySelectorAll('.card').forEach(function (c) {
c.classList.add('loading');
c.querySelector('pre').textContent = 'Loading…';
});
try {
const apiAllUrl = <?= json_encode($api_all_url ?? base_url('util/claims-collection-v2/all')) ?>;
const res = await fetch(apiAllUrl + '?client_policy=' + encodeURIComponent(policyId));
const json = await res.json();
if (!json.status) {
throw new Error(json.message || 'Request failed');
}
Object.keys(json.data || {}).forEach(function (method) {
const block = json.data[method];
setCardState(method, '', JSON.stringify(block.rows, null, 2));
});
} catch (e) {
grid.querySelectorAll('.card').forEach(function (c) {
c.classList.remove('loading');
c.classList.add('error');
c.querySelector('pre').textContent = e.message;
});
} finally {
grid.querySelectorAll('.card.loading').forEach(function (c) {
c.classList.remove('loading');
});
}
}
document.getElementById('btn-load-all').addEventListener('click', loadAll);
document.getElementById('btn-clear').addEventListener('click', function () {
grid.querySelectorAll('.card').forEach(function (c) {
c.classList.remove('error');
c.querySelector('pre').textContent = '—';
});
});
})();
</script>
</body>
</html>

View File

@ -209,7 +209,7 @@ input:checked + .slider_blue::before {
data-parsley-pattern="^[1-9][0-9]*$"
data-parsley-pattern-message="Please select a valid Policy Type.">
<option value="0">Select Policy Type</option>
<?php foreach ($policy_types as $value) { ?>
<?php foreach ($policy_types ?? [] as $value) { ?>
<option value="<?= $value['id']?>"><?= $value['policy_type'] ?></option>
<?php } ?>
</select>
@ -230,7 +230,7 @@ input:checked + .slider_blue::before {
<label for="insurer">Insurer<span class="text-danger">*</span></label>
<select class="form-control" id="insurer" name="insurer" onchange="setInsuerAndBranchValue(this)" required>
<option value="">Select Insurer</option>
<?php foreach ($insurer as $value) { ?>
<?php foreach ($insurer ?? [] as $value) { ?>
<option data-id="<?= $value['insurer_id']?>" value="<?= $value['id'] . '-' . $value['insurer_id'] ?>">
<?= $value['insurer_name'] . '-' . $value['branch_code'] ?></option>
<?php } ?>
@ -241,7 +241,7 @@ input:checked + .slider_blue::before {
<label for="tpa">TPA<span id="tpa_danger" class="text-danger">*</span></label>
<select class="form-control" id="tpa" name="tpa" required>
<option value="">Select TPA</option>
<?php foreach ($tpa as $value) { ?>
<?php foreach ($tpa ?? [] as $value) { ?>
<option value="<?= $value['id'] . '-' . $value['tpa_id'] ?>">
<?= $value['tpa_short_name'] . '-' . $value['branch_code'] ?></option>
<?php } ?>
@ -454,7 +454,7 @@ input:checked + .slider_blue::before {
const showExpired = $('#chk-show-expired').is(':checked');
var startDatePicker = flatpickr("#start_date", {
dateFormat: "d-m-Y",
dateFormat: "d/m/Y",
defaultDate: today,
allowInput: false,
onChange: function(selectedDates, dateStr, instance) {
@ -467,7 +467,7 @@ input:checked + .slider_blue::before {
// Initialize Flatpickr for the start date with today's date
var openDatePicker = flatpickr("#open_date", {
dateFormat: "d-m-Y",
dateFormat: "d/m/Y",
defaultDate: today,
allowInput: false,
});
@ -478,14 +478,14 @@ input:checked + .slider_blue::before {
closeDate.setDate(closeDate.getDate() - 1); // Set end date to last day of next year
var endDatePicker = flatpickr("#end_date", {
dateFormat: "d-m-Y",
dateFormat: "d/m/Y",
defaultDate: closeDate,
allowInput: false
});
// Initialize Flatpickr for the end date with the calculated end date
var closeDatePicker = flatpickr("#close_date", {
dateFormat: "d-m-Y",
dateFormat: "d/m/Y",
defaultDate: today,
allowInput: false
});
@ -566,7 +566,7 @@ input:checked + .slider_blue::before {
<td>${policy_name_data}</td>
<td>${item.branch_name ? item.branch_name : ' - '}</td>
<td>${tpaValue}</td>
<td>${(item.policy_start_date)} / ${(item.policy_end_date)}</td>
<td>${formatPolicyDisplayDate(item.policy_start_date)} - ${formatPolicyDisplayDate(item.policy_end_date)}</td>
<td>${checkDateStatus(item.policy_end_date, 1)}</td>
<td>
@ -751,6 +751,12 @@ input:checked + .slider_blue::before {
$('.loader-mask').fadeIn();
var formData = new FormData($('#policy_form')[0]);
['policy_start_date', 'policy_end_date', 'open_date', 'close_date'].forEach(function(fieldName) {
var val = formData.get(fieldName);
if (val) {
formData.set(fieldName, policyFormDateForSubmit(val));
}
});
var policy_form_action = $('#policy_form_action').val();
console.log(formData+'form data');
$.ajax({
@ -853,7 +859,7 @@ input:checked + .slider_blue::before {
<td>${item.branch_name ? item.branch_name : ' - '}</td>
<td>${tpaValue}</td>
<td>${(item.policy_start_date)} / ${(item.policy_end_date)}</td>
<td>${formatPolicyDisplayDate(item.policy_start_date)} - ${formatPolicyDisplayDate(item.policy_end_date)}</td>
<td>${checkDateStatus(item.policy_end_date, 1)}</td>
<td>
<div class="btn-group dropdown">
@ -1512,31 +1518,74 @@ input:checked + .slider_blue::before {
});
//for date convert to indian formate like this 'yyyy-mm-dd' to this 'dd-mm-yyyy'
function rearrangeDateFormat(inputDate) {
console.log('inputDate', inputDate)
// Check if inputDate is a string and not empty
if (typeof inputDate === 'string' && inputDate.trim() !== '') {
var dateComponents = inputDate.split("-");
// Check if dateComponents has the expected number of parts
if (dateComponents.length === 3) {
var rearrangedDate = dateComponents[2] + "-" + dateComponents[1] + "-" + dateComponents[0];
return rearrangedDate;
} else {
// Handle unexpected date format
return '';
}
} else {
// Handle the case where inputDate is not a valid string
return '';
function parsePolicyDate(inputDate) {
if (!inputDate || (typeof inputDate === 'string' && inputDate.trim() === '')) {
return null;
}
var str = String(inputDate).trim();
var dmyMon = str.match(/^(\d{1,2})\/([A-Za-z]{3})\/(\d{4})$/i);
if (dmyMon) {
return new Date(str);
}
var dmy = str.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
if (dmy) {
return new Date(parseInt(dmy[3], 10), parseInt(dmy[2], 10) - 1, parseInt(dmy[1], 10));
}
var iso = str.match(/^(\d{4})-(\d{2})-(\d{2})/);
if (iso) {
return new Date(parseInt(iso[1], 10), parseInt(iso[2], 10) - 1, parseInt(iso[3], 10));
}
var dmyDash = str.match(/^(\d{1,2})-([A-Za-z]{3}|\d{1,2})-(\d{4})$/i);
if (dmyDash) {
if (/^[A-Za-z]{3}$/i.test(dmyDash[2])) {
return new Date(str);
}
return new Date(parseInt(dmyDash[3], 10), parseInt(dmyDash[2], 10) - 1, parseInt(dmyDash[1], 10));
}
var parsed = new Date(str);
return isNaN(parsed.getTime()) ? null : parsed;
}
var policyMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
function formatPolicyDisplayDate(inputDate) {
var d = parsePolicyDate(inputDate);
if (!d) {
return (inputDate && String(inputDate).trim() !== '') ? String(inputDate) : '';
}
return d.getDate() + '/' + policyMonthNames[d.getMonth()] + '/' + d.getFullYear();
}
function formatPolicyFormDate(inputDate) {
var d = parsePolicyDate(inputDate);
if (!d) {
return (inputDate && String(inputDate).trim() !== '') ? String(inputDate) : '';
}
var day = ('0' + d.getDate()).slice(-2);
var month = ('0' + (d.getMonth() + 1)).slice(-2);
return day + '/' + month + '/' + d.getFullYear();
}
function policyFormDateForSubmit(inputDate) {
var formatted = formatPolicyFormDate(inputDate);
if (!formatted) {
return inputDate || '';
}
var parts = formatted.split('/');
return parts[0] + '-' + parts[1] + '-' + parts[2];
}
// Convert API/storage dates to d/m/Y for form inputs
function rearrangeDateFormat(inputDate) {
return formatPolicyFormDate(inputDate);
}
function checkDateStatus(inputDate, bg = false) {
var givenDate = new Date(inputDate);
var givenDate = parsePolicyDate(inputDate);
if (!givenDate) {
return bg ? '' : '';
}
var currentDate = new Date();
if (bg != false) {
@ -2763,7 +2812,7 @@ $(document).ready(function () {
<td>${policy_name_data}</td>
<td>${item.branch_name ? item.branch_name : ' - '}</td>
<td>${tpaValue}</td>
<td>${(item.policy_start_date)} / ${(item.policy_end_date)}</td>
<td>${formatPolicyDisplayDate(item.policy_start_date)} - ${formatPolicyDisplayDate(item.policy_end_date)}</td>
<td>${checkDateStatus(item.policy_end_date, 1)}</td>
<td>
@ -2809,7 +2858,7 @@ $(document).ready(function () {
<td>${policy_name_data}</td>
<td>${item.branch_name ? item.branch_name : ' - '}</td>
<td>${tpaValue}</td>
<td>${(item.policy_start_date)} / ${(item.policy_end_date)}</td>
<td>${formatPolicyDisplayDate(item.policy_start_date)} - ${formatPolicyDisplayDate(item.policy_end_date)}</td>
<td>${checkDateStatus(item.policy_end_date, 1)}</td>
<td>

View File

@ -182,7 +182,7 @@
<td><?php echo ucfirst($row['department']) ?> </td>
<td><?php echo $row['rules_count'] ?></td>
<td><?php echo ucfirst($row['file_status']) ?> </td>
<td><?php echo change_date_format($row['created_at'],'Y-m-d H:i:s', 'd M Y h:i A') . ' by <strong>' . $row['created_user_name'] . '</strong>' ?>
<td><?php echo change_date_format($row['created_at'],'Y-m-d H:i:s', 'd/m/Y h:i A') . ' by <strong>' . $row['created_user_name'] . '</strong>' ?>
<td>
<div class="btn-group dropdown">
<a href="javascript: void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm" data-toggle="dropdown" aria-expanded="false"><i class="mdi mdi-dots-horizontal"></i></a>

View File

@ -252,7 +252,7 @@ $ex_col_width_px = nhance_dt_column_widths_px($ex_header_labels, $ex_col_max_len
<td><?= number_format((float) ($row['amount'] ?? 0), 2); ?></td>
<td>
<?php if (! empty($row['expense_date'])): ?>
<?= date('d-m-Y', strtotime($row['expense_date'])); ?>
<?= date('d/m/Y', strtotime($row['expense_date'])); ?>
<?php endif; ?>
</td>
<td>

View File

@ -23,7 +23,7 @@ if (!empty($fileList) && is_array($fileList)) {
);
$fl_col_max_len[4] = max($fl_col_max_len[4], mb_strlen($policy_display));
$fl_col_max_len[5] = max($fl_col_max_len[5], mb_strlen((string) ($file['action'] ?? '')));
$userTime = change_date_format($file['created_at'] ?? '', 'Y-m-d H:i:s', 'd M Y h:i a')
$userTime = change_date_format($file['created_at'] ?? '', 'Y-m-d H:i:s', 'd/m/Y h:i a')
. ' by '
. ($file['first_name'] ?? '');
$fl_col_max_len[6] = max($fl_col_max_len[6], mb_strlen($userTime));
@ -203,7 +203,7 @@ $fl_col_width_px = nhance_dt_column_widths_px($fl_header_labels, $fl_col_max_len
<!-- <td><?php echo isset($file['policy_name']) ? $file['policy_name'] : '' ?> - <?php echo isset($file['policy_no']) ? $file['policy_no'] : '' ?> - <?php echo isset($file['policy_type']) ? $file['policy_type'] : '' ?></td> -->
<td><?php echo isset($file['policy_type']) ? $file['policy_type'] : '' ?> - <?php echo isset($file['policy_no']) ? $file['policy_no'] : '' ?></td>
<td><?php echo $file['action'] ?></td>
<td><?php echo change_date_format($file['created_at'],'Y-m-d H:i:s', 'd M Y h:i a') . ' by <strong>' . $file['first_name'] . '</strong>' ?>
<td><?php echo change_date_format($file['created_at'],'Y-m-d H:i:s', 'd/m/Y h:i a') . ' by <strong>' . $file['first_name'] . '</strong>' ?>
</td>
<td>
<?php

View File

@ -255,7 +255,7 @@ $hr_col_width_px = nhance_dt_column_widths_px($hr_header_labels, $hr_col_max_len
<td><?php echo $file['branch_name'] ?></td>
<td><?php echo $file['policy_no'] ?></td>
<td><?php echo $file['file_action'] ?></td>
<td><?php echo change_date_format($file['created_at'],'Y-m-d H:i:s', 'd M Y h:i A') . ' by <strong>' . $file['first_name'] . '</strong>' ?></td>
<td><?php echo change_date_format($file['created_at'],'Y-m-d H:i:s', 'd/m/Y h:i A') . ' by <strong>' . $file['first_name'] . '</strong>' ?></td>
<td><?php echo $file['status']; ?> </td>
<td> </td>
</tr>

View File

@ -64,7 +64,7 @@
<td><?= $row['nhance_claim_ref_no'] ?: 'N/A'; ?></td>
<td><?= $row['short_name'] ?: ($row['client_name'] ?? 'N/A'); ?></td>
<td><?= $row['insurer_short_name'] ?: ($row['insurer_name'] ?: 'N/A'); ?></td>
<td><?= !empty($row['loss_date']) ? date('d-m-Y', strtotime($row['loss_date'])) : 'N/A'; ?></td>
<td><?= !empty($row['loss_date']) ? date('d/m/Y', strtotime($row['loss_date'])) : 'N/A'; ?></td>
<td><?= $row['nature_of_loss'] ?: 'N/A'; ?></td>
<td style="display:none;"><?= $row['acm_name'] ?? ''; ?></td>

View File

@ -181,7 +181,7 @@
}
</style>
<script src="<?= base_url('public/assets/js/pages/policy_transaction_endorsement_form_validation.js') ?>"></script>
<script src="<?= base_url('public/assets/js/pages/policy_transaction_endorsement_form_validation.js') ?>?v=20260529"></script>
<div class="tab-pane fade active show" id="form">
<div class="row" id="endorsement_form">
@ -297,7 +297,7 @@
<div class="form-group col-md-3">
<label for="addon_policy">Policy No<span id="base_danger"class="text-danger"></span></label>
<input type="text" class="form-control" id="policy_no" name="policy_no"placeholder="Enter Policy No" readonly>
<input type="text" class="form-control" id="policy_no" name="policy_no" placeholder="Enter Policy No" readonly data-parsley-validate="false" data-parsley-exclude-charset="true">
</div>
<div class="form-group col-md-3">
@ -326,7 +326,7 @@
<div class="form-group col-md-3">
<label for="addon_policy">Endorsement No<span id="base_danger" class="text-danger"></span></label>
<input type="text" class="form-control" id="endorsement_no" name="endorsement_no" placeholder="Enter Endorsement No" onchange="validateInput(this, 'policy_transaction', 'endorsement_no')">
<input type="text" class="form-control" id="endorsement_no" name="endorsement_no" placeholder="Enter Endorsement No" data-parsley-validate="false" data-parsley-exclude-charset="true">
</div>
<div class="form-group col-md-3">
@ -757,6 +757,9 @@
// console.log('tpa',tpa);
$('#policy_no').val(policy_no);
if (typeof window.clearEndorsementExcludedFieldsValidation === 'function') {
window.clearEndorsementExcludedFieldsValidation('#endorsement_form_id');
}
$('#insurer_id').val(insurer);
$('#tpa').val(tpa).change();
// $('#cd_ac_no').val(cd_ac_no);
@ -1206,6 +1209,9 @@
$('#policy_no').val(res.data.policy_no);
$('#action_type').val(res.data.action_type);
$('#endorsement_no').val(res.data.endorsement_no);
if (typeof window.clearEndorsementExcludedFieldsValidation === 'function') {
window.clearEndorsementExcludedFieldsValidation('#endorsement_form_id');
}
$('#data_received_date').val(res.data.data_received_date);
$('#policy_issue_date').val(res.data.policy_issue_date);
$('#emp_count').val(res.data.emp_count);

View File

@ -195,7 +195,7 @@
}
</style>
<script src="<?= base_url('public/assets/js/pages/policy_transaction_endorsement_form_validation.js') ?>"></script>
<script src="<?= base_url('public/assets/js/pages/policy_transaction_endorsement_form_validation.js') ?>?v=20260529"></script>
<div class="row" id="endorsement_form" style="display: none;">
<div class="col-12">
@ -310,7 +310,7 @@
<div class="form-group col-md-3">
<label for="addon_policy">Policy No<span id="base_danger"class="text-danger"></span></label>
<input type="text" class="form-control" id="policy_no" name="policy_no"placeholder="Enter Policy No" readonly>
<input type="text" class="form-control" id="policy_no" name="policy_no" placeholder="Enter Policy No" readonly data-parsley-validate="false" data-parsley-exclude-charset="true">
</div>
<div class="form-group col-md-3">
@ -339,7 +339,7 @@
<div class="form-group col-md-3">
<label for="addon_policy">Endorsement No<span id="base_danger" class="text-danger"></span></label>
<input type="text" class="form-control" id="endorsement_no" name="endorsement_no" placeholder="Enter Endorsement No" onchange="validateInput(this, 'policy_transaction', 'endorsement_no')">
<input type="text" class="form-control" id="endorsement_no" name="endorsement_no" placeholder="Enter Endorsement No" data-parsley-validate="false" data-parsley-exclude-charset="true">
</div>
<div class="form-group col-md-3">
@ -613,6 +613,9 @@
// console.log('tpa',tpa);
$('#policy_no').val(policy_no);
if (typeof window.clearEndorsementExcludedFieldsValidation === 'function') {
window.clearEndorsementExcludedFieldsValidation('#endorsement_form_id');
}
$('#insurer_id').val(insurer);
$('#tpa').val(tpa).change();
// $('#cd_ac_no').val(cd_ac_no);
@ -1037,6 +1040,9 @@
$('#policy_no').val(res.data.policy_no);
$('#action_type').val(res.data.action_type);
$('#endorsement_no').val(res.data.endorsement_no);
if (typeof window.clearEndorsementExcludedFieldsValidation === 'function') {
window.clearEndorsementExcludedFieldsValidation('#endorsement_form_id');
}
$('#data_received_date').val(res.data.data_received_date);
$('#policy_issue_date').val(res.data.policy_issue_date);
$('#emp_count').val(res.data.emp_count);

View File

@ -1,11 +1,14 @@
<style>
.table th,
.table td {
padding: 8px;
#scroll-horizontal-datatable thead th,
#scroll-horizontal-datatable tbody td {
padding: 4px 4px !important;
box-sizing: border-box;
}
table.dataTable tbody td {
#scroll-horizontal-datatable_wrapper .dataTables_scrollHead table thead th,
#scroll-horizontal-datatable_wrapper .dataTables_scrollBody table tbody td {
padding: 4px 4px !important;
box-sizing: border-box;
}
.col-12 {
@ -76,7 +79,7 @@ table.dataTable tbody td {
</div>
<div class="badge-container">
Total Policy Count: <span class="text-primary"><?= $policy_count ?></span>
Total Policy Count: <span class="text-primary"><?= $policy_count ?? 0 ?></span>
</div>
</div>
@ -111,7 +114,7 @@ table.dataTable tbody td {
<th style="display: none;">Total Premium</th>
<th>Agreed BP %</th>
<th>Agreed TP %</th>
<th style="display: true;">Rewards</th>
<th>Rewards</th>
<th>Agreed Amount</th>
<th>Invoiced Amount</th>
<th>Outstanding Amount</th>
@ -199,7 +202,7 @@ table.dataTable tbody td {
<td class="right-align-input" style="display: none;"><?php echo ($row['total_irda_amt'] != 0.00) ? ($row['total_premium'] ?: '0.00') : '0.00'; ?></td>
<td class="right-align-input"><?php echo ($row['total_irda_amt'] != 0.00) ? ($row['agreed_bp_per'] ?: '0.00') : '0.00'; ?>%</td>
<td class="right-align-input"><?php echo ($row['total_irda_amt'] != 0.00) ? ($row['agreed_tp_or_ter_per'] ?: '0.00') : '0.00'; ?>%</td>
<td class="right-align-input" style="display: true;"><?php echo isset($row['reward']) ? $row['reward'] : '0.00'; ?></td>
<td class="right-align-input"><?php echo isset($row['reward']) ? $row['reward'] : '0.00'; ?></td>
<?php
// Below Line its old version i am removed. reason no value ['total_irda_amt'] means taken as ['exp_amt'] so.
@ -335,8 +338,9 @@ $(document).ready(function() {
var ticketsTable = $('#scroll-horizontal-datatable');
if (ticketsTable.length) {
ticketsTable.DataTable({
scrollX: true,
nhanceListDataTableBeforeInit();
var nhBdsReportTable = ticketsTable.DataTable(nhanceMergeListDataTableOptions({
autoWidth: false,
// dom: "<'row'<'col-sm-6'f><'col-sm-6 text-right'B>>" + // Filter left, buttons right
// "<'row'<'col-sm-12'tr>>" +
// "<'row'<'col-sm-5'i><'col-sm-7'p>>", // Pagination at the bottom, without page length selector
@ -711,7 +715,9 @@ $(document).ready(function() {
// var totalUnbilled = getUniqueUnbilled(27);
// $('#total_unbilled').text(totalUnbilled.toFixed(2));
}
});
}));
nhanceListDataTableAfterInit();
nhanceListDataTableBindAdjust(nhBdsReportTable);
} else {
console.error("Table atet found.");
}

View File

@ -257,7 +257,7 @@ $ret_col_width_px = nhance_dt_column_widths_px($ret_header_labels, $ret_col_max_
<td><?php echo $employee['agent_name'] ?? 'N/A' ?></td>
<td><?php echo $employee['manager_name'] ?? 'N/A' ?></td>
<td><?php if (!empty($employee['created_at'])):
$cd = date("j F Y", strtotime($employee['created_at']));
$cd = date("j/F/Y", strtotime($employee['created_at']));
$ct = date("h:i A", strtotime($employee['created_at']));
echo $cd . "<br><span class='time'> " . $ct . "</span>";
endif; ?></td>

View File

@ -901,7 +901,7 @@ async function viewDetail(id) {
function renderCard(opps) {
const opp_cont = document.getElementById('opportunitiesContainer');
opp_cont.innerHTML = opps.length ? opps.map(o => {
let lead_type = o.lead_type == 1 ? 'EB' : 'Non-EB';
let lead_type = o.lead_form_type == 1 ? 'EB' : 'Non-EB';
let status = o.status?.toLowerCase();
let statusClass = {
won: 'status-text-won',

View File

@ -269,7 +269,7 @@ $gst_total = 0;
<td><?php echo $employee['emp_code']; ?></td>
<td><?php echo $employee['relationship']; ?></td>
<td><?php echo $employee['gender']; ?></td>
<td><?php echo date('d/M/Y', strtotime($employee['dob'])); ?></td>
<td><?php echo date('d/m/Y', strtotime($employee['dob'])); ?></td>
<?php /*
<!-- <td><?php //echo isset($employee['policy_type']) ? $employee['policy_type'] : ''; ?> - <?php echo isset($employee['policy_no']) ? $employee['policy_no'] : ''; ?></td>

View File

@ -188,7 +188,7 @@ beccause = dataTables_length and dataTables_paginate need in same line thats why
<td class="text-left"><?php echo $row['assignee_name'] ? $row['assignee_name'] : 'N/A'; ?></td>
<td class="text-left">
<?php if (!empty($row['created_at'])):
$cd = date("j M Y", strtotime($row['created_at']));
$cd = date("j/m/Y", strtotime($row['created_at']));
$ct = date("h:i A", strtotime($row['created_at']));
echo $cd . "<br><span class='time'> " . $ct . "</span>";
endif;
@ -196,7 +196,7 @@ beccause = dataTables_length and dataTables_paginate need in same line thats why
</td>
<td class="text-left">
<?php if (!empty($row['updated_at'])):
$ud = date("j M Y", strtotime($row['updated_at']));
$ud = date("j/m/Y", strtotime($row['updated_at']));
$ut = date("h:i A", strtotime($row['updated_at']));
echo $ud . "<br><span class='time'> " . $ut . "</span>";
endif;

View File

@ -80,7 +80,7 @@
var end = moment(end, 'DD/MM/YYYY');
function cb(start, end) {
$('#reportrange span').html(start.format('D-MM-YYYY') + ' - ' + end.format('D-MM-YYYY'));
$('#reportrange span').html(start.format('D/MM/YYYY') + ' - ' + end.format('D/MM/YYYY'));
$('#startDate').val(start.format('DD-MM-YYYY'));
$('#endDate').val(end.format('DD-MM-YYYY'));
}

View File

@ -1,12 +1,79 @@
<?php
helper('datatable_view');
$vd_header_labels = [
'Date', 'Record Date', 'Unit', 'Policy', 'Endorsement No', 'Sub Type',
'Credit', 'Debit', 'Balance', 'Description', 'User',
];
$vd_col_count = count($vd_header_labels);
$vd_col_max_len = array_fill(0, $vd_col_count, 0);
for ($i = 0; $i < $vd_col_count; $i++) {
$vd_col_max_len[$i] = mb_strlen($vd_header_labels[$i]);
}
$depositdata = $depositdata ?? [];
$subTypeOptions = $subTypeOptions ?? [];
foreach ($depositdata as $row) {
$vd_col_max_len[0] = max($vd_col_max_len[0], mb_strlen(date('d-M-Y h:i A', strtotime((string) $row->created_at))));
$rec = ! empty($row->record_date) ? date('d-M-Y', strtotime((string) $row->record_date)) : '-';
$vd_col_max_len[1] = max($vd_col_max_len[1], mb_strlen($rec));
$vd_col_max_len[2] = max($vd_col_max_len[2], mb_strlen(trim((string) ($row->unit ?? ' - '))));
$policyType = $row->policy_type ?? '';
$policyNo = $row->policy_no ?? '';
$policyCell = ($policyType || $policyNo) ? trim($policyType . ' - ' . $policyNo, ' -') : '-';
$vd_col_max_len[3] = max($vd_col_max_len[3], mb_strlen($policyCell));
$vd_col_max_len[4] = max($vd_col_max_len[4], mb_strlen(strip_tags((string) ($row->endorsement_no ?? '-'))));
$subLabel = isset($subTypeOptions[$row->sub_type]) ? (string) $subTypeOptions[$row->sub_type] : '';
$vd_col_max_len[5] = max($vd_col_max_len[5], mb_strlen($subLabel));
$credit = ($row->transaction_type ?? '') === 'Credit' ? (string) ($row->amount ?? '-') : '-';
$debit = ($row->transaction_type ?? '') === 'Debit' ? (string) ($row->amount ?? '-') : '-';
$vd_col_max_len[6] = max($vd_col_max_len[6], mb_strlen($credit));
$vd_col_max_len[7] = max($vd_col_max_len[7], mb_strlen($debit));
$vd_col_max_len[8] = max($vd_col_max_len[8], mb_strlen((string) ($row->balance ?? '')));
$vd_col_max_len[9] = max($vd_col_max_len[9], mb_strlen((string) ($row->description ?? '')));
$vd_col_max_len[10] = max($vd_col_max_len[10], mb_strlen((string) ($row->username ?? '')));
}
$vd_col_min_px = [120, 100, 72, 160, 110, 88, 88, 88, 100, 140, 100];
$vd_col_max_px = [200, 120, 120, 360, 160, 140, 120, 120, 140, 400, 200];
$vd_col_width_px = nhance_dt_column_widths_px($vd_header_labels, $vd_col_max_len, $vd_col_min_px, $vd_col_max_px);
?>
<style>
.table th,
.table td {
padding: 8px;
}
table.dataTable tbody td {
padding: 4px 4px !important;
}
<?php for ($i = 0; $i < $vd_col_count; $i++) : ?>
#scroll-horizontal-datatable_wrapper .dataTables_scrollHead table thead th:nth-child(<?= $i + 1 ?>),
#scroll-horizontal-datatable thead th:nth-child(<?= $i + 1 ?>) {
min-width: <?= (int) $vd_col_width_px[$i] ?>px;
width: <?= (int) $vd_col_width_px[$i] ?>px;
box-sizing: border-box;
vertical-align: middle;
overflow: visible !important;
}
#scroll-horizontal-datatable tbody td:nth-child(<?= $i + 1 ?>) {
width: <?= (int) $vd_col_width_px[$i] ?>px;
max-width: <?= (int) $vd_col_width_px[$i] ?>px;
min-width: <?= (int) $vd_col_width_px[$i] ?>px;
box-sizing: border-box;
vertical-align: middle;
}
<?php endfor; ?>
#scroll-horizontal-datatable tbody td {
padding: 5px 11px !important;
font-size: 13px;
line-height: 1.25;
overflow: hidden;
text-overflow: ellipsis;
}
#scroll-horizontal-datatable_wrapper .dataTables_scrollHead table thead th,
#scroll-horizontal-datatable thead th {
padding: 5px 11px !important;
font-size: 13px;
line-height: 1.25;
}
#scroll-horizontal-datatable_wrapper .dataTables_scrollHead table,
#scroll-horizontal-datatable_wrapper .dataTables_scrollBody table {
table-layout: fixed;
width: 100% !important;
}
#List-page .card-body > .table-responsive {
overflow-x: auto;
}
.deposit-header {
display: flex;
align-items: center;
@ -123,7 +190,7 @@
</div> -->
<div class="table-responsive">
<table data-custom-table-css="table" class="table mb-0 nowrap w-100 table-centered" cellspacing="0" id="scroll-horizontal-datatable">
<table data-custom-table-css="table" class="table mb-0 nowrap w-100" cellspacing="0" id="scroll-horizontal-datatable">
<thead class="bg-light">
<tr>
<th class="font-weight-medium">Date</th>
@ -154,11 +221,11 @@
if ($policyType || $policyNo) {
echo trim($policyType . ' - ' . $policyNo, ' -');
} else {
echo '<center> - </center>';
echo '-';
}
?>
</td>
<td><?php echo $row->endorsement_no ?? '<center> - </center>'; ?></td>
<td><?php echo $row->endorsement_no ?? '-'; ?></td>
<td><?php echo isset($subTypeOptions[$row->sub_type]) ? $subTypeOptions[$row->sub_type] : ''; ?>
</td>
<td><?php echo ($row->transaction_type == 'Credit') ? $row->amount : '-'; ?></td>
@ -304,8 +371,8 @@
allowInput: false,
});
$('#scroll-horizontal-datatable').DataTable({
scrollX: true,
nhanceListDataTableBeforeInit();
var vdDepositTable = $('#scroll-horizontal-datatable').DataTable(nhanceMergeListDataTableOptions({
// 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>>",
@ -400,8 +467,16 @@
emptyTable: '<div class="text-center text-muted">No Data found</div>'
},
ordering: false,
paging: true
});
paging: true,
autoWidth: false,
columnDefs: [
<?php for ($i = 0; $i < $vd_col_count; $i++) : ?>
{ targets: <?= $i ?>, width: '<?= (int) $vd_col_width_px[$i] ?>px' },
<?php endfor; ?>
],
}));
nhanceListDataTableAfterInit();
nhanceListDataTableBindAdjust(vdDepositTable);
});
</script>

262
hr-dashboard.md Normal file
View File

@ -0,0 +1,262 @@
# Claims Collection V2 — HR Dashboard API
**Created:** 2026-06-02
**Controller:** `App\Controllers\ClaimsCollectionV2DashboardController`
**Model:** `App\Models\ClaimsCollectionV2DashboardModel`
**Source queries:** `metabase_raw_queries.csv` → collection `Claims Collection V2`
**Base app URL (local):** `https://localhost/PHP828APPS/ruc/nhance/index.php`
---
## Overview
Each Metabase question in the CSV is a separate PHP method on the model.
The API exposes them in three ways:
| What | URL fragment | Use case |
|------|-------------|----------|
| **Single KPI** | `kpi/{slug or Metabase id}` | FE loads one card at a time |
| **All KPIs** | `all` | FE loads entire dashboard in one call |
| **Debug / preview** | `debug` / `preview` | Admin checks raw output in browser |
All endpoints require `client_policy` or `client_policy_id` as a query param
(or route segment for `debug/{id}` / `preview/{id}`).
---
## Route stacks
### 1. Admin — `authMVC` (session login required)
Prefix: `util/claims-collection-v2`
| Method | Path | Handler | Purpose |
|--------|------|---------|---------|
| GET | `util/claims-collection-v2/preview` | `::preview` | UI debug grid in browser |
| GET | `util/claims-collection-v2/preview/{policy_id}` | `::preview` | Same, policy in URL |
| GET | `util/claims-collection-v2/debug` | `::debug` | Raw JSON dump (all KPIs) |
| GET | `util/claims-collection-v2/debug/{policy_id}` | `::debug` | Same, policy in URL |
| GET | `util/claims-collection-v2/all` | `::all` | JSON — all 31 KPIs |
| GET | `util/claims-collection-v2/kpi/{slug\|id}` | `::kpi` | JSON — single KPI |
**Filters applied:** `authMVC`, `AclFilter`, `HttpRequestLog`, `Cors`, `SecurityInputFilter`
---
### 2. Frontend / HR App — `authJWT` (Bearer token required)
Prefix: `employeeRest/claims-collection-v2`
| Method | Path | Handler | Purpose |
|--------|------|---------|---------|
| GET | `employeeRest/claims-collection-v2/all` | `::all` | JSON — all 31 KPIs |
| GET | `employeeRest/claims-collection-v2/kpi/{slug\|id}` | `::kpi` | JSON — single KPI |
| GET | `employeeRest/claims-collection-v2/preview` | `::preview` | UI grid (FE debug) |
| GET | `employeeRest/claims-collection-v2/preview/{policy_id}` | `::preview` | Same, policy in URL |
| GET | `employeeRest/claims-collection-v2/debug` | `::debug` | Raw JSON (FE debug) |
| GET | `employeeRest/claims-collection-v2/debug/{policy_id}` | `::debug` | Same, policy in URL |
**Filters applied:** `GlobalPostFileUploadGuard`, `ratelimit`, `appSignature`, `authJWT`
---
## Parameters
| Param | Location | Type | Required | Notes |
|-------|----------|------|----------|-------|
| `client_policy` | query string | int | **Yes** (API) | Policy ID |
| `client_policy_id` | query string | int | **Yes** (API) | Alias for above |
| `{policy_id}` | URL segment | int | No | Only on `preview/{id}` and `debug/{id}`; falls back to 4687 if omitted |
| `{slug\|id}` | URL segment | string/int | Yes (kpi only) | KPI method slug OR Metabase question id |
> **Default policy ID (4687)** is only the method-signature default for `preview` and `debug`.
> Change it by passing the query param or URL segment — never hardcoded elsewhere.
---
## How to call — Admin (browser / Postman, session cookie)
Open in browser while logged in to admin:
```
# UI preview page (loads grid, click "Load all KPIs")
GET /index.php/util/claims-collection-v2/preview?client_policy=4687
# Preview with policy in URL
GET /index.php/util/claims-collection-v2/preview/4687
# Raw JSON — all 31 KPIs
GET /index.php/util/claims-collection-v2/debug?client_policy=4687
# Raw JSON — single KPI by slug
GET /index.php/util/claims-collection-v2/kpi/incurred_ratio?client_policy=4687
# Raw JSON — single KPI by Metabase question id
GET /index.php/util/claims-collection-v2/kpi/207?client_policy=4687
```
---
## How to call — Frontend / HR App (JWT)
```http
GET /index.php/employeeRest/claims-collection-v2/all?client_policy=4687
Authorization: Bearer <jwt_token>
X-App-Signature: <app_signature>
Content-Type: application/json
```
```http
GET /index.php/employeeRest/claims-collection-v2/kpi/incurred_ratio?client_policy=4687
Authorization: Bearer <jwt_token>
X-App-Signature: <app_signature>
```
```http
GET /index.php/employeeRest/claims-collection-v2/kpi/207?client_policy=4687
Authorization: Bearer <jwt_token>
X-App-Signature: <app_signature>
```
---
## Sample responses
### `kpi/{slug}` or `kpi/{id}`
```json
{
"status": true,
"policy_id": 4687,
"kpi_id": 207,
"kpi": "incurred_ratio",
"label": "Incurred Ratio",
"rows": [
{ "incurred_ratio": "72.34%" }
]
}
```
### `all`
```json
{
"status": true,
"policy_id": 4687,
"data": {
"policy_exposure_summary": {
"id": 181,
"label": "POLICY & EXPOSURE SUMMARY",
"rows": [
{
"policy_start_date": "2024-01-01",
"policy_end_date": "2024-12-31",
"insurer_name": "HDFC Ergo",
"tpa_name": "Medi Assist"
}
]
},
"incurred_ratio": {
"id": 207,
"label": "Incurred Ratio",
"rows": [{ "incurred_ratio": "72.34%" }]
}
}
}
```
### Error — missing policy id
```json
{
"status": false,
"message": "client_policy or client_policy_id is required."
}
```
**HTTP 422**
### Error — unknown KPI
```json
{
"status": false,
"message": "Unknown KPI. Pass Metabase id or method slug.",
"allowed": {
"181": "policy_exposure_summary",
"207": "incurred_ratio"
}
}
```
**HTTP 404**
---
## All 31 KPIs
| Metabase ID | Method slug | Label |
|-------------|-------------|-------|
| 181 | `policy_exposure_summary` | POLICY & EXPOSURE SUMMARY |
| 185 | `premium_as_on_date` | PREMIUM AS ON DATE |
| 186 | `claims_experience_summary` | CLAIMS EXPERIENCE SUMMARY |
| 190 | `claim_amount_by_gender` | Claim Amount by Gender |
| 191 | `age_band` | Age Band |
| 194 | `top_5_hospitals_by_incurred_amount` | Top 5 Hospitals by Incurred amount |
| 197 | `claims_incidence_rate` | Claims Incidence Rate |
| 198 | `policy_start_date` | Policy Start Date |
| 199 | `policy_end_date` | Policy End Date |
| 200 | `insurer` | Insurer |
| 201 | `tpa` | TPA |
| 203 | `earned_premium` | Earned Premium |
| 204 | `total_claims` | Total Claims |
| 206 | `incurred_amount` | Incurred Amount |
| 207 | `incurred_ratio` | Incurred Ratio |
| 208 | `projected_claims` | Projected Claims |
| 209 | `projected_ratio` | Projected Ratio |
| 213 | `total_reimbursement_amount` | Total Reimbursement Amount |
| 214 | `total_reimbursement_amt_pct` | Total Reimbursement Amt % |
| 215 | `cashless_claim_amt` | Cashless Claim Amt |
| 216 | `cashless_claim_amt_pct` | Cashless Claim Amt % |
| 217 | `total_incurred_by_city` | Total Incurred by city |
| 219 | `claim_amount_by_claim_status` | Claim Amount by Claim Status |
| 220 | `hospitals_in_detail` | Hospitals in detail |
| 221 | `hospital_city_wise_si_limit_pregnancy` | Hospital city wise SI Limit - Pregnancy |
| 224 | `s_pregnancy_normal_delivery_exceeded_amt` | S-PREGNANCY - NORMAL DELIVERY Exceeded Amt |
| 225 | `s_pregnancy_c_sec_avg_exceeded_amt` | S-Pregnancy C-Sec avg exceeded amt |
| 228 | `cataract_exceeded_claim_amount` | Cataract exceeded claim amount |
| 229 | `cataract_avg_exceeded_amount` | Cataract avg exceeded amount |
| 230 | `hospital_city_wise_si_limit_cataract` | Hospital city wise SI Limit - Cataract |
| 231 | `total_incurred_by_cliam_status` | Total Incurred by Cliam Status |
> **Note:** KPIs 214 and 216 were renamed from the auto-generated slug to avoid collision with 213 and 215.
---
## Files
| File | Purpose |
|------|---------|
| `app/Models/ClaimsCollectionV2DashboardModel.php` | 31 KPI query methods, `KPI_MAP`, `KPI_LABELS`, `getAllKpis()`, `getKpi()` |
| `app/Controllers/ClaimsCollectionV2DashboardController.php` | `kpi()`, `all()`, `preview()`, `debug()` |
| `app/Views/claims_collection_v2_dashboard.php` | Admin/FE debug preview UI (KPI card grid) |
| `app/Config/Routes.php` | Both route groups (search `claims-collection-v2`) |
| `tests/smoke_claims_collection_v2.php` | CLI smoke test — run: `php tests/smoke_claims_collection_v2.php 4687` |
| `metabase_raw_queries.csv` | Source of truth for all SQL queries |
---
## FE integration notes
- Call `all` once on dashboard mount; render each `data[method].rows` into its card.
- Call `kpi/{slug}` for lazy/on-demand loading of individual cards.
- `policy_id` should come from the HR session / selected policy context — never hardcoded.
- All rows are raw arrays; formatting (currency, %, dates) is already applied inside the SQL (`FORMAT()`, `CONCAT()`).
- `rows` may be empty `[]` if no claims exist for that policy — handle gracefully in UI.
---
## BE notes
- To add a new KPI: add an entry to `KPI_MAP` + `KPI_LABELS` in the model and write the corresponding method `public function my_kpi(int $policyId): array`.
- All queries use named binding `:policy_id:` (CodeIgniter style, replaces Metabase `{{policy_id}}`).
- Literal `\t` / `\n` in CSV SQL is normalized in `runKpiQuery()` — safe to re-generate from CSV.
- Run `php tests/smoke_claims_collection_v2.php {policy_id}` after any model change.

1048639
metabase_raw_queries.csv Normal file

File diff suppressed because it is too large Load Diff

View File

@ -47,12 +47,61 @@
return true;
}
function isExcludedCharsetField(el) {
if (!el) {
return false;
}
if ($(el).attr('data-parsley-exclude-charset') === 'true') {
return true;
}
var id = (el.id || '').toLowerCase();
var name = (el.name || '').toLowerCase();
return id === 'policy_no' || id === 'endorsement_no' ||
name === 'policy_no' || name === 'endorsement_no';
}
function clearExcludedFieldValidation($form) {
if (!$form || !$form.length) {
return;
}
$form.find('input, textarea, select').each(function () {
var el = this;
if (!isExcludedCharsetField(el)) {
return;
}
var $el = $(el);
$el.removeAttr('data-parsley-endorsementcharset');
$el.attr('data-parsley-validate', 'false');
$el.removeClass('parsley-error parsley-success');
$el.siblings('ul.parsley-errors-list').remove();
$el.closest('.form-group').find('ul.parsley-errors-list').remove();
if (typeof $el.parsley === 'function') {
try {
var fieldInstance = $el.parsley();
if (fieldInstance && typeof fieldInstance.reset === 'function') {
fieldInstance.reset();
}
if (fieldInstance && typeof fieldInstance.destroy === 'function') {
fieldInstance.destroy();
}
} catch (e) {
// no-op
}
}
});
refreshParsley($form);
}
function registerValidator() {
if (!isParsleyReady() || window.Parsley.__endorsementFormValidatorRegistered) {
return;
}
window.Parsley.addValidator('endorsementcharset', {
validateString: function (value) {
var el = this.$element && this.$element.length ? this.$element[0] : null;
if (isExcludedCharsetField(el)) {
return true;
}
if (!value || String(value).trim() === '') {
return true;
}
@ -85,6 +134,12 @@
return;
}
if (isExcludedCharsetField(el)) {
$el.removeAttr('data-parsley-endorsementcharset');
$el.attr('data-parsley-validate', 'false');
return;
}
if (isCharsetCandidate(el) || isDocumentNameField(el)) {
if (!$el.attr('data-parsley-endorsementcharset')) {
$el.attr('data-parsley-endorsementcharset', 'true');
@ -144,7 +199,7 @@
}
function validateField(field) {
if (!field || isSkippableField(field) || !isParsleyReady()) {
if (!field || isSkippableField(field) || isExcludedCharsetField(field) || !isParsleyReady()) {
return;
}
var $field = $(field);
@ -181,6 +236,7 @@
registerValidator();
applyConstraints($form);
clearExcludedFieldValidation($form);
refreshParsley($form);
stripParsleyFormSubmitHandlers($form);
@ -237,18 +293,14 @@
initWithRetry(40);
});
$(window).on('load', function () {
if (!isParsleyReady()) {
window.clearEndorsementExcludedFieldsValidation = function (formSelector) {
var sel = formSelector || '#endorsement_form_id';
var $form = $(sel);
if (!$form.length || !isParsleyReady()) {
return;
}
FORM_SELECTORS.forEach(function (selector) {
var $f = $(selector);
if ($f.length) {
refreshParsley($f);
stripParsleyFormSubmitHandlers($f);
}
});
});
clearExcludedFieldValidation($form);
};
window.refreshEndorsementFormValidation = function (formSelector) {
if (!formSelector || !isParsleyReady()) {
@ -271,12 +323,32 @@
stripOrphanParsleyUi($form);
$form.removeData(LIVE_VALIDATE_DATA);
try {
clearExcludedFieldValidation($form);
refreshParsley($form);
stripParsleyFormSubmitHandlers($form);
} catch (e2) {
// no-op
}
};
// form-validation.init.js binds all .parsley-examples after this script loads
$(window).on('load', function () {
window.setTimeout(function () {
if (!isParsleyReady()) {
return;
}
FORM_SELECTORS.forEach(function (selector) {
var $f = $(selector);
if (!$f.length) {
return;
}
applyConstraints($f);
clearExcludedFieldValidation($f);
refreshParsley($f);
stripParsleyFormSubmitHandlers($f);
});
}, 0);
});
})(function () {
return window.jQuery;
});

View File

@ -0,0 +1,156 @@
<?php
/**
* One-off smoke test: Claims Collection V2 dashboard.
* Run: php tests/smoke_claims_collection_v2.php [policy_id]
*/
declare(strict_types=1);
ob_start();
define('FCPATH', __DIR__ . '/../public/');
chdir(FCPATH);
require FCPATH . '../app/Config/Paths.php';
$paths = new Config\Paths();
require rtrim($paths->systemDirectory, '\\/ ') . DIRECTORY_SEPARATOR . 'bootstrap.php';
require_once SYSTEMPATH . 'Config/DotEnv.php';
(new CodeIgniter\Config\DotEnv(ROOTPATH))->load();
defined('ENVIRONMENT') || define('ENVIRONMENT', env('CI_ENVIRONMENT', 'development'));
$boot = APPPATH . 'Config/Boot/' . ENVIRONMENT . '.php';
if (is_file($boot)) {
require_once $boot;
}
// Load autoloaded services without full HTTP stack.
helper('url');
use App\Controllers\ClaimsCollectionV2DashboardController;
use App\Models\ClaimsCollectionV2DashboardModel;
use Config\Services;
$policyId = isset($argv[1]) ? (int) $argv[1] : 4687;
$pass = 0;
$fail = 0;
$results = [];
function ok(string $label, bool $cond, string $detail = ''): void
{
global $pass, $fail, $results;
if ($cond) {
$pass++;
$results[] = '[PASS] ' . $label . ($detail ? "{$detail}" : '');
} else {
$fail++;
$results[] = '[FAIL] ' . $label . ($detail ? "{$detail}" : '');
}
}
$model = new ClaimsCollectionV2DashboardModel();
$kpiMap = ClaimsCollectionV2DashboardModel::KPI_MAP;
ok('KPI_MAP count', count($kpiMap) === 31, (string) count($kpiMap));
$uniqueMethods = array_unique(array_values($kpiMap));
ok('unique KPI method names', count($uniqueMethods) === 31, count($uniqueMethods) . ' methods');
foreach (['policy_exposure_summary', 'incurred_ratio'] as $slug) {
ok("slug map contains {$slug}", in_array($slug, $kpiMap, true));
}
ok('id 207 maps to incurred_ratio', ($kpiMap[207] ?? '') === 'incurred_ratio');
ok('id 181 maps to policy_exposure_summary', ($kpiMap[181] ?? '') === 'policy_exposure_summary');
try {
$rows = $model->policy_exposure_summary($policyId);
ok('model policy_exposure_summary', is_array($rows), 'rows=' . count($rows));
} catch (Throwable $e) {
ok('model policy_exposure_summary', false, $e->getMessage());
}
try {
$rows = $model->getKpi('incurred_ratio', $policyId);
ok('model getKpi(incurred_ratio)', is_array($rows), 'rows=' . count($rows));
} catch (Throwable $e) {
ok('model getKpi(incurred_ratio)', false, $e->getMessage());
}
$request = Services::request(null, false);
$response = Services::response();
$request->setGlobal('get', ['client_policy' => (string) $policyId]);
$controller = new ClaimsCollectionV2DashboardController();
$controller->initController($request, $response, service('logger'));
$slugResp = json_decode($controller->kpi('incurred_ratio')->getJSON(), true);
ok('controller kpi by slug', ($slugResp['status'] ?? false) === true && ($slugResp['kpi'] ?? '') === 'incurred_ratio');
$idResp = json_decode($controller->kpi('207')->getJSON(), true);
ok('controller kpi by id 207', ($idResp['status'] ?? false) === true && ($idResp['kpi_id'] ?? 0) === 207);
$badResp = json_decode($controller->kpi('not_a_kpi')->getJSON(), true);
ok('controller unknown kpi 404', ($badResp['status'] ?? true) === false);
$allResp = json_decode($controller->all()->getJSON(), true);
ok('controller all KPIs', ($allResp['status'] ?? false) === true && count($allResp['data'] ?? []) === 31);
$debugOut = $controller->debug($policyId);
$debugBody = is_string($debugOut) ? $debugOut : $debugOut->getBody();
$debugJson = json_decode($debugBody, true);
ok('controller debug JSON', ($debugJson['status'] ?? false) === true && isset($debugJson['data']));
$previewOut = $controller->preview($policyId);
$previewHtml = is_string($previewOut) ? $previewOut : $previewOut->getBody();
ok('controller preview HTML', str_contains($previewHtml, 'Claims Collection V2') && str_contains($previewHtml, 'kpi-grid'));
$routeCollection = Services::routes(true);
$mvcRoutes = [];
$jwtRoutes = [];
foreach ($routeCollection->getRoutes('get') as $pattern => $handler) {
if (! str_contains($pattern, 'claims-collection-v2')) {
continue;
}
if (str_starts_with($pattern, 'util/')) {
$mvcRoutes[] = $pattern;
}
if (str_starts_with($pattern, 'employeeRest/')) {
$jwtRoutes[] = $pattern;
}
}
ok('MVC claims-collection-v2 routes registered', count($mvcRoutes) >= 5, implode(', ', $mvcRoutes) ?: 'none');
ok('JWT claims-collection-v2 routes registered', count($jwtRoutes) >= 5, implode(', ', $jwtRoutes) ?: 'none');
$baseUrl = rtrim((string) env('app.baseURL', ''), '/');
if ($baseUrl !== '') {
$results[] = '';
$results[] = '=== HTTP auth gate checks (no session/token) ===';
$urls = [
'MVC preview' => $baseUrl . '/util/claims-collection-v2/preview?client_policy=' . $policyId,
'MVC kpi slug' => $baseUrl . '/util/claims-collection-v2/kpi/incurred_ratio?client_policy=' . $policyId,
'MVC kpi id' => $baseUrl . '/util/claims-collection-v2/kpi/207?client_policy=' . $policyId,
'MVC debug' => $baseUrl . '/util/claims-collection-v2/debug?client_policy=' . $policyId,
'JWT kpi slug' => $baseUrl . '/employeeRest/claims-collection-v2/kpi/incurred_ratio?client_policy=' . $policyId,
'JWT debug' => $baseUrl . '/employeeRest/claims-collection-v2/debug?client_policy=' . $policyId,
];
foreach ($urls as $label => $url) {
$ctx = stream_context_create(['http' => ['ignore_errors' => true, 'timeout' => 10]]);
$body = @file_get_contents($url, false, $ctx);
$code = 0;
if (isset($http_response_header[0]) && preg_match('/\s(\d{3})\s/', $http_response_header[0], $m)) {
$code = (int) $m[1];
}
$blocked = in_array($code, [401, 403, 302, 303], true);
$reachable = $code >= 200 && $code < 500;
ok("HTTP {$label} (" . ($code ?: 'no connection') . ')', $blocked || $reachable, $url);
}
} else {
$results[] = '[SKIP] HTTP checks — app.baseURL not set in .env';
}
ob_end_clean();
echo '=== Claims Collection V2 smoke test (policy_id=' . $policyId . ') ===' . PHP_EOL . PHP_EOL;
echo implode(PHP_EOL, $results) . PHP_EOL;
echo PHP_EOL . "=== Summary: {$pass} passed, {$fail} failed ===" . PHP_EOL;
exit($fail > 0 ? 1 : 0);