nhance/app/Controllers/ClientAPIController.php
2025-04-16 11:05:18 +05:30

311 lines
12 KiB
PHP

<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\API\ResponseTrait;
use App\Helpers\ClientTokenHelper;
use App\Helpers\ClientQueryHelper;
use App\Models\ClientApiModel;
use App\Models\ClientPolicyModel;
use App\Controllers\TicketController;
class ClientAPIController extends BaseController
{
use ResponseTrait;
protected $clientAPI;
protected $clientPolicy;
protected $myLogger;
protected $clientQueryHelper;
protected $clientTokenHelper;
protected $ticketController;
protected $operators;
protected $propertyNames;
public function __construct()
{
set_session_context('Client API Controller');
$this->myLogger = \Config\Services::mylogger();
//models
$this->clientAPI = new ClientApiModel();
$this->clientPolicy = new ClientPolicyModel();
//helper
$this->clientQueryHelper = new ClientQueryHelper();
//controller
$this->ticketController = new TicketController();
//variables
$this->operators = [
"GT" => ">",
"LT" => "<",
"GTE" => ">=",
"LTE" => "<=",
"ET" => "=",
"NE" => "!=",
"LIKE" => "LIKE",
"NL" => "NOT LIKE",
"BTW" => "BETWEEN",
"NB" => "NOT BETWEEN",
"IS" => "IS NULL",
"ISN" => "IS NOT NULL",
];
$this->propertyNames = [
'empMaster' => ['name','emp_code','relationship','client_branch_id','emp_status','mobile','email_corporate','change_event','dob','doj','band','gender'],
'claimMaster' => ['emp_name','insured_name',"emp_code",'policy_no','emp_mobile','emp_mail','hospital_name','claim_type','claim_status','claim_no','claim_amount','claim_date','si_amt','raised_date','registration_date','denial_date','denial_reason','approved_amount','utr_details','return_remark','cancel_remark','non_id_reason','head_rejection_reason'],
];
}
public function validateToken()
{
try {
$authHeader = $this->request->getHeaderLine('Authorization');
// Check if header exists
if (empty($authHeader)) {
$this->myLogger->log('error', 'Authorization header missing');
return $this->respond(['status' => "Failure", 'error' => ['message' => 'Authorization header missing', 'code' => 401]], 401);
}
// Check if Bearer is present
if (!str_contains($authHeader, 'Bearer ')) {
$this->myLogger->log('error', 'Authorization Bearer missing');
return $this->respond(['status' => "Failure", 'error' => ['message' => 'Invalid Authorization header', 'code' => 401]], 401);
}
// Extract the token
$token = str_replace('Bearer ', '', $authHeader);
if (empty($token)) {
$this->myLogger->log('error', 'Empty Token');
return $this->respond(['status' => "Failure", 'error' => ['message' => 'Invalid Token Format', 'code' => 401]], 401);
}
try {
// Extract client_id from the token
$client_id = ClientTokenHelper::extractClientId($token);
} catch (\Exception $e) {
$this->myLogger->log('error', 'Invalid Client Token Format');
return $this->respond(['status' => "Failure", 'error' => 'Invalid Token Format'], 401);
}
// Fetch client details from the database
$client = $this->clientAPI->where('client_id', $client_id)->where("is_active", 1)->where("api_access", 1)->first();
// Client validation
if (!$client) {
$this->myLogger->log('error', 'Client Not Found or Unauthorized');
return $this->respond(['status' => "Failure", 'error' => ['message' => 'Client not found or unauthorized', 'code' => '403']], 403);
}
// Validate the token
if (hash_equals($client['client_token'], $token)) {
$this->myLogger->log('error', 'Access Granted For Client : ' . $client_id);
return true;
} else {
$this->myLogger->log('error', 'Invalid Token given for client : ' . $client_id);
return $this->respond([
'status' => "Failure",
'error' => ['message' => 'Invalid token', 'code' => 401]
], 401);
}
} catch (\Exception $e) {
log_message('error', 'Error in ClientAPIController:validateToken - ' . $e->getMessage());
return $this->respond(['status' => "Failure", 'error' => ['message' => 'Internal Server Error', 'code' => 500]], 500);
}
}
public function getClientIdfromToken()
{
$authHeader = $this->request->getHeaderLine('Authorization');
$token = str_replace('Bearer ', '', $authHeader);
$client_id = ClientTokenHelper::extractClientId($token);
$this->myLogger->log('error', 'Client ID: ' . $client_id);
return [$client_id, $token];
}
public function sendPolicyMaster()
{
$data = $this->getClientIdfromToken();
$client_id = $data[0];
$keyString = $data[1];
// Extract only the actual key (after colon)
// list($prefix, $hexKey) = explode(':', $keyString, 2);
// // Convert hex to binary (32 bytes)
// $key = hex2bin($hexKey);
$clientPolicy = $this->clientQueryHelper->clientPolicyMaster($client_id);
$this->myLogger->log('error', 'Client Policy Master: ' . json_encode($clientPolicy));
// $encode_data = ClientTokenHelper::encryptData($clientPolicy, $key);
// return $this->respond(['status' => "Success", 'data' => $encode_data], 200);
return $this->respond(['status' => "Success", 'data' => $clientPolicy], 200);
}
public function sendEmpMaster()
{
$data = $this->getClientIdfromToken();
$client_id = $data[0];
$keyString = $data[1];
$received_data = $this->request->getJSON();
$filters = $received_data->filters ?? null;
$limit = $received_data->limit ?? null;
$after = $received_data->after ?? 0;
if ($limit > getenv('MAX_LIMIT')) {
$this->myLogger->log('error', "Limit exceeds maximum allowed limit");
return $this->respond(['status' => "Failure", 'error' => ['message' => 'Limit exceeds maximum allowed limit', 'code' => 400]], 400);
}
try{
if (!empty($filters)) {
$whereConditions = $this->prepareWhereConditions($filters,"",'empMaster');
$employees = $this->clientQueryHelper->sendEmpMaster($client_id, $whereConditions,!empty($limit) ? $limit : 10,$after);
}else{
$employees = $this->clientQueryHelper->sendEmpMaster($client_id, [],!empty($limit) ? $limit : 10,$after);
}
}catch (\InvalidArgumentException $e) {
return $this->respond(['status' => "Failure",'error' => ['message' => $e->getMessage(), 'code' => 400]], 400);
}
foreach ($employees as &$employee){
$employee['policy_details'] = $this->clientQueryHelper->sendEmpPolicies($employee['ref_no']);
}
$next_after = (count($employees) < $limit) ? null : ($after + $limit);
if (!empty($employees)){
return $this->respond(['Status' => "Success","data" => $employees,'next_after'=>$next_after], 200);
}else{
return $this->respond(['Status' => "Failure","error" => ['message' => 'No Employees Found', 'code' => 404]], 404);
}
}
public function sendClaimMaster()
{
$policy_type = $this->ticketController->ticketType;
$data = $this->getClientIdfromToken();
$client_id = $data[0];
$keyString = $data[1];
$received_data = $this->request->getJSON();
$filters = $received_data->filters ?? null;
$limit = $received_data->limit ?? null;
$after = $received_data->after ?? 0;
if ($limit > getenv('MAX_LIMIT')) {
$this->myLogger->log('error', "Limit exceeds maximum allowed limit");
return $this->respond(['status' => "Failure", 'error' => ['message' => 'Limit exceeds maximum allowed limit', 'code' => 400]], 400);
}
try{
if (!empty($filters)) {
$whereConditions = $this->prepareWhereConditions($filters,"ticket_master",'claimMaster');
$claimDetails = $this->clientQueryHelper->sendClaimMaster($client_id,$whereConditions,!empty($limit) ? $limit : 10);
}else{
$claimDetails = $this->clientQueryHelper->sendClaimMaster($client_id, [],!empty($limit) ? $limit : 10);
}
} catch (\InvalidArgumentException $e) {
return $this->respond(['status' => "Failure",'error' => ['message' => $e->getMessage(), 'code' => 400]], 400);
}
foreach ($claimDetails as &$claim){
$claim['policy_type'] = $policy_type[$claim['policy_type']];
}
// dd($claimDetails);
$next_after = (count($claimDetails) < $limit) ? null : ($after + $limit);
if (!empty($claimDetails)){
return $this->respond(['Status' => "Success","data" => $claimDetails,'next_after'=>$next_after], 200);
}else{
return $this->respond(['Status' => "Failure","error" => ['message' => 'No Claims Found', 'code' => 404]], 404);
}
}
public function prepareWhereConditions($filters,$tableName = null,$model)
{
$whereConditions = [];
foreach ($filters as $filter) {
$propertyName = $filter->propertyName;
$operator = $filter->operator;
$this->myLogger->log('error', 'Property Name: ' . $propertyName);
if (!in_array($operator, array_keys($this->operators))) {
$this->myLogger->log('error', 'Invalid operator: ' . $operator);
throw new \InvalidArgumentException('Invalid operator');
}
if (!in_array($propertyName, $this->propertyNames[$model])) {
$this->myLogger->log('error', 'Invalid property name: ' . $propertyName);
throw new \InvalidArgumentException('Invalid property name '.$propertyName);
}
$value = isset($filter->value) ? $filter->value : null;
$sqlOperator = $this->operators[$operator];
$column = !empty($tableName) ? "{$tableName}.{$propertyName}" : $propertyName;
if ($sqlOperator === '=') {
$whereConditions[$column] = $value;
} else if($sqlOperator == "LIKE" || $sqlOperator == "NOT LIKE") {
$whereConditions["{$column} {$sqlOperator}"] = "%{$value}%";
} else if ($sqlOperator == 'BETWEEN') {
if (is_array($value) && count($value) === 2) {
// $whereConditions[] = [$column, $sqlOperator, $value[0]];
$whereConditions["{$column} >="] = $value[0];
$whereConditions["{$column} <="] = $value[1];
} else {
return $this->respond(['status' => "Failure", 'error' => ['message' => 'Invalid value for BETWEEN operator', 'code' => 400]], 400);
}
}else if ($sqlOperator == 'NOT BETWEEN') {
if (is_array($value) && count($value) === 2) {
$whereConditions["{$column} <="] = $value[0];
$whereConditions["{$column} >="] = $value[1];
} else {
return $this->respond(['status' => "Failure", 'error' => ['message' => 'Invalid value for NOT BETWEEN operator', 'code' => 400]], 400);
}
}else {
$whereConditions["{$column} {$sqlOperator}"] = $value;
}
}
return $whereConditions;
}
}