diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 86e47622..fd1f09ca 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -32,6 +32,8 @@ $routes->get("update-policy-terms-for-corrections", "ClientController::updatePol $routes->get("update_rack_rate_json", "ClientController::updateRackRateJson"); $routes->get("updatajson", "EmpDataServiceController::updatajson"); $routes->get("view", "EmployeeController::viewECard/$1"); +$routes->get("checkWellnessOnboardStatus/(:any)", "EmployeeController::checkWellnessOnboardStatus/$1"); +$routes->get("initiateWellnessOnboard/(:any)", "EmployeeController::initiateWellnessOnboard/$1"); $routes->get("exportQCRandRFQ/(:any)", "LeadsController::exportQCRandRFQ/$1"); $routes->get("smapletest", "ClientController::smapletest"); $routes->get("testMailAttachments", "ClientController::testMailAttachments"); @@ -162,6 +164,11 @@ $routes->group("/client", ["filter" => "authMVC"], function ($routes) { $routes->post("edit", "ClientController::editClientKYCInfo"); $routes->get("list/(:any)", "ClientController::getKycDocsById/$1"); $routes->get("delete/(:any)", "ClientController::deleteClientKycDocs/$1"); + + $routes->post("create_2", "ClientController::createClientKYCInfo_2"); + $routes->post("edit_2", "ClientController::editClientKYCInfo_2"); + $routes->post("delete_2", "ClientController::deleteClientKycDocs_2/$1"); + }); $routes->group("premimum", ["filter" => "authMVC"], function ($routes) { @@ -566,10 +573,15 @@ $routes->group("employeeRest", ['filter' => ["appSignature"] ], function ($route $routes->get("getHRAccessData", "RestAuthenticationController::getHRAccessData"); $routes->post("getPostEmployeeDataForAuth", "RestAuthenticationController::getPostEmployeeDataForAuth"); + $routes->post("getRetailUserData", "RestAuthenticationController::getRetailUserData"); $routes->get("getClientDetails", "EmployeeRestController::getClientDetails"); $routes->get("getAdvertisementImage", "EmployeeRestController::getAdvertisementImage"); + //retail user apis + $routes->post("getVerifiedRetailUserData", "RestAuthenticationController::getVerifiedRetailUserData"); + $routes->post("updateRetailUserAuthDetails", "RestAuthenticationController::updateRetailUserAuthDetails"); + }); $routes->group("employeeRest", ["filter" => ["authJWT"]], function ($routes) { diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index e0a556db..b67ae501 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -1005,6 +1005,153 @@ class ClientController extends AdminController + public function createClientKYCInfo_2() + { + $this->myLogger->logme('error', 'create Client kyc function called'); + $data = $this->request->getPost(); + + $uploadedFile = $this->request->getFile('file_name'); + + if ($uploadedFile && $uploadedFile->isValid() && !$uploadedFile->hasMoved()) { + $this->myLogger->logme('info', 'File is valid and ready to move.'); + } else { + $this->myLogger->logme('error', 'File failed validation or was not uploaded.'); + } + + $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents'; + + $File = file_Upload($uploadedFile, $uploadFilePath); + $this->myLogger->logme('info', 'Result of file_Upload: ' . $File); + unset($data['file_name']); + + if (!empty($File)) { $data['file_name'] = $File; } + + $data['created_by'] = get_session_userid(); + $insert = $this->clientKYCDocsModel->insert($data); + + if ($insert) { + $html = $this->generateKycSingleTable($data['client_id']); + $dropdown = $this->fetch_dropdown($data['client_id']); + return $this->respond(['status' => true, 'code' => 200, 'file_name' => $File, 'html' => $html,'dropdown'=>$dropdown], 200); + } else { + $this->myLogger->logme('error', 'Database insert failed.'); + return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to add document'], 200); + } + } + + public function editClientKYCInfo_2() + { + + $kyc_id = $this->request->getPost('id'); + $client_id = $this->request->getPost('client_id'); + $old_file_name = $this->request->getPost('old_file_name'); + $uploadedFile = $this->request->getFile('file_name'); + $new_file_name = null; + $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents'; + + + if ($uploadedFile && $uploadedFile->isValid() && !$uploadedFile->hasMoved()) { + + + $new_file_name = file_Upload($uploadedFile, $uploadFilePath); + + if (!empty($new_file_name)) { + + $updateData['file_name'] = $new_file_name; + + // Delete the old file from the storage if it exists + // if (!empty($old_file_name)) { + // $old_file_path = $uploadFilePath . '/' . $old_file_name; + // if (file_exists($old_file_path)) { + // unlink($old_file_path); + // // Optionally delete from G-Drive here if applicable + // } + // } + } else { + // New file upload failed + return $this->respond(['status' => false, 'code' => 500, 'message' => 'New file upload failed on server.'], 200); + } + } + + // 2. Perform the database update + if (!empty($updateData)) { + + $updateData['updated_by'] = get_session_userid(); + $update = $this->clientKYCDocsModel->update($kyc_id, $updateData); + $html = $this->generateKycSingleTable($client_id); + $dropdown = $this->fetch_dropdown($client_id); + + if ($update) { + return $this->respond(['status' => true, 'code' => 200, 'message' => 'Document updated successfully.','html' => $html,'dropdown' => $dropdown], 200); + } + } else { + + return $this->respond(['status' => true, 'code' => 200, 'message' => 'No changes detected. Document remains the same.'], 200); + } + + + return $this->respond(['status' => false, 'code' => 404, 'message' => 'Database update failed or record not found.'], 200); + } + + + public function deleteClientKycDocs_2() + { + + $kyc_id = $this->request->getPost('id'); + $client_id = $this->request->getPost('client_id'); + + if (empty($kyc_id)) { + return $this->respond(['status' => false, 'code' => 400, 'message' => 'Missing document ID.'], 200); + } + $updateData['updated_by'] = get_session_userid(); + $updateData['is_active'] = $this->request->getPost('is_active'); + + $delete = $this->clientKYCDocsModel->update($kyc_id, $updateData); + + if ($delete) { + $html = $this->generateKycSingleTable($client_id); + $dropdown = $this->fetch_dropdown($client_id); + return $this->respond(['status' => true, 'code' => 200, 'id' => $kyc_id, 'message' => 'Document successfully deactivated.','html' => $html,'dropdown' => $dropdown], 200); + } else { + return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to update record (ID not found or DB error).'], 200); + } + } + + public function fetch_dropdown($client_id){ + + $db = db_connect(); + + + $submitted_ids_subquery = $db->table('client_kyc_documents ckd') + ->select('ckd.kyc_doc_type_id') + ->where('ckd.client_id', $client_id) + ->where('ckd.is_active', 1) + ->getCompiledSelect(); + + + $result = $db->table('kyc_docs kd') + ->select('kd.*') + ->join('clients c', 'kd.kyc_type_id = c.entity_type_id') + ->where('c.id', $client_id) + ->where("kd.kyc_type_id NOT IN ({$submitted_ids_subquery})") + ->groupBy('kd.id') + ->get() + ->getResultArray(); + + + $dropdown = ''; + $dropdown .= ''; + + foreach ($result as $row) { + $dropdown .= ''; + } + + return $dropdown; + } + + public function createClientRelation() { @@ -2361,6 +2508,36 @@ class ClientController extends AdminController } + + public function generateKycSingleTable($client_id) + { + + + $result['ckdlist'] = db_connect()->table('client_kyc_documents ckd') + ->select("ckd.id,ckd.client_id,ckd.kyc_doc_type_id,ckd.file_name,kd.file_name AS kd_docs_name,ckd.other_docs_name,ckd.vehicle_id,ckd.is_active, + CASE + WHEN ckd.kyc_doc_type_id IS NULL + OR ckd.kyc_doc_type_id = 0 + OR ckd.kyc_doc_type_id = '' + THEN ckd.other_docs_name + ELSE kd.file_name + END AS ui_docs_name") + ->join('kyc_docs kd','ckd.kyc_doc_type_id = kd.kyc_type_id','left') + ->where('ckd.client_id',$client_id) + ->where('ckd.is_active',1) + ->groupBy('ckd.id') + ->get() + ->getResultArray(); + + + $result['client_id'] = $client_id; + $table = view('client_kyc_single_table', $result); + + return $table; + // print_r($table); die; + + } + public function getPolicesByInsurerId($id = null) { $this->myLogger->logme('error', 'getPolicesByInsurerId function called'); diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php index 6064e4b6..ca24ec6b 100755 --- a/app/Controllers/EmployeeController.php +++ b/app/Controllers/EmployeeController.php @@ -3213,4 +3213,367 @@ class EmployeeController extends AdminController } + public function checkWellnessOnboardStatus($client_policy_id) + { + // echo $client_policy_id;die(); + $data = $this->employeePolicyModel->select('employee_polices.*,emp.name,emp.relationship,emp.emp_code,emp.name,emp.email_corporate,emp.mobile,emp.dob,cp.policy_no,cp.wellness_plan_id,cp.wellness_vendor_id,cp.policy_start_date as cp_policy_start_date,cp.policy_end_date,cls.short_name') + ->join('client_policy cp', 'cp.id = employee_polices.client_policy_id') + ->join('clients cls', "cp.client_id = cls.id") + ->join('employees emp', "emp.id = employee_polices.employee_id") + ->where('employee_polices.is_active', 1) + ->where('employee_polices.status', 'active') + ->where('employee_polices.client_policy_id', $client_policy_id) + ->where('employee_polices.tpa_id is not null') + ->where('employee_polices.wellness_onboard', '0') + ->where('emp.emp_status', 'active') + ->where('emp.is_active', 1) + ->where('cp.wellness_plan_id is not null') + ->where('cp.wellness_vendor_id is null') + // ->where('cp.policy_status',1) + // ->where('cp.is_active',1) + ->findAll(); + // echo count($data);die(); + // if(is_array($data) && count($data)) + // { + return $this->respond(['status' => true, 'code' => 200, 'data' => count($data)], 200); + // } + // return $this->respond(['status' => true, 'code' => 200, 'message' => 'Inception and Member data comparision skiped successfully!'], 200); + } + + public function initiateWellnessOnboard($client_policy_id) + { + $r = Jobs::addJob(['job_name' => 'initiateWellnessOnboardJob','payload' => ['client_policy_id' => $client_policy_id]]); + return $this->respond(['status' => true, 'code' => 200, 'message' => 'Process started'], 200); + } + + public function initiateWellnessOnboardJob($arr) + { + + $client_policy_id = $arr['client_policy_id']; + // $this->updateWellnessOnboardResponseToDB();die(); + // echo $client_policy_id;die(); + $data = $this->employeePolicyModel->select('employee_polices.*,emp.name,emp.relationship,emp.emp_code,emp.name,emp.email_corporate,emp.mobile,emp.dob,cp.policy_no,cp.wellness_plan_id,cp.wellness_vendor_id,cp.policy_start_date as cp_policy_start_date,cp.policy_end_date,cls.short_name') + ->join('client_policy cp', 'cp.id = employee_polices.client_policy_id') + ->join('clients cls', "cp.client_id = cls.id") + ->join('employees emp', "emp.id = employee_polices.employee_id") + ->where('employee_polices.is_active', 1) + ->where('employee_polices.status', 'active') + ->where('employee_polices.client_policy_id', $client_policy_id) + ->where('employee_polices.tpa_id is not null') + ->where('employee_polices.wellness_onboard', '0') + ->where('emp.emp_status', 'active') + ->where('emp.is_active', 1) + ->where('cp.wellness_plan_id is not null') + ->where('cp.wellness_vendor_id is null') + // ->where('cp.policy_status',1) + // ->where('cp.is_active',1) + ->findAll(); + // print_r($this->employeePolicyModel->getLastQuery()); + // print_r($data); + // echo '==============================';die(); + // $data = '[{"id":12847,"employee_id":"TEST_EMP_001","client_policy_id":null,"tpa_id":null,"uhid":null,"batch_code":null,"status":"active","pre_existing_alignments":null,"age_band":null,"basic_cover_si":"0","date_coverage":"2025-01-01","policy_end_date":"2025-12-31","days":"0","premium":"0","rata_premimum":"0","gst":"0","si_enhancement_date":null,"date_of_exit":null,"reason_for_exit":null,"claim_status":"0","created_by":null,"created_at":null,"updated_by":null,"updated_at":null,"is_active":"1","rand_string":null,"ecard_sent_status":"0","payable_employee":"0","file_id":null,"wellness_onboard":"0","name":"test name","relationship":"SELF","emp_code":"TEST_EMP_001","email_corporate":"test@gmail.com","mobile":"9797976565","dob":"1975-08-09"},{"id":12846,"employee_id":"TEST_EMP_001","client_policy_id":null,"tpa_id":null,"uhid":null,"batch_code":null,"status":"active","pre_existing_alignments":null,"age_band":null,"basic_cover_si":"0","date_coverage":"2025-01-01","policy_end_date":"2025-12-31","days":"0","premium":"0","rata_premimum":"0","gst":"0","si_enhancement_date":null,"date_of_exit":null,"reason_for_exit":null,"claim_status":"0","created_by":null,"created_at":null,"updated_by":null,"updated_at":null,"is_active":"1","rand_string":null,"ecard_sent_status":"0","payable_employee":"0","file_id":null,"wellness_onboard":"0","name":"dependent 1","relationship":"SON","emp_code":"TEST_EMP_001","email_corporate":"dependent1@gmail.com","mobile":"9898989898","dob":"2001-08-09"}]'; + // $data = (array)json_decode($data,true); + // print_r($data); + // echo '==============================';die(); + if(is_array($data) && count($data)) + { + // $data = $input['data'] ?? []; + + // ------------------ GROUP BY FAMILY (emp_code) ------------------ + $families = []; // [emp_code => [rows...]] + + foreach ($data as $row) { + if (empty($row['emp_code'])) { + // If emp_code is missing, you can skip or handle separately + continue; + } + + $empCode = $row['emp_code']; + if (!isset($families[$empCode])) { + $families[$empCode] = []; + } + $families[$empCode][] = $row; + } + + // ------------------ BUILD PAYLOAD FOR ALL FAMILIES ------------------ + $familiesPayload = []; + + foreach ($families as $empCode => $members) { + $familiesPayload[$empCode] = $this->buildFamilyPayload($empCode, $members); + } + + // print_r($familiesPayload);die(); + $apiResponse = $this->sendFamiliesToWellnessApi($familiesPayload); + // print_r($apiResponse); + $updatedData = $this->updateWellnessOnboardResponseToDB($apiResponse); + // print_r($updatedData);die(); + return true; + + + + + } + else + { + return $this->respond(['status' => false, 'code' => 200, 'message' => 'No employees found for wellness onboard!'], 200); + + } + + } + + + + # ------------------ FUNCTION TO BUILD FAMILY PAYLOAD ------------------ + /** + * Build the required payload for a single family. + * + * @param string $empCode + * @param array $members Array of rows for this emp_code + * @return array + */ + private function buildFamilyPayload(string $empCode, array $members): array + { + // Use the first member as primary reference for policy level data + $primary = $members[0]; + + // Map DB fields to your required "policyDetails" structure + $policyStartDate = $primary['cp_policy_start_date'] ?? null; + // $policyStartDate = '2025-01-01'; + $policyEndDate = $primary['policy_end_date'] ?? null; + // $policyEndDate = '2025-12-31'; + + $payload = [ + "policyDetails" => [ + "policyNumber" => $primary["policy_no"] ?? null, + "employeeId" => $empCode, + "policyName" => "GMC", // Static or from DB + "policyStartDate" => $policyStartDate, + "policyEndDate" => $policyEndDate, + "plan" => $primary["wellness_plan_id"] ?? null, + "source" => $primary['short_name'] ?? null, + "employer" => $primary['short_name'] ?? null, + "employeeCode" => $empCode, + "accountNumber" => "", // Fill from DB if available + "ifsc" => "", // Fill from DB if available + "accountType" => "" // Fill from DB if available + ], + "memberDetails" => [] + ]; + + // Build "memberDetails" for each member in this family + foreach ($members as $index => $row) { + + // You don't have gender in data, so put null or default + $gender = null; // or "MALE" / "FEMALE" if you infer from somewhere + + $payload["memberDetails"][] = [ + "memberId" => $row["id"], // or custom ID (e.g. employee_id.'-'.$index) + "name" => $row["name"], + "phone" => $row["mobile"], + "email" => $row["email_corporate"], + "relationshipName" => strtoupper($row["relationship"] ?? ''), + "gender" => $gender, + "dob" => $row["dob"] + ]; + } + + return $payload; + } + + + + /** + * Send each family payload to API and attach the response + * + * @param array $familiesPayload [emp_code => ['policyDetails' => ..., 'memberDetails' => [...]]] + * @return array Same array but with ['apiResponse'] added for each family + */ + public function sendFamiliesToWellnessApi(array $familiesPayload): array + { + // CI4 HTTP client + $client = \Config\Services::curlrequest();//die(); + $endpointUrl = getenv('WELLNESS_ONBOARD_ENDPOINT_URL'); + // Custom headers + $headers = [ + 'Content-Type' => 'application/json', + 'Authorization' => 'Basic ' . getenv('WELLNESS_ONBOARD_AUTHORIZATION') + ]; + + foreach ($familiesPayload as $empCode => &$family) { + + try { + $response = $client->post($endpointUrl, [ + 'headers' => $headers, + 'body' => json_encode($family), + 'http_errors' => false, // so we can handle non-2xx manually + 'timeout' => 30, + ]); + + $statusCode = $response->getStatusCode(); + $body = (string) $response->getBody(); + $decoded = json_decode($body, true); + + $family['apiResponse'] = [ + 'statusCode' => $statusCode, + 'rawBody' => $body, + 'data' => $decoded, + ]; + } catch (\Throwable $e) { + // In case of exception, store error info + $family['apiResponse'] = [ + 'statusCode' => 0, + 'rawBody' => null, + 'data' => null, + 'error' => $e->getMessage(), + ]; + } + } + + unset($family); // break reference + + return $familiesPayload; + } + + + + /** + * Batch update wellness_onboard for each family using referenceId from API response. + * + * @param array $familiesWithResponse // output of sendFamiliesToApi() + * @return void + */ + public function updateWellnessOnboardResponseToDB(array $familiesWithResponse = []): void + { + // echo 'START'; + // Collect all rows to update in a single big batch (optional but efficient) + $allUpdates = []; + + // $apiResponse = [ + // "message" => "success", + // "body" => "The policy details are posted successfully", + // "policyDetails" => [ + // [ + // "memberId" => "12847", + // "name" => "test name", + // "phone" => 9797976565, + // "email" => "test@gmail.com", + // "relationshipName" => "SELF", + // "gender" => "MALE", + // "dob" => "1975-08-09" + // ], + // [ + // "memberId" => "12846", + // "name" => "dependent 1", + // "phone" => 9898989898, + // "email" => "dependent1@gmail.com", + // "relationshipName" => "SON", + // "gender" => "MALE", + // "dob" => "2001-08-09" + // ] + // ], + // "referenceId" => "TESTPOL001-client1-1764914537069" + // ]; + + // $familiesWithResponse = [ + + // "TEST_EMP_001" => [ + // "policyDetails" => [ + // "policyNumber" => "TESTPOL001", + // "employeeId" => "TEST_EMP_001", + // "policyName" => "Client Policy Name", + // "policyStartDate" => "2025-01-01", + // "policyEndDate" => "2025-12-31", + // "plan" => "plan-A", + // "source" => "client1", + // "employer" => "employeer1", + // "employeeCode" => "TEST_EMP_001", + // "accountNumber" => "", + // "ifsc" => "", + // "accountType" => "" + // ], + // "memberDetails" => [ + // [ + // "memberId" => "12847", + // "name" => "test name", + // "phone" => 9797976565, + // "email" => "test@gmail.com", + // "relationshipName" => "SELF", + // "gender" => "MALE", + // "dob" => "1975-08-09" + // ], + // [ + // "memberId" => "12846", + // "name" => "dependent 1", + // "phone" => 9898989898, + // "email" => "dependent1@gmail.com", + // "relationshipName" => "SON", + // "gender" => "MALE", + // "dob" => "2001-08-09" + // ] + // ], + + // "apiResponse" => [ 'statusCode' => 200 ,"rawBody" => "", "data" => $apiResponse] + // ] + // ]; + + + + foreach ($familiesWithResponse as $empCode => $family) { + + $apiResponse = $family['apiResponse'] ?? null; + if (!$apiResponse || !isset($apiResponse['data'])) { + // No valid API data for this family + $this->myLogger->logme('error', "Wellness Onboard API error for emp_code {$empCode} No apiResponse found:"); + continue; + } + + // Your endpoint response + $statusCode = $apiResponse['statusCode'] ?? null; + if (empty($statusCode) || $statusCode == 400 || $statusCode == 500) { + $this->myLogger->logme('error', "Wellness Onboard API error for emp_code {$empCode} {}: " . ($apiResponse['rawBody'] ?? 'No response')); + + // No referenceId, nothing to update + continue; + } + + $data = $apiResponse['data']; + + // Your endpoint response + $referenceId = $data['referenceId'] ?? null; + if (empty($referenceId)) { + // No referenceId, nothing to update + $this->myLogger->logme('error', "Wellness Onboard API error for emp_code {$empCode} No referenceId found:"); + continue; + } + + // All members in this family share the same referenceId + if (empty($family['memberDetails']) || !is_array($family['memberDetails'])) { + $this->myLogger->logme('error', "Wellness Onboard API error for emp_code {$empCode} No memberDetails found:"); + continue; + } + + foreach ($family['memberDetails'] as $member) { + $memberPk = $member['memberId'] ?? null; // This is employee_policy.id + + if (empty($memberPk)) { + continue; + } + + $allUpdates[] = [ + 'id' => $memberPk, // PK column of your table + 'wellness_onboard' => $referenceId, + // uncomment if you have updated_at column + // 'updated_at' => date('Y-m-d H:i:s'), + ]; + } + } + // print_r($allUpdates);die(); + // Do a single batch update for all families/members + if (!empty($allUpdates)) { + // 2nd param is the key to match on; here it's 'id' + $this->employeePolicyModel->updateBatch($allUpdates, 'id'); + } + } + + } diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index 8aa30d71..859b51d1 100755 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -2820,7 +2820,43 @@ class EmployeeRestController extends AdminController function getEmployeeActiveOrInactivePolicy() - { + { + + // for retail user policy only + $receviedPayload = $this->request->getGet(); + + if( + empty($receviedPayload['client_id']) && + empty($receviedPayload['client_branch_id']) && + empty($receviedPayload['emp_code']) + ){ + + if(!empty($receviedPayload['mobile_no']) || !empty($receviedPayload['email_id'])){ + + $retailUserData = (object) [ + 'id' => null, + 'mobile' => $receviedPayload['mobile_no'], + 'email_id' => $receviedPayload['email_id'] + ]; + + $emp_reatail_policy_data = $this->getEmpRetailPolicy($retailUserData); + + $query = $this->clientModel + ->where('is_active', 1) + ->where('client_type', 2); + + if (!empty($receviedPayload['mobile_no'])) { + $query->where('phone', $receviedPayload['mobile_no']); + } else { + $query->where('email', $receviedPayload['email_id'] ?? null); + } + + $retailClientData = $query->first(); + $wellness_data = ['status' => 'failed','message' => 'Coming soon........!']; + return $this->respond(['status' => 'success', 'code' => 200, 'data' => [], 'emp_name' => $retailClientData['client_name'] ?? "", 'pre_policy_count' => 0, 'retail_policy_data' => $emp_reatail_policy_data, 'wellness_data' => $wellness_data], 200); + } + } + if ($this->request->getGet('type') == 'Active') { $policy_status = 1; $policy_status_key = "Active"; @@ -4648,6 +4684,7 @@ class EmployeeRestController extends AdminController $emp_id = $employeeData->id ?? null; $mobile_number = $employeeData->mobile ?? null; + $email_id = $employeeData->email_id ?? null; $emp_retail_policy_data = []; if ($emp_id != null) { @@ -4678,7 +4715,7 @@ class EmployeeRestController extends AdminController if (!empty($mobile_number)) { $emp_retail_client_data = $this->clientModel ->select(" - $emp_id as emp_id, + '{$emp_id}' AS emp_id, policy_transaction.insurer_id, policy_transaction.policy_type_id, policy_transaction.policy_no, @@ -4696,9 +4733,31 @@ class EmployeeRestController extends AdminController ->where('clients.is_active', 1) ->where('clients.phone', $mobile_number) ->findAll(); + }else { + $emp_retail_client_data = $this->clientModel + ->select(" + '{$emp_id}' AS emp_id, + policy_transaction.insurer_id, + policy_transaction.policy_type_id, + policy_transaction.policy_no, + DATE_FORMAT(policy_transaction.policy_start_date, '%d-%b-%Y') as policy_start_date, + DATE_FORMAT(policy_transaction.policy_end_date, '%d-%b-%Y') as policy_end_date, + policy_type.policy_type, + policy_type.long_name as policy_type_long_name, + insurers.name as insurer_name, + insurers.short_name as insurer_short_name + ") + ->join('policy_transaction', 'policy_transaction.client_id = clients.id') + ->join('insurers', 'policy_transaction.insurer_id = insurers.id') + ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id') + ->where('policy_transaction.is_active', 1) + ->where('clients.is_active', 1) + ->where('clients.email IS NOT NULL') + ->where('clients.email', $email_id) + ->findAll(); } - // print_r($emp_retail_policy_data); die; + // print_r($this->clientModel->getLastQuery()); die; $complete_emp_retail_policy_data = array_values( array_column( @@ -4736,7 +4795,7 @@ class EmployeeRestController extends AdminController $data = $db->table('employees e') ->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') + cp.policy_no as policyNumber, ep.employee_id as employeeId, cp.policy_start_date as policyStartDate, cp.policy_end_date as policyEndDate , cp.wellness_plan_id as planId') ->join('employee_polices ep', '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') diff --git a/app/Controllers/JobWorker.php b/app/Controllers/JobWorker.php index 190a1058..43935749 100755 --- a/app/Controllers/JobWorker.php +++ b/app/Controllers/JobWorker.php @@ -187,6 +187,10 @@ class JobWorker extends AdminController 'type' => 'CC', // Handler Category 'handler' => 'App\Controllers\PolicyTransactionController', ], + 'initiateWellnessOnboardJob' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmployeeController', + ], ]; diff --git a/app/Controllers/NotificationController.php b/app/Controllers/NotificationController.php index e288a7a0..cc13b100 100755 --- a/app/Controllers/NotificationController.php +++ b/app/Controllers/NotificationController.php @@ -375,7 +375,7 @@ class NotificationController extends AdminController // Insert file attachment record if ($this->MailAttachmentModel->insert($data)) { // Retrieve active attachments to return in response - $attachment_data = $this->MailAttachmentModel->where('is_active', 1)->findAll(); + $attachment_data = $this->MailAttachmentModel->where('notification_id', $find_notification['id'])->where('is_active', 1)->findAll()??[]; return $this->respond([ 'status' => true, 'code' => 200, diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php index e60d0be1..5b348a0f 100644 --- a/app/Controllers/PolicyTransactionController.php +++ b/app/Controllers/PolicyTransactionController.php @@ -994,6 +994,7 @@ $clientController = new ClientController(); $data['client_kyc_primary_table'] = $clientController->generateKycPrimaryTable($data['client_id']); $data['client_kyc_other_table'] = $clientController->generateKycOthersTable($data['client_id']); + // $data['client_kyc_single_table'] = $clientController->generateKycSingleTable($data['client_id']); $data['entity_type_id'] = $client_data['entity_type_id']; return $this->respondSuccess($insert, "Policy transaction created successfully", $data); @@ -1056,6 +1057,7 @@ $clientController = new ClientController(); $data['client_kyc_primary_table'] = $clientController->generateKycPrimaryTable($data['client_id']); $data['client_kyc_other_table'] = $clientController->generateKycOthersTable($data['client_id']); + // $data['client_kyc_single_table'] = $clientController->generateKycSingleTable($data['client_id']); $data['entity_type_id'] = $client_data['entity_type_id']; @@ -1624,6 +1626,8 @@ $clientController = new ClientController(); $data['client_kyc_primary_table'] = $clientController->generateKycPrimaryTable($data['client_id']); $data['client_kyc_other_table'] = $clientController->generateKycOthersTable($data['client_id']); + $data['client_kyc_single_table'] = $clientController->generateKycSingleTable($data['client_id']); + $data['client_kyc_dd_data'] = $clientController->fetch_dropdown($data['client_id']); $data['vehicle_docs'] = $this->clientKYCDocsModel ->where('client_id', $data['client_id']) @@ -1894,6 +1898,7 @@ $clientController = new ClientController(); $data['client_kyc_primary_table'] = $clientController->generateKycPrimaryTable($data['client_id']); $data['client_kyc_other_table'] = $clientController->generateKycOthersTable($data['client_id']); + $data['client_kyc_single_table'] = $clientController->generateKycSingleTable($data['client_id']); $data['vehicle_docs'] = $this->clientKYCDocsModel ->where('client_id', $data['client_id']) diff --git a/app/Controllers/RestAuthenticationController.php b/app/Controllers/RestAuthenticationController.php index 45a8db6b..b0f56392 100755 --- a/app/Controllers/RestAuthenticationController.php +++ b/app/Controllers/RestAuthenticationController.php @@ -339,7 +339,7 @@ class RestAuthenticationController extends AdminController public function updateEmpMPIN() { try { - log_message('info', 'MPIN update request received.'); + log_message('error', 'MPIN update request received.'); $requestData = $this->request->getJSON(); log_message('debug', 'Request data: ' . json_encode($requestData)); @@ -361,7 +361,7 @@ class RestAuthenticationController extends AdminController $updated = $this->employeeModel->where('id', $employee_id)->set(['mpin' => $mpin])->update(); if ($updated) { - log_message('info', "MPIN updated successfully for employee ID: {$employee_id}"); + log_message('error', "MPIN updated successfully for employee ID: {$employee_id}"); return $this->response->setJSON([ 'status' => true, 'message' => 'MPIN updated successfully.' @@ -1283,7 +1283,7 @@ class RestAuthenticationController extends AdminController // Step 2: Fetch employee data if ($mobile_number) { - log_message('info', 'Looking up employee by mobile number: ' . $mobile_number); + log_message('error', 'Looking up employee by mobile number: ' . $mobile_number); $builder = $this->employeeModel ->select('employees.*') ->join('employee_polices', 'employees.id = employee_polices.employee_id') @@ -1302,7 +1302,7 @@ class RestAuthenticationController extends AdminController } else { - log_message('info', 'Looking up employee by email: ' . $email_id); + log_message('error', 'Looking up employee by email: ' . $email_id); $builder = $this->employeeModel ->select('employees.*') ->join('employee_polices', 'employees.id = employee_polices.employee_id') @@ -1343,7 +1343,7 @@ class RestAuthenticationController extends AdminController ->update(); if ($updated) { - log_message('info', 'MPIN reset successful for employee ID: ' . $employeeData['id']); + log_message('error', 'MPIN reset successful for employee ID: ' . $employeeData['id']); return $this->respond([ 'status' => 'success', 'code' => 200, @@ -1776,7 +1776,7 @@ class RestAuthenticationController extends AdminController $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyPassword: Verified employee found"); - // ✅ Log authentication info + // ✅ Log authentication error $auth = HttpRequestHelper::getRequestInfo(); if ($auth) { $this->authHistoryModel->insert([ @@ -2043,4 +2043,247 @@ class RestAuthenticationController extends AdminController ], 500); } } + + public function getRetailUserData() + { + $params = $this->request->getJSON(true); + // print_r( $params); die; + + $mobile_number = $params['mobile_number'] ?? null; + $email_id = $params['email_id'] ?? null; + $otp = $params['otp'] ?? null; + $old_mpin = $params['old_mpin'] ?? null; + + if (empty($mobile_number) && empty($email_id)) { + return $this->respond(['status' => 'failed', 'message' => 'Mobile number or Email ID is required.', 'data' => [],], 200); + } + + if (!empty($mobile_number)) { + + $builder = $this->clientModel + ->select('clients.*') + ->join('policy_transaction', 'policy_transaction.client_id = clients.id') + ->where('policy_transaction.is_active', 1) + ->where('clients.is_active', 1) + ->where('clients.phone', $mobile_number); + + if (!empty($otp)) { + $builder->where('clients.otp', $otp); + } + + if (!empty($old_mpin)) { + $builder->where('clients.mpin', $old_mpin); + } + + $retailUserData = $builder->orderBy('clients.id', 'desc')->first(); + } else { + + $builder = $this->clientModel + ->select('clients.*') + ->join('policy_transaction', 'policy_transaction.client_id = clients.id') + ->where('policy_transaction.is_active', 1) + ->where('clients.is_active', 1) + ->where('clients.email', $email_id); + + if (!empty($otp)) { + $builder->where('clients.otp', $otp); + } + + if (!empty($old_mpin)) { + $builder->where('clients.mpin', $old_mpin); + } + + $retailUserData = $builder->orderBy('clients.id', 'desc')->first(); + } + + if ($retailUserData) { + return $this->respond(['status' => 'success', 'data' => $retailUserData,], 200); + } + + return $this->respond(['status' => 'failed', 'message' => 'No employee found.', 'code' => 404, 'data' => [],], 200); + } + + public function updateRetailUserAuthDetails() + { + try { + + log_message('error', 'Retail Auth Update Request Received'); + + $requestData = $this->request->getJSON(); + + $client_id = $requestData->client_id ?? null; + $email_id = $requestData->email_id ?? null; + $mobile_number = $requestData->mobile_number ?? null; + $otp = $requestData->otp ?? null; + $mpin = $requestData->mpin ?? null; + $password = $requestData->password ?? null; + + /** Check if at least one identification exists */ + if (!$client_id && !$email_id && !$mobile_number) { + log_message('error', 'Identification missing: Need client_id or mobile/email.'); + return $this->respond(['status' => false,'message' => 'client_id, email or mobile number is required.']); + } + + /** Find client by ID or Email or Mobile */ + $clientQuery = $this->clientModel->where('is_active', 1); + + if ($client_id) { + $clientQuery->where('id', $client_id); + } elseif ($email_id) { + $clientQuery->where('email', $email_id); + } elseif ($mobile_number) { + $clientQuery->where('phone', $mobile_number); + } + + $clientData = $clientQuery->get()->getRowArray(); + + /** If no client found, return error */ + if (!$clientData) { + log_message('error', 'Client not found for given identifier.'); + return $this->respond(['status' => false,'message' => 'Client not found.']); + } + + /** Now update fields that exist in request */ + $updateData = []; + + if ($otp) { + $updateData['otp'] = $otp; + } + + if ($mpin) { + $updateData['mpin'] = password_hash($mpin, PASSWORD_DEFAULT); // Secure MPIN Hash + } + + if ($password) { + $updateData['password'] = password_hash($password, PASSWORD_DEFAULT); // Secure Password Hash + } + + /** If nothing to update */ + if (empty($updateData)) { + log_message('error', 'No valid fields to update (OTP/MPIN/Password missing)'); + return $this->respond(['status' => false,'message' => 'No valid credentials provided for update.']); + } + + /** Update */ + $updated = $this->clientModel->where('id', $clientData['id'])->set($updateData)->update(); + + if ($updated) { + log_message('error', "Credentials updated successfully for Client ID: {$clientData['id']}"); + return $this->respond(['status' => true,'message' => 'Credentials updated successfully.']); + } else { + log_message('error', "Failed updating credentials for Client ID: {$clientData['id']}"); + return $this->respond(['status' => false,'message' => 'Failed to update credentials.']); + } + + } catch (\Exception $e) { + + log_message('error', 'Exception in updateRetailAuthDetails: ' . $e->getMessage()); + return $this->respond(['status' => false,'message' => 'Unexpected error occurred.','error' => $e->getMessage()], 500); + } + } + + public function getVerifiedRetailUserData() + { + $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedRetailUserData: Received payload = " . json_encode($this->request->getJSON() ?? [])); + + try { + + $mobile_number = isset($this->request->getJSON()->mobile_number) ? $this->request->getJSON()->mobile_number : null; + $email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null; + $otp = isset($this->request->getJSON()->otp) ? $this->request->getJSON()->otp : null; + $client_id = $this->request->getJSON()->client_id ?? null; + + if(empty($otp)){ + return $this->respond(['status' => 'OTP is required','code' => 400,'message' => 'OTP is required'], 200); + } + + if (empty($mobile_number) && empty($email_id)) { + return $this->respond(['status' => 'failed','code' => 400,'message' => 'Mobile number or Email ID is required'], 200); + } + + if (!empty($mobile_number)) { + + $builder = $this->clientModel + ->select('clients.*') + ->join('policy_transaction', 'policy_transaction.client_id = clients.id') + ->where('policy_transaction.is_active', 1) + ->where('clients.is_active', 1) + ->where('clients.phone', $mobile_number); + + if (!empty($otp)) { + $builder->where('clients.otp', $otp); + } + + if (!empty($old_mpin)) { + $builder->where('clients.mpin', $old_mpin); + } + + $retailUserData = $builder->orderBy('clients.id', 'desc')->first(); + } else { + + $builder = $this->clientModel + ->select('clients.*') + ->join('policy_transaction', 'policy_transaction.client_id = clients.id') + ->where('policy_transaction.is_active', 1) + ->where('clients.is_active', 1) + ->where('clients.email', $email_id); + + if (!empty($otp)) { + $builder->where('clients.otp', $otp); + } + + if (!empty($old_mpin)) { + $builder->where('clients.mpin', $old_mpin); + } + + $retailUserData = $builder->orderBy('clients.id', 'desc')->first(); + } + + $lastQuery = $this->clientModel->db->getLastQuery(); + $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedRetailUserData: Last Executed Query: " . $lastQuery); + $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedRetailUserData: retailUserData: " . json_encode($retailUserData ?? [])); + + + if ($retailUserData && isset($this->request->getJSON()->otp) ) + { + $auth = HttpRequestHelper::getRequestInfo(); + if ($auth) { + $data = [ + 'user_id' => $retailUserData['id'], + 'user_type' => 'retail_user', + 'ip' => $auth['ip'], + 'platform' => $auth['platform'], + 'broswer' => $auth['browser'], + ]; + $this->authHistoryModel->insert($data); + } + + $retailUserData['client_id'] = null; + $retailUserData['client_branch_id'] = null; + $retailUserData['emp_code'] = null; + $retailUserData['emp_status'] = null; + $retailUserData['name'] = $retailUserData['client_name']; + $retailUserData['email_corporate'] = $retailUserData['email']; + $retailUserData['mobile'] = $retailUserData['phone']; + $retailUserData['token_type'] = "retail"; + $result = JWTToken::encode($retailUserData); + + if(isset($this->request->getJSON()->otp)){ + $this->clientModel->where('id', $retailUserData['id'])->where('otp', $otp)->set(['otp'=>null])->update(); + $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedRetailUserData: Reset the otp to null"); + } + + + return $this->respond(['status' => 'success','code' => 200,'data' => $result],200); + + } else { + $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedRetailUserData: Employee not verified POST"); + return $this->respond(['status' => 'failed','code' => 404,'data' => "", 'message' => 'Invalid OTP'],200); + } + } catch (\Exception $e) { + $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedRetailUserData: Exception: " . $e->getMessage() . " --- Line: " . $e->getLine() . " --- Trace: " . $e->getTraceAsString()); + return $this->respond(['status' => 'failed','code' => 500,'data' => "", 'message' => "Invalid OTP", 'error' => $e->getMessage()],500); + } + } + } \ No newline at end of file diff --git a/app/Models/ClientModel.php b/app/Models/ClientModel.php index 2397f4df..90a9b1f6 100755 --- a/app/Models/ClientModel.php +++ b/app/Models/ClientModel.php @@ -41,6 +41,7 @@ class ClientModel extends Model "mail_domain", "addon_subheading", "parent_client_id", + "otp", ]; diff --git a/app/Models/PolicyTransactionModel.php b/app/Models/PolicyTransactionModel.php index 1d752149..44a0550d 100644 --- a/app/Models/PolicyTransactionModel.php +++ b/app/Models/PolicyTransactionModel.php @@ -2477,6 +2477,12 @@ pt.id AS id, pt.endorsement_no, pt.ref, + + pt.data_received_date, + pt.renewal_date, + pt.installment, + nhance_branch.branch_name as nhance_branch, + DATE_FORMAT(pt.policy_issue_date, '%d %b %Y') AS policy_issue_date, DATE_FORMAT(pcsd.pt_policy_issue_date, '%b %Y') AS policy_issue_month, pt.month as statement_month, @@ -2559,6 +2565,7 @@ LEFT JOIN user_profiles su ON pt.sales_generated_by = su.id LEFT JOIN user_profiles se ON pt.serviced_by = se.id LEFT JOIN user_profiles created_user ON pt.created_by = created_user.id + LEFT JOIN nhance_branch ON pt.issuer_branch = nhance_branch.id WHERE pt.is_active = 1 AND pcsd.is_active = 1 @@ -2573,6 +2580,12 @@ pt.id AS id, pt.endorsement_no, pt.ref, + + pt.data_received_date, + pt.renewal_date, + pt.installment, + nhance_branch.branch_name as nhance_branch, + DATE_FORMAT(pt.policy_issue_date, '%d %b %Y') AS policy_issue_date, DATE_FORMAT(IF(insq.month IS NULL, pcsd.pt_policy_issue_date, insq.month),'%b %Y') AS policy_issue_month, insq.month as statement_month, @@ -2694,6 +2707,7 @@ LEFT JOIN user_profiles su ON pt.sales_generated_by = su.id LEFT JOIN user_profiles se ON pt.serviced_by = se.id LEFT JOIN user_profiles created_user ON pt.created_by = created_user.id + LEFT JOIN nhance_branch ON pt.issuer_branch = nhance_branch.id WHERE pt.is_active = 1 AND pcsd.is_active = 1 diff --git a/app/Views/client_kyc_2.php b/app/Views/client_kyc_2.php new file mode 100755 index 00000000..8a2ce5ed --- /dev/null +++ b/app/Views/client_kyc_2.php @@ -0,0 +1,322 @@ + + +
| S. No | +Document Name | +File Name | +Action | +
|---|