diff --git a/app/Config/Filters.php b/app/Config/Filters.php
index fcdd999a..9badfb5c 100755
--- a/app/Config/Filters.php
+++ b/app/Config/Filters.php
@@ -53,11 +53,13 @@ class Filters extends BaseConfig
public array $globals = [
'before' => [
'HttpRequestLog' => ['except' => 'cli/*'],
+ 'Cors',
// 'csrf',
// 'invalidchars',
],
'after' => [
- 'CloseDbConnection'
+ 'CloseDbConnection',
+ 'Cors',
// 'secureheaders',
],
];
diff --git a/app/Config/Routes.php b/app/Config/Routes.php
index 822e8d4b..92552865 100755
--- a/app/Config/Routes.php
+++ b/app/Config/Routes.php
@@ -3,6 +3,13 @@
use CodeIgniter\Router\RouteCollection;
+
+// Allow OPTIONS for all routes
+$routes->options('(:any)', function() {
+ // This will never be called because the CORS filter returns early
+ // But having this route ensures OPTIONS isn't rejected as 404
+});
+
/**
* @var RouteCollection $routes
*/
@@ -12,6 +19,8 @@ $routes->get('/chatbottest', 'ChatbotControllerNew::chatbotest');
$routes->get('/chatbot', 'ChatbotControllerNew::chatbot');
$routes->get('/swagger', 'SwaggerController::index', ['filter' => 'authMVC']);
+$routes->get('/fedeploy', 'DeployController::fedeploy_view', ['filter' => 'authMVC']);
+$routes->post('/fedeploy', 'DeployController::fedeploy', ['filter' => 'authMVC']);
// Reminder Mail Notification
@@ -480,7 +489,6 @@ $routes->group("rfq", ["filter" => "authMVC"], function ($routes) {
$routes->get("driveListFiles", "GoogleDriveController::listFiles");
$routes->post('dmsSearch', 'PolicyTransactionController::dmsSearch', ['filter' => 'authMVC']);
$routes->get('dmsSearch', 'PolicyTransactionController::dmsSearch', ['filter' => 'authMVC']);
-$routes->get('payouts', 'PolicyTransactionController::payouts', ['filter' => 'authMVC']);
$routes->get('downloadGdriveFile', 'GoogleDriveController::downloadGdriveFile', ['filter' => 'authMVC']);
$routes->get('cli/sendZeptoMail', 'MasterController::testZeptoSMTP');
@@ -776,6 +784,14 @@ $routes->group('payout', function($routes) {
$routes->post('fetchUtrDetails',"PayoutController::fetchUtrDetails");
$routes->post('saveUtrDetails',"PayoutController::saveUtrDetails");
$routes->post('removeUtrDetails',"PayoutController::removeUtrDetails");
+ // invoice policy mapping
+ $routes->get('invoices', 'PayoutController::invoices');
+ $routes->post('invoices/save', 'PayoutController::saveInvoice');
+ $routes->get('invoices/history', 'PayoutController::auditHistory');
+ $routes->get('invoices/preview', 'PayoutController::preview');
+ $routes->get('invoices/downloadPdf/(:any)', 'PayoutController::downloadPdf/$1');
+ $routes->get('invoice/generate-number/(:num)', 'PayoutController::generateInvoiceNumberAjax/$1');
+
});
//PARTNER COMMISSION
@@ -786,5 +802,17 @@ $routes->group('commission', function($routes) {
$routes->get('downloadErrorFile',"RuleImportController::downloadErrorFile");
$routes->get("deleteCommissionData/(:any)", "RuleImportController::deleteCommissionData/$1");
$routes->get('checkSameEntry',"RuleImportController::checkSameEntry");
+ $routes->get('rules/list/(:any)',"RuleImportController::ruleList/$1");
+ $routes->post('rules/save/',"RuleImportController::saveRule");
+ $routes->post('rules/remove/',"RuleImportController::removeRule");
+ $routes->get('checkRuleUsage',"RuleImportController::checkRuleUsage");
});
+//BDS BULK UPLOAD
+
+$routes->group('bds_upload', function($routes) {
+ $routes->match (['get','post'],'list',"PolicyTransactionController::policyBulkUpload");
+ $routes->get('downloadBDSDumpFile/(:any)',"PolicyTransactionController::downloadBDSDumpFile/$1");
+ $routes->get('getBdsDumpFileErrorData',"PolicyTransactionController::getBdsDumpFileErrorData");
+ $routes->get('getBdsDumpExcelFileErrors/(:any)',"PolicyTransactionController::getBdsDumpExcelFileErrors/$1");
+});
diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php
index 8ee13498..e0a556db 100755
--- a/app/Controllers/ClientController.php
+++ b/app/Controllers/ClientController.php
@@ -5065,25 +5065,60 @@ class ClientController extends AdminController
public function get_client_policy_data_using_policy_no()
{
- $received_data = $this->request->getGet();
- $policy_no = $this->request->getGet('policy_no');
- $client_id = $this->request->getGet('client_id');
- $client_branch_id = $this->request->getGet('client_branch_id');
- $policy_type_id = $this->request->getGet('policy_type_id');
- $client_type = $this->request->getGet('client_type');
+ $received_data = $this->request->getGet();
+ $policy_no = trim($this->request->getGet('policy_no'));
+ $client_id = $this->request->getGet('client_id') ?? null;
+ $client_branch_id = $this->request->getGet('client_branch_id') ?? null;
+ $policy_type_id = $this->request->getGet('policy_type_id') ?? null;
+ $client_type = $this->request->getGet('client_type') ?? null;
- $data = $this->policyTransactionModel
+ // Check in Policy Transaction (BDS)
+ $bds_count = $this->policyTransactionModel
->where('is_active', 1)
->where('action_type', 'inception')
- ->where('policy_no', $policy_no)
+ ->where('TRIM(policy_no)', $policy_no)
+ ->where('policy_no IS NOT NULL AND policy_no <> ""')
->countAllResults();
- $client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('policy_status', 1)->where('policy_no', trim($policy_no))->first();
+ // Check in Enrollment (client_policy)
+ $client_policy_data = $this->clientPolicyModel
+ ->where('is_active', 1)
+ ->where('policy_status', 1)
+ ->where('TRIM(policy_no)', $policy_no)
+ ->first();
+
+ // Decide message + count
+ if ($bds_count > 0) {
+
+ return $this->respond([
+ 'status' => true,
+ 'message' => "This policy number is already linked to another policy in the BDS",
+ 'code' => 409,
+ 'data' => $bds_count,
+ 'received_data' => $received_data,
+ 'client_policy_id' => $client_policy_data['id'] ?? null
+ ], 200);
+
+ } elseif (!empty($client_policy_data)) {
+
+ return $this->respond([
+ 'status' => true,
+ 'message' => "This policy number is already linked to another policy in the Enrollment",
+ 'code' => 409,
+ 'data' => 1,
+ 'received_data' => $received_data,
+ 'client_policy_id' => $client_policy_data['id']
+ ], 200);
- if ($data > 0) {
- return $this->respond(['status' => true, 'message' => 'This policy number is already linked to another client', 'data' => $data, 'code' => 409, 'received_data' => $received_data, 'client_policy_id' => $client_policy_data['id'] ?? null], 200);
} else {
- return $this->respond(['status' => false, 'message' => 'No Data Found', 'code' => 404, 'received_data' => $received_data, 'client_policy_id' => $client_policy_data['id'] ?? null], 200);
+
+ return $this->respond([
+ 'status' => false,
+ 'message' => 'No Data Found',
+ 'code' => 404,
+ 'received_data' => $received_data,
+ 'client_policy_id' => null
+ ], 200);
}
}
@@ -5652,11 +5687,9 @@ class ClientController extends AdminController
public function sendextraparam()
{
- // $data = db_connect()->table('jobs')->where('id', 1677)->get()->getRowArray();
- // // dd($data);
+ // $return = db_connect()->table('jobs')->where('id', 1677)->get()->getRowArray();
// $return = $this->updatePolicyTransactionDataWhileClinetPolicyUpdate(json_decode($data['payload'], true));
// dd($return);
- // die;
// $ticket_id = 515;
// $apiServiceController = new ApiServiceController();
@@ -5680,7 +5713,9 @@ class ClientController extends AdminController
// $response = $ticketServiceController->extractExcelData("claims_dump_form_client.xlsx");
// dd($response);
- // $TicketController = new TicketController();
+ // ---------- TICKET SERVICE CONTROLLER --------------------------------------------------------------------------------
+
+ $TicketController = new TicketController();
// $response = $TicketController->getMoreInfo($requestFrom = 'rest', $ticket_id = 70);
// dd($response);
@@ -5689,7 +5724,8 @@ class ClientController extends AdminController
$empServiceController = new EmployeeServiceController();
// $res = $empServiceController->excelFileFormatValidation(['file_id' => '1126']);
// $res = $empServiceController->excelFileDataValidation(['file_id' => '865']);
- // $res = $empServiceController->employeesOnboardPreprocess(['file_id' => 726]);
+ // $res = $empServiceController->employeesOnboardPreprocess(['file_id' => 1183]);
+ // $res = $empServiceController->employeesOnboardPreprocess(['file_id' => 1169]);
// $res = $empServiceController->employeesOnboardProcess(['file_id' => 835]);
// $res = $empServiceController->employeesEnrollmentInsert(['file_id' => 836]);
// $res = $empServiceController->employeesSIEnhanceProcess(['file_id' => '1131']);
@@ -5698,13 +5734,13 @@ class ClientController extends AdminController
// $res = $empServiceController->compareMemberDataAndInceptionData(['file_id' => '1126']);
// dd($res);
+ // ---------- EMP MULTI EVENT SERVICE CONTROLLER --------------------------------------------------------------------------------
+
$EmployeeMultiEventServiceController = new EmployeeMultiEventServiceController();
// $res = $EmployeeMultiEventServiceController->constructMultiEventData(['file_id' => '1069']);
// $res = $EmployeeMultiEventServiceController->excelMultieventFileFormateValidation(['file_id' => '2373']);
// $res = $EmployeeMultiEventServiceController->excelMultieventFileDataValidation(['file_id' => '2373']);
// $res = $EmployeeMultiEventServiceController->excelMultieventFileOnBoard(['file_id' => '1069']);
- // dd($res);
-
// $res = $EmployeeMultiEventServiceController->getExcelErrorData(1069, $res);
// $res['file_id'] = 1069;
// echo view('excel_errors', $res);
@@ -6033,8 +6069,8 @@ class ClientController extends AdminController
->where('employees.is_active', 1)
->where('employees.relationship', "Self")
->where('employee_polices.is_active', 1)
- ->whereIn('employees.emp_status', ['active'])
- ->whereIn('employee_polices.status', ['active'])
+ ->whereIn('employees.emp_status', ['active', 'expired'])
+ ->whereIn('employee_polices.status', ['active', 'expired'])
->where('employees.is_active', 1)
->where('client_policy.id', $param)
->groupBy('employees.emp_code')
@@ -6147,10 +6183,10 @@ class ClientController extends AdminController
->where('insurers.is_active', 1)
->where('tpa.is_active', 1)
->where('employees.is_active', 1)
- ->where('employees.emp_status', "active")
+ ->whereIn('employees.emp_status', ['active', 'expired'])
->where('employees.relationship', "Self")
->where('employee_polices.is_active', 1)
- ->where('employee_polices.status', "active")
+ ->whereIn('employee_polices.status', ['active', 'expired'])
->where($field_name, $param);
if (!empty($client_id)) {
diff --git a/app/Controllers/DeployController.php b/app/Controllers/DeployController.php
new file mode 100644
index 00000000..de73092a
--- /dev/null
+++ b/app/Controllers/DeployController.php
@@ -0,0 +1,286 @@
+myLogger = \Config\Services::mylogger();
+ }
+ // public function fedeploy()
+ // {
+ // $request = $this->request;
+
+ // // Multiple zip files:
+ // // $zipFiles = $this->request->getFileMultiple('zip_files');
+ // $zipFiles = $this->request->getFile('zip_files');//('zip_files');
+ // // print_r($zipFiles);die();
+
+ // // Matching dropdown/text values (arrays, indexed same as zip_files[])
+ // $zipFolders = (array) $request->getPost('zip_folder'); // e.g. ["web/", "dist/"]
+ // $s3Buckets = (array) $request->getPost('s3_bucket'); // e.g. ["benefits-app-bucket", ...]
+ // $s3Prefixes = (array) $request->getPost('s3_prefix'); // e.g. ["hr/", "payroll/"]
+ // $cfDistributions = (array) $request->getPost('cf_distribution_id'); // e.g. ["DIST1", "DIST1", "DIST2"]
+ // $cfPathsList = (array) $request->getPost('cf_paths'); // e.g. ["/hr/*", "/hr/special/*", "/payroll/*"]
+
+ // // Path to Python interpreter and deploy_assets.py script
+ // $pythonBin = getenv('PY_PATH'); // adjust if needed
+ // $scriptPath = getenv('PY_SCRIPT_PATH'); // full path to your script
+
+ // $results = [];
+
+ // if (empty($zipFiles)) {
+ // return $this->response->setJSON([
+ // 'status' => 'error',
+ // 'message' => 'No zip files uploaded',
+ // ]);
+ // }
+
+ // // --------------------------------------------------------
+ // // 1) Pre-process distribution IDs → group by distribution
+ // // - So we can run ONE invalidation per distribution
+ // // - And merge all paths into a single JSON array
+ // // --------------------------------------------------------
+ // $distGroups = []; // [distId => ['indexes' => [...], 'paths' => [...], 'firstIndex' => int]]
+
+ // foreach ($cfDistributions as $i => $distId) {
+ // $distId = trim((string) $distId);
+ // $path = trim((string) ($cfPathsList[$i] ?? ''));
+
+ // // Only consider entries where both distribution ID and path are set
+ // if ($distId === '' || $path === '') {
+ // continue;
+ // }
+
+ // if (!isset($distGroups[$distId])) {
+ // $distGroups[$distId] = [
+ // 'indexes' => [],
+ // 'paths' => [],
+ // ];
+ // }
+
+ // $distGroups[$distId]['indexes'][] = $i;
+ // $distGroups[$distId]['paths'][] = $path;
+ // }
+
+ // // Set firstIndex and unique paths per distribution
+ // foreach ($distGroups as $distId => $info) {
+ // $distGroups[$distId]['firstIndex'] = $info['indexes'][0]; // first file index for this dist
+ // $distGroups[$distId]['paths'] = array_values(array_unique($info['paths'])); // unique paths
+ // }
+
+ // // --------------------------------------------------------
+ // // 2) Process each uploaded file
+ // // --------------------------------------------------------
+ // foreach ($zipFiles as $index => $file) {
+ // if (!$file->isValid() || $file->hasMoved()) {
+ // $results[] = [
+ // 'file' => $file->getName(),
+ // 'status' => 'error',
+ // 'message' => 'Invalid file or already moved.',
+ // ];
+ // continue;
+ // }
+
+ // // Read matching form values (or fallback)
+ // $zipFolder = $zipFolders[$index] ?? 'web/'; // default example
+ // $s3Bucket = $s3Buckets[$index] ?? '';
+ // $s3Prefix = $s3Prefixes[$index] ?? '';
+ // $cfDistribution = $cfDistributions[$index] ?? '';
+ // $cfDistribution = trim((string) $cfDistribution);
+
+ // // Move file into a known directory (keep original name)
+ // // $uploadDir = WRITEPATH . 'uploads/deploy';
+ // $uploadDir = '/home/ubuntu/py';
+ // if (!is_dir($uploadDir)) {
+ // mkdir($uploadDir, 0775, true);
+ // }
+
+ // $originalName = $file->getName();
+ // $file->move($uploadDir, $originalName);
+ // $zipPath = $uploadDir . DIRECTORY_SEPARATOR . $originalName;
+
+ // // --------------------------------------------------------
+ // // Decide whether THIS file should trigger invalidation
+ // // - Only firstIndex of each distribution will do it
+ // // - cf-paths-json = JSON array of all unique paths for that dist
+ // // --------------------------------------------------------
+ // $doInvalidation = false;
+ // $cfPathsJson = '';
+
+ // if ($cfDistribution !== '' && isset($distGroups[$cfDistribution])) {
+ // $group = $distGroups[$cfDistribution];
+
+ // if ($group['firstIndex'] === $index) {
+ // // This is the first file for this distribution ID → do invalidation ONCE
+ // $doInvalidation = true;
+
+ // // Build CloudFront paths JSON array (AWS syntax: ["path1", "path2", ...])
+ // $cfPathsJson = json_encode($group['paths']); // e.g. ["\/hr\/*","\/hr\/special\/*"]
+ // }
+ // // Else: same distribution ID but NOT first index → no invalidation
+ // }
+
+ // // --------------------------------------------------------
+ // // Build the python command safely using escapeshellarg
+ // // --------------------------------------------------------
+ // $cmdParts = [
+ // escapeshellarg($pythonBin),
+ // escapeshellarg($scriptPath),
+ // '--zip-path', escapeshellarg($zipPath),
+ // '--zip-folder', escapeshellarg($zipFolder),
+ // '--s3-bucket', escapeshellarg($s3Bucket),
+ // '--s3-prefix', escapeshellarg($s3Prefix),
+ // '--do-webhook', // always send webhook after success
+ // ];
+
+ // if ($doInvalidation) {
+ // $cmdParts[] = '--do-invalidation';
+ // $cmdParts[] = '--cf-distribution-id';
+ // $cmdParts[] = escapeshellarg($cfDistribution);
+ // $cmdParts[] = '--cf-paths-json';
+ // $cmdParts[] = escapeshellarg($cfPathsJson); // e.g. '["/hr/*","/hr/special/*"]'
+ // }
+
+ // // Final command string (2>&1 to capture stderr too)
+ // $cmd = implode(' ', $cmdParts) . ' 2>&1';
+ // print_r($cmd);die();
+ // $output = [];
+ // $returnVar = 0;
+
+ // exec($cmd, $output, $returnVar);
+
+ // $results[] = [
+ // 'file' => $originalName,
+ // 'zip_path' => $zipPath,
+ // 'command' => $cmd,
+ // 'output' => $output,
+ // 'exit_code' => $returnVar,
+ // 'status' => $returnVar === 0 ? 'success' : 'error',
+ // ];
+ // }
+
+ // return $this->response->setJSON([
+ // 'status' => 'completed',
+ // 'results' => $results,
+ // ]);
+ // }
+
+ public function fedeploy()
+ {
+ $request = $this->request;
+
+ // Single zip file:
+ $file = $request->getFile('zip_file');
+
+ if (!$file || !$file->isValid()) {
+ return $this->response->setJSON([
+ 'status' => 'error',
+ 'message' => 'No valid zip file uploaded',
+ ]);
+ }
+
+ // Read scalar form values
+ $zipFolder = (string) $request->getPost('zip_folder') ?: 'web/';
+ $s3Bucket = (string) $request->getPost('s3_bucket') ?: '';
+ $s3Prefix = (string) $request->getPost('s3_prefix') ?: '';
+ $cfDistribution = trim((string) $request->getPost('cf_distribution_id'));
+ $cfPathsRaw = (string) $request->getPost('cf_paths');
+
+ // Python interpreter and script path from env
+ $pythonBin = getenv('PY_PATH'); // e.g. /usr/bin/python3
+ $scriptPath = getenv('PY_SCRIPT_PATH'); // e.g. /home/ubuntu/deploy_assets.py
+
+ if (empty($pythonBin) || empty($scriptPath)) {
+ return $this->response->setJSON([
+ 'status' => 'error',
+ 'message' => 'Python path or script path not configured in environment.',
+ ]);
+ }
+
+ // Move file into known directory (keep original name)
+ $uploadDir = '~/py';
+ if (!is_dir($uploadDir)) {
+ mkdir($uploadDir, 0775, true);
+ }
+
+ $originalName = $file->getName();
+ $file->move($uploadDir, $originalName);
+ $zipPath = $uploadDir . DIRECTORY_SEPARATOR . $originalName;
+
+ // -----------------------------
+ // CloudFront invalidation data
+ // -----------------------------
+ $doInvalidation = false;
+ $cfPathsJson = '';
+
+ // Allow comma or newline separated paths: "/hr/*,/hr/special/*" or
+ // "/hr/*\n/hr/special/*"
+ $paths = array_filter(
+ array_map('trim', preg_split('/[\r\n,]+/', $cfPathsRaw)),
+ 'strlen'
+ );
+
+ if ($cfDistribution !== '' && !empty($paths)) {
+ $doInvalidation = true;
+ $cfPathsJson = json_encode($paths); // e.g. ["\/hr\/*","\/hr\/special\/*"]
+ }
+
+ // -----------------------------
+ // Build python command
+ // -----------------------------
+ $cmdParts = [
+ escapeshellarg($pythonBin),
+ escapeshellarg($scriptPath),
+ '--zip-path', escapeshellarg($zipPath),
+ '--zip-folder', escapeshellarg($zipFolder),
+ '--s3-bucket', escapeshellarg($s3Bucket),
+ '--s3-prefix', escapeshellarg($s3Prefix),
+ '--do-webhook', // always send webhook after success
+ ];
+
+ if ($doInvalidation) {
+ $cmdParts[] = '--do-invalidation';
+ $cmdParts[] = '--cf-distribution-id';
+ $cmdParts[] = escapeshellarg($cfDistribution);
+ $cmdParts[] = '--cf-paths-json';
+ $cmdParts[] = escapeshellarg($cfPathsJson);
+ }
+
+ // Final command string (2>&1 to capture stderr too)
+ $cmd = implode(' ', $cmdParts) . ' 2>&1';
+ $output = [];
+ $returnVar = 0;
+ print_r($cmd);die();
+ exec($cmd, $output, $returnVar);
+
+ $result = [
+ 'file' => $originalName,
+ 'zip_path' => $zipPath,
+ 'command' => $cmd,
+ 'output' => $output,
+ 'exit_code' => $returnVar,
+ 'status' => $returnVar === 0 ? 'success' : 'error',
+ ];
+
+ return $this->response->setJSON([
+ 'status' => 'completed',
+ 'result' => $result,
+ ]);
+ }
+
+
+ public function fedeploy_view()
+ {
+ // $this->load->view('fedeploy');
+ $this->loadLayout('fedeploy');
+ }
+
+}
diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php
index 1c22f967..99829bf0 100755
--- a/app/Controllers/EmpDataServiceController.php
+++ b/app/Controllers/EmpDataServiceController.php
@@ -43,6 +43,7 @@ use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Exception as SpreadsheetReaderException;
use PhpParser\Node\Expr\Cast\Double;
use Kint\Kint;
+use PhpParser\Node\Stmt\TraitUseAdaptation;
use function PHPUnit\Framework\returnSelf;
@@ -2179,18 +2180,18 @@ class EmpDataServiceController extends BaseController
'user_id' => $user_id,
]]);
- // $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [
- // 'client_policy_id' => $client_policy_id ?? null,
- // 'endorsement_no' => $endorsement_id ?? null,
- // 'emp_count' => $emp_count ?? null,
- // 'action_type' => $file['event_type'] ?? null,
- // 'no_of_insured' => count($no_of_insured ?? []) ?? null,
- // 'no_of_dependent' => count($no_of_dependent ?? []) ?? null,
- // 'base_premium' => $base_bremium_and_gst['base_premium'] ?? null,
- // 'gst' => $base_bremium_and_gst['gst'] ?? null,
- // 'policy_issue_date' => $policy_issue_date ?? null,
- // 'created_by' => $file['created_by'] ?? null,
- // ]]);
+ $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [
+ 'client_policy_id' => $client_policy_id ?? null,
+ 'endorsement_no' => $endorsement_id ?? null,
+ 'emp_count' => $emp_count ?? null,
+ 'action_type' => $file['event_type'] ?? null,
+ 'no_of_insured' => count($no_of_insured ?? []) ?? null,
+ 'no_of_dependent' => count($no_of_dependent ?? []) ?? null,
+ 'base_premium' => $base_bremium_and_gst['base_premium'] ?? null,
+ 'gst' => $base_bremium_and_gst['gst'] ?? null,
+ 'policy_issue_date' => $policy_issue_date ?? null,
+ 'created_by' => $file['created_by'] ?? null,
+ ]]);
// $this->cashDepositCalculationForInception($depositeData);
// $this->sendMailForDownloadingECard($emp_policy_ids);
@@ -2620,14 +2621,14 @@ class EmpDataServiceController extends BaseController
$file_data = $this->getDataByFileId($file_id, 'success');
$this->setPullNotification($file_data);
- // $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [
- // 'client_policy_id' => $client_policy_id ?? null,
- // 'endorsement_no' => $endorsement_id[0] ?? null,
- // 'emp_count' => $emp_count ?? null,
- // 'action_type' => $file['event_type'] ?? null,
- // 'policy_issue_date' => $policy_issue_date ?? null,
- // 'created_by' => $file['created_by'] ?? null,
- // ]]);
+ $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [
+ 'client_policy_id' => $client_policy_id ?? null,
+ 'endorsement_no' => $endorsement_id[0] ?? null,
+ 'emp_count' => $emp_count ?? null,
+ 'action_type' => $file['event_type'] ?? null,
+ 'policy_issue_date' => $policy_issue_date ?? null,
+ 'created_by' => $file['created_by'] ?? null,
+ ]]);
//import file to upload Google Drive
@@ -3354,18 +3355,18 @@ class EmpDataServiceController extends BaseController
'user_id' => $user_id,
]]);
- // $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [
- // 'client_policy_id' => $client_policy_id ?? null,
- // 'endorsement_no' => $endorsement_id ?? null,
- // 'emp_count' => $emp_count ?? null,
- // 'action_type' => $file['event_type'] ?? null,
- // 'no_of_insured' => count($no_of_insured ?? []) ?? null,
- // 'no_of_dependent' => count($no_of_dependent ?? []) ?? null,
- // 'base_premium' => $base_bremium_and_gst['base_premium'] ?? null,
- // 'gst' => $base_bremium_and_gst['gst'] ?? null,
- // 'policy_issue_date' => $policy_issue_date ?? null,
- // 'created_by' => $file['created_by'] ?? null,
- // ]]);
+ $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [
+ 'client_policy_id' => $client_policy_id ?? null,
+ 'endorsement_no' => $endorsement_id ?? null,
+ 'emp_count' => $emp_count ?? null,
+ 'action_type' => $file['event_type'] ?? null,
+ 'no_of_insured' => count($no_of_insured ?? []) ?? null,
+ 'no_of_dependent' => count($no_of_dependent ?? []) ?? null,
+ 'base_premium' => $base_bremium_and_gst['base_premium'] ?? null,
+ 'gst' => $base_bremium_and_gst['gst'] ?? null,
+ 'policy_issue_date' => $policy_issue_date ?? null,
+ 'created_by' => $file['created_by'] ?? null,
+ ]]);
}
@@ -3865,18 +3866,18 @@ class EmpDataServiceController extends BaseController
'user_id' => $user_id,
]]);
- // $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [
- // 'client_policy_id' => $client_policy_id ?? null,
- // 'endorsement_no' => $endorsement_id ?? null,
- // 'emp_count' => $emp_count ?? null,
- // 'action_type' => $file['event_type'] ?? null,
- // 'no_of_insured' => count($no_of_insured ?? []) ?? null,
- // 'no_of_dependent' => count($no_of_dependent ?? []) ?? null,
- // 'base_premium' => $base_bremium_and_gst['base_premium'] ?? null,
- // 'gst' => $base_bremium_and_gst['gst'] ?? null,
- // 'policy_issue_date' => $policy_issue_date ?? null,
- // 'created_by' => $file['created_by'] ?? null,
- // ]]);
+ $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [
+ 'client_policy_id' => $client_policy_id ?? null,
+ 'endorsement_no' => $endorsement_id ?? null,
+ 'emp_count' => $emp_count ?? null,
+ 'action_type' => $file['event_type'] ?? null,
+ 'no_of_insured' => count($no_of_insured ?? []) ?? null,
+ 'no_of_dependent' => count($no_of_dependent ?? []) ?? null,
+ 'base_premium' => $base_bremium_and_gst['base_premium'] ?? null,
+ 'gst' => $base_bremium_and_gst['gst'] ?? null,
+ 'policy_issue_date' => $policy_issue_date ?? null,
+ 'created_by' => $file['created_by'] ?? null,
+ ]]);
}
$file_data = $this->getDataByFileId($file_id, 'success');
@@ -5170,6 +5171,7 @@ class EmpDataServiceController extends BaseController
public function makeEntryForBDSPolicyTransaction($params)
{
try {
+
$this->myLogger->logme("error", "makeEntryForBDSPolicyTransaction() started: " . json_encode(['params' => $params]));
if (empty($params) || !isset($params['client_policy_id']) || empty($params['client_policy_id'])) {
@@ -5182,18 +5184,23 @@ class EmpDataServiceController extends BaseController
return ['status' => "Failed", 'message' => "Action type is missing or empty", 'data' => ['params' => $params]];
}
- //Function call for if the old policy transaction entries exisit than active the Policy transaction entries
- $existing_policy_transaction_entry = $this->retrivePolicyTransactionEntries($params);
+ //get the policy data
+ $policy_data = $this->clientPolicyModel->where('id', $params['client_policy_id'])->where('is_active', 1)->first();
+ $params['policy_no'] = $policy_data['policy_no'] ?? null;
+
+ //check if the entries available in the policy transaction table
+ $check_policy_exist = $this->checkPolicyTransactionExist($params);
- if($existing_policy_transaction_entry != false){
- return $existing_policy_transaction_entry;
+ if($check_policy_exist['status'] == true) {
+ return $check_policy_exist;
}
- //get the policy data
- $policy_data = $this->clientPolicyModel
- ->where('id', $params['client_policy_id'])
- ->where('is_active', 1)
- ->first();
+ //Function call for if the old policy transaction entries exisit than active the Policy transaction entries
+ // $existing_policy_transaction_entry = $this->retrivePolicyTransactionEntries($params);
+
+ // if($existing_policy_transaction_entry != false) {
+ // return $existing_policy_transaction_entry;
+ // }
if (empty($policy_data)) {
$this->myLogger->logme("error", "No policy data found: " . json_encode(['client_policy_id' => $params['client_policy_id']]));
@@ -5201,10 +5208,7 @@ class EmpDataServiceController extends BaseController
}
//get the leads data
- $lead_data = $this->leadsModel
- ->where('is_policy_created', $params['client_policy_id'])
- ->where('is_active', 1)
- ->first();
+ $lead_data = $this->leadsModel->where('is_policy_created', $params['client_policy_id'])->where('is_active', 1)->first();
if (empty($lead_data)) {
$this->myLogger->logme("error", "No lead data found: " . json_encode(['client_policy_id' => $params['client_policy_id']]));
@@ -5227,14 +5231,13 @@ class EmpDataServiceController extends BaseController
$this->myLogger->logme("error", "Policy transaction inserted successfully: " . json_encode(['insert_id' => $insert_id]));
//do not remove this commented item
- $coShareDetails = $this->ConstructPTShareData($policy_data, $insert_id, $params);
+ $coShareDetails = $this->ConstructPTShareData($policy_data, $insert_id, $params, $lead_data);
$pt_co_share_id = $this->PTCOShareDetailsModel->insert($coShareDetails);
-
- // $this->myLogger->logme("error", "PT Co share data inserted successfully: " . json_encode(['pt_co_share_id' => $pt_co_share_id]));
+ $this->myLogger->logme("error", "PT Co share data inserted successfully: " . json_encode(['pt_co_share_id' => $pt_co_share_id]));
// get the lead installment data
-
if(!empty($lead_data)){
+
$lead_installment_data = $this->leadInstallmentPaymentDetailesModel
->select('lead_id, installment_amount, payment_date, utr_no')
->where('lead_id', $lead_data['id'])
@@ -5253,12 +5256,20 @@ class EmpDataServiceController extends BaseController
return ['status' => "Success", 'message' => "Policy transaction entry created successfully", 'data' => ['params' => $params, 'insert_id' => $insert_id]];
} catch (\Throwable $e) {
+
+ $errorDetails = [
+ 'error_message' => $e->getMessage(),
+ 'file' => $e->getFile(),
+ 'line' => $e->getLine(),
+ 'stack_trace' => $e->getTraceAsString(),
+ ];
+
$this->myLogger->logme("error", "Exception occurred in makeEntryForBDSPolicyTransaction(): " . json_encode([
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]));
- return ['status' => "Error", 'message' => "An unexpected error occurred", 'data' => ['error' => $e]];
+ return ['status' => "Error", 'message' => "An unexpected error occurred", 'data' => $errorDetails];
}
}
@@ -5271,9 +5282,20 @@ class EmpDataServiceController extends BaseController
$action_type_string = "addition";
}
+ $user_data = db_connect()->table('user_profiles')->where('is_active', 1)->where('id', $lead_data['created_by'] ?? null)->get()->getRowArray();
+
+ $salse_person_id = null;
+ if(isset($lead_data['salse_person_id']) && !empty($lead_data['salse_person_id'])){
+ $salse_person_array = json_decode($lead_data['salse_person_id'] ?? '{}', true) ?? [];
+ $salse_person_id = $salse_person_array[0] ?? null;
+ }else{
+ $salse_person_id = $lead_data['created_by'] ?? null;
+ }
+
$policyTransactionData = [
'issuer' => 2,
+ 'issuer_branch' => $user_data['nhance_branch_id'] ?? 1,
'client_id' => $policy_data['client_id'] ?? null,
'client_branch_id' => $policy_data['client_branch_id'] ?? null,
'insurer_id' => $policy_data['insurer_id'] ?? null,
@@ -5292,7 +5314,7 @@ class EmpDataServiceController extends BaseController
'closure_date' => $policy_data['closure_date'] ?? null,
'emp_count' => $params['no_of_insured'] ?? null,
'dependent_count' => $params['no_of_dependent'] ?? null,
- 'revenue_type' => isset($lead_data['lead_type']) ?($lead_data['lead_type'] == 1 ? "NA" : ($lead_data['lead_type'] == 2 ? "EA" : "EANR") ) : null,
+ 'revenue_type' => isset($lead_data['lead_type']) ?($lead_data['lead_type'] == 1 ? "NA" : ($lead_data['lead_type'] == 2 ? "EA" : "EANR") ) : "NA",
'co_share' => $policy_data['co_share'] ?? 0,
'pre_payable_by' => $policy_data['pre_payable_by'] ?? 1,
'renewal_date' => $policy_data['policy_end_date'] ?? null,
@@ -5312,6 +5334,10 @@ class EmpDataServiceController extends BaseController
'tsi' => generate_tsi_code($lead_data['lead_type'] ?? 1) ?? null,
'installment' => $lead_data['no_of_installment'] ?? null,
'created_by' => $params['created_by'] ?? null,
+ 'entry_from' => 2,
+
+ 'sales_generated_by' => $salse_person_id,
+ 'serviced_by' => $params['created_by'] ?? null,
];
$this->myLogger->logme("error", "Constructed policy transaction data: " . json_encode($policyTransactionData));
@@ -5319,7 +5345,7 @@ class EmpDataServiceController extends BaseController
return $policyTransactionData;
}
- private function ConstructPTShareData($policy_data, $pt_id, $params)
+ private function ConstructPTShareData($policy_data, $pt_id, $params, $lead_data)
{
$policyTypeModel = new PolicyTypeModel();
$policy_type_data = $policyTypeModel->where('is_active', 1)->where('id', $policy_data['policy_type_id'])->first();
@@ -5336,10 +5362,15 @@ class EmpDataServiceController extends BaseController
'co_share_type' => 1,
'co_share_per' => 100,
'standerd_bp_per' => $policy_type_data['ebp'],
+ 'pt_policy_issue_date' => $params['policy_issue_date'] ?? null,
'amount' => ($params['base_premium'] ?? 0) + ($params['gst'] ?? 0),
];
- $coShareData['exp_amt'] = (($params['base_premium'] ?? 0) * ($policy_type_data['ebp'] ?? 0)) / 100;
+ if(isset($lead_data['agreed_percentage']) && !empty($lead_data['agreed_percentage'])){
+ $coShareData['exp_amt'] = (($params['base_premium'] ?? 0) * ($lead_data['agreed_percentage'] ?? 0)) / 100;
+ }else{
+ $coShareData['exp_amt'] = (($params['base_premium'] ?? 0) * ($policy_type_data['ebp'] ?? 0)) / 100;
+ }
$this->myLogger->logme("error", "Constructed PT co-share data: " . json_encode($coShareData));
@@ -5391,8 +5422,7 @@ class EmpDataServiceController extends BaseController
$activated_pt_co_share_ids[] = $value['id'];
}
- $this->myLogger->logme("error", "Activated pt_co_share_ids : ". json_encode($activated_pt_co_share_ids));
-
+ $this->myLogger->logme("error", "Activated pt_co_share_ids : ". json_encode($activated_pt_co_share_ids));
$update_return = $this->policyTransactionModel->where('id', $policy_transaction_data['id'])->set(['is_active' => 1])->update();
@@ -5405,6 +5435,30 @@ class EmpDataServiceController extends BaseController
}
}
+
+ public function checkPolicyTransactionExist($params)
+ {
+ // Trim the input
+ $policy_no = trim($params['policy_no']);
+
+ // Base query
+ $policy_transaction_data = $this->policyTransactionModel->where('is_active', 1)->where('TRIM(policy_no)', $policy_no);
+
+ // Add endorsement condition only if not inception
+ if ($params['action_type'] !== "inception") {
+ $policy_transaction_data = $policy_transaction_data ->where('TRIM(endorsement_no)', trim($params['endorsement_no']));
+ }
+
+ $policy_transaction_data = $policy_transaction_data->first();
+
+ // If record exists → log and return true
+ if (!empty($policy_transaction_data)) {
+ $this->myLogger->logme("error", "Policy Transaction already exists. Input Parameters: " . json_encode($params) );
+ return ['status' => true, 'message' => "This entry already available in the Policy Transaction table", 'data' => $policy_transaction_data['id']];
+ }
+
+ return ['status' => false, 'message' => "This entry not available in the Policy Transaction table", 'data' => ''];
+ }
public function removeBDSPolicyTransactionEntryFromTruncate($params)
{
diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php
index 0da7f5a7..eee1b16f 100755
--- a/app/Controllers/EmployeeController.php
+++ b/app/Controllers/EmployeeController.php
@@ -483,6 +483,8 @@ class EmployeeController extends AdminController
$filePath = ROOTPATH . 'public/sample_excel/Sample_Member_Data.xlsx';
}else if ($actionType == 'all') {
$filePath = ROOTPATH . 'public/sample_excel/sample_multievent_file.xlsx';
+ }else if ($actionType == 'bds_upload') {
+ $filePath = ROOTPATH . 'public/sample_excel/sample_bds_bulk_upload_excel.xlsx';
}
// Check if the file exists
diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php
index 733c2352..6c655880 100755
--- a/app/Controllers/EmployeeRestController.php
+++ b/app/Controllers/EmployeeRestController.php
@@ -2656,7 +2656,7 @@ class EmployeeRestController extends AdminController
->where('is_active', 1)
->where('file_type', 2)
->where('ticket_id', $ticket_id)
- ->where('ticket_message_id', $ticket_message['id'])
+ // ->where('ticket_message_id', $ticket_message['id'])
->findAll();
foreach ($claim_files_data as &$value) {
@@ -3850,6 +3850,8 @@ class EmployeeRestController extends AdminController
foreach ($client_claim_status as $claim_key => $claim_value) {
if (in_array($value['claim_status_id'], $claim_value)) { // Corrected argument order
$ticket_data[$key]['claim_status'] = $claim_key ?? null; // Assign back to the main array
+ }else if(in_array($value['old_status_id'], $claim_value)){
+ $ticket_data[$key]['claim_status'] = $claim_key ?? null; // Assign back to the main array
}
}
diff --git a/app/Controllers/EmployeeServiceController.php b/app/Controllers/EmployeeServiceController.php
index 690e9c08..fd2f4694 100755
--- a/app/Controllers/EmployeeServiceController.php
+++ b/app/Controllers/EmployeeServiceController.php
@@ -1385,12 +1385,18 @@ class EmployeeServiceController extends AdminController
$existing_famility_details = transform_db_data_to_excel($existing_famility_details,$file);
// Kint::dump($existing_famility_details);
$family = array_merge($family,$existing_famility_details);
- $family = data_group_by_family($family)[ $emp_id ];// reason to call this again is bring self to first index of the array
- // dd($family);
+ $family = data_group_by_family($family, 'excel', 1)[ $emp_id ];// reason to call this again is bring self to first index of the array
+ // dd($family);
+ $self = current(array_filter($family, fn($r) => strtolower($r[5] ?? '') === 'self'));
+ $premium = (int)($self['temp']['rata_premimum'] ?? 0);
+ foreach ($family as &$r) if (strtolower($r[5] ?? '') !== 'self') $r['self_rata_premium'] = $premium;
}
// Kint::dump($family);
$data = calculate_premium_new(family_data:$family,policy_terms: $policy_terms,slab_details : $slab_details,fileArr: $file, existing_units:$existing_units);
+ if($file['action'] == 'dependent_addition') {
+ $data = validatet_family_floter_rata_premium($data);
+ }
// dd($data);
$employee_data_group_by_family[$emp_id] = $data;
$this->employeesOnboardProcess(['familiy_data' => $data,'file' => $file]);
diff --git a/app/Controllers/InsuranceCommissionController.php b/app/Controllers/InsuranceCommissionController.php
index 3798237a..f2907bf6 100644
--- a/app/Controllers/InsuranceCommissionController.php
+++ b/app/Controllers/InsuranceCommissionController.php
@@ -13,7 +13,7 @@ class InsuranceCommissionController extends AdminController
public function __construct()
{
- set_session_context('Client');
+ set_session_context('InsuranceCommissionController');
$this->myLogger = \Config\Services::mylogger();
// Load rules file if present in writable config path
// $rulesPath = WRITEPATH . 'config/insurance_rules.json';
@@ -122,7 +122,10 @@ class InsuranceCommissionController extends AdminController
// Normalise department keys to lowercase for consistent lookups
$this->rules = [];
foreach ($parsed as $dept => $rules) {
- $this->rules[strtolower($dept)] = $rules;
+ if($rules['is_deleted'] === false)
+ {
+ $this->rules[strtolower($dept)] = $rules;
+ }
}
// print_r($this->rules);die();
diff --git a/app/Controllers/JobWorker.php b/app/Controllers/JobWorker.php
index eadca406..190a1058 100755
--- a/app/Controllers/JobWorker.php
+++ b/app/Controllers/JobWorker.php
@@ -179,6 +179,14 @@ class JobWorker extends AdminController
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\MediAssistApiController',
],
+ 'bdsDumpExcelFileFormatValidation' => [
+ 'type' => 'CC', // Handler Category
+ 'handler' => 'App\Controllers\PolicyTransactionController',
+ ],
+ 'insertBulkBdsData' => [
+ 'type' => 'CC', // Handler Category
+ 'handler' => 'App\Controllers\PolicyTransactionController',
+ ],
];
diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php
index 92fa8a52..a3ebe469 100644
--- a/app/Controllers/LeadsController.php
+++ b/app/Controllers/LeadsController.php
@@ -3292,6 +3292,7 @@ class LeadsController extends BaseController
'no_of_installment' => $params['no_of_installment'] ?? null,
'is_installment' => $params['is_installment'] ?? null,
'acm_id' => $params['acm_pk'] ?? null,
+ 'agreed_percentage' => $params['agreed_percentage'] ?? null,
];
if(isset($params['tpa_id']) && !empty($params['tpa_id'])){
diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php
index d2ce1329..fec5dc4e 100755
--- a/app/Controllers/MasterController.php
+++ b/app/Controllers/MasterController.php
@@ -1980,6 +1980,7 @@ class MasterController extends AdminController
'files' => WRITEPATH . 'uploads/commission/files',
'rules' => WRITEPATH . 'uploads/commission/rules',
'claim_sample_forms' => ROOTPATH . 'public/claim_sample_forms/',
+ 'bds_dump_excel' => WRITEPATH . 'uploads/bds_dump_excel/',
];
foreach ($folders as $folderName => $folderPath) {
diff --git a/app/Controllers/NotificationController.php b/app/Controllers/NotificationController.php
index ee50a0fd..e288a7a0 100755
--- a/app/Controllers/NotificationController.php
+++ b/app/Controllers/NotificationController.php
@@ -217,40 +217,44 @@ class NotificationController extends AdminController
}
// This function for sent a mail for testing
- public function sentTestMail($template_id, $test_mail)
+ // keep watching this
+ public function sentTestMail($template_id, $test_mail, $string_flag)
{
$notification_data = $this->notificationModel->where('id', $template_id)->first();
+
+
+ if(empty($notification_data)) {
+ return $this->respond(['status' => false,'code' => 200, 'message' => 'Notification Template not enabled']);
+ }
+
$client_data = $this->clientModel->where('id', $notification_data['client_id'])->where('is_active', 1)->first();
- if(!empty($notification_data)){
-
- $params = [
+ $params = [
'client_data' => $client_data,
'notification_data' => $notification_data,
'test_mail' => $test_mail
- ];
+ ];
- $testMailData = sendMailNotification::sendMailNotificationForTesting($notification_data['template_name'], $params);
- // print_r($testMailData); die;
- if (!empty($testMailData)) {
+ $testMailData = sendMailNotification::sendMailNotificationForTesting($notification_data['template_name'], $params);
- $mail_send_return1 = MailHelper::send_email($testMailData);
- $this->myLogger->logme("info", $mail_send_return1);
- $this->myLogger->logme("info", $mail_send_return1);
+ if(empty($testMailData)) {
+ return $this->respond(['status' => false,'code' => 200, 'message' => 'Test Mail Data Does Not Exist']);
+ }
- return $this->respond(['status' => true,'code' => 200, 'respond' => json_decode($mail_send_return1)]);
-
- }else{
-
- return $this->respond(['status' => false,'code' => 200, 'message' => 'Test Mail Data Does Not Exist']);
- }
- }else{
-
- return $this->respond(['status' => false,'code' => 200, 'message' => 'Notification Template not enabled']);
+ if($string_flag == "send"){
+ $mail_send_return1 = MailHelper::send_email($testMailData);
+ $this->myLogger->logme("info", $mail_send_return1);
+ return $this->respond(['status' => true,'code' => 200, 'respond' => json_decode($mail_send_return1)]);
+ }
+ if($string_flag == "preview"){
+ return $this->respond([
+ 'status' => true,
+ 'code' => 200,
+ 'content' => $testMailData
+ ]);
}
}
-
public function sendCommonTestMail()
@@ -258,7 +262,7 @@ class NotificationController extends AdminController
$template_id = $this->request->getPost('template_id');
- $test_mail = $this->request->getPost('test_mail');
+ // $test_mail = $this->request->getPost('test_mail');
$test_mail_list = $this->request->getPost('test_mail_list');
@@ -268,27 +272,67 @@ class NotificationController extends AdminController
if(!empty($notification_data)){
- $params = [
- 'client_data' => $client_data,
- 'notification_data' => $notification_data,
- 'test_mail' => $test_mail,
- 'test_mail_list' => $test_mail_list
- ];
+ // First Index as test mail all are testmaillist
+ // $params = [
+ // 'client_data' => $client_data,
+ // 'notification_data' => $notification_data,
+ // 'test_mail' => $test_mail,
+ // 'test_mail_list' => $test_mail_list
+ // ];
+ // $testMailData = sendMailNotification::sendMailNotificationForTesting($notification_data['template_name'], $params);
+ // if (!empty($testMailData)) {
+ // $mail_send_return1 = MailHelper::send_email($testMailData);
+ // $this->myLogger->logme("info", $mail_send_return1);
+ // $this->myLogger->logme("info", $mail_send_return1);
+ // return $this->respond(['status' => true,'code' => 200, 'respond' => json_decode($mail_send_return1)]);
+ // }else{
+ // return $this->respond(['status' => false,'code' => 200, 'message' => 'Test Mail Data Does Not Exist']);
+ // }
- $testMailData = sendMailNotification::sendMailNotificationForTesting($notification_data['template_name'], $params);
- // print_r($testMailData); die;
- if (!empty($testMailData)) {
- $mail_send_return1 = MailHelper::send_email($testMailData);
- $this->myLogger->logme("info", $mail_send_return1);
- $this->myLogger->logme("info", $mail_send_return1);
+ $mailArray = explode(',', $test_mail_list);
+ $successMails = [];
+ $failedMails = [];
- return $this->respond(['status' => true,'code' => 200, 'respond' => json_decode($mail_send_return1)]);
+ foreach ($mailArray as $singleMail) {
+ $singleMail = trim($singleMail);
- }else{
+ $params = [
+ 'client_data' => $client_data,
+ 'notification_data' => $notification_data,
+ 'test_mail' => $singleMail,
+ 'test_mail_list' => "" // optional
+ ];
+
+ $testMailData = sendMailNotification::sendMailNotificationForTesting($notification_data['template_name'], $params);
+
+ if (!empty($testMailData)) {
+ $mail_send_return1 = MailHelper::send_email($testMailData);
+
+ if ($mail_send_return1) {
+ $successMails[] = $singleMail;
+ } else {
+ $failedMails[] = $singleMail;
+ }
+
+ $this->myLogger->logme("info", "Mail attempt to {$singleMail}: " . $mail_send_return1);
+ } else {
+ $failedMails[] = $singleMail;
+ $this->myLogger->logme("info", "Test Mail Data Does Not Exist for {$singleMail}");
+ }
+ }
+
+ // Prepare final response
+ if (!empty($successMails)) {
+ $responseMessage = "Count " . count($successMails) . " mail(s) sent successfully: \n" . implode("\n", $successMails);
+ if (!empty($failedMails)) {
+ $responseMessage .= "\nCount " . count($failedMails) . " mail(s) failed: \n" . implode("\n", $failedMails);
+ }
+ return $this->respond(['status' => true,'code' => 200,'message' => $responseMessage]);
+ } else {
+ return $this->respond(['status' => false,'code' => 200,'message' => 'All mails failed to send: ' . implode(", ", $failedMails)]);
+ }
- return $this->respond(['status' => false,'code' => 200, 'message' => 'Test Mail Data Does Not Exist']);
- }
}else{
return $this->respond(['status' => false,'code' => 200, 'message' => 'Notification Template not enabled']);
diff --git a/app/Controllers/PayoutController.php b/app/Controllers/PayoutController.php
index 02bbe1b2..7dccb5ba 100644
--- a/app/Controllers/PayoutController.php
+++ b/app/Controllers/PayoutController.php
@@ -9,6 +9,10 @@ use App\Models\InvoiceItemModel;
use App\Models\InvoiceModel;
use App\Models\InvoiceUtrModel;
use App\Models\PolicyTransactionModel;
+use App\Models\AuditHistoryModel;
+
+use Dompdf\Dompdf;
+use Dompdf\Options;
class PayoutController extends BaseController
{
@@ -20,21 +24,23 @@ class PayoutController extends BaseController
protected $policyTransactionModel;
protected $payout_status;
+ protected $auditHistory;
+
public function __construct()
{
set_session_context('PayoutController');
$this->myLogger = \Config\Services::mylogger();
$this->payout_status = [
- 1 => "Draft",
- 2 => "Pending",
- 3 => "Complete",
+ 1 => "Pending",
+ 2 => "Completed",
];
$this->invoiceItemModel = new InvoiceItemModel();
$this->invoiceModel = new InvoiceModel();
$this->invoiceUtrModel = new InvoiceUtrModel();
$this->policyTransactionModel = new PolicyTransactionModel();
+ $this->auditHistory = new AuditHistoryModel();
}
public function payoutList()
@@ -81,7 +87,7 @@ class PayoutController extends BaseController
// for list
$data['payout_status'] = $this->payout_status;
$data['agent_list'] = $this->invoiceModel->agentList();
- $data['page_name'] = "Payout";
+ $data['page_name'] = "Invoices";
$payout_data['payout_list_data'] = $this->invoiceModel->invoiceList();
$data['payout_list'] = view('payout_list', $payout_data);
@@ -189,4 +195,422 @@ class PayoutController extends BaseController
}
+ /*************************************************************************************************************/
+ //... Payout-invoice Mapping Commission's amount and Adjustment's Amount - Data Display
+ public function invoices()
+ {
+
+ $type = $this->request->getGet('type');
+
+ $title = $type === 'add' ? 'Add Payouts'
+ : ($type === 'edit' ? 'Edit Payouts'
+ : ($type === 'adjustment' ? 'Payouts Adjustment'
+ : 'Payouts'));
+
+ $data['tab_name'] = $title;
+ $data['page_name'] = $title;
+
+ $id = $this->request->getGet('id');
+
+ if($type == 'add')
+ {
+ $data['agents'] = $this->invoiceModel->agentList(['is_active' => 1]); // common both add and edit
+ }
+ else
+ {
+ $data['agents'] = $this->invoiceModel->agentList(); // common both add and edit
+ }
+ // $data['checked_policy_numbers'] = [];
+ // $data['invoice'] = [];
+ // $data['extra_payouts'] = [];
+
+ //... Now Seperated add => 'policy_transaction_payouts1'
+ //... Now Seperated edit and adjustment => 'policy_transaction_payouts' old file
+ //... Reason : Due Datatable issues Export button Searching like that so seperated
+ if ($type === 'add') {
+ // $invoiceNo = $this->generateInvoiceNumber();
+ $data['payouts'] = $this->invoiceModel->payoutList(1);
+ // print_rr($data['payouts']);die();
+ // print_rr($this->invoiceModel->getLastQuery());die();
+ // $data['invoice_number'] = $invoiceNo;
+ return $this->loadLayout('invoice_policy_mapping_add', $data);
+ }
+
+ if (($type === 'edit' || $type === 'adjustment') && !empty($id)) {
+
+ $invoice = $this->invoiceModel->where('id', $id)->first();
+ $data['freeze_edit'] = $this->auditHistory->where('table_name', 'partner_invoice')->where('pk', $id)->countAllResults();
+
+
+ $agentId = $invoice['agent_id'] ?? null;
+
+ $data['payouts'] = $this->invoiceModel->payoutList(2 ,$agentId,$id);
+ $data['extra_payouts'] = $agentId ? $this->invoiceModel->payoutList(3, $agentId) : [];
+
+ $invoice_items = $this->invoiceItemModel->where('invoice_id', $id)->findAll();
+
+ if (!$invoice) { return redirect()->to('payout/invoices')->with('error', 'Invoice not found'); }
+
+ $data['invoice'] = $invoice;
+ $data['invoice_items'] = $invoice_items;
+ // Initialize array for policy numbers
+ $data['checked_policy_numbers'] = array_column(array_filter($invoice_items, fn($ii) => isset($ii['is_active']) && $ii['is_active'] == 1),'policy_no');
+
+ $data['invoice_number']= $invoice['invoice_no'];
+ $data['type'] = $type;
+ $data['payout_status'] = $invoice['payout_status'] ;
+ // dd($data);
+ return $this->loadLayout('invoice_policy_mapping', $data);
+
+ }
+
+
+ }
+
+ //... Payout-invoice Mapping - Save/update/soft Delete/Hard Delete Data
+ public function saveInvoice()
+ {
+ $json = $this->request->getJSON(true);
+ // print_rr($json);die();
+
+ if (!$json) {
+ return $this->response->setJSON(['error' => 'Invalid JSON','message' => 'Invalid JSON received.'])->setStatusCode(400);
+ }
+
+ $id = $json['invoice_id'] ?? null;
+ try {
+
+ //... ADD Part
+ if (empty($id)) {
+ $exists = $this->invoiceModel
+ ->where('invoice_no', $json['invoice_no'])
+ ->first();
+
+ if ($exists) {
+ $InvNum = $this->generateInvoiceNumber($json['agent_id']);
+ } else {
+ $InvNum = $json['invoice_no'];
+ }
+
+ $invoiceData = [
+ 'invoice_no' => $InvNum,
+ 'agent_id' => $json['agent_id'],
+ 'invoice_date' => $json['invoice_date'],
+ 'invoice_amount' => $json['invoice_amount'],
+ 'payout_status' => 1
+ ];
+
+ $invoiceId = $this->invoiceModel->insert($invoiceData);
+
+ foreach ($json['policies'] as $p) {
+ $this->invoiceItemModel->insert([
+ 'invoice_id' => $invoiceId,
+ 'policy_id' => $p['partner_policy_id'],
+ 'policy_no' => $p['policy_no'],
+ 'commission_amount' => $p['commission_amount'],
+ 'is_active' => 1
+ ]);
+ }
+
+ $message = "Invoice created successfully.\nInvoice No: " . $json['invoice_no'];
+
+ }
+
+ // ... EDIT part
+ if (!empty($id)) {
+
+ $invoiceId = $id;
+
+ $invoiceData = [
+ 'invoice_no' => $json['invoice_no'],
+ 'agent_id' => $json['agent_id'],
+ 'invoice_date' => $json['invoice_date'],
+ 'invoice_amount' => $json['invoice_amount'],
+ ];
+
+ $this->invoiceModel->update($invoiceId, $invoiceData);
+
+ //... Fetch existing invoice item rows
+ $existingItems = $this->invoiceItemModel
+ ->where('invoice_id', $invoiceId)
+ ->findAll();
+
+ //... Create map by policy_no
+ $existingMap = [];
+ foreach ($existingItems as $item) {
+ $existingMap[$item['policy_no']] = $item;
+ }
+
+ $newPolicyNos = [];
+
+ //... Loop new JSON policies
+ foreach ($json['policies'] as $p) {
+
+ $newPolicyNos[] = $p['policy_no'];
+
+ if (isset($existingMap[$p['policy_no']])) {
+
+ //... Update existing item
+ $this->invoiceItemModel
+ ->where('id', $existingMap[$p['policy_no']]['id'])
+ ->set([
+ 'commission_amount' => $p['commission_amount'],
+ 'is_active' => 1
+ ])
+ ->update();
+
+ } else {
+
+ //... Insert new item
+ $this->invoiceItemModel->insert([
+ 'invoice_id' => $invoiceId,
+ 'policy_id' => $p['policy_id'],
+ 'policy_no' => $p['policy_no'],
+ 'commission_amount' => $p['commission_amount'],
+ 'is_active' => 1,
+ ]);
+ }
+ }
+
+ //... Delete items removed in JSON (hard delete)
+ foreach ($existingItems as $old) {
+ if (!in_array($old['policy_no'], $newPolicyNos)) {
+ $this->invoiceItemModel
+ ->where('id', $old['id'])
+ ->delete();
+ }
+ }
+ //... Delete items removed in JSON (soft delete REF : SVM )
+ // foreach ($existingItems as $old) {
+ // if (!in_array($old['policy_no'], $newPolicyNos)) {
+ // $this->invoiceItemModel
+ // ->where('id', $old['id'])
+ // ->set(['is_active' => 0])
+ // ->update();
+ // }
+ // }
+
+ $message = "Invoice updated successfully.";
+
+ }
+
+ return $this->response->setJSON([
+ 'status' => 'success',
+ 'message' => $message,
+ 'invoice_id' => $invoiceId
+ ]);
+
+ } catch (\Exception $e) {
+
+ return $this->response->setJSON([
+ 'status' => 'error',
+ 'message' => 'Unexpected error occurred: ' . $e->getMessage()
+ ]);
+ }
+ }
+
+
+
+ //... Payout-invoice Mapping - Invoice number is auto-generated only for the Add mode.
+ // Note New Pattern : INV/AG001/20251101/xx (REF:SVM)
+ public function generateInvoiceNumberAjax($agentId)
+ {
+ if (!$agentId) {
+ return $this->response->setJSON([
+ 'status' => 'error',
+ 'message' => 'Agent ID missing'
+ ]);
+ }
+
+ $invoiceNo = $this->generateInvoiceNumber($agentId);
+
+ return $this->response->setJSON([
+ 'status' => 'success',
+ 'invoice_no' => $invoiceNo
+ ]);
+ }
+
+ //... Payout-invoice Mapping - Invoice number is auto-generated only for the Add mode.
+ // Note New Pattern : INV/AG001/20251101/xx (REF:SVM)
+ private function generateInvoiceNumber($agentId)
+ {
+ $agent = $this->invoiceModel->agentListById($agentId);
+ $agentCode = $agent["agent_code"];
+
+ $today = date("Ymd");
+ $likePattern = "INV/$agentCode/$today/%";
+
+ $count = $this->invoiceModel
+ ->like("invoice_no", $likePattern)
+ ->countAllResults();
+
+ $nextNumber = $count + 1;
+
+ return "INV/$agentCode/$today/$nextNumber";
+ }
+
+ // private function generateInvoiceNumber()
+ // {
+ // $year = date('Y');
+ // $month = date('m');
+
+ // do {
+ // // random 3-digit number
+ // $random = str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
+ // $invoiceNo = "INV{$year}{$month}{$random}";
+
+ // // check main invoice table
+ // $existsMain = $this->invoiceModel
+ // ->where('invoice_no', $invoiceNo)
+ // ->first();
+
+ // // check partner invoice table
+ // $existsPartner = $this->invoiceModel
+ // ->where('invoice_no', $invoiceNo)
+ // ->first();
+
+ // } while ($existsMain || $existsPartner); // regenerate if duplicate found
+
+ // return $invoiceNo;
+ // }
+
+ //... Payout-invoice Mapping Audit History Based on "Adjustment" value (REF: KV,SVM)
+ public function auditHistory()
+ {
+
+
+ $iid = $this->request->getGet('id');
+
+ $details['invoice'] = $this->auditHistory
+ ->select('auditing_history.*,partner_invoice.invoice_no, user_profiles.first_name as created_name')
+ ->join('user_profiles', 'user_profiles.id = auditing_history.created_by', 'left')
+ ->join('partner_invoice', 'partner_invoice.id = auditing_history.pk', 'left')
+ ->where('auditing_history.table_name', 'partner_invoice') // ok
+ ->where('auditing_history.pk', $iid)
+ ->orderBy('auditing_history.created_at', 'desc')
+ ->get()
+ ->getResultArray();
+
+ $details['invoice_child'] = $this->auditHistory
+ ->select('auditing_history.*,partner_invoice.invoice_no, user_profiles.first_name as created_name,partner_invoice_items.policy_no')
+ ->join('user_profiles', 'user_profiles.id = auditing_history.created_by', 'left')
+ ->join('partner_invoice_items', 'partner_invoice_items.id = auditing_history.pk', 'left')
+ ->join('partner_invoice', 'partner_invoice.id = partner_invoice_items.invoice_id', 'left')
+ ->where('auditing_history.table_name', 'partner_invoice_items') // FIXED
+ ->where('partner_invoice.id', $iid)
+ ->orderBy('auditing_history.created_at', 'desc')
+ ->get()
+ ->getResultArray();
+
+ return $this->response->setJSON([
+ 'status' => 'success',
+ 'data' => $details
+ ]);
+
+ }
+
+ // ****************************************************************************************************************************************************************
+
+ public function preview($invoiceId = null)
+ {
+ $invoiceId = $this->request->getGet('invoice_id');
+
+ // Get invoice data from database
+ $invoiceData = $this->getInvoiceData($invoiceId);
+
+ if (empty($invoiceData)) {
+ return $this->respond([
+ 'status' => false,
+ 'code' => 404,
+ 'data' => '',
+ 'message' => 'Invoice not found'
+ ], 200);
+ }
+
+ // Load view with data
+ $html = view('invoice_template_2', $invoiceData);
+ // echo $html; die;
+
+ return $this->respond([
+ 'status' => true,
+ 'code' => 200,
+ 'data' => $html
+ ], 200);
+ }
+
+ public function downloadPdf($invoiceId = null, $type = 0)
+ {
+ // Get invoice data from database
+ $invoiceData = $this->getInvoiceData($invoiceId);
+
+ if (empty($invoiceData)) {
+ return redirect()->back()->with('error', 'Invoice not found');
+ }
+
+ // Generate HTML
+ $html = view('invoice_template_2', $invoiceData);
+
+ // Configure Dompdf
+ $options = new Options();
+ $options->set('isHtml5ParserEnabled', true);
+ $options->set('isPhpEnabled', true);
+ $options->set('isRemoteEnabled', true);
+ $options->set('defaultFont', 'Arial');
+ $options->set('chroot', FCPATH);
+
+ // Initialize Dompdf
+ $dompdf = new Dompdf($options);
+
+ // Load HTML
+ $dompdf->loadHtml($html);
+
+ // Set paper size and orientation
+ $dompdf->setPaper('A4', 'portrait');
+
+ // Render PDF
+ $dompdf->render();
+
+ // Generate filename
+ $filename = 'Invoice_' . $invoiceData['invoice_no'] . '_' . date('Ymd') . '.pdf';
+
+ if($type == 0){
+ // Download PDF
+ return $this->response
+ ->setHeader('Content-Type', 'application/pdf')
+ ->setHeader('Content-Disposition', 'attachment; filename="' . $filename . '"')
+ ->setBody($dompdf->output());
+ }else{
+ // View PDF
+ return $this->response
+ ->setHeader('Content-Type', 'application/pdf')
+ ->setHeader('Content-Disposition', 'inline; filename="' . $filename . '"')
+ ->setBody($dompdf->output());
+ }
+
+
+ }
+
+ private function getInvoiceData($invoiceId)
+ {
+ $invoice_data = $this->invoiceModel
+ ->select('
+
+ partner_invoice.*,
+
+ pa.name as agent_name,
+ pa.email as agent_email,
+ pa.mobile as agent_mobile,
+ pa.address as agent_address,
+ pa.agent_code,
+ pa.certificate_file_name,
+ pa.commission_retain
+ ')
+ ->join('partner_agent pa', 'partner_invoice.agent_id = pa.id')
+ ->where('partner_invoice.is_active', 1)
+ ->where('partner_invoice.id', $invoiceId)
+ ->first();
+
+ return $invoice_data;
+ }
+
}
diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php
index 8d24f27b..5058dea6 100644
--- a/app/Controllers/PolicyTransactionController.php
+++ b/app/Controllers/PolicyTransactionController.php
@@ -37,6 +37,8 @@
use App\Helpers\MailHelper;
use App\Helpers\ExcelSanitizeHelper;
use App\Models\NhanceBranchModel;
+ use App\Models\BDSDumpModel;
+ use App\Models\VehicleModel;
use Exception;
class PolicyTransactionController extends BaseController
@@ -71,6 +73,10 @@
protected $coShareStmtDetailsModel;
protected $BdsPlacementModel;
protected $nhanceBranchModel;
+ protected $bdsDumpModel;
+ protected $vehicleModel;
+ protected $bds_bulk_upload_excel_file_column;
+
public function __construct()
{
@@ -103,12 +109,439 @@
$this->coShareStmtDetailsModel = new COShareStmtDetailsModel();
$this->BdsPlacementModel = new BdsPlacementModel();
$this->nhanceBranchModel = new NhanceBranchModel();
+ $this->bdsDumpModel = new BDSDumpModel();
+ $this->vehicleModel = new VehicleModel();
$this->invoiceStatus = [
'pending' => 'Pending',
'generated' => 'Generated',
'sent' => 'Sent',
'payment_received' => 'Payment
Received',
];
+
+ $this->bds_bulk_upload_excel_file_column = [
+
+ 'sno' => [
+ 'col_idx' => 0,
+ 'col_cell_name' => 'A',
+ 'col_name' => 'S.No.',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'nhance_branch' => [
+ 'col_idx' => 1,
+ 'col_cell_name' => 'B',
+ 'col_name' => 'Nhance Branch',
+ 'is_mandatory' => true,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_nhance_branch',
+ 'params' => ['row', 'nhance_branch_data']
+ ],
+
+ 'vehicle_no' => [
+ 'col_idx' => 2,
+ 'col_cell_name' => 'C',
+ 'col_name' => 'Vehicle No',
+ 'is_mandatory' => true,
+ 'data_type' => 'vehicle',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_rto_data',
+ 'params' => ['row', 'rto_master']
+ ],
+
+ 'vehicle_type' => [
+ 'col_idx' => 3,
+ 'col_cell_name' => 'D',
+ 'col_name' => 'Vehicle Type',
+ 'is_mandatory' => true,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_vehicle_type',
+ 'params' => ['row', 'vehicle_type']
+ ],
+
+ 'policy_no' => [
+ 'col_idx' => 4,
+ 'col_cell_name' => 'E',
+ 'col_name' => 'Policy No',
+ 'is_mandatory' => true,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_policy_no',
+ 'params' => ['row', 'pt_data']
+ ],
+
+ 'insured_name' => [
+ 'col_idx' => 5,
+ 'col_cell_name' => 'F',
+ 'col_name' => 'Insured Name',
+ 'is_mandatory' => true,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'insured_email' => [
+ 'col_idx' => 6,
+ 'col_cell_name' => 'G',
+ 'col_name' => 'Insured Email',
+ 'is_mandatory' => true,
+ 'data_type' => 'email',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'insurer' => [
+ 'col_idx' => 7,
+ 'col_cell_name' => 'H',
+ 'col_name' => 'Insurer',
+ 'is_mandatory' => true,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_insurer_exist',
+ 'params' => ['row', 'insurer_data']
+ ],
+
+ 'insurer_branch' => [
+ 'col_idx' => 8,
+ 'col_cell_name' => 'I',
+ 'col_name' => 'Insurer Branch',
+ 'is_mandatory' => true,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_insurer_branch_exist',
+ 'params' => ['row', 'insurer_branch_data', 'insurers']
+ ],
+
+ 'policy_issue_date' => [
+ 'col_idx' => 9,
+ 'col_cell_name' => 'J',
+ 'col_name' => 'Policy Issue Date',
+ 'is_mandatory' => true,
+ 'data_type' => 'date',
+ 'format' => 'd/M/Y',
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'policy_start_date' => [
+ 'col_idx' => 10,
+ 'col_cell_name' => 'K',
+ 'col_name' => 'Policy Start Date',
+ 'is_mandatory' => true,
+ 'data_type' => 'date',
+ 'format' => 'd/M/Y',
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'policy_end_date' => [
+ 'col_idx' => 11,
+ 'col_cell_name' => 'L',
+ 'col_name' => 'Policy End Date',
+ 'is_mandatory' => true,
+ 'data_type' => 'date',
+ 'format' => 'd/M/Y',
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'revenue_type' => [
+ 'col_idx' => 12,
+ 'col_cell_name' => 'M',
+ 'col_name' => 'Revenue Type',
+ 'is_mandatory' => true,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => ['NA', 'EA', 'EANR'],
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'sales_generated_by' => [
+ 'col_idx' => 13,
+ 'col_cell_name' => 'N',
+ 'col_name' => 'Sales Generated By',
+ 'is_mandatory' => true,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_user_exist',
+ 'params' => ['row', 'col_key', 'user_data']
+ ],
+
+ 'serviced_by' => [
+ 'col_idx' => 14,
+ 'col_cell_name' => 'O',
+ 'col_name' => 'Serviced By',
+ 'is_mandatory' => true,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_user_exist',
+ 'params' => ['row', 'col_key', 'user_data']
+ ],
+
+ 'agent_code' => [
+ 'col_idx' => 15,
+ 'col_cell_name' => 'P',
+ 'col_name' => 'Agent Code',
+ 'is_mandatory' => true,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_agent_exist',
+ 'params' => ['row', 'agent_data']
+ ],
+
+ 'base_premium' => [
+ 'col_idx' => 16,
+ 'col_cell_name' => 'Q',
+ 'col_name' => 'Base Premium',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'non_commission_premium_amount' => [
+ 'col_idx' => 17,
+ 'col_cell_name' => 'R',
+ 'col_name' => 'Non commission permium Amount',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'tp_premium' => [
+ 'col_idx' => 18,
+ 'col_cell_name' => 'S',
+ 'col_name' => 'TP Premium',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'igst' => [
+ 'col_idx' => 19,
+ 'col_cell_name' => 'T',
+ 'col_name' => 'IGST',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'cgst' => [
+ 'col_idx' => 20,
+ 'col_cell_name' => 'U',
+ 'col_name' => 'CGST',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'sgst' => [
+ 'col_idx' => 21,
+ 'col_cell_name' => 'V',
+ 'col_name' => 'SGST',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'stamp_duty' => [
+ 'col_idx' => 22,
+ 'col_cell_name' => 'W',
+ 'col_name' => 'Stamp Duty',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'total' => [
+ 'col_idx' => 23,
+ 'col_cell_name' => 'X',
+ 'col_name' => 'Total',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'agreed_amount' => [
+ 'col_idx' => 24,
+ 'col_cell_name' => 'Y',
+ 'col_name' => 'Agreed Amount',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'agreed_bp_percentage' => [
+ 'col_idx' => 25,
+ 'col_cell_name' => 'Z',
+ 'col_name' => 'Agreed BP Percentage',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'agreed_tp_percentage' => [
+ 'col_idx' => 26,
+ 'col_cell_name' => 'AA',
+ 'col_name' => 'Agreed TP Percentage',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'actual_bp_amount' => [
+ 'col_idx' => 27,
+ 'col_cell_name' => 'AB',
+ 'col_name' => 'Actual BP Amount',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'actual_tp_amount' => [
+ 'col_idx' => 28,
+ 'col_cell_name' => 'AC',
+ 'col_name' => 'Actual TP Amount',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'actual_bp_percentage' => [
+ 'col_idx' => 29,
+ 'col_cell_name' => 'AD',
+ 'col_name' => 'Actual BP Percentage',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'actual_tp_percentage' => [
+ 'col_idx' => 30,
+ 'col_cell_name' => 'AE',
+ 'col_name' => 'Actual TP Percentage',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'actual_bp_brokerage_amount' => [
+ 'col_idx' => 31,
+ 'col_cell_name' => 'AF',
+ 'col_name' => 'Actual BP Brokerage Amount',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'actual_tp_brokerage_amount' => [
+ 'col_idx' => 32,
+ 'col_cell_name' => 'AG',
+ 'col_name' => 'Actual TP Brokerage Amount',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'expected_amount' => [
+ 'col_idx' => 33,
+ 'col_cell_name' => 'AH',
+ 'col_name' => 'Expected Amount',
+ 'is_mandatory' => true,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ 'rewards' => [
+ 'col_idx' => 34,
+ 'col_cell_name' => 'AI',
+ 'col_name' => 'Rewards',
+ 'is_mandatory' => false,
+ 'data_type' => '',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null,
+ 'params' => null
+ ],
+
+ ];
+
}
// Policy Transaction Inception
@@ -244,6 +677,12 @@
->where('user_profiles.is_active', 1)
->findAll();
+ // Fetch Partner Agent
+ $data['partner_agent'] = db_connect()->table('partner_agent')
+ ->where('is_active', 1)
+ ->get()
+ ->getResultArray();
+
// Fetch ACM
$data['ACM'] = $this->userModel
->where('role', 3) // Assuming `role` is in `user_profiles`
@@ -496,12 +935,18 @@
$cop_amt = $data['co_premium'][$index] ?? 0;
}
+ if(isset($data['calc_policy_issue_date'][$index])){
+ $data['calc_policy_issue_date'][$index] = change_date_format($data['calc_policy_issue_date'][$index]);
+ }
+
+ $co_share_type_value = (($data['co_share'] ?? 0) == 1) ? ($data['co_share_type'][$index] ?? 1) : 1;
+
// Prepare each co-share detail entry
$coShareDetails[] = [
'pt_id' => $pt_id,
'insurer_id' => $insurer_id ?? 0,
'insurer_branch_id' => $insurer_branch_id ?? 0,
- 'co_share_type' => $data['co_share_type'][$index] ?? 1,
+ 'co_share_type' => $co_share_type_value,
'co_share_per' => $data['co_share_per'][$index] ?? 0,
'bp_amt' => $data['base_premium'][$index] ?? 0,
'bp_gst_amt' => $data['gst_amount'][$index] ?? 0,
@@ -539,6 +984,7 @@
'id' => $data['co_share_id'][$index] ?? null, // Assuming this is the ID to identify existing records
'follower_policy_no' => $data['follower_policy_no'][$index] ?? null,
'non_comm_per_amt' => $data['non_comm_per_amt'][$index] ?? null,
+ 'pt_policy_issue_date' => $data['calc_policy_issue_date'][$index] ?? null,
];
}
@@ -1001,7 +1447,9 @@
co_share_id = pt_co_share_details.id
AND is_active = 1
- ) AS actual_tep_brokerage_amount
+ ) AS actual_tep_brokerage_amount,
+
+ DATE_FORMAT(pt_policy_issue_date, '%d/%m/%Y') AS pt_policy_issue_date
")
->where('pt_id', $id)
@@ -1590,7 +2038,9 @@
co_share_id = pt_co_share_details.id
AND is_active = 1
- ) AS actual_tep_brokerage_amount
+ ) AS actual_tep_brokerage_amount,
+
+ DATE_FORMAT(pt_policy_issue_date, '%d/%m/%Y') AS pt_policy_issue_date
")
->where('pt_id', $id)
@@ -2811,20 +3261,6 @@
$this->loadLayout('dms_search', $data);
}
- public function payouts()
- {
-
- $data['tab_name'] = 'Payouts';
- $data['page_name'] = 'Payouts';
- $data['payouts'] = [];
- $data['agents'] = [ 1 => "Agent 1", 2 => "Agent 2", 3 => "Agent 3", 4 => "Agent 4", 5 => "Agent 5", 6 => "Agent 6", 7 => "Agent 7", 8 => "Agent 8"];
- $data['brokers'] = [];
-
- if ($this->request->is('post')) {}
- if ($this->request->is('get')) {}
-
- $this->loadLayout('policy_transaction_payouts', $data);
- }
//---------------------------------------------------------------------------------------------------
public function getCoShareStatementDetails($pt_id)
@@ -3210,117 +3646,926 @@
return [$policyList, $policyListByClient];
}
+ public function reportBDSNew()
+ {
+ // 🧭 Basic Page Info
+ $data['tab_name'] = 'BDS Report';
+ $data['page_name'] = 'BDS Report';
- public function reportBDSNew()
- {
- // 🧭 Basic Page Info
- $data['tab_name'] = 'BDS Report';
- $data['page_name'] = 'BDS Report';
+ // 📋 Dropdown Data
+ $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
+ $data['client_type'] = [1 => 'Group', 2 => 'Individual'];
+ $data['issuing_type'] = [1 => 'Fresh', 2 => 'Renewal', 3 => 'Roll Over'];
+ $data['policy_status'] = [
+ 'pending' => 'Pending',
+ 'exported_to_insurer' => 'Exported to Insurer',
+ 'imported_from_insurer'=> 'Imported from Insurer',
+ 'exported_to_tpa' => 'Exported to TPA',
+ 'imported_from_tpa' => 'Imported from TPA',
+ 'completed' => 'Completed'
+ ];
+ $data['invoice_status_array'] = [
+ 'yet_to_generate' => 'Yet to Generate',
+ 'generated' => 'Generated',
+ 'send' => 'Send',
+ 'recived' => 'Recived',
+ ];
+ $data['date_type'] = [
+ 'policy_issue_date' => 'Policy Issue Date',
+ 'policy_start_date' => 'Policy Start Date',
+ 'policy_end_date' => 'Policy End Date',
+ 'data_received_date' => 'Data Received Date',
+ 'closure_date' => 'Closure Date',
+ 'statement_month' => 'Statement Month',
+ ];
- // 📋 Dropdown Data
- $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
- $data['client_type'] = [1 => 'Group', 2 => 'Individual'];
- $data['issuing_type'] = [1 => 'Fresh', 2 => 'Renewal', 3 => 'Roll Over'];
- $data['policy_status'] = [
- 'pending' => 'Pending',
- 'exported_to_insurer' => 'Exported to Insurer',
- 'imported_from_insurer'=> 'Imported from Insurer',
- 'exported_to_tpa' => 'Exported to TPA',
- 'imported_from_tpa' => 'Imported from TPA',
- 'completed' => 'Completed'
- ];
- $data['invoice_status_array'] = [
- 'yet_to_generate' => 'Yet to Generate',
- 'generated' => 'Generated',
- 'send' => 'Send',
- 'recived' => 'Recived',
- ];
- $data['date_type'] = [
- 'policy_issue_date' => 'Policy Issue Date',
- 'policy_start_date' => 'Policy Start Date',
- 'policy_end_date' => 'Policy End Date',
- 'data_received_date' => 'Data Received Date',
- 'closure_date' => 'Closure Date',
- 'statement_month' => 'Statement Month',
- ];
+ // 🏢 Fetch Active Data
+ $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll();
+ $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll();
+ $data['clients'] = $this->clientModel->where('is_active', 1)->findAll();
+ $data['users'] = $this->userModel->where('is_active', 1)->findAll();
+ $data['policy_count'] = $this->policyTransactionModel->where('is_active', 1)->countAllResults();
- // 🏢 Fetch Active Data
- $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll();
- $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll();
- $data['clients'] = $this->clientModel->where('is_active', 1)->findAll();
- $data['users'] = $this->userModel->where('is_active', 1)->findAll();
- $data['policy_count'] = $this->policyTransactionModel->where('is_active', 1)->countAllResults();
+ // 🕐 Filters
+ $start_date = $this->request->getGet('start_date');
+ $end_date = $this->request->getGet('end_date');
+ $client_id = $this->request->getGet('client_id');
+ $insurer_id = $this->request->getGet('insurer_id');
+ $policy_type_id = $this->request->getGet('policy_type_id');
+ $date_type = $this->request->getGet('date_type');
+ $issuer = $this->request->getGet('issuer');
+ $client_branch_id = $this->request->getGet('client_branch_id');
+ $insurer_branch_id = $this->request->getGet('insurer_branch_id');
+ $client_policy_id = $this->request->getGet('client_policy_id');
+ $user_id = $this->request->getGet('user_id');
- // 🕐 Filters
- $start_date = $this->request->getGet('start_date');
- $end_date = $this->request->getGet('end_date');
- $client_id = $this->request->getGet('client_id');
- $insurer_id = $this->request->getGet('insurer_id');
- $policy_type_id = $this->request->getGet('policy_type_id');
- $date_type = $this->request->getGet('date_type');
- $issuer = $this->request->getGet('issuer');
- $client_branch_id = $this->request->getGet('client_branch_id');
- $insurer_branch_id = $this->request->getGet('insurer_branch_id');
- $client_policy_id = $this->request->getGet('client_policy_id');
- $user_id = $this->request->getGet('user_id');
+ // Handle statement month range
+ if ($date_type == 'statement_month') {
+ $start_date = (string) date('Y-m-01', strtotime($start_date));
+ $end_date = (string) date('Y-m-31', strtotime($end_date));
+ }
- // Handle statement month range
- if ($date_type == 'statement_month') {
- $start_date = (string) date('Y-m-01', strtotime($start_date));
- $end_date = (string) date('Y-m-31', strtotime($end_date));
+ // Ensure default values
+ $start_date = $start_date ?: 0;
+ $end_date = $end_date ?: 0;
+ $client_id = $client_id ?: 0;
+ $insurer_id = $insurer_id ?: 0;
+ $policy_type_id = $policy_type_id ?: 0;
+ $date_type = $date_type ?: 0;
+ $issuer = $issuer ?: 0;
+ $client_branch_id = $client_branch_id ?: 0;
+ $insurer_branch_id = $insurer_branch_id ?: 0;
+ $client_policy_id = $client_policy_id ?: 0;
+ $user_id = $user_id ?: 0;
+
+ // 🧾 Handle POST requests (Dashboard filters)
+ if ($this->request->is('post')) {
+ $isFromDashboard = $this->request->getPost('is_dashboard');
+
+ if (!empty($isFromDashboard) && $isFromDashboard == 1) {
+ $ids = array_filter(explode(',', $this->request->getPost('ids')));
+
+ if (!empty($ids)) {
+ $idsStr = implode(',', array_map('intval', $ids)); // sanitize IDs
+ $where = "policy_transaction.id IN ($idsStr)";
+ } else {
+ $where = []; // No valid IDs
+ }
+ }
+ }
+
+ // 📊 Fetch report data
+ $data['report_list'] = $this->policyTransactionModel->reportBDSNew(
+ $start_date,
+ $end_date,
+ $client_id,
+ $insurer_id,
+ $policy_type_id,
+ $date_type,
+ $issuer,
+ $client_branch_id,
+ $insurer_branch_id,
+ $client_policy_id,
+ $user_id,
+ $where ?? ''
+ );
+
+ $data['list_new'] = true;
+
+ // 🧩 Load View
+ $this->loadLayout('report_bds_filter', $data);
}
- // Ensure default values
- $start_date = $start_date ?: 0;
- $end_date = $end_date ?: 0;
- $client_id = $client_id ?: 0;
- $insurer_id = $insurer_id ?: 0;
- $policy_type_id = $policy_type_id ?: 0;
- $date_type = $date_type ?: 0;
- $issuer = $issuer ?: 0;
- $client_branch_id = $client_branch_id ?: 0;
- $insurer_branch_id = $insurer_branch_id ?: 0;
- $client_policy_id = $client_policy_id ?: 0;
- $user_id = $user_id ?: 0;
+ // ------------ BDS BULK MOTER POLICY UPLOAD -----------------------------------------------------------------------------------------------
- // 🧾 Handle POST requests (Dashboard filters)
- if ($this->request->is('post')) {
- $isFromDashboard = $this->request->getPost('is_dashboard');
+ public function policyBulkUpload()
+ {
+ $data['page_name'] = "BDS Bulk File Upload";
+ $data['tab_name'] = "BDS File Upload";
- if (!empty($isFromDashboard) && $isFromDashboard == 1) {
- $ids = array_filter(explode(',', $this->request->getPost('ids')));
+ // $response = $this->insertBulkBdsData(['file_id' => 17]);
+ // dd($response);
- if (!empty($ids)) {
- $idsStr = implode(',', array_map('intval', $ids)); // sanitize IDs
- $where = "policy_transaction.id IN ($idsStr)";
+
+ if ($this->request->is('get')) {
+
+ $data['bds_dump_file_data'] = $this->bdsDumpModel
+ ->select('
+ bds_dump_files.id as file_id,
+ bds_dump_files.file_name,
+ bds_dump_files.status,
+ bds_dump_files.created_at,
+ up.first_name as user_name
+ ')
+ ->join('user_profiles as up', 'bds_dump_files.created_by = up.id', 'left')
+ ->where('bds_dump_files.is_active', 1)
+ ->orderBy('bds_dump_files.id', 'desc')
+ ->findAll();
+
+ return $this->loadLayout('bds_dump_file_list', $data);
+ } else {
+
+ $filename = '';
+ $fileSize = '';
+
+ //validate uploaded file
+ $validated = $this->validate([
+ 'bds_dump_list' => [
+ 'uploaded[bds_dump_list]',
+ 'mime_in[bds_dump_list,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.oasis.opendocument.spreadsheet]',
+ 'max_size[bds_dump_list,16384]',
+ ],
+ ]);
+
+ if ($validated) {
+ $avatar = $this->request->getFile('bds_dump_list');
+ if (!$avatar) {
+ $this->myLogger->logme("error", 'File not found');
+ return $this->respond(['status' => false, 'code' => 400, 'message' => 'File not found'], 400);
+ }
+
+ $is_moved = $avatar->move(WRITEPATH . 'uploads/bds_dump_excel/');
+
+ if ($is_moved) {
+ $filename = $avatar->getName();
+ $fileSize = $avatar->getSize(); // File size in bytes
+ $fileSize = $fileSize / (1024 * 1024); // Convert to MB
+
+ $this->myLogger->logme("error", 'File move successful');
+ } else {
+ $this->myLogger->logme("error", 'File move failed');
+ return $this->respond(['status' => false, 'code' => 500, 'message' => 'File move failed'], 500);
+ }
} else {
- $where = []; // No valid IDs
+ $this->myLogger->logme("error", 'Upload failed Invalid file');
+ return $this->respond(['status' => false, 'code' => 404, 'message' => 'Invalid file'], 404);
}
+
+
+ $status = 'inprogress';
+ $insert_data = [
+ 'file_name' => $filename,
+ 'status' => $status
+ ];
+
+ $file_id = $this->bdsDumpModel->insert($insert_data);
+ $this->myLogger->logme("error", 'claim_dumb_file_id : {file_id}, uploaded success', ['file_id' => $file_id]);
+
+ //after file upload success than call the file formate validation
+ // $response = $this->bdsDumpExcelFileFormatValidation(["file_id" => $file_id]);
+ $r = Jobs::addJob(['job_name' => 'bdsDumpExcelFileFormatValidation', 'payload' => ['file_id' => $file_id]]);
+
+ return $this->respond(['status' => true, 'code' => 200, 'message' => 'File uploaded successfully. File being validated'], 200);
}
}
- // 📊 Fetch report data
- $data['report_list'] = $this->policyTransactionModel->reportBDSNew(
- $start_date,
- $end_date,
- $client_id,
- $insurer_id,
- $policy_type_id,
- $date_type,
- $issuer,
- $client_branch_id,
- $insurer_branch_id,
- $client_policy_id,
- $user_id,
- $where ?? ''
- );
+ public function downloadBDSDumpFile($file_id)
+ {
+ // $actionType = $this->request->getGet();
+ $file_data = $this->bdsDumpModel->where('id', $file_id)->first();
+ $fileName = $file_data['file_name'];
- $data['list_new'] = true;
+ $filePath = WRITEPATH . '/uploads/bds_dump_excel/' . $fileName;
- // 🧩 Load View
- $this->loadLayout('report_bds_filter', $data);
- }
+ try {
+
+ // Check if the file exists
+ if (file_exists($filePath)) {
+ // Set the appropriate MIME type
+ $mimeType = mime_content_type($filePath);
+
+ // Send the file to the client for download
+ return $this->response->download($filePath, null, $mimeType);
+ } else {
+
+ $data['message'] = 'The Physical File Not Found';
+ echo view('errors/404', $data);
+ }
+ } catch (\Exception $e) {
+ // Handle any exceptions
+ $errorMessage = $e->getMessage();
+ $this->myLogger->logme('error', $errorMessage);
+ // You can return an error response here
+ echo $errorMessage;
+ }
+ }
+
+ public function bdsDumpExcelFileFormatValidation($params)
+ {
+ helper('excel_util_helper');
+ $file_id = $params['file_id'];
+ $file = $this->bdsDumpModel->where("id", $file_id)->first();
+
+ $return = [];
+ if (empty($file)) {
+ return array('status' => false, 'message' => 'File not found in Database');
+ }
+
+ $file_name_with_path = WRITEPATH . "/uploads/bds_dump_excel/" . $file['file_name'];
+
+ //check physical file exist
+ if (!file_exists($file_name_with_path)) {
+ $message = "Physcial file not found";
+ $this->myLogger->logme('error', ($message . ' for file id : ' . $file_id));
+ $this->bdsDumpModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+ return array('error_summary' => [5], 'error_data' => $message);
+ }
+
+ // get the BDS dump excel colums
+ $columns_to_check = $this->bds_bulk_upload_excel_file_column;
+ $keys = array_keys($columns_to_check);
+ $allowedHighestColumn = end($columns_to_check);
+
+ // Read the excel file
+ $excel_data = $this->extractExcelData($file['file_name'], $allowedHighestColumn['col_cell_name']);
+ $excel_columns = ($excel_data[0]);
+ // echo '
'; var_dump($excel_columns);
+ //check no of columns in excel
+ $total_defined_columns = count($columns_to_check);
+ $excel_columns_count = count($excel_columns);
+
+ if($total_defined_columns != $excel_columns_count)
+ {
+ //columns count mismatch
+ $message = "File columns count mismatch. Expected - $total_defined_columns and received - $excel_columns_count";
+ $this->myLogger->logme('error',($message . ' for file id ' . $file_id));
+ $this->bdsDumpModel->where('id', $file_id)->set(['status' => 'failed','reason' => json_encode(['error_summary' => array_count_values([5]),'error_data' => $message])])->update();
+ return array('error_summary' => [5], 'error_data' => $message);
+ }
+
+ //check columns order in excel
+ $column_count_res = check_columns_name($columns_to_check, $excel_columns);
+
+ if(isset($column_count_res) && count($column_count_res))
+ {
+ //columns count mismatch
+ $message = implode("\n", $column_count_res);
+ $this->myLogger->logme('error',($message . ' for file id ' . $file_id));
+ $this->bdsDumpModel->where('id', $file_id)->set(['status' => 'failed','reason' => json_encode(['error_summary' => array_count_values([6]), 'error_data' => $message])])->update();
+ return array('error_summary' => [6], 'error_data' => $message);
+ }
+
+ //Store the error data by this structure
+ $result = ['error_type' => 1, 'error_summary' => [], 'error_data' => []];
+
+ $insurer_data = $this->insurerModel->where('is_active', 1)->findAll();
+ $insurer_branch_data = $this->insurerBranchModel->where('is_active', 1)->findAll();
+ $pt_data = $this->policyTransactionModel->where('is_active', 1)->findAll();
+ $user_data = $this->userModel->where('is_active', 1)->findAll();
+ $agent_data = db_connect()->table('partner_agent')->where('is_active', 1)->get()->getResultArray();
+ $rto_master = db_connect()->table('rto_master')->where('is_active', 1)->get()->getResultArray();
+ $vehicle_type = db_connect()->table('vehicle_type')->where('is_active', 1)->get()->getResultArray();
+ $nhance_branch_data = db_connect()->table('nhance_branch')->where('is_active', 1)->get()->getResultArray();
+
+
+ //remove header
+ unset($excel_data[0]);
+
+ try {
+ foreach ($excel_data as $row_key => $row) {
+
+ //avoid empty rows
+ if (check_row_is_empty_or_null($row)) {
+ break;
+ }
+
+ $insurers = [];
+ foreach ($row as $col_key => $col)
+ {
+ $is_mandatory = $columns_to_check[$keys[$col_key]]['is_mandatory'];
+ $format = $columns_to_check[$keys[$col_key]]['format'];
+ $data_type = $columns_to_check[$keys[$col_key]]['data_type'];
+ $allowed_values = $columns_to_check[$keys[$col_key]]['allowed_values'];
+ $custom_function = isset($columns_to_check[$keys[$col_key]]['custom']) ? $columns_to_check[$keys[$col_key]]['custom'] : null;
+ $binding_params = isset($columns_to_check[$keys[$col_key]]['params']) ? $columns_to_check[$keys[$col_key]]['params'] : null;
+
+ $column_dispaly_name = $columns_to_check[$keys[$col_key]]['col_name'];
+ $column_index = $columns_to_check[$keys[$col_key]]['col_idx'];
+ $column_cell = $columns_to_check[$keys[$col_key]]['col_cell_name'];
+
+
+ //mandatory check
+ if(is_bool($is_mandatory) && $is_mandatory === true)
+ {
+ if($col == "" || $col == NULL)
+ {
+ array_push($result['error_summary'],1); //push error code for summary
+ $result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name
+ $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index
+ $result['error_data'][$row_key][$keys[$col_key]]['error'][] = 'Value is mandatory'; //push exact error desc
+ }
+ }
+
+ //format check
+ if(isset($format))
+ {
+ $validation = validate_excel_value($col, $data_type, $format, $allowed_values);
+ if (!$validation['status']) {
+ array_push($result['error_summary'], 2);
+
+ $result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name;
+ $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index;
+ $result['error_data'][$row_key][$keys[$col_key]]['error'][] = $validation['error'];
+ }
+ }
+
+ //allowed values check
+ if(($is_mandatory === true && isset($allowed_values) && is_array($allowed_values)) || (is_array($is_mandatory) && (isset($allowed_values) && is_array($allowed_values))))
+ {
+ if(!in_array((trim($col)),$allowed_values))
+ {
+ array_push($result['error_summary'],3);
+ $result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name
+ $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index
+ $result['error_data'][$row_key][$keys[$col_key]]['error'][] = "Value not allowed: Expected ".implode(",",$allowed_values)." and received $col";
+ }
+ }
+
+ //custom function check
+ if(isset($custom_function))
+ {
+ //convert string params into PHP variables
+ // Create an array of variables to pass custom helper funcitons
+ $param_values = [];
+ foreach($binding_params as $bkey => $bparam) { $param_values[] = ($$bparam); }
+ $res = call_user_func_array($custom_function,$param_values);
+ if($res['status'] === false) {
+ array_push($result['error_summary'],4);
+ $result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name
+ $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index
+ $result['error_data'][$row_key][$keys[$col_key]]['error'][] = $res['error'];
+ }
+
+ if($res['status'] == true && isset($res['insurer'])){
+ $insurers = $res['insurer'];
+ }
+
+ }
+
+ }//col foreach
+
+ }
+ } catch (\Exception $e) {
+ $errorDetails = [
+ 'error_message' => $e->getMessage(),
+ 'file' => $e->getFile(),
+ 'line' => $e->getLine(),
+ 'stack_trace' => $e->getTraceAsString(),
+ ];
+ $message = "Contact system admin";
+ $this->bdsDumpModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+ $this->myLogger->logme("error", 'Claim dump file format validation failed due to : ' . json_encode($errorDetails ?? []));
+ return $errorDetails;
+ }
+
+ // return $result;
+
+ if (isset($result['error_summary']) && count($result['error_summary'])) {
+ $result['error_summary'] = array_count_values($result['error_summary']);
+ $status = 'failed';
+ $failure_reason = ((json_encode($result)));
+ $this->bdsDumpModel->where('id', $file_id)->set(['status' => $status, 'reason' => $failure_reason])->update();
+ $this->myLogger->logme("error", '{file_id} uploaded failed', ['file_id' => $file_id]);
+ } else { //trigger next data validation via job queue server
+ //proceed next data level validation in JOB queue
+ $r = Jobs::addJob(['job_name' => 'insertBulkBdsData', 'payload' => ['file_id' => $file_id]]);
+ // $response = $this->insertBulkBdsData(['file_id' => $file_id]);
+ }
+
+ return $result;
+ }
+
+ public function insertBulkBdsData($params)
+ {
+ helper('excel_util_helper');
+ $file_id = $params['file_id'];
+ $file = $this->bdsDumpModel->where("id", $file_id)->first();
+
+ $return = [];
+ if (empty($file)) {
+ return array('status' => false, 'message' => 'File not found in Database');
+ }
+
+ $file_name_with_path = WRITEPATH . "/uploads/bds_dump_excel/" . $file['file_name'];
+
+ //check physical file exist
+ if (!file_exists($file_name_with_path)) {
+ $message = "Physcial file not found";
+ $this->myLogger->logme('error', ($message . ' for file id : ' . $file_id));
+ $this->bdsDumpModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+ return array('error_summary' => [5], 'error_data' => $message);
+ }
+
+ // get the BDS dump excel colums
+ $columns_to_check = $this->bds_bulk_upload_excel_file_column;
+ $keys = array_keys($columns_to_check);
+ $allowedHighestColumn = end($columns_to_check);
+
+ // Read the excel file
+ $excel_data = $this->extractExcelData($file['file_name'], $allowedHighestColumn['col_cell_name']);
+ $excel_columns = ($excel_data[0]);
+
+ //remove header
+ unset($excel_data[0]);
+ // dd($excel_data);
+
+ //Store the error data by this structure
+ $result = ['error_type' => 1, 'error_summary' => [], 'error_data' => []];
+
+ $client_data = $this->clientModel->where('is_active', 1)->where('client_type', 1)->findAll();
+ $insurer_data = $this->insurerModel->where('is_active', 1)->findAll();
+ $insurer_branch_data = $this->insurerBranchModel->where('is_active', 1)->findAll();
+ $vehicle_data = $this->vehicleModel->where('is_active', 1)->findAll();
+ $user_data = $this->userModel->where('is_active', 1)->findAll();
+ $agent_data = db_connect()->table('partner_agent')->where('is_active', 1)->get()->getResultArray();
+ $rto_master = db_connect()->table('rto_master')->where('is_active', 1)->get()->getResultArray();
+ $vehicle_type_data = db_connect()->table('vehicle_type')->where('is_active', 1)->get()->getResultArray();
+ $nhance_branch_data = db_connect()->table('nhance_branch')->where('is_active', 1)->get()->getResultArray();
+
+ try {
+
+ $pt_ids = [];
+ foreach ($excel_data as $row_key => $row) {
+
+ //avoid empty rows
+ if (check_row_is_empty_or_null($row)) {
+ break;
+ }
+
+ $vehicle_number = trim($row[2]);
+ $vehicle_type = trim($row[3]);
+ $client_name = trim($row[5]);
+ $client_email = trim($row[6]);
+
+ $insurer_short_name = trim($row[7]);
+ $insurer_branch_code = trim($row[8]);
+ $salse_generated_by = trim($row[13]);
+ $serviced_by = trim($row[14]);
+ $agent_code = trim($row[15]);
+ $nhance_branch = trim($row[1]);
+
+ $policy_no = trim($row[4]);
+ $policy_issue_date = trim($row[9]);
+ $policy_start_date = trim($row[10]);
+ $policy_end_date = trim($row[11]);
+ $revenue_type = trim($row[12]);
+
+ $base_premium = trim($row[16]);
+ $non_commission_premium_amount = trim($row[17]);
+ $tp_premium = trim($row[18]);
+ $igst = trim($row[19]);
+ $cgst = trim($row[20]);
+ $sgst = trim($row[21]);
+ $stamp_duty = trim($row[22]);
+ $total = trim($row[23]);
+ $agreed_amount = trim($row[24]);
+ $agreed_bp_percentage = trim($row[25]);
+ $agreed_tp_percentage = trim($row[26]);
+ $actual_bp_amount = trim($row[27]);
+ $actual_tp_amount = trim($row[28]);
+ $actual_bp_percentage = trim($row[29]);
+ $actual_tp_percentage = trim($row[30]);
+ $actual_bp_brokerage_amount = trim($row[31]);
+ $actual_tp_brokerage_amount = trim($row[32]);
+ $expected_amount = trim($row[33]);
+ $rewards = trim($row[34]);
+
+ $current_insurer_data = check_insurer_exist($row, $insurer_data)['insurer'] ?? null;
+ $current_insurer_branch_data = check_insurer_branch_exist($row, $insurer_branch_data, $current_insurer_data)['branch'] ?? null;
+
+ $current_nhance_branch = check_nhance_branch($row, $nhance_branch_data)['branch'] ?? null;
+ $current_agent_data = check_agent_exist($row, $agent_data)['agent'] ?? null;
+
+ $salse = check_user_exist($row, 13, $user_data)['user'] ?? null;
+ $service = check_user_exist($row, 14, $user_data)['user'] ?? null;
+
+ $gst_amt = calculate_gst_amount($row) ?? null;
+
+ // get the client and vehicle id
+ $vehicle_and_client_ids = $this->getClientAndVehicleId($row, $vehicle_data, $client_data, $rto_master, $vehicle_type_data);
+ $vehicle_id = $vehicle_and_client_ids['vehicle_id'] ?? null;
+ $client_id = $vehicle_and_client_ids['client_id'] ?? null;
+
+ $policy_transaction_data = [
+
+ 'issuer' => 2,
+ 'issuer_branch' => $current_nhance_branch['id'] ?? null,
+ 'client_id' => $client_id,
+ 'policy_type_id' => 8,
+ 'insurer_id' => $current_insurer_branch_data['insurer_id'] ?? null,
+ 'insurer_branch_id' => $current_insurer_branch_data['id'] ?? null,
+ 'policy_no' => $policy_no,
+ 'vehicle_id' => $vehicle_id,
+ 'issue_type' => 1,
+ 'policy_issue_date' => change_date_format($policy_issue_date, 'd/M/Y', 'Y-m-d'),
+ 'policy_start_date' => change_date_format($policy_start_date, 'd/M/Y', 'Y-m-d'),
+ 'policy_end_date' => change_date_format($policy_end_date, 'd/M/Y', 'Y-m-d'),
+ 'action_type' => 'inception',
+ 'revenue_type' => $revenue_type,
+ 'co_share' => 0,
+ 'status' => 'completed',
+ 'renewal_date' => change_date_format($policy_end_date, 'd/M/Y', 'Y-m-d'),
+ 'policy_holder_name' => $client_name,
+ 'month' => change_date_format($policy_issue_date, 'd/M/Y', 'Y-m-d'),
+ 'sales_generated_by' => $salse['id'] ?? null,
+ 'serviced_by' => $service['id'] ?? null,
+ 'agent_id' => $current_agent_data['id'] ?? null,
+ 'agent_code' => $current_agent_data['agent_code'] ?? null,
+ 'file_id' => $params['file_id'],
+
+ 'endorsement_no' => null,
+ 'client_branch_id' => null,
+ 'client_policy_id' => null,
+ 'ct_type' => null,
+ 'remarks' => null,
+
+ ];
+
+ $co_share_data = [
+
+ 'pt_id' => null,
+ 'insurer_id' => $current_insurer_branch_data['insurer_id'] ?? null,
+ 'insurer_branch_id' => $current_insurer_branch_data['id'] ?? null,
+ 'co_share_type' => 1,
+ 'co_share_per' => 100,
+
+ 'bp_amt' => $base_premium,
+ 'bp_gst_amt' => $gst_amt,
+ 'bp_igst' => $igst ,
+ 'bp_sgst' => $sgst,
+ 'bp_cgst' => $cgst,
+
+ 'tp_amt' => $tp_premium,
+ 'tp_gst_amt' => 0,
+ 'tp_igst' => 0,
+ 'tp_sgst' => 0,
+ 'tp_cgst' => 0,
+
+ 'tep_amt' => 0,
+ 'tep_gst_amt' => 0,
+ 'tep_igst' => 0,
+ 'tep_sgst' => 0,
+ 'tep_cgst' => 0,
+
+ 'agreed_amt' => $agreed_amount,
+ 'agreed_bp_per' => $agreed_bp_percentage,
+ 'agreed_tp_per' => $agreed_tp_percentage,
+ 'agreed_tep_per' => 0,
+
+ 'actual_bp_amt' => $actual_bp_amount,
+ 'actual_tp_amt' => $actual_tp_amount,
+ 'actual_tep_amt' => 0,
+
+ 'actual_bp_per' => $actual_bp_percentage,
+ 'actual_tp_per' => $actual_tp_percentage,
+ 'actual_tep_per' => 0,
+
+ 'actual_bp_brokerage_amt' => $actual_bp_brokerage_amount,
+ 'actual_tp_brokerage_amt' => $actual_tp_brokerage_amount,
+ 'actual_tep_brokerage_amt' => 0,
+
+ 'standerd_bp_per' => 15.00,
+ 'standerd_tp_per' => 2.50,
+ 'agreed_tep_per' => 0,
+
+ 'reward' => $rewards,
+ 'variance' => 0,
+
+ 'remark' => null,
+ 'amount' => $total,
+ 'stamp_duty' => $stamp_duty,
+
+ 'cop_amt' => $base_premium,
+ 'cotp_amt' => $tp_premium,
+ 'cotep_amt' => 0.00,
+
+ 'exp_amt' => $expected_amount,
+ 'statement_id' => null,
+
+ 'follower_policy_no' => null,
+ 'non_comm_per_amt' => $non_commission_premium_amount,
+
+ 'pt_policy_issue_date' => change_date_format($policy_issue_date, 'd/M/Y', 'Y-m-d'),
+
+ 'file_id' => $params['file_id']
+ ];
+
+ if(!empty($vehicle_id) && !empty($client_id)){
+ $pt_id = $this->policyTransactionModel->insert($policy_transaction_data);
+ if($pt_id){
+ $co_share_data['pt_id'] = $pt_id;
+ $pt_co_share_id = $this->PTCOShareDetailsModel->insert($co_share_data);
+
+ $client_policy_insert_data = $this->prepareClientPolicyInsertData($policy_transaction_data);
+ $client_policy_id = $this->clientPolicyModel->insert($client_policy_insert_data);
+ $this->policyTransactionModel->update($pt_id, ['client_policy_id' => $client_policy_id]);
+ $pt_ids[] = $pt_id;
+ $this->myLogger->logme('error', "BDS entry successfully added with pt_id : $pt_id, pt_co_share_id : $pt_co_share_id, client_policy_id :$client_policy_id");
+
+ }
+ }else{
+ $this->myLogger->logme('error', 'Skipped......... , vehicle id and client id missing');
+ }
+
+ }
+
+ } catch (\Exception $e) {
+ $errorDetails = [
+ 'error_message' => $e->getMessage(),
+ 'file' => $e->getFile(),
+ 'line' => $e->getLine(),
+ 'stack_trace' => $e->getTraceAsString(),
+ ];
+ $message = "Contact system admin";
+ $this->bdsDumpModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+ $this->myLogger->logme("error", 'Claim dump file format validation failed due to : ' . json_encode($errorDetails ?? []));
+ return $errorDetails;
+ }
+
+ // return $result;
+
+ if (isset($result['error_summary']) && count($result['error_summary'])) {
+ $result['error_summary'] = array_count_values($result['error_summary']);
+ $status = 'failed';
+ $failure_reason = ((json_encode($result)));
+ $this->bdsDumpModel->where('id', $file_id)->set(['status' => $status, 'reason' => $failure_reason])->update();
+ $this->myLogger->logme("error", '{file_id} uploaded failed', ['file_id' => $file_id]);
+ } else{
+ $result = count($pt_ids);
+ $status = 'success';
+ $failure_reason = ((json_encode($result)));
+ $this->bdsDumpModel->where('id', $file_id)->set(['status' => $status, 'reason' => $failure_reason])->update();
+ $this->myLogger->logme("error", '{file_id} uploaded success', ['file_id' => $file_id]);
+ }
+
+ return $result;
+ }
+
+ public function extractExcelData($file_name, $highestColumn)
+ {
+ // $file_name = "claims_dump_form_client.xlsx";
+ // Load the Excel file
+ $file_name_with_path = WRITEPATH . "/uploads/bds_dump_excel/" . $file_name;
+ $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
+ $worksheet = $spreadsheet->getActiveSheet();
+
+ // Get the highest row and column numbers
+ $highestRow = $worksheet->getHighestDataRow();
+ // $highestColumn = $worksheet->getHighestDataColumn();
+ // dd($highestRow, $highestColumn);
+
+ // Get header row (assuming headers are in row 1)
+ // $headerRow = $worksheet->rangeToArray('A1:' . $highestColumn . '1', null, true, false)[0];
+ $excel_data = $worksheet->rangeToArray('A1:' . $highestColumn . $highestRow);
+ // print_rr($excel_data); die;
+
+ //Sanitize the excel data
+ $excel_data = ExcelSanitizeHelper::sanitizeArrayData($excel_data);
+ // dd($excel_data);
+
+ // dd($data);
+ return $excel_data;
+ }
+
+ public function getBdsBulkUploadExcelErrorData($file_id)
+ {
+ try {
+
+ $file = $this->bdsDumpModel->where('id', $file_id)->first();
+ $error_data = json_decode($file['reason']);
+ // dd($error_data);
+
+ $file_name_with_path = WRITEPATH . "/uploads/bds_dump_excel/" . $file['file_name'];
+ // Kint::dump(file_exists($file_name_with_path)); die;
+
+ //check the file exist or not
+ if (!file_exists($file_name_with_path)) {
+ $error_message = "File not found";
+ $this->myLogger->logme('error', ($error_message . ' for file id ' . $file_id));
+ return 0;
+ }
+
+ $columns_to_check = $this->bds_bulk_upload_excel_file_column;
+ $allowedHighestColumn = end($columns_to_check);
+ // Kint::dump($columns_to_check); die;
+
+ $excel_data = $this->extractExcelData($file['file_name'], $allowedHighestColumn['col_cell_name']);
+ $excelErrorData['excel_header'] = $excel_data[0];
+ unset($excel_data[0]);
+
+ // Kint::dump($excel_data); die;
+ if ($error_data->error_type == 1) {
+
+ $finalArray = [];
+ foreach ($error_data->error_data as $key => $value) {
+ foreach ($value as $key2 => $value2) {
+ $error_data = $value2->error;
+ $data = ['value' => $excel_data[$key][$value2->col_idx], 'error' => $error_data,];
+ $excel_data[$key][$value2->col_idx] = $data;
+ }
+ array_push($finalArray, $excel_data[$key]);
+ }
+
+ foreach ($finalArray as $fkey => $value) {
+ foreach ($value as $vkey => $arrayData) {
+ if (!is_array($arrayData)) {
+ $data = ['value' => $arrayData];
+ $finalArray[$fkey][$vkey] = $data;
+ }
+ }
+ }
+
+ $excelErrorData['excel_data'] = $finalArray;
+ return $excelErrorData;
+ } else if ($error_data->error_type == 2) {
+
+
+ $allErrors = [];
+ $typeTowArray = [];
+
+ foreach ($error_data->error_data as $index => $item) {
+
+ foreach ($item as $field) {
+ if (!isset($allErrors[$index])) {
+ $allErrors[$index] = [];
+ }
+ $allErrors[$index] = array_merge($allErrors[$index], $field->error);
+ }
+ }
+
+ // dd(array_keys($allErrors));
+ foreach ($allErrors as $key => $value) {
+ // echo $key;
+ // print_r($value);
+ foreach ($excel_data as $excel_data_index => $excel_data_value) {
+ if ($excel_data_value[0] == $key) {
+ $data = ['value' => $excel_data[$excel_data_index][1], 'error' => $value,];
+ $excel_data[$excel_data_index][1] = $data;
+ array_push($typeTowArray, $excel_data[$excel_data_index]);
+ break;
+ }
+ }
+ }
+ // dd($data);
+ foreach ($typeTowArray as $fkey => $value) {
+ foreach ($value as $vkey => $arrayData) {
+ if (!is_array($arrayData)) {
+ $data = ['value' => $arrayData];
+ $typeTowArray[$fkey][$vkey] = $data;
+ }
+ }
+ }
+
+ $excelErrorData['excel_data'] = $typeTowArray;
+ return $excelErrorData;
+ }
+
+ } catch (\Exception $e) {
+ // Handle any exceptions
+ $errorMessage = $e->getMessage(); //die();
+ $this->myLogger->logme('error', $errorMessage);
+ return false; // You can return an error response here
+ }
+ }
+
+ public function getBdsdumpFileErrorData()
+ {
+ $file_id = $this->request->getGet('file_id');
+ $file = $this->bdsDumpModel->where('id', $file_id)->first();
+ if (!isset($file)) {
+ return $this->respond(['status' => false, 'code' => 404, 'message' => 'No data found'], 200);
+ } else {
+ return $this->respond(['status' => true, 'code' => 200, 'data' => $file['reason']], 200);
+ }
+ }
+
+ public function getBdsDumpExcelFileErrors($file_id)
+ {
+ // Render views and capture output
+ $result = $this->getBdsBulkUploadExcelErrorData($file_id) ?? [];
+ // dd($result);
+
+ if ($result != 0) {
+
+ $result['file_id'] = $file_id;
+ echo view('excel_errors', $result);
+ } else if ($result == 0) {
+
+ $data['message'] = 'File Not Found Physically';
+ return view('errors/404', $data);
+ } else {
+
+ echo view('errors/html/production');
+ }
+ }
+
+ public function getClientAndVehicleId($row, $vehicle_data, $client_data, $rto_master, $vehicle_type_data)
+ {
+ $vehicle_number = trim($row[2]);
+ $client_name = trim($row[5]);
+ $client_email = trim($row[6]);
+
+ $vehicle_id = null;
+ $client_id = null;
+
+ // -------------------------------------------
+ // 1. First Stage: Check if vehicle already exists
+ // -------------------------------------------
+ foreach ($vehicle_data as $v) {
+ if (strcasecmp(trim($v['vehicle_no']), $vehicle_number) === 0) {
+ $vehicle_id = $v['id'];
+ $client_id = $v['owner'];
+ break;
+ }
+ }
+
+ // -------------------------------------------
+ // 2. Second Stage: Vehicle not found -> check client by email
+ // -------------------------------------------
+ $second_stage_client_id = null;
+
+ if (empty($vehicle_id) && empty($client_id)) {
+
+ foreach ($client_data as $c) {
+ if (strcasecmp(trim($c['email']), $client_email) === 0) {
+ $second_stage_client_id = $c['id'];
+ break;
+ }
+ }
+
+ if (!empty($second_stage_client_id)) {
+
+ // Existing client – Insert vehicle
+ $matched_rto_id = check_rto_data($row, $rto_master);
+ $vehicle_type_id = check_vehicle_type($row, $vehicle_type_data);
+
+ $vehicle_insert = [
+ 'vehicle_no' => $vehicle_number,
+ 'vehicle_type' => $vehicle_type_id['vehicle_type']['id'] ?? null,
+ 'owner' => $second_stage_client_id,
+ 'rto_id' => $matched_rto_id['rto_data']['id'] ?? null,
+ ];
+
+ $vehicle_id = $this->vehicleModel->insert($vehicle_insert);
+ $client_id = $second_stage_client_id;
+ } else {
+
+ // -------------------------------------------
+ // 3. Third Stage: No existing client → Insert new client then insert vehicle
+ // -------------------------------------------
+ $client_insert = [
+ 'client_name' => $client_name,
+ 'short_name' => $client_name,
+ 'email' => $client_email,
+ 'entity_type_id' => 7,
+ 'client_type' => 2,
+ ];
+
+ $client_id = $this->clientModel->insert($client_insert);
+
+ if ($client_id) {
+
+ $matched_rto_id = check_rto_data($row, $rto_master);
+ $vehicle_type_id = check_vehicle_type($row, $vehicle_type_data);
+
+ $vehicle_insert = [
+ 'vehicle_no' => $vehicle_number,
+ 'vehicle_type' => $vehicle_type_id['vehicle_type']['id'] ?? null,
+ 'owner' => $client_id,
+ 'rto_id' => $matched_rto_id['rto_data']['id'] ?? null,
+ ];
+
+ $vehicle_id = $this->vehicleModel->insert($vehicle_insert);
+ }
+ }
+ }
+
+ return [
+ 'client_id' => $client_id,
+ 'vehicle_id' => $vehicle_id,
+ ];
+ }
}
diff --git a/app/Controllers/RestAuthenticationController.php b/app/Controllers/RestAuthenticationController.php
index 761ceffa..4a4b7cbd 100755
--- a/app/Controllers/RestAuthenticationController.php
+++ b/app/Controllers/RestAuthenticationController.php
@@ -398,47 +398,54 @@ class RestAuthenticationController extends AdminController
$otp = isset($this->request->getJSON()->otp) ? $this->request->getJSON()->otp : null;
$client_id = $this->request->getJSON()->client_id ?? null;
- if (isset($mobile_number))
- {
- // $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->where('emp_status !=', 'truncated')->where('is_active', 1)->first();
- $builder = $this->employeeModel
- ->select('employees.*')
- ->join('employee_polices', 'employees.id = employee_polices.employee_id')
- ->where('employees.mobile', $mobile_number)
- ->where('employees.relationship', 'Self')
- ->where('employee_polices.is_active', 1)
- ->whereIn('employee_polices.status', ['active', 'expired'])
- ->where('employees.is_active', 1)
- ->whereIn('employees.emp_status', ['active', 'expired'])
- ->where('otp', $otp);
+ if(empty($otp)){
+ return $this->respond(['status' => 'OTP is required','code' => 400,'message' => 'OTP is required'], 200);
+ }
- if (!empty($client_id)) {
- $builder->where('employees.client_id', $client_id);
- }
+ if (empty($mobile_number) && empty($email_id)) {
+ return $this->respond(['status' => 'failed','code' => 400,'message' => 'Mobile number or Email ID is required'], 200);
+ }
- $employeeData = $builder->orderBy('employees.id', 'desc')->first();
+ if (isset($mobile_number))
+ {
+ // $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->where('emp_status !=', 'truncated')->where('is_active', 1)->first();
+ $builder = $this->employeeModel
+ ->select('employees.*')
+ ->join('employee_polices', 'employees.id = employee_polices.employee_id')
+ ->where('employees.mobile', $mobile_number)
+ ->where('employees.relationship', 'Self')
+ ->where('employee_polices.is_active', 1)
+ ->whereIn('employee_polices.status', ['active', 'expired'])
+ ->where('employees.is_active', 1)
+ ->whereIn('employees.emp_status', ['active', 'expired'])
+ ->where('otp', $otp);
- } else {
- // $employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('otp', $otp)->where('relationship', 'self')->where('emp_status !=', 'truncated')->where('is_active', 1)->first();
- $builder = $this->employeeModel
- ->select('employees.*')
- ->join('employee_polices', 'employees.id = employee_polices.employee_id')
- ->where('employees.email_corporate', $email_id)
- ->where('employees.relationship', 'Self')
- ->where('employee_polices.is_active', 1)
- ->whereIn('employee_polices.status', ['active', 'expired'])
- ->where('employees.is_active', 1)
- ->whereIn('employees.emp_status', ['active', 'expired'])
- ->where('otp', $otp);
+ if (!empty($client_id)) {
+ $builder->where('employees.client_id', $client_id);
+ }
- if (!empty($client_id)) {
- $builder->where('employees.client_id', $client_id);
- }
+ $employeeData = $builder->orderBy('employees.id', 'desc')->first();
- $employeeData = $builder->orderBy('employees.id', 'desc')->first();
- }
+ } else {
+ // $employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('otp', $otp)->where('relationship', 'self')->where('emp_status !=', 'truncated')->where('is_active', 1)->first();
+ $builder = $this->employeeModel
+ ->select('employees.*')
+ ->join('employee_polices', 'employees.id = employee_polices.employee_id')
+ ->where('employees.email_corporate', $email_id)
+ ->where('employees.relationship', 'Self')
+ ->where('employee_polices.is_active', 1)
+ ->whereIn('employee_polices.status', ['active', 'expired'])
+ ->where('employees.is_active', 1)
+ ->whereIn('employees.emp_status', ['active', 'expired'])
+ ->where('otp', $otp);
+
+ if (!empty($client_id)) {
+ $builder->where('employees.client_id', $client_id);
+ }
+
+ $employeeData = $builder->orderBy('employees.id', 'desc')->first();
+ }
-
$lastQuery = $this->employeeModel->db->getLastQuery();
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedUserData: Last Executed Query: " . $lastQuery);
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedUserData: employeeData: " . json_encode($employeeData ?? []));
diff --git a/app/Controllers/RuleImportController.php b/app/Controllers/RuleImportController.php
index f5579aac..d1647bae 100644
--- a/app/Controllers/RuleImportController.php
+++ b/app/Controllers/RuleImportController.php
@@ -4,6 +4,9 @@ namespace App\Controllers;
use CodeIgniter\API\ResponseTrait;
use App\Models\CommissionFilesModel;
use App\Models\InsurerModel;
+use App\Models\PartnerPolicyModel;
+
+
class RuleImportController extends AdminController
{
@@ -12,7 +15,9 @@ class RuleImportController extends AdminController
protected $ruleImportService;
protected $commissionFilesModel;
protected $departments;
+ protected $departmentFields;
protected $insurerModel;
+ protected $partnerPolicyModel;
public function __construct()
{
@@ -20,13 +25,40 @@ class RuleImportController extends AdminController
$this->myLogger = \Config\Services::mylogger();
$this->ruleImportService = \Config\Services::ruleImportService();
-
+ $this->partnerPolicyModel = new partnerPolicyModel();
$this->commissionFilesModel = new CommissionFilesModel();
$this->insurerModel = new InsurerModel();
$this->departments = [
'motor' => 'Motor',
'health' => 'Health',
];
+
+ $this->departmentFields = [
+ 'motor' => [
+ 'department',
+ 'vehicle_type',
+ 'vehicle_sub_type',
+ 'policy_type',
+ 'vehicle_age',
+ 'is_new_vehicle',
+ 'cubic_capacity',
+ 'policy_business_type',
+ 'fuel_type',
+ 'produt',
+ 'geo_rto_state',
+ 'geo_rto_city',
+ 'model',
+ 'make',
+ 'weight',
+ 'renewal_type',
+ 'renewal_sub_type',
+ 'premium',
+ 'od_premium',
+ 'tp_premium',
+ 'product'
+ ],
+ ];
+
}
public function commissionFileUploadList()
@@ -194,6 +226,8 @@ class RuleImportController extends AdminController
'insurer_id' => (int)$insurerId,
'department' => $department,
'commission_month' => $commissionMonth,
+ 'created_by' => (int)$createdBy,
+
];
$this->myLogger->logme('info', 'RuleImportController::upload - Calling ruleImportService->processUpload', ['payload' => $payload]);
@@ -262,10 +296,22 @@ class RuleImportController extends AdminController
// handle existing JSON file based on $override (bool)
if (file_exists($jsonPath)) {
if ($overwrite) {
- // delete existing file before writing (deterministic overwrite)
- if (!@unlink($jsonPath)) {
- $this->myLogger->logme('warning', 'RuleImportController::upload - Failed to delete existing JSON before overwrite', ['json_path' => $jsonPath]);
- // proceed to overwrite anyway by writing to the same path
+ // rename existing file before overwrite
+ if (file_exists($jsonPath)) {
+
+ $backupPath = $jsonPath . '.' . date('YmdHis') . '.bak';
+
+ if (!@rename($jsonPath, $backupPath)) {
+ $this->myLogger->logme(
+ 'warning',
+ 'RuleImportController::upload - Failed to rename existing JSON before overwrite',
+ [
+ 'json_path' => $jsonPath,
+ 'backup_path' => $backupPath
+ ]
+ );
+ // continue anyway; writing to same path will overwrite
+ }
}
$finalJson = $jsonData;
} else {
@@ -487,7 +533,7 @@ class RuleImportController extends AdminController
public function deleteCommissionData($id)
{
- $return = $this->removeCommissionRules($id);
+ $return = $this->updateCommissionRules($id);
// dd($return);
if($return['status'] == true){
@@ -498,7 +544,7 @@ class RuleImportController extends AdminController
}
}
- public function deActiveCommissionRules($id)
+ public function updateCommissionRules($id, $post_data = null)
{
// 1. Fetch commission record
$commission_data = $this->commissionFilesModel
@@ -528,7 +574,7 @@ class RuleImportController extends AdminController
// 4. Read JSON
$json = file_get_contents($filePath);
$rules = json_decode($json, true);
- // dd($rules);
+ // print_rr($rules); die;
if (!is_array($rules)) {
$this->myLogger->logme("error", "Invalid JSON structure in file: $filePath");
@@ -537,9 +583,58 @@ class RuleImportController extends AdminController
// 5. Mark matching rule as deleted
$ruleFound = false;
- foreach ($rules as &$rule) {
- if (!isset($rule['is_deleted']) && isset($rule['file_id']) && $rule['file_id'] == $id) {
- $rule['is_deleted'] = true; // <-- NEW FEATURE
+ $log_message = "Rule file updated successfully";
+
+ if(empty($post_data)){
+ foreach ($rules as &$rule) {
+ if (isset($rule['file_id']) && $rule['file_id'] == $id && isset($rule['is_deleted']) && $rule['is_deleted'] == false) {
+ $rule['is_deleted'] = true;
+ $ruleFound = true;
+ }
+ }
+ $log_message = "Rule marked as deleted and file updated successfully";
+ } else {
+
+ foreach ($rules as &$rule) {
+ // Match rules for the same file and not deleted
+ if (isset($rule['file_id']) && $rule['file_id'] == $id && $rule['is_deleted'] == false)
+ {
+ // 1. DELETE RULE
+ if (!empty($post_data['rule_id']) && $post_data['rule_id'] == $rule['id'] && isset($post_data['is_deleted']))
+ {
+ $rule['is_deleted'] = true;
+ $ruleFound = true;
+ break;
+ }
+
+ // 2. UPDATE RULE
+ if (!empty($post_data['rule_id']) && $post_data['rule_id'] == $rule['id'])
+ {
+ $rule['conditions'] = $post_data['rule_data']['conditions'];
+ $rule['calculation'] = $post_data['rule_data']['calculation'];
+ $rule['name'] = $post_data['rule_data']['name'];
+ $ruleFound = true;
+ break;
+ }
+ }
+ }
+
+ // 3. CREATE NEW RULE (only if not found)
+ if (empty($post_data['rule_id']) && !$ruleFound) {
+
+ $newRuleId = 'rule_' . substr(md5(json_encode($post_data['rule_data']) . time()), 0, 13) . '_' . $id . '_' . strtolower($monthFolder);
+ $newRule = [
+ 'id' => $newRuleId,
+ 'name' => $post_data['rule_data']['name'],
+ "department" => $post_data['rule_data']['department'] ?? "motor",
+ 'is_deleted' => false,
+ 'file_id' => $id,
+ 'conditions' => $post_data['rule_data']['conditions'],
+ 'calculation' => $post_data['rule_data']['calculation'],
+ ];
+
+ $rules[] = $newRule; // correctly push new rule
+
$ruleFound = true;
}
}
@@ -552,11 +647,11 @@ class RuleImportController extends AdminController
// 6. Always save file back (No unlink)
file_put_contents($filePath, json_encode($rules, JSON_PRETTY_PRINT));
- $this->myLogger->logme("error", "Rule marked deleted and file updated: $filePath");
+ $this->myLogger->logme("error", $log_message);
return [
'status' => true,
- 'message' => 'Rule marked as deleted and file updated successfully'
+ 'message' => $log_message
];
}
@@ -641,5 +736,109 @@ class RuleImportController extends AdminController
}
}
+ public function ruleList($id)
+ {
+ $data['page_name'] = "Rule Manager";
+ $data['departments'] = $this->departments;
+ $data['commission_file_id'] = $id;
+ $data['departmentFields'] = json_encode($this->departmentFields);
+ $data['rules'] = $this->getRuleJson($id);
+ return $this->loadLayout('commission_rules_list', $data);
+ }
+
+ public function getRuleJson($id)
+ {
+
+ // 1. Fetch commission record
+ $commission_data = $this->commissionFilesModel
+ ->where('is_active', 1)
+ ->where('id', $id)
+ ->first();
+
+ if (!$commission_data) {
+ $this->myLogger->logme("error", "Commission record not found for ID: $id");
+ return [];
+ }
+
+ // 2. Convert commission_month → OCT2025
+ $month = date("M", strtotime($commission_data['commission_month']));
+ $year = date("Y", strtotime($commission_data['commission_month']));
+ $monthFolder = strtoupper($month . $year);
+
+ // 3. Path
+ $fileName = $commission_data['insurer_id'] . '_' . $commission_data['department'] . '.json';
+ $filePath = WRITEPATH . "uploads/commission/rules/" . $monthFolder . "/" . $fileName;
+
+ if (!file_exists($filePath)) {
+ $this->myLogger->logme("error", "Rule file not found: $filePath");
+ return [];
+ }
+
+ // 4. Read JSON
+ $json = file_get_contents($filePath);
+ $rules = json_decode($json, true);
+
+ if(!empty($rules)){
+ return $rules;
+ }else{
+ return [];
+ }
+
+ }
+
+ public function saveRule()
+ {
+ $post_data = $this->request->getPost();
+
+ $file_id = $post_data['file_id'];
+ $return = $this->updateCommissionRules($file_id, $post_data);
+ // print_r($return); die;
+
+ if(empty($post_data['rule_id'])){
+ $success_message = "New rule created successfully";
+ $error_message = "Failed to created the new rule";
+ }else{
+ $success_message = "Rule updated successfully";
+ $error_message = "Failed to update the rule";
+ }
+
+ if($return['status'] == true){
+ $data = $this->getRuleJson($file_id);
+ return $this->respond(['status' => true, 'code' => 200, 'data' => $data, 'message' => $success_message], 200);
+ }else{
+ return $this->respond(['status' => false, 'code' => 400, 'message' => $error_message], 200);
+ }
+
+ }
+
+ public function removeRule()
+ {
+ $post_data = $this->request->getPost();
+
+ $file_id = $post_data['file_id'];
+ $return = $this->updateCommissionRules($file_id, $post_data);
+ // print_r($return); die;
+
+ $success_message = "Rule deleted successfully";
+ $error_message = "Failed to delete the rule";
+
+ if($return['status'] == true){
+ $data = $this->getRuleJson($file_id);
+ return $this->respond(['status' => true, 'code' => 200, 'data' => $data, 'message' => $success_message], 200);
+ }else{
+ return $this->respond(['status' => false, 'code' => 400, 'message' => $error_message], 200);
+ }
+ }
+
+ public function checkRuleUsage()
+ {
+ $rule_id = $this->request->getGet('rule_id');
+
+ $count = $this->partnerPolicyModel->where('commission_applied_rule', $rule_id)
+ ->countAllResults();
+ // $count = 1;
+ return $this->respond(['status' => true, 'code' => 200, 'count' => $count, 'message' => ""], 200);
+ }
+
}
diff --git a/app/Controllers/ThzController.php b/app/Controllers/ThzController.php
index 29f89df4..139b5b8e 100644
--- a/app/Controllers/ThzController.php
+++ b/app/Controllers/ThzController.php
@@ -102,16 +102,19 @@ class ThzController extends BaseController
public function ticketList()
{
- try {
+ // try {
$returnType = strtolower($this->request->getGet('return_type') ?? 'api');
$data = $this->request->getGet();
- if ($returnType === 'web' && in_array(get_role_id(), [3, 4])) {
+ if ($returnType === 'web' && in_array(get_role_id(), [4])) {
$data['assign_to'] = $data['assign_to'] ?? get_session_userid();
}
+ if ($returnType === 'web' && in_array(get_role_id(), [3])) {
+ $data['clientIds'] = $this->clientModel->getClientIdBasedonLoggedInSessionID();
+ }
$tickets = $this->fetchTicketsBasedOnrole($data);
@@ -124,8 +127,9 @@ class ThzController extends BaseController
} else {
$data['ticket_data'] = $tickets;
$data['assignee'] = $this->userModel->where('is_active', 1)->whereIn('role', ['3', '4'])->findAll();
- // enga 5-"head" and 1-"admin" assign pannvaga so dropdown la varakudhathu , 2-"manager l2 " - ivangalum assign pannalam
- // 3,4 remain person varannum.
+ // enga 5-"head" and 1-"admin" assign pannvaga so dropdown la varakudhathu , 2-"manager l2 " - ivangalum assign pannalam. 3,4 remain person varannum dropdown la.
+ // Roles - 5 (Head) , 1 (Admin) and 2 (Manager) are already assigned to others, so the dropdown should not be shown.
+ // 3 (Account Manager) and 4 (Staff) should be selectable, so have to show in dropdown .
$data['client_list'] = $this->clientModel->getCreatedByUserName();
$data['ticket_type'] = $this->thzTypeModel->where('is_active', 1)->findAll();
$data['tab_name'] = "Tickets";
@@ -138,9 +142,9 @@ class ThzController extends BaseController
'status' => 'success',
'data' => $tickets,
])->setStatusCode(200);
- } catch (\Throwable $e) {
- return handle_exception($e, $this->myLogger, $this->response);
- }
+ // } catch (\Throwable $e) {
+ // return handle_exception($e, $this->myLogger, $this->response);
+ // }
}
public function ticketConversationSave()
@@ -348,6 +352,7 @@ class ThzController extends BaseController
// $id = $data['thz_id'] ?? null;
$assign_to = $data['assign_to'] ?? null;
$mobile = $data['mobile'] ?? null;
+ $clientIds = $data['clientIds'] ?? null;
if (!empty($assign_to)) {
// Tickets assigned to a staff
@@ -371,6 +376,17 @@ class ThzController extends BaseController
->findAll();
}
+
+ if (!empty($clientIds)) {
+ return $this->thzMasterModel
+ ->select('thz_master.*, user_profiles.first_name as assignee_name')
+ ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left')
+ ->whereIn('thz_master.client_id', $clientIds)
+ ->orderBy('thz_master.created_at', 'desc')
+ ->findAll();
+ }
+
+
// All tickets (e.g., for managers)
return $this->thzMasterModel
->select('thz_master.*, user_profiles.first_name as assignee_name')
diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php
index 6219326a..87620e51 100644
--- a/app/Controllers/TicketController.php
+++ b/app/Controllers/TicketController.php
@@ -26,6 +26,7 @@ use App\Models\VehicleModel;
use App\Models\PartnerPolicyModel;
use DOMDocument;
+use DOMXPath;
use Psr\Log\LoggerInterface;
use Kint\Kint;
@@ -1313,7 +1314,7 @@ class TicketController extends BaseController
}
}
- public function convertHtmlToText($html)
+ public function convertHtmlToTextOld($html)
{
if(!empty($html)){
$dom = new DOMDocument();
@@ -1324,6 +1325,36 @@ class TicketController extends BaseController
}
}
+ public function convertHtmlToText($html)
+ {
+ if (empty($html)) {
+ return '';
+ }
+
+ // Remove BOM / strange characters
+ $html = preg_replace('/[\x00-\x1F\x80-\xFF]/', ' ', $html);
+
+ // Load HTML safely
+ $dom = new DOMDocument();
+ libxml_use_internal_errors(true);
+ $dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
+
+ // Remove style and script tags
+ $xpath = new DOMXPath($dom);
+ foreach ($xpath->query('//style|//script') as $node) {
+ $node->parentNode->removeChild($node);
+ }
+
+ // Extract clean text
+ $text = $dom->textContent;
+
+ // Clean extra spaces
+ $text = preg_replace('/\s+/', ' ', $text);
+
+ return trim($text);
+ }
+
+
public function removeTicket()
{
$ticket_id = $this->request->getGet('ticket_id');
@@ -2068,7 +2099,7 @@ class TicketController extends BaseController
->join('policy_type', 'policy_type.id = client_policy.policy_type_id AND policy_type.is_active = 1')
->join('insurers', 'insurers.id = client_policy.insurer_id AND insurers.is_active = 1', 'left')
->join('tpa', 'tpa.id = client_policy.tpa_id AND tpa.is_active = 1', 'left')
- ->where('client_policy.policy_status', 1)
+ // ->where('client_policy.policy_status', 1)
->whereIn('client_policy.id', $policy_ids)
->findAll();
diff --git a/app/Controllers/UserController.php b/app/Controllers/UserController.php
index ea0e4fb8..ee62c702 100755
--- a/app/Controllers/UserController.php
+++ b/app/Controllers/UserController.php
@@ -20,6 +20,7 @@ use App\Models\AuthHistoryModel;
use App\Models\UserActivityHistoryModel;
use App\Models\PartnerStaffModel;
use App\Models\PartnerManagerIncentiveFileModel;
+use App\Models\NhanceBranchModel;
class UserController extends AdminController
@@ -36,6 +37,7 @@ class UserController extends AdminController
protected $userActivityHistoryModel;
protected $partnerStaffModel;
protected $partnerManagerIncentiveFileModel;
+ protected $nhanceBranchModel;
public function __construct()
{
@@ -51,6 +53,7 @@ class UserController extends AdminController
$this->userActivityHistoryModel = new UserActivityHistoryModel();
$this->partnerStaffModel = new PartnerStaffModel();
$this->partnerManagerIncentiveFileModel = new PartnerManagerIncentiveFileModel();
+ $this->nhanceBranchModel = new NhanceBranchModel();
}
public function list()
@@ -63,6 +66,7 @@ class UserController extends AdminController
// print_r($data); die;
$data['roleData'] = $this->roleModel->select('id, role')->findAll();
$data['teamData'] = $this->teamModel->select('id, name')->where('is_active',1)->findAll();
+ $data['NHanceBranchData'] = $this->nhanceBranchModel->select('id, branch_name')->where('is_active',1)->findAll();
$this->loadLayout('UserList', $data);
}
@@ -70,6 +74,7 @@ class UserController extends AdminController
public function create()
{
$this->myLogger->logme('error', 'User create function called');
+ dd($this->request->getPost());
$teams = $this->request->getPost('team');
//if this is get method return to user creation page
diff --git a/app/Filters/Cors.php b/app/Filters/Cors.php
new file mode 100644
index 00000000..c47f2762
--- /dev/null
+++ b/app/Filters/Cors.php
@@ -0,0 +1,422 @@
+
+ */
+ protected array $allowedOrigins = [];
+
+ /**
+ * Whether to allow credentials (cookies, authorization headers) in CORS requests
+ * WARNING: Cannot be true if using wildcard (*) origin
+ *
+ * @var bool
+ */
+ protected bool $allowCredentials = false;
+
+ /**
+ * HTTP methods allowed for CORS requests
+ *
+ * @var string
+ */
+ protected string $allowedMethods = 'GET,POST,PUT,PATCH,DELETE,OPTIONS';
+
+ /**
+ * HTTP headers allowed in CORS requests
+ *
+ * @var string
+ */
+ protected string $allowedHeaders = 'Content-Type,Authorization,X-Requested-With,Accept,Origin';
+
+ /**
+ * Headers exposed to the client (accessible via JavaScript)
+ *
+ * @var string
+ */
+ protected string $exposeHeaders = '';
+
+ /**
+ * How long (in seconds) the preflight response can be cached
+ * Default: 24 hours (86400 seconds)
+ *
+ * @var int
+ */
+ protected int $maxAge = 86400;
+
+ /**
+ * Whether to enable debug logging for CORS requests
+ *
+ * @var bool
+ */
+ protected bool $debug = false;
+
+ /**
+ * Initialize CORS configuration from environment variables
+ *
+ * @throws \RuntimeException If configuration is invalid
+ */
+
+ protected $myLogger;
+ public function __construct()
+ {
+
+ $this->myLogger = \Config\Services::mylogger();
+ // Parse allowed origins from environment variable
+ // Format: comma or semicolon separated list
+ // Examples: "https://example.com,https://app.example.com" or "*.example.com"
+ $raw = env('CORS_ALLOWED_ORIGINS', '*');
+ $parts = preg_split('/\s*[,;]\s*/', trim($raw));
+ $this->allowedOrigins = array_filter(array_map('trim', $parts));
+
+ // Load other configuration from environment
+ $this->allowCredentials = filter_var(
+ env('CORS_ALLOW_CREDENTIALS', false),
+ FILTER_VALIDATE_BOOLEAN
+ );
+ $this->allowedMethods = env('CORS_ALLOWED_METHODS', $this->allowedMethods);
+ $this->allowedHeaders = env('CORS_ALLOWED_HEADERS', $this->allowedHeaders);
+ $this->exposeHeaders = env('CORS_EXPOSE_HEADERS', $this->exposeHeaders);
+ $this->maxAge = (int) env('CORS_MAX_AGE', $this->maxAge);
+ $this->debug = filter_var(env('CORS_DEBUG', false), FILTER_VALIDATE_BOOLEAN);
+
+ // Security validation: wildcard origin cannot be used with credentials
+ // This is a browser security requirement, not just a best practice
+ if ($this->allowCredentials && in_array('*', $this->allowedOrigins, true)) {
+ throw new \RuntimeException(
+ 'CORS configuration error: Cannot use wildcard (*) origin with credentials enabled. ' .
+ 'This violates browser security policies. Either disable credentials or specify explicit origins.'
+ );
+ }
+
+ $this->log('CORS filter initialized', [
+ 'allowed_origins' => $this->allowedOrigins,
+ 'allow_credentials' => $this->allowCredentials,
+ 'allowed_methods' => $this->allowedMethods,
+ ]);
+ }
+
+ /**
+ * Check if a given origin is allowed to access this API
+ *
+ * Supports:
+ * - Exact matches: https://example.com
+ * - Wildcard origins: *.example.com
+ * - Scheme-less matching: example.com (matches http and https)
+ * - Universal wildcard: *
+ *
+ * @param string|null $origin The Origin header from the request
+ * @return bool True if origin is allowed, false otherwise
+ */
+ protected function isOriginAllowed(?string $origin): bool
+ {
+ // Reject empty origins
+ if (empty($origin)) {
+ $this->log('Origin rejected: empty origin header');
+ return false;
+ }
+
+ // Validate origin format - must include scheme (http:// or https://)
+ // This prevents malformed origins from being accepted
+ if (!preg_match('#^https?://#i', $origin)) {
+ $this->log('Origin rejected: invalid format (missing scheme)', ['origin' => $origin]);
+ return false;
+ }
+
+ // If wildcard present in configuration, allow any origin
+ if (in_array('*', $this->allowedOrigins, true)) {
+ $this->log('Origin allowed: wildcard match', ['origin' => $origin]);
+ return true;
+ }
+
+ // Parse the host from the origin for wildcard matching
+ // Example: https://app.example.com:8080 → app.example.com
+ $originHost = parse_url($origin, PHP_URL_HOST) ?: $origin;
+
+ foreach ($this->allowedOrigins as $allowed) {
+ if ($allowed === '') {
+ continue;
+ }
+
+ // 1. Exact match (including scheme and port)
+ // Example: https://example.com matches https://example.com
+ if (strcasecmp($allowed, $origin) === 0) {
+ $this->log('Origin allowed: exact match', [
+ 'origin' => $origin,
+ 'matched_rule' => $allowed
+ ]);
+ return true;
+ }
+
+ // 2. Handle scheme-less and wildcard patterns
+ // If the allowed entry doesn't contain ://, it's either a host-only or wildcard pattern
+ if (strpos($allowed, '://') === false) {
+
+ // 2a. Wildcard subdomain pattern: *.example.com
+ // Matches: app.example.com, api.example.com, dev.app.example.com
+ // Does NOT match: example.com (use explicit entry for root domain)
+ if (strpos($allowed, '*.') === 0) {
+ $allowedRoot = substr($allowed, 2); // Remove *. prefix
+
+ // Check if origin host ends with the allowed root domain
+ if ($originHost === $allowedRoot || str_ends_with($originHost, '.' . $allowedRoot)) {
+ $this->log('Origin allowed: wildcard subdomain match', [
+ 'origin' => $origin,
+ 'matched_rule' => $allowed,
+ 'origin_host' => $originHost
+ ]);
+ return true;
+ }
+ }
+ // 2b. Direct host match (scheme-less)
+ // Allows both http and https for the same host
+ // Example: example.com matches both http://example.com and https://example.com
+ else {
+ if (strcasecmp($allowed, $originHost) === 0) {
+ $this->log('Origin allowed: host match (scheme-less)', [
+ 'origin' => $origin,
+ 'matched_rule' => $allowed,
+ 'origin_host' => $originHost
+ ]);
+ return true;
+ }
+ }
+ }
+ }
+
+ // No match found - reject this origin
+ $this->log('Origin rejected: no matching rule', [
+ 'origin' => $origin,
+ 'checked_rules' => $this->allowedOrigins
+ ]);
+ return false;
+ }
+
+ /**
+ * Build the Access-Control-Allow-Origin header value
+ *
+ * Returns either:
+ * - '*' if wildcard is configured and credentials are disabled
+ * - The actual origin value if credentials are enabled or specific origins configured
+ *
+ * Note: When credentials are enabled, you MUST echo back the specific origin,
+ * browsers reject wildcard with credentials.
+ *
+ * @param string $origin The validated origin
+ * @return string The value for Access-Control-Allow-Origin header
+ */
+ protected function buildAllowOriginHeader(string $origin): string
+ {
+ // If wildcard configured and credentials NOT required, can safely return '*'
+ // This allows any origin to access the resource
+ if (in_array('*', $this->allowedOrigins, true) && !$this->allowCredentials) {
+ return '*';
+ }
+
+ // Otherwise, must return the specific origin
+ // This is required when allow-credentials is true
+ return $origin;
+ }
+
+ /**
+ * Add all CORS headers to the response
+ *
+ * This method is called for both preflight and actual requests
+ * to ensure consistent CORS headers across all responses.
+ *
+ * @param ResponseInterface $response The response object to add headers to
+ * @param RequestInterface $request The original request
+ * @param string $origin The validated origin
+ * @param bool $isPreflight Whether this is a preflight OPTIONS request
+ * @return void
+ */
+ protected function addCorsHeaders(
+ ResponseInterface $response,
+ RequestInterface $request,
+ string $origin,
+ bool $isPreflight = false
+ ): void {
+ // CRITICAL: Vary header prevents caching issues
+ // Without this, a cached response for origin A might be served to origin B,
+ // causing CORS errors because the Access-Control-Allow-Origin won't match
+ $response->setHeader('Vary', 'Origin');
+
+ // Set the allowed origin
+ $allowOrigin = $this->buildAllowOriginHeader($origin);
+ $response->setHeader('Access-Control-Allow-Origin', $allowOrigin);
+
+ // If credentials are allowed, set the header
+ // This allows cookies, authorization headers, and TLS client certificates
+ if ($this->allowCredentials) {
+ $response->setHeader('Access-Control-Allow-Credentials', 'true');
+ }
+
+ // Allowed HTTP methods
+ $response->setHeader('Access-Control-Allow-Methods', $this->allowedMethods);
+
+ // Handle allowed headers
+ if ($isPreflight) {
+ // For preflight: respect what the browser is asking for
+ // The browser sends Access-Control-Request-Headers to ask permission
+ $requestedHeaders = $request->getHeaderLine('Access-Control-Request-Headers');
+ $response->setHeader(
+ 'Access-Control-Allow-Headers',
+ $requestedHeaders ?: $this->allowedHeaders
+ );
+ } else {
+ // For actual requests: use configured headers
+ // Access-Control-Request-Headers is only for preflight
+ $response->setHeader('Access-Control-Allow-Headers', $this->allowedHeaders);
+ }
+
+ // Expose additional headers to the client (accessible via JavaScript)
+ // Without this, only simple headers are accessible: Cache-Control, Content-Language,
+ // Content-Type, Expires, Last-Modified, Pragma
+ if (!empty($this->exposeHeaders)) {
+ $response->setHeader('Access-Control-Expose-Headers', $this->exposeHeaders);
+ }
+
+ // Cache duration for preflight responses
+ // Reduces preflight requests by allowing browser to cache the permissions
+ if ($this->maxAge > 0) {
+ $response->setHeader('Access-Control-Max-Age', (string) $this->maxAge);
+ }
+ }
+
+ /**
+ * Execute before the controller
+ *
+ * Handles preflight OPTIONS requests by returning early with appropriate headers.
+ * For other requests, allows them to proceed to the controller.
+ *
+ * @param RequestInterface $request The request object
+ * @param mixed $arguments Optional arguments
+ * @return ResponseInterface|null Response for preflight, null for other requests
+ */
+ public function before(RequestInterface $request, $arguments = null)
+ {
+ $origin = $request->getHeaderLine('Origin') ?: '';
+ $method = strtoupper($request->getMethod());
+
+ // Handle preflight OPTIONS requests
+ // Preflight is sent by browsers before actual cross-origin requests
+ // to check if the actual request is safe to send
+ if ($method === 'OPTIONS') {
+ $this->log('Preflight request received', [
+ 'origin' => $origin,
+ 'method' => $method,
+ 'uri' => (string) $request->getUri()
+ ]);
+
+ // Validate origin - reject if not allowed
+ if (empty($origin) || !$this->isOriginAllowed($origin)) {
+ $this->log('Preflight rejected: origin not allowed', ['origin' => $origin]);
+
+ // Return 403 Forbidden for rejected origins
+ // Some prefer 200 with no CORS headers, but 403 is more explicit
+ return Services::response()
+ ->setStatusCode(403)
+ ->setJSON(['error' => 'Origin not allowed']);
+ }
+
+ // Origin is valid - build preflight response
+ $response = Services::response();
+ $this->addCorsHeaders($response, $request, $origin, true);
+
+ // 204 No Content is the standard response for successful preflight
+ // It indicates "permission granted, but no data to return"
+ $response->setStatusCode(204);
+ $response->setBody('');
+
+ $this->log('Preflight approved', [
+ 'origin' => $origin,
+ 'allowed_methods' => $this->allowedMethods
+ ]);
+
+ return $response;
+ }
+
+ // For non-OPTIONS requests, don't return a response
+ // Let the request proceed to the controller
+ // CORS headers will be added in after() method
+ return null;
+ }
+
+ /**
+ * Execute after the controller
+ *
+ * Adds CORS headers to the response for actual (non-preflight) requests.
+ * This ensures all API responses include proper CORS headers.
+ *
+ * @param RequestInterface $request The request object
+ * @param ResponseInterface $response The response object
+ * @param mixed $arguments Optional arguments
+ * @return void
+ */
+ public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
+ {
+ $origin = $request->getHeaderLine('Origin') ?: '';
+
+ // Only add CORS headers if origin is present and allowed
+ // No origin header means it's a same-origin request (no CORS needed)
+ if (empty($origin)) {
+ return;
+ }
+
+ if (!$this->isOriginAllowed($origin)) {
+ $this->log('Response blocked: origin not allowed', [
+ 'origin' => $origin,
+ 'uri' => (string) $request->getUri()
+ ]);
+ return;
+ }
+
+ // Add CORS headers to the response
+ $this->addCorsHeaders($response, $request, $origin, false);
+
+ $this->log('CORS headers added to response', [
+ 'origin' => $origin,
+ 'status' => $response->getStatusCode()
+ ]);
+ }
+
+ /**
+ * Log debug information if debug mode is enabled
+ *
+ * Logs to CodeIgniter's log system at 'info' level.
+ * Enable with CORS_DEBUG=true in .env file.
+ *
+ * @param string $message The log message
+ * @param array $context Additional context data
+ * @return void
+ */
+ protected function log(string $message, array $context = []): void
+ {
+ if (!$this->debug) {
+ return;
+ }
+
+ // $logger = Services::logger();
+ $contextString = !empty($context) ? json_encode($context, JSON_UNESCAPED_SLASHES) : '';
+ $this->myLogger->logme('error','[CORS] ' . $message . ($contextString ? ' | ' . $contextString : ''));
+ // $logger->info('[CORS] ' . $message . ($contextString ? ' | ' . $contextString : ''));
+ }
+}
\ No newline at end of file
diff --git a/app/Helpers/MailHelper.php b/app/Helpers/MailHelper.php
index 89e90262..6c16ca8a 100755
--- a/app/Helpers/MailHelper.php
+++ b/app/Helpers/MailHelper.php
@@ -318,7 +318,7 @@ class MailHelper
$attachments = isset($params['attachments']) ? $params['attachments'] : [];
$common = isset($params['common']) ? $params['common'] : '';
$bcc = isset($params['bcc']) ? $params['bcc'] : '';
- $cc = isset($params['cc']) ? $params['cc'] : '';
+ $cc = (isset($params['cc']) && !empty($params['cc'])) ? $params['cc'] : '';
$from_address = isset($params['from_mail']) && !empty($params['from_mail']) ? $params['from_mail'] : getenv('email.fromEmail');
// $from_address = "claims@nhanceindia.in";
diff --git a/app/Helpers/excel_util_helper.php b/app/Helpers/excel_util_helper.php
index 15f41462..b5334313 100755
--- a/app/Helpers/excel_util_helper.php
+++ b/app/Helpers/excel_util_helper.php
@@ -50,7 +50,6 @@ if (!function_exists('check_columns_name')) {
}
}
-
if (!function_exists('check_row_is_empty_or_null')) {
function check_row_is_empty_or_null($arr)
@@ -89,7 +88,6 @@ if (!function_exists('check_excel_date_format')) {
}
}
-
if (!function_exists('check_relationship')) {
function check_relationship($row, $relationship, $policy_terms)
{
@@ -132,7 +130,6 @@ if (!function_exists('check_relationship')) {
}
}
-
if (!function_exists('check_doj')) {
function check_doj($row)
@@ -179,7 +176,6 @@ if (!function_exists('check_doc')) {
}
}
-
if (!function_exists('check_employee_band')) {
function check_employee_band($row, $policy_terms, $slab_details)
{
@@ -218,7 +214,6 @@ if (!function_exists('check_employee_band')) {
}
}
-
if (!function_exists('check_si')) {
function check_si($row, $policy_details, $slab_details)
{
@@ -326,7 +321,6 @@ if (!function_exists('check_basic_pay')) {
}
}
-
if (!function_exists('check_dob_diff')) {
function check_dob_diff($row, $relationships, $default_age_ratio, $policy_details)
{
@@ -381,6 +375,10 @@ if (!function_exists('data_group_by_family')) {
if ($data_source == 'excel') {
if (!check_row_is_empty_or_null($row)) {
+ if(empty($action)){
+ $row['data_from'] = "excel";
+ }
+
// for this condition to avoid 5,00,000 to 500000
if($current_column_action == 'SI'){
$row[3] = removeNumberFormatting($row[3]);
@@ -398,6 +396,8 @@ if (!function_exists('data_group_by_family')) {
} else {
$result[$row[1]][] = $row;
}
+
+
}
} else if ($data_source = 'db') {
if (strtolower($row['relationship']) == 'self' && isset($result[$row['emp_code']])) {
@@ -464,8 +464,6 @@ if (!function_exists('check_self_available_in_family')) {
}
}
-
-
if (!function_exists('name_and_empid_check_in_db')) {
function name_and_empid_check_in_db($family_data, $actionArr)
{
@@ -955,7 +953,6 @@ if (!function_exists('calculate_premium_new')) {
}
}
-
if (!function_exists('transform_excel_data_to_db')) {
function transform_excel_data_to_db($memArr, $actionArr)
{
@@ -1022,12 +1019,19 @@ if (!function_exists('transform_excel_data_to_db')) {
$result['temp']['rata_premimum'] = isset($memArr['temp']['rata_premimum']) ? $memArr['temp']['rata_premimum'] : 0;
$result['policy_details'] = $policy;
+ if(isset($memArr['self_rata_premium'])){
+ $result['self_rata_premium'] = $memArr['self_rata_premium'] ?? 0;
+ }
+
+ if(isset($memArr['data_from'])){
+ $result['data_from'] = $memArr['data_from'] ?? 'excel';
+ }
+
return $result;
}
}
}
-
if (!function_exists('premium_calculation_manager_old')) {
function premium_calculation_manager_old($emp_data, $policy_terms, $slab_details, $default_si = null)
{
@@ -1839,6 +1843,15 @@ if (!function_exists('premium_calculation_manager')) {
//set dependent si to 0
$emp_data['policy_details']['basic_cover_si'] = 0;
$emp_data['policy_details']['premium'] = 0;
+
+ if(isset($emp_data['self_rata_premium']) && !empty($emp_data['self_rata_premium'])){
+ $self_rata_premium = (int)($emp_data['self_rata_premium'] ?? 0);
+ $dependent_rata_premium = (int)($emp_data['policy_details']['rata_premimum'] ?? 0);
+ $actual_rata_premium = abs($dependent_rata_premium - $self_rata_premium);
+ $emp_data['policy_details']['rata_premimum'] = $actual_rata_premium;
+ $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
+ }
+
}else if(strtolower($emp_data['relationship']) != 'self' && $temp_slab_rates[0]['premium_type'] == 1 && ($emp_data['temp']['action'] == 'I' || $emp_data['temp']['action'] == 'A' || $emp_data['temp']['action'] == 'MI')){
$emp_data['policy_details']['basic_cover_si'] = 0;
@@ -1853,7 +1866,6 @@ if (!function_exists('premium_calculation_manager')) {
}
}
-
if (!function_exists('calculate_pro_rata_premimum')) {
function calculate_pro_rata_premimum($premium, $employee_policy_coverage_days, $policy_coverage_days)
{
@@ -1976,7 +1988,6 @@ if (!function_exists('get_emp_policy_records_from_audit_history')) {
}
}
-
if (!function_exists('replace_original_data')) {
function replace_original_data(array $original_data, array $current_data)
{
@@ -2048,7 +2059,6 @@ if (!function_exists('remap_default_age_ratio_into_relationship')) {
}
}
-
if (!function_exists('check_dup_mobileno')) {
function check_dup_mobileno(array $row, array $existing_mobilenos)
{
@@ -2178,7 +2188,6 @@ if (!function_exists('convert_string_to_date')) {
}
}
-
if (!function_exists('transform_enrollment_row_to_inception_row')) {
function transform_enrollment_row_to_inception_row($row)
{
@@ -2414,7 +2423,6 @@ if (!function_exists('check_unit')) {
}
}
-
if (!function_exists('transform_si_excel_row_to_calculatable_format')) {
function transform_si_excel_row_to_calculatable_format(array $employee, array $employee_policy, array $maxage_and_maxcount, array $slab_details, string $applicable_slab_name, string $augmented_si, array $grid_master)
{
@@ -2874,3 +2882,458 @@ if (!function_exists('is_valid_or_empty_email')) {
}
}
+if (!function_exists('validatet_family_floter_rata_premium')) {
+ function validatet_family_floter_rata_premium($family){
+
+ // print_rr($family); die;
+ if (count($family) === 2) {
+ return $family; // skip if only two members
+ }
+
+ $excelCount = count(array_filter($family, fn($r) => ($r['data_from'] ?? '') === 'excel') ?? []);
+ $reset_family_premium = false;
+ $dependentRataGiven = false;
+
+ if($excelCount == 1){
+
+ $selfPremium = 0;
+ $familyPremium = 0;
+
+ foreach ($family as $row) {
+
+ // Get self premium
+ if (isset($row['relationship']) && strtolower($row['relationship']) == 'self') {
+ $selfPremium = (float) ($row['policy_details']['rata_premimum'] ?? 0);
+ }
+
+ // Sum the dependents premium
+ if (isset($row['relationship']) && strtolower($row['relationship']) !== 'self')
+ {
+ $familyPremium += (float) ($row['policy_details']['rata_premimum'] ?? 0);
+ }
+ }
+
+ if($selfPremium > $familyPremium || $selfPremium == $familyPremium){
+ $reset_family_premium = true;
+ }
+ }
+
+ foreach ($family as &$row) {
+
+ // Skip if the member is self
+ if (isset($row['relationship']) && strtolower($row['relationship']) == 'self') {
+ continue;
+ }
+
+ // For dependents
+ if (isset($row['temp']['premium_type']) && $row['temp']['premium_type'] == 1) {
+
+ if (!$dependentRataGiven && isset($row['data_from']) && $row['data_from'] === 'excel') {
+ // First eligible dependent keeps premium
+ $dependentRataGiven = true;
+ } else if(isset($row['data_from']) && $row['data_from'] === 'excel'){
+ $row['policy_details']['rata_premimum'] = 0;
+ $row['policy_details']['gst'] = 0;
+ }
+
+ if($reset_family_premium == true && isset($row['data_from']) && $row['data_from'] === 'excel'){
+ $row['policy_details']['rata_premimum'] = 0;
+ $row['policy_details']['gst'] = 0;
+ }
+
+ }
+
+ }
+
+ return $family;
+ }
+}
+
+
+if (!function_exists('validate_excel_value')) {
+ function validate_excel_value($value, $data_type, $format = null, $allowed_values = null)
+ {
+ switch ($data_type) {
+
+ case 'date':
+ return validate_date_value($value, $format);
+
+ case 'mobile':
+ return validate_mobile_value($value);
+
+ case 'email':
+ return validate_email_value($value);
+
+ case 'vehicle':
+ return validate_indian_vehicle_number($value);
+
+ default:
+ return [
+ 'status' => true,
+ 'error' => null
+ ];
+ }
+ }
+}
+
+if (!function_exists('validate_date_value')) {
+ function validate_date_value($value, $format)
+ {
+ if(empty($value)) {
+ return ['status' => true, 'error' => null]; // allow empty
+ }
+
+ $d = DateTime::createFromFormat($format, $value);
+
+ if ($d && $d->format($format) === $value) {
+ return ['status' => true, 'error' => null];
+ }
+
+ return [
+ 'status' => false,
+ 'error' => "Invalid date format. Expected format: {$format}"
+ ];
+ }
+}
+
+if (!function_exists('validate_mobile_value')) {
+ function validate_mobile_value($value)
+ {
+ if (preg_match('/^[0-9]{10}$/', $value)) {
+ return ['status' => true, 'error' => null];
+ }
+
+ return [
+ 'status' => false,
+ 'error' => "Invalid mobile number. Expected 10 digits."
+ ];
+ }
+}
+
+if (!function_exists('validate_email_value')) {
+ function validate_email_value($value)
+ {
+ if (filter_var($value, FILTER_VALIDATE_EMAIL)) {
+ return ['status' => true, 'error' => null];
+ }
+
+ return [
+ 'status' => false,
+ 'error' => "Invalid email address."
+ ];
+ }
+}
+
+if (!function_exists('validate_indian_vehicle_number')) {
+ function validate_indian_vehicle_number($number)
+ {
+ $number = strtoupper(trim($number));
+
+ // Normal Format:
+ // 2 letters (state) + 2 digits (district) + 1 or 2 letters (series) + 4 digits
+ $normalPattern = '/^[A-Z]{2}[0-9]{2}[A-Z]{1,2}[0-9]{4}$/';
+
+ // BH Series: 22BH1234AA
+ $bhPattern = '/^[0-9]{2}BH[0-9]{4}[A-Z]{2}$/';
+
+ if (preg_match($normalPattern, $number)) {
+ return ['status' => true, 'error' => null];
+ }
+
+ if (preg_match($bhPattern, $number)) {
+ return ['status' => true, 'error' => null];
+ }
+
+ return [
+ 'status' => false,
+ 'error' => "Invalid Vehicle Number"
+ ];
+ }
+}
+
+if (!function_exists('check_user_exist')) {
+ function check_user_exist($row, $col_key, $user_data)
+ {
+ // Get the uploaded value from the column
+ $input_value = trim($row[$col_key]);
+
+ // Loop DB user list
+ foreach ($user_data as $user) {
+
+ // Check if DB has 'first_name' key and matches input
+ if (isset($user['first_name']) && strtolower(trim($user['first_name'])) === strtolower($input_value)) {
+
+ return [
+ 'status' => true,
+ 'error' => null,
+ 'user' => $user,
+ ];
+ }
+ }
+
+ // If no user matched
+ return [
+ 'status' => false,
+ 'error' => "User '{$input_value}' not found in database."
+ ];
+ }
+}
+
+if (!function_exists('check_agent_exist')) {
+ function check_agent_exist($row, $agent_data)
+ {
+ // Get agent code from the uploaded row
+ $agent_code = trim($row[15]); // or use index if needed
+
+ // Loop agent data from DB
+ foreach ($agent_data as $agent) {
+ // Assuming DB keys: agent_code
+ if (isset($agent['agent_code']) && $agent['agent_code'] == $agent_code) {
+ return [
+ 'status' => true,
+ 'error' => null,
+ 'agent' => $agent,
+ ];
+ }
+ }
+
+ // If not matched
+ return [
+ 'status' => false,
+ 'error' => "Agent code '{$agent_code}' not found in database."
+ ];
+ }
+}
+
+if (!function_exists('check_rto_data')) {
+ function check_rto_data($row, $rto_master)
+ {
+ // Vehicle number from uploaded row
+ $vehicle_no = strtoupper(trim($row[2])); // Example: TN10AB1234
+
+ // Must be at least 4 characters to extract RTO
+ if (strlen($vehicle_no) < 4) {
+ return [
+ 'status' => false,
+ 'error' => "Invalid vehicle number format: '{$vehicle_no}'"
+ ];
+ }
+
+ // Extract State (first 2 letters) and RTO Code (next 2 digits)
+ $state_code = substr($vehicle_no, 0, 2); // TN
+ $rto_code = substr($vehicle_no, 2, 2); // 10
+
+ // Validate they are correct format
+ if (!ctype_alpha($state_code) || !ctype_digit($rto_code)) {
+ return [
+ 'status' => false,
+ 'error' => "Vehicle number '{$vehicle_no}' has invalid state or RTO code."
+ ];
+ }
+
+ // Loop RTO master data
+ foreach ($rto_master as $rto) {
+
+ // Expected DB fields: rto_state, rto_code
+ if (
+ isset($rto['rto_state']) &&
+ isset($rto['rto_code']) &&
+ strtoupper($rto['rto_state']) === $state_code &&
+ (string)$rto['rto_code'] === $rto_code
+ ) {
+ return [
+ 'status' => true,
+ 'error' => null,
+ 'rto_data' => $rto
+ ];
+ }
+ }
+
+ // Not found in RTO master
+ return [
+ 'status' => false,
+ 'error' => "RTO '{$state_code} {$rto_code}' not found in RTO master."
+ ];
+ }
+}
+
+if (!function_exists('check_vehicle_type')) {
+ function check_vehicle_type($row, $vehicle_type)
+ {
+ // Vehicle type from uploaded Excel row
+ $input_type = strtolower(trim($row[3])); // Example: CAR
+
+ // Loop vehicle type master
+ foreach ($vehicle_type as $vt) {
+
+ if (isset($vt['vehicle_type']) && strtolower($vt['vehicle_type']) == $input_type) {
+ return [
+ 'status' => true,
+ 'error' => null,
+ 'vehicle_type' => $vt,
+ ];
+ }
+ }
+
+ // Not found in master
+ return [
+ 'status' => false,
+ 'error' => "Vehicle type '{$input_type}' not found in master."
+ ];
+ }
+}
+
+if (!function_exists('check_policy_no')) {
+ function check_policy_no($row, $pt_data)
+ {
+ // Get policy number from Excel row
+ $policy_no = strtolower(trim($row[4]));
+
+ // Empty policy number
+ if ($policy_no === '') {
+ return [
+ 'status' => false,
+ 'error' => "Policy number is empty."
+ ];
+ }
+
+ // Loop all policy transactions (pt_data)
+ foreach ($pt_data as $pt) {
+
+ // Check policy_no exists in DB list
+ if (isset($pt['policy_no']) && strtolower($pt['policy_no']) == $policy_no) {
+ return [
+ 'status' => false,
+ 'error' => "Duplicate policy number '{$policy_no}' found in database."
+ ];
+ }
+ }
+
+ // If no match found → not duplicate
+ return [
+ 'status' => true,
+ 'error' => null
+ ];
+ }
+}
+
+if (!function_exists('check_insurer_exist')) {
+ function check_insurer_exist($row, $insurer_master)
+ {
+ // Get insurer short name from Excel row (col 7)
+ $short_name = strtolower(trim($row[7]));
+
+ foreach ($insurer_master as $insurer) {
+ if (
+ isset($insurer['short_name']) &&
+ strtolower($insurer['short_name']) === $short_name
+ ) {
+ return [
+ 'status' => true,
+ 'error' => null,
+ 'insurer' => $insurer // return entire insurer row for next validation
+ ];
+ }
+ }
+
+ return [
+ 'status' => false,
+ 'error' => "Insurer '{$short_name}' not found in database."
+ ];
+ }
+}
+
+if (!function_exists('check_insurer_branch_exist')) {
+ function check_insurer_branch_exist($row, $insurer_branch_master, $insurer)
+ {
+ // Get branch code from Excel row (col 8)
+ $branch_code = strtolower(trim($row[8]));
+
+ // Loop all branches
+ foreach ($insurer_branch_master as $branch) {
+
+ if (
+ isset($insurer['id']) && $branch['insurer_id'] == $insurer['id'] &&
+ strtolower($branch['branch_code']) == $branch_code
+ ) {
+ return [
+ 'status' => true,
+ 'error' => null,
+ 'branch' => $branch
+ ];
+ }
+ }
+
+ return [
+ 'status' => false,
+ 'error' => "Branch code '{$branch_code}' not found in database."
+ ];
+ }
+}
+
+if (!function_exists('check_nhance_branch')) {
+ function check_nhance_branch($row, $nhance_branch_master)
+ {
+ // Get branch name from Excel row (col 8)
+ $branch_name = strtolower(trim($row[1]));
+
+ // Loop all branches
+ foreach ($nhance_branch_master as $branch) {
+
+ if (
+ isset($branch['branch_name']) &&
+ strtolower($branch['branch_name']) == $branch_name
+ ) {
+ return [
+ 'status' => true,
+ 'error' => null,
+ 'branch' => $branch
+ ];
+ }
+ }
+
+ return [
+ 'status' => false,
+ 'error' => "Branch '{$branch_name}' not found in database."
+ ];
+ }
+}
+
+if (!function_exists('calculate_gst_amount')) {
+ function calculate_gst_amount($row) {
+
+ // Extract values
+ $base_premium = (float)trim($row[16]);
+ $non_commission_premium_amount = (float)trim($row[17]);
+ $tp_premium = (float)trim($row[18]);
+ $igst = (float)trim($row[19]);
+ $cgst = (float)trim($row[20]);
+ $sgst = (float)trim($row[21]);
+
+ // Total GST percentage
+ $gst_percentage = $igst + $cgst + $sgst;
+
+ // Step 1: Choose taxable amount
+ if ($non_commission_premium_amount > 0) {
+ // GST on non-commission premium
+ $taxable_amount = $non_commission_premium_amount;
+ } else {
+ // GST on base premium + TP premium
+ $taxable_amount = $base_premium + $tp_premium;
+ }
+
+ // Step 2: GST Amount calculation
+ $gst_amount = ($taxable_amount * $gst_percentage) / 100;
+
+ return round($gst_amount, 2);
+ }
+}
+
+
+
+
+
+
+
+
+
diff --git a/app/Helpers/sendMailNotification.php b/app/Helpers/sendMailNotification.php
index fae31ef5..cc46a3cd 100755
--- a/app/Helpers/sendMailNotification.php
+++ b/app/Helpers/sendMailNotification.php
@@ -381,7 +381,7 @@ class sendMailNotification
}
$table_content .= $policy_name_for_policy_type . '';
- $table_content .= '| Name | '; @@ -1554,7 +1554,7 @@ class sendMailNotification // Generate summary table for addon if applicable if (count($Addon_list) > 0) { $table_content .= '|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Name | '; @@ -1709,7 +1709,7 @@ class sendMailNotification // Generate summary table for addon if applicable if (count($Addon_list) > 0) { $table_content .= '||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Name | '; @@ -1865,7 +1865,7 @@ class sendMailNotification if (count($Addon_list) > 0) { $table_content .= '|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| " . $ct . ""; endif; ?> @@ -448,7 +449,7 @@ table.dataTable tbody td { |
" . $ut . "";
endif;
?>
@@ -486,6 +487,18 @@ table.dataTable tbody td {
+
+
+
+
+
+
+
@@ -849,6 +862,13 @@ table.dataTable tbody td {
var table;
$(document).ready(function () {
+ $('#nhance_branch_id').select2();
+
+ $('#nhance_branch_id')
+ .val(null) // ✅ MUST be null
+ .trigger('change.select2'); // ✅ correct trigger
+
+
var incentiveMonthPicker = flatpickr("#incentive_month", {
dateFormat: "Y-m-d", // real value stored (hidden)
altInput: true, // show a user-friendly display
@@ -858,9 +878,13 @@ table.dataTable tbody td {
table = $('#user-table').DataTable({
scrollX: true,
+ // dom: "<'row'<'col-sm-3'f><'col-sm-9'B>>" +
+ // "<'row'<'col-sm-12'tr>>" +
+ // "<'row'<'col-sm-5'i><'col-sm-7'p>>",
dom: "<'row'<'col-sm-3'f><'col-sm-9'B>>" +
- "<'row'<'col-sm-12'tr>>" +
- "<'row'<'col-sm-5'i><'col-sm-7'p>>",
+ "<'row'<'col-sm-12'tr>>" +
+ "<'row align-items-center'<'col-5 text-start'i><'col-7 d-flex justify-content-end align-items-center'<'me-2'l>p>>",
+ lengthMenu: [[10, 20, 50, 100], [10, 20, 50, 100]],
buttons: [
// {
// extend: 'collection',
@@ -983,6 +1007,18 @@ table.dataTable tbody td {
}
});
+ // IMPORTANT — DataTables draw event REF: TTS
+ table.on('draw.dt', function () {
+
+ let rowCount = $('#scroll-horizontal-datatable').DataTable().rows({ filter: 'applied' }).count();
+
+ if (rowCount <= 2) {
+ $('.dataTables_scrollBody').css('overflow', 'inherit');
+ } else {
+ $('.dataTables_scrollBody').css('overflow', 'auto');
+ }
+ });
+
$('#team').multiselect({
@@ -1022,7 +1058,8 @@ table.dataTable tbody td {
type: "GET",
dataType: 'json',
success: function (res) {
- console.log(res)
+ console.log(":():",res);
+ console.log(":():",res.data.nhance_branch_id);
$('#updateModal').modal('show');
$('#role').val('')
$('#UserForm').attr('action', '');
@@ -1033,6 +1070,18 @@ table.dataTable tbody td {
$('#mobile').val(res.data.mobile);
$('#emp_code').val(res.data.emp_code);
$('#role option[value="' + res.data.role + '"]').prop('selected', true);
+ if (res.data.nhance_branch_id !== null &&
+ res.data.nhance_branch_id !== "" &&
+ res.data.nhance_branch_id !== 0) {
+ $('#nhance_branch_id')
+ .val(res.data.nhance_branch_id)
+ .trigger('change.select2'); // ✅ correct trigger
+ } else {
+ $('#nhance_branch_id')
+ .val(null) // ✅ MUST be null
+ .trigger('change.select2'); // ✅ correct trigger
+ }
+
$('#btnSubmit').html('Update');
$.each(res.userTeamData, function(index, item) {
@@ -1769,6 +1818,7 @@ table.dataTable tbody td {
$('#email').val('');
$('#mobile').val('');
$('#emp_code').val('');
+ $('#nhance_branch_id').val('0');
$('#UserForm').attr('action', '');
let myModal = new bootstrap.Modal(document.getElementById('con-close-modal'));
myModal.show(); // open modal
diff --git a/app/Views/add_image_list.php b/app/Views/add_image_list.php
index 46332236..ff3770a1 100755
--- a/app/Views/add_image_list.php
+++ b/app/Views/add_image_list.php
@@ -16,6 +16,9 @@ table.dataTable thead th {
max-width: 98% !important;
}
+
+.dataTables_length label {height: 21px !important;}
+
@@ -36,9 +39,9 @@ table.dataTable thead th {
@@ -117,9 +119,13 @@ $(document).ready(function() {
if (ticketsTable.length) {
ticketsTable.DataTable({
scrollX: true,
+ // dom: "<'row'<'col-sm-2'f><'col-sm-10 text-right'B>>" + // Filter left, buttons right
+ // "<'row'<'col-sm-12'tr>>" +
+ // "<'row'<'col-sm-5'i><'col-sm-7'p>>", // Pagination at the bottom, without page length selector
dom: "<'row'<'col-sm-2'f><'col-sm-10 text-right'B>>" + // Filter left, buttons right
"<'row'<'col-sm-12'tr>>" +
- "<'row'<'col-sm-5'i><'col-sm-7'p>>", // Pagination at the bottom, without page length selector
+ "<'row align-items-center'<'col-5 text-start'i><'col-7 d-flex justify-content-end align-items-center'<'me-2'l>p>>",
+ lengthMenu: [[10, 20, 50, 100], [10, 20, 50, 100]],
buttons: [
{
extend: 'collection',
diff --git a/app/Views/bds_report_Insurer_wise_Data.php b/app/Views/bds_report_Insurer_wise_Data.php
index d020fb8c..b122a7e1 100644
--- a/app/Views/bds_report_Insurer_wise_Data.php
+++ b/app/Views/bds_report_Insurer_wise_Data.php
@@ -23,6 +23,7 @@ table.dataTable tbody td {
#scroll-horizontal-datatable tfoot .right-align-input {
text-align: right !important;
}
+.dataTables_length label {height: 21px !important;}
@@ -74,9 +75,13 @@ table.dataTable tbody td {
if (ticketsTable.length) {
ticketsTable.DataTable({
scrollX: true,
+ // dom: "<'row'<'col-sm-6'f><'col-sm-6 text-right'B>>" + // Filter left, buttons right
+ // "<'row'<'col-sm-12'tr>>" +
+ // "<'row'<'col-sm-5'i><'col-sm-7'p>>", // Pagination at the bottom, without page length selector
dom: "<'row'<'col-sm-6'f><'col-sm-6 text-right'B>>" + // Filter left, buttons right
- "<'row'<'col-sm-12'tr>>" +
- "<'row'<'col-sm-5'i><'col-sm-7'p>>", // Pagination at the bottom, without page length selector
+ "<'row'<'col-sm-12'tr>>" +
+ "<'row align-items-center'<'col-5 text-start'i><'col-7 d-flex justify-content-end align-items-center'<'me-2'l>p>>",
+ lengthMenu: [[10, 20, 50, 100], [10, 20, 50, 100]],
buttons: [
{
extend: 'collection',
diff --git a/app/Views/bds_report_bap_wise_data.php b/app/Views/bds_report_bap_wise_data.php
index 928ad3a4..812f0abf 100644
--- a/app/Views/bds_report_bap_wise_data.php
+++ b/app/Views/bds_report_bap_wise_data.php
@@ -23,6 +23,7 @@ table.dataTable tbody td {
#scroll-horizontal-datatable tfoot .right-align-input {
text-align: right !important;
}
+.dataTables_length label {height: 21px !important;}
@@ -76,9 +77,13 @@ table.dataTable tbody td {
if (ticketsTable.length) {
ticketsTable.DataTable({
scrollX: true,
+ // dom: "<'row'<'col-sm-6'f><'col-sm-6 text-right'B>>" + // Filter left, buttons right
+ // "<'row'<'col-sm-12'tr>>" +
+ // "<'row'<'col-sm-5'i><'col-sm-7'p>>", // Pagination at the bottom, without page length selector
dom: "<'row'<'col-sm-6'f><'col-sm-6 text-right'B>>" + // Filter left, buttons right
- "<'row'<'col-sm-12'tr>>" +
- "<'row'<'col-sm-5'i><'col-sm-7'p>>", // Pagination at the bottom, without page length selector
+ "<'row'<'col-sm-12'tr>>" +
+ "<'row align-items-center'<'col-5 text-start'i><'col-7 d-flex justify-content-end align-items-center'<'me-2'l>p>>",
+ lengthMenu: [[10, 20, 50, 100], [10, 20, 50, 100]],
buttons: [
{
extend: 'collection',
diff --git a/app/Views/bds_tat_wise_report.php b/app/Views/bds_tat_wise_report.php
index c47cc259..6d904cec 100644
--- a/app/Views/bds_tat_wise_report.php
+++ b/app/Views/bds_tat_wise_report.php
@@ -19,6 +19,7 @@
.right-align-input {
text-align: right;
}
+ .dataTables_length label {height: 21px !important;}
@@ -91,9 +92,9 @@
if (ticketsTable.length) {
ticketsTable.DataTable({
scrollX: true,
- dom: "<'row'<'col-sm-6'f><'col-sm-6 text-right'B>>" +
- "<'row'<'col-sm-12'tr>>" +
- "<'row'<'col-sm-5'i><'col-sm-7'p>>",
+ // dom: "<'row'<'col-sm-6'f><'col-sm-6 text-right'B>>" +
+ // "<'row'<'col-sm-12'tr>>" +
+ // "<'row'<'col-sm-5'i><'col-sm-7'p>>",
// buttons: [
// {
// extend: 'csv',
@@ -107,6 +108,10 @@
// },
// ],
+ dom: "<'row'<'col-sm-6'f><'col-sm-6 text-right'B>>" +
+ "<'row'<'col-sm-12'tr>>" +
+ "<'row align-items-center'<'col-5 text-start'i><'col-7 d-flex justify-content-end align-items-center'<'me-2'l>p>>",
+ lengthMenu: [[10, 20, 50, 100], [10, 20, 50, 100]],
buttons: [
{
extend: 'collection',
diff --git a/app/Views/business_team_list.php b/app/Views/business_team_list.php
index 3aeb2ed0..3a91bf1e 100644
--- a/app/Views/business_team_list.php
+++ b/app/Views/business_team_list.php
@@ -43,6 +43,7 @@
color: #16181b !important;
cursor: pointer !important;
}
+ .dataTables_length label {height: 21px !important;}
@@ -338,9 +339,13 @@
if (ticketsTable.length) {
ticketsTable.DataTable({
+ // dom: "<'row'<'col-sm-6'f><'col-sm-6 text-right'B>>" + // Filter left, buttons right
+ // "<'row'<'col-sm-12'tr>>" +
+ // "<'row'<'col-sm-5'i><'col-sm-7'p>>", // Pagination at the bottom, without page length selector
dom: "<'row'<'col-sm-6'f><'col-sm-6 text-right'B>>" + // Filter left, buttons right
- "<'row'<'col-sm-12'tr>>" +
- "<'row'<'col-sm-5'i><'col-sm-7'p>>", // Pagination at the bottom, without page length selector
+ "<'row'<'col-sm-12'tr>>" +
+ "<'row align-items-center'<'col-5 text-start'i><'col-7 d-flex justify-content-end align-items-center'<'me-2'l>p>>",
+ lengthMenu: [[10, 20, 50, 100], [10, 20, 50, 100]],
buttons: [
{
extend: 'collection',
diff --git a/app/Views/cd_master_list.php b/app/Views/cd_master_list.php
index c0ff4584..139a0c75 100755
--- a/app/Views/cd_master_list.php
+++ b/app/Views/cd_master_list.php
@@ -17,6 +17,8 @@ table.dataTable thead th {
max-width: 98% !important;
}
+.column-header {margin-right: 10px;}
+
.custom-dropdown-menu {
display: none;
position: absolute;
@@ -49,6 +51,8 @@ table.dataTable thead th {
.dataTables_filter {
position: absolute;
}
+.dataTables_length label {height: 21px !important;}
+
@@ -70,15 +74,15 @@ table.dataTable thead th {
+
+
+
+
+
+
+
+
diff --git a/app/Views/hr_activity_history.php b/app/Views/hr_activity_history.php
index 8f52d592..00b45f96 100644
--- a/app/Views/hr_activity_history.php
+++ b/app/Views/hr_activity_history.php
@@ -47,6 +47,8 @@ table.dataTable tbody td {
#hr_activity_history_append_area tbody tr {
background-color: transparent !important;
}
+.dataTables_length label {height: 21px !important;}
+
@@ -98,12 +100,26 @@ $(document).ready(function () {
var table = ticketsTable.DataTable({
scrollX: true,
+ // dom: "<'row'<'col-12 d-flex justify-content-between align-items-center'<'datatable-search dataTables_filter'f><'datatable-buttons dt-buttons'B>>>" +
+ // "<'row'<'col-sm-12'tr>>" +
+ // "<'row'<'col-sm-5'i><'col-sm-7'p>>",
dom: "<'row'<'col-12 d-flex justify-content-between align-items-center'<'datatable-search dataTables_filter'f><'datatable-buttons dt-buttons'B>>>" +
"<'row'<'col-sm-12'tr>>" +
- "<'row'<'col-sm-5'i><'col-sm-7'p>>",
+ "<'row align-items-center'<'col-5 text-start'i><'col-7 d-flex justify-content-end align-items-center'<'me-2'l>p>>",
+ lengthMenu: [[10, 20, 50, 100], [10, 20, 50, 100]],
language: {
- search: "_INPUT_",
- searchPlaceholder: "Search..."
+ search: `
+
+ _INPUT_
+
+
+
+
+ `,
+ searchPlaceholder: "Search",
+ emptyTable: 'No Data found '
},
paging: true,
pageLength: 10,
diff --git a/app/Views/hr_file_upload.php b/app/Views/hr_file_upload.php
index 9d5cf1e5..5df2f43e 100644
--- a/app/Views/hr_file_upload.php
+++ b/app/Views/hr_file_upload.php
@@ -3,6 +3,8 @@
padding: 5px 7px 5px 0 !important;
color: #000000;
}
+ .dataTables_length label {height: 21px !important;}
+
@@ -143,7 +145,7 @@
|
|
- | ' . $file['first_name'] . '' ?> |
+ ' . $file['first_name'] . '' ?> |
|
|
@@ -182,9 +185,13 @@
$(document).ready(function() {
$('#tickets-table').DataTable({
+ // dom: "<'row'<'col-12 d-flex justify-content-between align-items-center'<'datatable-search dataTables_filter'f><'datatable-buttons dt-buttons'B>>>" +
+ // "<'row'<'col-sm-12'tr>>" +
+ // "<'row'<'col-sm-5'i><'col-sm-7'p>>",
dom: "<'row'<'col-12 d-flex justify-content-between align-items-center'<'datatable-search dataTables_filter'f><'datatable-buttons dt-buttons'B>>>" +
- "<'row'<'col-sm-12'tr>>" +
- "<'row'<'col-sm-5'i><'col-sm-7'p>>",
+ "<'row'<'col-sm-12'tr>>" +
+ "<'row align-items-center'<'col-5 text-start'i><'col-7 d-flex justify-content-end align-items-center'<'me-2'l>p>>",
+ lengthMenu: [[10, 20, 50, 100], [10, 20, 50, 100]],
buttons: [
{
text: ' Add ',
diff --git a/app/Views/insurer_or_tpa_data.php b/app/Views/insurer_or_tpa_data.php
index 33e34bf2..902e5419 100755
--- a/app/Views/insurer_or_tpa_data.php
+++ b/app/Views/insurer_or_tpa_data.php
@@ -101,13 +101,13 @@
-
+
@@ -171,10 +171,10 @@
$(document).ready(function() {
- // var policy_issue_datePicker = flatpickr("#policy_issue_date", {
- // dateFormat: "d/m/Y",
- // allowInput: false,
- // });
+ var policy_issue_datePicker = flatpickr("#policy_issue_date", {
+ dateFormat: "d/m/Y",
+ allowInput: false,
+ });
$('#insurer_or_tpa, #action_type').on('change', togglePolicyIssueDate);
});
@@ -796,15 +796,15 @@
function togglePolicyIssueDate() {
let insurer = $('#insurer_or_tpa').val();
let action = $('#action_type').val();
- // if (insurer === 'insurer' && action === 'import') {
- // $('.policy_issue_date_row').show();
- // $('#policy_issue_date').attr('required', true);
- // $('#policy_issue_date_label').html('Policy Issue Date *');
- // } else {
- // $('.policy_issue_date_row').hide();
- // $('#policy_issue_date').removeAttr('required').val('');
- // $('#policy_issue_date_label').text('Policy Issue Date');
- // }
+ if (insurer === 'insurer' && action === 'import') {
+ $('.policy_issue_date_row').show();
+ $('#policy_issue_date').attr('required', true);
+ $('#policy_issue_date_label').html('Policy Issue Date *');
+ } else {
+ $('.policy_issue_date_row').hide();
+ $('#policy_issue_date').removeAttr('required').val('');
+ $('#policy_issue_date_label').text('Policy Issue Date');
+ }
}
function fetchTpaIdFromTpa(){
diff --git a/app/Views/insurer_statement_list.php b/app/Views/insurer_statement_list.php
index 197d19ed..3728bfff 100644
--- a/app/Views/insurer_statement_list.php
+++ b/app/Views/insurer_statement_list.php
@@ -164,6 +164,15 @@
margin-left: 5px;
border-radius: 6px;
}
+ th.no-sort {
+ pointer-events: none; /* disable click */
+ }
+
+ th.no-sort:before,
+ th.no-sort:after {
+ display: none !important; /* hide DataTables sorting arrows */
+ }
+
@@ -205,11 +214,12 @@
+
+
-
+
+
+
+
+
+
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||