nhance/app/Controllers/DashboardController.php

626 lines
28 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 = [];
$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();
$businessTeamStatusData = $this->data_construct_for_bds($businessTeamData);
$financeTeamStatusData = $this->data_construct_for_bds($financeTeamData);
$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;
$data['businessTeamStatusData'] = $businessTeamStatusData;
$data['financeTeamStatusData'] = $financeTeamStatusData;
$data['policyStatus'] = $this->policyStatus;
$data['colorShades'] = $this->colorShades;
// print_r($data);die;
$data['page_name'] = 'Dashboard';
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']);
}
public function updatePolicyEnrollmentStatus()
{
$clientPolicyModel = new ClientPolicyModel();
$myLogger = \Config\Services::mylogger();
$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.');
}
}
$myLogger->logme('error', 'enrollment_status function completed');
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();
$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');
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', 'sendRemainderMail function called');
// dd($client_policy_data, $send_mail_for_manual_or_crone);
$reminder_whole_mail = [];
foreach ($client_policy_data as $client_policy) {
if (empty($send_mail_for_manual_or_crone)) {
// 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.*, 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.emp_status', 'draft')
->where('employees.is_active', 1)
->where('employee_polices.status', 'draft')
->where('employee_polices.is_active', 1)
->where('employees.relationship', 'Self')
->findAll();
// dd($employees);
// 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;
$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', 'Notification was not sent for Client Policy ID: ' . $client_policy['id']);
$this->myLogger->logme('error', 'Notification setup not found or not enabled');
}
} else {
$currentDate = date('d');
$remainder_dates = explode(",", $client_policy['reminder_date']);
foreach ($remainder_dates as $date) {
if ($currentDate == $date) {
$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();
// Check if notification should be sent
if ($notification_data && $notification_data['enabled'] == 1 && !empty($notification_data['mail_content'])) {
// echo '4';
$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.*, 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.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;
$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 {
// echo '5';
$this->myLogger->logme('error', 'Notification not sent for client policy ID: ' . $client_policy['id']);
}
}
}
}
}
// dd($reminder_whole_mail);
// Process and queue bulk emails
if (!empty($reminder_whole_mail) && count($reminder_whole_mail) > 0) {
$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]);
}
}
if (count($reminder_whole_mail) > 0) {
return true;
} else {
return false;
}
}
public function sendManualReminder($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);
}
}
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;
}
}