From 6d855d95ac3b9da87c100de96af5b132c4b461a5 Mon Sep 17 00:00:00 2001 From: Srinivas-Saravanan Date: Wed, 16 Apr 2025 11:05:18 +0530 Subject: [PATCH 01/42] FEAT_CLIENT_API_FIRST_COMMIT_SRI --- app/Config/Filters.php | 2 + app/Config/Routes.php | 15 + app/Controllers/ClientAPIController.php | 310 +++++++++++++ app/Controllers/ClientController.php | 41 +- app/Controllers/ClientWebHooksController.php | 319 +++++++++++++ app/Filters/AuthClientApi.php | 87 ++++ app/Helpers/ClientQueryHelper.php | 100 ++++ app/Helpers/ClientTokenHelper.php | 54 +++ app/Helpers/clientWebHookHelper.php | 39 ++ app/Models/ClientApiModel.php | 45 ++ app/Views/client_api.php | 452 +++++++++++++++++++ app/Views/client_onboarding.php | 9 +- app/Views/testWebhook.php | 1 + 13 files changed, 1471 insertions(+), 3 deletions(-) create mode 100644 app/Controllers/ClientAPIController.php create mode 100644 app/Controllers/ClientWebHooksController.php create mode 100644 app/Filters/AuthClientApi.php create mode 100644 app/Helpers/ClientQueryHelper.php create mode 100644 app/Helpers/ClientTokenHelper.php create mode 100644 app/Helpers/clientWebHookHelper.php create mode 100644 app/Models/ClientApiModel.php create mode 100644 app/Views/client_api.php create mode 100644 app/Views/testWebhook.php diff --git a/app/Config/Filters.php b/app/Config/Filters.php index 0855ec3e..2cf9a260 100755 --- a/app/Config/Filters.php +++ b/app/Config/Filters.php @@ -12,6 +12,7 @@ use CodeIgniter\Filters\SecureHeaders; use App\Filters\AuthMVC; use App\Filters\HttpRequestLog; use App\Filters\CloseDbConnection; +use App\Filters\AuthClientApi; use App\Filters\AuthJWT; @@ -34,6 +35,7 @@ class Filters extends BaseConfig 'authMVC' => AuthMVC::class, 'HttpRequestLog' => HttpRequestLog::class, 'authJWT' => AuthJWT::class, + 'AuthClientApi' => AuthClientApi::class, 'CloseDbConnection' => CloseDbConnection::class ]; diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 45619181..d2802469 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -87,6 +87,8 @@ $routes->group("/client", ["filter" => "authMVC"], function ($routes) { $routes->get('view_deposit/(:num)', 'ClientController::view_Deposit/$1'); $routes->get('createtransaction', 'ClientController::createtransaction'); $routes->post('save_deposit', 'ClientController::saveDeposit'); + $routes->post("saveApiData", "ClientController::saveApiData"); + $routes->get("generateToken","ClientController::sendToken"); // $routes->get('view_Deposit/(:num)/(:num)','ClientController/view_Deposit/$1/$2'); $routes->group("notification", ["filter" => "authMVC"], function ($routes) { @@ -553,3 +555,16 @@ $routes->group("/ticket", ["filter" => "authMVC"], function ($routes) { // $routes->post('ticket_messages','TicketController::getTicketMessage'); }); +$routes->group("clientApi",["filter" => "AuthClientApi"], function ($routes){ + + $routes->post("getPolicyMaster","ClientAPIController::sendPolicyMaster"); + $routes->post("getEmployeeMaster","ClientAPIController::sendEmpMaster"); + $routes->post("getClaimMaster","ClientAPIController::sendClaimMaster"); + // $routes->post("pushData","ClientWebHooksController::sendSample"); +}); + +$routes->post("dispatchWebhookData/(:any)/(:any)",'ClientWebHooksController::pushData/$1/$2'); + + +$routes->post("retrieveWebhookDataEmp","ClientWebHooksController::pullData_emp"); +$routes->post("retrieveWebhookDataClaim","ClientWebHooksController::pullData_claim"); diff --git a/app/Controllers/ClientAPIController.php b/app/Controllers/ClientAPIController.php new file mode 100644 index 00000000..4a6bff4f --- /dev/null +++ b/app/Controllers/ClientAPIController.php @@ -0,0 +1,310 @@ +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; + } + +} diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index 21f0afa5..0fd70edc 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -4,6 +4,7 @@ namespace App\Controllers; use App\Helpers\DepositHelper; use App\Helpers\MailHelper; +use App\Helpers\ClientTokenHelper; use App\helpers\JWTToken; use CodeIgniter\HTTP\IncomingRequest; use CodeIgniter\HTTP\RequestInterface; @@ -39,6 +40,7 @@ use App\Models\PolicyTransactionModel; use App\Models\PolicyTransactionStatusModel; use App\Models\VehicleModel; use App\Models\LeadsModel; +use App\Models\ClientApiModel; use App\Controllers\EmpDataServiceController; use App\Controllers\GoogleDriveController; @@ -83,7 +85,7 @@ class ClientController extends AdminController protected $policyTransactionStatusModel; protected $vehicleModel; protected $leadsModel; - + protected $clientApi; public function __construct() @@ -119,6 +121,7 @@ class ClientController extends AdminController $this->policyTransactionStatusModel = new PolicyTransactionStatusModel(); $this->vehicleModel = new VehicleModel(); $this->leadsModel = new LeadsModel(); + $this->clientApi = new ClientApiModel(); } //-------------------------------------------------------------------------------------------------------- @@ -751,7 +754,7 @@ class ClientController extends AdminController $editData['client_policy']['role'] = get_role_id(); $editData['notification'] = $this->notificationModel->select('template_name,enabled')->where('client_id', $id)->findAll(); $editData['placeHolders'] = ['member_name', 'member_mobile', 'nhance_logo', 'tpa_id', 'ecard_download_link', 'client_logo', 'policy_no', 'member_summary', 'app_link', 'post_enrollment_app_link', 'client_name']; - + $editData['api_data'] = $this->clientApi->where("client_id", $id)->where("is_active",1)->first(); // dd($editData); echo view('layout/header', $headerData); echo view('client_onboarding', $editData); @@ -5683,6 +5686,40 @@ class ClientController extends AdminController return $result; } + public function saveApiData(){ + + $receivedData = $this->request->getPost(); + + if (!empty($receivedData['id'])){ + $status = $this->clientApi->save($receivedData); + + }else{ + $status = $this->clientApi->insert($receivedData); + } + + + if ($status){ + return $this->respond(['status'=>"Sucesss",'message'=>"Submitted Successfully"],200); + }else{ + return $this->respond(['status'=>"Failed",'message'=>"Submission Faild"],500); + } + + } + + public function sendToken(){ + + $client_id = $this->request->getGet('client_id'); + + $token = ClientTokenHelper::generateKey($client_id); + + if ($token){ + return $this->respond(['status' => 'success', 'token' => $token,'message' => "Token Generated Successfully"],200); + }else{ + return $this->respond(['status' => "Failed","message"=>"Token Generation Failed, Try Again After some time"],500); + } + } } + + diff --git a/app/Controllers/ClientWebHooksController.php b/app/Controllers/ClientWebHooksController.php new file mode 100644 index 00000000..a54deaf2 --- /dev/null +++ b/app/Controllers/ClientWebHooksController.php @@ -0,0 +1,319 @@ +myLogger = \Config\Services::mylogger(); + + //models + $this->clientAPI = new ClientApiModel(); + $this->clientPolicy = new ClientPolicyModel(); + + // Helpers + $this->webHookHelper = new clientWebHookHelper(); + $this->clientTokenHelper = new ClientTokenHelper(); + } + + public function pushData($clientID, $type) + { + if ($type == 1) { + + $webHookType = "emp"; + } else if ($type == 2) { + + $webHookType = "claim"; + } + log_message('error', 'Client ID: ' . $clientID); + log_message('error', 'Webhook Type: ' . $webHookType); + // Validate client ID + if (empty($clientID)) { + return $this->respond(["status" => "Failure", "error" => ["message" => 'Client ID is required.', "code" => 400]], 400); + } + $webhookData = $this->clientAPI->where('client_id', $clientID)->where('is_active', 1)->first(); + if (empty($webhookData)) { + log_message('error', 'Client Not Found or Unauthorized'); + return $this->respond(["status" => "Failure", "error" => ["message" => 'Client Not Found or Client Does not have any Active Hooks.', "code" => 404]], 404); + } + $url = $webhookData[$webHookType . '_url']; + if (empty($url)) { + log_message('error', 'No active webhook found for the client.'); + return $this->respond(["status" => "Failure", "error" => ["message" => 'No active webhook found for the client.', "code" => 404]], 404); + } + + + $method = $webhookData[$webHookType . '_method']; + $auth_method = $webhookData[$webHookType . '_tkn_type']; + $token = $webhookData[$webHookType . '_token']; + $objectType = json_decode($webhookData[$webHookType . '_obj']); + + try { + $client = \Config\Services::curlrequest(); + $data = [ + "name" => "Kavitha", + "emp_code" => "EMP001-K4", + "emp_status" => "active", + "mobile" => "2233448965" + ]; + + try { + $mapped_data = $this->webHookHelper->mapObjectType($data, $objectType); + } catch (Exception $e) { + $errorMessage = "Object Mapping Failed: " . $e->getMessage(); + log_message('error', $errorMessage); + + return $this->respond(['status' => 'Failure', 'error' => ['code' => 500, 'message' => "Object Mapping Failed"]], 500); + } + + // Create payload + $payload = [ + 'event_type' => 'insert', + 'timestamp' => date('c'), + 'data' => $mapped_data + ]; + + log_message("error", "Payload: " . json_encode($payload)); + + // Configure request headers + $headers = ['Content-Type' => 'application/json']; + if ($auth_method && $token) { + if (strtolower($auth_method) === 'bearer') { + $headers['Authorization'] = 'Bearer ' . $token; + } else { + $headers[$auth_method] = $token; + } + } + + // Configure request based on method + $options = [ + 'headers' => $headers, + 'timeout' => 10, + 'http_errors' => false // Don't throw exceptions for 4xx/5xx responses + ]; + + if ($method === 'GET') { + $options['query'] = $payload; + } else { + $options['json'] = $payload; + } + + // Execute webhook request + $response = $client->request($method, $url, $options); + $statusCode = $response->getStatusCode(); + $responseBody = $response->getBody(); + + // Log and format response + $logMessage = "Webhook to {$url} returned status: {$statusCode}"; + log_message('error', $logMessage); + + return $this->respond(['status' => 'Success', "response" => $responseBody], $statusCode); + } catch (\Throwable $e) { + $errorMessage = "Webhook failed: " . $e->getMessage(); + log_message('error', $errorMessage); + + return $this->respond(['status' => 'Failure', 'error' => ['code' => 500, 'message' => $errorMessage, 'exception' => get_class($e)]], 500); + } + } + + public function validateToken($type) + { + $type = $type == 1 ? "pull_emp_token" : "pull_claim_token"; + try { + + $authHeader = $this->request->getHeaderLine('Authorization'); + + // Check if header exists + if (empty($authHeader)) { + log_message('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 ')) { + log_message('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)) { + + log_message('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) { + log_message('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) { + log_message('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[$type], $token)) { + log_message('error', 'Access Granted For Client : ' . $client_id); + return true; + } else { + log_message('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); + + log_message('error', 'Client ID: ' . $client_id); + return [$client_id, $token]; + } + + public function pullData_emp() + { + $validationStatus = $this->validateToken(1); + + $data = $this->getClientIdfromToken(); + $client_id = $data[0]; + + log_message('error', "Pull data emp from Client ID: ". $client_id); + $client = $this->clientAPI->where('client_id', $client_id)->where("is_active", 1)->where("api_access", 1)->first(); + if (empty($client)) { + log_message('error', 'Client Not Found or Unauthorized'); + return $this->respond(['status' => 'Failure', 'error' => ['code' => 404, 'message' => 'Client Not Found or Unauthorized']], 404); + } + + $objectType = $client['pull_emp_obj']; + + if ($validationStatus) { + $responseBody = $this->request->getBody(); + $data_to_map = json_decode($responseBody, true); + $objectType = json_decode($objectType, true); + if (!isset($data_to_map['data']) || !is_array($data_to_map['data'])) { + + log_message('error', "Invalid Response from Endpoint 'data' Key Missing"); + return $this->respond(['status' => 'Failure', 'error' => ['code' => 500, 'message' => "Invalid Response from Endpoint 'data' Key Missing"]], 500); + } + + foreach ($data_to_map['data'] as $index => $item) { + + try { + $mapped_data = $this->webHookHelper->mapObjectType($item, $objectType); + } catch (Exception $e) { + $errorMessage = "Object Mapping Failed: " . $e->getMessage(); + log_message('error', $errorMessage); + + return $this->respond(['status' => 'Failure', 'error' => ['code' => 500, 'message' => "Object Mapping Failed"]], 500); + } + + try { + $mapped_data['client_id'] = $client_id; + $this->webHookHelper->insertData($mapped_data, 1); + } catch (Exception $e) { + $errorMessage = "Data Insertion Failed: " . $e->getMessage(); + log_message('error', $errorMessage); + + return $this->respond(['status' => 'Failure', 'error' => ['code' => 500, 'message' => "Data Insertion Failed"]], 500); + } + } + + log_message('error', "Data Inserted Successfully for Client ID: " . $client_id); + // Return success response + return $this->respond(['status' => 'Success', 'message' => "Data Inserted Successfully"], 200); + } + } + + public function pullData_claim() + { + $validationStatus = $this->validateToken(2); + + $data = $this->getClientIdfromToken(); + $client_id = $data[0]; + log_message('error', "Pull data claim from Client ID: ". $client_id); + $client = $this->clientAPI->where('client_id', $client_id)->where("is_active", 1)->where("api_access", 1)->first(); + if (empty($client)) { + log_message('error', 'Client Not Found or Unauthorized'); + return $this->respond(['status' => 'Failure', 'error' => ['code' => 404, 'message' => 'Client Not Found or Unauthorized']], 404); + } + + $objectType = $client['pull_claim_obj']; + + if ($validationStatus) { + $responseBody = $this->request->getBody(); + $data_to_map = json_decode($responseBody, true); + $objectType = json_decode($objectType, true); + if (!isset($data_to_map['data']) || !is_array($data_to_map['data'])) { + + log_message('error', "Invalid Response from Endpoint 'data' Key Missing"); + return $this->respond(['status' => 'Failure', 'error' => ['code' => 500, 'message' => "Invalid Response from Endpoint 'data' Key Missing"]], 500); + } + foreach ($data_to_map['data'] as $index => $item) { + try { + $mapped_data = $this->webHookHelper->mapObjectType($item, $objectType); + } catch (Exception $e) { + $errorMessage = "Object Mapping Failed: " . $e->getMessage(); + log_message('error', $errorMessage); + + return $this->respond(['status' => 'Failure', 'error' => ['code' => 500, 'message' => "Object Mapping Failed"]], 500); + } + + try { + $mapped_data['client_id'] = $client_id; + $this->webHookHelper->insertData($mapped_data, 2); + } catch (Exception $e) { + $errorMessage = "Data Insertion Failed: " . $e->getMessage(); + log_message('error', $errorMessage); + + return $this->respond(['status' => 'Failure', 'error' => ['code' => 500, 'message' => "Data Insertion Failed"]], 500); + } + } + + + log_message('error', "Data Inserted Successfully for Client ID: " . $client_id); + // Return success response + return $this->respond(['status' => 'Success', 'message' => "Data Inserted Successfully"], 200); + } + } +} diff --git a/app/Filters/AuthClientApi.php b/app/Filters/AuthClientApi.php new file mode 100644 index 00000000..2b3eb46e --- /dev/null +++ b/app/Filters/AuthClientApi.php @@ -0,0 +1,87 @@ +clientAPI = new ClientApiModel(); + $this->myLogger = \Config\Services::mylogger(); + + } + public function before(RequestInterface $request, $arguments = null) + { + $response = service('response'); + try { + + $authHeader = $request->getHeaderLine('Authorization'); + + // Check if header exists + if (empty($authHeader)) { + $this->myLogger->log('error', 'Authorization header missing'); + return $response->setJson(['status' => "Failure", 'error' => ['message'=>'Authorization header missing','code'=> 401]], 401); + } + + if(!str_contains($authHeader, 'Bearer ')){ + $this->myLogger->log('error', 'Authorization Bearer missing'); + return $response->setJson(['status' => "Failure", 'error' => ['message'=>'Invalid Authorization header','code'=>401]], 401); + } + + $token = str_replace('Bearer ', '', $authHeader); + if (empty($token)) { + + $this->myLogger->log('error', 'Empty Token'); + return $response->setJson(['status' => "Failure", 'error' => ['message'=>'Invalid Token Format','code'=> 401]], 401); + } + + try{ + + $client_id = ClientTokenHelper::extractClientId($token); + + }catch(\Exception $e){ + + $this->myLogger->log('error', 'Invalid Client Token Format'); + + return $response->setJson(['status' => "Failure", 'error' => 'Invalid Token Format'], 401); + } + $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 $response->setJson(['status' => "Failure", 'error' => ['message' => 'Client not found or unauthorized','code'=>'403']], 403); + } + + 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 $response->setJson(['status' => "Failure", 'error' => ['message' => 'Invalid token','code'=>401] + ], 401); + } + } catch (\Exception $e) { + log_message('error', 'Error in ClientAPIController:validateToken - ' . $e->getMessage()); + return $response->setJson(['status' => "Failure", 'error' => ['message'=>'Internal Server Error','code'=> 500]], 500); + } + + } + + public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) + { + // Do something here + } +} + diff --git a/app/Helpers/ClientQueryHelper.php b/app/Helpers/ClientQueryHelper.php new file mode 100644 index 00000000..6d58de19 --- /dev/null +++ b/app/Helpers/ClientQueryHelper.php @@ -0,0 +1,100 @@ +clientPolicy = new ClientPolicyModel(); + $this->empModel = new EmployeeModel(); + $this->empPolicyModel = new EmployeePolicyModel(); + $this->claimModel = new TicketMasterModel(); + } + + public function clientPolicyMaster($client_id){ + + return $this->clientPolicy->select("client_policy.id as policy_ref_no,client_policy.client_branch_id as branch_ref_no,client_branch.branch_code, + client_policy.insurer_id as insurer_ref_no,insurers.name as insurer,client_policy.policy_type_id,policy_type.policy_type, + client_policy.tpa_id as tpa_ref_no,client_policy.policy_start_date,client_policy.policy_end_date,client_policy.policy_no,client_policy.policy_status") + ->join('insurers', 'client_policy.insurer_id = insurers.id and insurers.is_active = 1') + ->join('policy_type', 'client_policy.policy_type_id = policy_type.id and policy_type.is_active = 1') + ->join('client_branch', 'client_policy.client_branch_id = client_branch.id and client_branch.is_active = 1') + ->where('client_policy.is_active', 1) + ->where('client_policy.client_id', $client_id) + ->get() + ->getResultArray(); + } + + public function sendEmpMaster($client_id,$where,$limit,$offset = 0) + { + + return $this->empModel->select("id as ref_no,name,emp_code, + relationship,emp_status,mobile,email_corporate, + change_event,dob,doj,band,gender") + ->where("is_active",1) + ->where("client_id", $client_id) + ->where($where) + ->whereNotIn('emp_status', ['truncated'],) + ->orderBy("id") + ->limit($limit,$offset) + ->get() + ->getResultArray(); + + } + + public function sendEmpPolicies($emp_id) + { + return $this->empPolicyModel->select("id as ref_no,client_policy_id as policy_ref_no, + tpa_id as tpa_ref_no,uhid as policy_no,pre_existing_alignments,age_band,basic_cover_si,date_coverage, + policy_end_date,days,premium,rata_premimum,date_of_exit,reason_for_exit,payable_employee") + ->where("employee_id", $emp_id) + ->where("is_active", 1) + ->whereNotIn("status", ['truncated']) + ->orderBy("id") + ->get() + ->getResultArray(); + } + + public function sendClaimMaster($client_id,$where,$limit,$offset = 0) + { + + return $this->claimModel->select("i.name as insurer,tpa.name as tpa,concat(up.first_name,' ',up.last_name) as acm_name, + cs.claim_status,ticket_master.emp_name,ticket_master.insured_name, + ticket_master.emp_code,ticket_master.policy_no,ticket_master.ticket_type_id as policy_type, + ticket_master.emp_mobile,ticket_master.emp_mail,ticket_master.hospital_name,ticket_master.doa, + ticket_master.dod,ticket_master.claim_amount,ticket_master.date_of_join,ticket_master.date_of_incep, + ticket_master.date_of_accident,ticket_master.date_of_death, + ticket_master.date_of_intimat,ticket_master.claim_number,ticket_master.si_amt, + ticket_master.raised_date,ticket_master.registration_date,ticket_master.denial_date, + ticket_master.settled_date,ticket_master.denial_reason,ticket_master.approved_amount, + ticket_master.utr_details,ticket_master.return_remark,ticket_master.cancel_remark, + ticket_master.non_id_reason,ticket_master.head_rejection_reason") + ->join("tpa","tpa.id = ticket_master.tpa_id and tpa.is_active = 1") + ->join("user_profiles up", "ticket_master.acm_id = up.id and up.is_active = 1") + ->join('insurers i', 'ticket_master.insurer_id = i.id and i.is_active = 1') + ->join('ticket_claim_status cs', 'ticket_master.claim_status_id = cs.id and cs.is_active = 1') + ->where("ticket_master.client_id", $client_id) + ->where("ticket_master.is_active", 1) + ->where($where) + ->orderBy("ticket_master.id") + ->limit($limit,$offset) + ->get() + ->getResultArray(); + + } + + +} \ No newline at end of file diff --git a/app/Helpers/ClientTokenHelper.php b/app/Helpers/ClientTokenHelper.php new file mode 100644 index 00000000..50c73f23 --- /dev/null +++ b/app/Helpers/ClientTokenHelper.php @@ -0,0 +1,54 @@ +empModel = new EmployeeModel(); + $this->empPolicyModel = new EmployeePolicyModel(); + $this->claimModel = new TicketMasterModel(); + + } + + public function mapObjectType($data_to_map, $objectType) + { + $mapped_data = []; + foreach ($objectType as $key => $value){ + $mapped_data[$key] = $data_to_map[$value]; + } + + return $mapped_data; + } + + public function insertData($mapped_data, $type){ + + $model = $type == 1 ? "empModel" : "claimModel"; + $this->$model->insert($mapped_data); + } +} diff --git a/app/Models/ClientApiModel.php b/app/Models/ClientApiModel.php new file mode 100644 index 00000000..59830aa0 --- /dev/null +++ b/app/Models/ClientApiModel.php @@ -0,0 +1,45 @@ + + .card { + padding-top: 0px; + } + +
+
+ +
+
+ + +
+
+ +
+ "> +
+
Generate New Token
+
+
+ " class="form-control" id="client_token" placeholder="Click generate to create token" readonly required> +
+
+ + +
+ +
+ +
+ +
+
+
Webhooks (PUSH)
+
+
+ + +
+
+ + +
+
+ + " class="form-control emp_webhook" onchange="validateWebhookUrlById(this.id)" id="webhook_url" placeholder="Enter Webhook URL"> +
+
+ + +
+
+ + " class="form-control emp_webhook" placeholder="Enter Client API token" /> + +
+ +
+
+ + +
+
+
+
+ + +
+
+ + +
+
+ + " class="form-control claim_webhook" onchange="validateWebhookUrlById(this.id)" id="webhook_url_claims" placeholder="Enter Webhook URL"> +
+
+ + +
+
+ + " class="form-control claim_webhook" placeholder="Enter Client API token"> +
+
+
+ + +
+
+
+
Webhooks (PULL)
+
+
+ + +
+
+ + +
+
+ + " class="form-control" onchange="validateWebhookUrlById(this.id)" id="webhook_url2" readonly placeholder="Enter Webhook URL"> +
+
+ + +
+
+ +
+
+ + " class="form-control" id="pull_emp_token" placeholder="Click generate to create token" readonly required> +
+
+ + +
+
+ +
+ + +
+ +

+
+
+ + +
+
+ + +
+
+ + " class="form-control" onchange="validateWebhookUrlById(this.id)" id="webhook_url2" readonly placeholder="Enter Webhook URL"> +
+
+ + +
+
+
+ + " class="form-control" id="pull_claim_token" placeholder="Click generate to create token" readonly required> +
+
+ + +
+
+ + +
+
+
+ +
+ +
+
+
+ + \ No newline at end of file diff --git a/app/Views/client_onboarding.php b/app/Views/client_onboarding.php index 814a97cd..fd334113 100755 --- a/app/Views/client_onboarding.php +++ b/app/Views/client_onboarding.php @@ -88,6 +88,12 @@ body { Policies +
+ + +
+ + + + + @@ -229,6 +248,7 @@ +
diff --git a/app/Views/claims_dash.php b/app/Views/claims_dash.php new file mode 100644 index 00000000..44538323 --- /dev/null +++ b/app/Views/claims_dash.php @@ -0,0 +1,304 @@ + + +
+
+
+
+
+
GMC
+

+

 

+

 

+
+
+ +
+
+
+
+
GPA
+

+

 

+

 

+
+
+
+ +
+
+
+
EDLI
+

+

 

+

 

+
+
+
+ +
+
+
+
GTLI
+

+

 

+

 

+
+
+
+ +
+ + +
+ + + $statuses) : ?> + + + $count) : ?> + + 20 ? substr($formattedStatus, 0, 15) . '...' : $formattedStatus; + $showTooltip = strlen($formattedStatus) > 20; + ?> + + + + + +
+ + +
+ + \ No newline at end of file diff --git a/app/Views/leads_dash.php b/app/Views/leads_dash.php new file mode 100644 index 00000000..f7ea2ad4 --- /dev/null +++ b/app/Views/leads_dash.php @@ -0,0 +1,173 @@ + +
+
+
+
+
+
Leads
+

+

 

+

 

+
+
+
+
+
+
+
Renewals
+

+

 

+

 

+
+
+
+ +
+ + +
+ +
+
+ \ No newline at end of file From 7de412ef7264f7f7d76fe21aae91f514c0a2eb5a Mon Sep 17 00:00:00 2001 From: velz Date: Fri, 18 Apr 2025 12:27:38 +0530 Subject: [PATCH 03/42] FIX_ADD_ONE_DAY_IN_INSURER_HANDLED --- app/Helpers/excel_util_helper.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Helpers/excel_util_helper.php b/app/Helpers/excel_util_helper.php index c90eebb3..e13d9793 100755 --- a/app/Helpers/excel_util_helper.php +++ b/app/Helpers/excel_util_helper.php @@ -1132,7 +1132,7 @@ if (!function_exists('premium_calculation_manager')) { $insurer = new InsurerModel(); $insurer = ($insurer->find($policy_terms['insurer_id'])); - if($insurer['addition_add_day'] == true) + if(isset($insurer['addition_add_day']) && $insurer['addition_add_day'] == true) { // $emp_data['policy_details']['date_coverage'] = (new DateTime($emp_data['policy_details']['date_coverage']))->modify('+1 day')->format('Y-m-d'); From 75da2ab3e13341299536c8225aee4223c45dc2fe Mon Sep 17 00:00:00 2001 From: Srinivas-Saravanan Date: Mon, 21 Apr 2025 10:35:23 +0530 Subject: [PATCH 04/42] FIX_NONeB_POLICY_REGISTER --- app/Views/view_rfq_non_eb.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/app/Views/view_rfq_non_eb.php b/app/Views/view_rfq_non_eb.php index 5f9aba17..364f2d34 100644 --- a/app/Views/view_rfq_non_eb.php +++ b/app/Views/view_rfq_non_eb.php @@ -3820,7 +3820,12 @@ tables.forEach(table => { if (table.id.includes("summary")) { - table.remove(); // reMove summary table from the top + let tableContainer = table.closest(".table-container") || table.parentElement; + if (tableContainer) { + tableContainer.remove(); // Remove the container, including table and collapsible bar + } else { + table.remove(); // Fallback to removing just the table if no container is found + } } }); From f8d3e49cfd1820b86655c6905e98f862eb963a4b Mon Sep 17 00:00:00 2001 From: "venkatesh.r" Date: Tue, 22 Apr 2025 09:24:44 +0530 Subject: [PATCH 05/42] FIX_SI_ENHANCE_FILE_UPLOAD : RV --- app/Controllers/ClientController.php | 5 +++++ app/Controllers/EmployeeServiceController.php | 12 +++++++----- app/Helpers/excel_util_helper.php | 10 +++++----- app/Models/EmployeeModel.php | 2 +- 4 files changed, 18 insertions(+), 11 deletions(-) diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index 0a096c82..c808bac5 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -4583,6 +4583,11 @@ class ClientController extends AdminController // $employeeRestController->employeesOnboardProcess(['file_id' => 835]); // $employeeRestController->employeesEnrollmentInsert(['file_id' => 836]); // $r = Jobs::addJob(['job_name' => 'employeesEnrollmentInsert','payload' => ['file_id' => 721]]); + $empServiceController = new EmployeeServiceController(); + // $res = $empServiceController->excelFileFormatValidation(['file_id' => '873']); + // $res = $empServiceController->excelFileDataValidation(['file_id' => '874']); + // $res = $empServiceController->employeesSIEnhanceProcess(['file_id' => '874']); + // dd('-----', $res); // ----------EMP DATA SERVICE CONTROLLER-------------------------------------------------------------------------------- diff --git a/app/Controllers/EmployeeServiceController.php b/app/Controllers/EmployeeServiceController.php index 61e0af4a..993194a0 100755 --- a/app/Controllers/EmployeeServiceController.php +++ b/app/Controllers/EmployeeServiceController.php @@ -468,7 +468,7 @@ class EmployeeServiceController extends AdminController 'format' => null, 'allowed_values' => null, 'custom' => 'check_si', - 'params' => ['row', 'policy_terms', 'slab_details'] + 'params' => ['row', 'policy_details', 'slab_details'] ], 'date_of_enhancement' => [ 'col_idx' => 4, @@ -1552,9 +1552,11 @@ class EmployeeServiceController extends AdminController 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']); - if(in_array(strtolower($employee['relationship']), $rack_rate_json) && $rack_rate_json[ strtolower($employee['relationship']) ] != 0 && $rack_rate_json[ strtolower($employee['relationship']) ] != 'NA') - { + $rack_rate_json = json_decode($slab_value['additional_relationship'], true); + $relationship_array_key = strtolower($employee['relationship']); + + if(array_key_exists($relationship_array_key, $rack_rate_json) && $rack_rate_json[ strtolower($employee['relationship']) ] != 0 && $rack_rate_json[ strtolower($employee['relationship']) ] != 'NA') + { $applicable_rack_rate_name = $slab_value['rack_rate_name']; $applicable_rack_rate_master = $slab_value['grid_master']; break; @@ -1563,7 +1565,7 @@ class EmployeeServiceController extends AdminController } //get max age,max count of the familiy - $max_age_and_max_count_of_current_member = $this->employeeModel->getFamiliyCountAndMaxage($employee['emp_code']); + $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); diff --git a/app/Helpers/excel_util_helper.php b/app/Helpers/excel_util_helper.php index c90eebb3..69fe4d98 100755 --- a/app/Helpers/excel_util_helper.php +++ b/app/Helpers/excel_util_helper.php @@ -407,7 +407,7 @@ if (!function_exists('data_group_by_family')) $row = transform_enrollment_row_to_inception_row($row); } - if(strtolower($row[5]) == 'self' && isset($result[$row[1]])) + if(isset($row[5]) && strtolower($row[5]) == 'self' && isset($result[$row[1]])) { array_unshift($result[$row[1]],$row); }else @@ -2119,15 +2119,15 @@ if(!function_exists('check_unit')) if(!function_exists('transform_si_excel_row_to_calculatable_format')) { - function transform_si_excel_row_to_calculatable_format(array $employee,array$employee_policy,array $maxage_and_maxcount,array $slab_details,string $applicable_slab_name,string $augmented_si,array $grid_master) - { + function transform_si_excel_row_to_calculatable_format(array $employee, array $employee_policy,array $maxage_and_maxcount,array $slab_details,string $applicable_slab_name,string $augmented_si,array $grid_master) + { $employee['temp'] = []; $employee['temp']['max_age'] = $maxage_and_maxcount[0]['max_age']; $employee['temp']['max_count'] = $maxage_and_maxcount[0]['family_member_count']; $employee['temp']['grid_name'] = $applicable_slab_name; $employee['temp']['grid_master'] = $grid_master; $employee['temp']['acting_self'] = true; - $employee['temp']['premium_type'] = $grid_master['premium_type']; + $employee['temp']['premium_type'] = $slab_details['slab_rates'][0]['premium_type']; $employee['temp']['grid_type'] = $applicable_slab_name; $employee['temp']['grid_id'] = $grid_master['ui_type']; $employee['temp']['action'] = 'SI'; @@ -2137,7 +2137,7 @@ if(!function_exists('transform_si_excel_row_to_calculatable_format')) $employee['temp']['policy_status'] = null; $employee['temp']['emp_status'] = null; $employee['temp']['rata_premimum'] = null; - + $employee['policy_details'] = $employee_policy; return $employee; diff --git a/app/Models/EmployeeModel.php b/app/Models/EmployeeModel.php index 524eb18b..6f4af68b 100755 --- a/app/Models/EmployeeModel.php +++ b/app/Models/EmployeeModel.php @@ -222,7 +222,7 @@ class EmployeeModel extends Model ) AS family_stats ORDER BY family_member_count DESC, max_age DESC LIMIT 1;"; - $results = $this->db->query($query)->getResult(); + $results = $this->db->query($query)->getResultArray(); return $results; } From 12d72ca614579c0d4c31b23badbb178b9ff72e10 Mon Sep 17 00:00:00 2001 From: velz Date: Tue, 22 Apr 2025 09:30:24 +0530 Subject: [PATCH 06/42] FIX_TPA&INS_FILE_CORRUPT_ISSUE --- app/Controllers/EmpDataServiceController.php | 5 +++++ phpqueue.sh | 7 ------- 2 files changed, 5 insertions(+), 7 deletions(-) delete mode 100755 phpqueue.sh diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php index c7f9d689..cb259f6c 100755 --- a/app/Controllers/EmpDataServiceController.php +++ b/app/Controllers/EmpDataServiceController.php @@ -529,6 +529,7 @@ class EmpDataServiceController extends BaseController // Close and remove temporary file fclose($tempFile); + exit(); return true; // Excel file successfully generated and exported @@ -633,6 +634,7 @@ class EmpDataServiceController extends BaseController // Close and remove the temporary file fclose($tempFile); + exit(); return true; } else { @@ -784,6 +786,7 @@ class EmpDataServiceController extends BaseController // Close and remove the temporary file fclose($tempFile); + exit(); return true; } else { @@ -897,6 +900,7 @@ class EmpDataServiceController extends BaseController // Close and remove the temporary file fclose($tempFile); + exit(); return true; } else { @@ -1196,6 +1200,7 @@ class EmpDataServiceController extends BaseController // Close and remove temporary file fclose($tempFile); + exit(); return true; // Excel file successfully generated and exported diff --git a/phpqueue.sh b/phpqueue.sh deleted file mode 100755 index cc97a2db..00000000 --- a/phpqueue.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/bash - -while true; do - echo "Running job at $(date)" - /usr/bin/php /var/www/nhance/zenith/public/index.php cli/processjob - sleep 1 # Optional: Add a sleep to avoid CPU overload -done From 25e7296e85d7b5172b4f7bbed2d57426ad501367 Mon Sep 17 00:00:00 2001 From: Srinivas-Saravanan Date: Tue, 22 Apr 2025 12:07:56 +0530 Subject: [PATCH 07/42] FIX_CLAIMS_TAT,FEAT_DASHBOARD_USERROLE_BASED --- app/Config/Routes.php | 2 +- app/Controllers/DashboardController.php | 34 +- app/Controllers/LeadsController.php | 78 +- .../PolicyTransactionController.php | 1264 ++++++++--------- app/Controllers/TicketController.php | 83 +- app/Models/ClientPolicyModel.php | 504 +++---- app/Models/LeadsModel.php | 126 +- app/Models/PolicyTransactionModel.php | 302 ++-- app/Models/TicketMasterModel.php | 189 ++- app/Views/DashBoard.php | 31 +- app/Views/bds_dash.php | 20 +- app/Views/claims_dash.php | 95 +- app/Views/client_api.php | 3 +- app/Views/client_onboarding.php | 4 +- app/Views/leads_dash.php | 159 ++- app/Views/ticket_mail_template.php | 1 + app/Views/view_deposit.php | 301 ++-- 17 files changed, 1796 insertions(+), 1400 deletions(-) diff --git a/app/Config/Routes.php b/app/Config/Routes.php index a6e3eb12..9d398006 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -376,7 +376,7 @@ $routes->group("policy_tranction", ["filter" => "authMVC"], function ($routes) { }); $routes->group("report", ["filter" => "authMVC"], function ($routes) { - $routes->get("list", "PolicyTransactionController::reportBDS"); + $routes->match(['get', 'post'],"list", "PolicyTransactionController::reportBDS"); $routes->get("report-varience-list", "PolicyTransactionController::reportVarience"); $routes->get("report-business-list", "PolicyTransactionController::reportBusinessList"); $routes->get("report-finance-list", "PolicyTransactionController::reportFinanceList"); diff --git a/app/Controllers/DashboardController.php b/app/Controllers/DashboardController.php index 78d1b86e..2adf141a 100755 --- a/app/Controllers/DashboardController.php +++ b/app/Controllers/DashboardController.php @@ -244,10 +244,20 @@ class DashboardController extends AdminController $data['policyStatus'] = $this->policyStatus; $data['colorShades'] = $this->colorShades; } + if ((get_role_id() == STAFF_ROLE_ID && in_array(CLAIMS_TEAM_ID,user_team())) || in_array(get_role_id(),[1,5])){ + $data['claim_data'] = $this->getClaimData(); + $data['colorShades'] = $this->colorShades; - $data['claim_data'] = $this->getClaimData(); - $data['lead_data'] = $this->getLeadData(); + } + if ((get_role_id() == STAFF_ROLE_ID && in_array(ENROLLMENT_TEAM_ID,user_team())) || in_array(get_role_id(),[1,5])){ + $data['lead_data'] = $this->leadModel->getDashData(); + $data['bds_renewal'] = $this->policyTransactionModel->getBDSRenewalData(); + $data['colorShades'] = $this->colorShades; + } + + // dd(get_role_id(),user_team()); + $data['page_name'] = 'Dashboard'; echo view('layout/header', $data); @@ -255,9 +265,6 @@ class DashboardController extends AdminController echo view('layout/footer'); } - public function getLeadData(){ - - } public function getClaimData() { @@ -281,7 +288,6 @@ class DashboardController extends AdminController $claim_status[$typeId] = []; } - // Use associative array keys to mimic a set $claim_status[$typeId][$status] = true; } @@ -291,15 +297,8 @@ class DashboardController extends AdminController } $data = $this->ticketModel->getDashData($claim_status, $this->claimDashLimit); - // dd($data); - // foreach ($data as $dat){ - // foreach ($dat as $key => $value){ - // echo($key . " => ". $value); - // } - // } - // die(); - return $data; + return $data; } @@ -765,8 +764,9 @@ class DashboardController extends AdminController return $groupedData; } - public function prepareClaimSearchData(){ - + public function prepareClaimSearchData() + { + $received_data = $this->request->getPost(); $ticketTypeId = $received_data['ticketTypeId']; $status = $received_data['status']; @@ -780,6 +780,6 @@ class DashboardController extends AdminController ->where("tcs.claim_status", $status) ->first(); $data['ticket_type_id'] = $ticketTypeId; - return $this->respond(['status' => "success","data" => $data],200); + return $this->respond(['status' => "success", "data" => $data], 200); } } diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php index 617add8f..79ca3591 100644 --- a/app/Controllers/LeadsController.php +++ b/app/Controllers/LeadsController.php @@ -146,19 +146,36 @@ class LeadsController extends BaseController $this->loadLayout('lead_filter', $data); } else { - $search_data = $this->request->getPost(); - // print_r($search_data); + $isFromDashboard = $this->request->getPost("is_dashboard"); - $where = []; - foreach ($search_data as $search_objects => $key) { - if ($key != null && $key != '' && $key != 0) { - $where[$search_objects] = $key; + if (isset($isFromDashboard) && !empty($isFromDashboard) && $isFromDashboard == 1) { + $ids = $this->request->getPost('ids'); + $ids = array_filter(explode(',', $ids)); + + if (!empty($ids)) { + $idsStr = implode(',', array_map('intval', $ids)); // sanitize IDs to be integers + $where = "leads.id IN ($idsStr)"; + } else { + $where = '1 = 0'; // No valid IDs, return empty result } - } + // dd($where ); + $data['lead_data_list'] = $this->leadsModel->getLeadDataForLising($where); + $this->loadLayout('lead_filter', $data); + } else { + $search_data = $this->request->getPost(); - $data['lead_data_list'] = $this->leadsModel->getLeadDataForLising($where); - $html = view('leads_list', $data); - return $this->respond(['status' => true, 'html' => $html], 200); + $where = []; + foreach ($search_data as $search_objects => $key) { + if ($key != null && $key != '' && $key != 0 && $search_objects != 'is_dashboard') { + $where[$search_objects] = $key; + } + } + + $data['lead_data_list'] = $this->leadsModel->getLeadDataForLising($where); + + $html = view('leads_list', $data); + return $this->respond(['status' => true, 'html' => $html], 200); + } } } @@ -602,7 +619,7 @@ class LeadsController extends BaseController return $this->respond(['status' => false, 'message' => 'File could not be removed.'], 200); } } - //--------RFQ----------------------------------------------------------------------------------------------- + //--------RFQ----------------------------------------------------------------------------------------------- public function viewRFQ($id, $type = 1) @@ -678,11 +695,10 @@ class LeadsController extends BaseController "; - if ($data['lead_data']['policy_end_date'] != null){ + if ($data['lead_data']['policy_end_date'] != null) { $subject = "{{CLIENT_NAME}} _ {{POLICY_TYPE}} _ {{RFQ_OR_QCR}} _ {{POLICY_YEAR}} {{POLICY_END_DATE}}"; - }else{ + } else { $subject = "{{CLIENT_NAME}} _ {{POLICY_TYPE}} _ {{RFQ_OR_QCR}} _ {{POLICY_YEAR}}"; - } $data['mail_content'] = $this->transformMailContent($lead_data, $mail_content, $data['page_name']); @@ -690,7 +706,7 @@ class LeadsController extends BaseController $data['multi_file_data'] = $this->leadFilesModel->where('lead_id', $id)->where('is_active', 1)->findAll() ?? null; $data['attachment_html'] = view('rfq/attachment_files', $data) ?? ""; - $data['user_team'] = $this->userModel->select("ut.team_id")->join("user_teams ut","ut.user_id = user_profiles.id and ut.is_active = 1")->where("user_profiles.is_active",1)->first()['team_id']; + $data['user_team'] = $this->userModel->select("ut.team_id")->join("user_teams ut", "ut.user_id = user_profiles.id and ut.is_active = 1")->where("user_profiles.is_active", 1)->first()['team_id']; // dd($data); if ($data['lead_data']['lead_form_type'] == 1) { @@ -866,7 +882,7 @@ class LeadsController extends BaseController if ($subKey !== 'Quote Asked' && isset($subVal['Total'])) { $proposals[$key] = $value; break; - }else{ + } else { $proposals[$key] = $value; } } @@ -1546,7 +1562,7 @@ class LeadsController extends BaseController ], ]); - + // Set filename $string = ($type == 2) ? 'QCR' : 'RFQ'; @@ -1554,15 +1570,14 @@ class LeadsController extends BaseController $next_year = $current_year + 1; $policy_year = "$current_year-$next_year"; - if (!empty($rfq_data['policy_end_date'])){ + if (!empty($rfq_data['policy_end_date'])) { $policy_expiry = strtotime($lead_data['policy_end_date']); - $formatted_policy = date("d-m-Y",$policy_expiry); + $formatted_policy = date("d-m-Y", $policy_expiry); - $filename = "{$rfq_data['client_name']}_{$rfq_data['policy_type']}_{$string}_" .$policy_year.'(Due On '.$formatted_policy . ')' .'.xlsx'; - - }else{ - $filename = "{$rfq_data['client_name']}_{$rfq_data['policy_type']}_{$string}_".$policy_year.'_' . '.xlsx'; + $filename = "{$rfq_data['client_name']}_{$rfq_data['policy_type']}_{$string}_" . $policy_year . '(Due On ' . $formatted_policy . ')' . '.xlsx'; + } else { + $filename = "{$rfq_data['client_name']}_{$rfq_data['policy_type']}_{$string}_" . $policy_year . '_' . '.xlsx'; } @@ -2190,12 +2205,11 @@ class LeadsController extends BaseController } else if ($recipient_type == 'client') { - $mailIDS = explode(',',$params['contact_mail']); + $mailIDS = explode(',', $params['contact_mail']); $recipient_data = []; - foreach ($mailIDS as $mail){ + foreach ($mailIDS as $mail) { $recipient_data[] = ['name' => $lead_data['contact_person_name'], 'email' => $mail]; } - } else { $recipient_data = [['name' => "Team", 'email' => $params['to']]]; } @@ -2902,10 +2916,10 @@ class LeadsController extends BaseController $policy_expiry = strtotime($lead_data['policy_end_date']); - $formatted_policy = date("d-m-Y",$policy_expiry); + $formatted_policy = date("d-m-Y", $policy_expiry); $logged_user_id = get_session_userid(); - $logged_user_data = $this->userModel->where("id",$logged_user_id)->where("is_active",1)->first(); + $logged_user_data = $this->userModel->where("id", $logged_user_id)->where("is_active", 1)->first(); if ($lead_data) { @@ -2916,11 +2930,11 @@ class LeadsController extends BaseController $message = str_replace("{{POLICY_TYPE}}", $lead_data['policy_type'] ?? "Insurance Policy", $message); $message = str_replace("{{RFQ_OR_QCR}}", $page_name, $message); $message = str_replace("{{POLICY_YEAR}}", $policy_year, $message); - $message = str_replace("{{POLICY_END_DATE}}"," (Due On ".$formatted_policy.")",$message); + $message = str_replace("{{POLICY_END_DATE}}", " (Due On " . $formatted_policy . ")", $message); - $message = str_replace("{{LOGGED_USER_NAME}}",ucfirst($logged_user_data['first_name'])." ".ucfirst($logged_user_data['last_name']),$message); - $message = str_replace("{{LOGGED_USER_EMAIL}}",$logged_user_data['email'],$message); - $message = str_replace("{{LOGGED_USER_MOBILE}}",$logged_user_data['mobile'],$message); + $message = str_replace("{{LOGGED_USER_NAME}}", ucfirst($logged_user_data['first_name']) . " " . ucfirst($logged_user_data['last_name']), $message); + $message = str_replace("{{LOGGED_USER_EMAIL}}", $logged_user_data['email'], $message); + $message = str_replace("{{LOGGED_USER_MOBILE}}", $logged_user_data['mobile'], $message); return $message; } else { diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php index a4721770..99180333 100644 --- a/app/Controllers/PolicyTransactionController.php +++ b/app/Controllers/PolicyTransactionController.php @@ -64,7 +64,7 @@ class PolicyTransactionController extends BaseController protected $batchFileModel; protected $filesModel; protected $coShareStmtDetailsModel; - + public function __construct() { set_session_context('Policy Tranction'); @@ -106,7 +106,7 @@ class PolicyTransactionController extends BaseController public function viewInception() { $data['page_name'] = 'Policy'; - + // Static arrays for dropdowns $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance']; $data['client_type'] = [1 => 'Group', 2 => 'Individual']; @@ -148,7 +148,7 @@ class PolicyTransactionController extends BaseController 'policy_start_date' => 'Policy Start Date', 'policy_end_date' => 'Policy End Date', ]; - + // Filter data $start_date = $this->request->getGet('start_date'); $end_date = $this->request->getGet('end_date'); @@ -158,7 +158,7 @@ class PolicyTransactionController extends BaseController $date_type = $this->request->getGet('date_type'); $issuer = $this->request->getGet('issuer'); $status = $this->request->getGet('status'); - + // Handle null or empty values $start_date = empty($start_date) ? 0 : $start_date; $end_date = empty($end_date) ? 0 : $end_date; @@ -168,7 +168,7 @@ class PolicyTransactionController extends BaseController $date_type = empty($date_type) ? 0 : $date_type; $issuer = empty($issuer) ? 0 : $issuer; $status = empty($status) ? 0 : $status; // Corrected from `$issuer` - + // Fetch inception data list $data['inception_data_list'] = $this->policyTransactionModel->getInceptionTranctionListData( $start_date, @@ -180,7 +180,7 @@ class PolicyTransactionController extends BaseController $issuer, $status ); - + // Fetch additional data $data['client'] = $this->clientModel->where('is_active', 1)->findAll(); $data['client_branch'] = $this->clientBranchModel->where('is_active', 1)->findAll(); @@ -190,7 +190,7 @@ class PolicyTransactionController extends BaseController $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll(); $data['insurer_branch'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames(); $data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames(); - + // Fetch PP Teams Data $data['ppTeamsData'] = $this->userModel ->where('is_active', 1) @@ -204,22 +204,22 @@ class PolicyTransactionController extends BaseController ->where('user_teams.is_active', 1) ->where('user_profiles.is_active', 1) ->findAll(); - + // Fetch ACM $data['ACM'] = $this->userModel ->where('role', 3) // Assuming `role` is in `user_profiles` ->where('is_active', 1) ->findAll(); - + // echo '
';
         // print_r($data['ppTeamsData']); die;
-        
+
         // dd($data);
-    
+
         // Load view
         $this->loadLayout('policy_transaction_inception_list', $data);
     }
-    
+
     // policy Transaction Create function start
     public function createInceptionPolicy()
     {
@@ -229,56 +229,56 @@ class PolicyTransactionController extends BaseController
         $data['cd_ac_pk'] = $this->request->getPost('cd_ac_no');
         // print_r($this->request->getPost()); die;
 
-    
+
         if (!$id) {
             return $this->insertInceptionPolicy($data);
         } else {
             return $this->updateInceptionPolicy($id, $data);
         }
     }
-    
+
     private function preparePolicyData()
     {
         $data = $this->request->getPost();
-    
+
         // print_r($data); die;
         // var_dump($data); die;
 
-        if(empty($data['policy_issue_date'])){
+        if (empty($data['policy_issue_date'])) {
             $data['policy_issue_date'] = null;
         }
 
-        if(empty($data['policy_start_date'])){
-            $data['policy_start_date'] = null;        
+        if (empty($data['policy_start_date'])) {
+            $data['policy_start_date'] = null;
         }
 
-        if(empty($data['policy_end_date'])){
-            $data['policy_end_date'] = null;        
+        if (empty($data['policy_end_date'])) {
+            $data['policy_end_date'] = null;
         }
 
-        if(empty($data['renewal_date'])){
-            $data['renewal_date'] = null;        
+        if (empty($data['renewal_date'])) {
+            $data['renewal_date'] = null;
         }
 
-        if(empty($data['rollover_date'])){
-            $data['rollover_date'] = null;        
+        if (empty($data['rollover_date'])) {
+            $data['rollover_date'] = null;
         }
 
-        if(empty($data['last_action_date'])){
+        if (empty($data['last_action_date'])) {
             $data['last_action_date'] = null;
-        }else{
+        } else {
             $data['last_action_date'] = change_date_format($data['last_action_date']);
         }
 
 
         // Separate Insurer and TPA Branch IDs and IDs
-        if(isset($data['insurer_id']) && !empty($data['insurer_id'])){
+        if (isset($data['insurer_id']) && !empty($data['insurer_id'])) {
             list($data['insurer_branch_id'], $data['insurer_id']) = explode('-', $data['insurer_id']);
             if (isset($data['tpa']) && !empty($data['tpa'])) {
                 list($data['tpa_branch_id'], $data['tpa_id']) = explode('-', $data['tpa']);
             }
         }
-    
+
         $data['tsi'] = generate_tsi_code($data['issue_type']);
         $data['action_type'] = 'inception';
 
@@ -287,13 +287,13 @@ class PolicyTransactionController extends BaseController
         } elseif ($data['co_share']) {
             $data['co_share'] = 1;
         }
-    
+
         if (!isset($data['bro_payable_by'])) {
             $data['bro_payable_by'] = 0;
         } elseif ($data['bro_payable_by']) {
             $data['bro_payable_by'] = 1;
         }
-    
+
         if (!isset($data['same_as_proposer'])) {
             $data['same_as_proposer'] = 0;
         } elseif ($data['same_as_proposer']) {
@@ -312,24 +312,23 @@ class PolicyTransactionController extends BaseController
             $data['is_cd_reduce_from_bds'] = 1;
         }
 
-        if($data['ct_type'] == ""){
+        if ($data['ct_type'] == "") {
             $data['ct_type'] = 1;
         }
 
         // $month = '01-'.(string)$this->request->getPost('month');
         // $data['month'] = empty($data['month']) ? null : date('Y-m-d', strtotime($month));    
-    
+
         // Determine $is_addon value
-        $data['is_addon'] = in_array($data['policy_type_id'], [1, 2, 6, 7]) ? 1 :
-                            (in_array($data['policy_type_id'], [4, 5]) ? 2 : ($data['policy_type_id'] == 3 && isset($data['base_policy']) ? 3 : 1));
-    
+        $data['is_addon'] = in_array($data['policy_type_id'], [1, 2, 6, 7]) ? 1 : (in_array($data['policy_type_id'], [4, 5]) ? 2 : ($data['policy_type_id'] == 3 && isset($data['base_policy']) ? 3 : 1));
+
         // print_r($data); die;
 
         return $data;
     }
-    
+
     private function insertInceptionPolicy($data)
-    {   
+    {
         // print_r($data); die;
 
         $insert = $this->policyTransactionModel->insert($data);
@@ -337,7 +336,7 @@ class PolicyTransactionController extends BaseController
             $this->insertTransactionStatus($insert, $data, 1);
             $emp_data = $this->processInsertIndividualMemberInEmpTable($data);
 
-            if(isset($data['follow_insurer_id']) && !empty($data['follow_insurer_id'][0])){
+            if (isset($data['follow_insurer_id']) && !empty($data['follow_insurer_id'][0])) {
 
                 $pt_co_share_details = $this->insertOrUpdateCoShareDetails($data, $insert);
 
@@ -356,7 +355,7 @@ class PolicyTransactionController extends BaseController
 
                 $data['pt_co_share_details'] = $this->PTCOShareDetailsModel->where('pt_id', $insert)->where('is_active', 1)->findAll();
             }
-            
+
             $client_data = $this->clientModel->where('id', $data['client_id'])->first();
             $data['client_kyc']       = $this->clientKYCDocsModel->where('client_id',  $data['client_id'])->findAll();
             $data['entity_type_id'] =  $client_data['entity_type_id'];
@@ -365,77 +364,76 @@ class PolicyTransactionController extends BaseController
         }
         return $this->respondError("Failed to create policy transaction");
     }
-    
+
     private function updateInceptionPolicy($id, $data)
-    {   
+    {
         // print_r($data); die;
         if ($this->policyTransactionModel->update($id, $data)) {
-    
+
             $this->insertTransactionStatus($id, $data, 1);
             $emp_data = $this->processInsertIndividualMemberInEmpTable($data);
-    
+
             if (isset($data['follow_insurer_id']) && !empty($data['follow_insurer_id'][0])) {
-    
+
                 $this->insertOrUpdateCoShareDetails($data, $id);
 
                 if ($data['ct_type'] == 1) {
-                    $this->policyTransactionModel->update($id, ['client_policy_id' => $data['client_policy_id']]);    
+                    $this->policyTransactionModel->update($id, ['client_policy_id' => $data['client_policy_id']]);
                 }
-    
+
                 if (empty($data['client_policy_id']) || $data['client_policy_id'] == 0) {
-    
+
                     if ($data['ct_type'] == 2) {
                         $client_policy_insert_data = $this->prepareClientPolicyInsertData($data);
                         $client_policy_id = $this->clientPolicyModel->insert($client_policy_insert_data);
-                        $this->policyTransactionModel->update($id, ['client_policy_id' => $client_policy_id]);    
+                        $this->policyTransactionModel->update($id, ['client_policy_id' => $client_policy_id]);
                         $this->InsertIndividualEmpPolicyTable($emp_data, $client_policy_id);
                     }
-    
                 } else {
                     if (isset($data['emp_policy_id']) && !empty($data['emp_policy_id'][0])) {
                         $this->InsertIndividualEmpPolicyTable($emp_data, $data['client_policy_id']);
                     }
                 }
-    
+
                 if ($data['status'] == 'completed' && $data['ct_type'] == 2) {
-                    if($data['client_type'] == 1 && $data['is_cd_reduce_from_bds'] == 1){
+                    if ($data['client_type'] == 1 && $data['is_cd_reduce_from_bds'] == 1) {
                         $this->processCompletedStatus($data, $data['client_policy_id'], $data['insurer_id']);
                     }
                 }
-    
+
                 $data['pt_co_share_details'] = $this->PTCOShareDetailsModel->where('pt_id', $id)->where('is_active', 1)->findAll();
             }
-    
+
             $client_data = $this->clientModel->where('id', $data['client_id'])->first();
             $data['client_kyc']       = $this->clientKYCDocsModel->where('client_id',  $data['client_id'])->findAll();
             $data['entity_type_id'] =  $client_data['entity_type_id'];
 
             return $this->respondSuccess($id, "Policy transaction updated successfully", $data);
         }
-    
+
         return $this->respondError("Failed to update policy transaction");
     }
-    
+
     private function insertOrUpdateCoShareDetails($data, $pt_id)
-    {   
+    {
         // Prepare data for insertion and updating
         $coShareDetails = [];
-        
+
         // print_r($data); die;
         // die;
 
-        if(isset($data['co_share_id']) && !empty($data['co_share_id'])){
+        if (isset($data['co_share_id']) && !empty($data['co_share_id'])) {
             $this->removePtCoShareRecords($data['co_share_id'], $pt_id);
         }
 
-        if(isset($data['follow_insurer_id'])){
+        if (isset($data['follow_insurer_id'])) {
 
             foreach ($data['follow_insurer_id'] as $index => $insurer) {
-                
+
                 // Separate the insurer and insurer branch
-                if(isset($insurer) && !empty($insurer)){
-                    list($insurer_branch_id, $insurer_id) = explode('-', $insurer);                
-                }else{
+                if (isset($insurer) && !empty($insurer)) {
+                    list($insurer_branch_id, $insurer_id) = explode('-', $insurer);
+                } else {
                     $insurer_branch_id = null;
                     $insurer_id = null;
                 }
@@ -481,47 +479,46 @@ class PolicyTransactionController extends BaseController
                     'created_by' => get_session_userid() ?? null,
                     'updated_by' => get_session_userid() ?? null,
                     'id' => $data['co_share_id'][$index] ?? null, // Assuming this is the ID to identify existing records
-                    'follower_policy_no' => $data['follower_policy_no'][$index] ?? null, 
-                    'non_comm_per_amt' => $data['non_comm_per_amt'][$index] ?? null, 
+                    'follower_policy_no' => $data['follower_policy_no'][$index] ?? null,
+                    'non_comm_per_amt' => $data['non_comm_per_amt'][$index] ?? null,
                 ];
             }
 
             // print_r($pt_id); 
             // print_r($coShareDetails); 
             // die;
-        
+
             // Separate data into insert and update batches
-            $insertData = array_filter($coShareDetails, function($detail) {
+            $insertData = array_filter($coShareDetails, function ($detail) {
                 return empty($detail['id']); // Only insert new records
             });
-        
-            $updateData = array_filter($coShareDetails, function($detail) {
+
+            $updateData = array_filter($coShareDetails, function ($detail) {
                 return !empty($detail['id']); // Only update existing records
             });
-        
+
             // Insert new records
             if (!empty($insertData)) {
                 $this->PTCOShareDetailsModel->insertBatch($insertData);
             }
-        
+
             // Update existing records
             if (!empty($updateData)) {
                 $this->PTCOShareDetailsModel->updateBatch($updateData, 'id'); // Assuming 'id' is the unique identifier
             }
-            
+
             // print_r($this->PTCOShareDetailsModel->getLastQuery()); die;
 
             // print_r($coShareDetails); 
             // die;
 
             return true;
-
         }
-        
+
         // print_r($data); 
         // die;
     }
-    
+
     private function prepareClientPolicyInsertData($data)
     {
         return [
@@ -532,7 +529,7 @@ class PolicyTransactionController extends BaseController
             'tpa_branch_id' => $data['tpa_branch_id'] ?? null,
             'policy_type_id' => $data['policy_type_id'] ?? null,
             'policy_start_date' => $data['policy_start_date'] ?? null,
-            'policy_end_date' => $data['policy_end_date'] ?? null ,
+            'policy_end_date' => $data['policy_end_date'] ?? null,
             'policy_status' => 1,
             'is_addon' => $data['is_addon'] ?? null,
             'base_policy' => $data['base_policy'] ?? 0,
@@ -543,7 +540,7 @@ class PolicyTransactionController extends BaseController
             'gst' => 18,
         ];
     }
-    
+
     private function insertTransactionStatus($policyTranId, $data, $statusType)
     {
         $statusData = [
@@ -555,12 +552,12 @@ class PolicyTransactionController extends BaseController
         ];
         $this->policyTransactionStatusModel->insert($statusData);
     }
-    
+
     private function processCompletedStatus($data, $client_policy_id, $insurer_id)
     {
         $totalAmount = (int)$data['total'][0] ?? 0;
         $description = 'The following amount of Rs. ' . $totalAmount . '/- has been debited for the ' . $data['emp_count'] . ' employees at Inception (BDS).';
-    
+
         $cdTransactionData = [
             'amount' => $totalAmount,
             'sub_type_id' => 4,
@@ -581,32 +578,32 @@ class PolicyTransactionController extends BaseController
     }
 
     private function processInsertIndividualMemberInEmpTable($data)
-    {   
+    {
         // print_r($data);
-        if(isset($data['family_name']) && !empty($data['family_name'])){
+        if (isset($data['family_name']) && !empty($data['family_name'])) {
 
             $emp_data = [];
             $emp_ids = [];
             $random_code = generateRandomCode(); // Generate random code once
-            
+
             foreach ($data['family_name'] as $index => $val) {
-            
+
                 // Determine the gender based on the relationship
                 $relationship = $data['relationship'][$index] ?? '';
                 $gender = 'M'; // Default to Male
-                
+
                 // Set gender based on relationship
                 if (in_array($relationship, ['Mother', 'Daughter', 'Mother in law', 'Spouse'])) {
                     $gender = 'F';
                 }
-            
+
                 $emp_data[] = [
                     'client_id' => $data['client_id'] ?? 0,
                     'client_branch_id' => $data['client_branch_id'] ?? 0,
                     'name' => $val,
                     'relationship' => $relationship,
-                    'gender' => $gender, 
-                    'emp_status' => 'active', 
+                    'gender' => $gender,
+                    'emp_status' => 'active',
                     'created_by' => get_session_userid(),
                     'emp_code' => $random_code, // Use the same random code for all
                     'id' => $data['emp_id'][$index] ?? null
@@ -614,52 +611,51 @@ class PolicyTransactionController extends BaseController
 
                 $emp_ids[] = $data['emp_id'][$index] ?? 0;
             }
-            
-            
+
+
             // print_r($emp_data); die;
-            
+
             // Separate data into insert and update batches
-            $insertData = array_filter($emp_data, function($detail) {
+            $insertData = array_filter($emp_data, function ($detail) {
                 return empty($detail['id']); // Only insert new records
             });
-        
-            $updateData = array_filter($emp_data, function($detail) {
+
+            $updateData = array_filter($emp_data, function ($detail) {
                 return !empty($detail['id']); // Only update existing records
             });
-        
+
             // Insert new records
             if (!empty($insertData)) {
                 $this->employeeModel->insertBatch($insertData);
             }
-        
+
             // Update existing records
             if (!empty($updateData)) {
                 $this->employeeModel->updateBatch($updateData, 'id'); // Assuming 'id' is the unique identifier
             }
-            
-            return $emp_ids;
 
+            return $emp_ids;
         }
     }
 
     private function InsertIndividualEmpPolicyTable($emp_ids, $client_policy_id)
-    {   
-        if(!empty($emp_ids)){
+    {
+        if (!empty($emp_ids)) {
 
             $emp_policy_data = [];
-            
+
             foreach ($emp_ids as $index => $emp_id) {
 
                 $emp_policy_data[] = [
                     'employee_id' => $emp_id ?? 0,
                     'client_policy_id' => $client_policy_id ?? 0,
                     'created_by' => get_session_userid(),
-                    'status' => 'active', 
+                    'status' => 'active',
                 ];
             }
-            
+
             // print_r($emp_policy_data); die;
-            
+
             // Insert new records
             if (!empty($emp_policy_data)) {
                 $this->employeePolicyModel->insertBatch($emp_policy_data);
@@ -667,15 +663,14 @@ class PolicyTransactionController extends BaseController
 
 
             return true;
-
         }
     }
-    
+
     private function respondSuccess($id, $message, $data)
     {
-        return $this->respond(['status' => true, 'pt_id' => $id, 'message' => $message, 'data' =>$data], 200);
+        return $this->respond(['status' => true, 'pt_id' => $id, 'message' => $message, 'data' => $data], 200);
     }
-    
+
     private function respondError($message)
     {
         return $this->respond(['status' => false, 'message' => $message], 200);
@@ -686,7 +681,7 @@ class PolicyTransactionController extends BaseController
     public function getInceptionDataForEdit($id)
     {
         $data = $this->policyTransactionModel
-                ->select('
+            ->select('
                         policy_transaction.*, 
                         clients.short_name as client_short_name, 
                         clients.client_type, 
@@ -707,83 +702,83 @@ class PolicyTransactionController extends BaseController
 
                         ) as last_action_date
                     ')
-                ->join('clients', 'clients.id = policy_transaction.client_id')
-                ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
-                ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left')
-                ->where('policy_transaction.id', $id)
-                ->where('policy_transaction.is_active', 1)
-                ->first();
+            ->join('clients', 'clients.id = policy_transaction.client_id')
+            ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
+            ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left')
+            ->where('policy_transaction.id', $id)
+            ->where('policy_transaction.is_active', 1)
+            ->first();
 
-            // $data['policy_issue_date'] = (isset($data['policy_issue_date']) && $data['policy_issue_date'] !== null && $data['policy_issue_date'] !== '') 
-            //     ? date('d/m/Y', strtotime($data['policy_issue_date'])) 
-            //     : null;
-            
-            // $data['policy_start_date'] = (isset($data['policy_start_date']) && $data['policy_start_date'] !== null && $data['policy_start_date'] !== '') 
-            //     ? date('d/m/Y', strtotime($data['policy_start_date'])) 
-            //     : null;
-            
-            // $data['policy_end_date'] = (isset($data['policy_end_date']) && $data['policy_end_date'] !== null && $data['policy_end_date'] !== '') 
-            //     ? date('d/m/Y', strtotime($data['policy_end_date'])) 
-            //     : null;
-            
-            // $data['renewal_date'] = (isset($data['renewal_date']) && $data['renewal_date'] !== null && $data['renewal_date'] !== '') 
-            //     ? date('d/m/Y', strtotime($data['renewal_date'])) 
-            //     : null;
-            
-            // $data['rollover_date'] = (isset($data['rollover_date']) && $data['rollover_date'] !== null && $data['rollover_date'] !== '') 
-            //     ? date('d/m/Y', strtotime($data['rollover_date'])) 
-            //     : null;
-            
-            // $data['month'] = (isset($data['month']) && $data['month'] !== null && $data['month'] !== '') 
-            //     ? date('M/Y', strtotime($data['month'])) 
-            //     : null;
+        // $data['policy_issue_date'] = (isset($data['policy_issue_date']) && $data['policy_issue_date'] !== null && $data['policy_issue_date'] !== '') 
+        //     ? date('d/m/Y', strtotime($data['policy_issue_date'])) 
+        //     : null;
 
-            
-            $data['created_at'] = (isset($data['created_at']) && $data['created_at'] !== null && $data['created_at'] !== '') 
-                ? date('d/m/Y h:i:s A', strtotime($data['created_at'])) 
-                : null;
-            
-            $data['updated_at'] = (isset($data['updated_at']) && $data['updated_at'] !== null && $data['updated_at'] !== '') 
-                ? date('d/m/Y h:i:s A', strtotime($data['updated_at'])) 
-                : null;
-            
+        // $data['policy_start_date'] = (isset($data['policy_start_date']) && $data['policy_start_date'] !== null && $data['policy_start_date'] !== '') 
+        //     ? date('d/m/Y', strtotime($data['policy_start_date'])) 
+        //     : null;
+
+        // $data['policy_end_date'] = (isset($data['policy_end_date']) && $data['policy_end_date'] !== null && $data['policy_end_date'] !== '') 
+        //     ? date('d/m/Y', strtotime($data['policy_end_date'])) 
+        //     : null;
+
+        // $data['renewal_date'] = (isset($data['renewal_date']) && $data['renewal_date'] !== null && $data['renewal_date'] !== '') 
+        //     ? date('d/m/Y', strtotime($data['renewal_date'])) 
+        //     : null;
+
+        // $data['rollover_date'] = (isset($data['rollover_date']) && $data['rollover_date'] !== null && $data['rollover_date'] !== '') 
+        //     ? date('d/m/Y', strtotime($data['rollover_date'])) 
+        //     : null;
+
+        // $data['month'] = (isset($data['month']) && $data['month'] !== null && $data['month'] !== '') 
+        //     ? date('M/Y', strtotime($data['month'])) 
+        //     : null;
+
+
+        $data['created_at'] = (isset($data['created_at']) && $data['created_at'] !== null && $data['created_at'] !== '')
+            ? date('d/m/Y h:i:s A', strtotime($data['created_at']))
+            : null;
+
+        $data['updated_at'] = (isset($data['updated_at']) && $data['updated_at'] !== null && $data['updated_at'] !== '')
+            ? date('d/m/Y h:i:s A', strtotime($data['updated_at']))
+            : null;
+
+
+        if (!empty($data['policy_issue_date'])) {
+            $data['policy_issue_date'] =  change_date_format($data['policy_issue_date'], 'Y-m-d', 'd/m/Y');
+        }
+
+        if (!empty($data['policy_start_date'])) {
+            $data['policy_start_date'] =  change_date_format($data['policy_start_date'], 'Y-m-d', 'd/m/Y');
+        }
+
+        if (!empty($data['policy_end_date'])) {
+            $data['policy_end_date'] =  change_date_format($data['policy_end_date'], 'Y-m-d', 'd/m/Y');
+        }
+
+        if (!empty($data['renewal_date'])) {
+            $data['renewal_date'] =  change_date_format($data['renewal_date'], 'Y-m-d', 'd/m/Y');
+        }
+
+        if (!empty($data['rollover_date'])) {
+            $data['rollover_date'] =  change_date_format($data['rollover_date'], 'Y-m-d', 'd/m/Y');
+        }
+
+        if (!empty($data['endorse_eff_date'])) {
+            $data['endorse_eff_date'] =  change_date_format($data['endorse_eff_date'], 'Y-m-d', 'd/m/Y');
+        }
+
+        if (!empty($data['last_action_date'])) {
+            $data['last_action_date'] =  change_date_format($data['last_action_date'], 'Y-m-d', 'd/m/Y');
+        }
+
+        if (!empty($data['month'])) {
+            $data['month'] =  change_date_format($data['month'], 'Y-m-d', 'M/Y');
+        } else {
+            $data['month'] = null;
+        }
 
-            if(!empty($data['policy_issue_date'])){
-                $data['policy_issue_date'] =  change_date_format($data['policy_issue_date'], 'Y-m-d', 'd/m/Y');
-            }
 
-            if(!empty($data['policy_start_date'])){
-                $data['policy_start_date'] =  change_date_format($data['policy_start_date'], 'Y-m-d', 'd/m/Y');
-            }
-    
-            if(!empty($data['policy_end_date'])){
-                $data['policy_end_date'] =  change_date_format($data['policy_end_date'], 'Y-m-d', 'd/m/Y');
-            }
-    
-            if(!empty($data['renewal_date'])){
-                $data['renewal_date'] =  change_date_format($data['renewal_date'], 'Y-m-d', 'd/m/Y');
-            }
-    
-            if(!empty($data['rollover_date'])){
-                $data['rollover_date'] =  change_date_format($data['rollover_date'], 'Y-m-d', 'd/m/Y');
-            }
-    
-            if(!empty($data['endorse_eff_date'])){
-                $data['endorse_eff_date'] =  change_date_format($data['endorse_eff_date'], 'Y-m-d', 'd/m/Y');
-            }
 
-            if(!empty($data['last_action_date'])){
-                $data['last_action_date'] =  change_date_format($data['last_action_date'], 'Y-m-d', 'd/m/Y');
-            }
-    
-            if(!empty($data['month'])){
-                $data['month'] =  change_date_format($data['month'], 'Y-m-d', 'M/Y');
-            }else{
-                $data['month'] = null;
-            }
-    
-            
-                
         // print_r($data); die;
 
         $data['renewal_policy'] = $this->clientPolicyModel
@@ -794,15 +789,15 @@ class PolicyTransactionController extends BaseController
             ->where('client_policy.is_active', 1)
             ->findAll();
 
-       
+
         $data['base_policy_data'] = $this->clientPolicyModel
-                ->select('client_policy.*, policy_type.policy_type')
-                ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
-                ->where('client_policy.client_id', $data['client_id'])
-                ->where('client_policy.client_branch_id', $data['client_branch_id'])
-                ->whereIn('client_policy.policy_type_id', [2, 3])
-                ->where('client_policy.is_active', 1)
-                ->findAll();
+            ->select('client_policy.*, policy_type.policy_type')
+            ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
+            ->where('client_policy.client_id', $data['client_id'])
+            ->where('client_policy.client_branch_id', $data['client_branch_id'])
+            ->whereIn('client_policy.policy_type_id', [2, 3])
+            ->where('client_policy.is_active', 1)
+            ->findAll();
 
 
         $ptFileQuery = $this->PTFileModel
@@ -811,7 +806,7 @@ class PolicyTransactionController extends BaseController
             ->where('pt_files.is_active', 1);
 
         if (!in_array(get_role_id(), [1, 5]) && empty(array_intersect(user_team(), [MANAGEMENT_TEAM_ID, FINANCE_TEAM_ID, BUSINESS_TEAM_ID]))) {
-            
+
             if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
                 $ptFileQuery->where('pt_files.created_by', get_session_userid());
             }
@@ -822,7 +817,7 @@ class PolicyTransactionController extends BaseController
 
 
         $data['pt_co_share_details'] = $this->PTCOShareDetailsModel
-                ->select("
+            ->select("
                     pt_co_share_details.*,
             
                     (
@@ -938,41 +933,39 @@ class PolicyTransactionController extends BaseController
                         ) AS actual_tep_brokerage_amount
 
                 ")
-                ->where('pt_id', $id)
-                ->where('is_active', 1)
-                ->orderBy('id', 'asc')
-                ->findAll();
-            
+            ->where('pt_id', $id)
+            ->where('is_active', 1)
+            ->orderBy('id', 'asc')
+            ->findAll();
+
         $data['emp_data'] = $this->employeeModel
-                        ->select('employees.*, employee_polices.id as emp_policy_id')
-                        ->join('employee_polices', 'employees.id = employee_polices.employee_id', 'left')
-                        ->where('employees.client_id', $data['client_id'])
-                        ->where('employees.is_active', 1)->findAll();
+            ->select('employees.*, employee_polices.id as emp_policy_id')
+            ->join('employee_polices', 'employees.id = employee_polices.employee_id', 'left')
+            ->where('employees.client_id', $data['client_id'])
+            ->where('employees.is_active', 1)->findAll();
         $data['client_kyc']   = $this->clientKYCDocsModel->where('client_id',  $data['client_id'])->findAll();
         $data['vehicle_docs'] = $this->clientKYCDocsModel
-                        ->where('client_id',  $data['client_id'])
-                        ->where('vehicle_id', $data['vehicle_id'])
-                        ->findAll();
+            ->where('client_id',  $data['client_id'])
+            ->where('vehicle_id', $data['vehicle_id'])
+            ->findAll();
 
         // print_r( $data['pt_co_share_details']); die;
 
-        if($data){
+        if ($data) {
             return $this->respond(['status' => true, 'data' => $data], 200);
-        }else{
+        } else {
             return $this->respond(['status' => false], 200);
         }
-
     }
 
     public function removePolicyTransaction($id)
     {
         if ($id) {
-            
+
             $data['is_active']  = 0;
             $this->policyTransactionModel->where('id', $id)->set($data)->update();
             $this->PTCOShareDetailsModel->where('pt_id', $id)->set($data)->update();
             return $this->respond(['status' => true, 'code' => 200, 'message' => 'Policy Transaction removed successfully'], 200);
-        
         } else {
 
             return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to remove policy transaction'], 200);
@@ -980,31 +973,31 @@ class PolicyTransactionController extends BaseController
     }
 
     //function for soft delete for pt_co_share_details records
-    public function removePtCoShareRecords($primaryKeys, $pt_id) 
+    public function removePtCoShareRecords($primaryKeys, $pt_id)
     {
         if (empty($primaryKeys)) {
-            return false; 
+            return false;
         }
-    
+
         // Convert array to a comma-separated string of placeholders for query binding
         $placeholders = implode(',', array_fill(0, count($primaryKeys), '?'));
-    
+
         // Prepare the query with proper binding
         $sql = "UPDATE pt_co_share_details SET is_active = 0 WHERE pt_id = ? AND id NOT IN ($placeholders)";
-        
+
         // Merge pt_id with primary keys for binding
         $params = array_merge([$pt_id], $primaryKeys);
-        
+
         // Execute the query with bound parameters
         return db_connect()->query($sql, $params);
     }
-    
-    
+
+
     //------------------------------------------------------------------------------------------------
 
     // Policy Transaction Endorsement
     public function viewEndorsement()
-    {   
+    {
         // echo '
';
         // !dd($this->getEndorsementDataForEdit(17));
 
@@ -1062,16 +1055,16 @@ class PolicyTransactionController extends BaseController
         $date_type = $this->request->getGet('date_type');
         $issuer = $this->request->getGet('issuer');
         $status = $this->request->getGet('status');
-        
+
         $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date;
         $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date;
-        
+
         $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
-        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;      
-        $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;      
-        $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;      
-        $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;   
-        $status = (!isset($issuer) || $status === '' || $status === null) ? 0 : $status;   
+        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
+        $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;
+        $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;
+        $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;
+        $status = (!isset($issuer) || $status === '' || $status === null) ? 0 : $status;
 
 
         $data['endorsement_data_list'] = $this->policyTransactionModel->getEndorsementTranctionListData($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status);
@@ -1080,8 +1073,8 @@ class PolicyTransactionController extends BaseController
 
         $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll();
         // $data['tpa']           = $this->tpaModel->where('is_active', 1)->findAll();
-        $data['insurer_branch']      = $this->insurerBranchModel ->getInsurerBranchesWithInsurerNames();
-        $data['tpa']           = $this->tpaBranchModel ->getTpaBranchesWithTpaNames();
+        $data['insurer_branch']      = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
+        $data['tpa']           = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
 
 
         $this->loadLayout('policy_transaction_endorsement_list', $data);
@@ -1092,7 +1085,7 @@ class PolicyTransactionController extends BaseController
         $id = $this->request->getPost('id');
         $data = $this->preparePolicyTransactionData();
         // print_r($data); die;
-        
+
         if (!$id) {
             return $this->insertEndorsementTransaction($data);
         } else {
@@ -1120,47 +1113,45 @@ class PolicyTransactionController extends BaseController
             $data['is_cd_reduce_from_bds'] = 1;
         }
 
-        if(empty($data['data_received_date'])){
+        if (empty($data['data_received_date'])) {
             $data['data_received_date'] = null;
-        }else{
+        } else {
             $data['data_received_date'] =  change_date_format($data['data_received_date'], 'd/m/Y', 'Y-m-d');
         }
 
-        if(empty($data['policy_issue_date'])){
+        if (empty($data['policy_issue_date'])) {
             $data['policy_issue_date'] = null;
-        }else{
+        } else {
             $data['policy_issue_date'] =  change_date_format($data['policy_issue_date'], 'd/m/Y', 'Y-m-d');
         }
 
-        if(empty($data['endorse_eff_date'])){
+        if (empty($data['endorse_eff_date'])) {
             $data['endorse_eff_date'] = null;
-        }else{
+        } else {
             $data['endorse_eff_date'] =  change_date_format($data['endorse_eff_date'], 'd/m/Y', 'Y-m-d');
-
         }
 
-        if(empty($data['install_due_date'])){
+        if (empty($data['install_due_date'])) {
             $data['install_due_date'] = null;
-        }else{
+        } else {
             $data['install_due_date'] =  change_date_format($data['install_due_date'], 'd/m/Y', 'Y-m-d');
-
         }
 
-        if(!empty($data['month'])){
-            $month = '01/'.$data['month'];
+        if (!empty($data['month'])) {
+            $month = '01/' . $data['month'];
             $data['month'] =  change_date_format($month, 'd/M/Y', 'Y-m-d');
         }
 
-        if(empty($data['last_action_date'])){
+        if (empty($data['last_action_date'])) {
             $data['last_action_date'] = null;
-        }else{
+        } else {
             $data['last_action_date'] = change_date_format($data['last_action_date']);
         }
 
         // print_r($data); die;   
 
         // Separate Insurer and TPA Branch IDs and IDs
-        if(isset($data['insurer_id']) && !empty($data['insurer_id'])){
+        if (isset($data['insurer_id']) && !empty($data['insurer_id'])) {
             list($data['insurer_branch_id'], $data['insurer_id']) = explode('-', $data['insurer_id']);
             if (isset($data['tpa']) && !empty($data['tpa'])) {
                 list($data['tpa_branch_id'], $data['tpa_id']) = explode('-', $data['tpa']);
@@ -1168,20 +1159,20 @@ class PolicyTransactionController extends BaseController
         }
 
         $issue_type = $this->policyTransactionModel
-                        ->where('action_type', 'inception')
-                        ->where('client_id', $this->request->getPost('client_id'))
-                        ->where('client_policy_id', $this->request->getPost('client_policy_id'))
-                        ->where('policy_transaction.is_active', 1)
-                        ->first();
+            ->where('action_type', 'inception')
+            ->where('client_id', $this->request->getPost('client_id'))
+            ->where('client_policy_id', $this->request->getPost('client_policy_id'))
+            ->where('policy_transaction.is_active', 1)
+            ->first();
 
         $data['tsi'] = generate_tsi_code($issue_type['issue_type'] ?? 1);
 
         $client_branch_id = $data['client_branch_id'];
-        if($data['client_branch_id'] == ""){
+        if ($data['client_branch_id'] == "") {
             $client_branch_id = $issue_type['client_branch_id'];
         }
 
-        if(!$data['id']){
+        if (!$data['id']) {
 
             $data += [
                 'issuer' => $issue_type['issuer'] ?? null,
@@ -1189,8 +1180,8 @@ class PolicyTransactionController extends BaseController
                 'policy_type_id' => $issue_type['policy_type_id'] ?? null,
                 'issue_type' => $issue_type['issue_type'] ?? null,
                 'source_client_policy_id' => $issue_type['source_client_policy_id'] ?? null,
-                'cd_ac_no' => isset( $data['cd_ac_no']) && !empty($data['cd_ac_no']) ? $data['cd_ac_no'] : $issue_type['cd_ac_no'] ?? null,
-                'cd_ac_pk' => isset( $data['cd_ac_pk']) && !empty($data['cd_ac_pk']) ? $data['cd_ac_pk'] : $issue_type['cd_ac_pk'] ?? null,
+                'cd_ac_no' => isset($data['cd_ac_no']) && !empty($data['cd_ac_no']) ? $data['cd_ac_no'] : $issue_type['cd_ac_no'] ?? null,
+                'cd_ac_pk' => isset($data['cd_ac_pk']) && !empty($data['cd_ac_pk']) ? $data['cd_ac_pk'] : $issue_type['cd_ac_pk'] ?? null,
                 // 'policy_issue_date' => $issue_type['policy_issue_date'] ?? null,
                 'policy_start_date' => $issue_type['policy_start_date'] ?? null,
                 'policy_end_date' => $issue_type['policy_end_date'] ?? null,
@@ -1200,7 +1191,7 @@ class PolicyTransactionController extends BaseController
                 'installment' => $issue_type['installment'] ?? null,
                 'installment_data' => $issue_type['installment_data'] ?? null,
                 'location' => $issue_type['location'] ?? null,
-                'links' =>  $issue_type['links'] ??null,
+                'links' =>  $issue_type['links'] ?? null,
                 'stage' => $issue_type['stage'] ?? null,
                 'etat' => $issue_type['etat'] ?? null,
                 'etat_band' => $issue_type['etat_band'] ?? null,
@@ -1262,13 +1253,13 @@ class PolicyTransactionController extends BaseController
     }
 
     private function handleCompletedStatus($data, $policy_tran_id)
-    {    
+    {
         if ($data['client_type'] == 1 && $data['status'] == 'completed' && $data['is_cd_reduce_from_bds'] == 1) {
 
             $tolamt = $data['total'][0] ?? 0;
 
-            $description = 'The following amount of Rs. ' . round($tolamt, 2) . '/- has been' . 
-                        ($data['action_type'] == 'deletion' ? ' Credit ' : ' Debit ') . 'from the policy transaction (BDS)';
+            $description = 'The following amount of Rs. ' . round($tolamt, 2) . '/- has been' .
+                ($data['action_type'] == 'deletion' ? ' Credit ' : ' Debit ') . 'from the policy transaction (BDS)';
 
             $cd_tranction_data = [
                 'amount' => $tolamt,
@@ -1486,13 +1477,13 @@ class PolicyTransactionController extends BaseController
 
     //file upload function 
     public function uploadFile()
-    {   
+    {
         $GoogleDriveController = new GoogleDriveController();
         $files = $this->request->getFiles();
-        $doc_name = $this->request->getPost('doc_name[]');     
-        $pt_id = $this->request->getPost('pt_id');     
-        $client_policy_id = $this->request->getPost('client_policy_id');     
-        $data = $this->request->getPost();     
+        $doc_name = $this->request->getPost('doc_name[]');
+        $pt_id = $this->request->getPost('pt_id');
+        $client_policy_id = $this->request->getPost('client_policy_id');
+        $data = $this->request->getPost();
 
         $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';
 
@@ -1525,7 +1516,7 @@ class PolicyTransactionController extends BaseController
                     $insert = $this->PTFileModel->insert($docData);
 
                     if ($insert) {
-                        $uploadData[] = $docData; 
+                        $uploadData[] = $docData;
                     }
                 }
             }
@@ -1534,23 +1525,23 @@ class PolicyTransactionController extends BaseController
         // print_r($uploadData); die;
 
         // $uploadData = uploadFilesToGoogleDrive($files['file'], $doc_name, $pt_id);
-        
+
         if (!empty($uploadData)) {
 
-        $ptFileQuery = $this->PTFileModel
-            ->join('policy_transaction', 'pt_files.pt_id = policy_transaction.id')
-            ->where('pt_files.pt_id', $pt_id)
-            ->where('pt_files.is_active', 1);
+            $ptFileQuery = $this->PTFileModel
+                ->join('policy_transaction', 'pt_files.pt_id = policy_transaction.id')
+                ->where('pt_files.pt_id', $pt_id)
+                ->where('pt_files.is_active', 1);
 
-        if (!in_array(get_role_id(), [1, 5]) && empty(array_intersect(user_team(), [MANAGEMENT_TEAM_ID, FINANCE_TEAM_ID, BUSINESS_TEAM_ID]))) {
-            
-            if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
-                $ptFileQuery->where('pt_files.created_by', get_session_userid());
+            if (!in_array(get_role_id(), [1, 5]) && empty(array_intersect(user_team(), [MANAGEMENT_TEAM_ID, FINANCE_TEAM_ID, BUSINESS_TEAM_ID]))) {
+
+                if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
+                    $ptFileQuery->where('pt_files.created_by', get_session_userid());
+                }
             }
-        }
 
-        $data['pt_files'] = $ptFileQuery->findAll();        
-                 
+            $data['pt_files'] = $ptFileQuery->findAll();
+
             return $this->respond(['status' => true, 'message' => 'File uploaded successfully in G-Drive', 'data' => $data]);
         } else {
             return $this->respond(['status' => false, 'message' => 'Failed to upload file in G-Drive']);
@@ -1566,7 +1557,7 @@ class PolicyTransactionController extends BaseController
         // var_dump($ids); die;
 
         $data['invoice_status'] = $this->request->getPost('invoice_status');
-        if($this->request->getPost('invoice_status') == 'generated'){
+        if ($this->request->getPost('invoice_status') == 'generated') {
             $data['invoice_no'] = $this->request->getPost('invoice_no');
         }
 
@@ -1575,8 +1566,8 @@ class PolicyTransactionController extends BaseController
             ->whereIn('id', $ids)
             ->set($data)
             ->update();
-            
-    
+
+
         if ($update) {
 
             return $this->respond(['status' => true, 'data' => $ids, 'message' => 'Invoice status updated successfully'], 200);
@@ -1593,7 +1584,7 @@ class PolicyTransactionController extends BaseController
             'updated_by' => get_session_userid(),
             'is_active' => 0
         ];
-        
+
         $update = $this->PTCOShareDetailsModel->where('id', $id)->set($data)->update();
 
         if ($update) {
@@ -1636,8 +1627,8 @@ class PolicyTransactionController extends BaseController
             ->where('action_type', 'inception')
             ->where('is_active', 1)
             ->first();
-            
-        $cd_ac_no = db_connect()->table('cd_master')->where('id', $is_copay_yes['cd_ac_pk'] ?? null)->get()->getRowArray();    
+
+        $cd_ac_no = db_connect()->table('cd_master')->where('id', $is_copay_yes['cd_ac_pk'] ?? null)->get()->getRowArray();
 
         if ($totalCount) {
             return $this->respond(['status' => true, 'code' => 200, 'data' => $totalCount, 'is_copay_yes' => $is_copay_yes, "cd_master_data" => $cd_ac_no], 200);
@@ -1645,7 +1636,6 @@ class PolicyTransactionController extends BaseController
             $insurer_data = $this->clientPolicyModel->where('id', $client_policy_id)->where('is_active', 1)->first();
             return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to get data'], 200);
         }
-
     }
 
     public function checkInvoiceStatus($pt_id)
@@ -1660,28 +1650,28 @@ class PolicyTransactionController extends BaseController
             ->where('insurer_statements.invoice_no IS NOT NULL')
             ->countAllResults();
 
-        if($data){
-            return $this->respond(['status' => true, 'count'=> $data,  'code' => 200], 200);
-        }else{
-            return $this->respond(['status' => false, 'count'=> 0, 'message' => 'No Data Found', 'code' => 404], 200);
+        if ($data) {
+            return $this->respond(['status' => true, 'count' => $data,  'code' => 200], 200);
+        } else {
+            return $this->respond(['status' => false, 'count' => 0, 'message' => 'No Data Found', 'code' => 404], 200);
         }
     }
 
     public function getBasePolicy($client_id, $client_branch_id)
     {
         $data = $this->clientPolicyModel
-        ->select('client_policy.*, policy_type.policy_type')
-        ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
-        ->where('client_policy.client_id', $client_id)
-        ->where('client_policy.client_branch_id', $client_branch_id)
-        ->whereIn('client_policy.policy_type_id', [2, 3])
-        ->where('client_policy.is_active', 1)
-        ->findAll();
+            ->select('client_policy.*, policy_type.policy_type')
+            ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
+            ->where('client_policy.client_id', $client_id)
+            ->where('client_policy.client_branch_id', $client_branch_id)
+            ->whereIn('client_policy.policy_type_id', [2, 3])
+            ->where('client_policy.is_active', 1)
+            ->findAll();
 
-        if($data){
-            return $this->respond(['status' => true, 'data'=> $data,  'code' => 200], 200);
-        }else{
-            return $this->respond(['status' => false, 'count'=> 0, 'message' => 'No Data Found', 'code' => 404], 200);
+        if ($data) {
+            return $this->respond(['status' => true, 'data' => $data,  'code' => 200], 200);
+        } else {
+            return $this->respond(['status' => false, 'count' => 0, 'message' => 'No Data Found', 'code' => 404], 200);
         }
     }
 
@@ -1689,7 +1679,7 @@ class PolicyTransactionController extends BaseController
 
     //get BDS Reports data old function
     public function reportBDSOld()
-    {   
+    {
 
         $data['page_name'] = 'BDS Report';
 
@@ -1703,7 +1693,7 @@ class PolicyTransactionController extends BaseController
             'exported_to_tpa' => 'Exported to TPA',
             'imported_from_tpa' => 'Imported from TPA',
             'completed' => 'Completed'
-        ];   
+        ];
         $data['invoice_status_array'] = [
             'yet_to_generate' => 'Yet to Generate',
             'generated' => 'Generated',
@@ -1730,27 +1720,27 @@ class PolicyTransactionController extends BaseController
         $policy_type_id = $this->request->getGet('policy_type_id');
         $date_type = $this->request->getGet('date_type');
         $issuer = $this->request->getGet('issuer');
-        
+
         $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date;
         $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date;
-        
+
         $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
-        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;      
-        $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;      
-        $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;      
-        $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;   
-        
-        
+        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
+        $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;
+        $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;
+        $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;
+
+
         //Actual data for the list
         $data['report_list'] = $this->policyTransactionModel->getBDSReportList($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer);
         // dd($data);
-        
-        $this->loadLayout('report_bds_filter', $data); 
+
+        $this->loadLayout('report_bds_filter', $data);
     }
 
     //get BDS Reports data New Function
     public function reportBDS()
-    {   
+    {
 
         $data['page_name'] = 'BDS Report';
 
@@ -1764,7 +1754,7 @@ class PolicyTransactionController extends BaseController
             'exported_to_tpa' => 'Exported to TPA',
             'imported_from_tpa' => 'Imported from TPA',
             'completed' => 'Completed'
-        ];   
+        ];
         $data['invoice_status_array'] = [
             'yet_to_generate' => 'Yet to Generate',
             'generated' => 'Generated',
@@ -1784,6 +1774,7 @@ class PolicyTransactionController extends BaseController
         $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll();
         $data['clients'] = $this->clientModel->where('is_active', 1)->findAll();
 
+
         //filter datas
         $start_date = $this->request->getGet('start_date');
         $end_date = $this->request->getGet('end_date');
@@ -1796,35 +1787,50 @@ class PolicyTransactionController extends BaseController
         $insurer_branch_id = $this->request->getGet('insurer_branch_id');
         $client_policy_id = $this->request->getGet('client_policy_id');
 
-        if($date_type == 'statement_month'){
+        if ($date_type == 'statement_month') {
             $start_date = (string)date('Y-m-01', strtotime($start_date));
             $end_date = (string)date('Y-m-31', strtotime($end_date));
         }
 
         // dd($start_date, $end_date, $date_type);
-        
+
         $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date;
         $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date;
-        
+
         $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
-        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;      
-        $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;      
-        $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;      
-        $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;   
-        $client_branch_id = (!isset($client_branch_id) || $client_branch_id === '' || $client_branch_id === null) ? 0 : $client_branch_id;   
-        $insurer_branch_id = (!isset($insurer_branch_id) || $insurer_branch_id === '' || $insurer_branch_id === null) ? 0 : $insurer_branch_id;   
-        $client_policy_id = (!isset($client_policy_id) || $client_policy_id === '' || $client_policy_id === null) ? 0 : $client_policy_id;   
-        
-        
+        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
+        $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;
+        $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;
+        $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;
+        $client_branch_id = (!isset($client_branch_id) || $client_branch_id === '' || $client_branch_id === null) ? 0 : $client_branch_id;
+        $insurer_branch_id = (!isset($insurer_branch_id) || $insurer_branch_id === '' || $insurer_branch_id === null) ? 0 : $insurer_branch_id;
+        $client_policy_id = (!isset($client_policy_id) || $client_policy_id === '' || $client_policy_id === null) ? 0 : $client_policy_id;
+        if ($this->request->is('post')) {
+            $isFromDashboard = $this->request->getPost("is_dashboard");
+
+            if (isset($isFromDashboard) && !empty($isFromDashboard) && $isFromDashboard == 1) {
+                $ids = $this->request->getPost('ids');
+                
+                $ids = array_filter(explode(',', $ids));
+
+                if (!empty($ids)) {
+                    $idsStr = implode(',', array_map('intval', $ids)); // sanitize IDs to be integers
+                    $where = "policy_transaction.id IN ($idsStr)";
+                } else {
+                    $where = []; // No valid IDs, return empty result
+                }
+            }
+            // dd($ids);
+        }
         //Actual data for the list
-        $data['report_list'] = $this->policyTransactionModel->getBDSReportList($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $client_branch_id, $insurer_branch_id, $client_policy_id);
+        $data['report_list'] = $this->policyTransactionModel->getBDSReportList($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $client_branch_id, $insurer_branch_id, $client_policy_id, isset($where) ? $where : '');
         //!dd($data['report_list']);
-        
-        $this->loadLayout('report_bds_filter', $data); 
+
+        $this->loadLayout('report_bds_filter', $data);
     }
 
     public function reportVarience()
-    {   
+    {
         $data['page_name'] = 'Variance Report';
 
         $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
@@ -1851,30 +1857,29 @@ class PolicyTransactionController extends BaseController
         $insurer_branch_id = $this->request->getGet('insurer_branch_id');
         $client_policy_id = $this->request->getGet('client_policy_id');
 
-        
+
         $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date;
         $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date;
-        
-        $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
-        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;      
-        $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;      
-        $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;      
-        $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;   
 
-        $client_branch_id = (!isset($client_branch_id) || $client_branch_id === '' || $client_branch_id === null) ? 0 : $client_branch_id;   
-        $insurer_branch_id = (!isset($insurer_branch_id) || $insurer_branch_id === '' || $insurer_branch_id === null) ? 0 : $insurer_branch_id;   
-        $client_policy_id = (!isset($client_policy_id) || $client_policy_id === '' || $client_policy_id === null) ? 0 : $client_policy_id;   
+        $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
+        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
+        $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;
+        $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;
+        $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;
+
+        $client_branch_id = (!isset($client_branch_id) || $client_branch_id === '' || $client_branch_id === null) ? 0 : $client_branch_id;
+        $insurer_branch_id = (!isset($insurer_branch_id) || $insurer_branch_id === '' || $insurer_branch_id === null) ? 0 : $insurer_branch_id;
+        $client_policy_id = (!isset($client_policy_id) || $client_policy_id === '' || $client_policy_id === null) ? 0 : $client_policy_id;
 
 
         $data['varience_list'] = $this->policyTransactionModel->getVarienceReportLIst($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $client_branch_id, $insurer_branch_id, $client_policy_id);
         // !dd($data['varience_list']);
-        $this->loadLayout('variance_report_list', $data); 
-
+        $this->loadLayout('variance_report_list', $data);
     }
 
 
     public function reportBusinessList()
-    {   
+    {
         $data['page_name'] = 'Business Report';
 
         $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
@@ -1897,24 +1902,24 @@ class PolicyTransactionController extends BaseController
         $policy_type_id = $this->request->getGet('policy_type_id');
         $date_type = $this->request->getGet('date_type');
         $issuer = $this->request->getGet('issuer');
-        
+
         $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date;
         $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date;
-        
+
         $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
-        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;      
-        $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;      
-        $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;      
-        $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;   
+        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
+        $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;
+        $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;
+        $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;
 
 
         $data['business_list'] = $this->policyTransactionModel->getBusinessReportList($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer);
-        $this->loadLayout('business_team_list', $data);     
+        $this->loadLayout('business_team_list', $data);
     }
 
 
     public function reportFinanceList()
-    {   
+    {
         $data['page_name'] = 'Finance Report';
 
         $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
@@ -1937,24 +1942,24 @@ class PolicyTransactionController extends BaseController
         $policy_type_id = $this->request->getGet('policy_type_id');
         $date_type = $this->request->getGet('date_type');
         $issuer = $this->request->getGet('issuer');
-        
+
         $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date;
         $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date;
-        
+
         $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
-        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;      
-        $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;      
-        $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;      
-        $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;   
+        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
+        $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;
+        $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;
+        $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;
 
 
 
         $data['finance_list'] = $this->policyTransactionModel->getFinanceReportList($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer);
-        $this->loadLayout('finance_team_list', $data); 
+        $this->loadLayout('finance_team_list', $data);
     }
 
     public function reportOutstanding()
-    {   
+    {
         $data['page_name'] = 'Outstanding Report';
 
         $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
@@ -1975,20 +1980,19 @@ class PolicyTransactionController extends BaseController
         $client_id = $this->request->getGet('client_id');
         $insurer_id = $this->request->getGet('insurer_id');
         $insurer_branch_id = $this->request->getGet('insurer_branch_id');
-        
-        $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : change_date_format($start_date,'d-m-Y','Y-m-01');
-        $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : change_date_format($end_date,'d-m-Y','Y-m-31');
-        // dd([$start_date,$end_date]);
-        
-        
-        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;      
-        $insurer_branch_id = (!isset($insurer_branch_id) || $insurer_branch_id === '' || $insurer_branch_id === null) ? 0 : $insurer_branch_id;      
 
-        $data['outstanting_list'] = $this->policyTransactionModel->getOutstandingReportLIst($start_date, $end_date,$insurer_id, $insurer_branch_id);
+        $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : change_date_format($start_date, 'd-m-Y', 'Y-m-01');
+        $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : change_date_format($end_date, 'd-m-Y', 'Y-m-31');
+        // dd([$start_date,$end_date]);
+
+
+        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
+        $insurer_branch_id = (!isset($insurer_branch_id) || $insurer_branch_id === '' || $insurer_branch_id === null) ? 0 : $insurer_branch_id;
+
+        $data['outstanting_list'] = $this->policyTransactionModel->getOutstandingReportLIst($start_date, $end_date, $insurer_id, $insurer_branch_id);
         // dd($this->policyTransactionModel->getLastQuery());
         // dd($data);
-        $this->loadLayout('outstanding_report_list', $data); 
-
+        $this->loadLayout('outstanding_report_list', $data);
     }
 
     //---------------------------------------------------------------------------------------------------
@@ -1997,16 +2001,17 @@ class PolicyTransactionController extends BaseController
     public function statementList()
     {
         // dd($this->validateInsurerStatement(['file_id' => 30]));
-         // $data['insurers'] = $this->insurerModel->where('is_active',1)->findAll();
+        // $data['insurers'] = $this->insurerModel->where('is_active',1)->findAll();
         $today = date('Y-m-d');
         $fromday = $from_date = date('Y-m-d', strtotime('-180 days', strtotime($today)));
         // echo $fromday;die();
-         $data['invoice_status_array'] = $this->invoiceStatus;
-         $data['insurers'] = $this->insurerBranchModel ->getInsurerBranchesWithInsurerNames();
+        $data['invoice_status_array'] = $this->invoiceStatus;
+        $data['insurers'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
 
-         // dd( $data['insurers']);
-         $data['insurer_statement_list'] = $this->insurerStatements
-                                                ->select('insurer_statements.*, 
+        // dd( $data['insurers']);
+        $data['insurer_statement_list'] = $this->insurerStatements
+            ->select(
+                'insurer_statements.*, 
                                                           insurers.name AS insurer_name, 
                                                           insurers.short_name, 
                                                           user_profiles.first_name, 
@@ -2021,18 +2026,18 @@ class PolicyTransactionController extends BaseController
                                                            WHERE inv_payment_details.is_active = 1 
                                                              AND inv_payment_details.statement_id = insurer_statements.id
                                                           ) AS received_inv_amt'
-                                                )
-                                                ->join('insurers', 'insurer_statements.insurer_id = insurers.id')
-                                                ->join('insurer_branch', 'insurer_statements.branch_id = insurer_branch.id')
-                                                ->join('user_profiles', 'insurer_statements.created_by = user_profiles.id')
-                                                ->where('insurer_statements.is_active', 1)
-                                                // ->where('insurer_statements.file_status','success')
-                                                ->where('date(insurer_statements.created_at) >= ', $from_date)
-                                                ->where('date(insurer_statements.created_at) <= ', $today)
-                                                ->orderBy('insurer_statements.id', 'DESC')
-                                                ->findAll();
+            )
+            ->join('insurers', 'insurer_statements.insurer_id = insurers.id')
+            ->join('insurer_branch', 'insurer_statements.branch_id = insurer_branch.id')
+            ->join('user_profiles', 'insurer_statements.created_by = user_profiles.id')
+            ->where('insurer_statements.is_active', 1)
+            // ->where('insurer_statements.file_status','success')
+            ->where('date(insurer_statements.created_at) >= ', $from_date)
+            ->where('date(insurer_statements.created_at) <= ', $today)
+            ->orderBy('insurer_statements.id', 'DESC')
+            ->findAll();
 
-            // dd( $this->insurerStatements->getLastQuery());
+        // dd( $this->insurerStatements->getLastQuery());
         $data['page_name'] = 'Statement Upload';
 
         $this->loadLayout('insurer_statement_list',  $data);
@@ -2083,80 +2088,77 @@ class PolicyTransactionController extends BaseController
     public function uploadInsurerStatement()
     {
 
-            //validate uploaded file
-            $filename = '';
-            $validated = $this->validate([
-                'statement' => [
-                    'uploaded[statement]',
-                    'mime_in[statement,application/vnd.ms-excel,application/vnd,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.oasis.opendocument.spreadsheet]',
-                    'max_size[statement,16384]',
-                ],
-            ]);
-            // $this->createStatementFolder();
-            if ($validated) 
-            {
-                    $avatar = $this->request->getFile('statement');
-                    if (!$avatar) {
-                        $this->myLogger->logme("error", 'Statement File not found');
-                        return $this->respond(['dataStatus' => false, 'code' => 400, 'message' => 'File not found'], 400);
-                    }
+        //validate uploaded file
+        $filename = '';
+        $validated = $this->validate([
+            'statement' => [
+                'uploaded[statement]',
+                'mime_in[statement,application/vnd.ms-excel,application/vnd,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.oasis.opendocument.spreadsheet]',
+                'max_size[statement,16384]',
+            ],
+        ]);
+        // $this->createStatementFolder();
+        if ($validated) {
+            $avatar = $this->request->getFile('statement');
+            if (!$avatar) {
+                $this->myLogger->logme("error", 'Statement File not found');
+                return $this->respond(['dataStatus' => false, 'code' => 400, 'message' => 'File not found'], 400);
+            }
 
-                    $is_moved = $avatar->move(WRITEPATH . 'uploads/statements/');
-                    if ($is_moved) {
-                        $filename = $avatar->getName();
-                        // Handle successful upload, e.g., log success or further processing
-                        $this->myLogger->logme("error", 'Statement File moved successful');
-                        
-                    } else {
-                        $this->myLogger->logme("error", 'Statement File move failed');
-                        return $this->respond(['dataStatus' => false, 'code' => 500, 'message' => 'File move failed'], 500);
-                    }
+            $is_moved = $avatar->move(WRITEPATH . 'uploads/statements/');
+            if ($is_moved) {
+                $filename = $avatar->getName();
+                // Handle successful upload, e.g., log success or further processing
+                $this->myLogger->logme("error", 'Statement File moved successful');
             } else {
-                $this->myLogger->logme("error", 'Statement Upload failed Invalid file');
-                return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'Invalid file'], 404);
+                $this->myLogger->logme("error", 'Statement File move failed');
+                return $this->respond(['dataStatus' => false, 'code' => 500, 'message' => 'File move failed'], 500);
             }
+        } else {
+            $this->myLogger->logme("error", 'Statement Upload failed Invalid file');
+            return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'Invalid file'], 404);
+        }
 
-            //process post variable entry in file table
-            $loggedInUserID = get_session_userid();
-            // dd($loggedInUserID);
-            // $loggedInUserID = 8;
+        //process post variable entry in file table
+        $loggedInUserID = get_session_userid();
+        // dd($loggedInUserID);
+        // $loggedInUserID = 8;
 
-            $insurer = $this->request->getPost('insurer');
+        $insurer = $this->request->getPost('insurer');
 
-            $insurer_id = explode('-', $insurer)[0];
-            $branch_id = explode('-', $insurer)[1];
-            // print_r($insurer_id);
-            // print_r($branch_id);
-            // die();
-            $month = $this->request->getPost('statement_month');
-            $month = $month.'-01';
-            // print_r($month);die;
-            $month = change_date_format($month,'Y-M-d','Y-m-d');
-            $stmt_sno = $this->request->getPost('statement_no');
-            // print_r($month);die;
+        $insurer_id = explode('-', $insurer)[0];
+        $branch_id = explode('-', $insurer)[1];
+        // print_r($insurer_id);
+        // print_r($branch_id);
+        // die();
+        $month = $this->request->getPost('statement_month');
+        $month = $month . '-01';
+        // print_r($month);die;
+        $month = change_date_format($month, 'Y-M-d', 'Y-m-d');
+        $stmt_sno = $this->request->getPost('statement_no');
+        // print_r($month);die;
 
-            $file_id = $this->insurerStatements->insert(['insurer_id' => $insurer_id, 'branch_id' => $branch_id, 'file_name' => $filename,'month' => $month, 'created_by' => $loggedInUserID,'stmt_sno' => $stmt_sno]); //here field policy_id have client_policy_id and not policy id from policy master
-            $this->myLogger->logme("error", '{file_id} statement uploaded success', ['file_id' => $file_id]);
+        $file_id = $this->insurerStatements->insert(['insurer_id' => $insurer_id, 'branch_id' => $branch_id, 'file_name' => $filename, 'month' => $month, 'created_by' => $loggedInUserID, 'stmt_sno' => $stmt_sno]); //here field policy_id have client_policy_id and not policy id from policy master
+        $this->myLogger->logme("error", '{file_id} statement uploaded success', ['file_id' => $file_id]);
 
-            //validate file
-            $validation_result = $this->validateInsurerStatement(['file_id' => $file_id]);
-            //update file content to DB
-            if($validation_result['status'] )
-            {
-                $this->updateInsurerStatement(['file_id' => $file_id]);
-            }
-           
-            if (!isset($file_id) || !$validation_result['status']) {
-                return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'file not uploaded', 'error_data' => $validation_result['error_data'],'error_code' =>   $validation_result['error_code']], 200);
-            }
+        //validate file
+        $validation_result = $this->validateInsurerStatement(['file_id' => $file_id]);
+        //update file content to DB
+        if ($validation_result['status']) {
+            $this->updateInsurerStatement(['file_id' => $file_id]);
+        }
 
-            if (isset($file_id) || $validation_result['status']) {
-                $this->insurerStatements->where('id', $file_id)->set(['invoice_status' => 'pending'])->update();
-            }
+        if (!isset($file_id) || !$validation_result['status']) {
+            return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'file not uploaded', 'error_data' => $validation_result['error_data'], 'error_code' =>   $validation_result['error_code']], 200);
+        }
+
+        if (isset($file_id) || $validation_result['status']) {
+            $this->insurerStatements->where('id', $file_id)->set(['invoice_status' => 'pending'])->update();
+        }
 
 
 
-            return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => 'file upload success'], 200);
+        return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => 'file upload success'], 200);
     }
 
     public function createStatementFolder()
@@ -2164,23 +2166,20 @@ class PolicyTransactionController extends BaseController
         $folderPath = WRITEPATH . 'uploads/statements/';
 
         // Check if the folder doesn't exist
-        if (!file_exists($folderPath)) 
-        {
+        if (!file_exists($folderPath)) {
             // Create the folder
             if (mkdir($folderPath, 0777, true)) {
-               $this->myLogger->logme('error','statement upload folder created successfully');
-                
+                $this->myLogger->logme('error', 'statement upload folder created successfully');
+
                 // Set permissions to a+rwx (read, write, execute for all)
                 chmod($folderPath, 0777);
-                $this->myLogger->logme('error','Permissions set to a+rwx.');
+                $this->myLogger->logme('error', 'Permissions set to a+rwx.');
             } else {
                 // echo "Failed to create folder.";
-                $this->myLogger->logme('error','Failed to create statement upload folder.');
+                $this->myLogger->logme('error', 'Failed to create statement upload folder.');
             }
-        } 
-        else 
-        {
-            $this->myLogger->logme('error','upload folder exists.');
+        } else {
+            $this->myLogger->logme('error', 'upload folder exists.');
         }
     }
 
@@ -2192,37 +2191,35 @@ class PolicyTransactionController extends BaseController
         $file = $this->insurerStatements->find($file_id);
         // dd($file);
         $date = new \DateTime($file['month']);
-        
-        $month = $date->format('m'); 
+
+        $month = $date->format('m');
         $year = $date->format('Y');
 
-        $error_data = ['error_code' => '','error_data' => []];
+        $error_data = ['error_code' => '', 'error_data' => []];
         $status = 'success';
         $ret_status = true;
         // dd($month.'-'.$year);
         $return = [];
-        if(!isset($file))
-        {
+        if (!isset($file)) {
             //file not found in DB
             return array('status' => false, 'msg' => 'statement file not found in DB');
         }
-        $file_name_with_path = WRITEPATH."/uploads/statements/".$file['file_name'];
-        
+        $file_name_with_path = WRITEPATH . "/uploads/statements/" . $file['file_name'];
+
         //check physical file
-        if(!file_exists($file_name_with_path))
-        {
+        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 statement file id ' . $file_id));
-            $this->insurerStatements->where('id', $file_id)->set(['file_status' => 'failed','reason' => json_encode(['error_code' => 0,'error_data' => $message])])->update();
+            $this->myLogger->logme('error', ($message . ' for statement file id ' . $file_id));
+            $this->insurerStatements->where('id', $file_id)->set(['file_status' => 'failed', 'reason' => json_encode(['error_code' => 0, 'error_data' => $message])])->update();
             return  array('status' => false, 'error_code' => 0); //0 - Physcial file not found
         }
 
         //get excel data to php array
         $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
         $sheet = $spreadsheet->getActiveSheet();
-        
+
         $highestRowAndColumn = $sheet->getHighestRowAndColumn();
         // dd($highestRowAndColumn);
         $excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
@@ -2231,33 +2228,29 @@ class PolicyTransactionController extends BaseController
         //get no of line items and update in DB
         $line_items = 0;
         // get uploaded month transactions data
-        $source_data = $this->PTCOShareDetailsModel->getNonReconcileredPolicyTransactions(insurer_id:$file['insurer_id'],insurer_branch_id:$file['branch_id']);
+        $source_data = $this->PTCOShareDetailsModel->getNonReconcileredPolicyTransactions(insurer_id: $file['insurer_id'], insurer_branch_id: $file['branch_id']);
         // var_dump($source_data);die();
         // Kint::dump($source_data);//die();
 
-       
+
         // check policy no,insurer and etc in DB for this month
         // if all good return true, otherwise return false with messssage 
-        foreach ($excel_data as $excel_key => $excel_row) 
-        {
+        foreach ($excel_data as $excel_key => $excel_row) {
             $is_row_empty = check_row_is_empty_or_null($excel_row);
-            if(!$is_row_empty)
-            {
+            if (!$is_row_empty) {
                 // $excel_row = ExcelSanitizeHelper::sanitizeArrayData($excel_row);
                 $is_source_found = 0;
-                $policy_start_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[4]);//policy_start_date from excel
-                $policy_end_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[5]);//policy_end_date from excel
-                $policy_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[1]);//policy_end_date from excel
-                $policy_no = preg_replace('/[\x{200C}\x{200B}]/u', '',  $excel_row[1]);//policy_end_date from excel
-                $client_name = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[3]);//clientname from excel
-                $endorsement_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[2]);//policy_end_date from excel
+                $policy_start_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[4]); //policy_start_date from excel
+                $policy_end_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[5]); //policy_end_date from excel
+                $policy_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[1]); //policy_end_date from excel
+                $policy_no = preg_replace('/[\x{200C}\x{200B}]/u', '',  $excel_row[1]); //policy_end_date from excel
+                $client_name = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[3]); //clientname from excel
+                $endorsement_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[2]); //policy_end_date from excel
                 // Kint::dump($policy_no);
-                foreach ($source_data as $source_key => $source_row) 
-                {
+                foreach ($source_data as $source_key => $source_row) {
                     $source_endorsement_no = $source_row['endorsement_no'] !== null ? $source_row['endorsement_no'] : null;
                     // Kint::dump($source_endorsement_no);
-                    if( ($policy_no == $source_row['policy_no']) && $endorsement_no == $source_endorsement_no  && change_date_format($policy_start_date,'d-m-Y','Y-m-d') == $source_row['policy_start_date'] &&  change_date_format($policy_end_date,'d-m-Y','Y-m-d') == $source_row['policy_end_date'] && $client_name == $source_row['client_name'])
-                    {
+                    if (($policy_no == $source_row['policy_no']) && $endorsement_no == $source_endorsement_no  && change_date_format($policy_start_date, 'd-m-Y', 'Y-m-d') == $source_row['policy_start_date'] &&  change_date_format($policy_end_date, 'd-m-Y', 'Y-m-d') == $source_row['policy_end_date'] && $client_name == $source_row['client_name']) {
                         $is_source_found = 1;
                         $line_items = $line_items + 1;
                         unset($source_data[$source_key]);
@@ -2265,27 +2258,24 @@ class PolicyTransactionController extends BaseController
                     }
                 }
 
-                if($is_source_found == 0)
-                {
+                if ($is_source_found == 0) {
                     // echo $excel_key.'-'.$excel_row[1] . '- not found
'; - $error_data['error_code'] = 1;//match not found + $error_data['error_code'] = 1; //match not found // $error_data['error_data'] = ($error_data['error_data'] ?? []); - $error_data['error_data'] = array_merge($error_data['error_data'],[$excel_row[0]]);//match not found + $error_data['error_data'] = array_merge($error_data['error_data'], [$excel_row[0]]); //match not found } - } } // dd($error_data); - if($error_data['error_code']) - { - $status = 'failed'; - $ret_status = false; + if ($error_data['error_code']) { + $status = 'failed'; + $ret_status = false; } - //update in DB - $this->insurerStatements->where('id', $file_id)->set(['line_items' => $line_items,'file_status' => $status,'reason' => json_encode($error_data)])->update(); - return array('status' => $ret_status, 'error_code' => $error_data['error_code'],'error_data' => $error_data['error_data']); + //update in DB + $this->insurerStatements->where('id', $file_id)->set(['line_items' => $line_items, 'file_status' => $status, 'reason' => json_encode($error_data)])->update(); + return array('status' => $ret_status, 'error_code' => $error_data['error_code'], 'error_data' => $error_data['error_data']); } @@ -2297,37 +2287,35 @@ class PolicyTransactionController extends BaseController $file = $this->insurerStatements->find($file_id); // dd($file); $date = new \DateTime($file['month']); - - $month = $date->format('m'); + + $month = $date->format('m'); $year = $date->format('Y'); - $error_data = ['error_code' => '','error_data' => []]; + $error_data = ['error_code' => '', 'error_data' => []]; $status = 'success'; $ret_status = true; // dd($month.'-'.$year); $return = []; - if(!isset($file)) - { + if (!isset($file)) { //file not found in DB return array('status' => false, 'msg' => 'statement file not found in DB'); } - $file_name_with_path = WRITEPATH."/uploads/statements/".$file['file_name']; - + $file_name_with_path = WRITEPATH . "/uploads/statements/" . $file['file_name']; + //check physical file - if(!file_exists($file_name_with_path)) - { + 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 statement file id ' . $file_id)); - $this->insurerStatements->where('id', $file_id)->set(['file_status' => 'failed','reason' => json_encode(['error_code' => 0,'error_data' => $message])])->update(); + $this->myLogger->logme('error', ($message . ' for statement file id ' . $file_id)); + $this->insurerStatements->where('id', $file_id)->set(['file_status' => 'failed', 'reason' => json_encode(['error_code' => 0, 'error_data' => $message])])->update(); return array('status' => false, 'error_code' => 0); //0 - Physcial file not found } //get excel data to php array $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path); $sheet = $spreadsheet->getActiveSheet(); - + $highestRowAndColumn = $sheet->getHighestRowAndColumn(); // dd($highestRowAndColumn); $excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']); @@ -2336,33 +2324,29 @@ class PolicyTransactionController extends BaseController //get no of line items and update in DB $line_items = count($excel_data); // get uploaded month transactions data - $source_data = $this->PTCOShareDetailsModel->getNonReconcileredPolicyTransactions(insurer_id:$file['insurer_id'],insurer_branch_id:$file['branch_id']); + $source_data = $this->PTCOShareDetailsModel->getNonReconcileredPolicyTransactions(insurer_id: $file['insurer_id'], insurer_branch_id: $file['branch_id']); // Kint::dump($source_data);//die; // Kint::dump($excel_data); // die; // check policy no,insurer and etc in DB for this month // if all good return true, otherwise return false with messssage $data_to_update = []; - foreach ($excel_data as $excel_key => $excel_row) - { + foreach ($excel_data as $excel_key => $excel_row) { $is_row_empty = check_row_is_empty_or_null($excel_row); - if(!$is_row_empty) - { - + if (!$is_row_empty) { + $is_source_found = 0; - $policy_start_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[4]);//policy_start_date from excel - $policy_end_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[5]);//policy_end_date from excel - $policy_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[1]);//policy_end_date from excel - $policy_no = preg_replace('/[\x{200C}\x{200B}]/u', '', $excel_row[1]);// - $client_name = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[3]);//clientname from excel - $endorsement_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[2]);//policy_end_date from excel - - foreach ($source_data as $source_key => $source_row) - { + $policy_start_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[4]); //policy_start_date from excel + $policy_end_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[5]); //policy_end_date from excel + $policy_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[1]); //policy_end_date from excel + $policy_no = preg_replace('/[\x{200C}\x{200B}]/u', '', $excel_row[1]); // + $client_name = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[3]); //clientname from excel + $endorsement_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[2]); //policy_end_date from excel + + foreach ($source_data as $source_key => $source_row) { // Kint::dump(change_date_format($excel_row[3],'d-m-Y','Y-m-d')); $source_endorsement_no = $source_row['endorsement_no'] !== null ? $source_row['endorsement_no'] : null; - if( ($policy_no == $source_row['policy_no']) && $endorsement_no == $source_endorsement_no && change_date_format($policy_start_date,'d-m-Y','Y-m-d') == $source_row['policy_start_date'] && change_date_format($policy_end_date,'d-m-Y','Y-m-d') == $source_row['policy_end_date'] && $client_name == $source_row['client_name']) - { + if (($policy_no == $source_row['policy_no']) && $endorsement_no == $source_endorsement_no && change_date_format($policy_start_date, 'd-m-Y', 'Y-m-d') == $source_row['policy_start_date'] && change_date_format($policy_end_date, 'd-m-Y', 'Y-m-d') == $source_row['policy_end_date'] && $client_name == $source_row['client_name']) { $is_source_found = 1; //calculate percentage first @@ -2372,18 +2356,13 @@ class PolicyTransactionController extends BaseController $actual_bp_brokerage = trim($excel_row[12]); $actual_bp_amt = trim($excel_row[6]); - if(($actual_bp_brokerage && $actual_bp_brokerage != 0 && $actual_bp_brokerage != "")) - { + if (($actual_bp_brokerage && $actual_bp_brokerage != 0 && $actual_bp_brokerage != "")) { $total_amt += $actual_bp_brokerage; //percentage reverse calculation - if($actual_bp_per == 0 || $actual_bp_per == "") - { - $actual_bp_per = round(($actual_bp_brokerage / $actual_bp_amt) * 100,2); + if ($actual_bp_per == 0 || $actual_bp_per == "") { + $actual_bp_per = round(($actual_bp_brokerage / $actual_bp_amt) * 100, 2); } - - } - else - { + } else { $actual_bp_brokerage = $actual_bp_amt * ($actual_bp_per / 100); $total_amt += $actual_bp_brokerage; } @@ -2392,17 +2371,13 @@ class PolicyTransactionController extends BaseController $actual_tp_brokerage = trim($excel_row[13]); $actual_tp_amt = trim($excel_row[7]); - if($actual_tp_brokerage && $actual_tp_brokerage != 0 && $actual_tp_brokerage != "") - { + if ($actual_tp_brokerage && $actual_tp_brokerage != 0 && $actual_tp_brokerage != "") { $total_amt += $actual_tp_brokerage; //percentage reverse calculation - if($actual_tp_per == 0 || $actual_tp_per == "") - { + if ($actual_tp_per == 0 || $actual_tp_per == "") { $actual_tp_per = ($actual_tp_brokerage / $actual_tp_amt) * 100; } - } - else - { + } else { $actual_tp_brokerage = $actual_tp_amt * ($actual_tp_per / 100); $total_amt += $actual_tp_brokerage; } @@ -2411,17 +2386,13 @@ class PolicyTransactionController extends BaseController $actual_tep_brokerage = trim($excel_row[14]); $actual_tep_amt = trim($excel_row[8]); - if($actual_tep_brokerage && $actual_tep_brokerage != 0 && $actual_tep_brokerage != "") - { + if ($actual_tep_brokerage && $actual_tep_brokerage != 0 && $actual_tep_brokerage != "") { $total_amt += $actual_tep_brokerage; //percentage reverse calculation - if($actual_tep_per == 0 || $actual_tep_per == "") - { + if ($actual_tep_per == 0 || $actual_tep_per == "") { $actual_tep_per = ($actual_tep_brokerage / $actual_tep_amt) * 100; } - } - else - { + } else { $actual_tep_brokerage = $actual_tep_amt * ($actual_tep_per / 100); $total_amt += $actual_tep_brokerage; } @@ -2429,13 +2400,12 @@ class PolicyTransactionController extends BaseController //find variance $variance_amt = $source_row['exp_amt'] - $total_amt; - $data_to_update[] = ['co_share_id' => $source_row['id'],'actual_bp_amt' => $actual_bp_amt,'actual_tp_amt' => $actual_tp_amt,'actual_tep_amt' => $actual_tep_amt,'actual_bp_per' => $actual_bp_per,'actual_tp_per' => $actual_tp_per,'actual_tep_per' => $actual_tep_per,'variance' => $variance_amt,'actual_tep_brokerage_amt' => $actual_tep_brokerage,'actual_tp_brokerage_amt' => $actual_tp_brokerage,'actual_bp_brokerage_amt' => $actual_bp_brokerage,'reward' => trim($excel_row[15]),'statement_id' => $file_id]; + $data_to_update[] = ['co_share_id' => $source_row['id'], 'actual_bp_amt' => $actual_bp_amt, 'actual_tp_amt' => $actual_tp_amt, 'actual_tep_amt' => $actual_tep_amt, 'actual_bp_per' => $actual_bp_per, 'actual_tp_per' => $actual_tp_per, 'actual_tep_per' => $actual_tep_per, 'variance' => $variance_amt, 'actual_tep_brokerage_amt' => $actual_tep_brokerage, 'actual_tp_brokerage_amt' => $actual_tp_brokerage, 'actual_bp_brokerage_amt' => $actual_bp_brokerage, 'reward' => trim($excel_row[15]), 'statement_id' => $file_id]; unset($source_data[$source_key]); continue 2; } } - } } // dd($data_to_update); @@ -2446,59 +2416,57 @@ class PolicyTransactionController extends BaseController // $status = 'failed'; // $ret_status = false; // } - //update in DB - $this->insurerStatements->where('id', $file_id)->set(['file_status' => $status,'reason' => json_encode($error_data),'invoice_status' =>'pending'])->update(); - return array('status' => $ret_status, 'error_code' => $error_data['error_code'],'error_data' => $error_data['error_data']); + //update in DB + $this->insurerStatements->where('id', $file_id)->set(['file_status' => $status, 'reason' => json_encode($error_data), 'invoice_status' => 'pending'])->update(); + return array('status' => $ret_status, 'error_code' => $error_data['error_code'], 'error_data' => $error_data['error_data']); } public function getInvoicePaymentDetails() { - $statement_id = $this->request->getUri()->getSegment(4); - - $inv_details = $this->insurerStatements->find($statement_id); - $inv_payment_details = $this->invPaymentDetailsModel - ->where('statement_id',$statement_id) - ->where('is_active',1) - ->get() - ->getResultArray(); - if(!$inv_details['invoice_value']) - { + $statement_id = $this->request->getUri()->getSegment(4); + + $inv_details = $this->insurerStatements->find($statement_id); + $inv_payment_details = $this->invPaymentDetailsModel + ->where('statement_id', $statement_id) + ->where('is_active', 1) + ->get() + ->getResultArray(); + if (!$inv_details['invoice_value']) { $stmt_level_value = $this->coShareStmtDetailsModel->select('sum(actual_tep_brokerage_amt) + sum(actual_tp_brokerage_amt) + sum(actual_bp_brokerage_amt) + sum(reward) as invoice_value') - ->where('statement_id',$statement_id) - ->groupBy('statement_id') - ->get() - ->getResultArray(); - // print_r($stmt_level_value); - if($stmt_level_value && count($stmt_level_value) && isset($stmt_level_value[0])) - { + ->where('statement_id', $statement_id) + ->groupBy('statement_id') + ->get() + ->getResultArray(); + // print_r($stmt_level_value); + if ($stmt_level_value && count($stmt_level_value) && isset($stmt_level_value[0])) { $inv_details['invoice_value'] = $stmt_level_value[0]['invoice_value']; } } - // ~dd($inv_details); - $data = [ 'invoice_status' => $inv_details['invoice_status'], - 'gst_per' => isset($inv_details['gst_per']) ? $inv_details['gst_per'] : 18 , - 'invoice_value' => $inv_details['invoice_value'], - 'gst_value' => $inv_details['gst_value'], - 'invoice_no' => $inv_details['invoice_no'], - 'invoice_amount' => $inv_details['invoice_amount'], - 'invoice_date' => isset($inv_details['invoice_date']) ? change_date_format($inv_details['invoice_date'],'Y-m-d','d/m/Y') : null ]; + // ~dd($inv_details); + $data = [ + 'invoice_status' => $inv_details['invoice_status'], + 'gst_per' => isset($inv_details['gst_per']) ? $inv_details['gst_per'] : 18, + 'invoice_value' => $inv_details['invoice_value'], + 'gst_value' => $inv_details['gst_value'], + 'invoice_no' => $inv_details['invoice_no'], + 'invoice_amount' => $inv_details['invoice_amount'], + 'invoice_date' => isset($inv_details['invoice_date']) ? change_date_format($inv_details['invoice_date'], 'Y-m-d', 'd/m/Y') : null + ]; $data['payments'] = $inv_payment_details; return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $data], 200); - - } public function saveInvoicePaymentDetails() { - $jsonData = $this->request->getJSON(); - $jsonData = (array)$jsonData; - // echo 'Hi'; - // print_r($jsonData);die(); + $jsonData = $this->request->getJSON(); + $jsonData = (array)$jsonData; + // echo 'Hi'; + // print_r($jsonData);die(); $invoiceStatus = $jsonData['invoice_status']; $hiddenStatementId = $jsonData['hidden_statement_id']; $invoiceNo = $jsonData['invoice_no']; - $invoiceDate = change_date_format($jsonData['invoice_date'],'d/m/Y','Y-m-d'); + $invoiceDate = change_date_format($jsonData['invoice_date'], 'd/m/Y', 'Y-m-d'); $invoice_amount = $jsonData['invoice_amount']; $invoice_value = $jsonData['invoice_value']; $gst_per = $jsonData['invoice_gst_per']; @@ -2516,10 +2484,10 @@ class PolicyTransactionController extends BaseController 'updated_by' => get_session_userid() ]; - + $this->insurerStatements->update($hiddenStatementId, $parentData); - + // Process child data $receivedAmounts = $jsonData['received_amount']; $utrNos = $jsonData['utr_no']; @@ -2541,19 +2509,20 @@ class PolicyTransactionController extends BaseController 'utr_no' => $utrNo, 'tds' => $tds, 'gst' => $gst, - 'received_date' => change_date_format($paymentDate,'d/m/Y','Y-m-d'), + 'received_date' => change_date_format($paymentDate, 'd/m/Y', 'Y-m-d'), 'statement_id' => $hiddenStatementId ]; - if($pk){ - $childData['updated_by'] = get_session_userid(); - $childData['id'] = (int)$pk; + if ($pk) { + $childData['updated_by'] = get_session_userid(); + $childData['id'] = (int)$pk; + } else { + $childData['created_by'] = get_session_userid(); } - else { $childData['created_by'] = get_session_userid(); } // print_r($childData); // Insert or update $this->invPaymentDetailsModel->save($childData); // print_r($this->invPaymentDetailsModel->errors()); - + } return $this->respond(['dataStatus' => true, 'code' => 200], 200); @@ -2570,7 +2539,7 @@ class PolicyTransactionController extends BaseController public function downloadSampleInsurerStatement() { - + $filePath = ROOTPATH . 'public/sample_excel/insurer_stament_sample.xlsx'; // Check if the file exists if (file_exists($filePath)) { @@ -2590,14 +2559,13 @@ class PolicyTransactionController extends BaseController { $file_id = $this->request->getUri()->getSegment(4); $file = $this->insurerStatements->find($file_id); - return $this->respond(['dataStatus' => true, 'code' => 200,'data' => $file['reason']], 200); + return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $file['reason']], 200); } public function dmsSearch() { - // echo 'scbsc';die(); - if ($this->request->getMethod() == 'post') - { + // echo 'scbsc';die(); + if ($this->request->getMethod() == 'post') { // $jsonData = (array)$this->request->getJSON(); $customer_id = $this->request->getPost('customer_id'); $policy_id = $this->request->getPost('policy_id'); @@ -2608,37 +2576,33 @@ class PolicyTransactionController extends BaseController $batch_files = []; $files = []; // print_r($jsonData);die(); - if($policy_id != "") - { + if ($policy_id != "") { //get policy docs from policy transation related tables - $pt_files = $this->PTFileModel->getPolicyDriveFilesIndex($policy_id,$policy_doc_name); - $batch_files = $this->batchFileModel->getBatchFilesDataForDocumentSearch($policy_id,$policy_doc_name); - $files = $this->filesModel->getFilesDataForDocumentSearch($policy_id,$policy_doc_name); + $pt_files = $this->PTFileModel->getPolicyDriveFilesIndex($policy_id, $policy_doc_name); + $batch_files = $this->batchFileModel->getBatchFilesDataForDocumentSearch($policy_id, $policy_doc_name); + $files = $this->filesModel->getFilesDataForDocumentSearch($policy_id, $policy_doc_name); // dd($files); // dd($this->PTFileModel->getLastQuery()); // ~dd($pt_files); } - if($customer_id != "") - { - $kyc_files = $this->clientKYCDocsModel->getClientKYCDriveFilesIndex($customer_id,$cus_doc_name); + if ($customer_id != "") { + $kyc_files = $this->clientKYCDocsModel->getClientKYCDriveFilesIndex($customer_id, $cus_doc_name); // dd($this->clientKYCDocsModel->getLastQuery()); // !dd($kyc_files); } - $data['files'] = array_merge($pt_files,$kyc_files,$batch_files,$files); - // dd($data['files']); + $data['files'] = array_merge($pt_files, $kyc_files, $batch_files, $files); + // dd($data['files']); } $data['page_name'] = 'Documents Search'; - $data['customers'] = $this->clientModel->select('id,client_name,short_name as display_value')->where('is_active',1)->get()->getResultarray(); + $data['customers'] = $this->clientModel->select('id,client_name,short_name as display_value')->where('is_active', 1)->get()->getResultarray(); $data['policies'] = $this->clientPolicyModel->select("client_policy.id,client_policy.policy_no,policy_type.policy_type,concat(policy_type.policy_type,' - ',client_policy.policy_no) as display_value") - ->join('policy_type','client_policy.policy_type_id = policy_type.id') - ->where('client_policy.is_active',1)->get()->getResultarray(); - // dd($data); + ->join('policy_type', 'client_policy.policy_type_id = policy_type.id') + ->where('client_policy.is_active', 1)->get()->getResultarray(); + // dd($data); $this->loadLayout('dms_search', $data); - - } //--------------------------------------------------------------------------------------------------- @@ -2698,7 +2662,7 @@ class PolicyTransactionController extends BaseController ], 200); } } - + public function getClientPolicyDataBasedOnClientAndInsuer() { @@ -2709,14 +2673,14 @@ class PolicyTransactionController extends BaseController $policy_type_id = $this->request->getGet('policy_type_id') ?? 0; $builder = db_connect()->table("client_policy") - ->select(" + ->select(" client_policy.*, policy_type.policy_type, ") - ->join('policy_type', 'client_policy.policy_type_id = policy_type.id') - ->where([ - 'client_policy.is_active' => 1, - ]); + ->join('policy_type', 'client_policy.policy_type_id = policy_type.id') + ->where([ + 'client_policy.is_active' => 1, + ]); if (!empty($client_id)) { $builder->where('client_policy.client_id', $client_id); @@ -2737,22 +2701,22 @@ class PolicyTransactionController extends BaseController $result = $builder->get()->getResultArray(); if ($result) { - return $this->respond(['status' => true,'code' => 200,'data' => $result, 'getData' => $this->request->getGet()], 200); + return $this->respond(['status' => true, 'code' => 200, 'data' => $result, 'getData' => $this->request->getGet()], 200); } else { - return $this->respond(['status' => false,'code' => 400,'message' => 'No data found'], 200); + return $this->respond(['status' => false, 'code' => 400, 'message' => 'No data found'], 200); } } - + public function checkCDAmountForBasePremium() { $base_premium = $this->request->getGet('base_premium') ?? 0; $cd_ac_no = $this->request->getGet('cd_ac_no') ?? 0; - + // Validate inputs if (empty($cd_ac_no)) { return $this->respond(['status' => false, 'code' => 400, 'message' => 'CD Account Number is required'], 200); } - + // Build query $db = db_connect(); $builder = $db->table("cash_deposit") @@ -2760,13 +2724,13 @@ class PolicyTransactionController extends BaseController ->where('is_active', 1) ->orderBy('id', 'desc') ->limit(1); - + $result = $builder->get()->getRowArray(); - + if ($result) { // Check if base premium exceeds balance $base_premium_greater_than_balance = $base_premium > $result['balance']; - + return $this->respond([ 'status' => true, 'code' => 200, @@ -2776,48 +2740,44 @@ class PolicyTransactionController extends BaseController 'base_premium_greater_than_balance' => $base_premium_greater_than_balance, ], 200); } - + return $this->respond(['status' => false, 'code' => 400, 'message' => 'No data found for this CD'], 200); } - public function getInsurerStatementMonth() + public function getInsurerStatementMonth() { $insurer_id = $this->request->getGet('insurer_id'); $month = $this->request->getGet('month'); // echo $month; - $insurer_branch_id = explode('-',$insurer_id)[1]; - $insurer_id = explode('-',$insurer_id)[0]; - $month = $month.'-01'; - $month = change_date_format($month,'Y-M-d','Y-m-d'); + $insurer_branch_id = explode('-', $insurer_id)[1]; + $insurer_id = explode('-', $insurer_id)[0]; + $month = $month . '-01'; + $month = change_date_format($month, 'Y-M-d', 'Y-m-d'); // echo $month; $res_data = $this->insurerStatements - ->where('insurer_id',$insurer_id) - ->where('branch_id',$insurer_branch_id) - ->where('month', $month) - ->where('is_active', 1) - ->where('file_status', 'success') - ->findAll(); - - return $this->respond(['dataStatus' => true, 'code' => 200,'data' => $res_data], 200); - + ->where('insurer_id', $insurer_id) + ->where('branch_id', $insurer_branch_id) + ->where('month', $month) + ->where('is_active', 1) + ->where('file_status', 'success') + ->findAll(); + return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $res_data], 200); } public function deleteStatement($id) { // echo $id;die(); - $this->coShareStmtDetailsModel->where('statement_id',$id) - ->set(['is_active' => 0]) - ->update(); - $this->invPaymentDetailsModel->where('statement_id',$id) - ->set(['is_active' => 0]) - ->update(); - $this->insurerStatements->where('id',$id) - ->set(['is_active' => 0]) - ->update(); + $this->coShareStmtDetailsModel->where('statement_id', $id) + ->set(['is_active' => 0]) + ->update(); + $this->invPaymentDetailsModel->where('statement_id', $id) + ->set(['is_active' => 0]) + ->update(); + $this->insurerStatements->where('id', $id) + ->set(['is_active' => 0]) + ->update(); return $this->respond(['dataStatus' => true, 'code' => 200], 200); } - - -} \ No newline at end of file +} diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php index b9d62ff5..3e74a6dc 100644 --- a/app/Controllers/TicketController.php +++ b/app/Controllers/TicketController.php @@ -181,15 +181,16 @@ class TicketController extends BaseController return $this->loadLayout('ticket_search', $data); } else { - $data['ticket_data'] = $this->ticketSearch(); $isFromDashboard = $this->request->getPost("is_dashboard"); if (isset($isFromDashboard) && !empty($isFromDashboard) && $isFromDashboard == 1) { $data['page_name'] = "Claims"; + $data['ticket_data'] = $this->ticketSearch(3); $data['claim_status'] = $this->claimStatus->select('id,ticket_type,claim_status')->where('is_active', 1)->findAll(); $data['client_list'] = $this->clientModel->select('id,client_name')->where('is_active', 1)->findAll(); return $this->loadLayout('ticket_search', $data); }else{ + $data['ticket_data'] = $this->ticketSearch(); $html = view('ticket_list', $data); return $this->respond(['status' => true, 'html' => $html], 200); } @@ -201,39 +202,38 @@ class TicketController extends BaseController { $db = db_connect(); - $subquery = $db->table('ticket_history th') - ->select([ - 'th.ticket_id', - "CASE - WHEN DATEDIFF( - th.created_at, - COALESCE( - (SELECT MIN(created_at) FROM ticket_history th2 WHERE th2.ticket_id = th.ticket_id), - tm.created_at - ) - ) BETWEEN 0 AND 6 THEN '0-6 Days' - WHEN DATEDIFF( - th.created_at, - COALESCE( - (SELECT MIN(created_at) FROM ticket_history th2 WHERE th2.ticket_id = th.ticket_id), - tm.created_at - ) - ) BETWEEN 7 AND 12 THEN '7-12 Days' - WHEN DATEDIFF( - th.created_at, - COALESCE( - (SELECT MIN(created_at) FROM ticket_history th2 WHERE th2.ticket_id = th.ticket_id), - tm.created_at - ) - ) BETWEEN 13 AND 20 THEN '13-20 Days' - ELSE 'Above 20 Days' - END AS tat" - ]) - ->join('ticket_master tm', 'tm.id = th.ticket_id', 'right') - ->where('tm.is_active', 1) - ->groupBy('th.ticket_id, tm.created_at'); + $subquery = $db->table('ticket_master tm') + ->select([ + 'tm.id AS ticket_id', + "CASE + WHEN DATEDIFF( + CURDATE(), + COALESCE(latest_history.created_at, tm.created_at) + ) BETWEEN 0 AND 6 THEN '0-6 Days' + WHEN DATEDIFF( + CURDATE(), + COALESCE(latest_history.created_at, tm.created_at) + ) BETWEEN 7 AND 12 THEN '7-12 Days' + WHEN DATEDIFF( + CURDATE(), + COALESCE(latest_history.created_at, tm.created_at) + ) BETWEEN 13 AND 20 THEN '13-20 Days' + ELSE 'Above 20 Days' + END AS tat" + ]) + ->join( + '(SELECT th.ticket_id, MAX(th.created_at) AS created_at + FROM ticket_history th + WHERE th.field_name = "claim_status_id" + GROUP BY th.ticket_id) AS latest_history', + 'latest_history.ticket_id = tm.id', + 'left' + ) + ->where('tm.is_active', 1) + ->groupBy('tm.id, tm.created_at, latest_history.created_at'); - //action 1 get last 100 rows, action 2 filter and get all rows related to that + + //action 1 get last 100 rows, action 2 filter and get all rows related to that and action 3 gets according to dashboard if ($action == 1) { $query = $db->table('ticket_master tm') @@ -268,6 +268,18 @@ class TicketController extends BaseController return $data; + }else if ($action == 3) { + $ids = $this->request->getPost('ids'); + $ids = array_filter(explode(',', $ids)); + + if (!empty($ids)) { + $idsStr = implode(',', array_map('intval', $ids)); // sanitize IDs to be integers + $where = "tm.id IN ($idsStr)"; + } else { + $where = '1 = 0'; // No valid IDs, return empty result + } + // dd($where); + } else { $search_data = $this->request->getPost(); // print_r($search_data); die() @@ -278,7 +290,9 @@ class TicketController extends BaseController } } // print_rr($where); - $query = $db->table('ticket_master tm') + + } + $query = $db->table('ticket_master tm') ->select([ 'tm.id', 'tm.ticket_type_id', @@ -311,7 +325,6 @@ class TicketController extends BaseController // print_rr($data);die(); return $data; - } } public function ticket_form($ticket_type) diff --git a/app/Models/ClientPolicyModel.php b/app/Models/ClientPolicyModel.php index 360081a4..d456c311 100755 --- a/app/Models/ClientPolicyModel.php +++ b/app/Models/ClientPolicyModel.php @@ -71,7 +71,7 @@ class ClientPolicyModel extends Model protected function checkAndADDCreatedByValue(array $data) { // Check if 'updated_by' value is null or empty - if (empty($data['data']['created_by'])) { + if (empty($data['data']['created_by'])) { // Set 'updated_by' value to the current session user ID $data['data']['created_by'] = get_session_userid(); } @@ -82,7 +82,7 @@ class ClientPolicyModel extends Model protected function checkAndUpdateUpdatedByValue(array $data) { // Check if 'updated_by' value is null or empty - if (empty($data['data']['updated_by'])) { + if (empty($data['data']['updated_by'])) { // Set 'updated_by' value to the current session user ID $data['data']['updated_by'] = get_session_userid(); } @@ -90,100 +90,100 @@ class ClientPolicyModel extends Model return $data; } - public function getClientPolicyById($id){ + public function getClientPolicyById($id) + { return $this->db->table('client_policy') - ->select('insurers.name as insurer_name, insurers.short_name as insurer_short') - ->select('tpa.name as tpa_name, tpa.short_name as tpa_short') - ->select('policies.name as policy_name') - ->select('insurer_branch.branch_name as insurer_branch_name, insurer_branch.branch_code as insurer_branch_code') - ->select('tpa_branch.branch_name as tpa_branch_name, tpa_branch.branch_code as tpa_branch_code') - ->join('insurers', 'insurers.id = client_policy.insurer_id') - ->join('insurer_branch', 'client_policy.insurer_branch_id = insurer_branch.id') - ->join('tpa', 'tpa.id = client_policy.tpa_id') - ->join('tpa_branch', 'client_policy.tpa_branch_id = tpa_branch.id') - ->join('policies', 'policies.id = client_policy.policy_id') - ->where('client_policy.id', $id) - ->get() - ->getResult(); - + ->select('insurers.name as insurer_name, insurers.short_name as insurer_short') + ->select('tpa.name as tpa_name, tpa.short_name as tpa_short') + ->select('policies.name as policy_name') + ->select('insurer_branch.branch_name as insurer_branch_name, insurer_branch.branch_code as insurer_branch_code') + ->select('tpa_branch.branch_name as tpa_branch_name, tpa_branch.branch_code as tpa_branch_code') + ->join('insurers', 'insurers.id = client_policy.insurer_id') + ->join('insurer_branch', 'client_policy.insurer_branch_id = insurer_branch.id') + ->join('tpa', 'tpa.id = client_policy.tpa_id') + ->join('tpa_branch', 'client_policy.tpa_branch_id = tpa_branch.id') + ->join('policies', 'policies.id = client_policy.policy_id') + ->where('client_policy.id', $id) + ->get() + ->getResult(); } - public function getClientPolicyByClientId($client_id){ - + public function getClientPolicyByClientId($client_id) + { + return $this->db->table('client_policy') - ->select('client_policy.*') - ->select('insurers.name as insurer_name, insurers.short_name as insurer_short') - ->select('tpa.name as tpa_name, tpa.short_name as tpa_short') - ->select('policy_type.policy_type as policy_type_name') - ->select('insurer_branch.branch_name as insurer_branch_name, insurer_branch.branch_code as insurer_branch_code') - ->select('tpa_branch.branch_name as tpa_branch_name, tpa_branch.branch_code as tpa_branch_code') - ->select('policy_type.policy_type as policy_type_name') - ->select('client_branch.branch_name as branch_name') - ->join('insurers', 'insurers.id = client_policy.insurer_id') - ->join('insurer_branch', 'client_policy.insurer_branch_id = insurer_branch.id') - ->join('tpa', 'tpa.id = client_policy.tpa_id', 'left') - ->join('tpa_branch', 'client_policy.tpa_branch_id = tpa_branch.id', 'left') - ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') - ->join('client_branch', 'client_branch.id = client_policy.client_branch_id') - ->where('client_policy.client_id', $client_id) - ->where('client_policy.policy_status', 1) - ->where('client_policy.is_active', 1) - ->get() - ->getResult(); - - - + ->select('client_policy.*') + ->select('insurers.name as insurer_name, insurers.short_name as insurer_short') + ->select('tpa.name as tpa_name, tpa.short_name as tpa_short') + ->select('policy_type.policy_type as policy_type_name') + ->select('insurer_branch.branch_name as insurer_branch_name, insurer_branch.branch_code as insurer_branch_code') + ->select('tpa_branch.branch_name as tpa_branch_name, tpa_branch.branch_code as tpa_branch_code') + ->select('policy_type.policy_type as policy_type_name') + ->select('client_branch.branch_name as branch_name') + ->join('insurers', 'insurers.id = client_policy.insurer_id') + ->join('insurer_branch', 'client_policy.insurer_branch_id = insurer_branch.id') + ->join('tpa', 'tpa.id = client_policy.tpa_id', 'left') + ->join('tpa_branch', 'client_policy.tpa_branch_id = tpa_branch.id', 'left') + ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') + ->join('client_branch', 'client_branch.id = client_policy.client_branch_id') + ->where('client_policy.client_id', $client_id) + ->where('client_policy.policy_status', 1) + ->where('client_policy.is_active', 1) + ->get() + ->getResult(); } - public function getPolicyPremium($policy_id){ + public function getPolicyPremium($policy_id) + { return $this->db->table('policies') - ->select('policy_type.*') - ->join('policy_type', 'policy_type.id = policies.policy_type_id') - ->where('policies.id', $policy_id) - ->get() - ->getResult(); + ->select('policy_type.*') + ->join('policy_type', 'policy_type.id = policies.policy_type_id') + ->where('policies.id', $policy_id) + ->get() + ->getResult(); } - public function getPolicyPremiumPolicyTypeId($policy_type_id){ + public function getPolicyPremiumPolicyTypeId($policy_type_id) + { return $this->db->table('policies') - ->select('policy_type.*') - ->join('policy_type', 'policy_type.id = policies.policy_type_id') - ->where('policies.id', $policy_type_id) - ->get() - ->getResult(); + ->select('policy_type.*') + ->join('policy_type', 'policy_type.id = policies.policy_type_id') + ->where('policies.id', $policy_type_id) + ->get() + ->getResult(); } - public function getPolicyDetails($client_id,$policy_id) + public function getPolicyDetails($client_id, $policy_id) { return $this->select('*') - ->where('client_id',$client_id) - ->where('id',$policy_id) - ->get() - ->getResult(); - + ->where('client_id', $client_id) + ->where('id', $policy_id) + ->get() + ->getResult(); } - public function getinsurerswithclientid($id){ + public function getinsurerswithclientid($id) + { return $this->db->table('client_policy') - ->select('client_policy.*, cd_master.cd_ac_no as cd_master_account_no') - ->select('insurers.name as insurer_name, insurers.short_name as insurer_short') - ->select('clients.client_name as client_name') - ->join('clients','clients.id=client_policy.client_id') - ->join('insurers', 'insurers.id = client_policy.insurer_id') - ->join('cd_master', 'cd_master.insurer_id = insurers.id AND cd_master.client_id = client_policy.client_id') - ->where('client_policy.client_id', $id) - ->where('cd_master.id = client_policy.cd_ac_pk') - ->groupBy('client_policy.insurer_id') - ->groupBy('client_policy.client_id', $id) // Group by insurer_id - ->get() - ->getResult(); + ->select('client_policy.*, cd_master.cd_ac_no as cd_master_account_no') + ->select('insurers.name as insurer_name, insurers.short_name as insurer_short') + ->select('clients.client_name as client_name') + ->join('clients', 'clients.id=client_policy.client_id') + ->join('insurers', 'insurers.id = client_policy.insurer_id') + ->join('cd_master', 'cd_master.insurer_id = insurers.id AND cd_master.client_id = client_policy.client_id') + ->where('client_policy.client_id', $id) + ->where('cd_master.id = client_policy.cd_ac_pk') + ->groupBy('client_policy.insurer_id') + ->groupBy('client_policy.client_id', $id) // Group by insurer_id + ->get() + ->getResult(); // return $this->db->table('client_policy') // ->select('insurers.name as insurer_name, insurers.short_name as insurer_short') @@ -198,26 +198,28 @@ class ClientPolicyModel extends Model // ->getResult(); } - - public function getinsurerswithinsurenceid($insurerId){ + + public function getinsurerswithinsurenceid($insurerId) + { return $this->db->table('client_policy') - ->select('client_policy.*') - ->select('insurers.name as insurer_name, insurers.short_name as insurer_short') - ->select('clients.client_name as clientname, clients.short_name as clientshort') - ->join('insurers', 'insurers.id = client_policy.insurer_id') - ->join('clients', 'clients.id = client_policy.client_id') - ->where('client_policy.insurer_id', $insurerId) - ->groupBy('client_policy.client_id') // Group by insurer_id - ->get() - ->getResult(); + ->select('client_policy.*') + ->select('insurers.name as insurer_name, insurers.short_name as insurer_short') + ->select('clients.client_name as clientname, clients.short_name as clientshort') + ->join('insurers', 'insurers.id = client_policy.insurer_id') + ->join('clients', 'clients.id = client_policy.client_id') + ->where('client_policy.insurer_id', $insurerId) + ->groupBy('client_policy.client_id') // Group by insurer_id + ->get() + ->getResult(); } - public function getClientById($id) { + public function getClientById($id) + { $query = $this->db->table('clients')->getWhere(['id' => $id]); - // Debug statement + // Debug statement return $query->getRow(); } @@ -248,112 +250,113 @@ class ClientPolicyModel extends Model ->get() ->getResult(); } - - + + public function getDepositSummary($clientId, $insurerId) -{ - // Fetch the sum of credit and debit transactions and calculate the balance - return $this->db->table('cash_deposit') - ->select('SUM(CASE WHEN transaction_type = "Credit" THEN amount ELSE 0 END) AS total_credit') - ->select('SUM(CASE WHEN transaction_type = "Debit" THEN amount ELSE 0 END) AS total_withdraw') - ->select('SUM(CASE WHEN transaction_type = "Credit" THEN amount ELSE -amount END) AS balance') - ->select('SUM(CASE WHEN sub_type = 3 THEN amount ELSE 0 END) AS total_refund') - ->where('client_id', $clientId) - ->where('insurer_id', $insurerId) - ->where('cash_deposit.is_active', 1) - ->get() - ->getRow(); -} -// Inside your clientPolicyModel -// Inside your clientPolicyModel -// public function getDepositDataWithBalance($clientId, $insurerId) -// { -// // Fetch deposit data with balance information -// $builder = $this->db->table('cash_deposit'); -// $builder->select('id, created_at, description, sub_type, amount, transaction_type'); + { + // Fetch the sum of credit and debit transactions and calculate the balance + return $this->db->table('cash_deposit') + ->select('SUM(CASE WHEN transaction_type = "Credit" THEN amount ELSE 0 END) AS total_credit') + ->select('SUM(CASE WHEN transaction_type = "Debit" THEN amount ELSE 0 END) AS total_withdraw') + ->select('SUM(CASE WHEN transaction_type = "Credit" THEN amount ELSE -amount END) AS balance') + ->select('SUM(CASE WHEN sub_type = 3 THEN amount ELSE 0 END) AS total_refund') + ->where('client_id', $clientId) + ->where('insurer_id', $insurerId) + ->where('cash_deposit.is_active', 1) + ->get() + ->getRow(); + } + // Inside your clientPolicyModel + // Inside your clientPolicyModel + // public function getDepositDataWithBalance($clientId, $insurerId) + // { + // // Fetch deposit data with balance information + // $builder = $this->db->table('cash_deposit'); + // $builder->select('id, created_at, description, sub_type, amount, transaction_type'); -// $builder->where('client_id', $clientId); -// $builder->where('insurer_id', $insurerId); -// $builder->orderBy('created_at', 'asc'); + // $builder->where('client_id', $clientId); + // $builder->where('insurer_id', $insurerId); + // $builder->orderBy('created_at', 'asc'); -// $depositData = $builder->get()->getResult(); + // $depositData = $builder->get()->getResult(); -// $currentBalance = 0; + // $currentBalance = 0; -// foreach ($depositData as $transaction) { -// if ($transaction->transaction_type == 'Credit') { -// $currentBalance += $transaction->amount; -// } elseif ($transaction->transaction_type == 'Debit') { -// $currentBalance -= $transaction->amount; -// } + // foreach ($depositData as $transaction) { + // if ($transaction->transaction_type == 'Credit') { + // $currentBalance += $transaction->amount; + // } elseif ($transaction->transaction_type == 'Debit') { + // $currentBalance -= $transaction->amount; + // } -// $transaction->balance = $currentBalance; -// } + // $transaction->balance = $currentBalance; + // } -// return $depositData; -// } + // return $depositData; + // } -public function getBalances($clientId) -{ - $depositsummary = $this->getDepositlistsummary($clientId); - $balances = []; + public function getBalances($clientId) + { + $depositsummary = $this->getDepositlistsummary($clientId); + $balances = []; - foreach ($depositsummary as $summary) { - $insurerId = $summary->insurer_id; - $balances[$insurerId] = $summary; + foreach ($depositsummary as $summary) { + $insurerId = $summary->insurer_id; + $balances[$insurerId] = $summary; + } + + return $balances; } - return $balances; -} - -public function getDepositlistsummary($id) -{ - return $this->db->table('cash_deposit') - ->select('insurer_id') - ->select('SUM(CASE WHEN transaction_type = "Credit" THEN amount ELSE -amount END) AS balance') - ->where('client_id', $id) - ->groupBy('insurer_id') - ->get() - ->getResult(); -} + public function getDepositlistsummary($id) + { + return $this->db->table('cash_deposit') + ->select('insurer_id') + ->select('SUM(CASE WHEN transaction_type = "Credit" THEN amount ELSE -amount END) AS balance') + ->where('client_id', $id) + ->groupBy('insurer_id') + ->get() + ->getResult(); + } -public function updateStatus(){ + public function updateStatus() + { - // Update client_policy table - $client = $this->db->query("UPDATE client_policy SET policy_status = 0 WHERE policy_end_date < CURDATE()"); - $client_count = $this->db->affectedRows(); - // Update employee_polices table - $employee = $this->db->query("UPDATE employee_polices SET status = 'expired' WHERE policy_end_date < CURDATE()"); - $emp_count = $this->db->affectedRows(); + // Update client_policy table + $client = $this->db->query("UPDATE client_policy SET policy_status = 0 WHERE policy_end_date < CURDATE()"); + $client_count = $this->db->affectedRows(); + // Update employee_polices table + $employee = $this->db->query("UPDATE employee_polices SET status = 'expired' WHERE policy_end_date < CURDATE()"); + $emp_count = $this->db->affectedRows(); - return ['client'=>$client_count, 'emp' => $emp_count]; + return ['client' => $client_count, 'emp' => $emp_count]; + } + + public function getpolicyWithPattern($client_id) + { + + $query = $this->db->table('client_policy') + ->select('client_policy.*, policies.name, policies.policy_type_id, policy_type.policy_type') + ->join('policies', 'policies.id = client_policy.policy_id') + ->join('policy_type', 'policy_type.id = policies.policy_type_id') + // ->where('policy_type.policy_type', 'GMC') + ->whereIn('policy_type.id', [2, 3]) + ->where('client_policy.client_id', $client_id) + ->get() + ->getResult(); -} + return $query; + } -public function getpolicyWithPattern($client_id){ + public function getTopUpPolicy($client_id, $type) + { - $query = $this->db->table('client_policy') - ->select('client_policy.*, policies.name, policies.policy_type_id, policy_type.policy_type') - ->join('policies', 'policies.id = client_policy.policy_id') - ->join('policy_type', 'policy_type.id = policies.policy_type_id') - // ->where('policy_type.policy_type', 'GMC') - ->whereIn('policy_type.id', [2, 3]) - ->where('client_policy.client_id', $client_id) - ->get() - ->getResult(); - - - return $query; -} - -public function getTopUpPolicy($client_id, $type){ - - $query = " + $query = " SELECT client_policy.*, policies.name, policies.policy_type_id FROM client_policy JOIN policies ON policies.id = client_policy.policy_id @@ -361,65 +364,63 @@ public function getTopUpPolicy($client_id, $type){ WHERE policy_type.policy_type = '{$type}' AND client_policy.client_id = {$client_id}"; - $result = $this->db->query($query)->getResult(); + $result = $this->db->query($query)->getResult(); - return $result; - -} - - -public function getClientPolicyByPolicyType($client_id, $type){ - - - $query = $this->db->table('client_policy') - ->select('client_policy.*, insurers.name as insurer_name, insurers.short_name as insurer_short') - ->select('tpa.name as tpa_name, tpa.short_name as tpa_short') - ->select('policies.name as policy_name, policies.policy_type_id') - ->select('policy_type.policy_type as policy_type_name') - ->select('insurer_branch.branch_name as insurer_branch_name, insurer_branch.branch_code as insurer_branch_code') - ->select('tpa_branch.branch_name as tpa_branch_name, tpa_branch.branch_code as tpa_branch_code') - ->join('insurers', 'insurers.id = client_policy.insurer_id') - ->join('insurer_branch', 'client_policy.insurer_branch_id = insurer_branch.id') - ->join('tpa', 'tpa.id = client_policy.tpa_id') - ->join('tpa_branch', 'client_policy.tpa_branch_id = tpa_branch.id') - ->join('policies', 'policies.id = client_policy.policy_id') - ->join('policy_type', 'policy_type.id = policies.policy_type_id') - ->where('client_policy.client_id', $client_id) - ->where('client_policy.policy_status', 1); - - if ($type == 2) { - $query->where('policy_type.policy_type', 'GMC - Top-up'); - } else if ($type == 3) { - $query->whereIn('policy_type.policy_type', ['GMC - Parents', 'GMC - Top-up(Parents)']); + return $result; } - $result = $query->get()->getResult(); - return $result; + public function getClientPolicyByPolicyType($client_id, $type) + { -} + $query = $this->db->table('client_policy') + ->select('client_policy.*, insurers.name as insurer_name, insurers.short_name as insurer_short') + ->select('tpa.name as tpa_name, tpa.short_name as tpa_short') + ->select('policies.name as policy_name, policies.policy_type_id') + ->select('policy_type.policy_type as policy_type_name') + ->select('insurer_branch.branch_name as insurer_branch_name, insurer_branch.branch_code as insurer_branch_code') + ->select('tpa_branch.branch_name as tpa_branch_name, tpa_branch.branch_code as tpa_branch_code') + ->join('insurers', 'insurers.id = client_policy.insurer_id') + ->join('insurer_branch', 'client_policy.insurer_branch_id = insurer_branch.id') + ->join('tpa', 'tpa.id = client_policy.tpa_id') + ->join('tpa_branch', 'client_policy.tpa_branch_id = tpa_branch.id') + ->join('policies', 'policies.id = client_policy.policy_id') + ->join('policy_type', 'policy_type.id = policies.policy_type_id') + ->where('client_policy.client_id', $client_id) + ->where('client_policy.policy_status', 1); + + if ($type == 2) { + $query->where('policy_type.policy_type', 'GMC - Top-up'); + } else if ($type == 3) { + $query->whereIn('policy_type.policy_type', ['GMC - Parents', 'GMC - Top-up(Parents)']); + } + + $result = $query->get()->getResult(); + + return $result; + } -public function getPolicyTypeForPolicyBinding($client_id){ + public function getPolicyTypeForPolicyBinding($client_id) + { - $result = $this->table('client_policy') - ->select('policy_type.*, client_policy.id as client_policy_id, client_policy.policy_no') - ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') - ->where('client_policy.client_id', $client_id) - ->where('client_policy.is_active', 1) - ->whereIn('policy_type.id', [2,3]) - ->findAll(); + $result = $this->table('client_policy') + ->select('policy_type.*, client_policy.id as client_policy_id, client_policy.policy_no') + ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') + ->where('client_policy.client_id', $client_id) + ->where('client_policy.is_active', 1) + ->whereIn('policy_type.id', [2, 3]) + ->findAll(); - return $result; + return $result; + } -} + public function getCliendDataForExcelFileName($client_policy_id) + { - -public function getCliendDataForExcelFileName($client_policy_id){ - - return $this->table('client_policy') + return $this->table('client_policy') ->select('clients.short_name, policy_type.policy_type, client_branch.branch_code') ->join('clients', 'clients.id = client_policy.client_id') ->join('client_branch', 'client_branch.id = client_policy.client_branch_id') @@ -427,49 +428,48 @@ public function getCliendDataForExcelFileName($client_policy_id){ ->where('client_policy.id', $client_policy_id) ->where('client_policy.is_active', 1) ->first(); - -} - -//for this using in CRONE JOB -public function getPolicyDetailsForRemainder($client_id = null, $branch_id = null, $policy_id = null) -{ - $builder = $this->table('client_policy') - ->where('client_policy.is_active', 1) - ->where('client_policy.policy_status', 1) - // ->where('client_policy.is_addon', 1) - // ->where('client_policy.inception_type', 2) - ->where('client_policy.open_for_enrollment', 1); - - if ($client_id && $branch_id) { - $builder->where('client_policy.client_id', $client_id) - ->where('client_policy.client_branch_id', $branch_id); } - if(empty($policy_id)){ - $builder->whereIn('client_policy.policy_type_id', [2, 3, 4, 5]); - }else{ - $builder->where('client_policy.id', $policy_id); + //for this using in CRONE JOB + public function getPolicyDetailsForRemainder($client_id = null, $branch_id = null, $policy_id = null) + { + $builder = $this->table('client_policy') + ->where('client_policy.is_active', 1) + ->where('client_policy.policy_status', 1) + // ->where('client_policy.is_addon', 1) + // ->where('client_policy.inception_type', 2) + ->where('client_policy.open_for_enrollment', 1); + + if ($client_id && $branch_id) { + $builder->where('client_policy.client_id', $client_id) + ->where('client_policy.client_branch_id', $branch_id); + } + + if (empty($policy_id)) { + $builder->whereIn('client_policy.policy_type_id', [2, 3, 4, 5]); + } else { + $builder->where('client_policy.id', $policy_id); + } + + return $builder->get()->getResultArray(); } - return $builder->get()->getResultArray(); -} + //for this using in CRONE JOB + public function getPolicyDetailsForEnrollment($client_id = null, $branch_id = null) + { + $builder = $this->table('client_policy') + ->where('client_policy.is_active', 1) + ->where('client_policy.policy_status', 1) + ->where('client_policy.open_date IS NOT NULL') + ->where('client_policy.close_date IS NOT NULL'); -//for this using in CRONE JOB -public function getPolicyDetailsForEnrollment($client_id = null, $branch_id = null) -{ - $builder = $this->table('client_policy') - ->where('client_policy.is_active', 1) - ->where('client_policy.policy_status', 1) - ->where('client_policy.open_date IS NOT NULL') - ->where('client_policy.close_date IS NOT NULL'); + if ($client_id && $branch_id) { + $builder->where('client_policy.client_id', $client_id) + ->where('client_policy.client_branch_id', $branch_id); + } - if ($client_id && $branch_id) { - $builder->where('client_policy.client_id', $client_id) - ->where('client_policy.client_branch_id', $branch_id); + return $builder->get()->getResultArray(); } - return $builder->get()->getResultArray(); + } - -} - diff --git a/app/Models/LeadsModel.php b/app/Models/LeadsModel.php index cd516c7a..64dfd8d0 100644 --- a/app/Models/LeadsModel.php +++ b/app/Models/LeadsModel.php @@ -30,17 +30,17 @@ class LeadsModel extends Model 'source_policy_id', 'policy_type_id', 'salse_person_id', - 'insurer_id', - 'insurer_branch_id', - 'tpa_id', - 'tpa_branch_id', - 'policy_start_date', - 'policy_end_date', - 'no_of_lives', - 'incurred_claims', - 'location', - 'proposed_insurer_id', - 'proposed_insurer_branch_id', + 'insurer_id', + 'insurer_branch_id', + 'tpa_id', + 'tpa_branch_id', + 'policy_start_date', + 'policy_end_date', + 'no_of_lives', + 'incurred_claims', + 'location', + 'proposed_insurer_id', + 'proposed_insurer_branch_id', 'proposed_tpa_id', 'proposed_tpa_branch_id', 'proposel_data', @@ -90,7 +90,7 @@ class LeadsModel extends Model 'source_policy_start_date', 'source_policy_end_date', - + 'payment_date', 'is_cd' ]; @@ -110,7 +110,7 @@ class LeadsModel extends Model protected function checkAndADDCreatedByValue(array $data) { // Check if 'updated_by' value is null or empty - if (empty($data['data']['created_by'])) { + if (empty($data['data']['created_by'])) { // Set 'updated_by' value to the current session user ID $data['data']['created_by'] = get_session_userid(); } @@ -121,7 +121,7 @@ class LeadsModel extends Model protected function checkAndUpdateUpdatedByValue(array $data) { // Check if 'updated_by' value is null or empty - if (empty($data['data']['updated_by'])) { + if (empty($data['data']['updated_by'])) { // Set 'updated_by' value to the current session user ID $data['data']['updated_by'] = get_session_userid(); } @@ -153,10 +153,10 @@ class LeadsModel extends Model ) AS rfq_count ') - ->join('kyc_entity_type', 'leads.entity_type_id = kyc_entity_type.id', 'left') - ->join('user_profiles', 'leads.salse_person_id = user_profiles.id', 'left') - ->join('policy_type', 'leads.policy_type_id = policy_type.id', 'left') - ->where('leads.is_active', 1); + ->join('kyc_entity_type', 'leads.entity_type_id = kyc_entity_type.id', 'left') + ->join('user_profiles', 'leads.salse_person_id = user_profiles.id', 'left') + ->join('policy_type', 'leads.policy_type_id = policy_type.id', 'left') + ->where('leads.is_active', 1); if (!empty($where)) { $data->where($where); @@ -168,12 +168,12 @@ class LeadsModel extends Model public function getLeadForInsertClientList($type = null, $client_id = null) { $query = $this->db->table('leads') - ->select('leads.*, user_profiles.first_name as user_name') - ->join('user_profiles', 'leads.created_by = user_profiles.id') - ->where('leads.is_active', 1) - ->where('leads.status', 'won') - ->where("leads.proposel_data IS NOT NULL AND leads.proposel_data <> ''") - ->where("(leads.is_client_created = '' OR leads.is_client_created IS NULL)"); + ->select('leads.*, user_profiles.first_name as user_name') + ->join('user_profiles', 'leads.created_by = user_profiles.id') + ->where('leads.is_active', 1) + ->where('leads.status', 'won') + ->where("leads.proposel_data IS NOT NULL AND leads.proposel_data <> ''") + ->where("(leads.is_client_created = '' OR leads.is_client_created IS NULL)"); @@ -183,11 +183,83 @@ class LeadsModel extends Model if ($client_id) { $query->where('leads.client_id', $client_id); } - + $result = $query->get()->getResultArray(); return $result; - + } + + public function getDashData() + { + $statuses = $this->db->table('leads') + ->select('status') + ->where("is_active", 1) + ->groupBy('status') + ->get() + ->getResultArray(); + + $selectParts = []; + + foreach ($statuses as $status) { + $s = $status['status']; + $alias = strtolower(str_replace(' ', '_', $s)); + + // Count alias + $selectParts[] = "SUM(CASE WHEN status = '{$s}' THEN 1 ELSE 0 END) AS `{$alias}`"; + + // IDs alias + $selectParts[] = "GROUP_CONCAT(CASE WHEN status = '{$s}' THEN leads.id ELSE NULL END) AS `{$alias}_ids`"; + } + + $select = implode(", ", $selectParts); + + // Start query builder + $builder = $this->db->table('leads'); + + $builder->select($select); + + // Auditing subquery + $subquery = "(SELECT pk, MAX(created_at) AS last_claim_status_change + FROM auditing_history + WHERE table_name = 'leads' AND field_name = 'status' + GROUP BY pk)"; + + $builder->join("{$subquery} AS th", 'leads.id = th.pk', 'left'); + + // Date filtering for last status change + $dateLimit = 3; + $dateThreshold = date('Y-m-d H:i:s', strtotime("-{$dateLimit} days")); + + $builder->groupStart() + ->where('th.last_claim_status_change <=', $dateThreshold) + ->orWhere('th.last_claim_status_change IS NULL') + ->groupEnd(); + + // Add only active + $builder->where("leads.is_active", 1); + + $lead_data = $builder->get()->getResultArray(); + + // Fallback for empty results + if (empty($lead_data)) { + $lead_data[0] = ['total' => 0]; + foreach ($statuses as $status) { + $alias = strtolower(str_replace(' ', '_', $status['status'])); + $lead_data[0][$alias] = 0; + $lead_data[0]["{$alias}_ids"] = ''; + } + } + + // Calculate total + $total = 0; + foreach ($lead_data[0] as $key => $value) { + if (!str_ends_with($key, '_ids') && $key != "won") { + $total += (int) $value; + } + } + $lead_data[0]['total'] = $total; + + // dd($lead_data[0]); + return $lead_data[0]; } - } diff --git a/app/Models/PolicyTransactionModel.php b/app/Models/PolicyTransactionModel.php index b5d42e54..cb7a1ce4 100644 --- a/app/Models/PolicyTransactionModel.php +++ b/app/Models/PolicyTransactionModel.php @@ -81,7 +81,7 @@ class PolicyTransactionModel extends Model 'policy_with_corr', 'is_cd_reduce_from_bds', ]; - + // Callbacks @@ -98,7 +98,7 @@ class PolicyTransactionModel extends Model protected function checkAndADDCreatedByValue(array $data) { // Check if 'updated_by' value is null or empty - if (empty($data['data']['created_by'])) { + if (empty($data['data']['created_by'])) { // Set 'updated_by' value to the current session user ID $data['data']['created_by'] = get_session_userid(); } @@ -109,7 +109,7 @@ class PolicyTransactionModel extends Model protected function checkAndUpdateUpdatedByValue(array $data) { // Check if 'updated_by' value is null or empty - if (empty($data['data']['updated_by'])) { + if (empty($data['data']['updated_by'])) { // Set 'updated_by' value to the current session user ID $data['data']['updated_by'] = get_session_userid(); } @@ -267,21 +267,21 @@ class PolicyTransactionModel extends Model ->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left') ->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left') ->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left') - ->where('policy_transaction.is_active', 1); - + ->where('policy_transaction.is_active', 1); + // Check if the start date and end date are provided if ($start_date != 0 && $end_date != 0 && $date_type != 0) { $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); - $builder->where('policy_transaction.'.$date_type.'>=', $startDate) - ->where('policy_transaction.'.$date_type.'<=', $endDate); - }else{ + $builder->where('policy_transaction.' . $date_type . '>=', $startDate) + ->where('policy_transaction.' . $date_type . '<=', $endDate); + } else { // $fromDate = date('Y-m-d', strtotime('-30 days')); // $toDate = date('Y-m-d 23:59:59'); - + // $builder->where('policy_transaction.created_at >=', $fromDate) // ->where('policy_transaction.created_at <=', $toDate); } @@ -289,31 +289,30 @@ class PolicyTransactionModel extends Model if ($client_id != 0) { $builder->where('policy_transaction.client_id', $client_id); } - + if ($insurer_id != 0) { $builder->where('policy_transaction.insurer_id', $insurer_id); } - + if ($policy_type_id != 0) { $builder->where('client_policy.policy_type_id', $policy_type_id); } - + if ($issuer != 0) { $builder->where('policy_transaction.issuer', $issuer); } - if($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0){ + if ($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0) { $fromDate = date('Y-m-d', strtotime('-30 days')); $toDate = date('Y-m-d 23:59:59'); - - $builder->where('policy_transaction.created_at >=', $fromDate) - ->where('policy_transaction.created_at <=', $toDate); + $builder->where('policy_transaction.created_at >=', $fromDate) + ->where('policy_transaction.created_at <=', $toDate); } $builder->orderBy('policy_transaction.id', 'desc'); - + return $builder->get()->getResultArray(); } @@ -446,7 +445,7 @@ class PolicyTransactionModel extends Model // AND insurer_statements.is_active = 1 // AND insurer_statements.invoice_status IS NOT NULL // $date_condition - + // ), // 2 // ) AS billed_amt, @@ -511,7 +510,7 @@ class PolicyTransactionModel extends Model // ->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left') // ->where('policy_transaction.is_active', 1) // ->where('pt_co_share_details.is_active', 1); - + // // Check if the start date and end date are provided // if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') { @@ -547,7 +546,7 @@ class PolicyTransactionModel extends Model // if ($client_id != 0) { // $builder->where('policy_transaction.client_id', $client_id); // } - + // if ($insurer_id != 0) { // $builder->where('policy_transaction.insurer_id', $insurer_id); // } @@ -555,7 +554,7 @@ class PolicyTransactionModel extends Model // if ($client_branch_id != 0) { // $builder->where('policy_transaction.client_branch_id', $client_branch_id); // } - + // if ($insurer_branch_id != 0) { // $builder->where('policy_transaction.insurer_branch_id', $insurer_branch_id); // } @@ -565,11 +564,11 @@ class PolicyTransactionModel extends Model // } - + // if ($policy_type_id != 0) { // $builder->where('client_policy.policy_type_id', $policy_type_id); // } - + // if ($issuer != 0) { // $builder->where('policy_transaction.issuer', $issuer); // } @@ -578,7 +577,7 @@ class PolicyTransactionModel extends Model // $fromDate = date('Y-m-d', strtotime('-30 days')); // $toDate = date('Y-m-d 23:59:59'); - + // $builder->where('policy_transaction.created_at >=', $fromDate) // ->where('policy_transaction.created_at <=', $toDate); @@ -589,18 +588,18 @@ class PolicyTransactionModel extends Model // $result = $builder->get()->getResultArray(); // // dd($this->db->getLastQuery()); - + // return $result; // } - public function getBDSReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0) - { + public function getBDSReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0, $where = []) + { $date_condition = ''; - if($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) { + if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) { $date_condition = " - AND insurer_statements.month >= '".$start_date ."' - AND insurer_statements.month <= '".$end_date ."' + AND insurer_statements.month >= '" . $start_date . "' + AND insurer_statements.month <= '" . $end_date . "' "; } @@ -782,7 +781,7 @@ class PolicyTransactionModel extends Model ->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left') ->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left') ->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left') - ->where('policy_transaction.is_active', 1) + ->where('policy_transaction.is_active', 1) ->where('pt_co_share_details.is_active', 1); if ( @@ -797,16 +796,18 @@ class PolicyTransactionModel extends Model $builder->where('policy_transaction.created_by', get_session_userid()); } } - + if (!empty($where)) { + log_message('info', 'Where condition: ' . json_encode($where)); + $builder->where($where); + } // Check if the start date and end date are provided if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') { $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); - $builder->where('policy_transaction.'.$date_type.'>=', $startDate) - ->where('policy_transaction.'.$date_type.'<=', $endDate); - + $builder->where('policy_transaction.' . $date_type . '>=', $startDate) + ->where('policy_transaction.' . $date_type . '<=', $endDate); } // if($date_type == 'statement_month' && $start_date != 0 && $end_date != 0){ @@ -823,17 +824,17 @@ class PolicyTransactionModel extends Model $endDate = date('Y-m-d', strtotime($end_date)); $builder->join('co_share_stmt_details', 'pt_co_share_details.id = co_share_stmt_details.co_share_id', 'left') - ->join('insurer_statements', 'co_share_stmt_details.statement_id = insurer_statements.id','left') - ->where('insurer_statements.is_active', 1) - ->where('insurer_statements.month >=', $startDate) - ->where('insurer_statements.month <=', $endDate) - ->groupBy('co_share_stmt_details.co_share_id'); + ->join('insurer_statements', 'co_share_stmt_details.statement_id = insurer_statements.id', 'left') + ->where('insurer_statements.is_active', 1) + ->where('insurer_statements.month >=', $startDate) + ->where('insurer_statements.month <=', $endDate) + ->groupBy('co_share_stmt_details.co_share_id'); } if ($client_id != 0) { $builder->where('policy_transaction.client_id', $client_id); } - + if ($insurer_id != 0) { $builder->where('policy_transaction.insurer_id', $insurer_id); } @@ -841,7 +842,7 @@ class PolicyTransactionModel extends Model if ($client_branch_id != 0) { $builder->where('policy_transaction.client_branch_id', $client_branch_id); } - + if ($insurer_branch_id != 0) { $builder->where('policy_transaction.insurer_branch_id', $insurer_branch_id); } @@ -851,23 +852,24 @@ class PolicyTransactionModel extends Model } - + if ($policy_type_id != 0) { $builder->where('client_policy.policy_type_id', $policy_type_id); } - + if ($issuer != 0) { $builder->where('policy_transaction.issuer', $issuer); } - if($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0){ + if ($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0) { $fromDate = date('Y-m-d', strtotime('-30 days')); $toDate = date('Y-m-d 23:59:59'); - - $builder->where('policy_transaction.created_at >=', $fromDate) - ->where('policy_transaction.created_at <=', $toDate); + if (empty($where)) { + $builder->where('policy_transaction.created_at >=', $fromDate) + ->where('policy_transaction.created_at <=', $toDate); + } } $builder->orderBy('policy_transaction.id', 'desc'); @@ -875,10 +877,10 @@ class PolicyTransactionModel extends Model $result = $builder->get()->getResultArray(); // dd($this->db->getLastQuery()); - + return $result; } - + // public function getInceptionTranctionListData($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) // { // // dd($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status); @@ -917,7 +919,7 @@ class PolicyTransactionModel extends Model // // $fromDate = date('Y-m-d', strtotime('-30 days')); // // $toDate = date('Y-m-d 23:59:59'); - + // // $builder->where('policy_transaction.created_at >=', $fromDate) // // ->where('policy_transaction.created_at <=', $toDate); // } @@ -925,15 +927,15 @@ class PolicyTransactionModel extends Model // if ($client_id != 0) { // $builder->where('policy_transaction.client_id', $client_id); // } - + // if ($insurer_id != 0) { // $builder->where('policy_transaction.insurer_id', $insurer_id); // } - + // if ($policy_type_id != 0) { // $builder->where('client_policy.policy_type_id', $policy_type_id); // } - + // if ($issuer != 0) { // $builder->where('policy_transaction.issuer', $issuer); // } @@ -945,12 +947,12 @@ class PolicyTransactionModel extends Model // $fromDate = date('Y-m-d', strtotime('-30 days')); // $toDate = date('Y-m-d 23:59:59'); - + // $builder->where('policy_transaction.created_at >=', $fromDate) // ->where('policy_transaction.created_at <=', $toDate); // } - + // $builder->orderBy('policy_transaction.id', 'desc')->limit(10); // $result = $builder->get()->getResultArray(); @@ -1003,7 +1005,7 @@ class PolicyTransactionModel extends Model // Optimize Date Filtering if (!empty($start_date) && !empty($end_date) && !empty($date_type)) { $builder->where("policy_transaction.$date_type >=", date('Y-m-d 00:00:00', strtotime($start_date))) - ->where("policy_transaction.$date_type <=", date('Y-m-d 23:59:59', strtotime($end_date))); + ->where("policy_transaction.$date_type <=", date('Y-m-d 23:59:59', strtotime($end_date))); } // Apply Filters Only When Necessary @@ -1029,7 +1031,7 @@ class PolicyTransactionModel extends Model $toDate = date('Y-m-d 23:59:59'); $builder->where('policy_transaction.created_at >=', $fromDate) - ->where('policy_transaction.created_at <=', $toDate); + ->where('policy_transaction.created_at <=', $toDate); } // Optimize Query Execution @@ -1038,7 +1040,7 @@ class PolicyTransactionModel extends Model return $builder->get()->getResultArray(); } - + public function getEndorsementTranctionListData($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) { // dd($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status); @@ -1055,7 +1057,7 @@ class PolicyTransactionModel extends Model ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') ->join('clients', 'policy_transaction.client_id = clients.id', 'left') ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left') - ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id','left') + ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left') ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left') ->where('policy_transaction.is_active', 1) @@ -1073,20 +1075,20 @@ class PolicyTransactionModel extends Model $builder->where('policy_transaction.created_by', get_session_userid()); } } - + if ($start_date != 0 && $end_date != 0 && $date_type != 0) { $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); - $builder->where('policy_transaction.'.$date_type.'>=', $startDate) - ->where('policy_transaction.'.$date_type.'<=', $endDate); - }else{ + $builder->where('policy_transaction.' . $date_type . '>=', $startDate) + ->where('policy_transaction.' . $date_type . '<=', $endDate); + } else { // $fromDate = date('Y-m-d', strtotime('-30 days')); // $toDate = date('Y-m-d 23:59:59'); - + // $builder->where('policy_transaction.created_at >=', $fromDate) // ->where('policy_transaction.created_at <=', $toDate); } @@ -1094,15 +1096,15 @@ class PolicyTransactionModel extends Model if ($client_id != 0) { $builder->where('policy_transaction.client_id', $client_id); } - + if ($insurer_id != 0) { $builder->where('policy_transaction.insurer_id', $insurer_id); } - + if ($policy_type_id != 0) { $builder->where('client_policy.policy_type_id', $policy_type_id); } - + if ($issuer != 0) { $builder->where('policy_transaction.issuer', $issuer); } @@ -1110,16 +1112,15 @@ class PolicyTransactionModel extends Model $builder->where('policy_transaction.status', $status); } - if($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0){ + if ($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0) { $fromDate = date('Y-m-d', strtotime('-30 days')); $toDate = date('Y-m-d 23:59:59'); - - $builder->where('policy_transaction.created_at >=', $fromDate) - ->where('policy_transaction.created_at <=', $toDate); + $builder->where('policy_transaction.created_at >=', $fromDate) + ->where('policy_transaction.created_at <=', $toDate); } - + $builder->orderBy('policy_transaction.id', 'desc'); return $builder->get()->getResultArray(); @@ -1235,14 +1236,14 @@ class PolicyTransactionModel extends Model // ->having('premium_variance_amt !=',0); // ->group_start() - ->having('variance_amt IS NOT NULL') - ->orHaving('variance_amt !=', 0) - ->having('premium_variance_amt IS NOT NULL') - ->orHaving('premium_variance_amt !=', 0); - // ->group_end(); - // ->where('pt_co_share_details.actual_bp_brokerage_amt IS NOT NULL AND pt_co_share_details.actual_bp_brokerage_amt != 0'); - // ->where('pt_co_share_details.variance IS NOT NULL') - // ->where('pt_co_share_details.variance !=', 0); + ->having('variance_amt IS NOT NULL') + ->orHaving('variance_amt !=', 0) + ->having('premium_variance_amt IS NOT NULL') + ->orHaving('premium_variance_amt !=', 0); + // ->group_end(); + // ->where('pt_co_share_details.actual_bp_brokerage_amt IS NOT NULL AND pt_co_share_details.actual_bp_brokerage_amt != 0'); + // ->where('pt_co_share_details.variance IS NOT NULL') + // ->where('pt_co_share_details.variance !=', 0); if ($start_date != 0 && $end_date != 0 && $date_type != 0) { @@ -1279,7 +1280,7 @@ class PolicyTransactionModel extends Model if ($client_branch_id != 0) { $builder->where('policy_transaction.client_branch_id', $client_branch_id); } - + if ($insurer_branch_id != 0) { $builder->where('policy_transaction.insurer_branch_id', $insurer_branch_id); } @@ -1296,6 +1297,7 @@ class PolicyTransactionModel extends Model public function getBusinessReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) { + $dateThreshold = date('Y-m-d H:i:s', strtotime("- 3 days")); $builder = $this->db->table('policy_transaction') ->select([ 'policy_transaction.id AS policy_trns_id', @@ -1319,9 +1321,19 @@ class PolicyTransactionModel extends Model ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left') ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') + ->join( + '(SELECT policy_tran_id, MAX(created_at) AS last_policy_status_change,is_active + FROM policy_transaction_status + WHERE is_active = 1 + GROUP BY policy_tran_id) th', + 'policy_transaction.id = th.policy_tran_id' + + ) + ->where("th.last_policy_status_change <= '{$dateThreshold}'", null, false) ->where('policy_transaction.is_active', 1) // ->where('policy_transaction.status', 'completed') - ->where('pt_co_share_details.bp_amt IS NULL OR pt_co_share_details.bp_amt = 0'); + ->where('(pt_co_share_details.bp_amt IS NULL OR pt_co_share_details.bp_amt = 0)', null, false); + if ($start_date != 0 && $end_date != 0 && $date_type != 0) { @@ -1360,15 +1372,21 @@ class PolicyTransactionModel extends Model } $builder->orderBy('policy_transaction.id', 'desc'); + // echo $builder->getCompiledSelect(); + // exit; $returnData = $builder->get()->getResultArray(); + + // dd($returnData); return $returnData; } public function getFinanceReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) { + $dateThreshold = date('Y-m-d H:i:s', strtotime("- 3 days")); + $builder = $this->db->table('policy_transaction') ->select(" policy_transaction.id, @@ -1391,11 +1409,20 @@ class PolicyTransactionModel extends Model ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left') ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') + ->join( + '(SELECT policy_tran_id, MAX(created_at) AS last_policy_status_change,is_active + FROM policy_transaction_status + WHERE is_active = 1 + GROUP BY policy_tran_id) th', + 'policy_transaction.id = th.policy_tran_id' + + ) + ->where("th.last_policy_status_change <= '{$dateThreshold}'", null, false) ->where('policy_transaction.is_active', 1) // ->where('policy_transaction.status', 'completed') ->where('COALESCE(pt_co_share_details.agreed_bp_per, 0) + COALESCE(pt_co_share_details.agreed_tp_per, 0) + COALESCE(pt_co_share_details.agreed_tep_per, 0) = 0') ->where('COALESCE(pt_co_share_details.actual_bp_amt, 0) + COALESCE(pt_co_share_details.actual_tp_amt, 0) + COALESCE(pt_co_share_details.actual_tep_amt, 0) = 0') - ->where('COALESCE(pt_co_share_details.actual_bp_brokerage_amt, 0) + COALESCE(pt_co_share_details.actual_tp_brokerage_amt, 0) + COALESCE(pt_co_share_details.actual_tep_brokerage_amt, 0) = 0'); + ->where('COALESCE(pt_co_share_details.actual_bp_brokerage_amt, 0) + COALESCE(pt_co_share_details.actual_tp_brokerage_amt, 0) + COALESCE(pt_co_share_details.actual_tep_brokerage_amt, 0) = 0'); if ($start_date != 0 && $end_date != 0 && $date_type != 0) { @@ -1492,55 +1519,55 @@ class PolicyTransactionModel extends Model ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') ->where('policy_transaction.is_active', 1); - + // Date range filtering if ($start_date != 0 && $end_date != 0 && $date_type != 0) { $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); - + $builder->where('policy_transaction.' . $date_type . '>=', $startDate) ->where('policy_transaction.' . $date_type . '<=', $endDate); } else { $fromDate = date('Y-m-d', strtotime('-30 days')); $toDate = date('Y-m-d 23:59:59'); - + $builder->where('policy_transaction.created_at >=', $fromDate) ->where('policy_transaction.created_at <=', $toDate); } - + // Additional filters if ($client_id != 0) { $builder->where('policy_transaction.client_id', $client_id); } - + if ($insurer_id != 0) { $builder->where('policy_transaction.insurer_id', $insurer_id); } - + if ($policy_type_id != 0) { $builder->where('client_policy.policy_type_id', $policy_type_id); } - + if ($issuer != 0) { $builder->where('policy_transaction.issuer', $issuer); } - + if ($status != 0) { $builder->where('policy_transaction.status', $status); } - + // Filter where outstanding_amount is not null $builder->having('outstanding_amount IS NOT NULL'); - + $builder->orderBy('policy_transaction.id', 'desc'); - + return $builder->get()->getResultArray(); } - public function getOutstandingReportList($start_date = 0, $end_date = 0, $insurer_id = 0,$insurer_branch_id = 0) + public function getOutstandingReportList($start_date = 0, $end_date = 0, $insurer_id = 0, $insurer_branch_id = 0) { $builder = $this->db->table('insurer_statements s') - ->select(' + ->select(' s.id, s.insurer_id, s.branch_id, @@ -1556,32 +1583,32 @@ class PolicyTransactionModel extends Model COALESCE(SUM(p.inv_amt) + SUM(p.tds) + SUM(p.gst), 0) AS total_paid, (s.invoice_amount - COALESCE(SUM(p.inv_amt) + SUM(p.tds) + SUM(p.gst), 0)) AS outstanding_amount ') - ->join('inv_payment_details p', 's.id = p.statement_id', 'left') - ->join('insurers ins', 's.insurer_id = ins.id') - ->join('insurer_branch ib', 's.branch_id = ib.id') - ->where('s.is_active', 1) - ->where('p.is_active', 1) - ->groupBy('s.id, s.invoice_no, s.invoice_date, s.invoice_amount') - ->having('outstanding_amount >', 0); - // ->get(); + ->join('inv_payment_details p', 's.id = p.statement_id', 'left') + ->join('insurers ins', 's.insurer_id = ins.id') + ->join('insurer_branch ib', 's.branch_id = ib.id') + ->where('s.is_active', 1) + ->where('p.is_active', 1) + ->groupBy('s.id, s.invoice_no, s.invoice_date, s.invoice_amount') + ->having('outstanding_amount >', 0); + // ->get(); + - // Date range filtering if ($start_date != 0 && $end_date != 0) { - + $builder->where('s.month >=', $start_date) ->where('s.month <=', $end_date); - } - + } + if ($insurer_id != 0) { $builder->where('s.insurer_id', $insurer_id); } - if ($insurer_branch_id != 0) { + if ($insurer_branch_id != 0) { $builder->where('s.branch_id', $insurer_branch_id); } $builder->orderBy('s.id', 'desc'); - + return $builder->get()->getResultArray(); } @@ -1591,12 +1618,12 @@ class PolicyTransactionModel extends Model { $fromDate = date('Y-m-d', strtotime('-60 days')); $toDate = date('Y-m-d 23:59:59'); - + if (!empty($start_date) && !empty($end_date)) { $fromDate = change_date_format($start_date); $toDate = change_date_format($end_date); } - + $query = $this->db->table('policy_transaction pt') ->select(' pt.*, @@ -1621,7 +1648,7 @@ class PolicyTransactionModel extends Model ->where('pt.is_active', 1) ->where('pt_co.is_active', 1) ->where('pt.action_type', "inception"); - + // Apply filters if parameters are provided if (!empty($client_type)) { $query->where('c.client_type', $client_type); @@ -1632,7 +1659,7 @@ class PolicyTransactionModel extends Model if (!empty($issuer)) { // Corrected condition to check $issuer $query->where('pt.issuer', $issuer); } - + $query->groupBy('pt.id'); $query->orderBy('pt.id', 'DESC'); // Fetch and return results @@ -1640,6 +1667,47 @@ class PolicyTransactionModel extends Model // print($this->db->getLastQuery()); die; return $results; } - - + + public function getBDSRenewalData() + { + // Increase GROUP_CONCAT limit + $this->db->query("SET SESSION group_concat_max_len = 1000000;"); + + $builder = $this->db->table('policy_transaction pt'); + + $builder->select([ + 'SUM(CASE WHEN pt.policy_end_date < CURDATE() THEN 1 ELSE 0 END) AS Expired', + 'SUM(CASE WHEN pt.policy_end_date BETWEEN CURDATE() AND (CURDATE() + INTERVAL 1 MONTH) THEN 1 ELSE 0 END) AS `Renewal Pending`', + 'GROUP_CONCAT(CASE WHEN pt.policy_end_date < CURDATE() THEN pt.id ELSE NULL END) AS Expired_ids', + 'GROUP_CONCAT(CASE WHEN pt.policy_end_date BETWEEN CURDATE() AND (CURDATE() + INTERVAL 1 MONTH) THEN pt.id ELSE NULL END) AS Renewal_Pending_ids' + ]); + $builder->where("pt.policy_end_date IS NOT NULL", null, false); + $builder->where('pt.is_active', 1); + + // Self join to check if a policy has been renewed + $builder->join('policy_transaction renewed', 'renewed.source_client_policy_id = pt.client_policy_id and renewed.client_id = pt.client_id and renewed.client_branch_id = pt.client_branch_id', 'left'); + + // Filter for expired or expiring policies + $builder->where("(pt.policy_end_date < CURDATE() OR pt.policy_end_date BETWEEN CURDATE() AND (CURDATE() + INTERVAL 1 MONTH))", null, false); + + $builder->where('renewed.id IS NULL', null, false); + $query = $builder->get(); + $result = $query->getResultArray(); + + $total = 0; + foreach ($result[0] as $key => $value) { + if ($key !== 'Expired_ids' && $key !== 'Renewal_Pending_ids') { + $total += $value; + } + } + + // Ensure ID fields are arrays (not null) + $result[0]['Expired_ids'] = $result[0]['Expired_ids'] ? $result[0]['Expired_ids'] : []; + $result[0]['Renewal Pending_ids'] = $result[0]['Renewal_Pending_ids'] ? $result[0]['Renewal_Pending_ids'] : []; + + // Add total count + $result[0]['total'] = $total; + + return $result[0]; + } } diff --git a/app/Models/TicketMasterModel.php b/app/Models/TicketMasterModel.php index 4bd247dc..7e011952 100644 --- a/app/Models/TicketMasterModel.php +++ b/app/Models/TicketMasterModel.php @@ -726,76 +726,145 @@ class TicketMasterModel extends Model $finalResults = []; foreach ($claim_statuses as $typeId => $statuses) { - $builder = $this->db->table('ticket_master tm'); + // Get all active, non-null claim status tickets for this type + $builder = $this->db->table('ticket_master tm') + ->select('tm.id, tm.ticket_type_id, tcs.claim_status, th.last_claim_status_change') + ->join('ticket_claim_status tcs', 'tm.claim_status_id = tcs.id', 'left') + ->join( + '(SELECT ticket_id, MAX(created_at) AS last_claim_status_change + FROM ticket_history + WHERE field_name = \'claim_status_id\' + GROUP BY ticket_id) th', + 'tm.id = th.ticket_id', + 'left' + ) + ->where('tm.ticket_type_id', $typeId) + ->where('tm.is_active', 1) + ->where('tm.claim_status_id IS NOT NULL'); - // Start with ticket_type_id in SELECT - $selects = ['tm.ticket_type_id']; + $results = $builder->get()->getResultArray(); - // Dynamically build status counts with COALESCE to handle missing values - foreach ($statuses as $status) { - $alias = strtolower($status); - $alias = str_replace(' ', '_', $alias); - $selects[] = "COALESCE(SUM(CASE WHEN tcs.claim_status = " . $this->db->escape($status) . " AND tm.ticket_type_id = {$typeId} THEN 1 ELSE 0 END), 0) AS `{$alias}`"; - } + $summary = [ + 'ticket_type_id' => $typeId, + ]; - $builder->select(implode(',', $selects)); - $builder->join('ticket_claim_status tcs', 'tm.claim_status_id = tcs.id', 'left'); - - // Subquery for latest status change, with LEFT JOIN to avoid missing ticket_type_id - $builder->join( - '(SELECT ticket_id, MAX(created_at) AS last_claim_status_change - FROM ticket_history - WHERE field_name = \'claim_status_id\' - GROUP BY ticket_id) th', - 'tm.id = th.ticket_id', - 'left' - ); - - // Set the date limit based on the status - foreach ($statuses as $status) { - $dateLimit = $limit[$typeId][$status] ?? 3; - $dateThreshold = date('Y-m-d H:i:s', strtotime("-{$dateLimit} days")); - - $builder->groupStart() - ->where('th.last_claim_status_change <=', $dateThreshold) - ->orWhere('th.last_claim_status_change IS NULL') - ->groupEnd(); - } - - - $builder->where('tm.ticket_type_id', $typeId); - $builder->where('tm.is_active', 1); - $builder->where('tm.claim_status_id is not null'); - - $builder->groupBy('tm.ticket_type_id'); - - $query = $builder->get(); - $result = $query->getRowArray(); - - // Add Total count $total = 0; - foreach ($result as $key => $res) { - // Ensure that ticket_type_id is excluded from the sum - if ($key !== 'ticket_type_id') { - $total += $res; - } - } - $result['total'] = $total; + foreach ($statuses as $status) { + $alias = strtolower(str_replace(' ', '_', $status)); + $summary[$alias] = 0; + $summary[$alias . '_ids'] = ''; - // If no result, initialize an empty result for the ticket_type_id - if (!$result) { - $result = ['ticket_type_id' => $typeId, 'total' => 0]; - foreach ($statuses as $status) { - $alias = strtolower($status); - $alias = str_replace(' ', '_', $alias); - $result[$alias] = 0; + $dateLimit = $limit[$typeId][$status] ?? 3; + $threshold = date('Y-m-d H:i:s', strtotime("-{$dateLimit} days")); + + $ticketIds = []; + // dd($results); + foreach ($results as $row) { + if ( + $row['claim_status'] === $status && + ( + !$row['last_claim_status_change'] || + $row['last_claim_status_change'] <= $threshold + ) + ) { + $summary[$alias]++; + $ticketIds[] = $row['id']; + if ($status == "APPROVED"|| $status == "SETTLED"|| $status == "CLOSED" ){ + continue; + } + + $total++; + + + } } + + // Convert ticket IDs array to a comma-separated string + $summary[$alias . '_ids'] = implode(',', $ticketIds); } - // Add the result to the final array - $finalResults[$typeId] = $result; + $summary['total'] = $total; + + // Add approved but not settled IDs and count + $approvedNotSettled = $this->getNotSettledbutApprovedCount($typeId); + $summary['approved_not_settled'] = $approvedNotSettled['count']; + $summary['approved_not_settled_ids'] = $approvedNotSettled['ticket_ids']; + + $finalResults[$typeId] = $summary; } + // dd($finalResults); return $finalResults; } + + + + public function getNotSettledbutApprovedCount($ticket_type) + { + // Fetch the approved and settled claim_status IDs + $builder = $this->db->table("ticket_claim_status approved") + ->select("approved.id AS approved_id, settled.id AS settled_id") + ->join("ticket_claim_status settled", "approved.ticket_type = settled.ticket_type") + ->where("approved.claim_status", "APPROVED") + ->where("settled.claim_status", "SETTLED") + ->where("approved.ticket_type", $ticket_type) + ->where("approved.is_active", 1) + ->where("settled.is_active", 1); + + $ids = $builder->get()->getRowArray(); + + // If no matching status IDs are found, return empty + if (!$ids) { + return ['count' => 0, 'ticket_ids' => '']; + } + + // Extract approved and settled status IDs + $approved_id = $ids['approved_id']; + $settled_id = $ids['settled_id']; + + // Subquery to get the latest approval time for each ticket + $subquery = $this->db->table('ticket_history') + ->select('ticket_id, MAX(created_at) AS approved_time') + ->where('field_name', 'claim_status_id') + ->where('new_value', $approved_id) + ->groupBy('ticket_id'); + + // Main query to find tickets that are approved but not settled + $builder = $this->db->table('ticket_master tm'); + + $builder->join("({$subquery->getCompiledSelect()}) latest_approval", 'tm.id = latest_approval.ticket_id', 'inner'); + + // Left join to find if there is a settled status for each ticket after approval + $builder->join( + 'ticket_history th_settled', + "th_settled.ticket_id = tm.id + AND th_settled.field_name = 'claim_status_id' + AND th_settled.new_value = {$settled_id} + AND th_settled.created_at > latest_approval.approved_time", + 'left', + false // Important for raw ON condition + ); + + // Filtering conditions: not settled and approved time older than 12 days + $builder->where('tm.claim_status_id !=', $settled_id); + $builder->where('tm.is_active', 1); + $builder->where("latest_approval.approved_time <= DATE_SUB(NOW(), INTERVAL 12 DAY)", null, false); + $builder->where('th_settled.id IS NULL', null, false); + + // Final select to get ticket IDs of approved but not settled tickets + $builder->select('tm.id'); + + // Execute the query + $query = $builder->get(); + $ticketIds = array_column($query->getResultArray(), 'id'); // Extract the IDs + + // Convert ticket IDs array to a comma-separated string + $ticketIdsString = implode(',', $ticketIds); + + // Return the count and comma-separated ticket IDs + return [ + 'count' => count($ticketIds), + 'ticket_ids' => $ticketIdsString + ]; + } } diff --git a/app/Views/DashBoard.php b/app/Views/DashBoard.php index 55b75fc5..40d25654 100755 --- a/app/Views/DashBoard.php +++ b/app/Views/DashBoard.php @@ -173,7 +173,7 @@ - +
@@ -217,28 +217,43 @@ - + + - + + + + + +
- + + + + - + + + diff --git a/app/Views/bds_dash.php b/app/Views/bds_dash.php index c6711ec9..4afc8015 100644 --- a/app/Views/bds_dash.php +++ b/app/Views/bds_dash.php @@ -131,11 +131,14 @@ body{
- -