nhance/app/Controllers/DashboardController.php

420 lines
17 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;
class DashboardController extends AdminController
{
use ResponseTrait;
protected $messageModel;
protected $clientModel;
protected $userMessageModel;
protected $clientPolicyModel;
protected $notificationModel;
protected $employeePolicyModel;
protected $policyTransactionModel;
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();
}
public function dashboard()
{
$data = [];
$results = $this->clientModel->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, employees.id as employee_id,
employees.name as employee_name, employees.relationship,
employees.emp_code, employees.emp_status, auth_history.user_type, client_policy.policy_type_id, client_policy.id as client_policy_id')
->join('client_branch', 'clients.id = client_branch.client_id', 'left')
->join('client_policy', 'client_branch.id = client_policy.client_branch_id', 'left')
->join('employees', 'client_branch.id = employees.client_branch_id', 'left')
->join('auth_history', 'employees.id = auth_history.user_id AND "employee" = auth_history.user_type', 'left')
->findAll();
$pendingActionsController = new PendingActionsController;
$pendingActionsData = $pendingActionsController->getPendingActionsForDashBoard();
$businessTeamData = $this->policyTransactionModel->getBusinessReportList();
$financeTeamData = $this->policyTransactionModel->getFinanceReportList();
$groupedData = [];
foreach ($results as $row) {
$clientId = $row['client_id'];
$clientName = $row['client_name'];
$shortName = $row['short_name'];
$branchId = $row['client_branch_id'];
$branchName = $row['branch_name'];
$branchCode = $row['branch_code'];
$clientPolicyId = $row['client_policy_id'];
$policyTypeId = $row['policy_type_id'];
$employeeId = '';
if ($employeeId != $row['employee_id']) {
$employeeId = $row['employee_id'];
} else {
$employeeId = null;
}
$employeeName = $row['employee_name'];
$employeeRelationship = $row['relationship'];
$employeeEmpCode = $row['emp_code'];
$employeeEmpStatus = $row['emp_status'];
$employeeUserType = $row['user_type'];
// Initialize the client entry if it doesn't exist
if (!isset($groupedData[$clientId])) {
$groupedData[$clientId] = [
'client_id' => $clientId,
'client_name' => $clientName,
'short_name' => $shortName,
'branches' => []
];
}
// Initialize the branch entry if it doesn't exist
if (!isset($groupedData[$clientId]['branches'][$branchId])) {
$groupedData[$clientId]['branches'][$branchId] = [
'client_branch_id' => $branchId,
'branch_name' => $branchName,
'branch_code' => $branchCode,
'emp_login' => 0,
'emp_enroll' => 0,
'client_policies' => [],
'employees' => []
];
}
// Add the client policy to the branch's policies list if it exists, not already added, and policyTypeId is not equal to 1
if ($clientPolicyId !== null && $policyTypeId != 1 && !in_array(['client_policy_id' => $clientPolicyId, 'policy_type_id' => $policyTypeId], $groupedData[$clientId]['branches'][$branchId]['client_policies'])) {
$groupedData[$clientId]['branches'][$branchId]['client_policies'][] = [
'client_policy_id' => $clientPolicyId,
'policy_type_id' => $policyTypeId
];
}
// Append employee error to the branch's employees list if relationship is 'Self' and not already added
$employeeKey = $employeeId . '-' . $employeeName; // unique key to identify an employee
if ($employeeId !== null && $employeeRelationship == 'Self' && !isset($groupedData[$clientId]['branches'][$branchId]['employees'][$employeeKey])) {
$groupedData[$clientId]['branches'][$branchId]['employees'][$employeeKey] = [
'employee_id' => $employeeId,
'employee_name' => $employeeName,
'relationship' => $employeeRelationship,
'emp_code' => $employeeEmpCode,
'emp_status' => $employeeEmpStatus,
'user_type' => $employeeUserType
];
if (!empty($employeeUserType)) {
$groupedData[$clientId]['branches'][$branchId]['emp_login']++;
}
// Increment emp_enroll if emp_status is not 'draft'
if ($employeeEmpStatus !== 'draft') {
$groupedData[$clientId]['branches'][$branchId]['emp_enroll']++;
}
}
}
// Re-index the arrays to match the expected structure
foreach ($groupedData as &$client) {
foreach ($client['branches'] as &$branch) {
$branch['employees'] = array_values($branch['employees']);
}
$client['branches'] = array_values($client['branches']);
}
$data['client_branch_emp_list'] = $groupedData;
$session = \Config\Services::session();
$session->set('enrollment_data', json_encode($data));
// echo "<pre>";
$data['pendingActionsData'] = $pendingActionsData;
$data['businessTeamCount'] = count($businessTeamData) ?? 0;
$data['financeTeamCount'] = count($financeTeamData) ?? 0;
// print_r($data);die;
echo view('layout/header');
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']);
}
public function updatePolicyEnrollmentStatus()
{
$clientModel = new ClientModel();
$clientPolicyModel = new ClientPolicyModel();
$notificationModel = new NotificationModel();
$employeePolicyModel = new EmployeePolicyModel();
$myLogger = \Config\Services::mylogger();
// $myLogger->logme('error', 'enrollment_status function called');
$client_policy_data = $clientPolicyModel->getPolicyDetailsForRemainder();
$myLogger->logme('error', 'Fetched client policy data');
// dd($client_policy_data);
$currentDate = date('d');
// $myLogger->logme('error', 'Current date: ' . $currentDate);
// Update policy status based on start and end dates
foreach ($client_policy_data as $client_policy) {
$id = $client_policy['id'];
$openDate = date('d', strtotime($client_policy['open_date']));
$closeDate = date('d', strtotime($client_policy['close_date']));
// $myLogger->logme('error', 'Processing client policy ID: ' . $id);
// $myLogger->logme('error', 'Open date: ' . $openDate . ', Close date: ' . $closeDate);
if ($currentDate == $openDate) {
$clientPolicyModel->update($id, ['open_for_enrollment' => 1]);
$myLogger->logme('error', 'Updated policy ID ' . $id . ' to open for enrollment.');
}
if ($closeDate < $currentDate) {
$clientPolicyModel->update($id, ['open_for_enrollment' => 0]);
$myLogger->logme('error', 'Updated policy ID ' . $id . ' to close for enrollment.');
}
}
// Mail send function
// $myLogger->logme('error', 'Calling sendRemainderMail function');
if( $currentDate == date('d', strtotime($client_policy['reminder_date']))){
$result = $this->sendRemainderMail($client_policy_data);
}else{
$result = false;
}
// $myLogger->logme('error', 'enrollment_status function completed');
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)
{
// $this->myLogger->logme('error', 'sendRemainderMail function called');
$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();
// $this->myLogger->logme('error', 'Notification data fetched: ' . json_encode($notification_data));
// Check if notification should be sent
if ($notification_data && $notification_data['enabled'] == 1 && !empty($notification_data['mail_content'])) {
$this->myLogger->logme('error', 'Notification should be sent for client policy ID: ' . $client_policy['id']);
// Fetch all employees related to the client policy
$employees = $this->employeePolicyModel
->select('employees.*')
->join('employees', 'employee_polices.employee_id = employees.id', 'left')
->where('employee_polices.client_policy_id', $client_policy['id'])
->where('employees.emp_status', 'draft')
->where('employees.is_active', 1)
->where('employee_polices.status', 'draft')
->where('employee_polices.is_active', 1)
->where('employees.relationship', 'Self')
->findAll();
// Process each employee
foreach ($employees as $employee) {
if ($employee['emp_status'] == 'draft' && $employee['relationship'] == 'Self') {
$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;
// 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', 'Notification not sent for client policy ID: ' . $client_policy['id']);
}
}
$this->myLogger->logme('error', 'Whole email, count: ' . $reminder_whole_mail);
// Process and queue bulk emails
$temp_whole_data = [];
$count = 0;
foreach ($reminder_whole_mail as $whole_index => $values) {
foreach ($values as $index => $value) {
$temp_whole_data[] = $value;
$count++;
$this->myLogger->logme('error', 'Queueing email, count: ' . $count);
if ($count == 20 || ($whole_index == count($reminder_whole_mail) - 1 && $index == count($values) - 1)) {
if (!empty($temp_whole_data)) {
Jobs::addJob(['job_name' => 'bulk_mail', 'payload' => $temp_whole_data]);
$this->myLogger->logme('error', 'Added bulk mail job: ' . json_encode($temp_whole_data));
$temp_whole_data = [];
$count = 0;
}
}
}
}
if (count($temp_whole_data) > 0) {
Jobs::addJob(['job_name' => 'bulk_mail', 'payload' => $temp_whole_data]);
$this->myLogger->logme('error', 'Added final bulk mail job: ' . json_encode($temp_whole_data));
return true;
}
if(count($reminder_whole_mail) > 0){
return true;
}else{
return false;
}
}
public function sendManualRemainder($client_id, $client_branch_id)
{
$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);
// 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);
$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);
}
}
}