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 .= '';
+                        $table_content .= '
'; // Add text-align: center to the table head $table_content .= ''; @@ -518,7 +518,7 @@ class sendMailNotification } $table_content .= $policy_name_for_policy_type . ' ( Payable By Employee ) '; - $table_content .= '
'; + $table_content .= '
'; // Add text-align: center to the table head $table_content .= ''; @@ -555,7 +555,7 @@ class sendMailNotification if (count($Addon_list) > 0) { $table_content .= '
'; - $table_content .= '
'; + $table_content .= '
'; // Center align for table header and body $table_content .= ''; @@ -738,7 +738,7 @@ class sendMailNotification } $table_content .= $policy_name_for_policy_type . ''; - $table_content .= '
'; + $table_content .= '
'; // Add text-align: center to the table head $table_content .= ''; @@ -824,7 +824,7 @@ class sendMailNotification } $table_content .= $policy_name_for_policy_type . ' ( Payable By Employee ) '; - $table_content .= '
'; + $table_content .= '
'; // Add text-align: center to the table head $table_content .= ''; @@ -862,7 +862,7 @@ class sendMailNotification if (count($Addon_list) > 0) { $table_content .= '
'; - $table_content .= '
'; + $table_content .= '
'; // Center align for table header and body $table_content .= ''; @@ -1046,7 +1046,7 @@ class sendMailNotification } $table_content .= $policy_name_for_policy_type . ''; - $table_content .= '
'; + $table_content .= '
'; // Add text-align: center to the table head $table_content .= ''; @@ -1132,7 +1132,7 @@ class sendMailNotification } $table_content .= $policy_name_for_policy_type . ' ( Payable By Employee ) '; - $table_content .= '
'; + $table_content .= '
'; // Add text-align: center to the table head $table_content .= ''; @@ -1169,7 +1169,7 @@ class sendMailNotification if (count($Addon_list) > 0) { $table_content .= '
'; - $table_content .= '
'; + $table_content .= '
'; // Center align for table header and body $table_content .= ''; @@ -1502,7 +1502,7 @@ class sendMailNotification // Start table row $table_content .= $policy_name . ''; - $table_content .= '
'; + $table_content .= '
'; $table_content .= ''; $table_content .= ''; $table_content .= ''; @@ -1554,7 +1554,7 @@ class sendMailNotification // Generate summary table for addon if applicable if (count($Addon_list) > 0) { $table_content .= '
'; - $table_content .= '
Name
'; + $table_content .= '
'; $table_content .= ''; $table_content .= ''; @@ -1657,7 +1657,7 @@ class sendMailNotification // Start table row $table_content .= $policy_name . ''; - $table_content .= '
'; + $table_content .= '
'; $table_content .= ''; $table_content .= ''; $table_content .= ''; @@ -1709,7 +1709,7 @@ class sendMailNotification // Generate summary table for addon if applicable if (count($Addon_list) > 0) { $table_content .= '
'; - $table_content .= '
Name
'; + $table_content .= '
'; $table_content .= ''; $table_content .= ''; @@ -1812,7 +1812,7 @@ class sendMailNotification // Start table row $table_content .= $policy_name . ''; - $table_content .= '
'; + $table_content .= '
'; $table_content .= ''; $table_content .= ''; $table_content .= ''; @@ -1865,7 +1865,7 @@ class sendMailNotification if (count($Addon_list) > 0) { $table_content .= '
'; - $table_content .= '
Name
'; + $table_content .= '
'; $table_content .= ''; $table_content .= ''; @@ -1900,7 +1900,7 @@ class sendMailNotification $mail_content = str_replace(["[[member_summary]]", "{{member_summary}}"], $table_content , $mail_content); $mail_content = preg_replace('/]*>( |\s)*<\/p>/i', '', $mail_content); - + $data['params'] = $params;$data['client_logo'] = $client_logo; $data['mail_content'] = $mail_content; $mail_content = view('mail_template', $data); diff --git a/app/Libraries/RuleImportService.php b/app/Libraries/RuleImportService.php index 3e471f57..33fdab3d 100644 --- a/app/Libraries/RuleImportService.php +++ b/app/Libraries/RuleImportService.php @@ -62,6 +62,7 @@ class RuleImportService protected array $expectedColumns; protected array $columnValidators; + protected array $incomingData; protected string $annotatedDir; protected string $department; protected string $uploadedCommissionFileID; @@ -148,7 +149,7 @@ class RuleImportService { // dd($params); $startTime = microtime(true); - + $this->incomingData = $params; try { $this->department = $params['department']; $this->uploadedCommissionFileID = $params['id']; @@ -898,13 +899,33 @@ class RuleImportService */ protected function convertRowToRule(array $rowData): array { + $temp_rule_id = $this->generateRuleId($rowData); + //rule_e07f52d4366a2_32_oct2025_3_com + + $conditions = $this->buildConditions($rowData); + // $temp_rule_id .= '_'.$this->incomingData['id'].'_'. strtolower(date('MY')).'_'.(count($conditions)); + $monthFormatted = strtoupper(date('M', strtotime($this->incomingData['commission_month']))) + . date('Y', strtotime($this->incomingData['commission_month'])); + + $temp_rule_id .= '_'.$this->incomingData['id'].'_'.$monthFormatted; + $calculation = $this->buildCalculation($rowData); + + + // $temp_rule_id .= '_'.substr($calculation['type'], 0, 3); + $rule = [ - 'id' => $this->generateRuleId($rowData), + 'id' => $temp_rule_id, 'name' => $this->sanitize($rowData[self::COL_RULE_NAME] ?? ''), 'department' => $this->department, + 'is_deleted' => false, 'file_id' => $this->uploadedCommissionFileID, - 'conditions' => $this->buildConditions($rowData), - 'calculation' => $this->buildCalculation($rowData) + 'conditions' => $conditions, + 'calculation' => $calculation, + 'created_at' => date('Y-m-d H:i:s'), + 'updated_at' => date('Y-m-d H:i:s'), + 'created_by' => $this->incomingData['created_by'], + 'updated_by' => $this->incomingData['created_by'], + ]; return $rule; @@ -1090,31 +1111,31 @@ class RuleImportService if ($weightMin !== '' && $weightMax !== '') { if ($weightMin === $weightMax) { $conditions[] = [ - 'field' => 'vehicle_weight', + 'field' => 'weight', 'operator' => '==', 'value' => (float)$weightMin ]; } else { $conditions[] = [ - 'field' => 'vehicle_weight', + 'field' => 'weight', 'operator' => '>=', 'value' => (float)$weightMin ]; $conditions[] = [ - 'field' => 'vehicle_weight', + 'field' => 'weight', 'operator' => '<=', 'value' => (float)$weightMax ]; } } elseif ($weightMin !== '') { $conditions[] = [ - 'field' => 'vehicle_weight', + 'field' => 'weight', 'operator' => '>=', 'value' => (float)$weightMin ]; } elseif ($weightMax !== '') { $conditions[] = [ - 'field' => 'vehicle_weight', + 'field' => 'weight', 'operator' => '<=', 'value' => (float)$weightMax ]; @@ -1126,13 +1147,13 @@ class RuleImportService if (count($states) > 1) { $conditions[] = [ - 'field' => 'rto_state', + 'field' => 'geo_rto_state', 'operator' => 'in', 'value' => $states ]; } else { $conditions[] = [ - 'field' => 'rto_state', + 'field' => 'geo_rto_state', 'operator' => '==', 'value' => $states[0] ]; @@ -1145,13 +1166,13 @@ class RuleImportService if (count($cities) > 1) { $conditions[] = [ - 'field' => 'rto_city', + 'field' => 'geo_rto_city', 'operator' => 'in', 'value' => $cities ]; } else { $conditions[] = [ - 'field' => 'rto_city', + 'field' => 'geo_rto_city', 'operator' => '==', 'value' => $cities[0] ]; @@ -1170,7 +1191,7 @@ class RuleImportService // Policy Name if (!empty($rowData[self::COL_POLICY_NAME])) { $conditions[] = [ - 'field' => 'policy_name', + 'field' => 'product', 'operator' => '==', 'value' => $this->sanitize($rowData[self::COL_POLICY_NAME]) ]; diff --git a/app/Models/BDSDumpModel.php b/app/Models/BDSDumpModel.php new file mode 100644 index 00000000..d89da194 --- /dev/null +++ b/app/Models/BDSDumpModel.php @@ -0,0 +1,55 @@ +join('policy_type pt','client_policy.policy_type_id = pt.id') ->where('client_policy.client_id',$client['id']) ->where('client_policy.is_active', 1) - ->where('client_policy.policy_status', 1) + // ->where('client_policy.policy_status', 1) ->findAll(); $client['policies'] = $clientPolicies; @@ -239,5 +239,24 @@ class ClientModel extends Model return $builder->getNumRows() > 0 ? true : false; } + + + public function getClientIdBasedonLoggedInSessionID() + { + $user_id = get_session_userid(); + $builder = $this->db->table('client_rm rm') + ->select('c.id AS client_id') + ->join('clients c', 'c.id = rm.client_id', 'inner') + ->where('rm.is_active', 1) + ->where('c.is_active', 1) + ->where('rm.user_id', $user_id) + ->get(); + $result = $builder->getResultArray(); + + $clientIds = !empty($result) ? array_column($result, 'client_id') : []; + // print_r($clientIds);die; + return $clientIds; + } + } diff --git a/app/Models/ClientPolicyModel.php b/app/Models/ClientPolicyModel.php index 2d37d053..14685074 100755 --- a/app/Models/ClientPolicyModel.php +++ b/app/Models/ClientPolicyModel.php @@ -133,7 +133,7 @@ class ClientPolicyModel extends Model ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') ->join('client_branch', 'client_branch.id = client_policy.client_branch_id') ->where('client_policy.client_id', $client_id) - ->where('client_policy.policy_status', 1) + // ->where('client_policy.policy_status', 1) ->where('client_policy.is_active', 1) ->get() ->getResult(); diff --git a/app/Models/EmployeeModel.php b/app/Models/EmployeeModel.php index 7f210ca7..b9adb13f 100755 --- a/app/Models/EmployeeModel.php +++ b/app/Models/EmployeeModel.php @@ -275,8 +275,8 @@ class EmployeeModel extends Model ->join('employee_polices', 'employees.id = employee_polices.employee_id', 'left') ->where('employees.is_active', 1) ->where('employee_polices.is_active', 1) - ->where('employees.emp_status', "active") - ->where('employee_polices.status', "active") + ->whereIn('employees.emp_status', ['active', 'expired']) + ->whereIn('employee_polices.status', ['active', 'expired']) ->where('employees.emp_code', $emp_code); if(!empty($client_id)){ diff --git a/app/Models/InvoiceItemModel.php b/app/Models/InvoiceItemModel.php index 328be1d9..2533dd0f 100644 --- a/app/Models/InvoiceItemModel.php +++ b/app/Models/InvoiceItemModel.php @@ -38,4 +38,29 @@ class InvoiceItemModel extends Model protected $validationMessages = []; protected $skipValidation = false; + + protected $beforeInsert = ["checkAndAddCreatedByValue"]; + protected $beforeUpdate = ["checkAndUpdateUpdatedByValue"]; + + protected function checkAndAddCreatedByValue(array $data) + { + // Check if 'updated_by' value is null or empty + if (empty($data['data']['created_by'])) { + // Set 'updated_by' value to the current session user ID + $data['data']['created_by'] = get_session_userid(); + } + + return $data; + } + + protected function checkAndUpdateUpdatedByValue(array $data) + { + // Check if 'updated_by' value is null or empty + if (empty($data['data']['updated_by'])) { + // Set 'updated_by' value to the current session user ID + $data['data']['updated_by'] = get_session_userid(); + } + + return $data; + } } diff --git a/app/Models/InvoiceModel.php b/app/Models/InvoiceModel.php index 49d91ced..dcbd93fc 100644 --- a/app/Models/InvoiceModel.php +++ b/app/Models/InvoiceModel.php @@ -29,7 +29,7 @@ class InvoiceModel extends Model protected $useTimestamps = false; protected $createdField = 'created_at'; protected $updatedField = 'updated_at'; - + // Validation (optional) protected $validationRules = [ 'invoice_no' => 'required|max_length[100]', @@ -101,7 +101,7 @@ class InvoiceModel extends Model -- Payout status CASE WHEN payout_status = 1 THEN 'Pending' - WHEN payout_status = 2 THEN 'Complete' + WHEN payout_status = 2 THEN 'Completed' END AS status_text, partner_agent.name as agent_name @@ -143,9 +143,12 @@ class InvoiceModel extends Model return $return_data; } - public function agentList() + public function agentList($params = []) { - return $this->db->table('partner_agent')->where('is_active', 1)->get()->getResultArray(); + if(isset($params['is_active'])){ + return $this->db->table('partner_agent')->where('is_active', $params['is_active'])->get()->getResultArray(); + } + return $this->db->table('partner_agent')->get()->getResultArray(); } public function utrSummary($invoice_id) @@ -175,7 +178,7 @@ class InvoiceModel extends Model -- Payout status CASE WHEN payout_status = 1 THEN 'Pending' - WHEN payout_status = 2 THEN 'Complete' + WHEN payout_status = 2 THEN 'Completed' END AS status_text, partner_agent.name as agent_name @@ -187,4 +190,67 @@ class InvoiceModel extends Model return $data; } + + + public function payoutList($flag, $agentId = null, $invoiceId = null) + { + $builder = $this->db->table('policy_transaction pt') + ->select(' + pt.id, + pt.policy_no AS policyNo, + pt.agent_id AS agentId, + pp.insured_name AS customer, + pp.premium_amount AS premium, + COALESCE(pii.commission_amount, pp.commission_amount) AS commission, + pp.issued_date AS date_db, + DATE_FORMAT(pp.issued_date, "%d/%m/%Y") AS date, + pii.id AS invoiceItemId, + pii.commission_amount as paid_amount, + pi.payout_status, + pp.id as partner_policy_id, + pp.policy_transaction_id + ') + ->join('partner_invoice_items pii','pii.policy_no = pt.policy_no','left') + ->join('partner_invoice pi','pi.id = pii.invoice_id','left') + ->join('partner_policy pp','pt.policy_no = pp.policy_number AND pt.agent_id = pp.agent_id AND pt.id = pp.policy_transaction_id') + ->where('pt.is_active',1) + ->where('pt.agent_id IS NOT NULL'); + + if ($flag == 1) { // Add mode + // EXCLUDE all policies that exist in partner_invoice_items + $builder->where("pt.id NOT IN (SELECT policy_id FROM partner_invoice_items)", null, false); + } + + if ($flag == 2) { // Edit mode + // Policies belonging to a specific invoice + $builder->where('pii.is_active',1); + if ($invoiceId) { + $builder->where('pi.id', $invoiceId); // only policies of this invoice + } + if ($agentId) { + $builder->where('pt.agent_id', $agentId); + } + } + + if ($flag == 3) { // Extra policies + // Policies not assigned to any invoice + $builder->where('pii.id IS NULL', null, false); + if ($agentId) { + $builder->where('pt.agent_id', $agentId); + } + } + + return $builder->get()->getResultArray(); + } + + public function agentListById($agentId) + { + return $this->db->table('partner_agent') + ->where('id', $agentId) + ->where('is_active', 1) + ->get() + ->getRowArray(); + } + + } diff --git a/app/Models/LeadsModel.php b/app/Models/LeadsModel.php index d3c9ac40..1c028645 100644 --- a/app/Models/LeadsModel.php +++ b/app/Models/LeadsModel.php @@ -107,6 +107,7 @@ class LeadsModel extends Model 'quote_received_insurer', 'acm_id', 'policy_with_correction', + 'agreed_percentage', ]; diff --git a/app/Models/PTCOShareDetailsModel.php b/app/Models/PTCOShareDetailsModel.php index 1b2c84fd..dc4e9953 100644 --- a/app/Models/PTCOShareDetailsModel.php +++ b/app/Models/PTCOShareDetailsModel.php @@ -68,6 +68,8 @@ class PTCOShareDetailsModel extends Model 'non_comm_per_amt', 'cotp_amt', 'cotep_amt', + 'pt_policy_issue_date', + 'file_id', ]; public function getNonReconcileredPolicyTransactions(string $insurer_id,string $insurer_branch_id) diff --git a/app/Models/PolicyTransactionModel.php b/app/Models/PolicyTransactionModel.php index 7f3ca607..1d752149 100644 --- a/app/Models/PolicyTransactionModel.php +++ b/app/Models/PolicyTransactionModel.php @@ -81,6 +81,10 @@ 'install_due_date', 'policy_with_corr', 'is_cd_reduce_from_bds', + 'agent_id', + 'agent_code', + 'file_id', + 'entry_from', ]; @@ -593,7 +597,7 @@ // return $result; // } - public function getBDSReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0, $user_id = 0, $where = []) + public function getBDSReportList1($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0, $user_id = 0, $where = []) { $date_condition = ''; @@ -652,7 +656,7 @@ ROUND((ROUND((pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 2) + ROUND((ROUND((pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 2) * 18 / 100), 2)), 2) AS total_premium_velmurugan, - ROUND(COALESCE(tep_gst_amt, 0) + COALESCE(bp_gst_amt, 0) + COALESCE(tp_amt, 0),2) AS gst_amount, + ROUND(COALESCE(tep_gst_amt, 0) + COALESCE(bp_gst_amt, 0) + COALESCE(tp_gst_amt, 0),2) AS gst_amount, ROUND(ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) + ROUND(COALESCE(tep_gst_amt, 0) + COALESCE(bp_gst_amt, 0) + COALESCE(tp_amt, 0),2), @@ -665,6 +669,7 @@ (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per) AS agreed_tp_or_ter_per, pt_co_share_details.agreed_bp_per, + ROUND( ( SELECT @@ -686,6 +691,7 @@ ), 2 ) AS total_irda_amt, + ROUND( ( SELECT @@ -725,7 +731,6 @@ AND insurer_statements.is_active = 1 AND insurer_statements.invoice_status IS NOT NULL $date_condition - ), 2 ) AS billed_amt, @@ -772,7 +777,9 @@ ), 2 ) AS unbilled_amt, + created_user.first_name as user_name, + CASE WHEN pt_co_share_details.co_share_type IN (0, 1) THEN policy_transaction.policy_no @@ -826,8 +833,16 @@ $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); - $builder->where('policy_transaction.' . $date_type . '>=', $startDate) - ->where('policy_transaction.' . $date_type . '<=', $endDate); + // $builder->where('policy_transaction.' . $date_type . '>=', $startDate) + // ->where('policy_transaction.' . $date_type . '<=', $endDate); + + if($date_type == "policy_issue_date"){ + $builder->where("pt_co_share_details.pt_policy_issue_date >=", $startDate) + ->where("pt_co_share_details.pt_policy_issue_date <=", $endDate); + }else{ + $builder->where('policy_transaction.' . $date_type . '>=', $startDate) + ->where('policy_transaction.' . $date_type . '<=', $endDate); + } } // if($date_type == 'statement_month' && $start_date != 0 && $end_date != 0){ @@ -1043,8 +1058,18 @@ // Optimize Date Filtering if (!empty($start_date) && !empty($end_date) && !empty($date_type)) { - $builder->where("policy_transaction.$date_type >=", date('Y-m-d 00:00:00', strtotime($start_date))) - ->where("policy_transaction.$date_type <=", date('Y-m-d 23:59:59', strtotime($end_date))); + + $startDate = change_date_format($start_date, 'd/m/Y', 'Y-m-d 00:00:00'); + $endDate = change_date_format($end_date, 'd/m/Y', 'Y-m-d 23:59:59'); + + if($date_type == "policy_issue_date"){ + $builder->where("pt_co_share_details.pt_policy_issue_date >=", $startDate) + ->where("pt_co_share_details.pt_policy_issue_date <=", $endDate); + + }else{ + $builder->where("policy_transaction.$date_type >=", $startDate) + ->where("policy_transaction.$date_type <=", $startDate); + } } // Apply Filters Only When Necessary @@ -1080,6 +1105,7 @@ // Optimize Query Execution $builder->orderBy('policy_transaction.id', 'desc'); $data = $builder->get()->getResultArray(); + // dd($this->db->getLastQuery()); return $data; } @@ -1134,11 +1160,17 @@ if ($start_date != 0 && $end_date != 0 && $date_type != 0) { - $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); - $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); + $startDate = change_date_format($start_date, 'd/m/Y', 'Y-m-d 00:00:00'); + $endDate = change_date_format($end_date, 'd/m/Y', 'Y-m-d 23:59:59'); + + if($date_type == "policy_issue_date"){ + $builder->where("pt_co_share_details.pt_policy_issue_date >=", $startDate) + ->where("pt_co_share_details.pt_policy_issue_date <=", $endDate); + }else{ + $builder->where('policy_transaction.' . $date_type . '>=', $startDate) + ->where('policy_transaction.' . $date_type . '<=', $endDate); + } - $builder->where('policy_transaction.' . $date_type . '>=', $startDate) - ->where('policy_transaction.' . $date_type . '<=', $endDate); } else { // $fromDate = date('Y-m-d', strtotime('-30 days')); @@ -1177,7 +1209,7 @@ } $builder->orderBy('policy_transaction.id', 'desc'); - + // dd($this->db->getLastQuery()); return $builder->get()->getResultArray(); } @@ -1315,8 +1347,17 @@ $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); - $builder->where('policy_transaction.' . $date_type . '>=', $startDate) - ->where('policy_transaction.' . $date_type . '<=', $endDate); + // $builder->where('policy_transaction.' . $date_type . '>=', $startDate) + // ->where('policy_transaction.' . $date_type . '<=', $endDate); + + if($date_type == "policy_issue_date"){ + $builder->where("pt_co_share_details.pt_policy_issue_date >=", $startDate) + ->where("pt_co_share_details.pt_policy_issue_date <=", $endDate); + }else{ + $builder->where('policy_transaction.' . $date_type . '>=', $startDate) + ->where('policy_transaction.' . $date_type . '<=', $endDate); + } + } else { $fromDate = date('Y-m-d', strtotime('-90 days')); @@ -1356,8 +1397,10 @@ $builder->orderBy('policy_transaction.id', 'desc'); + $return_data = $builder->get()->getResultArray(); + // dd(db_connect()->getLastQuery()); - return $builder->get()->getResultArray(); + return $return_data; } public function getBusinessReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) @@ -1418,8 +1461,16 @@ $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); - $builder->where('policy_transaction.' . $date_type . '>=', $startDate) - ->where('policy_transaction.' . $date_type . '<=', $endDate); + // $builder->where('policy_transaction.' . $date_type . '>=', $startDate) + // ->where('policy_transaction.' . $date_type . '<=', $endDate); + + if($date_type == "policy_issue_date"){ + $builder->where("pt_co_share_details.pt_policy_issue_date >=", $startDate) + ->where("pt_co_share_details.pt_policy_issue_date <=", $endDate); + }else{ + $builder->where('policy_transaction.' . $date_type . '>=', $startDate) + ->where('policy_transaction.' . $date_type . '<=', $endDate); + } } else { $fromDate = date('Y-m-d', strtotime('-90 days')); @@ -1521,8 +1572,17 @@ $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); - $builder->where('policy_transaction.' . $date_type . '>=', $startDate) - ->where('policy_transaction.' . $date_type . '<=', $endDate); + // $builder->where('policy_transaction.' . $date_type . '>=', $startDate) + // ->where('policy_transaction.' . $date_type . '<=', $endDate); + + if($date_type == "policy_issue_date"){ + $builder->where("pt_co_share_details.pt_policy_issue_date >=", $startDate) + ->where("pt_co_share_details.pt_policy_issue_date <=", $endDate); + }else{ + $builder->where('policy_transaction.' . $date_type . '>=', $startDate) + ->where('policy_transaction.' . $date_type . '<=', $endDate); + } + } else { $fromDate = date('Y-m-d', strtotime('-90 days')); @@ -1627,8 +1687,16 @@ $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); - $builder->where('policy_transaction.' . $date_type . '>=', $startDate) - ->where('policy_transaction.' . $date_type . '<=', $endDate); + // $builder->where('policy_transaction.' . $date_type . '>=', $startDate) + // ->where('policy_transaction.' . $date_type . '<=', $endDate); + + if($date_type == "policy_issue_date"){ + $builder->where("pt_co_share_details.pt_policy_issue_date >=", $startDate) + ->where("pt_co_share_details.pt_policy_issue_date <=", $endDate); + }else{ + $builder->where('policy_transaction.' . $date_type . '>=', $startDate) + ->where('policy_transaction.' . $date_type . '<=', $endDate); + } } else { $fromDate = date('Y-m-d', strtotime('-90 days')); $toDate = date('Y-m-d 23:59:59'); @@ -1826,8 +1894,9 @@ $client_policy_id = 0, $user_id = 0, $where = [] - ) { - + ) + { + $date_condition = ''; // ============================== @@ -1835,9 +1904,9 @@ // ============================== if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) { $date_condition = " - AND insurer_statements_oq.month >= '{$start_date}' - AND insurer_statements_oq.month <= '{$end_date}' - "; + AND insurer_statements_oq.month >= '{$start_date}' + AND insurer_statements_oq.month <= '{$end_date}' + "; } // ============================== @@ -1852,92 +1921,92 @@ $builder2 = $this->db->table('policy_transaction') ->select(" - policy_transaction.id AS id, - policy_transaction.endorsement_no AS endorsement_no, - policy_transaction.ref AS ref, - DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date, + policy_transaction.id AS id, + policy_transaction.endorsement_no AS endorsement_no, + policy_transaction.ref AS ref, + DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date, - DATE_FORMAT( policy_transaction.policy_issue_date, '%b %Y') AS policy_issue_month, + DATE_FORMAT( policy_transaction.policy_issue_date, '%b %Y') AS policy_issue_month, - CASE - WHEN 1 = 1 THEN 'no statement uploaded' - ELSE 'statement uploaded' - END AS statement_uploaded , + CASE + WHEN 1 = 1 THEN 'no statement uploaded' + ELSE 'statement uploaded' + END AS statement_uploaded , - CASE - WHEN clients.client_type = 1 THEN 'Group' - WHEN clients.client_type = 2 THEN 'Retail' - ELSE '-' - END AS client_type, + CASE + WHEN clients.client_type = 1 THEN 'Group' + WHEN clients.client_type = 2 THEN 'Retail' + ELSE '-' + END AS client_type, - CASE - WHEN policy_transaction.revenue_type = 'NA' THEN 'Fresh' - ELSE 'Renewal' - END AS revenue_type, + CASE + WHEN policy_transaction.revenue_type = 'NA' THEN 'Fresh' + ELSE 'Renewal' + END AS revenue_type, - CASE - WHEN policy_transaction.action_type = 'inception' THEN 'Policy' - ELSE 'Endorsement' - END AS action_type, + CASE + WHEN policy_transaction.action_type = 'inception' THEN 'Policy' + ELSE 'Endorsement' + END AS action_type, - clients.client_name AS client_name, - clients.short_name AS client_short_name, - client_branch.branch_name AS client_branch_name, - client_branch.address1 AS client_address, - policy_type.policy_type, - policy_type.bap, - insurers.name AS insurer_name, - insurers.short_name AS insurer_short_name, - insurer_branch.branch_name AS insurer_branch_name, - insurer_branch.branch_code AS insurer_branch_code, - user_profiles.first_name AS user_name, - vehicle.vehicle_no, - tpa.name AS tpa_name, - pt_co_share_details.remark AS remarks, - pt_co_share_details.cop_amt AS bp_amt, - pt_co_share_details.exp_amt, - pt_co_share_details.id AS pt_id, - sales_user.first_name AS salse_person_name, - service_user.first_name AS service_person_name, + clients.client_name AS client_name, + clients.short_name AS client_short_name, + client_branch.branch_name AS client_branch_name, + client_branch.address1 AS client_address, + policy_type.policy_type, + policy_type.bap, + insurers.name AS insurer_name, + insurers.short_name AS insurer_short_name, + insurer_branch.branch_name AS insurer_branch_name, + insurer_branch.branch_code AS insurer_branch_code, + user_profiles.first_name AS user_name, + vehicle.vehicle_no, + tpa.name AS tpa_name, + pt_co_share_details.remark AS remarks, + pt_co_share_details.cop_amt AS bp_amt, + pt_co_share_details.exp_amt, + pt_co_share_details.id AS pt_id, + sales_user.first_name AS salse_person_name, + service_user.first_name AS service_person_name, - ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) AS premium_wo_gst, - ROUND((ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) * 18 / 100), 2) AS gst_amount, - ROUND( - ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) + - ROUND((ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) * 18 / 100), 2), - 2) AS total_premium, + ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) AS premium_wo_gst, + ROUND((ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) * 18 / 100), 2) AS gst_amount, + ROUND( + ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) + + ROUND((ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) * 18 / 100), 2), + 2) AS total_premium, - ROUND(pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) AS tp_or_ter, - DATEDIFF(policy_transaction.policy_end_date, CURDATE()) AS days, - (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per) AS agreed_tp_or_ter_per, - pt_co_share_details.agreed_bp_per, + ROUND(pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) AS tp_or_ter, + DATEDIFF(policy_transaction.policy_end_date, CURDATE()) AS days, + (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per) AS agreed_tp_or_ter_per, + pt_co_share_details.agreed_bp_per, - -- ============================== - -- SUBQUERY: Total IRDA Amount - -- Alias Agreed Amount ...!! - -- ============================== - ROUND(pt_co_share_details.exp_amt, 2) AS total_irda_amt, + -- ============================== + -- SUBQUERY: Total IRDA Amount + -- Alias Agreed Amount ...!! + -- ============================== + ROUND(pt_co_share_details.exp_amt, 2) AS total_irda_amt, - -- Reward Only - ROUND(0, 2) AS reward, + -- Reward Only + ROUND(0, 2) AS reward, - -- Billed Amount - ROUND(0, 2) AS billed_amt, + -- Billed Amount + ROUND(0, 2) AS billed_amt, - created_user.first_name AS user_name, + created_user.first_name AS user_name, - CASE - WHEN pt_co_share_details.co_share_type IN (0, 1) THEN policy_transaction.policy_no - WHEN pt_co_share_details.co_share_type > 1 THEN - CASE - WHEN pt_co_share_details.follower_policy_no IS NULL OR pt_co_share_details.follower_policy_no = '' - THEN policy_transaction.policy_no - ELSE pt_co_share_details.follower_policy_no - END - ELSE policy_transaction.policy_no - END AS policy_no - ") + CASE + WHEN pt_co_share_details.co_share_type IN (0, 1) THEN policy_transaction.policy_no + WHEN pt_co_share_details.co_share_type > 1 THEN + CASE + WHEN pt_co_share_details.follower_policy_no IS NULL OR pt_co_share_details.follower_policy_no = '' + THEN policy_transaction.policy_no + ELSE pt_co_share_details.follower_policy_no + END + ELSE policy_transaction.policy_no + END AS policy_no + ") // ============================== // JOINS @@ -1955,15 +2024,16 @@ ->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left') ->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left') ->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left') - ->join('user_profiles AS created_user', 'policy_transaction.created_by = created_user.id', 'left') - + ->join('user_profiles AS created_user', 'policy_transaction.created_by = created_user.id', 'left') + ->where('policy_transaction.is_active', 1) ->where('pt_co_share_details.is_active', 1) - // ======================================================== - // GROUP BY Insurer Statement Months - // ======================================================= - ->groupBy('policy_transaction.policy_no , pt_co_share_details.insurer_id '); + // ======================================================== + // GROUP BY Insurer Statement Months + // ======================================================= + // ->groupBy('policy_transaction.policy_no , pt_co_share_details.insurer_id ') + ; // ============================== // ROLE-BASED FILTERS @@ -1994,7 +2064,7 @@ $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); $builder2->where("policy_transaction.{$date_type} >=", $startDate) - ->where("policy_transaction.{$date_type} <=", $endDate); + ->where("policy_transaction.{$date_type} <=", $endDate); } @@ -2014,10 +2084,10 @@ // DEFAULT 90-DAY FILTER // ============================== if ( - $client_id == 0 && - $insurer_id == 0 && - $policy_type_id == 0 && - $date_type == 0 && + $client_id == 0 && + $insurer_id == 0 && + $policy_type_id == 0 && + $date_type == 0 && $issuer == 0 ) { $fromDate = date('Y-m-d', strtotime('-90 days')); @@ -2025,7 +2095,7 @@ if (empty($where)) { $builder2->where('policy_transaction.created_at >=', $fromDate) - ->where('policy_transaction.created_at <=', $toDate); + ->where('policy_transaction.created_at <=', $toDate); } } @@ -2055,123 +2125,123 @@ $builder = $this->db->table('policy_transaction') ->select(" - policy_transaction.id AS id, - policy_transaction.endorsement_no AS endorsement_no, - policy_transaction.ref AS ref, - DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date, - DATE_FORMAT( - IF(insurer_statements_oq.month IS NULL, - policy_transaction.policy_issue_date, - insurer_statements_oq.month - ), '%b %Y' - ) AS policy_issue_month, + policy_transaction.id AS id, + policy_transaction.endorsement_no AS endorsement_no, + policy_transaction.ref AS ref, + DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date, + DATE_FORMAT( + IF(insurer_statements_oq.month IS NULL, + policy_transaction.policy_issue_date, + insurer_statements_oq.month + ), '%b %Y' + ) AS policy_issue_month, - CASE - WHEN insurer_statements_oq.month IS NULL THEN 'no statement uploaded' - ELSE 'statement uploaded' - END AS statement_uploaded , + CASE + WHEN insurer_statements_oq.month IS NULL THEN 'no statement uploaded' + ELSE 'statement uploaded' + END AS statement_uploaded , - CASE - WHEN clients.client_type = 1 THEN 'Group' - WHEN clients.client_type = 2 THEN 'Retail' - ELSE '-' - END AS client_type, + CASE + WHEN clients.client_type = 1 THEN 'Group' + WHEN clients.client_type = 2 THEN 'Retail' + ELSE '-' + END AS client_type, - CASE - WHEN policy_transaction.revenue_type = 'NA' THEN 'Fresh' - ELSE 'Renewal' - END AS revenue_type, + CASE + WHEN policy_transaction.revenue_type = 'NA' THEN 'Fresh' + ELSE 'Renewal' + END AS revenue_type, - CASE - WHEN policy_transaction.action_type = 'inception' THEN 'Policy' - ELSE 'Endorsement' - END AS action_type, + CASE + WHEN policy_transaction.action_type = 'inception' THEN 'Policy' + ELSE 'Endorsement' + END AS action_type, - clients.client_name AS client_name, - clients.short_name AS client_short_name, - client_branch.branch_name AS client_branch_name, - client_branch.address1 AS client_address, - policy_type.policy_type, - policy_type.bap, - insurers.name AS insurer_name, - insurers.short_name AS insurer_short_name, - insurer_branch.branch_name AS insurer_branch_name, - insurer_branch.branch_code AS insurer_branch_code, - user_profiles.first_name AS user_name, - vehicle.vehicle_no, - tpa.name AS tpa_name, - pt_co_share_details.remark AS remarks, - pt_co_share_details.cop_amt AS bp_amt, - pt_co_share_details.exp_amt, - pt_co_share_details.id AS pt_id, - sales_user.first_name AS salse_person_name, - service_user.first_name AS service_person_name, + clients.client_name AS client_name, + clients.short_name AS client_short_name, + client_branch.branch_name AS client_branch_name, + client_branch.address1 AS client_address, + policy_type.policy_type, + policy_type.bap, + insurers.name AS insurer_name, + insurers.short_name AS insurer_short_name, + insurer_branch.branch_name AS insurer_branch_name, + insurer_branch.branch_code AS insurer_branch_code, + user_profiles.first_name AS user_name, + vehicle.vehicle_no, + tpa.name AS tpa_name, + pt_co_share_details.remark AS remarks, + pt_co_share_details.cop_amt AS bp_amt, + pt_co_share_details.exp_amt, + pt_co_share_details.id AS pt_id, + sales_user.first_name AS salse_person_name, + service_user.first_name AS service_person_name, - ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) AS premium_wo_gst, - ROUND((ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) * 18 / 100), 2) AS gst_amount, - ROUND( - ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) + - ROUND((ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) * 18 / 100), 2), - 2) AS total_premium, + ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) AS premium_wo_gst, + ROUND((ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) * 18 / 100), 2) AS gst_amount, + ROUND( + ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) + + ROUND((ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) * 18 / 100), 2), + 2) AS total_premium, - ROUND(pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) AS tp_or_ter, - DATEDIFF(policy_transaction.policy_end_date, CURDATE()) AS days, - (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per) AS agreed_tp_or_ter_per, - pt_co_share_details.agreed_bp_per, + ROUND(pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) AS tp_or_ter, + DATEDIFF(policy_transaction.policy_end_date, CURDATE()) AS days, + (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per) AS agreed_tp_or_ter_per, + pt_co_share_details.agreed_bp_per, - -- ============================== - -- SUBQUERY: Total IRDA Amount - -- Alias Agreed Amount ...!! - -- ============================== - ROUND(pt_co_share_details.exp_amt, 2) AS total_irda_amt, - -- Reward Only - ROUND(( - SELECT SUM(co_share_stmt_details.reward) - FROM co_share_stmt_details - JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id - WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id - AND co_share_stmt_details.is_active = 1 - AND insurer_statements.is_active = 1 - AND insurer_statements.month = insurer_statements_oq.month - {$date_condition} - GROUP BY('policy_transaction.policy_no , insurer_statements.month , pt_co_share_details.insurer_id') - ), 2) AS reward, + -- ============================== + -- SUBQUERY: Total IRDA Amount + -- Alias Agreed Amount ...!! + -- ============================== + ROUND(pt_co_share_details.exp_amt, 2) AS total_irda_amt, + -- Reward Only + ROUND(( + SELECT SUM(co_share_stmt_details.reward) + FROM co_share_stmt_details + JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id + WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id + AND co_share_stmt_details.is_active = 1 + AND insurer_statements.is_active = 1 + AND insurer_statements.month = insurer_statements_oq.month + {$date_condition} + GROUP BY('policy_transaction.policy_no , insurer_statements.month , pt_co_share_details.insurer_id') + ), 2) AS reward, - -- Billed Amount - ROUND(( - SELECT SUM( - COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) + - COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) + - COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) + - COALESCE(co_share_stmt_details.reward, 0) - ) - FROM co_share_stmt_details - JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id - JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id - WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id - AND co_share_stmt_details.is_active = 1 - AND pt_table.is_active = 1 - AND insurer_statements.is_active = 1 - AND insurer_statements.invoice_status IS NOT NULL - AND insurer_statements.month = insurer_statements_oq.month - {$date_condition} - GROUP BY('policy_transaction.policy_no , insurer_statements.month , pt_co_share_details.insurer_id') - ), 2) AS billed_amt, + -- Billed Amount + ROUND(( + SELECT SUM( + COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) + + COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) + + COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) + + COALESCE(co_share_stmt_details.reward, 0) + ) + FROM co_share_stmt_details + JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id + JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id + WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id + AND co_share_stmt_details.is_active = 1 + AND pt_table.is_active = 1 + AND insurer_statements.is_active = 1 + AND insurer_statements.invoice_status IS NOT NULL + AND insurer_statements.month = insurer_statements_oq.month + {$date_condition} + GROUP BY('policy_transaction.policy_no , insurer_statements.month , pt_co_share_details.insurer_id') + ), 2) AS billed_amt, - created_user.first_name AS user_name, + created_user.first_name AS user_name, - CASE - WHEN pt_co_share_details.co_share_type IN (0, 1) THEN policy_transaction.policy_no - WHEN pt_co_share_details.co_share_type > 1 THEN - CASE - WHEN pt_co_share_details.follower_policy_no IS NULL OR pt_co_share_details.follower_policy_no = '' - THEN policy_transaction.policy_no - ELSE pt_co_share_details.follower_policy_no - END - ELSE policy_transaction.policy_no - END AS policy_no - ") + CASE + WHEN pt_co_share_details.co_share_type IN (0, 1) THEN policy_transaction.policy_no + WHEN pt_co_share_details.co_share_type > 1 THEN + CASE + WHEN pt_co_share_details.follower_policy_no IS NULL OR pt_co_share_details.follower_policy_no = '' + THEN policy_transaction.policy_no + ELSE pt_co_share_details.follower_policy_no + END + ELSE policy_transaction.policy_no + END AS policy_no + ") // ============================== // JOINS @@ -2189,12 +2259,12 @@ ->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left') ->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left') ->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left') - ->join('user_profiles AS created_user', 'policy_transaction.created_by = created_user.id', 'left') - - - ->join('co_share_stmt_details', 'pt_co_share_details.id = co_share_stmt_details.co_share_id','left') - ->join('insurer_statements insurer_statements_oq','insurer_statements_oq.id = co_share_stmt_details.statement_id','left') - + ->join('user_profiles AS created_user', 'policy_transaction.created_by = created_user.id', 'left') + + + ->join('co_share_stmt_details', 'pt_co_share_details.id = co_share_stmt_details.co_share_id', 'left') + ->join('insurer_statements insurer_statements_oq', 'insurer_statements_oq.id = co_share_stmt_details.statement_id', 'left') + ->where('policy_transaction.is_active', 1) ->where('pt_co_share_details.is_active', 1) ->where('co_share_stmt_details.is_active', 1) @@ -2202,10 +2272,11 @@ ->where('insurer_statements_oq.id IS NOT NULL') - // ======================================================== - // GROUP BY Insurer Statement Months - // ======================================================= - ->groupBy('policy_transaction.policy_no , pt_co_share_details.insurer_id ,insurer_statements_oq.month'); + // ======================================================== + // GROUP BY Insurer Statement Months + // ======================================================= + // ->groupBy('policy_transaction.policy_no , pt_co_share_details.insurer_id ,insurer_statements_oq.month') + ; // ============================== // ROLE-BASED FILTERS @@ -2236,7 +2307,7 @@ $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); $builder->where("policy_transaction.{$date_type} >=", $startDate) - ->where("policy_transaction.{$date_type} <=", $endDate); + ->where("policy_transaction.{$date_type} <=", $endDate); } // JOIN FOR STATEMENT MONTH FILTER @@ -2245,11 +2316,11 @@ $endDate = date('Y-m-d', strtotime($end_date)); $builder->join('co_share_stmt_details cssdfilter', 'pt_co_share_details.id = cssdfilter.co_share_id', 'left') - ->join('insurer_statements', 'cssdfilter.statement_id = insurer_statements.id', 'left') - ->where('insurer_statements.is_active', 1) - ->where('insurer_statements.month >=', $startDate) - ->where('insurer_statements.month <=', $endDate) - ->groupBy('cssdfilter.co_share_id'); + ->join('insurer_statements', 'cssdfilter.statement_id = insurer_statements.id', 'left') + ->where('insurer_statements.is_active', 1) + ->where('insurer_statements.month >=', $startDate) + ->where('insurer_statements.month <=', $endDate) + ->groupBy('cssdfilter.co_share_id'); } // ============================== @@ -2268,10 +2339,10 @@ // DEFAULT 90-DAY FILTER // ============================== if ( - $client_id == 0 && - $insurer_id == 0 && - $policy_type_id == 0 && - $date_type == 0 && + $client_id == 0 && + $insurer_id == 0 && + $policy_type_id == 0 && + $date_type == 0 && $issuer == 0 ) { $fromDate = date('Y-m-d', strtotime('-90 days')); @@ -2279,7 +2350,7 @@ if (empty($where)) { $builder->where('policy_transaction.created_at >=', $fromDate) - ->where('policy_transaction.created_at <=', $toDate); + ->where('policy_transaction.created_at <=', $toDate); } } @@ -2290,17 +2361,428 @@ $sql1 = $builder2->getCompiledSelect(); $sql2 = $builder->getCompiledSelect(); - $finalSql = "($sql1) UNION ALL ($sql2) - ORDER BY policy_no DESC, insurer_branch_name ASC, statement_uploaded ASC, - STR_TO_DATE(policy_issue_month, '%b %Y') ASC"; + $finalSql = "($sql1) UNION ALL ($sql2) + ORDER BY policy_no DESC, insurer_branch_name ASC, statement_uploaded ASC, + STR_TO_DATE(policy_issue_month, '%b %Y') ASC"; $result = $this->db->query($finalSql)->getResultArray(); - + // dd($this->db->getLastQuery()); return $result; - } + public function getBDSReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0, $user_id = 0, $where = []) + { + + $statement_month_condition = ''; + if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) { + $statement_month_condition = " + WHERE statement_month >= '" . $start_date . "' + AND statement_month <= '" . $end_date . "' + "; + } + + $default_date_filter = ''; + if ($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0) { + + $fromDate = date('Y-m-d', strtotime('-90 days')); + $toDate = date('Y-m-d 23:59:59'); + + if (empty($where)) { + + $default_date_filter = " + AND pt.created_at >= '" . $fromDate . "' + AND pt.created_at <= '" . $toDate . "' + "; + } + } + + $conditions = ""; // start safely + + // 1. Role-based restrictions + if ( + (!in_array(get_role_id(), [1, 5])) && + !( + in_array(MANAGEMENT_TEAM_ID, user_team()) || + in_array(FINANCE_TEAM_ID, user_team()) || + in_array(BUSINESS_TEAM_ID, user_team()) + ) + ) { + if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) { + $conditions .= " AND pt.created_by = " . get_session_userid(); + } + } + + // 2. Dynamic $where array + if (!empty($where)) { + foreach ($where as $column => $value) { + $value = addslashes($value); + $conditions .= " AND `$column` = '$value' "; + } + } + + // 3. Date condition (except statement_month) + if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') { + + $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); + $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); + + if ($date_type === "policy_issue_date") { + $conditions .= " AND pcsd.pt_policy_issue_date >= '$startDate' "; + $conditions .= " AND pcsd.pt_policy_issue_date <= '$endDate' "; + } else { + $conditions .= " AND pt.$date_type >= '$startDate' "; + $conditions .= " AND pt.$date_type <= '$endDate' "; + } + } + + // 4. Common filters + if ($client_id != 0) { + $conditions .= " AND pt.client_id = $client_id "; + } + + if ($insurer_id != 0) { + $conditions .= " AND pt.insurer_id = $insurer_id "; + } + + if ($client_branch_id != 0) { + $conditions .= " AND pt.client_branch_id = $client_branch_id "; + } + + if ($insurer_branch_id != 0) { + $conditions .= " AND pt.insurer_branch_id = $insurer_branch_id "; + } + + if ($client_policy_id != 0) { + $conditions .= " AND pt.client_policy_id = $client_policy_id "; + } + + if ($user_id != 0) { + $conditions .= " AND pt.created_by = $user_id "; + } + + if ($policy_type_id != 0) { + $conditions .= " AND pt.policy_type_id = $policy_type_id "; + } + + if ($issuer != 0) { + $conditions .= " AND pt.issuer = $issuer "; + } + + + $sql = " + SELECT * FROM ( + + SELECT + pt.id AS id, + pt.endorsement_no, + pt.ref, + DATE_FORMAT(pt.policy_issue_date, '%d %b %Y') AS policy_issue_date, + DATE_FORMAT(pcsd.pt_policy_issue_date, '%b %Y') AS policy_issue_month, + pt.month as statement_month, + + 'no statement uploaded' AS statement_uploaded, + + CASE + WHEN c.client_type = 1 THEN 'Group' + WHEN c.client_type = 2 THEN 'Retail' + ELSE '-' + END AS client_type, + + CASE + WHEN pt.revenue_type = 'NA' THEN 'Fresh' + ELSE 'Renewal' + END AS revenue_type, + + CASE + WHEN pt.action_type = 'inception' THEN 'Policy' + ELSE 'Endorsement' + END AS action_type, + + pt.action_type as action_type_string, + + c.client_name, + c.short_name AS client_short_name, + cb.branch_name AS client_branch_name, + cb.address1 AS client_address, + ptype.policy_type, + ptype.bap, + ins.name AS insurer_name, + ins.short_name AS insurer_short_name, + ib.branch_name AS insurer_branch_name, + ib.branch_code AS insurer_branch_code, + + created_user.first_name AS user_name, + v.vehicle_no, + tpa.name AS tpa_name, + + pcsd.remark AS remarks, + pcsd.cop_amt AS bp_amt, + pcsd.exp_amt, + pcsd.id AS pt_id, + + su.first_name AS salse_person_name, + se.first_name AS service_person_name, + + ROUND(pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt, 2) AS premium_wo_gst, + ROUND((pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt) * 0.18, 2) AS gst_amount, + ROUND((pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt) * 1.18, 2) AS total_premium, + + ROUND(pcsd.cotp_amt + pcsd.cotep_amt, 2) AS tp_or_ter, + DATEDIFF(pt.policy_end_date, CURDATE()) AS days, + (pcsd.agreed_tp_per + pcsd.agreed_tep_per) AS agreed_tp_or_ter_per, + pcsd.agreed_bp_per, + + ROUND(pcsd.exp_amt, 2) AS total_irda_amt, + 0.00 AS reward, + 0.00 AS billed_amt, + + CASE + WHEN pcsd.co_share_type IN (0,1) THEN pt.policy_no + WHEN pcsd.co_share_type > 1 THEN + IFNULL(NULLIF(pcsd.follower_policy_no,''), pt.policy_no) + ELSE pt.policy_no + END AS policy_no + + FROM policy_transaction pt + LEFT JOIN pt_co_share_details pcsd ON pt.id = pcsd.pt_id + JOIN clients c ON c.id = pt.client_id + LEFT JOIN client_branch cb ON pt.client_branch_id = cb.id + LEFT JOIN client_policy cp ON pt.client_policy_id = cp.id + LEFT JOIN user_profiles up ON pt.created_by = up.id + LEFT JOIN vehicle v ON pt.vehicle_id = v.id + LEFT JOIN policy_type ptype ON pt.policy_type_id = ptype.id + LEFT JOIN insurers ins ON pcsd.insurer_id = ins.id + LEFT JOIN insurer_branch ib ON pcsd.insurer_branch_id = ib.id + LEFT JOIN tpa ON pt.tpa_id = tpa.id + LEFT JOIN tpa_branch tb ON pt.tpa_branch_id = tb.id + LEFT JOIN user_profiles su ON pt.sales_generated_by = su.id + LEFT JOIN user_profiles se ON pt.serviced_by = se.id + LEFT JOIN user_profiles created_user ON pt.created_by = created_user.id + + WHERE pt.is_active = 1 + AND pcsd.is_active = 1 + $default_date_filter + $conditions + + GROUP BY pt.policy_no, pt.endorsement_no, pcsd.insurer_id + + UNION ALL + + SELECT + pt.id AS id, + pt.endorsement_no, + pt.ref, + DATE_FORMAT(pt.policy_issue_date, '%d %b %Y') AS policy_issue_date, + DATE_FORMAT(IF(insq.month IS NULL, pcsd.pt_policy_issue_date, insq.month),'%b %Y') AS policy_issue_month, + insq.month as statement_month, + + 'statement uploaded' AS statement_uploaded, + + CASE + WHEN c.client_type = 1 THEN 'Group' + WHEN c.client_type = 2 THEN 'Retail' + ELSE '-' + END AS client_type, + + CASE + WHEN pt.revenue_type = 'NA' THEN 'Fresh' + ELSE 'Renewal' + END AS revenue_type, + + CASE + WHEN pt.action_type = 'inception' THEN 'Policy' + ELSE 'Endorsement' + END AS action_type, + + pt.action_type as action_type_string, + + c.client_name, + c.short_name AS client_short_name, + cb.branch_name AS client_branch_name, + cb.address1 AS client_address, + ptype.policy_type, + ptype.bap, + ins.name AS insurer_name, + ins.short_name AS insurer_short_name, + ib.branch_name AS insurer_branch_name, + ib.branch_code AS insurer_branch_code, + + CASE + WHEN + IFNULL(cssd.actual_tep_brokerage_amt,0) = 0 AND + IFNULL(cssd.actual_tp_brokerage_amt,0) = 0 AND + IFNULL(cssd.actual_bp_brokerage_amt,0) = 0 AND + IFNULL(cssd.reward,0) != 0 + THEN 'Rewards' + ELSE created_user.first_name + END AS user_name, + + v.vehicle_no, + tpa.name AS tpa_name, + + pcsd.remark AS remarks, + pcsd.cop_amt AS bp_amt, + pcsd.exp_amt, + pcsd.id AS pt_id, + + su.first_name AS salse_person_name, + se.first_name AS service_person_name, + + ROUND(pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt,2) AS premium_wo_gst, + ROUND((pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt) * 0.18,2) AS gst_amount, + ROUND((pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt) * 1.18,2) AS total_premium, + + ROUND(pcsd.cotp_amt + pcsd.cotep_amt,2) AS tp_or_ter, + DATEDIFF(pt.policy_end_date, CURDATE()) AS days, + (pcsd.agreed_tp_per + pcsd.agreed_tep_per) AS agreed_tp_or_ter_per, + pcsd.agreed_bp_per, + + CASE + WHEN insq.month = pt.month THEN pcsd.exp_amt + ELSE 0 + END AS total_irda_amt_2, + + COALESCE(( + SELECT SUM(cs.reward) + FROM co_share_stmt_details cs + JOIN insurer_statements i ON cs.statement_id = i.id + WHERE cs.co_share_id = pcsd.id AND i.month = insq.month + AND i.is_active = 1 + AND cs.is_active = 1 + GROUP BY pt.policy_no, i.month, pcsd.insurer_id + ),0) AS reward, + + COALESCE(( + SELECT SUM( + COALESCE(cs.actual_bp_brokerage_amt,0) + + COALESCE(cs.actual_tp_brokerage_amt,0) + + COALESCE(cs.actual_tep_brokerage_amt,0) + + COALESCE(cs.reward,0) + ) + FROM co_share_stmt_details cs + JOIN insurer_statements i ON cs.statement_id = i.id + WHERE cs.co_share_id = pcsd.id + AND i.invoice_status IS NOT NULL + AND i.month = insq.month + AND i.is_active = 1 + AND cs.is_active = 1 + GROUP BY pt.policy_no, i.month, pcsd.insurer_id + ),0) AS billed_amt, + + CASE + WHEN pcsd.co_share_type IN (0,1) THEN pt.policy_no + WHEN pcsd.co_share_type > 1 + THEN IFNULL(NULLIF(pcsd.follower_policy_no,''), pt.policy_no) + ELSE pt.policy_no + END AS policy_no + + FROM policy_transaction pt + LEFT JOIN pt_co_share_details pcsd ON pt.id = pcsd.pt_id + LEFT JOIN co_share_stmt_details cssd ON pcsd.id = cssd.co_share_id + LEFT JOIN insurer_statements insq ON cssd.statement_id = insq.id + JOIN clients c ON c.id = pt.client_id + LEFT JOIN client_branch cb ON pt.client_branch_id = cb.id + LEFT JOIN client_policy cp ON pt.client_policy_id = cp.id + LEFT JOIN user_profiles up ON pt.created_by = up.id + LEFT JOIN vehicle v ON pt.vehicle_id = v.id + LEFT JOIN policy_type ptype ON pt.policy_type_id = ptype.id + LEFT JOIN insurers ins ON pcsd.insurer_id = ins.id + LEFT JOIN insurer_branch ib ON pcsd.insurer_branch_id = ib.id + LEFT JOIN tpa ON pt.tpa_id = tpa.id + LEFT JOIN tpa_branch tb ON pt.tpa_branch_id = tb.id + LEFT JOIN user_profiles su ON pt.sales_generated_by = su.id + LEFT JOIN user_profiles se ON pt.serviced_by = se.id + LEFT JOIN user_profiles created_user ON pt.created_by = created_user.id + + WHERE pt.is_active = 1 + AND pcsd.is_active = 1 + AND cssd.is_active = 1 + AND insq.is_active = 1 + $default_date_filter + $conditions + + GROUP BY pt.policy_no, pt.endorsement_no, pcsd.insurer_id, insq.month + + ) AS final_result + + $statement_month_condition + -- GROUP BY statement_month, insurer_name, policy_no + -- WHERE id = 6063 + + ORDER BY + id DESC, + policy_no ASC, + insurer_branch_name ASC, + statement_uploaded ASC, + statement_month ASC, + STR_TO_DATE(policy_issue_month, '%b %Y') ASC + "; + $query = $this->db->query($sql); + $result = $query->getResultArray(); + // dd($result); + // dd($this->db->getLastQuery()); + + $keys = []; + $filtered = []; + + foreach ($result as $row) { + + $endorsement_number = "-"; + if(!empty($row['endorsement_no'])){ + $endorsement_number = $row['endorsement_no']; + } + + $key = $row['statement_month'].'|'.$row['insurer_name'].'|'.$row['policy_no'] . '|' . $endorsement_number; + + // If uploaded record exists, always keep it and override previous + if ($row['statement_uploaded'] === 'statement uploaded') { + $filtered[$key] = $row; // overwrite no-statement row if it exists + $keys[$key] = true; + + } + // Keep "no statement uploaded" only if uploaded one not added yet + elseif (!isset($keys[$key])) { + $filtered[$key] = $row; + } + } + + $result = array_values($filtered); + // dd($result); + + $runningBilled = []; + $totalIrdaMap = []; + $final = []; + + foreach ($result as $row) { + $ptId = $row['pt_id']; + + // Store total_irda_amt only once (first non-zero value) + if (!isset($totalIrdaMap[$ptId]) && $row['total_irda_amt'] > 0) { + $totalIrdaMap[$ptId] = $row['total_irda_amt']; + } + + // Initialize running sum + if (!isset($runningBilled[$ptId])) { + $runningBilled[$ptId] = 0; + } + + // Add billed amount to running total + $runningBilled[$ptId] += (float)$row['billed_amt']; + + // Calculate unbilled amount + $row['unbilled_amount'] = ($totalIrdaMap[$ptId] ?? 0) - $runningBilled[$ptId] ; + + $final[] = $row; + } + + $result = $final; + + // print_rr($result); die; + return $result; + } + + diff --git a/app/Models/TicketMasterModel.php b/app/Models/TicketMasterModel.php index 05196827..bf40409b 100644 --- a/app/Models/TicketMasterModel.php +++ b/app/Models/TicketMasterModel.php @@ -793,7 +793,26 @@ class TicketMasterModel extends Model //api public function get_ticket_data($emp_id, $returnType,$ticket_type = null, $ticket_id = null) { - $query = $this->select('ticket_master.*, tms.mail_subject as subject, tms.id as ticket_message_id') + $query = $this->select(" + + ticket_master.*, + tms.mail_subject as subject, + tms.id as ticket_message_id, + ( + SELECT th1.old_value + FROM ticket_history th1 + JOIN ticket_claim_status tcs ON th1.old_value = tcs.id + WHERE th1.field_name = 'claim_status_id' + AND th1.ticket_id = ticket_master.id + AND th1.id = ( + SELECT MAX(th2.id) + FROM ticket_history th2 + WHERE th2.ticket_id = th1.ticket_id + AND th2.field_name = 'claim_status_id' + ) + ) AS old_status_id + + ") ->join('ticket_messages tms', 'ticket_master.id = tms.ticket_id', 'left') ->where('ticket_master.is_active', 1); $query->whereIn('sender', ['staff', 'user']); diff --git a/app/Models/UserModel.php b/app/Models/UserModel.php index 8a5eff7d..20baa54c 100755 --- a/app/Models/UserModel.php +++ b/app/Models/UserModel.php @@ -27,6 +27,7 @@ class UserModel extends Model "updated_by", "updated_at", "is_active", + "nhance_branch_id", ]; // Dates diff --git a/app/Views/UserList.php b/app/Views/UserList.php index d0dca952..94442753 100755 --- a/app/Views/UserList.php +++ b/app/Views/UserList.php @@ -339,6 +339,7 @@ table.dataTable tbody td { border: 1px solid #ddd; /* matches border-width:1px */ padding: 3px; } + .dataTables_length label {height: 21px !important;} @@ -440,7 +441,7 @@ table.dataTable tbody td { - + @@ -356,9 +358,13 @@ // for datatable $(document).ready(function() { $('#hr_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 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', text: ' Export ', diff --git a/app/Views/insurer_list.php b/app/Views/insurer_list.php index bf145a61..5a25fd9e 100755 --- a/app/Views/insurer_list.php +++ b/app/Views/insurer_list.php @@ -37,6 +37,9 @@ color: white; border: 1px solid rgba(41, 139, 142, 1); } + + .dataTables_length label {height: 21px !important;} +
@@ -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 @@
-
+
+
" . $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 { - - - + + + @@ -222,9 +225,13 @@ var table; $(document).ready(function() { table = $('#tickets-table').DataTable({ - dom: "<'row'<'col-sm-1'f><'col-sm-11 text-right'B>>" + // Filter left, button right + // dom: "<'row'<'col-sm-1'f><'col-sm-11 text-right'B>>" + // Filter left, button right + // "<'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]], buttons: [ { text: 'Add', diff --git a/app/Views/batch_list.php b/app/Views/batch_list.php index 6600162f..123950fb 100755 --- a/app/Views/batch_list.php +++ b/app/Views/batch_list.php @@ -13,6 +13,7 @@ overflow: hidden; text-overflow: ellipsis; } +.dataTables_length label {height: 21px !important;}
@@ -224,9 +225,9 @@ $(document).ready(function() { $('#datatable-buttons').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>>", // buttons: [{ // extend: 'csv', // text: 'CSV', @@ -239,6 +240,10 @@ // left: "50px" // }); // }, + 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 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', text: ' Export ', diff --git a/app/Views/bds_dump_file_list.php b/app/Views/bds_dump_file_list.php new file mode 100644 index 00000000..2c243dcd --- /dev/null +++ b/app/Views/bds_dump_file_list.php @@ -0,0 +1,393 @@ + + +
+
+
+
Advertisement Image NameStatusAction
Advertisement Image Name
Status
Action
+ + + + + + + + + + + + $file) { + ?> + + + + + + + + + + + +
S.No File nameUser/TimeStatusAction
+ + ' . $file['user_name'] . '' ?> + + + + + + + + + + + + + + + +
+
+
+
+ + + + + + + + \ No newline at end of file diff --git a/app/Views/bds_multi_report.php b/app/Views/bds_multi_report.php index 33fa456a..dab4e951 100644 --- a/app/Views/bds_multi_report.php +++ b/app/Views/bds_multi_report.php @@ -19,6 +19,7 @@ .right-align-input { text-align: right; } + .dataTables_length label {height: 21px !important;} @@ -89,9 +90,13 @@ 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>>", + "<'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_renewal_report_list.php b/app/Views/bds_renewal_report_list.php index c11290a7..c4873dda 100644 --- a/app/Views/bds_renewal_report_list.php +++ b/app/Views/bds_renewal_report_list.php @@ -14,6 +14,8 @@ table.dataTable tbody td { table[data-custom-table-css="table"].dataTable thead th { padding-right: 20px !important; } + .dataTables_length label {height: 21px !important;} +
@@ -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 { - - - - - - - - - + + + + + + + + + @@ -215,9 +219,13 @@ table.dataTable thead th { $('#scroll-horizontal-datatable').DataTable({ scrollX: true, - dom: "<'row'<'col-sm-2'f><'col-sm-10 text-right'B>>" + - "<'row'<'col-sm-12'tr>>" + - "<'row'<'col-sm-5'i><'col-sm-7'p>>", + // 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 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/claim_dump_file_list.php b/app/Views/claim_dump_file_list.php index 70282d89..696d97ce 100644 --- a/app/Views/claim_dump_file_list.php +++ b/app/Views/claim_dump_file_list.php @@ -21,6 +21,7 @@ position: absolute; } + .dataTables_length label {height: 21px !important;} + +
+ + +
+ +
+ +
+
+ +
+ + +
+ Add more filters (field-level) (Add arbitrary condition-field filters (e.g., vehicle_type, fuel_type, policy_type). Each row is ANDed together.) +
+
+ +
+ +
+ +
+ + + + +
+
+
+ + + + + +
+ +
+ + + + + + + + + diff --git a/app/Views/dms_search.php b/app/Views/dms_search.php index 6bdd968a..f3e1bad0 100644 --- a/app/Views/dms_search.php +++ b/app/Views/dms_search.php @@ -22,6 +22,9 @@ .autocomplete-suggestion:hover { background-color: #e9e9e9; } + + .dataTables_length label {height: 21px !important;} +
@@ -173,9 +176,13 @@ if (ticketsTable.length) { ticketsTable.DataTable({ scrollX: true, - dom: "<'row'<'col-sm-2'f><'col-sm-10 text-right'B>>" + - "<'row'<'col-sm-12'tr>>" + - "<'row'<'col-sm-5'i><'col-sm-7'p>>", + // 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 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', text: ' Export ', @@ -197,6 +204,20 @@ }], paging: true, pageLength: 10, + language: { + search: ` +
+ _INPUT_ + + + +
+ `, + searchPlaceholder: "Search", + emptyTable: '
No Data found
' + }, order: [ [0, 'desc'] ] diff --git a/app/Views/drive_file_upload.php b/app/Views/drive_file_upload.php index db20f6d4..96a4fc79 100644 --- a/app/Views/drive_file_upload.php +++ b/app/Views/drive_file_upload.php @@ -49,7 +49,7 @@
S.No Client Name Insurer Name Insurer Branch Name Opening Date CD Account No Opening Amount Date/User Action 
S.No 
Client Name 
Insurer Name 
Insurer Branch Name 
Opening Date 
CD Account No 
Opening Amount 
Date/User 
Action 
- + diff --git a/app/Views/employee_data_list.php b/app/Views/employee_data_list.php index 4b594084..9bdc75d5 100755 --- a/app/Views/employee_data_list.php +++ b/app/Views/employee_data_list.php @@ -76,6 +76,9 @@ border-radius: 5px; box-shadow: 0 0 5px rgba(0, 0, 0, 0.1); } + + .dataTables_length label {height: 21px !important;} + @@ -341,9 +344,13 @@ 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/endorsement_list.php b/app/Views/endorsement_list.php index 8512e000..a5535107 100755 --- a/app/Views/endorsement_list.php +++ b/app/Views/endorsement_list.php @@ -12,6 +12,8 @@ position: relative; left: 79px; } + .dataTables_length label {height: 21px !important;} +
@@ -594,9 +596,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 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 ', className: 'btn app-btn-primary mr-2', diff --git a/app/Views/fedeploy.php b/app/Views/fedeploy.php new file mode 100644 index 00000000..906bf5f7 --- /dev/null +++ b/app/Views/fedeploy.php @@ -0,0 +1,43 @@ +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + + +
+ + + diff --git a/app/Views/file_list.php b/app/Views/file_list.php index 52fb1940..5e2f79dc 100755 --- a/app/Views/file_list.php +++ b/app/Views/file_list.php @@ -8,6 +8,11 @@ cursor: pointer; } +.dataTables_length label {height: 21px !important;} + +.column-header { margin-right: 10px; /* Adjust this value as needed */ } + +
@@ -19,18 +24,19 @@
+
S.No S.No  Docs Name  File Name  Action 
- - - - - - - - - + + + + + + + + + @@ -112,6 +118,7 @@
S.No File name Client Client Branch Policy Event User/Time Status Action 
S.No
File name
Client
Client Branch
Policy
Event
User/Time
Status
Action
+
@@ -461,12 +468,16 @@ $(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>>>" + + // 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'<'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 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', text: ' Export ', diff --git a/app/Views/finance_team_list.php b/app/Views/finance_team_list.php index 6e6d2016..d80aaad5 100644 --- a/app/Views/finance_team_list.php +++ b/app/Views/finance_team_list.php @@ -43,6 +43,8 @@ color: #16181b !important; cursor: pointer !important; } + .dataTables_length label {height: 21px !important;} + @@ -336,10 +338,14 @@ $(document).ready(function () { if (ticketsTable.length) { ticketsTable.DataTable({ - dom: - "<'row'<'col-sm-6'f><'col-sm-6 text-right'B>>" + // Filter left, buttons right + // 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 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/frontend_content_list2.php b/app/Views/frontend_content_list2.php new file mode 100644 index 00000000..4c867152 --- /dev/null +++ b/app/Views/frontend_content_list2.php @@ -0,0 +1,319 @@ + + + +
+
+
+
+ + + + + + + + + + + + + + + $row) { ?> + + + + + + + + + + + + + + + + +
S.No.TypeContent SectionHeadingAction
+ +
No data available
+
+
+
+
+ + + + + + 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'] . '' ?>
- + @@ -269,7 +279,7 @@ - +
Insurer
by ' . $row['first_name'] ?> by ' . $row['first_name'] ?>
- +
- +
@@ -342,7 +342,7 @@ - + - - +
+ +
-
+
+
- + - + + +
@@ -208,7 +219,7 @@ - + @@ -217,10 +228,11 @@ @@ -247,21 +259,64 @@ + + + + \ No newline at end of file diff --git a/app/Views/payout_list_handler.php b/app/Views/payout_list_handler.php index 80315199..329645bd 100644 --- a/app/Views/payout_list_handler.php +++ b/app/Views/payout_list_handler.php @@ -128,6 +128,7 @@ $('#reportrange').val(''); $('#startDate').val(''); $('#endDate').val(''); + window.location.reload(true); }); }); diff --git a/app/Views/payout_utr_details.php b/app/Views/payout_utr_details.php index 18b03778..ee10ded8 100644 --- a/app/Views/payout_utr_details.php +++ b/app/Views/payout_utr_details.php @@ -154,6 +154,7 @@ toastr.success(response.message, 'SUCCESS'); $('#modal_body').empty(); $('#modal_body').append(response.data); + window.location.href = ''; }else{ toastr.warning(response.message || 'Unable to fetch data', 'WARNING'); } @@ -163,7 +164,6 @@ $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); - }, error: function(xhr, status, error) { $('.loader').fadeOut(); diff --git a/app/Views/policy_gmc_terms.php b/app/Views/policy_gmc_terms.php index 5c28b10a..a53b4c54 100755 --- a/app/Views/policy_gmc_terms.php +++ b/app/Views/policy_gmc_terms.php @@ -109,7 +109,6 @@ margin-top:10px; } - - + + + + + - + @@ -926,7 +966,7 @@ dataType: 'json', success: function (res) { - console.log(res) + console.log("get_client_policy_data_using_policy_no_and_endo_no Response : ", res); if(res.status == true){ $('#ct_type').val(1) }else{ @@ -939,6 +979,8 @@ console.error(status, error); } }); + }else{ + console.log('Policy number or Endorsement Number is empty') } }) @@ -2120,100 +2162,103 @@ break; case 4: // follower policy no newCell = ``; + break; + case 5: // calc_policy_issue_date + newCell = ``; break; - case 5: // Co-Share % + case 6: // Co-Share % newCell = ``; break; - case 6: // Non commissionable Premium amount % + case 7: // Non commissionable Premium amount % newCell = ``; break; - case 7: // Base Premium + case 8: // Base Premium newCell = ``; break; - case 8: // TP Premium + case 9: // TP Premium newCell = ``; break; - case 9: // Ter Premium + case 10: // Ter Premium newCell = ``; break; - case 10: // co Premium + case 11: // co Premium newCell = ``; break; - case 11: // Co TP Premium + case 12: // Co TP Premium newCell = ``; break; - case 12: // Co Ter Premium + case 13: // Co Ter Premium newCell = ``; break; - case 13: // CGST + case 14: // CGST newCell = ``; break; - case 14: // SGST + case 15: // SGST newCell = ``; break; - case 15: // IGST + case 16: // IGST newCell = ``; break; - case 16: // GST Amount + case 17: // GST Amount newCell = ``; break; - case 17: // Stamp Duty + case 18: // Stamp Duty newCell = ``; break; - case 18: // Total + case 19: // Total newCell = ``; break; - case 19: // Agreed BP % + case 20: // Agreed BP % newCell = ``; break; - case 20: // Agreed TP % + case 21: // Agreed TP % newCell = ``; break; - case 21: // Agreed Ter % + case 22: // Agreed Ter % newCell = ``; break; - case 22: // Agreed Amount + case 23: // Agreed Amount newCell = ``; break; - case 23: // Standard BP % + case 24: // Standard BP % newCell = ``; break; - case 24: // Standard TP % + case 25: // Standard TP % newCell = ``; break; - case 25: // Standard Ter % + case 26: // Standard Ter % newCell = ``; break; - case 26: // Actual BP Amount + case 27: // Actual BP Amount newCell = ``; break; - case 27: // Actual TP Amount + case 28: // Actual TP Amount newCell = ``; break; - case 28: // Actual TEP Amount + case 29: // Actual TEP Amount newCell = ``; break; - case 29: // Actual BP % + case 30: // Actual BP % newCell = ``; break; - case 30: // Actual TP % + case 31: // Actual TP % newCell = ``; break; - case 31: // Actual TEP % + case 32: // Actual TEP % newCell = ``; break; - case 32: // Actual BP Brokerage Amount + case 33: // Actual BP Brokerage Amount newCell = ``; break; - case 33: // Actual TP Brokerage Amount + case 34: // Actual TP Brokerage Amount newCell = ``; break; - case 34: // Actual TEP Brokerage Amount + case 35: // Actual TEP Brokerage Amount newCell = ``; break; - case 35: // Expected Amount + case 36: // Expected Amount newCell = ``; break; // case 30: // Variance @@ -2222,7 +2267,7 @@ // case 31: // Reward // newCell = ``; // break; - case 36: // ID For Update + case 37: // ID For Update newCell = ``; break; } @@ -2254,69 +2299,72 @@ case 4: // follower policy no newCell = ``; break; - case 5: // Co-Share % + case 5: // calc_policy_issue_date + newCell = ``; + break; + case 6: // Co-Share % newCell = ``; break; - case 6: // Non commissionable Premium amount % + case 7: // Non commissionable Premium amount % newCell = ``; break; - case 7: // Base Premium + case 8: // Base Premium newCell = ``; break; - case 8: // TP Premium + case 9: // TP Premium newCell = ``; break; - case 9: // Ter Premium + case 10: // Ter Premium newCell = ``; break; - case 10: // co Premium + case 11: // co Premium newCell = ``; break; - case 11: // Co TP Premium + case 12: // Co TP Premium newCell = ``; break; - case 12: // Co Ter Premium + case 13: // Co Ter Premium newCell = ``; break; - case 13: // CGST + case 14: // CGST newCell = ``; break; - case 14: // SGST + case 15: // SGST newCell = ``; break; - case 15: // IGST + case 16: // IGST newCell = ``; break; - case 16: // GST Amount + case 17: // GST Amount newCell = ``; break; - case 17: // Stamp Duty + case 18: // Stamp Duty newCell = ``; break; - case 18: // Total + case 19: // Total newCell = ``; break; - case 19: // Agreed BP % + case 20: // Agreed BP % newCell = ``; break; - case 20: // Agreed TP % + case 21: // Agreed TP % newCell = ``; break; - case 21: // Agreed Ter % + case 22: // Agreed Ter % newCell = ``; break; - case 22: // Standard BP % + case 23: // Standard BP % newCell = ``; break; - case 23: // Standard TP % + case 24: // Standard TP % newCell = ``; break; - case 24: // Standard Ter % + case 25: // Standard Ter % newCell = ``; break; - case 25: // ID For Update + case 26: // ID For Update newCell = ``; break; } @@ -2404,10 +2452,12 @@ if(is_co_pay_yes == 1){ $('.hidecotp').show(); $('#table_tr_7').show(); + $('#table_tr_35').show(); $('#table_tr_3').show(); }else{ $('.hidecotp').hide(); $('#table_tr_7').hide(); + $('#table_tr_35').hide(); $('#table_tr_3').hide(); } @@ -2452,6 +2502,11 @@ $('.follow_insurer').prop('required', false); } + var calc_policy_issue_date = flatpickr("#calc_policy_issue_date_" + insurerCount, { + dateFormat: "d/m/Y", + allowInput: false + }); + }); // Add click event for delete button @@ -2547,97 +2602,100 @@ case 4: // follower_policy_no cell.find('input').val(data.follower_policy_no); break; - case 5: // Co-Share % + case 5: // follower_policy_no + cell.find('input').val(data.pt_policy_issue_date); + break; + case 6: // Co-Share % cell.find('input').val(data.co_share_per).toggleClass('readonly-select', !!disable_td); break; - case 6: // non_comm_per_amt + case 7: // non_comm_per_amt cell.find('input').val(data.non_comm_per_amt); break; - case 7: // Base Premium + case 8: // Base Premium cell.find('input').val(status ? data.bp_amt : '').toggleClass('readonly-select', !!disable_td); break; - case 8: // TP Premium + case 9: // TP Premium cell.find('input').val(status ? data.tp_amt : '').toggleClass('readonly-select', !!disable_td); break; - case 9: // Ter Premium + case 10: // Ter Premium cell.find('input').val(status ? data.tep_amt : '').toggleClass('readonly-select', !!disable_td); break; - case 10: // Co Premium + case 11: // Co Premium cell.find('input').val(status ? data.cop_amt : '').toggleClass('readonly-select', !!disable_td); break; - case 11: // Co TP Premium + case 12: // Co TP Premium cell.find('input').val(status ? data.cotp_amt : '').toggleClass('readonly-select', !!disable_td); break; - case 12: // Co Ter Premium + case 13: // Co Ter Premium cell.find('input').val(status ? data.cotep_amt : '').toggleClass('readonly-select', !!disable_td); break; - case 13: // CGST + case 14: // CGST cell.find('input').val(data.bp_cgst).toggleClass('readonly-select', !!disable_td); break; - case 14: // SGST + case 15: // SGST cell.find('input').val(data.bp_sgst).toggleClass('readonly-select', !!disable_td); break; - case 15: // IGST + case 16: // IGST cell.find('input').val(data.bp_igst).toggleClass('readonly-select', !!disable_td); break; - case 16: // GST Amount + case 17: // GST Amount cell.find('input').val(status ? data.bp_gst_amt : '').toggleClass('readonly-select', !!disable_td); break; - case 17: // Stamp Duty + case 18: // Stamp Duty cell.find('input').val(status ? data.stamp_duty : '').toggleClass('readonly-select', !!disable_td); break; - case 18: // Total + case 19: // Total cell.find('input').val(status ? data.amount : ''); break; - case 19: // Agreed BP % + case 20: // Agreed BP % cell.find('input').val(data.agreed_bp_per).toggleClass('readonly-select', !!disable_td); break; - case 20: // Agreed TP % + case 21: // Agreed TP % cell.find('input').val(data.agreed_tp_per).toggleClass('readonly-select', !!disable_td); break; - case 21: // Agreed Ter % + case 22: // Agreed Ter % cell.find('input').val(data.agreed_tep_per).toggleClass('readonly-select', !!disable_td); break; - case 22: // Agreed Amount + case 23: // Agreed Amount cell.find('input').val(data.agreed_amt).toggleClass('readonly-select', !!disable_td); break; - case 23: // Standard BP % + case 24: // Standard BP % cell.find('input').val(data.standerd_bp_per); break; - case 24: // Standard TP % + case 25: // Standard TP % cell.find('input').val(data.standerd_tp_per); break; - case 25: // Standard Ter % + case 26: // Standard Ter % cell.find('input').val(data.standerd_tep_per); break; - case 26: // Actual BP Amount + case 27: // Actual BP Amount cell.find('input').val(status ? data.actual_bp_amt : ''); break; - case 27: // Actual TP Amount + case 28: // Actual TP Amount cell.find('input').val(status ? data.actual_tp_amt : ''); break; - case 28: // Actual Ter Amount + case 29: // Actual Ter Amount cell.find('input').val(status ? data.actual_tep_amt : ''); break; - case 29: // Actual BP % + case 30: // Actual BP % cell.find('input').val(status ? data.actual_bp_per : ''); break; - case 30: // Actual TP % + case 31: // Actual TP % cell.find('input').val(status ? data.actual_tp_per : ''); break; - case 31: // Actual Ter % + case 32: // Actual Ter % cell.find('input').val(status ? data.actual_tep_per : ''); break; - case 32: // Actual BP Brokerage Amount + case 33: // Actual BP Brokerage Amount cell.find('input').val(status ? data.actual_bp_brokerage_amt : ''); break; - case 33: // Actual TP Brokerage Amount + case 34: // Actual TP Brokerage Amount cell.find('input').val(status ? data.actual_tp_brokerage_amt : ''); break; - case 34: // Actual Ter Brokerage Amount + case 35: // Actual Ter Brokerage Amount cell.find('input').val(status ? data.actual_tep_brokerage_amt : ''); break; - case 35: // Expected Amount + case 36: // Expected Amount cell.find('input').val(status ? data.exp_amt : ''); break; // case 30: // Variance @@ -2646,7 +2704,7 @@ // case 31: // Reward // cell.find('input').val(status ? data.reward : ''); // break; - case 36: // Co-share ID (hidden field) + case 37: // Co-share ID (hidden field) cell.find('input[type="hidden"]').val(status ? data.id : ''); break; } @@ -2668,67 +2726,70 @@ case 4: // follower_policy_no cell.find('input').val(data.follower_policy_no); break; - case 5: // Co-Share % + case 5: // follower_policy_no + cell.find('input').val(data.pt_policy_issue_date); + break; + case 6: // Co-Share % cell.find('input').val(data.co_share_per).toggleClass('readonly-select', !!disable_td); break; - case 6: // non_comm_per_amt + case 7: // non_comm_per_amt cell.find('input').val(data.non_comm_per_amt); break; - case 7: // Base Premium + case 8: // Base Premium cell.find('input').val(status ? data.bp_amt : '').toggleClass('readonly-select', !!disable_td); break; - case 8: // TP Premium + case 9: // TP Premium cell.find('input').val(status ? data.tp_amt : '').toggleClass('readonly-select', !!disable_td); break; - case 9: // Ter Premium + case 10: // Ter Premium cell.find('input').val(status ? data.tep_amt : '').toggleClass('readonly-select', !!disable_td); break; - case 10: // Co Premium + case 11: // Co Premium cell.find('input').val(status ? data.cop_amt : '').toggleClass('readonly-select', !!disable_td); break; - case 11: // Co TP Premium + case 12: // Co TP Premium cell.find('input').val(status ? data.cotp_amt : '').toggleClass('readonly-select', !!disable_td); break; - case 12: // Co Ter Premium + case 13: // Co Ter Premium cell.find('input').val(status ? data.cotep_amt : '').toggleClass('readonly-select', !!disable_td); break; - case 13: // CGST + case 14: // CGST cell.find('input').val(data.bp_cgst).toggleClass('readonly-select', !!disable_td); break; - case 14: // SGST + case 15: // SGST cell.find('input').val(data.bp_sgst).toggleClass('readonly-select', !!disable_td); break; - case 15: // IGST + case 16: // IGST cell.find('input').val(data.bp_igst).toggleClass('readonly-select', !!disable_td); break; - case 16: // GST Amount + case 17: // GST Amount cell.find('input').val(status ? data.bp_gst_amt : '').toggleClass('readonly-select', !!disable_td); break; - case 17: // Stamp Duty + case 18: // Stamp Duty cell.find('input').val(status ? data.stamp_duty : '').toggleClass('readonly-select', !!disable_td); break; - case 18: // Total + case 19: // Total cell.find('input').val(status ? data.amount : ''); break; - case 19: // Agreed BP % + case 20: // Agreed BP % cell.find('input').val(data.agreed_bp_per).toggleClass('readonly-select', !!disable_td); break; - case 20: // Agreed TP % + case 21: // Agreed TP % cell.find('input').val(data.agreed_tp_per).toggleClass('readonly-select', !!disable_td); break; - case 21: // Agreed Ter % + case 22: // Agreed Ter % cell.find('input').val(data.agreed_tep_per).toggleClass('readonly-select', !!disable_td); break; - case 22: // Standard BP % + case 23: // Standard BP % cell.find('input').val(data.standerd_bp_per); break; - case 23: // Standard TP % + case 24: // Standard TP % cell.find('input').val(data.standerd_tp_per); break; - case 24: // Standard Ter % + case 25: // Standard Ter % cell.find('input').val(data.standerd_tep_per); break; - case 25: // Co-share ID (hidden field) + case 26: // Co-share ID (hidden field) cell.find('input[type="hidden"]').val(status ? data.id : ''); break; } @@ -2884,6 +2945,25 @@ }) + $('#policy_issue_date').on('change', function(){ + let date = $(this).val(); + + let date_set = false + $('[name="co_share_type[]"]').each(function () { + console.log('co_share_type[] value', $(this).val()); + if($(this).val() == 1){ + let uniqueid = $(this).data('id'); + $('#calc_policy_issue_date_' + uniqueid).val(date).addClass('readonly-select'); + date_set = true; + } + }); + + if(!date_set){ + $('#calc_policy_issue_date_1').val(date).addClass('readonly-select'); + } + }); + + //----------------------------------------------------------------------------------------------------------- $(document).on('change', '#insurerTable input, #insurerTable select, #insurerTable textarea', function() { diff --git a/app/Views/policy_transaction_endorsement_list.php b/app/Views/policy_transaction_endorsement_list.php index 59963f43..5d739144 100644 --- a/app/Views/policy_transaction_endorsement_list.php +++ b/app/Views/policy_transaction_endorsement_list.php @@ -164,6 +164,7 @@ table.dataTable thead th { .slider.round:before { border-radius: 50%; } + .dataTables_length label {height: 21px !important;}
@@ -489,9 +490,14 @@ table.dataTable thead th { if (ticketsTable.length) { ticketsTable.DataTable({ scrollX: true, - dom: "<'row'<'col-sm-1'f><'col-sm-11 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-1'f><'col-sm-11 text-right'B>>" + // Filter left, buttons right + // dom: "<'row'<'col-12 d-flex justify-content-between'<'datatable-search dataTables_filter'f><'datatable-buttons dt-buttons'B>>>" + + // "<'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-12 d-flex justify-content-between'<'datatable-search dataTables_filter'f><'datatable-buttons dt-buttons'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: [ { text: ' Add ', diff --git a/app/Views/policy_transaction_inception_form.php b/app/Views/policy_transaction_inception_form.php index 1d5b8133..13b516ed 100644 --- a/app/Views/policy_transaction_inception_form.php +++ b/app/Views/policy_transaction_inception_form.php @@ -32,11 +32,13 @@ box-shadow: none; outline: none; width: 100%; + padding: 5px 30px !important; } + #insurerTable th, #insurerTable td { - padding: 5px; - height: 30px; + padding: 2px 4px !important; + /* height: 30px; */ vertical-align: middle; } @@ -50,6 +52,7 @@ height: 20px; width: 20px; } + #insurerTable th, #insurerTable th { min-width: 230px; @@ -96,11 +99,11 @@ .input-with-percentage::after { content: '%'; position: absolute; - right: 5px; + right: 10px; top: 50%; transform: translateY(-50%); font-weight: bold; - color: #000; + color: #495057; } /* .select2-container .select2-selection__rendered { @@ -142,21 +145,55 @@ } /** newly implemented */ + #insurerTable thead th:first-child { border-top: 0px solid #fff !important; border-bottom: 0px solid #fff !important; background-color: transparent !important; } + #insurerTable tbody td { border-top: 0px solid #fff !important; border-bottom: 0px solid #fff !important; background-color: transparent !important; } + #insurerTable th{ color: black !important; background-color: transparent !important; } + #insurerTable input[type="text"], + #insurerTable select { + width: 100%; + font-size: 14px; + line-height: 1.5; + color: #000; + background-color: #fff; + background-clip: padding-box; + border: 1px solid #ced4da; + border-radius: 4px; + transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out; + box-sizing: border-box; + } + + /* Focus effect like form-control */ + #insurerTable input[type="text"]:focus, + #insurerTable select:focus { + border-color: #80bdff; + outline: 0; + box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25); + } + + /* Disabled & readonly styling */ + #insurerTable input[readonly], + #insurerTable input:disabled, + #insurerTable select:disabled { + background-color: #e0e0e0; /* Darker background */ + color: #666; /* Darker text color */ + cursor: not-allowed; + } + @@ -316,7 +317,7 @@ table.dataTable tbody td {
- + @@ -327,7 +328,7 @@ table.dataTable tbody td { - + - + - + @@ -100,9 +100,9 @@ table.dataTable tbody td { - + - + @@ -123,7 +123,7 @@ table.dataTable tbody td { echo base_url('policy_tranction/endorsement/list') . '?pt_id=' . $row['id'] ; } ?>" class="mdi mdi-pencil" > - + @@ -144,9 +144,9 @@ table.dataTable tbody td { - + - + @@ -175,9 +175,17 @@ table.dataTable tbody td { // REF : Velmurugan but he told handle in query // Date : 6/11/25 12:50 $unbilled_amt = $total_irda_amt - $row['billed_amt']; + if($total_irda_amt == "0.00"){ + $unbilled_amt = abs($unbilled_amt); + } $unbilled_amt = $unbilled_amt == 0 && $row['billed_amt'] == 0 ? $total_irda_amt : $unbilled_amt ; ?> - + @@ -232,9 +240,9 @@ $(document).ready(function() { 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 // buttons: [ // { // extend: 'csv', @@ -286,6 +294,10 @@ $(document).ready(function() { // } // } // ], + dom: "<'row'<'col-sm-6'f><'col-sm-6 text-right'B>>" + // Filter left, buttons right + "<'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', @@ -547,7 +559,7 @@ $(document).ready(function() { }; // Compute totals by column index - var totalPremium = getTotal(21); + var totalPremium = getTotal(20); var totalRewards = getTotal(24); var totalIrda = getTotal(25); var totalBilled = getTotal(26); @@ -628,5 +640,10 @@ function appendTableData(data) { }); } +$('table tbody').on('click', 'td', function () { + var index = $(this).index(); + console.log('Clicked TD index:', index); +}); + \ No newline at end of file diff --git a/app/Views/report_bds_new.php b/app/Views/report_bds_new.php index ed9b8fe3..1bb808aa 100644 --- a/app/Views/report_bds_new.php +++ b/app/Views/report_bds_new.php @@ -33,6 +33,7 @@ flex-wrap: wrap; gap: 8px; } + .dataTables_length label {height: 21px !important;} @@ -301,9 +302,9 @@ 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 // buttons: [ // { // extend: 'csv', @@ -355,6 +356,10 @@ // } // } // ], + dom: "<'row'<'col-sm-6'f><'col-sm-6 text-right'B>>" + // Filter left, buttons right + "<'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/report_bds_old.php b/app/Views/report_bds_old.php index 536769b6..52d16677 100644 --- a/app/Views/report_bds_old.php +++ b/app/Views/report_bds_old.php @@ -20,6 +20,7 @@ table.dataTable tbody td { .right-align-input { text-align: right; } +.dataTables_length label {height: 21px !important;}
@@ -149,9 +150,13 @@ $(document).ready(function() { 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 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: 'csv', diff --git a/app/Views/retail_endorsement_list.php b/app/Views/retail_endorsement_list.php index e605f723..d01de408 100755 --- a/app/Views/retail_endorsement_list.php +++ b/app/Views/retail_endorsement_list.php @@ -28,6 +28,7 @@ color: #00999E !important; transform: scale(1.5); } + .dataTables_length label {height: 21px !important;}
@@ -140,7 +141,7 @@
CD Amount
Endorsement Issue Date
Non Commitional
Premium Amount
Non Commissional
Premium Amount
Base Premium
S. NoUserUser Month Business Type Client Type Insured NamePolicy/
Endorsement
Policy /
Endorsement
Policy Type BAP Group Vehicle NumberRemarks BP Premium TP/Ter PremiumPremium
(without GST)
Premium
(without GST)
Total PremiumTotal Premium BP% TP/Ter% Rewards % % + +
" . $ct . ""; endif; ?> <'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>>", // buttons: [{ // extend: 'csv', // text: 'CSV', @@ -361,6 +362,10 @@ // } // } // }], + 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 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', text: ' Export ', diff --git a/app/Views/rto_master_list.php b/app/Views/rto_master_list.php index d9ecfad6..f95d688b 100644 --- a/app/Views/rto_master_list.php +++ b/app/Views/rto_master_list.php @@ -1,7 +1,6 @@ @@ -117,9 +116,13 @@ var ticketsTable = $('#user-table'); ticketsTable.DataTable({ scrollX: true, + // dom: "<'row'<'col-sm-7'f><'col-sm-5 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-7'f><'col-sm-5 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: [ { text: 'Add', diff --git a/app/Views/tat_report_band_wise_list.php b/app/Views/tat_report_band_wise_list.php index e4ee2f19..d75b74d2 100644 --- a/app/Views/tat_report_band_wise_list.php +++ b/app/Views/tat_report_band_wise_list.php @@ -17,6 +17,7 @@ .right-align-input { text-align: right; } + .dataTables_length label {height: 21px !important;}
@@ -97,9 +98,9 @@ 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 // buttons: [{ // extend: 'csv', // text: 'CSV', @@ -111,6 +112,10 @@ // title: 'TAT BAND WISE DATA', // } // ], + dom: "<'row'<'col-sm-6'f><'col-sm-6 text-right'B>>" + // Filter left, buttons right + "<'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/test_members_list.php b/app/Views/test_members_list.php index 946fe6ab..4f880091 100644 --- a/app/Views/test_members_list.php +++ b/app/Views/test_members_list.php @@ -120,7 +120,7 @@ th:first-child, td:first-child { background-color:#00999E ; margin-right:10px; } - +.dataTables_length label {height: 21px !important;} @@ -539,9 +539,13 @@ document.addEventListener("DOMContentLoaded", function () { 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: [{ text:'Map Employees', action: function(e, dt, node, config) { diff --git a/app/Views/thz_list.php b/app/Views/thz_list.php index 63c64862..dde7ad77 100644 --- a/app/Views/thz_list.php +++ b/app/Views/thz_list.php @@ -35,6 +35,20 @@ table.dataTable tbody td { color: #6c757d !important; } +/* don't erase it. keep it safe +beccause = dataTables_length and dataTables_paginate need in same line thats why i tried in css ... +.dataTables_info, +.dataTables_length, +.dataTables_paginate { + display: flex; + align-items: center; +} */ + +.dataTables_length label { + height: 21px !important; +} + +
@@ -43,7 +57,7 @@ table.dataTable tbody td {
- +
@@ -86,7 +100,7 @@ table.dataTable tbody td {
" . $ct . ""; endif; ?> @@ -94,7 +108,7 @@ table.dataTable tbody td { " . $ut . ""; endif; ?> @@ -315,14 +329,18 @@ table.dataTable tbody td { // Datatable document ready $(document).ready(function() { - var ticketsTable = $('#tickets-table'); + var ticketsTable = $('#thz-table'); if (ticketsTable.length) { ticketsTable.DataTable({ scrollX: true, + // dom: "<'row'<'col-sm-7'f><'col-sm-5 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-7'f><'col-sm-5 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: [ { text: ' Add ', @@ -349,7 +367,7 @@ table.dataTable tbody td { orthogonal: 'sort' }, className: 'app-btn-primary ', - title: 'Tickets' + title: 'Tickets', sheetName: 'Tickets', } ] @@ -374,6 +392,12 @@ table.dataTable tbody td { } else { console.error("Table not found."); } + + $(document).on('click', '.datatable-clear-icon', function () { + const input = $(this).closest('.datatable-search-wrapper').find('input'); + input.val('').trigger('input'); + $('#thz-table').DataTable().search('').draw(); + }); }); diff --git a/app/Views/thz_notes.php b/app/Views/thz_notes.php index b3d26b07..959a1633 100644 --- a/app/Views/thz_notes.php +++ b/app/Views/thz_notes.php @@ -274,7 +274,7 @@ hr{
- +
@@ -410,7 +410,7 @@ data-backdrop="static" diff --git a/app/Views/ticket_conversation.php b/app/Views/ticket_conversation.php index 6f4ddcdb..57d8370f 100644 --- a/app/Views/ticket_conversation.php +++ b/app/Views/ticket_conversation.php @@ -23,7 +23,7 @@
-
format('j F Y h:i a');?>
+
format('j F Y h:i A');?>

@@ -69,7 +69,7 @@
-
format('j F Y h:i a');?>
+
format('j F Y h:i A');?>

diff --git a/app/Views/ticket_feedback_list.php b/app/Views/ticket_feedback_list.php index 3902ca42..048c3663 100644 --- a/app/Views/ticket_feedback_list.php +++ b/app/Views/ticket_feedback_list.php @@ -34,7 +34,7 @@ table.dataTable tbody td { text-overflow: ellipsis !important; white-space: nowrap !important; } - +.dataTables_length label {height: 21px !important;} @@ -95,9 +95,9 @@ $(document).ready(function() { 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 // buttons: [{ // extend: 'csv', // text: 'CSV', @@ -112,6 +112,10 @@ $(document).ready(function() { // }, // }, // ], + dom: "<'row'<'col-sm-6'f><'col-sm-6 text-right'B>>" + // Filter left, buttons right + "<'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/ticket_form_gmc.php b/app/Views/ticket_form_gmc.php index 02f9dfb6..554d60c1 100644 --- a/app/Views/ticket_form_gmc.php +++ b/app/Views/ticket_form_gmc.php @@ -300,6 +300,7 @@
@@ -308,6 +309,7 @@
@@ -333,7 +335,7 @@