diff --git a/.gitignore b/.gitignore
index a599a01e..e0e9251f 100755
--- a/.gitignore
+++ b/.gitignore
@@ -33,3 +33,5 @@ build/
composer.lock
.env
.phpunit*
+phpqueue.sh
+
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 0059a7a1..a6e3eb12 100755
--- a/app/Config/Routes.php
+++ b/app/Config/Routes.php
@@ -52,6 +52,10 @@ $routes->get('/update-emp-policy-status', 'ClientController::updateEmpAndPolicyS
$routes->get('download-e-card/(:any)', 'EmployeeController::generateIDCardForEmployee/$1');
$routes->get('download-kyc-docs/(:segment)', 'ClientController::downloadKYCDocument/$1');
$routes->get('claim-form-download/(:any)', 'TicketController::downloadClaimForm/$1');
+$routes->match (['get','post'],"claims-feedback-form/(:any)/(:any)", "TicketController::viewClaimFeedbackForm/$1/$2");
+$routes->match (['get','post'],"claims-feedback-form/(:any)", "TicketController::viewClaimFeedbackForm/$1");
+
+
$routes->group("/user", ["filter" => "authMVC"], function ($routes) {
$routes->post("create", "UserController::create");
@@ -68,6 +72,7 @@ $routes->group("/dashboard", ["filter" => "authMVC"], function ($routes) {
$routes->get('get-notification', 'DashboardController::getDashboardNotifications');
$routes->get('acknowledge-notification/(:segment)', 'DashboardController::acknowledgeMessage/$1');
$routes->get('get-pending-action', 'PendingActionsController::getPendingActions');
+ $routes->post("prepareClaimSearchData","DashboardController::prepareClaimSearchData");
});
$routes->group("/client", ["filter" => "authMVC"], function ($routes) {
@@ -83,6 +88,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) {
@@ -348,6 +355,7 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) {
$routes->get('getTheEmpDataForClaimSearchByMobile/(:any)', 'ClientController::getTheEmpDataForClaimSearchByMobile/$1');
$routes->get('getLeadNonEB/(:any)', 'LeadsController::getLeadNonEB/$1');
$routes->get('getPolicyTypeFields', 'LeadsController::getPolicyTypeFields');
+ $routes->get('removeMultiFile', 'LeadsController::removeMultiFile');
});
$routes->group("policy_tranction", ["filter" => "authMVC"], function ($routes) {
@@ -533,6 +541,7 @@ $routes->group("/bdsReport", ["filter" => "authMVC"], function ($routes) {
//New Tickets
$routes->group("/ticket", ["filter" => "authMVC"], function ($routes) {
$routes->match( ['get', 'post'], 'list','TicketController::ticketList');
+ $routes->get('feedback-list','TicketController::feedbackList');
$routes->get('new/(:any)','TicketController::ticket_form/$1');
$routes->post('create','TicketController::createTicket');
$routes->post('update','TicketController::updateTicket');
@@ -547,3 +556,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/Chatbot/EcardDownloadConversation.php b/app/Controllers/Chatbot/EcardDownloadConversation.php
index b0cb78ae..c38d6977 100644
--- a/app/Controllers/Chatbot/EcardDownloadConversation.php
+++ b/app/Controllers/Chatbot/EcardDownloadConversation.php
@@ -17,10 +17,14 @@ class EcardDownloadConversation extends Conversation
protected function showEcardMenu()
{
+ log_message('error', ('showEcardMenu function called'));
+
$chat_session_info = get_chatbot_session_info();
$policy_list = ChatbotHelper::getListOfPolicies($chat_session_info);
$buttons = [];
$question = 'Choose Policy to Download Ecard:';
+ log_message('error', ('policy_list : ' . json_encode($policy_list)));
+
if(is_array($policy_list) && count($policy_list))
{
foreach($policy_list as $policy)
diff --git a/app/Controllers/Chatbot/MainMenuConversation.php b/app/Controllers/Chatbot/MainMenuConversation.php
index 87d9a4ef..f06fd078 100644
--- a/app/Controllers/Chatbot/MainMenuConversation.php
+++ b/app/Controllers/Chatbot/MainMenuConversation.php
@@ -46,9 +46,16 @@ class MainMenuConversation extends Conversation
$this->bot->reply($message);
}
+ log_message('error', ('user_reponse before: ' . $user_reponse));
+
+
if (!$answer->isInteractiveMessageReply()) {
$user_reponse = null;
}
+
+ log_message('error', ('user_reponse is interactive: ' . $answer->isInteractiveMessageReply()));
+
+
// Get just the existing path array
$path = $this->bot->userStorage()->get('path') ?? [];
@@ -60,25 +67,35 @@ class MainMenuConversation extends Conversation
'path' => $path
]);
+ log_message('error', ('user_reponse after: ' . $user_reponse));
+
+
switch ($user_reponse) {
case "ecard_download":
$this->bot->startConversation(new EcardDownloadConversation());
+ log_message('error', 'ecard_download clicked ');
+
break;
case "network_hospital":
$this->bot->startConversation(new NetworkHospitalConversation());
+ log_message('error', 'network_hospital clicked ');
break;
case "reimbursement_claim":
$this->bot->startConversation(new ReimbursementClaimProcessConversation());
+ log_message('error', 'reimbursement_claim clicked ');
break;
case "reimbursement_status":
$this->bot->startConversation(new ReimbursementClaimStatusConversation());
+ log_message('error', 'reimbursement_status clicked ');
break;
case "new_policy":
case "renew_policy":
$this->bot->startConversation(new policyConversation());
+ log_message('error', 'renew_policy || new_policy clicked ');
break;
default:
+ log_message('error', 'default shown ');
$this->say("Invalid selection. Please choose an option.");
$this->bot->startConversation(new MainMenuConversation());
break;
diff --git a/app/Controllers/Chatbot/NetworkHospitalConversation.php b/app/Controllers/Chatbot/NetworkHospitalConversation.php
index 2e59f896..4a1e991c 100644
--- a/app/Controllers/Chatbot/NetworkHospitalConversation.php
+++ b/app/Controllers/Chatbot/NetworkHospitalConversation.php
@@ -59,7 +59,10 @@ class NetworkHospitalConversation extends Conversation
$this->bot->userStorage()->save([
'path' => $path
]);
+ log_message('error', ('user_reponse : ' . $answer->getValue()));
+
switch ($answer->getValue()) {
+
case is_string($answer->getValue()) && is_array(explode('#',$answer->getValue())) && count((explode('#',$answer->getValue()))) == 2:
$client_poilicy_id = explode('#',$answer->getValue())[1];
diff --git a/app/Controllers/Chatbot/policyConversation.php b/app/Controllers/Chatbot/policyConversation.php
index 04c8d9a5..f2fe91c1 100644
--- a/app/Controllers/Chatbot/policyConversation.php
+++ b/app/Controllers/Chatbot/policyConversation.php
@@ -46,6 +46,9 @@ class policyConversation extends Conversation
if (!$answer->isInteractiveMessageReply()) {
$user_reponse = null;
}
+
+ log_message('error', ('user_reponse : ' . $answer->getValue()));
+
$path = $this->bot->userStorage()->get('path');
array_push($path,
$answer->getValue()
diff --git a/app/Controllers/ChatbotControllerNew.php b/app/Controllers/ChatbotControllerNew.php
index 610f2bda..dc38a3c9 100644
--- a/app/Controllers/ChatbotControllerNew.php
+++ b/app/Controllers/ChatbotControllerNew.php
@@ -84,12 +84,13 @@ class ChatbotControllerNew extends BaseController
public function index()
{
+
if($this->session->get('CHATBOT_RANDOM_USER_ID') == '-' || $this->session->get('CHATBOT_RANDOM_USER_ID') == '')
{
$user = $this->botman->getUser();
$id = $user->getId();
- // $this->myLogger->logme('error', ('TEST' . $id));
+ $this->myLogger->logme('error', ('TEST' . $id));
$this->session->set('CHATBOT_RANDOM_USER_ID', $id);
}
@@ -100,6 +101,7 @@ class ChatbotControllerNew extends BaseController
}
$this->botman->hears('.*', function ($bot) {
+ log_message("error","Inside Bot Type Function");
$bot->types(); // Typing indicator for the first message
sleep(0.5); // Delay
@@ -128,14 +130,14 @@ class ChatbotControllerNew extends BaseController
$this->botman->listen();
}
- private function registerHandlers()
- {
- // Handling Policy and Claims
- $this->botman->hears('group:policy:{option}', [\App\Controllers\Chatbot\PolicyHandler::class, 'handle']);
- $this->botman->hears('group:claim:{option}', [\App\Libraries\Chatbot\ClaimHandler::class, 'handle']);
+ // private function registerHandlers()
+ // {
+ // // Handling Policy and Claims
+ // $this->botman->hears('group:policy:{option}', [\App\Controllers\Chatbot\PolicyHandler::class, 'handle']);
+ // $this->botman->hears('group:claim:{option}', [\App\Libraries\Chatbot\ClaimHandler::class, 'handle']);
- }
+ // }
public function chatbot()
{
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 c808bac5..ff19c48c 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);
@@ -1994,9 +1997,22 @@ class ClientController extends AdminController
if ($id) {
$client_policy_data = $this->clientPolicyModel->where(['id' => $id, 'is_active' => 1])->first();
+
$insurer_id = $client_policy_data['insurer_id'];
$client_id = $client_policy_data['client_id'];
+ if (!empty($client_policy_data['policy_start_date'])) {
+ $client_policy_data['source_policy_start_date'] = change_date_format($client_policy_data['policy_start_date'], 'Y-m-d', 'd/m/Y');
+ } else {
+ $client_policy_data['source_policy_start_date'] = null;
+ }
+
+ if (!empty($client_policy_data['policy_end_date'])) {
+ $client_policy_data['source_policy_end_date'] = change_date_format($client_policy_data['policy_end_date'], 'Y-m-d', 'd/m/Y');
+ } else {
+ $client_policy_data['source_policy_end_date'] = null;
+ }
+
$polices = $this->policesModel
->select('policies.*, policy_type.policy_type')
->join('policy_type', 'policy_type.id = policies.policy_type_id')
@@ -2022,7 +2038,7 @@ class ClientController extends AdminController
'policy' => $polices,
'client_policy_list' => $client_policy_list,
'end_date' => $newDate,
- 'new_start_date' => date('d/m/Y', strtotime($client_policy_data['policy_end_date']))
+ 'new_start_date' => date('d/m/Y', strtotime($client_policy_data['policy_end_date'] . ' +1 day')),
], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
@@ -4745,8 +4761,7 @@ class ClientController extends AdminController
// }
// $data = $this->leadsModel->where('leads.id', 125)->where('leads.is_active', 1)->first();
- // $RFQdata = $RFQModel->getRFQTableDataWithLeadIDAndType(125, 2);
- // // Kint::dump($RFQdata);
+ // $RFQdata = $RFQModel->getRFQTableDataWithLeadIDAndType(145, 2);
// $returnData = $LeadsController->getPlacementJson($data);
// Kint::dump($returnData);
// $policy_terms = $LeadsController->convertNonEbQCRJsonToPolicyTerms(json_decode($returnData, true));
@@ -4756,6 +4771,29 @@ class ClientController extends AdminController
// $this->clientPolicyModel->where('id', 6050)->set('policy_terms', $policy_terms)->update();
// dd($returnData);
+ // Kint::dump($RFQdata['json']);
+ // $inputJson = json_decode($RFQdata['json'], true);
+ // Kint::dump($inputJson);
+ // // print_rr($inputJson['table_data']);
+ // $sortedJson = $this->reorderProposalsByInsurerTotal($inputJson);
+
+ // // If you want to convert back to JSON string
+ // $finalJson = json_encode($sortedJson, JSON_PRETTY_PRINT);
+
+ // // $RFQModel->insert(['lead_id' => 145, 'json' => $finalJson, 'type' => 1]);
+
+ // dd($finalJson);
+
+ // $baseWhere = [
+ // 'client_id' => 159,
+ // 'client_policy_id' => 336,
+ // 'insurer_id' => 1,
+ // 'cd_ac_pk' => 56,
+ // 'event_name' => "addition",
+ // ];
+ // $return_value = check_cd_entry_exist($baseWhere);
+ // dd($return_value);
+
}
// -------------------------------------------------------------------------------------------------------
@@ -5461,6 +5499,241 @@ class ClientController extends AdminController
$id = $InsurerModel->insert($insurerData);
return $id;
}
+
+ private function reorderProposalsByInsurerTotal(array $data): array {
+
+ Kint::dump($data);
+ if (!isset($data['premium_data']['data'])) return $data;
+ $original = $data['premium_data']['data'];
+ $proposals = [];
+ $others = [];
+ $emptyKeyData = [];
+ foreach ($original as $key => $value) {
+ // Match only keys that look like 'Proposal X'
+ if (preg_match('/^Proposal\s+\d+$/', $key)) {
+ // Get the insurer entry (not 'Quote Asked')
+ foreach ($value as $subKey => $subVal) {
+ if ($subKey !== 'Quote Asked' && isset($subVal['Total'])) {
+ $proposals[$key] = $value;
+ break;
+ }else{
+ $proposals[$key] = $value;
+ }
+ }
+ } else {
+
+ if ($key === '' && isset($value['']) && is_array($value[''])) {
+ // Capture empty key to push it later
+ $emptyKeyData[$key] = $value;
+ }else{
+ $others[$key] = $value;
+
+ }
+ }
+ }
+
+ // dd($proposals, $others, $emptyKeyData);
+ // Sort proposals by their insurer's total
+ uasort($proposals, function($a, $b) {
+ $totalA = 0;
+ $totalB = 0;
+
+ foreach ($a as $key => $val) {
+ if ($key !== 'Quote Asked' && isset($val['Total'])) {
+ $totalA = floatval($val['Total']);
+ break;
+ }
+ }
+
+ foreach ($b as $key => $val) {
+ if ($key !== 'Quote Asked' && isset($val['Total'])) {
+ $totalB = floatval($val['Total']);
+ break;
+ }
+ }
+
+ return $totalA <=> $totalB;
+ });
+
+ // Merge back the sorted proposals into the full structure
+ $data['premium_data']['data'] = array_merge($others, $proposals, $emptyKeyData);
+ $data = $this->reorderProposalDataByPremiumOrder($data);
+ return $data;
+ }
+
+ private function reorderProposalDataByPremiumOrder(array $data): array {
+ if (!isset($data['premium_data']['data'], $data['proposal_data']['over_all_column_data'])) {
+ return $data;
+ }
+
+ $premiumProposals = array_keys($data['premium_data']['data']);
+ $filteredProposals = [];
+
+ // Collect proposal keys that match the pattern "Proposal X"
+ foreach ($premiumProposals as $key) {
+ if (preg_match('/^Proposal\s+\d+$/', $key) && isset($data['proposal_data']['over_all_column_data'][$key])) {
+ $filteredProposals[$key] = $data['proposal_data']['over_all_column_data'][$key];
+ }
+ }
+
+ // dd($premiumProposals, $filteredProposals);
+
+ $data['proposal_data']['over_all_column_data'] = $filteredProposals;
+ $data = $this->reorderProposalInHeaderAndData($data);
+ return $data;
+ }
+
+ private function reorderProposalInHeaderAndData(array $data): array {
+
+ // Kint::dump($data);
+ $tableData = $data['table_data'];
+ $sortedProposalOrder = $data['proposal_data']['over_all_column_data'];
+ $headers = $tableData['headers'] ?? [];
+ $dataRows = $tableData['data'] ?? [];
+
+ // Step 1: Separate static and proposal headers
+ $staticHeaders = [];
+ $proposalHeaders = [];
+ $actionHeader = [];
+ foreach ($headers as $header) {
+ if (in_array($header['parentHeader'], array_keys($sortedProposalOrder))) {
+ $proposalHeaders[$header['parentHeader']] = $header;
+ } else {
+ if($header['parentHeader'] == "Action"){
+ $actionHeader[] = $header;
+ }else{
+ $staticHeaders[] = $header;
+ }
+ }
+ }
+
+ // dd($staticHeaders, $proposalHeaders, $sortedProposalOrder);
+
+ // Step 2: Reorder headers
+ $reorderedHeaders = [];
+ foreach ($sortedProposalOrder as $proposalKey => $proposalValue) {
+ if (isset($proposalHeaders[$proposalKey])) {
+ $reorderedHeaders[] = $proposalHeaders[$proposalKey];
+ }
+ }
+
+ // print_rr($reorderedHeaders); die;
+ foreach ($reorderedHeaders as $key => &$value) {
+ $value['parentHeader'] = 'Proposal ' . ($key + 1);
+ }
+ unset($value);
+
+
+ $reorderedHeaders = array_merge($staticHeaders, $reorderedHeaders, $actionHeader);
+
+
+ // Step 3: Reorder each row's `data` by matching parentth
+ foreach ($dataRows as $dataRowIndex => &$row) {
+ $staticData = [];
+ $proposalData = [];
+ $actionData = [];
+
+ foreach ($row['data'] as $entry) {
+ if (in_array($entry['parentth'], array_keys($sortedProposalOrder))) {
+ $proposalData[$entry['parentth']][] = $entry;
+ } else {
+ if($entry['parentth'] == "Action"){
+ $actionData[] = $entry;
+ }else{
+ $staticData[] = $entry;
+ }
+ }
+ }
+
+ $reorderedProposalData = [];
+ foreach ($sortedProposalOrder as $proposalKey => $proposalValue) {
+ if (isset($proposalData[$proposalKey])) {
+ foreach ($proposalData[$proposalKey] as $entry) {
+ $reorderedProposalData[] = $entry;
+ }
+ }
+ }
+
+ $dubParTh = "";
+ $increament = 0;
+ foreach ($reorderedProposalData as $key => &$value) {
+
+ if($dubParTh == $value['parentth']){
+ $value['parentth'] = 'Proposal ' . ($increament);
+ }else{
+ $dubParTh = $value['parentth'];
+ $increament = $increament + 1;
+ $value['parentth'] = 'Proposal ' . ($increament);
+ }
+ }
+ unset($value);
+
+ $row['data'] = array_merge($staticData, $reorderedProposalData, $actionData);
+ }
+
+ $data['table_data']['headers'] = $reorderedHeaders;
+ $data['table_data']['data'] = $dataRows;
+
+ // dd('-----', $data);
+ $renumberedArray = $this->renumberProposalKeys($data['proposal_data']['over_all_column_data']);
+ $updatedDataSet = $this->renumberProposalKeys($data['premium_data']['data']);
+ $data['proposal_data']['over_all_column_data'] = !empty($renumberedArray) ? $renumberedArray : $data['proposal_data']['over_all_column_data'];
+ $data['premium_data']['data'] = !empty($updatedDataSet) ? $updatedDataSet : $data['premium_data']['data'];
+
+ return $data;
+ }
+
+ private function renumberProposalKeys(array $input): array {
+ $result = [];
+ $counter = 1;
+
+ foreach ($input as $key => $value) {
+ if (strpos($key, 'Proposal') === 0) {
+ $newKey = 'Proposal ' . $counter++;
+ $result[$newKey] = $value;
+ } else {
+ $result[$key] = $value;
+ }
+ }
+
+ 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/Controllers/DashboardController.php b/app/Controllers/DashboardController.php
index f4eb8d34..78d1b86e 100755
--- a/app/Controllers/DashboardController.php
+++ b/app/Controllers/DashboardController.php
@@ -21,6 +21,10 @@ use App\Models\NotificationModel;
use App\Models\EmployeePolicyModel;
use App\Controllers\PendingActionsContrller;
use App\Controllers\EmpDataServiceController;
+use App\Models\TicketMasterModel;
+use App\Models\LeadsModel;
+use App\Models\TicketClaimStatusModel;
+
class DashboardController extends AdminController
{
@@ -33,8 +37,12 @@ class DashboardController extends AdminController
protected $notificationModel;
protected $employeePolicyModel;
protected $policyTransactionModel;
+ protected $leadModel;
+ protected $ticketModel;
+ protected $ticketStatusModel;
protected $policyStatus;
protected $colorShades;
+ protected $claimDashLimit;
protected $myLogger;
@@ -48,9 +56,76 @@ class DashboardController extends AdminController
$this->employeePolicyModel = new EmployeePolicyModel();
$this->clientModel = new ClientModel();
$this->policyTransactionModel = new PolicyTransactionModel();
+ $this->ticketModel = new TicketMasterModel();
+ $this->leadModel = new LeadsModel();
+ $this->ticketStatusModel = new TicketClaimStatusModel();
$this->myLogger = \Config\Services::mylogger();
+ $this->claimDashLimit = [
+ 1 => [
+ 'non_id' => 3,
+ 'id_not_generated' => 3,
+ 'cda' => 3,
+ 'information_required' => 3,
+ 'under_process' => 3,
+ 'rejected' => 3,
+ 'approved' => 3,
+ 'payment_initiated' => 3,
+ 'settled' => 3,
+ 'closed' => 3,
+ 'cancelled' => 3,
+ 'returned' => 3
+ ],
+
+ 2 => [
+ 'claim_intimation' => 3,
+ 'intimation_to_insurer' => 3,
+ 'client_pending' => 3,
+ 'insurer_pending' => 3,
+ 'investigation' => 3,
+ 'approved' => 3,
+ 'closed' => 3,
+ 'not_covered' => 3,
+ 'settled' => 3,
+ 'coverage_check' => 3,
+ 'cancelled' => 3,
+ 'returned' => 3,
+ 'rejected' => 3,
+ 'dv_sent_to_insured' => 3
+ ],
+ 3 => [
+ 'claim_intimation' => 3,
+ 'intimation_to_insurer' => 3,
+ 'client_pending' => 3,
+ 'insurer_pending' => 3,
+ 'investigation' => 3,
+ 'approved' => 3,
+ 'closed' => 3,
+ 'not_covered' => 3,
+ 'settled' => 3,
+ 'coverage_check' => 3,
+ 'cancelled' => 3,
+ 'returned' => 3,
+ 'rejected' => 3
+ ],
+ 4 => [
+ 'claim_intimation' => 3,
+ 'intimation_to_insurer' => 3,
+ 'client_pending' => 3,
+ 'insurer_pending' => 3,
+ 'investigation' => 3,
+ 'approved' => 3,
+ 'closed' => 3,
+ 'not_covered' => 3,
+ 'settled' => 3,
+ 'coverage_check' => 3,
+ 'cancelled' => 3,
+ 'returned' => 3,
+ 'rejected' => 3
+ ]
+ ];
+
$this->policyStatus = [
'under_process' => 'Under Process',
'client_pending' => 'Client Pending',
@@ -92,7 +167,6 @@ class DashboardController extends AdminController
'linear-gradient(45deg, #494f4f, #353d3d)' // SilverChalice shade 6
]
];
-
}
public function dashboard()
@@ -100,8 +174,8 @@ class DashboardController extends AdminController
$data = [];
- if (in_array(get_role_id(), [1,2,3,5]) || (in_array(MANAGEMENT_TEAM_ID, user_team()) || in_array(FINANCE_TEAM_ID, user_team()) || in_array(BUSINESS_TEAM_ID, user_team()))) {
-
+ if (in_array(get_role_id(), [1, 2, 3, 5]) || (in_array(MANAGEMENT_TEAM_ID, user_team()) || in_array(FINANCE_TEAM_ID, user_team()) || in_array(BUSINESS_TEAM_ID, user_team()))) {
+
$db = db_connect();
$sql = "SELECT
clients.id AS client_id,
@@ -169,17 +243,65 @@ class DashboardController extends AdminController
$data['financeTeamStatusData'] = $financeTeamStatusData;
$data['policyStatus'] = $this->policyStatus;
$data['colorShades'] = $this->colorShades;
- // print_r($data);die;
-
}
+ $data['claim_data'] = $this->getClaimData();
+ $data['lead_data'] = $this->getLeadData();
+
$data['page_name'] = 'Dashboard';
echo view('layout/header', $data);
echo view('DashBoard', $data);
echo view('layout/footer');
}
-
+
+ public function getLeadData(){
+
+ }
+
+ public function getClaimData()
+ {
+
+ $results = $this->ticketStatusModel
+ ->select("ticket_type as ticket_type_id, claim_status")
+ ->where("is_active", 1)
+ ->findAll();
+
+ $claim_status = [];
+
+ foreach ($results as $row) {
+ if (empty($row['ticket_type_id']) || empty($row['claim_status'])) {
+ continue; // Skip if either value is empty
+ }
+ $typeId = $row['ticket_type_id'];
+ $status = $row['claim_status'];
+
+ // Initialize if not set
+ if (!isset($claim_status[$typeId])) {
+ $claim_status[$typeId] = [];
+ }
+
+ // Use associative array keys to mimic a set
+ $claim_status[$typeId][$status] = true;
+ }
+
+ // Convert set-like structure to plain array
+ foreach ($claim_status as $typeId => $statuses) {
+ $claim_status[$typeId] = array_keys($statuses);
+ }
+ $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;
+
+ }
+
public function getDashboardNotifications()
{
@@ -212,29 +334,29 @@ class DashboardController extends AdminController
{
$clientPolicyModel = new ClientPolicyModel();
$myLogger = \Config\Services::mylogger();
-
+
$client_policy_data = $clientPolicyModel->getPolicyDetailsForEnrollment();
$myLogger->logme('error', 'Fetched client policy data for Enrollment Status update');
-
+
// dd($client_policy_data);
$currentDate = date('d-m-Y');
$openEnrollment = [];
$closeEnrollment = [];
-
+
// Update policy status based on start and end dates
foreach ($client_policy_data as $client_policy) {
$id = $client_policy['id'];
$openDate = date('d-m-Y', strtotime($client_policy['open_date']));
$closeDate = date('d-m-Y', strtotime($client_policy['close_date']));
-
+
if ($currentDate == $openDate) {
$clientPolicyModel->update($id, ['open_for_enrollment' => 1]);
$openEnrollment[] = $id;
$myLogger->logme('error', 'Updated policy ID ' . $id . ' to open for enrollment.');
}
-
+
if ($closeDate < $currentDate) {
$clientPolicyModel->update($id, ['open_for_enrollment' => 0]);
$closeEnrollment[] = $id;
@@ -243,37 +365,36 @@ class DashboardController extends AdminController
}
$myLogger->logme('error', 'enrollment_status function completed');
- $myLogger->logme('error', 'updated Open Enrollment Policy count : "'.count($openEnrollment).'" and Close Enrollment Policy count : "'.count($closeEnrollment).'"');
+ $myLogger->logme('error', 'updated Open Enrollment Policy count : "' . count($openEnrollment) . '" and Close Enrollment Policy count : "' . count($closeEnrollment) . '"');
return $this->respond([
- 'status' => true,
- 'message' => 'updated Open and Close Enrollment successfully',
- 'open_policy_count' => count($openEnrollment),
+ 'status' => true,
+ 'message' => 'updated Open and Close Enrollment successfully',
+ 'open_policy_count' => count($openEnrollment),
'close_policy_count' => count($closeEnrollment),
- 'open_policy_ids' => $openEnrollment,
+ 'open_policy_ids' => $openEnrollment,
'close_policy_ids' => $closeEnrollment,
]);
-
}
-
+
public function sendCroneRemainderMail()
{
$clientPolicyModel = new ClientPolicyModel();
$myLogger = \Config\Services::mylogger();
-
-
+
+
$client_policy_data = $clientPolicyModel->getPolicyDetailsForRemainder();
$myLogger->logme('error', 'Fetched client policy data');
// dd($client_policy_data);
-
+
// Mail send function
$result = $this->sendRemainderMail($client_policy_data, 'crone');
$myLogger->logme('error', 'sendCroneRemainderMail function completed');
-
- if($result){
+
+ if ($result) {
return json_encode(['status' => true, 'message' => 'Mail send successfully']);
- }else{
+ } else {
return json_encode(['status' => false, 'message' => 'There is no data to send']);
}
}
@@ -285,29 +406,22 @@ class DashboardController extends AdminController
$data = [];
- if($type == 'insurer'){
+ if ($type == 'insurer') {
$data = $pendingActionsData['uhid'];
-
- }else if($type == 'TPA'){
+ } else if ($type == 'TPA') {
$data = $pendingActionsData['tpa'];
-
- }else if($type == 'I'){
+ } else if ($type == 'I') {
$data = $pendingActionsData['inception'];
-
- }else if($type == 'D'){
+ } else if ($type == 'D') {
$data = $pendingActionsData['deletion'];
-
- }else if($type == 'C'){
+ } else if ($type == 'C') {
$data = $pendingActionsData['correction'];
-
- }else if($type == 'SI'){
+ } else if ($type == 'SI') {
$data = $pendingActionsData['si_enhancement'];
-
- }else if($type == 'policy'){
+ } else if ($type == 'policy') {
$data = $pendingActionsData['policy'];
-
- }else if($type == 'ticket'){
+ } else if ($type == 'ticket') {
$data = $pendingActionsData['uhid'];
}
@@ -421,7 +535,6 @@ class DashboardController extends AdminController
$reminder_whole_mail[] = $mail_result;
}
}
-
} else { // crone
if (!empty($client_policy['reminder_date'])) {
@@ -511,15 +624,12 @@ class DashboardController extends AdminController
// $this->myLogger->logme('error', 'Mail sent result: ' . json_encode($mail_result));
$reminder_whole_mail[] = $mail_result;
}
-
}
}
-
} else {
$this->myLogger->logme('error', "SEND REMAINDER CRONE --- Remainder date is empty()");
}
}
-
} else {
$this->myLogger->logme('error', 'Notification setup not found or not enabled');
@@ -549,29 +659,28 @@ class DashboardController extends AdminController
public function sendManualReminder($client_id, $client_branch_id, $client_policy_id = null)
{
- $this->myLogger->logme('error','Log Works');
+ $this->myLogger->logme('error', 'Log Works');
$this->myLogger->logme('error', "sendManualRemainder called with client_id: {$client_id}, client_branch_id: {$client_branch_id}");
-
+
$client_policy_data = $this->clientPolicyModel->getPolicyDetailsForRemainder($client_id, $client_branch_id, $client_policy_id);
// print_r($client_policy_data); die;
// print_r($this->clientPolicyModel->getLastQuery()); die;
// $this->myLogger->logme('error', "Policy details fetched: " . json_encode($client_policy_data));
-
+
if ($client_policy_data) {
$result = $this->sendRemainderMail($client_policy_data);
- log_message('error',json_encode($result));
- $this->myLogger->logme('error',$result);
+ log_message('error', json_encode($result));
+ $this->myLogger->logme('error', $result);
$this->myLogger->logme('error', "Manual Remainder Mail sending result: " . ($result ? 'success' : 'failure'));
-
+
if ($result) {
$this->myLogger->logme('error', 'Manual Remainder Mail sent successfully');
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Mail sent successfully'], 200);
} else {
$this->myLogger->logme('error', 'Failed to send manual remainder mail, no data to send');
- return $this->respond(['status' => false, 'code' => 200, 'message' => 'There is no data to send','message2' => 'Failed' ], 200);
+ return $this->respond(['status' => false, 'code' => 200, 'message' => 'There is no data to send', 'message2' => 'Failed'], 200);
}
-
} else {
$this->myLogger->logme('error', 'No policy data found to send');
return $this->respond(['status' => false, 'code' => 200, 'message' => 'There is no data to send', 'message2' => 'No policy data found to send'], 200);
@@ -581,19 +690,17 @@ class DashboardController extends AdminController
public function sendManualEcard($client_id, $client_branch_id, $policy_id)
{
$this->myLogger->logme('error', "sendManualEcard called with client_id: {$client_id}, client_branch_id: {$client_branch_id}, policy id : {$policy_id}");
-
- $notification = $this->notificationModel->where('client_id', $client_id)->where('template_name', 'member_ecard_mail')->first();
- // print_r(($notification)); die;
- if($notification && $notification['enabled'] == 0 && $notification['mail_content'] == '')
- {
- return $this->respond(['status' => false, 'code' => 400, 'message' => 'No template found','message2' => 'Failed' ], 200);
- }
-
+
+ $notification = $this->notificationModel->where('client_id', $client_id)->where('template_name', 'member_ecard_mail')->first();
+ // print_r(($notification)); die;
+ if ($notification && $notification['enabled'] == 0 && $notification['mail_content'] == '') {
+ return $this->respond(['status' => false, 'code' => 400, 'message' => 'No template found', 'message2' => 'Failed'], 200);
+ }
+
$emp_data = $this->employeePolicyModel->getEmployeePolicyForEcard($policy_id);
- if(count($emp_data) == 0)
- {
- return $this->respond(['status' => false, 'code' => 400, 'message' => 'No employees found','message2' => 'Failed' ], 200);
+ if (count($emp_data) == 0) {
+ return $this->respond(['status' => false, 'code' => 400, 'message' => 'No employees found', 'message2' => 'Failed'], 200);
}
$ids = array_column($emp_data, 'id');
// print_r(($ids)); die;
@@ -603,9 +710,8 @@ class DashboardController extends AdminController
// $empEmpDataServiceController = new EmpDataServiceController();
// $empEmpDataServiceController->sendMailForDownloadingECard($ids);
-
+
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Mail Queued'], 200);
-
}
public function data_construct_for_bds($data)
@@ -622,7 +728,7 @@ class DashboardController extends AdminController
'instalment_pending' => [],
'completed' => [],
];
-
+
// Loop through results and group them by their status
foreach ($data as $row) {
switch ($row['status']) {
@@ -655,8 +761,25 @@ class DashboardController extends AdminController
break;
}
}
-
+
return $groupedData;
}
+ public function prepareClaimSearchData(){
+
+ $received_data = $this->request->getPost();
+ $ticketTypeId = $received_data['ticketTypeId'];
+ $status = $received_data['status'];
+
+ $status = strtoupper($status);
+ $status = str_replace('_', ' ', $status);
+
+ $data = $this->ticketModel
+ ->select("tcs.id as claim_status_id")
+ ->join("ticket_claim_status tcs", "tcs.ticket_type = " . (int)$ticketTypeId)
+ ->where("tcs.claim_status", $status)
+ ->first();
+ $data['ticket_type_id'] = $ticketTypeId;
+ return $this->respond(['status' => "success","data" => $data],200);
+ }
}
diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php
index 76d44b73..c7f9d689 100755
--- a/app/Controllers/EmpDataServiceController.php
+++ b/app/Controllers/EmpDataServiceController.php
@@ -4105,6 +4105,9 @@ class EmpDataServiceController extends BaseController
AND emp_endorsement.pk IN (" . implode(',', $arrayData['employeeIds']) . ")
AND employee_polices.claim_status = 0
AND emp_endorsement.field_name = 'date_of_exit'
+ AND emp_endorsement.is_active = 1
+ AND emp_endorsement.actions = 'd'
+ AND emp_endorsement.status != 'truncated';
")->getRow();
// dd(db_connect()->getLastQuery(), $amount);
diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php
index 2d7bf436..9b137fda 100755
--- a/app/Controllers/EmployeeRestController.php
+++ b/app/Controllers/EmployeeRestController.php
@@ -3112,6 +3112,8 @@ class EmployeeRestController extends AdminController
}
+ // ---------------- TICKET API's ---------------------------------------------------------------------------------------------------
+
//Get Data from post for inserting ticket and message
public function initiateClaim()
{
@@ -3122,6 +3124,18 @@ class EmployeeRestController extends AdminController
$client_policy_id = $received_data['client_policy_id'];
$insured_emp_id = $received_data['insured_emp_id'];
+ if (empty($received_data['doa'])) {
+ $received_data['doa'] = null;
+ } else{
+ $ticket_data['doa'] = change_date_format($received_data['doa']);
+ }
+
+ if (empty($received_data['dod'])) {
+ $received_data['dod'] = null;
+ } else{
+ $ticket_data['dod'] = change_date_format($received_data['dod']);
+ }
+
$sql = "
select
cp.policy_type_id,
@@ -3164,29 +3178,42 @@ class EmployeeRestController extends AdminController
if(!empty($emp_ticket_data)){
$fetchData = $emp_ticket_data[0];
- $fetchData['claim_status_id'] = $this->claimStatusModel
- ->select('id')
- ->where('ticket_type', $fetchData['ticket_type_id'])
- ->orderBy('id', 'asc')
- ->first()['id'];
+
+ $claimStatusQuery = $this->claimStatusModel
+ ->select('id')
+ ->where('ticket_type', $fetchData['ticket_type_id'])
+ ->orderBy('id', 'asc');
+
+ if ($fetchData['ticket_type_id'] == 1 && !empty($fetchData['tpa_no'])) {
+ $results = $claimStatusQuery->findAll(2);
+ $fetchData['claim_status_id'] = $results[1]['id'] ?? $results[0]['id'];
+ } else {
+ $fetchData['claim_status_id'] = $claimStatusQuery->first()['id'];
+ }
+
$fetchData['priority'] = 1;
- $fetchData['mode_of_intimation'] = 1;
+ $fetchData['mode_of_intimation'] = 3;
+ $fetchData['claim_type'] = 1;
$fetchData = array_merge($fetchData, $received_data);
+ $fetchData['relationship'] = strtolower($fetchData['relationship']) ?? $fetchData['relationship'];
// print_r($fetchData); die;
$insert_status = $this->ticketMaster->insert($fetchData);
$ticket_id = $this->ticketMaster->insertID();
if ($insert_status && !empty($ticket_id)) {
+ //insert first history
+ $this->ticketController->putHistoryAfterInsert($fetchData, $ticket_id);
+
$messagesData = [
'ticket_id' => $ticket_id ?? null,
'sender' => 'user',
'claim_status' => $fetchData['claim_status_id'] ?? null,
'emp_mail' => $fetchData['emp_mail'] ?? null,
- 'mail_subject' => $fetchData['subject'] ?? null,
- 'mail_content' => $fetchData['message'] ?? null,
+ 'mail_subject' => $fetchData['subject'] ?? "New Claim",
+ 'mail_content' => $fetchData['message'] ?? "New Claim",
];
if (!empty($messagesData['ticket_id'])) {
diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php
index 1c5e9f80..617add8f 100644
--- a/app/Controllers/LeadsController.php
+++ b/app/Controllers/LeadsController.php
@@ -29,6 +29,7 @@ use App\Models\TPABranchModel;
use App\Models\RFQModel;
use App\Models\InsurerModel;
use App\Models\OccupancyMasterModel;
+use App\Models\LeadFilesModel;
use App\Helpers\MailHelper;
use App\Helpers\ExcelMergeHelper;
@@ -39,6 +40,7 @@ use Kint\Kint;
use App\Controllers\Jobs;
use App\Controllers\JobWorker;
use Google\Service\FactCheckTools\Resource\Claims;
+use GPBMetadata\Google\Type\Datetime;
class LeadsController extends BaseController
{
@@ -62,6 +64,7 @@ class LeadsController extends BaseController
protected $RFQModel;
protected $insurerModel;
protected $occupancyModel;
+ protected $leadFilesModel;
//variables for storing array
protected $issuer;
@@ -92,13 +95,14 @@ class LeadsController extends BaseController
$this->RFQModel = new RFQModel();
$this->insurerModel = new InsurerModel();
$this->occupancyModel = new OccupancyMasterModel();
+ $this->leadFilesModel = new LeadFilesModel();
$this->issuer = [1 => 'JIBS', 2 => 'Nhance'];
$this->clientType = [1 => 'Group', 2 => 'Individual'];
$this->leadType = [1 => 'Fresh', 2 => 'Renewal', 3 => 'Roll Over'];
$this->buisnessType = [1 => 'Industrial', 2 => 'Non Industrial'];
$this->leadsStatus = [
- 'queued' => 'Queued',
+ 'queued' => 'In-Queued',
'qcr_sent' => 'QCR sent',
'lost' => 'Lost',
'co_insurer_pending' => 'Co-Insurer Pending',
@@ -199,6 +203,7 @@ class LeadsController extends BaseController
} else {
$data = $this->prepareMultipleLeadData($data);
}
+
// print_r($data); die;
return $data;
}
@@ -206,13 +211,12 @@ class LeadsController extends BaseController
private function prepareSingleLeadData($data)
{
// print_r($data); die;
- $uploadFilePath = WRITEPATH . 'uploads/lead_files/';
-
- // Get all uploaded files for 'file_name[]'
- $files = $this->request->getFileMultiple('file_name');
-
- // print_r($files); die;
-
+ $index_plus_one = 1;
+ $form_file_name = "file_name_" . $index_plus_one;
+ $form_docs_name = "docs_name_" . $index_plus_one;
+ $leads_file_primary_key = $data['leads_file_id'] ?? [];
+ $files = $this->request->getFileMultiple($form_file_name);
+ $multi_file_data = $this->uploadMultiFiles($files, $data[$form_docs_name], $leads_file_primary_key);
// Separate the insurer and insurer branch, handle missing or invalid data
if (isset($data['insurer']) && strpos($data['insurer'], '-') !== false) {
@@ -249,7 +253,9 @@ class LeadsController extends BaseController
$data['policy_end_date'] = null;
}
- $data['file_name'] = file_Upload($files, $uploadFilePath);
+ // $data['file_name'] = file_Upload($files, $uploadFilePath);
+ $data['multi_file_data'] = $multi_file_data ?? null;
+
$processcedData[] = $data;
// print_r($data);die();
@@ -260,15 +266,16 @@ class LeadsController extends BaseController
{
// print_r($data); die;
$processedData = [];
- $uploadFilePath = WRITEPATH . 'uploads/lead_files/';
-
- // Get all uploaded files for 'file_name[]'
- $files = $this->request->getFileMultiple('file_name');
-
- // print_r($files); die;
foreach ($data['policy_type_id'] as $index => $value) {
+ $index_plus_one = $index + 1;
+ $form_file_name = "file_name_" . $index_plus_one;
+ $form_docs_name = "docs_name_" . $index_plus_one;
+ $leads_file_primary_key = $data['leads_file_id'] ?? [];
+ $files = $this->request->getFileMultiple($form_file_name);
+ $multi_file_data = $this->uploadMultiFiles($files, $data[$form_docs_name], $leads_file_primary_key);
+
// Separate the insurer and insurer branch, handle missing or invalid data
if (isset($data['insurer'][$index]) && strpos($data['insurer'][$index], '-') !== false) {
list($insurer_branch_id, $insurer_id) = explode('-', $data['insurer'][$index]);
@@ -318,13 +325,25 @@ class LeadsController extends BaseController
$incurred_claims_date = null;
}
- if (!empty($data['premium_date'][$index])) {
- $premium_date = change_date_format($data['premium_date'][$index], 'd/m/Y', 'Y-m-d');
+ // if (!empty($data['premium_date'][$index])) {
+ // $premium_date = change_date_format($data['premium_date'][$index], 'd/m/Y', 'Y-m-d');
+ // } else {
+ // $premium_date = null;
+ // }
+
+ if (!empty($data['source_policy_start_date'])) {
+ $data['source_policy_start_date'] = change_date_format($data['source_policy_start_date'], 'd/m/Y', 'Y-m-d');
} else {
- $premium_date = null;
+ $data['source_policy_start_date'] = null;
}
- $file_name = file_Upload($files[$index], $uploadFilePath);
+ if (!empty($data['source_policy_end_date'])) {
+ $data['source_policy_end_date'] = change_date_format($data['source_policy_end_date'], 'd/m/Y', 'Y-m-d');
+ } else {
+ $data['source_policy_end_date'] = null;
+ }
+
+ // $file_name = file_Upload($files[$index], $uploadFilePath);
$last_3_years_claims = $data['finyear'];
@@ -378,7 +397,7 @@ class LeadsController extends BaseController
'outstanding_claims' => $data['outstanding_claims'][$index] ?? 0,
'policy_run_days' => $data['policy_run_days'][$index] ?? 0,
'premium_at_inception' => $data['premium_at_inception'][$index] ?? 0,
- 'premium_date' => $premium_date,
+ 'premium_date' => $data['premium_date'][$index] ?? 0,
'earned_premium' => $data['earned_premium'][$index] ?? 0,
'annualised_claims' => $data['annualised_claims'][$index] ?? 0,
'incurred_claims_ratio' => $data['incurred_claims_ratio'][$index] ?? 0,
@@ -387,13 +406,17 @@ class LeadsController extends BaseController
'total_si_at_renewal' => $data['total_si_at_renewal'][$index] ?? 0,
'fin_years_claims' => $last_3_years_claims,
- 'file_name' => $file_name,
+ // 'file_name' => $file_name,
+ 'multi_file_data' => $multi_file_data ?? null,
'status' => $data['status'] ?? null,
'notes' => $data['notes'] ?? null,
'lead_form_type' => $data['lead_form_type'] ?? 1,
'custom_fields' => $data['custom_fields'] ?? null,
+
+ 'source_policy_start_date' => $data['source_policy_start_date'] ?? null,
+ 'source_policy_end_date' => $data['source_policy_end_date'] ?? null,
];
}
// print_r($processedData);die();
@@ -405,6 +428,11 @@ class LeadsController extends BaseController
$insertCount = [];
foreach ($data as $value) {
$insert = $this->leadsModel->insert($value);
+
+ if ($insert) {
+ $this->insertMultiFilesData($value['multi_file_data'], $insert);
+ }
+
$insertCount[] = $insert;
$this->insertLeadStatus($insert, $value['status'], 3);
@@ -427,13 +455,15 @@ class LeadsController extends BaseController
private function updateOldLead($id, $data)
{
if ($this->leadsModel->where('id', $id)->set($data[0])->update()) {
+
+ $this->insertMultiFilesData($data[0]['multi_file_data'], $id);
$this->insertLeadStatus($id, $data[0]['status'], 3);
return $this->respond(['status' => true, 'lead_id' => $id, 'message' => "Lead updated successfully", 'data' => $data], 200);
}
return $this->respond(['status' => false, 'lead_id' => $id, 'message' => "Failed to update Lead", 'data' => $data], 200);
}
- // Get the Single Lead data for edit
+ // Get the Single Lead data for edit uisng ajax ( do not delete)
public function getLeadDataForEdit($id)
{
@@ -466,11 +496,13 @@ class LeadsController extends BaseController
$data['incurred_claims_date'] = null;
}
- if (!empty($data['premium_date'])) {
- $data['premium_date'] = change_date_format($data['premium_date'], 'Y-m-d', 'd/m/Y');
- } else {
- $data['premium_date'] = null;
- }
+ // if (!empty($data['premium_date'])) {
+ // $data['premium_date'] = change_date_format($data['premium_date'], 'Y-m-d', 'd/m/Y');
+ // } else {
+ // $data['premium_date'] = null;
+ // }
+
+ $data['multi_file_data'] = $this->leadFilesModel->where('lead_id', $id)->first() ?? null;
$data['lastFiveYears'] = $this->getLastFiveFinancialYears();
$data['gpaClaimType'] = $this->claim_type_for_gpa;
@@ -485,6 +517,8 @@ class LeadsController extends BaseController
$data['html'] = $this->generateViewPageHtml($data['policy_type_id'], $data) ?? "";
+ // print_r($data); die;
+
if ($data) {
return $this->respond(['status' => true, 'data' => $data], 200);
} else {
@@ -503,8 +537,72 @@ class LeadsController extends BaseController
$this->policyTransactionStatusModel->insert($statusData);
}
+ public function uploadMultiFiles($files, $docs_names, $primaryKey)
+ {
+ $uploadFilePath = WRITEPATH . 'uploads/lead_files/';
- //--------RFQ-----------------------------------------------------------------------------------------------
+ $multi_file_data = [];
+ foreach ($files as $index => $value) {
+ $file_name = file_Upload($value, $uploadFilePath);
+ $multi_file_data[] = [
+ 'file_name' => $file_name,
+ 'docs_name' => $docs_names[$index],
+ 'id' => $primaryKey[$index] ?? "",
+ ];
+ }
+
+ return $multi_file_data;
+ }
+
+ public function insertMultiFilesData($data, $lead_id)
+ {
+ // print_r($data); die;
+
+ if (!empty($data)) {
+ foreach ($data as $key => $value) {
+
+ if (!empty($value['id'])) {
+
+ $lead_file_data = [
+ 'lead_id' => $lead_id,
+ 'docs_name' => $value['docs_name'],
+ ];
+
+ if (!empty($value['file_name'])) {
+ $lead_file_data['file_name'] = $value['file_name'];
+ }
+
+ $this->leadFilesModel->where('id', $value['id'])->set($lead_file_data)->update();
+ } else {
+
+ $lead_file_data = [
+ 'lead_id' => $lead_id,
+ 'docs_name' => $value['docs_name'],
+ 'file_name' => $value['file_name'],
+ ];
+ $this->leadFilesModel->insert($lead_file_data);
+ }
+
+ if ($key == 0 && !empty($value['file_name'])) {
+ $this->leadsModel->where('id', $lead_id)->set('file_name', $value['file_name'])->update();
+ }
+ }
+ }
+
+ return true;
+ }
+
+ public function removeMultiFile()
+ {
+ $id = $this->request->getGet('lead_file_id');
+ if (!empty($id)) {
+ $this->leadFilesModel->where('id', $id)->set(['is_active' => 0])->update();
+ return $this->respond(['status' => true, 'message' => 'File removed successfully'], 200);
+ } else {
+ return $this->respond(['status' => false, 'message' => 'File could not be removed.'], 200);
+ }
+ }
+ //--------RFQ-----------------------------------------------------------------------------------------------
public function viewRFQ($id, $type = 1)
@@ -558,6 +656,7 @@ class LeadsController extends BaseController
$data['page_name'] = $type == 2 ? 'QCR' : 'RFQ';
$data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
$data['userList'] = $this->userModel->getUserListForRFQ();
+ $data['exclusiveUserList'] = $this->userModel->getexclusiveUserListForRFQ();
$data['lead_data'] = $lead_data;
$mail_content = "
@@ -566,17 +665,34 @@ class LeadsController extends BaseController
Please find attached the {{RFQ_OR_QCR}} for {{POLICY_TYPE}} policy pertaining to {{CLIENT_NAME}} .
Kindly request you to share the competitive quotes at the earliest.
In case of any query, please feel free to contact us.
- Thank You!
+ Thank You!
+ Best regards,
+
+
+
{{LOGGED_USER_NAME}}
+
Email: {{LOGGED_USER_EMAIL}}
+
Mobile: {{LOGGED_USER_MOBILE}}
+
+
+
+
";
+ if ($data['lead_data']['policy_end_date'] != null){
+ $subject = "{{CLIENT_NAME}} _ {{POLICY_TYPE}} _ {{RFQ_OR_QCR}} _ {{POLICY_YEAR}} {{POLICY_END_DATE}}";
+ }else{
+ $subject = "{{CLIENT_NAME}} _ {{POLICY_TYPE}} _ {{RFQ_OR_QCR}} _ {{POLICY_YEAR}}";
- $subject = "{{CLIENT_NAME}} _ {{POLICY_TYPE}} _ {{RFQ_OR_QCR}} _ {{POLICY_YEAR}}";
+ }
$data['mail_content'] = $this->transformMailContent($lead_data, $mail_content, $data['page_name']);
$data['subject'] = $this->transformMailContent($lead_data, $subject, $data['page_name']);
+ $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'];
+ // dd($data);
-
if ($data['lead_data']['lead_form_type'] == 1) {
$this->loadLayout('view_rfq.php', $data);
@@ -585,14 +701,14 @@ class LeadsController extends BaseController
$data['occupancy'] = $this->occupancyModel->findAll();
// dd($data['occupancy']);
- if($lead_data['lead_type'] != 1 && $data['rfq_count'] == 0){
+ if ($lead_data['lead_type'] != 1 && $data['rfq_count'] == 0) {
$client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $lead_data['source_policy_id'])->first();
$data['rfq_data']['json'] = $client_policy_data['placement_json'];
}
- if(!empty($data['question_json'])){
+ if (!empty($data['question_json'])) {
$data['policies'] = json_decode($data['question_json'], true)['policies'];
- $data["child_table_data"] = json_decode($data['question_json'], true)['child_table_data'];
+ $data["child_table_data"] = json_decode($data['question_json'], true)['child_table_data'];
}
// $data['lead_register_data'] = json_decode($data['lead_data']['custom_fields']);
@@ -635,7 +751,6 @@ class LeadsController extends BaseController
}
}
-
public function createRFQ()
{
$data = $this->request->getPost();
@@ -645,15 +760,24 @@ class LeadsController extends BaseController
return $this->respond(['status' => false, 'message' => 'Lead ID is required'], 400);
}
+ $inputJson = json_decode($data['json'], true);
+ if (isset($inputJson['premium_data']) && !empty($inputJson['premium_data'])) {
+ $sortedJson = $this->reorderProposalsByInsurerTotal($inputJson);
+ $data['json'] = json_encode($sortedJson);
+ }
+
+
$data['type'] = 1;
// Deactivate existing RFQs for this lead and type
- $this->RFQModel
- ->where('lead_id', $lead_id)
- ->where('type', 1)
- ->where('is_active', 1)
- ->set('is_active', 0)
- ->update();
+ if (!isset($data['rfq_primaryKey']) && empty($data['rfq_primaryKey'])) {
+ $this->RFQModel
+ ->where('lead_id', $lead_id)
+ ->where('type', 1)
+ ->where('is_active', 1)
+ ->set('is_active', 0)
+ ->update();
+ }
// Handle registration_json
if (empty($data['registration_json'])) {
@@ -669,20 +793,29 @@ class LeadsController extends BaseController
}
}
- // Insert new RFQ
- $insertId = $this->RFQModel->insert($data);
+ // print_r($data); die;
+ // $data['json'] = "";
+ if (isset($data['rfq_primaryKey']) && !empty($data['rfq_primaryKey'])) {
+ $this->RFQModel->update($data['rfq_primaryKey'], $data);
+ $insertId = $data['rfq_primaryKey'];
+ $affectedRows = db_connect()->affectedRows();
+ } else {
+ // Insert new RFQ
+ $insertId = $this->RFQModel->insert($data);
+ }
if ($insertId) {
- $message = ($data['submit_type'] ?? '') == 'QCR' ? 'QCR submitted successfully' : 'RFQ submitted successfully';
+ $message = ($data['submit_type'] ?? '') == 'QCR' ? 'QCR saved successfully' : 'RFQ saved successfully';
return $this->respond([
'status' => true,
'id' => $insertId,
'message' => $message,
- 'data' => $data
+ 'data' => $data,
+ 'affectedRows' => $affectedRows ?? null,
], 200);
}
- $message = ($data['submit_type'] ?? '') == 'QCR' ? 'Failed to create QCR' : 'Failed to create RFQ';
+ $message = ($data['submit_type'] ?? '') == 'QCR' ? 'Failed to save QCR' : 'Failed to save RFQ';
return $this->respond([
'status' => false,
'id' => null,
@@ -691,7 +824,6 @@ class LeadsController extends BaseController
], 200);
}
-
public function createQCR()
{
@@ -716,6 +848,206 @@ class LeadsController extends BaseController
}
+ private function reorderProposalsByInsurerTotal(array $data): array
+ {
+
+ if (!isset($data['premium_data']['data'])) return $data;
+
+ $original = $data['premium_data']['data'];
+ $proposals = [];
+ $others = [];
+ $emptyKeyData = [];
+
+ foreach ($original as $key => $value) {
+ // Match only keys that look like 'Proposal X'
+ if (preg_match('/^Proposal\s+\d+$/', $key)) {
+ // Get the insurer entry (not 'Quote Asked')
+ foreach ($value as $subKey => $subVal) {
+ if ($subKey !== 'Quote Asked' && isset($subVal['Total'])) {
+ $proposals[$key] = $value;
+ break;
+ }else{
+ $proposals[$key] = $value;
+ }
+ }
+ } else {
+
+ if ($key === '' && isset($value['']) && is_array($value[''])) {
+ // Capture empty key to push it later
+ $emptyKeyData[$key] = $value;
+ } else {
+ $others[$key] = $value;
+ }
+ }
+ }
+
+ // Sort proposals by their insurer's total
+ uasort($proposals, function ($a, $b) {
+ $totalA = 0;
+ $totalB = 0;
+
+ foreach ($a as $key => $val) {
+ if ($key !== 'Quote Asked' && isset($val['Total'])) {
+ $totalA = floatval($val['Total']);
+ break;
+ }
+ }
+
+ foreach ($b as $key => $val) {
+ if ($key !== 'Quote Asked' && isset($val['Total'])) {
+ $totalB = floatval($val['Total']);
+ break;
+ }
+ }
+
+ return $totalA <=> $totalB;
+ });
+
+ // Merge back the sorted proposals into the full structure
+ $data['premium_data']['data'] = array_merge($others, $proposals, $emptyKeyData);
+ $data = $this->reorderProposalDataByPremiumOrder($data);
+ return $data;
+ }
+
+ private function reorderProposalDataByPremiumOrder(array $data): array
+ {
+ if (!isset($data['premium_data']['data'], $data['proposal_data']['over_all_column_data'])) {
+ return $data;
+ }
+
+ $premiumProposals = array_keys($data['premium_data']['data']);
+ $filteredProposals = [];
+
+ // Collect proposal keys that match the pattern "Proposal X"
+ foreach ($premiumProposals as $key) {
+ if (preg_match('/^Proposal\s+\d+$/', $key) && isset($data['proposal_data']['over_all_column_data'][$key])) {
+ $filteredProposals[$key] = $data['proposal_data']['over_all_column_data'][$key];
+ }
+ }
+
+ // dd($premiumProposals, $filteredProposals);
+
+ $data['proposal_data']['over_all_column_data'] = $filteredProposals;
+ $data = $this->reorderProposalInHeaderAndData($data);
+ return $data;
+ }
+
+ private function reorderProposalInHeaderAndData(array $data): array
+ {
+ $tableData = $data['table_data'];
+ $sortedProposalOrder = $data['proposal_data']['over_all_column_data'];
+ $headers = $tableData['headers'] ?? [];
+ $dataRows = $tableData['data'] ?? [];
+
+ // Step 1: Separate static and proposal headers
+ $staticHeaders = [];
+ $proposalHeaders = [];
+ $actionHeader = [];
+ foreach ($headers as $header) {
+ if (in_array($header['parentHeader'], array_keys($sortedProposalOrder))) {
+ $proposalHeaders[$header['parentHeader']] = $header;
+ } else {
+ if ($header['parentHeader'] == "Action") {
+ $actionHeader[] = $header;
+ } else {
+ $staticHeaders[] = $header;
+ }
+ }
+ }
+
+ // dd($staticHeaders, $proposalHeaders, $sortedProposalOrder);
+
+ // Step 2: Reorder headers
+ $reorderedHeaders = [];
+ foreach ($sortedProposalOrder as $proposalKey => $proposalValue) {
+ if (isset($proposalHeaders[$proposalKey])) {
+ $reorderedHeaders[] = $proposalHeaders[$proposalKey];
+ }
+ }
+
+ // print_rr($reorderedHeaders); die;
+ foreach ($reorderedHeaders as $key => &$value) {
+ $value['parentHeader'] = 'Proposal ' . ($key + 1);
+ }
+ unset($value);
+
+
+ $reorderedHeaders = array_merge($staticHeaders, $reorderedHeaders, $actionHeader);
+
+
+ // Step 3: Reorder each row's `data` by matching parentth
+ foreach ($dataRows as $dataRowIndex => &$row) {
+ $staticData = [];
+ $proposalData = [];
+ $actionData = [];
+
+ foreach ($row['data'] as $entry) {
+ if (in_array($entry['parentth'], array_keys($sortedProposalOrder))) {
+ $proposalData[$entry['parentth']][] = $entry;
+ } else {
+ if ($entry['parentth'] == "Action") {
+ $actionData[] = $entry;
+ } else {
+ $staticData[] = $entry;
+ }
+ }
+ }
+
+ $reorderedProposalData = [];
+ foreach ($sortedProposalOrder as $proposalKey => $proposalValue) {
+ if (isset($proposalData[$proposalKey])) {
+ foreach ($proposalData[$proposalKey] as $entry) {
+ $reorderedProposalData[] = $entry;
+ }
+ }
+ }
+
+ $dubParTh = "";
+ $increament = 0;
+ foreach ($reorderedProposalData as $key => &$value) {
+
+ if ($dubParTh == $value['parentth']) {
+ $value['parentth'] = 'Proposal ' . ($increament);
+ } else {
+ $dubParTh = $value['parentth'];
+ $increament = $increament + 1;
+ $value['parentth'] = 'Proposal ' . ($increament);
+ }
+ }
+ unset($value);
+
+ $row['data'] = array_merge($staticData, $reorderedProposalData, $actionData);
+ }
+
+ $data['table_data']['headers'] = $reorderedHeaders;
+ $data['table_data']['data'] = $dataRows;
+
+ $renumberedArray = $this->renumberProposalKeys($data['proposal_data']['over_all_column_data']);
+ $updatedDataSet = $this->renumberProposalKeys($data['premium_data']['data']);
+ $data['proposal_data']['over_all_column_data'] = !empty($renumberedArray) ? $renumberedArray : $data['proposal_data']['over_all_column_data'];
+ $data['premium_data']['data'] = !empty($updatedDataSet) ? $updatedDataSet : $data['premium_data']['data'];
+
+ return $data;
+ }
+
+ private function renumberProposalKeys(array $input): array
+ {
+ $result = [];
+ $counter = 1;
+
+ foreach ($input as $key => $value) {
+ if (strpos($key, 'Proposal') === 0) {
+ $newKey = 'Proposal ' . $counter++;
+ $result[$newKey] = $value;
+ } else {
+ $result[$key] = $value;
+ }
+ }
+
+ return $result;
+ }
+
+
//-----RFQ and QCR EXPORT------------------------------------------------------------------------------------------------
@@ -791,7 +1123,7 @@ class LeadsController extends BaseController
if ($rfq_data['policy_type_id'] == 2) {
$lead_data = [
-
+ 'policy_end_date' => $rfq_data['policy_end_date'],
'Insured' => $rfq_data['client_name'],
'Policy Status' => $rfq_data['status'],
@@ -804,6 +1136,7 @@ class LeadsController extends BaseController
];
} else if ($rfq_data['policy_type_id'] == 1) {
$lead_data = [
+ 'policy_end_date' => $rfq_data['policy_end_date'],
'Insured' => $rfq_data['client_name'],
'No of Employees at Inception' => $rfq_data['incept_emp_count'],
'Total Sum Insured at Inception ' => $rfq_data['total_si_at_incept'],
@@ -816,6 +1149,7 @@ class LeadsController extends BaseController
} else {
if ($rfq_data['policy_type_id'] == 2) {
$lead_data = [
+ 'policy_end_date' => $rfq_data['policy_end_date'],
'Insured' => $rfq_data['client_name'],
'Policy Status' => $rfq_data['status'],
@@ -844,6 +1178,7 @@ class LeadsController extends BaseController
];
} else if ($rfq_data['policy_type_id'] == 1) {
$lead_data = [
+ 'policy_end_date' => $rfq_data['policy_end_date'],
'Insured' => $rfq_data['client_name'],
'No of Employees at Renewal' => $rfq_data['renewal_emp_count'],
'Total Sum Insured at Renewal ' => $rfq_data['total_si_at_renewal'],
@@ -877,7 +1212,7 @@ class LeadsController extends BaseController
// Start with lead_data at the top
$rowNumber = 1;
- $mergeRange1 = "A{$rowNumber}:C{$rowNumber}";
+ $mergeRange1 = "A{$rowNumber}:B{$rowNumber}";
$sheet->mergeCells($mergeRange1);
$sheet->setCellValue("A{$rowNumber}", "Nhance India Insurance Broking Pvt Ltd");
$sheet->getStyle("A{$rowNumber}")->applyFromArray([
@@ -892,13 +1227,13 @@ class LeadsController extends BaseController
]);
// Set column width to fit the image properly
- $sheet->getColumnDimension('D')->setWidth(20); // Adjust as needed
+ $sheet->getColumnDimension('C')->setWidth(20); // Adjust as needed
$sheet->getRowDimension($rowNumber)->setRowHeight(40); // Adjust as needed
$drawing = new Drawing();
$path = ROOTPATH . "public/assets/images/Nhance-Logo-Final.png"; // Use FCPATH for server path
$drawing->setPath($path);
- $drawing->setCoordinates("D{$rowNumber}"); // Set position in column B
+ $drawing->setCoordinates("C{$rowNumber}"); // Set position in column B
$drawing->setHeight(35); // Adjust image height
// Center align the image in the cell
@@ -908,8 +1243,8 @@ class LeadsController extends BaseController
$drawing->setWorksheet($sheet);
// Apply center alignment to the cell
- $sheet->getStyle("D{$rowNumber}")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
- $sheet->getStyle("D{$rowNumber}")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
+ $sheet->getStyle("C{$rowNumber}")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
+ $sheet->getStyle("C{$rowNumber}")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
$rowNumber = $rowNumber + 1;
@@ -922,7 +1257,7 @@ class LeadsController extends BaseController
// Merge A:B for key and C:D for value
$mergeRangeKey = "A{$rowNumber}:B{$rowNumber}";
- $mergeRangeValue = "C{$rowNumber}:D{$rowNumber}";
+ $mergeRangeValue = "C{$rowNumber}";
$sheet->mergeCells($mergeRangeKey);
$sheet->mergeCells($mergeRangeValue);
@@ -955,9 +1290,9 @@ class LeadsController extends BaseController
// Set column width based on max content length (adjusted for padding)
$sheet->getColumnDimension('A')->setWidth($maxWidthA * 1.2);
- $sheet->getColumnDimension('B')->setWidth($maxWidthA * 1.2);
+ $sheet->getColumnDimension('B')->setWidth($maxWidthA * 5);
$sheet->getColumnDimension('C')->setWidth($maxWidthB * 1.2);
- $sheet->getColumnDimension('D')->setWidth($maxWidthB * 1.2);
+ // $sheet->getColumnDimension('D')->setWidth($maxWidthB * 1.2);
// $rowNumber += 2;
@@ -1016,7 +1351,7 @@ class LeadsController extends BaseController
}
if ($header['parentHeader'] === 'Particulars') {
- $sheet->getColumnDimension('B')->setWidth(40);
+ $sheet->getColumnDimension('B')->setWidth(80);
}
$startColumn = $columnLetter; // Start of the current header range
@@ -1200,7 +1535,7 @@ class LeadsController extends BaseController
}
$lastRow = count($lead_data) + 1;
- $leadRange = "A1:D{$lastRow}";
+ $leadRange = "A1:C{$lastRow}";
$sheet->getStyle($leadRange)->applyFromArray([
'borders' => [
@@ -1211,9 +1546,25 @@ class LeadsController extends BaseController
],
]);
+
+
// Set filename
$string = ($type == 2) ? 'QCR' : 'RFQ';
- $filename = "{$string}_{$rfq_data['client_short_name']}_{$rfq_data['policy_type']}_" . date('YmdHis') . '.xlsx';
+ $current_year = date('Y');
+ $next_year = $current_year + 1;
+ $policy_year = "$current_year-$next_year";
+
+ if (!empty($rfq_data['policy_end_date'])){
+ $policy_expiry = strtotime($lead_data['policy_end_date']);
+
+ $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';
+ }
+
// Save to temporary location
$uploadFilePath = WRITEPATH . 'tmp/' . $filename;
@@ -1693,6 +2044,7 @@ class LeadsController extends BaseController
$propsal_and_insurer = isset($params['proposal_insurer']) ? $params['proposal_insurer'] : null;
$mail_content = $params['mail_content'];
$mail_subject = $params['subject'];
+ $attachment_file_ids = $params['selected_attachment_files'];
$result_data = [];
// dd($recipient_mail);
@@ -1801,7 +2153,7 @@ class LeadsController extends BaseController
['file_path' => $temp_file_path, 'sheets' => []],
['file_path' => $lead_file_path, 'sheets' => []]
];
- $outputPath = dirname($temp_file_path) . '/' . 'merged_' . $temp_file_name;
+ $outputPath = dirname($temp_file_path) . '/' . $temp_file_name;
$result = ExcelMergeHelper::mergeExcelFiles($filePaths, $outputPath);
// print_rr($result);
}
@@ -1817,7 +2169,12 @@ class LeadsController extends BaseController
$file_path = $result;
$file_name = basename($result);
+
+ // Attacments part
$attachments = [['fileName' => $file_name, 'filePath' => $file_path]];
+ $other_attachments = $this->handleMultiFileAttachments($attachment_file_ids, $lead_id);
+ $attachments = array_merge($attachments, $other_attachments);
+ // print_r($attachments); die;
//get recipient address
if ($recipient_type == 'insurer' || $recipient_type == 'placement') {
@@ -1832,13 +2189,20 @@ class LeadsController extends BaseController
// print_r($recipient_data); die;
} else if ($recipient_type == 'client') {
- $recipient_data = [['name' => $lead_data['contact_person_name'], 'email' => $lead_data['contact_person_email']]];
+
+ $mailIDS = explode(',',$params['contact_mail']);
+ $recipient_data = [];
+ foreach ($mailIDS as $mail){
+ $recipient_data[] = ['name' => $lead_data['contact_person_name'], 'email' => $mail];
+ }
+
} else {
$recipient_data = [['name' => "Team", 'email' => $params['to']]];
}
// print_r($recipient_data); die;
$subject = $file_type == 'rfq' ? 'Request for Quotation from ' . $lead_data['client_name'] . ' for ' . $lead_data['policy_type'] : 'Quotation Comparison Report for ' . $lead_data['policy_type'];
+
$original_message = '
Request for Quotation (RFQ) Dear {{RECIPIENT_NAME}}, We are reaching out to request a quotation for the following insurance coverage. Please review the details below and provide your quote at your earliest convenience.
RFQ Details Client name {{CLIENT_NAME}} Coverage Type {{POLICY_LONG_NAME}} Policy Start Date {{POLICY_START_DATE}} Policy Duration {{DURATION}}
Please note: Additional terms and details are included in the attachment for your reference.
Please feel free to reach out if you require any further information to prepare the quote. We look forward to receiving your proposal.
Best regards,
Nhance India Pvt Ltd
© Nhance India Pvt Ltd. All rights reserved.
';
//for mail content
@@ -1887,7 +2251,9 @@ class LeadsController extends BaseController
'proposel_data' => json_encode($lead_update_data),
'status' => 'won',
'placement_date' => change_date_format($params['placement_date'], 'd/m/Y', 'Y-m-d'),
+ 'payment_date' => change_date_format($params['payment_date'], 'd/m/Y', 'Y-m-d'),
'utr_no' => $params['utr_no'],
+ 'is_cd' => $params['is_cd'],
'premium_amount' => $params['premium_amount'],
'total_amount' => $params['total_amount'],
'cd_amount' => $params['cd_amount'],
@@ -2299,16 +2665,15 @@ class LeadsController extends BaseController
// }
}
- if($data['lead_form_type'] == 1){
+ if ($data['lead_form_type'] == 1) {
$client_policy_data['policy_terms'] = $this->preparePolicyTermsFromRFQ($data);
- }else{
+ } else {
$placementJson = $this->getPlacementJson($data);
if ($placementJson) {
$client_policy_data['placement_json'] = $placementJson;
$client_policy_data['policy_terms'] = $this->convertNonEbQCRJsonToPolicyTerms(json_decode($placementJson, true));
}
-
}
// print_r($client_policy_data); die;
@@ -2447,12 +2812,11 @@ class LeadsController extends BaseController
}
return json_encode($terms_array);
-
} else {
return null;
}
}
-
+
public function featchClientPolicyFromLead($client_id, $branch_id, $lead_id)
{
$data = $this->leadsModel->where('leads.id', $lead_id)->where('leads.is_active', 1)->first();
@@ -2497,7 +2861,9 @@ class LeadsController extends BaseController
return $this->transformNonEbProposelData(
$jsonData,
$proposel_data['proposel_name'] ?? '',
- $proposel_data['insurer_name'] ?? '', null, 1
+ $proposel_data['insurer_name'] ?? '',
+ null,
+ 1
);
}, $jsonArray);
@@ -2517,7 +2883,7 @@ class LeadsController extends BaseController
}
unset($proposal); // Good practice after foreach by reference
}
-
+
$placement_json_data[] = $proposalData;
@@ -2534,6 +2900,13 @@ class LeadsController extends BaseController
$next_year = $current_year + 1;
$policy_year = "$current_year-$next_year";
+ $policy_expiry = strtotime($lead_data['policy_end_date']);
+
+ $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();
+
if ($lead_data) {
// Replacing placeholders with actual values
@@ -2543,6 +2916,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("{{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 {
@@ -2550,6 +2928,7 @@ class LeadsController extends BaseController
}
}
+
function getLastFiveFinancialYears()
{
$currentYear = date('Y');
@@ -2579,6 +2958,7 @@ class LeadsController extends BaseController
$this->loadLayout('view_rfq_non_eb');
}
+ // get lead data for edit bot EB and NON-EB
public function getLeadNonEB($type, $id = null)
{
// Set basic data
@@ -2606,9 +2986,15 @@ class LeadsController extends BaseController
->where('user_profiles.is_active', 1)
->findAll();
+
+
if (!empty($id)) {
+
$data['lead_edit_data'] = $this->leadsModel->where('id', $id)->first() ?? [];
+ $data['lead_edit_data']['multi_file_data'] = $this->leadFilesModel->where('lead_id', $id)->where('is_active', 1)->findAll() ?? null;
+ $data['lead_edit_data']['lead_file_count'] = count($data['lead_edit_data']['multi_file_data']);
+
// Decode and merge custom fields if present
$custom_fields_data = !empty($data['lead_edit_data']['custom_fields'])
? json_decode($data['lead_edit_data']['custom_fields'], true)
@@ -2619,7 +3005,7 @@ class LeadsController extends BaseController
}
if (!empty($data['lead_edit_data'])) {
- foreach (['policy_start_date', 'policy_end_date', 'incurred_claims_date', 'premium_date'] as $dateField) {
+ foreach (['policy_start_date', 'policy_end_date', 'source_policy_start_date', 'source_policy_end_date', 'incurred_claims_date'] as $dateField) {
$data['lead_edit_data'][$dateField] = !empty($data['lead_edit_data'][$dateField])
? change_date_format($data['lead_edit_data'][$dateField], 'Y-m-d', 'd/m/Y')
: null;
@@ -2633,6 +3019,9 @@ class LeadsController extends BaseController
$data['lead_edit_data']['policy_type_id'] ?? null,
$data
) ?? "";
+
+ $html = view('rfq/multi_files', $data);
+ $data['lead_edit_data']['multi_file_html'] = trim($html) !== '' ? $html : null;
}
if ($data['lead_edit_data']['lead_type'] != 1 && $data['lead_edit_data']['lead_form_type'] == 2) {
@@ -2707,7 +3096,7 @@ class LeadsController extends BaseController
$lead_data = array_merge(['Insured' => $rfq_data['client_name']], $lead_data);
$policy_registration_data = [];
- if(isset($rfq_data['registration_json']) && !empty($rfq_data['registration_json'])){
+ if (isset($rfq_data['registration_json']) && !empty($rfq_data['registration_json'])) {
$policy_registration_data = json_decode($rfq_data['registration_json'], true);
}
// dd($policy_registration_data);
@@ -2855,7 +3244,7 @@ class LeadsController extends BaseController
]);
$rowNumber++;
- }else{
+ } else {
$sheet->mergeCells("A{$rowNumber}:B{$rowNumber}");
$sheet->setCellValue("A{$rowNumber}", "Policy Type");
$sheet->setCellValue("C{$rowNumber}", ucfirst($key) . " Policy");
@@ -3043,7 +3432,7 @@ class LeadsController extends BaseController
$serial_no = 1;
$maxColumnWidths = [];
$RowSpanEnable = false;
-
+
// Add table data rows
foreach ($column_data as $dataRow) {
@@ -3068,11 +3457,11 @@ class LeadsController extends BaseController
$sheet->getStyle("{$columnLetter}{$mergeStart}:{$columnLetter}{$mergeEnd}")
->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
} else {
- if(!$hasPolicy && $key == 0){
+ if (!$hasPolicy && $key == 0) {
$RowSpanEnable = true;
$columnLetter++;
$sheet->setCellValue("{$columnLetter}{$rowNumber}", $cellData['display_content']);
- }else{
+ } else {
$sheet->setCellValue("{$columnLetter}{$rowNumber}", $cellData['display_content']);
}
}
@@ -3080,13 +3469,12 @@ class LeadsController extends BaseController
if (!($key === 0 && !$hasPolicy)) {
$columnLetter++;
}
-
}
$rowNumber++;
$serial_no++;
}
- if($key == 0 && $RowSpanEnable == true){
+ if ($key == 0 && $RowSpanEnable == true) {
$columnLetter++;
}
@@ -3389,7 +3777,7 @@ class LeadsController extends BaseController
return null;
}
- public function transformNonEbProposelData(&$data, $proposal, $insurer, $tableCount=null, $actionColumn = null)
+ public function transformNonEbProposelData(&$data, $proposal, $insurer, $tableCount = null, $actionColumn = null)
{
// Kint::dump($data, $proposal, $insurer, $tableCount);
@@ -3426,7 +3814,7 @@ class LeadsController extends BaseController
// Update the original data's headers
$data['table_data']['headers'] = $headerData;
- if(!empty($actionColumn)){
+ if (!empty($actionColumn)) {
$data['table_data']['headers'][] = [
'parentHeader' => "Action",
'subHeaders' => ['-']
@@ -3458,8 +3846,8 @@ class LeadsController extends BaseController
$filteredData[] = $item;
}
- if(!empty($actionColumn)){
- if($item['parentth'] === "Action"){
+ if (!empty($actionColumn)) {
+ if ($item['parentth'] === "Action") {
$filteredData[] = $item;
}
}
@@ -3477,19 +3865,33 @@ class LeadsController extends BaseController
return $data;
}
- // function getPreviousColumn($columnLetter)
- // {
- // $colIndex = Coordinate::columnIndexFromString($columnLetter);
- // if ($colIndex > 1) {
- // $colIndex--;
- // }
- // return Coordinate::stringFromColumnIndex($colIndex);
- // }
-
- function getPreviousColumn($columnLetter, $decrement = 1) {
+ public function getPreviousColumn($columnLetter, $decrement = 1)
+ {
$colIndex = Coordinate::columnIndexFromString($columnLetter);
$colIndex = max(1, $colIndex - $decrement); // ensure column index doesn't go below 1
return Coordinate::stringFromColumnIndex($colIndex);
}
-
+
+ public function handleMultiFileAttachments($json_string, $lead_id)
+ {
+ $attachments = [];
+
+ if (!empty($json_string)) {
+ $fileIds = json_decode($json_string, true);
+ $lead_file_path = WRITEPATH . 'uploads/lead_files/';
+
+ foreach ($fileIds as $id) {
+ $lead_file = $this->leadFilesModel->where('lead_id', $lead_id)->where('id', $id)->where('is_active', 1)->first();
+
+ if ($lead_file) {
+ $attachments[] = [
+ 'fileName' => $lead_file['file_name'],
+ 'filePath' => $lead_file_path . $lead_file['file_name']
+ ];
+ }
+ }
+ }
+
+ return $attachments;
+ }
}
diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php
index 4e1271f8..02409c2c 100755
--- a/app/Controllers/MasterController.php
+++ b/app/Controllers/MasterController.php
@@ -1422,11 +1422,12 @@ class MasterController extends AdminController
if ($insert) {
//for CD Tranction Table
+ $cd_tranction_data['cd_ac_pk'] = $this->CDMasterModel->insertID();
$response = DepositHelper::saveDeposit($cd_tranction_data, $loggedInUserID);
$cd_data = $this->CDMasterModel->where('client_id', $data['client_id'])->where('insurer_id', $data['insurer_id'])->findAll();
- return $this->respond(['status' => true, 'data' => $cd_data, 'cd_ac_no'=>$data['cd_ac_no'], 'message' => 'CD Account number created successfully'], 200);
+ return $this->respond(['status' => true, 'data' => $cd_data, 'cd_ac_no'=>$data['cd_ac_no'], 'message' => 'CD Account number created successfully', "FOR BDS PURPOSE"], 200);
}else{
return $this->respond(['status' => false, 'message' => 'Failed to created CD Account number'], 200);
}
diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php
index 3f7f36df..a4721770 100644
--- a/app/Controllers/PolicyTransactionController.php
+++ b/app/Controllers/PolicyTransactionController.php
@@ -306,6 +306,12 @@ class PolicyTransactionController extends BaseController
$data['policy_with_corr'] = 1;
}
+ if (!isset($data['is_cd_reduce_from_bds'])) {
+ $data['is_cd_reduce_from_bds'] = 0;
+ } elseif ($data['is_cd_reduce_from_bds']) {
+ $data['is_cd_reduce_from_bds'] = 1;
+ }
+
if($data['ct_type'] == ""){
$data['ct_type'] = 1;
}
@@ -342,7 +348,7 @@ class PolicyTransactionController extends BaseController
$this->policyTransactionModel->update($insert, ['client_policy_id' => $client_policy_id]);
$emp_policy_insert = $this->InsertIndividualEmpPolicyTable($emp_data, $client_policy_id);
- if ($data['client_type'] == 1 && $data['status'] == 'completed') {
+ if ($data['client_type'] == 1 && $data['status'] == 'completed' && $data['is_cd_reduce_from_bds'] == 1) {
$this->processCompletedStatus($data, $client_policy_id, $data['insurer_id']);
}
}
@@ -362,6 +368,7 @@ class PolicyTransactionController extends BaseController
private function updateInceptionPolicy($id, $data)
{
+ // print_r($data); die;
if ($this->policyTransactionModel->update($id, $data)) {
$this->insertTransactionStatus($id, $data, 1);
@@ -391,7 +398,7 @@ class PolicyTransactionController extends BaseController
}
if ($data['status'] == 'completed' && $data['ct_type'] == 2) {
- if($data['client_type'] == 1){
+ if($data['client_type'] == 1 && $data['is_cd_reduce_from_bds'] == 1){
$this->processCompletedStatus($data, $data['client_policy_id'], $data['insurer_id']);
}
}
@@ -426,7 +433,12 @@ class PolicyTransactionController extends BaseController
foreach ($data['follow_insurer_id'] as $index => $insurer) {
// Separate the insurer and insurer branch
- list($insurer_branch_id, $insurer_id) = explode('-', $insurer);
+ if(isset($insurer) && !empty($insurer)){
+ list($insurer_branch_id, $insurer_id) = explode('-', $insurer);
+ }else{
+ $insurer_branch_id = null;
+ $insurer_id = null;
+ }
// Prepare each co-share detail entry
$coShareDetails[] = [
@@ -547,7 +559,7 @@ class PolicyTransactionController extends BaseController
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.';
+ $description = 'The following amount of Rs. ' . $totalAmount . '/- has been debited for the ' . $data['emp_count'] . ' employees at Inception (BDS).';
$cdTransactionData = [
'amount' => $totalAmount,
@@ -562,8 +574,9 @@ class PolicyTransactionController extends BaseController
'updated_by' => get_session_userid(),
'event_name' => 'inception',
'is_active' => 1,
+ 'cd_ac_pk' => $data['cd_ac_pk']
];
-
+
DepositHelper::saveDeposit($cdTransactionData, get_session_userid());
}
@@ -987,7 +1000,6 @@ class PolicyTransactionController extends BaseController
}
-
//------------------------------------------------------------------------------------------------
// Policy Transaction Endorsement
@@ -1102,6 +1114,12 @@ class PolicyTransactionController extends BaseController
$data['policy_with_corr'] = 1;
}
+ if (!isset($data['is_cd_reduce_from_bds'])) {
+ $data['is_cd_reduce_from_bds'] = 0;
+ } elseif ($data['is_cd_reduce_from_bds']) {
+ $data['is_cd_reduce_from_bds'] = 1;
+ }
+
if(empty($data['data_received_date'])){
$data['data_received_date'] = null;
}else{
@@ -1171,8 +1189,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' => $issue_type['cd_ac_no'] ?? null,
- '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,
@@ -1231,6 +1249,7 @@ class PolicyTransactionController extends BaseController
$update = $this->policyTransactionModel->where('id', $id)->set($data)->update();
if ($update) {
+
$this->insertTransactionStatus($id, $data, 1);
$this->handleCompletedStatus($data, $id);
$this->insertOrUpdateCoShareDetails($data, $id);
@@ -1243,13 +1262,13 @@ class PolicyTransactionController extends BaseController
}
private function handleCompletedStatus($data, $policy_tran_id)
- {
- if ($data['status'] == 'completed' && $data['ct_type'] == 2) {
+ {
+ 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';
+ ($data['action_type'] == 'deletion' ? ' Credit ' : ' Debit ') . 'from the policy transaction (BDS)';
$cd_tranction_data = [
'amount' => $tolamt,
@@ -1264,6 +1283,7 @@ class PolicyTransactionController extends BaseController
'updated_by' => get_session_userid(),
'event_name' => $data['action_type'],
'is_active' => 1,
+ 'cd_ac_pk' => $data['cd_ac_pk'] ?? null,
];
DepositHelper::saveDeposit($cd_tranction_data, get_session_userid());
@@ -1589,6 +1609,7 @@ class PolicyTransactionController extends BaseController
->select("
pt_co_share_details.*,
policy_transaction.bro_payable_by,
+ policy_transaction.cd_ac_pk,
(
select cd_ac_no
from cd_master
@@ -1616,9 +1637,12 @@ class PolicyTransactionController extends BaseController
->where('is_active', 1)
->first();
+ $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], 200);
+ return $this->respond(['status' => true, 'code' => 200, 'data' => $totalCount, 'is_copay_yes' => $is_copay_yes, "cd_master_data" => $cd_ac_no], 200);
} else {
+ $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);
}
diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php
index a7392860..b9d62ff5 100644
--- a/app/Controllers/TicketController.php
+++ b/app/Controllers/TicketController.php
@@ -120,6 +120,9 @@ class TicketController extends BaseController
'((POLICY_TYPE))' => 'policy_type',
'((AUTO_QUERY_CONTENT))' => 'auto_query_content',
'((CLAIM_FORM_LINK))' => 'claim_form_link',
+ '((CLAIM_FEEDBACK_FORM))' => 'claim_feedback_form',
+ '((SETTLED_LETTER))' => 'settle_letter',
+ '((APPROVED_LETTER))' => 'approved_letter',
];
$this->extraFields = [
1 => ['non_id_reason'],
@@ -179,8 +182,18 @@ class TicketController extends BaseController
} else {
$data['ticket_data'] = $this->ticketSearch();
- $html = view('ticket_list', $data);
- return $this->respond(['status' => true, 'html' => $html], 200);
+ $isFromDashboard = $this->request->getPost("is_dashboard");
+
+ if (isset($isFromDashboard) && !empty($isFromDashboard) && $isFromDashboard == 1) {
+ $data['page_name'] = "Claims";
+ $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{
+ $html = view('ticket_list', $data);
+ return $this->respond(['status' => true, 'html' => $html], 200);
+ }
+
}
}
@@ -232,7 +245,9 @@ class TicketController extends BaseController
'tcs.claim_status AS status',
'tm.claim_number AS claim_no',
'tm.tpa_id',
+ 'tm.tpa_no',
'tm.emp_name',
+ 'tm.emp_code',
'i.name AS insurer_name',
'c.client_name',
'tm.insured_name',
@@ -255,10 +270,10 @@ class TicketController extends BaseController
} else {
$search_data = $this->request->getPost();
- // print_r($search_data);
+ // print_r($search_data); die()
$where = [];
foreach ($search_data as $search_objects => $key) {
- if ($key != null && $key != '' && $key != 0) {
+ if ($key != null && $key != '' && $key != 0 && $search_objects != 'is_dashboard') {
$where[$search_objects] = $key;
}
}
@@ -272,7 +287,9 @@ class TicketController extends BaseController
'tm.claim_status_id',
'tm.is_head_approved',
'tm.tpa_id',
+ 'tm.tpa_no',
'tm.emp_name',
+ 'tm.emp_code',
'i.name AS insurer_name',
'c.client_name',
'tm.insured_name',
@@ -456,7 +473,18 @@ class TicketController extends BaseController
$data['placeHolders'] = $this->placeHolders;
$data['message_data'] = $this->getTicketMessage($ticket_id);
$data['view_ticket_page'] = [];
- $data['member_data'] = $this->employeeModel->getEmployeeByEmployeeCode($ticket_data['emp_code']);
+
+ if($ticket_data['ticket_type_id'] == 1){
+ $data['member_data'] = $this->employeeModel->getEmployeeByEmployeeCode($ticket_data['emp_code']);
+ }else{
+ $data['member_data'] = array_filter(
+ $this->employeeModel->getEmployeeByEmployeeCode($ticket_data['emp_code']),
+ function ($member) {
+ return isset($member['emp_relationship']) && $member['emp_relationship'] == 'Self';
+ }
+ );
+ }
+
$data['ticket_history'] = $this->ticketHistory($ticket_id);
$data['ticket_check_list'] = db_connect()->table('ticket_check_list')->where('is_active', 1)->where('ticket_type_id', $ticket_data['ticket_type_id'])->get()->getResultArray();
if (!empty($ticket_data['client_policy_id'])){
@@ -578,7 +606,9 @@ class TicketController extends BaseController
$return_value = $this->ticketMasterModel->insert($ticket_data);
if ($return_value) {
//mail trigger part
+ $this->putHistoryAfterInsert($ticket_data, $return_value);
$mail_responce = $this->sendAutoMailTrigger($return_value);
+ $this->autoMessageInsertBasedOnMailResponse($mail_responce, $return_value);
return $this->respond(['status' => true, 'ticket_id' => $return_value, 'code' => 200, 'data' => $ticket_data, "message" => "Claim created successfully", 'mail_responce' => $mail_responce], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to create claim'], 200);
@@ -601,8 +631,12 @@ class TicketController extends BaseController
$return_value = $this->ticketMasterModel->where('id', $ticket_id)->set($ticket_data)->update();
if ($return_value) {
- //mail trigger part
- $mail_responce = $this->sendAutoMailTrigger($ticket_id);
+ $mail_responce = null;
+ if($old_ticket_data['claim_status_id'] != $ticket_data['claim_status_id']){
+ //mail trigger part
+ $mail_responce = $this->sendAutoMailTrigger($ticket_id);
+ $this->autoMessageInsertBasedOnMailResponse($mail_responce, $ticket_id);
+ }
//send mail to the head for rejected ticket approvel
if($ticket_data['claim_status_id'] == 8 && $ticket_data['is_head_approved'] == 0){
@@ -751,13 +785,20 @@ class TicketController extends BaseController
{
// log_message('error','Function called');die();
// $ticket_master_id = $this->request->getPost('id');
- $user_id = get_session_userid();
- $logged_user = $this->userModel->select('first_name,last_name,profile')->where('id', $user_id)->first();
$dataToSend = [];
- $dataToSend['user_name'] = $logged_user['first_name'] . ' ' . $logged_user['last_name'];
- $dataToSend['messages'] = $this->ticketMessageModel->where('is_active', 1)
- ->where('ticket_id', $ticket_master_id)->orderBy('created_at', 'DESC')
+
+ $user_id = get_session_userid();
+ // $logged_user = $this->userModel->select('first_name,last_name,profile')->where('id', $user_id)->first();
+ // $dataToSend['user_name'] = $logged_user['first_name'] . ' ' . $logged_user['last_name'];
+
+ $dataToSend['messages'] = $this->ticketMessageModel
+ ->select('ticket_messages.*,up.first_name as user_name')
+ ->join('user_profiles up', 'up.id = ticket_messages.created_by', 'left')
+ ->where('ticket_messages.is_active', 1)
+ ->where('ticket_messages.ticket_id', $ticket_master_id)
+ ->orderBy('ticket_messages.created_at', 'DESC')
->findAll();
+
foreach ($dataToSend['messages'] as $message) {
$mail_content_converted = $this->convertHtmlToText($message['mail_content']);
$message['mail_content'] = $mail_content_converted;
@@ -837,7 +878,7 @@ class TicketController extends BaseController
}
// Construct Mail Data
- $mailData = [
+ $mailData[] = [
'mail' => $ticket_data['emp_mail'],
'subject' => $subject,
'message' => $message,
@@ -845,6 +886,17 @@ class TicketController extends BaseController
'attachments' => []
];
+ // if the employee personal mail is not empty then send the mail to the employee personal mail
+ if(!empty($ticket_data['emp_personal_mail'])){
+ $mailData[] = [
+ 'mail' => $ticket_data['emp_personal_mail'],
+ 'subject' => $subject,
+ 'message' => $message,
+ 'cc' => $ticket_data['common_mails'] ?? '',
+ 'attachments' => []
+ ];
+ }
+
// print_r($mailData); die;
$this->myLogger->logme('error', "Final Email Data");
@@ -869,6 +921,12 @@ class TicketController extends BaseController
$replaceData = str_replace("Claim-", "", $this->ticketType[$ticket_data['ticket_type_id']] ?? "");
} else if ($value == "claim_form_link"){
$replaceData = 'Click here to download Claim Form ';
+ } else if ($value == "claim_feedback_form" && $ticket_data['ticket_type_id'] == 1){
+ $replaceData = 'Click to open Claim Feedback Form ';
+ } else if ($value == "settle_letter"){
+ $replaceData = ' View Settlement Letter ';
+ }else if ($value == "approved_letter"){
+ $replaceData = ' View Approved Letter ';
}else {
$replaceData = isset($ticket_data[$value]) ? $ticket_data[$value] : '';
}
@@ -927,6 +985,27 @@ class TicketController extends BaseController
$this->myLogger->logme('error', "Fetched ACM emails");
+
+ if(!empty($ticket_data['emp_personal_mail'])){
+
+ $this->myLogger->logme('error', "Send employee personal mail start");
+
+ $emailPersonalData = [
+ 'mail' => $ticket_data['emp_personal_mail'],
+ 'subject' => $mail_data['mail_subject'],
+ 'message' => $mail_data['mail_content'],
+ 'common' => [],
+ 'cc' => $acm_mails['common_mails'],
+ 'attachments' => []
+ ];
+
+ $this->sendTrigger($emailPersonalData);
+
+ $this->myLogger->logme('error', "Send employee personal mail successfully");
+ }else{
+ $this->myLogger->logme('error', "Send employee personal mail is empty");
+ }
+
$emailData = [
'mail' => $mail_data['emp_mail'],
'subject' => $mail_data['mail_subject'],
@@ -950,7 +1029,10 @@ class TicketController extends BaseController
if (!empty($auto_mail_enable) && $auto_mail_enable['is_auto_mail'] == 1) {
$mail_content = $this->constructMailContent($ticket_id);
// print_r($mail_content); die;
- $mail_responce = $this->sendTrigger($mail_content);
+ foreach ($mail_content as $key => $value) {
+ $mail_responce = $this->sendTrigger($value);
+ $this->myLogger->logme('error', '{data} - Auto Mail Sent, Successfully', ['data' => $key + 1]);
+ }
} elseif (!empty($auto_mail_enable) && $auto_mail_enable['is_auto_mail'] == 0) {
$this->myLogger->logme('error', 'Auto Mail Not Sent, Reason: Automail Not Enabled');
} else {
@@ -972,7 +1054,7 @@ class TicketController extends BaseController
th.old_value,
th.new_value,
th.created_at,
- CONCAT(creator.first_name, ' ', creator.last_name) as modified_by,
+ CONCAT_WS(' ', creator.first_name, creator.last_name) AS modified_by,
-- Claim Status
old_status.claim_status as old_status_value,
new_status.claim_status as new_status_value,
@@ -1032,6 +1114,7 @@ class TicketController extends BaseController
ORDER BY
th.created_at DESC";
$data = $this->ticketHistoryModel->query($sql)->getResultArray();
+ // dd(db_connect()->getLastQuery());
$priorityType = $this->priorityType;
$relationshipType = $this->relationshipType;
$modeOFIntimate = $this->modeOFIntimate;
@@ -1166,7 +1249,7 @@ class TicketController extends BaseController
if ($policy_type == 1){
$viewData['column_order'] = [
'ACM_NAME', 'ID NOT GENERATED', 'NON ID', 'CDA', 'INFORMATION REQUIRED',
- 'UNDER PROCESS - CLAIM NO. UPDATION', 'UNDER PROCESS - INVESTIGATION STATUS',
+ 'UNDER PROCESS - CLAIM NO. UPDATION',
'UNDER PROCESS - QUERY DOCUMENT RECEIVED', 'APPROVED', 'PAYMENT INITIATED',
'TOTAL'
];
@@ -1185,7 +1268,7 @@ class TicketController extends BaseController
}else{
$viewData['column_order'] = [
'ACM_NAME', 'CLAIM INTIMATION', 'INTIMATION TO INSURER', 'CLIENT PENDING',
- 'INSURER PENDING','INVESTIGATION','APPROVED','ON HOLD','TOTAL', 'NOT COVERED',
+ 'INSURER PENDING','INVESTIGATION','APPROVED','TOTAL', 'NOT COVERED',
'CLOSED', 'SETTLED', 'CLEARED_TOTAL'
];
$ordered_data = [];
@@ -1207,7 +1290,7 @@ class TicketController extends BaseController
$viewData['column_order'] = [
'TPA_NAME', 'NON ID', 'ID NOT GENERATED', 'CDA', 'INFORMATION REQUIRED',
- 'UNDER PROCESS - CLAIM NO. UPDATION', 'UNDER PROCESS - INVESTIGATION STATUS',
+ 'UNDER PROCESS - CLAIM NO. UPDATION',
'UNDER PROCESS - QUERY DOCUMENT RECEIVED', 'APPROVED', 'PAYMENT INITIATED',
'TOTAL', 'SETTLED', 'CLOSED', 'CANCELLED', 'RETURNED', 'CLEARED_TOTAL'
];
@@ -1371,7 +1454,8 @@ class TicketController extends BaseController
}
}
- public function getPoliciesbyEmpID() {
+ public function getPoliciesbyEmpID()
+ {
$received_data = $this->request->getPost();
$emp_id = $received_data['emp_id'];
@@ -1443,5 +1527,121 @@ class TicketController extends BaseController
return $this->response->setStatusCode(500)->setBody('An error occurred while downloading the file.');
}
}
-
+
+ // -------------------------------------------------------------------------------------------------------------------------
+
+ public function autoMessageInsertBasedOnMailResponse($mail_sent_status, $ticket_id)
+ {
+ if (gettype($mail_sent_status) == 'array') {
+ $this->myLogger->logme('error', "auto Message Insert Based On Mail Response Failed because is array :$ticket_id ");
+ } else {
+ $mail_sent_status = json_decode($mail_sent_status);
+ $this->myLogger->logme('error', "mail_sent_status is object :$ticket_id ");
+ }
+
+ if (!empty($mail_sent_status) && isset($mail_sent_status->status) && $mail_sent_status->status == 'success') {
+
+ $sent_message_data['ticket_id'] = $ticket_id;
+ $sent_message_data['sender'] = 'staff';
+ $sent_message_data['emp_mail'] = $mail_sent_status->data->params->mail;
+ $sent_message_data['mail_subject'] = $mail_sent_status->data->params->subject;
+ $sent_message_data['mail_content'] = $mail_sent_status->data->params->message;
+
+ $message_insert_status = $this->ticketMessageModel->insert($sent_message_data);
+
+ if ($message_insert_status) {
+ $this->myLogger->logme('error', "Claim initiated, Mail sent Successfully, successfully store message:$ticket_id ");
+ } else {
+ $this->myLogger->logme('error', "Claim initiated, Mail sent Successfully, Failed to store message:$ticket_id ");
+ }
+
+ return true;
+ } else {
+
+ $this->myLogger->logme('error', "Failed to send Mail :$ticket_id ");
+ return true;
+ }
+ }
+
+ public function putHistoryAfterInsert($ticket_data, $ticket_id)
+ {
+ $this->myLogger->logme('error', "Put History After Insert function called : $ticket_id");
+
+ if(!empty($ticket_data)){
+
+ $history_data = [
+ 'ticket_id' => $ticket_id,
+ 'field_name' => 'claim_status_id',
+ 'display_name' => 'Ticket Created',
+ 'old_value' => null,
+ 'new_value' => $ticket_data['claim_status_id'],
+ 'created_by' => get_session_userid(),
+ 'is_active' => 1
+ ];
+
+ $this->myLogger->logme('error', "Put History After Insert function called : " . json_encode($history_data));
+
+
+ $history_insert = $this->ticketHistoryModel->insert($history_data);
+
+ if($history_insert){
+ $this->myLogger->logme('error', "Put History After Insert Ticket Data Successfully");
+ }else{
+ $this->myLogger->logme('error', "Put History After Insert Ticket Data Failed");
+ }
+
+ }else{
+ $this->myLogger->logme('error', "Put History After Insert Ticket Data is empty");
+ }
+
+ return true;
+
+ }
+
+ public function viewClaimFeedbackForm($md5_ticket_id,$empView = null)
+ {
+
+ if ($this->request->is("get")){
+
+ $data['ticket_id'] = $md5_ticket_id;
+ $data['ticket_data'] = $this->ticketMasterModel->select('ticket_master.*,clients.client_name')->join('clients','clients.id = ticket_master.client_id')->where('MD5(ticket_master.id)',$md5_ticket_id)->where('ticket_master.is_active',1)->first();
+ $data['form_submitted'] = !empty($data['ticket_data']['feedback_json'])? 1 : 0;
+
+
+ $data['viewer'] = !empty($empView) ? $empView : 0;
+ // dd($data);
+ return view('ticket_feedback_form', $data);
+ }else{
+
+ $formDataJson = json_encode($this->request->getPost());
+ // log_message("error","Form data : ".$formDataJson);
+
+
+ $data_to_store = [
+
+ 'feedback_json' => $formDataJson
+ ];
+
+ if (!empty($formDataJson)){
+ // $this->ticketMasterModel->save($data_to_store);
+ $this->ticketMasterModel->where('MD5(id)', $md5_ticket_id)->set($data_to_store)->update();
+
+ return $this->respond(['status' => true,'id'=> $md5_ticket_id,'received_data' => $formDataJson], 200);
+
+ }else{
+ return $this->respond(['status' => false,'id'=> $md5_ticket_id,'received_data' => $formDataJson], 200);
+ }
+
+ }
+
+ }
+
+ public function feedbackList(){
+
+ $data['feedback_data'] = $this->ticketMasterModel->select("ticket_master.*,clients.client_name")->join("clients","clients.id = ticket_master.client_id")->where("ticket_master.is_active",1)->where("ticket_master.feedback_json IS NOT NULL", null, false)->where("ticket_master.feedback_json !=", "")->findAll();
+
+ // dd($data);
+ $this->loadLayout("ticket_feedback_list",$data);
+ }
+
}
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 @@
+query($getLastBalanceQuery, $getLastBalanceParams)->getRow()->balance ?? 0;
diff --git a/app/Helpers/ExcelMergeHelper.php b/app/Helpers/ExcelMergeHelper.php
index 36306692..405c4762 100644
--- a/app/Helpers/ExcelMergeHelper.php
+++ b/app/Helpers/ExcelMergeHelper.php
@@ -17,10 +17,13 @@ class ExcelMergeHelper {
{
try {
log_message('debug', 'Attempting merge with original file order');
+ // echo "Attempting merge with original file order\n";
return self::processFiles($filePaths, $outputPath);
} catch (Exception $e) {
log_message('error', 'First attempt failed: ' . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine());
+ // echo "First attempt failed: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() . "\n";
log_message('debug', 'Retrying with reversed file order');
+ // echo "Retrying with reversed file order\n";
// Reverse the file order and try again
$reversedFiles = array_reverse($filePaths);
@@ -29,6 +32,7 @@ class ExcelMergeHelper {
return self::processFiles($reversedFiles, $outputPath);
} catch (Exception $e2) {
log_message('error', 'Both attempts failed. Last error: ' . $e2->getMessage() . ' in ' . $e2->getFile() . ' on line ' . $e2->getLine());
+ // echo "Both attempts failed. Last error: " . $e2->getMessage() . ' in ' . $e2->getFile() . ' on line ' . $e2->getLine() . "\n";
return null;
}
}
@@ -45,7 +49,9 @@ class ExcelMergeHelper {
private static function processFiles(array $filePaths, string $outputPath): string
{
log_message('debug', 'Starting Excel merge process');
+ // echo "Starting Excel merge process\n";
log_message('debug', 'Files to process: ' . json_encode($filePaths));
+ // echo "Files to process: " . json_encode($filePaths) . "\n";
if (empty($filePaths)) {
throw new Exception("No files provided to merge");
@@ -66,6 +72,7 @@ class ExcelMergeHelper {
// Save the merged file
log_message('debug', "Saving merged file to: {$outputPath}");
+ // echo "Saving merged file to: {$outputPath}\n";
$writer = IOFactory::createWriter($mergedSpreadsheet, 'Xlsx');
$writer->setPreCalculateFormulas(false);
$writer->save($outputPath);
@@ -76,6 +83,7 @@ class ExcelMergeHelper {
gc_collect_cycles();
log_message('debug', 'Excel merge process completed successfully');
+ // echo "Excel merge process completed successfully\n";
return $outputPath;
}
@@ -87,15 +95,17 @@ class ExcelMergeHelper {
* @param int|null $index
* @throws Exception
*/
- private static function processSingleFile(array $fileInfo, Spreadsheet $mergedSpreadsheet, int $index = null)
+ private static function processSingleFile(array $fileInfo, Spreadsheet $mergedSpreadsheet, ?int $index = null)
{
if (!isset($fileInfo['file_path']) || !file_exists($fileInfo['file_path'])) {
$path = $fileInfo['file_path'] ?? 'undefined';
log_message('error', "File " . ($index ?? 'base') . ": Invalid or missing file path: {$path}");
+ // echo "File " . ($index ?? 'base') . ": Invalid or missing file path: {$path}\n";
return;
}
log_message('debug', "Processing file " . ($index ?? 'base') . ": " . $fileInfo['file_path']);
+ // echo "Processing file " . ($index ?? 'base') . ": " . $fileInfo['file_path'] . "\n";
try {
// Load the source spreadsheet
@@ -105,6 +115,7 @@ class ExcelMergeHelper {
$worksheets = $sourceSpreadsheet->getAllSheets();
$totalSheets = count($worksheets);
log_message('debug', "Total sheets in file: " . $totalSheets);
+ // echo "Total sheets in file: " . $totalSheets . "\n";
$sheetsToMerge = $fileInfo['sheets'] ?? [];
@@ -114,26 +125,30 @@ class ExcelMergeHelper {
try {
$sheetName = $worksheet->getTitle();
log_message('debug', "Processing sheet: {$sheetName}");
+ // echo "Processing sheet: {$sheetName}\n";
// Generate unique sheet name before cloning
$newName = $sheetName;
$counter = 1;
while (in_array($newName, $mergedSpreadsheet->getSheetNames())) {
- $newName = $sheetName . "_" . $counter++;
+ // $newName = $sheetName . "_" . $counter++;
log_message('debug', "Sheet name already exists. Trying new name: {$newName}");
+ // echo "Sheet name already exists. Trying new name: {$newName}\n";
}
// Clone the worksheet and set the new name
- $clonedSheet = clone $worksheet;
- $clonedSheet->setTitle($newName);
+ // $clonedSheet = clone $worksheet;
+ // $clonedSheet->setTitle($newName);
// Add as external sheet
- $mergedSpreadsheet->addExternalSheet($clonedSheet);
+ $mergedSpreadsheet->addExternalSheet($worksheet);
log_message('debug', "Successfully added sheet: {$newName}");
+ // echo "Successfully added sheet: {$newName}\n";
} catch (Exception $e) {
log_message('error', "Error processing sheet {$sheetName} as new name {$newName}: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine());
+ // echo "Error processing sheet {$sheetName} as new name {$newName}: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() . "\n";
}
}
}
@@ -145,6 +160,7 @@ class ExcelMergeHelper {
} catch (Exception $e) {
log_message('error', "Error processing file {$fileInfo['file_path']}: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine());
+ // echo "Error processing file {$fileInfo['file_path']}: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() . "\n";
}
}
}
\ No newline at end of file
diff --git a/app/Helpers/clientWebHookHelper.php b/app/Helpers/clientWebHookHelper.php
new file mode 100644
index 00000000..ba55eb18
--- /dev/null
+++ b/app/Helpers/clientWebHookHelper.php
@@ -0,0 +1,39 @@
+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/Helpers/excel_util_helper.php b/app/Helpers/excel_util_helper.php
index 69fe4d98..593b2d05 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');
diff --git a/app/Helpers/utility_helper.php b/app/Helpers/utility_helper.php
index 54a5883a..33f504c0 100755
--- a/app/Helpers/utility_helper.php
+++ b/app/Helpers/utility_helper.php
@@ -677,3 +677,69 @@ if (!function_exists('is_json_string')) {
}
}
+if (!function_exists('check_cd_entry_exist')) {
+ function check_cd_entry_exist($params)
+ {
+ $db = db_connect();
+
+ $client_id = $params['client_id'];
+ $client_policy_id = $params['client_policy_id'];
+ $insurer_id = $params['insurer_id'];
+ $cd_ac_pk = $params['cd_ac_pk'];
+ $event_name = $params['event_name'];
+
+ // Check if truncated entry (sub_type = 8) exists
+ $has_truncated = $db->table('cash_deposit')
+ ->where('client_id', $client_id)
+ ->where('insurer_id', $insurer_id)
+ ->where('cd_ac_pk', $cd_ac_pk)
+ ->where('client_policy_id', $client_policy_id)
+ ->where('event_name', $event_name)
+ ->where('sub_type', 8)
+ ->where('is_active', 1)
+ ->countAllResults();
+
+ if ($has_truncated) {
+
+ echo "has_truncated";
+ // Get all entries with same details (including truncated)
+ $entries = $db->table('cash_deposit')
+ ->where('client_id', $client_id)
+ ->where('insurer_id', $insurer_id)
+ ->where('cd_ac_pk', $cd_ac_pk)
+ ->where('client_policy_id', $client_policy_id)
+ ->where('event_name', $event_name)
+ ->where('is_active', 1)
+ ->where('sub_type !=', 8)
+ ->get()
+ ->getResultArray();
+
+ if (count($entries) > 1) {
+ // Only one entry found (truncated)
+ return true;
+ }else{
+ return false;
+ }
+ } else {
+ // Check if any other entry exists
+ $entry = $db->table('cash_deposit')
+ ->where('client_id', $client_id)
+ ->where('insurer_id', $insurer_id)
+ ->where('cd_ac_pk', $cd_ac_pk)
+ ->where('client_policy_id', $client_policy_id)
+ ->where('event_name', $event_name)
+ ->where('is_active', 1)
+ ->get()
+ ->getRowArray();
+
+ if (!empty($entry)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+}
+
+
+
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 @@
+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);
+
+ if (
+ (!in_array(get_role_id(), [1, 5])) &&
+ !(
+ in_array(MANAGEMENT_TEAM_ID, user_team()) ||
+ in_array(FINANCE_TEAM_ID, user_team()) ||
+ in_array(BUSINESS_TEAM_ID, user_team())
+ )
+ ) {
+ if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
+ $builder->where('policy_transaction.created_by', get_session_userid());
+ }
+ }
// Check if the start date and end date are provided
if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') {
@@ -1347,7 +1361,10 @@ class PolicyTransactionModel extends Model
$builder->orderBy('policy_transaction.id', 'desc');
- return $builder->get()->getResultArray();
+ $returnData = $builder->get()->getResultArray();
+
+
+ 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)
diff --git a/app/Models/TicketHistoryModel.php b/app/Models/TicketHistoryModel.php
index 6d7eb0f5..92041c8c 100644
--- a/app/Models/TicketHistoryModel.php
+++ b/app/Models/TicketHistoryModel.php
@@ -12,7 +12,7 @@ class TicketHistoryModel extends Model
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $protectFields = true;
- protected $allowedFields = ['id','field_name','display_name','old_value',
+ protected $allowedFields = ['id', "ticket_id", 'field_name','display_name','old_value',
'new_value','created_by','created_at','updated_by','updated_at','is_active'];
// Callbacks
diff --git a/app/Models/TicketMasterModel.php b/app/Models/TicketMasterModel.php
index 7fc418cb..4bd247dc 100644
--- a/app/Models/TicketMasterModel.php
+++ b/app/Models/TicketMasterModel.php
@@ -15,6 +15,7 @@ class TicketMasterModel extends Model
protected $allowedFields = [
'id',
'ticket_type_id',
+ 'feedback_json',
'claim_status_id',
'acm_id',
'insurer_id',
@@ -74,10 +75,10 @@ class TicketMasterModel extends Model
'pay_initiate_date',
'emp_personal_mail',
'client_policy_id'
-
- ];
-
-
+
+ ];
+
+
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = ["checkAndADDCreatedByValue"];
@@ -92,7 +93,7 @@ class TicketMasterModel 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();
}
@@ -103,7 +104,7 @@ class TicketMasterModel 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();
}
@@ -129,21 +130,21 @@ class TicketMasterModel extends Model
public function getTemplateDataByTicketID($ticket_id)
{
$template_data = $this
- ->select("ticket_mail_template.*, CASE
+ ->select("ticket_mail_template.*, CASE
WHEN employees.email_corporate IS NULL OR employees.email_corporate = ''
THEN ticket_master.emp_mail
ELSE employees.email_corporate
END as emp_mail, ,ticket_master.claim_status_id")
- ->join('ticket_claim_status', 'ticket_master.claim_status_id = ticket_claim_status.id and ticket_claim_status.is_active = 1')
- ->join('ticket_mail_template', '
+ ->join('ticket_claim_status', 'ticket_master.claim_status_id = ticket_claim_status.id and ticket_claim_status.is_active = 1')
+ ->join('ticket_mail_template', '
ticket_claim_status.trigger_type = ticket_mail_template.trigger_type
and ticket_claim_status.ticket_type = ticket_mail_template.ticket_type
and ticket_mail_template.is_active = 1')
- ->join('employees','employees.id = ticket_master.emp_id','left')
- ->where('ticket_master.id', $ticket_id)
- ->where('ticket_master.is_active', 1)
- ->where('ticket_claim_status.is_active', 1)
- ->first();
+ ->join('employees', 'employees.id = ticket_master.emp_id', 'left')
+ ->where('ticket_master.id', $ticket_id)
+ ->where('ticket_master.is_active', 1)
+ ->where('ticket_claim_status.is_active', 1)
+ ->first();
return $template_data;
}
@@ -172,16 +173,16 @@ class TicketMasterModel extends Model
->join('clients', 'ticket_master.client_id = clients.id', 'left')
->join('insurers', 'ticket_master.insurer_id = insurers.id', 'left')
->join('tpa', 'ticket_master.tpa_id = tpa.id', 'left')
- ->join('ticket_notes', 'ticket_master.id = ticket_notes.ticket_id and ticket_notes.is_active = 1 and ticket_notes.is_auto_query = 1','left')
+ ->join('ticket_notes', 'ticket_master.id = ticket_notes.ticket_id and ticket_notes.is_active = 1 and ticket_notes.is_auto_query = 1', 'left')
->join('user_profiles', 'ticket_master.acm_id = user_profiles.id', 'left')
- ->join('employees','employees.id = ticket_master.emp_id','left')
+ ->join('employees', 'employees.id = ticket_master.emp_id', 'left')
->where('ticket_master.id', $ticket_id)
->where('ticket_master.is_active', 1)
->first();
return $ticket_data;
}
-
+
//get TAT report BAND wise Data
// public function getTATReport($ticket_type = null, $start_date = null, $end_date = null)
// {
@@ -209,7 +210,7 @@ class TicketMasterModel extends Model
// ";
// $statusResult = $this->db->query($statusQuery)->getResultArray();
// // dd($statusResult);
-
+
// // Initialize dynamic query parts
// $dynamicSelect = '';
@@ -247,12 +248,12 @@ class TicketMasterModel extends Model
// 0
// ) AS `$columnName`, ";
// }
-
+
// // Remove the trailing comma from the SELECT part
// $dynamicSelect = rtrim($dynamicSelect, ', ');
// // dd($dynamicSelect);
-
+
// // Construct the full SQL query
// $sql = "
// SELECT
@@ -316,7 +317,7 @@ class TicketMasterModel extends Model
// ORDER BY
// FIELD(tc.TAT_Category, 'Above 20 Days', '13-20 Days', '7-12 Days', '0-6 Days');
// ";
-
+
// // Execute the query and return the result
// $data = $this->db->query($sql)->getResultArray();
// // print_rr($this->db->getLastQuery(), $data); die;
@@ -328,12 +329,12 @@ class TicketMasterModel extends Model
// // $tableData['headers'] = $headers;
// // $tableData['body'] = $data;
// // }
-
+
// return $data;
// }
public function getTATReport($ticket_type = null, $start_date = null, $end_date = null)
- {
+ {
//set default last 3 months data date
$fromDate = date('Y-m-d', strtotime('-90 days'));
$toDate = date('Y-m-d 23:59:59');
@@ -344,9 +345,9 @@ class TicketMasterModel extends Model
}
$ticket_type_data_1 = "";
$ticket_type_data_2 = "";
- if(!empty($ticket_type)){
- $ticket_type_data_1 = "AND ticket_type = $ticket_type";
- $ticket_type_data_2 = "WHERE tm.ticket_type_id = $ticket_type";
+ if (!empty($ticket_type)) {
+ $ticket_type_data_1 = "AND ticket_type = $ticket_type";
+ $ticket_type_data_2 = "WHERE tm.ticket_type_id = $ticket_type";
}
// Fetch claim statuses from the `ticket_claim_status` table
@@ -358,7 +359,7 @@ class TicketMasterModel extends Model
";
$statusResult = $this->db->query($statusQuery)->getResultArray();
// dd($statusResult);
-
+
// Initialize dynamic query parts
$dynamicSelect = '';
@@ -396,12 +397,12 @@ class TicketMasterModel extends Model
0
) AS `$columnName`, ";
}
-
+
// Remove the trailing comma from the SELECT part
$dynamicSelect = rtrim($dynamicSelect, ', ');
// dd($dynamicSelect);
-
+
// Construct the full SQL query
$sql = "
SELECT
@@ -471,7 +472,7 @@ class TicketMasterModel extends Model
'0-6 Days'
);
";
-
+
// Execute the query and return the result
$data = $this->db->query($sql)->getResultArray();
// print_rr($this->db->getLastQuery(), $data); die;
@@ -483,12 +484,13 @@ class TicketMasterModel extends Model
// $tableData['headers'] = $headers;
// $tableData['body'] = $data;
// }
-
+
return $data;
}
- public function tpaWiseReport($policy_type = null ,$start_date = null, $end_date = null){
- $ticket_type_data_1 = "";
+ public function tpaWiseReport($policy_type = null, $start_date = null, $end_date = null)
+ {
+ $ticket_type_data_1 = "";
$ticket_type_data_2 = "";
if (!empty($policy_type)) {
@@ -510,8 +512,17 @@ class TicketMasterModel extends Model
$dynamicSelect .= "
COUNT(CASE WHEN master.claim_status_id = {$status['id']} THEN master.id END) AS `{$status['claim_status']}`, ";
- if (in_array($status['claim_status'], ['ID NOT GENERATED', 'NON ID', 'CDA', 'INFORMATION REQUIRED','UNDER PROCESS - CLAIM NO. UPDATION',
- 'UNDER PROCESS - INVESTIGATION STATUS','UNDER PROCESS - QUERY DOCUMENT RECEIVED','APPROVED','PAYMENT INITIATED'])) {
+ if (in_array($status['claim_status'], [
+ 'ID NOT GENERATED',
+ 'NON ID',
+ 'CDA',
+ 'INFORMATION REQUIRED',
+ 'UNDER PROCESS - CLAIM NO. UPDATION',
+ 'UNDER PROCESS - INVESTIGATION STATUS',
+ 'UNDER PROCESS - QUERY DOCUMENT RECEIVED',
+ 'APPROVED',
+ 'PAYMENT INITIATED'
+ ])) {
$dynamicTotal .= "COUNT(CASE WHEN master.claim_status_id = {$status['id']} THEN master.id END) + ";
}
// Include in total count
@@ -552,47 +563,47 @@ class TicketMasterModel extends Model
// print_rr($result);die();
return $result;
-
}
- public function accountManagerWiseReport($policy_type = null ,$start_date = null, $end_date = null){
+ public function accountManagerWiseReport($policy_type = null, $start_date = null, $end_date = null)
+ {
if ($policy_type == 1) {
$ticket_type_data_1 = "";
- $ticket_type_data_2 = "";
+ $ticket_type_data_2 = "";
- if (!empty($policy_type)) {
- $ticket_type_data_1 = "AND ticket_type = $policy_type";
- $ticket_type_data_2 = "AND master.ticket_type_id = $policy_type";
- }
+ if (!empty($policy_type)) {
+ $ticket_type_data_1 = "AND ticket_type = $policy_type";
+ $ticket_type_data_2 = "AND master.ticket_type_id = $policy_type";
+ }
- // Fetch claim statuses dynamically
- $statusQuery = "SELECT id, claim_status FROM ticket_claim_status WHERE is_active = 1 $ticket_type_data_1";
- $statusResult = $this->db->query($statusQuery)->getResultArray();
+ // Fetch claim statuses dynamically
+ $statusQuery = "SELECT id, claim_status FROM ticket_claim_status WHERE is_active = 1 $ticket_type_data_1";
+ $statusResult = $this->db->query($statusQuery)->getResultArray();
- // Initialize dynamic query parts
- $dynamicSelect = '';
- $dynamicTotal = '';
+ // Initialize dynamic query parts
+ $dynamicSelect = '';
+ $dynamicTotal = '';
- // Loop through each claim status and generate the CASE statements
- foreach ($statusResult as $status) {
- $dynamicSelect .= "
+ // Loop through each claim status and generate the CASE statements
+ foreach ($statusResult as $status) {
+ $dynamicSelect .= "
COUNT(CASE WHEN master.claim_status_id = {$status['id']} THEN master.id END) AS `{$status['claim_status']}`, ";
- // Include in total count
- $dynamicTotal .= "COUNT(CASE WHEN master.claim_status_id = {$status['id']} THEN master.id END) + ";
+ // Include in total count
+ $dynamicTotal .= "COUNT(CASE WHEN master.claim_status_id = {$status['id']} THEN master.id END) + ";
- // Include only closed-related statuses in total2 count
+ // Include only closed-related statuses in total2 count
- }
+ }
- // Remove the trailing commas and `+` signs
- $dynamicSelect = rtrim($dynamicSelect, ', ');
- $dynamicTotal = rtrim($dynamicTotal, ' +');
- // print_rr($dynamicSelect);
- // Construct the final SQL query
- $sql = "
+ // Remove the trailing commas and `+` signs
+ $dynamicSelect = rtrim($dynamicSelect, ', ');
+ $dynamicTotal = rtrim($dynamicTotal, ' +');
+ // print_rr($dynamicSelect);
+ // Construct the final SQL query
+ $sql = "
SELECT
user_profiles.first_name AS ACM_NAME,
$dynamicSelect,
@@ -613,44 +624,49 @@ class TicketMasterModel extends Model
// dd($result);
return $result;
-
-
- }else{
+ } else {
$ticket_type_data_1 = "";
$ticket_type_data_2 = "";
-
+
if (!empty($policy_type)) {
$ticket_type_data_1 = "AND ticket_type = $policy_type";
$ticket_type_data_2 = "AND master.ticket_type_id = $policy_type";
}
-
+
// Fetch claim statuses dynamically
$statusQuery = "SELECT id, claim_status FROM ticket_claim_status WHERE is_active = 1 $ticket_type_data_1";
$statusResult = $this->db->query($statusQuery)->getResultArray();
-
+
// Initialize dynamic query parts
$dynamicSelect = '';
$dynamicTotal = '';
$dynamicClosedTotal = '';
-
+
// Loop through each claim status and generate the CASE statements
foreach ($statusResult as $status) {
$dynamicSelect .= "
COUNT(CASE WHEN master.claim_status_id = {$status['id']} THEN master.id END) AS `{$status['claim_status']}`, ";
-
- if (in_array($status['claim_status'], ['CLAIM INTIMATION', 'INTIMATION TO INSURER', 'CLIENT PENDING', 'INSURER PENDING','INVESTIGATION',
- 'APPROVED','ON HOLD'])) {
+
+ if (in_array($status['claim_status'], [
+ 'CLAIM INTIMATION',
+ 'INTIMATION TO INSURER',
+ 'CLIENT PENDING',
+ 'INSURER PENDING',
+ 'INVESTIGATION',
+ 'APPROVED',
+ 'ON HOLD'
+ ])) {
$dynamicTotal .= "COUNT(CASE WHEN master.claim_status_id = {$status['id']} THEN master.id END) + ";
}
// Include in total count
// $dynamicTotal .= "COUNT(CASE WHEN master.claim_status_id = {$status['id']} THEN master.id END) + ";
-
+
// Include only closed-related statuses in total2 count
if (in_array($status['claim_status'], ['CLOSED', 'SETTLED', 'NOT COVERED'])) {
$dynamicClosedTotal .= "COUNT(CASE WHEN master.claim_status_id = {$status['id']} THEN master.id END) + ";
}
}
-
+
// Remove the trailing commas and `+` signs
$dynamicSelect = rtrim($dynamicSelect, ', ');
$dynamicTotal = rtrim($dynamicTotal, ' +');
@@ -674,10 +690,10 @@ class TicketMasterModel extends Model
GROUP BY
user_profiles.id;
";
-
+
// Execute the query
$result = $this->db->query($sql)->getResultArray();
-
+
// print_rr($result);die();
return $result;
}
@@ -704,6 +720,82 @@ class TicketMasterModel extends Model
// dd($data, db_connect()->getLastQuery());
return $data;
}
-
-
+
+ public function getDashData($claim_statuses, $limit)
+ {
+ $finalResults = [];
+
+ foreach ($claim_statuses as $typeId => $statuses) {
+ $builder = $this->db->table('ticket_master tm');
+
+ // Start with ticket_type_id in SELECT
+ $selects = ['tm.ticket_type_id'];
+
+ // 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}`";
+ }
+
+ $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;
+
+ // 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;
+ }
+ }
+
+ // Add the result to the final array
+ $finalResults[$typeId] = $result;
+ }
+
+ return $finalResults;
+ }
}
diff --git a/app/Models/UserModel.php b/app/Models/UserModel.php
index 49b84400..ed5a8ace 100755
--- a/app/Models/UserModel.php
+++ b/app/Models/UserModel.php
@@ -134,5 +134,20 @@ class UserModel extends Model
->getResultArray();
}
+ public function getexclusiveUserListForRFQ(){
+ $data = $this->db->table('user_profiles')
+ ->select('user_profiles.*,user_teams.team_id')
+ ->select('roles.role as user_role')
+ ->join('roles', 'roles.id = user_profiles.role')
+ ->join('user_teams', 'user_teams.user_id = user_profiles.id')
+ ->get()
+ ->getResultArray();
+
+
+ // dd($data);
+
+ return $data;
+ }
+
}
?>
\ No newline at end of file
diff --git a/app/Views/DashBoard.php b/app/Views/DashBoard.php
index 3102ab15..55b75fc5 100755
--- a/app/Views/DashBoard.php
+++ b/app/Views/DashBoard.php
@@ -218,8 +218,27 @@
+
+
+
+ Claims
+
+
+
+
+
+
+ Leads and Renewals
+
+
+
+
+
+
+
+
@@ -229,6 +248,7 @@
+
diff --git a/app/Views/chatbot.php b/app/Views/chatbot.php
index 94373196..95bf5cde 100644
--- a/app/Views/chatbot.php
+++ b/app/Views/chatbot.php
@@ -41,7 +41,7 @@
origin: "mobile", // origin
emp_code:"HTL-007",
client_id:159,
- client_branch_id:125
+ client_branch_id:126
}
};
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
+
= isset($claim_data[1]['total']) ? $claim_data[1]['total'] : '0' ?>
+
+
+
+
+
+
+
+
+
+
GPA
+
= isset($claim_data[2]['total']) ? $claim_data[2]['total'] : '0' ?>
+
+
+
+
+
+
+
+
+
+
EDLI
+
= isset($claim_data[3]['total']) ? $claim_data[3]['total'] : '0' ?>
+
+
+
+
+
+
+
+
+
+
GTLI
+
= isset($claim_data[4]['total']) ? $claim_data[4]['total'] : '0' ?>
+
+
+
+
+
+
+
+
+
+
+
+
+ $statuses) : ?>
+
+
+ $count) : ?>
+
+ 20 ? substr($formattedStatus, 0, 15) . '...' : $formattedStatus;
+ $showTooltip = strlen($formattedStatus) > 20;
+ ?>
+
+
+
= $count ?>
+ >
+ = $truncatedStatus ?>
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/Views/client_api.php b/app/Views/client_api.php
new file mode 100644
index 00000000..67f93316
--- /dev/null
+++ b/app/Views/client_api.php
@@ -0,0 +1,452 @@
+
+
+
+
+
+
+ Enable API Access
+
+ id="is_api" type="checkbox" name="is_api">
+
+
+
+
+
+
+ Webhook Action
+
+
+
+ Webhook Method Type
+
+ POST
+
+
+
+ Webhook URL
+ " class="form-control" onchange="validateWebhookUrlById(this.id)" id="webhook_url2" readonly placeholder="Enter Webhook URL">
+
+
+ Token Type
+
+ Bearer Token
+
+
+
+
+ Authorization Token
+ " class="form-control" id="pull_claim_token" placeholder="Click generate to create token" readonly required>
+
+
+
+ Generate Token
+
+
+ Copy
+
+
+
+ Claim Object Type
+ = isset($api_data) ? htmlspecialchars($api_data['pull_claim_obj']) : "" ?>
+
+
+
+ Submit
+
+
+
+
+
+
+
\ 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
+
+
+
+ API
+
+
@@ -96,6 +102,7 @@ body {
+
@@ -246,7 +253,7 @@ body {
event.preventDefault();
client_notification();
});
-
+
diff --git a/app/Views/layout/header.php b/app/Views/layout/header.php
index 0abdf8d5..3491cacb 100755
--- a/app/Views/layout/header.php
+++ b/app/Views/layout/header.php
@@ -80,7 +80,17 @@
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/Views/leads_form.php b/app/Views/leads_form.php
index 003e8d96..fc2ee0f0 100644
--- a/app/Views/leads_form.php
+++ b/app/Views/leads_form.php
@@ -162,6 +162,16 @@
+
+ Source Policy Start Date
+
+
+
+
+ Source Policy End Date
+
+
+