nhance-enrollment/app/Controllers/EmployeeController.php
2026-05-27 11:10:51 +05:30

3042 lines
138 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\DepositHelper;
use App\Models\EmployeeModel;
use App\Models\EmployeePolicyModel;
use App\Models\ClientModel;
use App\Models\ClientBranchModel;
use App\Models\PolicesModel;
use App\Models\FileModel;
use App\Models\BatchListModel;
use App\Models\BatchFileModel;
use App\Models\EmpEndorsementModel;
use App\Models\ClientPolicyModel;
use App\Models\TPAModel;
use App\Models\InsurerExcelExportTemplateModel;
use App\Models\InsurerModel;
use App\Models\ClientDepositModel;
use App\Models\PolicyPremium2Model;
use App\Models\AuditHistoryModel;
use App\Models\UserModel;
use App\Models\HrFileUploadModel;
use App\Controllers\Jobs;
use App\Controllers\JobWorker;
use App\Controllers\Jobs\SubJob;
use App\Controllers\EmployeeServiceController;
use App\Controllers\EmpDataServiceController;
use CodeIgniter\API\ResponseTrait;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use Dompdf\Dompdf;
use Dompdf\Options;
use Kint;
class EmployeeController extends AdminController
{
use ResponseTrait;
protected $myLogger;
protected $employeeModel;
protected $employeePolicyModel;
protected $clientModel;
protected $clientBranchModel;
protected $fileModel;
protected $batchListModel;
protected $batchFileModel;
protected $empEndorsementModel;
protected $clientPolicyModel;
protected $TPAModel;
protected $policiesModel;
protected $excelExportTemplateModel;
protected $insurerModel;
protected $cashDepositModel;
protected $PolicyPremium2Model;
protected $auditHistory;
protected $userModel;
protected $hrFileUploadModel;
public function __construct()
{
// helper('utility');
set_session_context('Employee');
$this->myLogger = \Config\Services::mylogger();
$this->employeeModel = new EmployeeModel();
$this->employeePolicyModel = new EmployeePolicyModel();
$this->clientModel = new ClientModel();
$this->clientBranchModel = new ClientBranchModel();
$this->fileModel = new FileModel();
$this->batchListModel = new BatchListModel();
$this->batchFileModel = new BatchFileModel();
$this->empEndorsementModel = new EmpEndorsementModel();
$this->clientPolicyModel = new ClientPolicyModel();
$this->TPAModel = new TPAModel();
$this->policiesModel = new PolicesModel();
$this->insurerModel = new InsurerModel();
$this->cashDepositModel = new ClientDepositModel();
$this->PolicyPremium2Model = new PolicyPremium2Model();
$this->auditHistory = new AuditHistoryModel();
$this->userModel = new userModel();
$this->hrFileUploadModel = new HrFileUploadModel();
}
public function list()
{
// $model = new UserModel();
$data = [];
// $data['status'] = ['draft' => 'Draft', 'enrolled' => 'Enrolled', 'active' => 'Active', 'inactive' => 'In-Active', 'pending' => 'Pending'];
$data['status'] = ['draft' => 'Draft', 'enrolled' => 'Enrolled'];
if (count($this->request->getGet())) {
$filterData = $this->request->getGet();
// Convert the status field to an array if it exists in the request data
if (isset($filterData['status']) && !empty($filterData['status'])) {
// $filterData['status'] = explode(",", $filterData['status']);
}else{
$filterData['status'] = [];
}
// Fetch employees with the modified $filterData array
$data['employees'] = $this->employeePolicyModel->getEmployeePolicy(
client_id: $filterData['client_id'] ?? null,
policy_id: $filterData['policy_id'] ?? null,
branch_id: $filterData['branch_id'] ?? null,
emp_code : $filterData['emp_code'] ?? null,
emp_name : $filterData['emp_name'] ?? null,
status : $filterData['status'] ?? [],
);
// log_message('error',json_encode($data['employees']));
// Set getData in $data array with the processed $filterData
$data['getData'] = $filterData;
$html = view('employee_data_list', $data);
return $this->respond(['status' => true, 'html' => $html], 200);
}
// dd($this->employeeModel->getLastQuery());
// dd( $data['getData']);
// dd($this->request->getGet());
$this->myLogger->logme('error', 'list called');
$this->loadLayout('employee_list', $data);
}
public function getClientWithPolicies()
{
//echo $this->request->isAJAX();die();
$result = $this->clientModel->clientsWithPolicies();
// dd($result);
// print_r($result);die();
if (!count($result)) {
return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'no data found'], 200);
} else {
return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $result], 200);
}
}
public function getUploadedFileError()
{
$file_id = $this->request->uri->getSegment(3);
// dd($segments[2]);
// die();
// $file_id = $this->request->getGet();
// echo $file_id;die();
$file = $this->fileModel->find($file_id);
// print_r($result);die();
if (!isset($file)) {
return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'no data found'], 200);
} else {
return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $file['reason']], 200);
}
}
//handles employee & dependent bulk upload with events like inception,addition,deletion, correction and SI enhancements
public function employeesUplodWithEvents($post_data = [])
{
if(empty($post_data)){
$post_data = $this->request->getPost();
$post_data = array_merge($post_data, $this->request->getFiles());
$is_post_request = true;
}else{
$is_post_request = false;
}
// $empDataServiceController = new EmpDataServiceController();
// !dd($empDataServiceController->importInceptionUpdateTPAandUHID(['file_id' => 79]));
// $job_details = new Jobs();
// $r = Jobs::addJob(['job_name' => 'add','payload' => ['a' => 10, 'b' => 35]]);
// print_r($r);//die();
// // $jobWorker = new JobWorker();
// JobWorker::processJob($r);
// die();
// echo $this->request->getMethod();die();
// print_r($this->request->getFiles('emplist'));print_r($this->request->getPost('emplist'));
// print_r($this->request->getPost('clients'));
// print_r($this->request->getPost('policies'));
// print_r($this->request->getPost('upload-action-type'));
// die();
// $empServiceController = new EmployeeServiceController();
// $res = $empServiceController->excelFileFormatValidation(['file_id' => '42']);
// dd($res);
// $empServiceController = new EmployeeServiceController();
// $res = $empServiceController->employeeDisembark(['file_id' => '586']);
// dd($res);
// $existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(client_policy_id: '2');
// dd($existing_famility_details);
// $empServiceController = new EmployeeServiceController();
// $res = $empServiceController->employeesSIEnhanceProcess(['file_id' => '38']);
// dd($res);
// $empServiceController = new EmployeeServiceController();
// $res = $empServiceController->employeesCorrectionProcess(['file_id' => '37']);
// // dd($res);
// $empServiceController = new EmployeeServiceController();
// $res = $empServiceController->employeesOnboardPreprocess(['client_policy_id' => '3']);
// dd($res);
// $empServiceController = new EmployeeServiceController();
// $res = $empServiceController->employeeDisembark(['file_id' => '36']);
// dd($res);
// if(isset($res['error_summary']) && count($res['error_summary']))
// {
// $res['error_summary'] = (array_count_values($res['error_summary']));
// $failure_reason = ((json_encode($res)));
// // dd($failure_reason);
// $this->fileModel->where('id', '12')->set(['status' => 'failed','reason' => $failure_reason])->update();
// dd($failure_reason);
// }
// $this->truncateFileData(747, 5) ;
// print_rr($this->cloneWorksheet());
// die();
// old
// if ($this->request->getMethod() == 'post') {
// //validate uploaded file
// $filename = '';
// $fileSize = '';
// $validated = $this->validate([
// 'emplist' => [
// 'uploaded[emplist]',
// 'mime_in[emplist,application/vnd.ms-excel,application/vnd,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.oasis.opendocument.spreadsheet]',
// 'max_size[emplist,16384]',
// ],
// ]);
// if ($validated)
// {
// $avatar = $this->request->getFile('emplist');
// if (!$avatar) {
// $this->myLogger->logme("error", 'File not found');
// return $this->respond(['dataStatus' => false, 'code' => 400, 'message' => 'File not found'], 400);
// }
// $is_moved = $avatar->move(WRITEPATH . 'uploads/excel/');
// if ($is_moved) {
// $filename = $avatar->getName();
// $fileSize = $avatar->getSize(); // File size in bytes
// $fileSize = $fileSize / (1024 * 1024); // Convert to MB
// // Handle successful upload, e.g., log success or further processing
// $this->myLogger->logme("error", 'File move successful');
// } else {
// $this->myLogger->logme("error", 'File move failed');
// return $this->respond(['dataStatus' => false, 'code' => 500, 'message' => 'File move failed'], 500);
// }
// } else {
// $this->myLogger->logme("error", 'Upload failed Invalid file');
// return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'Invalid file'], 404);
// }
// //process post variable entry in file table
// $loggedInUserID = get_session_userid();
// // dd($loggedInUserID);
// // $loggedInUserID = 8;
// $client_id = $this->request->getPost('client_id');
// $policy_id = $this->request->getPost('policy_id');
// $branch_id = $this->request->getPost('branch_id');
// $enrollment_open_date = $this->request->getPost('enrollment_open_date');
// $enrollment_close_date = $this->request->getPost('enrollment_close_date');
// $action = $this->request->getPost('upload-action-type');
// $status = 'inprogress';
// $enrollment_open_date = change_date_format($enrollment_open_date, 'd/m/Y', 'Y-m-d');
// $enrollment_close_date = change_date_format($enrollment_close_date, 'd/m/Y', 'Y-m-d');
// $file_id = $this->fileModel->insert(['file_name' => $filename, 'client_id' => $client_id, 'policy_id' => $policy_id, 'created_by' => $loggedInUserID, 'status' => $status, 'action' => $action, 'client_branch_id' => $branch_id,'uploaded_by' => 1, 'enrollment_open_date' => $enrollment_open_date, 'enrollment_close_date' => $enrollment_close_date]); //here field policy_id have client_policy_id and not policy id from policy master
// $this->myLogger->logme("error", '{file_id} uploaded success', ['file_id' => $file_id]);
// //start validation process
// if($fileSize < 1) // if file size less than 1
// {
// $empServiceController = new EmployeeServiceController();
// $result = $empServiceController->excelFileFormatValidation(['file_id' => $file_id]);
// $this->myLogger->logme("error", '{file_id} is less than 1MB, validating on the fly', ['file_id' => $file_id]);
// //endof validation process
// if (isset($result['error_summary']) && count($result['error_summary'])) {
// return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'file rejected with errors'], 200);
// }
// }
// else //if file size greater than 1 add the file as job
// {
// $job_details = new Jobs();
// $r = Jobs::addJob(['job_name' => 'excelFileFormatValidation','payload' => ['file_id' => $file_id]]);
// $this->myLogger->logme("error", '{file_id} is greather than 1MB, validating with job queue', ['file_id' => $file_id]);
// }
// return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => 'file upload success'], 200);
// }
if (!empty($post_data) || $this->request->is('post') == 'post') {
//validate uploaded file
$filename = '';
$fileSize = '';
if (empty($post_data)) {
$validated = $this->validate([
'emplist' => [
'uploaded[emplist]',
'mime_in[emplist,application/vnd.ms-excel,application/vnd,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.oasis.opendocument.spreadsheet]',
'max_size[emplist,16384]',
],
]);
} else {
$validated = validateExcelFile($post_data['emplist']);
}
if ($validated) {
$avatar = isset($post_data['emplist']) ? $post_data['emplist'] : $this->request->getFile('emplist');
if (!$avatar) {
$this->myLogger->logme("error", 'File not found');
if (!$is_post_request) {
return ['status' => false, 'message' => 'File not found'];
} else {
return $this->respond(['dataStatus' => false, 'code' => 400, 'message' => 'File not found'], 400);
}
}
$is_moved = $avatar->move(WRITEPATH . 'uploads/excel/');
if ($is_moved) {
$filename = $avatar->getName();
$fileSize = $avatar->getSize(); // File size in bytes
$fileSize = $fileSize / (1024 * 1024); // Convert to MB
// Handle successful upload, e.g., log success or further processing
$this->myLogger->logme("error", 'File move successful');
} else {
$this->myLogger->logme("error", 'File move failed');
if (!$is_post_request) {
return ['status' => false, 'message' => 'File move failed'];
} else {
return $this->respond(['dataStatus' => false, 'code' => 500, 'message' => 'File move failed'], 500);
}
}
} else {
$this->myLogger->logme("error", 'Upload failed Invalid file');
if (!$is_post_request) {
return ['status' => false, 'message' => 'Invalid file'];
} else {
return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'Invalid file'], 404);
}
}
//process post variable entry in file table
$loggedInUserID = $post_data['created_by'] ?? get_session_userid();
// $client_id = isset($post_data['client_id']) ? $post_data['client_id'] : $this->request->getPost('client_id');
// $policy_id = isset($post_data['policy_id']) ? $post_data['policy_id'] : $this->request->getPost('policy_id');
// $branch_id = isset($post_data['client_branch_id']) ? $post_data['client_branch_id'] : $this->request->getPost('branch_id');
// $action = isset($post_data['file_action']) ? $post_data['file_action'] : $this->request->getPost('upload-action-type');
// $enrollment_open_date = isset($post_data['enrollment_open_date']) ? $post_data['enrollment_open_date'] : $this->request->getPost('enrollment_open_date') ?? null;
// $enrollment_close_date = isset($post_data['enrollment_close_date']) ? $post_data['enrollment_close_date'] : $this->request->getPost('enrollment_close_date') ?? null;
// $status = 'inprogress';
// $hr_id = $post_data['created_by'] ?? null;
$client_id = $post_data['client_id'] ?? null;
$policy_id = $post_data['policy_id'] ?? null;
$branch_id = $post_data['client_branch_id'] ?? null;
$action = "enrollment";
$enrollment_open_date = $post_data['enrollment_open_date'] ?? null;
$enrollment_close_date = $post_data['enrollment_close_date'] ?? null;
$status = 'inprogress';
$hr_id = $post_data['created_by'] ?? null;
$enrollment_open_date = change_date_format($enrollment_open_date, 'd/m/Y', 'Y-m-d');
$enrollment_close_date = change_date_format($enrollment_close_date, 'd/m/Y', 'Y-m-d');
$file_id = $this->fileModel->insert(['file_name' => $filename, 'client_id' => $client_id, 'policy_id' => $policy_id, 'created_by' => $loggedInUserID, 'status' => $status, 'action' => $action, 'client_branch_id' => $branch_id, 'uploaded_by' => 1, 'enrollment_open_date' => $enrollment_open_date, 'enrollment_close_date' => $enrollment_close_date, 'hr_id' => $hr_id]); //here field policy_id have client_policy_id and not policy id from policy master
$this->myLogger->logme("error", '{file_id} uploaded success', ['file_id' => $file_id]);
//start validation process
if ($fileSize < 1) // if file size less than 1
{
$empServiceController = new EmployeeServiceController();
$result = $empServiceController->excelFileFormatValidation(['file_id' => $file_id]);
$this->myLogger->logme("error", '{file_id} is less than 1MB, validating on the fly', ['file_id' => $file_id]);
//endof validation process
if (isset($result['error_summary']) && count($result['error_summary'])) {
if(!$is_post_request){
return ['status' => false, 'message' => 'File rejected with errors', 'file_id' => $file_id];
}else{
return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'File rejected with errors'], 200);
}
}
} else //if file size greater than 1 add the file as job
{
$job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'excelFileFormatValidation', 'payload' => ['file_id' => $file_id]]);
$this->myLogger->logme("error", '{file_id} is greather than 1MB, validating with job queue', ['file_id' => $file_id]);
}
if (!$is_post_request) {
return ['status' => true, 'message' => 'File upload successs, Data validation is in-progress', 'file_id' => $file_id];
} else {
return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => 'file upload success'], 200);
}
}
$data['page_name'] = 'View Inception';
//for TPA/insurer upload
// $data['events'] = ['inception' => 'Inception (Employee + Dependents)', 'missed_inception' => 'Missed Inception (Employee + Dependents)', 'addition' => 'Addition (Employee + Dependents)', 'dependent_addition' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement'];
//for inception upload
// $data['actions'] = ['inception' => 'Inception (Employee + Dependents)', 'missed_inception' => 'Missed Inception (Employee + Dependents)', 'addition' => 'Addition (Employee + Dependents)', 'dependent_addition' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement','enrollment' => 'Enrolment'];
$data['actions'] = ['enrollment' => 'Enrolment'];
$data['import_or_export'] = ['import' => 'Import', 'export' => 'Export'];
$data['insurer_or_tpa'] = ['insurer' => 'Insurer', 'tpa' => 'TPA'];
// $data['fileList'] = $this->fileModel
// ->select(['files.*', 'up.emp_code', 'up.first_name', 'pm.name as policy_name', 'c.short_name', 'cp.id as client_policy_id'])
// ->join('user_profiles up', 'files.created_by = up.id')
// ->join('client_policy cp', 'files.policy_id = cp.id', 'left')
// ->join('policies pm', 'cp.policy_id = pm.id', 'left')
// ->join('clients c', 'files.client_id = c.id and files.client_id = cp.client_id', 'left')
// ->where('files.created_by', get_session_userid())->orderBy('files.created_at', 'desc')->findAll();
// dd($this->fileModel->getLastQuery());
$data['fileList'] = $this->fileModel
->select([
'files.id','files.file_name','files.created_by','files.created_at','files.is_active','files.status','files.client_id','files.policy_id','files.client_branch_id','files.action','files.uploaded_by', 'enrollment_open_date', 'enrollment_close_date',
'up.emp_code',
// 'up.first_name',
'c.short_name',
'cb.branch_name',
'cp.id as client_policy_id',
'(SELECT COUNT(*)
FROM employees e
JOIN employee_polices ep ON e.id = ep.employee_id
WHERE e.file_id = files.id AND ep.client_policy_id = files.policy_id) as employee_count',
'(SELECT SUM(ep.rata_premimum) + SUM(ep.gst)
FROM employees e
JOIN employee_polices ep ON e.id = ep.employee_id
WHERE e.file_id = files.id AND ep.client_policy_id = files.policy_id) as total',
'policy_type.policy_type' ,
'cp.policy_no' ,
"CASE
WHEN files.hr_id IS NOT NULL THEN
CONCAT(
(
SELECT lc.name
FROM level_contacts lc
WHERE lc.id = files.hr_id
LIMIT 1
),
' (HR)'
)
ELSE up.first_name
END AS first_name
",
'files.hr_id'
])
->join('user_profiles up', 'files.created_by = up.id', 'left')
->join('client_policy cp', 'files.policy_id = cp.id', 'left')
->join('client_branch cb', 'files.client_branch_id = cb.id', 'left')
->join('policy_type', 'policy_type.id = cp.policy_type_id')
->join('clients c', 'files.client_id = c.id and files.client_id = cp.client_id', 'left')
// ->where('files.created_by', get_session_userid())
->orderBy('files.created_at', 'desc')
->limit(100)
->find();
// dd($data['fileList']);
// $data['batch_list'] = $this->batchFileModel->select(
// 'batch_files.*,
// clients.short_name as client_short_name,
// client_branch.branch_name,
// client_policy.policy_no,
// policy_type.policy_type
// ')
// ->join('client_policy', 'client_policy.id = batch_files.client_policy_id')
// ->join('client_branch', 'client_branch.id = batch_files.client_branch_id')
// ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
// ->join('clients', 'clients.id = client_policy.client_id')
// ->orderBy('batch_files.id', 'desc')
// ->limit(100)
// ->find();
// dd($data['fileList']);die();
if ($_SERVER['REQUEST_METHOD'] == "GET") {
$this->loadLayout('import_export', $data);
}
}
public function getExcelFileErrors($file_id, $retun_type = null)
{
$file_data = $this->fileModel->where('id', $file_id)->first();
$error = json_decode($file_data['reason'] ?? '{}', true);
if(!empty($error) && $retun_type == 'api' && $file_data['status'] == 'failed'){
$send = isset($error['error_summary'][5]) || isset($error['error_summary'][6]) ? true : false;
if($send){
$string = $error['error_data'] ?? 'System error';
$errorMap = [
"Column order conflict" => "Invalid file format. Please use the sample file.",
];
$message = $string; // Default to the original error
foreach ($errorMap as $keyword => $friendlyMessage) {
if (strpos($string, $keyword) !== false) {
$message = $friendlyMessage;
break; // Stop looking once we find a match
}
}
return $this->respond(['status' => false, 'code' => 404, 'message' => $message, 'data' => []], 200);
}
}
// $file_id = $this->request->uri->getSegment(3);
$empServiceController = new EmployeeServiceController();
// Render views and capture output
$result = $empServiceController->getExcelErrorData($file_id);
if($retun_type == 'api'){
if(!empty($result)){
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Error data feteched successfully', 'data' => $result], 200);
}else{
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to fetch error data', 'data' => []], 200);
}
}
if ($result != 0) {
$result['file_id'] = $file_id;
echo view('excel_errors', $result);
} else if ($result == 0) {
$data['message'] = 'File Not Found Physically';
return view('errors/404', $data);
} else {
echo view('errors/html/production');
}
}
/**
* The below function Downloads a sample Excel file based on the provided action type.
*
* @param string|null $actionType The type of action :
*
* - inception
* - correction
* - si_enhancement for selecting the appropriate sample Excel file.
*
* @return redirect back with an error message if the file is not found, otherwise sends the file to the user for download.
*/
public function downloadSampleExcelFile($actionType = null, $return_type = 0)
{
// $actionType = $this->request->getGet();
$filePath = '';
// Path to your file
if ($actionType == 'inception') {
$filePath = ($return_type == 1)
? base_url('public/sample_excel/sample_inception.xls')
: ROOTPATH . 'public/sample_excel/sample_inception.xls';
} else if ($actionType == 'correction') {
$filePath = ($return_type == 1)
? base_url('public/sample_excel/sample_correction.xls')
: ROOTPATH . 'public/sample_excel/sample_correction.xls';
} else if ($actionType == 'si_enhancement') {
$filePath = ($return_type == 1)
? base_url('public/sample_excel/sample_si_enhancement.xls')
: ROOTPATH . 'public/sample_excel/sample_si_enhancement.xls';
} else if ($actionType == 'dependent_addtion') {
$filePath = ($return_type == 1)
? base_url('public/sample_excel/sample_dependent_addition.xls')
: ROOTPATH . 'public/sample_excel/sample_dependent_addition.xls';
} else if ($actionType == 'addition') {
$filePath = ($return_type == 1)
? base_url('public/sample_excel/sample_addition.xls')
: ROOTPATH . 'public/sample_excel/sample_addition.xls';
} else if ($actionType == 'deletion') {
$filePath = ($return_type == 1)
? base_url('public/sample_excel/sample_deletion.xls')
: ROOTPATH . 'public/sample_excel/sample_deletion.xls';
} else if ($actionType == 'enrollment') {
$filePath = ($return_type == 1)
? base_url('public/sample_excel/enrollment.xlsx')
: ROOTPATH . 'public/sample_excel/enrollment.xlsx';
} else if ($actionType == 'missed_inception') {
$filePath = ($return_type == 1)
? base_url('public/sample_excel/sample_inception.xls')
: ROOTPATH . 'public/sample_excel/sample_inception.xls';
}
if($return_type == 1){
return $filePath;
}
// Check if the file exists
if (file_exists($filePath)) {
// Set the appropriate MIME type
$mimeType = mime_content_type($filePath);
// Send the file to the client for download
return $this->response->download($filePath, null, $mimeType);
} else {
// File not found, show an error message or redirect
echo view('errors/html/production');
}
}
/**
* The below function are Handles import and export operations based on the provided parameters.
*
* This function logs the call, retrieves necessary data, generates a filename,
* and then either exports data to an Excel file or imports data from an Excel file
* depending on the provided action type and event type.
*
* @return void Redirects the user to the appropriate page with flash messages indicating success or failure.
*/
public function importExport()
{
$array = $this->request->getPost('event_type');
if (is_array($array)) {
$event_type = 'MultipleEvents';
} else {
$event_type = $this->request->getPost('event_type');
}
$this->myLogger->logme('error', 'Import Export -- Function called');
$empDataServiceController = new EmpDataServiceController();
$client_id = $this->request->getPost('client_id');
$client_policy_id = $this->request->getPost('client_policy_id');
$client_branch_id = $this->request->getPost('client_branch_id');
$insurer_or_tpa = $this->request->getPost('insurer_or_tpa');
$actions = $this->request->getPost('action_type');
$client_data = $this->clientPolicyModel->getCliendDataForExcelFileName($client_policy_id);
$file_name = generate_filename($client_data['short_name'], $event_type, $actions, $insurer_or_tpa, $client_data['policy_type'], $client_data['branch_code']);
// dd($client_data, $file_name);
$batch_data = [
'client_id' => $client_id,
'client_policy_id' => $client_policy_id,
'client_branch_id' => $client_branch_id,
'insurer_or_tpa' => $insurer_or_tpa,
'event_type' => $event_type,
'actions' => $actions,
'file_name' => $file_name,
];
if ($actions == 'export') {
if ($event_type == 'inception' || $event_type == 'addition' || $event_type == 'dependent_addition' || $event_type == 'missed_inception' || ($event_type == 'MultipleEvents' && $insurer_or_tpa == 'tpa')) {
$return = $empDataServiceController->generateExcelForAdditionandInception($batch_data);
if ($return === 0) {
session()->setFlashdata('error', "Insufficient deposit amount.");
return redirect()->to(base_url('employee/upload'));
}else if($return === 5){
session()->setFlashdata('error', "The policy does not have a CD account number.");
return redirect()->to(base_url('employee/upload'));
}
else if($return === 6){
session()->setFlashdata('error', "The Insurer does not have an Excel export template format.");
return redirect()->to(base_url('employee/upload'));
}
if (!$return) {
if ($insurer_or_tpa == 'tpa') {
session()->setFlashdata('error', "No data was found for this action.");
return redirect()->to(base_url('employee/upload'));
} else if ($insurer_or_tpa == 'insurer') {
session()->setFlashdata('error', "No data was found for this action.");
return redirect()->to(base_url('employee/upload'));
}
} else {
$this->myLogger->logme('error', 'Successfully exported Excel file in {data}.', ['data' => $event_type]);
}
} else if ($event_type == 'correction') {
$return = $empDataServiceController->generateExcelForCorrection($batch_data);
if($return === 6){
session()->setFlashdata('error', "The Insurer does not have an Excel export template format.");
return redirect()->to(base_url('employee/upload'));
}
if (!$return) {
session()->setFlashdata('error', 'No data found about this action');
return redirect()->to(base_url('employee/upload'));
} else {
$this->myLogger->logme('error', 'Successfully exported Excel file in Correction.');
}
} else if ($event_type == 'si_enhancement') {
$return = $empDataServiceController->generateExcelForSIEnhancement($batch_data);
if ($return === 0) {
session()->setFlashdata('error', "Insufficient deposit amount.");
return redirect()->to(base_url('employee/upload'));
}else if($return === 5){
session()->setFlashdata('error', "The policy does not have a CD account number.");
return redirect()->to(base_url('employee/upload'));
}else if($return === 6){
session()->setFlashdata('error', "The Insurer does not have an Excel export template format.");
return redirect()->to(base_url('employee/upload'));
}
if (!$return) {
session()->setFlashdata('error', 'No data found about this action');
return redirect()->to(base_url('employee/upload'));
} else {
$this->myLogger->logme('error', 'Successfully exported Excel file in SI_Enhancement.');
}
} else if ($event_type == 'deletion') {
$return = $empDataServiceController->generateExcelForDeletion($batch_data);
if($return === 6){
session()->setFlashdata('error', "The Insurer does not have an Excel export template format.");
return redirect()->to(base_url('employee/upload'));
}
if (!$return) {
session()->setFlashdata('error', 'No data found about this action');
return redirect()->to(base_url('employee/upload'));
} else {
$this->myLogger->logme('error', 'Successfully exported Excel file in Deletion.');
}
} else if($event_type == 'MultipleEvents'){
$batch_data['event_type'] = $array;
$return = $empDataServiceController->generateExcelForAllEventType($batch_data);
if($return === 6){
session()->setFlashdata('error', "The Insurer does not have an Excel export template format.");
return redirect()->to(base_url('employee/upload'));
}
if (!$return) {
session()->setFlashdata('error', 'No data found about this action');
return redirect()->to(base_url('employee/upload'));
} else {
$this->myLogger->logme('error', 'Excel exported successfully.');
}
}
} else if ($actions == 'import') {
$batch_data['file'] = $this->request->getFile('import_file_data');
$file = $this->request->getFile('import_file_data');
$is_moved = $file->move(WRITEPATH . 'uploads/import_excel');
$filename = $file->getName();
$this->myLogger->logme('error', 'Inception Import file name : {data}', ['data' => $filename]);
$random_number_count = 4;
$batch_data['batch_code'] = generate_random_string($random_number_count);
$batch_data['created_by'] = get_session_userid();
$batch_data['status'] = 'pending';
$batch_data['file_name'] = $filename;
if ($event_type == 'inception' || $event_type == 'addition' || $event_type == 'dependent_addition' || $event_type == 'missed_inception') {
$file_id = $this->batchFileModel->insert($batch_data);
$job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'importInceptionFileValidation', 'payload' => ['file_id' => $file_id]]);
$return = 1;
// $return = $empDataServiceController->importInceptionFileValidation(['file_id' => $file_id]);
if ($return == 1) {
session()->setFlashdata('success', 'File Uploaded Successfully File is being validated.');
return redirect()->to(base_url('employee/upload'));
} else {
session()->setFlashdata($return['status'], $return['message']);
return redirect()->to(base_url('employee/upload'));
}
} else if ($event_type == 'correction') {
$file_id = $this->batchFileModel->insert($batch_data);
$job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'importCorrectionValidation', 'payload' => ['file_id' => $file_id]]);
$return = 1;
// $return = $empDataServiceController->importCorrectionValidation(['file_id' => $file_id]);
if ($return == 1) {
session()->setFlashdata('success', 'File Uploaded Successfully File is being validated.');
return redirect()->to(base_url('employee/upload'));
} else {
session()->setFlashdata('error', $return);
return redirect()->to(base_url('employee/upload'));
}
} else if ($event_type == 'si_enhancement') {
$file_id = $this->batchFileModel->insert($batch_data);
$job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'importSIEnhancementValidation', 'payload' => ['file_id' => $file_id]]);
$return = 1;
// $return = $empDataServiceController->importSIEnhancementValidation(['file_id' => $file_id]);
if ($return == 1) {
session()->setFlashdata('success', 'File Uploaded Successfully File is being validated.');
return redirect()->to(base_url('employee/upload'));
} else {
session()->setFlashdata('error', $return);
return redirect()->to(base_url('employee/upload'));
}
} else if ($event_type == 'deletion') {
$file_id = $this->batchFileModel->insert($batch_data);
$job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'importDeletionValidation', 'payload' => ['file_id' => $file_id]]);
$return = 1;
// $return = $empDataServiceController->importDeletionValidation(['file_id' => $file_id]);
if ($return == 1) {
session()->setFlashdata('success', 'File Uploaded Successfully File is being validated.');
return redirect()->to(base_url('employee/upload'));
} else {
session()->setFlashdata('error', $return);
return redirect()->to(base_url('employee/upload'));
}
}
}
}
// -------------------------------------------------------------------------------------------
/**
* Below function displays the endorsement list page.
*
* This method retrieves filter data from the request and fetches the endorsement list
* based on the provided filters such as client ID, policy ID, and status.
*/
public function endorsementList()
{
$data = [];
$data['status'] = ['pending' => 'Pending', 'inprogress' => 'In-Progress', 'complete' => 'Complete'];
if (count($this->request->getGet())) {
$filterData = $this->request->getGet();
$data['employees'] = $this->employeePolicyModel->getEmployeeEndorsementList(
client_id: $filterData['client_id'],
policy_id: $filterData['policy_id'],
status: $filterData['status'],
branch_id: $filterData['branch_id']
);
$data['getData'] = $filterData;
// echo "<pre>";
// print_r($data); die;
}
$this->myLogger->logme('error', 'list called');
$this->loadLayout('endorsement_list', $data);
}
/**
* Below function displays the Enrollment list page.
*
* This method retrieves filter data from the request and fetches the Enrollment list
* based on the provided filters such as client , client_branch , employee - ( Log-in-or-not , ENrolled-or-not).
*/
public function enrollmentClientList()
{
$data = [];
$client_list = $this->clientModel->where('clients.is_active', 1)->findAll();
$branch_list = $this->clientBranchModel->where('client_branch.is_active', 1)->findAll();
$policy_list = $this->clientPolicyModel
->select('client_policy.*, policy_type.policy_type')
->join('policy_type', 'client_policy.policy_type_id = policy_type.id')
->where('client_policy.is_active', 1)
->findAll();
$data['client_list'] = $client_list;
$data['branch_list'] = $branch_list;
$data['policy_list'] = $policy_list;
// Get session data if available
$data['selected_client_id'] = session()->get('client_id');
$data['selected_branch_id'] = session()->get('branch_id');
$data['selected_type'] = session()->get('type');
// dd($data);
$this->myLogger->logme('error', 'list called');
return $this->loadLayout('enrollment_list', $data);
}
public function empby_client_clientbranch($client_id, $branch_id, $client_policy_id)
{
$results = $this->clientModel->select('
employees.id as employee_id,
employees.name as employee_name,
employees.relationship,
employees.emp_code,
employees.emp_status,
auth_history.user_type
')
->join('employees', $client_id . '= employees.client_id AND ' . $branch_id . '= employees.client_branch_id', 'left')
->join('employee_polices', 'employees.id = employee_polices.employee_id')
->join('auth_history', 'employees.id = auth_history.user_id AND "employee" = auth_history.user_type', 'left')
->where('employees.is_active', 1)
->where('employees.emp_status !=', 'truncated')
->where('employee_polices.client_policy_id', $client_policy_id)
->where('employee_polices.is_active', 1)
->where('employee_polices.status !=', 'truncated')
->groupBy('employees.id')
->findAll();
$groupedData = [];
$employeeId = '';
foreach ($results as $row) {
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'];
// if ($employeeId !== null && $employeeRelationship == 'Self') {
if ($employeeId !== null) {
// Append employee info to the branch's employees list
$groupedData[] = [
'employee_id' => $employeeId,
'employee_name' => $employeeName,
'relationship' => $employeeRelationship,
'emp_code' => $employeeEmpCode,
'emp_status' => $employeeEmpStatus,
'user_type' => $employeeUserType
];
}
$employeeId = $row['employee_id'];
}
// print_r($groupedData); die;
return json_encode($groupedData);
}
/**
* Beleo function retrieves employee endorsement (emp_endorsement table) data.
*
* This method fetches endorsement data based on the provided ID.
* It determines the type of endorsement action (SI enhancement, deletion, or other),
* formats the data accordingly, and returns it as a response.
*
* @param int|null $id The ID of the endorsement entry to retrieve.
* @return \CodeIgniter\HTTP\Response Returns a JSON response containing the endorsement entry data.
*/
public function getEmpEndoresmentEntry($id = null)
{
// Create instance of EmpDataServiceController
$empDataServiceController = new EmpDataServiceController();
// Check if $id is provided
if ($id) {
// Retrieve group key and actions based on $id
$group_key_actions = $this->empEndorsementModel->select('group_key, actions')->where('id', $id)->first();
$groupedData = $this->empEndorsementModel->where('group_key', $group_key_actions['group_key'])->findAll();
// If group key and actions are found
if ($group_key_actions) {
// Retrieve endorsement data based on actions
switch ($group_key_actions['actions']) {
case 'si':
$data = $this->empEndorsementModel->getDataForEnodrsementListinSIEnhancement($group_key_actions['group_key']);
$formatedData = $empDataServiceController->convertRowTColumnForSIEnhancement($data);
break;
case 'd':
$data = $this->empEndorsementModel->getDataForEnodrsementListinDeletion($group_key_actions['group_key']);
$formatedData = $empDataServiceController->convertRowTColumnForDeletion($data);
break;
default:
$formatedData = $groupedData;
$formatedData[0]['field_name'] = remove_underscore_capitalize_first_letter($formatedData[0]['field_name']);
$formatedData[0]['old_value'] = formatDateOrReturn($formatedData[0]['old_value']);
$formatedData[0]['new_value'] = formatDateOrReturn($formatedData[0]['new_value']);
break;
}
// Return response with data
return $this->respond([
'dataStatus' => true,
'code' => 200,
'data' => $formatedData,
'data2' => $groupedData
], 200);
} else {
// Return response if group key and actions are not found
return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'no data found'], 200);
}
} else {
// Return response if $id is not provided
return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'no data found'], 200);
}
}
// @param int $client_policy_id
// this funciton initiate Inception/adition/DA of employees data only form enrollment app when passing
// client_policy_id pull draft and enrolled status employees and proceed to calculatin and make entry in DB
public function initiateManualEmployeesOnboardProcess($client_policy_id)
{
$client_data = $this->clientPolicyModel->select('clients.client_name as client_name,client_branch_id')
->join('clients', 'clients.id = client_policy.client_id')
// ->join('policies', 'policies.id = client_policy.policy_id')
->where('client_policy.id', $client_policy_id)
->first();
// dd($client_data);
$empServiceController = new EmployeeServiceController();
$res = $empServiceController->employeesOnboardPreprocess(['client_policy_id' => $client_policy_id,'client_branch_id' => $client_data['client_branch_id']]);
// dd($res);
$count = ($res);
$message = $count . ' Employees are Initiate Onboard Process againts Client ' . $client_data['client_name'] . ' and the Policy is ' .$client_policy_id;
session()->setFlashdata('success1', $message);
return redirect()->to(base_url('/employee/upload'));
}
public function downloadFileList($file_id = null)
{
// $actionType = $this->request->getGet();
$file_data = $this->fileModel->where('id', $file_id)->first();
$fileName = $file_data['file_name'];
$error_data = json_decode($file_data['reason']);
$filePath = WRITEPATH . '/uploads/excel/' . $fileName;
try {
// Check if the file exists
if (file_exists($filePath)) {
// Set the appropriate MIME type
$mimeType = mime_content_type($filePath);
// Send the file to the client for download
return $this->response->download($filePath, null, $mimeType);
} else {
$data['message'] = 'The Physical File Not Found';
echo view('errors/404', $data);
}
} catch (\Exception $e) {
// Handle any exceptions
$errorMessage = $e->getMessage();
$this->myLogger->logme('error', $errorMessage);
// You can return an error response here
echo $errorMessage;
}
}
public function featchEmpList()
{
$client_id = $this->request->getGet('client_id');
$policy_id = $this->request->getGet('policy_id');
$emp_data['employees'] = $this->employeePolicyModel->getEmployeePolicyForFileList($client_id, $policy_id);
$html = view('employee_data_list', $emp_data);
return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $html], 200);
}
public function viewUploadedEmployeeList()
{
$empDataServiceController = new EmpDataServiceController();
$file_id = $this->request->getGet('file_id');
// $emp_data['employees'] = $this->employeePolicyModel->getViewEmpSuccessList($file_id);
// $html = view('view_file_upload_emp_list', $emp_data);
$file_name = $this->fileModel
->select(['files.*', 'up.emp_code', 'up.first_name', 'pm.name as policy_name', 'c.short_name', 'cp.id as client_policy_id'])
->join('user_profiles up', 'files.created_by = up.id')
->join('client_policy cp', 'files.policy_id = cp.id', 'left')
->join('policies pm', 'cp.policy_id = pm.id', 'left')
->join('clients c', 'files.client_id = c.id and files.client_id = cp.client_id', 'left')
->where('files.id', $file_id)->first();
// dd($file_name);
try {
$filePath = WRITEPATH . '/uploads/excel/' . $file_name['file_name'];
if (file_exists($filePath)) {
$excel_data = $empDataServiceController->readExcelFileToArray($filePath);
$emp_data['thead'] = $excel_data[0];
unset($excel_data[0]);
$emp_data['tbody'] = $excel_data;
$emp_data['count'] = count($excel_data);
// dd($emp_data);
$html = view('view_file_upload_emp_list', $emp_data);
} else {
$html = '<div class="text-center">No Data Found</div>';
}
return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $html, 'file_data' => $file_name, 'excel_data' => $excel_data], 200);
} catch (\Exception $e) {
// Handle exception
$errorMessage = 'Error occurred: ' . $e->getMessage();
$this->myLogger->logme('error', $errorMessage);
$html = '<div class="text-center">No Data Found</div>';
return $this->respond(['dataStatus' => false, 'code' => 500, 'data' => $html, 'file_data' => $file_name], 500);
}
}
public function getEmpCount($id = null)
{
$data = $this->employeePolicyModel->select('employee_polices.id')
->where('employee_polices.is_active', 1)
->where('employee_polices.client_policy_id', $id)
->findAll();
$emp_count = count($data);
$events = ['inception' => 'Inception (Employee + Dependents)', 'addition' => 'Addition (Employee + Dependents)', 'dependent_addition' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement'];
return $this->respond(['dataStatus' => true, 'code' => 200, 'emp_count' => $emp_count, 'events' => $events, 'client_policy_id' => $id], 200);
}
public function downloadFullExcelErrorFile($file_id, $rowIndex = 1, $colIndex = 1)
{
// Get file data from the database
$file_data = $this->fileModel->find($file_id);
$error = json_decode($file_data['reason']);
// echo '<pre>';
// print_r($error); die;
// dd($error);
// Check if the file exists
if (!$file_data) {
$error_message = "File not found";
$this->myLogger->logme('error', $error_message . ' for file id ' . $file_id);
return $error_message;
}
$fileName = $file_data['file_name'];
$filePath = WRITEPATH . '/uploads/excel/' . $fileName;
// Check if the file exists
if (!file_exists($filePath)) {
$error_message = "File not found";
$this->myLogger->logme('error', $error_message . ' for file id ' . $file_id);
$data['message'] = 'Physical File Not Found';
return view('errors/404', $data);
}
// Load the Excel file
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($filePath);
$sheet = $spreadsheet->getActiveSheet();
// echo '<pre>';
foreach ($error->error_data as $index => $error_data) {
$rowIndex = $index + 1;
if ($error->error_type == 1) {
foreach ($error_data as $key => $value) {
$colIndex = $value->col_idx + 1;
$originalValue = $sheet->getCell([$colIndex, $rowIndex])->getValue();
$newValue = implode(', ', $value->error);
$val = $originalValue . ' ( ' . $newValue . ' )';
$sheet->setCellValue([$colIndex, $rowIndex], $val);
$style = [
'fill' => [
'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
'startColor' => ['rgb' => 'ffad99'] // Red color
]
];
$sheet->getStyle([$colIndex, $rowIndex])->applyFromArray($style);
}
} else if ($error->error_type == 2) {
foreach ($error_data as $key => $value) {
$originalValue = $sheet->getCell([1, $rowIndex])->getValue();
$newValue = implode(', ', $value->error);
$val = $originalValue . ' ( ' . $newValue . ' )';
$sheet->setCellValue([$colIndex, $rowIndex], $val);
$style = [
'fill' => [
'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
'startColor' => ['rgb' => 'ffad99'] // Red color
]
];
$sheet->getStyle([$colIndex, $rowIndex])->applyFromArray($style);
}
}
}
// Create a new filename for the modified Excel file
$newFileName = 'error_with_highlight_' . $fileName;
// Save the modified Excel file to a new location
$newFilePath = WRITEPATH . '/uploads/excel/' . $newFileName;
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->save($newFilePath);
// Set headers to force download
$response = service('response');
$response->setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->setHeader('Content-Disposition', 'attachment;filename="' . $newFileName . '"');
$response->setHeader('Cache-Control', 'max-age=0');
$response->setHeader('Content-Length', filesize($newFilePath));
$response->setBody(file_get_contents($newFilePath));
// Delete the temporary file
unlink($newFilePath);
// Return the response
return $response;
}
//E-CARD DOWNLOAD FUNCTION
public function generateIDCardForEmployee($rand_string, $people = 0)
{
// dd($rand_string, $people);
try {
$this->myLogger->logme('error', 'generateIDCardForEmployee function started.');
// Step 1: Attempt to fetch employee code and client policy ID
$this->myLogger->logme('error', 'Fetching employee code and client policy ID.');
$get_emp_code_and_client_policy_id = $this->employeePolicyModel
->select('employee_polices.client_policy_id, employees.emp_code, tpa.short_name,employees.client_id')
->join('client_policy', 'client_policy.id = employee_polices.client_policy_id')
->join('employees', 'employees.id = employee_polices.employee_id')
->join('tpa', 'tpa.id = client_policy.tpa_id')
->where('employees.emp_status', 'active')
->where('employees.is_active', '1')
->where("employee_polices.tpa_id IS NOT NULL AND employee_polices.tpa_id <> ''")
->where('employee_polices.status', 'active')
->where('employee_polices.is_active', '1')
->where('employee_polices.rand_string', $rand_string)
->first();
// dd($this->employeePolicyModel->getLastQuery());
// dd($rand_string, $get_emp_code_and_client_policy_id);
if ($get_emp_code_and_client_policy_id == null || $get_emp_code_and_client_policy_id == "") {
$this->myLogger->logme('error', 'Member not found in this rand_string: ' . $rand_string);
$data['message'] = 'Record Not Found';
return view('errors/404', $data);
}
$this->myLogger->logme('error', 'Member found. Client policy ID: ' . $get_emp_code_and_client_policy_id['client_policy_id']);
$client_policy_id = $get_emp_code_and_client_policy_id['client_policy_id'];
$emp_code = $get_emp_code_and_client_policy_id['emp_code'];
$client_id = $get_emp_code_and_client_policy_id['client_id'];
// Step 2: Fetch ECard data
$this->myLogger->logme('error', 'Fetching ECard data using client_policy_id: ' . $client_policy_id . ' and emp_code: ' . $emp_code);
$data = $this->employeePolicyModel->getECardDataUsingMd5($client_policy_id, $emp_code,$client_id);
if ($people == 0) {
$this->myLogger->logme('error', 'Fetching single ECard data using rand_string: ' . $rand_string . ' and emp_code: ' . $emp_code);
$data = $this->employeePolicyModel->getECardSingleData($rand_string, $emp_code,$client_id);
}
// Step 3: Prepare template path
$template_data_path = WRITEPATH . 'e_card_template/';
$tpa_short_name = strtolower(str_replace(' ', '_', $get_emp_code_and_client_policy_id['short_name'])) . '.html';
$final_path = $template_data_path . $tpa_short_name;
$this->myLogger->logme('error', 'Checking if template file exists at: ' . $final_path);
if (!file_exists($final_path)) {
$this->myLogger->logme('error', 'Template file not found: ' . $final_path);
$data['message'] = 'Template File Not Found';
return view('errors/404', $data);
}
$this->myLogger->logme('error', 'Template file found. Reading template data.');
$tmplt_data = file_get_contents($final_path);
// Step 4: Generate HTML content
$this->myLogger->logme('error', 'Generating HTML content from template.');
$html = "";
foreach ($data as $key => $value) {
$htmlContent = $tmplt_data;
$placeholders = [
'{CLIENT_NAME}' => $value['client_name'],
'{TPA_ID}' => $value['tpa_id'],
'{NAME}' => $value['name'],
'{UHID}' => $value['uhid'],
'{GENDER}' => $value['gender'],
'{DOB}' => date('d-M-Y', strtotime($value['dob'])),
'{SELF_NAME}' => $value['self'] ?? $value['name'],
'{POLICY_DATE}' => date('d-M-Y', strtotime($value['policy_end_date'])),
'{POLICY_START_DATE}' => date('d-M-Y', strtotime($value['policy_start_date'])),
'{POLICY_NO}' => $value['policy_no'],
'{INSURER_NAME}' => strtoupper($value['insurer_name']),
'{INSURER_LOGO}' => base_url() . 'public/uploads/logo/' . $value['insurer_logo'],
'{FRONT_CARD}' => base_url() . 'public/uploads/template_bg/' . $value['front_card'],
'{BACK_CARD}' => base_url() . 'public/uploads/template_bg/' . $value['back_card'],
'{EMP_ID}' => $value['emp_code'],
'{SI_AMT}' => $value['basic_cover_si'],
'{CORPORATE_NAME}' => $value['client_name'],
'{AGE}' => $value['emp_age'],
'{TPA_NAME}' => $value['tpa_name'],
'{INSURER_BRANCH}' => $value['insurer_branch_city'],
'{RELATION}' => $value['relationship'],
'{TPA_LOGO}' => base_url() . 'public/uploads/logo/' . $value['tpa_logo'],
'{MEDI_USER}' => base_url() . 'public/e_card_imgs/medi_uesr.jpg',
'{MEDI_INSURER}' => base_url() . 'public/e_card_imgs/Magma.png',
'{MEDI_BARCODE}' => base_url() . 'public/e_card_imgs/borcode.jpeg',
'{QR_ANDROID}' => base_url() . 'public/e_card_imgs/android.png',
'{QR_IOS}' => base_url() . 'public/e_card_imgs/ios.png',
'{QR_ANDROID_2}' => base_url() . 'public/e_card_imgs/play_store.png',
'{QR_IOS_2}' => base_url() . 'public/e_card_imgs/appstore.png',
];
$placeholders['{LEVELS}'] = $this->generateAcmAndMForEcard($client_id);
foreach ($placeholders as $placeholder => $replaceValue) {
$htmlContent = str_replace($placeholder, $replaceValue, $htmlContent);
}
$html .= $htmlContent;
}
// Step 5: Output HTML and script for printing
$this->myLogger->logme('error', 'Generating HTML output with print button.');
echo '<button id="downloadBtn" style="display: block;margin: 30px;position: relative;left: 220px;">Print</button>' . $html . '</button>
<script>
document.getElementById("downloadBtn").addEventListener("click", function() {
this.style.display = "none";
window.print();
this.style.display = "block";
});
</script>';
$this->myLogger->logme('error', 'generateIDCardForEmployee function completed successfully.');
} catch (\Exception $e) {
$this->myLogger->logme('error', 'Exception occurred: ' . $e->getMessage());
$data['message'] = 'Record Not Found';
return view('errors/404', $data);
}
}
public function viewECard()
{
// $this->loadLayout('ecard_template/default_ecard');
$empDataServiceController = new EmpDataServiceController();
$return = $empDataServiceController->importDeletionValidation(['file_id' => 130]);
}
//truncateFileDataIn DB (de activate rows) NEW FUNCTION
public function truncateFileData($file_id, $role_id = null)
{
$this->myLogger->logme('error', '---- truncateFileData Function called ----');
$file_id = $this->request->uri->getSegment(3);
// $file_id = 747;
$this->myLogger->logme('error', 'File id for truncate : -- FILE ID : {data} --', ['data' => $file_id]);
//get the files data
$file = $this->fileModel->find($file_id);
$client_id = $file['client_id'];
$client_policy_id = $file['policy_id'];
$loggedInUserID = get_session_userid();
//get the client policy data
$policy_data = $this->clientPolicyModel->where('id', $client_policy_id)->first();
//get the cd transaction data based on the insurer and client
$cd_tranction = $this->cashDepositModel
->where('client_id', $client_id) //client
->where('insurer_id', $policy_data['insurer_id']) //insurer
->where('event_name',$file['action']) //event
->where('client_policy_id', $client_policy_id)//policy
->orderBy('id', 'desc')
->first();
// print_r($file); die;
if ($file['action'] == 'inception' || $file['action'] == 'dependent_addition' || $file['action'] == 'addition' || $file['action'] == 'enrollment' || $file['action'] == 'missed_inception') {
if($file['action'] == 'enrollment'){
$result = $this->employeeModel->getEmpListByFileId(file_id: $file_id, emp_status: ['draft','enrolled'], policy_status: ['draft','enrolled']);
}else{
$result = $this->employeeModel->getEmpListByFileId(file_id: $file_id, emp_status: ['active'], policy_status: ['active']);
}
// print_r($result); die;
if (count($result) && $role_id == null) {
if(get_role_id() == 1 || get_role_id() == 5){
return $this->respond(['role' => get_role_id(), 'dataStatus' => false, 'code' => 404, 'message' => 'File data already processed. Do you want to truncate data from uploaded file?'], 200);
}else{
return $this->respond(['role' => get_role_id(), 'dataStatus' => false, 'code' => 404, 'message' => 'File data already processed'], 200);
}
} else {
$this->myLogger->logme('error', '---- TRUNCATED STARTED WITH ADMIN OR HEAD PERMISSION ----');
$this->myLogger->logme('error', '---- Event Type : -- {data} ----', ['data' => $file['action']]);
if($file['action'] != 'enrollment')
{
$employee_policy_data_with_file_id = $this->employeePolicyModel->where('file_id', $file_id)->findAll();
if(!empty($employee_policy_data_with_file_id) && count($employee_policy_data_with_file_id) > 0){
// GET THE CD TRANSACTION AMOUNT
$cd_amount_total = $this->employeePolicyModel->calculateCdTranctionAmount($file_id);
$cd_amount = $cd_amount_total['total'] ?? 0;
$this->myLogger->logme('error', '---- CD Amount : {data} ----', ['data' => $cd_amount]);
//STEP: 1 - Update employee policy table
$db = db_connect();
$query = "
UPDATE employee_polices
SET employee_polices.status = 'truncated', employee_polices.is_active = 0
WHERE employee_polices.file_id = $file_id
";
$db->query($query);
$affectedRows = $db->affectedRows();
$this->myLogger->logme('error', '---- employee_polices table update query : {data} ----', ['data' => $query]);
$this->myLogger->logme('error', '---- employee_polices table updated - Affected Rows : {data} ----', ['data' => $affectedRows]);
// print_r($db->getLastQuery()); die;
//STEP:2 - Update emp_endorsement Table
if(in_array($file['action'], ['addition', 'dependent_addition'])){
$this->empEndorsementModel->where('file_id', $file_id)->set(['status' => 'truncated','is_active' => 0])->update();
$this->myLogger->logme('error', '---- emp_endorsement table updated ----');
}
//STEP:3 - Update files table status
$this->fileModel->where('id', $file_id)->set(['status' => 'truncated','updated_by' => $loggedInUserID])->update();
$this->myLogger->logme('error', '---- files table updated ----');
//FINAL STEP - Update reverse entry in cash_deposite table
if(!empty($cd_amount)){
$cd_data = [
'amount' => $cd_amount,
'sub_type_id' => 8,
'endorsement_no' => null,
'insurer_id' =>$policy_data['insurer_id'],
'description' => 'The policy Truncated by Admin or Head',
'transaction_type' => 'Credit',
'updated_by' => 1,
'client_id' => $client_id,
'client_policy_id' => $client_policy_id,
'cd_ac_no' => $policy_data['cd_ac_no'] ?? null,
'cd_ac_pk' => $policy_data['cd_ac_pk'] ?? null,
'event_name' => $file['action'],
];
$response = DepositHelper::saveDeposit($cd_data, $loggedInUserID);
$this->myLogger->logme('error', 'cash_deposite table updated -- cd transaction');
}
}else{
$this->myLogger->logme('error', '---- There is no data to truncate ----');
return $this->respond(['role' => get_role_id(), 'dataStatus' => false, 'code' => 404, 'message' => 'There is no data to truncate'], 200);
}
}
else
{
// echo 'came here...1';
//check all dependents added by self and other dependent policies
$emp_codes = $this->employeeModel->select('emp_code')
->where('file_id', $file_id)
->findAll();
$emp_codes = array_column($emp_codes,'emp_code');
// Kint::dump($emp_codes);//die;
$dependent_policies = $this->clientPolicyModel->select('id')
->where('base_policy', $client_policy_id)
->findAll();
// $dependent_policies = [ [10],[25],[35] ];
// Kint::dump($dependent_policies);
// Kint::dump(array_column($dependent_policies,'id'));
if(count($dependent_policies))
{
$dependent_policies = array_column($dependent_policies,'id');
// Kint::dump($dependent_policies);
$second_level_dependent_policies = $this->clientPolicyModel->select('id')
->whereIn('base_policy', $dependent_policies)
->findAll();
// dd($second_level_dependent_policies);
if(count($second_level_dependent_policies))
{
$second_level_dependent_policies = array_column($second_level_dependent_policies,'id');
}
$dependent_policies = array_merge($dependent_policies,$second_level_dependent_policies);
}
$dependent_policies = array_merge($dependent_policies,[$client_policy_id]);
// Kint::dump($dependent_policies);
//update emp and emp plocies
$db = db_connect();
$emp_codes = '(' . implode(',', array_map(fn($code) => "'$code'", $emp_codes)) . ')';
$dependent_policies = '(' . implode(',', $dependent_policies) . ')';
$query = "
UPDATE employee_polices
JOIN employees ON employees.id = employee_polices.employee_id and employees.emp_code in $emp_codes
SET employee_polices.status = 'truncated', employee_polices.is_active = 0
WHERE employee_polices.client_policy_id in $dependent_policies
";
// print_r($query); die;
$db->query($query);
$affectedRows = $db->affectedRows();
// dd($affectedRows);
$affectedRows = $affectedRows * 2;
$this->fileModel->where('id', $file_id)->set(['status' => 'truncated','updated_by' => $loggedInUserID])->update();
}
$this->myLogger->logme('error', 'SUCCESSFULLY TRUNCATED');
return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => round($affectedRows / 2)], 200);
}
} else if ($file['action'] == 'si_enhancement' || $file['action'] == 'correction' || $file['action'] == 'deletion') {
$res = $this->empEndorsementModel->select(['count(id) as count'])
->where('emp_endorsement.file_id', $file_id)
->groupStart()
->where('emp_endorsement.endorsement_id is not null')
->orwhereIn('emp_endorsement.status', ['complete'])
->groupEnd()
->get()
->getResult();
// print_r($this->empEndorsementModel->getLastQuery());
// echo $res[0]->count;die();
if ($res[0]->count == 0 || $role_id == 5 || $role_id == 1) {
$this->myLogger->logme('error', 'TRUNCATED STARTED WITH ADMIN OR HEAD PERMISSION');
$this->myLogger->logme('error', 'Event Type : -- {data} --', ['data' => $file['action']]);
$transaction_type = 'Credit';
$cd_amount = $cd_tranction['amount'];
if($file['action'] == 'deletion'){
$transaction_type = 'Debit';
//get cd amount for the particular file id to reverse entry to the cash deposite for only deletion
$cd_amount_total = $this->employeePolicyModel->getDeletionDataForTruncated($file['id']);
$totalSum = array_sum(array_column($cd_amount_total, 'total'));
$cd_amount = $totalSum;
$this->myLogger->logme('error', 'Deletion CD Amount : {data}', ['data' => $cd_amount]);
}
$this->myLogger->logme('error', 'Endorsemnt CD Amount : {data}', ['data' => $cd_amount]);
//STEP 1:
//update truncated status to the Emp_endorsement table
$this->empEndorsementModel->where('file_id', $file_id)
->set(['status' => 'truncated','is_active' => 0])
->update();
$this->myLogger->logme('error', 'emp_endorsement table updated');
//STEP 2:
if($file['action'] == 'deletion') {
//update the employee policy table reverse the data
$this->employeePolicyModel->updateEmployeePolicyTruncateReverse($file_id);
$this->myLogger->logme('error', 'employee_polices table updated for deletion');
}
if($file['action'] == 'correction'){
}
// STEP 3:
//update files table status to "truncated"
$this->fileModel->where('id', $file_id)->set(['status' => 'truncated','updated_by' => $loggedInUserID])->update();
$this->myLogger->logme('error', 'files table updated');
if($cd_tranction && $file['action'] != 'correction'){
$cd_data = [
'amount' => $cd_amount,
'sub_type_id' => 8,
'endorsement_no' => null,
'insurer_id' =>$policy_data['insurer_id'],
'description' => 'The policy Truncated by Admin or Head',
'transaction_type' => $transaction_type,
'updated_by' => 1,
'client_id' => $client_id,
'client_policy_id' => $client_policy_id,
'cd_ac_no' => $policy_data['cd_ac_no'] ?? null,
'cd_ac_pk' => $policy_data['cd_ac_pk'] ?? null,
'event_name' => $file['action'],
];
$response = DepositHelper::saveDeposit($cd_data, $loggedInUserID);
$this->myLogger->logme('error', 'cash_deposite table updated -- cd transaction');
}
$this->myLogger->logme('error', 'SUCCESSFULLY TRUNCATED');
return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => 'success'], 200);
} else {
if(get_role_id() == 1 || get_role_id() == 5){
return $this->respond(['role' => get_role_id(), 'dataStatus' => false, 'code' => 404, 'message' => 'File data already processed. Do you want to truncate data from uploaded file?'], 200);
}else{
return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'File data already processed'], 200);
}
}
}
}
//truncateFileData OLD FUNCTION
public function truncateFileDataOld($file_id, $role_id = null)
{
$file_id = $this->request->uri->getSegment(3);
// $file_id = 747;
$file = $this->fileModel->find($file_id);
$client_id = $file['client_id'];
$client_policy_id = $file['policy_id'];
$loggedInUserID = get_session_userid();
$policy_data = $this->clientPolicyModel->where('id', $client_policy_id)->first();
$cd_tranction = $this->cashDepositModel
->where('client_id', $client_id) //client
->where('insurer_id', $policy_data['insurer_id']) //insurer
->where('event_name',$file['action']) //event
->where('client_policy_id', $client_policy_id)//policy
->orderBy('id', 'desc')
->first();
// $file['action'] = 'si_enhancement';
// $result = [];
// dd($file);
if ($file['action'] == 'inception' || $file['action'] == 'dependent_addition' || $file['action'] == 'addition' || $file['action'] == 'enrollment' || $file['action'] == 'missed_inception') {
if($file['action'] == 'enrollment'){
$result = $this->employeeModel->getEmpListByFileId(file_id: $file_id, emp_status: ['draft','enrolled'], policy_status: ['draft','enrolled']);
}else{
$result = $this->employeeModel->getEmpListByFileId(file_id: $file_id, emp_status: ['active'], policy_status: ['active']);
}
$result = [];
// ~dd($result);
if (count($result) && $role_id == null) {
if(get_role_id() == 1 || get_role_id() == 5){
return $this->respond(['role' => get_role_id(), 'dataStatus' => false, 'code' => 404, 'message' => 'File data already processed. Do you want to truncate data from uploaded file?'], 200);
}else{
return $this->respond(['role' => get_role_id(), 'dataStatus' => false, 'code' => 404, 'message' => 'File data already processed'], 200);
}
} else {
$this->myLogger->logme('error', 'TRUNCATED STARTED WITH ADMIN OR HEAD PERMISSION');
$this->myLogger->logme('error', 'Event Type : -- {data} --', ['data' => $file['action']]);
// GET THE CD AMOUND
//get cd amount for the particular file id to reverse entry to the cash deposite
$cd_amount = $cd_tranction['amount'];
if(in_array($file['action'], ['addition', 'dependent_addition'])){
$cd_amount_total = $this->employeePolicyModel->getAdditionDataForTruncated($file_id, $file['action']);
// dd($cd_amount_total);
$cd_amount = $cd_amount_total['total'];
$this->myLogger->logme('error', 'Addition or Dependent Addition CD Amount : {data}', ['data' => $cd_amount]);
}
$this->myLogger->logme('error', 'CD Amount : {data}', ['data' => $cd_amount]);
if($file['action'] != 'enrollment')
{
//STEP: 1 - Update employee policy table
//update emp and emp plocies
$db = db_connect();
$query = "
UPDATE employee_polices
JOIN employees ON employees.id = employee_polices.employee_id
SET employee_polices.status = 'truncated', employee_polices.is_active = 0
WHERE employees.file_id = $file_id
";
$db->query($query);
$affectedRows = $db->affectedRows();
$this->myLogger->logme('error', 'employee_polices table update query : {data}', ['data' => $query]);
$this->myLogger->logme('error', 'employee_polices table updated - Affected Rows : {data}', ['data' => $affectedRows]);
// print_r($db->getLastQuery()); die;
// $affectedRows = 10;
//STEP:2 - Update emp_endorsement Table
//update truncated status and is_active 0 to the Emp_endorsement table
if(in_array($file['action'], ['addition', 'dependent_addition'])){
$this->empEndorsementModel->where('file_id', $file_id)
->set(['status' => 'truncated','is_active' => 0])
->update();
$this->myLogger->logme('error', 'emp_endorsement table updated');
}
//STEP:3 - Update files table
//update file status
$this->fileModel->where('id', $file_id)->set(['status' => 'truncated'])->update();
$this->myLogger->logme('error', 'files table updated');
}
else
{
// echo 'came here...1';
//check all dependents added by self and other dependent policies
$emp_codes = $this->employeeModel->select('emp_code')
->where('file_id', $file_id)
->findAll();
$emp_codes = array_column($emp_codes,'emp_code');
// Kint::dump($emp_codes);//die;
$dependent_policies = $this->clientPolicyModel->select('id')
->where('base_policy', $client_policy_id)
->findAll();
// $dependent_policies = [ [10],[25],[35] ];
// Kint::dump($dependent_policies);
// Kint::dump(array_column($dependent_policies,'id'));
if(count($dependent_policies))
{
$dependent_policies = array_column($dependent_policies,'id');
// Kint::dump($dependent_policies);
$second_level_dependent_policies = $this->clientPolicyModel->select('id')
->whereIn('base_policy', $dependent_policies)
->findAll();
// dd($second_level_dependent_policies);
if(count($second_level_dependent_policies))
{
$second_level_dependent_policies = array_column($second_level_dependent_policies,'id');
}
$dependent_policies = array_merge($dependent_policies,$second_level_dependent_policies);
}
$dependent_policies = array_merge($dependent_policies,[$client_policy_id]);
// Kint::dump($dependent_policies);
//update emp and emp plocies
$db = db_connect();
$emp_codes = '(' . implode(',', array_map(fn($code) => "'$code'", $emp_codes)) . ')';
$dependent_policies = '(' . implode(',', $dependent_policies) . ')';
$query = "
UPDATE employee_polices
JOIN employees ON employees.id = employee_polices.employee_id and employees.emp_code in $emp_codes
SET employee_polices.status = 'truncated', employee_polices.is_active = 0
WHERE employee_polices.client_policy_id in $dependent_policies
";
$db->query($query);
$affectedRows = $db->affectedRows();
// dd($affectedRows);
$affectedRows = $affectedRows * 2;
$this->fileModel->where('id', $file_id)->set(['status' => 'truncated'])->update();
}
//FINAL STEP - Update reverse entry in cash_deposite table
if($cd_tranction){
$cd_data = [
'amount' => $cd_amount,
'sub_type_id' => 8,
'endorsement_no' => null,
'insurer_id' =>$policy_data['insurer_id'],
'description' => 'The policy Truncated by Admin or Head',
'transaction_type' => 'Credit',
'updated_by' => 1,
'client_id' => $client_id,
'client_policy_id' => $client_policy_id,
'cd_ac_no' => $policy_data['cd_ac_no'] ?? null,
'cd_ac_pk' => $policy_data['cd_ac_pk'] ?? null,
'event_name' => $file['action'],
];
$response = DepositHelper::saveDeposit($cd_data, $loggedInUserID);
$this->myLogger->logme('error', 'cash_deposite table updated -- cd transaction');
}
$this->myLogger->logme('error', 'SUCCESSFULLY TRUNCATED');
return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => round($affectedRows / 2)], 200);
}
} else if ($file['action'] == 'si_enhancement' || $file['action'] == 'correction' || $file['action'] == 'deletion') {
$res = $this->empEndorsementModel->select(['count(id) as count'])
->where('emp_endorsement.file_id', $file_id)
->groupStart()
->where('emp_endorsement.endorsement_id is not null')
->orwhereIn('emp_endorsement.status', ['complete'])
->groupEnd()
->get()
->getResult();
// print_r($this->empEndorsementModel->getLastQuery());
// echo $res[0]->count;die();
if ($res[0]->count == 0 || $role_id == 5 || $role_id == 1) {
$this->myLogger->logme('error', 'TRUNCATED STARTED WITH ADMIN OR HEAD PERMISSION');
$this->myLogger->logme('error', 'Event Type : -- {data} --', ['data' => $file['action']]);
$transaction_type = 'Credit';
$cd_amount = $cd_tranction['amount'];
if($file['action'] == 'deletion'){
$transaction_type = 'Debit';
//get cd amount for the particular file id to reverse entry to the cash deposite for only deletion
$cd_amount_total = $this->employeePolicyModel->getDeletionDataForTruncated($file['id']);
$totalSum = array_sum(array_column($cd_amount_total, 'total'));
$cd_amount = $totalSum;
$this->myLogger->logme('error', 'Deletion CD Amount : {data}', ['data' => $cd_amount]);
}
$this->myLogger->logme('error', 'Endorsemnt CD Amount : {data}', ['data' => $cd_amount]);
//STEP 1:
//update truncated status to the Emp_endorsement table
$this->empEndorsementModel->where('file_id', $file_id)
->set(['status' => 'truncated','is_active' => 0])
->update();
$this->myLogger->logme('error', 'emp_endorsement table updated');
//STEP 2:
if($file['action'] == 'deletion') {
//update the employee policy table reverse the data
$this->employeePolicyModel->updateEmployeePolicyTruncateReverse($file_id);
$this->myLogger->logme('error', 'employee_polices table updated for deletion');
}
if($file['action'] == 'correction'){
}
// STEP 3:
//update files table status to "truncated"
$this->fileModel->where('id', $file_id)->set(['status' => 'truncated'])->update();
$this->myLogger->logme('error', 'files table updated');
if($cd_tranction && $file['action'] != 'correction'){
$cd_data = [
'amount' => $cd_amount,
'sub_type_id' => 8,
'endorsement_no' => null,
'insurer_id' =>$policy_data['insurer_id'],
'description' => 'The policy Truncated by Admin or Head',
'transaction_type' => $transaction_type,
'updated_by' => 1,
'client_id' => $client_id,
'client_policy_id' => $client_policy_id,
'cd_ac_no' => $policy_data['cd_ac_no'] ?? null,
'cd_ac_pk' => $policy_data['cd_ac_pk'] ?? null,
'event_name' => $file['action'],
];
$response = DepositHelper::saveDeposit($cd_data, $loggedInUserID);
$this->myLogger->logme('error', 'cash_deposite table updated -- cd transaction');
}
$this->myLogger->logme('error', 'SUCCESSFULLY TRUNCATED');
return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => 'success'], 200);
} else {
if(get_role_id() == 1 || get_role_id() == 5){
return $this->respond(['role' => get_role_id(), 'dataStatus' => false, 'code' => 404, 'message' => 'File data already processed. Do you want to truncate data from uploaded file?'], 200);
}else{
return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'File data already processed'], 200);
}
}
}
}
// Preview E-Card Template function
public function previewTemplate($id = null)
{
$value = [
'tpa_id' => 'TPA12345',
'name' => 'John Doe',
'uhid' => 'UHID67890',
'gender' => 'Male',
'dob' => '1985-05-15',
'self' => 'John Doe',
'policy_end_date' => '2024-12-31',
'policy_start_date' => '2023-01-01',
'policy_no' => 'POL1234567890',
'insurer_name' => 'Example Insurance Company',
'emp_code' => 'EMP001122',
'client_name' => 'Corporate Client Inc.',
'emp_age' => 39,
'tpa_name' => 'Example TPA',
'insurer_branch_city' => 'New York',
'relationship' => 'Self',
'basic_cover_si' => '5,00,000',
];
$tpa_id = $this->TPAModel->where('id', $id)->first();
$template_data_path = WRITEPATH . 'e_card_template/';
$tpa_short_name = strtolower(str_replace(' ', '_', $tpa_id['short_name'])) . '.html';
$final_path = $template_data_path . $tpa_short_name;
if (!file_exists($final_path)) {
$data['message'] = 'Record Not Found';
return view('errors/404', $data);
}
$tmplt_data = file_get_contents($final_path);
$placeholders = [
'{TPA_ID}' => $value['tpa_id'],
'{NAME}' => $value['name'],
'{UHID}' => $value['uhid'],
'{GENDER}' => $value['gender'],
'{DOB}' => date('d-M-Y', strtotime($value['dob'])),
'{SELF_NAME}' => $value['self'] ?? $value['name'],
'{POLICY_DATE}' => date('d-M-Y', strtotime($value['policy_end_date'])),
'{POLICY_START_DATE}' => date('d-M-Y', strtotime($value['policy_start_date'])),
'{POLICY_NO}' => $value['policy_no'],
'{INSURER_NAME}' => strtoupper($value['insurer_name']),
'{EMP_ID}' => $value['emp_code'],
'{SI_AMT}' => $value['basic_cover_si'],
'{CORPORATE_NAME}' => $value['client_name'],
'{AGE}' => $value['emp_age'],
'{TPA_NAME}' => $value['tpa_name'],
'{INSURER_BRANCH}' => $value['insurer_branch_city'],
'{RELATION}' => $value['relationship'],
'{FRONT_CARD}' => base_url() . 'public/uploads/template_bg/' . $tpa_id['front_card'],
'{BACK_CARD}' => base_url() . 'public/uploads/template_bg/' . $tpa_id['back_card'],
'{TPA_LOGO}' => base_url() . 'public/uploads/logo/' . $tpa_id['tpa_logo'],
'{INSURER_LOGO}' => base_url() . 'public/assets/images/sample_logo_3.png',
'{MEDI_USER}' => base_url() . 'public/e_card_imgs/medi_uesr.jpg',
'{MEDI_INSURER}' => base_url() . 'public/e_card_imgs/Magma.png',
'{MEDI_BARCODE}' => base_url() . 'public/e_card_imgs/borcode.jpeg',
'{QR_ANDROID}' => base_url() . 'public/e_card_imgs/android.png',
'{QR_IOS}' => base_url() . 'public/e_card_imgs/ios.png',
'{QR_ANDROID_2}' => base_url() . 'public/e_card_imgs/play_store.png',
'{QR_IOS_2}' => base_url() . 'public/e_card_imgs/appstore.png',
];
// Get the values to replace the placeholders
$replaceValues = array_values($placeholders);
// Get the placeholders to search for
$searchPlaceholders = array_keys($placeholders);
// Replace placeholders with values in HTML content
$htmlContent = str_replace($searchPlaceholders, $replaceValues, $tmplt_data);
echo $htmlContent;
}
public function errorListExportImport($file_id)
{
$empDataServiceController = new EmpDataServiceController();
$file = $this->batchFileModel->where('id', $file_id)->first();
$client_id = $file['client_id'];
$client_policy_id = $file['client_policy_id'];
$insurer_or_tpa = $file['insurer_or_tpa'];
$event_type = $file['event_type'];
$error_data = json_decode($file['error_data']);
// dd($error_data);
$file_name_with_path = WRITEPATH . "/uploads/import_excel/" . $file['file_name'];
if (!file_exists($file_name_with_path)) {
$error_message = "File not found";
$this->myLogger->logme('error', ($error_message . ' for file id ' . $file_id));
$data['message'] = 'Physical File Not Found';
return view('errors/404', $data);
}
$excel_data = $empDataServiceController->readExcelFileToArray($file_name_with_path);
$excelErrorData['excel_header'] = $excel_data[0];
unset($excel_data[0]);
// if($event_type == 'inception' || $event_type == 'deletion'){
// array_pop($excel_data);
// }
// if($event_type == 'deletion'){
// array_pop($excel_data);
// }
$finalArray = [];
foreach ($error_data as $key => $values) {
foreach ($values as $key2 => $value) {
$row = $value->row;
$column = $value->column;
if(property_exists($value, 'db_data')){
$error = 'Expected value: ' . ($value->db_data == null || $value->db_data == "" ? 'NULL' : $value->db_data);
}else{
if($event_type == 'inception'){
if ($insurer_or_tpa == 'tpa') {
$error = 'Expected value : TPA ID';
} else if ($insurer_or_tpa == 'insurer') {
$error = 'Expected value : UHID';
}
}else{
$error = 'Expected value : ENDORSEMENT ID';
}
}
$data = ['value' => $excel_data[$row][$column], 'error' => $error,];
$excel_data[$row][$column] = $data;
}
array_push($finalArray, $excel_data[$key]);
}
foreach ($finalArray as $fkey => $value) {
foreach ($value as $vkey => $arrayData) {
if (!is_array($arrayData)) {
$data = ['value' => $arrayData];
$finalArray[$fkey][$vkey] = $data;
}
}
}
$excelErrorData['excel_data'] = $finalArray;
$excelErrorData['file_id'] = $file_id;
// dd($finalArray);
echo view('export_import_error_list', $excelErrorData);
}
public function hasPolicyConfigCompleted()
{
$client_policy_id = $this->request->uri->getSegment(3);
$policy_details = $this->clientPolicyModel->find($client_policy_id);
$insurer_details = $this->insurerModel->where('id', $policy_details['insurer_id'])->first();
$policy_terms = isset($policy_details['policy_terms']) ? true : false;
$si_enhancement_true_or_false = 1;
if($policy_terms == true){
$policyTermsData = json_decode($policy_details['policy_terms']);
if (isset($policyTermsData->suminsuredenhancement) && $policyTermsData->suminsuredenhancement !== null) {
$si_enhancement_true_or_false = $policyTermsData->suminsuredenhancement;
}
}
$slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($client_policy_id,$policy_details['client_id']);
$message = null;
if ($policy_terms == false) {
$message .= 'Policy terms';
}
if($slab_details['slab_rates'] == null && $slab_details['grid_master'] == null)
{
$message = isset($message) ? ($message . ' and rack rates ') : ($message . ' Rack rates');
}
$message = isset($message) ? ($message . ' not defined for choosed policy') : null;
return $this->respond(['dataStatus' => true, 'code' => 200, 'message' => $message, 'si_enhancement' => $si_enhancement_true_or_false, 'insurer_multi_event' => $insurer_details['is_multi_event'] ?? null], 200);
}
public function testRackRate()
{
helper('excel_util_helper');
if ($this->request->getMethod() == 'get') {
$filterData = $this->request->getGet('client_policy_id');
//just load UI only
$this->loadLayout('rack_rate_test');
}
if ($this->request->getMethod() == 'post') {
$json = $this->request->getJSON();
// return $this->respond(['dataStatus' => false, 'code' => 200, 'data' => $data], 200);
// $data = (json_decode(json_encode($data),true));
$client_id = $json->client_id;
$policy_id = $json->policy_id;
$branch_id = $json->branch_id;
$unit_id = $json->unit_id;
$action = $json->action;
$family_code = $json->emp_code;
$tabledata = $json->data;
$existing_famility_details = [];
if(count($tabledata))
{
$family_details = [];
foreach($tabledata as $key => $row)
{
$row = (array)$row;
if(!$row['column12'])
{
$temp[0] = $row['column1'];//sno
$temp[1] = $family_code != "" ? $family_code : $row['column2'];//emp code
$temp[2] = $row['column3'];//name
$temp[3] = $row['column4'];//DOB
$temp[4] = strtoupper($row['column5']);//Gender
$temp[5] = $row['column6'];//relation
$temp[6] = $row['column7'];//SI
$temp[7] = $row['column8'];//DOC
$temp[8] = '';//DOJ
$temp[9] = $row['column9'];//BP
$temp[10] = $row['column10'];//band
$temp[11] = '';//designation
$temp[12] = '';//mobile
$temp[13] = '';//EMail
$temp[14] = '';//CE
$temp[15] = '';//RFE
$temp[16] = '';//DOE
$temp[17] = '';//Unit
$temp[18] = $unit_id;//unit
$family_details[] = $temp;
}
}
}
if($action == 'dependent_addition')
{
$existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(emp_code: $family_code,client_id: $client_id,client_policy_id: $policy_id,emp_status: ['active'],policy_status:['active'],client_branch_id: [ $branch_id ]);
// ~dd($this->employeeModel->getLastQuery());
if(!count($existing_famility_details))
{
return $this->respond(['dataStatus' => false, 'code' => 404, 'data' => [],'messgae' => "No Data found for emp code $family_code"], 200);
}
//transsform familiy details from db columns to exxcel row with column indexs for checking remaining functionalitites
$existing_famility_details = transform_db_data_to_excel($existing_famility_details,[]);
// Kint::dump($existing_famility_details);
$family_details = array_merge($family_details,$existing_famility_details);
$family_details = data_group_by_family($family_details)[ $family_code ];// reason to call this again is bring self to first index of the array
// dd($family);
}
//get policy details
$policy_details = $this->clientPolicyModel->getPolicyDetails($client_id,$policy_id);
$policy_details = (array)$policy_details[0];
// ~dd($policy_details[0]->policy_start_date);
//get rack rates
$slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($policy_id,$client_id);
//get file array or construnct dummy file array here
$file = ['id' => null,'client_id' => $client_id,'policy_id' => $policy_id,'action' => 'inception','client_branch_id' => $branch_id,'created_by' => 1];
//get existing units in the current branch
$existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $client_id,client_branch_id: $branch_id);
//get familiy details in inception file format array from post method
$data = calculate_premium_new(family_data: $family_details,policy_terms:$policy_details,slab_details:$slab_details,fileArr: $file,existing_units: $existing_units);
// print_rr($data);die();
foreach($data as $key => $member )
{
// ~dd($member);
if(is_array($member) && isset($member['policy_details']['date_coverage']) && isset($member['policy_details']['policy_end_date']) )
{
$data[$key]['policy_details']['no_of_days'] = $member['policy_details']['date_coverage'] ? (calculate_days_bw_dates($member['policy_details']['date_coverage'],$member['policy_details']['policy_end_date'])->days + 1) : '';
}
else
{
$data[$key]['policy_details']['no_of_days'] = '0';
}
}
return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => ['new' => $data,'old' => $existing_famility_details], 200]);
}
}
public function testCheckDependentConflict()
{
helper('excel_util_helper');
if ($this->request->getMethod() == 'get') {
$filterData = $this->request->getGet('client_policy_id');
//just load UI only
$this->loadLayout('rack_rate_test');
}
if ($this->request->getMethod() == 'post') {
$json = $this->request->getJSON();
// return $this->respond(['dataStatus' => false, 'code' => 200, 'data' => $data], 200);
// $data = (json_decode(json_encode($data),true));
$client_id = $json->client_id;
$policy_id = $json->policy_id;
$branch_id = $json->branch_id;
$tabledata = $json->data;
if(count($tabledata))
{
$family_details = [];
foreach($tabledata as $key => $row)
{
$row = (array)$row;
if(!$row['column12'])
{
$temp[0] = $row['column1'];//sno
$temp[1] = $row['column2'];//emp code
$temp[2] = $row['column3'];//name
$temp[3] = $row['column4'];//DOB
$temp[4] = strtoupper($row['column5']);//Gender
$temp[5] = $row['column6'];//relation
$temp[6] = $row['column7'];//SI
$temp[7] = $row['column8'];//DOC
$temp[8] = '';//DOJ
$temp[9] = $row['column9'];//BP
$temp[10] = $row['column10'];//band
$temp[11] = '';//designation
$temp[12] = '';//mobile
$temp[13] = '';//EMail
$temp[14] = '';//CE
$temp[15] = '';//RFE
$temp[16] = '';//DOE
$temp[17] = '';//Unit
$temp[18] = $row['column11'];//unit
$family_details[] = $temp;
}
}
}
// print_r($family_details);
// return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $family_details], 200);
//get policy details
$policy_details = $this->clientPolicyModel->getPolicyDetails($client_id,$policy_id);
$policy_terms = (array)$policy_details[0];
$is_lgbtq = $policy_terms['is_lgbtq'];
// dd($policy_terms);
$policy_terms = json_decode($policy_terms['policy_terms']);
$policy_terms = (array) $policy_terms;// convert obj to array
//get file array or construnct dummy file array here
$file = ['id' => null,'client_id' => $client_id,'policy_id' => $policy_id,'action' => 'inception','client_branch_id' => $branch_id,'created_by' => 1];
//get familiy details in inception file format array from post method
$result = check_dependent_conflict($family_details, $policy_terms, $file['action'],$is_lgbtq);
return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => ['policy_terms' => $policy_terms['family_floaters'],'result' => $result] ], 200);
}
}
public function get_client_policy_list_for_remainder($client_id, $client_branch_id)
{
$policies = $this->clientPolicyModel
->select('client_policy.*, policy_type.policy_type as policy_name')
->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
->where('client_policy.client_id', $client_id)
->where('client_policy.client_branch_id', $client_branch_id)
->where('client_policy.is_active', 1)
->where('client_policy.policy_status', 1)
->whereIn('client_policy.policy_type_id', [2, 3])
->findAll();
return $this->respond(['status' => true, 'code' => 200, 'data' => $policies], 200);
}
//-------- Edit individual employee and View & Send E-card -----------------------------------------------------------------------------------------
public function get_emp_master_data_for_update($id)
{
$employee_data = $this->employeeModel->select("employees.*, DATE_FORMAT(dob, '%d/%m/%Y') AS formatted_dob,")->where('id', $id)->first();
if ($employee_data) {
return $this->respond(['status' => true,'code' => 200,'data' => $employee_data,], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'No data found.'], 404);
}
}
//UPDATE EMPLOYEE
public function update_emp_data()
{
helper('utility_helper');
$data = $this->request->getPost();
// print_rr($data);die();
// $data['dob'] = date('Y-m-d', strtotime($data['dob']));
if (isset($data['dob'])) {
$data['dob'] = change_date_format($data['dob'], null, 'Y-m-d');
}
// print_rr($data); die;
// Fetch current employee data
$employee_data = $this->employeeModel->where('id', $data['employee_primary_id'])->first();
if ($employee_data['relationship'] == 'Self') {
if (isset($data['gender'])) {
if ($employee_data['gender'] != $data['gender']) {
$spouse_gender = ($data['gender'] == 'M') ? 'F' : 'M';
$this->employeeModel
->where('emp_code', $employee_data['emp_code'])
->where('relationship', 'Spouse')
->set(['gender' => $spouse_gender])
->update();
}
}
}
// Update the employee data
$result = $this->employeeModel->where('id', $data['employee_primary_id'])->set($data)->update();
if ($result) {
return $this->respond(['status' => true, 'code' => 200, 'data' => $data, 'message' => 'Employee updated successfully'], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to update employee.'], 404);
}
}
public function send_mail_for_individual_employee_ecard($id)
{
$ids[] = $id;
$empDataServiceController = new EmpDataServiceController();
$result = $empDataServiceController->sendMailForDownloadingECard($ids, 1);
if ($result) {
return $this->respond(['status' => true,'code' => 200,'message' => 'Mail sent successfully', 'result' => $result,], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to sent mail.'], 404);
}
}
public function checkDeletionGetDataFunction()
{
// $batch_data = [
// 'client_id' => 159,
// 'client_policy_id' => 336,
// 'client_branch_id' => 126,
// ];
// $batch_data['insurer_or_tpa'] = 'insurer';
// $batch_data['insurer_or_tpa'] = 'tpa';
//INCEPTION
// $result = $this->employeePolicyModel->getInceptionEmployeeDataForExportExcel($batch_data);
// CORRECTION
// $result = $this->employeePolicyModel->getCorrectionEmployeesDataForExportExcel($batch_data);
//SI-ENHANCEMENT
// $result = $this->employeePolicyModel->getSIEnhancementEmployeesDataForExportExcel($batch_data);
//DELETION
// $result = $this->employeePolicyModel->getDeletionEmployeeDataForExportExcel($batch_data);
// print_rr($result); die;
//-------------------------------------------------------------------------------------------------------------
// $ids = [
// 'employeeIds' => [20252, 20258, 20277, 20282, 20196, 20237, 20314, 20325, 20356],
// 'client_id' => 17,
// 'client_policy_id' => 30,
// 'client_branch_id' => 18,
// 'cd_ac_no' => $CD_Account_Number['cd_ac_no'] ?? null,
// 'endorsement_no' => $endorsement_id ?? null,
// 'count' => 9,
// // 'event_name' => $file['event_type'],
// // 'policy_name' => $policy_name['policy_name'],
// // 'user_id' => $user_id,
// ];
// $empDataServiceController = new EmpDataServiceController();
// $result = $empDataServiceController->cashDepositCalculationForDeletion($ids);
}
// ---------- DOWNLOAD IMPORT BATCH FILE AND SAMPLE FILE ------------------------------------------------------------------------------------------------
public function downloadSampleImportExcelFile($actionType = null)
{
// $actionType = $this->request->getGet();
$filePath = '';
// Path to your file
if ($actionType == 'inception') {
$filePath = ROOTPATH . 'public/sample_import_excel/sample_import_Inception.xlsx';
} else if ($actionType == 'correction') {
$filePath = ROOTPATH . 'public/sample_import_excel/sample_import_correction.xlsx';
} else if ($actionType == 'si_enhancement') {
$filePath = ROOTPATH . 'public/sample_import_excel/sample_import_SI_Enhancement.xlsx';
} else if ($actionType == 'dependent_addition') {
$filePath = ROOTPATH . 'public/sample_import_excel/sample_import_Dependent_Addition.xlsx';
} else if ($actionType == 'addition') {
$filePath = ROOTPATH . 'public/sample_import_excel/sample_import_Addition.xlsx';
} else if ($actionType == 'deletion') {
$filePath = ROOTPATH . 'public/sample_import_excel/sample_import_Deletion.xlsx';
}else if ($actionType == 'missed_inception') {
$filePath = ROOTPATH . 'public/sample_import_excel/sample_import_Inception.xlsx';
}
// Check if the file exists
if (file_exists($filePath)) {
// Set the appropriate MIME type
$mimeType = mime_content_type($filePath);
// Send the file to the client for download
return $this->response->download($filePath, null, $mimeType);
} else {
// File not found, show an error message or redirect
echo view('errors/html/production');
}
}
public function download_import_file($file_id)
{
// $actionType = $this->request->getGet();
$file_data = $this->batchFileModel->where('id', $file_id)->first();
$fileName = $file_data['file_name'];
$filePath = WRITEPATH . '/uploads/import_excel/' . $fileName;
try {
// Check if the file exists
if (file_exists($filePath)) {
// Set the appropriate MIME type
$mimeType = mime_content_type($filePath);
// Send the file to the client for download
return $this->response->download($filePath, null, $mimeType);
} else {
$data['message'] = 'The Physical File Not Found';
echo view('errors/404', $data);
}
} catch (\Exception $e) {
// Handle any exceptions
$errorMessage = $e->getMessage();
$this->myLogger->logme('error', $errorMessage);
// You can return an error response here
echo $errorMessage;
}
}
//--------- LOG FILE VIEW AND DOWNLOAD ---------------------------------------------------------------------------------------------
public function listLogs()
{
$logPath = WRITEPATH . 'logs/';
$logs = [];
// Check if the log directory exists
if (is_dir($logPath)) {
$files = array_diff(scandir($logPath), ['.', '..']); // Exclude '.' and '..'
$files = array_reverse($files);
foreach ($files as $file) {
if (is_file($logPath . $file)) {
$logs[] = $file; // Add log files to the list
}
}
}
$data['logs'] = $logs;
$data['server_details'] = get_server_details();
// Pass log files to the view
return $this->loadLayout('log_view', $data);
}
public function downloadLog($fileName)
{
$logPath = WRITEPATH . 'logs/' . $fileName;
// Check if the requested file exists
if (file_exists($logPath)) {
return $this->response->download($logPath, null)->setFileName($fileName);
}
// Redirect back with an error if file doesn't exist
return redirect()->back()->with('error', 'Log file not found.');
}
public function viewLog($fileName)
{
$logPath = WRITEPATH . 'logs/' . $fileName;
if (file_exists($logPath)) {
$content = file_get_contents($logPath);
$data['fileName'] = $fileName;
$data['content'] = $content;
$data['server_details'] = get_server_details();
return $this->loadLayout('log_content_view', $data);
}
return redirect()->back()->with('error', 'Log file not found.');
}
public function exportToExceltpadata()
{
// Create a new Spreadsheet
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// Header row
$headers = [
'TPA_NAME', 'SHORT_NAME', 'TPA_BRANCH_NAME', 'TPA_BRANCH_CODE',
'TPA_CONTACT_PERSON_NAME', 'TPA_CONTACT_PERSON_EMAIL', 'TPA_CONTACT_PERSON_MOBILE',
'TPA_CONTACT_PERSON_DESIGNATION', 'IS_DELETED'
];
$sheet->fromArray($headers, NULL, 'A1');
// Data rows
$data = [
["ICICI Lombard Health Care", "IL Health care", "Chennai", "997133", "Heena", "dharanisri@jubiliant.in", "9043955294", "General Manager", "YES"],
["ICICI Lombard Health Care", "IL Health care", "Chennai", "997133", "Mahammad shireen", "mahammad.shireen@icicilombard.com", "8655420732", "Claims head", "NO"],
["Medi Assist Insurance TPA Private Limited", "Medi Assist", "Chennai", "YA0000000348", "Ragavi", "dharanisri@jubiliant.in", "9043955294", "Senior Manager", "YES"],
["Medi Assist Insurance TPA Private Limited", "Medi Assist", "Chennai", "YA0000000348", "Vijayalakshmi", "vijayalakshmi.c@mediassist.in", "7795542162", "Senior Executive | Account Management", "NO"],
["Vidal Health Insurance TPA", "Vidal", "Chennai", "YA0000000349", "vijalakshmi", "vijayalakshmi.c@mediassist.in", "7795542162", "Senior Executive", "NO"],
["Vidal Health Insurance TPA", "Vidal", "Chennai", "YA0000000349", "M.Pushparaj", "pushparaj.moorthy@vidalhealth.com", "8939634456", "Executive", "NO"],
["Digit in-House", "Digit in-House", "Go Digit General Insurance Ltd", "1", "sathish", "sathish.n@vidalhealth.com", "7823913800", "Senior Executive", "NO"],
["Digit in-House", "Digit in-House", "Go Digit General Insurance Ltd", "1", "Mr. Pavan", "TK.Pavankumar@godigit.com", "8754490492", "Strategic Partnerships", "NO"],
["Aditya Birla Health Insurance Co. Limited", "ABHI", "Chennai", "O1", "sathish", "sathish.n@vidalhealth.com", "7823913800", "Senior Executive", "NO"],
["Aditya Birla Health Insurance Co. Limited", "ABHI", "Chennai", "O1", "Jhonson Kj", "jhonson.kj@adityabirlacapital.com", "9900729513", "Executive", "NO"],
["Aditya Birla Health Insurance Co. Limited", "ABHI", "Chennai", "01", "Jhonson Kj", "jhonson.kj@adityabirlacapital.com", "9900729513", "Executive", "NO"],
["R Care Health", "R Care", "Chennai", "01", "Jeevanadam", "Jeevanandam.Kumaran@relianceada.com", "8825982053", "Executive", "NO"],
["IFFCO-TOKIO GENERAL INSURANCE CO. LTD", "ITGI", "Chennai", "01", "Anjali", "Anjali.K@ext.iffcotokio.co.in", "6374270165", "Senior Executive", "NO"],
["Star Health and Allied Insurance", "STAR", "Chennai", "110000", "Mr. Vijay Baskar", "vijayabhaskar.m@starhealth.in", "9840905286", "Area Manager", "NO"],
];
$sheet->fromArray($data, NULL, 'A2');
// Save the file
$filename = 'TPA_Data.xlsx';
$writer = new Xlsx($spreadsheet);
// Set headers for download
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
exit;
}
//------------------------------------------------------------------------------------------------------
public function test_members_list()
{
// $model = new EmployeeModel();
// $list = [
// ['relationship' => 'spouse','emp_code' => 'TEST002', 'name' => 'Lakshmi','email_personal' => 'lakshmi@gmail.com','mobile'=>'6382156701','gender'=>'female','dob'=>'1996-05-19','doj'=>'2022-02-01','basic_pay'=>'100000','emp_status'=>'enrolled'],
// ['relationship' => 'Daughter','emp_code' => 'TEST002', 'name' => 'Jayalakshmi','email_personal' => 'jayalakshmi@gmail.com','mobile'=>'6382156701','gender'=>'female','dob'=>'2018-05-19','doj'=>'2022-02-01','basic_pay'=>'100000','emp_status'=>'enrolled'],
// ['relationship' => 'Son','emp_code' => 'TEST002', 'name' => 'Jayam Ravi','email_personal' => 'jayamravi@gmail.com','mobile'=>'6382156701','gender'=>'male','dob'=>'1994-05-19','doj'=>'2019-02-01','basic_pay'=>'100000','emp_status'=>'enrolled'],
// // ['relationship' => 'self','emp_code' => 'TEST003', 'name' => 'Ravi Shankar','email_personal' => 'srinivassaravanan2002@gmail.com','email_corporate'=>'srinivas.saravanan@venbainfotech.com','mobile'=>'6382156701','gender'=>'male','dob'=>'1994-05-19','doj'=>'2022-02-01','basic_pay'=>'100000','emp_status'=>'enrolled']
// ['relationship' => 'spouse','emp_code' => 'TEST001', 'name' => 'Lakshmi','email_personal' => 'lakshmi@gmail.com','mobile'=>'6382156701','gender'=>'female','dob'=>'1996-05-19','doj'=>'2022-02-01','basic_pay'=>'100000','emp_status'=>'enrolled'],
// ];
// foreach($list as $listitem){
// $model->insert($listitem);
// }
// die();
$employee_data = $this->employeeModel->getTestEmployeeData();
$data['employees'] = $employee_data;
$data['clients'] = $this->clientModel->findAll();
// dd($data);
return $this->loadLayout('test_members_list',$data);
}
public function mapEmployees()
{
$client_id = $this->request->getPost('client_id');
$branch_id = $this->request->getPost('branch_id');
$policy_id = $this->request->getPost('client_policy_id');
$selected_employees = (array)$this->request->getPost('selected');
$si_amt = $this->request->getPost('si_amt');
$policy_start_date_unformatted = $this->request->getPost('policy_start_date');
$policy_start_date = change_date_format($policy_start_date_unformatted, 'd/M/Y', 'Y-m-d');
$data1 = [
'client_id' => $client_id,
'client_branch_id' => $branch_id,
];
$data2 = [
'client_policy_id' => $policy_id,
'status' => 'draft',
'date_coverage' => $policy_start_date,
'basic_cover_si' => $si_amt,
];
for($i = 0; $i < count($selected_employees); $i++){
$data2['employee_id'] = $selected_employees[$i];
$result1 = $this->employeeModel->set($data1)->where('id',$selected_employees[$i])->update();
$result2 = $this->employeePolicyModel->insert($data2);
}
if ($result1 && $result2) {
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Employees mapped successfully'], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to map employees.'], 404);
}
}
public function getDataForMapping()
{
$policy_id = $this->request->getPost('policy_id');log_message('error',$policy_id);
$data['policy_start_date'] = $this->clientPolicyModel->select('policy_start_date')->where('id',$policy_id)->first()['policy_start_date'];
$data['si_amt'] = $this->PolicyPremium2Model->select('si')->where('client_policy_id', $policy_id)->groupBy('si')->findAll();
log_message('error',json_encode($data).'policy id '.$policy_id);
return $this->respond(['status' => true, 'code' => 200, 'data' => $data], 200);
}
public function unmapEmployees($actionType)
{
$selected_employees = (array)$this->request->getPost('selected');
if($actionType == 0){
for($i = 0;$i<count($selected_employees);$i++){log_message('error',$selected_employees[$i]);
$result1 = $this->employeeModel->set(['client_id' => null, 'client_branch_id' => null])->where('id',$selected_employees[$i])->update();log_message('error',$result1);
$result2 = $this->employeePolicyModel->where('employee_id',$selected_employees[$i])->delete();log_message('error',$result2);
}
}
else if ($actionType == 1){
for($i = 0;$i<count($selected_employees);$i++){
log_message('error','Emp id is '.$selected_employees[$i]);
$result1 = $this->employeeModel->set(['client_id' => null, 'client_branch_id' => null])->where('id',$selected_employees[$i])->update();log_message('error','result 1 is '.$result1);
$result2 = $this->employeePolicyModel->where('employee_id',$selected_employees[$i])->delete();log_message('error', 'result 2 is '.$result2);
$emp_code = $this->employeeModel->select('emp_code')->where('id',$selected_employees[$i])->first()['emp_code'];log_message('error','emp_code is '.$emp_code);
$result3 = $this->employeeModel->where('emp_code',$emp_code)->whereNotIn('relationship',['self'])->delete();log_message('error','result 3 is '.$result3);
}
}
else{
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Invalid action type.'], 404);
}
if($actionType == 1){
if($result1 && $result2 && $result3){
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Employees unmapped successfully and Dependencies are Deleted'], 200);
}
else{
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to unmap employees.'], 404);
}
}else{
if($result1 && $result2 ){
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Employees unmapped successfully'], 200);
}
else{
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to unmap employees.'], 404);
}
}
}
public function cloneWorksheet()
{
// Define file paths
$inputFilePath = 'C:\Users\Venba\Downloads/merge1.xlsx'; // Path to the existing file
$outputFilePath = WRITEPATH . '/tmp/cloned_file.xlsx'; // Path to save the new file
try {
// Load the existing spreadsheet
$spreadsheet = IOFactory::load($inputFilePath);
// Get the first worksheet (or specify the index of the sheet to clone)
$originalWorksheet = $spreadsheet->getSheet(0);
// Clone the worksheet
$clonedWorksheet = clone $originalWorksheet;
// Generate a unique name for the cloned worksheet
$baseName = "Cloned Sheet";
$sheetIndex = 1;
$uniqueName = $baseName;
// Check for duplicate names and generate a unique one
while ($spreadsheet->sheetNameExists($uniqueName)) {
$uniqueName = $baseName . " " . $sheetIndex;
$sheetIndex++;
}
// Set the unique name for the cloned worksheet
$clonedWorksheet->setTitle($uniqueName);
// Add the cloned worksheet to the spreadsheet
$spreadsheet->addSheet($clonedWorksheet);
// Modify the cloned sheet (optional)
$clonedWorksheet->setCellValue('A1', 'Hello, Cloned Sheet!');
// Save the modified spreadsheet to a new file
$writer = new Xlsx($spreadsheet);
$writer->save($outputFilePath);
return $this->response->setJSON([
'status' => 'success',
'message' => 'Spreadsheet with cloned sheet created successfully!',
'file_path' => $outputFilePath,
]);
} catch (\Exception $e) {
// Handle exceptions
return $this->response->setJSON([
'status' => 'error',
'message' => $e->getMessage(),
]);
}
}
//------------------------------------------------------------------------------------------------------
public function generateAcmAndMForEcard($client_id)
{
$db = db_connect();
$builder = $db->table('client_rm');
$builder->select('user_profiles.first_name, user_profiles.mobile, user_profiles.email, client_rm.level');
$builder->join('user_profiles', 'client_rm.user_id = user_profiles.id');
$builder->where('client_rm.client_id', $client_id);
$builder->whereIn('client_rm.level', [2, 3]);
$builder->where('client_rm.is_active', 1);
$builder->orderBy('client_rm.level', 'desc');
$query = $builder->get();
$result = $query->getResultArray();
$levels = [
3 => [],
2 => []
];
foreach ($result as $value) {
$levels[$value['level']][] = $value;
}
// Generate the HTML content
$html = '';
foreach ($levels as $level => $contacts) {
$displayLevel = $level == 3 ? 1 : 2; // Switch levels for display
$html .= '<br>Level ' . $displayLevel . '<br>';
foreach ($contacts as $index => $contact) {
$html .= ($index + 1) . '. ' . $contact['first_name'] . ' / ' . $contact['mobile'] . ' / ' . $contact['email'] . '<br>';
}
}
$html .= '<br><br><br>';
return $html;
}
public function getEmpHistory()
{
$emp_id = $this->request->getPost('emp_id');
$data['emp_history'] = $this->auditHistory->select('field_name,old_value,new_value,created_by,created_at')->where('pk',$emp_id)->where('table_name','employees')->orderBy('created_at', 'DESC')->findAll();
foreach ($data['emp_history'] as &$emp_history) {
$emp_history['field_name'] = $this->formatFieldName($emp_history['field_name']);
$user = $emp_history['created_by'];
if ($user != null && $user != '') {
$userData = $this->userModel->select('first_name, last_name')->where('id', $user)->where('is_active', 1)->first();
if ($userData) {
$emp_history['created_by'] = ucwords($userData['first_name'] . ' ' . $userData['last_name']);
} else {
$emp_history['created_by'] = '-';
}
} else {
$emp_history['created_by'] = '-';
}
$emp_history['created_at'] = date("d/m/Y H:i:s", strtotime($emp_history['created_at']));
}
unset($emp_history);
$emp_pol_pk = $this->employeePolicyModel->select('id')->where('employee_id',$emp_id)->first()['id'];
$data['emp_pol_history'] = $this->auditHistory->select('field_name,old_value,new_value,created_by,created_at')->where('pk',$emp_pol_pk)->where('table_name','employee_polices')->findAll();
return $this->respond(['status' => true, 'data' => $data],200);
}
public function formatFieldName($unformattedString)
{
if (str_contains($unformattedString, '_')) {
$data = str_replace('_', ' ', $unformattedString);
}else{
$data = $unformattedString;
}
$format = ucwords($data);
return $format;
}
//------------------------------------------------------------------------------------------------------
public function download_inception()
{
$client = $this->request->getPost('client');
$branch = $this->request->getPost('branch');
$policies = $this->request->getPost('policies');
$status = $this->request->getPost('status');
$empCode = $this->request->getPost('empCode');
$empName = $this->request->getPost('empName');
$result = $this->employeePolicyModel->download_inception(
$client, $branch, $policies, $status, $empCode, $empName
);
if (empty($result)) {
return $this->response->setStatusCode(204)->setBody('No data found');
}
$formatted = [];
foreach ($result as $index => $row) {
$rowWithSerial = ['S.NO' => $index + 1] + $row;
$formatted[] = $rowWithSerial;
}
$result = $formatted;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$headers = array_keys($result[0]);
$columnWidth = 20; // standard column width
$colIndex = 1;
foreach ($headers as $header) {
$columnLetter = Coordinate::stringFromColumnIndex($colIndex);
$cellCoordinate = $columnLetter . '1';
$sheet->setCellValue($cellCoordinate, ucfirst(str_replace('_', ' ', $header)));
$sheet->getColumnDimension($columnLetter)->setWidth($columnWidth);
$style = $sheet->getStyle($cellCoordinate);
$style->getFont()->setBold(true);
$style->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
$style->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN);
$colIndex++;
}
$rowNum = 2;
foreach ($result as $row) {
$colIndex = 1;
foreach ($row as $cell) {
$columnLetter = Coordinate::stringFromColumnIndex($colIndex);
$cellCoordinate = $columnLetter . $rowNum;
$sheet->setCellValue($cellCoordinate, $cell);
$colIndex++;
}
$rowNum++;
}
$exportDir = WRITEPATH . 'exports';
if (!is_dir($exportDir)) {
mkdir($exportDir, 0777, true);
} else {
// chmod($exportDir, 0777);
}
$filename = 'inception_export_' . date('Ymd_His') . '.xlsx';
$filepath = $exportDir . '/' . $filename;
$writer = new Xlsx($spreadsheet);
$writer->save($filepath);
return $this->response->setJSON([
'status' => 'success',
'downloadUrl' => base_url('employee/download_file?file=' . urlencode($filename))
]);
}
public function download_file()
{
$filename = $this->request->getGet('file');
$filepath = WRITEPATH . 'exports/' . $filename;
if (!file_exists($filepath)) {
return $this->response->setStatusCode(404)->setBody('File not found.');
}
return $this->response->download($filepath, null)->setFileName($filename);
}
}