nhance-enrollment/app/Controllers/DashboardController.php

690 lines
31 KiB
PHP
Executable File

<?php
namespace App\Controllers;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Helpers\sendMailNotification;
use CodeIgniter\API\ResponseTrait;
use App\Models\MessageModel;
use App\Models\UserMessageModel;
use App\Models\ClientModel;
use App\Models\PolicyTransactionModel;
use App\Models\JobModel;
use App\Models\ClientPolicyModel;
use App\Models\NotificationModel;
use App\Models\EmployeePolicyModel;
use App\Controllers\PendingActionsContrller;
use App\Controllers\EmpDataServiceController;
class DashboardController extends AdminController
{
use ResponseTrait;
protected $messageModel;
protected $clientModel;
protected $userMessageModel;
protected $clientPolicyModel;
protected $notificationModel;
protected $employeePolicyModel;
protected $policyTransactionModel;
protected $policyStatus;
protected $colorShades;
protected $myLogger;
public function __construct()
{
set_session_context('Dashboard');
$this->messageModel = new MessageModel();
$this->userMessageModel = new UserMessageModel();
$this->clientPolicyModel = new ClientPolicyModel();
$this->notificationModel = new NotificationModel();
$this->employeePolicyModel = new EmployeePolicyModel();
$this->clientModel = new ClientModel();
$this->policyTransactionModel = new PolicyTransactionModel();
$this->myLogger = \Config\Services::mylogger();
$this->policyStatus = [
'under_process' => 'Under Process',
'client_pending' => 'Client Pending',
'insurer_pending' => 'Insurer Pending',
'co_insurer_pending' => 'Co-Insurer Pending',
'tpa_pending' => 'TPA Pending',
'validated' => 'Validated',
'cancelled' => 'Cancelled',
'instalment_pending' => 'Instalment Pending',
'completed' => 'Completed',
];
$this->colorShades = [
[
'linear-gradient(45deg, #66e9eb, #5cc7d2)', // Lighter shade 1
'linear-gradient(45deg, #4ce2e5, #45bcc9)', // Lighter shade 2
'linear-gradient(45deg, #33dbe0, #2baebd)', // Original shade (slightly lighter)
'linear-gradient(45deg, #00d6db, #00a8b5)', // Original
'linear-gradient(45deg, #00bfc4, #00929f)', // Darker shade 1
'linear-gradient(45deg, #009ea1, #00767a)' // Darker shade 2
],
// Shades for Grenadier
[
'linear-gradient(45deg, #ff9d37, #ff7a10)', // Grenadier shade 1
'linear-gradient(45deg, #ff8b30, #ff7310)', // Grenadier shade 2
'linear-gradient(45deg, #ff8020, #ff5a00)', // Grenadier shade 3
'linear-gradient(45deg, #f06d15, #e05505)', // Grenadier shade 4
'linear-gradient(45deg, #d85f10, #c04805)', // Grenadier shade 5
'linear-gradient(45deg, #b85606, #a04605)' // Grenadier shade 6
],
// Shades for SilverChalice
[
'linear-gradient(45deg, #a3a8a8, #8f9494)', // SilverChalice shade 1
'linear-gradient(45deg, #989d9d, #848989)', // SilverChalice shade 2
'linear-gradient(45deg, #7e8484, #686e6e)', // SilverChalice shade 3
'linear-gradient(45deg, #6c7676, #545e5e)', // SilverChalice shade 4
'linear-gradient(45deg, #5c6363, #434949)', // SilverChalice shade 5
'linear-gradient(45deg, #494f4f, #353d3d)' // SilverChalice shade 6
]
];
}
public function dashboard()
{
$data['page_name'] = 'Dashboard';
$db = db_connect();
$sql = "SELECT
clients.id AS client_id,
clients.client_name,
clients.short_name,
client_branch.id AS client_branch_id,
client_branch.branch_name,
client_branch.branch_code,
COUNT(employees.id) AS total_employees,
SUM(CASE WHEN employees.emp_status = 'draft' THEN 1 ELSE 0 END) AS draft_count,
SUM(CASE WHEN employees.emp_status IN ('enrolled', 'active') THEN 1 ELSE 0 END) AS enrolled_count,
SUM(CASE WHEN auth_history.user_id IS NOT NULL THEN 1 ELSE 0 END) AS logged_in_count,
SUM(CASE WHEN auth_history.user_id IS NULL THEN 1 ELSE 0 END) AS not_logged_in_count,
CASE
WHEN EXISTS (
SELECT 1 FROM client_policy
WHERE client_policy.client_branch_id = client_branch.id
AND client_policy.is_active = 1
AND client_policy.open_for_enrollment = 1
) THEN 1
ELSE 0
END AS open_or_close_enrollment
FROM clients
LEFT JOIN client_branch ON clients.id = client_branch.client_id
LEFT JOIN employees ON client_branch.id = employees.client_branch_id
LEFT JOIN (
SELECT user_id, user_type
FROM auth_history
WHERE user_type = 'employee'
GROUP BY user_id
) AS auth_history ON employees.id = auth_history.user_id
WHERE employees.relationship = 'Self'
AND employees.emp_status IN ('draft', 'enrolled', 'active')
AND employees.is_active = 1
AND clients.is_active = 1
AND client_branch.is_active = 1
GROUP BY clients.id, client_branch.id";
$query = $db->query($sql);
$results = $query->getResultArray();
$data['client_branch_emp_list'] = $results;
$session = \Config\Services::session();
$session->set('enrollment_data', json_encode($data));
// $pendingActionsController = new PendingActionsController;
// $pendingActionsData = $pendingActionsController->getPendingActionsForDashBoard();
// $businessTeamData = $this->policyTransactionModel->getBusinessReportList();
// $financeTeamData = $this->policyTransactionModel->getFinanceReportList();
// $businessTeamStatusData = $this->data_construct_for_bds($businessTeamData);
// $financeTeamStatusData = $this->data_construct_for_bds($financeTeamData);
// $data['pendingActionsData'] = $pendingActionsData;
// $data['businessTeamCount'] = count($businessTeamData) ?? 0;
// $data['financeTeamCount'] = count($financeTeamData) ?? 0;
// $data['businessTeamStatusData'] = $businessTeamStatusData;
// $data['financeTeamStatusData'] = $financeTeamStatusData;
// $data['policyStatus'] = $this->policyStatus;
// $data['colorShades'] = $this->colorShades;
// dd($data);
echo view('layout/header', $data);
echo view('DashBoard', $data);
echo view('layout/footer');
}
public function getDashboardNotifications()
{
// Pull notifications for the dashboard, especially for file upload cases.
$userId = get_session_userid();
$roleId = 5;
$teamId = 1;
if ($userId != null && $roleId != null && $teamId != null) {
$messages = $this->messageModel->getMessagesForUser($userId, $roleId, $teamId);
return $this->respond(['status' => true, 'code' => 200, 'message' => $messages], 200);
} else {
$this->myLogger->logme('error', 'The session is not set correctly. USER_ID : {user_id}, ROLE_ID : {role_id}, TEAM_ID : {team_id}', ['user_id' => $userId, 'role_id' => $roleId, 'team_id' => $teamId]);
return $this->respond(['status' => false, 'code' => 404, 'message' => 'No data found'], 200);
}
}
public function acknowledgeMessage($messageId)
{
$userId = get_session_userid();
$this->userMessageModel->markAsRead($userId, $messageId);
return $this->respond(['status' => 'success']);
}
//--------------- FOR CRONE JOB -----------------------------------------------------------------------------------------
public function updatePolicyEnrollmentStatus()
{
$clientPolicyModel = new ClientPolicyModel();
$myLogger = \Config\Services::mylogger();
$myLogger->logme('error', 'update Policy Enrollment Status Function called');
$myLogger->logme('error', 'OPEN OR CLOSE FOR ENROLLMENT UPDATE START TIME {{ ' . date('d-m-Y H:i:s a') . ' }}');
$client_policy_data = $clientPolicyModel->getPolicyDetailsForEnrollment();
$myLogger->logme('error', 'Fetched client policy data for Enrollment Status update');
// dd($client_policy_data);
$currentDate = date('d-m-Y');
$openEnrollment = [];
$closeEnrollment = [];
// Update policy status based on start and end dates
foreach ($client_policy_data as $client_policy) {
$id = $client_policy['id'];
$openDate = date('d-m-Y', strtotime($client_policy['open_date']));
$closeDate = date('d-m-Y', strtotime($client_policy['close_date']));
if ($currentDate == $openDate) {
$clientPolicyModel->update($id, ['open_for_enrollment' => 1]);
$openEnrollment[] = $id;
// $myLogger->logme('error', 'Updated policy ID ' . $id . ' to open for enrollment.');
}
if ($closeDate < $currentDate) {
$clientPolicyModel->update($id, ['open_for_enrollment' => 0]);
$closeEnrollment[] = $id;
// $myLogger->logme('error', 'Updated policy ID ' . $id . ' to close for enrollment.');
}
}
$this->myLogger->logme('info', 'Policy Enrollment Status Update: ' . json_encode([
'status' => true,
'message' => 'Updated Policy Enrollment Status',
'open_policy_count' => count($openEnrollment),
'close_policy_count' => count($closeEnrollment),
'open_policy_ids' => $openEnrollment,
'close_policy_ids' => $closeEnrollment,
], JSON_PRETTY_PRINT));
$myLogger->logme('error', 'update Policy Enrollment Status Function completed');
$myLogger->logme('error', 'OPEN OR CLOSE FOR ENROLLMENT UPDATE END TIME {{ ' . date('d-m-Y H:i:s a') . ' }}');
return $this->respond([
'status' => true,
'message' => 'updated Policy Enrollment Status',
'open_policy_count' => count($openEnrollment),
'close_policy_count' => count($closeEnrollment),
'open_policy_ids' => $openEnrollment,
'close_policy_ids' => $closeEnrollment,
]);
}
public function sendCroneRemainderMail()
{
$clientPolicyModel = new ClientPolicyModel();
$myLogger = \Config\Services::mylogger();
$myLogger->logme('error', 'SEND REMINDER MAIL FUNCTION START TIME {{ ' . date('d-m-Y H:i:s a') . ' }}');
$client_policy_data = $clientPolicyModel->getPolicyDetailsForRemainder();
$myLogger->logme('error', 'Fetched client policy data');
// dd($client_policy_data);
// Mail send function
$result = $this->sendRemainderMail($client_policy_data, 'crone');
$myLogger->logme('error', 'sendCroneRemainderMail function completed');
$myLogger->logme('error', 'SEND REMINDER MAIL FUNCTION END TIME {{ ' . date('d-m-Y H:i:s a') . ' }}');
if($result){
return json_encode(['status' => true, 'message' => 'Mail send successfully']);
}else{
return json_encode(['status' => false, 'message' => 'There is no data to send']);
}
}
//--------------------------------------------------------------------------------------------------------
public function featch_dashboard_data($type)
{
$pendingActionsController = new PendingActionsController;
$pendingActionsData = $pendingActionsController->getPendingActionsForClientData();
$data = [];
if($type == 'insurer'){
$data = $pendingActionsData['uhid'];
}else if($type == 'TPA'){
$data = $pendingActionsData['tpa'];
}else if($type == 'I'){
$data = $pendingActionsData['inception'];
}else if($type == 'D'){
$data = $pendingActionsData['deletion'];
}else if($type == 'C'){
$data = $pendingActionsData['correction'];
}else if($type == 'SI'){
$data = $pendingActionsData['si_enhancement'];
}else if($type == 'policy'){
$data = $pendingActionsData['policy'];
}else if($type == 'ticket'){
$data = $pendingActionsData['uhid'];
}
return $this->respond(['status' => true, 'data' => $data], 200);
}
public function sendRemainderMail($client_policy_data, $send_mail_for_manual_or_crone = null)
{
$this->myLogger->logme('error', 'send Remainder Mail function called');
// dd($client_policy_data, $send_mail_for_manual_or_crone);
$reminder_whole_mail = [];
foreach ($client_policy_data as $client_policy) {
// Fetch client data
$client_data = $this->clientModel->find($client_policy['client_id']);
// Fetch notification settings
$notification_data = $this->notificationModel
->where('client_id', $client_policy['client_id'])
->where('template_name', 'member_reminder_mail')
->first();
if ($notification_data && $notification_data['enabled'] == 1 && !empty($notification_data['mail_content'])) {
//manaual
if (empty($send_mail_for_manual_or_crone)) {
// Check if notification should be sent
$this->myLogger->logme('error', 'Notification should be sent for client policy ID: ' . $client_policy['id']);
$employees = [];
if (in_array($client_policy['policy_type_id'], [2, 4]) || ($client_policy['policy_type_id'] == 3 && $client_policy['is_addon'] == 1)) {
// Fetch all employees related to the client policy
$employees = $this->employeePolicyModel
->select('employees.*, employee_polices.id as emp_policy_id')
->join('employees', 'employee_polices.employee_id = employees.id', 'left')
->where('employee_polices.client_policy_id', $client_policy['id'])
->where('employees.is_active', 1)
->where('employee_polices.is_active', 1)
->where('employees.emp_status', 'draft')
->where('employee_polices.status', 'draft')
->where('employees.relationship', 'Self')
->where("employees.email_corporate IS NOT NULL AND employees.email_corporate != ''")
->findAll();
// dd($employees, 'first');
} else if (($client_policy['policy_type_id'] == 3 && $client_policy['is_addon'] == 3) || $client_policy['policy_type_id'] == 5) {
$empDependentData = $this->employeePolicyModel
->select('employees.*, employee_polices.id as emp_policy_id')
->join('employees', 'employee_polices.employee_id = employees.id', 'left')
->where('employee_polices.client_policy_id', $client_policy['id'])
->where('employees.is_active', 1)
->where('employee_polices.is_active', 1)
->where('employees.emp_status', 'draft')
->where('employee_polices.status', 'draft')
->where('employees.relationship !=', 'Self')
->findAll();
$empCodes = array_column($empDependentData, 'emp_code');
// dd($empDependentData, $empCodes,'second');
if (!empty($empCodes)) {
$empSelfData = $this->employeePolicyModel
->select('employees.*, employee_polices.id as emp_policy_id')
->join('employees', 'employee_polices.employee_id = employees.id', 'left')
->whereIn('employees.emp_code', $empCodes)
->where('employees.is_active', 1)
->where('employee_polices.is_active', 1)
->where('employees.relationship', 'Self')
->where("employees.email_corporate IS NOT NULL AND employees.email_corporate != ''")
->findAll();
$employees = array_merge($employees, $empSelfData);
}
}
// dd($employees);
// Process each employee
if (!empty($employees) && count($employees) > 0) {
foreach ($employees as $employee) {
$this->myLogger->logme('error', 'Employee status and relationship check passed for employee ID: ' . $employee['id']);
// Mail params
$params['emp_data'] = $employee;
$params['client_data'] = $client_data;
$params['notification_data'] = $notification_data;
$params['common'] = [
'client_id' => $client_policy['client_id'],
'client_branch_id' => $client_policy['client_branch_id'],
'client_policy_id' => $client_policy['id'],
'employee_policy_id' => $employee['emp_policy_id'],
'employee_id' => $employee['id'],
'mail_type' => 'member_reminder_mail',
];
// Send the mail notification
$mail_result = sendMailNotification::sendMailNotification('member_reminder_mail', $params);
// dd($mail_result);
// $this->myLogger->logme('error', 'Mail sent result: ' . json_encode($mail_result));
$reminder_whole_mail[] = $mail_result;
}
}
} else { // crone
if (!empty($client_policy['reminder_date'])) {
$currentDate = date('d');
$remainder_dates = explode(",", $client_policy['reminder_date']);
foreach ($remainder_dates as $date) {
if ($currentDate == $date) {
$this->myLogger->logme('error', 'Notification should be sent for client policy ID: ' . $client_policy['id']);
// Fetch all employees related to the client policy
$employees = [];
if (in_array($client_policy['policy_type_id'], [2, 4]) || ($client_policy['policy_type_id'] == 3 && $client_policy['is_addon'] == 1)) {
$employees = $this->employeePolicyModel
->select('employees.*, employee_polices.id as emp_policy_id')
->join('employees', 'employee_polices.employee_id = employees.id', 'left')
->where('employee_polices.client_policy_id', $client_policy['id'])
->where('employees.is_active', 1)
->where('employee_polices.is_active', 1)
->where('employees.emp_status', 'draft')
->where('employee_polices.status', 'draft')
->where('employees.relationship', 'Self')
->where("employees.email_corporate IS NOT NULL AND employees.email_corporate != ''")
->findAll();
// dd($employees, 'first');
} else if (($client_policy['policy_type_id'] == 3 && $client_policy['is_addon'] == 3) || $client_policy['policy_type_id'] == 5) {
$empDependentData = $this->employeePolicyModel
->select('employees.*, employee_polices.id as emp_policy_id')
->join('employees', 'employee_polices.employee_id = employees.id', 'left')
->where('employee_polices.client_policy_id', $client_policy['id'])
->where('employees.is_active', 1)
->where('employee_polices.is_active', 1)
->where('employees.emp_status', 'draft')
->where('employee_polices.status', 'draft')
->where('employees.relationship !=', 'Self')
->findAll();
$empCodes = array_column($empDependentData, 'emp_code');
// dd($empDependentData, $empCodes,'second');
if (!empty($empCodes)) {
$empSelfData = $this->employeePolicyModel
->select('employees.*, employee_polices.id as emp_policy_id')
->join('employees', 'employee_polices.employee_id = employees.id', 'left')
->whereIn('employees.emp_code', $empCodes)
->where('employees.is_active', 1)
->where('employee_polices.is_active', 1)
->where('employees.relationship', 'Self')
->where("employees.email_corporate IS NOT NULL AND employees.email_corporate != ''")
->findAll();
$employees = array_merge($employees, $empSelfData);
}
}
// dd($employees);
// Process each employee
foreach ($employees as $employee) {
$this->myLogger->logme('error', 'Employee status and relationship check passed for employee ID: ' . $employee['id']);
// Mail params
$params['emp_data'] = $employee;
$params['client_data'] = $client_data;
$params['notification_data'] = $notification_data;
$params['common'] = [
'client_id' => $client_policy['client_id'],
'client_branch_id' => $client_policy['client_branch_id'],
'client_policy_id' => $client_policy['id'],
'employee_policy_id' => $employee['emp_policy_id'],
'employee_id' => $employee['id'],
'mail_type' => 'member_reminder_mail',
];
// Send the mail notification
$mail_result = sendMailNotification::sendMailNotification('member_reminder_mail', $params);
// $this->myLogger->logme('error', 'Mail sent result: ' . json_encode($mail_result));
$reminder_whole_mail[] = $mail_result;
}
}
}
} else {
$this->myLogger->logme('error', "send Remainder crone --- Remainder date is empty()");
}
}
} else {
$this->myLogger->logme('error', 'Notification setup not found or not enabled');
$this->myLogger->logme('error', 'Notification was not sent for this Client ID: ' . $client_policy['client_id']);
}
}
// dd($reminder_whole_mail, count($reminder_whole_mail));
// print_rr($reminder_whole_mail); die;
// Process and queue bulk emails
if (!empty($reminder_whole_mail) && count($reminder_whole_mail) > 0) {
$this->myLogger->logme('error', 'Remainder mail count: ' . count($reminder_whole_mail));
$reminder_whole_mail = array_chunk($reminder_whole_mail, 20);
foreach ($reminder_whole_mail as $key => $value) {
// $job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'bulk_mail', 'payload' => $value]);
$this->myLogger->logme('error', 'Bulk mail upload jobs completed successfully. Total: ' . count($value));
}
$this->myLogger->logme('error', 'Remainder mails sent successfully');
}else{
$this->myLogger->logme('error', "No reminder mail sent.");
}
$this->myLogger->logme('error', 'send Remainder Mail function completed');
// dd($reminder_whole_mail);
$mailCount = count($reminder_whole_mail);
if ($mailCount > 0) {
return true;
} else {
return false;
}
}
public function sendManualReminder($client_id, $client_branch_id, $client_policy_id = null)
{
$this->myLogger->logme('error','Log Works');
$this->myLogger->logme('error', "sendManualRemainder called with client_id: {$client_id}, client_branch_id: {$client_branch_id}");
$client_policy_data = $this->clientPolicyModel->getPolicyDetailsForRemainder($client_id, $client_branch_id, $client_policy_id);
// print_r($client_policy_data); die;
// print_r($this->clientPolicyModel->getLastQuery()); die;
// $this->myLogger->logme('error', "Policy details fetched: " . json_encode($client_policy_data));
if ($client_policy_data) {
$result = $this->sendRemainderMail($client_policy_data);
log_message('error',json_encode($result));
$this->myLogger->logme('error',$result);
$this->myLogger->logme('error', "Manual Remainder Mail sending result: " . ($result ? 'success' : 'failure'));
if ($result) {
$this->myLogger->logme('error', 'Manual Remainder Mail sent successfully');
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Mail sent successfully'], 200);
} else {
$this->myLogger->logme('error', 'Failed to send manual remainder mail, no data to send');
return $this->respond(['status' => false, 'code' => 200, 'message' => 'There is no data to send','message2' => 'Failed' ], 200);
}
} else {
$this->myLogger->logme('error', 'No policy data found to send');
return $this->respond(['status' => false, 'code' => 200, 'message' => 'There is no data to send', 'message2' => 'No policy data found to send'], 200);
}
}
public function sendManualEcard($client_id, $client_branch_id, $policy_id)
{
$this->myLogger->logme('error', "sendManualEcard called with client_id: {$client_id}, client_branch_id: {$client_branch_id}, policy id : {$policy_id}");
$notification = $this->notificationModel->where('client_id', $client_id)->where('template_name', 'member_ecard_mail')->first();
// print_r(($notification)); die;
if($notification && $notification['enabled'] == 0 && $notification['mail_content'] == '')
{
return $this->respond(['status' => false, 'code' => 400, 'message' => 'No template found','message2' => 'Failed' ], 200);
}
$emp_data = $this->employeePolicyModel->getEmployeePolicyForEcard($policy_id);
if(count($emp_data) == 0)
{
return $this->respond(['status' => false, 'code' => 400, 'message' => 'No employees found','message2' => 'Failed' ], 200);
}
$ids = array_column($emp_data, 'id');
// print_r(($ids)); die;
// print_r($this->clientPolicyModel->getLastQuery()); die;
// $this->myLogger->logme('error', "Policy details fetched: " . json_encode($client_policy_data));
Jobs::addJob(['job_name' => 'sendMailForDownloadingECard', 'payload' => $ids]);
// $empEmpDataServiceController = new EmpDataServiceController();
// $empEmpDataServiceController->sendMailForDownloadingECard($ids);
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Mail Queued'], 200);
}
public function data_construct_for_bds($data)
{
$groupedData = [
'under_process' => [],
'client_pending' => [],
'insurer_pending' => [],
'co_insurer_pending' => [],
'tpa_pending' => [],
'validated' => [],
'cancelled' => [],
'instalment_pending' => [],
'completed' => [],
];
// Loop through results and group them by their status
foreach ($data as $row) {
switch ($row['status']) {
case 'completed':
$groupedData['completed'][] = $row;
break;
case 'cancelled':
$groupedData['cancelled'][] = $row;
break;
case 'client_pending':
$groupedData['client_pending'][] = $row;
break;
case 'insurer_pending':
$groupedData['insurer_pending'][] = $row;
break;
case 'co_insurer_pending':
$groupedData['co_insurer_pending'][] = $row;
break;
case 'tpa_pending':
$groupedData['tpa_pending'][] = $row;
break;
case 'validated':
$groupedData['validated'][] = $row;
break;
case 'instalment_pending':
$groupedData['instalment_pending'][] = $row;
break;
default:
$groupedData['under_process'][] = $row;
break;
}
}
return $groupedData;
}
}