nhance/app/Controllers/EmpDataServiceController.php

1659 lines
57 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\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\Controllers\Jobs;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
// use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Exception as SpreadsheetReaderException;
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;
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();
}
/**
* 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;
}
/**
* 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)
{
// Fetch employee data for export from the database
$objects = $this->employeePolicyModel->getInceptionEmployeeDataForExportExcel($export_data);
// dd($objects);
$totals = 0;
foreach ($objects as $key => $value) {
$totals += $value->total;
}
// Log the count of exported data
$count = count($objects);
$export_data['count'] = $count;
$export_data['amount'] = $totals;
$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);
// If batch operation is successful
if ($return) {
// 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)
{
$client_id = $import_data['client_id'];
$client_policy_id = $import_data['client_policy_id'];
$file = $import_data['file'];
$data = $this->readExcelToArray($file);
if (!$data) {
return 0;
}
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 ($import_data['insurer_or_tpa'] == 'tpa') {
if ($value[15] === null) {
$missing_id[] = $key + 1;
}
} else if ($import_data['insurer_or_tpa'] == 'insurer') {
if ($value[16] === null) {
$missing_id[] = $key + 1;
}
}
$emp_code = $value[2];
$name = $value[1];
$totals += $value[20];
$db = \Config\Database::connect();
// 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 ($import_data['insurer_or_tpa'] == 'tpa') {
$query->where('(employee_polices.tpa_id IS NULL OR employee_polices.tpa_id = "")');
} else if ($import_data['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'];
}
} catch (\Exception $e) {
return 0;
}
}
$missing_id_count = count($missing_id);
$empty_id_count = count($empty_emp_tpa_uh_ids);
if ($import_data['insurer_or_tpa'] == 'tpa') {
if ($empty_id_count == 0) {
return 3;
}
if ($missing_id_count != 0) {
return 2;
}
} else if ($import_data['insurer_or_tpa'] == 'insurer') {
if ($empty_id_count == 0) {
return 5;
}
if ($missing_id_count != 0) {
return 4;
}
}
// if ($missing_id_count != $count) {
// return 2;
// }
// if ($empty_emp_tpa_uh_ids != $count) {
// return 3;
// }
// dd($empty_emp_tpa_uh_ids);
$is_moved = $file->move(WRITEPATH . 'uploads/import_excel');
$filename = $file->getName();
$this->myLogger->logme('error', 'Inception Import file name : {data}', ['data' => $filename]);
$import_data['count'] = $count;
$import_data['file_name'] = $filename;
$import_data['amount'] = $totals;
$this->insertBatchFileAndBatchListForImportExcel($import_data, $empty_emp_tpa_uh_ids);
// dd($import_data, $empty_emp_tpa_uh_ids);
$tpa_id = [];
$uhid = [];
foreach ($data as $key => $value) {
$tpa_id[] = $value[15];
$uhid[] = $value[16];
}
foreach ($empty_emp_tpa_uh_ids as $key => $id) {
$dataToUpdateTPAID = ['tpa_id' => $tpa_id[$key]];
$dataToUpdateUHID = ['uhid' => $uhid[$key]];
$this->employeePolicyModel->where('id', $id)
->where('(employee_polices.tpa_id IS NULL OR employee_polices.tpa_id = "")')
->set($dataToUpdateTPAID)->update();
$this->employeePolicyModel->where('id', $id)
->where('(employee_polices.uhid IS NULL OR employee_polices.uhid = "")')
->set($dataToUpdateUHID)->update();
}
if($import_data['insurer_or_tpa'] == 'tpa'){
$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' => $count,
'event' => $import_data['event_type'],
'policy_name' => $policy_name['policy_name'],
];
$this->cashDepositCalculationForInception($depositeData);
$this->sendMailForDownloadingECard($empty_emp_tpa_uh_ids);
}
return 1;
}
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']) . '.';
$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' => 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 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)
{
try {
foreach ($ids as $key => $id) {
$get_emp_email_and_other_details = $this->employeePolicyModel
->select('employee_polices.client_policy_id, employees.emp_code, employees.email_corporate, 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();
if ($get_emp_email_and_other_details != null && $get_emp_email_and_other_details != "") {
$name = $get_emp_email_and_other_details['name'];
$email = $get_emp_email_and_other_details['email_corporate'];
$rand_string = $get_emp_email_and_other_details['rand_string'];
$tpa_id = $get_emp_email_and_other_details['tpa_id'];
$link = generate_download_link($rand_string);
$subject = 'Download E-Card';
$html = '<body>
<p>Dear ' .$name .',</p>
<p>Your Policy( ' .$tpa_id .' ) has been successfully created. Please click the link below to download the insurance card:</p>
<p><a href="'.$link.'">Download Insurance Card</a></p>
<p>Thank you,</p>
</body>';
if ($email != null && $email != "") {
$mail_data = [
'mail' => $email,
'subject' => $subject,
'message' => $html
];
// dd($mail_data);
$result = Mailhelper::send_email($mail_data);
$decoded_result = (array) json_decode($result);
$data = [
'status' => $decoded_result['status'],
'message'=>$decoded_result['message'] ?? 'Internal Server Error',
'email' => $decoded_result['data']
];
// dd($data);
$this->myLogger->logme('error', 'status : {status}, message : {message}, email : {email}', $data);
}
}
}
return true; // Email(s) sent successfully
} catch (\Exception $e) {
// Log the error
$this->myLogger->log('error', 'Error occurred while sending email: ' . $e->getMessage());
return false; // Email(s) sending failed
}
}
}