diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 013d4413..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"); 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 705081cd..859b51d1 100755 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -4795,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/Views/employee_upload.php b/app/Views/employee_upload.php index 94e6b240..5732111a 100755 --- a/app/Views/employee_upload.php +++ b/app/Views/employee_upload.php @@ -1071,6 +1071,128 @@ function checkPolicyTermsAndRackRatesHasDefiend(event) } +function checkWellnessOnboardStatus(event) +{ + // console.log(event.target.id); + var policy_id = (event.target.value); + console.log('checkWellnessOnboardStatus called ' + policy_id); + if(policy_id != 0 && policy_id != " " && policy_id != undefined) + { + var apiURL = '' + 'checkWellnessOnboardStatus/' + policy_id; + // console.log(apiURL); + + $('.loader').fadeIn(); + $('.loader-mask').fadeIn(); + + $.ajax({ + url: apiURL, + method: 'GET', + headers: { + "Content-Type": "application/json", + "X-Requested-With": "XMLHttpRequest" + }, + success: function(response) { + + setTimeout(function() { + $('.loader').fadeOut(); + $('.loader-mask').delay(350).fadeOut('slow'); + }, 300); + + console.log('check wellness response', response); + if(response.data && response.data != 0) + { + var btn_txt = 'click here to onboard ('+ response.data +') employees to Visit wellness'; + $("#on_board_btn_txt").attr("data-id", response.data); + $('#on_board_btn_txt').text(btn_txt); + $('#onboard_div').show(); + + } + else + { + console.log('wellness button remains disabled'); + $('#onboard_div').hide(); + $('#on_board_btn_txt').text(""); + } + }, + error: function(xhr, status, error) { + setTimeout(function() { + $('.loader').fadeOut(); + $('.loader-mask').delay(350).fadeOut('slow'); + }, 300); + // toastr.error('Something went wrong! Try Later', 'Error'); + console.error('Error fetching data from checkPolicyTermsAndRackRatesHasDefiend API:', error); + return false; + } + }); + } + +} + +function initiateWellnessOnboard(e) +{ + + var empCount = $("#on_board_btn_txt").data("id"); + if (confirm("Are you sure? You are about to onboard " + empCount + " employees to Visit wellness program.")) { + + // user clicked OK + console.log("onboard Confirmed"); + } else { + // user clicked Cancel + console.log("onboard Cancelled"); + return false; + } + + // return false; + + // console.log(event.target.id); + var policy_id = document.getElementById('policy').value; + console.log('initiateWellnessOnboard called ' + policy_id); + if(policy_id != 0 && policy_id != " " && policy_id != undefined) + { + var apiURL = '' + 'initiateWellnessOnboard/' + policy_id; + // console.log(apiURL); + + $('.loader').fadeIn(); + $('.loader-mask').fadeIn(); + + $.ajax({ + url: apiURL, + method: 'GET', + headers: { + "Content-Type": "application/json", + "X-Requested-With": "XMLHttpRequest" + }, + success: function(response) { + + setTimeout(function() { + $('.loader').fadeOut(); + $('.loader-mask').delay(350).fadeOut('slow'); + }, 300); + + console.log('initiate wellness response', response); + toastr.success(response.message, 'SUCCESS'); + $('#onboard_div').hide(); + + }, + error: function(xhr, status, error) { + setTimeout(function() { + $('.loader').fadeOut(); + $('.loader-mask').delay(350).fadeOut('slow'); + }, 300); + // toastr.error('Something went wrong! Try Later', 'Error'); + console.error('Error initiate data from initiateWellnessOnboard API:', error); + toastr.error(error, 'Error'); + return false; + } + }); + }else{ + + toastr.error('Please select policy to initiate wellness onboard', 'Error'); + return false; + } + +} + function checkValues() { diff --git a/app/Views/insurer_or_tpa_data.php b/app/Views/insurer_or_tpa_data.php index 902e5419..60efbcb4 100755 --- a/app/Views/insurer_or_tpa_data.php +++ b/app/Views/insurer_or_tpa_data.php @@ -49,7 +49,7 @@