nhance/app/Controllers/EmpDataServiceController.php

2271 lines
81 KiB
PHP

<?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\Helpers\MailHelper;
use App\Helpers\sendMailNotification;
use App\Models\EmployeeModel;
use App\Models\EmployeePolicyModel;
use App\Models\ClientModel;
use App\Models\ClientPolicyModel;
use App\Models\FileModel;
use App\Models\BatchListModel;
use App\Models\BatchFileModel;
use App\Models\EmpEndorsementModel;
use App\Models\ClientDepositModel;
use App\Models\NotificationModel;
use App\Models\MessageModel;
use App\Models\UserMessageModel;
use App\Controllers\Jobs;
use App\Controllers\JobWorker;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Exception as SpreadsheetReaderException;
use PhpParser\Node\Expr\Cast\Double;
use function PHPUnit\Framework\returnSelf;
class EmpDataServiceController extends BaseController
{
protected $myLogger;
protected $employeeModel;
protected $employeePolicyModel;
protected $clientModel;
protected $fileModel;
protected $clientPolicyModel;
protected $batchListModel;
protected $batchFileModel;
protected $empEndorsementModel;
protected $clientDepositModel;
protected $notificationModel;
protected $messageModel;
protected $userMessageModel;
public function __construct()
{
// helper('utility');
set_session_context('EmployeeDataService Second Service');
$this->myLogger = \Config\Services::mylogger();
$this->employeeModel = new EmployeeModel();
$this->employeePolicyModel = new EmployeePolicyModel();
$this->clientModel = new ClientModel();
$this->fileModel = new FileModel();
$this->clientPolicyModel = new ClientPolicyModel();
$this->batchListModel = new BatchListModel();
$this->batchFileModel = new BatchFileModel();
$this->empEndorsementModel = new EmpEndorsementModel();
$this->clientDepositModel = new ClientDepositModel();
$this->notificationModel = new NotificationModel();
$this->messageModel = new MessageModel();
$this->userMessageModel = new UserMessageModel();
}
/**
* The below function are Inserts batch files and corresponding batch list entries into the database.
*
* @param array $data An array containing data for batch file insertion.
* @param array $objects An array of objects containing information for batch list entries.
* @return bool Returns true on successful insertion.
*/
public function batchFilesAndBatchListEntry($data, $objects)
{
$random_number_count = 4;
$data['batch_code'] = generate_random_string($random_number_count);
$data['created_by'] = get_session_userid();
$insert = $this->batchFileModel->insert($data);
$batch_file_batch_code = $this->batchFileModel->where('id', $insert)->first();
if ($insert) {
foreach ($objects as $value) {
$batch_list_data['batch_code'] = $batch_file_batch_code['batch_code'];
$batch_list_data['emp_policy_id'] = $value->primaryKey ?? $value->employee_policy_id ?? '';
$batch_list_data['created_by'] = get_session_userid();
$this->batchListModel->insert($batch_list_data);
}
}
return true;
}
public function insertBatchList($params){
foreach ($params['batch_list_data'] as $value) {
$batch_list_data['batch_code'] = $params['batch_code'];
$batch_list_data['emp_policy_id'] = $value['primaryKey'];
$batch_list_data['created_by'] = get_session_userid();
$this->batchListModel->insert($batch_list_data);
}
}
/**
* Generates an Excel file for Inception_Addititon_DependentAddititon, Correction, SI_Enhancement and Deletion events based on given export data.
*
* @param array $export_data An array containing export data such as
* client_policy_id,
* insurer_or_tpa,
* event_type,
* actions,
* file_name.
* @return bool True if the Excel file is successfully generated and exported, otherwise false.
*/
public function generateExcelForAdditionandInception($export_data)
{
$return = $this->removeOldExportInfoFromBatchFile($export_data);
// Fetch employee data for export from the database
$objects = $this->employeePolicyModel->getInceptionEmployeeDataForExportExcel($export_data);
$insurer_id = $this->clientPolicyModel->where('id', $export_data['client_policy_id'])->first();
$cash_balance = $this->clientDepositModel->where('client_id', $export_data['client_id'])->where('insurer_id', $insurer_id['insurer_id'])->orderBy('id', 'DESC')->first();
$totals = 0;
foreach ($objects as $key => $value) {
$totals += $value->total;
}
if (!empty($cash_balance)) {
if ((int) $cash_balance['balance'] < (int) $totals) {
return 0;
}
} else {
// return 0;
}
// Log the count of exported data
$count = count($objects);
$export_data['count'] = $count;
$export_data['amount'] = $totals;
$export_data['status'] = 'success';
$this->myLogger->logme('error', 'Inception export data count : {data}', ['data' => $count]);
// If no data is found for export, return false
if ($count == 0) {
return false;
}
// Log the export file name
$this->myLogger->logme('error', 'Inception export file name : {data}', ['data' => $export_data['file_name']]);
// Transform retrieved objects to an array suitable for export
$data = transform_objects_to_array_for_inception($objects);
// Define headers for the Excel file
$headers = [
'S.No',
'NAME OF EMP/DEP',
'EMP ID',
'EMP/DEP TYPE',
'RELATION',
'DOB',
'GENDER',
'PRE EXISTING AILMENTS',
'BASIC COVER SI',
'DATE OF COVERAGE',
'AGE',
'RELATIONSHIP',
'REMARKS',
'POLICY END DATE',
'NO OF DAYS',
'TPA ID',
'UHID',
'PREMIUM',
'PR0 RATA PREMIUM',
'GST',
'TOTAL'
];
// Generate Excel file
$tempFile = tmpfile();
$success = generate_excel($headers, $data, $tempFile, 1);
// If Excel generation is successful
if ($success) {
// Batch files and list entry
// $return = $this->batchFilesAndBatchListEntry($export_data, $objects);
$random_number_count = 4;
$export_data['batch_code'] = generate_random_string($random_number_count);
$export_data['created_by'] = get_session_userid();
$insert = $this->batchFileModel->insert($export_data);
$batch_file_batch_code = $this->batchFileModel->where('id', $insert)->first();
$batch_code = $batch_file_batch_code['batch_code'];
// $this->insertBatchList(['batch_code' => $batch_code, 'batch_list_data' => $objects ]);
$job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'insertBatchList','payload' => ['batch_code' => $batch_code, 'batch_list_data' => $objects ]]);
// If batch operation is successful
if (true) {
// Set headers for Excel file download
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $export_data['file_name'] . '"');
header('Cache-Control: max-age=0');
// Output file contents
rewind($tempFile);
fpassthru($tempFile);
// Close and remove temporary file
fclose($tempFile);
return true; // Excel file successfully generated and exported
} else {
return false; // Batch operation failed
}
}
return false; // Excel generation failed
}
public function generateExcelForCorrection($export_data)
{
$ids = [];
$objects = $this->employeePolicyModel->getCorrectionEmployeesDataForExportExcel($export_data);
foreach ($objects as $obj) {
$ids[] = $obj->id;
}
// echo '<pre>';
// print_r($objects); die;
$count = count($objects);
$export_data['count'] = $count;
$this->myLogger->logme('error', 'Correction export data count : {data}', ['data' => $count]);
if ($count == 0) {
return false;
}
$this->myLogger->logme('error', 'Correction export file name : {data}', ['data' => $export_data['file_name']]);
$correction_data = transform_objects_to_array_for_correction($objects);
$headers = [
'Emp Code',
'RISK ID',
'NAME OF EMP/DEP',
'EMP/DEP TYPE',
'RELATION',
'DOB',
'GENDER',
'Wrong Data',
'Correct Data',
'Remarks',
'Endorsement_Id'
];
// Create a temporary file in memory
$tempFile = tmpfile();
// Generate Excel file with the temporary file
$value = generate_excel($headers, $correction_data, $tempFile);
if ($value) {
$return = $this->batchFilesAndBatchListEntry($export_data, $objects);
if ($return) {
foreach ($ids as $key => $id) {
$group_key = $this->empEndorsementModel->select('group_key')->where('id', $id)->first();
if ($group_key) {
$this->empEndorsementModel->where('group_key', $group_key)->set('status', 'inprogress')->update();
}
}
// Set the appropriate headers for Excel file download
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $export_data['file_name'] . '"');
header('Cache-Control: max-age=0');
// Rewind the temporary file pointer
rewind($tempFile);
// Output the contents of the temporary file to the browser
fpassthru($tempFile);
// Close and remove the temporary file
fclose($tempFile);
return true;
} else {
return false;
}
}
}
public function generateExcelForSIEnhancement($export_data)
{
$ids = [];
$objects = $this->employeePolicyModel->getSIEnhancementEmployeesDataForExportExcel($export_data);
$totals = 0;
foreach ($objects as $obj) {
$ids[] = $obj->endorsement_primarykey;
$totals += $obj->total;
}
$rounded_totals = round($totals, 2);
// echo '<pre>';
// print_r($ids); die;
$count = count($objects);
$export_data['count'] = $count;
$export_data['amount'] = $rounded_totals;
$this->myLogger->logme('error', 'SI_Enhancement export data count : {data}', ['data' => $count]);
if ($count == 0) {
return false;
}
$this->myLogger->logme('error', 'SI_Enhancement export file name : {data}', ['data' => $export_data['file_name']]);
$si_data = transform_objects_to_array_for_si_enhancement($objects);
$headers = [
'S.No',
'NAME OF EMP/DEP',
'EMP ID',
'EMP/DEP TYPE',
'RELATION',
'DOB',
'GENDER',
'PRE EXISTING AILMENTS',
'BASIC COVER SI',
'Old Sum Insured',
'Date of Coverage',
'Policy End Date',
'No Of Days',
'Old SI Premium',
'New SI premium',
'Difference premium',
'Pro Rata Premium',
'GST',
'Total',
'ENDORSEMENT_ID'
];
// Create a temporary file in memory
$tempFile = tmpfile();
// Generate Excel file with the temporary file
$value = generate_excel($headers, $si_data, $tempFile);
if ($value) {
$return = $this->batchFilesAndBatchListEntry($export_data, $objects);
if ($return) {
foreach ($ids as $key => $id) {
$group_key = $this->empEndorsementModel->select('group_key')->where('id', $id)->first();
if ($group_key) {
$this->empEndorsementModel->where('group_key', $group_key)->set('status', 'inprogress')->update();
}
}
// Set the appropriate headers for Excel file download
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $export_data['file_name'] . '"');
header('Cache-Control: max-age=0');
// Rewind the temporary file pointer
rewind($tempFile);
// Output the contents of the temporary file to the browser
fpassthru($tempFile);
// Close and remove the temporary file
fclose($tempFile);
return true;
} else {
return false;
}
}
}
public function generateExcelForDeletion($export_data)
{
$ids = [];
$objects = $this->employeePolicyModel->getDeletionEmployeeDataForExportExcel($export_data);
$totals = 0;
foreach ($objects as $obj) {
$ids[] = $obj->endorsement_primarykey;
$totals += $obj->total;
}
$rounded_totals = round($totals, 2);
// echo '<pre>';
// print_r($ids);
// print_r($objects); die;
$count = count($objects);
$export_data['count'] = $count;
$export_data['amount'] = $rounded_totals;
$this->myLogger->logme('error', 'Deletion export data count : {data}', ['data' => $count]);
if ($count == 0) {
return false;
}
$this->myLogger->logme('error', 'Deletion export file name : {data}', ['data' => $export_data['file_name']]);
$si_data = transform_objects_to_array_for_deletion($objects);
// dd($si_data);
$headers = [
'S.No',
'EMP ID',
'EMP NAME',
'DOB',
'GENDER',
'RELATIONSHIP',
'SUM INSURED',
'Date of Leaving',
'Policy End Date',
'No Of Days',
'Premium',
'Pro Rata Premium',
'GST',
'Total',
'Claim Status',
'ENDORSEMENT_ID'
];
// Create a temporary file in memory
$tempFile = tmpfile();
// Generate Excel file with the temporary file
$value = generate_excel($headers, $si_data, $tempFile, 2);
if ($value) {
$return = $this->batchFilesAndBatchListEntry($export_data, $objects);
if ($return) {
foreach ($ids as $key => $id) {
$group_key = $this->empEndorsementModel->select('group_key')->where('id', $id)->first();
if ($group_key) {
$this->empEndorsementModel->where('group_key', $group_key)->set('status', 'inprogress')->update();
}
}
// Set the appropriate headers for Excel file download
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $export_data['file_name'] . '"');
header('Cache-Control: max-age=0');
// Rewind the temporary file pointer
rewind($tempFile);
// Output the contents of the temporary file to the browser
fpassthru($tempFile);
// Close and remove the temporary file
fclose($tempFile);
return true;
} else {
return false;
}
}
}
/**
* The below functions are Imports data from an Excel file for :
* - Inception
* - Deletion
* - Correction
* - SI_Enhancement
*
* This functions are processes the uploaded Excel file, extracts relevant information,
* and updates employee policies and employees table accordingly.
*
* @param array $import_data An associative array containing :
* - client_id,
* - client_policy_id,
* - the uploaded file.
* @return int Returns:
* - 1 if data import is successful.
* - 2 if the file does not exist.
* - 0 if the provided data is incomplete or incorrect.
*/
public function importExcelDataForInception($import_data)
{
$file = $import_data['file'];
$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;
$import_data['batch_code'] = generate_random_string($random_number_count);
$import_data['created_by'] = get_session_userid();
$import_data['status'] = 'pending';
$import_data['file_name'] = $filename;
$insert = $this->batchFileModel->insert($import_data);
$file_id['file_id'] = $insert;
$job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'importInceptionFileValidation','payload' => ['file_id' => $insert]]);
return 1;
}
public function importInceptionFileValidation($params)
{
$this->myLogger->logme('info', 'importInceptionFileValidation called');
$file_id = $params['file_id'];
$this->myLogger->logme('error', 'importInceptionFileValidation batch file table primary id : {data}', ['data' => $file_id]);
$file = $this->batchFileModel->where('id', $file_id)->first();
$client_id = $file['client_id'];
$client_policy_id = $file['client_policy_id'];
$batch_code = $file['batch_code'];
$insurer_or_tpa = $file['insurer_or_tpa'];
if ($insurer_or_tpa == 'tpa') {
$id = 'tpa_id';
} else if ($insurer_or_tpa == 'insurer') {
$id = 'uhid';
}
$file_name_with_path = WRITEPATH . "/uploads/import_excel/" . $file['file_name'];
$excel_data = $this->readExcelFileToArray($file_name_with_path);
unset($excel_data[0]);
array_pop($excel_data);
$emp_count = count($excel_data);
$employee_data = $this->employeePolicyModel
->select('
employee_polices.id as emp_policy_id,
employees.name AS emp_name,
employees.emp_code AS emp_code,
"Has Define" as emp_type,
employees.relationship_code AS emp_relationship_code,
employees.dob AS emp_dob,
employees.gender AS emp_gender,
employee_polices.pre_existing_alignments,
employee_polices.basic_cover_si,
employee_polices.date_coverage,
TIMESTAMPDIFF(YEAR, employees.dob, CURDATE()) AS emp_age,
employees.relationship AS emp_relationship,
employees.change_event AS change_event,
employee_polices.policy_end_date,
employee_polices.days,
employee_polices.tpa_id,
employee_polices.uhid,
employee_polices.premium,
employee_polices.rata_premimum,
employee_polices.gst,
(employee_polices.rata_premimum + employee_polices.gst) AS total
')
->join('employees', 'employees.id = employee_polices.employee_id')
->where('employee_polices.client_policy_id', $client_policy_id)
->where('employees.client_id', $client_id)
->where("employee_polices.{$id} IS NULL OR employee_polices.{$id} = ''")
->findAll();
// echo '<pre>';
// print_r($employee_data); die;
if ($employee_data == null || empty($employee_data)) {
if ($insurer_or_tpa == 'tpa') {
$data = [
'status' => 'failed-1',
];
$this->batchFileModel->where('id', $file_id)->set($data)->update();
$this->myLogger->logme('error', 'importInceptionFileValidation TPAID already updated');
$file_data = $this->getDataByFileId($file_id, 'failure');
$this->setPullNotification($file_data);
return 'The list of employees provided has already been updated with the TPA ID, or this is not the correct file';
} else if ($insurer_or_tpa == 'insurer') {
$data = [
'status' => 'failed-2',
];
$this->batchFileModel->where('id', $file_id)->set($data)->update();
$this->myLogger->logme('error', 'importInceptionFileValidation UHID already updated');
$file_data = $this->getDataByFileId($file_id, 'failure');
$this->setPullNotification($file_data);
return 'The list of employees provided has already been updated with the UHID, or this is not the correct file';
}
$this->myLogger->logme('error', 'importInceptionFileValidation UHID or TPAID already updated or the uploadedfile is not correct');
}
$excel_data_count = count($excel_data);
$emp_data_count = count($employee_data);
$this->myLogger->logme('error', 'importInceptionFileValidation excel file count : {data}', ['data' => $excel_data_count]);
$this->myLogger->logme('error', 'importInceptionFileValidation database count : {data}', ['data' => $emp_data_count]);
// dd($excel_data_count, $emp_data_count);
$difference = $emp_data_count - $excel_data_count;
$status = 'in-progress';
if ($excel_data_count < $emp_data_count) {
$status = 'in-progress-partially';
$partially_updated_data = 'Expected : ' . $emp_data_count . ', ' . 'Updated : ' . $excel_data_count . ', ' . 'difference : ' . $difference;
$this->myLogger->logme('error', 'importInceptionFileValidation excel file count partially : {data}', ['data' => $partially_updated_data]);
}
if ($emp_data_count < $excel_data_count) {
$data = [
'status' => 'failed-3',
];
$this->batchFileModel->where('id', $file_id)->set($data)->update();
$this->myLogger->logme('error', 'importInceptionFileValidation excel file count ( {excel} ) exceeds db count ( {db} )', ['db' => $emp_data_count, 'excel' => $excel_data_count]);
$file_data = $this->getDataByFileId($file_id, 'failure');
$this->setPullNotification($file_data);
return 'The Excel record count exceeds the DB record count. excel file count : ' . $excel_data_count . 'db count : ' . $emp_data_count;
}
$errors = []; // Initialize an array to store errors
$missing_id = [];
$batch_list_id = [];
foreach ($employee_data as $key => $emp_value) {
$key = $key + 1;
if(!isset($excel_data[$key])){
break;
}
if ($insurer_or_tpa == 'tpa') {
if ($excel_data[$key][15] === null) {
$missing_id[$key][] = [
'row' => $key,
'column' => 15,
];
}
} else if ($insurer_or_tpa == 'insurer') {
if ($excel_data[$key][16] === null) {
$missing_id[$key][] = [
'row' => $key,
'column' => 16,
];
}
}
if ($emp_value['emp_name'] != $excel_data[$key][1]) {
$errors[$key][] = [
'row' => $key,
'column' => 1,
'db_data' => $emp_value['emp_name'],
'excel_data' => $excel_data[$key][1]
];
}
if ($emp_value['emp_code'] != $excel_data[$key][2]) {
$errors[$key][] = [
'row' => $key,
'column' => 2,
'db_data' => $emp_value['emp_code'],
'excel_data' => $excel_data[$key][2]
];
}
if ($emp_value['emp_dob'] != $excel_data[$key][5]) {
$errors[$key][] = [
'row' => $key,
'column' => 5,
'db_data' => $emp_value['emp_dob'],
'excel_data' => $excel_data[$key][5]
];
}
if ($emp_value['emp_gender'] != $excel_data[$key][6]) {
$errors[$key][] = [
'row' => $key,
'column' => 6,
'db_data' => $emp_value['emp_gender'],
'excel_data' => $excel_data[$key][6]
];
}
if ($emp_value['pre_existing_alignments'] != $excel_data[$key][7]) {
$errors[$key][] = [
'row' => $key,
'column' => 7,
'db_data' => $emp_value['pre_existing_alignments'],
'excel_data' => $excel_data[$key][7]
];
}
if ($emp_value['basic_cover_si'] != $excel_data[$key][8]) {
$errors[$key][] = [
'row' => $key,
'column' => 8,
'db_data' => $emp_value['basic_cover_si'],
'excel_data' => $excel_data[$key][8]
];
}
if ($emp_value['emp_relationship'] != $excel_data[$key][11]) {
$errors[$key][] = [
'row' => $key,
'column' => 11,
'db_data' => $emp_value['emp_relationship'],
'excel_data' => $excel_data[$key][11]
];
}
if ($emp_value['policy_end_date'] != $excel_data[$key][13]) {
$errors[$key][] = [
'row' => $key,
'column' => 13,
'db_data' => $emp_value['policy_end_date'],
'excel_data' => $excel_data[$key][13]
];
}
if ($emp_value['days'] != $excel_data[$key][14]) {
$errors[$key][] = [
'row' => $key,
'column' => 14,
'db_data' => $emp_value['days'],
'excel_data' => $excel_data[$key][14]
];
}
if ($emp_value['premium'] != $excel_data[$key][17]) {
$errors[$key][] = [
'row' => $key,
'column' => 17,
'db_data' => $emp_value['premium'],
'excel_data' => $excel_data[$key][17]
];
}
if ($emp_value['rata_premimum'] != $excel_data[$key][18]) {
$errors[$key][] = [
'row' => $key,
'column' => 18,
'db_data' => $emp_value['rata_premimum'],
'excel_data' => $excel_data[$key][18]
];
}
if ($emp_value['gst'] != $excel_data[$key][19]) {
$errors[$key][] = [
'row' => $key,
'column' => 19,
'db_data' => $emp_value['gst'],
'excel_data' => $excel_data[$key][19]
];
}
if ($insurer_or_tpa == 'tpa') {
if ($emp_value['uhid'] != $excel_data[$key][16]) {
$errors[$key][] = [
'row' => $key,
'column' => 16,
'db_data' => $emp_value['uhid'],
'excel_data' => $excel_data[$key][16]
];
}
} else if ($insurer_or_tpa == 'insurer') {
if ($emp_value['tpa_id'] != $excel_data[$key][15]) {
$errors[$key][] = [
'row' => $key,
'column' => 15,
'db_data' => $emp_value['tpa_id'],
'excel_data' => $excel_data[$key][15]
];
}
}
$batch_list_id[] = $emp_value['emp_policy_id'];
}
$error_count = count($errors);
$json_errors = json_encode($errors);
// echo $json_errors; die;
$missing_id_count = count($missing_id);
$json_missing_id = json_encode($missing_id);
// dd($error_count, $missing_id_count, $json_errors, $json_missing_id);
// dd($batch_list_id);
if ($missing_id_count > 0) {
$data = [
'error_data' => $json_missing_id,
'status' => 'failed',
];
$this->batchFileModel->where('id', $file_id)->set($data)->update();
if ($insurer_or_tpa == 'tpa') {
$file_data = $this->getDataByFileId($file_id, 'failure');
$this->setPullNotification($file_data);
return 'The TPA ID column is either partially or entirely empty.';
} else if ($insurer_or_tpa == 'insurer') {
$file_data = $this->getDataByFileId($file_id, 'failure');
$this->setPullNotification($file_data);
return 'The UHID column is either partially or entirely empty.';
}
}
if ($error_count > 0) {
$data = [
'error_data' => $json_errors,
'status' => 'failed',
];
$this->batchFileModel->where('id', $file_id)->set($data)->update();
return 0;
} else {
$data = [
'count' => $emp_count,
'status' => $status,
'error_data' => $partially_updated_data ?? null,
];
$this->batchFileModel->where('id', $file_id)->set($data)->update();
foreach ($batch_list_id as $key => $value) {
$data = [
'emp_policy_id' => $value,
'batch_code' => $batch_code,
];
$insert = $this->batchListModel->insert($data);
}
$parameters['file_id'] = $file_id;
$job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'importInceptionUpdateTPAandUHID','payload' => ['file_id' => $file_id]]);
// $this->importInceptionUpdateTPAandUHID(['file_id' => $file_id]);
}
}
public function importInceptionUpdateTPAandUHID($params)
{
$this->myLogger->logme('error', 'importInceptionUpdateTPAandUHID called');
$file_id = $params['file_id'];
$file = $this->batchFileModel->find($file_id);
if (!$file) {
$data = [
'status' => 'failed-4',
];
$this->batchFileModel->where('id', $file_id)->set($data)->update();
$this->myLogger->logme('error', 'importInceptionUpdateTPAandUHID the Physical file not found - file id : {data}', ['data' => $file_id]);
$file_data = $this->getDataByFileId($file_id, 'failure');
$this->setPullNotification($file_data);
return 'importInceptionUpdateTPAandUHID the Physical file not found'; // Return error code if file not found
}
$client_id = $file['client_id'];
$client_policy_id = $file['client_policy_id'];
$insurer_or_tpa = $file['insurer_or_tpa'];
$status = $file['status'];
$batch_code = $file['batch_code'];
$user_id = $file['created_by'];
$status_val = 'success';
if ($status == 'in-progress-partially') {
$status_val = 'partially success';
}
$this->myLogger->logme('error', 'importInceptionUpdateTPAandUHID file name : {data}', ['data'=> $file['file_name']]);
$file_name_with_path = WRITEPATH . "/uploads/import_excel/" . $file['file_name'];
$excel_data = $this->readExcelFileToArray($file_name_with_path);
unset($excel_data[0]); // Remove header row
array_pop($excel_data); // Remove footer row
$totals = 0;
$empty_emp_tpa_uh_ids = [];
$emp_count = count($excel_data);
$db = \Config\Database::connect();
foreach ($excel_data as $key => $value) {
$name = $value[1];
$emp_code = $value[2];
$tpa_id = $value[15];
$uhid = $value[16];
$amount = $value[20];
$totals += $amount;
// Execute the query
$query = $db->table('employee_polices');
$query->select('employee_polices.id');
$query->join('employees', 'employees.id = employee_polices.employee_id');
$query->where('employee_polices.client_policy_id', $client_policy_id);
$query->where('employees.client_id', $client_id);
$query->where('employees.name', $name);
$query->where('employees.emp_code', $emp_code);
if ($file['insurer_or_tpa'] == 'tpa') {
$query->where('(employee_polices.tpa_id IS NULL OR employee_polices.tpa_id = "")');
} else if ($file['insurer_or_tpa'] == 'insurer') {
$query->where('(employee_polices.uhid IS NULL OR employee_polices.uhid = "")');
}
$query->where('employee_polices.is_active', 1);
$query->limit(1);
// Get the result
$result = $query->get()->getRowArray();
if (isset($result['id']) && $result['id'] !== null) {
$empty_emp_tpa_uh_ids[] = $result['id'];
}
$sql = "
UPDATE employee_polices
JOIN employees ON employees.id = employee_polices.employee_id
SET tpa_id = ?
WHERE employees.name = ?
AND employees.emp_code = ?
AND employee_polices.client_policy_id = ?
AND (employee_polices.tpa_id IS NULL OR employee_polices.tpa_id = '')";
$params = [$tpa_id, $name, $emp_code, $client_policy_id];
$db->query($sql, $params);
$sql = "
UPDATE employee_polices
JOIN employees ON employees.id = employee_polices.employee_id
SET employee_polices.uhid = ?
WHERE employees.name = ?
AND employees.emp_code = ?
AND employee_polices.client_policy_id = ?
AND (employee_polices.uhid IS NULL OR employee_polices.uhid = '')";
$params = [$uhid, $name, $emp_code, $client_policy_id];
$db->query($sql, $params);
}
// Update batch file status and amount
$this->batchFileModel->update($file_id, [
'count' => $emp_count,
'status' => $status_val,
'amount' => $totals,
]);
$this->myLogger->logme('error', 'importInceptionUpdateTPAandUHID employee count : {data}', ['data'=> $emp_count]);
$this->myLogger->logme('error', 'importInceptionUpdateTPAandUHID batch file status : {data}', ['data'=> $status_val]);
$this->myLogger->logme('error', 'importInceptionUpdateTPAandUHID total amount for cash deposite : {data}', ['data'=> $totals]);
if ($file['insurer_or_tpa'] == 'tpa') {
$this->myLogger->logme('error', 'importInceptionUpdateTPAandUHID set cashDepositCalculationForInception and sendMailForDownloadingECard in JOB QUEUE');
$policy_name = $this->getPolicyNameUsingClientPolicyId($client_policy_id);
$depositeData = [
'employeeIds' => $empty_emp_tpa_uh_ids,
'client_id' => $client_id,
'client_policy_id' => $client_policy_id,
'count' => $emp_count,
'event' => $file['event_type'],
'policy_name' => $policy_name['policy_name'],
'user_id' => $user_id,
];
$job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'cashDepositCalculationForInception','payload' => [
'employeeIds' => $empty_emp_tpa_uh_ids,
'client_id' => $client_id,
'client_policy_id' => $client_policy_id,
'count' => $emp_count,
'event' => $file['event_type'],
'policy_name' => $policy_name['policy_name'],
'user_id' => $user_id,
]]);
$job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'sendMailForDownloadingECard','payload' => $empty_emp_tpa_uh_ids]);
// $this->cashDepositCalculationForInception($depositeData);
// $this->sendMailForDownloadingECard($empty_emp_tpa_uh_ids);
}
$file_data = $this->getDataByFileId($file_id, 'success');
$this->setPullNotification($file_data);
return 'Import Inception Updated '. $status_val . '- Updated Count : ' . $emp_count;
}
public function importExcelDataForCorrection($import_data)
{
$client_id = $import_data['client_id'];
$client_policy_id = $import_data['client_policy_id'];
$file = $import_data['file'];
$data = $this->readExcelToArray($file);
unset($data[0]);
$count = count($data);
$missing_id = [];
$empty_emp_tpa_uh_ids = [];
foreach ($data as $key => $value) {
try {
if ($value[10] === null) {
$missing_id[] = $key + 1;
}
$emp_code = $value[0];
$uhid = $value[1];
$endorsement_id = $value[10] != null ? $value[10] : '';
$db = \Config\Database::connect();
// Execute the query
$query = $db->table('emp_endorsement')
->select('emp_endorsement.id')
->join('employees', 'employees.id = emp_endorsement.pk')
->join('employee_polices', 'employee_polices.employee_id = employees.id')
->where('employee_polices.client_policy_id', $client_policy_id)
->where('employees.client_id', $client_id)
->where('employee_polices.uhid', $uhid)
->where('employees.emp_code', $emp_code)
->where('(emp_endorsement.endorsement_id IS NULL OR emp_endorsement.endorsement_id = "")')
->groupBy('emp_endorsement.group_key')
->limit(1);
// Get the result
$result = $query->get()->getRowArray();
if (isset($result['id']) && $result['id'] !== null) {
$empty_emp_tpa_uh_ids[] = $result['id'];
}
} catch (\Exception $e) {
// Handle the exception here
return 0;
}
}
$missing_id_count = count($missing_id);
$empty_id_count = count($empty_emp_tpa_uh_ids);
// if($missing_id_count != $count){
// return 2;
// }
if ($missing_id_count != 0) {
return 2;
}
// if($empty_emp_tpa_uh_ids != $count){
// return 3;
// }
if ($empty_id_count == 0) {
return 3;
}
// dd($count, $missing_id, $missing_id_count, $empty_id_count, $data, $empty_emp_tpa_uh_ids);
$is_moved = $file->move(WRITEPATH . 'uploads/import_excel');
$filename = $file->getName();
$this->myLogger->logme('error', 'Correction Import file name : {data}', ['data' => $filename]);
$random_number_count = 4;
$batch_code = generate_random_string($random_number_count);
$this->myLogger->logme('error', 'Correction Import BATCH CODE : {data}', ['data' => $batch_code]);
$import_data['batch_code'] = $batch_code;
$import_data['created_by'] = get_session_userid();
$import_data['file_name'] = $filename;
$insert = $this->batchFileModel->insert($import_data);
$batch_file_batch_code = $this->batchFileModel->where('id', $insert)->first();
$batch_code_for_batch_list['batch_code'] = $batch_file_batch_code['batch_code'];
$batch_code_for_batch_list['created_by'] = get_session_userid();
$file_name_with_path = WRITEPATH . "/uploads/import_excel/" . $batch_file_batch_code['file_name'];
if (!file_exists($file_name_with_path)) {
return 2;
}
$data = read_excel_file_to_array($file_name_with_path);
unset($data[0]);
$count = count($data);
$this->batchFileModel->where('id', $insert)->set('count', $count)->update();
foreach ($data as $key => $value) {
if (!empty($value) && isset($value[10])) {
$emp_code = $value[0];
$uhid = $value[1];
$endorsement_id = $value[10] != null ? $value[10] : '';
$val = $this->employeePolicyModel
->select('employees.id')
->join('employees', 'employees.id = employee_polices.employee_id')
->where('employee_polices.client_policy_id', $client_policy_id)
->where('employees.client_id', $client_id)
->where('employee_polices.uhid', $uhid)
->where('employees.emp_code', $emp_code)
->where('employees.is_active', 1)
->first();
$batch_code_for_batch_list['emp_policy_id'] = $val['id'];
$this->batchListModel->insert($batch_code_for_batch_list);
// $this->employeePolicyModel->updateCorrectionData($emp_code, $uhid, $endorsement_id);
$queryData = $this->empEndorsementModel->select('emp_endorsement.*, employees.id as emp_id')
->join('employees', 'employees.id = emp_endorsement.pk')
->join('employee_polices', 'employee_polices.employee_id = employees.id')
->where('employees.emp_code', $emp_code)
->where('employees.client_id', $client_id)
->where('employee_polices.client_policy_id', $client_policy_id)
->where('employee_polices.uhid', $uhid)
->get()
->getResultArray();
// dd($queryData);
foreach ($queryData as $endorsementData) {
$emp_endoresment_id = $endorsementData['id'];
$emp_id = $endorsementData['emp_id'];
$field_name = $endorsementData['field_name'];
$new_value = $endorsementData['new_value'];
$endoresment_udate_data = [
'endorsement_id' => $endorsement_id,
'status' => 'complete',
];
$this->empEndorsementModel->where('id', $emp_endoresment_id)->set($endoresment_udate_data)->update();
$this->employeeModel->where('id', $emp_id)->set($field_name, $new_value)->update();
}
// $query = $this->employeePolicyModel->getLastQuery();
// echo $query . "<br>";
} else {
return 0;
}
}
return 1;
}
public function importExcelDataForSIEnhancement($import_data)
{
$client_id = $import_data['client_id'];
$client_policy_id = $import_data['client_policy_id'];
$file = $import_data['file'];
$data = $this->readExcelToArray($file);
unset($data[0]);
$count = count($data);
$missing_id = [];
$empty_emp_tpa_uh_ids = [];
$totals = 0;
foreach ($data as $key => $value) {
try {
if ($value[19] === null) {
$missing_id[] = $key + 1;
}
$totals += $value[18];
$emp_name = $value[1];
$emp_code = $value[2];
$endorsement_id = $value[19] != null ? $value[19] : '';
$db = \Config\Database::connect();
// Execute the query
$query = $db->table('emp_endorsement')
->select('emp_endorsement.id')
->join('employee_polices', 'employee_polices.id = emp_endorsement.pk')
->join('employees', 'employees.emp_code = emp_endorsement.emp_code')
->where('employees.emp_code', $emp_code)
->where('employees.name', $emp_name)
->where('employees.client_id', $client_id)
->where('emp_endorsement.actions', 'si')
->where('employee_polices.client_policy_id', $client_policy_id)
->where('(emp_endorsement.endorsement_id IS NULL OR emp_endorsement.endorsement_id = "")')
->groupBy('emp_endorsement.group_key');
// Get the result
$result = $query->get()->getRowArray();
if (isset($result['id']) && $result['id'] !== null) {
$empty_emp_tpa_uh_ids[] = $result['id'];
}
} catch (\Exception $e) {
// Handle the exception here
return 0;
}
}
$rounded_totals = round($totals, 2);
$missing_id_count = count($missing_id);
$empty_id_count = count($empty_emp_tpa_uh_ids);
// if($missing_id_count != $count){
// return 2;
// }
if ($missing_id_count != 0) {
return 2;
}
// if($empty_emp_tpa_uh_ids != $count){
// return 3;
// }
if ($empty_id_count == 0) {
return 3;
}
// dd($count, $missing_id, $missing_id_count, $empty_id_count, $data, $empty_emp_tpa_uh_ids);
$is_moved = $file->move(WRITEPATH . 'uploads/import_excel');
$filename = $file->getName();
$this->myLogger->logme('error', 'SI_Enhancement Import file name : {data}', ['data' => $filename]);
$random_number_count = 4;
$batch_code = generate_random_string($random_number_count);
$this->myLogger->logme('error', 'SI_Enhancement Import BATCH CODE : {data}', ['data' => $batch_code]);
$import_data['batch_code'] = $batch_code;
$import_data['created_by'] = get_session_userid();
$import_data['file_name'] = $filename;
$import_data['amount'] = $rounded_totals;
$insert = $this->batchFileModel->insert($import_data);
$batch_file_batch_code = $this->batchFileModel->where('id', $insert)->first();
$batch_code_for_batch_list['batch_code'] = $batch_file_batch_code['batch_code'];
$batch_code_for_batch_list['created_by'] = get_session_userid();
$file_name_with_path = WRITEPATH . "/uploads/import_excel/" . $batch_file_batch_code['file_name'];
if (!file_exists($file_name_with_path)) {
return 2;
}
$data = read_excel_file_to_array($file_name_with_path);
unset($data[0]);
$count = count($data);
$this->batchFileModel->where('id', $insert)->set('count', $count)->update();
$employeeIds = [];
foreach ($data as $key => $value) {
if (!empty($value) && isset($value[19])) {
$emp_name = $value[1];
$emp_code = $value[2];
// echo $emp_name .'-'. $emp_code; die;
$endorsement_id = $value[19] != null ? $value[19] : '';
$updateData = [
'emp_code' => $emp_code,
'client_id' => $client_id,
'client_policy_id' => $client_policy_id,
'emp_name' => $emp_name,
'endorsement_id' => $endorsement_id,
];
$this->employeePolicyModel->updateEndoresmentIdForSIEnhancement($updateData);
$queryData = $this->employeePolicyModel
->select('employee_polices.*')
->join('employees', 'employee_polices.employee_id = employees.id')
->where('employees.emp_code', $emp_code)
->where('employees.name', $emp_name)
->where('employees.client_id', $client_id)
->where('employee_polices.client_policy_id', $client_policy_id)
->where('employee_polices.is_active', 1)
->first();
$queryData['is_active'] = 0;
$this->employeePolicyModel->save($queryData);
unset($queryData['id']);
unset($queryData['created_by']);
unset($queryData['created_at']);
unset($queryData['updated_by']);
unset($queryData['updated_at']);
unset($queryData['is_active']);
$queryData['basic_cover_si'] = $value[8];
$queryData['premium'] = $value[14];
$queryData['si_enhancement_date'] = $value[10];
$queryData['rata_premimum'] = $value[16];
$queryData['gst'] = $value[17];
$queryData['created_by'] = get_session_userid();
//new insert
$this->employeePolicyModel->save($queryData);
$val = $this->employeePolicyModel
->select('employee_polices.id')
->join('employees', 'employees.id = employee_polices.employee_id')
->where('employee_polices.client_policy_id', $client_policy_id)
->where('employees.client_id', $client_id)
->where('employees.name', $emp_name)
->where('employees.emp_code', $emp_code)
->where('employee_polices.is_active', 1)
->first();
if ($val !== null) {
$id = $val['id'];
$batch_code_for_batch_list['emp_policy_id'] = $id;
$this->batchListModel->insert($batch_code_for_batch_list);
array_push($employeeIds, $id);
}
} else {
return 0;
}
}
$policy_name = $this->getPolicyNameUsingClientPolicyId($client_policy_id);
$depositeData = [
'employeeIds' => $employeeIds,
'client_id' => $client_id,
'client_policy_id' => $client_policy_id,
'count' => $count,
'event' => $import_data['event_type'],
'policy_name' => $policy_name['policy_name'],
];
// dd($depositeData);
$this->cashDepositCalculationForSIEnhancement($depositeData);
return 1;
}
public function importExcelDataForDeletion($import_data)
{
$client_id = $import_data['client_id'];
$client_policy_id = $import_data['client_policy_id'];
$file = $import_data['file'];
$data = $this->readExcelToArray($file);
unset($data[0]);
array_pop($data);
$count = count($data);
$missing_id = [];
$empty_emp_tpa_uh_ids = [];
$totals = 0;
foreach ($data as $key => $value) {
try {
if ($value[15] === null) {
$missing_id[] = $key + 1;
}
$totals += $value[13];
$emp_name = $value[2]; //employee name
$emp_code = $value[1]; //employee code
$date_of_exit = $value[7]; // date of releving
$endorsement_id = $value[15] != null ? $value[15] : ''; //endorsement id
$db = \Config\Database::connect();
// Execute the query
$query = $db->table('emp_endorsement')
->select('emp_endorsement.id')
->join('employee_polices', 'employee_polices.id = emp_endorsement.pk')
->join('employees', 'employees.emp_code = emp_endorsement.emp_code')
->where('employees.emp_code', $emp_code)
->where('employees.name', $emp_name)
->where('employees.client_id', $client_id)
->where('emp_endorsement.actions', 'd')
->where('employee_polices.client_policy_id', $client_policy_id)
->where('(emp_endorsement.endorsement_id IS NULL OR emp_endorsement.endorsement_id = "")')
->groupBy('emp_endorsement.group_key');
$result = $query->get()->getRowArray();
if (isset($result['id']) && $result['id'] !== null) {
$empty_emp_tpa_uh_ids[] = $result['id'];
}
} catch (\Exception $e) {
// Handle the exception here
return 0;
}
}
$rounded_totals = round($totals, 2);
$missing_id_count = count($missing_id);
$empty_id_count = count($empty_emp_tpa_uh_ids);
// if($missing_id_count != $count){
// return 2;
// }
if ($missing_id_count != 0) {
return 2;
}
// if($empty_emp_tpa_uh_ids != $count){
// return 3;
// }
if ($empty_id_count == 0) {
return 3;
}
// dd($count, $missing_id_count, $empty_id_count, $data, $empty_emp_tpa_uh_ids);
$is_moved = $file->move(WRITEPATH . 'uploads/import_excel');
$filename = $file->getName();
$this->myLogger->logme('error', 'Deletion Import file name : {data}', ['data' => $filename]);
$random_number_count = 4;
$batch_code = generate_random_string($random_number_count);
$this->myLogger->logme('error', 'Deletion Import BATCH CODE : {data}', ['data' => $batch_code]);
$import_data['batch_code'] = $batch_code;
$import_data['created_by'] = get_session_userid();
$import_data['file_name'] = $filename;
$import_data['amount'] = $rounded_totals;
$insert = $this->batchFileModel->insert($import_data);
$batch_file_batch_code = $this->batchFileModel->where('id', $insert)->first();
$batch_code_for_batch_list['batch_code'] = $batch_file_batch_code['batch_code'];
$batch_code_for_batch_list['created_by'] = get_session_userid();
$file_name_with_path = WRITEPATH . "/uploads/import_excel/" . $batch_file_batch_code['file_name'];
if (!file_exists($file_name_with_path)) {
return 2;
}
$data = read_excel_file_to_array($file_name_with_path);
unset($data[0]);
array_pop($data);
$count = count($data);
$this->batchFileModel->where('id', $insert)->set('count', $count)->update();
$employeeIds = [];
foreach ($data as $key => $value) {
if (!empty($value) && isset($value[15])) {
$emp_name = $value[2]; //employee name
$emp_code = $value[1]; //employee code
$date_of_exit = $value[7]; // date of releving
// echo $emp_name .'-'. $emp_code .'-'. $date_of_exit; die;
$endorsement_id = $value[15] != null ? $value[15] : ''; //endorsement id
$val = $this->employeePolicyModel
->select('employee_polices.id')
->join('employees', 'employees.id = employee_polices.employee_id')
->where('employee_polices.client_policy_id', $client_policy_id)
->where('employees.client_id', $client_id)
->where('employees.name', $emp_name)
->where('employees.emp_code', $emp_code)
->where('employee_polices.is_active', 1)
->first();
if ($val !== null) {
$id = $val['id'];
$batch_code_for_batch_list['emp_policy_id'] = $id;
$this->batchListModel->insert($batch_code_for_batch_list);
array_push($employeeIds, $id);
}
// $updateData = [
// 'emp_code' =>$emp_code,
// 'client_id' =>$client_id,
// 'client_policy_id' =>$client_policy_id,
// 'emp_name' =>$emp_name,
// 'endorsement_id' =>$endorsement_id,
// ];
// $this->employeePolicyModel->updateEndoresmentIdForDeletion($updateData);
$deletionDataForEmployee = $this->empEndorsementModel
->select('emp_endorsement.new_value, emp_endorsement.id as ee_id, employees.id')
->join('employees', 'emp_endorsement.emp_code = employees.emp_code')
->join('employee_polices', 'employee_polices.employee_id = employees.id')
->where('emp_endorsement.emp_code', $emp_code)
->where('employees.client_id', $client_id)
->where('employee_polices.client_policy_id', $client_policy_id)
->where('emp_endorsement.name', $emp_name)
->where('emp_endorsement.field_name', 'emp_status')
->first();
$deletionDataForEmployee['updated_by'] = get_session_userid();
$this->employeeModel->save($deletionDataForEmployee);
$e_Data = [
'endorsement_id' => $endorsement_id,
'status' => 'complete',
];
$group_key = $this->empEndorsementModel->select('group_key')->where('id', $deletionDataForEmployee['ee_id'])->first();
$this->empEndorsementModel->where('group_key', $group_key)->set($e_Data)->update();
$fetchData = [
'emp_code' => $emp_code,
'client_policy_id' => $client_policy_id,
'emp_name' => $emp_name,
];
$deletionDataForEmployeePolicy = $this->employeePolicyModel->fetchEmpEndorsementData($fetchData);
$deletionDataForEmployeePolicy['updated_by'] = get_session_userid();
$this->employeePolicyModel->save($deletionDataForEmployeePolicy);
// $query = $this->employeePolicyModel->getLastQuery();
// echo $query . "<br>";
} else {
return 0;
}
}
$policy_name = $this->getPolicyNameUsingClientPolicyId($client_policy_id);
$depositeData = [
'employeeIds' => $employeeIds,
'client_id' => $client_id,
'client_policy_id' => $client_policy_id,
'count' => $count,
'event' => $import_data['event_type'],
'policy_name' => $policy_name['policy_name'],
];
$this->cashDepositCalculationForDeletion($depositeData);
return 1;
}
/**
* The below functions are Calculates and records cash deposits for employee policies at inception.
*
* @param array $arrayData An array containing necessary data including :
* - employee IDs,
* - client policy ID,
* - client ID,
* - count of employees,
* - policy_name, and
* - event type.
*
* @return bool Returns true if the operation is successful, otherwise returns 0.
*/
public function cashDepositCalculationForInception($arrayData)
{
if (!empty($arrayData)) {
$amount = $this->employeePolicyModel->query("
SELECT SUM(rata_premimum + gst) AS total_sum
FROM employee_polices
WHERE id IN (" . implode(',', $arrayData['employeeIds']) . ")
")->getRow();
$insurer_id = $this->clientPolicyModel->where('id', $arrayData['client_policy_id'])->first();
$description = 'The following amount of Rs. ' . $amount->total_sum . '/- has been debited for the ' . $arrayData['count'] . ' employees at ' . remove_underscore_capitalize_first_letter($arrayData['event']) . ' to ' . remove_underscore_capitalize_first_letter($arrayData['policy_name']) . '.';
if(get_session_userid() == null){
}
$data = [
'amount' => $amount->total_sum ?? 0,
'sub_type_id' => 4,
'client_id' => $arrayData['client_id'],
'insurer_id' => $insurer_id['insurer_id'],
'description' => $description,
'transaction_type' => 'Debit',
'updated_by' => $arrayData['user_id'],
'is_active' => 1,
];
$response = DepositHelper::saveDeposit($data, $arrayData['user_id']);
return true;
// print_r($response);
// $query = $this->employeePolicyModel->getLastQuery();
// echo $query . "<br>";
} else {
return 0;
}
}
public function cashDepositCalculationForSIEnhancement($arrayData)
{
if (!empty($arrayData)) {
$amount = $this->employeePolicyModel->query("
SELECT
SUM(ROUND((employee_polices.premium * DATEDIFF(employee_polices.policy_end_date, employee_polices.si_enhancement_date)) / 365, 2) +
ROUND(((employee_polices.premium * DATEDIFF(employee_polices.policy_end_date, employee_polices.si_enhancement_date)) / 365) * 0.18, 2)) AS total_sum
FROM employee_polices
WHERE id IN (" . implode(',', $arrayData['employeeIds']) . ")
")->getRow();
$insurer_id = $this->clientPolicyModel->where('id', $arrayData['client_policy_id'])->first();
$description = 'The following amount of ' . $amount->total_sum . ' has been credited for the ' . $arrayData['count'] . ' employees at ' . remove_underscore_capitalize_first_letter($arrayData['event']) . ' to ' . remove_underscore_capitalize_first_letter($arrayData['policy_name']) . '.';
$data = [
'amount' => $amount->total_sum,
'sub_type_id' => 4,
'client_id' => $arrayData['client_id'],
'insurer_id' => $insurer_id['insurer_id'],
'description' => $description,
'transaction_type' => 'Debit',
'updated_by' => get_session_userid(),
'is_active' => 1,
];
$response = DepositHelper::saveDeposit($data, get_session_userid());
return true;
// print_r($response);
// $query = $this->employeePolicyModel->getLastQuery();
// echo $query . "<br>";
} else {
return 0;
}
}
public function cashDepositCalculationForDeletion($arrayData)
{
// print_r($arrayData);
if (!empty($arrayData)) {
// echo '<pre>';
// print_r($arrayData); die;
$amount = $this->employeePolicyModel->query("
SELECT
SUM(ROUND((employee_polices.premium * DATEDIFF(employee_polices.policy_end_date, employee_polices.date_of_exit)) / 365, 2) +
ROUND(((employee_polices.premium * DATEDIFF(employee_polices.policy_end_date, employee_polices.date_of_exit)) / 365) * 0.18, 2)) AS total_sum
FROM employee_polices
WHERE id IN (" . implode(',', $arrayData['employeeIds']) . ")
")->getRow();
$insurer_id = $this->clientPolicyModel->where('id', $arrayData['client_policy_id'])->first();
$description = 'The following amount of ' . $amount->total_sum . ' has been credited for the ' . $arrayData['count'] . ' employees at ' . remove_underscore_capitalize_first_letter($arrayData['event']) . ' to ' . remove_underscore_capitalize_first_letter($arrayData['policy_name']) . '.';
$data = [
'amount' => $amount->total_sum,
'sub_type_id' => 3,
'client_id' => $arrayData['client_id'],
'insurer_id' => $insurer_id['insurer_id'],
'description' => $description,
'transaction_type' => 'Credit',
'updated_by' => get_session_userid(),
'is_active' => 1,
];
$response = DepositHelper::saveDeposit($data, get_session_userid());
return true;
// print_r($response);
// $query = $this->employeePolicyModel->getLastQuery();
// echo $query . "<br>";
} else {
return 0;
}
}
/**
* Below function retrieves the policy name associated with a given client policy ID.
*
* @param int $client_policy_id The ID of the client policy.
* @return mixed Returns the policy name if found, otherwise null.
*/
public function getPolicyNameUsingClientPolicyId($client_policy_id)
{
return $this->clientPolicyModel->select('policies.name as policy_name')
->join('policies', 'policies.id = client_policy.policy_id')
->where('client_policy.id', $client_policy_id)
->first();
}
/**
* Below function converts row data into column data format for SI enhancement.
*
* This function takes an array of data containing information about SI enhancement
* and calculates additional fields such as pro rata premium, GST, and total.
*
* @param array $data The array of data containing SI enhancement information.
* @return array Returns the converted data in column format.
*/
public function convertRowTColumnForSIEnhancement($data)
{
$result = array();
foreach ($data as $obj) {
$pro_rata_premium = round(($obj->difference_premium * $obj->no_of_days / 365), 2);
$gst = round(($pro_rata_premium * 18 / 100), 2);
$total = round(($pro_rata_premium + $gst), 2);
$old_total = round(($obj->old_rata + $obj->old_gst), 2);
$result[] = array(
"field_name" => 'Basic Cover SI',
"old_value" => $obj->old_basic_cover_si,
"new_value" => $obj->new_basic_cover_si
);
$result[] = array(
"field_name" => 'Premium',
"old_value" => $obj->old_si_premium,
"new_value" => $obj->new_si_premium
);
$result[] = array(
"field_name" => 'SI Enhancement Date',
"old_value" => change_date_format($obj->old_date, 'Y-m-d', 'd-M-Y'),
"new_value" => change_date_format($obj->date_of_coverage, 'Y-m-d', 'd-M-Y')
);
$result[] = array(
"field_name" => 'Difference Premium',
"old_value" => ' --- ',
"new_value" => $obj->difference_premium
);
$result[] = array(
"field_name" => 'No of Days',
"old_value" => $obj->old_days,
"new_value" => $obj->no_of_days
);
$result[] = array(
"field_name" => 'Pro Rata Premium',
"old_value" => $obj->old_rata,
"new_value" => $pro_rata_premium
);
$result[] = array(
"field_name" => 'GST(18%)',
"old_value" => $obj->old_gst,
"new_value" => $gst
);
$result[] = array(
"field_name" => 'Total',
"old_value" => $old_total,
"new_value" => $total
);
}
return $result;
}
/**
* Below function converts row data into column data format for deletion records.
*
* This function takes an array of data containing information about deletion records
* and converts it into a column format. It also calculates additional fields such as
* period of non-coverage, premium for non-coverage period, GST, total amount, and
* claim status based on the exist_reason field.
*
* @param array $data The array of data containing deletion records information.
* @return array Returns the converted data in column format.
*/
public function convertRowTColumnForDeletion($data)
{
$result = array();
foreach ($data as $obj) {
$old_total = round(($obj->old_rata + $obj->old_gst), 2);
$result[] = array(
"field_name" => 'Policy Period',
"data" => change_date_format($obj->start_date, 'Y-m-d', 'd-M-Y') . ' - <br> ' . change_date_format($obj->end_date, 'Y-m-d', 'd-M-Y'),
);
$result[] = array(
"field_name" => 'Exit on',
"data" => change_date_format($obj->date_of_leaving, 'Y-m-d', 'd-M-Y'),
);
$result[] = array(
"field_name" => 'Reason',
"data" => $obj->exist_reason,
);
if ($obj->exist_reason != 'death') {
$result[] = array(
"field_name" => 'Period of non coverage',
"data" => $obj->no_of_days
);
$result[] = array(
"field_name" => 'Premium for non coverage period',
"data" => $obj->pro_rata_premium
);
$result[] = array(
"field_name" => 'GST(18%)',
"data" => $obj->gst
);
$result[] = array(
"field_name" => 'Total Amount',
"data" => $obj->total
);
$result[] = array(
"field_name" => 'Claim',
"data" => '---',
);
}
}
return $result;
}
// -----------------------------------------------------------------------------------
public function readExcelToArray($file)
{
if ($file->isValid() && !$file->hasMoved()) {
$file = $file;
try {
$reader = IOFactory::createReaderForFile($file->getPathname());
$spreadsheet = $reader->load($file->getPathname());
// Get the active sheet
$sheet = $spreadsheet->getActiveSheet();
// Iterate through rows to read data
$data = [];
foreach ($sheet->getRowIterator() as $row) {
$rowData = [];
foreach ($row->getCellIterator() as $cell) {
$rowData[] = $cell->getValue();
}
$data[] = $rowData;
}
return $data;
} catch (SpreadsheetReaderException $e) {
error_log('PhpSpreadsheet reader exception: ' . $e->getMessage());
return false;
}
} else {
return false;
}
}
public function insertBatchFileAndBatchListForImportExcel($data, $ids)
{
$random_number_count = 4;
$data['batch_code'] = generate_random_string($random_number_count);
$data['created_by'] = get_session_userid();
$insert = $this->batchFileModel->insert($data);
$batch_file_batch_code = $this->batchFileModel->where('id', $insert)->first();
if ($insert) {
foreach ($ids as $id) {
$batch_list_data['batch_code'] = $batch_file_batch_code['batch_code'];
$batch_list_data['emp_policy_id'] = $id;
$batch_list_data['created_by'] = get_session_userid();
$this->batchListModel->insert($batch_list_data);
}
}
return true;
}
public function sendMailForDownloadingECard(array $ids)
{
$this->myLogger->logme('error', 'sendMailForDownloadingECard - function called');
if (count($ids) > 0) {
$temp_id = $ids[0];
$get_client_info_for_notification = $this->employeePolicyModel
->select('employee_polices.client_policy_id, employees.emp_code, employees.email_corporate,employees.client_id as client_id, employees.name, employee_polices.rand_string, employee_polices.tpa_id')
->join('employees', 'employees.id = employee_polices.employee_id')
->where('employees.emp_status', 'active')
->where('employees.is_active', '1')
->where('employee_polices.status', 'active')
->where('employee_polices.is_active', '1')
->where('employee_polices.id', $ids[0])->first();
$client_data = $this->clientModel->where('id', $get_client_info_for_notification['client_id'])->first();
$notification = $this->notificationModel->where('client_id', $get_client_info_for_notification['client_id'])->where('template_name', 'member_ecard_mail')->first();
if ($notification != null && !empty($notification) && $notification['enabled'] == 1) {
try {
$this->myLogger->logme('error', 'sendMailForDownloadingECard - inside try');
$count = 0;
$counts = 0;
foreach ($ids as $key => $id) {
$get_emp_email_and_other_details = $this->employeePolicyModel
->select('employee_polices.client_policy_id, employees.relationship, employees.emp_code, employees.email_corporate,employees.client_id as client_id, employees.name, employee_polices.rand_string, employee_polices.tpa_id')
->join('employees', 'employees.id = employee_polices.employee_id')
->where('employees.emp_status', 'active')
->where('employees.is_active', '1')
->where('employee_polices.status', 'active')
->where('employee_polices.is_active', '1')
->where('employee_polices.id', $id)->first();
$this->myLogger->logme('error', 'sendMailForDownloadingECard - emp_policy_id : {id}', ['id' => $id]);
if ($get_emp_email_and_other_details != null && !empty($get_emp_email_and_other_details)) {
$this->myLogger->logme('error', 'sendMailForDownloadingECard - Send Bulk Mail function inside if condition ',);
$rand_string = $get_emp_email_and_other_details['rand_string'];
$tpa_id = $get_emp_email_and_other_details['tpa_id'];
$params['rand_string'] = $rand_string;
$params['tpa_id'] = $tpa_id;
$params['notification'] = $notification;
$params['client_data'] = $client_data;
$params['notification'] = $notification;
$params['notification'] = $notification;
$params['get_emp_email_and_other_details'] = $get_emp_email_and_other_details;
// $this->myLogger->logme('error', 'sendMailForDownloadingECard - Send Bulk Mail function end ',);
if (isset($get_emp_email_and_other_details['email_corporate']) && !empty($get_emp_email_and_other_details['email_corporate']) && $get_emp_email_and_other_details['relationship'] === 'Self') {
$wholeData[] = sendMailNotification::sendMailNotification('member_ecard_mail', $params);
$count++;
}
$counts++;
if ($count == 20 || $counts == count($ids) - 1) {
if(count($wholeData) > 0){
$this->myLogger->logme('error', 'sendMailForDownloadingECard - create a job to bulk mail',);
$job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'bulk_mail', 'payload' => $wholeData]);
$wholeData = [];
$count = 0;
}
}
$this->myLogger->logme('error', 'sendMailForDownloadingECard - Send Bulk Mail function end ',);
}
}
return true; // Email(s) sent successfully
} catch (\Exception $e) {
// Log the error
$this->myLogger->logme('error', 'sendMailForDownloadingECard : inside catch');
$this->myLogger->logme('error', 'Error occurred while sending email: ' . $e->getMessage());
return false; // Email(s) sending failed
}
} else {
$this->myLogger->logme('error', 'sendMailForDownloadingECard - the client notification setup not created or not enabled the E-Card Notification');
return false;
}
} else {
$this->myLogger->logme('error', 'sendMailForDownloadingECard - employee_policy_ids are empty');
return false;
}
}
public function readExcelFileToArray($path)
{
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($path);
$sheet = $spreadsheet->getActiveSheet();
$highestRowAndColumn = $sheet->getHighestRowAndColumn();
$excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
return $excel_data;
}
public function removeOldExportInfoFromBatchFile($params){
$client_id = $params['client_id'];
$client_policy_id = $params['client_policy_id'];
$insurer_or_tpa = $params['insurer_or_tpa'];
$event_type = $params['event_type'];
$actions = $params['actions'];
$batch_data = $this->batchFileModel
->where('client_id', $client_id)
->where('client_policy_id', $client_policy_id)
->where('insurer_or_tpa', $insurer_or_tpa)
->where('event_type', $event_type)
->where('actions', $actions)
->first();
if(!empty($batch_data)){
$id = $batch_data['id'];
$batch_code = $batch_data['batch_code'];
$this->batchFileModel->where('id', $id)->delete();
$this->batchListModel->where('batch_code', $batch_code)->delete();
}
}
public function getDataByFileId($file_id, $status = 'success'){
$data = $this->batchFileModel
->select('batch_files.*, clients.client_name, clients.short_name, policies.name as policy_name')
->join('clients', 'clients.id = batch_files.client_id')
->join('client_policy', 'client_policy.id = batch_files.client_policy_id')
->join('policies', 'policies.id = client_policy.policy_id')
->where('batch_files.id', $file_id)
->first();
if($status == 'success'){
$msg_txt = $data['short_name'] . ' - ' . $data['policy_name'] . ' - ' . $data['event_type'] . ' - ' . $data['actions'] . ' - ' . $data['insurer_or_tpa'];
$msg_title = 'File Upload Success';
}else if ($status == 'failure'){
$msg_txt = $data['short_name'] . ' - ' . $data['policy_name'] . ' - ' . $data['event_type'] . ' - ' . $data['actions'] . ' - ' . $data['insurer_or_tpa'];
$msg_title = 'File Upload Failure';
}
$user_id = $data['created_by'];
$url = 'employee/upload#KYC-DOC-tab';
return ['msg_txt' => $msg_txt, 'user_id' => $user_id, 'url' => $url, 'status' => $status, 'title' => $msg_title];
}
public function setPullNotification($data){
$array = ['message_text' => $data['msg_txt'], 'action_url' => $data['url'], 'msg_status' => $data['status'], 'msg_title' => $data['title']];
$jsonEncodeData = json_encode($array);
$msg_data = [
'message_text' => $jsonEncodeData,
'user_id' => $data['user_id'],
'role_id' => NULL,
'team_id' => NULL,
'message_type' => '1to1',
];
$this->messageModel->insert($msg_data);
}
}