diff --git a/app/Config/Routes.php b/app/Config/Routes.php index be79c96f..634252a7 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -776,3 +776,13 @@ $routes->group('payout', function($routes) { $routes->post('removeUtrDetails',"PayoutController::removeUtrDetails"); }); +//PARTNER COMMISSION +$routes->group('commission', function($routes) { + $routes->match (['get','post'],'list',"RuleImportController::commissionFileUploadList"); + $routes->post('upload',"RuleImportController::upload"); + $routes->get('sample_file',"RuleImportController::downloadSampleCommissionFileUploadExcel"); + $routes->get('downloadErrorFile',"RuleImportController::downloadErrorFile"); + $routes->get("deleteCommissionData/(:any)", "RuleImportController::deleteCommissionData/$1"); + $routes->get('checkSameEntry',"RuleImportController::checkSameEntry"); +}); + diff --git a/app/Controllers/ApiServiceController.php b/app/Controllers/ApiServiceController.php index fe275b21..ac6cb0dd 100644 --- a/app/Controllers/ApiServiceController.php +++ b/app/Controllers/ApiServiceController.php @@ -79,6 +79,7 @@ class ApiServiceController extends BaseController $client_policy_id = $params['client_policy_id'] ?? null; $policy_no = $params['policy_no'] ?? null; $type = $params['type'] ?? 'download'; + $all_member = $params['all_member'] ?? null; log_message('error', 'Received Payload INTERNAL : '. json_encode($params ?? "")); @@ -107,10 +108,16 @@ class ApiServiceController extends BaseController // direct download $data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string'].'/1'; }else{ - // view and download - $data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string'].'/0/1'; + if(isset($all_member) && !empty($all_member)){ + // view and download all members + $data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string'].'/1/1'; + }else{ + // view and download single member + $data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string'].'/0/1'; + } } } + $data['message'] = "E-card generated"; if(empty($data['eCardDownload'])){ $data['message'] = "E-card not generated"; diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index 87ec5222..8ee13498 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -792,6 +792,7 @@ class ClientController extends AdminController $editData['RM'] = $this->userModel->where('is_active', 1)->findAll(); $editData['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames(); + $editData['tpa_list'] = $this->tpaModel->where('is_active', 1)->findAll(); $editData['state'] = $this->stateModel->getAllStates(); $editData['police'] = $this->policesModel->findAll(); $editData['entity'] = $this->kycEntityTypeModel->findAll(); @@ -1439,7 +1440,9 @@ class ClientController extends AdminController $data['is_member_modify_allowed'] = $this->request->getPost('is_member_modify_allowed') ? 1 : 0; $data['enrolment_visibility'] = $this->request->getPost('enrolment_visibility') ? 1 : 0; $data['is_lgbtq'] = $this->request->getPost('is_lgbtq') ? 1 : 0; - + $data['wellness_plan_id'] = $this->request->getPost('wellness_plan_id'); + $data['wellness_vendor_id'] = $this->request->getPost('wellness_vendor_id'); + $data['wellness_vendor_id'] = !empty($data['wellness_vendor_id']) ? $data['wellness_vendor_id'] : null; if ($policy_type_id == 1 || $policy_type_id == 2 || $policy_type_id == 6 || $policy_type_id == 7) { @@ -1536,10 +1539,14 @@ class ClientController extends AdminController $data['cd_ac_pk'] = $this->request->getPost('cd_ac_no'); $data['gst'] = $this->request->getPost('gst'); $data['disclaimer'] = $this->request->getPost('disclaimer'); - $data['policy_start_date'] = change_date_format($this->request->getPost('policy_start_date'), 'd-m-Y', 'Y-m-d'); - $data['policy_end_date'] = change_date_format($this->request->getPost('policy_end_date'), 'd-m-Y', 'Y-m-d'); + $data['policy_start_date'] = change_date_format($this->request->getPost('policy_start_date'), 'd-m-Y', 'Y-m-d'); + $data['policy_end_date'] = change_date_format($this->request->getPost('policy_end_date'), 'd-m-Y', 'Y-m-d'); $data['is_member_modify_allowed'] = $this->request->getPost('is_member_modify_allowed') ? 1 : 0; - $data['is_lgbtq'] = $this->request->getPost('is_lgbtq') ? 1 : 0; + $data['is_lgbtq'] = $this->request->getPost('is_lgbtq') ? 1 : 0; + $data['wellness_plan_id'] = $this->request->getPost('wellness_plan_id'); + $data['wellness_vendor_id'] = $this->request->getPost('wellness_vendor_id'); + $data['wellness_vendor_id'] = !empty($data['wellness_vendor_id']) ? $data['wellness_vendor_id'] : null; + if ($data['inception_type'] == 2) { $data['open_date'] = change_date_format($this->request->getPost('open_date'), 'd-m-Y', 'Y-m-d'); $data['close_date'] = change_date_format($this->request->getPost('close_date'), 'd-m-Y', 'Y-m-d'); diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php index dfaac349..1c22f967 100755 --- a/app/Controllers/EmpDataServiceController.php +++ b/app/Controllers/EmpDataServiceController.php @@ -4968,6 +4968,10 @@ class EmpDataServiceController extends BaseController 'client_policy_id' => $emp_details['client_policy_id'], ]; + if(empty($single_mail)){ + $params['all_member'] = 1; + } + $params['common'] = [ 'client_id' => $emp_details['client_id'], 'client_branch_id' => $emp_details['client_branch_id'], diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index 65b7ba3f..10a0b636 100755 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -754,7 +754,7 @@ class EmployeeRestController extends AdminController $result = $empServiceController->excelFileFormatValidation(['file_id' => $file_id]); if (isset($result['error_summary']) && count($result['error_summary'])) { $result = $empServiceController->getExcelErrorData($file_id); - return $this->respond(['status' => 'failed', 'code' => 404, 'message' => "file upload failed with errors", 'data' => $result], 200); + return $this->respond(['status' => 'failed', 'code' => 404, 'message' => "The data format is invalid. Click 'Next' to view details.", 'data' => $result], 200); } @@ -2573,95 +2573,117 @@ class EmployeeRestController extends AdminController public function claimView() { - $ticket_id = $this->request->getGet('ticket_id'); - $ticketController = new TicketController; - $data['ticket_history'] = $ticketController->ticketHistory($ticket_id); - $data['claims_data'] = $this->ticketMaster->getTicketDataByTicketID($ticket_id); - $data['ticket_data'] = $ticketController->getMoreInfo($requestFrom = 'rest', $ticket_id); + try { - // $ticketData = $data['ticket_data']; - // $ticketHistory = $data['ticket_history']; + $ticket_id = $this->request->getGet('ticket_id'); + $ticketController = new TicketController; + $data['ticket_history'] = $ticketController->ticketHistory($ticket_id); + $data['claims_data'] = $this->ticketMaster->getTicketDataByTicketID($ticket_id); + $data['ticket_data'] = $ticketController->getMoreInfo($requestFrom = 'rest', $ticket_id); - $ticketClaimStatus = $this->claimStatusModel->select('claim_status, display_name')->where('display_name is not null')->where('is_active', 1)->findAll(); - $status_list = array_column($ticketClaimStatus, 'display_name', 'claim_status'); - - $data['ticket_data'] = array_fill_keys(array_keys($data['ticket_data']), []); + // $ticketData = $data['ticket_data']; + // $ticketHistory = $data['ticket_history']; + // print_r($ticketHistory); die; + $currentClaimStatus = $this->claimStatusModel->select("claim_status")->where('id', $data['claims_data']['claim_status_id'])->where('is_active', 1)->first(); + $ticketClaimStatus = $this->claimStatusModel->select('claim_status, display_name')->where('display_name is not null')->where('is_active', 1)->findAll(); + $status_list = array_column($ticketClaimStatus, 'display_name', 'claim_status'); + // print_r($currentClaimStatus); die; - // Loop through ticket_data - foreach ($data['ticket_data'] as $status => &$fields) { - // Search ticket_history for matching old_status_value - foreach ($data['ticket_history'] as $history) { + $data['ticket_data'] = array_fill_keys(array_keys($data['ticket_data']), []); - if ($history['old_status_value'] === $status) { - // Attach modified_by and created_at - // $fields['modified_by'] = $history['modified_by']; - $fields['modified_by'] = ""; - $fields['modified_at'] = date('d-m-Y h:i A', strtotime($history['created_at'])); - // Break after first match (assuming latest entry is enough) - break; + // Loop through ticket_data + foreach ($data['ticket_data'] as $status => &$fields) { + // Search ticket_history for matching old_status_value + foreach ($data['ticket_history'] as $history) { + + if ($history['old_status_value'] === $status) { + // Attach modified_by and created_at + // $fields['modified_by'] = $history['modified_by']; + $fields['modified_by'] = ""; + $fields['modified_at'] = date('d-m-Y h:i A', strtotime($history['created_at'])); + // Break after first match (assuming latest entry is enough) + break; + } } } - } - $new_ticket_data = []; + $data['ticket_data'][$currentClaimStatus['claim_status']]['modified_by'] = ""; + $data['ticket_data'][$currentClaimStatus['claim_status']]['modified_at'] = $formatted = date('d-m-Y h:i A', strtotime($data['claims_data']['updated_at'])); - foreach ($data['ticket_data'] as $oldKey => $value) { + $new_ticket_data = []; - // Only process if key exists in status_list - if (!isset($status_list[$oldKey])) { - continue; // skip and do NOT add to new array + foreach ($data['ticket_data'] as $oldKey => $value) { + + // Only process if key exists in status_list + if (!isset($status_list[$oldKey])) { + continue; // skip and do NOT add to new array + } + + // Get new key based on mapping + $newKey = $status_list[$oldKey]; + + // Avoid duplicates + if (!isset($new_ticket_data[$newKey])) { + $new_ticket_data[$newKey] = $value; + } } - // Get new key based on mapping - $newKey = $status_list[$oldKey]; + uasort($new_ticket_data, function ($a, $b) { + $timeA = \DateTime::createFromFormat('d-m-Y h:i A', $a['modified_at']); + $timeB = \DateTime::createFromFormat('d-m-Y h:i A', $b['modified_at']); + return $timeA <=> $timeB; // Ascending + }); - // Avoid duplicates - if (!isset($new_ticket_data[$newKey])) { - $new_ticket_data[$newKey] = $value; - } - } - - uasort($new_ticket_data, function ($a, $b) { - $timeA = \DateTime::createFromFormat('d-m-Y h:i A', $a['modified_at']); - $timeB = \DateTime::createFromFormat('d-m-Y h:i A', $b['modified_at']); - return $timeA <=> $timeB; // Ascending - }); - - $data['ticket_data'] = $new_ticket_data; + $data['ticket_data'] = $new_ticket_data; - $ticketMesssageModel = new TicketMessageModel(); - $ticket_message = $ticketMesssageModel - ->where('is_active', 1) - ->where('sender', "user") - ->where('ticket_id', $ticket_id) - ->orderBy('id', "desc") - ->first(); - - $claim_file_urls = []; - - if (isset($ticket_message['id'])) { - - $claimFiles = new ClaimFilesModel(); - $claim_files_data = $claimFiles - ->select('id as claim_file_id, doc_name as claim_file_name') + $ticketMesssageModel = new TicketMessageModel(); + $ticket_message = $ticketMesssageModel ->where('is_active', 1) - ->where('file_type', 2) + ->where('sender', "user") ->where('ticket_id', $ticket_id) - ->where('ticket_message_id', $ticket_message['id']) - ->findAll(); + ->orderBy('id', "desc") + ->first(); - foreach ($claim_files_data as &$value) { - $value['url'] = base_url('downloadClaimFile/') . $value['claim_file_id']; - $claim_file_urls[] = $value; + $claim_file_urls = []; + + if (isset($ticket_message['id'])) { + + $claimFiles = new ClaimFilesModel(); + $claim_files_data = $claimFiles + ->select('id as claim_file_id, doc_name as claim_file_name') + ->where('is_active', 1) + ->where('file_type', 2) + ->where('ticket_id', $ticket_id) + ->where('ticket_message_id', $ticket_message['id']) + ->findAll(); + + foreach ($claim_files_data as &$value) { + $value['url'] = base_url('downloadClaimFile/') . $value['claim_file_id']; + $claim_file_urls[] = $value; + } + unset($value); } - unset($value); + + $data['claim_files'] = $claim_file_urls; + + return $this->respond(['status' => (count($data) ? 'success' : 'failed'), 'code' => (count($data) ? 200 : 404), 'data' => $data,], 200); + + } catch (\Throwable $th) { + $this->myLogger->logme("error", 'claim_view' .($th->getMessage() . ' --- ' . $th->getLine() . '----' . $th->getTraceAsString())); + $errorData = [ + 'message' => $th->getMessage(), + 'file' => $th->getFile(), + 'line' => $th->getLine(), + 'code' => $th->getCode(), + 'trace' => $th->getTraceAsString(), + 'trace_array' => $th->getTrace(), // full array version (optional) + 'function' => $th->getTrace()[0]['function'] ?? null, + 'class' => $th->getTrace()[0]['class'] ?? null, + ]; + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => "", 'error_data' => $errorData], 500); } - - $data['claim_files'] = $claim_file_urls; - - return $this->respond(['status' => (count($data) ? 'success' : 'failed'), 'code' => (count($data) ? 200 : 404), 'data' => $data,], 200); } @@ -3810,15 +3832,17 @@ class EmployeeRestController extends AdminController // 'Under Process' => [5, 6, 7, 10, 19, 23, 45, 50, 29, 33, 51, 39, 43, 56], // ]; - $client_claim_status = [ - 'Claim Received' => [1, 2, 3, 15, 16, 17, 18, 25, 26, 27, 28, 35, 36, 37, 38], - 'Under Process' => [5, 6, 7, 10, 19, 23, 45, 50, 29, 33, 51, 39, 43, 56], - 'Information Required' => [4], - 'Approved' => [9, 20, 30, 40], - 'Settled' => [11, 24, 34], - 'Denial Review Awaited' => [66], - 'Rejected' => [8, 49, 55, 60], - ]; + // $client_claim_status = [ + // 'Claim Received' => [1, 2, 3, 15, 16, 17, 18, 25, 26, 27, 28, 35, 36, 37, 38], + // 'Under Process' => [5, 6, 7, 10, 19, 23, 45, 50, 29, 33, 51, 39, 43, 56], + // 'Information Required' => [4], + // 'Approved' => [9, 20, 30, 40], + // 'Settled' => [11, 24, 34], + // 'Denial Review Awaited' => [66], + // 'Rejected' => [8, 49, 55, 60], + // ]; + + $client_claim_status = $this->getClaimStatusGrouped(); foreach ($ticket_data as $key => $value) { @@ -3866,6 +3890,32 @@ class EmployeeRestController extends AdminController return $this->response->setJSON(['ticket_data' => $ticket_data])->setStatusCode(200); } + public function getClaimStatusGrouped() + { + // Fetch active claim statuses + $ticketClaimStatus = $this->claimStatusModel + ->select('id, display_name') + ->where('display_name IS NOT NULL') + ->where('is_active', 1) + ->findAll(); + + $result = []; + + foreach ($ticketClaimStatus as $row) { + $name = $row['display_name']; + $id = $row['id']; + + if (!isset($result[$name])) { + $result[$name] = []; + } + + $result[$name][] = $id; + } + + return $result; + } + + // not in use did for testing function encrypt_for_sso(): string { diff --git a/app/Controllers/InsuranceCommissionController.php b/app/Controllers/InsuranceCommissionController.php index 11f61daa..3798237a 100644 --- a/app/Controllers/InsuranceCommissionController.php +++ b/app/Controllers/InsuranceCommissionController.php @@ -118,26 +118,28 @@ class InsuranceCommissionController extends AdminController if (json_last_error() !== JSON_ERROR_NONE) { throw new \Exception('Invalid JSON in rules file: ' . json_last_error_msg()); } - + // print_r($parsed);die(); // Normalise department keys to lowercase for consistent lookups $this->rules = []; foreach ($parsed as $dept => $rules) { $this->rules[strtolower($dept)] = $rules; } + + // print_r($this->rules);die(); } public function calculateCommission(array $policyData) { $department = $policyData['department'] ?? ''; $deptKey = strtolower($department); - - if (!isset($this->rules[$deptKey])) { - throw new \Exception("No rules found for department: {$department}"); - } + // print_r($this->rules);die(); + // if (!isset($this->rules[$deptKey])) { + // throw new \Exception("No rules found for department: {$department}"); + // } $matchingRules = []; - foreach ($this->rules[$deptKey] as $rule) { + foreach ($this->rules as $rule) { if ($this->evaluateConditions($rule['conditions'] ?? [], $policyData)) { $matchingRules[] = $rule; } @@ -146,7 +148,7 @@ class InsuranceCommissionController extends AdminController if (empty($matchingRules)) { throw new \Exception('No matching rules found for the policy data'); } - + // print_r($matchingRules);die; // Use the first matching rule. In future you can implement priority/weighting $applicableRule = $matchingRules[0]; diff --git a/app/Controllers/MediAssistApiController.php b/app/Controllers/MediAssistApiController.php index 4e13298c..621a187f 100644 --- a/app/Controllers/MediAssistApiController.php +++ b/app/Controllers/MediAssistApiController.php @@ -331,6 +331,7 @@ class MediAssistApiController extends BaseController $db = \Config\Database::connect(); $updated = 0; + $employee_policy_ids = []; foreach ($employeePolicyData as $policy_data) { foreach ($allBenef as $row) { @@ -370,6 +371,10 @@ class MediAssistApiController extends BaseController WHERE id = ?"; $db->query($sql, [$row['benefMediAssistID'], $policy_data['emp_policy_id']]); + // for e-card send + if(strtolower(trim($policy_data['relationship'])) == 'self'){ + $employee_policy_ids[] = $policy_data['emp_policy_id']; + } if ($db->affectedRows() > 0) { $updated++; @@ -384,6 +389,12 @@ class MediAssistApiController extends BaseController } } + // send e-card + if(!empty($employee_policy_ids)){ + log_message('error', "sendMailForDownloadingECard JOB PUSHED."); + Jobs::addJob(['job_name' => 'sendMailForDownloadingECard', 'payload' => $employee_policy_ids]); + } + // update file table status after the tpa id successfully updated if (isset($requestData['file_id']) && !empty($requestData['file_id'])) { $file_model = new BatchFileModel(); diff --git a/app/Controllers/PayoutController.php b/app/Controllers/PayoutController.php index 06762fd8..02bbe1b2 100644 --- a/app/Controllers/PayoutController.php +++ b/app/Controllers/PayoutController.php @@ -81,6 +81,7 @@ class PayoutController extends BaseController // for list $data['payout_status'] = $this->payout_status; $data['agent_list'] = $this->invoiceModel->agentList(); + $data['page_name'] = "Payout"; $payout_data['payout_list_data'] = $this->invoiceModel->invoiceList(); $data['payout_list'] = view('payout_list', $payout_data); diff --git a/app/Controllers/RuleImportController.php b/app/Controllers/RuleImportController.php index a3162499..f5579aac 100644 --- a/app/Controllers/RuleImportController.php +++ b/app/Controllers/RuleImportController.php @@ -1,13 +1,48 @@ myLogger = \Config\Services::mylogger(); $this->ruleImportService = \Config\Services::ruleImportService(); + + $this->commissionFilesModel = new CommissionFilesModel(); + $this->insurerModel = new InsurerModel(); + $this->departments = [ + 'motor' => 'Motor', + 'health' => 'Health', + ]; + } + + public function commissionFileUploadList() + { + $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); } /** @@ -21,7 +56,7 @@ class RuleImportController extends AdminController try { $file = $this->request->getFile('rules_file'); if (!$file || !$file->isValid()) { - return $this->response->setJSON(['status'=>'error','message'=>'No file uploaded or upload error']); + return $this->response->setJSON(['status'=>false,'message'=>'No file uploaded or upload error']); } // Move uploaded file to writable temp location @@ -42,53 +77,42 @@ class RuleImportController extends AdminController return $this->response->setJSON($result); } catch (\Throwable $e) { - log_message('critical', 'RuleImportController::upload ' . $e->getMessage()); - return $this->response->setJSON(['status'=>'exception','message'=>$e->getMessage()]); + $this->myLogger->logme('error', 'RuleImportController::upload ' . $e->getMessage()); + return $this->response->setJSON(['status'=>false,'message'=>$e->getMessage()]); } } public function upload() { - // Make sure filesystem helpers available if you need them - helper(['filesystem']); - - // CommissionFilesModel – adjust namespace if different - $commissionFilesModel = new \App\Models\CommissionFilesModel(); - try { + // --------------------------------------------------------- // 1. Get uploaded file // --------------------------------------------------------- $file = $this->request->getFile('rules_file'); if (!$file || !$file->isValid()) { - log_message('warning', 'RuleImportController::upload - No file or invalid upload.'); - return $this->respond([ - 'status' => 'error', - 'message' => 'No file uploaded or upload error.' - ], 400); + $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); } // --------------------------------------------------------- // 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'); - $createdBy = $this->request->getPost('created_by'); + $overwrite = $this->request->getPost('overwrite') ?? 1; + $createdBy = get_session_userid(); - if (empty($insurerId) || empty($department) || empty($commissionMonth) || empty($createdBy)) { - log_message('warning', 'RuleImportController::upload - Missing required POST data.', [ - 'insurer_id' => $insurerId, - 'department' => $department, - 'commission_month' => $commissionMonth, - 'created_by' => $createdBy, - ]); - return $this->respond([ - 'status' => 'error', - 'message' => 'Missing required fields: insurer_id, department, commission_month, created_by.' - ], 400); + 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'; @@ -111,19 +135,18 @@ class RuleImportController extends AdminController // sanitize user file name but keep it deterministic (no random, no timestamp) $safeName = preg_replace('/[^a-zA-Z0-9_\-\.]/', '_', $postedFileName); - $targetFileName = $safeName; - $movedFullPath = $uploadDir . $targetFileName; + + // $movedFullPath = $uploadDir . $safeName; - $file->move($uploadDir, $targetFileName); + $file->move($uploadDir, $safeName); + $targetFileName = $file->getName(); + $movedFullPath = $uploadDir . $targetFileName; if (!file_exists($movedFullPath)) { - log_message('error', "RuleImportController::upload - Failed to move uploaded file to {$movedFullPath}"); - return $this->respond([ - 'status' => 'error', - 'message' => 'Failed to store uploaded file.' - ], 500); + $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); } - log_message('info', "RuleImportController::upload - File moved to {$movedFullPath}"); + $this->myLogger->logme('info', "RuleImportController::upload - File moved to {$movedFullPath}"); // --------------------------------------------------------- // 4. Insert commission_files row with status pending @@ -132,7 +155,7 @@ class RuleImportController extends AdminController 'file_name' => $targetFileName, 'insurer_id' => (int)$insurerId, 'department' => $department, - 'commission_month'=> $commissionMonth, + 'commission_month' => $commissionMonth, 'rules_count' => 0, // will update on success 'file_status' => $fileStatus, // 'pending' by default 'is_active' => $isActive, @@ -140,18 +163,19 @@ class RuleImportController extends AdminController 'created_at' => date('Y-m-d H:i:s'), ]; - $commissionFilesModel->insert($insertData); - $insertId = $commissionFilesModel->getInsertID(); + $this->commissionFilesModel->insert($insertData); + $insertId = $this->commissionFilesModel->getInsertID(); if (empty($insertId)) { - log_message('error', 'RuleImportController::upload - Failed to insert commission_files record', ['data' => $insertData]); + $this->myLogger->logme('error', 'RuleImportController::upload - Failed to insert commission_files record', ['data' => $insertData]); return $this->respond([ - 'status' => 'error', + 'status' => false, + 'code' => 404, 'message' => 'Failed to record upload in database.' - ], 500); + ], 200); } - log_message('info', "RuleImportController::upload - commission_files inserted id={$insertId}", $insertData); + $this->myLogger->logme('info', "RuleImportController::upload - commission_files inserted id={$insertId}", $insertData); // --------------------------------------------------------- // 5. Call ruleImportService->processUpload with inserted file info @@ -172,22 +196,23 @@ class RuleImportController extends AdminController 'commission_month' => $commissionMonth, ]; - log_message('info', 'RuleImportController::upload - Calling ruleImportService->processUpload', ['payload' => $payload]); + $this->myLogger->logme('info', 'RuleImportController::upload - Calling ruleImportService->processUpload', ['payload' => $payload]); $result = $this->ruleImportService->processUpload($payload); if (!is_array($result) || !isset($result['status'])) { - log_message('error', 'RuleImportController::upload - Invalid service response', ['response' => $result]); + $this->myLogger->logme('error', 'RuleImportController::upload - Invalid service response', ['response' => $result]); // update file status as failed - $commissionFilesModel->update($insertId, [ + $this->commissionFilesModel->update($insertId, [ 'file_status' => 'failed', 'updated_by' => (int)$createdBy, 'updated_at' => date('Y-m-d H:i:s'), ]); return $this->respond([ - 'status' => 'error', + 'status' => false, + 'code' => 404, 'message' => 'Invalid response from import service.' - ], 500); + ], 200); } // --------------------------------------------------------- @@ -202,56 +227,123 @@ class RuleImportController extends AdminController $rulesCount = count($rulesArray); // Save JSON to WRITEPATH . 'uploads/commission/json/{insurer_id}_{department}.json' - $jsonDir = WRITEPATH . 'uploads/commission/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) { - log_message('error', 'RuleImportController::upload - json_encode failed for rules', [ + $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 - $commissionFilesModel->update($insertId, [ + $this->commissionFilesModel->update($insertId, [ 'file_status' => 'failed', 'updated_by' => (int)$createdBy, 'updated_at' => date('Y-m-d H:i:s'), ]); return $this->respond([ - 'status' => 'error', + 'status' => false, + 'code' => 404, 'message' => 'Failed to encode rules as JSON.' - ], 500); + ], 200); } - if (file_put_contents($jsonPath, $jsonData) === false) { - log_message('error', 'RuleImportController::upload - Failed to write rules JSON file', ['json_path' => $jsonPath]); - $commissionFilesModel->update($insertId, [ + // handle existing JSON file based on $override (bool) + if (file_exists($jsonPath)) { + if ($overwrite) { + // delete existing file before writing (deterministic overwrite) + if (!@unlink($jsonPath)) { + $this->myLogger->logme('warning', 'RuleImportController::upload - Failed to delete existing JSON before overwrite', ['json_path' => $jsonPath]); + // proceed to overwrite anyway by writing to the same path + } + $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' => 'error', + 'status' => false, + 'code' => 404, 'message' => 'Failed to store rules JSON file.' ], 500); } - log_message('info', 'RuleImportController::upload - Rules JSON written', [ + // 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 - $commissionFilesModel->update($insertId, [ - 'file_status' => 'processed', + $this->commissionFilesModel->update($insertId, [ + 'file_status' => 'success', 'rules_count' => $rulesCount, 'updated_by' => (int)$createdBy, 'updated_at' => date('Y-m-d H:i:s'), @@ -260,7 +352,8 @@ class RuleImportController extends AdminController ]); return $this->respond([ - 'status' => 'success', + 'status' => true, + 'code' => 200, 'message' => 'File processed successfully.', 'file_id' => $insertId, 'rules_count' => $rulesCount, @@ -280,7 +373,7 @@ class RuleImportController extends AdminController $errors = $result['errors'] ?? []; $updateData = [ - 'file_status' => 'validation_failed', + 'file_status' => 'failed', 'rules_count' => 0, // do not save rules 'updated_by' => (int)$createdBy, 'updated_at' => date('Y-m-d H:i:s'), @@ -291,15 +384,16 @@ class RuleImportController extends AdminController $updateData['annotated_file_path'] = $annotatedPath; } - $commissionFilesModel->update($insertId, $updateData); + $this->commissionFilesModel->update($insertId, $updateData); - log_message('warning', "RuleImportController::upload - Validation failed for file_id={$insertId}", [ + $this->myLogger->logme('error', "RuleImportController::upload - Validation failed for file_id={$insertId}", [ 'errors' => $errors, 'annotated_file' => $annotatedPath ]); return $this->respond([ - 'status' => 'error', + 'status' => false, + 'code' => 404, 'message' => 'Validation failed. No rules saved.', 'file_id' => $insertId, 'errors' => $errors, @@ -310,41 +404,242 @@ class RuleImportController extends AdminController // --------------------------------------------------------- // 8. Unexpected status // --------------------------------------------------------- - log_message('error', 'RuleImportController::upload - Unexpected result status from service', ['result' => $result]); - $commissionFilesModel->update($insertId, [ + $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' => 'error', - 'message' => 'Unexpected import service result.' - ], 500); - + 'status' => false, + 'code' => 404, + 'message' => $result['message'] + ], 200); } catch (\Throwable $ex) { - log_message('critical', 'RuleImportController::upload exception: ' . $ex->getMessage(), [ + $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 { - $commissionFilesModel->update($insertId, [ + $this->commissionFilesModel->update($insertId, [ 'file_status' => 'failed', - 'updated_by' => isset($createdBy) ? (int)$createdBy : null, + 'updated_by' => get_session_userid(), 'updated_at' => date('Y-m-d H:i:s'), 'notes' => 'Upload exception: ' . $ex->getMessage(), ]); } catch (\Throwable $e2) { - log_message('error', 'RuleImportController::upload - failed to update commission_files after exception: ' . $e2->getMessage()); + $this->myLogger->logme('error', 'RuleImportController::upload - failed to update commission_files after exception: ' . $e2->getMessage()); } } return $this->respond([ - 'status' => 'exception', + '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->removeCommissionRules($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 deActiveCommissionRules($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); + + // 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); + // dd($rules); + + 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; + foreach ($rules as &$rule) { + if (!isset($rule['is_deleted']) && isset($rule['file_id']) && $rule['file_id'] == $id) { + $rule['is_deleted'] = true; // <-- NEW FEATURE + $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", "Rule marked deleted and file updated: $filePath"); + + return [ + 'status' => true, + 'message' => 'Rule marked as deleted and file updated successfully' + ]; + } + + 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); + } + } + + } diff --git a/app/Models/ClientPolicyModel.php b/app/Models/ClientPolicyModel.php index 185f4a20..2d37d053 100755 --- a/app/Models/ClientPolicyModel.php +++ b/app/Models/ClientPolicyModel.php @@ -57,6 +57,8 @@ class ClientPolicyModel extends Model "placement_json", "policy_entry_from", "is_from_lead", + "wellness_plan_id", + "wellness_vendor_id", ]; // Callbacks diff --git a/app/Models/CommissionFilesModel.php b/app/Models/CommissionFilesModel.php index 99a44a8b..9ddf1e35 100644 --- a/app/Models/CommissionFilesModel.php +++ b/app/Models/CommissionFilesModel.php @@ -21,6 +21,7 @@ class CommissionFilesModel extends Model 'is_active', 'created_by', 'updated_by', + 'rules_count', ]; // Auto timestamps by CI4 @@ -28,6 +29,39 @@ class CommissionFilesModel extends Model protected $createdField = 'created_at'; protected $updatedField = 'updated_at'; + // Callbacks + protected $allowCallbacks = true; + protected $beforeInsert = ["checkAndADDCreatedByValue"]; + protected $afterInsert = []; + protected $beforeUpdate = ["checkAndUpdateUpdatedByValue"]; + protected $afterUpdate = []; + protected $beforeFind = []; + protected $afterFind = []; + protected $beforeDelete = []; + protected $afterDelete = []; + + protected function checkAndADDCreatedByValue(array $data) + { + // Check if 'updated_by' value is null or empty + if (empty($data['data']['created_by'])) { + // Set 'updated_by' value to the current session user ID + $data['data']['created_by'] = get_session_userid(); + } + + return $data; + } + + protected function checkAndUpdateUpdatedByValue(array $data) + { + // Check if 'updated_by' value is null or empty + if (empty($data['data']['updated_by'])) { + // Set 'updated_by' value to the current session user ID + $data['data']['updated_by'] = get_session_userid(); + } + + return $data; + } + // Validation rules (optional) // protected $validationRules = [ // 'file_name' => 'required|min_length[1]|max_length[100]', diff --git a/app/Views/client_policy.php b/app/Views/client_policy.php index fdb0c39e..cb197be9 100755 --- a/app/Views/client_policy.php +++ b/app/Views/client_policy.php @@ -235,7 +235,7 @@ input:checked + .slider_blue::before {