diff --git a/app/Config/Filters.php b/app/Config/Filters.php index 2cf9a260..029d2706 100755 --- a/app/Config/Filters.php +++ b/app/Config/Filters.php @@ -13,6 +13,8 @@ use App\Filters\AuthMVC; use App\Filters\HttpRequestLog; use App\Filters\CloseDbConnection; use App\Filters\AuthClientApi; +use App\Filters\CommissionApiFilter; +use App\Filters\Cors; use App\Filters\AuthJWT; @@ -36,7 +38,9 @@ class Filters extends BaseConfig 'HttpRequestLog' => HttpRequestLog::class, 'authJWT' => AuthJWT::class, 'AuthClientApi' => AuthClientApi::class, - 'CloseDbConnection' => CloseDbConnection::class + 'CloseDbConnection' => CloseDbConnection::class, + 'CommissionApiFilter' => CommissionApiFilter::class, + 'Cors' => Cors::class ]; /** @@ -49,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 efec8a5d..96252c3f 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 @@ -34,6 +43,8 @@ $routes->get("updateRenewalData", "ClientController::updateRenewalData"); $routes->get("updateRenewalDataNotExistingClient", "ClientController::updateRenewalDataNotExistingClient"); $routes->get("updateRenewalInsurerData", "ClientController::updateRenewalInsurerData"); $routes->get("sendMutipleToEmails", "MasterController::sendMutipleToEmails"); +$routes->post("getCommission", "InsuranceCommissionController::initiateCommissionCalc",['filter' => 'CommissionApiFilter']); +$routes->get("importRules", "RuleImportController::upload"); // $routes->post("iAgreeForAddOn", "EmployeeRestController::iAgreeForAddOn"); // $routes->get("sendCroneRemainderMail", "DashboardController::sendCroneRemainderMail"); // $routes->post("employeeUpload", "EmployeeRestController::employeeUpload"); @@ -549,7 +560,7 @@ $routes->post("employeeRest/getPostEmployeeDataForAuth", "RestAuthenticationCont $routes->get("employeeRest/getClientDetails", "EmployeeRestController::getClientDetails"); $routes->get("employeeRest/getAdvertisementImage", "EmployeeRestController::getAdvertisementImage"); - +$routes->get("getSSORedirectUrl", "ApiServiceController::getSSORedirectUrl"); $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) { @@ -736,7 +747,6 @@ $routes->get('testTracelog','TestBusinessController::a'); $routes->get("claimView", "EmployeeRestController::claimView"); // General Tickets - $routes->post("ticketSave", "ThzController::ticketSave"); $routes->get("ticketList", "ThzController::ticketList"); $routes->post("ticketConversationSave", "ThzController::ticketConversationSave"); @@ -766,3 +776,33 @@ $routes->group('test', function($routes) { }); $routes->cli('cli/testcli', 'TestingController::testcli'); +//PARTNER PAYOUT +$routes->group('payout', function($routes) { + $routes->match (['get','post'],'list',"PayoutController::payoutList"); + $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 +$routes->group('commission', function($routes) { + $routes->match (['get','post'],'list',"RuleImportController::commissionFileUploadList"); + $routes->post('upload',"RuleImportController::upload"); + $routes->get('sample_file',"RuleImportController::downloadSampleCommissionFileUploadExcel"); + $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"); +}); + diff --git a/app/Config/Services.php b/app/Config/Services.php index fab85a50..5f982877 100755 --- a/app/Config/Services.php +++ b/app/Config/Services.php @@ -7,6 +7,7 @@ use App\Libraries\Slug; use App\Libraries\MyLogger; use App\Libraries\GmailAPI; use App\Libraries\MyGoogleDrive; +use App\Libraries\RuleImportService; use App\Libraries\DataServiceSqlite; use App\Controllers\Home; @@ -80,5 +81,14 @@ class Services extends BaseService return new MyGoogleDrive(); } + + public static function ruleImportService($getShared = true) + { + if ($getShared) { + return static::getSharedInstance('ruleImportService'); + } + + return new RuleImportService(); + } } diff --git a/app/Controllers/ApiServiceController.php b/app/Controllers/ApiServiceController.php index ad6a114c..ac6cb0dd 100644 --- a/app/Controllers/ApiServiceController.php +++ b/app/Controllers/ApiServiceController.php @@ -79,6 +79,7 @@ class ApiServiceController extends BaseController $client_policy_id = $params['client_policy_id'] ?? null; $policy_no = $params['policy_no'] ?? null; $type = $params['type'] ?? 'download'; + $all_member = $params['all_member'] ?? null; log_message('error', 'Received Payload INTERNAL : '. json_encode($params ?? "")); @@ -107,10 +108,16 @@ class ApiServiceController extends BaseController // direct download $data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string'].'/1'; }else{ - // view and download - $data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string'].'/0/1'; + if(isset($all_member) && !empty($all_member)){ + // view and download all members + $data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string'].'/1/1'; + }else{ + // view and download single member + $data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string'].'/0/1'; + } } } + $data['message'] = "E-card generated"; if(empty($data['eCardDownload'])){ $data['message'] = "E-card not generated"; @@ -213,7 +220,7 @@ class ApiServiceController extends BaseController } - public function getWellnessUrl() + public function getWellnessUrl() { $emp_id = $this->request->getGet('emp_id'); @@ -238,8 +245,8 @@ class ApiServiceController extends BaseController $data = $db->table('employee_polices ep') ->select('pt.policy_type, - e.name, e.email_corporate as email, e.mobile as phone, e.emp_code as memberId, e.gender, e.dob, e.relationship as relation, - cp.policy_no as policyNumber, cp.policy_no as employeeId, cp.policy_start_date as policyStartDate, cp.policy_end_date as policyEndDate, cp.wellness_plan_id as planId') + e.name, e.email_corporate as email, e.mobile as phone, e.emp_code as memberId, e.gender, e.dob, e.relationship as relation, e.id as employeeId + cp.policy_no as policyNumber, cp.policy_start_date as policyStartDate, cp.policy_end_date as policyEndDate, cp.wellness_plan_id as planId') ->join('employees e', 'e.id = ep.employee_id') ->join('client_policy cp', 'ep.client_policy_id = cp.id') ->join('policy_type pt', 'cp.policy_type_id = pt.id') @@ -258,12 +265,12 @@ class ApiServiceController extends BaseController $userParams['name'] = $data->name; $userParams['email'] = $data->email; $userParams['phone'] = $data->phone; - $userParams['memberId'] = $data->memberId; + $userParams['memberId'] = $data->employeeId; // memberId is unique primary key. $userParams['gender'] = $data->gender; $userParams['dob'] = $data->dob; $userParams['relation'] = $data->relation; $userParams['policyNumber'] = $data->policyNumber; - $userParams['employeeId'] = $data->employeeId; + $userParams['employeeId'] = $data->memberId; $userParams['policyStartDate']= $data->policyStartDate; $userParams['policyEndDate'] = $data->policyEndDate; $userParams['policyName'] = 'Nhance ' . $data->policy_type; @@ -310,6 +317,87 @@ class ApiServiceController extends BaseController + function getSSORedirectUrl($email = 'user@example.com') + { + // ---------- CONFIG ---------- + $authUrl = env('VIDAL_WELLNESS_BASE_URL'); // Authentication API URL + $subscriptionKey = env('VIDAL_WELLNESS_SUBSCRIPTION_KEY'); + $apiVersion = "1"; + + // Provided Base64 AES key + $base64Key = env('VIDAL_WELLNESS_BASE64_KEY'); + $key = base64_decode($base64Key); + + // ---------- STEP 1: Build plaintext payload ---------- + $plainPayload = json_encode([ + "email" => $email, + "corporateId" => env('VIDAL_WELLNESS_CORPORATE_ID'), + "urlIdentifier" => env('VIDAL_WELLNESS_URL_IDENTIFIER') + ]); + + // ---------- STEP 2: Encrypt payload ---------- + $iv = random_bytes(16); + $encryptedRaw = openssl_encrypt($plainPayload, "AES-256-CBC", $key, OPENSSL_RAW_DATA, $iv); + + $encryptedPayload = base64_encode($iv) . ":" . base64_encode($encryptedRaw); + + // ---------- STEP 3: Call Authentication API ---------- + $requestBody = json_encode([ + "payload" => $encryptedPayload, + "source" => "portal", + "subPartnerId" => env('VIDAL_WELLNESS_SUB_PARTNER_ID') + ]); + + $headers = [ + "Ocp-Apim-Subscription-Key: $subscriptionKey", + "apiver: $apiVersion", + "mode: encrypt", + "Content-Type: application/json" + ]; + + $ch = curl_init($authUrl); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody); + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + + $apiResponse = curl_exec($ch); + curl_close($ch); + + $jsonResponse = json_decode($apiResponse, true); + + dd($jsonResponse); + + if (!isset($jsonResponse["data"])) { + return ["error" => "Invalid API response", "response" => $apiResponse]; + } + + + + // ---------- STEP 4: Decrypt response ---------- + list($ivBase64, $cipherBase64) = explode(":", $jsonResponse["data"]); + + $respIv = base64_decode($ivBase64); + $respCipher = base64_decode($cipherBase64); + + $decryptedJson = openssl_decrypt($respCipher, "AES-256-CBC", $key, OPENSSL_RAW_DATA, $respIv); + + $decryptedData = json_decode($decryptedJson, true); + + if (!isset($decryptedData["redirectUrl"])) { + return ["error" => "redirectUrl missing", "decrypted" => $decryptedData]; + } + + // ---------- FINAL ---------- + return $decryptedData["redirectUrl"]; + } + + + + + + + diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index 0bed75f5..fcf5c373 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -792,6 +792,7 @@ class ClientController extends AdminController $editData['RM'] = $this->userModel->where('is_active', 1)->findAll(); $editData['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames(); + $editData['tpa_list'] = $this->tpaModel->where('is_active', 1)->findAll(); $editData['state'] = $this->stateModel->getAllStates(); $editData['police'] = $this->policesModel->findAll(); $editData['entity'] = $this->kycEntityTypeModel->findAll(); @@ -1439,7 +1440,9 @@ class ClientController extends AdminController $data['is_member_modify_allowed'] = $this->request->getPost('is_member_modify_allowed') ? 1 : 0; $data['enrolment_visibility'] = $this->request->getPost('enrolment_visibility') ? 1 : 0; $data['is_lgbtq'] = $this->request->getPost('is_lgbtq') ? 1 : 0; - + $data['wellness_plan_id'] = $this->request->getPost('wellness_plan_id'); + $data['wellness_vendor_id'] = $this->request->getPost('wellness_vendor_id'); + $data['wellness_vendor_id'] = !empty($data['wellness_vendor_id']) ? $data['wellness_vendor_id'] : null; if ($policy_type_id == 1 || $policy_type_id == 2 || $policy_type_id == 6 || $policy_type_id == 7) { @@ -1536,10 +1539,14 @@ class ClientController extends AdminController $data['cd_ac_pk'] = $this->request->getPost('cd_ac_no'); $data['gst'] = $this->request->getPost('gst'); $data['disclaimer'] = $this->request->getPost('disclaimer'); - $data['policy_start_date'] = change_date_format($this->request->getPost('policy_start_date'), 'd-m-Y', 'Y-m-d'); - $data['policy_end_date'] = change_date_format($this->request->getPost('policy_end_date'), 'd-m-Y', 'Y-m-d'); + $data['policy_start_date'] = change_date_format($this->request->getPost('policy_start_date'), 'd-m-Y', 'Y-m-d'); + $data['policy_end_date'] = change_date_format($this->request->getPost('policy_end_date'), 'd-m-Y', 'Y-m-d'); $data['is_member_modify_allowed'] = $this->request->getPost('is_member_modify_allowed') ? 1 : 0; - $data['is_lgbtq'] = $this->request->getPost('is_lgbtq') ? 1 : 0; + $data['is_lgbtq'] = $this->request->getPost('is_lgbtq') ? 1 : 0; + $data['wellness_plan_id'] = $this->request->getPost('wellness_plan_id'); + $data['wellness_vendor_id'] = $this->request->getPost('wellness_vendor_id'); + $data['wellness_vendor_id'] = !empty($data['wellness_vendor_id']) ? $data['wellness_vendor_id'] : null; + if ($data['inception_type'] == 2) { $data['open_date'] = change_date_format($this->request->getPost('open_date'), 'd-m-Y', 'Y-m-d'); $data['close_date'] = change_date_format($this->request->getPost('close_date'), 'd-m-Y', 'Y-m-d'); @@ -5645,11 +5652,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(); @@ -5673,12 +5678,19 @@ class ClientController extends AdminController // $response = $ticketServiceController->extractExcelData("claims_dump_form_client.xlsx"); // dd($response); + // ---------- TICKET SERVICE CONTROLLER -------------------------------------------------------------------------------- + + $TicketController = new TicketController(); + // $response = $TicketController->getMoreInfo($requestFrom = 'rest', $ticket_id = 70); + // dd($response); + // ---------- EMP SERVICE CONTROLLER -------------------------------------------------------------------------------- $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']); @@ -5687,13 +5699,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); @@ -6022,8 +6034,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') @@ -6136,10 +6148,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 dfaac349..1c22f967 100755 --- a/app/Controllers/EmpDataServiceController.php +++ b/app/Controllers/EmpDataServiceController.php @@ -4968,6 +4968,10 @@ class EmpDataServiceController extends BaseController 'client_policy_id' => $emp_details['client_policy_id'], ]; + if(empty($single_mail)){ + $params['all_member'] = 1; + } + $params['common'] = [ 'client_id' => $emp_details['client_id'], 'client_branch_id' => $emp_details['client_branch_id'], diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index a77a10cb..19563217 100755 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -16,7 +16,6 @@ use App\Controllers\VidalApiController; use App\Controllers\ICICILombardController; use App\Controllers\MediAssistApiController; - use App\Models\EmployeeModel; use App\Models\EmployeePolicyModel; use App\Models\ClientModel; @@ -43,8 +42,8 @@ use App\Models\HrFileUploadModel; -use App\Controllers\Jobs ; -use App\Controllers\JobWorker ; +use App\Controllers\Jobs; +use App\Controllers\JobWorker; use App\Controllers\TicketController; @@ -68,7 +67,7 @@ use Kreait\Firebase\Exception\MessagingException; class EmployeeRestController extends AdminController { - + use ResponseTrait; protected $myLogger; @@ -98,8 +97,8 @@ class EmployeeRestController extends AdminController protected $insurerModel; protected $hrFileUploadModel; protected $ticketMailTemplateModel; - - + + public function __construct() { // helper('utility'); @@ -111,7 +110,7 @@ class EmployeeRestController extends AdminController $this->clientRMModel = new ClientRMModel(); $this->policesModel = new PolicesModel(); $this->relationshipModel = new RelationshipModel(); - $this->fileModel= new FileModel(); + $this->fileModel = new FileModel(); $this->clientPolicyModel = new ClientPolicyModel(); $this->policyPremium1Model = new PolicyPremium1Model(); $this->policyPremium2Model = new PolicyPremium2Model(); @@ -131,13 +130,12 @@ class EmployeeRestController extends AdminController $this->insurerModel = new InsurerModel(); $this->hrFileUploadModel = new HrFileUploadModel(); $this->ticketMailTemplateModel = new TicketMailTemplateModel(); - } - + public function getEmployeeProfile() { - try { + try { $emp_code = $this->request->getGet('emp_code'); $client_id = $this->request->getGet('client_id'); $client_branch_id = $this->request->getGet('client_branch_id'); @@ -150,38 +148,37 @@ class EmployeeRestController extends AdminController // ->where('relationship', $relationship) // ->first(); $employee = $this->employeeModel - ->select('employees.*') - ->join('employee_polices', 'employees.id = employee_polices.employee_id') - ->where('employees.emp_code', $emp_code) - ->where('employees.client_id', $client_id) - ->where('employees.client_branch_id', $client_branch_id) - ->where('employees.is_active', 1 ) - ->where('employees.relationship', $relationship) - ->where('employee_polices.status', ['active']) - ->where('employees.is_active', 1) - ->where('employees.emp_status', ['active']) - ->first(); + ->select('employees.*') + ->join('employee_polices', 'employees.id = employee_polices.employee_id') + ->where('employees.emp_code', $emp_code) + ->where('employees.client_id', $client_id) + ->where('employees.client_branch_id', $client_branch_id) + ->where('employees.is_active', 1) + ->where('employees.relationship', $relationship) + ->where('employee_polices.status', ['active']) + ->where('employees.is_active', 1) + ->where('employees.emp_status', ['active']) + ->first(); - if (null !== $this->request->getGet('client_policy_id')) - { - $date_coverage = $this->employeePolicyModel->where('employee_id',$employee['id'])->where('client_policy_id',$this->request->getGet('client_policy_id'))->get()->getRow()->date_coverage; - $employee['date_coverage'] = $date_coverage; + if (null !== $this->request->getGet('client_policy_id')) { + $date_coverage = $this->employeePolicyModel->where('employee_id', $employee['id'])->where('client_policy_id', $this->request->getGet('client_policy_id'))->get()->getRow()->date_coverage; + $employee['date_coverage'] = $date_coverage; } $result = $employee; $AccountManagerDetails = $this->clientRMModel->select('client_rm.* , user_profiles.*') - ->join('user_profiles', 'client_rm.user_id = user_profiles.id', 'left') - ->where('client_rm.client_id', $client_id ) - ->where('client_rm.level', 3 ) - ->findAll(); - return $this->respond(['status' => 'success','code' => 200,'data' => $result, 'AccountManagerDetails'=> isset($AccountManagerDetails[0]) ? $AccountManagerDetails[0] : null ],200); + ->join('user_profiles', 'client_rm.user_id = user_profiles.id', 'left') + ->where('client_rm.client_id', $client_id) + ->where('client_rm.level', 3) + ->findAll(); + return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result, 'AccountManagerDetails' => isset($AccountManagerDetails[0]) ? $AccountManagerDetails[0] : null], 200); } else { $result = "No Match's"; - return $this->respond(['status' => 'failed','code' => 404,'data' => $result],404); + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 404); } - } catch (\Throwable $th) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500); - } + } catch (\Throwable $th) { + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $th], 500); + } } //not in use @@ -191,20 +188,19 @@ class EmployeeRestController extends AdminController $data = $this->request->getJSON(); if ($data) { $id = $data->id; - $employee = $this->employeeModel->where('is_active', 1 )->update($id, $data); + $employee = $this->employeeModel->where('is_active', 1)->update($id, $data); if ($employee) { $result = []; - return $this->respond(['status' => 'success','code' => 200,'data' => $result],200); + return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result], 200); } else { $result = "No Match's"; - return $this->respond(['status' => 'failed','code' => 404,'data' => $result],404); + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 404); } } - } catch (\Throwable $th) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500); - } - + } catch (\Throwable $th) { + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $th], 500); + } } //not in use @@ -213,8 +209,8 @@ class EmployeeRestController extends AdminController try { $emp_code = $this->request->getGet('emp_code'); if ($emp_code) { - $employee = $this->employeeModel->where('is_active', 1 )->where('emp_code', $emp_code)->findAll(); - $dateConverter = function($item) { + $employee = $this->employeeModel->where('is_active', 1)->where('emp_code', $emp_code)->findAll(); + $dateConverter = function ($item) { if ($item['dob'] !== '0000-00-00') { $dateTime = \DateTime::createFromFormat('Y-m-d', $item['dob']); $item['dob'] = $dateTime->format('d-m-Y'); @@ -222,16 +218,14 @@ class EmployeeRestController extends AdminController return $item; }; $employee = array_map($dateConverter, $employee); - return $this->respond(['status' => 'success','code' => 200,'data' => $employee],200); - + return $this->respond(['status' => 'success', 'code' => 200, 'data' => $employee], 200); } else { - - return $this->respond(['status' => 'failed','code' => 404,'data' => []],404); + + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 404); } - } catch (\Throwable $th) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500); - } - + } catch (\Throwable $th) { + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $th], 500); + } } //not in use @@ -245,257 +239,240 @@ class EmployeeRestController extends AdminController foreach ($data as $item) { $id = $item->id; $item->dob = $this->convertDateFormatYMD($item->dob); - $employee = $this->employeeModel->where('is_active', 1 )->update($id, (array)$item); + $employee = $this->employeeModel->where('is_active', 1)->update($id, (array)$item); if ($employee) { $updatedCount++; } } - + if ($updatedCount > 0) { $result = []; - return $this->respond(['status' => 'success','code' => 200,'data' => $result], 200); + return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result], 200); } else { $result = "No Matches"; - return $this->respond(['status' => 'failed','code' => 404,'data' => $result], 404); + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 404); } } } catch (\Exception $e) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $e], 500); + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e], 500); } - } - + public function addEmployeeAndDependence() { try { $data = $this->request->getJSON(); $openForEnrollment = $this->findThePolicyIsOpenForEnrollment($data[0]->client_policy_id); - if($openForEnrollment == false){ return $this->respond(['status' => 'failed','code' => 404,'data' => 'Enrollment closed'], 404); } + if ($openForEnrollment == false) { + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => 'Enrollment closed'], 404); + } if ($data) { $Count = 0; foreach ($data as $item) { - + if (isset($item->id)) { //update old data $id = $item->id; $item->family_floater_key = $this->RelationshipMap($item->relationship); - $item->gender = $this->GenderMap($item->relationship , $item->emp_code); + $item->gender = $this->GenderMap($item->relationship, $item->emp_code); $item->dob = $this->convertDateFormatYMD($item->dob); $item->emp_status = 'draft'; - $employee = $this->employeeModel->where('is_active', 1 )->update($id, (array)$item); + $employee = $this->employeeModel->where('is_active', 1)->update($id, (array)$item); if ($employee) { $Count++; } - }else{ + } else { //create new data $item->family_floater_key = $this->RelationshipMap($item->relationship); - $item->gender = $this->GenderMap($item->relationship , $item->emp_code); + $item->gender = $this->GenderMap($item->relationship, $item->emp_code); $item->dob = $this->convertDateFormatYMD($item->dob); $item->emp_status = 'draft'; - + $employee = $this->employeeModel->insert($item); - + if ($employee) { $Count++; } - } - + } } - + if ($Count > 0) { - if(isset($data[0]->id)) - { - $this->createEmployeePolicyData($data[0]->id , $data[0]->emp_code , $data[0]->client_id , $data[0]->client_policy_id , $data[0]->basic_cover_si); - }else - { - $payable_employee = $this->getEmployeePayableValue($data[0]->client_policy_id,$data[0]->relationship); - $this->createEmployeePolicyData($employee , $data[0]->emp_code , $data[0]->client_id , $data[0]->client_policy_id , $data[0]->basic_cover_si , $payable_employee); + if (isset($data[0]->id)) { + $this->createEmployeePolicyData($data[0]->id, $data[0]->emp_code, $data[0]->client_id, $data[0]->client_policy_id, $data[0]->basic_cover_si); + } else { + $payable_employee = $this->getEmployeePayableValue($data[0]->client_policy_id, $data[0]->relationship); + $this->createEmployeePolicyData($employee, $data[0]->emp_code, $data[0]->client_id, $data[0]->client_policy_id, $data[0]->basic_cover_si, $payable_employee); } - $this->updatePremiumAmount($data[0]->client_policy_id , $data[0]->emp_code , $data[0]->client_branch_id); + $this->updatePremiumAmount($data[0]->client_policy_id, $data[0]->emp_code, $data[0]->client_branch_id); $result = []; - return $this->respond(['status' => 'success','code' => 200,'data' => $result], 200); + return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result], 200); } else { $result = "No Matches"; - return $this->respond(['status' => 'failed','code' => 404,'data' => $result], 404); + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 404); } } } catch (\Exception $e) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500); + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500); } - } - public function getEmployeePayableValue($client_policy_id,$relationship) + public function getEmployeePayableValue($client_policy_id, $relationship) { - $terms = $this->clientPolicyModel->where('id',$client_policy_id)->get()->getRow()->policy_terms; + $terms = $this->clientPolicyModel->where('id', $client_policy_id)->get()->getRow()->policy_terms; - if(isset(json_decode($terms)->is_payable_employee)) - { + if (isset(json_decode($terms)->is_payable_employee)) { $is_payable_obj = json_decode($terms)->is_payable_employee; - if ($relationship === 'Mother' || $relationship === 'Father' || $relationship === 'Father in Law' || $relationship === 'Mother in Law') - { + if ($relationship === 'Mother' || $relationship === 'Father' || $relationship === 'Father in Law' || $relationship === 'Mother in Law') { return $is_payable_obj->elders; - } - else if($relationship === 'Son' || $relationship === 'Daughter') - { + } else if ($relationship === 'Son' || $relationship === 'Daughter') { return $is_payable_obj->childern; - } - else if($relationship === 'Spouse') - { + } else if ($relationship === 'Spouse') { return $is_payable_obj->spouse; } - - }else{ + } else { return 0; } - - - - } - public function createEmployeePolicyData($employee_id,$emp_code,$client_id,$client_policy_id,$basic_cover_si = null,$payable_employee = 0) + public function createEmployeePolicyData($employee_id, $emp_code, $client_id, $client_policy_id, $basic_cover_si = null, $payable_employee = 0) { - - if($basic_cover_si == null) - { + + if ($basic_cover_si == null) { $client_policy = $this->clientPolicyModel->where('id', $client_policy_id)->where('client_id', $client_id)->first(); $policy_terms = json_decode($client_policy['policy_terms']); $basic_cover_si = $policy_terms->sum_insured; - } + } - $checkDataExist = $this->employeePolicyModel->where('employee_id',$employee_id)->where('client_policy_id',$client_policy_id)->first(); + $checkDataExist = $this->employeePolicyModel->where('employee_id', $employee_id)->where('client_policy_id', $client_policy_id)->first(); - if($checkDataExist){ + if ($checkDataExist) { - $this->employeePolicyModel - ->where('client_policy_id',$client_policy_id ) - ->where('employee_id' , $employee_id ) - ->where('is_active', 1 ) - ->set(array('basic_cover_si'=> $basic_cover_si )) - ->update(); + $this->employeePolicyModel + ->where('client_policy_id', $client_policy_id) + ->where('employee_id', $employee_id) + ->where('is_active', 1) + ->set(array('basic_cover_si' => $basic_cover_si)) + ->update(); + } else { - }else{ + $data['employee_id'] = $employee_id; + $data['client_policy_id'] = $client_policy_id; + $data['basic_cover_si'] = $basic_cover_si; + $data['payable_employee'] = $payable_employee; + $data['status'] = 'draft'; + $data['date_coverage'] = $this->getEmployeeCoverageDate($emp_code, $client_policy_id); - $data['employee_id']= $employee_id; - $data['client_policy_id']= $client_policy_id; - $data['basic_cover_si']= $basic_cover_si; - $data['payable_employee']= $payable_employee; - $data['status']= 'draft'; - $data['date_coverage'] = $this->getEmployeeCoverageDate($emp_code, $client_policy_id); + $this->employeePolicyModel->insert($data); + } - $this->employeePolicyModel->insert($data); - - } - - return true; + return true; } - public function updatePremiumAmount($client_policy_id , $emp_code , $client_branch_id) + public function updatePremiumAmount($client_policy_id, $emp_code, $client_branch_id) { - $response = $this->calculatePremium($client_policy_id , $emp_code , null , $client_branch_id); - - if(count($response[$emp_code])) - { - - foreach ($response[$emp_code] as $key => $value) - { + $response = $this->calculatePremium($client_policy_id, $emp_code, null, $client_branch_id); - if(isset($value['temp'])) - { + if (count($response[$emp_code])) { + + foreach ($response[$emp_code] as $key => $value) { + + if (isset($value['temp'])) { $checkIfExist = $this->employeePolicyModel->where('employee_id', $value['temp']['emp_id']) - ->where('client_policy_id', $value['policy_details']['client_policy_id']) - ->where('is_active', 1 ) - ->findAll(); - if($checkIfExist) - { + ->where('client_policy_id', $value['policy_details']['client_policy_id']) + ->where('is_active', 1) + ->findAll(); + if ($checkIfExist) { $this->employeePolicyModel - ->where('client_policy_id',$value['policy_details']['client_policy_id'] ) - ->where('employee_id' , $value['temp']['emp_id'] ) - ->where('is_active', 1 ) - ->set(array('basic_cover_si' => $value['policy_details']['basic_cover_si'],'premium'=> $value['policy_details']['premium'] , 'rata_premimum'=> $value['policy_details']['rata_premimum'] , 'gst'=> $value['policy_details']['gst'] )) - ->update(); - + ->where('client_policy_id', $value['policy_details']['client_policy_id']) + ->where('employee_id', $value['temp']['emp_id']) + ->where('is_active', 1) + ->set(array('basic_cover_si' => $value['policy_details']['basic_cover_si'], 'premium' => $value['policy_details']['premium'], 'rata_premimum' => $value['policy_details']['rata_premimum'], 'gst' => $value['policy_details']['gst'])) + ->update(); } - } - - } } } public function getEmployeeCoverageDate($emp_code, $client_policy_id) { - $empData = $this->employeeModel->where('emp_code',$emp_code)->where('relationship', 'self')->where('is_active',1)->first();; - if($empData) - { + $empData = $this->employeeModel->where('emp_code', $emp_code)->where('relationship', 'self')->where('is_active', 1)->first();; + if ($empData) { $empPolicyData = $this->employeePolicyModel->select('employee_polices.employee_id,employee_polices.client_policy_id,employee_polices.date_coverage,client_policy.policy_type_id,client_policy.base_policy') - ->join('client_policy', 'client_policy.id = employee_polices.client_policy_id', 'left') - ->where('employee_polices.employee_id' , $empData['id'] ) - ->where('employee_polices.is_active' , 1 ) - ->findAll(); - if(count($empPolicyData)) - { + ->join('client_policy', 'client_policy.id = employee_polices.client_policy_id', 'left') + ->where('employee_polices.employee_id', $empData['id']) + ->where('employee_polices.is_active', 1) + ->findAll(); + if (count($empPolicyData)) { // find same policy 'self' date of coverage - $filterSelfPolicy = array_filter($empPolicyData, function($row) use ($client_policy_id) { + $filterSelfPolicy = array_filter($empPolicyData, function ($row) use ($client_policy_id) { return $row['client_policy_id'] == $client_policy_id; }); $filterSelfPolicy = array_values($filterSelfPolicy); // Reset the index of the filtered result - if(count($filterSelfPolicy)){ + if (count($filterSelfPolicy)) { return $filterSelfPolicy[0]['date_coverage']; - }else{ + } else { // find base policy 'self' date of coverage - $basePolicy = $this->clientPolicyModel->where('id',$client_policy_id)->get()->getRow()->base_policy; - - $filterSelfBasePolicy = array_filter($empPolicyData, function($row) use ($basePolicy) { + $basePolicy = $this->clientPolicyModel->where('id', $client_policy_id)->get()->getRow()->base_policy; + + $filterSelfBasePolicy = array_filter($empPolicyData, function ($row) use ($basePolicy) { return $row['client_policy_id'] == $basePolicy; }); $filterSelfBasePolicy = array_values($filterSelfBasePolicy); // Reset the index of the filtered result - if(count($filterSelfBasePolicy)){ + if (count($filterSelfBasePolicy)) { return $filterSelfBasePolicy[0]['date_coverage']; - }else{ return null; } + } else { + return null; + } } - - }else{ return null; } - - }else{ return null; } - } - - - public function RelationshipMap($value){ - - if ($value === 'Mother' || $value === 'Father') { - return 'parent'; - } else if($value === 'Son' || $value === 'Daughter'){ - return 'child'; - }else if($value === 'Father in Law' || $value === 'Mother in Law'){ - return 'parent_in_law'; - }else if($value === 'Spouse'){ - return 'spouse'; + } else { + return null; } + } else { + return null; + } } - public function GenderMap($value,$empCode){ - + + public function RelationshipMap($value) + { + + if ($value === 'Mother' || $value === 'Father') { + return 'parent'; + } else if ($value === 'Son' || $value === 'Daughter') { + return 'child'; + } else if ($value === 'Father in Law' || $value === 'Mother in Law') { + return 'parent_in_law'; + } else if ($value === 'Spouse') { + return 'spouse'; + } + } + + public function GenderMap($value, $empCode) + { + if ($value === 'Mother' || $value === 'Daughter' || $value === 'Mother in Law') { return 'F'; - } else if($value === 'Son' || $value === 'Father' || $value === 'Father in Law'){ + } else if ($value === 'Son' || $value === 'Father' || $value === 'Father in Law') { return 'M'; - }else if($value === 'Spouse'){ + } else if ($value === 'Spouse') { - $Gender = $this->employeeModel->where('emp_code',$empCode)->where('relationship','Self')->get()->getRow()->gender; - if($Gender == 'M'){ return 'F'; }else{ return 'M'; } + $Gender = $this->employeeModel->where('emp_code', $empCode)->where('relationship', 'Self')->get()->getRow()->gender; + if ($Gender == 'M') { + return 'F'; + } else { + return 'M'; + } } } @@ -526,196 +503,178 @@ class EmployeeRestController extends AdminController public function deleteDependence() { try { - - if($this->request->getGet('id')) - { - $this->employeeModel->where('id', $this->request->getGet('id') ) - ->where('is_active', 1 ) - ->set(array('is_active'=> 0 )) - ->update(); - $this->employeePolicyModel->where('employee_id',$this->request->getGet('id') ) - ->where('is_active', 1 ) - ->set(array('is_active'=> 0 )) - ->update(); - return $this->respond(['status' => 'success','code' => 200,'data' =>[] ], 200); - - }else{ - return $this->respond(['status' => 'failed','code' => 404,'data' => [] ], 404); + if ($this->request->getGet('id')) { + $this->employeeModel->where('id', $this->request->getGet('id')) + ->where('is_active', 1) + ->set(array('is_active' => 0)) + ->update(); + + $this->employeePolicyModel->where('employee_id', $this->request->getGet('id')) + ->where('is_active', 1) + ->set(array('is_active' => 0)) + ->update(); + return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200); + } else { + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 404); } - - } catch (\Exception $e) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500); + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500); } - } public function createOrUpdateEmployeePolicySiAmount() - { - + { + try { $requestData = $this->request->getJSON(); $openForEnrollment = $this->findThePolicyIsOpenForEnrollment($requestData[0]->client_policy_id); - if($openForEnrollment == false){ return $this->respond(['status' => 'failed','code' => 404,'data' => 'Enrollment closed'], 404); } + if ($openForEnrollment == false) { + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => 'Enrollment closed'], 404); + } - foreach ($requestData as $key => $value) - { + foreach ($requestData as $key => $value) { $checkIfExist = $this->employeePolicyModel->where('employee_id', $value->employee_id) - ->where('client_policy_id', $value->client_policy_id) - ->where('is_active', 1 ) - ->findAll(); - - + ->where('client_policy_id', $value->client_policy_id) + ->where('is_active', 1) + ->findAll(); + + if ($checkIfExist) { $empPolicy = $this->employeePolicyModel->updateSiAndPremium($value->client_policy_id, $value->employee_id, $value->basic_cover_si); + } else { - }else{ - - $data['employee_id']= $value->employee_id; - $data['client_policy_id']= $value->client_policy_id; - $data['basic_cover_si']= $value->basic_cover_si; + $data['employee_id'] = $value->employee_id; + $data['client_policy_id'] = $value->client_policy_id; + $data['basic_cover_si'] = $value->basic_cover_si; $data['status'] = 'draft'; - + $this->employeePolicyModel->insert($data); } } - if(count($requestData)) - { - $this->updatePremiumAmount($requestData[0]->client_policy_id , $requestData[0]->emp_code , $requestData[0]->client_branch_id); + if (count($requestData)) { + $this->updatePremiumAmount($requestData[0]->client_policy_id, $requestData[0]->emp_code, $requestData[0]->client_branch_id); } - - return $this->respond(['status' => 'success','code' => 200,'data' => []], 200); - + + return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200); } catch (\Exception $e) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500); + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500); } } - public function findPremiumAmount($slabArray,$siAmount) + public function findPremiumAmount($slabArray, $siAmount) { foreach ($slabArray as $key => $value) { - if($value['si'] == $siAmount){ + if ($value['si'] == $siAmount) { return $value['premium']; break; } - } + } } - + public function relationshipList() { try { - - $relation_ships= $this->relationshipModel->findAll(); - if(count($relation_ships) > 0){ - return $this->respond(['status' => 'success','code' => 200,'data' => $relation_ships], 200); - }else{ - return $this->respond(['status' => 'success','code' => 200,'data' => "No Data..!"], 200); + $relation_ships = $this->relationshipModel->findAll(); + + if (count($relation_ships) > 0) { + return $this->respond(['status' => 'success', 'code' => 200, 'data' => $relation_ships], 200); + } else { + return $this->respond(['status' => 'success', 'code' => 200, 'data' => "No Data..!"], 200); } - } catch (\Exception $e) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500); + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500); } } public function getEmployeeAndDependenceByClientId() { try { - $empData = $this->employeePolicyModel->getEmployeePolicy( client_id:$this->request->getGet('client_id'),policy_id: $this->request->getGet('client_policy_id'),status:0,branch_id:$this->request->getGet('client_branch_id')); - + $empData = $this->employeePolicyModel->getEmployeePolicy(client_id: $this->request->getGet('client_id'), policy_id: $this->request->getGet('client_policy_id'), status: 0, branch_id: $this->request->getGet('client_branch_id')); + if ($empData) { return $this->respond(['status' => 'success', 'code' => 200, 'data' => $empData], 200); } else { return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 404); } - - } catch (\Exception $e) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500); + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500); } - } public function exportDataByClientPolicyId() { try { - $empData = $this->employeePolicyModel->getEmployeePolicy( client_id:$this->request->getGet('client_id'),policy_id: $this->request->getGet('client_policy_id'),status:0,branch_id:$this->request->getGet('client_branch_id')); + $empData = $this->employeePolicyModel->getEmployeePolicy(client_id: $this->request->getGet('client_id'), policy_id: $this->request->getGet('client_policy_id'), status: 0, branch_id: $this->request->getGet('client_branch_id')); - if(count($empData)) - { - // Define headers and map database fields to Excel fields - $headers = [ - 'Employee Code' => 'emp_code', - 'Name' => 'name', - 'Relationship' => 'relationship', - 'DOB' => 'dob', - 'Gender' => 'gender', - 'Mobile' => 'mobile', - 'Email' => 'email_corporate', - 'SI' => 'basic_cover_si', - 'Premium' => 'rata_premimum', - 'Policy Name' => 'policy_name', - 'Insurer Branch Name' => 'insurer_branch_name', - 'TPA Name' => 'tpa_name', - 'Status' => 'emp_status' - ]; + if (count($empData)) { + // Define headers and map database fields to Excel fields + $headers = [ + 'Employee Code' => 'emp_code', + 'Name' => 'name', + 'Relationship' => 'relationship', + 'DOB' => 'dob', + 'Gender' => 'gender', + 'Mobile' => 'mobile', + 'Email' => 'email_corporate', + 'SI' => 'basic_cover_si', + 'Premium' => 'rata_premimum', + 'Policy Name' => 'policy_name', + 'Insurer Branch Name' => 'insurer_branch_name', + 'TPA Name' => 'tpa_name', + 'Status' => 'emp_status' + ]; - // Create a new Spreadsheet object - $spreadsheet = new Spreadsheet(); + // Create a new Spreadsheet object + $spreadsheet = new Spreadsheet(); - // Get the active sheet - $sheet = $spreadsheet->getActiveSheet(); + // Get the active sheet + $sheet = $spreadsheet->getActiveSheet(); - // Add headers - $column = 'A'; - foreach ($headers as $header => $dbField) { - $sheet->setCellValue($column . '1', $header); - $column++; - } - - // Add data - $row = 2; - foreach ($empData as $employee) { + // Add headers $column = 'A'; - foreach ($headers as $dbField) { - $sheet->setCellValue($column . $row, $employee[$dbField]); + foreach ($headers as $header => $dbField) { + $sheet->setCellValue($column . '1', $header); $column++; } - $row++; + + // Add data + $row = 2; + foreach ($empData as $employee) { + $column = 'A'; + foreach ($headers as $dbField) { + $sheet->setCellValue($column . $row, $employee[$dbField]); + $column++; + } + $row++; + } + + + // Set the header for download + $filename = $empData[0]['policy_name'] . '-Enrolment.xlsx'; + header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + header('Content-Disposition: attachment;filename="' . $filename . '"'); + header('Cache-Control: max-age=0'); + + // Save the Excel file to output + $writer = new Xlsx($spreadsheet); + $writer->save('php://output'); + exit; + + return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200); + } else { + + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200); } - - - // Set the header for download - $filename = $empData[0]['policy_name'].'-Enrolment.xlsx'; - header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); - header('Content-Disposition: attachment;filename="' . $filename . '"'); - header('Cache-Control: max-age=0'); - - // Save the Excel file to output - $writer = new Xlsx($spreadsheet); - $writer->save('php://output'); - exit; - - return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200); - - }else{ - - return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200); - } - - - - } catch (\Exception $e) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500); + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500); } - } //not in use @@ -723,35 +682,30 @@ class EmployeeRestController extends AdminController { try { $ClientPolicyData = $this->clientPolicyModel->select('client_policy.id as client_policy_id , client_policy.client_id as client_id, policies.id as policy_id,policies.policy_type_id as policy_type_id, policies.name as policy_name , client_policy.is_addon as is_addon') - ->join('policies', 'client_policy.policy_id = policies.id', 'left') - ->where('client_policy.client_id', $this->request->getGet('client_id') ) - ->findAll(); + ->join('policies', 'client_policy.policy_id = policies.id', 'left') + ->where('client_policy.client_id', $this->request->getGet('client_id')) + ->findAll(); $result = []; foreach ($ClientPolicyData as $key => $value) { - $getSlabAndGridData = $this->policesModel->getPolicySlabRatesForEmpOnboard( $value['client_policy_id'],$value['client_id']); - if($value['is_addon'] == "2"){ + $getSlabAndGridData = $this->policesModel->getPolicySlabRatesForEmpOnboard($value['client_policy_id'], $value['client_id']); + if ($value['is_addon'] == "2") { $value['type'] = 'SI TopUp'; - }else if($value['is_addon'] == "3"){ + } else if ($value['is_addon'] == "3") { $value['type'] = 'Dependent AddOn'; - }else{ + } else { $value['type'] = $getSlabAndGridData['grid_master']['policy_type']; } - - array_push($result,$value); - - + + array_push($result, $value); } if ($ClientPolicyData) { return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result], 200); } else { return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 404); } - - } catch (\Exception $e) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500); + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500); } - } // Upload the Employee Detail in DB by Sheet Data @@ -764,12 +718,12 @@ class EmployeeRestController extends AdminController $policy_id = $this->request->getPost('policy_id'); $client_data = $this->clientModel->where('id', $client_id)->first(); - $notification = $this->notificationModel->where('client_id',$client_id)->where('template_name','member_welcome_mail')->first(); + $notification = $this->notificationModel->where('client_id', $client_id)->where('template_name', 'member_welcome_mail')->first(); $jwt = $this->request->getHeaderLine('Authorization'); $jwtParts = explode(' ', $jwt); - + $token = $jwtParts[1]; $decodedPayload = json_decode(base64_decode(explode('.', $token)[1]), true); @@ -777,38 +731,36 @@ class EmployeeRestController extends AdminController // get the employee id from token $employee_id = $decodedPayload['id']; - + $client_policy = $this->clientPolicyModel->where('id', $policy_id)->where('client_id', $client_id)->where('client_branch_id', $client_branch_id)->first(); if ($client_policy) { $policy = $this->policesModel->where('id', $client_policy['policy_id'])->first(); - $policy_permium_1 = $this->policyPremium1Model->where(['client_id' => $client_id , 'client_policy_id' => $policy_id,'is_active' =>1])-> first(); - $policy_permium_2 = $this->policyPremium2Model->where(['client_id' => $client_id , 'client_policy_id' => $policy_id,'is_active' =>1])-> first(); + $policy_permium_1 = $this->policyPremium1Model->where(['client_id' => $client_id, 'client_policy_id' => $policy_id, 'is_active' => 1])->first(); + $policy_permium_2 = $this->policyPremium2Model->where(['client_id' => $client_id, 'client_policy_id' => $policy_id, 'is_active' => 1])->first(); $sum_insured_amount_for_check_employee_1 = isset($policy_permium_1['si']) ? $policy_permium_1['si'] : null; $sum_insured_amount_for_check_employee_2 = isset($policy_permium_2['si']) ? $policy_permium_2['si'] : null; $is_moved = $file->move(WRITEPATH . 'uploads/excel'); $filename = $file->getName(); - $file_name_with_path = WRITEPATH."/uploads/excel/".$filename; + $file_name_with_path = WRITEPATH . "/uploads/excel/" . $filename; //make an entry in DB - $file_id = $this->fileModel->insert(['file_name' => $filename, 'client_id' => $client_id, 'policy_id' => $policy_id, 'created_by' => $employee_id, 'status' => 'inprogress', 'action' => 'enrollment', 'client_branch_id' => $client_branch_id]); //here field policy_id have client_policy_id and not policy id from policy master + $file_id = $this->fileModel->insert(['file_name' => $filename, 'client_id' => $client_id, 'policy_id' => $policy_id, 'created_by' => $employee_id, 'status' => 'inprogress', 'action' => 'enrollment', 'client_branch_id' => $client_branch_id]); //here field policy_id have client_policy_id and not policy id from policy master $this->myLogger->logme("error", '{file_id} - client uploaded success', ['file_id' => $file_id]); - $empServiceController = new EmployeeServiceController(); - $result = $empServiceController->excelFileFormatValidation(['file_id' => $file_id]); - if(isset($result['error_summary']) && count($result['error_summary'])) - { + $empServiceController = new EmployeeServiceController(); + $result = $empServiceController->excelFileFormatValidation(['file_id' => $file_id]); + if (isset($result['error_summary']) && count($result['error_summary'])) { $result = $empServiceController->getExcelErrorData($file_id); - return $this->respond(['status' => 'failed', 'code' => 404, 'message' => "file upload failed with errors",'data' => $result], 200); - } - - + return $this->respond(['status' => 'failed', 'code' => 404, 'message' => "The data format is invalid. Click 'Next' to view details.", 'data' => $result], 200); + } + + //check the file exist or not - if(!file_exists($file_name_with_path)) - { + if (!file_exists($file_name_with_path)) { session()->setFlashdata('error', 'File not found'); return redirect()->to(base_url('employee/upload')); } @@ -824,7 +776,7 @@ class EmployeeRestController extends AdminController $highestRowAndColumn = $sheet->getHighestRowAndColumn(); $data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']); - + // $extractData['file_name']= $filename; // $extractData['client_id']= $client_id; // $extractData['client_branch_id']= $client_branch_id; @@ -876,25 +828,25 @@ class EmployeeRestController extends AdminController } } $dataToInsert = []; - $basic_cover_si= []; + $basic_cover_si = []; foreach ($extra['0'] as $index => $id) { - $relation =''; + $relation = ''; if (strtolower(trim($extra['5'][$index])) === 'mother' || strtolower(trim($extra['5'][$index])) === 'father') { $relation = 'parent'; - } else if(strtolower(trim($extra['5'][$index])) === 'son' || strtolower(trim($extra['5'][$index])) === 'daughter'){ + } else if (strtolower(trim($extra['5'][$index])) === 'son' || strtolower(trim($extra['5'][$index])) === 'daughter') { $relation = 'child'; - }else if(strtolower(trim($extra['5'][$index])) === 'father in law' || strtolower(trim($extra['5'][$index])) === 'mother in law'){ + } else if (strtolower(trim($extra['5'][$index])) === 'father in law' || strtolower(trim($extra['5'][$index])) === 'mother in law') { $relation = 'parent_in_law'; - }else if(strtolower(trim($extra['5'][$index])) === 'spouse'){ + } else if (strtolower(trim($extra['5'][$index])) === 'spouse') { $relation = 'spouse'; - }else{ + } else { $relation = 'self'; } // Simplified formatDate function // Assigning formatted dates - $doj = $extra['3'][$index] ; - $dob = $extra['6'][$index] ; + $doj = $extra['3'][$index]; + $dob = $extra['6'][$index]; // Change date format for $doj $doj_new_format = date('Y-m-d', strtotime($doj)); // $doj_new_format will be "2001-02-12" @@ -903,10 +855,10 @@ class EmployeeRestController extends AdminController $dob_new_format = date('Y-m-d', strtotime($dob)); // Your existing code here - $emp_code =isset($extra['1'][$index]) ? $extra['1'][$index] : 0; + $emp_code = isset($extra['1'][$index]) ? $extra['1'][$index] : 0; $name = $extra['2'][$index]; - if($emp_code != 0 && $name != '' || $name != null){ + if ($emp_code != 0 && $name != '' || $name != null) { $record = [ // 'id' => $id, 'emp_code' => $emp_code, @@ -918,64 +870,63 @@ class EmployeeRestController extends AdminController 'family_floater_key' => $relation, 'dob' => $dob_new_format, 'email_corporate' => $extra['7'][$index], - 'mobile'=> $extra['8'][$index], + 'mobile' => $extra['8'][$index], 'client_id' => $client_id, - 'emp_status'=>'draft', - 'band'=> $extra['10'][$index], - 'basic_pay'=> $extra['11'][$index], - 'unit'=> isset($extra['12'][$index]) ? $extra['12'][$index] : null, + 'emp_status' => 'draft', + 'band' => $extra['10'][$index], + 'basic_pay' => $extra['11'][$index], + 'unit' => isset($extra['12'][$index]) ? $extra['12'][$index] : null, 'client_branch_id' => $client_branch_id, - 'date_coverage' => $extra['13'][$index] != "" && $extra['13'][$index] != null ? change_date_format($extra['13'][$index],'d-M-Y','Y-m-d') : null - + 'date_coverage' => $extra['13'][$index] != "" && $extra['13'][$index] != null ? change_date_format($extra['13'][$index], 'd-M-Y', 'Y-m-d') : null + ]; $basic_cover_si_value = null; - + //Grid id is 10 and 11 sum insure value add only for self other grid type self sum insure is for the dependence - if (isset($policy_permium_2['policy_grid_id']) == 10 || isset($policy_permium_2['policy_grid_id']) == 11) { - if (strtolower($extra['5'][$index]) == 'self') { - $basic_cover_si_value = $extra['9'][$index]; - }else{ - $basic_cover_si_value = null; - } - }else{ - if (strtolower($extra['5'][$index]) == 'self') { - $basic_cover_si_value = $extra['9'][$index]; - }else{ - for ($i=0; $i < count($extra['1']) ; $i++) { - - if ($extra['1'][$i] == $extra['1'][$index]) { - if (strtolower($extra['5'][$i]) == 'self') { - $basic_cover_si_value = $extra['9'][$i]; - } + if (isset($policy_permium_2['policy_grid_id']) == 10 || isset($policy_permium_2['policy_grid_id']) == 11) { + if (strtolower($extra['5'][$index]) == 'self') { + $basic_cover_si_value = $extra['9'][$index]; + } else { + $basic_cover_si_value = null; + } + } else { + if (strtolower($extra['5'][$index]) == 'self') { + $basic_cover_si_value = $extra['9'][$index]; + } else { + for ($i = 0; $i < count($extra['1']); $i++) { + + if ($extra['1'][$i] == $extra['1'][$index]) { + if (strtolower($extra['5'][$i]) == 'self') { + $basic_cover_si_value = $extra['9'][$i]; } } } } - + } + $record2 = [ 'basic_cover_si' => $basic_cover_si_value, ]; $dataToInsert[] = $record; - $basic_cover_si[]= $basic_cover_si_value; + $basic_cover_si[] = $basic_cover_si_value; } } $count = 0; - $wholeData=[];// Initialize an empty array to store employee email. + $wholeData = []; // Initialize an empty array to store employee email. - for ($a=0; $a employeeModel->checkExistingEmployee($dataToInsert[$a],$client_branch_id); - $emp_id =0; - - $data_after_gpa_or_gmc =[]; + $employee = $this->employeeModel->checkExistingEmployee($dataToInsert[$a], $client_branch_id); + $emp_id = 0; + + $data_after_gpa_or_gmc = []; if ($client_policy['policy_type_id'] == 1) { if (strtolower($dataToInsert[$a]['relationship']) == 'self') { $data_after_gpa_or_gmc = $dataToInsert[$a]; } - }else{ + } else { $data_after_gpa_or_gmc = $dataToInsert[$a]; } date_default_timezone_set('Asia/Kolkata'); @@ -983,53 +934,53 @@ class EmployeeRestController extends AdminController $formatted_date_time = date('Y-m-d H:i:s', $current_timestamp); if ($employee) { - - $emp_id =$employee['id']; - $id =$emp_id; + + $emp_id = $employee['id']; + $id = $emp_id; $data_after_gpa_or_gmc['id'] = $id; $data_after_gpa_or_gmc['updated_by'] = $employee_id; $data_after_gpa_or_gmc['updated_at'] = $formatted_date_time; $result = $this->employeeModel->save($data_after_gpa_or_gmc); if ($result) { - $log_message = 'Update Employee - '.$employee['name'].'('.$employee['emp_code'].') with PK '.$employee['id']; - $this->myLogger->logme('error',('Update - ' . $employee['id'].' - '. $employee['emp_code'] .' - '.$employee['name'])); + $log_message = 'Update Employee - ' . $employee['name'] . '(' . $employee['emp_code'] . ') with PK ' . $employee['id']; + $this->myLogger->logme('error', ('Update - ' . $employee['id'] . ' - ' . $employee['emp_code'] . ' - ' . $employee['name'])); } - }else{ + } else { if ($dataToInsert[$a]['emp_code'] != 0) { - $result =false; + $result = false; if (count($data_after_gpa_or_gmc) != 0) { $data_after_gpa_or_gmc['created_by'] = $employee_id; $result = $this->employeeModel->insert($data_after_gpa_or_gmc); } - $emp_id =$result; + $emp_id = $result; if ($result) { $emp = $this->employeeModel->where('id', $result)->get()->getResult(); $policy_name = $this->employeePolicyModel->where('employee_id', $result)->get()->getResult();; - - - $log_message = 'Insert Employee- '.$dataToInsert[$a]['name'] .'('.$dataToInsert[$a]['emp_code'] .') with PK '; - $this->myLogger->logme('error',('Insert - ' . $dataToInsert[$a]['emp_code'] .' - '. $dataToInsert[$a]['name'])); + + + $log_message = 'Insert Employee- ' . $dataToInsert[$a]['name'] . '(' . $dataToInsert[$a]['emp_code'] . ') with PK '; + $this->myLogger->logme('error', ('Insert - ' . $dataToInsert[$a]['emp_code'] . ' - ' . $dataToInsert[$a]['name'])); } } } - $employee_policy = $this->employeePolicyModel->checkExistingEmpPolicy(['employee_id' => $emp_id,'client_policy_id' => $policy_id]); + $employee_policy = $this->employeePolicyModel->checkExistingEmpPolicy(['employee_id' => $emp_id, 'client_policy_id' => $policy_id]); - $emp_policy_data =[ - 'employee_id'=>$emp_id, - 'client_policy_id'=>$policy_id, - 'status'=> 'draft', + $emp_policy_data = [ + 'employee_id' => $emp_id, + 'client_policy_id' => $policy_id, + 'status' => 'draft', 'date_coverage' => $date_coverage, 'payable_employee' => check_pay_by_employee_or_company($client_policy['policy_terms'], $dataToInsert[$a]['relationship']), - 'basic_cover_si'=>isset($basic_cover_si[$a]) ? $basic_cover_si[$a] : null, + 'basic_cover_si' => isset($basic_cover_si[$a]) ? $basic_cover_si[$a] : null, 'file_id' => isset($employee_policy['file_id']) && $employee_policy['file_id'] != '' ? $employee_policy['file_id'] : $file_id, ]; // print_r($employee_policy); die; if ($employee_policy) { foreach ($employee_policy as $existing_policy) { - $emp_policy_data['id']= $existing_policy['id']; + $emp_policy_data['id'] = $existing_policy['id']; $emp_policy_data['updated_at'] = $formatted_date_time; $this->employeePolicyModel->save($emp_policy_data); } @@ -1043,21 +994,21 @@ class EmployeeRestController extends AdminController //trigger // $wholeData=[]; if ($dataToInsert[$a]['relationship'] == 'Self' && isset($dataToInsert[$a]['email_corporate']) && !empty($dataToInsert[$a]['email_corporate'])) { - + $params['dataToInsert'] = $dataToInsert[$a]; $params['notification'] = $notification; $params['client_data'] = $client_data; $params['common'] = [ - 'client_id' => $client_id, - 'client_branch_id' => $client_branch_id, + 'client_id' => $client_id, + 'client_branch_id' => $client_branch_id, 'client_policy_id' => $policy_id, 'employee_policy_id' => $emp_policy_id ?? null, 'employee_id' => $emp_id, 'mail_type' => 'member_welcome_mail', ]; - - $wholeData[] = sendMailNotification::sendMailNotification('member_welcome_mail', $params); - $count++; + + $wholeData[] = sendMailNotification::sendMailNotification('member_welcome_mail', $params); + $count++; } // if($count == 20 || $a == count($dataToInsert)-1){ @@ -1068,10 +1019,10 @@ class EmployeeRestController extends AdminController // $count = 0; // } // } - + // if ($dataToInsert[$a]['email_corporate'] != null || $dataToInsert[$a]['email_corporate'] != '' && $dataToInsert[$a]['relationship'] == 'Self') { - + } } @@ -1087,47 +1038,41 @@ class EmployeeRestController extends AdminController $r = Jobs::addJob(['job_name' => 'bulk_mail', 'payload' => $value]); } } - - $this->fileModel->where('id', $file_id)->set(['status' => 'success','reason' => '','error_data' => ''])->update(); - return $this->respond(['status' => 'success', 'code' => 200, 'message' => "Success" ], 200); - }else{ - return $this->respond(['status' => 'failed', 'code' => 404, 'message' => "Client id and Client Policy id is Not Match!" ], 404); + + $this->fileModel->where('id', $file_id)->set(['status' => 'success', 'reason' => '', 'error_data' => ''])->update(); + return $this->respond(['status' => 'success', 'code' => 200, 'message' => "Success"], 200); + } else { + return $this->respond(['status' => 'failed', 'code' => 404, 'message' => "Client id and Client Policy id is Not Match!"], 404); } } catch (\Exception $e) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500); + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500); } - - - - } //------------------------------------- - public function getAgeRange($terms,$familyFloatesValue) + public function getAgeRange($terms, $familyFloatesValue) { - - $ageRangeArray = ['self' => ['min' => 18, 'max' => 60] , 'spouse' => ['min' => 18, 'max' => 60] , 'child' => ['min' => 0, 'max' => 25] , 'elders' => ['min' => 18, 'max' => 60] ]; - $ageKey = (preg_replace('/\d/', '', $familyFloatesValue) == 'parent' || preg_replace('/\d/', '', $familyFloatesValue) == 'parent_in_law') ? 'elders' : preg_replace('/\d/', '', $familyFloatesValue); - if(isset($terms->age_ratio)){ - return $terms->age_ratio->$ageKey; - }else{ + $ageRangeArray = ['self' => ['min' => 18, 'max' => 60], 'spouse' => ['min' => 18, 'max' => 60], 'child' => ['min' => 0, 'max' => 25], 'elders' => ['min' => 18, 'max' => 60]]; + + $ageKey = (preg_replace('/\d/', '', $familyFloatesValue) == 'parent' || preg_replace('/\d/', '', $familyFloatesValue) == 'parent_in_law') ? 'elders' : preg_replace('/\d/', '', $familyFloatesValue); + if (isset($terms->age_ratio)) { + return $terms->age_ratio->$ageKey; + } else { return $ageRangeArray[$ageKey]; } - - } public function getEmployeePolicy() - { + { try { $id = $this->request->getGet('id'); $emp_code = $this->request->getGet('emp_code'); $client_id = $this->request->getGet('client_id'); - $client_branch_id = $this->request->getGet('client_branch_id'); - $login_by_hr = $this->request->getGet('login_by_hr'); + $client_branch_id = $this->request->getGet('client_branch_id'); + $login_by_hr = $this->request->getGet('login_by_hr'); // This is an array containing keys to be removed from the terms and conditions array $keysToRemove = ["removable_keys"]; @@ -1135,51 +1080,51 @@ class EmployeeRestController extends AdminController $empPolicy = $this->employeeModel->getEmployeePolicy($id); // dd($empPolicy); // Retrieve employee and dependents data by passing the employee code - $employeeData = $this->employeeModel->where('emp_code',$emp_code) - ->where('client_id',$client_id) - ->where('client_branch_id',$client_branch_id) - ->where('is_active', 1 ) - ->where('is_addon_value',0)->findAll(); + $employeeData = $this->employeeModel->where('emp_code', $emp_code) + ->where('client_id', $client_id) + ->where('client_branch_id', $client_branch_id) + ->where('is_active', 1) + ->where('is_addon_value', 0)->findAll(); + - if ($empPolicy) { $result = []; - foreach ($empPolicy as $array) { + foreach ($empPolicy as $array) { // Reset employee array $empData = $employeeData; - + // Removes specific keys from the decoded array and assigns the result to $refusingData $decodedArray = json_decode($array->Policy_Terms); $refusingData = (object) array_diff_key((array) $decodedArray, array_flip($keysToRemove)); $array->Policy_Terms = $refusingData; // Retrieve slab rate and grid master data by passing the ClientPolicyId and ClientId - $getSlabAndGridData = $this->policesModel->getPolicySlabRatesForEmpOnboard($array->ClientPolicyId,$array->ClientId); + $getSlabAndGridData = $this->policesModel->getPolicySlabRatesForEmpOnboard($array->ClientPolicyId, $array->ClientId); $array->SlabRates = $getSlabAndGridData['slab_rates']; $array->GridMaster = $getSlabAndGridData['grid_master']; - if($array->tpa_id != null){ - $array->eCardDownload = base_url('download-e-card/') . $array->rand_string.'/1'; - }else{ $array->eCardDownload = null; } + if ($array->tpa_id != null) { + $array->eCardDownload = base_url('download-e-card/') . $array->rand_string . '/1'; + } else { + $array->eCardDownload = null; + } // Construct value for policy type GPA // $getSlabAndGridData['grid_master']['policy_type'] == "GPA" - if($array->policy_type_id == 1 && $this->request->getGet('policy') == 'GPA') - { + if ($array->policy_type_id == 1 && $this->request->getGet('policy') == 'GPA') { $si_value = 0; $si_premium_value = 0; $si_gst_value = 0; // Filter employee data where the family_floater_key is 'self' - $selfData = array_filter($empData, fn($arr) => trim(strtolower($arr['family_floater_key'])) === 'self'); - $employee_policy = $this->employeePolicyModel->where('employee_id',$selfData[0]['id'])->where('client_policy_id',$array->ClientPolicyId)->where('is_active', 1 )->get()->getRow(); + $selfData = array_filter($empData, fn($arr) => trim(strtolower($arr['family_floater_key'])) === 'self'); + $employee_policy = $this->employeePolicyModel->where('employee_id', $selfData[0]['id'])->where('client_policy_id', $array->ClientPolicyId)->where('is_active', 1)->get()->getRow(); $si_value = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : 0; - if(isset($employee_policy->payable_employee) && $employee_policy->payable_employee == 1) - { + if (isset($employee_policy->payable_employee) && $employee_policy->payable_employee == 1) { $si_premium_value = $si_premium_value + $employee_policy->rata_premimum; $si_gst_value = $si_gst_value + $employee_policy->gst; } @@ -1191,56 +1136,57 @@ class EmployeeRestController extends AdminController $self['data']['name'] = $selfData[0]['name']; $self['data']['dob'] = $this->convertDateFormatDMY($selfData[0]['dob']); $self['data']['mobile'] = $selfData[0]['mobile']; - $self['data']['client_policy_id'] = $array->ClientPolicyId; - $self['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : 0; + $self['data']['client_policy_id'] = $array->ClientPolicyId; + $self['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : 0; $array->mapped_family_floaters = $self; $array->type = 'GPA'; $array->si_value = $si_value; $array->si_premium_value = $si_premium_value; $array->si_gst_value = $si_gst_value; - - + + $res = []; - array_push($res,$array); - $EDLIPolicy = $this->getAdditionalGPAPolicy($employeeData,6,$emp_code,$client_id,$client_branch_id,$login_by_hr); - if($EDLIPolicy){ array_push($res,$EDLIPolicy); } - $GTLIPolicy = $this->getAdditionalGPAPolicy($employeeData,7,$emp_code,$client_id,$client_branch_id,$login_by_hr); - if($GTLIPolicy){ array_push($res,$GTLIPolicy); } - return $this->respond(['status' => 'success','code' => 200,'data' => $res ], 200); - - - // Return result - if($this->request->getGet('policy') == 'GPA') - { - return $this->respond(['status' => 'success','code' => 200,'data' => $array], 200); + array_push($res, $array); + $EDLIPolicy = $this->getAdditionalGPAPolicy($employeeData, 6, $emp_code, $client_id, $client_branch_id, $login_by_hr); + if ($EDLIPolicy) { + array_push($res, $EDLIPolicy); } - - // Construct value for policy type GMC - // $getSlabAndGridData['grid_master']['policy_type'] == "GMC" - }else if($array->policy_type_id == 2 && $this->request->getGet('policy') == 'GMC' ) - { + $GTLIPolicy = $this->getAdditionalGPAPolicy($employeeData, 7, $emp_code, $client_id, $client_branch_id, $login_by_hr); + if ($GTLIPolicy) { + array_push($res, $GTLIPolicy); + } + return $this->respond(['status' => 'success', 'code' => 200, 'data' => $res], 200); + + + // Return result + if ($this->request->getGet('policy') == 'GPA') { + return $this->respond(['status' => 'success', 'code' => 200, 'data' => $array], 200); + } + + // Construct value for policy type GMC + // $getSlabAndGridData['grid_master']['policy_type'] == "GMC" + } else if ($array->policy_type_id == 2 && $this->request->getGet('policy') == 'GMC') { + + - - // Map family floaters that already exist in the employee table $familyFloates = $array->Policy_Terms->family_floaters; - + // Generate Notes string based on familyFloates terms $array->notes = $this->FloterNotesConvertion($familyFloates); - - if($getSlabAndGridData['slab_rates'][0]['premium_type'] == 1 || $getSlabAndGridData['slab_rates'][0]['premium_type'] == 3) - { + + if ($getSlabAndGridData['slab_rates'][0]['premium_type'] == 1 || $getSlabAndGridData['slab_rates'][0]['premium_type'] == 3) { $array->floter_text_heading = 'Floater Sum Insured'; $array->floter_text_description = 'This is a floater sum insured. A floater is a type of sum insured that provides coverage to more than one member ot a family at the same time. Simply put, its a single insurance cover for the entire family.'; - }else{ + } else { $array->floter_text_heading = 'Sum Insured'; $array->floter_text_description = ''; } // remove parent and parent-in-law from familyFloaters - if($familyFloates->{'either-parents-pil'} != 0){ + if ($familyFloates->{'either-parents-pil'} != 0) { unset($familyFloates->parents); unset($familyFloates->parents_in_law); } @@ -1250,34 +1196,39 @@ class EmployeeRestController extends AdminController $dependent_and_si_value = 0; $dependent_and_si_premium_value = 0; $dependent_and_si_gst_value = 0; - foreach ($floters as $familyFloatesValue) { + foreach ($floters as $familyFloatesValue) { $dependent = preg_replace('/\d/', '', $familyFloatesValue); - - if(count($empData)){ + + if (count($empData)) { foreach ($empData as $key => $value) { if ($value['family_floater_key'] === $dependent) { - $employee_policy = $this->employeePolicyModel->where('employee_id',$value['id'])->where('client_policy_id',$array->ClientPolicyId)->where('is_active', 1 )->get()->getRow(); - if(isset($employee_policy->basic_cover_si)){ $dependent_and_si_value = ($dependent_and_si_value == 0) ? $employee_policy->basic_cover_si : $dependent_and_si_value; } - if(isset($employee_policy->payable_employee) && $employee_policy->payable_employee == 1) - { - if(isset($employee_policy->rata_premimum)){ $dependent_and_si_premium_value = $dependent_and_si_premium_value + $employee_policy->rata_premimum;} - if(isset($employee_policy->gst)){ $dependent_and_si_gst_value = $dependent_and_si_gst_value + $employee_policy->gst;} + $employee_policy = $this->employeePolicyModel->where('employee_id', $value['id'])->where('client_policy_id', $array->ClientPolicyId)->where('is_active', 1)->get()->getRow(); + if (isset($employee_policy->basic_cover_si)) { + $dependent_and_si_value = ($dependent_and_si_value == 0) ? $employee_policy->basic_cover_si : $dependent_and_si_value; } - + if (isset($employee_policy->payable_employee) && $employee_policy->payable_employee == 1) { + if (isset($employee_policy->rata_premimum)) { + $dependent_and_si_premium_value = $dependent_and_si_premium_value + $employee_policy->rata_premimum; + } + if (isset($employee_policy->gst)) { + $dependent_and_si_gst_value = $dependent_and_si_gst_value + $employee_policy->gst; + } + } + $temp['is_value_exist'] = true; $temp['data']['family_floater_key'] = $familyFloatesValue; $temp['data']['employee_id'] = $value['id']; $temp['data']['relationship'] = $value['relationship']; $temp['data']['name'] = $value['name']; $temp['data']['dob'] = $this->convertDateFormatDMY($value['dob']); - $temp['data']['client_policy_id'] = $array->ClientPolicyId; - $temp['data']['form_type'] = $dependent; - $temp['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : 0; - - - $temp['data']['age_validation'] = $this->getAgeRange($decodedArray,$familyFloatesValue); - - array_push($data,$temp); + $temp['data']['client_policy_id'] = $array->ClientPolicyId; + $temp['data']['form_type'] = $dependent; + $temp['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : 0; + + + $temp['data']['age_validation'] = $this->getAgeRange($decodedArray, $familyFloatesValue); + + array_push($data, $temp); unset($empData[$key]); $floters = array_diff($floters, [$familyFloatesValue]); break; @@ -1285,54 +1236,57 @@ class EmployeeRestController extends AdminController } } } - - + + // Remove Unwanted floter key from floters array based on either-parents-pil term value - if($familyFloates->{'either-parents-pil'} == 1 && count($floters)) - { + if ($familyFloates->{'either-parents-pil'} == 1 && count($floters)) { $count_parent = 0; $count_parent_in_law = 0; foreach ($floters as $value) { - if (preg_replace('/\d/', '', $value) == 'parent') { $count_parent++; } - if (preg_replace('/\d/', '', $value) == 'parent_in_law') {$count_parent_in_law++;} + if (preg_replace('/\d/', '', $value) == 'parent') { + $count_parent++; + } + if (preg_replace('/\d/', '', $value) == 'parent_in_law') { + $count_parent_in_law++; + } } - if($count_parent != 2) { + if ($count_parent != 2) { $floters = array_filter($floters, fn($value) => strpos($value, 'parent_in_law') === false); } - if($count_parent_in_law != 2) { + if ($count_parent_in_law != 2) { $floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false || strpos($value, 'parent_in_law') !== false); } - } - else if($familyFloates->{'either-parents-pil'} == 2 && count($floters)) - { + } else if ($familyFloates->{'either-parents-pil'} == 2 && count($floters)) { $count_parent = 0; $count_parent_in_law = 0; foreach ($floters as $value) { - if (preg_replace('/\d/', '', $value) == 'parent') { $count_parent++; } - if (preg_replace('/\d/', '', $value) == 'parent_in_law') {$count_parent_in_law++;} + if (preg_replace('/\d/', '', $value) == 'parent') { + $count_parent++; + } + if (preg_replace('/\d/', '', $value) == 'parent_in_law') { + $count_parent_in_law++; + } } - if(($count_parent + $count_parent_in_law) == 2) { + if (($count_parent + $count_parent_in_law) == 2) { $floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false); } - } - + // Add family floter buttons placement data for FE validation - if(count($floters)){ + if (count($floters)) { foreach ($floters as $familyFloatesValue) { $temp2['is_value_exist'] = false; $temp2['data']['family_floater_key'] = $familyFloatesValue; - $temp2['data']['client_policy_id'] = $array->ClientPolicyId; - $temp2['data']['button_name'] = 'Add '.ucfirst(str_replace('_', ' ', preg_replace('/\d/', '', $familyFloatesValue))); + $temp2['data']['client_policy_id'] = $array->ClientPolicyId; + $temp2['data']['button_name'] = 'Add ' . ucfirst(str_replace('_', ' ', preg_replace('/\d/', '', $familyFloatesValue))); $temp2['data']['form_type'] = preg_replace('/\d/', '', $familyFloatesValue); - - - $temp2['data']['age_validation'] = $this->getAgeRange($decodedArray,$familyFloatesValue); - array_push($data,$temp2); + $temp2['data']['age_validation'] = $this->getAgeRange($decodedArray, $familyFloatesValue); + + array_push($data, $temp2); } } @@ -1341,56 +1295,51 @@ class EmployeeRestController extends AdminController $array->family_floaters_of_dependent_and_si_value = $dependent_and_si_value > 0 ? $dependent_and_si_value : 0; $array->family_floaters_of_dependent_and_si_premium_value = $dependent_and_si_premium_value > 0 ? round($dependent_and_si_premium_value) : 0; $array->family_floaters_of_dependent_and_gst_value = $dependent_and_si_gst_value > 0 ? round($dependent_and_si_gst_value) : 0; - + $checkGmcParentsPolicyExist = $this->clientPolicyModel->select('client_policy.id as ClientPolicyId , client_policy.client_id as ClientId, client_policy.policy_type_id as policy_type_id, policy_type.long_name as Policy_Name , client_policy.is_addon as is_addon , client_policy.open_for_enrollment as OpenForEnrollment , client_policy.inception_type as inception_type , client_policy.policy_terms as Policy_Terms') - ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left') - ->where('client_policy.policy_type_id', 3 ) - ->where('client_policy.is_addon', 1 ) - ->where('client_policy.client_id', $this->request->getGet('client_id') ) - ->where('client_policy.client_branch_id', $this->request->getGet('client_branch_id') ) - ->where('client_policy.is_active', 1 ) - ->get() - ->getResult(); - if($checkGmcParentsPolicyExist) - { - $GmcParrentsData = $this->getGmcParrentsPolicy($checkGmcParentsPolicyExist,$emp_code,$client_id,$client_branch_id); - return $this->respond(['status' => 'success','code' => 200,'data' => [$array,$GmcParrentsData]], 200); - + ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left') + ->where('client_policy.policy_type_id', 3) + ->where('client_policy.is_addon', 1) + ->where('client_policy.client_id', $this->request->getGet('client_id')) + ->where('client_policy.client_branch_id', $this->request->getGet('client_branch_id')) + ->where('client_policy.is_active', 1) + ->get() + ->getResult(); + if ($checkGmcParentsPolicyExist) { + $GmcParrentsData = $this->getGmcParrentsPolicy($checkGmcParentsPolicyExist, $emp_code, $client_id, $client_branch_id); + return $this->respond(['status' => 'success', 'code' => 200, 'data' => [$array, $GmcParrentsData]], 200); } - if($this->request->getGet('policy') == 'GMC'){ - return $this->respond(['status' => 'success','code' => 200,'data' => [$array]], 200); + if ($this->request->getGet('policy') == 'GMC') { + return $this->respond(['status' => 'success', 'code' => 200, 'data' => [$array]], 200); } - } - - // $result[] = $array; + + // $result[] = $array; } - return $this->respond(['status' => 'success','code' => 200,'data' => []], 200); - - - }else{ - return $this->respond(['status' => 'failed','code' => 404,'data' => []], 200); + return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200); + } else { + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200); } } catch (\Exception $e) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getLine()], 500); + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getLine()], 500); } } - public function getGmcParrentsPolicy($GmcParrentsPolicy,$emp_code,$client_id,$client_branch_id) + public function getGmcParrentsPolicy($GmcParrentsPolicy, $emp_code, $client_id, $client_branch_id) { - $employeeData = $this->employeeModel->where('emp_code',$emp_code) - ->where('client_id',$client_id) - ->where('client_branch_id',$client_branch_id) - ->where('is_active', 1 ) - ->where('is_addon_value',0)->findAll(); + $employeeData = $this->employeeModel->where('emp_code', $emp_code) + ->where('client_id', $client_id) + ->where('client_branch_id', $client_branch_id) + ->where('is_active', 1) + ->where('is_addon_value', 0)->findAll(); // return $employeeData; foreach ($GmcParrentsPolicy as $key => $array) { - + // Reset employee array $empData = $employeeData; @@ -1400,89 +1349,91 @@ class EmployeeRestController extends AdminController // Retrieve slab rate and grid master data by passing the ClientPolicyId and ClientId - $getSlabAndGridData = $this->policesModel->getPolicySlabRatesForEmpOnboard($array->ClientPolicyId,$array->ClientId); + $getSlabAndGridData = $this->policesModel->getPolicySlabRatesForEmpOnboard($array->ClientPolicyId, $array->ClientId); $array->SlabRates = $getSlabAndGridData['slab_rates']; $array->GridMaster = $getSlabAndGridData['grid_master']; $tpaArray = $this->employeeModel->select('employees.name as name , employee_polices.tpa_id as tpa_id , employee_polices.rand_string as rand_string') - ->join('employee_polices', 'employee_polices.employee_id = employees.id') - ->where('employees.emp_code',$emp_code) - ->where('employees.is_active',1) - ->where('employee_polices.client_policy_id',$array->ClientPolicyId) - ->get() - ->getResult(); - - if(count($tpaArray)) - { + ->join('employee_polices', 'employee_polices.employee_id = employees.id') + ->where('employees.emp_code', $emp_code) + ->where('employees.is_active', 1) + ->where('employee_polices.client_policy_id', $array->ClientPolicyId) + ->get() + ->getResult(); - if($tpaArray[0]->tpa_id != null) - $array->eCardDownload = base_url('download-e-card/') . $tpaArray[0]->rand_string.'/1'; - else - $array->eCardDownload = null; + if (count($tpaArray)) { - }else{ - $array->eCardDownload = null; + if ($tpaArray[0]->tpa_id != null) + $array->eCardDownload = base_url('download-e-card/') . $tpaArray[0]->rand_string . '/1'; + else + $array->eCardDownload = null; + } else { + $array->eCardDownload = null; } - + $array->eCardDownload = null; // Map family floaters that already exist in the employee table $familyFloates = $array->Policy_Terms->family_floaters; - + // Generate Notes string based on familyFloates terms $array->notes = $this->FloterNotesConvertion($familyFloates); - - if($getSlabAndGridData['slab_rates'][0]['premium_type'] == 1 || $getSlabAndGridData['slab_rates'][0]['premium_type'] == 3) - { + + if ($getSlabAndGridData['slab_rates'][0]['premium_type'] == 1 || $getSlabAndGridData['slab_rates'][0]['premium_type'] == 3) { $array->floter_text_heading = 'Floater Sum Insured'; $array->floter_text_description = 'This is a floater sum insured. A floater is a type of sum insured that provides coverage to more than one member ot a family at the same time. Simply put, its a single insurance cover for the entire family.'; - }else{ + } else { $array->floter_text_heading = 'Sum Insured'; $array->floter_text_description = ''; } // remove parent and parent-in-law from familyFloaters - if($familyFloates->{'either-parents-pil'} != 0){ + if ($familyFloates->{'either-parents-pil'} != 0) { unset($familyFloates->parents); unset($familyFloates->parents_in_law); } // Convert familyFloaters terms data to plain array $floters = $this->FloterConvertion($familyFloates); - + $data = []; $dependent_and_si_value = 0; $dependent_and_si_premium_value = 0; $dependent_and_si_gst_value = 0; - foreach ($floters as $familyFloatesValue) { + foreach ($floters as $familyFloatesValue) { $dependent = preg_replace('/\d/', '', $familyFloatesValue); - - if(count($empData)){ + + if (count($empData)) { foreach ($empData as $key => $value) { if ($value['family_floater_key'] === $dependent) { - $employee_policy = $this->employeePolicyModel->where('employee_id',$value['id'])->where('client_policy_id',$array->ClientPolicyId)->where('is_active', 1 )->get()->getRow(); - if(isset($employee_policy->basic_cover_si)){ $dependent_and_si_value = ($dependent_and_si_value == 0) ? $employee_policy->basic_cover_si : $dependent_and_si_value; } - if(isset($employee_policy->payable_employee) && $employee_policy->payable_employee == 1) - { - if(isset($employee_policy->rata_premimum)){ $dependent_and_si_premium_value = $dependent_and_si_premium_value + $employee_policy->rata_premimum;} - if(isset($employee_policy->gst)){ $dependent_and_si_gst_value = $dependent_and_si_gst_value + $employee_policy->gst;} + $employee_policy = $this->employeePolicyModel->where('employee_id', $value['id'])->where('client_policy_id', $array->ClientPolicyId)->where('is_active', 1)->get()->getRow(); + if (isset($employee_policy->basic_cover_si)) { + $dependent_and_si_value = ($dependent_and_si_value == 0) ? $employee_policy->basic_cover_si : $dependent_and_si_value; } - + if (isset($employee_policy->payable_employee) && $employee_policy->payable_employee == 1) { + if (isset($employee_policy->rata_premimum)) { + $dependent_and_si_premium_value = $dependent_and_si_premium_value + $employee_policy->rata_premimum; + } + if (isset($employee_policy->gst)) { + $dependent_and_si_gst_value = $dependent_and_si_gst_value + $employee_policy->gst; + } + } + $temp['is_value_exist'] = true; $temp['data']['family_floater_key'] = $familyFloatesValue; $temp['data']['employee_id'] = $value['id']; $temp['data']['relationship'] = $value['relationship']; $temp['data']['name'] = $value['name']; $temp['data']['dob'] = $this->convertDateFormatDMY($value['dob']); - $temp['data']['client_policy_id'] = $array->ClientPolicyId; - $temp['data']['form_type'] = $dependent; + $temp['data']['client_policy_id'] = $array->ClientPolicyId; + $temp['data']['form_type'] = $dependent; $temp['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : 0; - $temp['data']['age_validation'] = $this->getAgeRange($array->Policy_Terms,$familyFloatesValue); - - - array_push($data,$temp); + $temp['data']['age_validation'] = $this->getAgeRange($array->Policy_Terms, $familyFloatesValue); + + + array_push($data, $temp); unset($empData[$key]); $floters = array_diff($floters, [$familyFloatesValue]); break; @@ -1492,49 +1443,52 @@ class EmployeeRestController extends AdminController } // Remove Unwanted floter key from floters array based on either-parents-pil term value - if($familyFloates->{'either-parents-pil'} == 1 && count($floters)) - { + if ($familyFloates->{'either-parents-pil'} == 1 && count($floters)) { $count_parent = 0; $count_parent_in_law = 0; foreach ($floters as $value) { - if (preg_replace('/\d/', '', $value) == 'parent') { $count_parent++; } - if (preg_replace('/\d/', '', $value) == 'parent_in_law') {$count_parent_in_law++;} + if (preg_replace('/\d/', '', $value) == 'parent') { + $count_parent++; + } + if (preg_replace('/\d/', '', $value) == 'parent_in_law') { + $count_parent_in_law++; + } } - if($count_parent != 2) { + if ($count_parent != 2) { $floters = array_filter($floters, fn($value) => strpos($value, 'parent_in_law') === false); } - if($count_parent_in_law != 2) { + if ($count_parent_in_law != 2) { $floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false || strpos($value, 'parent_in_law') !== false); } - } - else if($familyFloates->{'either-parents-pil'} == 2 && count($floters)) - { + } else if ($familyFloates->{'either-parents-pil'} == 2 && count($floters)) { $count_parent = 0; $count_parent_in_law = 0; foreach ($floters as $value) { - if (preg_replace('/\d/', '', $value) == 'parent') { $count_parent++; } - if (preg_replace('/\d/', '', $value) == 'parent_in_law') {$count_parent_in_law++;} + if (preg_replace('/\d/', '', $value) == 'parent') { + $count_parent++; + } + if (preg_replace('/\d/', '', $value) == 'parent_in_law') { + $count_parent_in_law++; + } } - if(($count_parent + $count_parent_in_law) == 2) { + if (($count_parent + $count_parent_in_law) == 2) { $floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false); } - } // Add family floter buttons placement data for FE validation - if(count($floters)){ - foreach ($floters as $familyFloatesValue) { - - $temp2['is_value_exist'] = false; - $temp2['data']['family_floater_key'] = $familyFloatesValue; - $temp2['data']['client_policy_id'] = $array->ClientPolicyId; - $temp2['data']['button_name'] = 'Add '.ucfirst(str_replace('_', ' ', preg_replace('/\d/', '', $familyFloatesValue))); - $temp2['data']['form_type'] = preg_replace('/\d/', '', $familyFloatesValue); - $temp2['data']['age_validation'] = $this->getAgeRange($array->Policy_Terms,$familyFloatesValue); - array_push($data,$temp2); + if (count($floters)) { + foreach ($floters as $familyFloatesValue) { + $temp2['is_value_exist'] = false; + $temp2['data']['family_floater_key'] = $familyFloatesValue; + $temp2['data']['client_policy_id'] = $array->ClientPolicyId; + $temp2['data']['button_name'] = 'Add ' . ucfirst(str_replace('_', ' ', preg_replace('/\d/', '', $familyFloatesValue))); + $temp2['data']['form_type'] = preg_replace('/\d/', '', $familyFloatesValue); + $temp2['data']['age_validation'] = $this->getAgeRange($array->Policy_Terms, $familyFloatesValue); + array_push($data, $temp2); + } } - } $array->mapped_family_floaters = $data; $array->type = "GMC - Parents"; @@ -1543,24 +1497,22 @@ class EmployeeRestController extends AdminController $array->family_floaters_of_dependent_and_gst_value = $dependent_and_si_gst_value > 0 ? round($dependent_and_si_gst_value) : 0; return $array; - } - } - public function getAdditionalGPAPolicy($empData,$policy_type,$emp_code,$client_id,$client_branch_id,$login_by_hr) + public function getAdditionalGPAPolicy($empData, $policy_type, $emp_code, $client_id, $client_branch_id, $login_by_hr) { $checkPolicyExist = $this->clientPolicyModel->select('client_policy.id as ClientPolicyId , client_policy.client_id as ClientId, client_policy.policy_type_id as policy_type_id, client_policy.is_addon as is_addon , client_policy.open_for_enrollment as OpenForEnrollment , client_policy.inception_type as inception_type , client_policy.policy_terms as Policy_Terms , client_policy.enrolment_visibility') - ->where('client_policy.policy_type_id', $policy_type ) - ->where('client_policy.is_addon', 1 ) - ->where('client_policy.client_id', $client_id ) - ->where('client_policy.client_branch_id', $client_branch_id ) - ->where('client_policy.is_active', 1 ) - ->get() - ->getResult(); - - if($checkPolicyExist){ + ->where('client_policy.policy_type_id', $policy_type) + ->where('client_policy.is_addon', 1) + ->where('client_policy.client_id', $client_id) + ->where('client_policy.client_branch_id', $client_branch_id) + ->where('client_policy.is_active', 1) + ->get() + ->getResult(); + + if ($checkPolicyExist) { foreach ($checkPolicyExist as $key => $array) { @@ -1571,28 +1523,29 @@ class EmployeeRestController extends AdminController $si_gst_value = 0; // Filter employee data where the family_floater_key is 'self' - $selfData = array_filter($empData, fn($arr) => trim(strtolower($arr['family_floater_key'])) === 'self'); - $employee_policy = $this->employeePolicyModel->where('employee_id',$selfData[0]['id'])->where('client_policy_id',$array->ClientPolicyId)->where('is_active', 1 )->get()->getRow(); + $selfData = array_filter($empData, fn($arr) => trim(strtolower($arr['family_floater_key'])) === 'self'); + $employee_policy = $this->employeePolicyModel->where('employee_id', $selfData[0]['id'])->where('client_policy_id', $array->ClientPolicyId)->where('is_active', 1)->get()->getRow(); $si_value = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : 0; - if(isset($employee_policy->payable_employee) && $employee_policy->payable_employee == 1) - { + if (isset($employee_policy->payable_employee) && $employee_policy->payable_employee == 1) { $si_premium_value = $si_premium_value + $employee_policy->rata_premimum; $si_gst_value = $si_gst_value + $employee_policy->gst; } - $policyTypeData = $this->policyTypeModel->where('id',$policy_type)->get()->getRow(); + $policyTypeData = $this->policyTypeModel->where('id', $policy_type)->get()->getRow(); $array->type = $policyTypeData->policy_type; $array->Policy_Name = $policyTypeData->long_name; $array->si_value = $si_value; $array->si_premium_value = $si_premium_value; $array->si_gst_value = $si_gst_value; - - if($employee_policy){ - if($employee_policy->tpa_id != null){ - $array->eCardDownload = base_url('download-e-card/') . $employee_policy->rand_string.'/1'; - }else{ $array->eCardDownload = null; } + if ($employee_policy) { + + if ($employee_policy->tpa_id != null) { + $array->eCardDownload = base_url('download-e-card/') . $employee_policy->rand_string . '/1'; + } else { + $array->eCardDownload = null; + } $self['is_value_exist'] = true; $self['data']['family_floater_key'] = 'self'; @@ -1601,305 +1554,296 @@ class EmployeeRestController extends AdminController $self['data']['name'] = $selfData[0]['name']; $self['data']['dob'] = $this->convertDateFormatDMY($selfData[0]['dob']); $self['data']['mobile'] = $selfData[0]['mobile']; - $self['data']['client_policy_id'] = $array->ClientPolicyId; + $self['data']['client_policy_id'] = $array->ClientPolicyId; $self['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : 0; $array->mapped_family_floaters = $self; - if (isset($login_by_hr) && $login_by_hr == true) - { + if (isset($login_by_hr) && $login_by_hr == true) { return $array; - }else{ + } else { - if($array->enrolment_visibility == 1) + if ($array->enrolment_visibility == 1) return $array; else return false; - } - - - - }else{ - return false; + } else { + return false; } - - - } - } } - - public function FloterConvertion($array){ - $result = []; - - foreach ($array as $key => $value) { - if ($value > 0 && $key != 'elders_count') { - if ($value != 0 && $key === 'childrens') { + public function FloterConvertion($array) + { - if($value > 2){ $value = 2; } + $result = []; - for ($i = 1; $i <= $value; $i++) { - $result[] = "child" . $i; - } - } else if($value != 0 && $key ==='parents') { - for ($i = 1; $i <= $value; $i++) { - $result[] = "parent" . $i; - } - }else if($value != 0 && $key ==='parents-in-law') { - for ($i = 1; $i <= $value; $i++) { - $result[] = "parent_in_law" . $i; - } - }else if($value != 0 && $key ==='either-parents-pil') { - for ($i = 1; $i <= 2; $i++) { - $result[] = "parent" . $i; - $result[] = "parent_in_law" . $i; - } - }else { - $result[] = $key; + foreach ($array as $key => $value) { + if ($value > 0 && $key != 'elders_count') { + if ($value != 0 && $key === 'childrens') { + + if ($value > 2) { + $value = 2; } + + for ($i = 1; $i <= $value; $i++) { + $result[] = "child" . $i; + } + } else if ($value != 0 && $key === 'parents') { + for ($i = 1; $i <= $value; $i++) { + $result[] = "parent" . $i; + } + } else if ($value != 0 && $key === 'parents-in-law') { + for ($i = 1; $i <= $value; $i++) { + $result[] = "parent_in_law" . $i; + } + } else if ($value != 0 && $key === 'either-parents-pil') { + for ($i = 1; $i <= 2; $i++) { + $result[] = "parent" . $i; + $result[] = "parent_in_law" . $i; + } + } else { + $result[] = $key; } } + } - return $result; + return $result; } - public function FloterNotesConvertion($array){ + public function FloterNotesConvertion($array) + { $result = ' '; foreach ($array as $key => $value) { if ($value > 0) { - if($value == 1 && $key ==='either-parents-pil') { + if ($value == 1 && $key === 'either-parents-pil') { $result .= ' + Either 2 Parents or 2 Parents in law'; - }else if($value == 2 && $key ==='either-parents-pil') { + } else if ($value == 2 && $key === 'either-parents-pil') { $result .= ' + Any 2 of Parents and Parents in law'; - }else if($value != 0 && $key ==='spouse') { + } else if ($value != 0 && $key === 'spouse') { $string = str_replace('-', ' ', $key); $string = ucwords($string); - $result .= ' + '.$string; - }else if($value != 0 && $key ==='self') { + $result .= ' + ' . $string; + } else if ($value != 0 && $key === 'self') { $result = 'Allowed members Self '; - }else if($value != 0 && $key ==='childrens') { - if($value > 1){ $result .= ' + '.$value.' Children'; }else{ $result .= ' + '.$value.' Child'; } - }else if($value != 0 && $key ==='elders_count') { - - }else{ + } else if ($value != 0 && $key === 'childrens') { + if ($value > 1) { + $result .= ' + ' . $value . ' Children'; + } else { + $result .= ' + ' . $value . ' Child'; + } + } else if ($value != 0 && $key === 'elders_count') { + } else { $string = str_replace('-', ' ', $key); $string = ucwords($string); - $result .= ' + '.$value.' '.$string; + $result .= ' + ' . $value . ' ' . $string; } - - } } $first_two_chars = substr($result, 0, 3); - - if($first_two_chars == " +"){ + + if ($first_two_chars == " +") { $modified_string = substr($result, 3); - return "Allowed members ".$modified_string; - }else{ + return "Allowed members " . $modified_string; + } else { return $result; } - return substr($result, 0, 2) !== " +"; - - + return substr($result, 0, 2) !== " +"; } public function getClientDetails() - { + { try { - $client = $this->clientModel->where('id',$this->request->getGet('client_id'))->first(); - if(!empty($client)) { - $client['client_logo'] = base_url().'public/uploads/logo/'.$client['client_logo']; - $clientPolicy = $this->clientPolicyModel->where('client_id',$this->request->getGet('client_id')) - ->where('client_branch_id',$this->request->getGet('client_branch_id'))->findAll(); - return $this->respond(['status' => 'success','code' => 200,'data' => ['client'=>$client,'client_policy'=>$clientPolicy]], 200); - - }else{ - return $this->respond(['status' => 'failed','code' => 404,'data' => []], 404); + $client = $this->clientModel->where('id', $this->request->getGet('client_id'))->first(); + if (!empty($client)) { + $client['client_logo'] = base_url() . 'public/uploads/logo/' . $client['client_logo']; + $clientPolicy = $this->clientPolicyModel->where('client_id', $this->request->getGet('client_id')) + ->where('client_branch_id', $this->request->getGet('client_branch_id'))->findAll(); + return $this->respond(['status' => 'success', 'code' => 200, 'data' => ['client' => $client, 'client_policy' => $clientPolicy]], 200); + } else { + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 404); } } catch (\Exception $e) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500); + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500); } } public function getAddOnPolicy() - { + { try { - $addOnEmployeeData = $this->employeeModel->where('is_active', 1 ) - ->where('emp_code',$this->request->getGet('emp_code')) - ->where('client_id',$this->request->getGet('client_id')) - ->where('client_branch_id',$this->request->getGet('client_branch_id')) - ->where('is_addon_value',1)->findAll(); + $addOnEmployeeData = $this->employeeModel->where('is_active', 1) + ->where('emp_code', $this->request->getGet('emp_code')) + ->where('client_id', $this->request->getGet('client_id')) + ->where('client_branch_id', $this->request->getGet('client_branch_id')) + ->where('is_addon_value', 1)->findAll(); - - $clientPolicy = $this->clientPolicyModel->where('client_id',$this->request->getGet('client_id')) - ->where('client_branch_id',$this->request->getGet('client_branch_id')) - ->where('policy_status', 1) - ->where('is_active', 1) - ->findAll(); - - if(count($clientPolicy)) - { - $self = $this->employeeModel->where('employees.is_active', 1) - ->where('employees.emp_code', $this->request->getGet('emp_code')) - ->where('employees.client_id', $this->request->getGet('client_id')) - ->where('employees.client_branch_id', $this->request->getGet('client_branch_id')) - ->where('employees.family_floater_key', 'self') - ->get() - ->getRow(); - - $band = $self->band; - $PolicyData = []; - foreach ($clientPolicy as $key => $array) { - $responce = []; - - $decodedArray = json_decode($array['policy_terms']); - $policy_terms = $decodedArray; - $getSlabAndGridData = $this->policesModel->getPolicySlabRatesForEmpOnboard($array['id'],$array['client_id']); - $uniqueData = []; - $siValues = []; - foreach ($getSlabAndGridData['slab_rates'] as $item) { - if($getSlabAndGridData['grid_master']['emp_band'] == 1 ){ - if ($item['grade'] == $band) { - $uniqueData[] = $item; - } - }else{ - if (!in_array($item['si'], $siValues) ) { - if ($item['policy_grid_id'] == 11 && ($item['max_si'] != 0 || $item['max_si'] != null)) { - $uniqueData[] = $item; - $siValues[] = $item['si']; - }else if($item['policy_grid_id'] != 11){ - $uniqueData[] = $item; - $siValues[] = $item['si']; + $clientPolicy = $this->clientPolicyModel->where('client_id', $this->request->getGet('client_id')) + ->where('client_branch_id', $this->request->getGet('client_branch_id')) + ->where('policy_status', 1) + ->where('is_active', 1) + ->findAll(); + + if (count($clientPolicy)) { + $self = $this->employeeModel->where('employees.is_active', 1) + ->where('employees.emp_code', $this->request->getGet('emp_code')) + ->where('employees.client_id', $this->request->getGet('client_id')) + ->where('employees.client_branch_id', $this->request->getGet('client_branch_id')) + ->where('employees.family_floater_key', 'self') + ->get() + ->getRow(); + + $band = $self->band; + $PolicyData = []; + foreach ($clientPolicy as $key => $array) { + $responce = []; + + $decodedArray = json_decode($array['policy_terms']); + $policy_terms = $decodedArray; + $getSlabAndGridData = $this->policesModel->getPolicySlabRatesForEmpOnboard($array['id'], $array['client_id']); + $uniqueData = []; + $siValues = []; + foreach ($getSlabAndGridData['slab_rates'] as $item) { + if ($getSlabAndGridData['grid_master']['emp_band'] == 1) { + if ($item['grade'] == $band) { + $uniqueData[] = $item; + } + } else { + if (!in_array($item['si'], $siValues)) { + + if ($item['policy_grid_id'] == 11 && ($item['max_si'] != 0 || $item['max_si'] != null)) { + $uniqueData[] = $item; + $siValues[] = $item['si']; + } else if ($item['policy_grid_id'] != 11) { + $uniqueData[] = $item; + $siValues[] = $item['si']; + } + } } - } - } - - } - - $policyTypeData = $this->policyTypeModel->where('id',$array['policy_type_id'])->get()->getRow(); - $responce['policy_name'] = $policyTypeData->long_name; - $responce['type'] = $policyTypeData->policy_type; - $responce['SlabRates'] = $uniqueData; - $responce['GridMaster'] = $getSlabAndGridData['grid_master']; - $responce['client_id'] = $array['client_id']; - $responce['client_policy_id'] = $array['id']; - $responce['is_addon'] = $array['is_addon']; - $responce['OpenForEnrollment'] = $array['open_for_enrollment']; - $responce['policy_terms'] = $decodedArray; - $responce['policy_type_id'] = $array['policy_type_id']; - //$responce['is_member_modify_allowed'] = $array['is_member_modify_allowed']; - $responce['disclaimer'] = $array['disclaimer']; - $tpaArray = $this->employeeModel->select('employees.name as name , employee_polices.tpa_id as tpa_id , employee_polices.rand_string as rand_string') - ->join('employee_polices', 'employee_polices.employee_id = employees.id') - ->where('employees.emp_code',$this->request->getGet('emp_code')) - ->where('employees.is_active',1) - ->where('employee_polices.client_policy_id',$array['id']) + $policyTypeData = $this->policyTypeModel->where('id', $array['policy_type_id'])->get()->getRow(); + $responce['policy_name'] = $policyTypeData->long_name; + $responce['type'] = $policyTypeData->policy_type; + $responce['SlabRates'] = $uniqueData; + $responce['GridMaster'] = $getSlabAndGridData['grid_master']; + $responce['client_id'] = $array['client_id']; + $responce['client_policy_id'] = $array['id']; + $responce['is_addon'] = $array['is_addon']; + $responce['OpenForEnrollment'] = $array['open_for_enrollment']; + $responce['policy_terms'] = $decodedArray; + $responce['policy_type_id'] = $array['policy_type_id']; + //$responce['is_member_modify_allowed'] = $array['is_member_modify_allowed']; + $responce['disclaimer'] = $array['disclaimer']; + + $tpaArray = $this->employeeModel->select('employees.name as name , employee_polices.tpa_id as tpa_id , employee_polices.rand_string as rand_string') + ->join('employee_polices', 'employee_polices.employee_id = employees.id') + ->where('employees.emp_code', $this->request->getGet('emp_code')) + ->where('employees.is_active', 1) + ->where('employee_polices.client_policy_id', $array['id']) + ->get() + ->getResult(); + + + if (count($tpaArray)) { + if ($tpaArray[0]->tpa_id != null) + $responce['eCardDownload'] = base_url('download-e-card/') . $tpaArray[0]->rand_string . '/1'; + else + $responce['eCardDownload'] = null; + } else { + $responce['eCardDownload'] = null; + } + + if (count($getSlabAndGridData['slab_rates'])) { + if ($getSlabAndGridData['slab_rates'][0]['premium_type'] == 1 || $getSlabAndGridData['slab_rates'][0]['premium_type'] == 3) { + $responce['floter_text_heading'] = 'Floater Sum Insured'; + } else { + $responce['floter_text_heading'] = 'Sum Insured'; + } + } + + + if ($array['is_addon'] == 3 && $array['policy_type_id'] == 3) //dependent add on policy + { + + if ($this->request->getGet('client_id') == 8) // This changes only for client "sterling" + { + + $selfGMC = $this->employeeModel->select('employees.name , employee_polices.basic_cover_si') + ->join('employee_polices', 'employees.id = employee_polices.employee_id') + ->join('client_policy', 'client_policy.id = employee_polices.client_policy_id AND client_policy.policy_type_id = 2') + ->where('employees.is_active', 1) + ->where('employees.emp_code', $this->request->getGet('emp_code')) + ->where('employees.client_id', $this->request->getGet('client_id')) + ->where('employees.client_branch_id', $this->request->getGet('client_branch_id')) + ->where('employees.family_floater_key', 'self') ->get() - ->getResult(); - + ->getRow(); - if(count($tpaArray)) - { - if($tpaArray[0]->tpa_id != null) - $responce['eCardDownload'] = base_url('download-e-card/') . $tpaArray[0]->rand_string.'/1'; - else - $responce['eCardDownload'] = null; + $selfSi = $selfGMC->basic_cover_si; + $filteredSlabRates = array_filter($responce['SlabRates'], function ($rate) use ($selfSi) { + return $rate['si'] === $selfSi; + }); + // To reindex the array to have a proper 0 index + $responce['SlabRates'] = array_values($filteredSlabRates); + } - }else{ - $responce['eCardDownload'] = null; - } - - if(count($getSlabAndGridData['slab_rates'])){ - if($getSlabAndGridData['slab_rates'][0]['premium_type'] == 1 || $getSlabAndGridData['slab_rates'][0]['premium_type'] == 3) - { - $responce['floter_text_heading'] = 'Floater Sum Insured'; - }else{ - $responce['floter_text_heading'] = 'Sum Insured'; - } - } - - - if($array['is_addon'] == 3 && $array['policy_type_id'] == 3)//dependent add on policy - { - - if($this->request->getGet('client_id') == 8) // This changes only for client "sterling" - { - - $selfGMC = $this->employeeModel->select('employees.name , employee_polices.basic_cover_si') - ->join('employee_polices', 'employees.id = employee_polices.employee_id') - ->join('client_policy', 'client_policy.id = employee_polices.client_policy_id AND client_policy.policy_type_id = 2') - ->where('employees.is_active', 1) - ->where('employees.emp_code', $this->request->getGet('emp_code')) - ->where('employees.client_id', $this->request->getGet('client_id')) - ->where('employees.client_branch_id', $this->request->getGet('client_branch_id')) - ->where('employees.family_floater_key', 'self') - ->get() - ->getRow(); - - $selfSi = $selfGMC->basic_cover_si; - $filteredSlabRates = array_filter($responce['SlabRates'], function ($rate) use ($selfSi) { - return $rate['si'] === $selfSi; - }); - // To reindex the array to have a proper 0 index - $responce['SlabRates'] = array_values($filteredSlabRates); - - } - // Map family floaters that already exist in the employee table $familyFloates = $policy_terms->family_floaters; // remove parent and parent-in-law from familyFloaters - if($familyFloates->{'either-parents-pil'} != 0){ + if ($familyFloates->{'either-parents-pil'} != 0) { unset($familyFloates->parents); unset($familyFloates->parents_in_law); } // Convert familyFloaters terms data to plain array $floters = $this->FloterConvertion($familyFloates); - + $data = []; $dependent_and_si_value = 0; $dependent_and_si_premium_value = 0; $dependent_and_si_gst_value = 0; - foreach ($floters as $familyFloatesValue) { + foreach ($floters as $familyFloatesValue) { $dependent = preg_replace('/\d/', '', $familyFloatesValue); - if(count($addOnEmployeeData)){ + if (count($addOnEmployeeData)) { foreach ($addOnEmployeeData as $key => $value) { if ($value['family_floater_key'] === $dependent) { - $employee_policy = $this->employeePolicyModel->where('employee_id',$value['id'])->where('client_policy_id',$array['id'])->where('is_active', 1 )->get()->getRow(); - if(isset($employee_policy->basic_cover_si)){ $dependent_and_si_value = ($dependent_and_si_value == 0) ? $employee_policy->basic_cover_si : $dependent_and_si_value; } - if(isset($employee_policy->payable_employee) && $employee_policy->payable_employee == 1) - { - if(isset($employee_policy->rata_premimum)){ $dependent_and_si_premium_value = $dependent_and_si_premium_value + $employee_policy->rata_premimum;} - if(isset($employee_policy->gst)){ $dependent_and_si_gst_value = $dependent_and_si_gst_value + $employee_policy->gst;} + $employee_policy = $this->employeePolicyModel->where('employee_id', $value['id'])->where('client_policy_id', $array['id'])->where('is_active', 1)->get()->getRow(); + if (isset($employee_policy->basic_cover_si)) { + $dependent_and_si_value = ($dependent_and_si_value == 0) ? $employee_policy->basic_cover_si : $dependent_and_si_value; } - + if (isset($employee_policy->payable_employee) && $employee_policy->payable_employee == 1) { + if (isset($employee_policy->rata_premimum)) { + $dependent_and_si_premium_value = $dependent_and_si_premium_value + $employee_policy->rata_premimum; + } + if (isset($employee_policy->gst)) { + $dependent_and_si_gst_value = $dependent_and_si_gst_value + $employee_policy->gst; + } + } + $temp['is_value_exist'] = true; $temp['data']['family_floater_key'] = $familyFloatesValue; $temp['data']['employee_id'] = $value['id']; $temp['data']['relationship'] = $value['relationship']; $temp['data']['name'] = $value['name']; $temp['data']['dob'] = $this->convertDateFormatDMY($value['dob']); - $temp['data']['client_policy_id'] = $array['id']; - $temp['data']['form_type'] = $dependent; + $temp['data']['client_policy_id'] = $array['id']; + $temp['data']['form_type'] = $dependent; $temp['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : null; - $temp['data']['premium'] = isset($employee_policy->premium) ? $employee_policy->premium : null; - $temp['data']['age_validation'] = $this->getAgeRange($decodedArray,$familyFloatesValue); - - array_push($data,$temp); + $temp['data']['premium'] = isset($employee_policy->premium) ? $employee_policy->premium : null; + $temp['data']['age_validation'] = $this->getAgeRange($decodedArray, $familyFloatesValue); + + array_push($data, $temp); unset($addOnEmployeeData[$key]); $floters = array_diff($floters, [$familyFloatesValue]); break; @@ -1907,285 +1851,303 @@ class EmployeeRestController extends AdminController } } } - + //Remove Unwanted floter key from floters array based on either-parents-pil term value - if($familyFloates->{'either-parents-pil'} == 1 && count($floters)) - { - + if ($familyFloates->{'either-parents-pil'} == 1 && count($floters)) { + $count_parent = 0; $count_parent_in_law = 0; foreach ($floters as $value) { - if (preg_replace('/\d/', '', $value) == 'parent') { $count_parent++; } - if (preg_replace('/\d/', '', $value) == 'parent_in_law') {$count_parent_in_law++;} + if (preg_replace('/\d/', '', $value) == 'parent') { + $count_parent++; + } + if (preg_replace('/\d/', '', $value) == 'parent_in_law') { + $count_parent_in_law++; + } } - if($count_parent != 2) { + if ($count_parent != 2) { $floters = array_filter($floters, fn($value) => strpos($value, 'parent_in_law') === false); } - if($count_parent_in_law != 2) { + if ($count_parent_in_law != 2) { $floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false || strpos($value, 'parent_in_law') !== false); } - - - } - else if($familyFloates->{'either-parents-pil'} == 2 && count($floters)) - { + } else if ($familyFloates->{'either-parents-pil'} == 2 && count($floters)) { $count_parent = 0; - $count_parent_in_law = 0; - foreach ($floters as $value) { - if (preg_replace('/\d/', '', $value) == 'parent') { $count_parent++; } - if (preg_replace('/\d/', '', $value) == 'parent_in_law') {$count_parent_in_law++;} + $count_parent_in_law = 0; + foreach ($floters as $value) { + if (preg_replace('/\d/', '', $value) == 'parent') { + $count_parent++; } - if(($count_parent + $count_parent_in_law) == 2) { - $floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false); + if (preg_replace('/\d/', '', $value) == 'parent_in_law') { + $count_parent_in_law++; } - + } + if (($count_parent + $count_parent_in_law) == 2) { + $floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false); + } } - + // Add family floter buttons placement data for FE validation - if(count($floters)){ - foreach ($floters as $familyFloatesValue) { + if (count($floters)) { + foreach ($floters as $familyFloatesValue) { - $temp2['is_value_exist'] = false; - $temp2['data']['family_floater_key'] = $familyFloatesValue; - $temp2['data']['client_policy_id'] = $array['id']; - $temp2['data']['button_name'] = 'Add '.ucfirst(str_replace('_', ' ', preg_replace('/\d/', '', $familyFloatesValue))); - $temp2['data']['form_type'] = preg_replace('/\d/', '', $familyFloatesValue); - - $temp2['data']['age_validation'] = $this->getAgeRange($decodedArray,$familyFloatesValue); + $temp2['is_value_exist'] = false; + $temp2['data']['family_floater_key'] = $familyFloatesValue; + $temp2['data']['client_policy_id'] = $array['id']; + $temp2['data']['button_name'] = 'Add ' . ucfirst(str_replace('_', ' ', preg_replace('/\d/', '', $familyFloatesValue))); + $temp2['data']['form_type'] = preg_replace('/\d/', '', $familyFloatesValue); - array_push($data,$temp2); + $temp2['data']['age_validation'] = $this->getAgeRange($decodedArray, $familyFloatesValue); + array_push($data, $temp2); + } } - } - + $responce['family_floaters_of_dependent_and_si_array'] = $data; $responce['family_floaters_of_dependent_and_si_value'] = $dependent_and_si_value > 0 ? $dependent_and_si_value : 0; $responce['family_floaters_of_dependent_and_si_premium_value'] = $dependent_and_si_premium_value > 0 ? round($dependent_and_si_premium_value) : 0; $responce['family_floaters_of_dependent_and_gst_value'] = $dependent_and_si_gst_value > 0 ? round($dependent_and_si_gst_value) : 0; - - - if($this->request->getGet('policy') == 'GMC-DEPENDENT-ADDON'){ - return $this->respond(['status' => 'success','code' => 200,'data' => ['gmc_dependent_addon'=>$responce]], 200); - } - - //array_push($PolicyData, $responce); - }else if($array['is_addon'] == 2 && $array['policy_type_id'] == 4)//Topup policy - { - - $whereArray = []; - foreach ( $decodedArray->family_floaters as $key => $value) { - if($value != 0){ - if($key == 'parents'){ $text = ["parent"]; } - else if($key == 'childrens'){ $text = ["child"]; } - else if($key == 'parents-in-law'){ $text = ["parent_in_law"];} - else if($key ==='either-parents-pil') { $text = ["parent", "parent_in_law"];} - else{ $text = [$key]; } - $whereArray = array_merge($whereArray, $text); - } - } - - - $getAddOnType = $this->clientPolicyModel->where('id',$array['base_policy'])->where('policy_status', 1)->get()->getRow(); - $basePolicyAddOnType = $getAddOnType->is_addon; - // if is_addon value is 1 it is GMC if not it is one of the Add On policy - if($basePolicyAddOnType == 1){ $is_addon_value = 0; }else{ $is_addon_value = 1; } - $only_si_array = []; - $only_si_value = 0; - $only_si_premium_value = 0; - $only_si_gst_value = 0; - $BasePolicyEmployeeData = $this->employeeModel->where('is_active', 1 )->where('emp_code',$this->request->getGet('emp_code'))->where('client_id',$this->request->getGet('client_id'))->where('is_addon_value',$is_addon_value)->whereIn('family_floater_key',$whereArray)->findAll(); - foreach ($BasePolicyEmployeeData as $key => $value) { - - $employee_policy = $this->employeePolicyModel->where('employee_id',$value['id'])->where('client_policy_id',$array['id'])->where('is_active', 1 )->get()->getRow(); - if(isset($employee_policy->basic_cover_si)){ $only_si_value = ($only_si_value == 0) ? $employee_policy->basic_cover_si : $only_si_value; } - if(isset($employee_policy->payable_employee) && $employee_policy->payable_employee == 1) - { - if(isset($employee_policy->rata_premimum)){ $only_si_premium_value = $only_si_premium_value + $employee_policy->rata_premimum;} - if(isset($employee_policy->gst)){ $only_si_gst_value = $only_si_gst_value + $employee_policy->gst;} + if ($this->request->getGet('policy') == 'GMC-DEPENDENT-ADDON') { + return $this->respond(['status' => 'success', 'code' => 200, 'data' => ['gmc_dependent_addon' => $responce]], 200); } - $temp3['is_value_exist'] = true; - $temp3['data']['employee_id'] = $value['id']; - $temp3['data']['relationship'] = $value['relationship']; - $temp3['data']['name'] = $value['name']; - $temp3['data']['dob'] = $this->convertDateFormatDMY($value['dob']); - $temp3['data']['client_policy_id'] = $array['id']; - $temp3['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : null; - $temp3['data']['premium'] = isset($employee_policy->premium) ? $employee_policy->premium : null; - array_push($only_si_array,$temp3); - } + //array_push($PolicyData, $responce); - $responce['family_floaters_of_only_si_array'] = $only_si_array; - $responce['family_floaters_of_only_si_value'] = $only_si_value; - $responce['family_floaters_of_only_si_premium_value'] = round($only_si_premium_value); - $responce['family_floaters_of_only_si_gst_value'] = $only_si_gst_value; - - - if($this->request->getGet('policy') == 'GMC-SI-TOPUP'){ - return $this->respond(['status' => 'success','code' => 200,'data' => ['gmc_si_topup'=>$responce]], 200); - } + } else if ($array['is_addon'] == 2 && $array['policy_type_id'] == 4) //Topup policy + { - }else if($array['is_addon'] == 2 && $array['policy_type_id'] == 5)//Parents Topup policy - { + $whereArray = []; + foreach ($decodedArray->family_floaters as $key => $value) { + if ($value != 0) { + if ($key == 'parents') { + $text = ["parent"]; + } else if ($key == 'childrens') { + $text = ["child"]; + } else if ($key == 'parents-in-law') { + $text = ["parent_in_law"]; + } else if ($key === 'either-parents-pil') { + $text = ["parent", "parent_in_law"]; + } else { + $text = [$key]; + } + $whereArray = array_merge($whereArray, $text); + } + } - $whereArray = []; - foreach ( $decodedArray->family_floaters as $key => $value) { - if($value != 0){ - if($key == 'parents'){ $text = ["parent"]; } - else if($key == 'childrens'){ $text = ["child"]; } - else if($key == 'parents-in-law'){ $text = ["parent_in_law"];} - else if($key ==='either-parents-pil') { $text = ["parent", "parent_in_law"];} - else{ $text = [$key]; } - $whereArray = array_merge($whereArray, $text); + + $getAddOnType = $this->clientPolicyModel->where('id', $array['base_policy'])->where('policy_status', 1)->get()->getRow(); + $basePolicyAddOnType = $getAddOnType->is_addon; + // if is_addon value is 1 it is GMC if not it is one of the Add On policy + if ($basePolicyAddOnType == 1) { + $is_addon_value = 0; + } else { + $is_addon_value = 1; + } + $only_si_array = []; + $only_si_value = 0; + $only_si_premium_value = 0; + $only_si_gst_value = 0; + $BasePolicyEmployeeData = $this->employeeModel->where('is_active', 1)->where('emp_code', $this->request->getGet('emp_code'))->where('client_id', $this->request->getGet('client_id'))->where('is_addon_value', $is_addon_value)->whereIn('family_floater_key', $whereArray)->findAll(); + foreach ($BasePolicyEmployeeData as $key => $value) { + + $employee_policy = $this->employeePolicyModel->where('employee_id', $value['id'])->where('client_policy_id', $array['id'])->where('is_active', 1)->get()->getRow(); + if (isset($employee_policy->basic_cover_si)) { + $only_si_value = ($only_si_value == 0) ? $employee_policy->basic_cover_si : $only_si_value; + } + if (isset($employee_policy->payable_employee) && $employee_policy->payable_employee == 1) { + if (isset($employee_policy->rata_premimum)) { + $only_si_premium_value = $only_si_premium_value + $employee_policy->rata_premimum; + } + if (isset($employee_policy->gst)) { + $only_si_gst_value = $only_si_gst_value + $employee_policy->gst; + } + } + $temp3['is_value_exist'] = true; + $temp3['data']['employee_id'] = $value['id']; + $temp3['data']['relationship'] = $value['relationship']; + $temp3['data']['name'] = $value['name']; + $temp3['data']['dob'] = $this->convertDateFormatDMY($value['dob']); + $temp3['data']['client_policy_id'] = $array['id']; + $temp3['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : null; + $temp3['data']['premium'] = isset($employee_policy->premium) ? $employee_policy->premium : null; + array_push($only_si_array, $temp3); + } + + $responce['family_floaters_of_only_si_array'] = $only_si_array; + $responce['family_floaters_of_only_si_value'] = $only_si_value; + $responce['family_floaters_of_only_si_premium_value'] = round($only_si_premium_value); + $responce['family_floaters_of_only_si_gst_value'] = $only_si_gst_value; + + + if ($this->request->getGet('policy') == 'GMC-SI-TOPUP') { + return $this->respond(['status' => 'success', 'code' => 200, 'data' => ['gmc_si_topup' => $responce]], 200); + } + } else if ($array['is_addon'] == 2 && $array['policy_type_id'] == 5) //Parents Topup policy + { + + $whereArray = []; + foreach ($decodedArray->family_floaters as $key => $value) { + if ($value != 0) { + if ($key == 'parents') { + $text = ["parent"]; + } else if ($key == 'childrens') { + $text = ["child"]; + } else if ($key == 'parents-in-law') { + $text = ["parent_in_law"]; + } else if ($key === 'either-parents-pil') { + $text = ["parent", "parent_in_law"]; + } else { + $text = [$key]; + } + $whereArray = array_merge($whereArray, $text); + } + } + + $getAddOnType = $this->clientPolicyModel->where('id', $array['base_policy'])->where('policy_status', 1)->get()->getRow(); + $basePolicyAddOnType = $getAddOnType->is_addon; + // if is_addon value is 1 it is GMC if not it is one of the Add On policy + if ($basePolicyAddOnType == 1) { + $is_addon_value = 0; + } else { + $is_addon_value = 1; + } + $only_si_array = []; + $only_si_value = 0; + $only_si_premium_value = 0; + $only_si_gst_value = 0; + $BasePolicyEmployeeData = $this->employeeModel->where('is_active', 1)->where('emp_code', $this->request->getGet('emp_code'))->where('client_id', $this->request->getGet('client_id'))->where('is_addon_value', $is_addon_value)->whereIn('family_floater_key', $whereArray)->findAll(); + foreach ($BasePolicyEmployeeData as $key => $value) { + + $employee_policy = $this->employeePolicyModel->where('employee_id', $value['id'])->where('client_policy_id', $array['id'])->where('is_active', 1)->get()->getRow(); + if (isset($employee_policy->basic_cover_si)) { + $only_si_value = ($only_si_value == 0) ? $employee_policy->basic_cover_si : $only_si_value; + } + if (isset($employee_policy->payable_employee) && $employee_policy->payable_employee == 1) { + if (isset($employee_policy->rata_premimum)) { + $only_si_premium_value = $only_si_premium_value + $employee_policy->rata_premimum; + } + if (isset($employee_policy->gst)) { + $only_si_gst_value = $only_si_gst_value + $employee_policy->gst; + } + } + $temp3['is_value_exist'] = true; + $temp3['data']['employee_id'] = $value['id']; + $temp3['data']['relationship'] = $value['relationship']; + $temp3['data']['name'] = $value['name']; + $temp3['data']['dob'] = $this->convertDateFormatDMY($value['dob']); + $temp3['data']['client_policy_id'] = $array['id']; + $temp3['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : null; + $temp3['data']['premium'] = isset($employee_policy->premium) ? $employee_policy->premium : null; + array_push($only_si_array, $temp3); + } + + $responce['family_floaters_of_only_si_array'] = $only_si_array; + $responce['family_floaters_of_only_si_value'] = $only_si_value; + $responce['family_floaters_of_only_si_premium_value'] = round($only_si_premium_value); + $responce['family_floaters_of_only_si_gst_value'] = round($only_si_gst_value); + + + if ($this->request->getGet('policy') == 'GMC-SI-PARENT-TOPUP') { + return $this->respond(['status' => 'success', 'code' => 200, 'data' => ['gmc_si_parent_topup' => $responce]], 200); + } } } - $getAddOnType = $this->clientPolicyModel->where('id',$array['base_policy'])->where('policy_status', 1)->get()->getRow(); - $basePolicyAddOnType = $getAddOnType->is_addon; - // if is_addon value is 1 it is GMC if not it is one of the Add On policy - if($basePolicyAddOnType == 1){ $is_addon_value = 0; }else{ $is_addon_value = 1; } - $only_si_array = []; - $only_si_value = 0; - $only_si_premium_value = 0; - $only_si_gst_value = 0; - $BasePolicyEmployeeData = $this->employeeModel->where('is_active', 1 )->where('emp_code',$this->request->getGet('emp_code'))->where('client_id',$this->request->getGet('client_id'))->where('is_addon_value',$is_addon_value)->whereIn('family_floater_key',$whereArray)->findAll(); - foreach ($BasePolicyEmployeeData as $key => $value) { - $employee_policy = $this->employeePolicyModel->where('employee_id',$value['id'])->where('client_policy_id',$array['id'])->where('is_active', 1 )->get()->getRow(); - if(isset($employee_policy->basic_cover_si)){ $only_si_value = ($only_si_value == 0) ? $employee_policy->basic_cover_si : $only_si_value; } - if(isset($employee_policy->payable_employee) && $employee_policy->payable_employee == 1) - { - if(isset($employee_policy->rata_premimum)){ $only_si_premium_value = $only_si_premium_value + $employee_policy->rata_premimum;} - if(isset($employee_policy->gst)){ $only_si_gst_value = $only_si_gst_value + $employee_policy->gst;} - } - $temp3['is_value_exist'] = true; - $temp3['data']['employee_id'] = $value['id']; - $temp3['data']['relationship'] = $value['relationship']; - $temp3['data']['name'] = $value['name']; - $temp3['data']['dob'] = $this->convertDateFormatDMY($value['dob']); - $temp3['data']['client_policy_id'] = $array['id']; - $temp3['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : null; - $temp3['data']['premium'] = isset($employee_policy->premium) ? $employee_policy->premium : null; - array_push($only_si_array,$temp3); - - } - - $responce['family_floaters_of_only_si_array'] = $only_si_array; - $responce['family_floaters_of_only_si_value'] = $only_si_value; - $responce['family_floaters_of_only_si_premium_value'] = round($only_si_premium_value); - $responce['family_floaters_of_only_si_gst_value'] = round($only_si_gst_value); - - - if($this->request->getGet('policy') == 'GMC-SI-PARENT-TOPUP'){ - return $this->respond(['status' => 'success','code' => 200,'data' => ['gmc_si_parent_topup'=>$responce]], 200); - } - - - } - - } - - - return $this->respond(['status' => 'success','code' => 200,'data' => []], 200); - - }else{ - return $this->respond(['status' => 'failed','code' => 404,'data' => []], 200); + return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200); + } else { + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200); } } catch (\Exception $e) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500); + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500); } } public function iAgreeForAddOn() - { - + { + $postData = json_decode($this->request->getBody(), true); $this->myLogger->logme("error", $this->request->getBody()); $client_policy_id = $postData['client_policy_id']; sort($client_policy_id); - + $emp_code = $postData['emp_code']; $client_id = $postData['client_id']; - $empData = $this->employeeModel->where('emp_code', $emp_code )->where('client_id', $client_id ) ->where('is_active', 1 )->findAll(); + $empData = $this->employeeModel->where('emp_code', $emp_code)->where('client_id', $client_id)->where('is_active', 1)->findAll(); $employeeIds = array_column($empData, 'id'); //for mail common parameter $filteredEmpData = array_filter($empData, fn($item) => $item['relationship'] === 'Self'); - if (!is_null($client_policy_id) && is_array($client_policy_id)) - { + if (!is_null($client_policy_id) && is_array($client_policy_id)) { $array_list = []; - foreach ($client_policy_id as $key => $value) - { - $policy = $this->clientPolicyModel->where('id',$value)->where('open_for_enrollment',1)->find(); - if($policy) - { - $this->myLogger->logme("error", 'client policy id = '.$value.' is open for enrollment'); + foreach ($client_policy_id as $key => $value) { + $policy = $this->clientPolicyModel->where('id', $value)->where('open_for_enrollment', 1)->find(); + if ($policy) { + $this->myLogger->logme("error", 'client policy id = ' . $value . ' is open for enrollment'); - $empPolicyData = $this->employeePolicyModel->where('client_policy_id', $value ) - ->where('is_active', 1 ) - ->whereIn('employee_id',$employeeIds) - ->findAll(); - if(count($empPolicyData)) - { + $empPolicyData = $this->employeePolicyModel->where('client_policy_id', $value) + ->where('is_active', 1) + ->whereIn('employee_id', $employeeIds) + ->findAll(); + if (count($empPolicyData)) { $empIdsFromPolicyData = array_column($empPolicyData, 'employee_id'); //update emp polict table - $this->employeePolicyModel->where('client_policy_id', $value ) - ->where('is_active', 1 ) - ->whereIn('employee_id', $empIdsFromPolicyData ) - ->groupStart() - ->where('status', 'draft') - ->orWhere('status', 'enrolled') - ->groupEnd() - ->set(array('status'=>'enrolled')) - ->update(); + $this->employeePolicyModel->where('client_policy_id', $value) + ->where('is_active', 1) + ->whereIn('employee_id', $empIdsFromPolicyData) + ->groupStart() + ->where('status', 'draft') + ->orWhere('status', 'enrolled') + ->groupEnd() + ->set(array('status' => 'enrolled')) + ->update(); //update Employee table $this->employeeModel->where('emp_code', $emp_code) - ->whereIn('id', $empIdsFromPolicyData) - ->where('client_id', $client_id) - ->where('is_active', 1) - ->groupStart() - ->where('emp_status', 'draft') - ->orWhere('emp_status', 'enrolled') - ->groupEnd() - ->set(['emp_status' => 'enrolled']) - ->update(); - + ->whereIn('id', $empIdsFromPolicyData) + ->where('client_id', $client_id) + ->where('is_active', 1) + ->groupStart() + ->where('emp_status', 'draft') + ->orWhere('emp_status', 'enrolled') + ->groupEnd() + ->set(['emp_status' => 'enrolled']) + ->update(); } - $find = $this->employeeModel->getEmpFamilybyEmpCode(client_policy_id: $value,emp_code: $emp_code,client_id: $client_id,emp_status:['draft','enrolled'],policy_status:['draft','enrolled']); - if(count($find) > 0){ + $find = $this->employeeModel->getEmpFamilybyEmpCode(client_policy_id: $value, emp_code: $emp_code, client_id: $client_id, emp_status: ['draft', 'enrolled'], policy_status: ['draft', 'enrolled']); + if (count($find) > 0) { $array_list[] = $find; } - - }else { $this->myLogger->logme("error", 'client policy id = '.$value.' is not open for enrollment');} - + } else { + $this->myLogger->logme("error", 'client policy id = ' . $value . ' is not open for enrollment'); + } } - - $notification = $this->notificationModel->where('client_id' ,$client_id)->where('template_name', 'member_review_and_summary_mail')->first(); + + $notification = $this->notificationModel->where('client_id', $client_id)->where('template_name', 'member_review_and_summary_mail')->first(); if (isset($notification) && $notification['enabled'] == 1 && count($array_list)) { - $params ['array_list'] = $array_list; - $params ['client_policy_id'] = $client_policy_id; - $params ['emp_code'] = $emp_code; - $params ['client_id'] = $client_id; - $params ['notification'] = $notification; + $params['array_list'] = $array_list; + $params['client_policy_id'] = $client_policy_id; + $params['emp_code'] = $emp_code; + $params['client_id'] = $client_id; + $params['notification'] = $notification; $params['common'] = [ - 'client_id' => $filteredEmpData[0]['client_id'], - 'client_branch_id' => $filteredEmpData[0]['client_branch_id'], + 'client_id' => $filteredEmpData[0]['client_id'], + 'client_branch_id' => $filteredEmpData[0]['client_branch_id'], 'client_policy_id' => null, 'employee_policy_id' => null, 'employee_id' => $filteredEmpData[0]['id'], @@ -2193,208 +2155,201 @@ class EmployeeRestController extends AdminController ]; // print_r($params);die; - $wholeData =sendMailNotification::sendMailNotification('member_review_and_summary_mail', $params); + $wholeData = sendMailNotification::sendMailNotification('member_review_and_summary_mail', $params); $mail_send_return = MailHelper::send_email($wholeData[0]); $this->myLogger->logme("error", $mail_send_return); if (isset($wholeData[0])) { - - $params['common']['mail_type'] = 'account_maneger_summary_mail'; - $account_manager_wholeData =sendMailNotification::sendMailNotification('account_maneger_summary_mail', $params); - if($account_manager_wholeData != null && $account_manager_wholeData != '' && count($account_manager_wholeData)) - { + $params['common']['mail_type'] = 'account_maneger_summary_mail'; + $account_manager_wholeData = sendMailNotification::sendMailNotification('account_maneger_summary_mail', $params); + + if ($account_manager_wholeData != null && $account_manager_wholeData != '' && count($account_manager_wholeData)) { foreach ($account_manager_wholeData as $key => $value) { $mail_send_return1 = MailHelper::send_email($value); $this->myLogger->logme("error", $mail_send_return1); } - }else{ + } else { $this->myLogger->logme("error", 'Account Manager Mail Configuration not Enable for this client'); } $params['common']['mail_type'] = 'client_hr_summary_mail'; - $client_hr_wholeData =sendMailNotification::sendMailNotification('client_hr_summary_mail', $params); + $client_hr_wholeData = sendMailNotification::sendMailNotification('client_hr_summary_mail', $params); - if($client_hr_wholeData != null && $client_hr_wholeData != '' &&count($client_hr_wholeData)) - { + if ($client_hr_wholeData != null && $client_hr_wholeData != '' && count($client_hr_wholeData)) { foreach ($client_hr_wholeData as $key => $value) { $mail_send_return2 = MailHelper::send_email($value); $this->myLogger->logme("error", $mail_send_return2); } - }else{ + } else { $this->myLogger->logme("error", 'Client HR Mail Configuration not Enable for this client'); } } - }else{ + } else { $this->myLogger->logme("error", 'Member Review Mail Configuration not Enable for this client'); } - } - - return $this->respond(['status' => 'success','code' => 200,'data' => [] ], 200); + + return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200); } //Post method - which receives client_policy id and empcode of the family. //Pull records againest emp code and calculate premium // retun array - public function calculatePremium($clientPolicyId = null , $empCode = null, $default_si = null , $client_branch_id = null)//family level - { + public function calculatePremium($clientPolicyId = null, $empCode = null, $default_si = null, $client_branch_id = null) //family level + { // dd($clientPolicyId, $empCode, $default_si, $client_branch_id); helper('excel_util_helper'); - if($this->request){ // + if ($this->request) { // $client_policy_id = $this->request->getVar('client_policy_id') ?? $clientPolicyId; $emp_code = $this->request->getVar('emp_code') ?? $empCode; - $default_si = $this->request->getVar('si') ?? $default_si;// si amt which choosed in add on policy + $default_si = $this->request->getVar('si') ?? $default_si; // si amt which choosed in add on policy $client_branch_id = $this->request->getVar('client_branch_id') ?? $client_branch_id; - }else{ + } else { //Cli and enrollment $client_policy_id = $clientPolicyId; $emp_code = $empCode; - $default_si = $default_si;// si amt which choosed in add on policy - $client_branch_id =$client_branch_id; + $default_si = $default_si; // si amt which choosed in add on policy + $client_branch_id = $client_branch_id; } // dd($client_policy_id); $client_id = ($this->clientPolicyModel->select('client_id')->find($client_policy_id))['client_id']; // get policy and rack details - $policy_terms = $this->clientPolicyModel->getPolicyDetails($client_id,$client_policy_id); + $policy_terms = $this->clientPolicyModel->getPolicyDetails($client_id, $client_policy_id); $policy_type = $policy_terms[0]->is_addon; $base_policy = $policy_terms[0]->base_policy; - $policy_terms = (array) $policy_terms[0];// convert obj to array + $policy_terms = (array) $policy_terms[0]; // convert obj to array //get policy slab rates - $slab_details = $this->policesModel->getPolicySlabRatesForEmpOnboard($client_policy_id,$client_id); + $slab_details = $this->policesModel->getPolicySlabRatesForEmpOnboard($client_policy_id, $client_id); // print_r($slab_details);die(); - $existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(client_id: $client_id,client_policy_id: $client_policy_id,emp_code: $emp_code,emp_status:['draft','enrolled'],policy_status:['draft','enrolled']); + $existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(client_id: $client_id, client_policy_id: $client_policy_id, emp_code: $emp_code, emp_status: ['draft', 'enrolled'], policy_status: ['draft', 'enrolled']); - if(!count($existing_famility_details) && $policy_type == 2)//top up addon only + if (!count($existing_famility_details) && $policy_type == 2) //top up addon only { //get basepolicy id then pull emplist from base policy if only current policy is DA addon policy and emplist is zero // echo 'inside'; $client_policy_id = $base_policy; - $existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(client_id: $client_id,client_policy_id: $client_policy_id,emp_code: $emp_code,emp_status:['draft','enrolled'],policy_status:['draft','enrolled']); + $existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(client_id: $client_id, client_policy_id: $client_policy_id, emp_code: $emp_code, emp_status: ['draft', 'enrolled'], policy_status: ['draft', 'enrolled']); } - $file = ['id' => null,'client_id' => $client_id,'policy_id' => $client_policy_id,'action' => 'inception']; + $file = ['id' => null, 'client_id' => $client_id, 'policy_id' => $client_policy_id, 'action' => 'inception']; // dd($this->employeeModel->getLastQuery()); // print_r($existing_famility_details);die(); - $employee_data_group_by_family = data_group_by_family($existing_famility_details,$data_source = 'db'); + $employee_data_group_by_family = data_group_by_family($existing_famility_details, $data_source = 'db'); // print_r(($employee_data_group_by_family));//die(); - $existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $client_id,client_branch_id: $client_branch_id); + $existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $client_id, client_branch_id: $client_branch_id); - foreach ($employee_data_group_by_family as $emp_id => $family) - { + foreach ($employee_data_group_by_family as $emp_id => $family) { $transformed_famility_details = transform_db_data_to_excel($family); - $data = calculate_premium_new(family_data: $transformed_famility_details,policy_terms:$policy_terms,slab_details:$slab_details,fileArr: $file,existing_units: $existing_units,default_si : $default_si); - + $data = calculate_premium_new(family_data: $transformed_famility_details, policy_terms: $policy_terms, slab_details: $slab_details, fileArr: $file, existing_units: $existing_units, default_si: $default_si); + $employee_data_group_by_family[$emp_id] = $data; - } - if($clientPolicyId != null && $empCode != null) - { - return $employee_data_group_by_family; - }else{ + if ($clientPolicyId != null && $empCode != null) { + return $employee_data_group_by_family; + } else { // dd ($employee_data_group_by_family); - return $this->respond(['status' => 'success','code' => (count($employee_data_group_by_family) ? 200 : 404),'data' => [$employee_data_group_by_family] ], 200); - + return $this->respond(['status' => 'success', 'code' => (count($employee_data_group_by_family) ? 200 : 404), 'data' => [$employee_data_group_by_family]], 200); } - } - public function getHRAccessData( $hr_id = null , $request_for = 'post_enrollment') + public function getHRAccessData($hr_id = null, $request_for = 'post_enrollment') { $hr_id = $this->request->getGet('hr_id') ?? $hr_id; $request_for = $this->request->getGet('request_for') ?? $request_for; - if($request_for == 'pre_enrollment'){ $idField = 'pre_hr_id'; }else{ $idField = 'post_hr_id'; } + if ($request_for == 'pre_enrollment') { + $idField = 'pre_hr_id'; + } else { + $idField = 'post_hr_id'; + } - $data = $this->hrAccessControlModel->where($idField , $hr_id)->where('is_active' , 1)->first(); + $data = $this->hrAccessControlModel->where($idField, $hr_id)->where('is_active', 1)->first(); - if($request_for == 'post_enrollment'){ return $data ?? []; } + if ($request_for == 'post_enrollment') { + return $data ?? []; + } - return $this->respond(['status' => (($data) ? 'success' : 'failed'),'code' => (($data) ? 200 : 404),'data' => $data ], 200); + return $this->respond(['status' => (($data) ? 'success' : 'failed'), 'code' => (($data) ? 200 : 404), 'data' => $data], 200); } public function getPolicyLevelEmployeeSummaryData() { - $hr_id = $this->request->getGet('hr_id'); - $HRAccessData = $this->getHRAccessData($hr_id,'post_enrollment'); + $hr_id = $this->request->getGet('hr_id'); + $HRAccessData = $this->getHRAccessData($hr_id, 'post_enrollment'); - if(isset($HRAccessData['allowed_active_policies'])) - { - $policyId = json_decode($HRAccessData['allowed_active_policies'],true); - }else{ - $policyId = []; - } + if (isset($HRAccessData['allowed_active_policies'])) { + $policyId = json_decode($HRAccessData['allowed_active_policies'], true); + } else { + $policyId = []; + } - if(count($policyId) == 0){ - return $this->respond(['status' => 'failed','code' => (count($policyId) ? 200 : 404),'data' => [] ], 200); - } + if (count($policyId) == 0) { + return $this->respond(['status' => 'failed', 'code' => (count($policyId) ? 200 : 404), 'data' => []], 200); + } - - - $ClientPolicyData = $this->clientPolicyModel->select('client_policy.id as client_policy_id , client_policy.client_id as client_id, client_policy.policy_type_id as policy_type_id, client_policy.is_addon as is_addon , client_policy.open_for_enrollment as OpenForEnrollment , client_policy.inception_type as inception_type, client_policy.policy_no as policy_no, client_policy.insurer_id as insurer_id, DATE_FORMAT(client_policy.policy_end_date, "%d-%m-%Y") AS policy_expiry_date ') - ->where('client_policy.client_id', $this->request->getGet('client_id') ) - ->where('client_policy.client_branch_id', $this->request->getGet('client_branch_id') ) - ->where('client_policy.is_active', 1 ) - ->where('client_policy.policy_status', $this->request->getGet('policy_status')) - ->whereIn('client_policy.id', $policyId) - ->findAll(); - - $result = []; - // dd( $ClientPolicyData); - foreach ($ClientPolicyData as $key => $value) - { - $policyTypeData = $this->policyTypeModel->where('id',$value['policy_type_id'])->get()->getRow(); - $insurerData = $this->insurerModel->where('id',$value['insurer_id'])->get()->getRow(); - $value['type'] = $policyTypeData->policy_type; - $value['policy_name'] = $policyTypeData->long_name; - $value['insurer_name'] = $insurerData->name; - $value['insurer_short_name'] = $insurerData->short_name; - $employeeDetails = $this->employeePolicyModel->getEmployeePolicy( client_id:$value['client_id'],policy_id: $value['client_policy_id'],status:0,branch_id:$this->request->getGet('client_branch_id')); - // dd($employeeDetails); - $activeCount = 0; - $inactiveCount = 0; - if(count($employeeDetails)) - { - foreach ($employeeDetails as $item) { - if ($item['emp_status'] === 'active') { - $activeCount++; - } elseif ($item['emp_status'] === 'inactive') { - $inactiveCount++; - } + $ClientPolicyData = $this->clientPolicyModel->select('client_policy.id as client_policy_id , client_policy.client_id as client_id, client_policy.policy_type_id as policy_type_id, client_policy.is_addon as is_addon , client_policy.open_for_enrollment as OpenForEnrollment , client_policy.inception_type as inception_type, client_policy.policy_no as policy_no, client_policy.insurer_id as insurer_id, DATE_FORMAT(client_policy.policy_end_date, "%d-%m-%Y") AS policy_expiry_date ') + ->where('client_policy.client_id', $this->request->getGet('client_id')) + ->where('client_policy.client_branch_id', $this->request->getGet('client_branch_id')) + ->where('client_policy.is_active', 1) + ->where('client_policy.policy_status', $this->request->getGet('policy_status')) + ->whereIn('client_policy.id', $policyId) + ->findAll(); + + + $result = []; + // dd( $ClientPolicyData); + foreach ($ClientPolicyData as $key => $value) { + $policyTypeData = $this->policyTypeModel->where('id', $value['policy_type_id'])->get()->getRow(); + $insurerData = $this->insurerModel->where('id', $value['insurer_id'])->get()->getRow(); + + $value['type'] = $policyTypeData->policy_type; + $value['policy_name'] = $policyTypeData->long_name; + $value['insurer_name'] = $insurerData->name; + $value['insurer_short_name'] = $insurerData->short_name; + $employeeDetails = $this->employeePolicyModel->getEmployeePolicy(client_id: $value['client_id'], policy_id: $value['client_policy_id'], status: 0, branch_id: $this->request->getGet('client_branch_id')); + // dd($employeeDetails); + $activeCount = 0; + $inactiveCount = 0; + if (count($employeeDetails)) { + foreach ($employeeDetails as $item) { + if ($item['emp_status'] === 'active') { + $activeCount++; + } elseif ($item['emp_status'] === 'inactive') { + $inactiveCount++; } } - - $value['totalMembersCount'] = count($employeeDetails); - $value['membersCountOfActive'] = $activeCount; - $value['membersCountOfInactive'] = $inactiveCount; - - - array_push($result,$value); } - + + $value['totalMembersCount'] = count($employeeDetails); + $value['membersCountOfActive'] = $activeCount; + $value['membersCountOfInactive'] = $inactiveCount; - if($result) - { - return $this->respond(['status' => 'success','code' => (count($result) ? 200 : 404),'data' => $result ], 200); - }else{ - return $this->respond(['status' => 'failed','code' => (count($result) ? 200 : 404),'data' => [] ], 200); + array_push($result, $value); + } + + + + if ($result) { + return $this->respond(['status' => 'success', 'code' => (count($result) ? 200 : 404), 'data' => $result], 200); + } else { + return $this->respond(['status' => 'failed', 'code' => (count($result) ? 200 : 404), 'data' => []], 200); } - } @@ -2402,57 +2357,52 @@ class EmployeeRestController extends AdminController { $hr_id = $this->request->getGet('hr_id'); - $HRAccessData = $this->getHRAccessData($hr_id,'post_enrollment'); + $HRAccessData = $this->getHRAccessData($hr_id, 'post_enrollment'); // print_rr($HRAccessData);die(); - if(isset($HRAccessData['allowed_cd'])) - { - $allowed_cd = json_decode($HRAccessData['allowed_cd'],true); - }else{ - $allowed_cd = []; - } + if (isset($HRAccessData['allowed_cd'])) { + $allowed_cd = json_decode($HRAccessData['allowed_cd'], true); + } else { + $allowed_cd = []; + } // $allowed_cd = [125]; // print_r($allowed_cd);die(); - if(count($allowed_cd) == 0){ - return $this->respond(['status' => 'failed','code' => (count($allowed_cd) ? 200 : 404),'data' => [] ], 200); + if (count($allowed_cd) == 0) { + return $this->respond(['status' => 'failed', 'code' => (count($allowed_cd) ? 200 : 404), 'data' => []], 200); } $clientId = $this->request->getGet('client_id'); $clientController = new ClientController; - $result = $clientController->deposit($clientId , $requestFrom = 'rest' , []); + $result = $clientController->deposit($clientId, $requestFrom = 'rest', []); // print_rr($result);die(); $data = []; - - foreach ($result['clientData'] as $key => $value) - { - if( in_array($value->cd_ac_pk, $allowed_cd) ) - { - $temp['client_id'] = $value->client_id; - $temp['insurer_id'] = $value->insurer_id; - $temp['cd_ac_pk'] = $value->cd_ac_pk; - $temp['insurer_name'] = $value->insurer_name; - $temp['cd_master_account_no'] = $value->cd_master_account_no; - if (isset($result['balances'][$temp['insurer_id'].'-'.$temp['cd_ac_pk']])) { - $balance = $result['balances'][$temp['insurer_id'].'-'.$temp['cd_ac_pk']]->balance; - $temp['balance'] = $balance; - } else { - $temp['balance'] = "N/A"; - } - - array_push($data,$temp); + foreach ($result['clientData'] as $key => $value) { + if (in_array($value->cd_ac_pk, $allowed_cd)) { + $temp['client_id'] = $value->client_id; + $temp['insurer_id'] = $value->insurer_id; + $temp['cd_ac_pk'] = $value->cd_ac_pk; + $temp['insurer_name'] = $value->insurer_name; + $temp['cd_master_account_no'] = $value->cd_master_account_no; + + if (isset($result['balances'][$temp['insurer_id'] . '-' . $temp['cd_ac_pk']])) { + $balance = $result['balances'][$temp['insurer_id'] . '-' . $temp['cd_ac_pk']]->balance; + $temp['balance'] = $balance; + } else { + $temp['balance'] = "N/A"; } + + array_push($data, $temp); } - - - if($data) - { - return $this->respond(['status' => 'success','code' => (count($data) ? 200 : 404),'data' => $data ], 200); - }else{ - return $this->respond(['status' => 'failed','code' => (count($data) ? 200 : 404),'data' => [] ], 200); } - + + + if ($data) { + return $this->respond(['status' => 'success', 'code' => (count($data) ? 200 : 404), 'data' => $data], 200); + } else { + return $this->respond(['status' => 'failed', 'code' => (count($data) ? 200 : 404), 'data' => []], 200); + } } public function cdTransactionData() @@ -2463,8 +2413,8 @@ class EmployeeRestController extends AdminController $cdAccountPrimaryKey = $this->request->getGet('cd_ac_pk'); $clientController = new ClientController; - $result = $clientController->view_Deposit($insurerId , $requestFrom = 'rest' , $param = ['client_id'=>$clientId, 'cd_ac_pk'=>$cdAccountPrimaryKey ]); - + $result = $clientController->view_Deposit($insurerId, $requestFrom = 'rest', $param = ['client_id' => $clientId, 'cd_ac_pk' => $cdAccountPrimaryKey]); + $data['insurer_name'] = $result['insurerName']->name; $data['account_number'] = $result['insurerName']->cd_master_account_no; $data['total_deposit'] = $result['deposiamount']->total_credit; @@ -2472,17 +2422,15 @@ class EmployeeRestController extends AdminController $data['total_refund'] = $result['deposiamount']->total_refund; $data['currect_balance'] = $result['deposiamount']->balance; $data['deposit_data'] = $result['depositdata']; - + // dd($data); - if($data) - { - return $this->respond(['status' => 'success','code' => (count($data) ? 200 : 404),'data' => $data ], 200); - }else{ - return $this->respond(['status' => 'failed','code' => (count($data) ? 200 : 404),'data' => [] ], 200); + if ($data) { + return $this->respond(['status' => 'success', 'code' => (count($data) ? 200 : 404), 'data' => $data], 200); + } else { + return $this->respond(['status' => 'failed', 'code' => (count($data) ? 200 : 404), 'data' => []], 200); } - } @@ -2490,44 +2438,49 @@ class EmployeeRestController extends AdminController { if ($this->request->is('get')) { - + $data['claim_status'] = $this->claimStatusModel->select('id,ticket_type,claim_status')->where('is_active', 1)->findAll(); $data['ticket_type'] = [ - ["ticket_type" => "1", "type_name" => "Claim-GMC"], - ["ticket_type" => "2", "type_name" => "Claim-GPA"], - ["ticket_type" => "3", "type_name" => "EDLI"], - ["ticket_type" => "4", "type_name" => "GTLI"], - ]; - - return $this->respond(['status' => (count($data) ? 'success' : 'failed'),'code' => (count($data) ? 200 : 404),'data' => $data ], 200); - + ["ticket_type" => "1", "type_name" => "Claim-GMC"], + ["ticket_type" => "2", "type_name" => "Claim-GPA"], + ["ticket_type" => "3", "type_name" => "EDLI"], + ["ticket_type" => "4", "type_name" => "GTLI"], + ]; + + return $this->respond(['status' => (count($data) ? 'success' : 'failed'), 'code' => (count($data) ? 200 : 404), 'data' => $data], 200); } $db = db_connect(); $search_data = $this->request->getJSON(true); // Get JSON as associative array - + $client_id = isset($search_data['client_id']) ? (int) $search_data['client_id'] : 0; unset($search_data['client_id']); $from_date = isset($search_data['from_date']) ? $search_data['from_date'] : null; $to_date = isset($search_data['to_date']) ? $search_data['to_date'] : null; unset($search_data['from_date'], $search_data['to_date']); - + $where = []; - + // Dynamically build WHERE conditions from non-empty parameters foreach ($search_data as $key => $value) { if (!empty($value) && $value !== 0 && $value !== '0') { $where["tm.$key"] = $value; } } - + $builder = $db->table('ticket_master tm'); $builder->select([ 'tm.id', 'tm.ticket_type_id', - 'tcs.claim_status AS status', + 'tcs.claim_status AS original_status', + "CASE + WHEN tcs.display_name IS NULL OR tcs.display_name = '' + THEN tcs.claim_status + ELSE UPPER(tcs.display_name) + END AS status + ", 'tm.claim_number AS claim_no', 'tm.claim_status_id', 'tm.is_head_approved', @@ -2541,11 +2494,11 @@ class EmployeeRestController extends AdminController 'tm.insured_name', 'c.short_name', 'DATE_FORMAT(tm.created_at, "%d-%m-%Y") AS ticket_created_date', - + '(SELECT first_name FROM user_profiles WHERE user_profiles.id = tm.acm_id) AS acm_name', '(SELECT name FROM insurers WHERE insurers.id = tm.insurer_id) AS insurer_name_sub', '(SELECT name FROM tpa WHERE tpa.id = tm.tpa_id) AS tpa_name', - + 'tm.acm_id', 'tm.insurer_id', 'tm.client_policy_id', @@ -2588,108 +2541,160 @@ class EmployeeRestController extends AdminController 'pt.policy_type as policy_type', 'cp.policy_no as client_policy_no', ]); - + $builder->join('insurers i', 'i.id = tm.insurer_id AND i.is_active = 1', 'left'); $builder->join('clients c', 'c.id = tm.client_id AND c.is_active = 1', 'left'); $builder->join('ticket_claim_status tcs', 'tcs.id = tm.claim_status_id AND tcs.is_active = 1', 'left'); $builder->join('client_policy cp', 'tm.client_policy_id = cp.id', 'left'); $builder->join('policy_type pt', 'cp.policy_type_id = pt.id', 'left'); - + $builder->where('tm.is_active', 1); - + if ($client_id > 0) { $builder->where('tm.client_id', $client_id); } - + if (!empty($from_date) && !empty($to_date)) { $from_date_mysql = date('Y-m-d', strtotime($from_date)); $to_date_mysql = date('Y-m-d', strtotime($to_date)); $builder->where("DATE(tm.created_at) BETWEEN '$from_date_mysql' AND '$to_date_mysql'"); } - + if (!empty($where)) { $builder->where($where); } - + $builder->orderBy('tm.id', 'DESC'); - + $data = $builder->get()->getResultArray(); - return $this->respond(['status' => (count($data) ? 'success' : 'failed'),'code' => (count($data) ? 200 : 404),'data' => $data ], 200); - + return $this->respond(['status' => (count($data) ? 'success' : 'failed'), 'code' => (count($data) ? 200 : 404), 'data' => $data], 200); } public function claimView() { - $ticket_id = $this->request->getGet('ticket_id'); - $ticketController = new TicketController; - $data['ticket_history'] = $ticketController->ticketHistory($ticket_id); - $data['claims_data'] = $this->ticketMaster->getTicketDataByTicketID($ticket_id); - $data['ticket_data'] = $ticketController->getMoreInfo($requestFrom = 'rest', $ticket_id); - + try { - // $data = $response['data']; // Assuming your full array is stored in $response - // $ticketData = $data['ticket_data']; - // $ticketHistory = $data['ticket_history']; + $ticket_id = $this->request->getGet('ticket_id'); + $ticketController = new TicketController; + $data['ticket_history'] = $ticketController->ticketHistory($ticket_id); + $data['claims_data'] = $this->ticketMaster->getTicketDataByTicketID($ticket_id); + $data['ticket_data'] = $ticketController->getMoreInfo($requestFrom = 'rest', $ticket_id); - // Loop through ticket_data - foreach ($data['ticket_data'] as $status => &$fields) { - // Search ticket_history for matching old_status_value - foreach ($data['ticket_history'] as $history) { - if ($history['old_status_value'] === $status) { - // Attach modified_by and created_at - $fields['modified_by'] = $history['modified_by']; - $fields['modified_at'] = date('d-m-Y h:i A', strtotime($history['created_at'])); - // Break after first match (assuming latest entry is enough) - break; + // $ticketData = $data['ticket_data']; + // $ticketHistory = $data['ticket_history']; + // print_r($ticketHistory); die; + + $currentClaimStatus = $this->claimStatusModel->select("claim_status")->where('id', $data['claims_data']['claim_status_id'])->where('is_active', 1)->first(); + $ticketClaimStatus = $this->claimStatusModel->select('claim_status, display_name')->where('display_name is not null')->where('is_active', 1)->findAll(); + $status_list = array_column($ticketClaimStatus, 'display_name', 'claim_status'); + // print_r($currentClaimStatus); die; + + $data['ticket_data'] = array_fill_keys(array_keys($data['ticket_data']), []); + + // Loop through ticket_data + foreach ($data['ticket_data'] as $status => &$fields) { + // Search ticket_history for matching old_status_value + foreach ($data['ticket_history'] as $history) { + + if ($history['old_status_value'] === $status) { + // Attach modified_by and created_at + // $fields['modified_by'] = $history['modified_by']; + $fields['modified_by'] = ""; + $fields['modified_at'] = date('d-m-Y h:i A', strtotime($history['created_at'])); + // Break after first match (assuming latest entry is enough) + break; + } } } - } + $data['ticket_data'][$currentClaimStatus['claim_status']]['modified_by'] = ""; + $data['ticket_data'][$currentClaimStatus['claim_status']]['modified_at'] = $formatted = date('d-m-Y h:i A', strtotime($data['claims_data']['updated_at'])); - $ticketMesssageModel = new TicketMessageModel(); - $ticket_message = $ticketMesssageModel - ->where('is_active', 1) - ->where('sender', "user") - ->where('ticket_id', $ticket_id) - ->orderBy('id', "desc") - ->first(); + $new_ticket_data = []; - $claim_file_urls = []; + foreach ($data['ticket_data'] as $oldKey => $value) { - if (isset($ticket_message['id'])) { + // Only process if key exists in status_list + if (!isset($status_list[$oldKey])) { + continue; // skip and do NOT add to new array + } - $claimFiles = new ClaimFilesModel(); - $claim_files_data = $claimFiles - ->select('id as claim_file_id, doc_name as claim_file_name') - ->where('is_active', 1) - ->where('file_type', 2) - ->where('ticket_id', $ticket_id) - ->where('ticket_message_id', $ticket_message['id']) - ->findAll(); + // Get new key based on mapping + $newKey = $status_list[$oldKey]; - foreach ($claim_files_data as &$value) { - $value['url'] = base_url('downloadClaimFile/') . $value['claim_file_id']; - $claim_file_urls[] = $value; + // Avoid duplicates + if (!isset($new_ticket_data[$newKey])) { + $new_ticket_data[$newKey] = $value; + } } - unset($value); - } - $data['claim_files'] = $claim_file_urls; - - return $this->respond(['status' => (count($data) ? 'success' : 'failed'),'code' => (count($data) ? 200 : 404),'data' => $data, ], 200); + uasort($new_ticket_data, function ($a, $b) { + $timeA = \DateTime::createFromFormat('d-m-Y h:i A', $a['modified_at']); + $timeB = \DateTime::createFromFormat('d-m-Y h:i A', $b['modified_at']); + return $timeA <=> $timeB; // Ascending + }); + + $data['ticket_data'] = $new_ticket_data; + + + $ticketMesssageModel = new TicketMessageModel(); + $ticket_message = $ticketMesssageModel + ->where('is_active', 1) + ->where('sender', "user") + ->where('ticket_id', $ticket_id) + ->orderBy('id', "desc") + ->first(); + + $claim_file_urls = []; + + if (isset($ticket_message['id'])) { + + $claimFiles = new ClaimFilesModel(); + $claim_files_data = $claimFiles + ->select('id as claim_file_id, doc_name as claim_file_name') + ->where('is_active', 1) + ->where('file_type', 2) + ->where('ticket_id', $ticket_id) + ->where('ticket_message_id', $ticket_message['id']) + ->findAll(); + + foreach ($claim_files_data as &$value) { + $value['url'] = base_url('downloadClaimFile/') . $value['claim_file_id']; + $claim_file_urls[] = $value; + } + unset($value); + } + + $data['claim_files'] = $claim_file_urls; + + return $this->respond(['status' => (count($data) ? 'success' : 'failed'), 'code' => (count($data) ? 200 : 404), 'data' => $data,], 200); + + } catch (\Throwable $th) { + $this->myLogger->logme("error", 'claim_view' .($th->getMessage() . ' --- ' . $th->getLine() . '----' . $th->getTraceAsString())); + $errorData = [ + 'message' => $th->getMessage(), + 'file' => $th->getFile(), + 'line' => $th->getLine(), + 'code' => $th->getCode(), + 'trace' => $th->getTraceAsString(), + 'trace_array' => $th->getTrace(), // full array version (optional) + 'function' => $th->getTrace()[0]['function'] ?? null, + 'class' => $th->getTrace()[0]['class'] ?? null, + ]; + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => "", 'error_data' => $errorData], 500); + } } - + public function exportCashDepositData() { - $CashDepositData = $this->clientPolicyModel->getdepositData($this->request->getGet('client_id'),$this->request->getGet('insurer_id')); + $CashDepositData = $this->clientPolicyModel->getdepositData($this->request->getGet('client_id'), $this->request->getGet('insurer_id')); // echo '
';print_r($CashDepositData); echo '
';die; - if(count($CashDepositData)) - { + if (count($CashDepositData)) { // Define headers and map database fields to Excel fields $headers = [ 'Date' => 'created_at', @@ -2727,7 +2732,7 @@ class EmployeeRestController extends AdminController // Set the header for download - $filename = $CashDepositData[0]->insurer_name.'-CashDeposit.xlsx'; + $filename = $CashDepositData[0]->insurer_name . '-CashDeposit.xlsx'; header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="' . $filename . '"'); header('Cache-Control: max-age=0'); @@ -2738,12 +2743,10 @@ class EmployeeRestController extends AdminController exit; return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200); - - }else{ + } else { return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200); } - } @@ -2751,126 +2754,121 @@ class EmployeeRestController extends AdminController { try { - $clientPolicy = $this->clientPolicyModel->where('id',$this->request->getGet('client_policy_id')) - ->where('open_for_enrollment',1)->findAll(); - - if(count($clientPolicy)) - { + $clientPolicy = $this->clientPolicyModel->where('id', $this->request->getGet('client_policy_id')) + ->where('open_for_enrollment', 1)->findAll(); + + if (count($clientPolicy)) { - if($clientPolicy[0]['is_addon'] == 2)//Topup + if ($clientPolicy[0]['is_addon'] == 2) //Topup { - if($clientPolicy[0]['policy_type_id'] == 4)//GMC-Topup + if ($clientPolicy[0]['policy_type_id'] == 4) //GMC-Topup { - $empData = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code')) - ->where('is_addon_value', 0 ) - ->findAll(); - }else if($clientPolicy[0]['policy_type_id'] == 5)//GMC-Parent-Topup + $empData = $this->employeeModel->where('emp_code', $this->request->getGet('emp_code')) + ->where('is_addon_value', 0) + ->findAll(); + } else if ($clientPolicy[0]['policy_type_id'] == 5) //GMC-Parent-Topup { - $empData = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code')) - ->where('is_addon_value', 1 ) - ->findAll(); + $empData = $this->employeeModel->where('emp_code', $this->request->getGet('emp_code')) + ->where('is_addon_value', 1) + ->findAll(); } - - if(count($empData)) - { + + if (count($empData)) { foreach ($empData as $key => $value) { - $this->employeePolicyModel->where('client_policy_id',$this->request->getGet('client_policy_id') ) - ->where('employee_id', $value['id'] ) - ->set(array('is_active'=> 0 )) - ->update(); - + $this->employeePolicyModel->where('client_policy_id', $this->request->getGet('client_policy_id')) + ->where('employee_id', $value['id']) + ->set(array('is_active' => 0)) + ->update(); } } - - } - else if($clientPolicy[0]['is_addon'] == 3)//Dependent addon + } else if ($clientPolicy[0]['is_addon'] == 3) //Dependent addon { - $empData = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code')) - ->where('is_addon_value', 1 )->findAll(); - if(count($empData)) - { - foreach ($empData as $key => $value) { + $empData = $this->employeeModel->where('emp_code', $this->request->getGet('emp_code')) + ->where('is_addon_value', 1)->findAll(); + if (count($empData)) { + foreach ($empData as $key => $value) { - $this->employeePolicyModel->where('client_policy_id',$this->request->getGet('client_policy_id') ) - ->where('employee_id', $value['id'] ) - ->set(array('is_active'=> 0 )) - ->update(); + $this->employeePolicyModel->where('client_policy_id', $this->request->getGet('client_policy_id')) + ->where('employee_id', $value['id']) + ->set(array('is_active' => 0)) + ->update(); + } + $this->employeeModel->where('emp_code', $this->request->getGet('emp_code')) + ->where('is_active', 1)->where('is_addon_value', 1) + ->set(array('is_active' => 0)) + ->update(); } - - $this->employeeModel->where('emp_code', $this->request->getGet('emp_code') ) - ->where('is_active', 1 )->where('is_addon_value', 1 ) - ->set(array('is_active'=> 0 )) - ->update(); - } - } - - - return $this->respond(['status' => 'success','code' => 200,'data' =>[] ], 200); - - }else{ - return $this->respond(['status' => 'failed','code' => 404,'data' => [] ], 200); + + + return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200); + } else { + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200); } - - } catch (\Exception $e) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500); + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500); } - } function getEmployeeActiveOrInactivePolicy() { - if($this->request->getGet('type') == 'Active'){ $policy_status = 1; $policy_status_key = "Active"; }else{ $policy_status = 0; $policy_status_key = "InActive";} + if ($this->request->getGet('type') == 'Active') { + $policy_status = 1; + $policy_status_key = "Active"; + } else { + $policy_status = 0; + $policy_status_key = "InActive"; + } $dayInterval = 10; $ClientPolicyData = $this->clientPolicyModel->select("client_policy.* , policy_type.policy_type as policy_type,insurers.name as insurer_name,tpa.name as tpa_name,tpa.network_hospitals as network_hospitals_url, policy_type.long_name as policy_long_name, DATE_ADD(client_policy.policy_end_date, INTERVAL {$dayInterval} DAY) as claims_grace_date") - ->join('insurers', 'client_policy.insurer_id = insurers.id', 'left') - ->join('tpa', 'client_policy.tpa_id = tpa.id', 'left') - ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left') - ->where('client_policy.client_id', $this->request->getGet('client_id') ) - ->where('client_policy.client_branch_id', $this->request->getGet('client_branch_id') ) - ->where('client_policy.is_active', 1 ) - ->where('client_policy.policy_status', $policy_status) - ->where('client_policy.enrolment_visibility', 1) - ->orderby('client_policy.id' , 'ASC') - ->findAll(); + ->join('insurers', 'client_policy.insurer_id = insurers.id', 'left') + ->join('tpa', 'client_policy.tpa_id = tpa.id', 'left') + ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left') + ->where('client_policy.client_id', $this->request->getGet('client_id')) + ->where('client_policy.client_branch_id', $this->request->getGet('client_branch_id')) + ->where('client_policy.is_active', 1) + ->where('client_policy.policy_status', $policy_status) + ->where('client_policy.enrolment_visibility', 1) + ->orderby('client_policy.id', 'ASC') + ->findAll(); // Retrieve employee and dependents data by passing the employee code - $employeeData = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code')) - ->where('client_id',$this->request->getGet('client_id')) - ->where('client_branch_id',$this->request->getGet('client_branch_id')) - ->where('is_active', 1 )->findAll(); - - $employeeSelfData = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code')) - ->where('client_id',$this->request->getGet('client_id')) - ->where('client_branch_id',$this->request->getGet('client_branch_id')) - ->where('family_floater_key','self')->where('is_active', 1 ) - ->get()->getRow(); + $employeeData = $this->employeeModel->where('emp_code', $this->request->getGet('emp_code')) + ->where('client_id', $this->request->getGet('client_id')) + ->where('client_branch_id', $this->request->getGet('client_branch_id')) + ->where('is_active', 1)->findAll(); + + $employeeSelfData = $this->employeeModel->where('emp_code', $this->request->getGet('emp_code')) + ->where('client_id', $this->request->getGet('client_id')) + ->where('client_branch_id', $this->request->getGet('client_branch_id')) + ->where('family_floater_key', 'self')->where('is_active', 1) + ->get()->getRow(); $employeeName = $employeeSelfData->name ?? ""; - + //for get the pre enrollment policy count $empMobileNo = $this->request->getGet('mobile_no'); $clientId = $this->request->getGet('client_id'); - if(!empty($employeeSelfData) && isset($employeeSelfData->email_corporate)){ + if (!empty($employeeSelfData) && isset($employeeSelfData->email_corporate)) { $prePolicyCount = $this->getPreEmployeePolicyCount($empMobileNo, $clientId, $employeeSelfData->email_corporate); - }else{ + } else { $prePolicyCount = $this->getPreEmployeePolicyCount($empMobileNo, $clientId); } - - $whereArrayForId = []; - foreach ( $employeeData as $key => $value) { array_push($whereArrayForId, $value['id']); } - if(count($ClientPolicyData) > 0 && count($employeeData) > 0) - { + $whereArrayForId = []; + foreach ($employeeData as $key => $value) { + array_push($whereArrayForId, $value['id']); + } + + if (count($ClientPolicyData) > 0 && count($employeeData) > 0) { $result = []; foreach ($ClientPolicyData as $key => $ClientPolicyValue) { @@ -2878,38 +2876,35 @@ class EmployeeRestController extends AdminController continue; } - if($ClientPolicyValue['policy_type_id'] == 1) - { + if ($ClientPolicyValue['policy_type_id'] == 1) { $policyGroup = 'gpa'; $data['ticket_type_id'] = 2; + $data['ticket_settled_status_id'] = 24; $data['claim_subject'] = "Claim GPA"; $data['sum_insured_label'] = "Sum Assured"; - - }else if($ClientPolicyValue['policy_type_id'] == 6) - { + } else if ($ClientPolicyValue['policy_type_id'] == 6) { $policyGroup = 'other'; $data['ticket_type_id'] = 3; + $data['ticket_settled_status_id'] = 34; $data['claim_subject'] = "Claim EDLI"; $data['sum_insured_label'] = "Sum Assured"; - - }else if($ClientPolicyValue['policy_type_id'] == 7) - { + } else if ($ClientPolicyValue['policy_type_id'] == 7) { $policyGroup = 'other'; $data['ticket_type_id'] = 4; + $data['ticket_settled_status_id'] = 44; $data['claim_subject'] = "Claim GTLI"; $data['sum_insured_label'] = "Sum Assured"; - - }else - { + } else { $policyGroup = 'gmc'; $data['ticket_type_id'] = 1; + $data['ticket_settled_status_id'] = 11; $data['claim_subject'] = "Claim GMC"; $data['sum_insured_label'] = "Sum Insured"; } - $terms = json_decode($ClientPolicyValue['policy_terms'] , true); + $terms = json_decode($ClientPolicyValue['policy_terms'], true); $data['policy_terms'] = isset($terms['enrollment_display_key']) && !empty($terms['enrollment_display_key']) ? $terms['enrollment_display_key'] : $this->policyTermsFiter($terms, $policyGroup); - + $data['client_id'] = $ClientPolicyValue['client_id']; $data['client_policy_id'] = $ClientPolicyValue['id']; @@ -2934,61 +2929,80 @@ class EmployeeRestController extends AdminController // if($ClientPolicyValue['policy_type_id'] == 5){ $data['heading'] = 'Group Medical Coverage - Parents (Top Up)'; }else // if($ClientPolicyValue['policy_type_id'] == 7){ $data['heading'] = 'Group Term Life Insurance'; } - if($ClientPolicyValue['policy_type_id'] == 1 || $ClientPolicyValue['policy_type_id'] == 6 || $ClientPolicyValue['policy_type_id'] == 7) - { - $data['floter_text_heading'] = 'Sum Insured'; - }else{ - - if(isset($terms['family_floater']) && strpos(strtolower($terms['family_floater']), "no") !== false ){ $data['floter_text_heading'] = 'Sum Insured'; }else{ $data['floter_text_heading'] = 'Floter Sum Insured'; } + if ($ClientPolicyValue['policy_type_id'] == 1 || $ClientPolicyValue['policy_type_id'] == 6 || $ClientPolicyValue['policy_type_id'] == 7) { + $data['floter_text_heading'] = 'Sum Insured'; + } else { + + if (isset($terms['family_floater']) && strpos(strtolower($terms['family_floater']), "no") !== false) { + $data['floter_text_heading'] = 'Sum Insured'; + } else { + $data['floter_text_heading'] = 'Floter Sum Insured'; + } } - + $employee_policy = $this->employeePolicyModel->select('employees.*,employee_polices.employee_id , employee_polices.basic_cover_si , employee_polices.premium , employee_polices.gst , employee_polices.tpa_id , employee_polices.rand_string , employee_polices.uhid as uhid') - ->join('employees', 'employee_polices.employee_id = employees.id', 'left') - ->whereIn('employee_polices.employee_id',$whereArrayForId) - ->where('employee_polices.client_policy_id',$ClientPolicyValue['id']) - ->where('employee_polices.is_active', 1 )->findAll(); - if(count($employee_policy) > 0) - { + ->join('employees', 'employee_polices.employee_id = employees.id', 'left') + ->whereIn('employee_polices.employee_id', $whereArrayForId) + ->where('employee_polices.client_policy_id', $ClientPolicyValue['id']) + ->where('employee_polices.is_active', 1)->findAll(); + if (count($employee_policy) > 0) { $si_value = 0; $si_premium_value = 0; $si_gst_value = 0; - - foreach ($employee_policy as $key => $value) { - if(isset($value['basic_cover_si'])){ $si_value = ($si_value == 0) ? $value['basic_cover_si'] : $si_value; } - if(isset($value['premium'])){ $si_premium_value = $si_premium_value + $value['premium'];} - if(isset($value['gst'])){ $si_gst_value = $si_gst_value + $value['gst'];} - } - - if($employee_policy[0]['tpa_id'] != null) - $data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string'].'/1'; + foreach ($employee_policy as $key => $value) { + if (isset($value['basic_cover_si'])) { + $si_value = ($si_value == 0) ? $value['basic_cover_si'] : $si_value; + } + if (isset($value['premium'])) { + $si_premium_value = $si_premium_value + $value['premium']; + } + if (isset($value['gst'])) { + $si_gst_value = $si_gst_value + $value['gst']; + } + } + + + if ($employee_policy[0]['tpa_id'] != null) + $data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string'] . '/1'; else - $data['eCardDownload'] = null; - - - + $data['eCardDownload'] = null; + + + $data['si_value'] = $si_value; $data['si_premium_value'] = ($ClientPolicyValue['policy_type_id'] == 1 || $ClientPolicyValue['policy_type_id'] == 2) ? 0 : round($si_premium_value); $data['si_gst_value'] = ($ClientPolicyValue['policy_type_id'] == 1 || $ClientPolicyValue['policy_type_id'] == 2) ? 0 : round($si_gst_value); - + $data['EmployeePolicy'] = $employee_policy; + + //fetch claims data + $approvedClaimsAmount = $this->ticketMaster + ->select('SUM(approved_amount) AS total_settled_amount') + ->where('emp_code', $employee_policy[0]['emp_code']) + ->where('client_policy_id', $data['client_policy_id']) + ->where('claim_status_id', $data['ticket_settled_status_id']) + ->groupBy('emp_code') + ->groupBy('client_policy_id') + ->groupBy('claim_status_id') + ->get()->getRow(); + $data['total_settled_amount'] = $approvedClaimsAmount ? ($approvedClaimsAmount->total_settled_amount ?? 0) : 0; array_push($result, $data); } - + + } - return $this->respond(['status' => 'success','code' => 200,'data' => $result , 'emp_name' => $employeeName, 'pre_policy_count' => $prePolicyCount ], 200); - - }else{ - return $this->respond(['status' => 'failed','code' => 404,'data' => [] ], 200); + return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result, 'emp_name' => $employeeName, 'pre_policy_count' => $prePolicyCount], 200); + } else { + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200); } - } - function policyTermsFiter($terms , $type) - { - if(empty($terms)){ + function policyTermsFiter($terms, $type) + { + if (empty($terms)) { return []; } @@ -3020,7 +3034,7 @@ class EmployeeRestController extends AdminController ]; $gmc = [ - + "waiverofpreexistingdiseases" => "Waiver of Pre-existing Diseases", "waiverof1,2,3&4thyearexclusions" => "Waiver of 1, 2, 3 & 4th year Exclusions", "waiverof30dayswaitingperiod" => "Waiver of 30 days waiting period", @@ -3042,59 +3056,51 @@ class EmployeeRestController extends AdminController ]; $finalarray = []; - if($type == 'gpa'){ + if ($type == 'gpa') { foreach ($gpa as $key => $value) { - if(isset($terms->$key)) - { - if($terms->$key == 1) - { + if (isset($terms->$key)) { + if ($terms->$key == 1) { $termsValue = 'Yes'; - }else if($terms->$key == 0) - { + } else if ($terms->$key == 0) { $termsValue = 'No'; - }else - { + } else { $termsValue = $terms->$key; } $finalarray[$value] = $termsValue; } } - if(isset(($terms->gpa_special_condition_label)) && is_array($terms->gpa_special_condition_label) && is_array($terms->gpa_special_condition_input)){ - for ($i=0; $i < count($terms->gpa_special_condition_label); $i++) { + if (isset(($terms->gpa_special_condition_label)) && is_array($terms->gpa_special_condition_label) && is_array($terms->gpa_special_condition_input)) { + for ($i = 0; $i < count($terms->gpa_special_condition_label); $i++) { $finalarray[$terms->gpa_special_condition_label[$i]] = $terms->gpa_special_condition_input[$i]; } } - }else if($type == 'other'){ + } else if ($type == 'other') { foreach ($terms as $key => $value) { - if($key != "multiple_sum_insured" && $value != ""){ + if ($key != "multiple_sum_insured" && $value != "") { $result = ucwords(str_replace('_', ' ', $key)); $finalarray[$result] = $value; } } - if(isset(($terms->gpa_special_condition_label)) && is_array($terms->gpa_special_condition_label) && is_array($terms->gpa_special_condition_input)){ - for ($i=0; $i < count($terms->gpa_special_condition_label); $i++) { + if (isset(($terms->gpa_special_condition_label)) && is_array($terms->gpa_special_condition_label) && is_array($terms->gpa_special_condition_input)) { + for ($i = 0; $i < count($terms->gpa_special_condition_label); $i++) { $finalarray[$terms->gpa_special_condition_label[$i]] = $terms->gpa_special_condition_input[$i]; } } - }else{ + } else { foreach ($gmc as $key => $value) { - if(isset($terms->$key)) - { - if($terms->$key == 1) - { + if (isset($terms->$key)) { + if ($terms->$key == 1) { $termsValue = 'Yes'; - }else if($terms->$key == 0) - { + } else if ($terms->$key == 0) { $termsValue = 'No'; - }else - { + } else { $termsValue = $terms->$key; } $finalarray[$value] = $termsValue; - } + } } - if(isset(($terms->special_condition_label)) && is_array($terms->special_condition_label) && is_array($terms->special_condition_input)){ - for ($i=0; $i < count($terms->special_condition_label); $i++) { + if (isset(($terms->special_condition_label)) && is_array($terms->special_condition_label) && is_array($terms->special_condition_input)) { + for ($i = 0; $i < count($terms->special_condition_label); $i++) { $finalarray[$terms->special_condition_label[$i]] = $terms->special_condition_input[$i]; } } @@ -3119,42 +3125,40 @@ class EmployeeRestController extends AdminController public function getFEContent() { try { - + $feContentData = $this->feContentModel->findAll(); if (count($feContentData) > 0) { - - return $this->respond(['status' => 'success','code' => 200,'data' => $feContentData ],200); + return $this->respond(['status' => 'success', 'code' => 200, 'data' => $feContentData], 200); } else { - - return $this->respond(['status' => 'failed','code' => 404,'data' => 'No Data'],404); + + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => 'No Data'], 404); } - } catch (\Throwable $th) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500); - } + } catch (\Throwable $th) { + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $th], 500); + } } public function getAdvertisementImage() { try { - - $img = $this->addImgModel->where('is_active',1)->findAll(); - - if (count($img) > 0) { - $data=[]; - foreach ($img as $key => $value) { - $url = base_url('public/uploads/add_image_upload/').$value['name']; - array_push($data,$url); - } - - return $this->respond(['status' => 'success','code' => 200,'data' => $data ],200); + $img = $this->addImgModel->where('is_active', 1)->findAll(); + + if (count($img) > 0) { + $data = []; + foreach ($img as $key => $value) { + $url = base_url('public/uploads/add_image_upload/') . $value['name']; + array_push($data, $url); + } + + return $this->respond(['status' => 'success', 'code' => 200, 'data' => $data], 200); } else { - - return $this->respond(['status' => 'failed','code' => 404,'data' => 'No Data'],404); + + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => 'No Data'], 404); } } catch (\Throwable $th) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500); + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $th], 500); } } @@ -3162,29 +3166,28 @@ class EmployeeRestController extends AdminController public function storeFireBase() { try { - + $firebase_token = isset($this->request->getJSON()->firebase_token) ? $this->request->getJSON()->firebase_token : null; $mobile = isset($this->request->getJSON()->mobile) ? $this->request->getJSON()->mobile : null; $email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null; - + // Ensure the mobile number is provided if (empty($mobile)) { return $this->respond(['status' => 'failed', 'code' => 400, 'message' => 'Mobile number is required'], 400); } - + // Fetch employee - if (isset($mobile)) - { - $employee = $this->employeeModel->where('mobile', $mobile)->where('relationship', 'self')->where('is_active', 1)->first(); - } else { - $employee = $this->employeeModel->where('email_corporate', $email_id)->where('relationship', 'self')->where('is_active', 1)->first(); - } - - + if (isset($mobile)) { + $employee = $this->employeeModel->where('mobile', $mobile)->where('relationship', 'self')->where('is_active', 1)->first(); + } else { + $employee = $this->employeeModel->where('email_corporate', $email_id)->where('relationship', 'self')->where('is_active', 1)->first(); + } + + if ($employee) { // Check if firebase_token is provided if (!empty($firebase_token)) { - + // Check if the current firebase_token is different from the new one if ($employee['firebase_token'] !== $firebase_token) { // Update the employee's firebase_token @@ -3195,7 +3198,7 @@ class EmployeeRestController extends AdminController $db = \Config\Database::connect(); $builder = $db->table('employees'); $update_emp = $builder->update($data, ['id' => $id]); - + // Check if the update was successful if ($db->affectedRows() > 0) { // Fetch the updated employee data @@ -3229,16 +3232,16 @@ class EmployeeRestController extends AdminController // $deviceToken = 'cMVKESh8QzqIl8nh_yqbcl:APA91bHKm87Sh1goVJNKZtctV4etgLMQboI0eyDVn3MH1yf9cO-2RtQRlFnKLdataOxosoxm7a4JvATKjfI1_Bids46mGw5m8zesp90mR4odCbD_cJtGmBeMYt4hssSY0YtAht1emK_H'; // $title = 'Nhance'; // $body = 'All your policy enrolled successfully ..!'; - + // // Initialize Firebase with the service account // $firebase = (new Factory) // ->withServiceAccount(APPPATH . 'Config/google-services.json') // ->createMessaging(); - + // $notification = Notification::create($title, $body); // $message = CloudMessage::withTarget('token', $deviceToken) // ->withNotification($notification); - + // try { // $firebase->send($message); // return $this->response->setJSON(['status' => 'success']); @@ -3255,22 +3258,26 @@ class EmployeeRestController extends AdminController $empCode = $this->request->getGet('emp_code'); $clientId = $this->request->getGet('client_id'); $clientBranchId = $this->request->getGet('client_branch_id'); - - if (!$empCode || !$clientId || !$clientBranchId) { return $this->fail("emp_code, client_id, and client_branch_id are required parameters."); } + + if (!$empCode || !$clientId || !$clientBranchId) { + return $this->fail("emp_code, client_id, and client_branch_id are required parameters."); + } //Fetch active employee details $employees = $this->employeeModel->select('id,emp_code,name,relationship,dob,emp_status,is_addon_value,created_at,updated_at') - ->where([ - 'emp_code' => $empCode, - 'client_id' => $clientId, - 'client_branch_id' => $clientBranchId, - 'is_active' => 1 - ]) - ->findAll(); + ->where([ + 'emp_code' => $empCode, + 'client_id' => $clientId, + 'client_branch_id' => $clientBranchId, + 'is_active' => 1 + ]) + ->findAll(); //Find status of self - $selfEmployee = array_filter($employees, function($employee) { return $employee['relationship'] === 'Self'; }); + $selfEmployee = array_filter($employees, function ($employee) { + return $employee['relationship'] === 'Self'; + }); $data['self_status'] = !empty($selfEmployee) ? array_values($selfEmployee)[0]['emp_status'] : null; $data['self_enrolled_time'] = !empty($selfEmployee) ? array_values($selfEmployee)[0]['updated_at'] : null; $data['self_employee_id'] = !empty($selfEmployee) ? array_values($selfEmployee)[0]['id'] : null; @@ -3278,113 +3285,113 @@ class EmployeeRestController extends AdminController //Fetch employee policy details $employeeIds = array_column($employees, 'id'); - $policies = $this->employeePolicyModel->whereIn('employee_id', $employeeIds)->where('is_active',1)->findAll(); + $policies = $this->employeePolicyModel->whereIn('employee_id', $employeeIds)->where('is_active', 1)->findAll(); + - //Find the stage of enrolment process $employeeStatuses = array_column($employees, 'emp_status'); $employeePolicyStatuses = array_column($policies, 'status'); $uniqueStatuses = array_unique(array_merge($employeeStatuses, $employeePolicyStatuses)); - - if(count($uniqueStatuses) > 1){ $enrolmentStagekey = 1; }else{ if($uniqueStatuses[0] == 'draft'){ $enrolmentStagekey = 0; }else{ $enrolmentStagekey = 2; } } - - $enrolmentStage = ['Draft Only','Intermittent Enrollment','Successful Enrollment']; + + if (count($uniqueStatuses) > 1) { + $enrolmentStagekey = 1; + } else { + if ($uniqueStatuses[0] == 'draft') { + $enrolmentStagekey = 0; + } else { + $enrolmentStagekey = 2; + } + } + + $enrolmentStage = ['Draft Only', 'Intermittent Enrollment', 'Successful Enrollment']; $data['enrolment_stage'] = $enrolmentStage[$enrolmentStagekey]; $data['revert_employee_data'] = []; $data['revert_employee_policy_data'] = []; - if($enrolmentStagekey == 1) - { + if ($enrolmentStagekey == 1) { //Find active employee history $empIdsWithoutSelf = $employeeIds; $key = array_search($data['self_employee_id'], $empIdsWithoutSelf); - unset($empIdsWithoutSelf[$key]); - foreach ($empIdsWithoutSelf as $key => $pk) - { - $retrivedData = $this->retriveOldData($data['self_enrolled_time'],'employees',$pk); - if($retrivedData != false) - array_push($data['revert_employee_data'] , $retrivedData); + unset($empIdsWithoutSelf[$key]); + foreach ($empIdsWithoutSelf as $key => $pk) { + $retrivedData = $this->retriveOldData($data['self_enrolled_time'], 'employees', $pk); + if ($retrivedData != false) + array_push($data['revert_employee_data'], $retrivedData); } //Find inactive employee history $inActiveEmployees = $this->employeeModel->select('id,emp_code,name,relationship,dob,emp_status,is_addon_value,created_at,updated_at') - ->where([ - 'emp_code' => $empCode, - 'client_id' => $clientId, - 'client_branch_id' => $clientBranchId, - 'is_active' => 0 - ]) - ->findAll(); - $inActiveEmployeeIds = array_column($inActiveEmployees, 'id'); - foreach ($inActiveEmployeeIds as $key => $pk) - { - $retrivedData = $this->retriveOldData($data['self_enrolled_time'],'employees',$pk); - if($retrivedData != false) - array_push($data['revert_employee_data'] , $retrivedData); + ->where([ + 'emp_code' => $empCode, + 'client_id' => $clientId, + 'client_branch_id' => $clientBranchId, + 'is_active' => 0 + ]) + ->findAll(); + $inActiveEmployeeIds = array_column($inActiveEmployees, 'id'); + foreach ($inActiveEmployeeIds as $key => $pk) { + $retrivedData = $this->retriveOldData($data['self_enrolled_time'], 'employees', $pk); + if ($retrivedData != false) + array_push($data['revert_employee_data'], $retrivedData); } - + //Merged active and inactive employees , employee_polict history - $mergedEmpIds = array_merge($employeeIds,$inActiveEmployeeIds); + $mergedEmpIds = array_merge($employeeIds, $inActiveEmployeeIds); $empPolicyData = $this->employeePolicyModel->whereIn('employee_id', $mergedEmpIds)->findAll(); $employeePolicyIds = array_column($empPolicyData, 'id'); - foreach ($employeePolicyIds as $key => $pk) - { - $retrivedData = $this->retriveOldData($data['self_enrolled_time'],'employee_polices',$pk); - if($retrivedData != false) - array_push($data['revert_employee_policy_data'] , $retrivedData); + foreach ($employeePolicyIds as $key => $pk) { + $retrivedData = $this->retriveOldData($data['self_enrolled_time'], 'employee_polices', $pk); + if ($retrivedData != false) + array_push($data['revert_employee_policy_data'], $retrivedData); } } - if($this->request->getGet('revert_data') == 1) - { + if ($this->request->getGet('revert_data') == 1) { //update data back to employee - if(count($data['revert_employee_data'])){ - foreach ($data['revert_employee_data'] as $key => $val) - { - $this->employeeModel->where('id',$val['id'] )->set($val['data'])->update(); + if (count($data['revert_employee_data'])) { + foreach ($data['revert_employee_data'] as $key => $val) { + $this->employeeModel->where('id', $val['id'])->set($val['data'])->update(); } } //update data back to employee policy - if(count($data['revert_employee_policy_data'])){ - foreach ($data['revert_employee_policy_data'] as $key => $val) - { - $this->employeePolicyModel->where('id',$val['id'] )->set($val['data'])->update(); - } + if (count($data['revert_employee_policy_data'])) { + foreach ($data['revert_employee_policy_data'] as $key => $val) { + $this->employeePolicyModel->where('id', $val['id'])->set($val['data'])->update(); + } } //update enrolled status for self - if(count($data['revert_employee_data']) || count($data['revert_employee_policy_data'])){ - $this->employeeModel->where('id',$data['self_employee_id'] )->set(array('emp_status'=>'enrolled'))->update(); - $data['retrieve_status'] = 'Data revert successfully'; - }else{ - $data['retrieve_status'] = 'There is no data to revert'; + if (count($data['revert_employee_data']) || count($data['revert_employee_policy_data'])) { + $this->employeeModel->where('id', $data['self_employee_id'])->set(array('emp_status' => 'enrolled'))->update(); + $data['retrieve_status'] = 'Data revert successfully'; + } else { + $data['retrieve_status'] = 'There is no data to revert'; } - } - - + + // Fetch all policies related to these employees who currently active $current_employee_data = $this->employeeModel->select('id,emp_code,name,relationship,dob,emp_status,is_addon_value,created_at,updated_at') - ->where([ - 'emp_code' => $empCode, - 'client_id' => $clientId, - 'client_branch_id' => $clientBranchId, - 'is_active' => 1 - ]) - ->findAll(); - $Ids = array_column($current_employee_data, 'id'); - $policies = $this->employeePolicyModel->whereIn('employee_id', $Ids)->where('is_active',1)->findAll(); + ->where([ + 'emp_code' => $empCode, + 'client_id' => $clientId, + 'client_branch_id' => $clientBranchId, + 'is_active' => 1 + ]) + ->findAll(); + $Ids = array_column($current_employee_data, 'id'); + $policies = $this->employeePolicyModel->whereIn('employee_id', $Ids)->where('is_active', 1)->findAll(); // Group policies by policy_id $groupedPolicies = []; foreach ($policies as $policy) { $policyId = $policy['client_policy_id']; - + if (!isset($groupedPolicies[$policyId])) { $groupedPolicies[$policyId] = [ 'policy_id' => $policy['id'], @@ -3416,24 +3423,28 @@ class EmployeeRestController extends AdminController // Re-index the grouped policies $data['currentPolicies'] = array_values($groupedPolicies); - + return $this->respond(['data' => $data]); } - public function retriveOldData($self_enrolled_time,$table,$pk) + public function retriveOldData($self_enrolled_time, $table, $pk) { - $historyData = $this->auditHistoryModel->where('pk', $pk)->where('table_name',$table)->findAll(); + $historyData = $this->auditHistoryModel->where('pk', $pk)->where('table_name', $table)->findAll(); $beforeEnrolled = []; $afterEnrolled = []; // Split the array foreach ($historyData as $val) { - if ($val['created_at'] <= $self_enrolled_time) { $beforeEnrolled[] = $val; } else { $afterEnrolled[] = $val; } + if ($val['created_at'] <= $self_enrolled_time) { + $beforeEnrolled[] = $val; + } else { + $afterEnrolled[] = $val; + } } - if(count($beforeEnrolled) && count($afterEnrolled)){ //After enrolment edited some of the data - + if (count($beforeEnrolled) && count($afterEnrolled)) { //After enrolment edited some of the data + $temp['table'] = $table; $temp['id'] = $pk; // Extract earliest `old_value` for each `field_name` @@ -3447,22 +3458,19 @@ class EmployeeRestController extends AdminController } $temp['data'] = $originalValues; return $temp; - - }else if(!count($beforeEnrolled) && !count($afterEnrolled)){ //After enrolment created new data + } else if (!count($beforeEnrolled) && !count($afterEnrolled)) { //After enrolment created new data $temp['table'] = $table; $temp['id'] = $pk; - $temp['data'] = ['is_active'=> 0 ]; + $temp['data'] = ['is_active' => 0]; return $temp; - - }else if(!count($beforeEnrolled) && count($afterEnrolled)){ //After enrolment created new data and edited some of the data + } else if (!count($beforeEnrolled) && count($afterEnrolled)) { //After enrolment created new data and edited some of the data $temp['table'] = $table; $temp['id'] = $pk; - $temp['data'] = ['is_active'=> 0 ]; + $temp['data'] = ['is_active' => 0]; return $temp; - - }else if(count($beforeEnrolled) && !count($afterEnrolled)){ //After enrolment nothing changes from the data + } else if (count($beforeEnrolled) && !count($afterEnrolled)) { //After enrolment nothing changes from the data return false; } @@ -3472,13 +3480,12 @@ class EmployeeRestController extends AdminController public function findThePolicyIsOpenForEnrollment($plicy_id) { - $policy = $this->clientPolicyModel->where('id',$plicy_id)->where('open_for_enrollment',1)->find(); + $policy = $this->clientPolicyModel->where('id', $plicy_id)->where('open_for_enrollment', 1)->find(); - if($policy) - return true; + if ($policy) + return true; else - return false; - + return false; } // ---------------- TICKET API's --------------------------------------------------------------------------------------------------- @@ -3505,7 +3512,7 @@ class EmployeeRestController extends AdminController $insured_emp_id = $received_data['insured_emp_id']; $file_data = []; - if(isset($get_file_data) && !empty($get_file_data)){ + if (isset($get_file_data) && !empty($get_file_data)) { $file_path = WRITEPATH . 'uploads/claim_files/'; $file_data = multi_file_Upload($get_file_data, $file_path, $get_docs_name); } @@ -3513,13 +3520,13 @@ class EmployeeRestController extends AdminController if (empty($received_data['doa'])) { $received_data['doa'] = null; - } else{ + } else { $ticket_data['doa'] = change_date_format($received_data['doa']); } if (empty($received_data['dod'])) { $received_data['dod'] = null; - } else{ + } else { $ticket_data['dod'] = change_date_format($received_data['dod']); } @@ -3562,22 +3569,22 @@ class EmployeeRestController extends AdminController $emp_ticket_data = $this->employeeModel->query($sql)->getResultArray(); // print_r(db_connect()->getLastQuery()); die; - if(!empty($emp_ticket_data)){ + if (!empty($emp_ticket_data)) { $fetchData = $emp_ticket_data[0]; $claimStatusQuery = $this->claimStatusModel - ->select('id') - ->where('ticket_type', $fetchData['ticket_type_id']) - ->orderBy('id', 'asc'); - + ->select('id') + ->where('ticket_type', $fetchData['ticket_type_id']) + ->orderBy('id', 'asc'); + if ($fetchData['ticket_type_id'] == 1 && !empty($fetchData['tpa_no'])) { $results = $claimStatusQuery->findAll(2); $fetchData['claim_status_id'] = $results[1]['id'] ?? $results[0]['id']; } else { $fetchData['claim_status_id'] = $claimStatusQuery->first()['id']; } - + $fetchData['priority'] = 1; $fetchData['mode_of_intimation'] = 3; @@ -3636,21 +3643,18 @@ class EmployeeRestController extends AdminController $this->myLogger->logme('error', "Claim initiated, Failed to send Mail :$ticket_id "); return $this->respond(['status' => false, 'code' => 400, 'message' => $message], 200); } - } else { $message = 'Something Went Wrong'; return $this->respond(['status' => false, 'code' => 400, 'message' => $message], 200); } - - }else{ + } else { return $this->response->setJSON(['status' => false, 'code' => 200, 'message' => 'The employee is not active.'])->setStatusCode(404); } } public function handleCliamFiles($data, $ticket_id, $ticket_message_id = null) { - if(!empty($data) && !empty($ticket_id)) - { + if (!empty($data) && !empty($ticket_id)) { $insert_ids = []; $pdf_exist_in_the_file = false; $claim_file = new ClaimFilesModel(); @@ -3668,17 +3672,17 @@ class EmployeeRestController extends AdminController $insert_ids[] = $claim_file->insert($data); - if(getMimeTypeByFileName($value['file_name']) == "application/pdf"){ + if (getMimeTypeByFileName($value['file_name']) == "application/pdf") { $pdf_exist_in_the_file = true; } } - if($pdf_exist_in_the_file){ + if ($pdf_exist_in_the_file) { // this call for TPA integration $apiServiceController = new ApiServiceController(); $apiServiceController->pushClaims($ticket_id); log_message('error', "pushClaims function called with Ticket ID: {$ticket_id}, In Employee Rest Controller"); - }else{ + } else { log_message('error', "Failed to call the pushClaims function in EmployeeRestController for Ticket ID: {$ticket_id}, because the .pdf file does not exist."); } @@ -3777,8 +3781,7 @@ class EmployeeRestController extends AdminController } $filtered = array_values($filtered); - return $this->response->setJSON(['status' => true,'code' => 200, 'ticket_type' => $filtered ])->setStatusCode(200); - + return $this->response->setJSON(['status' => true, 'code' => 200, 'ticket_type' => $filtered])->setStatusCode(200); } catch (\Throwable $e) { $this->myLogger->logme('error', "Error in get_ticket_type: " . $e->getMessage() . " Trace: " . $e->getTraceAsString()); return $this->response->setJSON([ @@ -3804,7 +3807,7 @@ class EmployeeRestController extends AdminController $ticket_type = $this->request->getGet('ticket_type') ?? null; $ticket_id = $this->request->getGet('ticket_id') ?? null; $request = \Config\Services::request(); - $uri = $request->uri->getPath(); + $uri = $request->uri->getPath(); $returnType = ""; // $returnType = (strpos($uri, 'api') !== false) ? 'api' : 'web'; // dd($emp_id); @@ -3818,24 +3821,40 @@ class EmployeeRestController extends AdminController if (!empty($ticket_data)) { - $client_claim_status = [ - 'Received' => [1, 2, 3, 4, 15, 16, 17, 18, 25, 26, 27, 28, 35, 36, 37, 38], - 'Rejected' => [8, 49, 55, 60], - 'Cancelled' => [13, 47, 53, 58], - 'Returned' => [14, 48, 54, 59], - 'Closed' => [12, 22, 32, 42], - 'Approved' => [9, 20, 30, 40], - 'Settled' => [11, 24, 34], - 'Under Process' => [5, 6, 7, 10, 19, 23, 45, 50, 29, 33, 51, 39, 43, 56], - ]; + // $client_claim_status = [ + // 'Received' => [1, 2, 3, 4, 15, 16, 17, 18, 25, 26, 27, 28, 35, 36, 37, 38], + // 'Rejected' => [8, 49, 55, 60], + // 'Cancelled' => [13, 47, 53, 58], + // 'Returned' => [14, 48, 54, 59], + // 'Closed' => [12, 22, 32, 42], + // 'Approved' => [9, 20, 30, 40], + // 'Settled' => [11, 24, 34], + // 'Under Process' => [5, 6, 7, 10, 19, 23, 45, 50, 29, 33, 51, 39, 43, 56], + // ]; + + // $client_claim_status = [ + // 'Claim Received' => [1, 2, 3, 15, 16, 17, 18, 25, 26, 27, 28, 35, 36, 37, 38], + // 'Under Process' => [5, 6, 7, 10, 19, 23, 45, 50, 29, 33, 51, 39, 43, 56], + // 'Information Required' => [4], + // 'Approved' => [9, 20, 30, 40], + // 'Settled' => [11, 24, 34], + // 'Denial Review Awaited' => [66], + // 'Rejected' => [8, 49, 55, 60], + // ]; + + // construct the claim status + $client_claim_status = $this->getClaimStatusGrouped(); foreach ($ticket_data as $key => $value) { 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 } } + $ticket_data[$key]['priority_type'] = $priorityType[$value['priority']] ?? null; $ticket_data[$key]['mode_of_intimate_type'] = $modeOFIntimate[$value['mode_of_intimation']] ?? null; $ticket_data[$key]['relationship_type'] = ucfirst($value['relationship']) ?? null; @@ -3843,9 +3862,9 @@ class EmployeeRestController extends AdminController if (in_array($value['claim_type'], [2, 3, 4])) { $claimPrimaryTypey = "2"; } - $ticket_data[$key]['claim_type_value'] = $claimType[$claimPrimaryTypey][$value['claim_type']] ?? null; + $ticket_data[$key]['claim_type_value'] = $claimType[$claimPrimaryTypey][$value['claim_type']] ?? null; $ticket_data[$key]['ticket_policy_type'] = $ticketTypeArray[$value['ticket_type_id']] ?? null; - + $claim_file_urls = []; if (isset($value['ticket_message_id'])) { @@ -3860,7 +3879,7 @@ class EmployeeRestController extends AdminController ->findAll(); foreach ($claim_files_data as &$value) { - $value['url'] = base_url('downloadClaimFile/') . $value['claim_file_id']; + $value['url'] = base_url('downloadClaimFile/') . $value['claim_file_id']; $claim_file_urls[] = $value; } unset($value); @@ -3868,15 +3887,41 @@ class EmployeeRestController extends AdminController // always set the key (empty if no files found) $ticket_data[$key]['claim_files'] = $claim_file_urls; - } } return $this->response->setJSON(['ticket_data' => $ticket_data])->setStatusCode(200); } + public function getClaimStatusGrouped() + { + // Fetch active claim statuses + $ticketClaimStatus = $this->claimStatusModel + ->select('id, display_name') + ->where('display_name IS NOT NULL') + ->where('is_active', 1) + ->findAll(); + + $result = []; + + foreach ($ticketClaimStatus as $row) { + $name = $row['display_name']; + $id = $row['id']; + + if (!isset($result[$name])) { + $result[$name] = []; + } + + $result[$name][] = $id; + } + + return $result; + } + + // not in use did for testing - function encrypt_for_sso(): string { + function encrypt_for_sso(): string + { $key = "32D1D5535157AF3D4667ADAB0CC795D77D022BB281AD3272EB134C72BD0B185E"; @@ -3930,8 +3975,6 @@ class EmployeeRestController extends AdminController $finalUrl = $baseURL . '/sso?userParams=' . $output . '&clientId=' . $clientId; return $finalUrl; - - } @@ -4040,7 +4083,7 @@ class EmployeeRestController extends AdminController // } public function getPreEmployeePolicyCount($mobile_no, $clientId = null, $email = null) - { + { log_message('error', 'STEP 1: getPreEmployeePolicyCount called with params: ' . json_encode(['mobile_no' => $mobile_no, 'client_id' => $clientId, 'email' => $email])); if (empty($mobile_no) && empty($email)) { @@ -4061,25 +4104,23 @@ class EmployeeRestController extends AdminController } else { log_message('error', 'STEP 4: No client found for ID: ' . $clientId); } - } else { log_message('error', 'STEP 3: No clientId provided. Skipping client lookup.'); } - if(!empty($email)){ + if (!empty($email)) { $post_data = [ 'email_id' => $email, 'client_short_name' => $client_short_name ]; - }else{ + } else { $post_data = [ 'mobile_number' => $mobile_no, 'client_short_name' => $client_short_name ]; - } - + log_message('error', 'STEP 5: Calling third-party API with payload: ' . json_encode($post_data)); @@ -4104,80 +4145,79 @@ class EmployeeRestController extends AdminController } } - private function callThirdPartyAPI($postData , $endPoint) + private function callThirdPartyAPI($postData, $endPoint) { $client = \Config\Services::curlrequest(); - $url = env('PRE_ENROLLMENT_BASEURL').$endPoint; - $response = $client->post( $url, ['json' => $postData, 'http_errors' => false ] ); + $url = env('PRE_ENROLLMENT_BASEURL') . $endPoint; + $response = $client->post($url, ['json' => $postData, 'http_errors' => false]); // return json_decode($response->getBody(), true); return $response->getBody(); } - //-------------------------------------------------------------------------------------------- - public function hrFileUpload() - { - try { - // Check file - $file = $this->request->getFile('file_name'); - if (!$file) { - return $this->response->setJSON([ - 'status' => false, - 'message' => "Invalid file or file not uploaded.", - 'data' => "No Data" - ]); - } - - // Upload folder path - $uploadPath = WRITEPATH . 'uploads/hr_files/'; - - // If directory not exists, create it - if (!is_dir($uploadPath)) { - mkdir($uploadPath, 0777, true); - } - - // New file name with timestamp - $newFileName = time() . '_' . $file->getRandomName(); - - // Move file - $file->move($uploadPath, $newFileName); - - // Prepare data - $data = [ - 'client_id' => $this->request->getPost('client_id'), - 'client_branch_id' => $this->request->getPost('client_branch_id'), - 'policy_id' => $this->request->getPost('policy_id'), - 'policy_no' => $this->request->getPost('policy_no'), - 'file_name' => $newFileName, - 'file_action' => $this->request->getPost('file_action'), - 'status' => 'Yet to start', - 'created_by' => $this->request->getPost('created_by'), - 'updated_by' => $this->request->getPost('created_by'), - ]; - - // Save into DB - $result = $this->hrFileUploadModel->insert($data); + //-------------------------------------------------------------------------------------------- + public function hrFileUpload() + { + try { + // Check file + $file = $this->request->getFile('file_name'); + if (!$file) { + return $this->response->setJSON([ + 'status' => false, + 'message' => "Invalid file or file not uploaded.", + 'data' => "No Data" + ]); + } - if($result){ + // Upload folder path + $uploadPath = WRITEPATH . 'uploads/hr_files/'; + + // If directory not exists, create it + if (!is_dir($uploadPath)) { + mkdir($uploadPath, 0777, true); + } + + // New file name with timestamp + $newFileName = time() . '_' . $file->getRandomName(); + + // Move file + $file->move($uploadPath, $newFileName); + + // Prepare data + $data = [ + 'client_id' => $this->request->getPost('client_id'), + 'client_branch_id' => $this->request->getPost('client_branch_id'), + 'policy_id' => $this->request->getPost('policy_id'), + 'policy_no' => $this->request->getPost('policy_no'), + 'file_name' => $newFileName, + 'file_action' => $this->request->getPost('file_action'), + 'status' => 'Yet to start', + 'created_by' => $this->request->getPost('created_by'), + 'updated_by' => $this->request->getPost('created_by'), + ]; + + // Save into DB + $result = $this->hrFileUploadModel->insert($data); + + if ($result) { $this->giveNotificationToClientsAccountManager($data); - } - - return $this->respondCreated([ - 'status' => true, - 'message' => 'File uploaded successfully', - 'data' => $data - ]); - - } catch (\Exception $e) { - return $this->failServerError($e->getMessage()); - } - - } + } - private function giveNotificationToClientsAccountManager($data){ - - $client_name = $this->clientModel->where('id',$data['client_id'])->findAll()[0]['client_name'] ?? [] ; + return $this->respondCreated([ + 'status' => true, + 'message' => 'File uploaded successfully', + 'data' => $data + ]); + } catch (\Exception $e) { + return $this->failServerError($e->getMessage()); + } + } + + private function giveNotificationToClientsAccountManager($data) + { + + $client_name = $this->clientModel->where('id', $data['client_id'])->findAll()[0]['client_name'] ?? []; $account_manager_email = $this->clientRMModel->findAccountManagerEmail($data['client_id']); @@ -4185,20 +4225,20 @@ class EmployeeRestController extends AdminController $mailTemplate = $this->ticketMailTemplateModel->where('template_name', $templateName)->findAll()[0] ?? []; - if(empty($mailTemplate)){ + if (empty($mailTemplate)) { //empty mail template please update the template in database or create one..!! - log_message("error","Empty mail template for inception_addition please update the template in database or create one..!!"); - return ; + log_message("error", "Empty mail template for inception_addition please update the template in database or create one..!!"); + return; } - + $data['file_action'] = ucwords(preg_replace("/_/", " ", $data['file_action'])); $mailTemplate['mail_content'] = str_replace('%file_action%', $data['file_action'] ?? '', $mailTemplate['mail_content']); $mailTemplate['mail_content'] = str_replace('%client_name%', $client_name ?? '', $mailTemplate['mail_content']); $mailTemplate['mail_content'] = str_replace('%policy_no%', $data['policy_no'] ?? '', $mailTemplate['mail_content']); - $mailTemplate['subject'] = str_replace('%subject%',$data['file_action']??'',$mailTemplate['subject']); - $mailTemplate['subject'] = str_replace('%client_name%',$client_name??'',$mailTemplate['subject']); + $mailTemplate['subject'] = str_replace('%subject%', $data['file_action'] ?? '', $mailTemplate['subject']); + $mailTemplate['subject'] = str_replace('%client_name%', $client_name ?? '', $mailTemplate['subject']); $from_mail = ""; $to_mail = $account_manager_email; @@ -4208,62 +4248,60 @@ class EmployeeRestController extends AdminController $attachments = ""; $reply_to = ""; $bcc_string = ""; - - MailHelper::send_email(['from_mail' => $from_mail, 'mail' => $to_mail, 'cc' => $cc_string, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to, 'bcc' => $bcc_string]); - } + MailHelper::send_email(['from_mail' => $from_mail, 'mail' => $to_mail, 'cc' => $cc_string, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to, 'bcc' => $bcc_string]); + } + + public function updateHrFileUploadData() + { + try { + $id = $this->request->getPost('id'); + + if (!$id) { + return $this->failValidationErrors('ID is required for update.'); + } + + // Prepare data + $data = [ + 'client_id' => $this->request->getPost('client_id'), + 'client_branch_id' => $this->request->getPost('client_branch_id'), + 'policy_id' => $this->request->getPost('policy_id'), + 'policy_no' => $this->request->getPost('policy_no'), + 'file_action' => $this->request->getPost('file_action'), + 'status' => $this->request->getPost('status'), + 'updated_by' => $this->request->getPost('updated_by'), + ]; + + // Check if record exists + $record = $this->hrFileUploadModel->find($id); + if (!$record) { + return $this->failNotFound("Record with ID {$id} not found."); + } + + // Update record + $this->hrFileUploadModel->update($id, $data); + + return $this->respond([ + 'status' => true, + 'message' => 'File record updated successfully', + 'data' => $data + ], 200); + } catch (\Exception $e) { + return $this->failServerError($e->getMessage()); + } + } + + + public function hrFileDownload($id = null) + { + try { - public function updateHrFileUploadData() - { - try { - $id = $this->request->getPost('id'); - - if (!$id) { - return $this->failValidationErrors('ID is required for update.'); - } - - // Prepare data - $data = [ - 'client_id' => $this->request->getPost('client_id'), - 'client_branch_id' => $this->request->getPost('client_branch_id'), - 'policy_id' => $this->request->getPost('policy_id'), - 'policy_no' => $this->request->getPost('policy_no'), - 'file_action' => $this->request->getPost('file_action'), - 'status' => $this->request->getPost('status'), - 'updated_by' => $this->request->getPost('updated_by'), - ]; - - // Check if record exists - $record = $this->hrFileUploadModel->find($id); - if (!$record) { - return $this->failNotFound("Record with ID {$id} not found."); - } - - // Update record - $this->hrFileUploadModel->update($id, $data); - - return $this->respond([ - 'status' => true, - 'message' => 'File record updated successfully', - 'data' => $data - ], 200); - - } catch (\Exception $e) { - return $this->failServerError($e->getMessage()); - } - } - - - public function hrFileDownload($id = null) - { - try { - $file_id = $this->request->getGet('id') ?? $id; - + // Find record - $record = $this->hrFileUploadModel->where('id',$file_id)->find(); - + $record = $this->hrFileUploadModel->where('id', $file_id)->find(); + // print_rr( $record);die; if (!$record) { @@ -4281,19 +4319,19 @@ class EmployeeRestController extends AdminController // Force file download return $this->response->download($filePath, null) - ->setFileName($record[0]['file_name']); - } catch (\Exception $e) { - return $this->failServerError($e->getMessage()); - } - } - + ->setFileName($record[0]['file_name']); + } catch (\Exception $e) { + return $this->failServerError($e->getMessage()); + } + } + // public function hrFileList() // { // try { // $request = service('request'); // $builder = $this->hrFileUploadModel // ->select('hr_file_upload.* , c.short_name , cb.branch_name , lc.name as first_name '); - + // // Allowed filter keys // $filters = [ // 'client_id', @@ -4303,7 +4341,7 @@ class EmployeeRestController extends AdminController // 'status', // 'created_by' // ]; - + // // Apply filters dynamically // foreach ($filters as $key) { // $value = $request->getGetPost($key); // supports both GET and POST @@ -4311,13 +4349,13 @@ class EmployeeRestController extends AdminController // $builder->where($key, $value); // } // } - + // // Fetch results // $builder->join('clients c', 'c.id = hr_file_upload.client_id AND c.is_active = 1', 'left'); // $builder->join('client_branch cb', 'cb.id = hr_file_upload.client_branch_id AND cb.is_active = 1', 'left'); // $builder->join('level_contacts lc', 'lc.id = hr_file_upload.created_by AND lc.contact_type = "client" AND lc.is_active = 1', 'left'); // $data = $builder->findAll(); - + // return $this->respond([ // 'status' => true, // 'message' => 'File list fetched successfully', @@ -4370,10 +4408,10 @@ class EmployeeRestController extends AdminController FROM files f1 WHERE f1.is_active = 1 ORDER BY f1.id DESC - LIMIT 1) f', - 'f.hr_file_id = hr_file_upload.id', + LIMIT 1) f', + 'f.hr_file_id = hr_file_upload.id', 'left' - ); + ); // Allowed filter keys $filters = [ @@ -4406,7 +4444,7 @@ class EmployeeRestController extends AdminController return $this->failServerError($e->getMessage()); } } - + public function hrFileUploadMasters() { try { @@ -4432,14 +4470,14 @@ class EmployeeRestController extends AdminController if (empty($policy_id)) { $policy_id = $this->request->getGet('policy_id'); $api_name = $this->request->getGet('api_name'); - log_message('error', "Input parameters fetched from GET: policy_id={$policy_id}, api_name={$api_name}"); + log_message('error', "Input parameters fetched from GET: policy_id={$policy_id}, api_name={$api_name}"); } else { - log_message('error', "Input parameters received directly: policy_id={$policy_id}, api_name={$api_name}"); + log_message('error', "Input parameters received directly: policy_id={$policy_id}, api_name={$api_name}"); } // Step 2: Validate policy_id if (empty($policy_id)) { - log_message('error', 'Policy ID is empty'); + log_message('error', 'Policy ID is empty'); if ($return_type == 'api') { return $this->respond(['status' => false, 'code' => 200, 'message' => 'Policy ID missing']); } @@ -4447,14 +4485,14 @@ class EmployeeRestController extends AdminController } // Step 3: Fetch policy data - log_message('error', "Fetching policy data for policy_id={$policy_id}"); + log_message('error', "Fetching policy data for policy_id={$policy_id}"); $policy_data = $this->clientPolicyModel ->where('is_active', 1) ->where('id', $policy_id) ->first(); if (empty($policy_data)) { - log_message('error', "Policy data not found for policy_id={$policy_id}"); + log_message('error', "Policy data not found for policy_id={$policy_id}"); if ($return_type == 'api') { return $this->respond(['status' => false, 'code' => 200, 'message' => 'Policy data not found']); } @@ -4463,7 +4501,7 @@ class EmployeeRestController extends AdminController // Step 4: Check for TPA ID if (empty($policy_data['tpa_id'])) { - log_message('error', "TPA ID not found for policy_id={$policy_id}"); + log_message('error', "TPA ID not found for policy_id={$policy_id}"); if ($return_type == 'api') { return $this->respond(['status' => false, 'code' => 200, 'message' => 'TPA ID not found']); } @@ -4471,10 +4509,10 @@ class EmployeeRestController extends AdminController } $tpa_id = $policy_data['tpa_id']; - log_message('error', "Found TPA ID={$tpa_id} for policy_id={$policy_id}"); + log_message('error', "Found TPA ID={$tpa_id} for policy_id={$policy_id}"); // Step 5: Check if API service is enabled - log_message('error', "Checking TPA API service for TPA ID={$tpa_id} and API name={$api_name}"); + log_message('error', "Checking TPA API service for TPA ID={$tpa_id} and API name={$api_name}"); $tpaApiServiceModel = new TpaApiSeviceModel(); $api_data = $tpaApiServiceModel ->where('is_active', 1) @@ -4483,34 +4521,34 @@ class EmployeeRestController extends AdminController ->first(); if (!empty($api_data)) { - log_message('error', "API '{$api_name}' is enabled for TPA ID={$tpa_id}"); + log_message('error', "API '{$api_name}' is enabled for TPA ID={$tpa_id}"); if ($return_type == 'api') { return $this->respond(['status' => true, 'code' => 200, 'message' => 'API services enabled']); } return true; } else { - log_message('error', "API '{$api_name}' is NOT enabled for TPA ID={$tpa_id}"); + log_message('error', "API '{$api_name}' is NOT enabled for TPA ID={$tpa_id}"); if ($return_type == 'api') { return $this->respond(['status' => false, 'code' => 200, 'message' => 'API services not enabled']); } return false; } } catch (\Throwable $th) { - log_message('error', 'Exception in checkTpaApiEnable: ' . $th->getMessage()); + log_message('error', 'Exception in checkTpaApiEnable: ' . $th->getMessage()); if ($return_type == 'api') { return $this->respond(['status' => false, 'code' => 500, 'message' => 'Internal Server Error']); } return false; } finally { - log_message('error', '--- END checkTpaApiEnable ---'); + log_message('error', '--- END checkTpaApiEnable ---'); } } - public function getEcardURL() - { - try{ + public function getEcardURL() + { + try { $id = $this->request->getGet('id'); $emp_code = $this->request->getGet('emp_code'); @@ -4518,40 +4556,34 @@ class EmployeeRestController extends AdminController $policy_no = $this->request->getGet('policy_no'); $employee_policy = $this->employeePolicyModel - ->select('employees.*, employee_polices.tpa_id , employee_polices.rand_string , employee_polices.uhid as uhid , client_policy.tpa_id as tpa_primary_id ') - ->join('employees', 'employee_polices.employee_id = employees.id', 'left') - ->join('client_policy', 'employee_polices.client_policy_id = client_policy.id', 'left') - ->where('employee_polices.employee_id',$id) - ->where('employee_polices.client_policy_id',$client_policy_id) - ->where('employee_polices.is_active', 1 )->findAll(); + ->select('employees.*, employee_polices.tpa_id , employee_polices.rand_string , employee_polices.uhid as uhid , client_policy.tpa_id as tpa_primary_id ') + ->join('employees', 'employee_polices.employee_id = employees.id', 'left') + ->join('client_policy', 'employee_polices.client_policy_id = client_policy.id', 'left') + ->where('employee_polices.employee_id', $id) + ->where('employee_polices.client_policy_id', $client_policy_id) + ->where('employee_polices.is_active', 1)->findAll(); - - if(count($employee_policy) > 0) - { - if($employee_policy[0]['tpa_id'] != null) - { - if($employee_policy[0]['tpa_primary_id'] == 2)//Medi assist + + if (count($employee_policy) > 0) { + if ($employee_policy[0]['tpa_id'] != null) { + if ($employee_policy[0]['tpa_primary_id'] == 2) //Medi assist { $mediAssistController = new MediAssistApiController(); - $data['eCardDownload'] = $mediAssistController->EcardRequest( $emp_code, $policy_no ); - }else{ - $data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string'].'/1'; + $data['eCardDownload'] = $mediAssistController->EcardRequest($emp_code, $policy_no); + } else { + $data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string'] . '/1'; } - } else { - $data['eCardDownload'] = null; + $data['eCardDownload'] = null; } - }else{ - $data['eCardDownload'] = null; + } else { + $data['eCardDownload'] = null; } - return $this->respond(['status' => true,'message' => '','data' => $data]); - - } catch(\Exception $e){ - + return $this->respond(['status' => true, 'message' => '', 'data' => $data]); + } catch (\Exception $e) { } - } - -} \ No newline at end of file + } +} diff --git a/app/Controllers/EmployeeServiceController.php b/app/Controllers/EmployeeServiceController.php index 690e9c08..28721878 100755 --- a/app/Controllers/EmployeeServiceController.php +++ b/app/Controllers/EmployeeServiceController.php @@ -1387,10 +1387,16 @@ class EmployeeServiceController extends AdminController $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); + $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 new file mode 100644 index 00000000..f2907bf6 --- /dev/null +++ b/app/Controllers/InsuranceCommissionController.php @@ -0,0 +1,279 @@ +myLogger = \Config\Services::mylogger(); + // Load rules file if present in writable config path + // $rulesPath = WRITEPATH . 'config/insurance_rules.json'; + // if (file_exists($rulesPath)) { + // $this->loadRulesFromFile($rulesPath); + // } + } + + /** + * POST /insurance/calculate + * Accepts JSON body with policy data and returns commission calculation + */ + public function initiateCommissionCalc() + { + // Accept POST params (JSON, form-data, x-www-form-urlencoded) + $input = $this->request->getPost(); + + if (empty($input)) { + $json = $this->request->getJSON(true); + if ($json) { + $input = $json; + } + } + + if (empty($input)) { + return $this->failValidationError('No input data received'); + } + // -------- Required Params Check -------- + if (empty($input['policy_issue_date'])) { + return $this->failValidationError('policy_issue_date is required'); + } + + if (empty($input['department'])) { + return $this->failValidationError('department is required'); + } + + if (empty($input['insurer_id'])) { + return $this->failValidationError('insurer_id is required'); + } + + + // -------- Build Dynamic Rules Path -------- + $policyDate = strtotime($input['policy_issue_date']); + if (!$policyDate) { + return $this->failValidationError('Invalid policy_issue_date'); + } + + $month = strtoupper(date('M', $policyDate)); // SEP + $year = date('Y', $policyDate); // 2025 + $folderName = $month . $year; // SEP2025 + + $insurerId = $input['insurer_id']; // 5 + $department = ucfirst(strtolower($input['department'])); // Motor, Health, Fire + + // Final Path: WRITEPATH/rules/SEP2025/5_Motor.json + $rulesPath = WRITEPATH . "uploads/commission/rules/{$folderName}/{$insurerId}_{$department}.json"; + // echo $rulesPath;die(); + + if (!file_exists($rulesPath)) { + return $this->fail("Rules file not found at: {$rulesPath}"); + } + + // Load the dynamic rule set + $this->loadRulesFromFile($rulesPath); + + // -------- Execute Rule Matching & Commission Calculation -------- + try { + $result = $this->calculateCommission($input); + + $comment = isset($result['rule']['name']) + ? "Matched rule: " . $result['rule']['name'] + : "Matched rule: (unnamed rule)"; + + return $this->respond([ + 'success' => true, + 'data' => [ + 'payout' => $result['payout'], + 'rule' => $result['rule'], + 'comment' => $comment, + // 'rules_path_used' => $rulesPath + ] + ]); + + } catch (\Exception $e) { + return $this->fail($e->getMessage()); + } + } + + + /** + * Load rules JSON and normalise department keys to lowercase for lookups + */ + private function loadRulesFromFile(string $filePath) + { + if (!file_exists($filePath)) { + throw new \Exception("Rules file not found: {$filePath}"); + } + + $json = file_get_contents($filePath); + $parsed = json_decode($json, true); + + if (json_last_error() !== JSON_ERROR_NONE) { + throw new \Exception('Invalid JSON in rules file: ' . json_last_error_msg()); + } + // print_r($parsed);die(); + // Normalise department keys to lowercase for consistent lookups + $this->rules = []; + foreach ($parsed as $dept => $rules) { + if($rules['is_deleted'] === false) + { + $this->rules[strtolower($dept)] = $rules; + } + } + + // print_r($this->rules);die(); + } + + public function calculateCommission(array $policyData) + { + $department = $policyData['department'] ?? ''; + $deptKey = strtolower($department); + // print_r($this->rules);die(); + // if (!isset($this->rules[$deptKey])) { + // throw new \Exception("No rules found for department: {$department}"); + // } + + $matchingRules = []; + + foreach ($this->rules as $rule) { + if ($this->evaluateConditions($rule['conditions'] ?? [], $policyData)) { + $matchingRules[] = $rule; + } + } + + if (empty($matchingRules)) { + throw new \Exception('No matching rules found for the policy data'); + } + // print_r($matchingRules);die; + // Use the first matching rule. In future you can implement priority/weighting + $applicableRule = $matchingRules[0]; + + $payout = $this->applyCalculation($applicableRule['calculation'], $policyData); + + return ['rule' => $applicableRule, 'payout' => $payout]; + } + + private function evaluateConditions(array $conditions, array $data): bool + { + foreach ($conditions as $condition) { + $field = $condition['field']; + $operator = $condition['operator']; + $expectedValue = $condition['value']; + + if (!array_key_exists($field, $data)) { + return false; + } + + $actualValue = $data[$field]; + + if (!$this->compareValues($actualValue, $operator, $expectedValue)) { + return false; + } + } + + return true; + } + + private function compareValues($actual, string $operator, $expected): bool + { + switch ($operator) { + case '==': + return $actual == $expected; + case '!=': + return $actual != $expected; + case '>': + return $actual > $expected; + case '>=': + return $actual >= $expected; + case '<': + return $actual < $expected; + case '<=': + return $actual <= $expected; + case 'between': + return is_array($expected) && $actual >= $expected[0] && $actual <= $expected[1]; + case 'in': + return is_array($expected) && in_array($actual, $expected); + default: + throw new \Exception("Unsupported operator: {$operator}"); + } + } + + private function applyCalculation(array $calculation, array $policyData) + { + $type = $calculation['type'] ?? null; + + switch ($type) { + case 'percentage': + $percentage = $calculation['value'] ?? 0; + $base = $calculation['on'] ?? null; + + if ($base === null || !isset($policyData[$base])) { + throw new \Exception("Base value for calculation not found: {$base}"); + } + + return ($percentage / 100) * $policyData[$base]; + + case 'composite': + $total = 0; + + foreach ($calculation['components'] as $component) { + $percentage = $component['percentage'] ?? 0; + $base = $component['on'] ?? null; + + if ($base === null || !isset($policyData[$base])) { + throw new \Exception("Base value for calculation not found: {$base}"); + } + + if (!empty($component['only_first_year'])) { + if (!empty($policyData['is_renewal'])) { + continue; // Skip this component for renewals + } + } + + $total += ($percentage / 100) * $policyData[$base]; + } + + return $total; + + case 'fixed': + $fixedAmount = $calculation['value'] ?? 0; + + // If 'on' specified but not needed, return fixed amount as-is + return $fixedAmount; + + default: + throw new \Exception('Unsupported calculation type: ' . $type); + } + } + + public function getVolumeReward(array $premiumData) + { + $annualPremium = $premiumData['annual_premium'] ?? 0; + $department = $premiumData['department'] ?? ''; + + if ($department === 'Fire' || $department === 'Marine' || $department === 'Engineering') { + if ($annualPremium > 20000000) { + return 0.01 * $annualPremium; + } elseif ($annualPremium > 10000000) { + return 0.005 * $annualPremium; + } elseif ($annualPremium > 5000000) { + return 0.0025 * $annualPremium; + } + } elseif ($department === 'Motor') { + if ($annualPremium > 15000000) { + return 0.02 * $annualPremium; + } elseif ($annualPremium > 7500000) { + return 0.01 * $annualPremium; + } + } + + return 0; + } +} diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php index 76bd1a5a..d2ce1329 100755 --- a/app/Controllers/MasterController.php +++ b/app/Controllers/MasterController.php @@ -1976,6 +1976,9 @@ class MasterController extends AdminController 'lead_files' => WRITEPATH . 'uploads/lead_files/', 'claim_files' => WRITEPATH . 'uploads/claim_files/', 'claim_dump_excel' => WRITEPATH . 'uploads/claim_dump_excel/', + 'commission' => WRITEPATH . 'uploads/commission/', + 'files' => WRITEPATH . 'uploads/commission/files', + 'rules' => WRITEPATH . 'uploads/commission/rules', 'claim_sample_forms' => ROOTPATH . 'public/claim_sample_forms/', ]; diff --git a/app/Controllers/MediAssistApiController.php b/app/Controllers/MediAssistApiController.php index 4e13298c..621a187f 100644 --- a/app/Controllers/MediAssistApiController.php +++ b/app/Controllers/MediAssistApiController.php @@ -331,6 +331,7 @@ class MediAssistApiController extends BaseController $db = \Config\Database::connect(); $updated = 0; + $employee_policy_ids = []; foreach ($employeePolicyData as $policy_data) { foreach ($allBenef as $row) { @@ -370,6 +371,10 @@ class MediAssistApiController extends BaseController WHERE id = ?"; $db->query($sql, [$row['benefMediAssistID'], $policy_data['emp_policy_id']]); + // for e-card send + if(strtolower(trim($policy_data['relationship'])) == 'self'){ + $employee_policy_ids[] = $policy_data['emp_policy_id']; + } if ($db->affectedRows() > 0) { $updated++; @@ -384,6 +389,12 @@ class MediAssistApiController extends BaseController } } + // send e-card + if(!empty($employee_policy_ids)){ + log_message('error', "sendMailForDownloadingECard JOB PUSHED."); + Jobs::addJob(['job_name' => 'sendMailForDownloadingECard', 'payload' => $employee_policy_ids]); + } + // update file table status after the tpa id successfully updated if (isset($requestData['file_id']) && !empty($requestData['file_id'])) { $file_model = new BatchFileModel(); diff --git a/app/Controllers/NotificationController.php b/app/Controllers/NotificationController.php index ee50a0fd..98067fa9 100755 --- a/app/Controllers/NotificationController.php +++ b/app/Controllers/NotificationController.php @@ -258,7 +258,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 +268,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 new file mode 100644 index 00000000..7dccb5ba --- /dev/null +++ b/app/Controllers/PayoutController.php @@ -0,0 +1,616 @@ +myLogger = \Config\Services::mylogger(); + + $this->payout_status = [ + 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() + { + // for filtering list + if($this->request->is('post')){ + try{ + $data = $this->request->getPost(); + // print_r($data); die; + + $agent_id = $data['agent_id'] ?? null; + $status_id = $data['status_id'] ?? null; + $start_date = $data['start_date'] ?? null; + $end_date = $data['end_date'] ?? null; + + $payout_data = $this->invoiceModel->invoiceList($agent_id, $status_id, $start_date, $end_date); + + $payout_data['payout_list_data'] = $payout_data; + $payout_data = view('payout_list', $payout_data); + + if(!empty($payout_data)){ + return $this->respond(['status' => true, 'code' => 200, 'data' => $payout_data], 200); + }else{ + return $this->respond(['status' => false, 'code' => 400, 'data' => $payout_data, "message" => "No data found"], 200); + } + }catch (\Throwable $th) { + + $this->myLogger->logme("error", "PayoutController - payoutList: Exception: " . $th->getMessage() . " --- Line: " . $th->getLine() . " --- Trace: " . $th->getTraceAsString()); + $errorData = [ + 'message' => $th->getMessage(), + 'file' => $th->getFile(), + 'line' => $th->getLine(), + 'code' => $th->getCode(), + 'trace' => $th->getTraceAsString(), + 'trace_array' => $th->getTrace(), // full array version (optional) + 'function' => $th->getTrace()[0]['function'] ?? null, + 'class' => $th->getTrace()[0]['class'] ?? null, + ]; + $payout_data = view('payout_list'); + return $this->respond(['status' => false, 'code' => 500, 'data' => $payout_data, "message" => "No data found", 'error_data' => $errorData], 500); + } + } + + // for list + $data['payout_status'] = $this->payout_status; + $data['agent_list'] = $this->invoiceModel->agentList(); + $data['page_name'] = "Invoices"; + $payout_data['payout_list_data'] = $this->invoiceModel->invoiceList(); + $data['payout_list'] = view('payout_list', $payout_data); + + // dd($data); + return $this->loadLayout('payout_list_handler', $data); + } + + public function fetchUtrDetails() + { + $invoice_id = $this->request->getPost('invoice_id') ?? null; + $payout_data = $this->constructUtrDetails($invoice_id); + + if(!empty($payout_data)){ + return $this->respond(['status' => true, 'code' => 200, 'data' => $payout_data], 200); + }else{ + return $this->respond(['status' => false, 'code' => 400, 'data' => $payout_data, "message" => "No data found"], 200); + } + } + + public function constructUtrDetails($invoice_id) + { + $utr_data = $this->invoiceUtrModel->where('is_active', 1)->where('invoice_id', $invoice_id)->findAll(); + $summary_data = $this->invoiceModel->utrSummary($invoice_id); + + if($summary_data['invoice_amount'] == $summary_data['total_utr_amount']) { + $data['invoice_completed'] = true; + } + + $data['utr_list_data'] = $utr_data; + $data['summary'] = $summary_data; + $data = view('payout_utr_details', $data); + + return $data; + } + + public function saveUtrDetails() + { + $data = $this->request->getPost(); + $invoice_id = $this->request->getPost('invoice_id') ?? null; + $utr_id = $this->request->getPost('utr_pk') ?? null; + + if(isset($data['utr_date'])){ + $data['utr_date'] = change_date_format($data['utr_date']); + } + + + if(!empty($utr_id)){ + + $update = $this->invoiceUtrModel->where('id', $utr_id)->set($data)->update(); + $payout_edit_data = $this->constructUtrDetails($invoice_id); + + if($update){ + + $summary_data = $this->invoiceModel->utrSummary($invoice_id); + if($summary_data['invoice_amount'] == $summary_data['total_utr_amount']){ + $sql = "UPDATE partner_invoice SET payout_status = 2 WHERE id = ?"; + db_connect()->query($sql, [$invoice_id]); + } + + return $this->respond(['status' => true, 'code' => 200, 'data' => $payout_edit_data, "message" => "UTR successfully updated"], 200); + }else{ + return $this->respond(['status' => false, 'code' => 400, 'data' => $payout_edit_data, "message" => "Failed to update UTR"], 200); + } + + }else{ + + unset($data['utr_pk']); + $insert_id = $this->invoiceUtrModel->insert($data); + $payout_data = $this->constructUtrDetails($invoice_id); + + if($insert_id){ + + $summary_data = $this->invoiceModel->utrSummary($invoice_id); + if($summary_data['invoice_amount'] == $summary_data['total_utr_amount']){ + $sql = "UPDATE partner_invoice SET payout_status = 2 WHERE id = ?"; + db_connect()->query($sql, [$invoice_id]); + } + + return $this->respond(['status' => true, 'code' => 200, 'data' => $payout_data, "message" => "UTR added successfully"], 200); + }else{ + return $this->respond(['status' => false, 'code' => 400, 'data' => $payout_data, "message" => "Failed to add UTR"], 200); + } + } + } + + public function removeUtrDetails() + { + $data = $this->request->getPost(); + + if(isset($data['utr_id'])){ + + $sql = "UPDATE partner_invoice_utr SET is_active = 0 WHERE id = ?"; + $update = db_connect()->query($sql, [$data['utr_id']]); + + $payout_data = $this->constructUtrDetails($data['invoice_id'] ?? ""); + + if($update){ + return $this->respond(['status' => true, 'code' => 200, 'data' => $payout_data, "message" => "UTR removed successfully"], 200); + }else{ + return $this->respond(['status' => false, 'code' => 400, 'data' => $payout_data, "message" => "Failed to remove UTR"], 200); + } + }else { + return $this->respond(['status' => false, 'code' => 500, 'data' => "", "message" => "Failed to remove UTR"], 200); + } + } + + + /*************************************************************************************************************/ + //... 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 a2f88d5f..e970d9b5 100644 --- a/app/Controllers/PolicyTransactionController.php +++ b/app/Controllers/PolicyTransactionController.php @@ -496,12 +496,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'] == 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 +545,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 +1008,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 +1599,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) @@ -3197,116 +3208,116 @@ } - 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; + // 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'); + // 🧾 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($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 + 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); } - // 📊 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); - } - } diff --git a/app/Controllers/RuleImportController.php b/app/Controllers/RuleImportController.php new file mode 100644 index 00000000..d1647bae --- /dev/null +++ b/app/Controllers/RuleImportController.php @@ -0,0 +1,844 @@ +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() + { + $data['page_name'] = "Commision File Upload"; + $data['departments'] = $this->departments; + $data['insurers'] = $this->insurerModel->where('is_active', 1)->findAll(); + $data['commission_file_list'] = $this->commissionFilesModel + ->select('commission_files.*, insurers.short_name as insurer_name, user_profiles.first_name as created_user_name') + ->join('insurers', 'commission_files.insurer_id = insurers.id') + ->join('user_profiles', 'commission_files.created_by = user_profiles.id') + ->where('commission_files.is_active', 1) + ->orderBy('commission_files.id', 'desc') + ->findAll(); + // dd( $data); + return $this->loadLayout('commission_file_upload', $data); + } + + /** + * Upload endpoint for form (POST) + * Input form field: 'rules_file' + */ + public function uploadORI() + { + // echo 'hi'; + !dd($result = $this->ruleImportService->processUpload(['id' => 1,'file_name' => 'sample_commission.csv','insurer_id' => 5, 'department' => 'motor' ,'commission_month' => '2025-11-10']));die; + try { + $file = $this->request->getFile('rules_file'); + if (!$file || !$file->isValid()) { + return $this->response->setJSON(['status'=>false,'message'=>'No file uploaded or upload error']); + } + + // Move uploaded file to writable temp location + $tmpPath = WRITEPATH . 'uploads/' . $file->getRandomName(); + $file->move(WRITEPATH . 'uploads', $file->getName()); // keep original name inside uploads + $uploadedFullPath = $file->getTempName(); // Note: CI may store in tmp; we will use moved file path instead + $movedPath = WRITEPATH . 'uploads/' . $file->getName(); + + // Process file + $result = $this->ruleImportService->processUpload($movedPath, $file->getName()); + + // Return JSON with annotated file link if present + if (isset($result['annotated_file']) && $result['annotated_file']) { + $annotUrl = base_url('writable/uploads/annotated/' . basename($result['annotated_file'])); + $result['annotated_url'] = $annotUrl; + } + + return $this->response->setJSON($result); + + } catch (\Throwable $e) { + $this->myLogger->logme('error', 'RuleImportController::upload ' . $e->getMessage()); + return $this->response->setJSON(['status'=>false,'message'=>$e->getMessage()]); + } + } + + public function upload() + { + try { + + // --------------------------------------------------------- + // 1. Get uploaded file + // --------------------------------------------------------- + $file = $this->request->getFile('rules_file'); + if (!$file || !$file->isValid()) { + $this->myLogger->logme('error', 'RuleImportController::upload - No file or invalid upload.'); + return $this->respond(['status' => false, 'code' => 404, 'message' => 'No file uploaded or upload error.'], 200); + } + + // --------------------------------------------------------- + // 2. Read POST fields + // --------------------------------------------------------- + // print_r($this->request->getPost()); die; + $insurerId = $this->request->getPost('insurer_id'); + $department = $this->request->getPost('department'); + $commissionMonth = $this->request->getPost('commission_month'); + $overwrite = $this->request->getPost('overwrite') ?? 1; + $createdBy = get_session_userid(); + + if (empty($insurerId) || empty($department) || empty($commissionMonth)) { + $this->myLogger->logme('error', 'RuleImportController::upload - Missing required POST data.' . json_encode($this->request->getPost() ?? [])); + return $this->respond(['status' => false, 'code' => 404, 'message' => 'Missing required fields: insurer_id, department, commission_month'], 200); + } + + $commissionMonth = $commissionMonth . '-01'; + $commissionMonth = change_date_format($commissionMonth, 'Y-M-d', 'Y-m-d'); + + // Optional / default fields + $postedFileName = $this->request->getPost('file_name') ?: $file->getClientName(); + $fileStatus = $this->request->getPost('file_status') ?: 'pending'; + $isActive = $this->request->getPost('is_active') !== null ? (int)$this->request->getPost('is_active') : 1; + // rules_count is given by user but we will override it after processing on success + $postedRulesCount = $this->request->getPost('rules_count') !== null + ? (int)$this->request->getPost('rules_count') + : 0; + + // --------------------------------------------------------- + // 3. Move file to WRITEPATH/uploads/commission/files using user filename + // (no random name as per your requirement) + // --------------------------------------------------------- + $uploadDir = WRITEPATH . 'uploads/commission/files/'; + if (!is_dir($uploadDir)) { + if (!mkdir($uploadDir, 0755, true) && !is_dir($uploadDir)) { + throw new \RuntimeException("Failed to create upload directory: {$uploadDir}"); + } + } + + // sanitize user file name but keep it deterministic (no random, no timestamp) + $safeName = preg_replace('/[^a-zA-Z0-9_\-\.]/', '_', $postedFileName); + + // $movedFullPath = $uploadDir . $safeName; + + $file->move($uploadDir, $safeName); + $targetFileName = $file->getName(); + $movedFullPath = $uploadDir . $targetFileName; + if (!file_exists($movedFullPath)) { + $this->myLogger->logme('error', "RuleImportController::upload - Failed to move uploaded file to {$movedFullPath}"); + return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to store uploaded file.'], 500); + } + + $this->myLogger->logme('info', "RuleImportController::upload - File moved to {$movedFullPath}"); + + // --------------------------------------------------------- + // 4. Insert commission_files row with status pending + // --------------------------------------------------------- + $insertData = [ + 'file_name' => $targetFileName, + 'insurer_id' => (int)$insurerId, + 'department' => $department, + 'commission_month' => $commissionMonth, + 'rules_count' => 0, // will update on success + 'file_status' => $fileStatus, // 'pending' by default + 'is_active' => $isActive, + 'created_by' => (int)$createdBy, + 'created_at' => date('Y-m-d H:i:s'), + ]; + + $this->commissionFilesModel->insert($insertData); + $insertId = $this->commissionFilesModel->getInsertID(); + + if (empty($insertId)) { + $this->myLogger->logme('error', 'RuleImportController::upload - Failed to insert commission_files record', ['data' => $insertData]); + return $this->respond([ + 'status' => false, + 'code' => 404, + 'message' => 'Failed to record upload in database.' + ], 200); + } + + $this->myLogger->logme('info', "RuleImportController::upload - commission_files inserted id={$insertId}", $insertData); + + // --------------------------------------------------------- + // 5. Call ruleImportService->processUpload with inserted file info + // As per your spec: + // $this->ruleImportService->processUpload([ + // 'id' => 1, + // 'file_name' => 'sample_commission.csv', + // 'insurer_id' => 5, + // 'department' => 'motor', + // 'commission_month' => '2025-11-10' + // ]) + // --------------------------------------------------------- + $payload = [ + 'id' => (int)$insertId, + 'file_name' => $targetFileName, + 'insurer_id' => (int)$insurerId, + 'department' => $department, + 'commission_month' => $commissionMonth, + 'created_by' => (int)$createdBy, + + ]; + + $this->myLogger->logme('info', 'RuleImportController::upload - Calling ruleImportService->processUpload', ['payload' => $payload]); + + $result = $this->ruleImportService->processUpload($payload); + + if (!is_array($result) || !isset($result['status'])) { + $this->myLogger->logme('error', 'RuleImportController::upload - Invalid service response', ['response' => $result]); + // update file status as failed + $this->commissionFilesModel->update($insertId, [ + 'file_status' => 'failed', + 'updated_by' => (int)$createdBy, + 'updated_at' => date('Y-m-d H:i:s'), + ]); + return $this->respond([ + 'status' => false, + 'code' => 404, + 'message' => 'Invalid response from import service.' + ], 200); + } + + // --------------------------------------------------------- + // 6. Handle SUCCESS + // - result['rules'] exists + // - result['errors'] empty + // - NO annotated_file + // - Save rules as JSON in WRITEPATH/uploads/commission/json/{insurer_id}_{department}.json + // --------------------------------------------------------- + if ($result['status'] === 'success') { + $rulesArray = isset($result['rules']) && is_array($result['rules']) ? $result['rules'] : []; + $rulesCount = count($rulesArray); + + // Save JSON to WRITEPATH . 'uploads/commission/json/{insurer_id}_{department}.json' + $month_path = strtoupper(date('M', strtotime($commissionMonth))) . date('Y', strtotime($commissionMonth)); + $jsonDir = WRITEPATH . 'uploads/commission/rules/'.$month_path . '/'; + if (!is_dir($jsonDir)) { + if (!mkdir($jsonDir, 0755, true) && !is_dir($jsonDir)) { + throw new \RuntimeException("Failed to create JSON output directory: {$jsonDir}"); + } + } + + $this->myLogger->logme('error', 'RuleImportController::jsonDir' . $jsonDir); + + $deptSlug = preg_replace('/[^a-zA-Z0-9_\-]/', '_', strtolower($department)); + $jsonName = (int)$insurerId . '_' . $deptSlug . '.json'; + $jsonPath = $jsonDir . $jsonName; + + $jsonData = json_encode($rulesArray, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); + if ($jsonData === false) { + $this->myLogger->logme('error', 'RuleImportController::upload - json_encode failed for rules', [ + 'last_error' => json_last_error_msg() + ]); + // mark as failed since we cannot save rules + $this->commissionFilesModel->update($insertId, [ + 'file_status' => 'failed', + 'updated_by' => (int)$createdBy, + 'updated_at' => date('Y-m-d H:i:s'), + ]); + return $this->respond([ + 'status' => false, + 'code' => 404, + 'message' => 'Failed to encode rules as JSON.' + ], 200); + } + + // handle existing JSON file based on $override (bool) + if (file_exists($jsonPath)) { + if ($overwrite) { + // 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 { + // append: merge existing JSON with new JSON data + $existingRaw = @file_get_contents($jsonPath); + if ($existingRaw === false) { + $this->myLogger->logme('warning', 'RuleImportController::upload - Could not read existing JSON, will replace with new data', ['json_path' => $jsonPath]); + $finalJson = $jsonData; + } else { + $existingDecoded = json_decode($existingRaw, true); + $newDecoded = json_decode($jsonData, true); + + // if decoding fails, treat as empty array/object and log + if (json_last_error() !== JSON_ERROR_NONE && !is_array($existingDecoded) && !is_object($existingDecoded)) { + $this->myLogger->logme('warning', 'RuleImportController::upload - Existing JSON decode failed; replacing with new data', ['json_path' => $jsonPath, 'json_error' => json_last_error_msg()]); + $finalJson = $jsonData; + } else { + // normalize to PHP arrays for easy merging + if (!is_array($existingDecoded)) { + $existingDecoded = [$existingDecoded]; + } + if (!is_array($newDecoded)) { + $newDecoded = [$newDecoded]; + } + + // merge arrays (preserves numeric keys by reindexing) + $merged = array_merge($existingDecoded, $newDecoded); + $this->myLogger->logme('error', 'RuleImportController::JSON MERGED'); + $finalJson = json_encode($merged, JSON_PRETTY_PRINT); + if ($finalJson === false) { + $this->myLogger->logme('error', 'RuleImportController::upload - Failed to encode merged JSON', ['json_path' => $jsonPath, 'merge_count' => count($merged)]); + $this->commissionFilesModel->update($insertId, [ + 'file_status' => 'failed', + 'updated_by' => (int)$createdBy, + 'updated_at' => date('Y-m-d H:i:s'), + ]); + return $this->respond([ + 'status' => false, + 'code' => 500, + 'message' => 'Failed to encode merged rules JSON.' + ], 500); + } + } + } + } + } else { + // file doesn't exist, just write new data + $finalJson = $jsonData; + } + + // write final JSON to disk with exclusive lock + if (file_put_contents($jsonPath, $finalJson, LOCK_EX) === false) { + $this->myLogger->logme('error', 'RuleImportController::upload - Failed to write rules JSON file', ['json_path' => $jsonPath]); + $this->commissionFilesModel->update($insertId, [ + 'file_status' => 'failed', + 'updated_by' => (int)$createdBy, + 'updated_at' => date('Y-m-d H:i:s'), + ]); + return $this->respond([ + 'status' => false, + 'code' => 404, + 'message' => 'Failed to store rules JSON file.' + ], 500); + } + + // success continues... + $this->myLogger->logme('info', 'RuleImportController::upload - Rules JSON file written', ['json_path' => $jsonPath, 'overwrite' => (bool)$overwrite]); + + + $this->myLogger->logme('info', 'RuleImportController::upload - Rules JSON written', [ + 'file_id' => $insertId, + 'json_path' => $jsonPath, + 'rules_cnt' => $rulesCount, + ]); + + // Update DB: status, rules_count, updated_by + $this->commissionFilesModel->update($insertId, [ + 'file_status' => 'success', + 'rules_count' => $rulesCount, + 'updated_by' => (int)$createdBy, + 'updated_at' => date('Y-m-d H:i:s'), + // If you have a column for JSON path, uncomment: + // 'json_file_path' => $jsonPath, + ]); + + return $this->respond([ + 'status' => true, + 'code' => 200, + 'message' => 'File processed successfully.', + 'file_id' => $insertId, + 'rules_count' => $rulesCount, + 'json_file' => $jsonPath, + 'service' => $result, // optional: return full service response if you want + ], 200); + } + + // --------------------------------------------------------- + // 7. Handle ERROR (validation failed etc.) + // - Do NOT save any rules JSON + // - Update file_status to validation_failed + // - Store annotated_file path if you have such a column + // --------------------------------------------------------- + if ($result['status'] === 'error') { + $annotatedPath = $result['annotated_file'] ?? null; + $errors = $result['errors'] ?? []; + + $updateData = [ + 'file_status' => 'failed', + 'rules_count' => 0, // do not save rules + 'updated_by' => (int)$createdBy, + 'updated_at' => date('Y-m-d H:i:s'), + ]; + + // If you have a column for annotated file path, e.g. annotated_file_path + if ($annotatedPath) { + $updateData['annotated_file_path'] = $annotatedPath; + } + + $this->commissionFilesModel->update($insertId, $updateData); + + $this->myLogger->logme('error', "RuleImportController::upload - Validation failed for file_id={$insertId}", [ + 'errors' => $errors, + 'annotated_file' => $annotatedPath + ]); + + return $this->respond([ + 'status' => false, + 'code' => 404, + 'message' => 'Validation failed. No rules saved.', + 'file_id' => $insertId, + 'errors' => $errors, + 'annotated_file' => $annotatedPath, + ], 422); + } + + // --------------------------------------------------------- + // 8. Unexpected status + // --------------------------------------------------------- + $this->myLogger->logme('error', 'RuleImportController::upload - Unexpected result status from service', ['result' => $result]); + $this->commissionFilesModel->update($insertId, [ + 'file_status' => 'failed', + 'updated_by' => (int)$createdBy, + 'updated_at' => date('Y-m-d H:i:s'), + ]); + + return $this->respond([ + 'status' => false, + 'code' => 404, + 'message' => $result['message'] + ], 200); + } catch (\Throwable $ex) { + $this->myLogger->logme('error', 'RuleImportController::upload exception: ' . $ex->getMessage(), [ + 'trace' => $ex->getTraceAsString() + ]); + + // Try to update the commission_files record if insertId exists + if (isset($insertId) && !empty($insertId)) { + try { + $this->commissionFilesModel->update($insertId, [ + 'file_status' => 'failed', + 'updated_by' => get_session_userid(), + 'updated_at' => date('Y-m-d H:i:s'), + 'notes' => 'Upload exception: ' . $ex->getMessage(), + ]); + } catch (\Throwable $e2) { + $this->myLogger->logme('error', 'RuleImportController::upload - failed to update commission_files after exception: ' . $e2->getMessage()); + } + } + + return $this->respond([ + 'status' => false, + 'code' => 500, + 'message' => $ex->getMessage(), + ], 500); + } + } + + public function downloadSampleCommissionFileUploadExcel() + { + + $filePath = ROOTPATH . 'public/sample_excel/sample_commission.csv'; + // 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 { + // File not found, show an error message or redirect + echo view('errors/html/production'); + } + } + + public function downloadErrorFile() + { + $file_id = $this->request->getGet('file_id'); + + $file_data = $this->commissionFilesModel->where('id', $file_id)->where('is_active', 1)->first(); + + $filePath = WRITEPATH . 'uploads/commission/files/annotated_' . $file_data['file_name']; + + // 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 { + // File not found, show an error message or redirect + $data['message'] = 'The Physical File Not Found'; + echo view('errors/404', $data); + } + } + + public function deleteCommissionData($id) + { + + $return = $this->updateCommissionRules($id); + // dd($return); + + if($return['status'] == true){ + $this->commissionFilesModel->where('id', $id)->set(['is_active' => 0])->update(); + return $this->respond(['status' => true, 'code' => 200, 'message' => "File removed successfully"], 200); + }else{ + return $this->respond(['status' => false, 'code' => 400, 'message' => "Failed to remove file"], 200); + } + } + + public function updateCommissionRules($id, $post_data = null) + { + // 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 ['status' => false, 'message' => 'Commission record not found']; + } + + // 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 ['status' => false, 'message' => 'Rule file not found']; + } + + // 4. Read JSON + $json = file_get_contents($filePath); + $rules = json_decode($json, true); + // print_rr($rules); die; + + if (!is_array($rules)) { + $this->myLogger->logme("error", "Invalid JSON structure in file: $filePath"); + return ['status' => false, 'message' => 'Invalid rule file']; + } + + // 5. Mark matching rule as deleted + $ruleFound = false; + $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; + } + } + + if (!$ruleFound) { + $this->myLogger->logme("error", "No rule found with file_id: $id in file: $filePath"); + return ['status' => false, 'message' => 'Rule not found in file']; + } + + // 6. Always save file back (No unlink) + file_put_contents($filePath, json_encode($rules, JSON_PRETTY_PRINT)); + + $this->myLogger->logme("error", $log_message); + + return [ + 'status' => true, + 'message' => $log_message + ]; + } + + public function removeCommissionRules($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 ['status' => false, 'message' => 'Commission record not found']; + } + + // 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); // OCT2025 + + // 3. Build file name & 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 ['status' => false, 'message' => 'Rule file not found']; + } + + // 4. Read file + $json = file_get_contents($filePath); + $rules = json_decode($json, true); + // dd($rules); + + if (!is_array($rules)) { + $this->myLogger->logme("error","Invalid JSON structure in file: $filePath"); + return ['status' => false, 'message' => 'Invalid rule file']; + } + + // 5. Remove rule where file_id == commission_data id + $updatedRules = array_filter($rules, function ($rule) use ($id) { + return isset($rule['file_id']) && $rule['file_id'] != $id; + }); + + $updatedRules = array_values($updatedRules); + + // 6. If empty → delete file + if (empty($updatedRules)) { + unlink($filePath); + + $this->myLogger->logme("error","Rule removed. File deleted because no rules left: $filePath"); + + return [ + 'status' => true, + 'message' => 'Rule deleted and file removed (no rules left)' + ]; + } + + // 7. Write updated JSON + file_put_contents($filePath, json_encode($updatedRules, JSON_PRETTY_PRINT)); + + $this->myLogger->logme("error","Rule removed successfully and file updated: $filePath"); + + return [ + 'status' => true, + 'message' => 'Rule removed and file updated successfully' + ]; + } + + public function checkSameEntry() + { + $data = $this->request->getGet(); + $commissionMonth = $data['commission_month'] . '-01'; + $data['commission_month'] = change_date_format($commissionMonth, 'Y-M-d', 'Y-m-d'); + + $count = $this->commissionFilesModel->where($data)->where('is_active', 1)->countAllResults(); + if($count > 0){ + return $this->respond(['status' => true, 'code' => 200, 'data' => $count, 'message' => ""], 200); + }else{ + return $this->respond(['status' => false, 'code' => 404, 'data' => $count, 'message' => ""], 200); + } + } + + 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 c8adbcbb..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'); @@ -2011,6 +2042,7 @@ class TicketController extends BaseController { $received_data = $this->request->getPost(); $ticket_type_id = $this->request->getPost('ticket_type_id') ?? null; + $client_id = $this->request->getPost('client_id') ?? null; $emp_id = $received_data['emp_id']; // Get all client policy IDs for the given employee @@ -2027,6 +2059,9 @@ class TicketController extends BaseController $builder->where('e.is_active', 1); $builder->where('ep.is_active', 1); $builder->where('e.emp_code', $self_data['emp_code']); + if(!empty($client_id)){ + $builder->where('e.client_id', $client_id); + } $builder->groupBy('client_policy_id'); $query = $builder->get(); @@ -2064,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/Filters/CommissionApiFilter.php b/app/Filters/CommissionApiFilter.php new file mode 100644 index 00000000..d7ae956e --- /dev/null +++ b/app/Filters/CommissionApiFilter.php @@ -0,0 +1,55 @@ +getHeaderLine('X'); + $authHeader = $_SERVER['REDIRECT_HTTP_AUTHORIZATION']; + // echo $authHeader;die(); + if (empty($authHeader)) { + return service('response')->setJSON([ + 'success' => false, + 'error' => 'Authorization header missing' + ])->setStatusCode(403); + } + + // Expected format: Bearer YOUR_API_KEY + if (stripos($authHeader, 'Bearer ') !== 0) { + return service('response')->setJSON([ + 'success' => false, + 'error' => 'Invalid Authorization format. Expected: Bearer ' + ])->setStatusCode(403); + } + + $apiKey = trim(substr($authHeader, 7)); // extract token after 'Bearer ' + + $envKeys = getenv('ALLOWED_COMMISSION_API_KEYS'); + // Convert CSV -> Array + $allowedKeys = array_map('trim', explode(',', $envKeys)); + // print_r($allowedKeys);die(); + // Validate + if (!in_array($apiKey, $allowedKeys, true)) { + return service('response')->setJSON([ + 'success' => false, + 'error' => 'Invalid API Key' + ])->setStatusCode(403); + } + + // Allow request to proceed + return null; + } + + public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) + { + // Not needed + } +} 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 4329388d..f3e97d0c 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) { @@ -464,8 +458,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 +947,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 +1013,15 @@ 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; + } + return $result; } } } - if (!function_exists('premium_calculation_manager')) { function premium_calculation_manager($emp_data, $policy_terms, $slab_details, $default_si = null) { @@ -1435,6 +1429,432 @@ if (!function_exists('premium_calculation_manager')) { } } +if (!function_exists('premium_calculation_manager_new')) { + function premium_calculation_manager_new($emp_data, $policy_terms, $slab_details, $default_si = null) + { + // dd($emp_data,$policy_terms,$slab_details,$default_si); + + $myLogger = \Config\Services::mylogger(); + // grid type + // 1 = premium => si + // Kint::dump($emp_data); + + //check if the data comes from enrollment (DB) and status is draft then fetch original data of employee from + //audit history table then initiate calculation with it. so this data again get updated in emp table + + //check emp records + if ($emp_data['file_id'] == null && $emp_data['temp']['emp_status'] == 'draft' && $emp_data['temp']['policy_status'] == 'draft') { + // $original_emp_records = get_emp_records_from_audit_history($emp_data['temp']['emp_id']); + // if(is_array($original_emp_records)) + // { + // // Kint::dump($original_emp_records); + // // $emp_data = replace_original_data(original_data:$original_emp_records,current_data:$emp_data); + // // Kint::dump($value); + // } + } + + //check emp policy records + if ($emp_data['file_id'] == null && $emp_data['temp']['emp_status'] == 'draft' && $emp_data['temp']['policy_status'] == 'draft') { + // $original_emp_policy_records = get_emp_policy_records_from_audit_history($emp_data['temp']['emp_policy_id']); + // if(is_array($original_emp_policy_records)) + // { + // // Kint::dump($original_emp_records); + // $emp_data['policy_details'] = replace_original_data(original_data:$original_emp_policy_records,current_data:$emp_data['policy_details']); + // // Kint::dump($policy_data); + // } + + } //end of fetching data from audit history table + + //gird and calculation start + $slug = \Config\Services::slug(); + $grid_type = $emp_data['temp']['grid_id']; + $slab_index = isset($emp_data['temp']['grid_name']) ? $emp_data['temp']['grid_name'] : false; + // echo $emp_data['name']; + // kint::dump($slab_index); + if ($slab_index === false) { + // echo 'not set'; + return false; + } + $temp_slab_rates = $slab_details[$slab_index]['slab_rates']; + + //if curent action is dependent addition OR addition then pull insurer master to set whether add one day from employee date of coverage + if ($emp_data['temp']['action'] == 'DA' || $emp_data['temp']['action'] == 'A') { + $insurer = new InsurerModel(); + $insurer = ($insurer->find($policy_terms['insurer_id'])); + if (isset($insurer['addition_add_day']) && $insurer['addition_add_day'] == true) { + // $emp_data['policy_details']['date_coverage'] = (new DateTime($emp_data['policy_details']['date_coverage']))->modify('+1 day')->format('Y-m-d'); + + $emp_data['policy_details']['date_coverage'] = isset($emp_data['policy_details']['date_coverage']) && $emp_data['policy_details']['date_coverage'] != '' && $emp_data['policy_details']['date_coverage'] != null ? + (new DateTime($emp_data['policy_details']['date_coverage']))->modify('+1 day')->format('Y-m-d') : null; + } + } + // dd($emp_data); + $is_match_found = false; + $gst = isset($policy_terms['gst']) && $policy_terms['gst'] != 0 ? $policy_terms['gst'] : 18; + switch ($grid_type) { + case "1": + //GPA - Sum Insured (SI) * Multiplier + $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; + $employee_received_band = $emp_data['temp']['band']; + foreach ($temp_slab_rates as $skey => $slab_value) { + if (($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit']) || ($slab_value['grade'] != null && $slab_value['grade'] == $employee_received_band && $slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'])) { + $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; + $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date']; + $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1); + $emp_data['policy_details']['premium'] = $slab_value['premium']; + $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1)); + $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', ''); + $is_match_found = true; + break; + } + } + //auto calculate of SI and premium for basic pay type + if (!$is_match_found) { + if ($temp_slab_rates[0]['si_or_bp'] == 2) { + $temp_si = $emp_data['basic_pay'] * $temp_slab_rates[0]['basic_multiplier']; + $temp_premium = ($temp_si * $temp_slab_rates[0]['multiplier']) / 1000; + + $emp_data['policy_details']['basic_cover_si'] = $temp_si; + $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date']; + $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1); + $emp_data['policy_details']['premium'] = $temp_premium; + $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1)); + $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', ''); + $is_match_found = true; + + $log_message = 'Pre defined SI not found. auto calc SI & premium for -' . $emp_data['emp_code'] . ' - ' . $emp_data['name'] . ' - ' . $temp_si . ' - ' . $temp_premium; + $myLogger->logme('error', $log_message); + } + } + break; + case "2": + //GPA - Flat Rate for all SI + $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; + foreach ($temp_slab_rates as $skey => $slab_value) { + if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit']) { + $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; + $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date']; + $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1); + $emp_data['policy_details']['premium'] = $slab_value['premium']; + $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1)); + $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', ''); + $is_match_found = true; + break; + } + } + break; + case "3": + //GMC - SI + $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; + foreach ($temp_slab_rates as $skey => $slab_value) { + if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit']) { + $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; + $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date']; + $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1); + $emp_data['policy_details']['premium'] = $slab_value['premium']; + $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1)); + $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', ''); + $is_match_found = true; + break; + } + } + + break; + case "4": + + //GMC - Employees Age band + $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; + // dd($employee_received_si); + $temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $age = calculate_days_bw_dates(from_date: $emp_data['dob'], to_date: $temp_date)->y; + + foreach ($temp_slab_rates as $skey => $slab_value) { + + if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age)) { + // dd($slab_value); + $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; + $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date']; + $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1); + $emp_data['policy_details']['premium'] = $slab_value['premium']; + $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1)); + $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', ''); + $emp_data['policy_details']['age_band'] = $slab_value['age_from'] . '-' . $slab_value['age_to']; + $is_match_found = true; + break; + } + } + break; + case "5": + //GMC - Employees Age + SI + $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; + $temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $age = calculate_days_bw_dates(from_date: $emp_data['dob'], to_date: $temp_date)->y; + // kint::dump($age); + foreach ($temp_slab_rates as $skey => $slab_value) { + // dd($slab_value); + if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age)) { + $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; + $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date']; + $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1); + $emp_data['policy_details']['premium'] = $slab_value['premium']; + $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1)); + $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', ''); + $emp_data['policy_details']['age_band'] = $slab_value['age_from'] . '-' . $slab_value['age_to']; + $is_match_found = true; + break; + } + } + break; + case "6": + //GMC - Employees + Dependent Age band + $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; + $temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $age = calculate_days_bw_dates(from_date: $emp_data['dob'], to_date: $temp_date)->y; + foreach ($temp_slab_rates as $skey => $slab_value) { + + if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age)) { + // echo $emp_data['name']; die; + $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; + $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date']; + $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1); + $emp_data['policy_details']['premium'] = $slab_value['premium']; + $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1)); + $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', ''); + $emp_data['policy_details']['age_band'] = $slab_value['age_from'] . '-' . $slab_value['age_to']; + $is_match_found = true; + break; + } + } + break; + case "7": + //GMC - Employees + Dependent Age + SI + $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; + $temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $age = calculate_days_bw_dates(from_date: $emp_data['dob'], to_date: $temp_date)->y; + foreach ($temp_slab_rates as $skey => $slab_value) { + + if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age)) { + $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; + $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date']; + $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1); + $emp_data['policy_details']['premium'] = $slab_value['premium']; + $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1)); + $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', ''); + $emp_data['policy_details']['age_band'] = $slab_value['age_from'] . '-' . $slab_value['age_to']; + + $is_match_found = true; + break; + } + } + break; + case "8": + //GMC - SI as per Grade or Band + $employee_received_band = $emp_data['temp']['band']; + $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; + foreach ($temp_slab_rates as $skey => $slab_value) { + + if ($slab_value['grade'] == $employee_received_band && $slab_value['unit'] == $emp_data['unit'] && $slab_value['si'] == $employee_received_si) { + // $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; + $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; + $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date']; + $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1); + $emp_data['policy_details']['premium'] = $slab_value['premium']; + $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1)); + $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', ''); + $is_match_found = true; + break; + } + } + break; + case "9": + //GMC - Flat Rate for all + $employee_received_band = $emp_data['temp']['band']; + $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; + foreach ($temp_slab_rates as $skey => $slab_value) { + + if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit']) { + $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; + $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date']; + $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1); + $emp_data['policy_details']['premium'] = $slab_value['premium']; + $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1)); + $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', ''); + $is_match_found = true; + break; + } + } + break; + case "10": + //GMC - Maximum age of Dependents + $max_age = $emp_data['temp']['max_age']; + $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; + // echo $emp_data['name'].'-'.$employee_received_si.'
'; + // echo $emp_data['temp']['grid_type'].'
'; + $emp_data['policy_details']['basic_cover_si'] = null; + foreach ($temp_slab_rates as $skey => $slab_value) { + // echo $slab_value['si'].'-'.$slab_value['age_from'].'-'.$slab_value['age_to'].'-'.$max_age.'
'; + if ( + $slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $max_age && $slab_value['age_to'] >= $max_age) + ) { + $emp_data['policy_details']['basic_cover_si'] = $employee_received_si; + $emp_data['policy_details']['date_coverage'] = isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']; + $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date']; + $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1); + $emp_data['policy_details']['premium'] = $slab_value['premium']; + $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1)); + $emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '')); + $emp_data['policy_details']['age_band'] = $slab_value['age_from'] . '-' . $slab_value['age_to']; + + $is_match_found = true; + break; + } + } + break; + case "11": + //GMC - Maximum count per Family + $max_count = $emp_data['temp']['max_count']; + $employee_received_band = $emp_data['band']; + // echo $employee_received_band; + $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; + $emp_data['policy_details']['basic_cover_si'] = null; + foreach ($temp_slab_rates as $skey => $slab_value) { + + if ($slab_value['si'] == $employee_received_si && $slab_value['grade'] == $employee_received_band && $slab_value['unit'] == $emp_data['unit']) { + //calculate premium based on count + // echo $emp_data['name']; + $familiy_si_covered = $employee_received_si * $max_count; + $familiy_si_covered = ($familiy_si_covered >= $slab_value['max_si'] ? $slab_value['max_si'] : $familiy_si_covered); + + $emp_data['policy_details']['basic_cover_si'] = $familiy_si_covered; + $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date']; + $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1); + $emp_data['policy_details']['premium'] = get_premium_for_si(slab_details: $temp_slab_rates, si_amount: $familiy_si_covered, band: $employee_received_band, unit: $emp_data['unit']); + $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1)); + $emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '')); + $is_match_found = true; + break; + } + } + break; + + case "12": + //GMC - Employee + relationship + + $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; + $employee_relationship = $slug->slugify($emp_data['relationship']); + $employee_relationship = ($employee_relationship == 'daughter' || $employee_relationship == 'son' ? $employee_relationship = 'child' : $employee_relationship); + $emp_data['policy_details']['basic_cover_si'] = null; + foreach ($temp_slab_rates as $skey => $slab_value) { + if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && $slab_value['relationship'] == $employee_relationship) { + + $emp_data['policy_details']['basic_cover_si'] = $employee_received_si; + $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date']; + $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1); + $emp_data['policy_details']['premium'] = $slab_value['premium']; + $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1)); + $emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '')); + $is_match_found = true; + break; + } + } + break; + + case "13": + //GMC - Employee + relationship + age + $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; + $employee_relationship = $slug->slugify($emp_data['relationship']); + $employee_relationship = ($employee_relationship == 'daughter' || $employee_relationship == 'son' ? $employee_relationship = 'child' : $employee_relationship); + $emp_data['policy_details']['basic_cover_si'] = null; + $temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $age = calculate_days_bw_dates(from_date: $emp_data['dob'], to_date: $temp_date)->y; + foreach ($temp_slab_rates as $skey => $slab_value) { + if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && $slab_value['relationship'] == $employee_relationship) { + + $emp_data['policy_details']['basic_cover_si'] = $employee_received_si; + $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date']; + $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1); + $emp_data['policy_details']['premium'] = $slab_value['premium']; + $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days); + $emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '')); + $emp_data['policy_details']['age_band'] = $slab_value['age_from'] . '-' . $slab_value['age_to']; + $is_match_found = true; + break; + } + } + break; + + + + default: + $myLogger->logme('error', ($emp_data['emp_code'] . '-' . $emp_data['name'] . ' - grid type not found')); + } + + //this if condition for premium calculated & premium type 3 (familiy floater but premium calculated every individual implemented later) then remove si amount only for dependents (not self) + if ($is_match_found && strtolower($emp_data['relationship']) != 'self' && $temp_slab_rates[0]['premium_type'] == 3 && $policy_terms['is_addon'] != 3) { + //set dependent si to 0 + $emp_data['policy_details']['basic_cover_si'] = 0; + } + if (!$is_match_found) { + $temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $age = calculate_days_bw_dates(from_date: $emp_data['dob'], to_date: $temp_date)->y; + $log_message = '[ client_policy_id : ' . $emp_data['policy_details']['client_policy_id'] . ' - ' . $emp_data['emp_code'] . ' - ' . $emp_data['name'] . ' - ' . $emp_data['policy_details']['basic_cover_si'] . ', Age : ' . $age . ' ]'; + if ($temp_slab_rates[0]['premium_type'] == 1) { + $log_message .= ' - skipping, calculating only self..!'; + //reset emp si and others policy level data if premium only for self + // $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date']; + $emp_data['policy_details']['basic_cover_si'] = 0; + $emp_data['policy_details']['premium'] = 0; + $emp_data['policy_details']['rata_premimum'] = 0; + $emp_data['policy_details']['gst'] = 0; + $emp_data['policy_details']['days'] = 0; + $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date']; + } else { + $log_message .= '- skipping, slab rate not found'; + } + $myLogger->logme('error', $log_message); + // echo $log_message; + + } + // if the family floater case first self add first the process completed, after spouse or any dependent add the rata premium not added this change will handle this + if (strtolower($emp_data['relationship']) != 'self' && $temp_slab_rates[0]['premium_type'] == 1 && $emp_data['temp']['action'] == 'DA') { + //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; + $emp_data['policy_details']['premium'] = 0; + $emp_data['policy_details']['rata_premimum'] = 0; + $emp_data['policy_details']['gst'] = 0; + $emp_data['policy_details']['days'] = 0; + $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date']; + } + + return $emp_data; + } +} if (!function_exists('calculate_pro_rata_premimum')) { function calculate_pro_rata_premimum($premium, $employee_policy_coverage_days, $policy_coverage_days) @@ -1558,7 +1978,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) { @@ -1630,7 +2049,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) { @@ -1760,7 +2178,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) { @@ -1996,7 +2413,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) { @@ -2456,3 +2872,36 @@ if (!function_exists('is_valid_or_empty_email')) { } } +if (!function_exists('validatet_family_floter_rata_premium')) { + function validatet_family_floter_rata_premium($family){ + + if (count($family) === 2) { + return $family; // skip if only two members + } + + $dependentRataGiven = false; + + foreach ($family as &$row) { + + // Skip if the member is self + if (strtolower($row['relationship']) == 'self') { + continue; + } + + // For dependents + if (isset($row['temp']['premium_type']) && $row['temp']['premium_type'] == 1) { + + if (!$dependentRataGiven) { + // First eligible dependent keeps premium + $dependentRataGiven = true; + } else { + $row['policy_details']['rata_premimum'] = 0; + $row['policy_details']['gst'] = 0; + } + + } + } + + return $family; + } +} diff --git a/app/Libraries/RuleImportService.php b/app/Libraries/RuleImportService.php new file mode 100644 index 00000000..33fdab3d --- /dev/null +++ b/app/Libraries/RuleImportService.php @@ -0,0 +1,1394 @@ +initializeExpectedColumns(); + $this->initializeValidators(); + $this->setupAnnotatedDirectory(); + } + + /** + * Initialize expected column headers + */ + private function initializeExpectedColumns(): void + { + $this->expectedColumns = [ + self::COL_RULE_NAME, + self::COL_POLICY_BUSINESS_TYPE, + self::COL_POLICY_NAME, + self::COL_PREMIUM_TYPE, + self::COL_VEHICLE_TYPE, + self::COL_VEHICLE_SUB_TYPE, + self::COL_MAKE, + self::COL_MODEL, + self::COL_CC_MIN, + self::COL_CC_MAX, + self::COL_FUEL_TYPE, + self::COL_VEHICLE_AGE_MIN, + self::COL_VEHICLE_AGE_MAX, + self::COL_VEHICLE_WEIGHT_MIN, + self::COL_VEHICLE_WEIGHT_MAX, + self::COL_RTO_STATE, + self::COL_RTO_CITY, + self::COL_RENEWAL_TYPE, + self::COL_RENEWAL_SUB_TYPE, + self::COL_COMMISSION_TYPE, + self::COL_COMMISSION_VALUE, + self::COL_COMMISSION_PARAMS, + self::COL_NOTES + ]; + } + + /** + * Initialize column validators + */ + private function initializeValidators(): void + { + $this->columnValidators = [ + self::COL_CC_MIN => 'validateNumeric', + self::COL_CC_MAX => 'validateNumeric', + self::COL_VEHICLE_AGE_MIN => 'validateNumeric', + self::COL_VEHICLE_AGE_MAX => 'validateNumeric', + self::COL_VEHICLE_WEIGHT_MIN => 'validateNumeric', + self::COL_VEHICLE_WEIGHT_MAX => 'validateNumeric', + self::COL_FUEL_TYPE => 'validateCommaList', + self::COL_COMMISSION_TYPE => 'validateCommissionType', + self::COL_COMMISSION_VALUE => 'validateNumeric', + self::COL_COMMISSION_PARAMS => 'validateCompositeParams', + ]; + } + + /** + * Setup annotated directory for error files + */ + private function setupAnnotatedDirectory(): void + { + $this->annotatedDir = WRITEPATH . 'uploads/commission/files/'; + if (!is_dir($this->annotatedDir)) { + mkdir($this->annotatedDir, 0755, true); + } + } + + /** + * Process uploaded file + * + * @param string $tempFilePath Temporary file path + * @param string $originalName Original filename + * @return array Processing result + */ + public function processUpload(array $params): array + { + // dd($params); + $startTime = microtime(true); + $this->incomingData = $params; + try { + $this->department = $params['department']; + $this->uploadedCommissionFileID = $params['id']; + $tempFilePath = WRITEPATH.'uploads/commission/files/'.$params['file_name']; + $originalName = $params['file_name']; + // Validate file extension + $extension = $this->getFileExtension($params['file_name']); + $this->validateFileExtension($extension); + + // Load spreadsheet + $spreadsheet = $this->loadSpreadsheet($tempFilePath, $extension); + $sheet = $spreadsheet->getActiveSheet(); + + // Extract and validate headers + $headerMap = $this->extractHeaders($sheet); + $this->validateHeaders($headerMap); + // dd($headerMap); + + // Process rows + $this->validationResult = new ValidationResult(); + $rules = $this->processRows($sheet, $headerMap); + + // Generate annotated file if errors exist + $annotatedPath = null; + if ($this->validationResult->hasErrors()) { + $annotatedPath = $this->createAnnotatedFile( + $spreadsheet, + $headerMap, + $this->validationResult->getErrors(), + $originalName + ); + } + + $duration = round(microtime(true) - $startTime, 2); + + return $this->buildSuccessResponse($rules, $annotatedPath, $duration); + + } catch (Exception $e) { + log_message('error', "RuleImportService failed: " . $e->getMessage()); + return $this->buildErrorResponse($e); + } + } + + /** + * Get file extension + */ + private function getFileExtension(string $filename): string + { + return strtolower(pathinfo($filename, PATHINFO_EXTENSION)); + } + + /** + * Validate file extension + */ + private function validateFileExtension(string $extension): void + { + if (!in_array($extension, self::SUPPORTED_EXTENSIONS, true)) { + throw new RuntimeException( + "Unsupported file type: {$extension}. " . + "Supported types: " . implode(', ', self::SUPPORTED_EXTENSIONS) + ); + } + } + + /** + * Load spreadsheet based on file type + */ + private function loadSpreadsheet(string $filePath, string $extension): Spreadsheet + { + if ($extension === 'csv') { + $reader = IOFactory::createReader('Csv'); + $reader->setDelimiter(','); + $reader->setEnclosure('"'); + return $reader->load($filePath); + } + + return IOFactory::load($filePath); + } + + /** + * Extract header row and create column mapping + */ + private function extractHeaders($sheet): array + { + $highestCol = $sheet->getHighestColumn(); + $headerRowData = $sheet->rangeToArray("A1:{$highestCol}1", null, true, true, true); + $headerRow = array_values($headerRowData[1]); + + $headerMap = []; + foreach ($headerRow as $index => $header) { + $label = trim((string)$header); + if ($label !== '') { + $headerMap[$label] = $index + 1; + } + } + + return $headerMap; + } + + /** + * Validate all required headers are present + */ + private function validateHeaders(array $headerMap): void + { + $missingColumns = array_diff($this->expectedColumns, array_keys($headerMap)); + + if (!empty($missingColumns)) { + throw new RuntimeException( + "Missing required columns: " . implode(', ', $missingColumns) + ); + } + } + + /** + * Process all data rows + */ + private function processRows($sheet, array $headerMap): array + { + $rules = []; + $highestRow = $sheet->getHighestRow(); + + for ($rowNum = 2; $rowNum <= $highestRow; $rowNum++) { + $rowData = $this->extractRowData($sheet, $headerMap, $rowNum); + + // Skip empty rows + if ($this->isEmptyRow($rowData)) { + continue; + } + + // Validate row + $this->validateRow($rowData, $rowNum); + + // Convert to rule if no errors + if (!$this->validationResult->hasRowErrors($rowNum)) { + $rules[] = $this->convertRowToRule($rowData); + } + } + + return $rules; + } + + /** + * Extract data from a single row + // */ + // private function extractRowData($sheet, array $headerMap, int $rowNum): array + // { + // $rowData = []; + // foreach ($headerMap as $colName => $colIndex) { + // $cell = $sheet->getCellByColumnAndRow($colIndex, $rowNum); + // $rowData[$colName] = trim((string)$cell->getValue()); + // } + // return $rowData; + // } + + + /** + * Extract data from a single row + * + * @param \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $sheet + * @param array $headerMap Column name => column index mapping + * @param int $rowNum Row number to extract + * @return array Associative array of column name => value + */ + private function extractRowData($sheet, array $headerMap, int $rowNum): array + { + $rowData = []; + + foreach ($headerMap as $colName => $colIndex) { + // Convert column index to letter (A, B, C, etc.) + $colLetter = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($colIndex); + + // Get cell value using coordinate (e.g., "A2", "B2") + $cellCoordinate = $colLetter . $rowNum; + $value = $sheet->getCell($cellCoordinate)->getValue(); + + // Handle different data types + if ($value instanceof \PhpOffice\PhpSpreadsheet\RichText\RichText) { + $value = $value->getPlainText(); + } + + $rowData[$colName] = trim((string)$value); + } + + return $rowData; + } + + /** + * Check if row is empty + */ + private function isEmptyRow(array $rowData): bool + { + foreach ($rowData as $value) { + if ($value !== '') { + return false; + } + } + return true; + } + + /** + * Validate a single row + */ + private function validateRow(array $rowData, int $rowNum): void + { + // Field-level validation + foreach ($this->columnValidators as $colName => $validatorMethod) { + $value = $rowData[$colName] ?? ''; + if (!$this->$validatorMethod($value)) { + $errorMessage = $this->buildValidationMessage($value, $colName, $validatorMethod); + $this->validationResult->addError($rowNum, $colName, $errorMessage); + } + } + + // Range validations + $this->validateRangePair($rowData, self::COL_CC_MIN, self::COL_CC_MAX, $rowNum); + $this->validateRangePair($rowData, self::COL_VEHICLE_AGE_MIN, self::COL_VEHICLE_AGE_MAX, $rowNum); + $this->validateRangePair($rowData, self::COL_VEHICLE_WEIGHT_MIN, self::COL_VEHICLE_WEIGHT_MAX, $rowNum); + + // Business rule validations + $this->validateBusinessRules($rowData, $rowNum); + } + + /** + * Validate range pairs (min <= max) + */ + private function validateRangePair( + array $rowData, + string $minCol, + string $maxCol, + int $rowNum + ): void { + $min = $rowData[$minCol] ?? ''; + $max = $rowData[$maxCol] ?? ''; + + if ($min !== '' && $max !== '' && is_numeric($min) && is_numeric($max)) { + if ((float)$min > (float)$max) { + $this->validationResult->addError( + $rowNum, + $minCol, + "{$min} : ERROR - {$minCol} cannot be greater than {$maxCol}" + ); + } + } + } + + /** + * Validate business logic rules + */ + private function validateBusinessRules(array $rowData, int $rowNum): void + { + $commissionType = strtolower($rowData[self::COL_COMMISSION_TYPE] ?? ''); + $commissionValue = $rowData[self::COL_COMMISSION_VALUE] ?? ''; + $commissionParams = $rowData[self::COL_COMMISSION_PARAMS] ?? ''; + + // Composite commission requires params + if ($commissionType === self::COMMISSION_COMPOSITE && empty($commissionParams)) { + $this->validationResult->addError( + $rowNum, + self::COL_COMMISSION_PARAMS, + "Required when commission type is composite" + ); + } + + // Flat commission requires value + if ($commissionType === self::COMMISSION_FLAT && empty($commissionValue)) { + $this->validationResult->addError( + $rowNum, + self::COL_COMMISSION_VALUE, + "Required when commission type is flat" + ); + } + + // Percentage commission requires value + if ($commissionType === self::COMMISSION_PERCENTAGE && empty($commissionValue)) { + $this->validationResult->addError( + $rowNum, + self::COL_COMMISSION_VALUE, + "Required when commission type is percentage" + ); + } + } + + // ==================== VALIDATORS ==================== + + /** + * Validate numeric values + */ + protected function validateNumeric(string $value): bool + { + if ($value === '') { + return true; + } + return filter_var($value, FILTER_VALIDATE_FLOAT) !== false; + } + + /** + * Validate comma-separated list + */ + protected function validateCommaList(string $value): bool + { + if ($value === '') { + return true; + } + return preg_match("/^[a-zA-Z0-9\s,\-]+$/", $value) === 1; + } + + /** + * Validate commission type + */ + protected function validateCommissionType(string $value): bool + { + if (trim($value) === '') { + return false; // Required field + } + return in_array(strtolower(trim($value)), self::COMMISSION_TYPES, true); + } + + /** + * Validate composite parameters (TP:OD:PA format) + */ + protected function validateCompositeParams(string $value): bool + { + if ($value === '') { + return true; + } + + // Format: number:number or number:number:number + if (!preg_match('/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)(?::(\d+(?:\.\d+)?))?$/', $value, $matches)) { + return false; + } + + // Validate percentage ranges (0-100) + $values = array_filter($matches, 'is_numeric'); + foreach ($values as $val) { + if ($val < 0 || $val > 100) { + return false; + } + } + + return true; + } + + /** + * Build validation error message + */ + protected function buildValidationMessage( + string $value, + string $colName, + string $validatorMethod + ): string { + $messages = [ + 'validateNumeric' => 'expecting numeric value only', + 'validateCommaList' => 'expecting comma-separated values', + 'validateCommissionType' => 'expecting one of: ' . implode(', ', self::COMMISSION_TYPES), + 'validateCompositeParams' => 'expecting format TP:OD:PA (e.g., 10:25:0)' + ]; + + $suffix = $messages[$validatorMethod] ?? 'invalid value'; + return empty($value) ? "ERROR - {$suffix}" : "{$value} : ERROR - {$suffix}"; + } + + // ==================== CONVERSION ==================== + + /** + * Convert row data to rule JSON structure + */ + protected function convertRowToRuleV1(array $rowData): array + { + $rule = [ + 'id' => $this->generateRuleId($rowData), + 'name' => $this->sanitize($rowData[self::COL_RULE_NAME] ?? ''), + 'policy_business_type' => $this->sanitize($rowData[self::COL_POLICY_BUSINESS_TYPE] ?? ''), + 'policy_name' => $this->sanitize($rowData[self::COL_POLICY_NAME] ?? ''), + 'premium_type' => $this->sanitize($rowData[self::COL_PREMIUM_TYPE] ?? ''), + 'vehicle' => $this->buildVehicleData($rowData), + 'fuel_type' => $this->parseFuelTypes($rowData[self::COL_FUEL_TYPE] ?? ''), + 'vehicle_age' => $this->buildRangeData( + self::COL_VEHICLE_AGE_MIN, + self::COL_VEHICLE_AGE_MAX, + $rowData + ), + 'vehicle_weight' => $this->buildRangeData( + self::COL_VEHICLE_WEIGHT_MIN, + self::COL_VEHICLE_WEIGHT_MAX, + $rowData + ), + 'rto' => $this->buildRtoData($rowData), + 'renewal_type' => $this->sanitize($rowData[self::COL_RENEWAL_TYPE] ?? ''), + 'commission' => $this->buildCommissionData($rowData), + 'notes' => $this->sanitize($rowData[self::COL_NOTES] ?? '') + ]; + + return $this->removeEmptyValues($rule); + } + + /** + * Generate unique rule ID + */ + private function generateRuleId(array $rowData): string + { + return 'rule_' . substr(md5(json_encode($rowData) . time()), 0, 13); + } + + /** + * Build vehicle data structure + */ + private function buildVehicleData(array $rowData): array + { + return [ + 'type' => $this->sanitize($rowData[self::COL_VEHICLE_TYPE] ?? ''), + 'sub_type' => $this->sanitize($rowData[self::COL_VEHICLE_SUB_TYPE] ?? ''), + 'make' => $this->sanitize($rowData[self::COL_MAKE] ?? ''), + 'model' => $this->sanitize($rowData[self::COL_MODEL] ?? ''), + 'cc' => [ + 'min' => $this->parseFloat($rowData[self::COL_CC_MIN] ?? ''), + 'max' => $this->parseFloat($rowData[self::COL_CC_MAX] ?? '') + ] + ]; + } + + /** + * Build range data (min/max) + */ + private function buildRangeData(string $minCol, string $maxCol, array $rowData): array + { + return [ + 'min' => $this->parseFloat($rowData[$minCol] ?? ''), + 'max' => $this->parseFloat($rowData[$maxCol] ?? '') + ]; + } + + /** + * Build RTO data structure + */ + private function buildRtoData(array $rowData): array + { + return [ + 'state' => $this->sanitize($rowData[self::COL_RTO_STATE] ?? ''), + 'city' => $this->sanitize($rowData[self::COL_RTO_CITY] ?? '') + ]; + } + + /** + * Build commission data structure + */ + private function buildCommissionData(array $rowData): array + { + $commissionType = strtolower($this->sanitize($rowData[self::COL_COMMISSION_TYPE] ?? '')); + + $commission = [ + 'type' => $commissionType, + 'value' => $this->parseFloat($rowData[self::COL_COMMISSION_VALUE] ?? '') + ]; + + if ($commissionType === self::COMMISSION_COMPOSITE) { + $commission['components'] = $this->parseCompositeParams( + $rowData[self::COL_COMMISSION_PARAMS] ?? '' + ); + } + + return $commission; + } + + /** + * Parse composite commission parameters + */ + private function parseCompositeParams(string $params): array + { + if (empty($params)) { + return []; + } + + $parts = explode(':', $params); + $components = []; + $premiumTypes = ['tp_premium', 'od_premium', 'pa_premium']; + + foreach ($premiumTypes as $index => $premiumType) { + if (isset($parts[$index]) && $parts[$index] !== '') { + $percentage = (float)$parts[$index]; + if ($percentage > 0) { + $components[] = [ + 'on' => $premiumType, + 'percentage' => $percentage + ]; + } + } + } + + return $components; + } + + /** + * Parse fuel types from comma-separated string + */ + private function parseFuelTypes(string $fuelTypeString): array + { + if (empty($fuelTypeString)) { + return []; + } + + return array_values(array_filter( + array_map('trim', explode(',', $fuelTypeString)), + fn($value) => $value !== '' + )); + } + + /** + * Sanitize string value + */ + private function sanitize(string $value): string + { + return trim($value); + } + + /** + * Parse float value + */ + private function parseFloat(string $value): ?float + { + if ($value === '' || !is_numeric($value)) { + return null; + } + return (float)$value; + } + + /** + * Remove null and empty values from array recursively + */ + private function removeEmptyValues(array $data): array + { + return array_filter($data, function($value) { + if (is_array($value)) { + $filtered = $this->removeEmptyValues($value); + return !empty($filtered); + } + return $value !== null && $value !== ''; + }); + } + + // ==================== ANNOTATION ==================== + + /** + * Create annotated file with errors + */ + // private function createAnnotatedFile( + // Spreadsheet $spreadsheet, + // array $headerMap, + // array $errors, + // string $originalName + // ): string { + // $sheet = $spreadsheet->getActiveSheet(); + + // // Add error column header + // $lastCol = $sheet->getHighestColumn(); + // $lastColIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($lastCol); + // $errorColIndex = $lastColIndex + 1; + + // $sheet->setCellValueByColumnAndRow($errorColIndex, 1, 'Validation Errors'); + + // // Annotate errors + // foreach ($errors as $rowNum => $columns) { + // $errorMessages = []; + + // foreach ($columns as $colName => $message) { + // $colIndex = $headerMap[$colName]; + // $cell = $sheet->getCellByColumnAndRow($colIndex, $rowNum); + + // // Set error value in original column + // $cell->setValueExplicit( + // $message, + // \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING + // ); + + // $errorMessages[] = "{$colName}: {$message}"; + // } + + // // Set combined error message + // $sheet->setCellValueByColumnAndRow( + // $errorColIndex, + // $rowNum, + // implode(' | ', $errorMessages) + // ); + // } + + // return $this->saveAnnotatedFile($spreadsheet, $originalName); + // } + + /** + * Create annotated file with errors (Enhanced with styling) + */ + private function createAnnotatedFile( + Spreadsheet $spreadsheet, + array $headerMap, + array $errors, + string $originalName + ): string { + $sheet = $spreadsheet->getActiveSheet(); + + // Add error column header + $lastCol = $sheet->getHighestColumn(); + $lastColIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($lastCol); + $errorColIndex = $lastColIndex + 1; + $errorColLetter = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($errorColIndex); + + // Set header for validation errors column + $headerCoordinate = $errorColLetter . '1'; + $sheet->setCellValue($headerCoordinate, 'Validation Errors'); + + // Optional: Style the header + $sheet->getStyle($headerCoordinate)->applyFromArray([ + 'font' => ['bold' => true], + 'fill' => [ + 'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, + 'startColor' => ['rgb' => 'FFD700'] + ] + ]); + + // Annotate errors + foreach ($errors as $rowNum => $columns) { + $errorMessages = []; + + foreach ($columns as $colName => $message) { + if (!isset($headerMap[$colName])) { + continue; // Skip if column not found + } + + $colIndex = $headerMap[$colName]; + $colLetter = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($colIndex); + $cellCoordinate = $colLetter . $rowNum; + + // Set error value in original column + $sheet->setCellValueExplicit( + $cellCoordinate, + $message, + \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING + ); + + // Optional: Highlight error cells in red + $sheet->getStyle($cellCoordinate)->applyFromArray([ + 'fill' => [ + 'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, + 'startColor' => ['rgb' => 'FFB6C1'] // Light red + ], + 'font' => ['color' => ['rgb' => 'FF0000']] // Red text + ]); + + $errorMessages[] = "{$colName}: {$message}"; + } + + // Set combined error message in the validation errors column + $errorCellCoordinate = $errorColLetter . $rowNum; + $sheet->setCellValue($errorCellCoordinate, implode(' | ', $errorMessages)); + + // Optional: Style the summary error cell + $sheet->getStyle($errorCellCoordinate)->applyFromArray([ + 'fill' => [ + 'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, + 'startColor' => ['rgb' => 'FFA500'] // Orange + ] + ]); + } + + // Auto-size the error column for better readability + $sheet->getColumnDimension($errorColLetter)->setAutoSize(true); + + return $this->saveAnnotatedFile($spreadsheet, $originalName); + } + + + + + + /** + * Save annotated spreadsheet + */ + private function saveAnnotatedFile(Spreadsheet $spreadsheet, string $originalName): string + { + $safeName = preg_replace('/[^a-zA-Z0-9_\-\.]/', '_', $originalName); + $extension = $this->getFileExtension($originalName); + $timestamp = time(); + + $filename = "annotated_{$timestamp}_{$safeName}"; + $filename = "annotated_{$safeName}"; + $filepath = $this->annotatedDir . $filename; + + if ($extension === 'csv') { + $writer = IOFactory::createWriter($spreadsheet, 'Csv'); + $writer->setDelimiter(','); + $writer->setEnclosure('"'); + $writer->save($filepath); + } else { + $writer = IOFactory::createWriter($spreadsheet, 'Xlsx'); + if (!str_ends_with($filepath, '.xlsx')) { + $filepath .= '.xlsx'; + } + $writer->save($filepath); + } + + return $filepath; + } + + // ==================== RESPONSE BUILDERS ==================== + + /** + * Build success response + */ + private function buildSuccessResponse( + array $rules, + ?string $annotatedPath, + float $duration + ): array { + $hasErrors = $this->validationResult->hasErrors(); + + return [ + 'status' => $hasErrors ? 'error' : 'success', + 'rules' => $rules, + 'errors' => $hasErrors ? $this->validationResult->getErrors() : [], + 'annotated_file' => $annotatedPath, + 'statistics' => [ + 'total_rules' => count($rules), + 'error_count' => $this->validationResult->getErrorCount(), + 'duration_seconds' => $duration + ] + ]; + } + + /** + * Build error response + */ + private function buildErrorResponse(Exception $e): array + { + return [ + 'status' => 'exception', + 'message' => $e->getMessage(), + 'error_type' => get_class($e) + ]; + } + + + + /** + * Convert row data to rule engine JSON structure + * + * This function transforms Excel row data into a rule engine format with: + * - Conditions: Field-based criteria with operators (==, >=, <=, >, <, in) + * - Calculation: Commission calculation logic (percentage, flat/fixed, composite) + */ + 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' => $temp_rule_id, + 'name' => $this->sanitize($rowData[self::COL_RULE_NAME] ?? ''), + 'department' => $this->department, + 'is_deleted' => false, + 'file_id' => $this->uploadedCommissionFileID, + '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; + } + + /** + * Build conditions array from row data + * Converts Excel columns into rule engine conditions with operators + */ + private function buildConditions(array $rowData): array + { + $conditions = []; + + // Vehicle Type - exact match + if (!empty($rowData[self::COL_VEHICLE_TYPE])) { + $vehicleTypes = $this->parseCommaList($rowData[self::COL_VEHICLE_TYPE]); + + if (count($vehicleTypes) > 1) { + // Multiple values: use 'in' operator + $conditions[] = [ + 'field' => 'vehicle_type', + 'operator' => 'in', + 'value' => $vehicleTypes + ]; + } else { + // Single value: use '==' operator + $conditions[] = [ + 'field' => 'vehicle_type', + 'operator' => '==', + 'value' => $vehicleTypes[0] + ]; + } + } + + // Vehicle Sub Type + if (!empty($rowData[self::COL_VEHICLE_SUB_TYPE])) { + $conditions[] = [ + 'field' => 'vehicle_sub_type', + 'operator' => '==', + 'value' => $this->sanitize($rowData[self::COL_VEHICLE_SUB_TYPE]) + ]; + } + + // Make + if (!empty($rowData[self::COL_MAKE])) { + $makes = $this->parseCommaList($rowData[self::COL_MAKE]); + + if (count($makes) > 1) { + $conditions[] = [ + 'field' => 'make', + 'operator' => 'in', + 'value' => $makes + ]; + } else { + $conditions[] = [ + 'field' => 'make', + 'operator' => '==', + 'value' => $makes[0] + ]; + } + } + + // Model + if (!empty($rowData[self::COL_MODEL])) { + $models = $this->parseCommaList($rowData[self::COL_MODEL]); + + if (count($models) > 1) { + $conditions[] = [ + 'field' => 'model', + 'operator' => 'in', + 'value' => $models + ]; + } else { + $conditions[] = [ + 'field' => 'model', + 'operator' => '==', + 'value' => $models[0] + ]; + } + } + + // CC (Cubic Capacity) - Range handling + $ccMin = $rowData[self::COL_CC_MIN] ?? ''; + $ccMax = $rowData[self::COL_CC_MAX] ?? ''; + + if ($ccMin !== '' && $ccMax !== '') { + if ($ccMin === $ccMax) { + // Exact value + $conditions[] = [ + 'field' => 'cubic_capacity', + 'operator' => '==', + 'value' => (float)$ccMin + ]; + } else { + // Range: min and max + $conditions[] = [ + 'field' => 'cubic_capacity', + 'operator' => '>=', + 'value' => (float)$ccMin + ]; + $conditions[] = [ + 'field' => 'cubic_capacity', + 'operator' => '<=', + 'value' => (float)$ccMax + ]; + } + } elseif ($ccMin !== '') { + // Only minimum specified + $conditions[] = [ + 'field' => 'cubic_capacity', + 'operator' => '>=', + 'value' => (float)$ccMin + ]; + } elseif ($ccMax !== '') { + // Only maximum specified + $conditions[] = [ + 'field' => 'cubic_capacity', + 'operator' => '<=', + 'value' => (float)$ccMax + ]; + } + + // Fuel Type + if (!empty($rowData[self::COL_FUEL_TYPE])) { + $fuelTypes = $this->parseCommaList($rowData[self::COL_FUEL_TYPE]); + + if (count($fuelTypes) > 1) { + $conditions[] = [ + 'field' => 'fuel_type', + 'operator' => 'in', + 'value' => $fuelTypes + ]; + } else { + $conditions[] = [ + 'field' => 'fuel_type', + 'operator' => '==', + 'value' => $fuelTypes[0] + ]; + } + } + + // Vehicle Age - Range handling + $ageMin = $rowData[self::COL_VEHICLE_AGE_MIN] ?? ''; + $ageMax = $rowData[self::COL_VEHICLE_AGE_MAX] ?? ''; + + if ($ageMin !== '' && $ageMax !== '') { + if ($ageMin === $ageMax) { + $conditions[] = [ + 'field' => 'vehicle_age', + 'operator' => '==', + 'value' => (int)$ageMin + ]; + } else { + $conditions[] = [ + 'field' => 'vehicle_age', + 'operator' => '>=', + 'value' => (int)$ageMin + ]; + $conditions[] = [ + 'field' => 'vehicle_age', + 'operator' => '<=', + 'value' => (int)$ageMax + ]; + } + } elseif ($ageMin !== '') { + $conditions[] = [ + 'field' => 'vehicle_age', + 'operator' => '>=', + 'value' => (int)$ageMin + ]; + } elseif ($ageMax !== '') { + $conditions[] = [ + 'field' => 'vehicle_age', + 'operator' => '<=', + 'value' => (int)$ageMax + ]; + } + + // Vehicle Weight - Range handling + $weightMin = $rowData[self::COL_VEHICLE_WEIGHT_MIN] ?? ''; + $weightMax = $rowData[self::COL_VEHICLE_WEIGHT_MAX] ?? ''; + + if ($weightMin !== '' && $weightMax !== '') { + if ($weightMin === $weightMax) { + $conditions[] = [ + 'field' => 'weight', + 'operator' => '==', + 'value' => (float)$weightMin + ]; + } else { + $conditions[] = [ + 'field' => 'weight', + 'operator' => '>=', + 'value' => (float)$weightMin + ]; + $conditions[] = [ + 'field' => 'weight', + 'operator' => '<=', + 'value' => (float)$weightMax + ]; + } + } elseif ($weightMin !== '') { + $conditions[] = [ + 'field' => 'weight', + 'operator' => '>=', + 'value' => (float)$weightMin + ]; + } elseif ($weightMax !== '') { + $conditions[] = [ + 'field' => 'weight', + 'operator' => '<=', + 'value' => (float)$weightMax + ]; + } + + // RTO State + if (!empty($rowData[self::COL_RTO_STATE])) { + $states = $this->parseCommaList($rowData[self::COL_RTO_STATE]); + + if (count($states) > 1) { + $conditions[] = [ + 'field' => 'geo_rto_state', + 'operator' => 'in', + 'value' => $states + ]; + } else { + $conditions[] = [ + 'field' => 'geo_rto_state', + 'operator' => '==', + 'value' => $states[0] + ]; + } + } + + // RTO City + if (!empty($rowData[self::COL_RTO_CITY])) { + $cities = $this->parseCommaList($rowData[self::COL_RTO_CITY]); + + if (count($cities) > 1) { + $conditions[] = [ + 'field' => 'geo_rto_city', + 'operator' => 'in', + 'value' => $cities + ]; + } else { + $conditions[] = [ + 'field' => 'geo_rto_city', + 'operator' => '==', + 'value' => $cities[0] + ]; + } + } + + // Policy Business Type + if (!empty($rowData[self::COL_POLICY_BUSINESS_TYPE])) { + $conditions[] = [ + 'field' => 'policy_business_type', + 'operator' => '==', + 'value' => $this->sanitize($rowData[self::COL_POLICY_BUSINESS_TYPE]) + ]; + } + + // Policy Name + if (!empty($rowData[self::COL_POLICY_NAME])) { + $conditions[] = [ + 'field' => 'product', + 'operator' => '==', + 'value' => $this->sanitize($rowData[self::COL_POLICY_NAME]) + ]; + } + + // Premium Type (could be TP, OD, Comprehensive, etc.) + if (!empty($rowData[self::COL_PREMIUM_TYPE])) { + $premiumTypes = $this->parseCommaList($rowData[self::COL_PREMIUM_TYPE]); + + if (count($premiumTypes) > 1) { + $conditions[] = [ + 'field' => 'policy_type', + 'operator' => 'in', + 'value' => $premiumTypes + ]; + } else { + $conditions[] = [ + 'field' => 'policy_type', + 'operator' => '==', + 'value' => $premiumTypes[0] + ]; + } + } + + // Renewal Type + if (!empty($rowData[self::COL_RENEWAL_TYPE])) { + $renewalTypes = $this->parseCommaList($rowData[self::COL_RENEWAL_TYPE]); + + if (count($renewalTypes) > 1) { + $conditions[] = [ + 'field' => 'renewal_type', + 'operator' => 'in', + 'value' => $renewalTypes + ]; + } else { + $conditions[] = [ + 'field' => 'renewal_type', + 'operator' => '==', + 'value' => $renewalTypes[0] + ]; + } + } + + // Renewal Sub Type + if (!empty($rowData[self::COL_RENEWAL_SUB_TYPE])) { + $conditions[] = [ + 'field' => 'renewal_sub_type', + 'operator' => '==', + 'value' => $this->sanitize($rowData[self::COL_RENEWAL_SUB_TYPE]) + ]; + } + + return $conditions; + } + + /** + * Build calculation object based on commission type + */ + private function buildCalculation(array $rowData): array + { + $commissionType = strtolower(trim($rowData[self::COL_COMMISSION_TYPE] ?? '')); + $commissionValue = $rowData[self::COL_COMMISSION_VALUE] ?? ''; + $commissionParams = $rowData[self::COL_COMMISSION_PARAMS] ?? ''; + + switch ($commissionType) { + case 'composite': + return $this->buildCompositeCalculation($commissionParams); + + case 'percentage': + return $this->buildPercentageCalculation($commissionValue); + + case 'flat': + case 'fixed': + return $this->buildFixedCalculation($commissionValue); + + case 'tiered': + // For future implementation + return [ + 'type' => 'tiered', + 'tiers' => [] // To be implemented based on requirements + ]; + + default: + // Default to percentage if not specified + return $this->buildPercentageCalculation($commissionValue); + } + } + + /** + * Build composite calculation (multiple premium components) + */ + private function buildCompositeCalculation(string $params): array + { + $components = []; + + if (!empty($params)) { + $parts = explode(':', $params); + $premiumTypes = ['tp_premium', 'od_premium', 'pa_premium']; + + foreach ($premiumTypes as $index => $premiumType) { + if (isset($parts[$index]) && trim($parts[$index]) !== '') { + $percentage = (float)$parts[$index]; + if ($percentage > 0) { + $components[] = [ + 'percentage' => $percentage, + 'on' => $premiumType + ]; + } + } + } + } + + return [ + 'type' => 'composite', + 'components' => $components + ]; + } + + /** + * Build percentage calculation (single percentage on total/specific premium) + */ + private function buildPercentageCalculation(string $value): array + { + $percentage = !empty($value) ? (float)$value : 0; + + return [ + 'type' => 'percentage', + 'value' => $percentage, + 'on' => 'premium' // Default to total premium + ]; + } + + /** + * Build fixed/flat calculation (absolute amount) + */ + private function buildFixedCalculation(string $value): array + { + $amount = !empty($value) ? (float)$value : 0; + + return [ + 'type' => 'fixed', + 'value' => $amount, + 'on' => 'premium' // Default to total premium + ]; + } + + /** + * Parse comma-separated list into array + */ + private function parseCommaList(string $value): array + { + if (empty($value)) { + return []; + } + + return array_values(array_filter( + array_map('trim', explode(',', $value)), + fn($item) => $item !== '' + )); + } + +} + +/** + * ValidationResult - Helper class for managing validation errors + */ +class ValidationResult +{ + private array $errors = []; + + public function addError(int $row, string $column, string $message): void + { + $this->errors[$row][$column] = $message; + } + + public function hasErrors(): bool + { + return !empty($this->errors); + } + + public function hasRowErrors(int $row): bool + { + return isset($this->errors[$row]) && !empty($this->errors[$row]); + } + + public function getErrors(): array + { + return $this->errors; + } + + public function getErrorCount(): int + { + return array_sum(array_map('count', $this->errors)); + } + + public function getRowErrors(int $row): array + { + return $this->errors[$row] ?? []; + } +} \ No newline at end of file diff --git a/app/Models/ClientModel.php b/app/Models/ClientModel.php index b84bfae1..2397f4df 100755 --- a/app/Models/ClientModel.php +++ b/app/Models/ClientModel.php @@ -90,7 +90,7 @@ class ClientModel extends Model ->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 185f4a20..14685074 100755 --- a/app/Models/ClientPolicyModel.php +++ b/app/Models/ClientPolicyModel.php @@ -57,6 +57,8 @@ class ClientPolicyModel extends Model "placement_json", "policy_entry_from", "is_from_lead", + "wellness_plan_id", + "wellness_vendor_id", ]; // Callbacks @@ -131,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/CommissionFilesModel.php b/app/Models/CommissionFilesModel.php new file mode 100644 index 00000000..9ddf1e35 --- /dev/null +++ b/app/Models/CommissionFilesModel.php @@ -0,0 +1,101 @@ + 'required|min_length[1]|max_length[100]', + // 'insurer_id' => 'permit_empty|integer', + // 'department' => 'permit_empty|max_length[45]', + // 'commission_month' => 'permit_empty|valid_date', + // 'file_status' => 'permit_empty|max_length[10]', + // 'is_active' => 'permit_empty|in_list[0,1]' + // ]; + + protected $validationMessages = []; + protected $skipValidation = false; + + /** + * Get files with optional filters + */ + // public function getFiles($filters = []) + // { + // if (!empty($filters['insurer_id'])) { + // $this->where('insurer_id', $filters['insurer_id']); + // } + + // if (!empty($filters['department'])) { + // $this->where('department', $filters['department']); + // } + + // if (!empty($filters['file_status'])) { + // $this->where('file_status', $filters['file_status']); + // } + + // if (isset($filters['is_active'])) { + // $this->where('is_active', $filters['is_active']); + // } + + // return $this->orderBy('id', 'DESC')->findAll(); + // } +} 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 new file mode 100644 index 00000000..2533dd0f --- /dev/null +++ b/app/Models/InvoiceItemModel.php @@ -0,0 +1,66 @@ + 'required|integer', + 'policy_id' => 'required|integer', + 'policy_no' => 'required|max_length[100]', + 'commission_amount' => 'decimal' + ]; + + 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 new file mode 100644 index 00000000..dcbd93fc --- /dev/null +++ b/app/Models/InvoiceModel.php @@ -0,0 +1,256 @@ + 'required|max_length[100]', + 'invoice_amount' => 'decimal', + 'agent_id' => 'required|integer', + 'invoice_date' => 'required|valid_date', + ]; + + protected $validationMessages = []; + protected $skipValidation = false; + + // Callbacks + protected $allowCallbacks = true; + protected $beforeInsert = ["checkAndADDCreatedByValue"]; + protected $afterInsert = []; + protected $beforeUpdate = ["checkAndUpdateUpdatedByValue"]; + protected $afterUpdate = []; + protected $beforeFind = []; + protected $afterFind = []; + protected $beforeDelete = []; + protected $afterDelete = []; + + 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; + } + + + public function invoiceList($agent_id = null, $status_id = null, $start_date = null, $end_date = null) + { + $data = $this->select(" + partner_invoice.*, + + -- Total UTR Amount + (SELECT SUM(piu.amount) + FROM partner_invoice_utr piu + WHERE piu.invoice_id = partner_invoice.id + AND piu.is_active = 1 + ) AS total_utr_amount, + + -- Balance Amount + (partner_invoice.invoice_amount - + IFNULL( + (SELECT SUM(piu2.amount) + FROM partner_invoice_utr piu2 + WHERE piu2.invoice_id = partner_invoice.id + AND piu2.is_active = 1 + ), + 0) + ) AS balance_amount, + + -- Payout status + CASE + WHEN payout_status = 1 THEN 'Pending' + WHEN payout_status = 2 THEN 'Completed' + END AS status_text, + + partner_agent.name as agent_name + ") + ->join('partner_agent', 'partner_invoice.agent_id = partner_agent.id') + ->where('partner_invoice.is_active', 1); + + if(!empty($agent_id)){ + $data->where('partner_invoice.agent_id', $agent_id); + } + + if(!empty($status_id)){ + $data->where('partner_invoice.payout_status', $status_id); + } + + if (!empty($start_date) && !empty($end_date)) { + + $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); + $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); + + $data->where('partner_invoice.invoice_date >=', $startDate) + ->where('partner_invoice.invoice_date <=', $endDate); + } + + if(!empty($agent_id) && !empty($status_id) && !empty($start_date) && !empty($end_date)){ + + $fromDate = date('Y-m-d', strtotime('-60 days')); + $toDate = date('Y-m-d 23:59:59'); + + $data->where('partner_invoice.created_at >=', $fromDate) + ->where('partner_invoice.created_at <=', $toDate); + + } + + $return_data = $data->orderBy('partner_invoice.id','desc')->findAll(); + + // print_r($this->db->getLastQuery()); die; + + return $return_data; + } + + public function agentList($params = []) + { + 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) + { + $data = $this->select(" + + partner_invoice.*, + + -- Total UTR Amount + (SELECT SUM(piu.amount) + FROM partner_invoice_utr piu + WHERE piu.invoice_id = partner_invoice.id + AND piu.is_active = 1 + ) AS total_utr_amount, + + -- Balance Amount + (partner_invoice.invoice_amount - + IFNULL( + (SELECT SUM(piu2.amount) + FROM partner_invoice_utr piu2 + WHERE piu2.invoice_id = partner_invoice.id + AND piu2.is_active = 1 + ), + 0) + ) AS balance_amount, + + -- Payout status + CASE + WHEN payout_status = 1 THEN 'Pending' + WHEN payout_status = 2 THEN 'Completed' + END AS status_text, + + partner_agent.name as agent_name + ") + ->join('partner_agent', 'partner_invoice.agent_id = partner_agent.id') + ->where('partner_invoice.is_active', 1) + ->where('partner_invoice.id', $invoice_id) + ->first(); + + 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/InvoiceUtrModel.php b/app/Models/InvoiceUtrModel.php new file mode 100644 index 00000000..a9da5960 --- /dev/null +++ b/app/Models/InvoiceUtrModel.php @@ -0,0 +1,73 @@ + 'required|integer', + 'utr_no' => 'required|max_length[100]', + 'amount' => 'decimal' + ]; + + protected $validationMessages = []; + protected $skipValidation = false; + + // Callbacks + protected $allowCallbacks = true; + protected $beforeInsert = ["checkAndADDCreatedByValue"]; + protected $afterInsert = []; + protected $beforeUpdate = ["checkAndUpdateUpdatedByValue"]; + protected $afterUpdate = []; + protected $beforeFind = []; + protected $afterFind = []; + protected $beforeDelete = []; + protected $afterDelete = []; + + 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/PTCOShareDetailsModel.php b/app/Models/PTCOShareDetailsModel.php index 1b2c84fd..fb63d682 100644 --- a/app/Models/PTCOShareDetailsModel.php +++ b/app/Models/PTCOShareDetailsModel.php @@ -68,6 +68,7 @@ class PTCOShareDetailsModel extends Model 'non_comm_per_amt', 'cotp_amt', 'cotep_amt', + 'pt_policy_issue_date', ]; public function getNonReconcileredPolicyTransactions(string $insurer_id,string $insurer_branch_id) diff --git a/app/Models/PolicyTransactionModel.php b/app/Models/PolicyTransactionModel.php index 7f3ca607..b5015dbd 100644 --- a/app/Models/PolicyTransactionModel.php +++ b/app/Models/PolicyTransactionModel.php @@ -826,8 +826,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 +1051,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 +1098,7 @@ // Optimize Query Execution $builder->orderBy('policy_transaction.id', 'desc'); $data = $builder->get()->getResultArray(); + // dd($this->db->getLastQuery()); return $data; } @@ -1134,11 +1153,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 +1202,7 @@ } $builder->orderBy('policy_transaction.id', 'desc'); - + // dd($this->db->getLastQuery()); return $builder->get()->getResultArray(); } @@ -1315,8 +1340,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 +1390,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 +1454,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 +1565,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 +1680,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'); diff --git a/app/Models/TicketClaimStatusModel.php b/app/Models/TicketClaimStatusModel.php index 99078a03..87b09f3d 100644 --- a/app/Models/TicketClaimStatusModel.php +++ b/app/Models/TicketClaimStatusModel.php @@ -12,7 +12,7 @@ class TicketClaimStatusModel extends Model protected $returnType = 'array'; protected $useSoftDeletes = false; protected $protectFields = true; - protected $allowedFields = ["id", "ticket_type", "claim_status", "created_by", "updated_by", "is_active"]; + protected $allowedFields = ["id", "ticket_type", "claim_status", "display_name", "created_by", "updated_by", "is_active"]; // Callbacks protected $allowCallbacks = true; 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/Views/UserList.php b/app/Views/UserList.php index d0dca952..01db38eb 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 { " . $ct . ""; endif; ?> @@ -448,7 +449,7 @@ table.dataTable tbody td { " . $ut . ""; endif; ?> @@ -858,9 +859,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', 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_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 {
Advertisement Image NameStatusAction
Advertisement Image Name
Status
Action
- - - - - - - - - + + + + + + + + + @@ -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..2086aeef 100755 --- a/app/Views/file_list.php +++ b/app/Views/file_list.php @@ -8,6 +8,9 @@ cursor: pointer; } +.dataTables_length label {height: 21px !important;} + +
@@ -461,12 +464,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/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 @@
- + @@ -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_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 @@
-
+
+
S.No S.No  Docs Name  File Name  Action  ' . $file['first_name'] . '' ?>' . $file['first_name'] . '' ?>
- + @@ -269,7 +279,7 @@ - + +
Insurer
by ' . $row['first_name'] ?> by ' . $row['first_name'] ?> - +
- +
- +
@@ -342,7 +342,7 @@ - +
@@ -446,8 +447,7 @@
- - + - + + + @@ -490,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 ', @@ -568,10 +573,24 @@ table.dataTable thead th { maxDate: today // Disallow future dates }); + var month = flatpickr("#month", { + dateFormat: "M/Y", // Format as month and year + allowInput: false, // Disable manual input + }); - var closure_date = flatpickr("#policy_issue_date", { - dateFormat: "d/m/Y", - allowInput: false + var policy_issue_date = flatpickr("#policy_issue_date", { + dateFormat: "d/m/Y", // Format as day-month-year + allowInput: false, // Disable manual input + onChange: function(selectedDates, dateStr, instance) { + // Get the selected date + var selectedDate = new Date(selectedDates[0]); + + // Format the selected date to "M-Y" + var formattedMonth = flatpickr.formatDate(selectedDate, "M/Y"); + + // Set the value of the #month input + month.setDate(formattedMonth); + } }); var install_due_date = flatpickr("#install_due_date", { @@ -579,26 +598,11 @@ table.dataTable thead th { allowInput: false }); - // var start_date = flatpickr("#policy_start_date", { - // dateFormat: "d/m/Y", - // allowInput: false - // }); - - // var end_date = flatpickr("#policy_end_date", { - // dateFormat: "d/m/Y", - // allowInput: false - // }); - var endorse_eff_date = flatpickr("#endorse_eff_date", { dateFormat: "d/m/Y", allowInput: false }); - var month = flatpickr("#month", { - dateFormat: "M/Y", - allowInput: false, - }); - }); function hide_list_show_add() { diff --git a/app/Views/policy_transaction_inception_form.php b/app/Views/policy_transaction_inception_form.php index 3b8013c6..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; + } + @@ -561,9 +562,14 @@ $(document).ready(function() { 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-12'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_payouts.php b/app/Views/policy_transaction_payouts.php new file mode 100644 index 00000000..e69de29b diff --git a/app/Views/policy_type_list.php b/app/Views/policy_type_list.php index 2f6d6002..eeccbb28 100755 --- a/app/Views/policy_type_list.php +++ b/app/Views/policy_type_list.php @@ -65,6 +65,7 @@ z-index: -2; pointer-events: none; } + .dataTables_length label {height: 21px !important;}
@@ -217,9 +218,9 @@ $(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>>", // buttons: [ // { // extend: 'csv', @@ -230,6 +231,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', diff --git a/app/Views/report_bds.php b/app/Views/report_bds.php index 2261d79c..19e071c7 100644 --- a/app/Views/report_bds.php +++ b/app/Views/report_bds.php @@ -33,7 +33,7 @@ table.dataTable tbody td { flex-wrap: wrap; gap: 8px; } - +.dataTables_length label {height: 21px !important;} @@ -84,7 +84,7 @@ table.dataTable tbody td { Business Type Client Type Insured Name - Policy/
Endorsement + Policy /
Endorsement Policy Type BAP Group Vehicle Number @@ -100,9 +100,9 @@ table.dataTable tbody td { Remarks BP Premium TP/Ter Premium - Premium
(without GST) + Premium
(without GST) - Total Premium + Total Premium BP% TP/Ter% Rewards @@ -144,9 +144,9 @@ table.dataTable tbody td { - + - + % % @@ -232,9 +232,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 +286,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/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 @@ " . $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 095e8de7..7428ab32 100644 --- a/app/Views/ticket_form_gmc.php +++ b/app/Views/ticket_form_gmc.php @@ -333,7 +333,7 @@