Merge remote-tracking branch 'origin/dev' into dev

This commit is contained in:
velz 2026-05-22 15:01:34 +05:30
commit f3ac9c6833
26 changed files with 2287 additions and 507 deletions

View File

@ -818,6 +818,7 @@ $routes->group("/ticket", ["filter" => "authMVC"], function ($routes) {
$routes->get("getMoreInfo","TicketController::getMoreInfo"); $routes->get("getMoreInfo","TicketController::getMoreInfo");
$routes->post('upload_url',"TicketController::upload_url"); $routes->post('upload_url',"TicketController::upload_url");
$routes->post('getUrlDataByTicketId',"TicketController::getUrlDataByTicketId"); $routes->post('getUrlDataByTicketId',"TicketController::getUrlDataByTicketId");
$routes->post('manualMergeClaimFiles', 'TicketController::manualMergeClaimFiles');
$routes->post('uploadClaimFilesToTPA', 'TicketController::uploadClaimFilesToTPA'); $routes->post('uploadClaimFilesToTPA', 'TicketController::uploadClaimFilesToTPA');
$routes->get('remove_url',"TicketController::remove_url"); $routes->get('remove_url',"TicketController::remove_url");
$routes->get('fetchVehiclePolicy/(:any)','TicketController::fetchVehiclePolicy/$1'); $routes->get('fetchVehiclePolicy/(:any)','TicketController::fetchVehiclePolicy/$1');

View File

@ -15,6 +15,7 @@ use App\Controllers\MediAssistApiController;
use App\Controllers\FhplApiController; use App\Controllers\FhplApiController;
use App\Controllers\VoloApiController; use App\Controllers\VoloApiController;
use App\Models\BatchFileModel; use App\Models\BatchFileModel;
use App\Models\ClaimFilesModel;
use App\Models\FileModel; use App\Models\FileModel;
use App\Helpers\TPADataCompareHelper; use App\Helpers\TPADataCompareHelper;
use App\Helpers\TPADataCompareHelper2; use App\Helpers\TPADataCompareHelper2;
@ -25,6 +26,7 @@ class ApiServiceController extends BaseController
// protected $format = 'json'; // protected $format = 'json';
protected $db; protected $db;
protected $employeePolicyModel; protected $employeePolicyModel;
protected $claimFilesModel;
protected $medi_assist_primary_key; protected $medi_assist_primary_key;
protected $vidal_primary_key; protected $vidal_primary_key;
protected $icici_primary_key; protected $icici_primary_key;
@ -36,6 +38,7 @@ class ApiServiceController extends BaseController
{ {
$this->db = \Config\Database::connect(); $this->db = \Config\Database::connect();
$this->employeePolicyModel = new EmployeePolicyModel(); $this->employeePolicyModel = new EmployeePolicyModel();
$this->claimFilesModel = new ClaimFilesModel();
$this->medi_assist_primary_key = getenv('MEDI_ASSIST_PRIMARY_KEY_CONSTANT'); $this->medi_assist_primary_key = getenv('MEDI_ASSIST_PRIMARY_KEY_CONSTANT');
$this->vidal_primary_key = getenv('VIDAL_PRIMARY_KEY_CONSTANT'); $this->vidal_primary_key = getenv('VIDAL_PRIMARY_KEY_CONSTANT');
$this->icici_primary_key = getenv('ICICI_PRIMARY_KEY_CONSTANT'); $this->icici_primary_key = getenv('ICICI_PRIMARY_KEY_CONSTANT');
@ -177,20 +180,14 @@ class ApiServiceController extends BaseController
$voloApiController = new VoloApiController(); $voloApiController = new VoloApiController();
$data['eCardDownload'] = $voloApiController->EcardRequest( $emp_code, $policy_no , $employee_policy[0]['tpa_id'] ); $data['eCardDownload'] = $voloApiController->EcardRequest( $emp_code, $policy_no , $employee_policy[0]['tpa_id'] );
}else{ }
if($type == "download"){ if (empty($data['eCardDownload'])) {
// direct download $data['eCardDownload'] = $this->buildDefaultEcardDownloadUrl(
$data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string'].'/1'; $employee_policy[0]['rand_string'],
}else{ $type,
if(isset($all_member) && !empty($all_member)){ $all_member ?? null
// view and download all members );
$data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string'].'/1/1';
}else{
// view and download single member
$data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string'].'/0/1';
}
}
} }
$data['message'] = "E-card generated"; $data['message'] = "E-card generated";
@ -220,6 +217,19 @@ class ApiServiceController extends BaseController
} }
} }
private function buildDefaultEcardDownloadUrl(string $randString, string $type = 'download', $allMember = null): string
{
if ($type === 'download') {
return base_url('download-e-card/') . $randString . '/1';
}
if (!empty($allMember)) {
return base_url('download-e-card/') . $randString . '/1/1';
}
return base_url('download-e-card/') . $randString . '/0/1';
}
// Get TPAID // Get TPAID
public function getTPAID() public function getTPAID()
{ {
@ -583,6 +593,13 @@ class ApiServiceController extends BaseController
]); ]);
} }
if (! $this->claimFilesModel->hasPdfFileForTicket($claimId)) {
return $this->response->setJSON([
'status' => false,
'message' => 'No PDF file found for this claim'
]);
}
$result = $this->pushClaims($claimId); $result = $this->pushClaims($claimId);
if ($result !== null && is_array($result)) { if ($result !== null && is_array($result)) {

View File

@ -799,7 +799,7 @@ class ClientController extends AdminController
], ],
'cd_ac_no' => [ 'cd_ac_no' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9\/\-_]+$/]', 'rules' => 'required|regex_match[/^[a-zA-Z0-9\/\-_ ]+$/]',
'errors' => [ 'errors' => [
'required' => 'CD Account number is required.', 'required' => 'CD Account number is required.',
'regex_match' => 'CD Account number can only contain letters, numbers, hyphens(-), underscores(_), and slashes(/).', 'regex_match' => 'CD Account number can only contain letters, numbers, hyphens(-), underscores(_), and slashes(/).',
@ -874,12 +874,14 @@ class ClientController extends AdminController
$record_date = null; $record_date = null;
} }
$cd_master_data = $this->CDMasterModel->where('id', $cd_ac_pk)->where('is_active', 1)->first();
$data = [ $data = [
'amount' => $sanitized_post_data['amount'] ?? null, 'amount' => $sanitized_post_data['amount'] ?? null,
'sub_type_id' => $sanitized_post_data['sub_type_id'] ?? null, 'sub_type_id' => $sanitized_post_data['sub_type_id'] ?? null,
'client_id' => $sanitized_post_data['client_id'] ?? null, 'client_id' => $sanitized_post_data['client_id'] ?? null,
'client_policy_id' => null, 'client_policy_id' => null,
'cd_ac_no' => $cd_ac_no ?? null, 'cd_ac_no' => $cd_master_data['cd_ac_no'] ?? null,
'cd_ac_pk' => $cd_ac_pk ?? null, 'cd_ac_pk' => $cd_ac_pk ?? null,
'endorsement_no' => null, 'endorsement_no' => null,
'insurer_id' => $sanitized_post_data['insurer_id'] ?? null, 'insurer_id' => $sanitized_post_data['insurer_id'] ?? null,

View File

@ -517,7 +517,7 @@ class EmployeeController extends AdminController
") ")
->join('client_policy', 'client_policy.id = batch_files.client_policy_id') ->join('client_policy', 'client_policy.id = batch_files.client_policy_id')
->join('insurers', 'client_policy.insurer_id = insurers.id') ->join('insurers', 'client_policy.insurer_id = insurers.id')
->join('tpa', 'client_policy.tpa_id = tpa.id') ->join('tpa', 'client_policy.tpa_id = tpa.id', 'left')
->join('client_branch', 'client_branch.id = batch_files.client_branch_id') ->join('client_branch', 'client_branch.id = batch_files.client_branch_id')
->join('policy_type', 'policy_type.id = client_policy.policy_type_id') ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
->join('clients', 'clients.id = client_policy.client_id') ->join('clients', 'clients.id = client_policy.client_id')
@ -574,7 +574,6 @@ class EmployeeController extends AdminController
->orderBy('batch_files.id', 'desc') ->orderBy('batch_files.id', 'desc')
->find(); ->find();
// dd($data['fileList']);die(); // dd($data['fileList']);die();
if ($this->request->getMethod() == "get") { if ($this->request->getMethod() == "get") {
$this->loadLayout('import_export', $data); $this->loadLayout('import_export', $data);
@ -4256,25 +4255,36 @@ class EmployeeController extends AdminController
$emp_data_wo_tpa_id = $this->employeePolicyModel->getTPADataVariationReport($client_id, $client_policy_id, $file_id); $emp_data_wo_tpa_id = $this->employeePolicyModel->getTPADataVariationReport($client_id, $client_policy_id, $file_id);
// Reconcile DB records against TPA records and classify records for rec_type updates. // Reconcile DB records against TPA records and classify records for rec_type updates.
$consumedTpaIdsByEmpCode = [];
foreach ($emp_data_wo_tpa_id as $db_key => $db_row) { foreach ($emp_data_wo_tpa_id as $db_key => $db_row) {
$tpa_temp_data = $tpaByEmpCode[$db_row['emp_code']] ?? []; $empCode = (string) ($db_row['emp_code'] ?? '');
$match = $this->reconcileDbWithTpa($db_row, $tpa_temp_data); $empId = (string) ($db_row['id'] ?? '');
$empName = (string) ($db_row['name'] ?? '');
$tpa_temp_data = $tpaByEmpCode[$empCode] ?? [];
$excludeTpaIds = $consumedTpaIdsByEmpCode[$empCode] ?? [];
$match = $this->reconcileDbWithTpa($db_row, $tpa_temp_data, $excludeTpaIds);
$emp_data_wo_tpa_id[$db_key]['match'] = $match; $emp_data_wo_tpa_id[$db_key]['match'] = $match;
if (($match['status'] ?? '') === 'matched') { if (($match['status'] ?? '') === 'matched') {
$matchedTpaId = (int) ($match['tpa_record']['id'] ?? 0); $matchedTpaId = (int) ($match['tpa_record']['id'] ?? 0);
// echo 'matched' . $matchedTpaId . ' for emp_code ' . $empCode . PHP_EOL . '<br>';
if ($matchedTpaId > 0) { if ($matchedTpaId > 0) {
$consumedTpaIdsByEmpCode[$empCode][] = $matchedTpaId;
// If compare-fields list has differences, the row must be reviewed. // If compare-fields list has differences, the row must be reviewed.
// Otherwise keep it as matched. // Otherwise keep it as matched.
$recTypeById[$matchedTpaId] = empty($match['not_matching']) ? 'matched' : 'need_to_review'; $recTypeById[$matchedTpaId] = empty($match['not_matching']) ? 'matched' : 'need_to_review';
} }
} else { } else {
// No relation-level match found for this DB member. // echo 'not matched' . ' for emp_code ' . $empCode . PHP_EOL . ' - ' . $empId . ' - ' . $empName . ' - ' . '<br>';
// Mark all candidate TPA rows for the same emp_code as review-required. // No match for this DB member: flag same-relation TPA rows not already paired.
$dbRel = strtolower(trim((string) ($db_row['relationship'] ?? '')));
foreach ($tpa_temp_data as $candidate) { foreach ($tpa_temp_data as $candidate) {
if (strtolower(trim((string) ($candidate['relation'] ?? ''))) !== $dbRel) {
continue;
}
$candidateId = (int) ($candidate['id'] ?? 0); $candidateId = (int) ($candidate['id'] ?? 0);
if ($candidateId > 0) { if ($candidateId > 0 && !in_array($candidateId, $excludeTpaIds, true)) {
$recTypeById[$candidateId] = 'need_to_review'; $recTypeById[$candidateId] = '';
} }
} }
} }
@ -4310,73 +4320,72 @@ class EmployeeController extends AdminController
// this will match tpa api data with emp/emp policy table and update ref in tpa api data once // this will match tpa api data with emp/emp policy table and update ref in tpa api data once
$this->reconTpaApiDataWithEmployeepolicies(['file_id' => $file_id]); $this->reconTpaApiDataWithEmployeepolicies(['file_id' => $file_id]);
} else { } else {
// echo 'else';die;
// Cached mode: // Cached mode:
// Read previously classified rows from rec_type, keep response shape compatible // `not_in_nhance` stays sourced from persisted rec_type snapshot.
// with existing UI/export (`mismatch_data` still contains DB row + match payload). // `mismatch_data` must match compute-mode shape: every policy row with
// tpa_id NULL gets reconcileDbWithTpa against *all* active TPA rows for
// that emp_code (not only rows flagged need_to_review), otherwise second+
// loads drop rows / lose not_matching vs the first compute pass.
$not_in_nhance = $tpaApiDataModel->select('*') $not_in_nhance = $tpaApiDataModel->select('*')
->where('is_active', 1) ->where('is_active', 1)
->where('file_id', $file_id) ->where('file_id', $file_id)
->where('rec_type', 'not_in_nhance') ->where('rec_type', 'not_in_nhance')
->findAll(); ->findAll();
$needToReviewRows = $tpaApiDataModel->select('*') $allActiveTpaRowsCached = $tpaApiDataModel->select('*')
->where('is_active', 1)
->where('file_id', $file_id) ->where('file_id', $file_id)
->where('rec_type', 'need_to_review') ->where('is_active', 1)
->findAll(); ->findAll();
$needToReviewByEmpCode = []; $tpaByEmpCodeCached = [];
foreach ($needToReviewRows as $row) { foreach ($allActiveTpaRowsCached as $tpaRow) {
$needToReviewByEmpCode[$row['emp_code']][] = $row; $tpaByEmpCodeCached[$tpaRow['emp_code']][] = $tpaRow;
} }
$baseRows = $this->employeePolicyModel->getTPADataVariationReport($client_id, $client_policy_id, $file_id); $emp_data_wo_tpa_id = $this->employeePolicyModel->getTPADataVariationReport($client_id, $client_policy_id, $file_id);
foreach ($baseRows as $db_row) { $consumedTpaIdsByEmpCodeCached = [];
$candidates = $needToReviewByEmpCode[$db_row['emp_code']] ?? []; foreach ($emp_data_wo_tpa_id as $db_key => $db_row) {
if (empty($candidates)) { $empCode = (string) ($db_row['emp_code'] ?? '');
continue; $tpa_temp_data = $tpaByEmpCodeCached[$empCode] ?? [];
$excludeTpaIds = $consumedTpaIdsByEmpCodeCached[$empCode] ?? [];
$match = $this->reconcileDbWithTpa($db_row, $tpa_temp_data, $excludeTpaIds);
$emp_data_wo_tpa_id[$db_key]['match'] = $match;
if (($match['status'] ?? '') === 'matched') {
$matchedTpaId = (int) ($match['tpa_record']['id'] ?? 0);
if ($matchedTpaId > 0) {
$consumedTpaIdsByEmpCodeCached[$empCode][] = $matchedTpaId;
}
}
}
} }
$selectedTpa = null; // print_rr($emp_data_wo_tpa_id);die();
foreach ($candidates as $candidate) {
// Prefer same-relation row to mimic reconcileDbWithTpa relation matching.
if (strtolower((string) ($candidate['relation'] ?? '')) === strtolower((string) ($db_row['relationship'] ?? ''))) {
$selectedTpa = $candidate;
break;
}
}
if ($selectedTpa === null) {
$selectedTpa = $candidates[0];
}
$db_row['match'] = [
'status' => 'matched',
'tpa_record' => $selectedTpa,
'not_matching' => [],
];
$emp_data_wo_tpa_id[] = $db_row;
}
}
// Intentionally keep `not_in_tpa` live from current join/query logic // Intentionally keep `not_in_tpa` live from current join/query logic
// (as requested) and do not source it from rec_type snapshot. // (as requested) and do not source it from rec_type snapshot.
$tpa_emp_codes = $tpaApiDataModel->select('emp_code') $tpa_emp_codes = $tpaApiDataModel->select('ref')
->where('file_id', $file_id) ->where('file_id', $file_id)
->where('is_active', 1) ->where('is_active', 1)
->groupBy('emp_code') ->groupBy('ref')
->findAll(); ->findAll();
$tpa_emp_codes = array_column($tpa_emp_codes, 'emp_code');
$not_in_tpa = $this->employeePolicyModel->getTPADataVariationReport($client_id, $client_policy_id, $file_id, $tpa_emp_codes); // $tpa_emp_codes = array_column($tpa_emp_codes, 'ref');
$tpa_ref = array_column($tpa_emp_codes, 'ref');
$not_in_tpa = $this->employeePolicyModel->getTPADataVariationReport($client_id, $client_policy_id, $file_id, $tpa_ref);
// Format dates for UI/export (dd/mm/yyyy). Applied after reconciliation so
// reconcileDbWithTpa can still compare raw Y-m-d values from the database.
$this->formatVariationReportDataForDisplay($not_in_tpa, $not_in_nhance, $emp_data_wo_tpa_id);
if (!empty($not_in_tpa) || !empty($not_in_nhance) || !empty($emp_data_wo_tpa_id)) { if (!empty($not_in_tpa) || !empty($not_in_nhance) || !empty($emp_data_wo_tpa_id)) {
$not_in_nhance_button_enable_status = false; $not_in_nhance_button_enable_status = false;
if(count($not_in_tpa)) if (count($not_in_nhance)) {
{ foreach ($not_in_nhance as $nih) {
foreach($not_in_nhance as $nih) $hasRefKey = array_key_exists('ref', $nih);
{ $ref = $hasRefKey ? $nih['ref'] : null;
if($nih['ref'] === '' || empty($nih['ref'])) $refIsEmpty = $ref === null || $ref === '';
{ if ($refIsEmpty) {
$not_in_nhance_button_enable_status = true; $not_in_nhance_button_enable_status = true;
break; break;
} }
@ -4411,6 +4420,21 @@ class EmployeeController extends AdminController
$not_in_nhance_deletion_count $not_in_nhance_deletion_count
); );
$not_matched_count = 0;
$not_matched_data = [];
foreach ($emp_data_wo_tpa_id as $key => $row) {
$notMatching = $row['match']['not_matching'] ?? [];
if (isset($row['match']) && is_array($notMatching) && $notMatching !== []) {
$not_matched_count++;
$not_matched_data[] = $row;
}
}
$need_to_review_proceed_button_text = sprintf(
'Proceed - Need to Review ( %d )',
$not_matched_count
);
$response = [ $response = [
'not_in_tpa' => $not_in_tpa, 'not_in_tpa' => $not_in_tpa,
'not_in_nhance' => $not_in_nhance, 'not_in_nhance' => $not_in_nhance,
@ -4419,6 +4443,9 @@ class EmployeeController extends AdminController
'not_in_nhance_inception_count' => $not_in_nhance_inception_count, 'not_in_nhance_inception_count' => $not_in_nhance_inception_count,
'not_in_nhance_deletion_count' => $not_in_nhance_deletion_count, 'not_in_nhance_deletion_count' => $not_in_nhance_deletion_count,
'not_in_nhance_proceed_button_text' => $not_in_nhance_proceed_button_text, 'not_in_nhance_proceed_button_text' => $not_in_nhance_proceed_button_text,
'not_matched_count' => $not_matched_count,
'not_matched_data' => $not_matched_data,
'need_to_review_proceed_button_text' => $need_to_review_proceed_button_text,
]; ];
if ($type === 'view') { if ($type === 'view') {
@ -4890,10 +4917,12 @@ class EmployeeController extends AdminController
} }
$mismatchRows = []; $mismatchRows = [];
$consumedTpaIdsByEmpCode = [];
foreach ($dbRows as $dbRow) { foreach ($dbRows as $dbRow) {
$empCode = (string) ($dbRow['emp_code'] ?? '');
$tpaRows = $TpaApiDataModel->select('*') $tpaRows = $TpaApiDataModel->select('*')
->where('emp_code', $dbRow['emp_code']) ->where('emp_code', $empCode)
->where('file_id', $batchFileId) ->where('file_id', $batchFileId)
->where('is_active', 1) ->where('is_active', 1)
->findAll(); ->findAll();
@ -4902,7 +4931,14 @@ class EmployeeController extends AdminController
continue; continue;
} }
$match = $this->reconcileDbWithTpa($dbRow, $tpaRows); $excludeTpaIds = $consumedTpaIdsByEmpCode[$empCode] ?? [];
$match = $this->reconcileDbWithTpa($dbRow, $tpaRows, $excludeTpaIds);
if (($match['status'] ?? '') === 'matched') {
$matchedTpaId = (int) ($match['tpa_record']['id'] ?? 0);
if ($matchedTpaId > 0) {
$consumedTpaIdsByEmpCode[$empCode][] = $matchedTpaId;
}
}
if (($match['status'] ?? '') !== 'matched') { if (($match['status'] ?? '') !== 'matched') {
continue; continue;
@ -5191,9 +5227,12 @@ class EmployeeController extends AdminController
$rowsSkippedNoDiff = 0; $rowsSkippedNoDiff = 0;
$rowsSkippedNoEmployee = 0; $rowsSkippedNoEmployee = 0;
$consumedTpaIdsByEmpCode = [];
foreach ($dbRows as $dbRow) { foreach ($dbRows as $dbRow) {
$empCode = (string) ($dbRow['emp_code'] ?? '');
$tpaRows = $TpaApiDataModel->select('*') $tpaRows = $TpaApiDataModel->select('*')
->where('emp_code', $dbRow['emp_code'] ?? '') ->where('emp_code', $empCode)
->where('file_id', $batchFileId) ->where('file_id', $batchFileId)
->where('is_active', 1) ->where('is_active', 1)
->findAll(); ->findAll();
@ -5202,7 +5241,8 @@ class EmployeeController extends AdminController
continue; continue;
} }
$match = $this->reconcileDbWithTpa($dbRow, $tpaRows); $excludeTpaIds = $consumedTpaIdsByEmpCode[$empCode] ?? [];
$match = $this->reconcileDbWithTpa($dbRow, $tpaRows, $excludeTpaIds);
if (($match['status'] ?? '') !== 'matched') { if (($match['status'] ?? '') !== 'matched') {
continue; continue;
@ -5211,6 +5251,11 @@ class EmployeeController extends AdminController
$tpaRecord = $match['tpa_record'] ?? []; $tpaRecord = $match['tpa_record'] ?? [];
$notMatching = $match['not_matching'] ?? []; $notMatching = $match['not_matching'] ?? [];
$matchedTpaId = (int) ($tpaRecord['id'] ?? 0);
if ($matchedTpaId > 0) {
$consumedTpaIdsByEmpCode[$empCode][] = $matchedTpaId;
}
if (!is_array($notMatching) || $notMatching === []) { if (!is_array($notMatching) || $notMatching === []) {
$rowsSkippedNoDiff++; $rowsSkippedNoDiff++;
continue; continue;
@ -5525,57 +5570,169 @@ class EmployeeController extends AdminController
]; ];
} }
public function reconcileDbWithTpa(array $db, array $tpaRows): array /**
* Convert a single variation-report date value to dd/mm/yyyy for display.
*/
private function formatVariationReportDateField($value): string
{ {
// Name normalization if ($value === null || $value === '') {
$normalizeName = function ($name) { return '';
}
$formatted = change_date_format((string) $value, null, 'd/m/Y');
return ($formatted !== null && $formatted !== '') ? (string) $formatted : (string) $value;
}
/**
* Format known date columns on one variation-report row (TPA or DB).
*/
private function formatVariationReportRowDates(array $row, array $dateFields = ['dob', 'doj']): array
{
foreach ($dateFields as $field) {
if (!array_key_exists($field, $row)) {
continue;
}
if ($row[$field] === null || $row[$field] === '') {
continue;
}
$row[$field] = $this->formatVariationReportDateField($row[$field]);
}
return $row;
}
/**
* Apply dd/mm/yyyy formatting to all variation-report payloads returned to the UI/export.
*/
private function formatVariationReportDataForDisplay(
array &$notInTpa,
array &$notInNhance,
array &$mismatchData
): void {
foreach ($notInTpa as $idx => $row) {
$notInTpa[$idx] = $this->formatVariationReportRowDates($row);
}
foreach ($notInNhance as $idx => $row) {
$notInNhance[$idx] = $this->formatVariationReportRowDates($row);
}
foreach ($mismatchData as $idx => $row) {
$row = $this->formatVariationReportRowDates($row);
if (isset($row['match']['tpa_record']) && is_array($row['match']['tpa_record'])) {
$row['match']['tpa_record'] = $this->formatVariationReportRowDates($row['match']['tpa_record']);
}
$mismatchData[$idx] = $row;
}
}
/**
* Pair one Nhance policy row with a TPA API row for the same emp_code.
*
* When multiple dependents share a relation (e.g. two Sons), candidates are scored
* on name / DOB / gender and the best unique match wins. Already-paired TPA ids
* (same emp_code) can be passed via $excludeTpaIds so each TPA row maps once.
*/
public function reconcileDbWithTpa(array $db, array $tpaRows, array $excludeTpaIds = []): array
{
$normalizeName = static function ($name) {
return strtolower( return strtolower(
preg_replace('/[.\s_]+/', '', trim($name)) preg_replace('/[.\s_]+/', '', trim((string) $name))
); );
}; };
foreach ($tpaRows as $tpa) { $normalizeRelation = static function ($relation) {
return strtolower(trim((string) $relation));
};
// 1⃣ emp_code + relation must match $dbRel = $normalizeRelation($db['relationship'] ?? '');
if (
// ($db['emp_code'] ?? '') !== ($tpa['emp_code'] ?? '') || $candidates = [];
strtolower($db['relationship']) !== strtolower($tpa['relation']) foreach ($tpaRows as $tpa) {
) { if (isset($tpa['match']['status']) && $tpa['match']['status'] === 'matched') {
continue; continue;
} }
// 2⃣ Field comparison $tpaId = (int) ($tpa['id'] ?? 0);
if ($tpaId > 0 && in_array($tpaId, $excludeTpaIds, true)) {
continue;
}
if ($normalizeRelation($tpa['relation'] ?? '') !== $dbRel) {
continue;
}
$candidates[] = $tpa;
}
if ($candidates === []) {
return ['status' => 'no_match'];
}
$scoreCandidate = static function (array $tpa) use ($db, $normalizeName) {
$score = 0;
if ($normalizeName($db['name'] ?? '') === $normalizeName($tpa['name'] ?? '')) {
$score += 4;
}
if ((string) ($db['dob'] ?? '') === (string) ($tpa['dob'] ?? '')) {
$score += 2;
}
if (strtoupper(trim((string) ($db['gender'] ?? ''))) === strtoupper(trim((string) ($tpa['gender'] ?? '')))) {
$score += 1;
}
return $score;
};
$bestTpa = null;
$bestScore = -1;
foreach ($candidates as $tpa) {
$score = $scoreCandidate($tpa);
if ($score > $bestScore) {
$bestScore = $score;
$bestTpa = $tpa;
}
}
if ($bestTpa === null) {
return ['status' => 'no_match'];
}
// Multiple Son/Daughter rows: require a unique tie-breaker (name or DOB).
if (count($candidates) > 1) {
$topCount = 0;
foreach ($candidates as $tpa) {
if ($scoreCandidate($tpa) === $bestScore) {
$topCount++;
}
}
if ($topCount > 1 || $bestScore < 2) {
return ['status' => 'no_match'];
}
}
$diff = []; $diff = [];
if ( if ($normalizeName($db['name'] ?? '') !== $normalizeName($bestTpa['name'] ?? '')) {
($db['name'] ?? '') !==
($tpa['name'] ?? '')
) {
$diff[] = 'name'; $diff[] = 'name';
} }
if (($db['dob'] ?? '') !== ($tpa['dob'] ?? '')) { if ((string) ($db['dob'] ?? '') !== (string) ($bestTpa['dob'] ?? '')) {
$diff[] = 'dob'; $diff[] = 'dob';
} }
if ( if (
strtoupper($db['gender'] ?? '') !== strtoupper(trim((string) ($db['gender'] ?? ''))) !==
strtoupper($tpa['gender'] ?? '') strtoupper(trim((string) ($bestTpa['gender'] ?? '')))
) { ) {
$diff[] = 'gender'; $diff[] = 'gender';
} }
// 3⃣ Match found
return [ return [
'status' => 'matched', 'status' => 'matched',
'tpa_record' => $tpa, 'tpa_record' => $bestTpa,
'not_matching' => $diff // empty = perfect match 'not_matching' => $diff,
];
}
// 4⃣ No match found
return [
'status' => 'no_match'
]; ];
} }

View File

@ -3785,14 +3785,6 @@ class EmployeeRestController extends AdminController
$this->handleCliamFiles($file_data, $ticket_id, $ticket_message_id); $this->handleCliamFiles($file_data, $ticket_id, $ticket_message_id);
// Merge all uploaded PDFs for this ticket into a single combined PDF
try {
helper('merge_pdf');
merge_ticket_pdfs((int) $ticket_id);
} catch (\Throwable $e) {
log_message('error', 'EmployeeRestController::initiateClaim | merge_ticket_pdfs failed | ticket_id=' . $ticket_id . ' | ' . $e->getMessage());
}
$mail_sent_status = ($this->ticketController->sendAutoMailTrigger($ticket_id)); $mail_sent_status = ($this->ticketController->sendAutoMailTrigger($ticket_id));
if (gettype($mail_sent_status) == 'array') { if (gettype($mail_sent_status) == 'array') {
$message = 'Claim Iniated Successfully'; $message = 'Claim Iniated Successfully';
@ -3931,6 +3923,15 @@ class EmployeeRestController extends AdminController
} }
} }
if (! empty($insert_ids)) {
try {
helper('merge_pdf');
merge_ticket_pdfs((int) $ticket_id);
} catch (\Throwable $e) {
log_message('error', 'EmployeeRestController::handleCliamFiles | merge_ticket_pdfs failed | ticket_id=' . $ticket_id . ' | ' . $e->getMessage());
}
}
$count = $this->ticketMaster->where('id', $ticket_id)->where('is_active', 1)->where('tpa_claim_push_reference_no IS NULL')->countAllResults(); $count = $this->ticketMaster->where('id', $ticket_id)->where('is_active', 1)->where('tpa_claim_push_reference_no IS NULL')->countAllResults();
log_message('error', 'Ticket validation | Ticket ID: ' . $ticket_id . ' | Matching active tickets with NULL TPA reference: ' . $count); log_message('error', 'Ticket validation | Ticket ID: ' . $ticket_id . ' | Matching active tickets with NULL TPA reference: ' . $count);
if ($count > 0 && $pdf_exist_in_the_file && $tpa_claim_push == true) { if ($count > 0 && $pdf_exist_in_the_file && $tpa_claim_push == true) {
@ -5452,14 +5453,6 @@ class EmployeeRestController extends AdminController
$result = $this->handleCliamFiles($file_data, $ticket_id, null, false, true); $result = $this->handleCliamFiles($file_data, $ticket_id, null, false, true);
if (! empty($result)) { if (! empty($result)) {
// Merge all uploaded PDFs for this ticket into a single combined PDF
try {
helper('merge_pdf');
merge_ticket_pdfs((int) $ticket_id);
} catch (\Throwable $e) {
log_message('error', 'EmployeeRestController::uploadIRDocs | merge_ticket_pdfs failed | ticket_id=' . $ticket_id . ' | ' . $e->getMessage());
}
// $this->ticketMaster->where('id', $ticket_id)->set(['required_docs', $required_docs])->update(); // $this->ticketMaster->where('id', $ticket_id)->set(['required_docs', $required_docs])->update();
db_connect()->query( db_connect()->query(
"UPDATE ticket_master SET required_docs = ? WHERE id = ?", "UPDATE ticket_master SET required_docs = ? WHERE id = ?",

View File

@ -554,30 +554,32 @@ class FhplApiController extends BaseController
foreach ($employeePolicyData as $policy) { foreach ($employeePolicyData as $policy) {
$hasMatchForThisPolicy = false; $hasMatchForThisPolicy = false;
foreach ($allMembers as $m) { foreach ($allMembers as $m) {
$apiRelation = map_relationship(trim($m['RELATION'] ?? ''));
if ( if (
strtolower(trim($policy['name'])) === strtolower(trim($m['BENEFICIARY_NAME'] ?? '')) && strtolower(trim((string) ($policy['name'] ?? ''))) === strtolower(trim((string) ($m['BENEFICIARY_NAME'] ?? '')))
($policy['emp_code'] ?? '') == ($m['EMPLOYEE_ID'] ?? '') && && trim((string) ($policy['emp_code'] ?? '')) === trim((string) ($m['EMPLOYEE_ID'] ?? ''))
strtolower($policy['relationship']) === strtolower($m['RELATION'] ?? '') && strtolower(trim((string) ($policy['relationship'] ?? ''))) === strtolower(trim((string) $apiRelation))
) { ) {
$hasMatchForThisPolicy = true; $hasMatchForThisPolicy = true;
$tpaId = $m['MEMBERSHIP_NO'] ?? $m['MEMBERSHIP_NO'] ?? null;
$sql = "UPDATE employee_polices SET tpa_id = ? WHERE id = ?"; $sql = 'UPDATE employee_polices SET tpa_id = ? WHERE id = ?';
$this->db->query($sql, [$m['MEMBERSHIP_NO'], $policy['emp_policy_id']]); $this->db->query($sql, [$tpaId, $policy['emp_policy_id']]);
// for e-card send // for e-card send
if(strtolower(trim($policy['relationship'])) == 'self'){ if (strtolower(trim((string) ($policy['relationship'] ?? ''))) === 'self') {
$employee_policy_ids[] = $policy['emp_policy_id']; $employee_policy_ids[] = $policy['emp_policy_id'];
} }
if ($this->db->affectedRows() > 0) { if ($this->db->affectedRows() > 0) {
$updated++; $updated++;
log_message('error', "FHPL - TPA ID Pull Updated tpa_id={$m['MEMBERSHIP_NO']} for emp_policy_id={$policy['emp_policy_id']} policy={$policyNo}"); log_message('error', "FHPL - TPA ID Pull Updated tpa_id={$tpaId} for emp_policy_id={$policy['emp_policy_id']} policy={$policyNo}");
} else { } else {
log_message('error', "FHPL - TPA ID Pull No update (already set or not matched) for emp_policy_id={$policy['emp_policy_id']} policy={$policyNo}"); log_message('error', "FHPL - TPA ID Pull No update (already set or not matched) for emp_policy_id={$policy['emp_policy_id']} policy={$policyNo}");
} }
break;
} }
} }
@ -1070,7 +1072,7 @@ class FhplApiController extends BaseController
'gender' => format_gender_v2($row['GENDER'] ?? null), 'gender' => format_gender_v2($row['GENDER'] ?? null),
'self' => strtolower($row['RELATION'] ?? '') === 'self' ? 1 : 0, 'self' => strtolower($row['RELATION'] ?? '') === 'self' ? 1 : 0,
'tpa_id' => trim($row['TPA_TPADETAIL_ID'] ?? null), 'tpa_id' => trim($row['MEMBERSHIP_NO'] ?? null),
'age' => is_numeric($row['AGE'] ?? null) ? (int) $row['AGE'] : null, 'age' => is_numeric($row['AGE'] ?? null) ? (int) $row['AGE'] : null,
'is_active' => 1, 'is_active' => 1,

View File

@ -368,6 +368,8 @@ class LeadsController extends BaseController
$id = $this->request->getPost('id'); $id = $this->request->getPost('id');
$actual_lead_id = $this->request->getPost('actual_lead_id'); $actual_lead_id = $this->request->getPost('actual_lead_id');
$actual_lead_id = ! empty($actual_lead_id) ? $actual_lead_id : null; $actual_lead_id = ! empty($actual_lead_id) ? $actual_lead_id : null;
$this->normalizeClaimHistoryPostData();
$postData = $this->request->getPost(); $postData = $this->request->getPost();
$data = $this->prepareLeadData(); $data = $this->prepareLeadData();
@ -526,41 +528,58 @@ class LeadsController extends BaseController
]; ];
if ((int) $this->request->getPost('claim_history') === 1) { if ((int) $this->request->getPost('claim_history') === 1) {
$rules['first_year.*'] = [ $nilClaimsRows = $this->resolveNilClaimRowFlags($postData);
$claimRowCount = $this->getClaimHistoryRowCount($postData, $nilClaimsRows);
for ($claimIndex = 0; $claimIndex < $claimRowCount; $claimIndex++) {
$rules["first_year.$claimIndex"] = [
'rules' => 'required|regex_match[/^\d{4}-\d{4}$/]', 'rules' => 'required|regex_match[/^\d{4}-\d{4}$/]',
'errors' => ['required' => 'Claim Year is required for all entries.', 'regex_match' => 'Year must be in format YYYY-YYYY.'], 'errors' => [
'required' => 'Claim Year is required for all entries.',
'regex_match' => 'Year must be in format YYYY-YYYY.',
],
]; ];
$rules['first_policy_type_.*'] = [
if (! empty($nilClaimsRows[$claimIndex])) {
continue;
}
$rules["first_policy_type_.$claimIndex"] = [
'rules' => 'required|regex_match[/^[a-zA-Z0-9 _-]+$/]', 'rules' => 'required|regex_match[/^[a-zA-Z0-9 _-]+$/]',
'errors' => ['required' => 'Policy Type is required in Claim History.', 'errors' => [
'required' => 'Policy Type is required in Claim History.',
'regex_match' => 'Policy Type only letters, numbers, space, hyphens and underscores are allowed', 'regex_match' => 'Policy Type only letters, numbers, space, hyphens and underscores are allowed',
], ],
]; ];
$rules['first_date_of_loss_.*'] = [ $rules["first_date_of_loss_.$claimIndex"] = [
'rules' => 'required|regex_match[/^[0-9]{2}-[0-9]{2}-[0-9]{4}$/]', 'rules' => 'required|regex_match[/^[0-9]{2}-[0-9]{2}-[0-9]{4}$/]',
'errors' => ['required' => 'Date of Loss is required.', 'errors' => [
'regex_match' => 'Date of Loss must be inValid format.'], 'required' => 'Date of Loss is required.',
'regex_match' => 'Date of Loss must be inValid format.',
],
]; ];
$rules['first_cause_of_loss.*'] = [ $rules["first_cause_of_loss.$claimIndex"] = [
'rules' => 'required|regex_match[/^[a-zA-Z0-9 _-]+$/]', 'rules' => 'required|regex_match[/^[a-zA-Z0-9 _-]+$/]',
'errors' => [ 'errors' => [
'required' => 'Cause of Loss is required.', 'required' => 'Cause of Loss is required.',
'regex_match' => 'Cause of Loss only letters, numbers, space, hyphens and underscores are allowed', 'regex_match' => 'Cause of Loss only letters, numbers, space, hyphens and underscores are allowed',
], ],
]; ];
$rules['first_claim_amount.*'] = [ $rules["first_claim_amount.$claimIndex"] = [
'rules' => 'required|numeric', 'rules' => 'required|numeric',
'errors' => [ 'errors' => [
'required' => 'Claim Amount is required.', 'required' => 'Claim Amount is required.',
'numeric' => 'Claim Amount must be a number.', 'numeric' => 'Claim Amount must be a number.',
], ],
]; ];
$rules['first_settled_amount.*'] = [ $rules["first_settled_amount.$claimIndex"] = [
'rules' => 'required|numeric', 'rules' => 'required|numeric',
'errors' => ['required' => 'Settled Amount is required.', 'errors' => [
'numeric' => 'Settled Amount must be a number.'], 'required' => 'Settled Amount is required.',
'numeric' => 'Settled Amount must be a number.',
],
]; ];
$rules['first_claim_status.*'] = [ $rules["first_claim_status.$claimIndex"] = [
'rules' => 'required|alpha_space', 'rules' => 'required|alpha_space',
'errors' => [ 'errors' => [
'required' => 'Claim Status is required.', 'required' => 'Claim Status is required.',
@ -568,6 +587,7 @@ class LeadsController extends BaseController
], ],
]; ];
} }
}
} }
@ -576,59 +596,68 @@ class LeadsController extends BaseController
$claimHistoryPolicyTypes = [1, 6, 7]; $claimHistoryPolicyTypes = [1, 6, 7];
$hasClaimHistoryPolicy = count(array_intersect($postedPolicyTypeIds, $claimHistoryPolicyTypes)) > 0; $hasClaimHistoryPolicy = count(array_intersect($postedPolicyTypeIds, $claimHistoryPolicyTypes)) > 0;
$isEbClaimHistory = $leadFormType === 1 $isEbClaimHistory = $leadFormType === 1
&& in_array((int) ($postData['lead_type'] ?? 0), [2, 3], true) && in_array((int) ($postData['lead_type'] ?? 0), [1, 2, 3], true)
&& $hasClaimHistoryPolicy && $hasClaimHistoryPolicy
&& (int) ($postData['claim_history'] ?? 0) === 1; && (int) ($postData['claim_history'] ?? 0) === 1;
if ($isEbClaimHistory) { if ($isEbClaimHistory) {
$rules['first_year.*'] = [ $nilClaimsRows = $this->resolveNilClaimRowFlags($postData);
$claimRowCount = $this->getClaimHistoryRowCount($postData, $nilClaimsRows);
for ($claimIndex = 0; $claimIndex < $claimRowCount; $claimIndex++) {
$rules["first_year.$claimIndex"] = [
'rules' => 'required|regex_match[/^\d{4}-\d{4}$/]', 'rules' => 'required|regex_match[/^\d{4}-\d{4}$/]',
'errors' => [ 'errors' => [
'required' => 'Claim Year is required for all entries.', 'required' => 'Claim Year is required for all entries.',
'regex_match' => 'Year must be in format YYYY-YYYY.', 'regex_match' => 'Year must be in format YYYY-YYYY.',
], ],
]; ];
$rules['emp_id.*'] = [
if (! empty($nilClaimsRows[$claimIndex])) {
continue;
}
$rules["emp_id.$claimIndex"] = [
'rules' => 'required', 'rules' => 'required',
'errors' => ['required' => 'Employee ID is required in Claim History.'], 'errors' => ['required' => 'Employee ID is required in Claim History.'],
]; ];
$rules['emp_name.*'] = [ $rules["emp_name.$claimIndex"] = [
'rules' => 'required', 'rules' => 'required',
'errors' => ['required' => 'Employee Name is required in Claim History.'], 'errors' => ['required' => 'Employee Name is required in Claim History.'],
]; ];
$rules['gender.*'] = [ $rules["gender.$claimIndex"] = [
'rules' => 'required|in_list[Female,Male]', 'rules' => 'required|in_list[Female,Male]',
'errors' => [ 'errors' => [
'required' => 'Gender is required in Claim History.', 'required' => 'Gender is required in Claim History.',
'in_list' => 'Gender must be Female or Male.', 'in_list' => 'Gender must be Female or Male.',
], ],
]; ];
$rules['designation.*'] = [ $rules["designation.$claimIndex"] = [
'rules' => 'required', 'rules' => 'required',
'errors' => ['required' => 'Designation is required in Claim History.'], 'errors' => ['required' => 'Designation is required in Claim History.'],
]; ];
$rules['sum_insured.*'] = [ $rules["sum_insured.$claimIndex"] = [
'rules' => 'required|numeric', 'rules' => 'required|numeric',
'errors' => [ 'errors' => [
'required' => 'Sum Insured is required in Claim History.', 'required' => 'Sum Insured is required in Claim History.',
'numeric' => 'Sum Insured must be a number.', 'numeric' => 'Sum Insured must be a number.',
], ],
]; ];
$rules['first_death_date.*'] = [ $rules["first_death_date.$claimIndex"] = [
'rules' => 'required|regex_match[/^[0-9]{2}-([0-9]{2}|[A-Za-z]{3})-[0-9]{4}$/]', 'rules' => 'required|regex_match[/^[0-9]{2}-([0-9]{2}|[A-Za-z]{3})-[0-9]{4}$/]',
'errors' => [ 'errors' => [
'required' => 'Date of Death is required.', 'required' => 'Date of Death is required.',
'regex_match' => 'Date of Death must be in DD-MM-YYYY or DD-MMM-YYYY format.', 'regex_match' => 'Date of Death must be in DD-MM-YYYY or DD-MMM-YYYY format.',
], ],
]; ];
$rules['first_cause_of_death.*'] = [ $rules["first_cause_of_death.$claimIndex"] = [
'rules' => 'required|in_list[natural_death,suicide,accident,cardiac_arrest,septic_shock,heart_attack]', 'rules' => 'required|in_list[natural_death,suicide,accident,cardiac_arrest,septic_shock,heart_attack]',
'errors' => [ 'errors' => [
'required' => 'Nature/Cause Of Death is required.', 'required' => 'Nature/Cause Of Death is required.',
'in_list' => 'Nature/Cause Of Death is invalid.', 'in_list' => 'Nature/Cause Of Death is invalid.',
], ],
]; ];
$rules['first_claim_amount.*'] = [ $rules["first_claim_amount.$claimIndex"] = [
'rules' => 'required|numeric', 'rules' => 'required|numeric',
'errors' => [ 'errors' => [
'required' => 'Claim/Settled Amount is required.', 'required' => 'Claim/Settled Amount is required.',
@ -636,6 +665,7 @@ class LeadsController extends BaseController
], ],
]; ];
} }
}
// 1. MANUALLY VALIDATE FILES BEFORE PROCESSING // 1. MANUALLY VALIDATE FILES BEFORE PROCESSING
// $allFiles = $this->request->getFiles(); // $allFiles = $this->request->getFiles();
@ -2866,7 +2896,9 @@ class LeadsController extends BaseController
//claim history new sheet; //claim history new sheet;
if ($claim_history == 1 && !empty($rfq_data['fin_years_claims'])) { if ($claim_history == 1 && !empty($rfq_data['fin_years_claims'])) {
$claim_details = json_decode($rfq_data['fin_years_claims'], true) ?? []; $claim_details = $this->sanitizeClaimDetailsForExport(
json_decode($rfq_data['fin_years_claims'], true) ?? []
);
if (! empty($claim_details['finyear'])) { if (! empty($claim_details['finyear'])) {
@ -4654,6 +4686,209 @@ class LeadsController extends BaseController
} }
} }
private function normalizeClaimHistoryPostData(): void
{
$post = $this->request->getPost();
if ((int) ($post['claim_history'] ?? 0) !== 1) {
return;
}
$rows = $this->getFinyearRowsFromPost($post);
if ($rows === []) {
return;
}
$leadFormType = (int) ($post['lead_form_type'] ?? 1);
$claimArrays = $leadFormType === 2
? $this->buildNonEbClaimHistoryPostArrays($rows)
: $this->buildEbClaimHistoryPostArrays($rows);
$this->request->setGlobal('post', array_merge($post, $claimArrays));
}
/**
* Remove internal nil_claims flag from stored/exported claim rows.
*
* @param array<string, mixed> $claimDetails
*
* @return array<string, mixed>
*/
private function sanitizeClaimDetailsForExport(array $claimDetails): array
{
if (empty($claimDetails['finyear']) || ! is_array($claimDetails['finyear'])) {
return $claimDetails;
}
$claimDetails['finyear'] = array_map(static function ($record) {
if (! is_array($record)) {
return $record;
}
unset($record['nil_claims']);
return $record;
}, $claimDetails['finyear']);
return $claimDetails;
}
/**
* @return list<array<string, mixed>>
*/
private function getFinyearRowsFromPost(array $postData): array
{
$jsonPayload = $postData['finyear'] ?? $postData['fin_years_claims'] ?? null;
if (! is_string($jsonPayload) || $jsonPayload === '') {
return [];
}
$decoded = json_decode($jsonPayload, true);
if (! is_array($decoded) || empty($decoded['finyear']) || ! is_array($decoded['finyear'])) {
return [];
}
return $decoded['finyear'];
}
/**
* @param list<array<string, mixed>> $rows
*
* @return array<string, list<string>>
*/
private function buildEbClaimHistoryPostArrays(array $rows): array
{
$arrays = [
'first_year' => [],
'nil_claims' => [],
'emp_id' => [],
'emp_name' => [],
'gender' => [],
'designation' => [],
'sum_insured' => [],
'first_death_date' => [],
'first_cause_of_death' => [],
'first_claim_amount' => [],
];
foreach ($rows as $row) {
$isNil = ! empty($row['nil_claims']);
$arrays['first_year'][] = (string) ($row['year'] ?? '');
$arrays['nil_claims'][] = $isNil ? '1' : '0';
if ($isNil) {
$arrays['emp_id'][] = 'Nil';
$arrays['emp_name'][] = 'Nil';
$arrays['gender'][] = 'Nil';
$arrays['designation'][] = 'Nil';
$arrays['sum_insured'][] = 'Nil';
$arrays['first_death_date'][] = 'Nil';
$arrays['first_cause_of_death'][] = 'Nil';
$arrays['first_claim_amount'][] = 'Nil';
} else {
$arrays['emp_id'][] = (string) ($row['emp_id'] ?? '');
$arrays['emp_name'][] = (string) ($row['emp_name'] ?? '');
$arrays['gender'][] = (string) ($row['gender'] ?? '');
$arrays['designation'][] = (string) ($row['designation'] ?? '');
$arrays['sum_insured'][] = (string) ($row['sum_insured'] ?? '');
$arrays['first_death_date'][] = (string) ($row['death_date'] ?? '');
$arrays['first_cause_of_death'][] = (string) ($row['cause_of_death'] ?? '');
$arrays['first_claim_amount'][] = (string) ($row['settled'] ?? ($row['claim_amount'] ?? ''));
}
}
return $arrays;
}
/**
* @param list<array<string, mixed>> $rows
*
* @return array<string, list<string>>
*/
private function buildNonEbClaimHistoryPostArrays(array $rows): array
{
$arrays = [
'first_year' => [],
'nil_claims' => [],
'first_policy_type_' => [],
'first_date_of_loss_' => [],
'first_cause_of_loss' => [],
'first_claim_amount' => [],
'first_settled_amount' => [],
'first_claim_status' => [],
];
foreach ($rows as $row) {
$isNil = ! empty($row['nil_claims']);
$arrays['first_year'][] = (string) ($row['year'] ?? '');
$arrays['nil_claims'][] = $isNil ? '1' : '0';
if ($isNil) {
$arrays['first_policy_type_'][] = 'Nil';
$arrays['first_date_of_loss_'][] = 'Nil';
$arrays['first_cause_of_loss'][] = 'Nil';
$arrays['first_claim_amount'][] = 'Nil';
$arrays['first_settled_amount'][] = 'Nil';
$arrays['first_claim_status'][] = 'Nil';
} else {
$arrays['first_policy_type_'][] = (string) ($row['policy_type'] ?? '');
$arrays['first_date_of_loss_'][] = (string) ($row['date_of_loss'] ?? '');
$arrays['first_cause_of_loss'][] = (string) ($row['cause_of_loss'] ?? '');
$arrays['first_claim_amount'][] = (string) ($row['claim_amount'] ?? '');
$arrays['first_settled_amount'][] = (string) ($row['settled_amount'] ?? '');
$arrays['first_claim_status'][] = (string) ($row['status'] ?? '');
}
}
return $arrays;
}
/**
* @return array<int, int> Row index => 1 when nil claims, else 0
*/
private function resolveNilClaimRowFlags(array $postData): array
{
$flags = [];
foreach ((array) ($postData['nil_claims'] ?? []) as $idx => $val) {
$flags[(int) $idx] = (int) $val;
}
foreach ($this->getFinyearRowsFromPost($postData) as $idx => $row) {
if (! is_array($row)) {
continue;
}
if (! empty($row['nil_claims'])) {
$flags[(int) $idx] = 1;
} elseif (! isset($flags[(int) $idx])) {
$flags[(int) $idx] = 0;
}
}
return $flags;
}
/**
* @param array<int, int> $nilClaimFlags
*/
private function getClaimHistoryRowCount(array $postData, array $nilClaimFlags): int
{
$counts = [
count((array) ($postData['first_year'] ?? [])),
count($nilClaimFlags),
];
$counts[] = count($this->getFinyearRowsFromPost($postData));
return max(0, ...$counts);
}
public function getLastFiveFinancialYears(): array public function getLastFiveFinancialYears(): array
{ {
$year = (int) date('Y'); $year = (int) date('Y');
@ -4921,8 +5156,11 @@ class LeadsController extends BaseController
$data['lead_edit_data']['multi_file_html'] = trim($html) !== '' ? $html : null; $data['lead_edit_data']['multi_file_html'] = trim($html) !== '' ? $html : null;
} }
if (! in_array((int) $data['lead_edit_data']['lead_type'], [1, 3], true) && $data['lead_edit_data']['lead_form_type'] == 2) { if (in_array((int) $data['lead_edit_data']['lead_type'], [1, 2, 3], true) && $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']); $data['lead_edit_data']['claims_details_html'] = view('rfq/claims_details_non_eb', [
'lead_edit_data' => $data['lead_edit_data'],
'lastFiveYears' => $data['lastFiveYears'] ?? $this->getLastFiveFinancialYears(),
]);
} else { } else {
$data['lead_edit_data']['claims_details_html'] = ""; $data['lead_edit_data']['claims_details_html'] = "";
} }
@ -5372,6 +5610,16 @@ class LeadsController extends BaseController
{ {
helper('excel_util_helper'); helper('excel_util_helper');
$finyear = array_map(static function ($record) {
if (! is_array($record)) {
return $record;
}
unset($record['nil_claims']);
return $record;
}, $finyear);
$first = $finyear[0] ?? null; $first = $finyear[0] ?? null;
if (! is_array($first) || $first === []) { if (! is_array($first) || $first === []) {
@ -5846,6 +6094,9 @@ class LeadsController extends BaseController
{ {
$data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames(); $data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
$data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames(); $data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
$data['lastFiveYears'] = $data['lastFiveYears'] ?? $this->getLastFiveFinancialYears();
$data['gpaClaimType'] = $data['gpaClaimType'] ?? $this->claim_type_for_gpa;
$data['causeOfDeath'] = $data['causeOfDeath'] ?? $this->cause_of_death;
$viewMap = [ $viewMap = [
1 => 'rfq/gpa', 1 => 'rfq/gpa',
@ -6483,7 +6734,9 @@ class LeadsController extends BaseController
if (! empty($rfq_data['fin_years_claims']) && $claim_history == 1) { if (! empty($rfq_data['fin_years_claims']) && $claim_history == 1) {
$claim_details = json_decode($rfq_data['fin_years_claims'], true) ?? []; $claim_details = $this->sanitizeClaimDetailsForExport(
json_decode($rfq_data['fin_years_claims'], true) ?? []
);
if (! empty($claim_details['finyear'])) { if (! empty($claim_details['finyear'])) {

View File

@ -20,12 +20,9 @@ class LoginController extends BaseController
public function index() public function index()
{ {
// $session_data = ['isLoggedIn' => True ,'userid' => '25'];
// set_session_data($session_data);
// $isLoggedIn = check_session();
$isLoggedIn = check_session(); $isLoggedIn = check_session();
$hasCookie = check_cookie(); $hasCookie = check_cookie();
if ($isLoggedIn && $hasCookie) { if ($isLoggedIn || $hasCookie) {
return redirect()->to(base_url('/dashboard/view')); return redirect()->to(base_url('/dashboard/view'));
} }
return view('login'); return view('login');

View File

@ -3677,13 +3677,6 @@ class TicketController extends BaseController
$employeeRest = new EmployeeRestController(); $employeeRest = new EmployeeRestController();
$result = $employeeRest->handleCliamFiles($file_data, $ticket_id); $result = $employeeRest->handleCliamFiles($file_data, $ticket_id);
if(!empty($result)){ if(!empty($result)){
// Merge all uploaded PDFs for this ticket into a single combined PDF
try {
helper('merge_pdf');
merge_ticket_pdfs((int) $ticket_id);
} catch (\Throwable $e) {
log_message('error', 'TicketController::upload_url | merge_ticket_pdfs failed | ticket_id=' . $ticket_id . ' | ' . $e->getMessage());
}
return $this->respond(['status' => true, 'message' => 'File uploaded successfully ']); return $this->respond(['status' => true, 'message' => 'File uploaded successfully ']);
}else{ }else{
return $this->respond(['status' => false, 'message' => 'Failed to upload file ']); return $this->respond(['status' => false, 'message' => 'Failed to upload file ']);
@ -3721,9 +3714,78 @@ class TicketController extends BaseController
->where('is_active', 1) ->where('is_active', 1)
->findAll(); ->findAll();
helper('merge_pdf');
$mergeUi = merge_ticket_manual_merge_status((int) $ticket_id);
return $this->response->setJSON([ return $this->response->setJSON([
'status' => true, 'status' => true,
'data' => $urlData 'data' => $urlData,
'merge_ui' => $mergeUi,
]);
}
/**
* Manually merge claim PDF/image files for a ticket (Claim Files tab).
*/
public function manualMergeClaimFiles()
{
$ticket_id = (int) $this->request->getPost('ticket_id');
if ($ticket_id <= 0) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Ticket ID is required',
]);
}
helper('merge_pdf');
$mergeUi = merge_ticket_manual_merge_status($ticket_id);
if (! $mergeUi['show_manual_merge'] && $mergeUi['mergeable_count'] < 1) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'No PDF or image files available on disk to merge.',
]);
}
$ticket = $this->ticketMasterModel
->select('id, ticket_type_id')
->where('id', $ticket_id)
->where('is_active', 1)
->first();
if (! $ticket) {
return $this->response->setStatusCode(404)->setJSON([
'status' => false,
'message' => 'Claim not found.',
]);
}
try {
$result = merge_ticket_pdfs($ticket_id, [
'ticket_type' => (int) ($ticket['ticket_type_id'] ?? 1),
'created_by' => function_exists('get_session_userid') ? get_session_userid() : null,
]);
} catch (\Throwable $e) {
log_message('error', 'TicketController::manualMergeClaimFiles | ticket_id=' . $ticket_id . ' | ' . $e->getMessage());
return $this->response->setStatusCode(500)->setJSON([
'status' => false,
'message' => 'Merge failed: ' . $e->getMessage(),
]);
}
if (! ($result['status'] ?? false)) {
return $this->response->setJSON([
'status' => false,
'message' => $result['message'] ?? 'Merge failed. Check logs for details.',
'data' => $result,
]);
}
return $this->response->setJSON([
'status' => true,
'message' => $result['message'] ?? 'Documents merged successfully.',
'data' => $result,
]); ]);
} }

View File

@ -1297,6 +1297,7 @@ class TicketServiceController extends AdminController
} else { } else {
//check the employee and insured //check the employee and insured
$params['is_from'] = 'claim_dump';
$employee_data = $ticketMasterModal->getEmployeeAndEmployeePolicyDetails($params) ?? []; $employee_data = $ticketMasterModal->getEmployeeAndEmployeePolicyDetails($params) ?? [];
// dd($employee_data); // dd($employee_data);
if (count($employee_data) == 0) { if (count($employee_data) == 0) {

View File

@ -72,19 +72,22 @@ if (! function_exists('merge_ticket_pdfs')) {
return $result; return $result;
} }
if (count($rows) ==1){
//set file_type for for that one file.
$claimFiles->where('id', $rows[0]['id'])->set(['file_type' => 4])->update();
$result['status'] = true;
$result['message'] = 'Only one PDF/image file to merge';
return $result;
}
$uploadDir = rtrim(WRITEPATH, '/\\') . DIRECTORY_SEPARATOR $uploadDir = rtrim(WRITEPATH, '/\\') . DIRECTORY_SEPARATOR
. 'uploads' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR
. 'claim_files' . DIRECTORY_SEPARATOR; . 'claim_files' . DIRECTORY_SEPARATOR;
$sourceFiles = []; $sourceFiles = [];
foreach ($rows as $row) { foreach ($rows as $row) {
$name = ! empty($row['url']) ? $row['url'] : ($row['file_name'] ?? ''); $full = merge_ticket_pdf_resolve_disk_path($row, $uploadDir);
if (empty($name)) { if ($full !== null) {
continue;
}
// url column may sometimes hold a full URL; we only care about the file basename on disk.
$full = $uploadDir . basename($name);
if (is_file($full) && is_readable($full)) {
$mime = merge_ticket_pdf_resolve_mime($full, (string) ($row['mime_type'] ?? '')); $mime = merge_ticket_pdf_resolve_mime($full, (string) ($row['mime_type'] ?? ''));
if (! in_array($mime, $opts['include_mime_types'], true)) { if (! in_array($mime, $opts['include_mime_types'], true)) {
log_message('error', "merge_ticket_pdfs | unsupported source mime {$mime} | claim_file_id={$row['id']} | path={$full}"); log_message('error', "merge_ticket_pdfs | unsupported source mime {$mime} | claim_file_id={$row['id']} | path={$full}");
@ -97,7 +100,8 @@ if (! function_exists('merge_ticket_pdfs')) {
'id' => $row['id'] ?? null, 'id' => $row['id'] ?? null,
]; ];
} else { } else {
log_message('error', "merge_ticket_pdfs | missing file on disk | claim_file_id={$row['id']} | path={$full}"); $name = ! empty($row['url']) ? $row['url'] : ($row['file_name'] ?? '');
log_message('error', "merge_ticket_pdfs | missing file on disk | claim_file_id={$row['id']} | path=" . $uploadDir . basename((string) $name));
} }
} }
@ -185,7 +189,7 @@ if (! function_exists('merge_ticket_pdfs')) {
$insertData = [ $insertData = [
'ticket_id' => $ticket_master_id, 'ticket_id' => $ticket_master_id,
'ticket_type' => $opts['ticket_type'], // 'ticket_type' => $opts['ticket_type'],
'file_type' => MERGED_CLAIM_FILE_TYPE, 'file_type' => MERGED_CLAIM_FILE_TYPE,
'doc_name' => 'MERGED_CLAIM_DOCS_PDF', 'doc_name' => 'MERGED_CLAIM_DOCS_PDF',
'file_name' => $mergedName, 'file_name' => $mergedName,
@ -332,10 +336,50 @@ if (! function_exists('merge_ticket_pdf_resolve_mime')) {
return 'image/png'; return 'image/png';
} }
if (in_array($detectedMime, ['application/octet-stream', 'binary/octet-stream'], true)) {
if ($ext === 'pdf') {
return 'application/pdf';
}
if (in_array($ext, ['jpg', 'jpeg'], true)) {
return 'image/jpeg';
}
if ($ext === 'png') {
return 'image/png';
}
}
return $detectedMime ?: ($storedMime ?: 'application/octet-stream'); return $detectedMime ?: ($storedMime ?: 'application/octet-stream');
} }
} }
if (! function_exists('merge_ticket_pdf_resolve_disk_path')) {
/**
* Resolve on-disk path for a claim_files row (url and/or file_name).
*/
function merge_ticket_pdf_resolve_disk_path(array $row, string $uploadDir): ?string
{
$candidates = [];
if (! empty($row['url'])) {
$candidates[] = basename((string) $row['url']);
}
if (! empty($row['file_name'])) {
$candidates[] = basename((string) $row['file_name']);
}
foreach (array_unique($candidates) as $name) {
if ($name === '' || preg_match('#^https?://#i', $name)) {
continue;
}
$full = $uploadDir . $name;
if (is_file($full) && is_readable($full)) {
return $full;
}
}
return null;
}
}
if (! function_exists('merge_ticket_pdf_add_image_page')) { if (! function_exists('merge_ticket_pdf_add_image_page')) {
/** /**
* Add an uploaded image as a single PDF page, preserving portrait/landscape * Add an uploaded image as a single PDF page, preserving portrait/landscape
@ -389,3 +433,86 @@ if (! function_exists('merge_ticket_pdf_add_image_page')) {
return true; return true;
} }
} }
if (! function_exists('merge_ticket_manual_merge_status')) {
/**
* UI/status helper: whether manual merge should be offered on Claim Files tab.
*
* @return array{
* has_merged_file: bool,
* mergeable_count: int,
* show_manual_merge: bool,
* button_label: string
* }
*/
function merge_ticket_manual_merge_status(int $ticket_master_id, array $opts = []): array
{
$opts += [
'include_file_types' => [1, 2],
'include_mime_types' => ['application/pdf', 'image/jpeg', 'image/png'],
];
$status = [
'has_merged_file' => false,
'mergeable_count' => 0,
'show_manual_merge' => false,
'button_label' => 'Merge documents',
];
if ($ticket_master_id <= 0) {
return $status;
}
$claimFiles = new ClaimFilesModel();
$rows = $claimFiles
->where('ticket_id', $ticket_master_id)
->where('is_active', 1)
->whereIn('file_type', array_merge($opts['include_file_types'], [MERGED_CLAIM_FILE_TYPE]))
->orderBy('id', 'ASC')
->findAll();
$uploadDir = rtrim(WRITEPATH, '/\\') . DIRECTORY_SEPARATOR
. 'uploads' . DIRECTORY_SEPARATOR
. 'claim_files' . DIRECTORY_SEPARATOR;
$mergeableCount = 0;
$sourceRowCount = 0;
foreach ($rows as $row) {
if ((int) ($row['file_type'] ?? 0) === MERGED_CLAIM_FILE_TYPE) {
$status['has_merged_file'] = true;
continue;
}
if (! in_array((int) ($row['file_type'] ?? 0), $opts['include_file_types'], true)) {
continue;
}
$sourceRowCount++;
$full = merge_ticket_pdf_resolve_disk_path($row, $uploadDir);
if ($full === null) {
continue;
}
$mime = merge_ticket_pdf_resolve_mime($full, (string) ($row['mime_type'] ?? ''));
if (in_array($mime, $opts['include_mime_types'], true)) {
$mergeableCount++;
}
}
$status['mergeable_count'] = $mergeableCount;
// Show manual merge when there is no merged file but user has uploaded docs in the list.
if (! $status['has_merged_file']) {
if ($mergeableCount >= 1 || $sourceRowCount >= 2) {
$status['show_manual_merge'] = true;
$status['button_label'] = 'Merge documents';
}
} elseif ($mergeableCount >= 2) {
$status['show_manual_merge'] = true;
$status['button_label'] = 'Re-merge documents';
}
return $status;
}
}

View File

@ -19,6 +19,7 @@ abstract class BaseTpaClaimImportService
protected $claimDumpFileModel; protected $claimDumpFileModel;
protected $clientPolicyModel; protected $clientPolicyModel;
protected $policyNumberMapping; protected $policyNumberMapping;
protected $tpaTableMapping;
public function __construct() public function __construct()
{ {
@ -33,6 +34,14 @@ abstract class BaseTpaClaimImportService
(int) env('R_CARE_PRIMARY_KEY_CONSTANT') => 'Policy Number', (int) env('R_CARE_PRIMARY_KEY_CONSTANT') => 'Policy Number',
(int) env('ICICI_PRIMARY_KEY_CONSTANT') => 'POLICY_NO', (int) env('ICICI_PRIMARY_KEY_CONSTANT') => 'POLICY_NO',
]; ];
$this->tpaTableMapping = [
(int) env('VIDAL_PRIMARY_KEY_CONSTANT') => 'claims_dump_vidal',
(int) env('ABHI_PRIMARY_KEY_CONSTANT') => 'claims_dump_abhi',
(int) env('MEDI_ASSIST_PRIMARY_KEY_CONSTANT') => 'claims_dump_medi_assist',
(int) env('FHPL_PRIMARY_KEY_CONSTANT') => 'claims_dump_fhpl',
(int) env('R_CARE_PRIMARY_KEY_CONSTANT') => 'claims_dump_reliance',
(int) env('ICICI_PRIMARY_KEY_CONSTANT') => 'claims_dump_icici',
];
} }
/** /**
@ -58,8 +67,7 @@ abstract class BaseTpaClaimImportService
} }
if (empty($rows)) { if (empty($rows)) {
$this->db->transRollback(); // ROLLBACK BEFORE RETURN return $this->failTpaClaimDumpInsert($fileId, 'Excel file contains no data or wrong file upload');
return ['status' => false, 'message' => 'Excel file contains no data or wrong file upload'];
} }
if(isset($this->policyNumberMapping[$fileData['tpa_id']]) && !empty($this->policyNumberMapping[$fileData['tpa_id']])){ if(isset($this->policyNumberMapping[$fileData['tpa_id']]) && !empty($this->policyNumberMapping[$fileData['tpa_id']])){
@ -70,22 +78,19 @@ abstract class BaseTpaClaimImportService
if($client_policy_data['policy_no'] != ($rows[0][$policy_number_column] ?? '')){ if($client_policy_data['policy_no'] != ($rows[0][$policy_number_column] ?? '')){
$this->db->transRollback(); return $this->failTpaClaimDumpInsert($fileId, 'Policy number mismatch in the file and in the system');
return ['status' => false, 'message' => 'Policy number mismatch in the file and in the system'];
} }
$tpaInsertData = $this->mapTPAData($rows, $fileId); $tpaInsertData = $this->mapTPAData($rows, $fileId);
if (empty($tpaInsertData)) { if (empty($tpaInsertData)) {
$this->db->transRollback(); // ROLLBACK BEFORE RETURN return $this->failTpaClaimDumpInsert($fileId, 'These records already exist in the system.');
return ['status' => false, 'message' => 'These records already exist in the system.'];
} }
$return_res = $this->bulkInsertTPATable($tpaInsertData); $return_res = $this->bulkInsertTPATable($tpaInsertData);
if ($return_res !== true) { if ($return_res !== true) {
$this->db->transRollback(); // ROLLBACK BEFORE RETURN return $this->failTpaClaimDumpInsert($fileId, 'TPA Import bulk insert failed');
return ['status' => false, 'message' => 'TPA Import bulk insert failed'];
} }
// 2. Commit if everything is fine // 2. Commit if everything is fine
@ -93,9 +98,7 @@ abstract class BaseTpaClaimImportService
return ['status' => true, 'message' => 'File uploaded successfully', 'record_count' => count($tpaInsertData)]; return ['status' => true, 'message' => 'File uploaded successfully', 'record_count' => count($tpaInsertData)];
} catch (\Throwable $e) { } catch (\Throwable $e) {
// 3. Rollback on any crash/exception return $this->failTpaClaimDumpInsert($fileId, 'System error : ' . $e->getMessage());
$this->db->transRollback();
return ['status' => false, 'message' => 'System error : ' . $e->getMessage()];
} }
} }
@ -113,7 +116,7 @@ abstract class BaseTpaClaimImportService
// Check if mapping failed // Check if mapping failed
if (!$ticketMasterData['status']) { if (!$ticketMasterData['status']) {
$this->db->transRollback(); // ALWAYS rollback before early return $this->rollbackAndCleanupClaimDumpData($file_id);
return $ticketMasterData; return $ticketMasterData;
} }
@ -125,13 +128,11 @@ abstract class BaseTpaClaimImportService
if (!empty($ticketMasterData['mapped_array'])) { if (!empty($ticketMasterData['mapped_array'])) {
$insert_res = $this->importClaimMaster($ticketMasterData['mapped_array']); $insert_res = $this->importClaimMaster($ticketMasterData['mapped_array']);
if (!$insert_res) { if (!$insert_res) {
$this->db->transRollback(); return $this->failTicketMasterInsert($file_id, 'Ticket Master Claim bulk insert failed');
return ['status' => false, 'message' => 'Ticket Master Claim bulk insert failed'];
} }
// Map newly created ticket IDs back to the TPA staging table // Map newly created ticket IDs back to the TPA staging table
if (!$this->updateTicketIdInTPATable($file_id)) { if (!$this->updateTicketIdInTPATable($file_id)) {
$this->db->transRollback(); return $this->failTicketMasterInsert($file_id, 'Updating ticket_id in TPA table failed');
return ['status' => false, 'message' => 'Updating ticket_id in TPA table failed'];
} }
$message .= 'Ticket Master Claim bulk insert success. '; $message .= 'Ticket Master Claim bulk insert success. ';
@ -144,8 +145,7 @@ abstract class BaseTpaClaimImportService
if (!empty($ticketMasterData['rejected_reason_array'])) { if (!empty($ticketMasterData['rejected_reason_array'])) {
$update_res = $this->updateTicketMasterRejectedReasonInTPATable($ticketMasterData['rejected_reason_array']); $update_res = $this->updateTicketMasterRejectedReasonInTPATable($ticketMasterData['rejected_reason_array']);
if (!$update_res) { if (!$update_res) {
$this->db->transRollback(); return $this->failTicketMasterInsert($file_id, 'Updating rejected reasons failed');
return ['status' => false, 'message' => 'Updating rejected reasons failed'];
} }
$message .= empty($ticketMasterData['mapped_array']) $message .= empty($ticketMasterData['mapped_array'])
@ -156,24 +156,69 @@ abstract class BaseTpaClaimImportService
// If nothing was processed but no error occurred // If nothing was processed but no error occurred
if (!$hasExecutedTask) { if (!$hasExecutedTask) {
$this->db->transRollback(); return $this->failTicketMasterInsert($file_id, 'No data found to process.');
return ['status' => false, 'message' => 'No data found to process.'];
} }
// 2. Commit the transaction // 2. Commit the transaction
$this->db->transCommit(); $this->db->transCommit();
if (!$status) {
$this->cleanupClaimDumpData($file_id);
}
return ['status' => $status, 'message' => trim($message)]; return ['status' => $status, 'message' => trim($message)];
} catch (\Throwable $th) { } catch (\Throwable $th) {
// 3. Rollback on crash $fileId = (int) ($params['file_id'] ?? 0);
$this->db->transRollback(); return $this->failTicketMasterInsert(
return [ $fileId,
'status' => false, 'System error during Ticket Master Insert: ' . $th->getMessage()
'message' => 'System error during Ticket Master Insert: ' . $th->getMessage() );
];
} }
} }
/**
* Remove TPA staging rows and ticket_master rows created for a failed claim dump upload.
*/
protected function cleanupClaimDumpData(int $fileId): void
{
if ($fileId <= 0) {
return;
}
$fileData = $this->claimDumpFileModel->where('id', $fileId)->first();
if (empty($fileData)) {
return;
}
$tpaId = (int) ($fileData['tpa_id'] ?? 0);
$tpaTable = $this->tpaTableMapping[$tpaId] ?? null;
if ($tpaTable !== null) {
$this->db->table($tpaTable)->where('file_id', $fileId)->delete();
}
$this->db->table('ticket_master')->where('file_id', $fileId)->delete();
}
protected function rollbackAndCleanupClaimDumpData(int $fileId): void
{
$this->db->transRollback();
$this->cleanupClaimDumpData($fileId);
}
protected function failTpaClaimDumpInsert(int $fileId, string $message): array
{
$this->rollbackAndCleanupClaimDumpData($fileId);
return ['status' => false, 'message' => $message];
}
protected function failTicketMasterInsert(int $fileId, string $message): array
{
$this->rollbackAndCleanupClaimDumpData($fileId);
return ['status' => false, 'message' => $message];
}
/** /**
* Read Excel and return associative rows (header based) * Read Excel and return associative rows (header based)
*/ */
@ -325,6 +370,14 @@ abstract class BaseTpaClaimImportService
*/ */
public function getEmployeeDetails(int $client_id, int $client_policy_id, string $emp_code, string $relation): array public function getEmployeeDetails(int $client_id, int $client_policy_id, string $emp_code, string $relation): array
{ {
$client_policy_data = $this->clientPolicyModel->where('id', $client_policy_id)->first();
if(!empty($client_policy_data)){
if(!empty($client_policy_data['base_policy'])){
$client_policy_id = $client_policy_data['base_policy'];
}
}
$EmployeeModel = new EmployeeModel(); $EmployeeModel = new EmployeeModel();
$employeeData = $EmployeeModel $employeeData = $EmployeeModel
->select([ ->select([

View File

@ -59,4 +59,18 @@ class ClaimFilesModel extends Model
return $data; return $data;
} }
/**
* Whether the claim (ticket) has at least one active PDF in claim_files.
*/
public function hasPdfFileForTicket($ticketId): bool
{
return $this->where('ticket_id', $ticketId)
->where('is_active', 1)
->groupStart()
->where('mime_type', 'pdf')
->orWhere('mime_type', 'application/pdf')
->groupEnd()
->countAllResults(false) > 0;
}
} }

View File

@ -756,14 +756,17 @@ class EmployeePolicyModel extends Model
LEFT JOIN ( LEFT JOIN (
SELECT SELECT
emp_code, emp_code,
group_key,
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 = '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 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, 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 MAX(CASE WHEN field_name = 'si_enhancement_date' THEN new_value END) AS date_of_coverage
FROM emp_endorsement FROM emp_endorsement
$subquery_endorsement_condition $subquery_endorsement_condition
GROUP BY emp_code AND actions = 'si'
) AS sidata ON a.emp_code = sidata.emp_code AND status != 'truncated'
GROUP BY emp_code, group_key
) AS sidata ON a.emp_code = sidata.emp_code AND a.group_key = sidata.group_key
WHERE employee_polices.client_policy_id = '{$client_policy_id}' WHERE employee_polices.client_policy_id = '{$client_policy_id}'
AND employees.client_branch_id = '{$client_branch_id}' AND employees.client_branch_id = '{$client_branch_id}'
$endorsement_condition $endorsement_condition
@ -2252,7 +2255,7 @@ class EmployeePolicyModel extends Model
} }
else if(count($emp_codes) > 0 && $all == false) else if(count($emp_codes) > 0 && $all == false)
{ {
$result->whereNotIn('emp.emp_code',$emp_codes); $result->whereNotIn('employee_polices.id',$emp_codes);
} }
else if(count($emp_codes) == 0 && $all == true) else if(count($emp_codes) == 0 && $all == true)
{ {

View File

@ -1118,12 +1118,23 @@ class TicketMasterModel extends Model
$policy_no = $params['policy_no'] ?? null; $policy_no = $params['policy_no'] ?? null;
$relationship = $params['relationship'] ?? null; $relationship = $params['relationship'] ?? null;
$insured_name = $params['insured_name'] ?? null; $insured_name = $params['insured_name'] ?? null;
$is_from = $params['is_from'] ?? null;
// $client_name = "6-Eleven"; // $client_name = "6-Eleven";
// $emp_code = "EMP0020K12"; // $emp_code = "EMP0020K12";
// $emp_name = "Lokesh"; // $emp_name = "Lokesh";
// $policy_no = "GMC-1999/2000/2021/2022"; // $policy_no = "GMC-1999/2000/2021/2022";
$base_policy_id = null;
if($is_from == "claim_dump"){
$client_policy_data = $this->db->table('client_policy')->where('policy_no', trim($policy_no))->where('is_active', 1)->get()->getRowArray();
if(isset($client_policy_data) && !empty($client_policy_data)){
if(!empty($client_policy_data['base_policy'])) {
$base_policy_id = $client_policy_data['base_policy'];
}
}
}
$builder = $this->db->table('employees e'); $builder = $this->db->table('employees e');
$builder->select(" $builder->select("
e.id as emp_id, e.id as emp_id,
@ -1161,7 +1172,13 @@ class TicketMasterModel extends Model
$builder->where('e.emp_code', trim($emp_code)); $builder->where('e.emp_code', trim($emp_code));
$builder->where('e.name', trim($emp_name)); $builder->where('e.name', trim($emp_name));
$builder->where('c.client_name', trim($client_name)); $builder->where('c.client_name', trim($client_name));
if(!empty($base_policy_id)) {
$builder->where('cp.id', trim($base_policy_id));
} else {
$builder->where('cp.policy_no', trim($policy_no)); $builder->where('cp.policy_no', trim($policy_no));
}
$builder->where('LOWER(e.relationship)', strtolower('self')); $builder->where('LOWER(e.relationship)', strtolower('self'));
$query = $builder->get(); $query = $builder->get();

View File

@ -112,18 +112,44 @@ for ($i = 0; $i < $batch_col_count; $i++) {
max-width: 95%; max-width: 95%;
} }
/* Make the modal content a flex column so only the body scrolls */
#tpa_variation_modal .modal-content { #tpa_variation_modal .modal-content {
max-height: 90vh; max-height: 90vh;
display: flex;
flex-direction: column;
} }
/* Internal vertical scroll for large tables, keep header/footer fixed */
#tpa_variation_modal .modal-body { #tpa_variation_modal .modal-body {
max-height: calc(85vh - 50px); flex: 1 1 auto;
overflow-y: auto; overflow-y: auto;
direction: ltr; direction: ltr;
} }
/* Tab panes must shrink inside flex modal-body so scrollX width is correct */
#tpa_variation_modal .tab-content,
#tpa_variation_modal .tab-pane {
min-width: 0;
}
/* Outer .table-responsive must not scroll when DataTables scrollX is active (see custom.css) */
#tpa_variation_modal .table-responsive { #tpa_variation_modal .table-responsive {
overflow-x: auto; width: 100%;
max-width: 100%;
}
#tpa_variation_modal .dataTables_wrapper {
width: 100%;
max-width: 100%;
}
#tpa_variation_modal .dataTables_scrollHead {
overflow: hidden !important;
}
#tpa_variation_modal .dataTables_scrollBody {
overflow-x: auto !important;
-webkit-overflow-scrolling: touch;
} }
#tpa_variation_modal table { #tpa_variation_modal table {
@ -548,6 +574,10 @@ for ($i = 0; $i < $batch_col_count; $i++) {
let tpaNotInNhanceProceedEnabled = true; let tpaNotInNhanceProceedEnabled = true;
/** From API `not_in_nhance_proceed_button_text` — label for Proceed on "Not in Nhance" tab. */ /** From API `not_in_nhance_proceed_button_text` — label for Proceed on "Not in Nhance" tab. */
let tpaNotInNhanceProceedButtonText = 'Proceed - Not in Nhance'; let tpaNotInNhanceProceedButtonText = 'Proceed - Not in Nhance';
/** From API `not_matched_count` — when 0, Proceed is disabled on "Need to Review" tab. */
let tpaNeedToReviewProceedEnabled = true;
/** From API `need_to_review_proceed_button_text` — label for Proceed on "Need to Review" tab. */
let tpaNeedToReviewProceedButtonText = 'Proceed - Need to Review ( 0 )';
const tpaVariationColumns = { const tpaVariationColumns = {
not_in_nhance: [ not_in_nhance: [
@ -694,6 +724,16 @@ for ($i = 0; $i < $batch_col_count; $i++) {
tpaNotInNhanceProceedButtonText = 'Proceed - Not in Nhance'; tpaNotInNhanceProceedButtonText = 'Proceed - Not in Nhance';
} }
const notMatchedCount = parseInt(data.not_matched_count, 10);
tpaNeedToReviewProceedEnabled = !isNaN(notMatchedCount) && notMatchedCount > 0;
if (typeof data.need_to_review_proceed_button_text === 'string' && data.need_to_review_proceed_button_text.trim() !== '') {
tpaNeedToReviewProceedButtonText = data.need_to_review_proceed_button_text.trim();
} else if (!isNaN(notMatchedCount)) {
tpaNeedToReviewProceedButtonText = 'Proceed - Need to Review ( ' + notMatchedCount + ' )';
} else {
tpaNeedToReviewProceedButtonText = 'Proceed - Need to Review ( 0 )';
}
showTPAVariationTabByLinkId('not-in-nhance-tab'); showTPAVariationTabByLinkId('not-in-nhance-tab');
updateTPAProceedButton('not-in-nhance-tab'); updateTPAProceedButton('not-in-nhance-tab');
adjustVariationTableByTabId('not-in-nhance-tab'); adjustVariationTableByTabId('not-in-nhance-tab');
@ -711,6 +751,20 @@ for ($i = 0; $i < $batch_col_count; $i++) {
updateTPAProceedButton($activeTab.attr('id')); updateTPAProceedButton($activeTab.attr('id'));
} }
function bindVariationScrollHeadSync($wrap) {
const $body = $wrap.find('.dataTables_scrollBody');
const $head = $wrap.find('.dataTables_scrollHead');
if (!$body.length || !$head.length) {
return;
}
$body.off('scroll.nhTpaVarHScroll').on('scroll.nhTpaVarHScroll', function () {
$head.scrollLeft($(this).scrollLeft());
});
$head.off('scroll.nhTpaVarHScroll').on('scroll.nhTpaVarHScroll', function () {
$body.scrollLeft($(this).scrollLeft());
});
}
function getVariationDataTableConfig() { function getVariationDataTableConfig() {
return { return {
dom: "<'dt-top'lf>" + dom: "<'dt-top'lf>" +
@ -722,7 +776,15 @@ for ($i = 0; $i < $batch_col_count; $i++) {
paging: true, paging: true,
ordering: false, ordering: false,
info: false, info: false,
scrollX: true,
scrollY: false,
scrollCollapse: false,
autoWidth: false, autoWidth: false,
initComplete: function () {
const $wrap = $(this.api().table().container());
$wrap.closest('.table-responsive').addClass('nh-dt-no-outer-scroll');
bindVariationScrollHeadSync($wrap);
},
language: { language: {
search: ` search: `
<div class="datatable-search-wrapper" style="position:relative; display:inline-block;"> <div class="datatable-search-wrapper" style="position:relative; display:inline-block;">
@ -773,8 +835,17 @@ for ($i = 0; $i < $batch_col_count; $i++) {
} }
const dt = $table.DataTable(); const dt = $table.DataTable();
const $wrap = $(dt.table().container());
bindVariationScrollHeadSync($wrap);
dt.columns.adjust().draw(false); dt.columns.adjust().draw(false);
bindVariationSearchIcons($table); bindVariationSearchIcons($table);
/* Re-measure after tab/modal becomes visible — hidden tables mis-size columns */
setTimeout(function () {
if ($table.is(':visible')) {
dt.columns.adjust().draw(false);
}
}, 0);
} }
function adjustVariationTableByTabId(tabId) { function adjustVariationTableByTabId(tabId) {
@ -814,7 +885,10 @@ for ($i = 0; $i < $batch_col_count; $i++) {
$button.prop('disabled', true); $button.prop('disabled', true);
} }
} else if (activeId === 'need-to-review-tab') { } else if (activeId === 'need-to-review-tab') {
$button.text('Proceed - Need to Review'); $button.text(tpaNeedToReviewProceedButtonText);
if (!tpaNeedToReviewProceedEnabled) {
$button.prop('disabled', true);
}
} else if (activeId === 'not-in-tpa-tab') { } else if (activeId === 'not-in-tpa-tab') {
$button.addClass('d-none'); $button.addClass('d-none');
} else { } else {
@ -829,12 +903,32 @@ for ($i = 0; $i < $batch_col_count; $i++) {
const activeId = $(e.target).attr('id'); const activeId = $(e.target).attr('id');
updateTPAProceedButton(activeId); updateTPAProceedButton(activeId);
adjustVariationTableByTabId(activeId); adjustVariationTableByTabId(activeId);
setTimeout(function () {
const tabToTableMap = {
'not-in-nhance-tab': '#not_in_nhance_table',
'not-in-tpa-tab': '#not_in_tpa_table',
'need-to-review-tab': '#need_to_review_table'
};
const sel = tabToTableMap[activeId];
const $t = sel ? $(sel) : $();
if ($.fn.DataTable.isDataTable($t)) {
$t.DataTable().columns.adjust().draw(false);
}
}, 50);
}); });
$('#tpa_variation_modal').on('shown.bs.modal', function () { $('#tpa_variation_modal').on('shown.bs.modal', function () {
showTPAVariationTabByLinkId('not-in-nhance-tab'); showTPAVariationTabByLinkId('not-in-nhance-tab');
updateTPAProceedButton('not-in-nhance-tab'); updateTPAProceedButton('not-in-nhance-tab');
adjustVariationTableByTabId('not-in-nhance-tab'); adjustVariationTableByTabId('not-in-nhance-tab');
setTimeout(function () {
['#not_in_nhance_table', '#not_in_tpa_table', '#need_to_review_table'].forEach(function (sel) {
const $t = $(sel);
if ($.fn.DataTable.isDataTable($t) && $t.is(':visible')) {
$t.DataTable().columns.adjust().draw(false);
}
});
}, 50);
}); });
$('#tpa_variation_modal').on('hidden.bs.modal', function () { $('#tpa_variation_modal').on('hidden.bs.modal', function () {
@ -1155,6 +1249,10 @@ for ($i = 0; $i < $batch_col_count; $i++) {
} else if (activeId === 'not-in-tpa-tab') { } else if (activeId === 'not-in-tpa-tab') {
proceedNotInTPA(); proceedNotInTPA();
} else if (activeId === 'need-to-review-tab') { } else if (activeId === 'need-to-review-tab') {
if (!tpaNeedToReviewProceedEnabled) {
toastr.warning('No mismatched records to proceed.', 'WARNING');
return;
}
proceedNeedToReview(); proceedNeedToReview();
} else { } else {
toastr.warning('Unknown tab selected.', 'WARNING'); toastr.warning('Unknown tab selected.', 'WARNING');

View File

@ -103,6 +103,11 @@
<h4 class="mb-0" style="position: relative;">File List</h4> <h4 class="mb-0" style="position: relative;">File List</h4>
</div> </div>
<div class="col-md-6 text-md-right mt-2 mt-md-0"> <div class="col-md-6 text-md-right mt-2 mt-md-0">
<button type="button" class="btn btn-warning waves-effect waves-light mr-2 d-none"
id="btn_manual_merge_claim_files"
title="Combine uploaded PDFs and images into one file">
Merge documents
</button>
<button type="button" class="btn btn-primary waves-effect waves-light" <button type="button" class="btn btn-primary waves-effect waves-light"
id="btn_upload_claim_files_to_tpa"> id="btn_upload_claim_files_to_tpa">
Upload files to TPA Upload files to TPA
@ -170,9 +175,18 @@
<script> <script>
$(document).ready(function(){ $(document).ready(function(){
let ticket_id = $('#ticket_master_id').val(); let ticket_id = getClaimFileListTicketId();
$('#ticket_id_url').val(ticket_id); $('#ticket_id_url').val(ticket_id);
let urlData = getUrlDataByTicketId(ticket_id); if (ticket_id) {
getUrlDataByTicketId(ticket_id);
}
});
$(document).on('shown.bs.tab', 'a[href="#uploads-tab"], #uploads_tab', function () {
var ticket_id = getClaimFileListTicketId();
if (ticket_id) {
getUrlDataByTicketId(ticket_id);
}
}); });
function getClaimFileListTicketId() { function getClaimFileListTicketId() {
@ -183,6 +197,88 @@
return id; return id;
} }
function resolveManualMergeUi(serverMergeUi, fileListData) {
if (serverMergeUi && serverMergeUi.show_manual_merge) {
return serverMergeUi;
}
if (!fileListData || !fileListData.length) {
return serverMergeUi || { show_manual_merge: false };
}
var hasMerged = fileListData.some(function (item) {
return item.file_type == 4 || item.file_type === '4';
});
var sourceCount = fileListData.filter(function (item) {
return item.file_type == 1 || item.file_type === '1'
|| item.file_type == 2 || item.file_type === '2';
}).length;
if (!hasMerged && sourceCount >= 1) {
return {
show_manual_merge: true,
button_label: 'Merge documents',
mergeable_count: sourceCount
};
}
return serverMergeUi || { show_manual_merge: false };
}
function updateManualMergeButton(mergeUi, fileListData) {
var $btn = $('#btn_manual_merge_claim_files');
if (!$btn.length) {
return;
}
var resolved = resolveManualMergeUi(mergeUi, fileListData);
if (resolved && resolved.show_manual_merge) {
$btn.removeClass('d-none').css('display', 'inline-block');
$btn.text(resolved.button_label || 'Merge documents');
$btn.prop('disabled', false);
} else {
$btn.addClass('d-none').css('display', '');
}
}
$(document).on('click', '#btn_manual_merge_claim_files', function () {
var ticket_id = getClaimFileListTicketId();
if (!ticket_id) {
toastr.warning('Ticket ID is missing. Please reload the page.', 'Validation');
return;
}
var $btn = $(this);
$.ajax({
url: "<?= base_url('ticket/manualMergeClaimFiles') ?>",
type: "POST",
data: { ticket_id: ticket_id },
dataType: "json",
beforeSend: function () {
$btn.prop('disabled', true);
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
},
success: function (res) {
if (res && res.status === true) {
toastr.success(res.message || 'Documents merged successfully', 'Success');
getUrlDataByTicketId(ticket_id);
} else {
toastr.error((res && res.message) ? res.message : 'Failed to merge documents', 'Error');
}
},
error: function (xhr) {
var msg = 'Failed to merge documents';
try {
var r = JSON.parse(xhr.responseText);
if (r.message) {
msg = r.message;
}
} catch (e) {}
toastr.error(msg, 'Error');
},
complete: function () {
$btn.prop('disabled', false);
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
}
});
});
$(document).on('click', '#btn_upload_claim_files_to_tpa', function () { $(document).on('click', '#btn_upload_claim_files_to_tpa', function () {
var ticket_id = getClaimFileListTicketId(); var ticket_id = getClaimFileListTicketId();
if (!ticket_id) { if (!ticket_id) {
@ -395,10 +491,13 @@
console.log('Form submitted response:', response); console.log('Form submitted response:', response);
if (response.status === true) { if (response.status === true) {
window._claimFilesMergeUi = response.merge_ui || null;
create_url_list(response.data); create_url_list(response.data);
updateManualMergeButton(response.merge_ui, response.data);
addHTMLInput(); addHTMLInput();
return ; return ;
} else { } else {
updateManualMergeButton(null, []);
addHTMLInput(); addHTMLInput();
console.warn("No Data"); console.warn("No Data");
} }
@ -555,6 +654,7 @@
} else { } else {
$('#table_bd').html('<tr><td colspan="5">No Data Found</td></tr>'); $('#table_bd').html('<tr><td colspan="5">No Data Found</td></tr>');
} }
updateManualMergeButton(window._claimFilesMergeUi || null, data || []);
} }
$(document).on('click', '.delete-url', function (e) { $(document).on('click', '.delete-url', function (e) {

View File

@ -163,7 +163,8 @@
</h4> --> </h4> -->
</div> </div>
<form role="form" class="parsley-examples" method="post" id="leads_form_id" <form role="form" class="parsley-examples" method="post" id="leads_form_id"
enctype="multipart/form-data"> enctype="multipart/form-data"
data-parsley-excluded="input[type=button], input[type=submit], input[type=reset], input[type=hidden], [disabled], :hidden, .select2-search__field">
<input type="hidden" name="id" id="leads_primarykey"> <input type="hidden" name="id" id="leads_primarykey">
<input type="hidden" name="lead_form_type" id="lead_form_type_id" value="<?= isset($selected_lead_type) ? $selected_lead_type : 1 ?>"> <input type="hidden" name="lead_form_type" id="lead_form_type_id" value="<?= isset($selected_lead_type) ? $selected_lead_type : 1 ?>">
@ -487,7 +488,7 @@
function restoreActualLeadGstNumber() { function restoreActualLeadGstNumber() {
if ($('#actual_lead_id').val() && $('#actual_lead_id').val() != 0 && actualLeadGstNumber) { if ($('#actual_lead_id').val() && $('#actual_lead_id').val() != 0 && actualLeadGstNumber) {
$('#gst').val(actualLeadGstNumber); $('#gst').val(String(actualLeadGstNumber).trim().toUpperCase());
} }
} }
@ -770,18 +771,7 @@
leadTypeBsedHideAndShow(lead_type, false, policy_type_id) leadTypeBsedHideAndShow(lead_type, false, policy_type_id)
if (lead_type == 1) { updateClaimRowVisibility(policy_type_id);
$('.claim-row').hide();
} else {
$('.claim-row').show();
if (policy_type_id == 1) {
$('.gpaClaimFileds').show();
$('.lifeClaimFields').hide();
} else if (policy_type_id == 6 || policy_type_id == 7) {
$('.gpaClaimFileds').hide();
$('.lifeClaimFields').show();
}
}
if (lead_type != 1 && policy_type_id != 1 && policy_type_id != 6 && policy_type_id != 7) { if (lead_type != 1 && policy_type_id != 1 && policy_type_id != 6 && policy_type_id != 7) {
// updateRenewalFields(dataIncrement); // updateRenewalFields(dataIncrement);
@ -1160,11 +1150,9 @@
leadTypeBsedHideAndShow(lead_type) leadTypeBsedHideAndShow(lead_type)
if (lead_type == 1) { updateClaimRowVisibility(policy_type_id);
$('.claim-row').hide();
} else if (!shouldShowClaimHistorySwitch(lead_type, policy_type_id)) {
$('.claim-row').show();
if (!shouldShowClaimHistorySwitch(lead_type, policy_type_id)) {
if (policy_type_id == 1) { if (policy_type_id == 1) {
$('.gpaClaimFileds').show(); $('.gpaClaimFileds').show();
$('.lifeClaimFields').hide(); $('.lifeClaimFields').hide();
@ -1774,15 +1762,56 @@
event.preventDefault(); event.preventDefault();
$('.claim-row').each(function() {
const isNil = $(this).find('.nil-claims-checkbox').prop('checked');
$(this).find('.nil-claims-value').val(isNil ? '1' : '0');
});
if (typeof window.prepareLeadsFormForSubmit === 'function') {
window.prepareLeadsFormForSubmit();
}
var isValid = $('#leads_form_id').parsley().validate(); var isValid = $('#leads_form_id').parsley().validate();
if (!isValid) { if (!isValid) {
$('#leads_form_id').find('input, select, textarea').each(function() { var invalidFields = typeof window.getLeadsFormInvalidFields === 'function'
if ($(this).parsley().isValid() === false && !$(this).val()) { ? window.getLeadsFormInvalidFields()
console.log('Empty field ID:', this.id); : [];
}
if (invalidFields.length) {
console.table(invalidFields);
invalidFields.forEach(function(f) {
console.log('Invalid field:', f.label || f.name || f.id, f);
}); });
console.log('Form is Empty', 'Warning');
var firstInvalid = invalidFields[0];
var fieldLabel = firstInvalid.label || firstInvalid.name || firstInvalid.id || 'A required field';
var fieldMessage = (firstInvalid.messages && firstInvalid.messages.length)
? firstInvalid.messages[0]
: (firstInvalid.isEmpty ? 'This field is required.' : 'Please check this field.');
if (typeof toastr !== 'undefined') {
toastr.warning(fieldLabel + ': ' + fieldMessage, 'Validation');
}
if (firstInvalid.id) {
var $invalidField = $('#' + firstInvalid.id);
if ($invalidField.length) {
var scrollTarget = $invalidField.closest('.form-group, .card, .dynamic-form-row');
if (scrollTarget.length) {
$('html, body').animate({
scrollTop: scrollTarget.offset().top - 100
}, 300);
}
$invalidField.focus();
}
}
} else {
console.warn('Form validation failed');
if (typeof toastr !== 'undefined') {
toastr.warning('Please correct the highlighted fields.', 'Validation');
}
}
return; return;
} }
@ -1803,12 +1832,11 @@
const jsonString = JSON.stringify(salse_person_id); const jsonString = JSON.stringify(salse_person_id);
console.log('jsonString', jsonString); console.log('jsonString', jsonString);
// Append the JSON string to the FormData object
formData.append('salse_person_id', jsonString); formData.append('salse_person_id', jsonString);
// Convert the claim experience array to JSON
const finyearJsonString = gatherClaimExperienceData(policy_type_ids); const finyearJsonString = gatherClaimExperienceData(policy_type_ids);
console.log('finyearJsonString', finyearJsonString); console.log('finyearJsonString', finyearJsonString);
formData.append('finyear', finyearJsonString); formData.append('finyear', finyearJsonString);
syncClaimHistoryFieldsToFormData(formData);
let claimHistoryStatus = $("#claim_history").length > 0 && $("#claim_history").prop("checked") ? 1 : 0; let claimHistoryStatus = $("#claim_history").length > 0 && $("#claim_history").prop("checked") ? 1 : 0;
formData.set('claim_history', claimHistoryStatus); formData.set('claim_history', claimHistoryStatus);
@ -2065,6 +2093,25 @@
$(".claim-row").each(function() { $(".claim-row").each(function() {
let isNilClaims = $(this).find(".nil-claims-checkbox").prop("checked");
if (isNilClaims) {
let year = $(this).find("[name='first_year[]']").val();
claimData.push({
"year": year,
"emp_id": "Nil",
"emp_name": "Nil",
"gender": "Nil",
"designation": "Nil",
"sum_insured": "Nil",
"death_date": "Nil",
"cause_of_death": "Nil",
"settled": "Nil",
"nil_claims": 1,
});
return;
}
let year = $(this).find("[name='first_year[]']").val(); let year = $(this).find("[name='first_year[]']").val();
let claimAmount = $(this).find("[name='first_claim_amount[]']").val(); let claimAmount = $(this).find("[name='first_claim_amount[]']").val();
let claimStatus = $(this).find("[name='first_claim_status[]']").val(); let claimStatus = $(this).find("[name='first_claim_status[]']").val();
@ -2088,6 +2135,7 @@
"death_date": deathDate, "death_date": deathDate,
"cause_of_death": causeOfDeath, "cause_of_death": causeOfDeath,
"settled": claimAmount, "settled": claimAmount,
"nil_claims": 0,
}); });
}); });
@ -2196,8 +2244,37 @@
return ['1', '6', '7'].includes(String(policyTypeId)); return ['1', '6', '7'].includes(String(policyTypeId));
} }
function getClaimHistoryLabel(leadType) {
return String(leadType) === '1' ? 'Mortality Claims' : 'Claims History';
}
function shouldShowClaimHistorySwitch(leadType, policyTypeId) { function shouldShowClaimHistorySwitch(leadType, policyTypeId) {
return (leadType == 2 || leadType == 3) && isClaimHistoryPolicyType(policyTypeId); return ['1', '2', '3'].includes(String(leadType)) && isClaimHistoryPolicyType(policyTypeId);
}
function updateClaimRowVisibility(fallbackPolicyTypeId = null) {
const leadType = $('#lead_type').val();
let policyTypeId = fallbackPolicyTypeId;
if (policyTypeId == null || policyTypeId === '') {
const $policySelect = $('[id^="policy_type_id_"]').first();
policyTypeId = $policySelect.length ? $policySelect.val() : '';
}
if (!shouldShowClaimHistorySwitch(leadType, policyTypeId)) {
$('.claim-row').hide();
return;
}
if ($('#claim_history').length) {
if ($('#claim_history').prop('checked')) {
$('.claim-row').show();
} else {
$('.claim-row').hide();
}
} else {
$('.claim-row').show();
}
} }
function appendThreeYearsClaims(count) { function appendThreeYearsClaims(count) {
@ -2210,20 +2287,21 @@
let lead_type = $('#lead_type').val(); let lead_type = $('#lead_type').val();
let showClaimHistorySwitch = shouldShowClaimHistorySwitch(lead_type, policy_type_id); let showClaimHistorySwitch = shouldShowClaimHistorySwitch(lead_type, policy_type_id);
let claimHistoryLabel = getClaimHistoryLabel(lead_type);
console.log('claimIndex from parent', claimIndex); console.log('claimIndex from parent', claimIndex);
let increment = claimIndex; let increment = claimIndex;
let claimsFields = `${showClaimHistorySwitch && !document.querySelector('#claim_history') ? `<div class="custom-control custom-switch"> let claimsFields = `${showClaimHistorySwitch && !document.querySelector('#claim_history') ? `<div class="custom-control custom-switch">
<input type="checkbox" onchange="claimHistoryToggle()" class="custom-control-input" id="claim_history" name="claim_history" checked> <input type="checkbox" onchange="claimHistoryToggle()" class="custom-control-input" id="claim_history" name="claim_history" checked>
<label class="custom-control-label" for="claim_history">Claims History</label> <label class="custom-control-label" for="claim_history">${claimHistoryLabel}</label>
</div><br>` : ``}`; </div><br>` : ``}`;
claimsFields += ` claimsFields += `
<div class="row claim-row"> <div class="row claim-row">
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-year-group">
<label for="first_year_${increment}">Year<span class="text-danger">*</span></label> <label for="first_year_${increment}">Year<span class="text-danger claim-required-star">*</span></label>
<select class="form-control first_year_ claim-input" id="first_year_${increment}" name="first_year[]"> <select class="form-control first_year_ claim-input" id="first_year_${increment}" name="first_year[]">
<option value="">Select Year</option> <option value="">Select Year</option>
<?php foreach ($lastFiveYears as $year) { <?php foreach ($lastFiveYears as $year) {
@ -2233,18 +2311,27 @@
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2">
<label for="emp_id_${increment}">Emp ID<span class="text-danger">*</span></label> <label>Nil Claims</label>
<input type="hidden" class="nil-claims-value" name="nil_claims[]" value="0">
<div class="custom-control custom-checkbox" style="padding-top: 8px;">
<input type="checkbox" class="custom-control-input nil-claims-checkbox" id="nil_claims_${increment}" onchange="nilClaimsToggle(this)">
<label class="custom-control-label" for="nil_claims_${increment}">Nil Claims</label>
</div>
</div>
<div class="form-group col-md-2 claim-field-group">
<label for="emp_id_${increment}">Emp ID<span class="text-danger claim-required-star">*</span></label>
<input type="text" class="form-control claim-input" id="emp_id_${increment}" name="emp_id[]"> <input type="text" class="form-control claim-input" id="emp_id_${increment}" name="emp_id[]">
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-field-group">
<label for="emp_name_${increment}">Employee Name<span class="text-danger">*</span></label> <label for="emp_name_${increment}">Employee Name<span class="text-danger claim-required-star">*</span></label>
<input type="text" class="form-control claim-input" id="emp_name_${increment}" name="emp_name[]"> <input type="text" class="form-control claim-input" id="emp_name_${increment}" name="emp_name[]">
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-field-group">
<label for="gender_${increment}">Gender<span class="text-danger">*</span></label> <label for="gender_${increment}">Gender<span class="text-danger claim-required-star">*</span></label>
<select class="form-control claim-input" id="gender_${increment}" name="gender[]"> <select class="form-control claim-input" id="gender_${increment}" name="gender[]">
<option value="">Select Gender</option> <option value="">Select Gender</option>
<option value="Female">Female</option> <option value="Female">Female</option>
@ -2252,26 +2339,26 @@
</select> </select>
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-field-group">
<label for="designation_${increment}">Designation <span class="text-danger">*</span></label> <label for="designation_${increment}">Designation <span class="text-danger claim-required-star">*</span></label>
<input type="text" class="form-control claim-input" id="designation_${increment}" name="designation[]"> <input type="text" class="form-control claim-input" id="designation_${increment}" name="designation[]">
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-field-group">
<label for="sum_insured_${increment}">Sum Insured <span class="text-danger">*</span></label> <label for="sum_insured_${increment}">Sum Insured <span class="text-danger claim-required-star">*</span></label>
<input type="text" class="form-control claim-input" id="sum_insured_${increment}" name="sum_insured[]"> <input type="text" class="form-control claim-input" id="sum_insured_${increment}" name="sum_insured[]">
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-field-group">
<label for="first_death_date_${increment}">Date of Death<span class="text-danger">*</span></label> <label for="first_death_date_${increment}">Date of Death<span class="text-danger claim-required-star">*</span></label>
<div class="input-icon"> <div class="input-icon">
<input type="text" class="form-control death_date flatpickr-date claim-input" id="first_death_date_${increment}" name="first_death_date[]" autocomplete="off"> <input type="text" class="form-control death_date flatpickr-date claim-input" id="first_death_date_${increment}" name="first_death_date[]" autocomplete="off">
<i class="mdi mdi-calendar-blank-outline additional-icon"></i> <i class="mdi mdi-calendar-blank-outline additional-icon"></i>
</div> </div>
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-field-group">
<label for="first_cause_of_death_${increment}">Nature/Cause Of Death <span class="text-danger">*</span></label> <label for="first_cause_of_death_${increment}">Nature/Cause Of Death <span class="text-danger claim-required-star">*</span></label>
<select class="form-control claim-input" id="first_cause_of_death_${increment}" name="first_cause_of_death[]"> <select class="form-control claim-input" id="first_cause_of_death_${increment}" name="first_cause_of_death[]">
<option value="">Select Cause of Death</option> <option value="">Select Cause of Death</option>
<?php foreach ($causeOfDeath as $cause => $death_value) { <?php foreach ($causeOfDeath as $cause => $death_value) {
@ -2280,8 +2367,8 @@
</select> </select>
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-field-group">
<label for="first_claim_amount_${increment}">Claim/Settled Amount<span class="text-danger">*</span></label> <label for="first_claim_amount_${increment}">Claim/Settled Amount<span class="text-danger claim-required-star">*</span></label>
<input type="text" class="form-control claim-input" id="first_claim_amount_${increment}" name="first_claim_amount[]"> <input type="text" class="form-control claim-input" id="first_claim_amount_${increment}" name="first_claim_amount[]">
</div> </div>
@ -2345,6 +2432,8 @@
if (showClaimHistorySwitch) { if (showClaimHistorySwitch) {
claimHistoryToggle(); claimHistoryToggle();
} else {
updateClaimRowVisibility(policy_type_id);
} }
toggleRequiredFields(); toggleRequiredFields();
@ -2363,15 +2452,198 @@
} }
} }
function isClaimRowNilClaims($row) {
return $row.find('.nil-claims-checkbox').prop('checked');
}
function setClaimSelectValue($select, value) {
if (!$select.length) {
return;
}
if ($select.find('option[value="' + value + '"]').length === 0) {
$select.append($('<option>', { value: value, text: value }));
}
$select.val(value);
if ($select.hasClass('select2-hidden-accessible')) {
$select.trigger('change');
}
}
function resetClaimYearField($yearField) {
if (!$yearField.length) {
return;
}
$yearField.find('option[value="Nil"]').remove();
if ($yearField.val() === 'Nil') {
$yearField.val('').trigger('change');
}
}
function nilClaimsToggle(checkbox) {
const $row = $(checkbox).closest('.claim-row');
const isNil = $(checkbox).prop('checked');
const $yearField = $row.find('[name="first_year[]"]');
resetClaimYearField($yearField);
$row.find('.nil-claims-value').val(isNil ? '1' : '0');
$row.toggleClass('claim-row-nil', isNil);
$row.find('.claim-field-group .claim-required-star').toggle(!isNil);
$row.find('.claim-input').not('[name="first_year[]"]').each(function() {
const $field = $(this);
if (isNil) {
if ($field.is('select')) {
setClaimSelectValue($field, 'Nil');
} else {
$field.val('Nil');
}
$field.prop('disabled', true).removeAttr('required');
if ($field.hasClass('select2-hidden-accessible')) {
$field.next('.select2-container').addClass('select2-container--disabled');
}
if ($field.parsley) {
$field.parsley().reset();
}
} else {
$field.prop('disabled', false);
if ($field.hasClass('select2-hidden-accessible')) {
$field.next('.select2-container').removeClass('select2-container--disabled');
}
if ($field.is('select')) {
$field.find('option[value="Nil"]').remove();
$field.val('').trigger('change');
} else {
$field.val('');
}
}
});
const claimHistoryOn = !$('#claim_history').length || $('#claim_history').prop('checked');
if (claimHistoryOn) {
$yearField.prop('required', true).prop('disabled', false);
if ($yearField.hasClass('select2-hidden-accessible')) {
$yearField.next('.select2-container').removeClass('select2-container--disabled');
}
if (!isNil) {
$row.find('.claim-input').not('[name="first_year[]"]').prop('required', true);
}
}
toggleRequiredFields();
if (typeof window.refreshLeadsFormValidation === 'function') {
window.refreshLeadsFormValidation();
}
}
function initNilClaimsRows() {
$('.claim-row .nil-claims-checkbox:checked').each(function() {
nilClaimsToggle(this);
});
}
function syncClaimHistoryFieldsToFormData(formData) {
const $rows = $('.claim-row');
if (!$rows.length) {
return;
}
const isEbRow = $rows.first().find('[name="emp_id[]"]').length > 0;
const fieldNames = isEbRow
? ['first_year[]', 'nil_claims[]', 'emp_id[]', 'emp_name[]', 'gender[]', 'designation[]', 'sum_insured[]', 'first_death_date[]', 'first_cause_of_death[]', 'first_claim_amount[]']
: ['first_year[]', 'nil_claims[]', 'first_policy_type_[]', 'first_date_of_loss_[]', 'first_cause_of_loss[]', 'first_claim_amount[]', 'first_settled_amount[]', 'first_claim_status[]'];
fieldNames.forEach(function(name) {
if (typeof formData.delete === 'function') {
formData.delete(name);
}
});
$rows.each(function() {
const $row = $(this);
const isNil = $row.find('.nil-claims-checkbox').prop('checked');
$row.find('.nil-claims-value').val(isNil ? '1' : '0');
formData.append('first_year[]', $row.find('[name="first_year[]"]').val() || '');
formData.append('nil_claims[]', isNil ? '1' : '0');
if (isEbRow) {
if (isNil) {
formData.append('emp_id[]', 'Nil');
formData.append('emp_name[]', 'Nil');
formData.append('gender[]', 'Nil');
formData.append('designation[]', 'Nil');
formData.append('sum_insured[]', 'Nil');
formData.append('first_death_date[]', 'Nil');
formData.append('first_cause_of_death[]', 'Nil');
formData.append('first_claim_amount[]', 'Nil');
} else {
formData.append('emp_id[]', $row.find('[name="emp_id[]"]').val() || '');
formData.append('emp_name[]', $row.find('[name="emp_name[]"]').val() || '');
formData.append('gender[]', $row.find('[name="gender[]"]').val() || '');
formData.append('designation[]', $row.find('[name="designation[]"]').val() || '');
formData.append('sum_insured[]', $row.find('[name="sum_insured[]"]').val() || '');
formData.append('first_death_date[]', $row.find('[name="first_death_date[]"]').val() || '');
formData.append('first_cause_of_death[]', $row.find('[name="first_cause_of_death[]"]').val() || '');
formData.append('first_claim_amount[]', $row.find('[name="first_claim_amount[]"]').val() || '');
}
} else if (isNil) {
formData.append('first_policy_type_[]', 'Nil');
formData.append('first_date_of_loss_[]', 'Nil');
formData.append('first_cause_of_loss[]', 'Nil');
formData.append('first_claim_amount[]', 'Nil');
formData.append('first_settled_amount[]', 'Nil');
formData.append('first_claim_status[]', 'Nil');
} else {
formData.append('first_policy_type_[]', $row.find('[name="first_policy_type_[]"]').val() || '');
formData.append('first_date_of_loss_[]', $row.find('[name="first_date_of_loss_[]"]').val() || '');
formData.append('first_cause_of_loss[]', $row.find('[name="first_cause_of_loss[]"]').val() || '');
formData.append('first_claim_amount[]', $row.find('[name="first_claim_amount[]"]').val() || '');
formData.append('first_settled_amount[]', $row.find('[name="first_settled_amount[]"]').val() || '');
formData.append('first_claim_status[]', $row.find('[name="first_claim_status[]"]').val() || '');
}
});
}
function claimHistoryToggle() { function claimHistoryToggle() {
let claimHistoryStatus = $("#claim_history").prop("checked") ? 1 : 0; let claimHistoryStatus = $("#claim_history").prop("checked") ? 1 : 0;
if (claimHistoryStatus == 1) { if (claimHistoryStatus == 1) {
$(".claim-row").show(); $(".claim-row").show();
$(".claim-input").attr("required", true); $(".claim-row").each(function() {
const $row = $(this);
$row.find('[name="first_year[]"]').prop("required", true);
if (!isClaimRowNilClaims($row)) {
$row.find(".claim-input").not('[name="first_year[]"]').prop("required", true);
}
});
} else { } else {
$(".claim-row").hide(); $(".claim-row").hide();
$(".claim-input").removeAttr("required").val(""); $(".claim-row").each(function() {
const $row = $(this);
$row.find('.nil-claims-checkbox').prop('checked', false);
$row.find('.nil-claims-value').val('0');
$row.removeClass('claim-row-nil');
$row.find('.claim-required-star').show();
});
$(".claim-input").removeAttr("required").prop('disabled', false).val("");
$(".claim-input").each(function() { $(".claim-input").each(function() {
if ($(this).hasClass('select2-hidden-accessible')) { if ($(this).hasClass('select2-hidden-accessible')) {
$(this).val(null).trigger('change'); $(this).val(null).trigger('change');
@ -2408,7 +2680,7 @@
if (value == 1) { if (value == 1) {
$('.btnDiv').show(); $('.btnDiv').show();
$('.claim-row').hide(); updateClaimRowVisibility(fallbackPolicyTypeId);
$('.emp_title_text').text('No of Employees') $('.emp_title_text').text('No of Employees')
$('.depnd_title_text').text('No of Dependents') $('.depnd_title_text').text('No of Dependents')
@ -2497,7 +2769,7 @@
} else { } else {
$('.btnDiv').hide(); $('.btnDiv').hide();
$('.claim-row').show(); updateClaimRowVisibility(fallbackPolicyTypeId);
$('.emp_title_text').text('No of Employees at Inception') $('.emp_title_text').text('No of Employees at Inception')
$('.depnd_title_text').text(' No of Dependents at Inception') $('.depnd_title_text').text(' No of Dependents at Inception')
@ -2564,27 +2836,30 @@
toggleRequiredFields(); toggleRequiredFields();
restoreActualLeadGstNumber(); restoreActualLeadGstNumber();
restoreActualLeadContactDetails(); restoreActualLeadContactDetails();
if (typeof window.refreshLeadsFormValidation === 'function') {
window.refreshLeadsFormValidation();
}
} }
function toggleRequiredFields() { function toggleRequiredFields() {
try { try {
const claimHistoryOn = !$('#claim_history').length || $('#claim_history').prop('checked');
$('.claim-row').each(function() { $('.claim-row').each(function() {
var isRowHidden = $(this).css('display') === 'none'; var isRowHidden = $(this).css('display') === 'none';
var isNilClaims = isClaimRowNilClaims($(this));
$(this).find('.form-group').each(function() { $(this).find('.claim-year-group .claim-input').prop('required', claimHistoryOn && !isRowHidden);
var input = $(this).find('input, select');
if (input.attr('name') === "gender[]") { $(this).find('.claim-field-group').each(function() {
return; var input = $(this).find('input.claim-input, select.claim-input');
}
if (input.length === 0) { if (input.length === 0) {
console.warn('No input/select fields found in:', this);
return; return;
} }
// Remove required if row is hidden, otherwise check field visibility input.prop('required', claimHistoryOn && !isRowHidden && !isNilClaims && $(this).css('display') !== 'none');
input.prop('required', !isRowHidden && $(this).css('display') !== 'none');
}); });
}); });
} catch (error) { } catch (error) {
@ -2694,7 +2969,7 @@
actualLeadClientName = actual_lead_client_details.company_name || ''; actualLeadClientName = actual_lead_client_details.company_name || '';
$('#client_name').val(actualLeadClientName); $('#client_name').val(actualLeadClientName);
actualLeadGstNumber = actual_lead_client_details.gst_number || actual_lead_client_details.gst || ''; actualLeadGstNumber = (actual_lead_client_details.gst_number || actual_lead_client_details.gst || '').toString().trim().toUpperCase();
$('#gst').val(actualLeadGstNumber); $('#gst').val(actualLeadGstNumber);
if (actual_lead_client_details.client_type !== undefined && actual_lead_client_details.client_type !== null && actual_lead_client_details.client_type !== '') { if (actual_lead_client_details.client_type !== undefined && actual_lead_client_details.client_type !== null && actual_lead_client_details.client_type !== '') {
$('#client_type').val(String(actual_lead_client_details.client_type)); $('#client_type').val(String(actual_lead_client_details.client_type));

View File

@ -846,12 +846,22 @@ if (isset($selected_lead_type)) {
claimHistoryToggle(); claimHistoryToggle();
} }
if (typeof initNilClaimsRows === 'function') {
initNilClaimsRows();
}
if (typeof updateClaimRowVisibility === 'function') {
updateClaimRowVisibility(policy_type_id);
}
$('.loader').fadeIn(); $('.loader').fadeIn();
$('.loader-mask').fadeIn(); $('.loader-mask').fadeIn();
if (lead_type == 1 || lead_type == 3) { if (lead_type == 1 || lead_type == 3) {
if (lead_type == 1 || !shouldShowClaimHistorySwitch(lead_type, policy_type_id)) { if (typeof updateClaimRowVisibility === 'function') {
updateClaimRowVisibility(policy_type_id);
} else if (!shouldShowClaimHistorySwitch(lead_type, policy_type_id)) {
$('.claim-row').hide(); $('.claim-row').hide();
} }
@ -948,6 +958,14 @@ if (isset($selected_lead_type)) {
claimHistoryToggle(); claimHistoryToggle();
} }
if (typeof initNilClaimsRows === 'function') {
initNilClaimsRows();
}
if (typeof updateClaimRowVisibility === 'function') {
updateClaimRowVisibility(policy_type_id);
}
if(lead_type == 3){ if(lead_type == 3){
let incurred_claim_date_id = 'incurred_claim_date'; let incurred_claim_date_id = 'incurred_claim_date';
@ -1121,7 +1139,7 @@ if (isset($selected_lead_type)) {
let policy_type_id = data.policy_type_id || null; let policy_type_id = data.policy_type_id || null;
let lead_type = data.lead_type || null; let lead_type = data.lead_type || null;
leadTypeBsedHideAndShow(lead_type); $('#lead_type').val(lead_type || '');
const isExistingClient = data.client_id !== undefined const isExistingClient = data.client_id !== undefined
&& data.client_id !== null && data.client_id !== null
@ -1192,7 +1210,6 @@ if (isset($selected_lead_type)) {
$('#leads_primarykey').val(data.id || ''); $('#leads_primarykey').val(data.id || '');
$('#actual_lead_id').val(data.actual_lead_id || 0); $('#actual_lead_id').val(data.actual_lead_id || 0);
$('#policy_start_date').val(data.policy_end_date || ''); $('#policy_start_date').val(data.policy_end_date || '');
$('#lead_type').val(data.lead_type || '');
$('#issuer').val(data.issuer || ''); $('#issuer').val(data.issuer || '');
$('#client_type').val(data.client_type || ''); $('#client_type').val(data.client_type || '');
$('#client_name').val(data.client_name || ''); $('#client_name').val(data.client_name || '');
@ -1253,9 +1270,23 @@ if (isset($selected_lead_type)) {
selecSalsePerson(data.salse_person_id); selecSalsePerson(data.salse_person_id);
} }
leadTypeBsedHideAndShow(lead_type, false, Boolean(data.claims_details_html));
let referenceDiv = document.getElementById('appendAreaForClaim'); let referenceDiv = document.getElementById('appendAreaForClaim');
referenceDiv.innerHTML = ''; referenceDiv.innerHTML = '';
referenceDiv.insertAdjacentHTML('beforeend', data.claims_details_html); referenceDiv.insertAdjacentHTML('beforeend', data.claims_details_html || '');
if (typeof initNilClaimsRows === 'function') {
initNilClaimsRows();
}
if (typeof updateNonEbClaimRowVisibility === 'function') {
updateNonEbClaimRowVisibility(lead_type);
} else if (typeof updateClaimRowVisibility === 'function') {
updateClaimRowVisibility(data.policy_type_id);
} else if (!data.claims_details_html && typeof setupNonEbClaimDetailsSection === 'function' && shouldShowNonEbClaimHistory(lead_type)) {
setupNonEbClaimDetailsSection(lead_type);
}
console.log("wdesfgefwregfefwregffeegf",data.lead_type); console.log("wdesfgefwregfefwregffeegf",data.lead_type);
var lead_type_value = data.lead_type; var lead_type_value = data.lead_type;

View File

@ -647,14 +647,7 @@ var pageBackButton = '<a href="<?= base_url('leads/list') ?>" class="topbar-icon
console.log(response.message, 'WARNING'); console.log(response.message, 'WARNING');
} }
if (lead_type != 1 && lead_type != 3) { setupNonEbClaimDetailsSection();
let html = `<hr><div class="form-row"> <div class="form-group col-md-3"><h4> Claim Details </h4></div></div>`
let referenceDiv = document.getElementById('appendAreaForClaim');
referenceDiv.insertAdjacentHTML('beforeend', html);
appendThreeYearsClaims();
}
// Hide loader // Hide loader
$('.loader').fadeOut(); $('.loader').fadeOut();
@ -675,6 +668,11 @@ var pageBackButton = '<a href="<?= base_url('leads/list') ?>" class="topbar-icon
event.preventDefault(); event.preventDefault();
$('.claim-row').each(function() {
const isNil = $(this).find('.nil-claims-checkbox').prop('checked');
$(this).find('.nil-claims-value').val(isNil ? '1' : '0');
});
var isValid = $('#leads_non_eb_form_id').parsley().validate(); var isValid = $('#leads_non_eb_form_id').parsley().validate();
console.log('isValid', isValid) console.log('isValid', isValid)
@ -728,6 +726,7 @@ var pageBackButton = '<a href="<?= base_url('leads/list') ?>" class="topbar-icon
const finyearJsonString = gatherClaimExperienceData(); const finyearJsonString = gatherClaimExperienceData();
console.log('finyearJsonString', finyearJsonString); console.log('finyearJsonString', finyearJsonString);
formData.append('fin_years_claims', finyearJsonString); formData.append('fin_years_claims', finyearJsonString);
syncClaimHistoryFieldsToFormData(formData);
cliam_history_status = $("#claim_history").prop("checked") ? 1 : 0; cliam_history_status = $("#claim_history").prop("checked") ? 1 : 0;
@ -799,7 +798,7 @@ var pageBackButton = '<a href="<?= base_url('leads/list') ?>" class="topbar-icon
}); });
$('#lead_type').change(function() { $('#lead_type').change(function() {
let value = $(this).val() let value = $(this).val();
// alert(value); // alert(value);
if (value == 1 || value == 3) { if (value == 1 || value == 3) {
// alert("Function Called"); // alert("Function Called");
@ -840,7 +839,7 @@ var pageBackButton = '<a href="<?= base_url('leads/list') ?>" class="topbar-icon
} }
leadTypeBsedHideAndShow(value, true) leadTypeBsedHideAndShow(value, true);
$('#contact_person_summary').empty(); $('#contact_person_summary').empty();
$('#contact_person_summary').append($('<option>', { $('#contact_person_summary').append($('<option>', {
@ -906,13 +905,72 @@ var pageBackButton = '<a href="<?= base_url('leads/list') ?>" class="topbar-icon
}) })
function leadTypeBsedHideAndShow(value, resetValues = false) { function getClaimHistoryLabel(leadType) {
return String(leadType) === '1' ? 'Mortality Claims' : 'Claims History';
}
function getClaimDetailsSectionTitle(leadType) {
return String(leadType) === '1' ? 'Mortality Claims' : 'Claim Details';
}
function shouldShowNonEbClaimHistory(leadType) {
return ['1', '2', '3'].includes(String(leadType));
}
function updateNonEbClaimRowVisibility(leadTypeOverride) {
const leadType = leadTypeOverride ?? $('#lead_type').val();
if (!shouldShowNonEbClaimHistory(leadType)) {
$('.claim-row').hide();
return;
}
if ($('#claim_history').length) {
if ($('#claim_history').prop('checked')) {
$('.claim-row').show();
} else {
$('.claim-row').hide();
}
} else {
$('.claim-row').show();
}
}
function setupNonEbClaimDetailsSection(leadTypeOverride) {
const leadType = leadTypeOverride ?? $('#lead_type').val();
const referenceDiv = document.getElementById('appendAreaForClaim');
if (!referenceDiv) {
return;
}
referenceDiv.innerHTML = '';
if (!shouldShowNonEbClaimHistory(leadType)) {
return;
}
const sectionTitle = getClaimDetailsSectionTitle(leadType);
const html = `<hr><div class="form-row claim-details-section-header"><div class="form-group col-md-3"><h4>${sectionTitle}</h4></div></div>`;
referenceDiv.insertAdjacentHTML('beforeend', html);
appendThreeYearsClaims();
updateNonEbClaimRowVisibility(leadType);
}
function leadTypeBsedHideAndShow(value, resetValues = false, skipClaimSetup = false) {
var actual_lead_id = $('#actual_lead_id').val(); var actual_lead_id = $('#actual_lead_id').val();
if (value == 1 || value == 3) { if (value == 1 || value == 3) {
$('.btnDiv').show(); $('.btnDiv').show();
if (!skipClaimSetup && shouldShowNonEbClaimHistory(value)) {
setupNonEbClaimDetailsSection(value);
} else if (!shouldShowNonEbClaimHistory(value)) {
$('#appendAreaForClaim').empty();
$('.claim-row').hide(); $('.claim-row').hide();
}
$('.emp_title_text').text('No of Employees') $('.emp_title_text').text('No of Employees')
@ -950,7 +1008,10 @@ var pageBackButton = '<a href="<?= base_url('leads/list') ?>" class="topbar-icon
} else { } else {
$('.btnDiv').hide(); $('.btnDiv').hide();
$('.claim-row').show();
if (!skipClaimSetup && shouldShowNonEbClaimHistory(value)) {
setupNonEbClaimDetailsSection(value);
}
$('.emp_title_text').text('No of Employees at Inception') $('.emp_title_text').text('No of Employees at Inception')
$('.depnd_title_text').text(' No of Dependents at Inception') $('.depnd_title_text').text(' No of Dependents at Inception')
@ -1178,11 +1239,158 @@ var pageBackButton = '<a href="<?= base_url('leads/list') ?>" class="topbar-icon
var increment = 1; var increment = 1;
function isClaimRowNilClaims($row) {
return $row.find('.nil-claims-checkbox').prop('checked');
}
function setClaimSelectValue($select, value) {
if (!$select.length) {
return;
}
if ($select.find('option[value="' + value + '"]').length === 0) {
$select.append($('<option>', { value: value, text: value }));
}
$select.val(value);
if ($select.hasClass('select2-hidden-accessible')) {
$select.trigger('change');
}
}
function resetClaimYearField($yearField) {
if (!$yearField.length) {
return;
}
$yearField.find('option[value="Nil"]').remove();
if ($yearField.val() === 'Nil') {
$yearField.val('').trigger('change');
}
}
function nilClaimsToggle(checkbox) {
const $row = $(checkbox).closest('.claim-row');
const isNil = $(checkbox).prop('checked');
const $yearField = $row.find('[name="first_year[]"]');
resetClaimYearField($yearField);
$row.find('.nil-claims-value').val(isNil ? '1' : '0');
$row.toggleClass('claim-row-nil', isNil);
$row.find('.claim-field-group .claim-required-star').toggle(!isNil);
$row.find('.claim-input').not('[name="first_year[]"]').each(function() {
const $field = $(this);
if (isNil) {
if ($field.is('select')) {
setClaimSelectValue($field, 'Nil');
} else {
$field.val('Nil');
}
$field.prop('disabled', true).removeAttr('required');
if ($field.hasClass('select2-hidden-accessible')) {
$field.next('.select2-container').addClass('select2-container--disabled');
}
if ($field.parsley) {
$field.parsley().reset();
}
} else {
$field.prop('disabled', false);
if ($field.hasClass('select2-hidden-accessible')) {
$field.next('.select2-container').removeClass('select2-container--disabled');
}
if ($field.is('select')) {
$field.find('option[value="Nil"]').remove();
$field.val('').trigger('change');
} else {
$field.val('');
}
}
});
const claimHistoryOn = !$('#claim_history').length || $('#claim_history').prop('checked');
if (claimHistoryOn) {
$yearField.prop('required', true).prop('disabled', false);
if ($yearField.hasClass('select2-hidden-accessible')) {
$yearField.next('.select2-container').removeClass('select2-container--disabled');
}
if (!isNil) {
$row.find('.claim-input').not('[name="first_year[]"]').prop('required', true);
}
}
if (typeof window.refreshLeadsFormValidation === 'function') {
window.refreshLeadsFormValidation();
}
}
function initNilClaimsRows() {
$('.claim-row .nil-claims-checkbox:checked').each(function() {
nilClaimsToggle(this);
});
}
function syncClaimHistoryFieldsToFormData(formData) {
const $rows = $('.claim-row');
if (!$rows.length) {
return;
}
const fieldNames = ['first_year[]', 'nil_claims[]', 'first_policy_type_[]', 'first_date_of_loss_[]', 'first_cause_of_loss[]', 'first_claim_amount[]', 'first_settled_amount[]', 'first_claim_status[]'];
fieldNames.forEach(function(name) {
if (typeof formData.delete === 'function') {
formData.delete(name);
}
});
$rows.each(function() {
const $row = $(this);
const isNil = $row.find('.nil-claims-checkbox').prop('checked');
$row.find('.nil-claims-value').val(isNil ? '1' : '0');
formData.append('first_year[]', $row.find('[name="first_year[]"]').val() || '');
formData.append('nil_claims[]', isNil ? '1' : '0');
if (isNil) {
formData.append('first_policy_type_[]', 'Nil');
formData.append('first_date_of_loss_[]', 'Nil');
formData.append('first_cause_of_loss[]', 'Nil');
formData.append('first_claim_amount[]', 'Nil');
formData.append('first_settled_amount[]', 'Nil');
formData.append('first_claim_status[]', 'Nil');
} else {
formData.append('first_policy_type_[]', $row.find('[name="first_policy_type_[]"]').val() || '');
formData.append('first_date_of_loss_[]', $row.find('[name="first_date_of_loss_[]"]').val() || '');
formData.append('first_cause_of_loss[]', $row.find('[name="first_cause_of_loss[]"]').val() || '');
formData.append('first_claim_amount[]', $row.find('[name="first_claim_amount[]"]').val() || '');
formData.append('first_settled_amount[]', $row.find('[name="first_settled_amount[]"]').val() || '');
formData.append('first_claim_status[]', $row.find('[name="first_claim_status[]"]').val() || '');
}
});
}
function appendThreeYearsClaims() { function appendThreeYearsClaims() {
const leadType = $('#lead_type').val();
const claimHistoryLabel = getClaimHistoryLabel(leadType);
let claimsFields = `${!document.querySelector('#claim_history') ? `<div class="custom-control custom-switch"> let claimsFields = `${!document.querySelector('#claim_history') ? `<div class="custom-control custom-switch">
<input type="checkbox" onchange="claimHistoryToggle()" class="custom-control-input" id="claim_history" name="claim_history" checked /> <input type="checkbox" onchange="claimHistoryToggle()" class="custom-control-input" id="claim_history" name="claim_history" checked />
<label class="custom-control-label" for="claim_history">Claims History</label> <label class="custom-control-label" for="claim_history">${claimHistoryLabel}</label>
</div><br>`: ``}` </div><br>`: ``}`
claimsFields += ` claimsFields += `
@ -1190,8 +1398,8 @@ var pageBackButton = '<a href="<?= base_url('leads/list') ?>" class="topbar-icon
<div id = "claimHistoryRow" class="row claim-row"> <div id = "claimHistoryRow" class="row claim-row">
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-year-group">
<label for="first_year_${increment}">Year<span class="text-danger">*</span></label> <label for="first_year_${increment}">Year<span class="text-danger claim-required-star">*</span></label>
<select class="form-control claim-input first_year_" id="first_year_${increment}" name="first_year[]"> <select class="form-control claim-input first_year_" id="first_year_${increment}" name="first_year[]">
<option value="">Select Year</option> <option value="">Select Year</option>
<?php foreach ($lastFiveYears as $year) { <?php foreach ($lastFiveYears as $year) {
@ -1199,28 +1407,38 @@ var pageBackButton = '<a href="<?= base_url('leads/list') ?>" class="topbar-icon
} ?> } ?>
</select> </select>
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2">
<label for="first_policy_type_${increment}">Policy Type<span class="text-danger">*</span></label> <label>Nil Claims</label>
<input type="hidden" class="nil-claims-value" name="nil_claims[]" value="0">
<div class="custom-control custom-checkbox" style="padding-top: 8px;">
<input type="checkbox" class="custom-control-input nil-claims-checkbox" id="nil_claims_${increment}" onchange="nilClaimsToggle(this)">
<label class="custom-control-label" for="nil_claims_${increment}">Nil Claims</label>
</div>
</div>
<div class="form-group col-md-2 claim-field-group">
<label for="first_policy_type_${increment}">Policy Type<span class="text-danger claim-required-star">*</span></label>
<input type="text" class="form-control claim-input" id="first_policy_type_${increment}" name="first_policy_type_[]"> <input type="text" class="form-control claim-input" id="first_policy_type_${increment}" name="first_policy_type_[]">
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-field-group">
<label for="first_date_of_loss_${increment}">Date of Loss<span class="text-danger">*</span></label> <label for="first_date_of_loss_${increment}">Date of Loss<span class="text-danger claim-required-star">*</span></label>
<input type="text" class="form-control loss_date claim-input" id="first_date_of_loss_${increment}" name="first_date_of_loss_[]"> <input type="text" class="form-control loss_date claim-input" id="first_date_of_loss_${increment}" name="first_date_of_loss_[]">
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-field-group">
<label for="first_cause_of_death_${increment}">Cause Of Loss <span class="text-danger">*</span></label> <label for="first_cause_of_loss_${increment}">Cause Of Loss <span class="text-danger claim-required-star">*</span></label>
<input type="text" class="form-control claim-input" id="first_cause_of_loss_${increment}" name="first_cause_of_loss[]"> <input type="text" class="form-control claim-input" id="first_cause_of_loss_${increment}" name="first_cause_of_loss[]">
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-field-group">
<label for="first_claim_amount_${increment}">Claim Amount<span class="text-danger">*</span></label> <label for="first_claim_amount_${increment}">Claim Amount<span class="text-danger claim-required-star">*</span></label>
<input type="text" class="form-control claim-input" id="first_claim_amount_${increment}" name="first_claim_amount[]"> <input type="text" class="form-control claim-input" id="first_claim_amount_${increment}" name="first_claim_amount[]">
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-field-group">
<label for="first_claim_amount_${increment}">Settled Amount<span class="text-danger">*</span></label> <label for="first_settled_amount_${increment}">Settled Amount<span class="text-danger claim-required-star">*</span></label>
<input type="text" class="form-control claim-input" id="first_settled_amount_${increment}" name="first_settled_amount[]"> <input type="text" class="form-control claim-input" id="first_settled_amount_${increment}" name="first_settled_amount[]">
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-field-group">
<label for="first_claim_status_${increment}">Claim Status<span class="text-danger">*</span></label> <label for="first_claim_status_${increment}">Claim Status<span class="text-danger claim-required-star">*</span></label>
<input type="text" class="form-control claim-input" id="first_claim_status_${increment}" name="first_claim_status[]"> <input type="text" class="form-control claim-input" id="first_claim_status_${increment}" name="first_claim_status[]">
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2">
@ -1241,7 +1459,10 @@ var pageBackButton = '<a href="<?= base_url('leads/list') ?>" class="topbar-icon
let lastRow = $(".claim-row").last(); let lastRow = $(".claim-row").last();
if (isChecked) { if (isChecked) {
lastRow.show(); lastRow.show();
lastRow.find(".claim-input").attr("required", true); lastRow.find('[name="first_year[]"]').prop("required", true);
if (!isClaimRowNilClaims(lastRow)) {
lastRow.find(".claim-input").not('[name="first_year[]"]').prop("required", true);
}
} else { } else {
lastRow.hide(); lastRow.hide();
lastRow.find(".claim-input").removeAttr("required"); lastRow.find(".claim-input").removeAttr("required");
@ -1274,8 +1495,31 @@ var pageBackButton = '<a href="<?= base_url('leads/list') ?>" class="topbar-icon
let claimData = []; let claimData = [];
if ($("#claim_history").length > 0 && !$("#claim_history").prop("checked")) {
return JSON.stringify({
"finyear": claimData
});
}
$(".claim-row").each(function() { $(".claim-row").each(function() {
let isNilClaims = $(this).find(".nil-claims-checkbox").prop("checked");
if (isNilClaims) {
let year = $(this).find("[name='first_year[]']").val();
claimData.push({
"year": year,
"policy_type": "Nil",
"date_of_loss": "Nil",
"claim_amount": "Nil",
"settled_amount": "Nil",
"cause_of_loss": "Nil",
"status": "Nil",
"nil_claims": 1,
});
return;
}
let year = $(this).find("[name='first_year[]']").val(); let year = $(this).find("[name='first_year[]']").val();
let policyType = $(this).find("[name='first_policy_type_[]']").val(); let policyType = $(this).find("[name='first_policy_type_[]']").val();
let dateOfLoss = $(this).find("[name='first_date_of_loss_[]']").val(); let dateOfLoss = $(this).find("[name='first_date_of_loss_[]']").val();
@ -1292,6 +1536,7 @@ var pageBackButton = '<a href="<?= base_url('leads/list') ?>" class="topbar-icon
"settled_amount": settledAmount, "settled_amount": settledAmount,
"cause_of_loss": causeOfLoss, "cause_of_loss": causeOfLoss,
"status": claimStatus, "status": claimStatus,
"nil_claims": 0,
}); });
}); });
@ -1309,26 +1554,41 @@ var pageBackButton = '<a href="<?= base_url('leads/list') ?>" class="topbar-icon
function claimHistoryToggle() { function claimHistoryToggle() {
cliam_history_status = $("#claim_history").prop("checked") ? 1 : 0; cliam_history_status = $("#claim_history").prop("checked") ? 1 : 0;
// alert(cliam_history_status);
if (cliam_history_status == 1) { if (cliam_history_status == 1) {
if ($(".claim-row").length > 0) { if ($(".claim-row").length > 0) {
// Rows already exist, just show them
$(".claim-row").show(); $(".claim-row").show();
} else { } else {
// No rows yet, so create them
appendThreeYearsClaims(); appendThreeYearsClaims();
} }
$(".claim-input").attr("required", true);
} else {
$(".claim-row").each(function() {
const $row = $(this);
$row.find('[name="first_year[]"]').prop("required", true);
if (!isClaimRowNilClaims($row)) {
$row.find(".claim-input").not('[name="first_year[]"]').prop("required", true);
}
});
} else {
$(".claim-row").hide(); $(".claim-row").hide();
$(".claim-input").removeAttr("required"); // Required Attributes Remove $(".claim-row").each(function() {
$(".claim-input").val(""); // Value Reset const $row = $(this);
$row.find('.nil-claims-checkbox').prop('checked', false);
$row.find('.nil-claims-value').val('0');
$row.removeClass('claim-row-nil');
$row.find('.claim-required-star').show();
});
$(".claim-input").removeAttr("required").prop('disabled', false).val("");
$(".claim-input").each(function() { $(".claim-input").each(function() {
$(this).parsley().reset(); // Validation Reset if ($(this).hasClass('select2-hidden-accessible')) {
$(this).val(null).trigger('change');
}
if ($(this).parsley) {
$(this).parsley().reset();
}
}); });
} }
} }
$('#exixting_client').change(function () { $('#exixting_client').change(function () {
@ -1476,5 +1736,12 @@ var pageBackButton = '<a href="<?= base_url('leads/list') ?>" class="topbar-icon
$('#lost_reason').val(""); $('#lost_reason').val("");
$('#lost_reason').removeAttr('required'); $('#lost_reason').removeAttr('required');
} }
const initialLeadType = $('#lead_type').val();
const isEditLead = String($('#actual_lead_id').val() || '0') !== '0';
if (initialLeadType && !isEditLead) {
leadTypeBsedHideAndShow(initialLeadType, false);
}
}); });
</script> </script>

View File

@ -1,19 +1,39 @@
<?php if(isset($lead_edit_data)) { <?php if (isset($lead_edit_data)) {
$claims = !empty($lead_edit_data['fin_years_claims_array']) ? $lead_edit_data['fin_years_claims_array'] : [ ['year' => '', 'claim_amount' => '', 'status' => '', 'claim_type' => '', 'cause_of_death' => '', 'death_date' => ''] ]; if (! isset($lastFiveYears) || ! is_array($lastFiveYears)) {
$year = (int) date('Y');
$month = (int) date('m');
$currentFYStart = ($month >= 4) ? $year : $year - 1;
$lastFiveYears = [];
for ($i = 0; $i < 6; $i++) {
$startYear = $currentFYStart - $i;
$lastFiveYears[] = "{$startYear}-" . ($startYear + 1);
}
}
$claims = ! empty($lead_edit_data['fin_years_claims_array'])
? $lead_edit_data['fin_years_claims_array']
: [['year' => '', 'claim_amount' => '', 'status' => '', 'policy_type' => '', 'date_of_loss' => '', 'cause_of_loss' => '']];
$leadType = (int) ($lead_edit_data['lead_type'] ?? 0);
$showClaimsSection = in_array($leadType, [1, 2, 3], true);
$claimHistoryLabel = $leadType === 1 ? 'Mortality Claims' : 'Claims History';
?> ?>
<?php if ($showClaimsSection) { ?>
<div class="custom-control custom-switch"> <div class="custom-control custom-switch">
<input type="checkbox" onchange="claimHistoryToggle()" class="custom-control-input" id="claim_history" name="claim_history" <?= $lead_edit_data['claim_history'] == 1 ? "checked" : "" ?> /> <input type="checkbox" onchange="claimHistoryToggle()" class="custom-control-input" id="claim_history" name="claim_history" <?= $lead_edit_data['claim_history'] == 1 ? 'checked' : '' ?> />
<label class="custom-control-label" for="claim_history">Claims History</label> <label class="custom-control-label" for="claim_history"><?= $claimHistoryLabel ?></label>
</div><br> </div><br>
<?php <?php
if ($lead_edit_data['claim_history'] == 1) { if ($lead_edit_data['claim_history'] == 1) {
foreach ($claims as $key => $value) { ?> foreach ($claims as $key => $value) {
$isNilClaimRow = ! empty($value['nil_claims']);
?>
<div class="row claim-row"> <div class="row claim-row<?= $isNilClaimRow ? ' claim-row-nil' : '' ?>">
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-year-group">
<label for="first_year">Year<span class="text-danger">*</span></label> <label for="first_year_<?= $key ?>">Year<span class="text-danger claim-required-star">*</span></label>
<select class="form-control first_year_" id="first_year" name="first_year[]"> <select class="form-control first_year_ claim-input" id="first_year_<?= $key ?>" name="first_year[]">
<option value="">Select Year</option> <option value="">Select Year</option>
<?php foreach ($lastFiveYears as $year) { <?php foreach ($lastFiveYears as $year) {
$selected = ($year == $value['year']) ? 'selected' : ''; $selected = ($year == $value['year']) ? 'selected' : '';
@ -21,35 +41,45 @@
} ?> } ?>
</select> </select>
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2">
<label for="first_policy_type_${increment}">Policy Type<span class="text-danger">*</span></label> <label>Nil Claims</label>
<input type="text" class="form-control" id="first_policy_type_${increment}" name="first_policy_type_[]" <input type="hidden" class="nil-claims-value" name="nil_claims[]" value="<?= $isNilClaimRow ? '1' : '0' ?>">
value="<?= htmlspecialchars($value['policy_type']) ?>"> <div class="custom-control custom-checkbox" style="padding-top: 8px;">
<input type="checkbox" class="custom-control-input nil-claims-checkbox" id="nil_claims_<?= $key ?>" onchange="nilClaimsToggle(this)"<?= $isNilClaimRow ? ' checked' : '' ?>>
<label class="custom-control-label" for="nil_claims_<?= $key ?>">Nil Claims</label>
</div> </div>
<div class="form-group col-md-2">
<label for="first_date_of_loss_${increment}">Date of Loss<span class="text-danger">*</span></label>
<input type="text" class="form-control loss_date" id="first_date_of_loss_${increment}" name="first_date_of_loss_[]"
value="<?= htmlspecialchars($value['date_of_loss']) ?>">
</div> </div>
<div class="form-group col-md-2">
<label for="first_cause_of_death_${increment}">Cause Of Loss <span class="text-danger">*</span></label> <div class="form-group col-md-2 claim-field-group">
<input type="text" class="form-control" id="first_cause_of_loss_${increment}" name="first_cause_of_loss[]" <label for="first_policy_type_<?= $key ?>">Policy Type<span class="text-danger claim-required-star"<?= $isNilClaimRow ? ' style="display:none;"' : '' ?>>*</span></label>
value="<?= htmlspecialchars($value['cause_of_loss']) ?>"> <input type="text" class="form-control claim-input" id="first_policy_type_<?= $key ?>" name="first_policy_type_[]"
value="<?= htmlspecialchars($value['policy_type'] ?? '') ?>"<?= $isNilClaimRow ? ' disabled' : '' ?>>
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-field-group">
<label for="first_claim_amount_${increment}">Claim Amount<span class="text-danger">*</span></label> <label for="first_date_of_loss_<?= $key ?>">Date of Loss<span class="text-danger claim-required-star"<?= $isNilClaimRow ? ' style="display:none;"' : '' ?>>*</span></label>
<input type="text" class="form-control" id="first_claim_amount_${increment}" name="first_claim_amount[]" <input type="text" class="form-control loss_date claim-input" id="first_date_of_loss_<?= $key ?>" name="first_date_of_loss_[]"
value="<?= htmlspecialchars($value['claim_amount']) ?>"> value="<?= htmlspecialchars($value['date_of_loss'] ?? '') ?>"<?= $isNilClaimRow ? ' disabled' : '' ?>>
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-field-group">
<label for="first_claim_amount_${increment}">Settled Amount<span class="text-danger">*</span></label> <label for="first_cause_of_loss_<?= $key ?>">Cause Of Loss <span class="text-danger claim-required-star"<?= $isNilClaimRow ? ' style="display:none;"' : '' ?>>*</span></label>
<input type="text" class="form-control" id="first_settled_amount_${increment}" name="first_settled_amount[]" <input type="text" class="form-control claim-input" id="first_cause_of_loss_<?= $key ?>" name="first_cause_of_loss[]"
value="<?= htmlspecialchars($value['settled_amount']) ?>"> value="<?= htmlspecialchars($value['cause_of_loss'] ?? '') ?>"<?= $isNilClaimRow ? ' disabled' : '' ?>>
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-field-group">
<label for="first_claim_status_${increment}">Claim Status<span class="text-danger">*</span></label> <label for="first_claim_amount_<?= $key ?>">Claim Amount<span class="text-danger claim-required-star"<?= $isNilClaimRow ? ' style="display:none;"' : '' ?>>*</span></label>
<input type="text" class="form-control" id="first_claim_status_${increment}" name="first_claim_status[]" <input type="text" class="form-control claim-input" id="first_claim_amount_<?= $key ?>" name="first_claim_amount[]"
value="<?= htmlspecialchars($value['status']) ?>"> value="<?= htmlspecialchars($value['claim_amount'] ?? '') ?>"<?= $isNilClaimRow ? ' disabled' : '' ?>>
</div>
<div class="form-group col-md-2 claim-field-group">
<label for="first_settled_amount_<?= $key ?>">Settled Amount<span class="text-danger claim-required-star"<?= $isNilClaimRow ? ' style="display:none;"' : '' ?>>*</span></label>
<input type="text" class="form-control claim-input" id="first_settled_amount_<?= $key ?>" name="first_settled_amount[]"
value="<?= htmlspecialchars($value['settled_amount'] ?? '') ?>"<?= $isNilClaimRow ? ' disabled' : '' ?>>
</div>
<div class="form-group col-md-2 claim-field-group">
<label for="first_claim_status_<?= $key ?>">Claim Status<span class="text-danger claim-required-star"<?= $isNilClaimRow ? ' style="display:none;"' : '' ?>>*</span></label>
<input type="text" class="form-control claim-input" id="first_claim_status_<?= $key ?>" name="first_claim_status[]"
value="<?= htmlspecialchars($value['status'] ?? '') ?>"<?= $isNilClaimRow ? ' disabled' : '' ?>>
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2">
<div class="" style="position: relative; top: 28px; float: right; text-align: end;"> <div class="" style="position: relative; top: 28px; float: right; text-align: end;">
@ -59,5 +89,24 @@
</div> </div>
</div> </div>
<?php } } ?> <?php
}
}
?>
<script>
$(".loss_date").each(function () {
flatpickr(this, {
dateFormat: "d-m-Y",
});
});
if (typeof initNilClaimsRows === 'function') {
initNilClaimsRows();
}
if (typeof updateNonEbClaimRowVisibility === 'function') {
updateNonEbClaimRowVisibility();
}
</script>
<?php } ?>
<?php } ?> <?php } ?>

View File

@ -42,16 +42,35 @@
<?php if(isset($lead_edit_data)) { ?> <?php if(isset($lead_edit_data)) { ?>
<?php <?php
if (! isset($lastFiveYears) || ! is_array($lastFiveYears)) {
$year = (int) date('Y');
$month = (int) date('m');
$currentFYStart = ($month >= 4) ? $year : $year - 1;
$lastFiveYears = [];
for ($i = 0; $i < 6; $i++) {
$startYear = $currentFYStart - $i;
$lastFiveYears[] = "{$startYear}-" . ($startYear + 1);
}
}
if (! isset($causeOfDeath) || ! is_array($causeOfDeath)) {
$causeOfDeath = [];
}
$savedClaims = !empty($lead_edit_data['fin_years_claims_array']) ? $lead_edit_data['fin_years_claims_array'] : []; $savedClaims = !empty($lead_edit_data['fin_years_claims_array']) ? $lead_edit_data['fin_years_claims_array'] : [];
$isClaimHistoryChecked = (isset($lead_edit_data['claim_history']) && (int) $lead_edit_data['claim_history'] === 1) || !empty($savedClaims); $isClaimHistoryChecked = (isset($lead_edit_data['claim_history']) && (int) $lead_edit_data['claim_history'] === 1) || !empty($savedClaims);
$showClaimHistorySwitch = isset($lead_edit_data['lead_type'], $lead_edit_data['policy_type_id']) $showClaimHistorySwitch = isset($lead_edit_data['lead_type'], $lead_edit_data['policy_type_id'])
&& in_array((int) $lead_edit_data['lead_type'], [2, 3], true) && in_array((int) $lead_edit_data['lead_type'], [1, 2, 3], true)
&& in_array((int) $lead_edit_data['policy_type_id'], [1, 6, 7], true); && in_array((int) $lead_edit_data['policy_type_id'], [1, 6, 7], true);
$claimHistoryLabel = (isset($lead_edit_data['lead_type']) && (int) $lead_edit_data['lead_type'] === 1)
? 'Mortality Claims'
: 'Claims History';
?> ?>
<?php if ($showClaimHistorySwitch) { ?> <?php if ($showClaimHistorySwitch) { ?>
<div class="custom-control custom-switch"> <div class="custom-control custom-switch">
<input type="checkbox" onchange="claimHistoryToggle()" class="custom-control-input" id="claim_history" name="claim_history" <?= $isClaimHistoryChecked ? 'checked' : '' ?>> <input type="checkbox" onchange="claimHistoryToggle()" class="custom-control-input" id="claim_history" name="claim_history" <?= $isClaimHistoryChecked ? 'checked' : '' ?>>
<label class="custom-control-label" for="claim_history">Claims History</label> <label class="custom-control-label" for="claim_history"><?= $claimHistoryLabel ?></label>
</div><br> </div><br>
<?php } ?> <?php } ?>
<div class="form-row" id="appendAreaForClaim_1"> <div class="form-row" id="appendAreaForClaim_1">
@ -59,13 +78,15 @@
$claims = !empty($savedClaims) ? $savedClaims : [ ['year' => '', 'claim_amount' => '', 'status' => '', 'claim_type' => '', 'cause_of_death' => '', 'death_date' => ''] ]; $claims = !empty($savedClaims) ? $savedClaims : [ ['year' => '', 'claim_amount' => '', 'status' => '', 'claim_type' => '', 'cause_of_death' => '', 'death_date' => ''] ];
foreach ($claims as $key => $value) { ?> foreach ($claims as $key => $value) {
$isNilClaimRow = !empty($value['nil_claims']);
?>
<div class="row claim-row"> <div class="row claim-row<?= $isNilClaimRow ? ' claim-row-nil' : '' ?>">
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-year-group">
<label for="first_year">Year<span class="text-danger">*</span></label> <label for="first_year_<?= $key ?>">Year<span class="text-danger claim-required-star">*</span></label>
<select class="form-control first_year_ claim-input" id="first_year" name="first_year[]"> <select class="form-control first_year_ claim-input" id="first_year_<?= $key ?>" name="first_year[]">
<option value="">Select Year</option> <option value="">Select Year</option>
<?php foreach ($lastFiveYears as $year) { <?php foreach ($lastFiveYears as $year) {
$selected = ($year == $value['year']) ? 'selected' : ''; $selected = ($year == $value['year']) ? 'selected' : '';
@ -75,54 +96,69 @@
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2">
<label for="emp_id">Emp ID<span class="text-danger">*</span></label> <label>Nil Claims</label>
<input type="text" class="form-control claim-input" id="emp_id" name="emp_id[]" value="<?= htmlspecialchars(isset($value['emp_id']) ? $value['emp_id'] : '-' ) ?>"> <input type="hidden" class="nil-claims-value" name="nil_claims[]" value="<?= $isNilClaimRow ? '1' : '0' ?>">
<div class="custom-control custom-checkbox" style="padding-top: 8px;">
<input type="checkbox" class="custom-control-input nil-claims-checkbox" id="nil_claims_<?= $key ?>" onchange="nilClaimsToggle(this)"<?= $isNilClaimRow ? ' checked' : '' ?>>
<label class="custom-control-label" for="nil_claims_<?= $key ?>">Nil Claims</label>
</div>
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-field-group">
<label for="emp_name">Employee Name<span class="text-danger">*</span></label> <label for="emp_id_<?= $key ?>">Emp ID<span class="text-danger claim-required-star"<?= $isNilClaimRow ? ' style="display:none;"' : '' ?>>*</span></label>
<input type="text" class="form-control claim-input" id="emp_name" name="emp_name[]" value="<?= htmlspecialchars(isset($value['emp_name']) ? $value['emp_name'] : '-' ) ?>"> <input type="text" class="form-control claim-input" id="emp_id_<?= $key ?>" name="emp_id[]" value="<?= htmlspecialchars(isset($value['emp_id']) ? $value['emp_id'] : '-' ) ?>"<?= $isNilClaimRow ? ' disabled' : '' ?>>
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-field-group">
<label for="gender">Gender<span class="text-danger">*</span></label> <label for="emp_name_<?= $key ?>">Employee Name<span class="text-danger claim-required-star"<?= $isNilClaimRow ? ' style="display:none;"' : '' ?>>*</span></label>
<select class="form-control claim-input" id="gender" name="gender[]"> <input type="text" class="form-control claim-input" id="emp_name_<?= $key ?>" name="emp_name[]" value="<?= htmlspecialchars(isset($value['emp_name']) ? $value['emp_name'] : '-' ) ?>"<?= $isNilClaimRow ? ' disabled' : '' ?>>
</div>
<div class="form-group col-md-2 claim-field-group">
<label for="gender_<?= $key ?>">Gender<span class="text-danger claim-required-star"<?= $isNilClaimRow ? ' style="display:none;"' : '' ?>>*</span></label>
<select class="form-control claim-input" id="gender_<?= $key ?>" name="gender[]"<?= $isNilClaimRow ? ' disabled' : '' ?>>
<option value="">Select Gender</option> <option value="">Select Gender</option>
<option value="Female" <?= (isset($value['gender']) && $value['gender'] == 'Female') ? 'selected' : '' ?>>Female</option> <option value="Female" <?= (isset($value['gender']) && $value['gender'] == 'Female') ? 'selected' : '' ?>>Female</option>
<option value="Male" <?= (isset($value['gender']) && $value['gender'] == 'Male') ? 'selected' : '' ?>>Male</option> <option value="Male" <?= (isset($value['gender']) && $value['gender'] == 'Male') ? 'selected' : '' ?>>Male</option>
<?php if ($isNilClaimRow) { ?>
<option value="Nil" selected>Nil</option>
<?php } ?>
</select> </select>
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-field-group">
<label for="designation">Designation <span class="text-danger">*</span></label> <label for="designation_<?= $key ?>">Designation <span class="text-danger claim-required-star"<?= $isNilClaimRow ? ' style="display:none;"' : '' ?>>*</span></label>
<input type="text" class="form-control claim-input" id="designation" name="designation[]" value="<?= htmlspecialchars(isset($value['designation']) ? $value['designation'] : '-' ) ?>"> <input type="text" class="form-control claim-input" id="designation_<?= $key ?>" name="designation[]" value="<?= htmlspecialchars(isset($value['designation']) ? $value['designation'] : '-' ) ?>"<?= $isNilClaimRow ? ' disabled' : '' ?>>
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-field-group">
<label for="sum_insured">Sum Insured <span class="text-danger">*</span></label> <label for="sum_insured_<?= $key ?>">Sum Insured <span class="text-danger claim-required-star"<?= $isNilClaimRow ? ' style="display:none;"' : '' ?>>*</span></label>
<input type="text" class="form-control claim-input" id="sum_insured" name="sum_insured[]" value="<?= htmlspecialchars(isset($value['sum_insured']) ? $value['sum_insured'] : '-' ) ?>"> <input type="text" class="form-control claim-input" id="sum_insured_<?= $key ?>" name="sum_insured[]" value="<?= htmlspecialchars(isset($value['sum_insured']) ? $value['sum_insured'] : '-' ) ?>"<?= $isNilClaimRow ? ' disabled' : '' ?>>
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-field-group">
<label for="first_death_date">Date of Death<span class="text-danger">*</span></label> <label for="first_death_date_<?= $key ?>">Date of Death<span class="text-danger claim-required-star"<?= $isNilClaimRow ? ' style="display:none;"' : '' ?>>*</span></label>
<input type="text" class="form-control flatpickr-date claim-input" id="first_death_date" name="first_death_date[]" value="<?= htmlspecialchars($value['death_date']) ?>" autocomplete="off"> <input type="text" class="form-control flatpickr-date claim-input" id="first_death_date_<?= $key ?>" name="first_death_date[]" value="<?= htmlspecialchars($value['death_date'] ?? '') ?>" autocomplete="off"<?= $isNilClaimRow ? ' disabled' : '' ?>>
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-field-group">
<label for="first_cause_of_death">Nature/Cause Of Death <span class="text-danger">*</span></label> <label for="first_cause_of_death_<?= $key ?>">Nature/Cause Of Death <span class="text-danger claim-required-star"<?= $isNilClaimRow ? ' style="display:none;"' : '' ?>>*</span></label>
<select class="form-control claim-input" id="first_cause_of_death" name="first_cause_of_death[]"> <select class="form-control claim-input" id="first_cause_of_death_<?= $key ?>" name="first_cause_of_death[]"<?= $isNilClaimRow ? ' disabled' : '' ?>>
<option value="">Select Cause of Death</option> <option value="">Select Cause of Death</option>
<?php foreach ($causeOfDeath as $cause => $death_value) { <?php foreach ($causeOfDeath as $cause => $death_value) {
$selected = ($cause == $value['cause_of_death']) ? 'selected' : ''; $selected = ($cause == $value['cause_of_death']) ? 'selected' : '';
echo "<option value='$cause' $selected>$death_value</option>"; echo "<option value='$cause' $selected>$death_value</option>";
} ?> } ?>
<?php if ($isNilClaimRow) { ?>
<option value="Nil" selected>Nil</option>
<?php } ?>
</select> </select>
</div> </div>
<div class="form-group col-md-2"> <div class="form-group col-md-2 claim-field-group">
<label for="first_claim_amount">Claim/Settled Amount<span class="text-danger">*</span></label> <label for="first_claim_amount_<?= $key ?>">Claim/Settled Amount<span class="text-danger claim-required-star"<?= $isNilClaimRow ? ' style="display:none;"' : '' ?>>*</span></label>
<input type="text" class="form-control claim-input" id="first_claim_amount" name="first_claim_amount[]" value="<?= htmlspecialchars(isset($value['claim_amount']) ? $value['claim_amount'] : ( isset($value['settled']) ? $value['settled'] : '-' )) ?>"> <input type="text" class="form-control claim-input" id="first_claim_amount_<?= $key ?>" name="first_claim_amount[]" value="<?= htmlspecialchars(isset($value['claim_amount']) ? $value['claim_amount'] : ( isset($value['settled']) ? $value['settled'] : '-' )) ?>"<?= $isNilClaimRow ? ' disabled' : '' ?>>
</div> </div>
<!-- <div class="form-group col-md-2"> <!-- <div class="form-group col-md-2">
@ -165,5 +201,9 @@ flatpickr('.flatpickr-date', {
maxDate: 'today', // Optional: disable future dates maxDate: 'today', // Optional: disable future dates
}); });
if (typeof initNilClaimsRows === 'function') {
initNilClaimsRows();
}
</script> </script>

View File

@ -39,12 +39,25 @@
<div class="card" style="margin-right: 23px;"> <div class="card" style="margin-right: 23px;">
<div class="card-body"> <div class="card-body">
<?php
$tpaActionButtons = '';
if (
!empty($ticket_data['is_tpa_api_service_enabled']) &&
empty($ticket_data['tpa_claim_push_reference_no']) &&
($ticket_data['claim_created_by'] ?? '') !== 'TPA'
) {
$tpaActionButtons .= ' <a href="#" class="btn btn-success btn-sm mr-2" onclick="manualTpaClaimPush(); return false;">Manual TPA Claim Push</a>';
}
if (!empty($ticket_data['tpa_claim_push_reference_no'])) {
$tpaActionButtons .= ' <a href="#" class="btn btn-success btn-sm mr-2" onclick="fetchTpaClaimStatus(); return false;">Fetch Claim Status</a>';
}
?>
<script> <script>
var pageHideMainNavTitle = true; var pageHideMainNavTitle = true;
var pageTitle = 'Claims<?php if(isset($ticket_data["tpa_claim_push_reference_no"]) && !empty($ticket_data["tpa_claim_push_reference_no"])) { echo " <a href=\"#\" class=\"btn btn-success mr-2\" onclick=\"fetchTpaClaimStatus()\">Fetch Claim Status</a>"; } ?>'; var pageTitle = 'Claims <?= $tpaActionButtons ?>';
var pageBackButton = '<a href="<?= base_url("ticket/list"); ?>" class="topbar-icon-btn" data-toggle="tooltip" data-placement="top" title="Back" aria-label="Back to list"><i class="ri-arrow-left-s-line"></i></a>'; var pageBackButton = '<a href="<?= base_url("ticket/list"); ?>" class="topbar-icon-btn" data-toggle="tooltip" data-placement="top" title="Back" aria-label="Back to list"><i class="ri-arrow-left-s-line"></i></a>';
</script> </script>
<!-- Header Section --> <!-- Header Section (TPA actions rendered in top navbar via pageTitle) -->
<!-- <div class="row mb-3 align-items-center justify-content-between"> <!-- <div class="row mb-3 align-items-center justify-content-between">
<div class="col-auto"> <div class="col-auto">
<h4 class="mb-0">Claims</h4> <h4 class="mb-0">Claims</h4>
@ -56,7 +69,7 @@
<?php if ( <?php if (
$ticket_data['is_tpa_api_service_enabled'] == true && $ticket_data['is_tpa_api_service_enabled'] == true &&
empty($ticket_data['tpa_claim_push_reference_no']) && empty($ticket_data['tpa_claim_push_reference_no']) &&
empty($ticket_data['claim_number']) $ticket_data['claim_created_by'] != 'TPA'
) : ?> ) : ?>
<a href="#" class="btn btn-success mr-2" onclick="manualTpaClaimPush(); return false;"> <a href="#" class="btn btn-success mr-2" onclick="manualTpaClaimPush(); return false;">
Manual TPA Claim Push Manual TPA Claim Push

View File

@ -577,6 +577,104 @@
<script> <script>
let GlobelExtraFields = []; let GlobelExtraFields = [];
var doa; var doa;
var STATUS_SECTION_CLASSES = ['cda_ir', 'settled', 'approved', 'rejected', 'up_qdr', 'up_cnu', 'canceled', 'returned', 'payment', 'non_id'];
var statusSectionInitialValues = {};
function captureSectionInitialValues(sectionClass) {
if (!sectionClass) {
return;
}
var values = {};
$('.' + sectionClass).find('input, textarea, select').each(function() {
var el = this;
var key = el.id || el.name;
if (!key) {
return;
}
values[key] = el.type === 'file' ? '' : String($(el).val() || '');
});
statusSectionInitialValues[sectionClass] = values;
}
function captureAllStatusSectionInitialValues() {
STATUS_SECTION_CLASSES.forEach(captureSectionInitialValues);
}
function hasSectionChanged(sectionClass) {
if (!sectionClass) {
return false;
}
var initial = statusSectionInitialValues[sectionClass];
if (!initial) {
return false;
}
var changed = false;
$('.' + sectionClass).find('input, textarea, select').each(function() {
var el = this;
var key = el.id || el.name;
if (!key) {
return;
}
if (el.type === 'file') {
if (el.files && el.files.length > 0) {
changed = true;
}
return;
}
var current = String($(el).val() || '');
var original = String(initial[key] !== undefined ? initial[key] : '');
if (current !== original) {
changed = true;
}
});
return changed;
}
function updateSectionRequiredLabels(sectionClass, isRequired) {
if (!sectionClass) {
return;
}
$('.' + sectionClass).find('input, textarea, select').each(function() {
var fieldId = $(this).attr('id');
if (!fieldId || fieldId === 'approved_description') {
return;
}
var $label = $("label[for='" + fieldId + "']");
if (!$label.length) {
return;
}
if (isRequired && !$label.find('.text-danger').length) {
$label.append(' <span class="text-danger">*</span>');
} else if (!isRequired) {
$label.find('.text-danger').remove();
}
});
}
function applyConditionalRequiredForSection(sectionClass) {
if (!sectionClass) {
return;
}
if (sectionClass === 'approved' || sectionClass === 'settled') {
enforceLetterPairRules();
updateSectionRequiredLabels(sectionClass, hasSectionChanged(sectionClass));
return;
}
var changed = hasSectionChanged(sectionClass);
$('.' + sectionClass).find('input, textarea, select').each(function() {
if (this.id === 'approved_description') {
return;
}
$(this).prop('required', changed);
});
updateSectionRequiredLabels(sectionClass, changed);
}
function refreshAllStatusSectionRequired() {
STATUS_SECTION_CLASSES.forEach(applyConditionalRequiredForSection);
$('#approved_description').prop('required', false);
$("label[for='approved_description'] .text-danger").remove();
}
$(document).ready(function() { $(document).ready(function() {
@ -645,6 +743,8 @@
GlobelExtraFields = extraFields; GlobelExtraFields = extraFields;
console.log("extraFields", extraFields); console.log("extraFields", extraFields);
claimStatusFieldChanges(extraFields); claimStatusFieldChanges(extraFields);
captureAllStatusSectionInitialValues();
refreshAllStatusSectionRequired();
handleTPARequired(tpa_id_for_hid_filed); handleTPARequired(tpa_id_for_hid_filed);
// syncApprovedLetterInputs(); // syncApprovedLetterInputs();
// syncSettleLetterInputs(); // syncSettleLetterInputs();
@ -736,24 +836,16 @@
showClass = '.payment'; showClass = '.payment';
} }
// Show the relevant section and enable required attributes
if (showClass) { if (showClass) {
// $(showClass).show().find('input, textarea').attr('required', true); $(showClass).show();
$(showClass).show().find('input, textarea').attr('required', true).each(function() { captureSectionInitialValues(showClass.replace('.', ''));
var $label = $("label[for='" + $(this).attr('id') + "']");
if ($label.length && !$label.find('.text-danger').length) {
$label.append(' <span class="text-danger">*</span>');
}
});
} }
$field = $('#approved_description') $field = $('#approved_description')
$field.prop('required', false); $field.prop('required', false);
var $parentDiv = $field.closest("div"); var $parentDiv = $field.closest("div");
$parentDiv.find("label[for='approved_description'] .text-danger").remove(); $parentDiv.find("label[for='approved_description'] .text-danger").remove();
syncApprovedLetterInputs(); refreshAllStatusSectionRequired();
syncSettleLetterInputs();
} }
$('#claim_status_id').on('change', function() { $('#claim_status_id').on('change', function() {
@ -837,13 +929,13 @@
const hasUrl = $.trim($urlInput.val()) !== ''; const hasUrl = $.trim($urlInput.val()) !== '';
const hasFile = $fileInput[0].files && $fileInput[0].files.length > 0; const hasFile = $fileInput[0].files && $fileInput[0].files.length > 0;
const isApprovedSectionVisible = $urlInput.closest('.approved').is(':visible'); const isApprovedSectionVisible = $urlInput.closest('.approved').is(':visible');
const approvedSectionChanged = hasSectionChanged('approved');
$fileInput.prop('disabled', hasUrl); $fileInput.prop('disabled', hasUrl);
$urlInput.prop('disabled', hasFile); $urlInput.prop('disabled', hasFile);
// Keep the file optional; URL remains conditionally required for approved state unless file is present.
$fileInput.prop('required', false); $fileInput.prop('required', false);
$urlInput.prop('required', isApprovedSectionVisible && !hasFile); $urlInput.prop('required', isApprovedSectionVisible && approvedSectionChanged && !hasFile);
} }
function syncSettleLetterInputs() { function syncSettleLetterInputs() {
@ -857,12 +949,13 @@
const hasUrl = $.trim($urlInput.val()) !== ''; const hasUrl = $.trim($urlInput.val()) !== '';
const hasFile = $fileInput[0].files && $fileInput[0].files.length > 0; const hasFile = $fileInput[0].files && $fileInput[0].files.length > 0;
const isSettledSectionVisible = $urlInput.closest('.settled').is(':visible'); const isSettledSectionVisible = $urlInput.closest('.settled').is(':visible');
const settledSectionChanged = hasSectionChanged('settled');
$fileInput.prop('disabled', hasUrl); $fileInput.prop('disabled', hasUrl);
$urlInput.prop('disabled', hasFile); $urlInput.prop('disabled', hasFile);
$fileInput.prop('required', false); $fileInput.prop('required', false);
$urlInput.prop('required', isSettledSectionVisible && !hasFile); $urlInput.prop('required', isSettledSectionVisible && settledSectionChanged && !hasFile);
} }
function enforceLetterPairRules() { function enforceLetterPairRules() {
@ -956,10 +1049,14 @@
} }
var selectedClaimStatus = $('#claim_status_id').val(); var selectedClaimStatus = $('#claim_status_id').val();
if (thirdClass === 'approved' || thirdClass === 'settled') {
applyConditionalRequiredForSection(thirdClass);
return;
}
var sectionChanged = hasSectionChanged(thirdClass);
var $thirdClass = $(`.${thirdClass}`); var $thirdClass = $(`.${thirdClass}`);
var hasValue = $thirdClass.find('input, textarea, select').filter(function() {
return $(this).val().trim() !== ''; // Check if at least one field is not empty
}).length > 0;
$thirdClass.each(function() { $thirdClass.each(function() {
var id = $(this).find('[id]').first().attr('id'); var id = $(this).find('[id]').first().attr('id');
@ -967,27 +1064,19 @@
var $thisDiv = $(this); var $thisDiv = $(this);
var $inputs = $thisDiv.find('input, textarea, select'); var $inputs = $thisDiv.find('input, textarea, select');
// ✅ Condition 1: Check if this ID is in extraFieldsArray (required by status)
var shouldAddRequired = extrafieldsArray[selectedClaimStatus] && extrafieldsArray[selectedClaimStatus].includes(id); var shouldAddRequired = extrafieldsArray[selectedClaimStatus] && extrafieldsArray[selectedClaimStatus].includes(id);
// ✅ Condition 2: If any field in the class has a value, make all required if (shouldAddRequired || sectionChanged) {
if (shouldAddRequired || hasValue) {
if ($label.length && !$label.find('.text-danger').length) { if ($label.length && !$label.find('.text-danger').length) {
$label.append(' <span class="text-danger">*</span>'); $label.append(' <span class="text-danger">*</span>');
} }
console.log("input from if ", $inputs);
// $inputs.attr('required', true);
$('.' + thirdClass).find('input, textarea,select').attr('required', true); $('.' + thirdClass).find('input, textarea,select').attr('required', true);
} else { } else {
$label.find('.text-danger').remove(); $label.find('.text-danger').remove();
console.log("input ", $inputs);
// $inputs.prop('required', false);
$('.' + thirdClass).find('input, textarea,select').attr('required', false); $('.' + thirdClass).find('input, textarea,select').attr('required', false);
} }
}); });
// Re-apply URL/file pair rules after bulk required toggles.
enforceLetterPairRules(); enforceLetterPairRules();
} }
@ -1034,12 +1123,12 @@
$field.prop('required', false); $field.prop('required', false);
var $parentDiv = $field.closest("div"); var $parentDiv = $field.closest("div");
$parentDiv.find("label[for='approved_description'] .text-danger").remove(); $parentDiv.find("label[for='approved_description'] .text-danger").remove();
enforceLetterPairRules(); refreshAllStatusSectionRequired();
}); });
$('#ticket_form_data').on('submit', function() { $('#ticket_form_data').on('submit', function() {
enforceLetterPairRules(); refreshAllStatusSectionRequired();
}); });
// function addRequiredFieldSymbol(field_name) { // function addRequiredFieldSymbol(field_name) {

View File

@ -269,12 +269,12 @@ table.dataTable tbody td {
<td style="display: none;"><?php echo $row['insurer_name']; ?></td> <td style="display: none;"><?php echo $row['insurer_name']; ?></td>
<td style="display: none;"><?php echo $row['tpa_name']; ?></td> <td style="display: none;"><?php echo $row['tpa_name']; ?></td>
<td style="display: none;"><?php echo $row['policy_no']; ?></td> <td style="display: none;"><?php echo $row['policy_no']; ?></td>
<td style="display: none;"><?php echo isset($priorityType[$row['priority'] ?? 0]) ? $priorityType[$row['priority'] ?? 0] : ''; ?></td> <td style="display: none;"><?php echo ($priorityType ?? [])[$row['priority'] ?? 0] ?? ''; ?></td>
<td style="display: none;"><?php echo $row['relationship']; ?></td> <td style="display: none;"><?php echo $row['relationship']; ?></td>
<td style="display: none;"><?php echo $row['emp_mobile']; ?></td> <td style="display: none;"><?php echo $row['emp_mobile']; ?></td>
<td style="display: none;"><?php echo $row['emp_mail']; ?></td> <td style="display: none;"><?php echo $row['emp_mail']; ?></td>
<td style="display: none;"><?php echo $row['emp_personal_mail']; ?></td> <td style="display: none;"><?php echo $row['emp_personal_mail']; ?></td>
<td style="display: none;"><?php echo isset($modeOFIntimate[$row['mode_of_intimation'] ?? '']) ? $modeOFIntimate[$row['mode_of_intimation']] : ''; ?></td> <td style="display: none;"><?php echo ($modeOFIntimate ?? [])[$row['mode_of_intimation'] ?? ''] ?? ''; ?></td>
<td style="display: none;"> <td style="display: none;">
<?php <?php
$typeId = $row['ticket_type_id'] ?? 0; $typeId = $row['ticket_type_id'] ?? 0;
@ -393,7 +393,8 @@ function getClaimSourceBadgeHtml(claimCreatedBy) {
if (!cls) { if (!cls) {
return ''; return '';
} }
return '<span class="claim-source-badge ' + cls + '">' + escapeHtml(key) + '</span>'; var label = key === 'CRM' ? 'STAFF' : key;
return '<span class="claim-source-badge ' + cls + '">' + escapeHtml(label) + '</span>';
} }
function getPolicyTypeIconHtml(tpaClaimType) { function getPolicyTypeIconHtml(tpaClaimType) {

View File

@ -29,7 +29,44 @@
} }
function isSkippableField(el) { function isSkippableField(el) {
return !el || el.disabled || el.type === 'hidden'; if (!el || el.disabled || el.type === 'hidden') {
return true;
}
if (el.classList && el.classList.contains('select2-search__field')) {
return true;
}
return false;
}
function isVisibleForValidation(el) {
if (isSkippableField(el)) {
return false;
}
var jq = getJq();
if (!jq) {
return true;
}
var $el = jq(el);
if (!$el.length || !$el.is(':visible')) {
return false;
}
return $el.closest('.form-group, .dynamic-form-row, .claim-row, .col-md-4, .col-md-12').filter(function () {
var display = jq(this).css('display');
return display === 'none';
}).length === 0;
}
function isEmptyValue(val) {
if (val == null || val === '') {
return true;
}
if (Array.isArray(val)) {
return val.length === 0;
}
return String(val).trim() === '';
} }
function isPanOrGstField(el) { function isPanOrGstField(el) {
@ -95,7 +132,7 @@
return true; return true;
} }
if (instance.$element.prop('required') && v.length === 0) { if (instance.$element.prop('required') && v.length === 0) {
return true; return false;
} }
return v.length === 10; return v.length === 10;
}, },
@ -181,7 +218,7 @@
} }
function validateField(field) { function validateField(field) {
if (!field || isSkippableField(field) || !isParsleyReady()) { if (!field || !isVisibleForValidation(field) || !isParsleyReady()) {
return; return;
} }
var $field = $(field); var $field = $(field);
@ -200,6 +237,70 @@
} }
} }
function prepareHiddenFieldsForSubmit($form) {
if (!$form || !$form.length) {
return;
}
$form.find('input, textarea, select').each(function () {
var el = this;
var $el = $(el);
if (isVisibleForValidation(el)) {
return;
}
$el.removeAttr('required').prop('required', false);
clearAttrs($el);
try {
if (typeof $el.parsley === 'function') {
var fieldInstance = $el.parsley();
if (fieldInstance && typeof fieldInstance.reset === 'function') {
fieldInstance.reset();
}
}
} catch (e) {
// no-op
}
});
}
function getInvalidFields($form) {
var invalid = [];
if (!$form || !$form.length || !isParsleyReady()) {
return invalid;
}
var instance = $form.parsley();
if (!instance) {
return invalid;
}
instance.fields.forEach(function (field) {
if (field.isValid()) {
return;
}
var el = field.$element[0];
if (!isVisibleForValidation(el)) {
return;
}
var val = field.$element.val();
invalid.push({
id: field.$element.attr('id') || '',
name: field.$element.attr('name') || '',
label: (field.$element.closest('.form-group, .mb-3, .col-md-4, .col-lg-4').find('label').first().text() || '').trim(),
messages: field.getErrorsMessages ? field.getErrorsMessages() : [],
isEmpty: isEmptyValue(val)
});
});
return invalid;
}
function init() { function init() {
var $form = $(FORM_SELECTOR); var $form = $(FORM_SELECTOR);
if (!$form.length || !isParsleyReady()) { if (!$form.length || !isParsleyReady()) {
@ -207,6 +308,7 @@
} }
registerValidators(); registerValidators();
prepareHiddenFieldsForSubmit($form);
applyConstraints($form); applyConstraints($form);
refreshParsley($form); refreshParsley($form);
@ -226,6 +328,22 @@
window.refreshLeadsFormValidation = function () { window.refreshLeadsFormValidation = function () {
init(); init();
}; };
window.prepareLeadsFormForSubmit = function () {
var $form = $(FORM_SELECTOR);
if (!$form.length || !isParsleyReady()) {
return;
}
registerValidators();
prepareHiddenFieldsForSubmit($form);
applyConstraints($form);
refreshParsley($form);
};
window.getLeadsFormInvalidFields = function () {
return getInvalidFields($(FORM_SELECTOR));
};
})(function () { })(function () {
return window.jQuery; return window.jQuery;
}); });