nhance/app/Controllers/RuleImportController.php
2026-04-16 15:28:06 +05:30

867 lines
37 KiB
PHP

<?php
namespace App\Controllers;
use CodeIgniter\API\ResponseTrait;
use App\Models\CommissionFilesModel;
use App\Models\InsurerModel;
use App\Models\PartnerPolicyModel;
class RuleImportController extends AdminController
{
use ResponseTrait;
protected $myLogger;
protected $ruleImportService;
protected $commissionFilesModel;
protected $departments;
protected $departmentFields;
protected $insurerModel;
protected $partnerPolicyModel;
public function __construct()
{
set_session_context('RuleImportController');
$this->myLogger = \Config\Services::mylogger();
$this->ruleImportService = \Config\Services::ruleImportService();
$this->partnerPolicyModel = new partnerPolicyModel();
$this->commissionFilesModel = new CommissionFilesModel();
$this->insurerModel = new InsurerModel();
$this->departments = [
'motor' => 'Motor',
'health' => 'Health',
];
$this->departmentFields = [
'motor' => [
'department',
'vehicle_type',
'vehicle_sub_type',
'policy_type',
'vehicle_age',
'is_new_vehicle',
'cubic_capacity',
'policy_business_type',
'fuel_type',
'produt',
'geo_rto_state',
'geo_rto_city',
'model',
'make',
'weight',
'renewal_type',
'renewal_sub_type',
'premium',
'od_premium',
'tp_premium',
'product'
],
];
}
public function commissionFileUploadList()
{
// print_rr($this->ruleImportService->processUpload([
// 'id' => 60,
// 'file_name' => 'Sample_commission_file-New.xlsx',
// 'insurer_id' => 77,
// 'department' => 'motor',
// 'commission_month' => '2025-11-10',
// 'created_by' => 10
// ]));
// die();
$data['page_name'] = "Commision File Upload";
$data['departments'] = $this->departments;
$data['insurers'] = $this->insurerModel->where('is_active', 1)->findAll();
$data['commission_file_list'] = $this->commissionFilesModel
->select('commission_files.*, insurers.short_name as insurer_name, user_profiles.first_name as created_user_name')
->join('insurers', 'commission_files.insurer_id = insurers.id')
->join('user_profiles', 'commission_files.created_by = user_profiles.id')
->where('commission_files.is_active', 1)
->orderBy('commission_files.id', 'desc')
->findAll();
// dd( $data);
return $this->loadLayout('commission_file_upload', $data);
}
/**
* Upload endpoint for form (POST)
* Input form field: 'rules_file'
*/
public function uploadORI()
{
// echo 'hi';
!dd($result = $this->ruleImportService->processUpload(['id' => 1,'file_name' => 'sample_commission.csv','insurer_id' => 5, 'department' => 'motor' ,'commission_month' => '2025-11-10']));die;
try {
$file = $this->request->getFile('rules_file');
if (!$file || !$file->isValid()) {
return $this->response->setJSON(['status'=>false,'message'=>'No file uploaded or upload error']);
}
if (!validate_upload_extension($file, UPLOAD_EXT_EXCEL)) {
return $this->response->setJSON(['status'=>false,'message'=>'Only Excel/CSV files (xls, xlsx, ods, csv) are allowed.']);
}
// Move uploaded file to writable temp location
$tmpPath = WRITEPATH . 'uploads/' . $file->getRandomName();
$file->move(WRITEPATH . 'uploads', $file->getName()); // keep original name inside uploads
$uploadedFullPath = $file->getTempName(); // Note: CI may store in tmp; we will use moved file path instead
$movedPath = WRITEPATH . 'uploads/' . $file->getName();
// Process file
$result = $this->ruleImportService->processUpload($movedPath, $file->getName());
// Return JSON with annotated file link if present
if (isset($result['annotated_file']) && $result['annotated_file']) {
$annotUrl = base_url('writable/uploads/annotated/' . basename($result['annotated_file']));
$result['annotated_url'] = $annotUrl;
}
return $this->response->setJSON($result);
} catch (\Throwable $e) {
$this->myLogger->logme('error', 'RuleImportController::upload ' . $e->getMessage());
return $this->response->setJSON(['status'=>false,'message'=>$e->getMessage()]);
}
}
public function upload()
{
try {
// ---------------------------------------------------------
// 1. Get uploaded file
// ---------------------------------------------------------
$file = $this->request->getFile('rules_file');
if (!$file || !$file->isValid()) {
$this->myLogger->logme('error', 'RuleImportController::upload - No file or invalid upload.');
return $this->respond(['status' => false, 'code' => 404, 'message' => 'No file uploaded or upload error.'], 200);
}
if (!validate_upload_extension($file, UPLOAD_EXT_EXCEL)) {
return $this->respond(['status' => false, 'code' => 400, 'message' => 'Only Excel/CSV files (xls, xlsx, ods, csv) are allowed.'], 200);
}
// ---------------------------------------------------------
// 2. Read POST fields
// ---------------------------------------------------------
// print_r($this->request->getPost()); die;
$insurerId = $this->request->getPost('insurer_id');
$department = $this->request->getPost('department');
$commissionMonth = $this->request->getPost('commission_month');
$overwrite = $this->request->getPost('overwrite') ?? 1;
$createdBy = get_session_userid();
if (empty($insurerId) || empty($department) || empty($commissionMonth)) {
$this->myLogger->logme('error', 'RuleImportController::upload - Missing required POST data.' . json_encode($this->request->getPost() ?? []));
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Missing required fields: insurer_id, department, commission_month'], 200);
}
$commissionMonth = $commissionMonth . '-01';
$commissionMonth = change_date_format($commissionMonth, 'Y-M-d', 'Y-m-d');
// Optional / default fields
$postedFileName = $this->request->getPost('file_name') ?: $file->getClientName();
$fileStatus = $this->request->getPost('file_status') ?: 'pending';
$isActive = $this->request->getPost('is_active') !== null ? (int)$this->request->getPost('is_active') : 1;
// rules_count is given by user but we will override it after processing on success
$postedRulesCount = $this->request->getPost('rules_count') !== null
? (int)$this->request->getPost('rules_count')
: 0;
// ---------------------------------------------------------
// 3. Move file to WRITEPATH/uploads/commission/files using user filename
// (no random name as per your requirement)
// ---------------------------------------------------------
$uploadDir = WRITEPATH . 'uploads/commission/files/';
if (!is_dir($uploadDir)) {
if (!mkdir($uploadDir, 0755, true) && !is_dir($uploadDir)) {
throw new \RuntimeException("Failed to create upload directory: {$uploadDir}");
}
}
// sanitize user file name but keep it deterministic (no random, no timestamp)
$safeName = preg_replace('/[^a-zA-Z0-9_\-\.]/', '_', $postedFileName);
// $movedFullPath = $uploadDir . $safeName;
$file->move($uploadDir, $safeName);
$targetFileName = $file->getName();
$movedFullPath = $uploadDir . $targetFileName;
if (!file_exists($movedFullPath)) {
$this->myLogger->logme('error', "RuleImportController::upload - Failed to move uploaded file to {$movedFullPath}");
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to store uploaded file.'], 500);
}
$this->myLogger->logme('info', "RuleImportController::upload - File moved to {$movedFullPath}");
// ---------------------------------------------------------
// 4. Insert commission_files row with status pending
// ---------------------------------------------------------
$insertData = [
'file_name' => $targetFileName,
'insurer_id' => (int)$insurerId,
'department' => $department,
'commission_month' => $commissionMonth,
'rules_count' => 0, // will update on success
'file_status' => $fileStatus, // 'pending' by default
'is_active' => $isActive,
'created_by' => (int)$createdBy,
'created_at' => date('Y-m-d H:i:s'),
];
$this->commissionFilesModel->insert($insertData);
$insertId = $this->commissionFilesModel->getInsertID();
if (empty($insertId)) {
$this->myLogger->logme('error', 'RuleImportController::upload - Failed to insert commission_files record', ['data' => $insertData]);
return $this->respond([
'status' => false,
'code' => 404,
'message' => 'Failed to record upload in database.'
], 200);
}
$this->myLogger->logme('info', "RuleImportController::upload - commission_files inserted id={$insertId}", $insertData);
// ---------------------------------------------------------
// 5. Call ruleImportService->processUpload with inserted file info
// As per your spec:
// $this->ruleImportService->processUpload([
// 'id' => 1,
// 'file_name' => 'sample_commission.csv',
// 'insurer_id' => 5,
// 'department' => 'motor',
// 'commission_month' => '2025-11-10'
// ])
// ---------------------------------------------------------
$payload = [
'id' => (int)$insertId,
'file_name' => $targetFileName,
'insurer_id' => (int)$insurerId,
'department' => $department,
'commission_month' => $commissionMonth,
'created_by' => (int)$createdBy,
];
$this->myLogger->logme('info', 'RuleImportController::upload - Calling ruleImportService->processUpload', ['payload' => $payload]);
$result = $this->ruleImportService->processUpload($payload);
if (!is_array($result) || !isset($result['status'])) {
$this->myLogger->logme('error', 'RuleImportController::upload - Invalid service response', ['response' => $result]);
// update file status as failed
$this->commissionFilesModel->update($insertId, [
'file_status' => 'failed',
'updated_by' => (int)$createdBy,
'updated_at' => date('Y-m-d H:i:s'),
]);
return $this->respond([
'status' => false,
'code' => 404,
'message' => 'Invalid response from import service.'
], 200);
}
// ---------------------------------------------------------
// 6. Handle SUCCESS
// - result['rules'] exists
// - result['errors'] empty
// - NO annotated_file
// - Save rules as JSON in WRITEPATH/uploads/commission/json/{insurer_id}_{department}.json
// ---------------------------------------------------------
if ($result['status'] === 'success') {
$rulesArray = isset($result['rules']) && is_array($result['rules']) ? $result['rules'] : [];
$rulesCount = count($rulesArray);
// Save JSON to WRITEPATH . 'uploads/commission/json/{insurer_id}_{department}.json'
$month_path = strtoupper(date('M', strtotime($commissionMonth))) . date('Y', strtotime($commissionMonth));
$jsonDir = WRITEPATH . 'uploads/commission/rules/'.$month_path . '/';
if (!is_dir($jsonDir)) {
if (!mkdir($jsonDir, 0755, true) && !is_dir($jsonDir)) {
throw new \RuntimeException("Failed to create JSON output directory: {$jsonDir}");
}
}
$this->myLogger->logme('error', 'RuleImportController::jsonDir' . $jsonDir);
$deptSlug = preg_replace('/[^a-zA-Z0-9_\-]/', '_', strtolower($department));
$jsonName = (int)$insurerId . '_' . $deptSlug . '.json';
$jsonPath = $jsonDir . $jsonName;
$jsonData = json_encode($rulesArray, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
if ($jsonData === false) {
$this->myLogger->logme('error', 'RuleImportController::upload - json_encode failed for rules', [
'last_error' => json_last_error_msg()
]);
// mark as failed since we cannot save rules
$this->commissionFilesModel->update($insertId, [
'file_status' => 'failed',
'updated_by' => (int)$createdBy,
'updated_at' => date('Y-m-d H:i:s'),
]);
return $this->respond([
'status' => false,
'code' => 404,
'message' => 'Failed to encode rules as JSON.'
], 200);
}
// handle existing JSON file based on $override (bool)
if (file_exists($jsonPath)) {
if ($overwrite) {
// rename existing file before overwrite
if (file_exists($jsonPath)) {
$backupPath = $jsonPath . '.' . date('YmdHis') . '.bak';
if (!@rename($jsonPath, $backupPath)) {
$this->myLogger->logme(
'warning',
'RuleImportController::upload - Failed to rename existing JSON before overwrite',
[
'json_path' => $jsonPath,
'backup_path' => $backupPath
]
);
// continue anyway; writing to same path will overwrite
}
}
$finalJson = $jsonData;
} else {
// append: merge existing JSON with new JSON data
$existingRaw = @file_get_contents($jsonPath);
if ($existingRaw === false) {
$this->myLogger->logme('warning', 'RuleImportController::upload - Could not read existing JSON, will replace with new data', ['json_path' => $jsonPath]);
$finalJson = $jsonData;
} else {
$existingDecoded = json_decode($existingRaw, true);
$newDecoded = json_decode($jsonData, true);
// if decoding fails, treat as empty array/object and log
if (json_last_error() !== JSON_ERROR_NONE && !is_array($existingDecoded) && !is_object($existingDecoded)) {
$this->myLogger->logme('warning', 'RuleImportController::upload - Existing JSON decode failed; replacing with new data', ['json_path' => $jsonPath, 'json_error' => json_last_error_msg()]);
$finalJson = $jsonData;
} else {
// normalize to PHP arrays for easy merging
if (!is_array($existingDecoded)) {
$existingDecoded = [$existingDecoded];
}
if (!is_array($newDecoded)) {
$newDecoded = [$newDecoded];
}
// merge arrays (preserves numeric keys by reindexing)
$merged = array_merge($existingDecoded, $newDecoded);
$this->myLogger->logme('error', 'RuleImportController::JSON MERGED');
$finalJson = json_encode($merged, JSON_PRETTY_PRINT);
if ($finalJson === false) {
$this->myLogger->logme('error', 'RuleImportController::upload - Failed to encode merged JSON', ['json_path' => $jsonPath, 'merge_count' => count($merged)]);
$this->commissionFilesModel->update($insertId, [
'file_status' => 'failed',
'updated_by' => (int)$createdBy,
'updated_at' => date('Y-m-d H:i:s'),
]);
return $this->respond([
'status' => false,
'code' => 500,
'message' => 'Failed to encode merged rules JSON.'
], 500);
}
}
}
}
} else {
// file doesn't exist, just write new data
$finalJson = $jsonData;
}
// write final JSON to disk with exclusive lock
if (file_put_contents($jsonPath, $finalJson, LOCK_EX) === false) {
$this->myLogger->logme('error', 'RuleImportController::upload - Failed to write rules JSON file', ['json_path' => $jsonPath]);
$this->commissionFilesModel->update($insertId, [
'file_status' => 'failed',
'updated_by' => (int)$createdBy,
'updated_at' => date('Y-m-d H:i:s'),
]);
return $this->respond([
'status' => false,
'code' => 404,
'message' => 'Failed to store rules JSON file.'
], 500);
}
// success continues...
$this->myLogger->logme('info', 'RuleImportController::upload - Rules JSON file written', ['json_path' => $jsonPath, 'overwrite' => (bool)$overwrite]);
$this->myLogger->logme('info', 'RuleImportController::upload - Rules JSON written', [
'file_id' => $insertId,
'json_path' => $jsonPath,
'rules_cnt' => $rulesCount,
]);
// Update DB: status, rules_count, updated_by
$this->commissionFilesModel->update($insertId, [
'file_status' => 'success',
'rules_count' => $rulesCount,
'updated_by' => (int)$createdBy,
'updated_at' => date('Y-m-d H:i:s'),
// If you have a column for JSON path, uncomment:
// 'json_file_path' => $jsonPath,
]);
return $this->respond([
'status' => true,
'code' => 200,
'message' => 'File processed successfully.',
'file_id' => $insertId,
'rules_count' => $rulesCount,
'json_file' => $jsonPath,
'service' => $result, // optional: return full service response if you want
], 200);
}
// ---------------------------------------------------------
// 7. Handle ERROR (validation failed etc.)
// - Do NOT save any rules JSON
// - Update file_status to validation_failed
// - Store annotated_file path if you have such a column
// ---------------------------------------------------------
if ($result['status'] === 'error') {
$annotatedPath = $result['annotated_file'] ?? null;
$errors = $result['errors'] ?? [];
$updateData = [
'file_status' => 'failed',
'rules_count' => 0, // do not save rules
'updated_by' => (int)$createdBy,
'updated_at' => date('Y-m-d H:i:s'),
];
// If you have a column for annotated file path, e.g. annotated_file_path
if ($annotatedPath) {
$updateData['annotated_file_path'] = $annotatedPath;
}
$this->commissionFilesModel->update($insertId, $updateData);
$this->myLogger->logme('error', "RuleImportController::upload - Validation failed for file_id={$insertId}", [
'errors' => $errors,
'annotated_file' => $annotatedPath
]);
return $this->respond([
'status' => false,
'code' => 404,
'message' => 'Validation failed. No rules saved.',
'file_id' => $insertId,
'errors' => $errors,
'annotated_file' => $annotatedPath,
], 422);
}
// ---------------------------------------------------------
// 8. Unexpected status
// ---------------------------------------------------------
$this->myLogger->logme('error', 'RuleImportController::upload - Unexpected result status from service', ['result' => $result]);
$this->commissionFilesModel->update($insertId, [
'file_status' => 'failed',
'updated_by' => (int)$createdBy,
'updated_at' => date('Y-m-d H:i:s'),
]);
return $this->respond([
'status' => false,
'code' => 404,
'message' => $result['message']
], 200);
} catch (\Throwable $ex) {
$this->myLogger->logme('error', 'RuleImportController::upload exception: ' . $ex->getMessage(), [
'trace' => $ex->getTraceAsString()
]);
// Try to update the commission_files record if insertId exists
if (isset($insertId) && !empty($insertId)) {
try {
$this->commissionFilesModel->update($insertId, [
'file_status' => 'failed',
'updated_by' => get_session_userid(),
'updated_at' => date('Y-m-d H:i:s'),
'notes' => 'Upload exception: ' . $ex->getMessage(),
]);
} catch (\Throwable $e2) {
$this->myLogger->logme('error', 'RuleImportController::upload - failed to update commission_files after exception: ' . $e2->getMessage());
}
}
return $this->respond([
'status' => false,
'code' => 500,
'message' => $ex->getMessage(),
], 500);
}
}
public function downloadSampleCommissionFileUploadExcel()
{
$filePath = ROOTPATH . 'public/sample_excel/sample_commission.csv';
// Check if the file exists
if (file_exists($filePath)) {
// Set the appropriate MIME type
$mimeType = mime_content_type($filePath);
// Send the file to the client for download
return $this->response->download($filePath, null, $mimeType);
} else {
// File not found, show an error message or redirect
echo view('errors/html/production');
}
}
public function downloadErrorFile()
{
$file_id = $this->request->getGet('file_id');
$file_data = $this->commissionFilesModel->where('id', $file_id)->where('is_active', 1)->first();
$filePath = WRITEPATH . 'uploads/commission/files/annotated_' . $file_data['file_name'];
// Check if the file exists
if (file_exists($filePath)) {
// Set the appropriate MIME type
$mimeType = mime_content_type($filePath);
// Send the file to the client for download
return $this->response->download($filePath, null, $mimeType);
} else {
// File not found, show an error message or redirect
$data['message'] = 'The Physical File Not Found';
echo view('errors/404', $data);
}
}
public function deleteCommissionData($id)
{
$return = $this->updateCommissionRules($id);
// dd($return);
if($return['status'] == true){
$this->commissionFilesModel->where('id', $id)->set(['is_active' => 0])->update();
return $this->respond(['status' => true, 'code' => 200, 'message' => "File removed successfully"], 200);
}else{
return $this->respond(['status' => false, 'code' => 400, 'message' => "Failed to remove file"], 200);
}
}
public function updateCommissionRules($id, $post_data = null)
{
// 1. Fetch commission record
$commission_data = $this->commissionFilesModel
->where('is_active', 1)
->where('id', $id)
->first();
if (!$commission_data) {
$this->myLogger->logme("error", "Commission record not found for ID: $id");
return ['status' => false, 'message' => 'Commission record not found'];
}
// 2. Convert commission_month → OCT2025
$month = date("M", strtotime($commission_data['commission_month']));
$year = date("Y", strtotime($commission_data['commission_month']));
$monthFolder = strtoupper($month . $year);
// 3. Path
$fileName = $commission_data['insurer_id'] . '_' . $commission_data['department'] . '.json';
$filePath = WRITEPATH . "uploads/commission/rules/" . $monthFolder . "/" . $fileName;
if (!file_exists($filePath)) {
$this->myLogger->logme("error", "Rule file not found: $filePath");
return ['status' => false, 'message' => 'Rule file not found'];
}
// 4. Read JSON
$json = file_get_contents($filePath);
$rules = json_decode($json, true);
// print_rr($rules); die;
if (!is_array($rules)) {
$this->myLogger->logme("error", "Invalid JSON structure in file: $filePath");
return ['status' => false, 'message' => 'Invalid rule file'];
}
// 5. Mark matching rule as deleted
$ruleFound = false;
$log_message = "Rule file updated successfully";
if(empty($post_data)){
foreach ($rules as &$rule) {
if (isset($rule['file_id']) && $rule['file_id'] == $id && isset($rule['is_deleted']) && $rule['is_deleted'] == false) {
$rule['is_deleted'] = true;
$ruleFound = true;
}
}
$log_message = "Rule marked as deleted and file updated successfully";
} else {
foreach ($rules as &$rule) {
// Match rules for the same file and not deleted
if (isset($rule['file_id']) && $rule['file_id'] == $id && $rule['is_deleted'] == false)
{
// 1. DELETE RULE
if (!empty($post_data['rule_id']) && $post_data['rule_id'] == $rule['id'] && isset($post_data['is_deleted']))
{
$rule['is_deleted'] = true;
$ruleFound = true;
break;
}
// 2. UPDATE RULE
if (!empty($post_data['rule_id']) && $post_data['rule_id'] == $rule['id'])
{
$rule['conditions'] = $post_data['rule_data']['conditions'];
$rule['calculation'] = $post_data['rule_data']['calculation'];
$rule['name'] = $post_data['rule_data']['name'];
$ruleFound = true;
break;
}
}
}
// 3. CREATE NEW RULE (only if not found)
if (empty($post_data['rule_id']) && !$ruleFound) {
$newRuleId = 'rule_' . substr(md5(json_encode($post_data['rule_data']) . time()), 0, 13) . '_' . $id . '_' . strtolower($monthFolder);
$newRule = [
'id' => $newRuleId,
'name' => $post_data['rule_data']['name'],
"department" => $post_data['rule_data']['department'] ?? "motor",
'is_deleted' => false,
'file_id' => $id,
'conditions' => $post_data['rule_data']['conditions'],
'calculation' => $post_data['rule_data']['calculation'],
];
$rules[] = $newRule; // correctly push new rule
$ruleFound = true;
}
}
if (!$ruleFound) {
$this->myLogger->logme("error", "No rule found with file_id: $id in file: $filePath");
return ['status' => false, 'message' => 'Rule not found in file'];
}
// 6. Always save file back (No unlink)
file_put_contents($filePath, json_encode($rules, JSON_PRETTY_PRINT));
$this->myLogger->logme("error", $log_message);
return [
'status' => true,
'message' => $log_message
];
}
public function removeCommissionRules($id)
{
// 1. Fetch commission record
$commission_data = $this->commissionFilesModel
->where('is_active', 1)
->where('id', $id)
->first();
if (!$commission_data) {
$this->myLogger->logme("error","Commission record not found for ID: $id");
return ['status' => false, 'message' => 'Commission record not found'];
}
// 2. Convert commission_month → OCT2025
$month = date("M", strtotime($commission_data['commission_month']));
$year = date("Y", strtotime($commission_data['commission_month']));
$monthFolder = strtoupper($month . $year); // OCT2025
// 3. Build file name & path
$fileName = $commission_data['insurer_id'] . '_' . $commission_data['department'] . '.json';
$filePath = WRITEPATH . "uploads/commission/rules/" . $monthFolder . "/" . $fileName;
if (!file_exists($filePath)) {
$this->myLogger->logme("error","Rule file not found: $filePath");
return ['status' => false, 'message' => 'Rule file not found'];
}
// 4. Read file
$json = file_get_contents($filePath);
$rules = json_decode($json, true);
// dd($rules);
if (!is_array($rules)) {
$this->myLogger->logme("error","Invalid JSON structure in file: $filePath");
return ['status' => false, 'message' => 'Invalid rule file'];
}
// 5. Remove rule where file_id == commission_data id
$updatedRules = array_filter($rules, function ($rule) use ($id) {
return isset($rule['file_id']) && $rule['file_id'] != $id;
});
$updatedRules = array_values($updatedRules);
// 6. If empty → delete file
if (empty($updatedRules)) {
unlink($filePath);
$this->myLogger->logme("error","Rule removed. File deleted because no rules left: $filePath");
return [
'status' => true,
'message' => 'Rule deleted and file removed (no rules left)'
];
}
// 7. Write updated JSON
file_put_contents($filePath, json_encode($updatedRules, JSON_PRETTY_PRINT));
$this->myLogger->logme("error","Rule removed successfully and file updated: $filePath");
return [
'status' => true,
'message' => 'Rule removed and file updated successfully'
];
}
public function checkSameEntry()
{
$data = $this->request->getGet();
$commissionMonth = $data['commission_month'] . '-01';
$data['commission_month'] = change_date_format($commissionMonth, 'Y-M-d', 'Y-m-d');
$count = $this->commissionFilesModel->where($data)->where('is_active', 1)->countAllResults();
if($count > 0){
return $this->respond(['status' => true, 'code' => 200, 'data' => $count, 'message' => ""], 200);
}else{
return $this->respond(['status' => false, 'code' => 404, 'data' => $count, 'message' => ""], 200);
}
}
public function ruleList($id)
{
$data['tab_name'] = "Rule Manager";
$data['page_name'] = "Rule Manager";
$data['departments'] = $this->departments;
$data['commission_file_id'] = $id;
$data['departmentFields'] = json_encode($this->departmentFields);
$data['rules'] = $this->getRuleJson($id);
return $this->loadLayout('commission_rules_list', $data);
}
public function getRuleJson($id)
{
// 1. Fetch commission record
$commission_data = $this->commissionFilesModel
->where('is_active', 1)
->where('id', $id)
->first();
if (!$commission_data) {
$this->myLogger->logme("error", "Commission record not found for ID: $id");
return [];
}
// 2. Convert commission_month → OCT2025
$month = date("M", strtotime($commission_data['commission_month']));
$year = date("Y", strtotime($commission_data['commission_month']));
$monthFolder = strtoupper($month . $year);
// 3. Path
$fileName = $commission_data['insurer_id'] . '_' . $commission_data['department'] . '.json';
$filePath = WRITEPATH . "uploads/commission/rules/" . $monthFolder . "/" . $fileName;
if (!file_exists($filePath)) {
$this->myLogger->logme("error", "Rule file not found: $filePath");
return [];
}
// 4. Read JSON
$json = file_get_contents($filePath);
$rules = json_decode($json, true);
if(!empty($rules)){
return $rules;
}else{
return [];
}
}
public function saveRule()
{
$post_data = $this->request->getPost();
$file_id = $post_data['file_id'];
$return = $this->updateCommissionRules($file_id, $post_data);
// print_r($return); die;
if(empty($post_data['rule_id'])){
$success_message = "New rule created successfully";
$error_message = "Failed to created the new rule";
}else{
$success_message = "Rule updated successfully";
$error_message = "Failed to update the rule";
}
if($return['status'] == true){
$data = $this->getRuleJson($file_id);
return $this->respond(['status' => true, 'code' => 200, 'data' => $data, 'message' => $success_message], 200);
}else{
return $this->respond(['status' => false, 'code' => 400, 'message' => $error_message], 200);
}
}
public function removeRule()
{
$post_data = $this->request->getPost();
$file_id = $post_data['file_id'];
$return = $this->updateCommissionRules($file_id, $post_data);
// print_r($return); die;
$success_message = "Rule deleted successfully";
$error_message = "Failed to delete the rule";
if($return['status'] == true){
$data = $this->getRuleJson($file_id);
return $this->respond(['status' => true, 'code' => 200, 'data' => $data, 'message' => $success_message], 200);
}else{
return $this->respond(['status' => false, 'code' => 400, 'message' => $error_message], 200);
}
}
public function checkRuleUsage()
{
$rule_id = $this->request->getGet('rule_id');
$count = $this->partnerPolicyModel->where('commission_applied_rule', $rule_id)
->countAllResults();
// $count = 1;
return $this->respond(['status' => true, 'code' => 200, 'count' => $count, 'message' => ""], 200);
}
}