Compare commits

..

7 Commits
live ... dev

Author SHA1 Message Date
3ac38fc5dc FIX_LOG_ISSUE 2026-08-06 14:05:12 +05:30
2ac40373b1 FIX_CORS_ERRO 2026-08-06 11:40:32 +05:30
c1a5418ff2 FIX_CLIENT_LOG 2026-08-06 11:31:53 +05:30
7dbdf444a0 CHANGE_THE_EMP_GET_API 2026-08-03 10:41:28 +05:30
bd46bd2e8b FIX_LIVE_ISSUE 2026-07-31 17:57:29 +05:30
85607b8e32 FIX_LIVE_ISSUE 2026-07-31 17:39:35 +05:30
9fa2dbe808 CHANGE_HR_CHANGES 2026-07-28 15:48:45 +05:30
4 changed files with 531 additions and 33 deletions

View File

@ -0,0 +1,189 @@
<?php
/**
* Manual test for EmployeePolicyModel global search.
*
* Usage:
* php spark test:employee-global-search
* php spark test:employee-global-search --search Self
* php spark test:employee-global-search --client_id cede2d63a7c04ebd4cb55a2228c7141a --client_policy_id 5769 --client_branch_id 444 --search john
*/
namespace App\Commands;
use App\Models\EmployeePolicyModel;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use Config\Database;
class TestEmployeeGlobalSearch extends BaseCommand
{
protected $group = 'Testing';
protected $name = 'test:employee-global-search';
protected $description = 'Test getEmployeePolicy global search (emp_code, name, mobile, email, tpa_id, dob, relationship, status)';
protected $usage = 'test:employee-global-search [--client_id ...] [--client_policy_id ...] [--client_branch_id ...] [--search ...]';
protected $options = [
'--client_id' => 'Client id (md5 hash or numeric)',
'--client_policy_id' => 'Client policy id',
'--client_branch_id' => 'Client branch id',
'--search' => 'Global search term',
'--limit' => 'Max rows to print (default 10)',
];
public function run(array $params)
{
$clientId = $this->optionValue($params, 'client_id', 'cede2d63a7c04ebd4cb55a2228c7141a');
$clientPolicyId = $this->optionValue($params, 'client_policy_id', '5769');
$clientBranchId = $this->optionValue($params, 'client_branch_id', '444');
$search = $this->optionValue($params, 'search', '');
$limit = (int) $this->optionValue($params, 'limit', '10');
$model = new EmployeePolicyModel();
$withoutSearch = $model->getEmployeePolicy(
client_id: $clientId,
policy_id: $clientPolicyId,
status: 0,
branch_id: $clientBranchId,
status_type: 'hr'
);
// Fallback to a real active employee_policy row when defaults have no data
if (count($withoutSearch) === 0 && !$this->hasExplicitIds($params)) {
$fixture = $this->findSampleIds();
if ($fixture === null) {
CLI::error('No active employee_policy rows found to test against.');
return;
}
$clientId = (string) $fixture['client_id'];
$clientPolicyId = (string) $fixture['client_policy_id'];
$clientBranchId = (string) $fixture['client_branch_id'];
CLI::write('Default IDs had no rows. Using sample from DB:', 'yellow');
CLI::write(" client_id : {$clientId}");
CLI::write(" client_policy_id : {$clientPolicyId}");
CLI::write(" client_branch_id : {$clientBranchId}");
CLI::newLine();
$withoutSearch = $model->getEmployeePolicy(
client_id: $clientId,
policy_id: $clientPolicyId,
status: 0,
branch_id: $clientBranchId,
status_type: 'hr'
);
}
if ($search === '' && count($withoutSearch) > 0) {
$search = (string) ($withoutSearch[0]['emp_code'] ?? $withoutSearch[0]['name'] ?? 'Self');
CLI::write("No --search given. Using sample term from first row: {$search}", 'yellow');
CLI::newLine();
}
CLI::write('Params:', 'yellow');
CLI::write(" client_id : {$clientId}");
CLI::write(" client_policy_id : {$clientPolicyId}");
CLI::write(" client_branch_id : {$clientBranchId}");
CLI::write(' search : ' . ($search !== '' ? $search : '(none)'));
CLI::newLine();
$withSearch = $model->getEmployeePolicy(
client_id: $clientId,
policy_id: $clientPolicyId,
status: 0,
branch_id: $clientBranchId,
status_type: 'hr',
search: $search
);
CLI::write('Result counts:', 'green');
CLI::write(' without search : ' . count($withoutSearch));
CLI::write(' with search : ' . count($withSearch));
CLI::newLine();
$rows = $search !== '' ? $withSearch : $withoutSearch;
$preview = array_slice($rows, 0, max(1, $limit));
CLI::write('Preview fields (emp_code | name | mobile | email | tpa_id | dob | relationship | status):', 'yellow');
foreach ($preview as $i => $row) {
CLI::write(sprintf(
'%d) %s | %s | %s | %s | %s | %s | %s | %s',
$i + 1,
$row['emp_code'] ?? '',
$row['name'] ?? '',
$row['mobile'] ?? '',
$row['email_corporate'] ?? '',
$row['tpa_id'] ?? '',
$row['formatted_dob'] ?? ($row['dob'] ?? ''),
$row['relationship'] ?? '',
$row['status'] ?? ($row['emp_status'] ?? '')
));
}
if (count($rows) > $limit) {
CLI::write('... ' . (count($rows) - $limit) . ' more row(s)');
}
if ($search !== '' && count($withSearch) > 0) {
CLI::newLine();
CLI::write('Matched sample JSON:', 'green');
CLI::write(json_encode(array_map(static function ($row) {
return [
'emp_code' => $row['emp_code'] ?? null,
'name' => $row['name'] ?? null,
'mobile' => $row['mobile'] ?? null,
'email_corporate' => $row['email_corporate'] ?? null,
'tpa_id' => $row['tpa_id'] ?? null,
'dob' => $row['dob'] ?? null,
'formatted_dob' => $row['formatted_dob'] ?? null,
'relationship' => $row['relationship'] ?? null,
'status' => $row['status'] ?? null,
'emp_status' => $row['emp_status'] ?? null,
];
}, array_slice($withSearch, 0, 3)), JSON_PRETTY_PRINT));
} elseif ($search !== '') {
CLI::write('No rows matched the search term.', 'red');
}
}
private function optionValue(array $params, string $name, string $default = ''): string
{
$value = $params[$name] ?? CLI::getOption($name);
if ($value === null || $value === false || $value === '') {
return $default;
}
return (string) $value;
}
private function hasExplicitIds(array $params): bool
{
foreach (['client_id', 'client_policy_id', 'client_branch_id'] as $key) {
$value = $params[$key] ?? CLI::getOption($key);
if ($value !== null && $value !== false && $value !== '') {
return true;
}
}
return false;
}
private function findSampleIds(): ?array
{
$db = Database::connect('default');
$row = $db->query(
"SELECT emp.client_id, ep.client_policy_id, emp.client_branch_id
FROM employee_polices ep
JOIN employees emp ON emp.id = ep.employee_id
WHERE ep.is_active = 1
AND emp.is_active = 1
ORDER BY ep.id DESC
LIMIT 1"
)->getRowArray();
return $row ?: null;
}
}

View File

@ -363,7 +363,7 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) {
$routes->post('checkSIMapping','ClientController::checkSIMapping');
$routes->post('deleteMapping','ClientController::deleteMapping');
$routes->get('removeLevelContacts','ClientController::removeLevelContacts');
$routes->get("downloadEmployeeListExcel", "EmployeeRestController::downloadEmployeeListExcel");
});
$routes->group("policy_tranction", ["filter" => "authMVC"], function ($routes) {
@ -488,6 +488,7 @@ $routes->group("employeeRest", ['filter' => [ 'GlobalPostFileUploadGuard', 'appS
$routes->post("iAgreeForAddOn", "EmployeeRestController::iAgreeForAddOn");
$routes->get("exportDataByClientPolicyId", "EmployeeRestController::exportDataByClientPolicyId");
$routes->get("downloadEmployeeListExcel", "EmployeeRestController::downloadEmployeeListExcel");
$routes->get("getPolicyLevelEmployeeSummaryData", "EmployeeRestController::getPolicyLevelEmployeeSummaryData");
$routes->get("exportCashDepositData", "EmployeeRestController::exportCashDepositData");

View File

@ -691,19 +691,139 @@ class EmployeeRestController extends AdminController
public function getEmployeeAndDependenceByClientId()
{
try {
$empData = $this->employeePolicyModel->getEmployeePolicy( client_id:$this->request->getGet('client_id'),policy_id: $this->request->getGet('client_policy_id'),status:0,branch_id:$this->request->getGet('client_branch_id'), status_type: 'hr');
$cardDataParam = strtolower(trim((string) ($this->request->getGet('card_data') ?? '')));
$cardDataParam = str_replace(['-', ' '], '_', $cardDataParam);
$search = trim((string) ($this->request->getGet('search') ?? ''));
$cardFilters = ['all', 'emp_count', 'submitted', 'logged_in', 'not_logged_in', 'draft'];
$empData = $this->employeePolicyModel->getEmployeePolicy(
client_id: $this->request->getGet('client_id'),
policy_id: $this->request->getGet('client_policy_id'),
status: 0,
branch_id: $this->request->getGet('client_branch_id'),
status_type: 'hr',
search: $cardDataParam === 'all' ? '' : $search
) ?: [];
if (in_array($cardDataParam, $cardFilters, true)) {
$response = $this->prepareMemberCardDataResponse($empData, $cardDataParam);
return $this->respond([
'status' => 'success',
'code' => 200,
'data' => $response['data'],
'card_data' => $response['card_data'],
], 200);
}
if ($empData) {
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $empData], 200);
} else {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
}
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500);
}
}
/**
* Build Member Details response for card_data filters (Self relationship only).
*
* @return array{data: array, card_data: array}
*/
private function prepareMemberCardDataResponse(array $empData, string $cardDataParam): array
{
$cardData = $this->buildMemberCardData($empData);
if ($cardDataParam === 'all') {
return [
'data' => [],
'card_data' => $cardData,
];
}
$filteredData = array_values(array_filter($empData, function ($row) use ($cardDataParam) {
return $this->matchesMemberCardFilter($row, $cardDataParam);
}));
return [
'data' => $filteredData,
'card_data' => $cardData,
];
}
/**
* Whether a row matches the selected card filter (Self only).
*/
private function matchesMemberCardFilter(array $row, string $cardDataParam): bool
{
if (strtolower(trim((string) ($row['relationship'] ?? ''))) !== 'self') {
return false;
}
if ($cardDataParam === 'emp_count') {
return true;
}
$status = strtolower(trim((string) ($row['status'] ?? '')));
$empStatus = strtolower(trim((string) ($row['emp_status'] ?? '')));
$isSubmitted = in_array($status, ['submitted', 'enrolled'], true)
|| $empStatus === 'enrolled';
$isLoggedIn = strtolower((string) ($row['logged_in'] ?? '')) === 'yes';
return match ($cardDataParam) {
'submitted' => $isSubmitted,
'logged_in' => $isLoggedIn,
'not_logged_in' => !$isLoggedIn,
'draft' => !$isSubmitted,
default => false,
};
}
/**
* Member Details badge counts Self relationship only.
*/
private function buildMemberCardData(array $empData): array
{
$counts = [
'emp_count' => 0,
'submitted' => 0,
'logged_in' => 0,
'not_logged_in' => 0,
'draft' => 0,
];
foreach ($empData as $row) {
if (strtolower(trim((string) ($row['relationship'] ?? ''))) !== 'self') {
continue;
}
$counts['emp_count']++;
$status = strtolower(trim((string) ($row['status'] ?? '')));
$empStatus = strtolower(trim((string) ($row['emp_status'] ?? '')));
$isSubmitted = in_array($status, ['submitted', 'enrolled'], true)
|| $empStatus === 'enrolled';
if ($isSubmitted) {
$counts['submitted']++;
}
$isLoggedIn = strtolower((string) ($row['logged_in'] ?? '')) === 'yes';
if ($isLoggedIn) {
$counts['logged_in']++;
} else {
$counts['not_logged_in']++;
}
// Draft = Self who has not submitted (matches Emp Count - Submitted).
if (!$isSubmitted) {
$counts['draft']++;
}
}
return $counts;
}
public function exportDataByClientPolicyId()
@ -783,6 +903,108 @@ class EmployeeRestController extends AdminController
}
/**
* Download employee + dependent list Excel.
* Filters: client_id, branch_id, policy_id only (same as getEmployeePolicy base filters).
* Columns: Emp Code, Name, TPA ID, Relationship, Date Of Birth, Gender, Mobile, Email, Status
*/
public function downloadEmployeeListExcel()
{
try {
$clientId = $this->request->getGet('client_id');
$branchId = $this->request->getGet('branch_id');
$policyId = $this->request->getGet('policy_id');
$empData = $this->employeePolicyModel->getEmployeePolicy(
client_id: $clientId,
policy_id: $policyId,
status: 0,
branch_id: $branchId
);
if (!count($empData)) {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => [], 'message' => 'No employee data found'], 200);
}
$headers = [
'Emp Code' => 'emp_code',
'Name' => 'name',
'TPA ID' => 'tpa_id',
'Relationship' => 'relationship',
'Date Of Birth' => 'formatted_dob',
'Gender' => 'gender',
'Mobile' => 'mobile',
'Email' => 'email_corporate',
'Status' => 'status',
];
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Employee List');
$column = 'A';
foreach ($headers as $header => $dbField) {
$sheet->setCellValue($column . '1', $header);
$column++;
}
$headerRange = 'A1:I1';
$sheet->getStyle($headerRange)->getFont()->setBold(true);
$sheet->getStyle($headerRange)->getFill()
->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
->getStartColor()->setRGB('BDD7EE');
$row = 2;
foreach ($empData as $employee) {
$column = 'A';
foreach ($headers as $dbField) {
$value = $employee[$dbField] ?? '';
if ($dbField === 'formatted_dob' && empty($value) && !empty($employee['dob'])) {
$value = date('d/m/Y', strtotime($employee['dob']));
}
if ($dbField === 'gender' && $value !== '') {
$genderLower = strtolower(trim((string) $value));
if ($genderLower === 'male' || $genderLower === 'm') {
$value = 'M';
} elseif ($genderLower === 'female' || $genderLower === 'f') {
$value = 'F';
}
}
$sheet->setCellValue($column . $row, $value);
$column++;
}
$row++;
}
foreach (range('A', 'I') as $col) {
$sheet->getColumnDimension($col)->setAutoSize(true);
}
$policyName = $empData[0]['policy_name'] ?? 'Employee';
$filename = preg_replace('/[^A-Za-z0-9_\-]/', '_', $policyName) . '-Employee-List.xlsx';
// Write to memory and return via CI Response so CORS after() filters still run.
// Raw header() + exit skips filters and causes CORS errors for cross-origin fetch.
$tempFile = tempnam(sys_get_temp_dir(), 'emp_list_');
$writer = new Xlsx($spreadsheet);
$writer->save($tempFile);
$excelData = file_get_contents($tempFile);
@unlink($tempFile);
return $this->response
->setStatusCode(200)
->setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
->setHeader('Content-Disposition', 'attachment;filename="' . $filename . '"')
->setHeader('Cache-Control', 'max-age=0')
->setBody($excelData);
} catch (\Exception $e) {
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
}
}
//not in use
public function getClientPolicy()
{
@ -2184,6 +2406,36 @@ class EmployeeRestController extends AdminController
// }
// }
private function hasValidClientLogo(?string $logo): bool
{
if ($logo === null || trim($logo) === '') {
return false;
}
$path = parse_url(trim($logo), PHP_URL_PATH) ?? trim($logo);
$filename = basename(rtrim($path, '/'));
return $filename !== '' && strcasecmp($filename, 'logo') !== 0;
}
private function getPreClientLogoUrl($preClientId): string
{
if (is_string($preClientId) && preg_match('/^[a-f0-9]{32}$/i', $preClientId)) {
$preClient = $this->clientModel->where('MD5(id)', $preClientId)->first();
} else {
$preClient = $this->clientModel->where('id', $preClientId)->first();
}
$logoFilename = $preClient['client_logo'] ?? '';
$logoPath = ROOTPATH . 'public/uploads/logo/' . $logoFilename;
if (!empty($logoFilename) && file_exists($logoPath)) {
return base_url() . 'public/uploads/logo/' . $logoFilename;
}
return '';
}
public function getClientDetails()
{
try {
@ -2191,28 +2443,48 @@ class EmployeeRestController extends AdminController
$pre_branch_id = $this->request->getGet('pre_branch_id');
$post_client_id = $this->request->getGet('post_client_id');
$post_branch_id = $this->request->getGet('post_branch_id');
// Both pre and post: prefer post data; fall back to pre logo if post has none
if (!empty($pre_client_id) && !empty($post_client_id)) {
$restAuthController = new RestAuthenticationController;
$queryParams = [
'client_id' => $post_client_id,
'client_branch_id' => $post_branch_id
];
$postResponse = $restAuthController->callThirdPartyGETAPI($queryParams, 'getClientDetails');
$postData = is_string($postResponse) ? json_decode($postResponse, true) : null;
if (
is_array($postData)
&& (($postData['status'] ?? '') === 'success' || (int) ($postData['code'] ?? 0) === 200)
&& !empty($postData['data']['client'])
) {
$postLogo = $postData['data']['client']['client_logo'] ?? '';
if (!$this->hasValidClientLogo($postLogo)) {
$postData['data']['client']['client_logo'] = $this->getPreClientLogoUrl($pre_client_id);
}
return $this->respond($postData, 200);
}
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
}
if (!empty($pre_client_id)) {
if (is_string($pre_client_id) && preg_match('/^[a-f0-9]{32}$/i', $pre_client_id)) {
$client = $this->clientModel->where('MD5(id)', $pre_client_id)->first();
}else{
} else {
$client = $this->clientModel->where('id', $pre_client_id)->first();
}
}
if ($client) {
$client['client_logo'] = base_url() . 'public/uploads/logo/' . $client['client_logo'];
$client['client_logo'] = $this->getPreClientLogoUrl($pre_client_id);
$clientPolicy = $this->clientPolicyModel
->where('client_id', $client['id'] ?? null)
->where('client_branch_id', $pre_branch_id)
->findAll();
return $this->respond([
'status' => 'success',
'code' => 200,
@ -2221,27 +2493,34 @@ class EmployeeRestController extends AdminController
'client_policy' => $clientPolicy
]
], 200);
} else {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
}
} elseif (!empty($post_client_id)) {
$restAuthController = new RestAuthenticationController;
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
}
if (!empty($post_client_id)) {
$restAuthController = new RestAuthenticationController;
$queryParams = [
'client_id' => $post_client_id,
'client_branch_id' => $post_branch_id
];
return $restAuthController->callThirdPartyGETAPI($queryParams, 'getClientDetails');
$postResponse = $restAuthController->callThirdPartyGETAPI($queryParams, 'getClientDetails');
$postData = is_string($postResponse) ? json_decode($postResponse, true) : null;
} else {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
if (
is_array($postData)
&& !empty($postData['data']['client'])
&& !$this->hasValidClientLogo($postData['data']['client']['client_logo'] ?? '')
) {
$postData['data']['client']['client_logo'] = '';
return $this->respond($postData, 200);
}
return $postResponse;
}
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
} catch (\Exception $e) {
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
}
}
@ -4627,21 +4906,21 @@ class EmployeeRestController extends AdminController
(
SELECT id FROM client_policy
WHERE policy_type_id = 3
AND base_policy = gmc_client_policy_id
AND base_policy = gmc_client_policy_id AND is_active = 1
LIMIT 1
) AS gmc_parent_policy_id,
(
SELECT id FROM client_policy
WHERE policy_type_id = 4
AND base_policy = gmc_client_policy_id
AND base_policy = gmc_client_policy_id AND is_active = 1
LIMIT 1
) AS gmc_topup_policy_id,
(
SELECT id FROM client_policy
WHERE policy_type_id = 72
AND base_policy = gmc_client_policy_id
AND base_policy = gmc_client_policy_id AND is_active = 1
LIMIT 1
) AS opd_topup_policy_id
")
@ -4652,6 +4931,7 @@ class EmployeeRestController extends AdminController
->where([
'employees.is_active' => 1,
'employee_polices.is_active' => 1,
'client_policy.is_active' => 1,
'client_policy.policy_type_id' => 2,
'employees.family_floater_key' => 'self',
'employees.emp_code' => $emp_code ?? null,

View File

@ -82,7 +82,7 @@ class EmployeePolicyModel extends Model
}
// ----------------------------------------------------------------------------------------------------------
public function getEmployeePolicy($client_id = 0, $policy_id = 0, $status = [], $branch_id = 0, $emp_code = "", $emp_name = "", $status_type = "")
public function getEmployeePolicy($client_id = 0, $policy_id = 0, $status = [], $branch_id = 0, $emp_code = "", $emp_name = "", $status_type = "", $search = "")
{
// dd($status);
@ -301,6 +301,10 @@ class EmployeePolicyModel extends Model
$result->like('emp.name', $emp_name);
}
if (!empty($search)) {
$this->applyEmployeeGlobalSearch($result, $search);
}
// Always check these conditions
$result->where('employee_polices.is_active', 1)
->where('emp.is_active', 1);
@ -311,6 +315,30 @@ class EmployeePolicyModel extends Model
return $res;
}
/**
* Global search across emp_code, name, mobile, email, tpa_id, dob, relationship, status.
*/
protected function applyEmployeeGlobalSearch($builder, string $search)
{
$search = trim($search);
if ($search === '') {
return $builder;
}
return $builder->groupStart()
->like('emp.emp_code', $search)
->orLike('emp.name', $search)
->orLike('emp.mobile', $search)
->orLike('emp.email_corporate', $search)
->orLike('employee_polices.tpa_id', $search)
->orLike('emp.dob', $search)
->orWhere("DATE_FORMAT(emp.dob, '%d/%m/%Y') LIKE " . $this->db->escape('%' . $search . '%'), null, false)
->orLike('emp.relationship', $search)
->orLike('employee_polices.status', $search)
->orLike('emp.emp_status', $search)
->groupEnd();
}
// public function getEmployeePolicy($client_id = 0, $policy_id = 0, $status = [], $branch_id = 0, $emp_code = "", $emp_name = "")
// {