nhance/app/Controllers/EmployeeServiceController.php

2631 lines
137 KiB
PHP
Executable File

<?php
namespace App\Controllers;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Models\EmployeeModel;
use App\Models\EmployeePolicyModel;
use App\Models\ClientModel;
use App\Models\ClientPolicyModel;
use App\Models\PolicesModel;
use App\Models\FileModel;
use App\Models\EmpEndorsementModel;
use App\Models\MessageModel;
use App\Models\ClientBranchModel;
use App\Models\NotificationModel;
use App\Models\InsurerModel;
use App\Helpers\sendMailNotification;
use App\Controllers\Jobs ;
use App\Controllers\JobWorker ;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Kint\Kint;
use App\Helpers\ExcelSanitizeHelper;
use App\Models\LeadsModel;
class EmployeeServiceController extends AdminController
{
protected $myLogger;
protected $employeeModel;
protected $employeePolicyModel;
protected $clientModel;
protected $fileModel;
protected $clientPolicyModel;
protected $policiesModel;
protected $empEndorsementModel;
protected $messageModel;
protected $clientBranchModel;
protected $notificationModel;
protected $insurerModel;
protected $general_relationships = [
'self' => [
'name' => 'Self',
'gender' => 'M',
'age_min' => 18,
'age_max' => null
],
'spouse' => [
'name' => 'Spouse',
'gender' => 'F',
'age_min' => 18,
'age_max' => null
],
'son' => [
'name' => 'Son',
'gender' => 'M',
'age_min' => null,
'age_max' => 25
],
'daughter' => [
'name' => 'Daughter',
'gender' => 'F',
'age_min' => null,
'age_max' => 25
],
'father' => [
'name' => 'Father',
'gender' => 'M',
'age_min' => 18,
'age_max' => null
],
'mother' => [
'name' => 'Mother',
'gender' => 'F',
'age_min' => 18,
'age_max' => null
],
'father-in-law' => [
'name' => 'Father in Law',
'gender' => 'M',
'age_min' => 18,
'age_max' => null
],
'mother-in-law' => [
'name' => 'Mother in Law',
'gender' => 'F',
'age_min' => 18,
'age_max' => null
]
];
protected $inception_excel_columns = [
'sno' => [
'col_idx' => 0,
'col_cell_name' => 'A',
'col_name' => 'S.No',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'emp_id' => [
'col_idx' => 1,
'col_cell_name' => 'B',
'col_name' => 'EMP ID',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'name_of_emp_dep' => [
'col_idx' => 2,
'col_cell_name' => 'C',
'col_name' => 'NAME OF EMP/DEP',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'dob' => [
'col_idx' => 3,
'col_cell_name' => 'D',
'col_name' => 'DOB',
'is_mandatory' => ['I', 'A', 'DA'],
'data_type' => 'str',
'format' => 'd-M-Y',
'allowed_values' => null,
'custom' => 'check_dob_diff',
'params' => ['row', 'relationship', 'default_age_ratio','policy_details']
],
'gender' => [
'col_idx' => 4,
'col_cell_name' => 'E',
'col_name' => 'Gender',
'is_mandatory' => ['I', 'A', 'DA'],
'data_type' => 'str',
'format' => null,
'allowed_values' => ['M', 'F', 'Male', 'Female', 'male', 'female', 'MALE', 'FEMALE']
],
'relationship' => [
'col_idx' => 5,
'col_cell_name' => 'F',
'col_name' => 'RELATIONSHIP',
'is_mandatory' => ['I', 'A', 'DA'],
'data_type' => 'str',
'format' => null,
'allowed_values' => ['Self', 'Spouse', 'Son', 'Daughter', 'Father', 'Mother', 'Father in Law', 'Mother in Law'],
'custom' => 'check_relationship',
'params' => ['row', 'relationship', 'policy_terms']
],
'basic_cover_si' => [
'col_idx' => 6,
'col_cell_name' => 'G',
'col_name' => 'BASIC COVER SI',
'is_mandatory' => null,
'data_type' => 'str',
'format' => null,
'allowed_values' => null,
'custom' => 'check_si',
'params' => ['row', 'policy_details', 'slab_details']
],
'doc' => [
'col_idx' => 7,
'col_cell_name' => 'H',
'col_name' => 'Date of Coverage',
'is_mandatory' => ['A', 'DA'],
'data_type' => 'str',
'format' => 'd-M-Y',
'allowed_values' => null,
'custom' => 'check_doc',
'params' => ['row', 'policy_details']
],
'doj' => [
'col_idx' => 8,
'col_cell_name' => 'I',
'col_name' => 'DOJ',
'is_mandatory' => false,
'data_type' => 'str',
'format' => 'd-M-Y',
'allowed_values' => null,
'custom' => 'check_doj',
'params' => ['row']
],
'basic_pay' => [
'col_idx' => 9,
'col_cell_name' => 'J',
'col_name' => 'Basic Pay',
'is_mandatory' => false,
'data_type' => 'str',
'format' => null,
'allowed_values' => null,
'custom' => 'check_basic_pay',
'params' => ['row', 'policy_terms', 'slab_details']
],
'band_grade' => [
'col_idx' => 10,
'col_cell_name' => 'K',
'col_name' => 'Band/Grade',
'is_mandatory' => false,
'data_type' => 'str',
'format' => null,
'allowed_values' => null,
'custom' => 'check_employee_band',
'params' => ['row', 'policy_terms', 'slab_details']
],
'designation' => [
'col_idx' => 11,
'col_cell_name' => 'L',
'col_name' => 'Designation',
'is_mandatory' => false,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'phone' => [
'col_idx' => 12,
'col_cell_name' => 'M',
'col_name' => 'Phone',
'is_mandatory' => false,
'data_type' => 'str',
'format' => null,
'allowed_values' => null,
'custom' => 'check_dup_mobileno',
'params' => ['row', 'existing_mobilenos']
],
'email' => [
'col_idx' => 13,
'col_cell_name' => 'N',
'col_name' => 'Email',
'is_mandatory' => false,
'data_type' => 'str',
'format' => null,
'allowed_values' => null,
'custom' => 'check_dup_email',
'params' => ['row', 'existing_mobilenos']
],
'pre_existing_ailments' => [
'col_idx' => 14,
'col_cell_name' => 'O',
'col_name' => 'PRE EXISTING AILMENTS',
'is_mandatory' => ['I', 'A', 'DA'],
'data_type' => 'str',
'format' => null,
'allowed_values' => ['0', '1']
],
'change_event' => [
'col_idx' => 15,
'col_cell_name' => 'P',
'col_name' => 'Change event',
'is_mandatory' => ['A', 'DA', 'D'],
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'date_of_exit' => [
'col_idx' => 16,
'col_cell_name' => 'Q',
'col_name' => 'Date of exit',
'is_mandatory' => ['D'],
'data_type' => 'str',
'format' => 'd-M-Y',
'allowed_values' => null
],
'reason_for_exit' => [
'col_idx' => 17,
'col_cell_name' => 'R',
'col_name' => 'Reason for exit',
'is_mandatory' => ['D'],
'data_type' => 'str',
'format' => null,
'allowed_values' => null
]
,
'unit' => [
'col_idx' => 18,
'col_cell_name' => 'S',
'col_name' => 'Unit',
'is_mandatory' => false,
'data_type' => 'str',
'format' => null,
'allowed_values' => null,
'custom' => 'check_unit',
'params' => ['row', 'existing_units']
]
];
protected $deletion_excel_columns = [
'sno' => [
'col_idx' => 0,
'col_cell_name' => 'A',
'col_name' => 'S.No',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'emp_id' => [
'col_idx' => 1,
'col_cell_name' => 'B',
'col_name' => 'EMP ID',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'name_of_emp_dep' => [
'col_idx' => 2,
'col_cell_name' => 'C',
'col_name' => 'NAME OF EMP/DEP',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'change_event' => [
'col_idx' => 3,
'col_cell_name' => 'D',
'col_name' => 'Change event',
'is_mandatory' => ['D'],
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'date_of_exit' => [
'col_idx' => 4,
'col_cell_name' => 'E',
'col_name' => 'Date of exit',
'is_mandatory' => ['D'],
'data_type' => 'str',
'format' => 'd-M-Y',
'allowed_values' => null
],
'reason_for_exit' => [
'col_idx' => 5,
'col_cell_name' => 'F',
'col_name' => 'Reason for exit',
'is_mandatory' => ['D'],
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'claim_status' => [
'col_idx' => 6,
'col_cell_name' => 'G',
'col_name' => 'Claim status',
'is_mandatory' => ['D'],
'data_type' => 'str',
'format' => null,
'allowed_values' => [0,1]
]
];
protected $correction_excel_columns = [
'sno' => [
'col_idx' => 0,
'col_cell_name' => 'A',
'col_name' => 'S.No',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'emp_id' => [
'col_idx' => 1,
'col_cell_name' => 'B',
'col_name' => 'EMP ID',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'name_of_emp_dep' => [
'col_idx' => 2,
'col_cell_name' => 'C',
'col_name' => 'NAME OF EMP/DEP',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'field' => [
'col_idx' => 3,
'col_cell_name' => 'D',
'col_name' => 'Field',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => ['name', 'dob', 'relationship', 'email_corporate']
],
'value' => [
'col_idx' => 4,
'col_cell_name' => 'E',
'col_name' => 'Value',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'date_of_correction' => [
'col_idx' => 5,
'col_cell_name' => 'F',
'col_name' => 'Date of Correction',
'is_mandatory' => true,
'data_type' => 'str',
'format' => 'd-M-Y',
'allowed_values' => null
],
'change_event' => [
'col_idx' => 6,
'col_cell_name' => 'G',
'col_name' => 'Change event',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'remarks' => [
'col_idx' => 7,
'col_cell_name' => 'H',
'col_name' => 'Remarks',
'is_mandatory' => false,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
]
];
protected $si_enhance_excel_columns = [
'sno' => [
'col_idx' => 0,
'col_cell_name' => 'A',
'col_name' => 'S.No',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'emp_id' => [
'col_idx' => 1,
'col_cell_name' => 'B',
'col_name' => 'EMP ID',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'name_of_emp_dep' => [
'col_idx' => 2,
'col_cell_name' => 'C',
'col_name' => 'NAME OF EMP/DEP',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'augmented_si' => [
'col_idx' => 3,
'col_cell_name' => 'D',
'col_name' => 'Augmented SI',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => null,
'custom' => 'check_si',
'params' => ['row', 'policy_details', 'slab_details']
],
'date_of_enhancement' => [
'col_idx' => 4,
'col_cell_name' => 'E',
'col_name' => 'Date of SI Enhancement',
'is_mandatory' => true,
'data_type' => 'str',
'format' => 'd-M-Y',
'allowed_values' => null
]
];
protected $enrollment_excel_columns = [
'sno' => [
'col_idx' => 0,
'col_cell_name' => 'A',
'col_name' => 'Sno',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'emp_id' => [
'col_idx' => 1,
'col_cell_name' => 'B',
'col_name' => 'Emp code',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'name_of_emp_dep' => [
'col_idx' => 2,
'col_cell_name' => 'C',
'col_name' => 'Name',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'doj' => [
'col_idx' => 3,
'col_cell_name' => 'D',
'col_name' => 'DOJ',
'is_mandatory' => true,
'data_type' => 'str',
'format' => 'd-M-Y',
'allowed_values' => null,
'custom' => null
],
'gender' => [
'col_idx' => 4,
'col_cell_name' => 'E',
'col_name' => 'Gender',
'is_mandatory' => ['I', 'A', 'DA','E'],
'data_type' => 'str',
'format' => null,
'allowed_values' => ['M', 'F', 'Male', 'Female', 'male', 'female', 'MALE', 'FEMALE']
],
'relationship' => [
'col_idx' => 5,
'col_cell_name' => 'F',
'col_name' => 'Relation',
'is_mandatory' => ['I', 'A', 'DA','E'],
'data_type' => 'str',
'format' => null,
'allowed_values' => null,
'custom' => null
],
'dob' => [
'col_idx' => 6,
'col_cell_name' => 'G',
'col_name' => 'DOB',
'is_mandatory' => ['I', 'A', 'DA'],
'data_type' => 'str',
'format' => 'd-M-Y',
'allowed_values' => null,
'custom' => null,
],
'email' => [
'col_idx' => 7,
'col_cell_name' => 'H',
'col_name' => 'Mail',
'is_mandatory' => false,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'phone' => [
'col_idx' => 8,
'col_cell_name' => 'I',
'col_name' => 'Mobile',
'is_mandatory' => false,
'data_type' => 'str',
'format' => null,
'allowed_values' => null,
'custom' => null
],
'basic_cover_si' => [
'col_idx' => 9,
'col_cell_name' => 'J',
'col_name' => 'SI',
'is_mandatory' => null,
'data_type' => 'str',
'format' => null,
'allowed_values' => null,
'custom' => null
],
'band_grade' => [
'col_idx' => 10,
'col_cell_name' => 'K',
'col_name' => 'Grade',
'is_mandatory' => false,
'data_type' => 'str',
'format' => null,
'allowed_values' => null,
'custom' => null
],
'basic_pay' => [
'col_idx' => 11,
'col_cell_name' => 'L',
'col_name' => 'Basic Pay',
'is_mandatory' => false,
'data_type' => 'str',
'format' => null,
'allowed_values' => null,
'custom' => null
],
'unit' => [
'col_idx' => 12,
'col_cell_name' => 'M',
'col_name' => 'Unit',
'is_mandatory' => false,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'doc' => [
'col_idx' => 13,
'col_cell_name' => 'N',
'col_name' => 'DOC',
'is_mandatory' => false,
'data_type' => 'str',
'format' => 'd-M-Y',
'allowed_values' => null
]
];
protected $incetion_to_enrollment_mapping = [
0 => 0, // inception: sno (S.No) -> enrollment: sno (Sno)
1 => 1, // inception: emp_id (EMP ID) -> enrollment: emp_code (Emp_Code)
2 => 2, // inception: name_of_emp_dep (NAME OF EMP/DEP) -> enrollment: name (NAME OF EMP/DEP)
3 => 6, // inception: dob (DOB) -> enrollment: dob (DOB)
4 => 4, // inception: gender (Gender) -> enrollment: gender (Gender)
5 => 5, // inception: relationship (RELATIONSHIP) -> enrollment: relationship (Relation)
6 => 9, // inception: basic_cover_si (BASIC COVER SI) -> enrollment: basic_cover_si (SI)
7 => 13, // inception: doc (Date of Coverage)
8 => 3, // inception: doj (DOJ) -> enrollment: doj (DOJ)
9 => 11, // inception: basic_pay (Basic Pay) -> enrollment: basic_pay (Basic Pay)
10 => 10, // inception: band_grade (Band/Grade) -> enrollment: band_grade (Grade)
11 => null, // inception: designation (Designation) -> No match in enrollment
12 => 8, // inception: phone (Phone) -> enrollment: phone (Mobile)
13 => 7, // inception: email (Email) -> enrollment: email (Email)
14 => null, // inception: pre_existing_ailments (PRE EXISTING AILMENTS) -> No match in enrollment
15 => null, // inception: change_event (Change event) -> No match in enrollment
16 => null, // inception: date_of_exit (Date of exit) -> No match in enrollment
17 => null, // inception: reason_for_exit (Reason for exit) -> No match in enrollment
18 => null // inception: reason_for_exit (Reason for exit) -> No match in enrollment
];
protected $enrollment_to_inception_mapping = [
0 => 0, // enrollment: sno (Sno) -> inception: sno (S.No)
1 => 1, // enrollment: emp_code (Emp_Code) -> inception: emp_id (EMP ID)
2 => 2, // enrollment: name (NAME OF EMP/DEP) -> inception: name_of_emp_dep (NAME OF EMP/DEP)
3 => 8, // enrollment: doj (DOJ) -> inception: doj (DOJ)
4 => 4, // enrollment: gender (Gender) -> inception: gender (Gender)
5 => 5, // enrollment: relationship (Relation) -> inception: relationship (RELATIONSHIP)
6 => 3, // enrollment: dob (DOB) -> inception: dob (DOB)
7 => 13, // enrollment: email (Email) -> inception: email (Email)
8 => 12, // enrollment: phone (Mobile) -> inception: phone (Phone)
9 => 6, // enrollment: basic_cover_si (SI) -> inception: basic_cover_si (BASIC COVER SI)
10 => 10, // enrollment: band_grade (Grade) -> inception: band_grade (Band/Grade)
11 => 9 // enrollment: basic_pay (Basic Pay) -> inception: basic_pay (Basic Pay)
];
protected $member_data_excel_columns = [
'sno' => [
'col_idx' => 0,
'col_cell_name' => 'A',
'col_name' => 'Sl no',
'is_mandatory' => false,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'emp_code' => [
'col_idx' => 1,
'col_cell_name' => 'B',
'col_name' => 'Emp Code',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'name' => [
'col_idx' => 2,
'col_cell_name' => 'C',
'col_name' => 'Name',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'relationship' => [
'col_idx' => 3,
'col_cell_name' => 'D',
'col_name' => 'Relationship',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => [
'Self', 'Spouse', 'Son', 'Daughter', 'Father', 'Mother',
'Father-in-law', 'Mother-in-law',
'self', 'spouse', 'son', 'daughter', 'father', 'mother',
'father-in-law', 'mother-in-law'
],
'custom' => 'check_relationship_for_member_data',
'params' => ['row', 'relationship', 'columns_to_check']
],
'gender' => [
'col_idx' => 4,
'col_cell_name' => 'E',
'col_name' => 'Gender',
'is_mandatory' => true,
'data_type' => 'str',
'format' => null,
'allowed_values' => ['M', 'F', 'Male', 'Female', 'male', 'female', 'MALE', 'FEMALE']
],
'dob' => [
'col_idx' => 5,
'col_cell_name' => 'F',
'col_name' => 'DOB',
'is_mandatory' => true,
'data_type' => 'str',
'format' => 'd-M-Y',
'allowed_values' => null,
'age_validation' => true,
// 'custom' => 'check_dob_diff',
// 'params' => ['row', 'relationship', 'default_age_ratio', 'policy_details']
],
'age' => [
'col_idx' => 6,
'col_cell_name' => 'G',
'col_name' => 'Age',
'is_mandatory' => true,
'data_type' => 'int',
'format' => null,
'allowed_values' => null
],
'email' => [
'col_idx' => 7,
'col_cell_name' => 'H',
'col_name' => 'Email',
'is_mandatory' => false,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'mobile' => [
'col_idx' => 8,
'col_cell_name' => 'I',
'col_name' => 'Mobile',
'is_mandatory' => false,
'data_type' => 'str',
'format' => null,
'allowed_values' => null
],
'si' => [
'col_idx' => 9,
'col_cell_name' => 'J',
'col_name' => 'SI',
'is_mandatory' => false,
'data_type' => 'int',
'format' => null,
'allowed_values' => null,
]
];
public function __construct()
{
// helper('utility');
set_session_context('EmployeeService');
$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->policiesModel = new PolicesModel();
$this->empEndorsementModel = new EmpEndorsementModel();
$this->messageModel = new MessageModel();
$this->clientBranchModel = new ClientBranchModel();
$this->notificationModel = new NotificationModel();
$this->insurerModel = new InsurerModel();
}
public function excelFileFormatValidation($params)
{
helper('excel_util_helper');
//get file name
// check_dob_diff('4-APr-1990');die();
$file_id = $params['file_id'];
$batch_file_id = $params['batch_file_id'] ?? null;
$file = $this->fileModel->find((int)$file_id);
// dd($file);
$return = [];
if(!isset($file))
{
//file not found in DB
return array('status' => false, 'msg' => 'file not found in DB');
}
$file_name_with_path = WRITEPATH."/uploads/excel/".$file['file_name'];
//check physical file
if(!file_exists($file_name_with_path))
{
//file not found update status and reason
$message = "Physcial file not found";
// echo $message;
$this->myLogger->logme('error',($message . ' for file id ' . $file_id));
$this->fileModel->where('id', $file_id)->set(['status' => 'failed','reason' => json_encode(['error_summary' => array_count_values([5]),'error_data' => $message])])->update();
return array('error_summary' => [5], 'error_data' => $message);
}
//start validation process
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
$sheet = $spreadsheet->getActiveSheet();
$highestRowAndColumn = $sheet->getHighestRowAndColumn();
// dd($highestRowAndColumn);
$columns_to_check = [];
if($file['action'] == 'inception'){ $columns_to_check = $this->inception_excel_columns; }
if($file['action'] == 'addition'){ $columns_to_check = $this->inception_excel_columns; }
if($file['action'] == 'dependent_addition'){ $columns_to_check = $this->inception_excel_columns; }
if($file['action'] == 'deletion'){ $columns_to_check = $this->deletion_excel_columns; }
if($file['action'] == 'correction'){ $columns_to_check = $this->correction_excel_columns; }
if($file['action'] == 'si_enhancement'){ $columns_to_check = $this->si_enhance_excel_columns; }
if($file['action'] == 'enrollment'){ $columns_to_check = $this->enrollment_excel_columns; }
if($file['action'] == 'missed_inception'){ $columns_to_check = $this->inception_excel_columns; }
$result = ['error_type' => 1,'error_summary' => [], 'error_data' => [] ];
$keys = array_keys($columns_to_check);
$allowedHighestColumn = end($columns_to_check);
// dd($allowedHighestColumn);
$excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']);
$excel_data = ExcelSanitizeHelper::sanitizeArrayData($excel_data);
// !dd(array_chunk($excel_data,20)[0]);
//check no of columns in excel
$total_defined_columns = count($columns_to_check);
$excel_columns = ($excel_data[0]);
// var_dump($total_defined_columns);die();
$excel_columns_count = count($excel_columns);
if($total_defined_columns != $excel_columns_count)
{
//columns count mismatch
$message = "File columns count mismatch. Expected - $total_defined_columns and received - $excel_columns_count";
// echo $message;
$this->myLogger->logme('error',($message . ' for file id ' . $file_id));
$this->fileModel->where('id', $file_id)->set(['status' => 'failed','reason' => json_encode(['error_summary' => array_count_values([5]),'error_data' => $message])])->update();
return array('error_summary' => [5], 'error_data' => $message);
}
//check columns order in excel
$column_count_res = check_columns_name($columns_to_check,$excel_columns);
if(isset($column_count_res) && count($column_count_res))
{
//columns count mismatch
$message = implode("\n", $column_count_res);
// echo $message;
$this->myLogger->logme('error',($message . ' for file id ' . $file_id));
$this->fileModel->where('id', $file_id)->set(['status' => 'failed','reason' => json_encode(['error_summary' => array_count_values([6]), 'error_data' => $message])])->update();
return array('error_summary' => [6], 'error_data' => $message);
}
// dd($columns_to_check);die();
// get policy and rack details
$policy_details = $this->clientPolicyModel->getPolicyDetails($file['client_id'],$file['policy_id']);
if(empty($policy_details)){
$message = "Policy configuration is incomplete. Cannot proceed.";
$this->myLogger->logme('error',($message . ' for file id ' . $file_id));
$this->fileModel->where('id', $file_id)->set(['status' => 'failed','reason' => json_encode(['error_summary' => array_count_values([5]),'error_data' => $message])])->update();
return array('error_summary' => [5], 'error_data' => $message);
}
$policy_terms = json_decode($policy_details[0]->policy_terms);
$policy_terms = (array) $policy_terms;// convert obj to array
$default_age_ratio = isset($policy_terms['age_ratio']) ? json_decode(json_encode($policy_terms['age_ratio']),true) : [];
//
// dd($default_age_ratio);
//get policy slab rates
$slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($file['policy_id'],$file['client_id']);
// dd($slab_details);
if(empty($slab_details) || (isset($slab_details['slab_rates']) && empty($slab_details['slab_rates']))){
$message = "Policy configuration is incomplete. Cannot proceed.";
$this->myLogger->logme('error',($message . ' for file id ' . $file_id));
$this->fileModel->where('id', $file_id)->set(['status' => 'failed','reason' => json_encode(['error_summary' => array_count_values([5]),'error_data' => $message])])->update();
return array('error_summary' => [5], 'error_data' => $message);
}
//remove header
unset($excel_data[0]);
$relationship = $this->general_relationships;
//get exisiting mobilr nos
$existing_mobilenos = $this->employeePolicyModel->getExisitingMobileNos(client_policy_id: $file['policy_id']);
//get existing units in the current branch
$existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $file['client_id'],client_branch_id: $file['client_branch_id']);
// dd($excel_data);
foreach ($excel_data as $row_key => $row)
{
//define row wise action/event in temporary variable
$current_column_action = null;
if($file['action'] == 'inception'){ $current_column_action = 'I'; }
else if($file['action'] == 'addition'){ $current_column_action = 'A'; }
else if($file['action'] == 'dependent_addition'){ $current_column_action = 'DA'; }
else if($file['action'] == 'deletion'){ $current_column_action = 'D'; }
else if($file['action'] == 'correction'){ $current_column_action = 'C'; }
else if($file['action'] == 'si_enhancement'){ $current_column_action = 'SI'; }
else if($file['action'] == 'enrollment'){ $current_column_action = 'I'; }
else if($file['action'] == 'missed_inception'){ $current_column_action = 'MI'; }
//1. avoid empty rows
if(check_row_is_empty_or_null($row))
{
break;
}
// Kint::dump($keys);
if ($file['action'] == 'enrollment')
{
$row = transform_enrollment_row_to_inception_row($row);
$columns_to_check = $this->inception_excel_columns;
$keys = array_keys($columns_to_check);
$enrollment_columns_to_check = $this->enrollment_excel_columns;
$enrollment_keys = array_keys($enrollment_columns_to_check);
}
// for this condition to avoid 5,00,000 to 500000
if($current_column_action == 'SI'){
$row[3] = removeNumberFormatting($row[3]);
}else if(in_array($current_column_action, ['I','DA', 'MI', 'A'])){
$row[6] = removeNumberFormatting($row[6]);
}
//iterate each row for columns validations
foreach ($row as $col_key => $col)
{
$is_mandatory = $columns_to_check[$keys[$col_key]]['is_mandatory'];
$format = $columns_to_check[$keys[$col_key]]['format'];
$allowed_values = $columns_to_check[$keys[$col_key]]['allowed_values'];
$custom_function = isset($columns_to_check[$keys[$col_key]]['custom']) ? $columns_to_check[$keys[$col_key]]['custom'] : null;
$binding_params = isset($columns_to_check[$keys[$col_key]]['params']) ? $columns_to_check[$keys[$col_key]]['params'] : null;
$column_dispaly_name = $columns_to_check[$keys[$col_key]]['col_name'];
$column_index = $columns_to_check[$keys[$col_key]]['col_idx'];
$column_cell = $columns_to_check[$keys[$col_key]]['col_cell_name'];
if($file['action'] == 'enrollment')
{
if(isset($enrollment_keys[$this->incetion_to_enrollment_mapping[$col_key]]) && $enrollment_keys[$this->incetion_to_enrollment_mapping[$col_key]] != null && $enrollment_keys[$this->incetion_to_enrollment_mapping[$col_key]] != "")
{
$column_dispaly_name = $enrollment_columns_to_check[$enrollment_keys[$this->incetion_to_enrollment_mapping[$col_key]]]['col_name'];
$column_index = $enrollment_columns_to_check[$enrollment_keys[$this->incetion_to_enrollment_mapping[$col_key]]]['col_idx'];
$column_cell = $enrollment_columns_to_check[$enrollment_keys[$this->incetion_to_enrollment_mapping[$col_key]]]['col_cell_name'];
}
}
$row['current_action'] = $current_column_action;
//mandatory check
if(is_bool($is_mandatory) && $is_mandatory === true)
{
if($col == "" || $col == NULL)
{
array_push($result['error_summary'],1); //push error code for summary
$result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name
$result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index
$result['error_data'][$row_key][$keys[$col_key]]['error'][] = 'Value is mandatory'; //push exact error desc
}
}
//if is_mandatory is array (action based mandatory check)
if($current_column_action != null && is_array($is_mandatory) && in_array(strtoupper(trim($current_column_action)),$is_mandatory))
{
$allowed_actions = $columns_to_check[$keys[$col_key]]['is_mandatory'];
if($col == "" || $col == NULL)
{
array_push($result['error_summary'],1);
$result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name
$result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index
$result['error_data'][$row_key][$keys[$col_key]]['error'][] = 'Value is mandatory for this action/event';
}
}
//format check
if(isset($format))
{
$format_error = check_excel_date_format($col,$format);
if(!$format_error['status'])
{
array_push($result['error_summary'],2);
$result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name
$result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index
$result['error_data'][$row_key][$keys[$col_key]]['error'][] = $format_error['error'];
}
}
// Kint::dump($is_mandatory);
//allowed values check
if(($is_mandatory === true && isset($allowed_values) && is_array($allowed_values)) || (is_array($is_mandatory) && (isset($allowed_values) && is_array($allowed_values))))
{
// print_r($allowed_values);
// dd($col);
if(!in_array((trim($col)),$allowed_values))
{
array_push($result['error_summary'],3);
$result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name
$result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index
$result['error_data'][$row_key][$keys[$col_key]]['error'][] = "Value not allowed: Expected ".implode(",",$allowed_values)." and received $col";
}
}
//custom function check
if(isset($custom_function))
{
//convert string params into PHP variables
// Create an array of variables to pass custom helper funcitons
$param_values = [];
foreach($binding_params as $bkey => $bparam) { $param_values[] = ($$bparam); }
// dd(($param_values));//die();
$res = call_user_func_array($custom_function,$param_values);
// print_r($res['status']);die();
if($res['status'] === false)
{
array_push($result['error_summary'],4);
$result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name
$result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index
$result['error_data'][$row_key][$keys[$col_key]]['error'][] = $res['error'];
}
}
}//col foreach
// break;
}//row foreach
if(isset($result['error_summary']) && count($result['error_summary']))
{
$result['error_summary'] = array_count_values($result['error_summary']);
$status = 'failed';
$failure_reason = ((json_encode($result)));
$this->fileModel->where('id', $file_id)->set(['status' => $status,'reason' => $failure_reason])->update();
$this->myLogger->logme("error",'{file_id} uploaded failed',['file_id' => $file_id]);
//set failure msg to pull notifications
$this->setPullNotification($this->getFileMetaDataByFileId($file_id,'failure'));
}
else //trigger next data validation via job queue server
{
// check the condition if the policy from the Leads and check the lead id exist in the client policy table
if($file['action'] == 'inception' && $policy_details[0]->policy_entry_from == 3 && !empty($policy_details[0]->is_from_lead)){
$r = Jobs::addJob(['job_name' => 'compareMemberDataAndInceptionData','payload' => ['file_id' => $file_id]]);
$this->myLogger->logme("error",'compareMemberDataAndInceptionData job pushed');
return $result;
}
if($file['action'] == 'enrollment' && $file['uploaded_by'] != 1) // if current action is enrollment and uploaded by HR (0 or NULL) call next validation and return result
{
// dd();
$res = $this->excelFileDataValidation(['file_id' => $file['id']]);
return $res;
}
//proceed next data level validation in JOB queue
$job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'excelFileDataValidation','payload' => ['file_id' => $file_id, 'batch_file_id' => $batch_file_id]]);
// $jobWorker = new JobWorker();
// JobWorker::processJob($r);
}
return $result;
}
public function excelFileDataValidation($params)
{
helper('excel_util_helper');
//get file name
$file_id = $params['file_id'];
$batch_file_id = $params['batch_file_id'] ?? null;
$file = $this->fileModel->find((int)$file_id);
// dd($file);
$return = [];
if(!isset($file))
{
//file not found in DB
return array('status' => false, 'msg' => 'file not found in DB');
}
$file_name_with_path = WRITEPATH."/uploads/excel/".$file['file_name'];
//check physical file
if(!file_exists($file_name_with_path))
{
//file not found update status and reason
$message = "Physical file not found";
// echo $message;
$this->myLogger->logme('error',($message . ' for file id ' . $file_id));
$this->fileModel->where('id', $file_id)->set(['status' => 'failed','reason' => json_encode(['error_summary' => array_count_values([5]),'error_data' => $message])])->update();
return array('error_summary' => [5], 'error_data' => $message);
}
$columns_to_check = [];
if($file['action'] == 'inception'){ $columns_to_check = $this->inception_excel_columns; }
if($file['action'] == 'addition'){ $columns_to_check = $this->inception_excel_columns; }
if($file['action'] == 'dependent_addition'){ $columns_to_check = $this->inception_excel_columns; }
if($file['action'] == 'deletion'){ $columns_to_check = $this->deletion_excel_columns; }
if($file['action'] == 'correction'){ $columns_to_check = $this->correction_excel_columns; }
if($file['action'] == 'si_enhancement'){ $columns_to_check = $this->si_enhance_excel_columns; }
if($file['action'] == 'enrollment'){ $columns_to_check = $this->enrollment_excel_columns; }
if($file['action'] == 'missed_inception'){ $columns_to_check = $this->inception_excel_columns; }
$current_column_action = null;
if($file['action'] == 'inception'){ $current_column_action = 'I'; }
else if($file['action'] == 'addition'){ $current_column_action = 'A'; }
else if($file['action'] == 'dependent_addition'){ $current_column_action = 'DA'; }
else if($file['action'] == 'deletion'){ $current_column_action = 'D'; }
else if($file['action'] == 'correction'){ $current_column_action = 'C'; }
else if($file['action'] == 'si_enhancement'){ $current_column_action = 'SI'; }
else if($file['action'] == 'enrollment'){ $current_column_action = 'I'; }
else if($file['action'] == 'missed_inception'){ $current_column_action = 'MI'; }
// get policy and rack details
$policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'],$file['policy_id']);
$policy_details = (array)$policy_terms[0];
$is_lgbtq = $policy_details['is_lgbtq'];
// dd($this->clientPolicyModel->getLastQuery());
$policy_terms = json_decode($policy_terms[0]->policy_terms);
$policy_terms = (array) $policy_terms;// convert obj to array
// dd($policy_terms);
//get excel data
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
$sheet = $spreadsheet->getActiveSheet();
$highestRowAndColumn = $sheet->getHighestRowAndColumn();
$result = ['error_type' => 2,'error_summary' => [], 'error_data' => [] ];
$keys = array_keys($columns_to_check);
$allowedHighestColumn = end($columns_to_check);
$excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']);
$excel_data = ExcelSanitizeHelper::sanitizeArrayData($excel_data);
//remove header
unset($excel_data[0]);
// dd($columns_to_check);
$relationship = $this->general_relationships;
if(in_array($file['action'],['inception','missed_inception','addition','dependent_addition','deletion','correction','si_enhancement','enrollment']))// the below funcitons are only for I,DA,A
{
$employee_data_group_by_family = data_group_by_family($excel_data,'excel',($file['action'] == 'enrollment' ? 'enrollment' : ''), $current_column_action);
// dd($employee_data_group_by_family);
$is_self_available_in_policy_terms = false;
if($policy_details['policy_type_id'] == 3) // GMC parents
{
$temp = $policy_terms['family_floaters'];
$temp = is_array($temp) ? $temp : (is_object($temp) ? (array)$temp : []);
$is_self_available_in_policy_terms = isset($temp['self']) && $temp['self'] == 1 ? true : false;
// Kint::dump($temp['self']);
// dd($is_self_available_in_policy_terms);
}
// dd($employee_data_group_by_family);
foreach ($employee_data_group_by_family as $emp_id => $family)
{
//if action is DA then get all familiy members,transfrom them into excel array, addd data source as db or excel
if($file['action'] == 'dependent_addition')
{
$existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(emp_code: $emp_id,client_id: $file['client_id'],client_policy_id: $file ['policy_id'],emp_status: ['active'],policy_status:['active'],client_branch_id:[ $file['client_branch_id'] ]);
// dd(($existing_famility_details));
//transsform familiy details from db columns to exxcel row with column indexs for checking remaining functionalitites
$existing_famility_details = transform_db_data_to_excel($existing_famility_details,$file);
// dd(array_keys($existing_famility_details[0]));
$family = array_merge($family,$existing_famility_details);
// kint::dump($family);
$family = data_group_by_family($family)[ $emp_id ];// reason to call this again bring self to first index of the array
}
$firstNonTemp = null;
foreach ($family as $fam) {
if (!isset($fam['temp'])) {
$firstNonTemp = $fam;
break;
}
}
// kint::dump($family);//die();
//check name dup within a family
if($file['action'] == 'inception' || $file['action'] == 'missed_inception' || $file['action'] == 'addition' || $file['action'] == 'dependent_addition' || $file['action'] == 'enrollment')
{
$res = name_dup_check_within_family($family,$file['action']);//in both file data & DB data
// dd($res);
if(count($res))
{
foreach($res as $k => $rowid)
{
array_push($result['error_summary'],7); // dup entry in excel file
$result['error_data'][$rowid]['name_of_emp_dep']['error'][] = "Twofold Name found within family";
}
}
}
if((($file['action'] == 'inception' || $file['action'] == 'missed_inception' || $file['action'] == 'addition' || $file['action'] == 'enrollment') || ($policy_details['policy_type_id'] == 3 && $is_self_available_in_policy_terms)) && ($policy_details['base_policy'] == null || $policy_details['base_policy'] == 0)) // 3 is GMC parents dep addon)
{
$res = check_self_available_in_family($family,$file['action']);
if(!$res['is_self_found'])
{
array_push($result['error_summary'],14); // Self not found
$result['error_data'][ $res['row_id'] ]['sno']['error'][] = "Self not found in uploaded file";
}
}
// check the employee code if dublicate exist
if(($file['action'] == 'inception' || $file['action'] == 'missed_inception' || $file['action'] == 'addition' || $file['action'] == 'enrollment'))
{
$res = check_emp_code_duplication($family, $file);
// dd($res);
if($res['status'])
{
foreach ($res['row_ids'] as $row_id) {
array_push($result['error_summary'],26);
$result['error_data'][ $row_id ]['emp_id']['error'][] = "Employee Code is already exist in the system";
}
}
}
//check self avaialbe either same policy DB level(i.e.) gMC parents
if($file['action'] == 'dependent_addition' || ($policy_details['policy_type_id'] == 3 && !$is_self_available_in_policy_terms)) // 3 is GMC parents as base policy not as dep addon)
{
$self_details = $this->employeeModel->getEmpFamilybyEmpCode(emp_code: trim($emp_id),client_id: $file['client_id'],emp_status: ['active','draft','enrolled'],policy_status:['active','draft','enrolled'],client_branch_id:[ $file['client_branch_id'] ],relationship:['self']);
// dd($self_details);
if(!count($self_details))
{
array_push($result['error_summary'],14); // Self not found
$result['error_data'][ $firstNonTemp[0] ]['sno']['error'][] = "Self not found in Database";
}
}
if($file['action'] == 'dependent_addition' || $file['action'] == 'addition' || $file['action'] == 'inception'|| $file['action'] == 'missed_inception' || $file['action'] == 'enrollment')
{
$res = check_dependent_conflict($family,$policy_terms,$file['action'],$is_lgbtq);
// Kint::dump($res);
if(!$res['status'])
{
foreach($res['error_data'] as $key => $value)
{
array_push($result['error_summary'],$value['code']);
$result['error_data'][ $value['row_id'] ][($value['col_name'])]['error'][] = $value['msg'];
}
}
}
//check dup with empid and name with db
$res = name_and_empid_check_in_db($family,$file);
// Kint::dump($res['del']);
// echo '<br/>';
// print_r($res);
if(count($res['del']))
{
foreach($res['del'] as $k => $rowid)
{
array_push($result['error_summary'],10); //record not avail for deletion
$result['error_data'][$rowid]['name_of_emp_dep']['error'][] = "Record Not found ";
}
}
if(count($res['i']))
{
foreach($res['i'] as $k => $rowid)
{
array_push($result['error_summary'],9); //dup entry
$result['error_data'][$rowid]['name_of_emp_dep']['error'][] = "Record already exists";
}
}
}// end of foreach
}// end of if current action I,DA,A
// return $result;
// die();
if(isset($result['error_summary']) && count($result['error_summary']))
{
$result['error_summary'] = array_count_values($result['error_summary']);
$status = 'failed';
$failure_reason = ((json_encode($result)));
$this->fileModel->where('id', $file_id)->set(['status' => $status,'reason' => $failure_reason])->update();
$this->myLogger->logme("error",'{file_id} uploaded failed',['file_id' => $file_id]);
//set failure msg to pull notifications
$this->setPullNotification($this->getFileMetaDataByFileId($file_id,'failure'));
}
else if($file['action'] == 'deletion')
{
//proceed next data level validation in JOB queue
$job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'employeeDisembark','payload' => ['file_id' => $file_id]]);
}
else if ($file['action'] == 'si_enhancement')
{
//proceed next data level validation in JOB queue
$job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'employeesSIEnhanceProcess','payload' => ['file_id' => $file_id]]);
}
else if ($file['action'] == 'correction')
{
//proceed next data level validation in JOB queue
$job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'employeesCorrectionProcess','payload' => ['file_id' => $file_id, 'batch_file_id' => $batch_file_id]]);
}
else if ($file['action'] == 'inception' || $file['action'] == 'missed_inception' || $file['action'] == 'addition' || $file['action'] == 'dependent_addition')//inception OR addition OR dependent addition
{
//proceed next data level validation in JOB queue
// $job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'employeesOnboardPreprocess','payload' => ['file_id' => $file_id, 'batch_file_id' => $batch_file_id]]);
// $jobWorker = new JobWorker();
// JobWorker::processJob($r);
}
else if($file['action'] == 'enrollment' && $file['uploaded_by'] == 1)// enrollment uploaded by nhance user not by hr
{
$r = Jobs::addJob(['job_name' => 'employeesEnrollmentInsert','payload' => ['file_id' => $file_id]]);
}
return $result;
}
// calculate data points and premium
public function employeesOnboardPreprocess($params)
{
helper('excel_util_helper');
// dd($params);
if (isset($params['file_id'])) //handle data from excel to inception
{
//get file name
$file_id = $params['file_id'];
$file = $this->fileModel->find((int)$file_id);
// dd($file);
$return = [];
if (!isset($file)) {
//file not found in DB
return array('status' => false, 'msg' => 'file not found in DB');
}
$file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name'];
//check physical file
if (!file_exists($file_name_with_path)) {
//file not found update status and reason
$message = "Physical file not found";
// echo $message;
$this->myLogger->logme('error', ($message . ' for file id ' . $file_id));
$this->fileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
return array('error_summary' => [5], 'error_data' => $message);
}
$columns_to_check = [];
if ($file['action'] == 'inception') {
$columns_to_check = $this->inception_excel_columns;
}
if ($file['action'] == 'addition') {
$columns_to_check = $this->inception_excel_columns;
}
if ($file['action'] == 'dependent_addition') {
$columns_to_check = $this->inception_excel_columns;
}
if ($file['action'] == 'deletion') {
$columns_to_check = $this->deletion_excel_columns;
}
if ($file['action'] == 'correction') {
$columns_to_check = $this->correction_excel_columns;
}
if ($file['action'] == 'si_enhancement') {
$columns_to_check = $this->si_enhance_excel_columns;
}
if ($file['action'] == 'missed_inception') {
$columns_to_check = $this->inception_excel_columns;
}
$current_column_action = null;
if ($file['action'] == 'inception') {
$current_column_action = 'I';
} else if ($file['action'] == 'addition') {
$current_column_action = 'A';
} else if ($file['action'] == 'dependent_addition') {
$current_column_action = 'DA';
} else if ($file['action'] == 'deletion') {
$current_column_action = 'D';
} else if ($file['action'] == 'correction') {
$current_column_action = 'C';
} else if ($file['action'] == 'si_enhancement') {
$current_column_action = 'SI';
} else if ($file['action'] == 'enrollment') {
$current_column_action = 'I';
} else if ($file['action'] == 'missed_inception') {
$current_column_action = 'MI';
}
// get policy and rack details
$policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'], $file['policy_id']);
$policy_terms = (array) $policy_terms[0]; // convert obj to array
// $policy_terms = json_decode($policy_terms[0]->policy_terms);
// dd($policy_terms);
//get excel data
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
$sheet = $spreadsheet->getActiveSheet();
$highestRowAndColumn = $sheet->getHighestRowAndColumn();
$allowedHighestColumn = end($columns_to_check);
// dd($allowedHighestColumn);
$excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']);
unset($excel_data[0]);
// dd($excel_data);
//get policy slab rates
$slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($file['policy_id'], $file['client_id']);
// dd($slab_details);
//get existing units in the current branch
$existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $file['client_id'], client_branch_id: $file['client_branch_id']);
$employee_data_group_by_family = data_group_by_family($excel_data, 'excel', '', $current_column_action);
// dd($employee_data_group_by_family);
$employee_insert_count = 0;
foreach ($employee_data_group_by_family as $emp_id => $family) {
//if action is DA then get all familiy members,transfrom them into excel array, addd data source as db or excel
if ($file['action'] == 'dependent_addition') {
$existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(emp_code: $emp_id, client_id: $file['client_id'], client_policy_id: $file['policy_id'], emp_status: ['active'], policy_status: ['active'], client_branch_id: [$file['client_branch_id']]);
// dd($existing_famility_details);
//transsform familiy details from db columns to exxcel row with column indexs for checking remaining functionalitites
$existing_famility_details = transform_db_data_to_excel($existing_famility_details, $file);
// Kint::dump($existing_famility_details);
$family = array_merge($family, $existing_famility_details);
$family = data_group_by_family($family, 'excel', 1)[$emp_id]; // reason to call this again is bring self to first index of the array
// dd($family);
$self = current(array_filter($family, fn($r) => strtolower($r[5] ?? '') === 'self'));
$premium = (int)($self['temp']['rata_premimum'] ?? 0);
foreach ($family as &$r) if (strtolower($r[5] ?? '') !== 'self') $r['self_rata_premium'] = $premium;
}
// Kint::dump($family);
$data = calculate_premium_new(family_data: $family, policy_terms: $policy_terms, slab_details: $slab_details, fileArr: $file, existing_units: $existing_units);
// dd($data);
$employee_data_group_by_family[$emp_id] = $data;
// $res = $this->employeesOnboardProcess(['familiy_data' => $data, 'file' => $file]);
// if ($res > 0) {
// $employee_insert_count++;
// }
}
if ($employee_insert_count > 0) {
$this->fileModel->where('id', $file_id)->set(['status' => 'success', 'reason' => ''])->update();
$this->myLogger->logme("error", '{file_id} uploaded success', ['file_id' => $file_id]);
} else {
$reason = json_encode([
'error_summary' => [5 => 1],
'error_data' => "Rack rate configuration issue: Please check the slab rates configuration"
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$this->fileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => $reason])->update();
$this->myLogger->logme("error", '{file_id} uploaded failed with reason: Rack rate configuration issue: Please check the slab rates configuration', ['file_id' => $file_id]);
}
// $this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'success'));
} else if (isset($params['client_policy_id'])) //handle data from enrollment to inception
{
$client_policy_id = $params['client_policy_id'];
//get client id
$client_id = ($this->clientPolicyModel->select('client_id')->find((int)$client_policy_id))['client_id'];
// dd($client_id);
// get policy and rack details
$policy_terms = $this->clientPolicyModel->getPolicyDetails($client_id, $client_policy_id);
$policy_terms = (array) $policy_terms[0]; // convert obj to array
//get policy slab rates
$slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($client_policy_id, $client_id);
$existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(client_id: $client_id, client_policy_id: $client_policy_id, emp_status: ['enrolled'], policy_status: ['enrolled']);
// $file = ['id' => null,'client_id' => $client_id,'policy_id' => $client_policy_id,'action' => 'inception'];
$file = ['id' => null, 'client_id' => $client_id, 'policy_id' => $client_policy_id, 'action' => 'inception', 'created_by' => get_session_userid(), 'client_branch_id' => $params['client_branch_id']];
//get existing units in the current branch
$existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $file['client_id'], client_branch_id: $file['client_branch_id']);
// dd($this->employeeModel->getLastQuery());
// Kint::dump($existing_famility_details);die();
$employee_data_group_by_family = data_group_by_family($existing_famility_details, $data_source = 'db');
// dd($employee_data_group_by_family);
foreach ($employee_data_group_by_family as $emp_id => $family) {
$transformed_famility_details = transform_db_data_to_excel($family);
// $data = calculate_premium_new($transformed_famility_details,$policy_terms,$slab_details,$file);
$data = calculate_premium_new(family_data: $transformed_famility_details, policy_terms: $policy_terms, slab_details: $slab_details, fileArr: $file, existing_units: $existing_units);
// dd($data);
$employee_data_group_by_family[$emp_id] = $data;
$this->employeesOnboardProcess(['familiy_data' => $data, 'file' => $file]);
}
// dd($employee_data_group_by_family);
}
if(count($employee_data_group_by_family ?? []) && isset($params['batch_file_id'])){
$r = Jobs::addJob(['job_name' => 'updateEmployeeDataFromTpa','payload' => ['file_id' => $file_id, 'batch_file_id' => $params['batch_file_id']]]);
$this->myLogger->logme("info", 'Batch file id {batch_file_id} processed successfully', ['batch_file_id' => $params['batch_file_id']]);
}
// die();
return (count($employee_data_group_by_family));
}
//deletion of emp
public function employeeDisembark($params)
{
helper('excel_util_helper');
//get file name
$file_id = $params['file_id'];
$file = $this->fileModel->find((int)$file_id);
// dd($file);
$file_name_with_path = WRITEPATH."/uploads/excel/".$file['file_name'];
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
$sheet = $spreadsheet->getActiveSheet();
$highestRowAndColumn = $sheet->getHighestRowAndColumn();
$allowedHighestColumn = end($this->deletion_excel_columns);
$excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']);
// $excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
// dd($excel_data);
unset($excel_data[0]);
// kint::dump($excel_data);
$endorsement_data = [];
$policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'],$file['policy_id']);
$insurer = new InsurerModel();
$insurer = ($insurer->find((int)$policy_terms[0]->insurer_id));
// kint::dump($insurer);
//make closure funciton which is going to use only by this method
$endorsement = function($data,$file,$row) use ($insurer){
$group_key = rand(100000, 999999);
$row[4] = change_date_format($row[4],'d-M-Y','Y-m-d');// date of exit from excel
// Kint::dump($row[4]);
// check if insurer configured with add one day for deletion
// if($insurer['deletion_add_day'] == true)
// {
// $row[4] = (new \DateTime($row[4]))->modify('+1 day')->format('Y-m-d');
// }
// dd($row[4]);
//for emp table
// $this->empEndorsementModel->save(['pk' => (int)$data['emp_id'],'emp_code' => $data['emp_code'],'table_name' => 'employees','actions' => 'd','name' => $data['name'],'field_name' => 'emp_status','old_value' => $data['emp_status'],'new_value' => 'deactivate','created_by' => $file['created_by'],'remarks' => 'general deletion','group_key' => $group_key,'file_id' => $file['id'],'status' => 'pending']);
// dd( $this->empEndorsementModel->getLastQuery());
// $this->empEndorsementModel->save(['pk' => (int)$data['emp_id'],'emp_code' => $data['emp_code'],'table_name' => 'employees','actions' => 'd','name' => $data['name'],'field_name' => 'change_event','old_value' => $data['change_event'],'new_value' => 'deletion','created_by' => $file['created_by'],'remarks' => 'general deletion']);
// for employee policy table
$this->empEndorsementModel->save(['pk' => (int)$data['emp_policy_id'],'emp_code' => $data['emp_code'],'table_name' => 'employee_polices','actions' => 'd','name' => $data['name'],'field_name' => 'date_of_exit','old_value' => $data['date_of_exit'],'new_value' => $row[4],'created_by' => $file['created_by'],'remarks' => 'general deletion','group_key' => $group_key,'file_id' => $file['id'],'status' => 'pending']);
$this->empEndorsementModel->save(['pk' => (int)$data['emp_policy_id'],'emp_code' => $data['emp_code'],'table_name' => 'employee_polices','actions' => 'd','name' => $data['name'],'field_name' => 'reason_for_exit','old_value' => $data['reason_for_exit'],'new_value' => $row[5],'created_by' => $file['created_by'],'remarks' => 'general deletion','group_key' => $group_key,'file_id' => $file['id'],'status' => 'pending']);
$this->empEndorsementModel->save(['pk' => (int)$data['emp_policy_id'],'emp_code' => $data['emp_code'],'table_name' => 'employee_polices','actions' => 'd','name' => $data['name'],'field_name' => 'status','old_value' => $data['status'],'new_value' => 'inactive','created_by' => $file['created_by'],'remarks' => 'general deletion','group_key' => $group_key,'file_id' => $file['id'],'status' => 'pending']);
$this->empEndorsementModel->save(['pk' => (int)$data['emp_policy_id'],'emp_code' => $data['emp_code'],'table_name' => 'employee_polices','actions' => 'd','name' => $data['name'],'field_name' => 'claim_status','old_value' => $data['claim_status'],'new_value' => $row[6],'created_by' => $file['created_by'],'remarks' => 'general deletion','group_key' => $group_key,'file_id' => $file['id'],'status' => 'pending']);
};
//iterate each row
foreach ($excel_data as $col_key => $row)
{
if(check_row_is_empty_or_null($row))
{
break;
}
// echo '<br>START- ' . $row[2];
$employee = $this->employeeModel
->select('employees.*, employee_polices.id as emp_policy_pk')
->join('employee_polices', 'employees.id = employee_polices.employee_id')
->where('employees.emp_code', $row[1])
->where('employees.name',$row[2])
->where('employees.client_id',$file['client_id'])
->where('employees.client_branch_id',$file['client_branch_id'])
->where('employee_polices.client_policy_id',$file['policy_id'])
->where('employees.emp_status','active')
->where('employees.is_active', 1)
->where('employee_polices.status','active')
->where('employee_polices.is_active', 1)
->first();
// $employee = $this->employeeModel->where('emp_code', $row[1])->where('name',$row[2])->where('client_id',$file['client_id'])->first();
// dd($employee);
// kint::dump($employee);
if(is_array($employee) && count($employee))
{
// dd($employee);
$existing_endorsements = $this->empEndorsementModel->where('actions','d')
->where('table_name','employee_polices')
->where('endorsement_id is null')
->where('emp_code',$employee['emp_code'])
->where('name',$employee['name'])
->where('pk',$employee['emp_policy_pk'])
->where('field_name','status')
->where('status !=','truncated')
->where('is_active', 1)
->findAll();
// dd($existing_endorsements);
if(!count($existing_endorsements))
{
// dd($employee);
if(strtolower($employee['relationship']) != 'self')
{
if(!in_array($employee['id'],$endorsement_data))//make entry in endorsement firsttime only with checking that PK of emp exisintg in variable $endorsement_data
{
$employee_policy = $this->employeePolicyModel
->where('employee_id',$employee['id'])
->where('client_policy_id',$file['policy_id'])
->where('status','active')
->where('is_active', 1)
->first();
$data = ['emp_id' => $employee['id'],'name' => $employee['name'],'emp_status' => $employee['emp_status'],'emp_policy_id' => $employee_policy['id'],'emp_code' => $employee['emp_code'],'change_event' => $employee['change_event'],'date_of_exit' => $employee_policy['date_of_exit'],'reason_for_exit' => $employee_policy['reason_for_exit'],'status' => $employee_policy['status'],'claim_status' => $employee_policy['claim_status']];
$endorsement($data,$file,$row);
$endorsement_data[] = $employee['id'];
}
}
else
{
$family = $this->employeeModel->getEmpFamilybyEmpCode(emp_code: $row[1],client_id: $file['client_id'],client_policy_id: $file ['policy_id'],emp_status: ['active'],policy_status: ['active']);
// Kint::dump($family);
foreach ($family as $key => $emp) {
if(!in_array($emp['emp_id'],$endorsement_data))
{
$endorsement($emp,$file,$row);
$endorsement_data[] = $emp['emp_id'];
}
}
}
}else{
$this->myLogger->logme("error",'Existing endorsement pending for this employee : emp_code : {emp_code} - emp_name : {name}',['emp_code' => $row[1],'name' => $row[2]]);
}
}
else
{
$this->myLogger->logme("error",'{emp_code} - {name} not found',['emp_code' => $row[1],'name' => $row[2]]);
}
// print_r($endorsement_data);
}
$this->fileModel->where('id', $file_id)->set(['status' => 'success','reason' => ''])->update();
$this->myLogger->logme("error",'{file_id} uploaded success',['file_id' => $file_id]);
//set success msg to pull notifications
$this->setPullNotification($this->getFileMetaDataByFileId($file_id,'success'));
return $endorsement_data;
}
//correction of emp
public function employeesCorrectionProcess($params)
{
helper('excel_util_helper');
//get file name
$file_id = $params['file_id'];
$batch_file_id = $params['batch_file_id'] ?? null;
$file = $this->fileModel->find((int)$file_id);
// dd($file);
$file_name_with_path = WRITEPATH."/uploads/excel/".$file['file_name'];
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
$sheet = $spreadsheet->getActiveSheet();
$highestRowAndColumn = $sheet->getHighestRowAndColumn();
$allowedHighestColumn = end($this->correction_excel_columns);
$excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']);
// $excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
unset($excel_data[0]);
// dd($excel_data);
//iterate each row
foreach ($excel_data as $col_key => $row)
{
if(check_row_is_empty_or_null($row))
{
break;
}
// echo '<br>START- ' . $row[2];
$field_name = $row[3];
$field_value = ($field_name == 'dob' ? change_date_format($row[4],'d-M-Y','Y-m-d') : $row[4] );
$employee = $this->employeeModel
->select('employees.*')
->join('employee_polices', 'employees.id = employee_polices.employee_id')
->where('employees.emp_code', $row[1])
->where('employees.name',$row[2])
->where('employees.client_id',$file['client_id'])
->where('employees.client_branch_id',$file['client_branch_id'])
->where('employee_polices.client_policy_id',$file['policy_id'])
->where('employees.emp_status','active')
->where('employees.is_active',1)
->where('employee_polices.status','active')
->where('employee_polices.is_active',1)
->first();
// Kint::dump($employee);
$existing_endorsements = $this->empEndorsementModel->where('actions','c')
->where('table_name','employees')
->where('endorsement_id is null')
->where('emp_code',$employee['emp_code'])
->where('name',$employee['name'])
->where('field_name',$field_name)
->where('is_active',1)
->where('status !=','truncated')
->findAll();
// dd($existing_endorsements);
//make entry in endorsement table
if(!count($existing_endorsements))
{
$group_key = rand(100000, 999999);
$this->empEndorsementModel->save(['pk' => (int)$employee['id'],'emp_code' => $employee['emp_code'],'table_name' => 'employees','actions' => 'c','name' => $employee['name'],'field_name' => $field_name,'old_value' => $employee[ $field_name ],'new_value' => $field_value,'created_by' => $file['created_by'],'remarks' => $row[7],'date_of_correction' => change_date_format($row[5],'d-M-Y','Y-m-d'),'group_key' => $group_key,'file_id' => $file['id'],'status' => 'pending']);
}
}
if(!empty($batch_file_id)){
$r = Jobs::addJob(['job_name' => 'updateEmployeeDataFromTpa','payload' => ['file_id' => $file_id, 'batch_file_id' => $batch_file_id]]);
$this->myLogger->logme("error", 'Batch file id {batch_file_id} processed successfully', ['batch_file_id' => $batch_file_id]);
}
$this->fileModel->where('id', $file_id)->set(['status' => 'success','reason' => ''])->update();
$this->myLogger->logme("error",'{file_id} uploaded success',['file_id' => $file_id]);
//set success msg to pull notifications
$this->setPullNotification($this->getFileMetaDataByFileId($file_id,'success'));
return true;
}
//enhance of emp
public function employeesSIEnhanceProcess($params)
{
helper('excel_util_helper');
//get file name
$file_id = $params['file_id'];
$file = $this->fileModel->find((int)$file_id);
// dd($file);
$file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name'];
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
$sheet = $spreadsheet->getActiveSheet();
$highestRowAndColumn = $sheet->getHighestRowAndColumn();
$allowedHighestColumn = end($this->si_enhance_excel_columns);
$excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']);
// $excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
unset($excel_data[0]);
// dd($excel_data);
//get policy slab rates
$slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($file['policy_id'], $file['client_id']);
//iterate each row
// dd($slab_details);
foreach ($excel_data as $col_key => $row) {
if (check_row_is_empty_or_null($row)) {
break;
}
$row[3] = removeNumberFormatting($row[3]);
// echo '<br>START- ' . $row[2];
$employee = $this->employeeModel
->where('emp_code', $row[1])
->where('name', $row[2])
->where('client_id', $file['client_id'])
->where('client_branch_id', $file['client_branch_id'])
->where('emp_status', 'active')
->where('is_active', 1)
->first();
$employee_policy = $this->employeePolicyModel
->where('employee_id', $employee['id'])
->where('client_policy_id', $file['policy_id'])
->where('status', 'active')
->where('is_active', 1)
->first();
// dd($employee, $employee_policy);
$existing_endorsements = $this->empEndorsementModel->where('actions', 'si')
->where('table_name', 'employee_polices')
->where('endorsement_id is null')
->where('emp_code', $employee['emp_code'])
->where('name', $employee['name'])
->where('field_name', 'basic_cover_si')
->where('is_active', 1)
->where('status !=', 'truncated')
->findAll();
// dd($existing_endorsements);
//make entry in endorsement table
if (!count($existing_endorsements)) {
//transform data to send
//get applicable slab rate for current member relation
$pre_rack_rate_name = '';
$applicable_rack_rate_name = '';
$applicable_rack_rate_master = [];
foreach ($slab_details['slab_rates'] as $skey => $slab_value) {
if ($pre_rack_rate_name != $slab_value['rack_rate_name']) {
$pre_rack_rate_name = $slab_value['rack_rate_name'];
$rack_rate_json = json_decode($slab_value['additional_relationship'], true);
$relationship_array_key = strtolower(trim($employee['relationship']));
if (in_array($relationship_array_key, ['son', 'daughter'])) {
$relationship_array_key = 'childrens';
} elseif (in_array($relationship_array_key, ['father', 'mother'])) {
$relationship_array_key = 'parents';
} elseif (in_array($relationship_array_key, ['father in law', 'mother in law', 'father-in-law', 'mother-in-law'])) {
$relationship_array_key = 'parents-in-law';
}
if (array_key_exists($relationship_array_key, $rack_rate_json) && $rack_rate_json[$relationship_array_key] != 0 && $rack_rate_json[$relationship_array_key] != 'NA') {
$applicable_rack_rate_name = $slab_value['rack_rate_name'];
$applicable_rack_rate_master = $slab_value['grid_master'];
break;
}
}
}
//get max age,max count of the familiy
$max_age_and_max_count_of_current_member = $this->employeeModel->getFamiliyCountAndMaxage($employee['emp_code']);
//transform SI excel row data as inception excel OR premium calculateable fomart
$data = transform_si_excel_row_to_calculatable_format(employee: $employee, employee_policy: $employee_policy, maxage_and_maxcount: $max_age_and_max_count_of_current_member, slab_details: $slab_details, applicable_slab_name: $applicable_rack_rate_name, augmented_si: $row[3], grid_master: $applicable_rack_rate_master);
$policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'], $file['policy_id']);
$policy_terms = (array) $policy_terms[0];
// dd($policy_terms);
//grouping slab details by rack rate name
$temp_slab_rates = group_slab_rates_basedon_name($slab_details);
$calculated_data = premium_calculation_manager($data, $policy_terms, $temp_slab_rates, $row[3]);
$group_key = rand(100000, 999999);
$this->empEndorsementModel->save(['pk' => (int)$employee_policy['id'], 'emp_code' => $employee['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'si', 'name' => $employee['name'], 'field_name' => 'basic_cover_si', 'old_value' => $employee_policy['basic_cover_si'], 'new_value' => $row[3], 'created_by' => $file['created_by'], 'remarks' => 'general si enhancement', 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']);
$this->empEndorsementModel->save(['pk' => (int)$employee_policy['id'], 'emp_code' => $employee['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'si', 'name' => $employee['name'], 'field_name' => 'premium', 'old_value' => $employee_policy['premium'], 'new_value' => $calculated_data['policy_details']['premium'], 'created_by' => $file['created_by'], 'remarks' => 'general si enhancement', 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']);
$this->empEndorsementModel->save(['pk' => (int)$employee_policy['id'], 'emp_code' => $employee['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'si', 'name' => $employee['name'], 'field_name' => 'si_enhancement_date', 'old_value' => null, 'new_value' => change_date_format($row[4], 'd-M-Y', 'Y-m-d'), 'created_by' => $file['created_by'], 'remarks' => 'general si enhancement', 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']);
} else {
$this->myLogger->logme("error", 'Endorsement already exists for this employee ' . json_encode(['file_id' => $file_id, 'emp_code' => $employee['emp_code'], 'emp_name' => $employee['name']]));
}
}
$this->fileModel->where('id', $file_id)->set(['status' => 'success', 'reason' => ''])->update();
$this->myLogger->logme("error", '{file_id} uploaded success', ['file_id' => $file_id]);
//set success msg to pull notifications
$this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'success'));
return true;
}
// insert or update in db for inception addition depent addition
public function employeesOnboardProcess($params)
{
// dd($params);
$familiy_data = $params['familiy_data'];
$file = $params['file'];
$policy_details = $this->clientPolicyModel->where('id', $file['policy_id'])->first();
// dd($policy_details);
$employee_insert_count = 0;
foreach($familiy_data as $fkey => $value)
{
if(is_array($value))
{
if (isset($value['gender'])) { $value['gender'] = normalizeGender($value['gender'] );}
if($file['id'] == null || $value['temp']['source'] == 'excel' || (($file['action'] == 'dependent_addition' && ($value['temp']['premium_type'] == 1 && strtolower($value['relationship']) == 'self') || ($value['temp']['premium_type'] == 2 || $value['temp']['premium_type'] == null)))) //insert data come from excel and from db i.e. ( $file['id'] == null for enrollment data)
{
$employee = $this->employeeModel->checkExistingEmp($value,$file['client_branch_id']);
$policy_data = $value['policy_details'];
$temp = $value['temp'];
unset($value['policy_details']);
unset($value['temp']);
// Kint::dump($value);
// Kint::dump($temp);
// Kint::dump($policy_data);
// echo '---------------------------------------';
//start implemet of si enhancement of grid type 10,11
if(count($employee) && $file['action'] == 'dependent_addition' && $temp['source'] == 'db' && in_array($temp['grid_id'],[10,11]) && ( ($temp['premium_type'] == 1 && (strtolower($value['relationship']) == 'self' || $temp['acting_self'])) || ($temp['premium_type'] == 2 || $temp['premium_type'] == null)))
{
$log_message = 'Employee record from DB,Checking SI for - '.$employee[0]['name'].'('.$employee[0]['emp_code'].')';
$this->myLogger->logme('error',$log_message);
$res = $this->employeesSIEnhanceProcessWhileOnbboard(employee:$employee[0],policy_data: $policy_data,file:$file);// where employee holds existing emp data and policy_data holds new si enhancement
break;//skip db employee
}
//end implemet of si enhancement of grid type
//save employee table
$value['relationship'] = ucfirst(trim($value['relationship']));
if(count($employee))
{
if (isset($employee[0]['email_corporate']) && $employee[0]['email_corporate'] != '')
{
unset($value['email_corporate']);
}
if (isset($employee[0]['mobile']) && $employee[0]['mobile'] != '')
{
unset($value['mobile']);
}
$value['updated_by'] = $file['created_by'];
$value['id'] = $employee[0]['id'];
$value['emp_status'] = 'active';
$value['family_floater_key'] = generate_family_floater_key($value['relationship']);
$value['client_branch_id'] = $file['client_branch_id'];
$value['file_id'] = isset($employee[0]['file_id']) && $employee[0]['file_id'] != '' ? $employee[0]['file_id'] : $file['id'] ;
$log_message = 'Update Employee - '.$employee[0]['name'].'('.$employee[0]['emp_code'].') with PK '.$employee[0]['id'];
// $this->myLogger->logme('error',('Update - ' . $employee[0]['id'].' - '. $employee[0]['emp_code'] .' - '.$employee[0]['name']));
// echo 'insert emp';
}
else
{
$value['emp_status'] = 'active';
$value['created_by'] = $file['created_by'];
$value['client_branch_id'] = $file['client_branch_id'];
$value['family_floater_key'] = generate_family_floater_key($value['relationship']);
$value['file_id'] = isset($employee[0]['file_id']) && $employee[0]['file_id'] != '' ? $employee[0]['file_id'] : $file['id'] ;
$log_message = 'Insert Employee- '.$value['name'] .'('.$value['emp_code'] .') with PK ';
// $this->myLogger->logme('error',('Insert - ' . $value['emp_code'] .' - '. $value['name']));
// echo 'update emp';
}
$value = ExcelSanitizeHelper::sanitizeArrayData($value);
$this->employeeModel->save($value);
if (isset($value['id'])) {
$emp_id = $value['id'];
} else {
$emp_id = $this->employeeModel->getInsertID();
$log_message .= $emp_id;
}
//commanded for last insert id is coming from buffer
// $emp_id = $this->employeeModel->getInsertID();
// if($emp_id != 0){ $log_message .= $emp_id; }
// else{ $emp_id = $employee[0]['id']; }
$this->myLogger->logme('error',$log_message);
//save policy table
$employee_policy = $this->employeePolicyModel->checkExistingEmpPolicy(['employee_id' => $emp_id,'client_policy_id' => $file['policy_id']]);
if(count($employee_policy))
{
$policy_data['updated_by'] = $file['created_by'];
$policy_data['id'] = $employee_policy[0]['id'];
$policy_data['status'] = 'active';
$policy_data['payable_employee'] = check_pay_by_employee_or_company($policy_details['policy_terms'], $value['relationship']);
$policy_data['file_id'] = isset($employee_policy[0]['file_id']) && $employee_policy[0]['file_id'] != '' ? $employee_policy[0]['file_id'] : $file['id'] ;
$log_message = 'Update Employee Policy for '. $value['name'].'('. $value['emp_code'].') with PK- ' . $employee_policy[0]['id'] .' client policy ID '.$employee_policy[0]['client_policy_id'].' with SI '.$policy_data['basic_cover_si'];
// echo 'insert policy';
}
else
{
$policy_data['employee_id'] = $emp_id;
$policy_data['client_policy_id'] = $file['policy_id'];
$policy_data['created_by'] = $file['created_by'];
$policy_data['status'] = 'active';
$policy_data['payable_employee'] = check_pay_by_employee_or_company($policy_details['policy_terms'], $value['relationship']);
$policy_data['file_id'] = $file['id'];
$log_message = 'Insert Employee Policy for '. $value['name'].'('. $value['emp_code'].') - client policy id -'. $file['policy_id'].' - with SI '.$policy_data['basic_cover_si'];
// echo 'update policy';
}
// log_message('error',json_encode($policy_data));
// dd($this->employeePolicyModel->save($policy_data));
$res = $this->employeePolicyModel->save($policy_data);
// if($res){log_message('error','ths the resul'.$res);}
if(isset($policy_data['id']))
{
$emp_policy_id = $policy_data['id'];
}else
{
$emp_policy_id = $this->employeePolicyModel->getInsertID();
}
if($emp_policy_id != 0)//emp policy inserted
{
$log_message .= ' with PK ' . $emp_policy_id;
//make endorsement entry if action is addition OR Dependt addition
if(($file['action'] == 'missed_inception' || $file['action'] == 'dependent_addition' || $file['action'] == 'addition') && $temp['source'] == 'excel')
{
$log_message = $file['action'].' - endorsement'. $value['emp_code'].' - '.$value['name'].' - with policy id'.$emp_policy_id;
$this->myLogger->logme('error',$log_message);
$actions = ($file['action'] == 'dependent_addition' ? 'da' : ($file['action'] == 'addition' ? 'a' : 'a'));
$addition_endorse_data = ['pk' => $emp_policy_id,'group_key' => rand(100000, 999999),'emp_code' => $value['emp_code'],'table_name' => 'employee_polices','actions' => $actions,'name' => $value['name'],'field_name' => 'basic_cover_si','old_value' => NULL,'new_value' => $policy_data['basic_cover_si'],'remarks' => 'addition endorsement','file_id' => $file['id'],'created_by' => $file['created_by'],'status' => 'pending'];
$this->employeeEndorsementforAddtionAndDependentAddition($addition_endorse_data);
}
}
// else{ $emp_policy_id = $employee_policy[0]['id']; }
$this->myLogger->logme('error',$log_message);
$employee_insert_count++;
}// if end
}// is array check end
else
{
$this->myLogger->logme('error','######Incoming value is not an array');
}
}// for end
return $employee_insert_count;
}//function end
public function employeeEndorsementforAddtionAndDependentAddition($employee)
{
$this->empEndorsementModel->save($employee);
}
// $employee -> holds existing emp model obj and $policy_data holds new policy changes as array
public function employeesSIEnhanceProcessWhileOnbboard(array $employee,array $policy_data,array $file)
{
$employee = $this->employeeModel->where('emp_code', $employee['emp_code'])->where('name',$employee['name'])->where('client_id',$employee['client_id'])->where('client_branch_id',$file['client_branch_id'])->where('is_active',1)->first();
// Kint::dump($this->employeeModel->getLastQuery());
// dd($employee);
$employee_policy = $this->employeePolicyModel->where('employee_id',$employee['id'])->where('client_policy_id',$file['policy_id'])->first();
// dd($employee_policy);
// $slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($employee_policy['client_policy_id'],$employee['client_id']);
// dd($slab_details);
// $temp_slab_details = ($temp['grid_type'] == 'primary' ? $slab_details['slab_rates'] : $slab_details['additional_slab_info']['slab_rates']);
//check si has changed in normal case OR check premium only changed, still treat as SI enhancement in grid type 10
if($employee_policy['basic_cover_si'] != $policy_data['basic_cover_si'] || ($policy_data['premium'] != null && $policy_data['premium'] != "" && $employee_policy['premium'] != $policy_data['premium']))
{
$existing_endorsements = $this->empEndorsementModel->where('actions','si')
->where('table_name','employee_polices')
->where('endorsement_id is null')
->where('emp_code',$employee['emp_code'])
->where('name',$employee['name'])
->where('field_name','basic_cover_si')
->findAll();
//make entry in endorsement table
if(!count($existing_endorsements))
{
$group_key = rand(100000, 999999);
$data = array(
['pk' => (int)$employee_policy['id'],'emp_code' => $employee['emp_code'],'table_name' => 'employee_polices','actions' => 'si','name' => $employee['name'],'field_name' => 'basic_cover_si','old_value' => $employee_policy['basic_cover_si'],'new_value' => $policy_data['basic_cover_si'],'created_by' => $file['created_by'],'remarks' => 'general si enhancement via DA','group_key' => $group_key,'file_id' => $file['id']],
['pk' => (int)$employee_policy['id'],'emp_code' => $employee['emp_code'],'table_name' => 'employee_polices','actions' => 'si','name' => $employee['name'],'field_name' => 'premium','old_value' => $employee_policy['premium'],'new_value' => $policy_data['premium'],'created_by' => $file['created_by'],'remarks' => 'general si enhancement via DA','group_key' => $group_key,'file_id' => $file['id']],
['pk' => (int)$employee_policy['id'],'emp_code' => $employee['emp_code'],'table_name' => 'employee_polices','actions' => 'si','name' => $employee['name'],'field_name' => 'si_enhancement_date','old_value' => null,'new_value' => date('Y-m-d'),'created_by' => $file['created_by'],'remarks' => 'general si enhancement via DA','group_key' => $group_key,'file_id' => $file['id']]
);
$this->empEndorsementModel->insertBatch($data);
$this->myLogger->logme('error',($employee['emp_code'].' - '.$employee['name'].'- ( NEW/OLD SI - '.$employee_policy['basic_cover_si'].'/'.$policy_data['basic_cover_si'].')'. '( NEW/OLD PREMIUM - '.$employee_policy['premium'].'/'.$policy_data['premium'].') '.' - si enhancement via DA'));
$log_message = 'SI enhancement done during dependent_addition - '.$employee['name'].'('.$employee['emp_code'].')';
$this->myLogger->logme('error',$log_message);
return true; //retun true when endorsement inserted
}
return false; //retun false when endorsement not happend
}
return false; //retun false when endorsement not happend
}
// ---------------------------------------------------------------------------------
public function getExcelErrorData($file_id)
{
try {
$file = $this->fileModel->find((int)$file_id);
$error_data = json_decode($file['reason']);
// dd($error_data);
// return $error_data;
$file_name_with_path = WRITEPATH."/uploads/excel/".$file['file_name'];
//check the file exist or not
if(!file_exists($file_name_with_path))
{
$error_message = "File not found";
$this->myLogger->logme('error',($error_message . ' for file id ' . $file_id));
return 0;
}
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
$sheet = $spreadsheet->getActiveSheet();
$highestRowAndColumn = $sheet->getHighestRowAndColumn();
$excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
$excelErrorData['excel_header'] = $excel_data[0];
unset($excel_data[0]);
// echo '<pre>';
// Kint::dump($excel_data);
if($error_data->error_type == 1){
$finalArray = [];
foreach ($error_data->error_data as $key => $value) {
foreach ($value as $key2 => $value2) {
$error_data = $value2->error;
$data = ['value' => $excel_data[$key][$value2->col_idx], 'error'=>$error_data,];
$excel_data[$key][$value2->col_idx] = $data;
}
array_push($finalArray, $excel_data[$key]);
}
foreach ($finalArray as $fkey => $value){
foreach ($value as $vkey => $arrayData){
if(!is_array($arrayData)){
$data = ['value' => $arrayData];
$finalArray[$fkey][$vkey] = $data;
}
}
}
$excelErrorData['excel_data'] = $finalArray;
return $excelErrorData;
}else if($error_data->error_type == 2){
$allErrors = [];
$typeTowArray = [];
foreach ($error_data->error_data as $index => $item) {
foreach ($item as $field) {
if (!isset($allErrors[$index])) {
$allErrors[$index] = [];
}
$allErrors[$index] = array_merge($allErrors[$index], $field->error);
}
}
// dd(array_keys($allErrors));
foreach ($allErrors as $key => $value){
// echo $key;
// print_r($value);
foreach($excel_data as $excel_data_index => $excel_data_value)
{
if($excel_data_value[0] == $key)
{
$data = ['value' => $excel_data[$excel_data_index][1], 'error'=>$value,];
$excel_data[$excel_data_index][1] = $data;
array_push($typeTowArray, $excel_data[$excel_data_index]);
break;
}
}
}
// dd($data);
foreach ($typeTowArray as $fkey => $value){
foreach ($value as $vkey => $arrayData){
if(!is_array($arrayData)){
$data = ['value' => $arrayData];
$typeTowArray[$fkey][$vkey] = $data;
}
}
}
$excelErrorData['excel_data'] = $typeTowArray;
return $excelErrorData;
}
}catch (\Exception $e) {
// Handle any exceptions
$errorMessage = $e->getMessage();//die();
$this->myLogger->logme('error', $errorMessage);
return false; // You can return an error response here
}
}
// ---------------------------------------------------------------------------------
public function getFileMetaDataByFileId($file_id, $status = 'success')
{
$data = $this->fileModel
->select('files.*, clients.client_name, clients.short_name, policy_type.policy_type as policy_name,client_branch.branch_code')
->join('clients', 'clients.id = files.client_id')
->join('client_policy', 'client_policy.id = files.policy_id')
->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
->join('client_branch', 'client_branch.id = files.client_branch_id','left')
->where('files.id', $file_id)
->first();
if($status == 'success')
{
$msg_title = 'File Upload Success';
}
else if ($status == 'failure')
{
$msg_title = 'File Upload Failure';
}
$msg_txt = $data['client_name'] . ' ('.$data['branch_code'].') - ' . $data['policy_name'] . ' - ' . ucfirst($data['action']);
$user_id = $data['created_by'];
$url = 'employee/upload';
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);
}
public function employeesEnrollmentInsert($params)
{
// dd($this->request);
helper('excel_util_helper');
//get file name
$file_id = $params['file_id'];
$file = $this->fileModel->find((int)$file_id);
// dd($file);
$return = [];
if(!isset($file))
{
//file not found in DB
return array('status' => false, 'msg' => 'file not found in DB');
}
$file_name_with_path = WRITEPATH."/uploads/excel/".$file['file_name'];
//check physical file
if(!file_exists($file_name_with_path))
{
//file not found update status and reason
$message = "Physical file not found";
// echo $message;
$this->myLogger->logme('error',($message . ' for file id ' . $file_id));
$this->fileModel->where('id', $file_id)->set(['status' => 'failed','reason' => json_encode(['error_summary' => array_count_values([5]),'error_data' => $message])])->update();
return array('error_summary' => [5], 'error_data' => $message);
}
//get excel data
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
$sheet = $spreadsheet->getActiveSheet();
$highestRowAndColumn = $sheet->getHighestRowAndColumn();
$result = ['error_type' => 2,'error_summary' => [], 'error_data' => [] ];
$columns_to_check = $this->enrollment_excel_columns;
$keys = array_keys($columns_to_check);
$allowedHighestColumn = end($columns_to_check);
$excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']);
// print_r($keys);die();
//get existing units in the current branch
$existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $file['client_id'],client_branch_id: $file['client_branch_id']);
//remove header
unset($excel_data[0]);
// dd($excel_data);
$emp_emails = [];
//check is welcome notification enabled
$notification = $this->notificationModel->where('client_id',$file['client_id'])->where('template_name','member_welcome_mail')->first();
// dd($notification);
$client_details = $this->clientModel->where('id', $file['client_id'])->first();
$policy_details = $this->clientPolicyModel->where('id', $file['policy_id'])->first();
// dd($policy_details);
//get policy slab rates
// $slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($file['policy_id'],$file['client_id']);
// dd($slab_details);
foreach ($excel_data as $key => $row)
{
$is_row_empty = check_row_is_empty_or_null($row);
if(!$is_row_empty)
{
$value = [];
$policy_data = [];
$temp_unit = '';
if(empty($row[12]))
{
$temp_unit = $existing_units[0];
}
$value['emp_code'] = $row[1];
$value['name'] = $row[2];
$value['doj'] = (!empty($row[3]) ? change_date_format($row[3],'d-M-Y','Y-m-d') : null );
$value['gender'] = normalizeGender($row[4]);
$value['relationship'] = ucfirst(trim($row[5]));
$value['dob'] = change_date_format($row[6],'d-M-Y','Y-m-d');
$value['email_corporate'] = $row[7];
$value['mobile'] = $row[8];
$value['band'] = $row[10];
$value['basic_pay'] = $row[11];
$value['unit'] = $temp_unit;
$value['family_floater_key'] = null;
$value['client_id'] = $file['client_id'];
$value['client_branch_id'] = $file['client_branch_id'];
$value['file_id'] = $file_id;
$value['is_addon_value'] = $policy_details['policy_type_id'] == 3 ? 1 : 0;
$value['temp']['emp_id'] = null; // dummy value for using exisitng funciton in model
if (strtolower(trim($value['relationship'])) === 'mother' || strtolower(trim($value['relationship'])) === 'father') {
$relation = 'parent';
} else if(strtolower(trim($value['relationship'])) === 'son' || strtolower(trim($value['relationship'])) === 'daughter'){
$relation = 'child';
}else if((strtolower(trim($value['relationship'])) === 'father in law' || strtolower(trim($value['relationship'])) === 'mother in law') || (strtolower(trim($value['relationship'])) === 'father-in-law' || strtolower(trim($value['relationship'])) === 'mother-in-law')){
$relation = 'parent_in_law';
}else if(strtolower(trim($value['relationship'])) === 'spouse'){
$relation = 'spouse';
}else if(strtolower(trim($value['relationship'])) === 'self'){
$relation = 'self';
}else {
$relation = '';
}
$value['family_floater_key'] = $relation;
// dd($value['family_floater_key']);
$policy_data['basic_cover_si'] = $row[9];
$policy_data['date_coverage'] = $row[13] != "" && $row[13] != null ? change_date_format($row[13],'d-M-Y','Y-m-d') : null;
$policy_data['client_policy_id'] = $file['policy_id'];
$employee = $this->employeeModel->checkExistingEmployee($value,$file['client_branch_id']);
unset($value['temp']);
//save employee table
// dd($employee['id']);
if($employee !== null)
{
$value['updated_by'] = $file['created_by'];
$value['id'] = $employee['id'];
$value['emp_status'] = 'draft';
$log_message = 'Enrollment Update Employee - '.$employee['name'].'('.$employee['emp_code'].') with PK '.$employee['id'];
}
else
{
$value['emp_status'] = 'draft';
$value['created_by'] = $file['created_by'];
$log_message = 'Enrollment Insert Employee- '.$value['name'] .'('.$value['emp_code'] .') with PK ';
}
$value = ExcelSanitizeHelper::sanitizeArrayData($value);
$this->employeeModel->save($value);
if (isset($value['id']))
{ $emp_id = $value['id']; }
else { $emp_id = $this->employeeModel->getInsertID();
$log_message .= $emp_id;
}
// $emp_id = $this->employeeModel->getInsertID();
// if($emp_id != 0){ $log_message .= $emp_id; }
// else{ $emp_id = $employee['id']; }
$this->myLogger->logme('error',$log_message);
//save policy table
$employee_policy = $this->employeePolicyModel->checkExistingEmpPolicy(['employee_id' => $emp_id,'client_policy_id' => $file['policy_id']]);
if(count($employee_policy))
{
$policy_data['updated_by'] = $file['created_by'];
$policy_data['id'] = $employee_policy[0]['id'];
$policy_data['status'] = 'draft';
$policy_data['payable_employee'] = check_pay_by_employee_or_company($policy_details['policy_terms'], $value['relationship']);
$policy_data['file_id'] = isset($employee_policy[0]['file_id']) && $employee_policy[0]['file_id'] != '' ? $employee_policy[0]['file_id'] : $file_id ;
$log_message = 'Update Employee Policy for '. $value['name'].'('. $value['emp_code'].') with PK- ' . $employee_policy[0]['id'] .' client policy ID '.$employee_policy[0]['client_policy_id'].' with SI '.$policy_data['basic_cover_si'];
// echo 'insert policy';
}
else
{
$policy_data['employee_id'] = $emp_id;
$policy_data['client_policy_id'] = $file['policy_id'];
$policy_data['created_by'] = $file['created_by'];
$policy_data['status'] = 'draft';
$policy_data['payable_employee'] = check_pay_by_employee_or_company($policy_details['policy_terms'], $value['relationship']);
$policy_data['file_id'] = $file_id;
$log_message = 'Insert Employee Policy for '. $value['name'].'('. $value['emp_code'].') - client policy id -'. $file['policy_id'].' - with SI '.$policy_data['basic_cover_si'];
// echo 'update policy';
}
log_message('error',json_encode($policy_data));
// dd($policy_data);
$this->employeePolicyModel->save($policy_data);
$emp_policy_id = $this->employeePolicyModel->getInsertID();
$this->myLogger->logme('error',$log_message);
$employeeRestController = new EmployeeRestController();
$employeeRestController->updatePremiumAmount($file['policy_id'], $value['emp_code'], $file['client_branch_id']);
//save email of self for send mail later
if (isset($notification) && $notification['enabled'] == 1 && $notification['mail_content'] != '')
{
if(strtolower($value['relationship']) == 'self' && $value['email_corporate'] != "")
{
$params['dataToInsert'] = $value; //holds employee master data
$params['notification'] = $notification;
$params['client_data'] = $client_details;
$params['common'] = [
'client_id' => $file['client_id'],
'client_branch_id' => $file['client_branch_id'],
'client_policy_id' => $file['policy_id'],
'employee_policy_id' => $emp_policy_id ?? null,
'employee_id' => $emp_id,
'mail_type' => 'member_welcome_mail',
];
//store email and mail content via helper to send notification
$emp_emails[] = sendMailNotification::sendMailNotification('member_welcome_mail', $params);
}
}
}// endof if row is empty check
} //end of for loop
// dd($emp_emails);
// for bulk mail queue job push
if (!empty($emp_emails) && count($emp_emails) > 0) {
$emp_emails = array_chunk($emp_emails, 20);
foreach ($emp_emails as $key => $value) {
$job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'bulk_mail', 'payload' => $value]);
}
}
$this->fileModel->where('id', $file_id)->set(['status' => 'success','reason' => ''])->update();
$this->myLogger->logme("error",'{file_id} uploaded success',['file_id' => $file_id]);
$this->setPullNotification($this->getFileMetaDataByFileId($file_id,'success'));
return true;
} //end of employeesEnrollmentInsert
// --------- MEMBER DATA AND INCEPTION DATA COMPARISION ------------------------------------------------------------------------
public function compareMemberDataAndInceptionData($params)
{
helper('excel_util_helper');
$file_id = $params['file_id'] ?? null;
if (empty($file_id)) {
return ['status' => false, 'msg' => 'File ID is missing'];
}
// ✅ Get File Data
$file = $this->fileModel->where(['is_active' => 1, 'id' => $file_id])->first();
if (empty($file)) {
return ['status' => false, 'msg' => 'File not found in DB'];
}
// ✅ Get Client Policy Data
$client_policy_data = $this->clientPolicyModel->where(['is_active' => 1, 'id' => $file['policy_id']])->first();
if (empty($client_policy_data)) {
return ['status' => false, 'msg' => 'Client policy data not found in DB (policy_id: ' . $file['policy_id'] . ')'];
}
// ✅ Get Lead Data
$leadModel = new LeadsModel();
$lead_data = $leadModel->where(['is_active' => 1, 'id' => $client_policy_data['is_from_lead']])->first();
if (empty($lead_data)) {
return ['status' => false, 'msg' => 'Lead data not found in DB (lead_id: ' . $client_policy_data['is_from_lead'] . ')'];
}
// ✅ Define File Paths
$inception_file_path = !empty($file['file_name']) ? WRITEPATH . "uploads/excel/" . $file['file_name'] : '';
$member_file_path = !empty($lead_data['file_name']) ? WRITEPATH . "uploads/lead_files/" . $lead_data['file_name'] : '';
// ✅ Check Inception File
if (empty($file['file_name']) || !file_exists($inception_file_path)) {
$message = empty($file['file_name']) ? "Inception file name is missing" : "Inception physical file not found";
$this->myLogger->logme('error', "$message for file id $file_id");
$this->fileModel->update($file_id, [
'status' => 'failed',
'reason' => json_encode(['error_summary' => [5], 'error_data' => $message])
]);
return ['error_summary' => [5], 'error_data' => $message];
}
// ✅ Check Member File
if (empty($lead_data['file_name']) || !file_exists($member_file_path)) {
$message = empty($lead_data['file_name']) ? "Member file name is missing" : "Member data physical file not found";
$this->myLogger->logme('error', "$message for lead id {$lead_data['id']}");
$this->fileModel->update($file_id, [
'status' => 'failed',
'reason' => json_encode(['error_summary' => [5], 'error_data' => $message])
]);
return ['error_summary' => [5], 'error_data' => $message];
}
// ✅ Read Inception Excel
$inception_columns = $this->inception_excel_columns;
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inception_file_path);
$sheet = $spreadsheet->getActiveSheet();
$highestRow = $sheet->getHighestDataRow();
$allowedColumn = end($inception_columns)['col_cell_name'];
$inception_data = $sheet->rangeToArray("A1:{$allowedColumn}{$highestRow}");
$inception_data = ExcelSanitizeHelper::sanitizeArrayData($inception_data);
// ✅ Read Member Excel
$member_columns = $this->member_data_excel_columns;
$spreadsheet2 = \PhpOffice\PhpSpreadsheet\IOFactory::load($member_file_path);
$sheet2 = $spreadsheet2->getSheet(0);
$highestRow2 = $sheet2->getHighestDataRow();
$allowedColumn2 = end($member_columns)['col_cell_name'];
$member_data = $sheet2->rangeToArray("A1:{$allowedColumn2}{$highestRow2}");
$member_data = ExcelSanitizeHelper::sanitizeArrayData($member_data);
// dd($inception_data, $member_data);
// ✅ Compare Inception Data with Member Data
$result = ['error_type' => 2, 'error_summary' => [], 'error_data' => []];
$inception_data_count = count($inception_data);
$member_data_count = count($member_data);
if ($inception_data_count !== $member_data_count) {
$result['error_summary'][] = 101;
$result['error_message'] = "
<strong>Inception Data Count:</strong>
<span class='badge badge-danger'>{$inception_data_count}</span>&nbsp;&nbsp;
<strong>Member Data Count:</strong>
<span class='badge badge-danger'>{$member_data_count}</span>";
}
foreach ($inception_data as $inception_key => $inception_row) {
// 🔹 If inception row is empty → stop all further processing
if (check_row_is_empty_or_null($inception_row)) {
break;
}
$match_found = false;
foreach ($member_data as $member_row) {
if (
$inception_row[1] == $member_row[1] && // emp_id / emp_code
$inception_row[2] == $member_row[2] && // name_of_emp_dep / name
$inception_row[5] == $member_row[3] && // relationship
normalizeGender($inception_row[4]) == normalizeGender($member_row[4]) && // gender
$inception_row[3] == $member_row[5] && // dob
$inception_row[13] == $member_row[7] && // email
$inception_row[12] == $member_row[8] // phone / mobile
) {
$match_found = true;
break;
}
}
if (!$match_found) {
array_push($result['error_summary'], 100);
$result['error_data'][$inception_key]['sno']['error'][] = "This inception row was not found in the member data list.";
}
}
// ✅ Handle Result
if (!empty($result['error_summary'])) {
$result['error_summary'] = array_count_values($result['error_summary']);
$this->fileModel->update($file_id, [
'status' => 'failed',
'reason' => json_encode($result)
]);
$this->myLogger->logme('error', "File ID $file_id comparison failed");
} else {
Jobs::addJob(['job_name' => 'excelFileDataValidation', 'payload' => ['file_id' => $file_id]]);
}
return $result;
}
/**
* Returns the inception Excel column configuration used for
* validating and processing Employee Upload with Events files.
* This allows other controllers to generate compatible Excel files.
*
* @return array
*/
public function getInceptionExcelColumns(): array
{
return $this->inception_excel_columns;
}
/**
* Returns the correction Excel column configuration used for
* validating and processing Employee correction files.
* This is reused by other controllers when they need to generate
* a correction-compatible Excel programmatically.
*
* @return array
*/
public function getCorrectionExcelColumns(): array
{
return $this->correction_excel_columns;
}
}