MERGE_TEST_BDS_CLIENTS_ECARD&LIVE_ISSUES

This commit is contained in:
Ubuntu 2025-10-24 18:15:08 +05:30
commit f01148df11
40 changed files with 9486 additions and 3910 deletions

View File

@ -48,6 +48,7 @@ $routes->get("frontend_content", "AppContentManagementController::frontend_conte
$routes->get('/test', 'Home::index');
$routes->get('/check_gemini', 'Home::check_Gemini');
$routes->get('/check_gemini2', 'Home::check_gemini_2');
$routes->get('/checkPolicyDoc', 'Home::checkPolicyDoc');
$routes->get('/login', 'LoginController::index'); ///auth/google
$routes->get('/loginPos', 'LoginController::loginPos'); //login POS team
$routes->post('/getVerifyPosMobileNo', 'LoginController::getVerifyPosMobileNo'); //Verify POS team mobile no
@ -395,6 +396,10 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) {
$routes->get('getMemberDataExcelFileErrors', 'LeadsController::getMemberDataExcelFileErrors');
$routes->post('savePlacementDataAndValidateMemberDataFile', 'LeadsController::savePlacementDataAndValidateMemberDataFile');
$routes->get('checkMemberDataFileValidationStatus', 'LeadsController::checkMemberDataFileValidationStatus');
$routes->match(['get', 'post', 'delete'], 'nhanceBranchMaster', 'MasterController::nhanceBranchMaster');
$routes->match(['get', 'post', 'delete'], 'vehicleTypeMaster', 'MasterController::vehicleTypeMaster');
$routes->match(['get', 'post', 'delete'], 'rtoMaster', 'MasterController::rtoMaster');
$routes->get('checkDuplicateCdAccount', 'MasterController::checkDuplicateCdAccount');
});
$routes->post("policy_tranction/sendInstallmentRemainderMail","PolicyTransactionController::sendInstallmentRemainderMail");
@ -422,6 +427,7 @@ $routes->group("policy_tranction", ["filter" => "authMVC"], function ($routes) {
$routes->group("report", ["filter" => "authMVC"], function ($routes) {
$routes->match(['get', 'post'],"list", "PolicyTransactionController::reportBDS");
$routes->match(['get', 'post'],"listNew", "PolicyTransactionController::reportBDSNew");
$routes->get("report-varience-list", "PolicyTransactionController::reportVarience");
$routes->get("report-business-list", "PolicyTransactionController::reportBusinessList");
$routes->get("report-finance-list", "PolicyTransactionController::reportFinanceList");
@ -711,6 +717,7 @@ $routes->group('test', function($routes) {
$routes->get('mapping_client_id_and_branch_id','TestingController::mapping_client_id_and_branch_id');
$routes->get('membervalidation', 'TestingController::membervalidation');
$routes->get('generateExcel', 'TestingController::generateExcel');
$routes->get('logo_renaming','TestingController::logo_renaming');
});
$routes->cli('cli/testcli', 'TestingController::testcli');

View File

@ -518,8 +518,8 @@ class ClientController extends AdminController
public function updateEmpAndPolicyStatus()
{
$return = $this->clientPolicyModel->updateStatus();
return $return;
$this->myLogger->logme('error', 'Client Policy Status Update Count: {data}', ['data' => $return['client']]);
$this->myLogger->logme('error', 'Employee Policy Status Update Count: {data}', ['data' => $return['emp']]);
}
@ -1613,7 +1613,7 @@ class ClientController extends AdminController
if ($update) {
$policy_transaction_update = $this->deactivatePolicyTransactionsPolicy($id);
// $policy_transaction_update = $this->deactivatePolicyTransactionsPolicy($id);
return $this->respond(['status' => true, 'code' => 200], 200);
} else {
@ -4669,7 +4669,7 @@ class ClientController extends AdminController
// Additional logic for non-individual clients (client_type != 2)
$branch_insert = null;
if ($client_type != 2) {
$unit[] = $postData['short_name'] . '-' . $postData['branch_code'] ?? 001;
$unit[] = $postData['short_name'] . '-' . ($postData['branch_code'] ?? 001);
$branch_data = [
'client_id' => $client_insert,
'branch_name' => $postData['branch_name'],
@ -4816,6 +4816,7 @@ class ClientController extends AdminController
'vehicle_no' => $data['vehicle_no'],
'type' => $data['type'],
'rc' => $data['rc'],
'rto_id' => $data['rto_id'],
'branch_id' => $branch_insert,
'owner' => $client_insert,
];
@ -4861,6 +4862,7 @@ class ClientController extends AdminController
'vehicle_no' => $data['vehicle_no'],
'type' => $data['type'],
'rc' => $data['rc'],
'rto_id' => $data['rto_id'],
'branch_id' => $data['branch_id'] ?? null,
'owner' => $data['owner'],
];
@ -5064,10 +5066,12 @@ class ClientController extends AdminController
->where('policy_no', $policy_no)
->countAllResults();
$client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('policy_status', 1)->where('policy_no', trim($policy_no))->first();
if ($data > 0) {
return $this->respond(['status' => true, 'message' => 'This policy number is already linked to another client', 'data' => $data, 'code' => 409, 'received_data' => $received_data], 200);
return $this->respond(['status' => true, 'message' => 'This policy number is already linked to another client', 'data' => $data, 'code' => 409, 'received_data' => $received_data, 'client_policy_id' => $client_policy_data['id'] ?? null], 200);
} else {
return $this->respond(['status' => false, 'message' => 'No Data Found', 'code' => 404, 'received_data' => $received_data], 200);
return $this->respond(['status' => false, 'message' => 'No Data Found', 'code' => 404, 'received_data' => $received_data, 'client_policy_id' => $client_policy_data['id'] ?? null], 200);
}
}
@ -7305,7 +7309,9 @@ class ClientController extends AdminController
$pre_hr_id = $db2->table('client_branch cb')
->select('lc.id')
->join('level_contacts lc','lc.ref_id = cb.id')
->where('cb.id',$pre_branch_id)->where('cb.is_Active',1)->where('lc.is_Active',1)->get()->getResultArray()[0]['id']??"";
->where('lc.contact_type', 'client')
->where('cb.id',$pre_branch_id)->where('cb.is_Active',1)
->where('lc.is_Active',1)->get()->getResultArray()[0]['id']??"";
return $pre_hr_id;
}

View File

@ -225,20 +225,23 @@ class DashboardController extends AdminController
$pendingActionsController = new PendingActionsController;
$pendingActionsData = $pendingActionsController->getPendingActionsForDashBoard();
$businessTeamData = $this->policyTransactionModel->getBusinessReportList();
$financeTeamData = $this->policyTransactionModel->getFinanceReportList();
$businessTeamStatusData = $this->data_construct_for_bds($businessTeamData);
$financeTeamStatusData = $this->data_construct_for_bds($financeTeamData);
//BDS dashboard data
// $businessTeamData = $this->policyTransactionModel->getBusinessReportList();
// $financeTeamData = $this->policyTransactionModel->getFinanceReportList();
// $businessTeamStatusData = $this->data_construct_for_bds($businessTeamData);
// $financeTeamStatusData = $this->data_construct_for_bds($financeTeamData);
$businessTeamData = [];
$financeTeamData = [];
$businessTeamStatusData = [];
$financeTeamStatusData = [];
$data['client_branch_emp_list'] = $results;
$session = \Config\Services::session();
$session->set('enrollment_data', json_encode($data));
// echo "<pre>";
$data['pendingActionsData'] = $pendingActionsData;
$data['businessTeamCount'] = count($businessTeamData) ?? 0;
// dd($businessTeamData);
$data['financeTeamCount'] = count($financeTeamData) ?? 0;
$data['businessTeamStatusData'] = $businessTeamStatusData;
$data['financeTeamStatusData'] = $financeTeamStatusData;

View File

@ -35,7 +35,7 @@ use App\Controllers\JobWorker;
use App\Controllers\Jobs\SubJob;
use App\Controllers\EmployeeServiceController;
use App\Controllers\EmpDataServiceController;
use App\Models\ThzMasterModel;
use CodeIgniter\API\ResponseTrait;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
@ -1193,7 +1193,7 @@ class EmployeeController extends AdminController
// --------------- For E-Card Download -----------------------------------------------------------------------------------------------------
//E-CARD DOWNLOAD FUNCTION USING HTML PRINT
//E-CARD DOWNLOAD FUNCTION USING HTML PRINT ( Not in use ) do not delete
public function generateIDCardForEmployeeUsingHtml($rand_string, $people = 0)
{
// dd($rand_string, $people);
@ -1418,7 +1418,7 @@ class EmployeeController extends AdminController
echo $htmlContent;
}
//E-CARD DOWNLOAD FUNCTION USING DOM PDF ( CURRENTLY USING THIS )
//E-CARD DOWNLOAD FUNCTION USING DOM PDF ( CURRENTLY USING THIS ) Dompdf
public function generateIDCardForEmployee($rand_string, $people = 0, $mode = 0)
{
// dd($rand_string, $people);
@ -1470,7 +1470,8 @@ class EmployeeController extends AdminController
// Step 3: Prepare template path
$template_data_path = WRITEPATH . 'e_card_template/';
// $tpa_short_name = strtolower(str_replace(' ', '_', $get_emp_code_and_client_policy_id['short_name'])) . '.html';
$tpa_short_name = 'common.html';
// $tpa_short_name = 'common.html';
$tpa_short_name = 'new_ecard.html';
$final_path = $template_data_path . $tpa_short_name;
$this->myLogger->logme('error', 'Checking if template file exists at: ' . $final_path);
@ -1494,6 +1495,7 @@ class EmployeeController extends AdminController
$value['back_card'] = "Nhance_Ecard_working_1_Back.png";
$placeholders = [
'{CLIENT_NAME}' => $value['client_name'],
'{TPA_ID}' => $value['tpa_id'],
'{NAME}' => $value['name'],
@ -1505,9 +1507,6 @@ class EmployeeController extends AdminController
'{POLICY_START_DATE}' => date('d-M-Y', strtotime($value['policy_start_date'])),
'{POLICY_NO}' => $value['policy_no'],
'{INSURER_NAME}' => strtoupper($value['insurer_name']),
'{INSURER_LOGO}' => base_url() . 'public/uploads/logo/' . $value['insurer_logo'],
'{FRONT_CARD}' => base_url() . 'public/uploads/template_bg/' . $value['front_card'],
'{BACK_CARD}' => base_url() . 'public/uploads/template_bg/' . $value['back_card'],
'{EMP_ID}' => $value['emp_code'],
'{SI_AMT}' => $value['basic_cover_si'],
'{CORPORATE_NAME}' => $value['client_name'],
@ -1515,18 +1514,38 @@ class EmployeeController extends AdminController
'{TPA_NAME}' => $value['tpa_name'],
'{INSURER_BRANCH}' => $value['insurer_branch_city'],
'{RELATION}' => $value['relationship'],
'{TPA_LOGO}' => base_url() . 'public/uploads/logo/' . $value['tpa_logo'],
'{MEDI_USER}' => base_url() . 'public/e_card_imgs/medi_uesr.jpg',
'{MEDI_INSURER}' => base_url() . 'public/e_card_imgs/Magma.png',
'{MEDI_BARCODE}' => base_url() . 'public/e_card_imgs/borcode.jpeg',
'{QR_ANDROID}' => base_url() . 'public/e_card_imgs/android.png',
'{QR_IOS}' => base_url() . 'public/e_card_imgs/ios.png',
'{QR_ANDROID_2}' => base_url() . 'public/e_card_imgs/play_store.png',
'{QR_IOS_2}' => base_url() . 'public/e_card_imgs/appstore.png',
'{TPA_LOGO}' => getFileIfExists('uploads/logo/' . $value['tpa_logo']),
'{MEDI_USER}' => getFileIfExists('e_card_imgs/medi_uesr.jpg'),
'{MEDI_INSURER}' => getFileIfExists('e_card_imgs/Magma.png'),
'{MEDI_BARCODE}' => getFileIfExists('e_card_imgs/borcode.jpeg'),
'{QR_ANDROID}' => getFileIfExists('e_card_imgs/android.png'),
'{QR_IOS}' => getFileIfExists('e_card_imgs/ios.png'),
'{QR_ANDROID_2}' => getFileIfExists('e_card_imgs/play_store.png'),
'{QR_IOS_2}' => getFileIfExists('e_card_imgs/appstore.png'),
'{NHANCE_N_LOGO}' => getFileIfExists('assets/images/Nhance_Favi.png'),
'{INSURER_LOGO}' => getFileIfExists('uploads/logo/' . $value['insurer_logo']),
'{FRONT_CARD}' => getFileIfExists('uploads/template_bg/' . $value['front_card']),
'{BACK_CARD}' => getFileIfExists('uploads/template_bg/' . $value['back_card']),
// '{TPA_LOGO}' => base_url() . 'public/uploads/logo/' . $value['tpa_logo'],
// '{MEDI_USER}' => base_url() . 'public/e_card_imgs/medi_uesr.jpg',
// '{MEDI_INSURER}' => base_url() . 'public/e_card_imgs/Magma.png',
// '{MEDI_BARCODE}' => base_url() . 'public/e_card_imgs/borcode.jpeg',
// '{QR_ANDROID}' => base_url() . 'public/e_card_imgs/android.png',
// '{QR_IOS}' => base_url() . 'public/e_card_imgs/ios.png',
// '{QR_ANDROID_2}' => base_url() . 'public/e_card_imgs/play_store.png',
// '{QR_IOS_2}' => base_url() . 'public/e_card_imgs/appstore.png',
// '{NHANCE_N_LOGO}' => base_url() . 'public/assets/images/Nhance_Favi.png',
// '{INSURER_LOGO}' => base_url() . 'public/uploads/logo/' . $value['insurer_logo'],
// '{FRONT_CARD}' => base_url() . 'public/uploads/template_bg/' . $value['front_card'],
// '{BACK_CARD}' => base_url() . 'public/uploads/template_bg/' . $value['back_card'],
];
$placeholders['{LEVELS}'] = $this->generateAcmAndMForEcard($client_id);
$placeholders['{NETWORK_HOSPITAL}'] = $this->generateNetworkHospitalsForEcard($value['network_hospitals']);
foreach ($placeholders as $placeholder => $replaceValue) {
$htmlContent = str_replace($placeholder, $replaceValue, $htmlContent);
}
@ -1534,13 +1553,23 @@ class EmployeeController extends AdminController
$html .= $htmlContent;
}
// return $html;
// DomPdf
$options = new Options();
$options->set('isRemoteEnabled', true);
$options->set('isHtml5ParserEnabled', true);
$dompdf = new Dompdf($options);
$dompdf->loadHtml('<style>@page { margin: 0; }</style>' . $html); // remove the margin
// $dompdf->loadHtml('<style>@page { margin: 0; }</style>' . $html); // remove the margin
$dompdf->loadHtml('
<style>
@page { margin: 0; }
@import url("https://fonts.googleapis.com/css2?family=Lato:wght@400;700&display=swap");
body { font-family: "Lato", sans-serif !important; }
</style>
' . $html
);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
@ -2939,20 +2968,43 @@ class EmployeeController extends AdminController
// Generate the HTML content
$html = '';
$level_index = 1;
foreach ($levels as $level => $contacts) {
$displayLevel = $level == 3 ? 1 : 2; // Switch levels for display
$html .= '<br>Level ' . $displayLevel . '<br>';
if($level_index == 1){
$html .= 'Level ' . $displayLevel . '<br>';
}else{
$html .= '<br> Level ' . $displayLevel . '<br>';
}
foreach ($contacts as $index => $contact) {
$html .= ($index + 1) . '. ' . $contact['first_name'] . ' / ' . $contact['mobile'] . ' / ' . $contact['email'] . '<br>';
}
$level_index++;
}
$html .= '<br><br><br>';
$html .= '<br>';
return $html;
}
public function generateNetworkHospitalsForEcard($network_hospitals)
{
$html = "";
if (!empty($network_hospitals)) {
$html = '<div style="margin-top: 6px;">
<span style="font-weight: 500;">Network Hospital:</span>
<a href="' . $network_hospitals . '" target="_blank" style="color: #0066cc; text-decoration: none; display: inline-block; max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: bottom;">' . $network_hospitals . '</a>
</div>';
}
// For debugging
// print_r($html); die;
return $html;
}
public function getBatchFileData()
{
$file_id = $this->request->getGet('file_id');
@ -3065,7 +3117,8 @@ class EmployeeController extends AdminController
} else {
$text = "create";
$data['created_by'] = get_session_userid();
$this->thzMasterModel->insert($data);
$thzMasterModel = new ThzMasterModel();
$thzMasterModel->insert($data);
$insertID = $this->partnerEndorsementRequestModel->insertID();
$result = true;
}

View File

@ -60,6 +60,8 @@ class Home extends PublicController
//print_rr($data);
}
//for insurer statement upload
public function check_gemini_2()
{
@ -158,6 +160,143 @@ class Home extends PublicController
// The final JSON payload
$data = [
"contents" => [
$content_parts
]
];
// Encode the data to a JSON string
$json_data = json_encode($data);
// Initialize cURL
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); // Set the Content-Type header
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data); // Set the JSON payload
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Optional: to bypass SSL verification if needed (not recommended for production)
// Execute the cURL request and get the response
$response = curl_exec($ch);
// Check for cURL errors
if (curl_errno($ch)) {
echo 'cURL Error: ' . curl_error($ch);
}
// Close the cURL handle
curl_close($ch);
// Decode the JSON response
$responseData = json_decode($response, true);
echo '<pre>';
print_r($responseData);
echo '<pre>';
// Check if the response contains generated text
if (isset($responseData['candidates'][0]['content']['parts'][0]['text'])) {
$generatedText = $responseData['candidates'][0]['content']['parts'][0]['text'];
echo "Generated Text: " . $generatedText;
} else {
echo "Error or no text generated. Response: " . $response;
}
}
//for insurer policy doc upload
public function checkPolicyDoc()
{
// $this->convertToPdf();die();
// Replace with your actual Gemini API key
$apiKey = 'AIzaSyBbx-uotRBqkYhqLpmD60420E_a0G0duP8';
// The model to use and the API endpoint
$model = "gemini-pro";
$model = "gemini-2.5-flash";
// $model = "gemini-1.5-pro";
// $model = "gemini-1.5-pro";
$url = "https://generativelanguage.googleapis.com/v1beta/models/{$model}:generateContent?key={$apiKey}";
$filePath = 'C:\Users\Venba\AppData\Local\Programs\Python\pyenv\pdfreader\bike-0904023124P114268957.pdf';
$filePath = 'C:\Users\Venba\AppData\Local\Programs\Python\pyenv\pdfreader\car-insurance-0904023124P114213011.pdf';
// Check if the file exists
if (!file_exists($filePath)) {
die("Error: File not found at {$filePath}");
}
// Get the file's MIME type using the finfo extension
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $filePath);
finfo_close($finfo);
// print_r($mimeType);die();
// Define supported inline MIME types
$supportedInlineMimeTypes = ['application/pdf','text/csv'];
// Read the file content and encode it to Base64
$fileContent = file_get_contents($filePath);
$base64Content = base64_encode($fileContent);
// The prompt you want to send to the model
// $prompt = "give me a json with emp data like name,age,dob,mobile and email. only json not any explanations";
$prompt = "Read the following motor policy pdf document and convert into JSON format as sample specified. Give me only JSON,not any explanations.";
$prompt .= '"{\"policy\":{\"policy_number\":\"\",\"issue_date\":\"\",\"period\":{\"start\":\"\",\"end\":\"\"},\"insurer\":\"\",\"previous_policy_number\":\"\"},\"insured\":{\"name\":\"\",\"father_name\":\"\",\"address\":[\"\"],\"mobile\":\"\",\"id_proofs\":{\"aadhaar\":\"\",\"pan\":\"\"}},\"vehicle\":{\"reg_no\":\"\",\"engine_no\":\"\",\"chassis_no\":\"\",\"make\":\"\",\"model\":\"\",\"year\":\"\",\"cubic_capacity\":\"\",\"vehicle_type\":\"\"},\"rto\":\"\",\"premium\":{\"tp\":0,\"od\":0,\"pa_od\":0,\"taxes\":{},\"total\":0,\"in_words\":\"\"},\"endorsements\":[{\"code\":\"\",\"desc\":\"\"}]}"';
$payloadPart = null;
// The text part of the prompt
$text_part = [
"text" => $prompt
];
// Conditionally handle the file upload based on MIME type
if (in_array($mimeType, $supportedInlineMimeTypes)) {
echo "Detected supported format inline MIME type ({$mimeType})";
// Handle PDF as inline data
$fileContent = file_get_contents($filePath);
$base64Content = base64_encode($fileContent);
$payloadPart = [
"inlineData" => [
"mimeType" => $mimeType,
"data" => $base64Content
]
];
$content_parts = [
"parts" => [
$text_part,
$payloadPart
]
];
} else {
// Handle Excel/CSV using the Files API
echo "Detected unsupported inline MIME type ({$mimeType}). Uploading via Files API...\n";
$fileInfo = $this->uploadFileToGemini($filePath, $apiKey); // Pass apiKey
print_r($fileInfo);
// The file part, using the URI from the Files API upload
$file_part = [
"fileData" => [
"fileUri" => $fileInfo['uri'],
"mimeType" => $fileInfo['mimeType']
]
];
// The full content array, containing both parts
$content_parts = [
"parts" => [
$text_part,
$file_part
]
];
}
// The final JSON payload
$data = [
"contents" => [

View File

@ -1024,14 +1024,7 @@ class LeadsController extends BaseController
// 3. Optimize lead data query with specific field selection
$lead_data = $this->leadsModel
->select('
leads.id,
leads.policy_type_id,
leads.lead_type,
leads.source_policy_id,
leads.policy_end_date,
leads.lead_form_type,
leads.created_by,
leads.client_name,
leads.*,
lead_files.status as demography_file_status,
policy_type.question_json,
policy_type.policy_type,
@ -1776,6 +1769,24 @@ class LeadsController extends BaseController
// dd($rfq_data, $lead_id, $type, $propsal_and_insurer);
// print_r($propsal_and_insurer); die;
// print_r($is_placement); die;
$data = json_decode($rfq_data['json'], true);
$sheetName = 'Worksheet';
if ($type == 2) {
$sheetName = 'QCR';
// $propsal_and_insurer = "Proposal 1-ICICIPRU-ICICI001";
$data = $this->convertJsonForQCR($data, $type);
if ($propsal_and_insurer !== null) {
list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2);
$data = $this->transformProposelData($data, $proposal_key, $insurer_key);
$is_placement = true;
$sheetName = 'Placement';
}
} else if ($type == 1) {
$sheetName = 'RFQ';
$data = $this->convertJsonForQCR($data, $type);
} // dd($data);
if ($rfq_data['lead_type'] == 1) {
@ -1808,36 +1819,71 @@ class LeadsController extends BaseController
} else {
if (in_array($rfq_data['policy_type_id'], [2, 3, 4, 5])) {
$lead_data = [
if($is_placement == true){
$lead_data = [
'Insured' => $rfq_data['client_name'],
'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "",
'Insured' => $rfq_data['client_name'],
'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "",
// 'No of Employees at Inception' => $rfq_data['incept_emp_count'],
// 'No of Dependents at Inception' => $rfq_data['incept_dept_count'],
// 'Total Lives at Inception ' => $rfq_data['incept_no_of_lives'],
// 'No of Employees at Inception' => $rfq_data['incept_emp_count'],
// 'No of Dependents at Inception' => $rfq_data['incept_dept_count'],
// 'Total Lives at Inception ' => $rfq_data['incept_no_of_lives'],
// 'No of Employees at Expiry' => $rfq_data['exp_emp_count'],
// 'No of Dependents at Expiry' => $rfq_data['exp_dept_count'],
// 'Total Lives at Expiry ' => $rfq_data['exp_no_of_lives'],
// 'No of Employees at Expiry' => $rfq_data['exp_emp_count'],
// 'No of Dependents at Expiry' => $rfq_data['exp_dept_count'],
// 'Total Lives at Expiry ' => $rfq_data['exp_no_of_lives'],
'No of Employees at Renewal' => $rfq_data['renewal_emp_count'],
'No of Dependents at Renewal' => $rfq_data['renewal_dept_count'],
'Total Lives at Renewal ' => $rfq_data['renewal_no_of_lives'],
'No of Employees at Renewal' => $rfq_data['renewal_emp_count'],
'No of Dependents at Renewal' => $rfq_data['renewal_dept_count'],
'Total Lives at Renewal ' => $rfq_data['renewal_no_of_lives'],
'Period of Insurance ' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided",
'Insurer' => $rfq_data['insurer_name'] ?? " - ",
'TPA' => $rfq_data['tpa_name'] ?? " - ",
'Period of Insurance ' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided",
'Insurer' => $rfq_data['insurer_name'] ?? " - ",
'TPA' => $rfq_data['tpa_name'] ?? " - ",
// 'Policy Run Days' => $rfq_data['policy_run_days'],
// 'Inception Premium' => formatIndianCurrency($rfq_data['premium_at_inception']),
// 'Premium as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => formatIndianCurrency($rfq_data['premium_date']),
// 'Earned Premium' => formatIndianCurrency(intval($rfq_data['earned_premium'])),
// 'Incurred Claims as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => formatIndianCurrency($rfq_data['incurred_claims']),
// 'Annualised Claims' => formatIndianCurrency(intval($rfq_data['annualised_claims'])),
// 'Incurred Claims Ratio' => $rfq_data['incurred_claims_ratio'] . " %",
// 'Earned Claims Ratio' => $rfq_data['earned_claims_ratio'] . " %",
];
// 'Policy Run Days' => $rfq_data['policy_run_days'],
// 'Inception Premium' => formatIndianCurrency($rfq_data['premium_at_inception']),
// 'Premium as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => formatIndianCurrency($rfq_data['premium_date']),
// 'Earned Premium' => formatIndianCurrency(intval($rfq_data['earned_premium'])),
// 'Incurred Claims as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => formatIndianCurrency($rfq_data['incurred_claims']),
// 'Annualised Claims' => formatIndianCurrency(intval($rfq_data['annualised_claims'])),
// 'Incurred Claims Ratio' => $rfq_data['incurred_claims_ratio'] . " %",
// 'Earned Claims Ratio' => $rfq_data['earned_claims_ratio'] . " %",
];
}else{
$lead_data = [
'Insured' => $rfq_data['client_name'],
'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "",
'No of Employees at Inception' => $is_placement ? '-' : $rfq_data['incept_emp_count'],
'No of Dependents at Inception' => $is_placement ? '-' : $rfq_data['incept_dept_count'],
'Total Lives at Inception ' => $is_placement ? '-' : $rfq_data['incept_no_of_lives'],
'No of Employees at Expiry' => $is_placement ? '-' : $rfq_data['exp_emp_count'],
'No of Dependents at Expiry' => $is_placement ? '-' : $rfq_data['exp_dept_count'],
'Total Lives at Expiry ' => $is_placement ? '-' : $rfq_data['exp_no_of_lives'],
'No of Employees at Renewal' => $rfq_data['renewal_emp_count'],
'No of Dependents at Renewal' => $rfq_data['renewal_dept_count'],
'Total Lives at Renewal ' => $rfq_data['renewal_no_of_lives'],
'Period of Insurance ' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date'])
? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date']))
: "To be decided",
'Insurer' => $rfq_data['insurer_name'] ?? " - ",
'TPA' => $rfq_data['tpa_name'] ?? " - ",
'Policy Run Days' => $is_placement ? '-' : $rfq_data['policy_run_days'],
'Inception Premium' => $is_placement ? '-' : formatIndianCurrency($rfq_data['premium_at_inception']),
'Premium as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => $is_placement ? '-' : formatIndianCurrency($rfq_data['premium_date']),
'Earned Premium' => $is_placement ? '-' : formatIndianCurrency(intval($rfq_data['earned_premium'])),
'Incurred Claims as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => $is_placement ? '-' : formatIndianCurrency($rfq_data['incurred_claims']),
'Annualised Claims' => $is_placement ? '-' : formatIndianCurrency(intval($rfq_data['annualised_claims'])),
'Incurred Claims Ratio' => $is_placement ? '-' : $rfq_data['incurred_claims_ratio'] . " %",
'Earned Claims Ratio' => $is_placement ? '-' : $rfq_data['earned_claims_ratio'] . " %",
];
}
} else if (in_array($rfq_data['policy_type_id'], [1, 6, 7])) {
$lead_data = [
@ -1857,27 +1903,8 @@ class LeadsController extends BaseController
];
}
}
// print_r($lead_data); die;
$data = json_decode($rfq_data['json'], true);
// dd($data);
$sheetName = 'Worksheet';
if ($type == 2) {
$sheetName = 'QCR';
// $propsal_and_insurer = "Proposal 1-ICICIPRU-ICICI001";
$data = $this->convertJsonForQCR($data, $type);
if ($propsal_and_insurer !== null) {
list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2);
$data = $this->transformProposelData($data, $proposal_key, $insurer_key);
$is_placement = true;
$sheetName = 'Placement';
}
} else if ($type == 1) {
$sheetName = 'RFQ';
$data = $this->convertJsonForQCR($data, $type);
// dd($data);
}
// dd($data);
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();

View File

@ -33,8 +33,11 @@ use App\Models\ClientDepositModel;
use App\Models\EmployeePolicyModel;
use App\Models\FileModel;
use App\Models\InsurerExcelExportTemplateModel;
use App\Models\NhanceBranchModel;
use App\Models\SettingsModel;
use App\Models\VehicleModel;
use App\Models\VehicleTypeModel;
use App\Models\RTOModel;
use CodeIgniter\CLI\CLI;
@ -1347,6 +1350,16 @@ class MasterController extends AdminController
// === INSERT ===
if (empty($id)) {
$cd_acc_count = $this->CDMasterModel->where('is_active', 1)
->where('client_id', $data['client_id'])
->where('insurer_id', $data['insurer_id'])
->where('insurer_branch_id', $data['insurer_branch_id'])
->countAllResults();
if($cd_acc_count > 0){
return $this->respond(['status' => false, 'message' => 'A CD account has already been created for this client, insurer, and insurer branch combination.'], 200);
}
$this->myLogger->logme("error", 'Performing INSERT operation.');
$insert = $this->CDMasterModel->insert($data);
$this->myLogger->logme("error", 'Insert result: ' . json_encode($insert));
@ -1571,6 +1584,15 @@ class MasterController extends AdminController
$data['insurer_branch_id'] = $insurer_branch_id;
$cd_acc_count = $this->CDMasterModel->where('is_active', 1)
->where('client_id', $data['client_id'])
->where('insurer_id', $data['insurer_id'])
->where('insurer_branch_id', $data['insurer_branch_id'])
->countAllResults();
if($cd_acc_count > 0){
return $this->respond(['status' => false, 'message' => 'A CD account has already been created for this client, insurer, and insurer branch combination.'], 200);
}
// array with data for CD Traction table
$cd_tranction_data = [
@ -1614,11 +1636,30 @@ class MasterController extends AdminController
}
}
public function checkDuplicateCdAccount()
{
$data = $this->request->getGet();
$cd_acc_count = $this->CDMasterModel
->where('is_active', 1)
->where('client_id', $data['client_id'])
->where('insurer_id', $data['insurer_id'])
->where('insurer_branch_id', $data['insurer_branch_id'])
->countAllResults();
if($cd_acc_count > 0){
return $this->respond(['status' => false, 'message' => 'A CD account has already been created for this client, insurer, and insurer branch combination.'], 200);
}else{
return $this->respond(['status' => true], 200);
}
}
//Vehicle Master data Function
public function VehicleMasterList()
{ $data['tab_name'] = 'Vehicle Master';
{
$data['tab_name'] = 'Vehicle Master';
$data['page_name'] = 'Vehicles';
$data['vehicle_type'] = [
'two_wheeler' => 'Two Wheeler',
@ -2020,4 +2061,255 @@ class MasterController extends AdminController
dd($result);
}
//----------------------------------------------------------------------------------------------------------
public function nhanceBranchMaster()
{
$nhanceBranchModel = new NhanceBranchModel();
$method = $this->request->getMethod();
$data['tab_name'] = 'Nhance Branch';
$data['page_name'] = 'Nhance Branchs';
if ($method === 'post') {
$id = $this->request->getPost('pk') ?? null;
$data = $this->request->getPost();
if (empty($id)) {
$update_status = $nhanceBranchModel->insert($data);
} else {
$update_status = $nhanceBranchModel->where('id', $id)->set($data)->update();
}
if ($update_status) {
return $this->respond([
'status' => true,
'code' => 200,
'message' => 'Nhance Branch Master updated successfully',
'data' => $data
], 200);
} else {
return $this->respond([
'status' => false,
'code' => 400,
'message' => 'Failed to update',
'data' => $data
], 200);
}
} elseif ($method === 'get') {
$id = $this->request->getGet('pk') ?? null;
if (!empty($id)) {
$data = $nhanceBranchModel->where('is_active', 1)->where('id', $id)->findAll();
if (!empty($data)) {
return $this->respond(['status' => true, 'code' => 200, 'data' => $data], 200);
} else {
return $this->respond(['status' => false, 'code' => 400, 'message' => 'No data found'], 200);
}
}
$data = $nhanceBranchModel->where('is_active', 1)->orderBy('id', 'DESC')->findAll();
return $this->loadLayout('nhance_branch_list', ['data' => $data]);
} elseif ($method === 'delete') {
$input = $this->request->getRawInput();
$id = $input['pk'] ?? null;
if (empty($id)) {
return $this->respond([
'status' => false,
'code' => 404,
'message' => 'No ID provided for deletion'
], 200);
}
$update_status = $nhanceBranchModel->where('id', $id)->set(['is_active' => 0])->update();
if ($update_status) {
return $this->respond([
'status' => true,
'code' => 200,
'message' => 'Data removed successfully',
'pk' => $id
], 200);
} else {
return $this->respond([
'status' => false,
'code' => 400,
'message' => 'Failed to remove data',
'pk' => $id
], 200);
}
}
}
public function vehicleTypeMaster()
{
$vehicleTypeModel = new VehicleTypeModel();
$method = $this->request->getMethod();
$data['tab_name'] = 'Vehicle Type';
$data['page_name'] = 'Vehicle Types';
if ($method === 'post') {
$id = $this->request->getPost('pk') ?? null;
$data = $this->request->getPost();
if (empty($id)) {
$update_status = $vehicleTypeModel->insert($data);
} else {
$update_status = $vehicleTypeModel->where('id', $id)->set($data)->update();
}
if ($update_status) {
return $this->respond([
'status' => true,
'code' => 200,
'message' => 'Vehicle Type Master updated successfully',
'data' => $data
], 200);
} else {
return $this->respond([
'status' => false,
'code' => 400,
'message' => 'Failed to update',
'data' => $data
], 200);
}
} elseif ($method === 'get') {
$id = $this->request->getGet('pk') ?? null;
if (!empty($id)) {
$data = $vehicleTypeModel->where('is_active', 1)->where('id', $id)->findAll();
if (!empty($data)) {
return $this->respond(['status' => true, 'code' => 200, 'data' => $data], 200);
} else {
return $this->respond(['status' => false, 'code' => 400, 'message' => 'No data found'], 200);
}
}
$data = $vehicleTypeModel->where('is_active', 1)->orderBy('id', 'DESC')->findAll();
return $this->loadLayout('vehicle_type_master_list', ['data' => $data]);
} elseif ($method === 'delete') {
$input = $this->request->getRawInput();
$id = $input['pk'] ?? null;
if (empty($id)) {
return $this->respond([
'status' => false,
'code' => 404,
'message' => 'No ID provided for deletion'
], 200);
}
$update_status = $vehicleTypeModel->where('id', $id)->set(['is_active' => 0])->update();
if ($update_status) {
return $this->respond([
'status' => true,
'code' => 200,
'message' => 'Data removed successfully',
'pk' => $id
], 200);
} else {
return $this->respond([
'status' => false,
'code' => 400,
'message' => 'Failed to remove data',
'pk' => $id
], 200);
}
}
}
public function rtoMaster()
{
$rtoModel = new RTOModel();
$method = $this->request->getMethod();
$data['tab_name'] = 'RTO';
$data['page_name'] = 'RTO';
if ($method === 'post') {
$id = $this->request->getPost('pk') ?? null;
$data = $this->request->getPost();
if (empty($id)) {
$update_status = $rtoModel->insert($data);
} else {
$update_status = $rtoModel->where('id', $id)->set($data)->update();
}
if ($update_status) {
return $this->respond([
'status' => true,
'code' => 200,
'message' => 'RTO Master updated successfully',
'data' => $data
], 200);
} else {
return $this->respond([
'status' => false,
'code' => 400,
'message' => 'Failed to update',
'data' => $data
], 200);
}
} elseif ($method === 'get') {
$id = $this->request->getGet('pk') ?? null;
if (!empty($id)) {
$data = $rtoModel->where('is_active', 1)->where('id', $id)->findAll();
if (!empty($data)) {
return $this->respond(['status' => true, 'code' => 200, 'data' => $data], 200);
} else {
return $this->respond(['status' => false, 'code' => 400, 'message' => 'No data found'], 200);
}
}
$data = $rtoModel->where('is_active', 1)->orderBy('id', 'DESC')->findAll();
return $this->loadLayout('rto_master_list', ['data' => $data]);
} elseif ($method === 'delete') {
$input = $this->request->getRawInput();
$id = $input['pk'] ?? null;
if (empty($id)) {
return $this->respond([
'status' => false,
'code' => 404,
'message' => 'No ID provided for deletion'
], 200);
}
$update_status = $rtoModel->where('id', $id)->set(['is_active' => 0])->update();
if ($update_status) {
return $this->respond([
'status' => true,
'code' => 200,
'message' => 'Data removed successfully',
'pk' => $id
], 200);
} else {
return $this->respond([
'status' => false,
'code' => 400,
'message' => 'Failed to remove data',
'pk' => $id
], 200);
}
}
}
}

View File

@ -113,7 +113,8 @@ class PolicyTransactionController extends BaseController
// Policy Transaction Inception
public function viewInception()
{
{
$bds_edit_pt_id = $this->request->getGet('pt_id') ?? null;
$data['tab_name'] = 'Policy';
$data['page_name'] = 'Policy';
@ -151,6 +152,8 @@ class PolicyTransactionController extends BaseController
// 'bicycle' => 'Bicycle'
// ];
$data['vehicle_type'] = db_connect()->table('vehicle_type')->where('is_active', 1)->get()->getResultArray();
$data['rto_details'] = db_connect()->table('rto_master')->where('is_active', 1)->get()->getResultArray();
$data['vehicle_des'] = [
'commercial' => 'Commercial',
'private' => 'Private',
@ -181,34 +184,38 @@ class PolicyTransactionController extends BaseController
$issuer = empty($issuer) ? 0 : $issuer;
$status = empty($status) ? 0 : $status; // Corrected from `$issuer`
if ($this->request->is('get')) {
if(empty($bds_edit_pt_id)){
if ($this->request->is('get')) {
// Fetch inception data list
$data['inception_data_list'] = $this->policyTransactionModel->getInceptionTranctionListData(
$start_date,
$end_date,
$client_id,
$insurer_id,
$policy_type_id,
$date_type,
$issuer,
$status
);
} else {
// Fetch inception data list
$data['inception_data_list'] = $this->policyTransactionModel->getInceptionTranctionListData(
$start_date,
$end_date,
$client_id,
$insurer_id,
$policy_type_id,
$date_type,
$issuer,
$status
);
} else {
$ids = $this->request->getPost('ids');
$ids = array_filter(explode(',', $ids));
$data['inception_data_list'] = $this->policyTransactionModel->getInceptionTranctionListData(
$start_date = 0,
$end_date = 0,
$client_id = 0,
$insurer_id = 0,
$policy_type_id = 0,
$date_type = 0,
$issuer = 0,
$status = 0,
$ids
);
$ids = $this->request->getPost('ids');
$ids = array_filter(explode(',', $ids));
$data['inception_data_list'] = $this->policyTransactionModel->getInceptionTranctionListData(
$start_date = 0,
$end_date = 0,
$client_id = 0,
$insurer_id = 0,
$policy_type_id = 0,
$date_type = 0,
$issuer = 0,
$status = 0,
$ids
);
}
}else{
$data['inception_data_list'] = [];
}
@ -261,6 +268,7 @@ class PolicyTransactionController extends BaseController
$data = $this->preparePolicyData();
$data['cd_ac_pk'] = $this->request->getPost('cd_ac_no');
$data['issuer'] = 2;
$data['status'] = 'completed';
$this->myLogger->logme('error', 'Policy Trancaction modified form data ( insert data ) : '. json_encode($data));
@ -276,7 +284,6 @@ class PolicyTransactionController extends BaseController
$data = $this->request->getPost();
// print_r($data); die;
// var_dump($data); die;
if (empty($data['policy_issue_date'])) {
$data['policy_issue_date'] = null;
@ -304,7 +311,6 @@ class PolicyTransactionController extends BaseController
$data['last_action_date'] = change_date_format($data['last_action_date']);
}
// Separate Insurer and TPA Branch IDs and IDs
if (isset($data['insurer_id']) && !empty($data['insurer_id'])) {
list($data['insurer_branch_id'], $data['insurer_id']) = explode('-', $data['insurer_id']);
@ -373,6 +379,7 @@ class PolicyTransactionController extends BaseController
$pt_co_share_details = $this->insertOrUpdateCoShareDetails($data, $insert);
$client_policy_id = null;
if ($data['ct_type'] == 2) {
$client_policy_insert_data = $this->prepareClientPolicyInsertData($data);
$client_policy_id = $this->clientPolicyModel->insert($client_policy_insert_data);
@ -381,7 +388,7 @@ class PolicyTransactionController extends BaseController
}
if ($data['client_type'] == 1 && $data['status'] == 'completed' && $data['is_cd_reduce_from_bds'] == 1) {
$this->processCompletedStatus($data, $client_policy_id, $data['insurer_id']);
$this->processCompletedStatus($data, $client_policy_id, $data['insurer_id'], $insert);
}
}
@ -391,7 +398,6 @@ class PolicyTransactionController extends BaseController
$clientController = new ClientController();
$data['client_kyc_primary_table'] = $clientController->generateKycPrimaryTable($data['client_id']);
$data['client_kyc_other_table'] = $clientController->generateKycOthersTable($data['client_id']);
$data['entity_type_id'] = $client_data['entity_type_id'];
return $this->respondSuccess($insert, "Policy transaction created successfully", $data);
@ -432,20 +438,20 @@ class PolicyTransactionController extends BaseController
}
}
if($old_pt_data['status'] != "completed"){
if ($data['status'] == 'completed' && $data['ct_type'] == 2) {
if ($data['client_type'] == 1 && $data['is_cd_reduce_from_bds'] == 1) {
$this->processCompletedStatus($data, $data['client_policy_id'], $data['insurer_id']);
}
}
}
// if($old_pt_data['status'] != "completed"){
// if ($data['status'] == 'completed' && $data['ct_type'] == 2) {
// if ($data['client_type'] == 1 && $data['is_cd_reduce_from_bds'] == 1) {
// $this->processCompletedStatus($data, $data['client_policy_id'], $data['insurer_id'], $id);
// }
// }
// }
$data['pt_co_share_details'] = $this->PTCOShareDetailsModel->where('pt_id', $id)->where('is_active', 1)->findAll();
}
if(isset($data['cd_amt_changed']) && !empty($data['cd_amt_changed'])){
$policy_data = $this->policyTransactionModel->where('is_active', 1)->where('id', $id)->first();
$this->cdCorrection($policy_data, $data['cd_amt_changed']);
$this->cdCorrection($policy_data, $data['cd_amt_changed'], $id);
}
$client_data = $this->clientModel->where('id', $data['client_id'])->first();
@ -467,10 +473,6 @@ class PolicyTransactionController extends BaseController
{
// Prepare data for insertion and updating
$coShareDetails = [];
// print_r($data); die;
// die;
if (isset($data['co_share_id']) && !empty($data['co_share_id'])) {
$this->removePtCoShareRecords($data['co_share_id'], $pt_id);
}
@ -564,7 +566,6 @@ class PolicyTransactionController extends BaseController
}
// print_r($this->PTCOShareDetailsModel->getLastQuery()); die;
// print_r($coShareDetails);
// die;
@ -594,6 +595,7 @@ class PolicyTransactionController extends BaseController
'client_branch_id' => $data['client_branch_id'] ?? 0,
'cd_ac_pk' => $data['cd_ac_no'] ?? null,
'gst' => 18,
'policy_entry_from' => 2,
];
}
@ -609,7 +611,7 @@ class PolicyTransactionController extends BaseController
$this->policyTransactionStatusModel->insert($statusData);
}
private function processCompletedStatus($data, $client_policy_id, $insurer_id)
private function processCompletedStatus($data, $client_policy_id, $insurer_id, $policyTranId)
{
$totalAmount = (int)$data['total'][0] ?? 0;
$description = 'The following amount of Rs. ' . $totalAmount . '/- has been debited for the ' . $data['emp_count'] . ' employees at Inception (BDS).';
@ -627,13 +629,19 @@ class PolicyTransactionController extends BaseController
'updated_by' => get_session_userid(),
'event_name' => 'inception',
'is_active' => 1,
'cd_ac_pk' => $data['cd_ac_pk']
'cd_ac_pk' => $data['cd_ac_pk'],
'pt_id' => $policyTranId ?? null,
];
DepositHelper::saveDeposit($cdTransactionData, get_session_userid());
$result = DepositHelper::saveDeposit($cdTransactionData, get_session_userid());
if(isset($result) && $result['success'] == true){
$update_data['ct_tran_id'] = $result['insert_id'];
$this->policyTransactionModel->where('id', $policyTranId)->set($update_data)->update();
}
}
private function cdCorrection($data, $amt)
private function cdCorrection($data, $amt, $policyTranId)
{
$totalAmount = (int)($amt ?? 0);
$description = 'The following amount of Rs. ' . $totalAmount . '/- has been debited towards the difference arising from the change in the BDS base premium.';
@ -651,7 +659,8 @@ class PolicyTransactionController extends BaseController
'updated_by' => get_session_userid(),
'event_name' => 'inception',
'is_active' => 1,
'cd_ac_pk' => $data['cd_ac_pk']
'cd_ac_pk' => $data['cd_ac_pk'],
'pt_id' => $policyTranId ?? null,
];
DepositHelper::saveDeposit($cdTransactionData, get_session_userid());
@ -1025,20 +1034,28 @@ class PolicyTransactionController extends BaseController
}
}
public function removePolicyTransaction($id)
{
public function removePolicyTransaction($id, $type = 0)
{
if ($id) {
$data['is_active'] = 0;
$policy_transaction_data = $this->policyTransactionModel->where('id', $id)->first();
if($policy_transaction_data['policy_type_id'] > 7){
if($policy_transaction_data['policy_type_id'] > 7 && $type == 0){
$this->policyTransactionModel->where('id', $id)->set($data)->update();
$this->PTCOShareDetailsModel->where('pt_id', $id)->set($data)->update();
$this->clientPolicyModel->where('id', $policy_transaction_data['client_policy_id'])->set($data)->update();
$this->policyTransactionModel->where('client_policy_id', $policy_transaction_data['client_policy_id'])->set($data)->update();
$cd_transaction_model = new ClientDepositModel();
$cd_transaction_model->where('policy_transaction_id', $id)->set($data)->update();
}else{
$this->policyTransactionModel->where('id', $id)->set($data)->update();
$this->PTCOShareDetailsModel->where('pt_id', $id)->set($data)->update();
$cd_transaction_model = new ClientDepositModel();
$cd_transaction_model->where('policy_transaction_id', $id)->set($data)->update();
}
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Policy Transaction removed successfully'], 200);
} else {
@ -1075,7 +1092,7 @@ class PolicyTransactionController extends BaseController
{
// echo '<pre>';
// !dd($this->getEndorsementDataForEdit(17));
$bds_edit_pt_id = $this->request->getGet('pt_id') ?? null;
$data['tab_name'] = 'Endorsement';
$data['page_name'] = 'Endorsement';
$data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
@ -1142,8 +1159,11 @@ class PolicyTransactionController extends BaseController
$issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;
$status = (!isset($issuer) || $status === '' || $status === null) ? 0 : $status;
$data['endorsement_data_list'] = $this->policyTransactionModel->getEndorsementTranctionListData($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status);
if($bds_edit_pt_id == null){
$data['endorsement_data_list'] = $this->policyTransactionModel->getEndorsementTranctionListData($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status);
}else{
$data['endorsement_data_list'] = [];
}
$data['client'] = $this->clientModel->where('is_active', 1)->findAll();
$data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll();
@ -1166,6 +1186,7 @@ class PolicyTransactionController extends BaseController
{
$id = $this->request->getPost('id');
$data = $this->preparePolicyTransactionData();
$data['status'] = 'completed';
// print_r($data); die;
if (!$id) {
@ -1250,9 +1271,10 @@ class PolicyTransactionController extends BaseController
$data['tsi'] = generate_tsi_code($issue_type['issue_type'] ?? 1);
$client_branch_id = $data['client_branch_id'];
if ($data['client_branch_id'] == "") {
if (!isset($data['client_branch_id']) || $data['client_branch_id'] == "") {
$client_branch_id = $issue_type['client_branch_id'];
}else{
$client_branch_id = $data['client_branch_id'];
}
$data['is_cd_reduce_from_bds'] = (isset($issue_type['policy_type_id']) && $issue_type['policy_type_id'] > 7 && $data['client_type'] == 1) ? 1 : 0;
@ -1333,9 +1355,9 @@ class PolicyTransactionController extends BaseController
if ($update) {
$this->insertTransactionStatus($id, $data, 1);
if($old_endorse_data['status'] != "completed"){
$this->handleCompletedStatus($data, $id);
}
// if($old_endorse_data['status'] != "completed"){
// $this->handleCompletedStatus($data, $id);
// }
$this->insertOrUpdateCoShareDetails($data, $id);
@ -1346,30 +1368,40 @@ class PolicyTransactionController extends BaseController
}
private function handleCompletedStatus($data, $policy_tran_id)
{
{
if ($data['client_type'] == 1 && $data['status'] == 'completed' && $data['is_cd_reduce_from_bds'] == 1) {
$tolamt = (int) $data['total'][0] ?? 0;
$description = 'The following amount of Rs. ' . round($tolamt, 2) . '/- has been' .
($data['action_type'] == 'deletion' ? ' Credit ' : ' Debit ') . 'from the policy transaction (BDS)';
$cd_tranction_data = [
'amount' => $tolamt,
'sub_type_id' => $data['action_type'] == 'deletion' ? 3 : 4,
'client_id' => $data['client_id'],
'client_policy_id' => $data['client_policy_id'],
'endorsement_no' => null,
'cd_ac_no' => $data['cd_ac_no'] ?? null,
'insurer_id' => $data['insurer_id'],
'description' => $description,
'transaction_type' => $data['action_type'] == 'deletion' ? 'Credit' : 'Debit',
'updated_by' => get_session_userid(),
'event_name' => $data['action_type'],
'is_active' => 1,
'cd_ac_pk' => $data['cd_ac_pk'] ?? null,
];
if(!empty($tolamt)){
$description = 'The following amount of Rs. ' . round($tolamt, 2) . '/- has been' .
($data['action_type'] == 'deletion' ? ' Credit ' : ' Debit ') . 'from the policy transaction (BDS)';
$cd_tranction_data = [
'amount' => abs($tolamt),
'sub_type_id' => $data['action_type'] == 'deletion' ? 3 : 4,
'client_id' => $data['client_id'],
'client_policy_id' => $data['client_policy_id'],
'endorsement_no' => null,
'cd_ac_no' => $data['cd_ac_no'] ?? null,
'insurer_id' => $data['insurer_id'],
'description' => $description,
'transaction_type' => $data['action_type'] == 'deletion' ? 'Credit' : 'Debit',
'updated_by' => get_session_userid(),
'event_name' => $data['action_type'],
'is_active' => 1,
'cd_ac_pk' => $data['cd_ac_pk'] ?? null,
'pt_id' => $policy_tran_id ?? null,
];
$result = DepositHelper::saveDeposit($cd_tranction_data, get_session_userid());
if(isset($result['success']) && $result['success']){
$update_data['ct_tran_id'] = $result['insert_id'];
$this->policyTransactionModel->where('id', $policy_tran_id)->set($update_data)->update();
}
}
DepositHelper::saveDeposit($cd_tranction_data, get_session_userid());
}
}
@ -1397,6 +1429,16 @@ class PolicyTransactionController extends BaseController
->orderBy('id', 'asc')
->first();
$pt_id = null;
if(!empty($data)){
$inception_data = $this->policyTransactionModel
->where('policy_no', $data['policy_no'])
->where('client_id', $data['client_id'])
->where('action_type', 'inception')
->first();
$pt_id = $inception_data['id'];
}
if (!empty($data['policy_start_date'])) {
$data['policy_start_date'] = change_date_format($data['policy_start_date'], 'Y-m-d', 'd/m/Y');
@ -1558,8 +1600,18 @@ class PolicyTransactionController extends BaseController
// print_r($data['endorse_eff_date']); die;
$pt_bp_amt = $this->PTCOShareDetailsModel
->select('bp_amt, amount')
->where('pt_id', $id)
->where('co_share_type', 1)
->where('is_active', 1)
->first();
// dd(db_connect()->getLastQuery() ,$pt_bp_amt);
$data['base_cd_amount'] = $pt_bp_amt['amount'] ?? null;
if ($data) {
return $this->respond(['status' => true, 'data' => $data], 200);
return $this->respond(['status' => true, 'data' => $data, 'pt_id' => $pt_id], 200);
} else {
return $this->respond(['status' => false], 200);
}
@ -1709,14 +1761,16 @@ class PolicyTransactionController extends BaseController
")
->join('policy_transaction', 'policy_transaction.id = pt_co_share_details.pt_id')
->where('policy_transaction.client_id', $client_id)
->where('policy_transaction.client_policy_id', $client_policy_id)
// ->where('policy_transaction.client_policy_id', $client_policy_id)
->where('policy_transaction.id', $client_policy_id)
->where('policy_transaction.action_type', 'inception')
->where('policy_transaction.is_active', 1)
->findAll();
$is_copay_yes = $this->policyTransactionModel
->where('client_id', $client_id)
->where('client_policy_id', $client_policy_id)
// ->where('client_policy_id', $client_policy_id)
->where('id', $client_policy_id)
->where('action_type', 'inception')
->where('is_active', 1)
->first();
@ -2102,7 +2156,7 @@ class PolicyTransactionController extends BaseController
//insurer statement list page
public function statementList()
{
// dd($this->validateInsurerStatement(['file_id' => 49])); // for check validateInsurerStatementfunction with hard coded file id always un command
// dd($this->updateInsurerStatement(['file_id' => 133])); // for check validateInsurerStatementfunction with hard coded file id always un command
$data['insurers'] = $this->insurerModel->where('is_active',1)->findAll();
$today = date('Y-m-d');
$fromday = $from_date = date('Y-m-d', strtotime('-180 days', strtotime($today)));
@ -2347,13 +2401,13 @@ class PolicyTransactionController extends BaseController
// $excel_row = ExcelSanitizeHelper::sanitizeArrayData($excel_row);
$is_source_found = 0;
// Kint::dump($excel_key,$excel_row[1],$excel_row[2]);
$policy_start_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[4]); //policy_start_date from excel
$policy_end_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[5]); //policy_end_date from excel
// $policy_start_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[4]); //policy_start_date from excel
// $policy_end_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[5]); //policy_end_date from excel
$policy_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[1]); //policy_end_date from excel
$policy_no = preg_replace( '/[\x{200B}\x{200C}\x{200D}\x{FEFF}\x{00A0}\x{200E}\x{200F}\x{202A}-\x{202E}]/u', '', $excel_row[1]); //policy_end_date from excel
$client_name = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[3]); //clientname from excel
// $client_name = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[3]); //clientname from excel
$endorsement_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[2]); //policy_end_date from excel
$endorsement_no = preg_replace( '/[\x{200B}\x{200C}\x{200D}\x{FEFF}\x{00A0}\x{200E}\x{200F}\x{202A}-\x{202E}]/u', '', $excel_row[2]); //policy_end_date from excel
@ -2459,11 +2513,11 @@ class PolicyTransactionController extends BaseController
if (!$is_row_empty) {
$is_source_found = 0;
$policy_start_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[4]); //policy_start_date from excel
$policy_end_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[5]); //policy_end_date from excel
// $policy_start_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[4]); //policy_start_date from excel
// $policy_end_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[5]); //policy_end_date from excel
$policy_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[1]); //policy_end_date from excel
$policy_no = preg_replace('/[\x{200C}\x{200B}]/u', '', $excel_row[1]); //
$client_name = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[3]); //clientname from excel
// $client_name = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[3]); //clientname from excel
$endorsement_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[2]); //policy_end_date from excel
foreach ($source_data as $source_key => $source_row) {
@ -2476,9 +2530,10 @@ class PolicyTransactionController extends BaseController
//calculate percentage first
$total_amt = 0;
$actual_bp_per = trim($excel_row[9]);
$actual_bp_brokerage = trim($excel_row[12]);
$actual_bp_amt = trim($excel_row[6]);
// $actual_bp_per = trim($excel_row[9]); //commented becoz this filed removed tfrom excel file
$actual_bp_per = 0; //set default value 0 for maintaining existing code flow
$actual_bp_brokerage = trim($excel_row[5]);
$actual_bp_amt = trim($excel_row[3]);
if (($actual_bp_brokerage && $actual_bp_brokerage != 0 && $actual_bp_brokerage != "")) {
$total_amt += $actual_bp_brokerage;
@ -2491,9 +2546,10 @@ class PolicyTransactionController extends BaseController
$total_amt += $actual_bp_brokerage;
}
$actual_tp_per = trim($excel_row[10]);
$actual_tp_brokerage = trim($excel_row[13]);
$actual_tp_amt = trim($excel_row[7]);
// $actual_tp_per = trim($excel_row[10]);//commented becoz this filed removed tfrom excel file
$actual_tp_per = 0;//set default value 0 for maintaining existing code flow
$actual_tp_brokerage = trim($excel_row[6]);
$actual_tp_amt = trim($excel_row[4]);
if ($actual_tp_brokerage && $actual_tp_brokerage != 0 && $actual_tp_brokerage != "") {
$total_amt += $actual_tp_brokerage;
@ -2506,9 +2562,13 @@ class PolicyTransactionController extends BaseController
$total_amt += $actual_tp_brokerage;
}
$actual_tep_per = trim($excel_row[11]);
$actual_tep_brokerage = trim($excel_row[14]);
$actual_tep_amt = trim($excel_row[8]);
// $actual_tep_per = trim($excel_row[11]);
// $actual_tep_brokerage = trim($excel_row[14]);
// $actual_tep_amt = trim($excel_row[8]);
$actual_tep_per = 0;
$actual_tep_brokerage = 0;
$actual_tep_amt = 0;
if ($actual_tep_brokerage && $actual_tep_brokerage != 0 && $actual_tep_brokerage != "") {
$total_amt += $actual_tep_brokerage;
@ -2524,7 +2584,7 @@ class PolicyTransactionController extends BaseController
//find variance
$variance_amt = $source_row['exp_amt'] - $total_amt;
$data_to_update[] = ['co_share_id' => $source_row['id'], 'actual_bp_amt' => $actual_bp_amt, 'actual_tp_amt' => $actual_tp_amt, 'actual_tep_amt' => $actual_tep_amt, 'actual_bp_per' => $actual_bp_per, 'actual_tp_per' => $actual_tp_per, 'actual_tep_per' => $actual_tep_per, 'variance' => $variance_amt, 'actual_tep_brokerage_amt' => $actual_tep_brokerage, 'actual_tp_brokerage_amt' => $actual_tp_brokerage, 'actual_bp_brokerage_amt' => $actual_bp_brokerage, 'reward' => trim($excel_row[15]), 'statement_id' => $file_id];
$data_to_update[] = ['co_share_id' => $source_row['id'], 'actual_bp_amt' => $actual_bp_amt, 'actual_tp_amt' => $actual_tp_amt, 'actual_tep_amt' => $actual_tep_amt, 'actual_bp_per' => $actual_bp_per, 'actual_tp_per' => $actual_tp_per, 'actual_tep_per' => $actual_tep_per, 'variance' => $variance_amt, 'actual_tep_brokerage_amt' => $actual_tep_brokerage, 'actual_tp_brokerage_amt' => $actual_tp_brokerage, 'actual_bp_brokerage_amt' => $actual_bp_brokerage, 'reward' => trim($excel_row[7]), 'statement_id' => $file_id];
unset($source_data[$source_key]);
continue 2;
@ -2627,6 +2687,10 @@ class PolicyTransactionController extends BaseController
$gst = $gstTotal[$index];
$paymentDate = $paymentDates[$index];
if($utrNo == "" && $tds == "" && $gst == "" && $receivedAmount == "")
{
continue;
}
// Prepare data for insert/update
$childData = [
'inv_amt' => $receivedAmount,
@ -3113,4 +3177,116 @@ class PolicyTransactionController extends BaseController
return [$policyList, $policyListByClient];
}
public function reportBDSNew()
{
// 🧭 Basic Page Info
$data['tab_name'] = 'BDS Report';
$data['page_name'] = 'BDS Report';
// 📋 Dropdown Data
$data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
$data['client_type'] = [1 => 'Group', 2 => 'Individual'];
$data['issuing_type'] = [1 => 'Fresh', 2 => 'Renewal', 3 => 'Roll Over'];
$data['policy_status'] = [
'pending' => 'Pending',
'exported_to_insurer' => 'Exported to Insurer',
'imported_from_insurer'=> 'Imported from Insurer',
'exported_to_tpa' => 'Exported to TPA',
'imported_from_tpa' => 'Imported from TPA',
'completed' => 'Completed'
];
$data['invoice_status_array'] = [
'yet_to_generate' => 'Yet to Generate',
'generated' => 'Generated',
'send' => 'Send',
'recived' => 'Recived',
];
$data['date_type'] = [
'policy_issue_date' => 'Policy Issue Date',
'policy_start_date' => 'Policy Start Date',
'policy_end_date' => 'Policy End Date',
'data_received_date' => 'Data Received Date',
'closure_date' => 'Closure Date',
'statement_month' => 'Statement Month',
];
// 🏢 Fetch Active Data
$data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll();
$data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll();
$data['clients'] = $this->clientModel->where('is_active', 1)->findAll();
$data['users'] = $this->userModel->where('is_active', 1)->findAll();
$data['policy_count'] = $this->policyTransactionModel->where('is_active', 1)->countAllResults();
// 🕐 Filters
$start_date = $this->request->getGet('start_date');
$end_date = $this->request->getGet('end_date');
$client_id = $this->request->getGet('client_id');
$insurer_id = $this->request->getGet('insurer_id');
$policy_type_id = $this->request->getGet('policy_type_id');
$date_type = $this->request->getGet('date_type');
$issuer = $this->request->getGet('issuer');
$client_branch_id = $this->request->getGet('client_branch_id');
$insurer_branch_id = $this->request->getGet('insurer_branch_id');
$client_policy_id = $this->request->getGet('client_policy_id');
$user_id = $this->request->getGet('user_id');
// Handle statement month range
if ($date_type == 'statement_month') {
$start_date = (string) date('Y-m-01', strtotime($start_date));
$end_date = (string) date('Y-m-31', strtotime($end_date));
}
// Ensure default values
$start_date = $start_date ?: 0;
$end_date = $end_date ?: 0;
$client_id = $client_id ?: 0;
$insurer_id = $insurer_id ?: 0;
$policy_type_id = $policy_type_id ?: 0;
$date_type = $date_type ?: 0;
$issuer = $issuer ?: 0;
$client_branch_id = $client_branch_id ?: 0;
$insurer_branch_id = $insurer_branch_id ?: 0;
$client_policy_id = $client_policy_id ?: 0;
$user_id = $user_id ?: 0;
// 🧾 Handle POST requests (Dashboard filters)
if ($this->request->is('post')) {
$isFromDashboard = $this->request->getPost('is_dashboard');
if (!empty($isFromDashboard) && $isFromDashboard == 1) {
$ids = array_filter(explode(',', $this->request->getPost('ids')));
if (!empty($ids)) {
$idsStr = implode(',', array_map('intval', $ids)); // sanitize IDs
$where = "policy_transaction.id IN ($idsStr)";
} else {
$where = []; // No valid IDs
}
}
}
// 📊 Fetch report data
$data['report_list'] = $this->policyTransactionModel->reportBDSNew(
$start_date,
$end_date,
$client_id,
$insurer_id,
$policy_type_id,
$date_type,
$issuer,
$client_branch_id,
$insurer_branch_id,
$client_policy_id,
$user_id,
$where ?? ''
);
// 🧩 Load View
$this->loadLayout('report_bds_filter', $data);
}
}

View File

@ -362,6 +362,17 @@ class TestingController extends BaseController
$pre_clients_list = $this->getNonDuplicatePreClients();
$log_post_clients_list = $post_clients_list ;
$log_pre_clients_list = $pre_clients_list ;
log_message('error', 'Post Clients to be processed: ' . count($log_post_clients_list));
log_message('error', 'Pre Clients to be processed: ' . count($log_pre_clients_list));
$matched_Count = 0 ;
$expected_match_count = min(count($post_clients_list), count($pre_clients_list));
if (
@ -372,12 +383,18 @@ class TestingController extends BaseController
$postDB = \Config\Database::connect();
$preDB = \Config\Database::connect('preDB');
foreach ($post_clients_list as $post_client) {
foreach ($post_clients_list as $index => $post_client) {
foreach ($pre_clients_list as $pre_client) {
foreach ($pre_clients_list as $index => $pre_client) {
if (trim($post_client['short_name']) == trim($pre_client['short_name'])) {
unset($log_post_clients_list[$index]);
unset($log_pre_clients_list[$index]);
$matched_Count++;
$postDB->table('clients')->where('id', $post_client['id'])->update(['pre_client_id' => $pre_client['id']]);
$preDB->table('clients')->where('id', $pre_client['id'])->update(['post_client_id' => $post_client['id']]);
@ -426,7 +443,32 @@ class TestingController extends BaseController
}
}
}
log_message('error', 'Expected Match Count : ' . $expected_match_count);
log_message('error', 'Total Matched Count: ' . $matched_Count);
log_message('error', 'Total UnMatched Count: ' . $expected_match_count - $matched_Count);
log_message('error','unmatched_reocrds');
$log_post_clients_list = array_values($log_post_clients_list);
$log_pre_clients_list = array_values($log_pre_clients_list);
if( (count($log_pre_clients_list) < count($log_post_clients_list))){
log_message('error',"unmatched records count from pre- ". count($log_pre_clients_list));
log_message('error',print_r($log_pre_clients_list,true));
} else {
log_message('error',"unmatched records count from post - ".count($log_post_clients_list));
log_message('error',print_r($log_post_clients_list,true));
}
}
return $this->response->setJSON(['status' => 'success', 'message' => 'Client and Branch mapping completed.'])->setStatusCode(200);
}
@ -673,4 +715,97 @@ class TestingController extends BaseController
];
}
public function logo_renaming(){
$directory = ROOTPATH . 'public/uploads/logo/';
if (!is_dir($directory)) {
die("Directory not found: $directory");
}
$files = scandir($directory);
$client_logo_files = $this->get_client_logo_files();
$rename_files = "";
$failed_rename_files = "";
foreach ($files as $file) {
// Skip system entries
if ($file === '.' || $file === '..' ) {
continue;
}
$oldPath = $directory . $file;
if (is_file($oldPath) && in_array(trim($file) , $client_logo_files)) {
// Remove all spaces from filename
$newFileName = preg_replace('/\s+|\x{00A0}|\x{200B}|\x{200C}|\x{200D}|\x{FEFF}/u', '', $file);
$newPath = $directory . $newFileName;
// Only rename if the name changed
if ($oldPath !== $newPath) {
if (rename($oldPath, $newPath)) {
$rename_files .= "\n Renamed: $file$newFileName \n";
} else {
$failed_rename_files .= "\n Failed file: $file \n";
}
}
}
}
$dbUpdated = $this->update_client_logo_files();
log_message('error', 'Renamed Files: ' . $rename_files);
log_message('error', 'Failed Renames: ' . $failed_rename_files);
log_message('error', 'Database Update Status: ' . ($dbUpdated ? 'Success' : 'No changes made'));
return $this->response->setJSON(['status' => 'success',
'message' => 'Logo renaming completed. kindly check backend logs for details',
'data' => [
'renamed_files' => $rename_files,
'failed_renames' => $failed_rename_files
]
])->setStatusCode(200);
}
public function get_client_logo_files(){
$db = \Config\Database::connect();
$sql = "SELECT client_logo FROM clients WHERE client_logo IS NOT NULL AND TRIM(client_logo) <> '' ";
$query = $db->query($sql);
$results = $query->getResultArray() ?? [];
$files = array_map(function($item) {
return trim($item['client_logo']);
}, $results);
return $files;
}
public function update_client_logo_files(){
$db = \Config\Database::connect();
$sql = "UPDATE clients
SET client_logo = REPLACE(REPLACE(REPLACE(client_logo, CHAR(160), ''), ' ', ''), '\t', '')
WHERE client_logo IS NOT NULL
AND TRIM(client_logo) <> ''
";
$query = $db->query($sql);
return $db->affectedRows() > 0;
}
}

View File

@ -66,7 +66,8 @@ class DepositHelper
'updated_by' => $data['updated_by'],
'balance' => $newBalance, // Include the new balance in the data array
'cd_ac_pk'=> isset($data['cd_ac_pk'])?$data['cd_ac_pk']:null,
'record_date' => $data['record_date'] ?? null
'record_date' => $data['record_date'] ?? null,
'policy_transaction_id' => $data['pt_id'] ?? null
];
// Insert data and get the insert ID

View File

@ -57,6 +57,7 @@ if (!function_exists('file_Upload')) {
if ($fileToUpload !== null && $fileToUpload->isValid() && !$fileToUpload->hasMoved()) {
$fileToUpload->move($filepath);
$fileName = $fileToUpload->getName();
$fileName = preg_replace('/[\s\x{00A0}\x{200B}-\x{200D}\x{FEFF}]/u', '', $fileName);
return $fileName;
} else {
return "";
@ -858,3 +859,10 @@ if (!function_exists('expected_amount_calc')) {
return round($expectedAmount, 2); // Optional: round to 2 decimal places
}
}
if (!function_exists('getFileIfExists')) {
function getFileIfExists($path)
{
return file_exists(FCPATH . $path) ? base_url($path) : '';
}
}

View File

@ -28,7 +28,8 @@ class ClientDepositModel extends Model
"event_name",
"unit",
"cd_ac_pk",
"record_date"
"record_date",
"policy_transaction_id",
];

View File

@ -55,6 +55,7 @@ class ClientPolicyModel extends Model
"cd_ac_pk",
"is_lgbtq",
"placement_json",
"policy_entry_from",
];
// Callbacks

View File

@ -1471,7 +1471,7 @@ class EmployeePolicyModel extends Model
ep.tpa_id,
ep.uhid,
ep.policy_end_date,
cp.policy_end_date,
ep.basic_cover_si,
clients.client_name,
@ -1492,6 +1492,7 @@ class EmployeePolicyModel extends Model
tpa.tpa_logo AS tpa_logo,
tpa.front_card,
tpa.back_card,
tpa.network_hospitals,
tpa.short_name AS tpa_short_name'
)
@ -1531,12 +1532,19 @@ class EmployeePolicyModel extends Model
e.doj,
e.band,
TIMESTAMPDIFF(YEAR, e.dob, CURDATE()) AS emp_age,
(SELECT name FROM employees WHERE relationship = "Self" and emp_code = ' . $this->db->escape($emp_code) . ' and client_id = '.$client_id.' LIMIT 1) AS self,
(
SELECT name FROM employees
WHERE relationship = "Self"
and emp_code = ' . $this->db->escape($emp_code) . '
and client_id = '.$client_id.'
and is_active = 1
and emp_status = "active"
LIMIT 1
) AS self,
ep.tpa_id,
ep.uhid,
ep.policy_end_date,
cp.policy_end_date,
ep.basic_cover_si,
clients.client_name,
@ -1557,6 +1565,7 @@ class EmployeePolicyModel extends Model
tpa.tpa_logo AS tpa_logo,
tpa.front_card,
tpa.back_card,
tpa.network_hospitals,
tpa.short_name AS tpa_short_name'
)

View File

@ -305,7 +305,7 @@ class PolicyTransactionModel extends Model
if ($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0) {
$fromDate = date('Y-m-d', strtotime('-30 days'));
$fromDate = date('Y-m-d', strtotime('-90 days'));
$toDate = date('Y-m-d 23:59:59');
$builder->where('policy_transaction.created_at >=', $fromDate)
@ -881,7 +881,7 @@ class PolicyTransactionModel extends Model
if ($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0) {
$fromDate = date('Y-m-d', strtotime('-60 days'));
$fromDate = date('Y-m-d', strtotime('-90 days'));
$toDate = date('Y-m-d 23:59:59');
if (empty($where)) {
@ -1060,7 +1060,7 @@ class PolicyTransactionModel extends Model
// Default to Last 30 Days if No Filters Are Applied
if (empty($client_id) && empty($insurer_id) && empty($policy_type_id) && empty($date_type) && empty($issuer) && empty($where)) {
$fromDate = date('Y-m-d', strtotime('-60 days'));
$fromDate = date('Y-m-d', strtotime('-90 days'));
$toDate = date('Y-m-d 23:59:59');
$builder->where('policy_transaction.created_at >=', $fromDate)
@ -1108,7 +1108,7 @@ class PolicyTransactionModel extends Model
->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left')
->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left')
->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
->where('policy_transaction.is_active', 1)
->where('policy_transaction.action_type !=', 'inception');
@ -1163,7 +1163,7 @@ class PolicyTransactionModel extends Model
if ($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0) {
$fromDate = date('Y-m-d', strtotime('-60 days'));
$fromDate = date('Y-m-d', strtotime('-90 days'));
$toDate = date('Y-m-d 23:59:59');
$builder->where('policy_transaction.created_at >=', $fromDate)
@ -1313,7 +1313,7 @@ class PolicyTransactionModel extends Model
->where('policy_transaction.' . $date_type . '<=', $endDate);
} else {
$fromDate = date('Y-m-d', strtotime('-30 days'));
$fromDate = date('Y-m-d', strtotime('-90 days'));
$toDate = date('Y-m-d 23:59:59');
$builder->where('policy_transaction.created_at >=', $fromDate)
@ -1416,7 +1416,7 @@ class PolicyTransactionModel extends Model
->where('policy_transaction.' . $date_type . '<=', $endDate);
} else {
$fromDate = date('Y-m-d', strtotime('-30 days'));
$fromDate = date('Y-m-d', strtotime('-90 days'));
$toDate = date('Y-m-d 23:59:59');
$builder->where('policy_transaction.created_at >=', $fromDate)
@ -1457,7 +1457,7 @@ class PolicyTransactionModel extends Model
public function getFinanceReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0)
{
$dateThreshold = date('Y-m-d H:i:s', strtotime("- 3 days"));
$dateThreshold = date('Y-m-d H:i:s', strtotime("-90 days"));
$builder = $this->db->table('policy_transaction')
->select("
@ -1519,7 +1519,7 @@ class PolicyTransactionModel extends Model
->where('policy_transaction.' . $date_type . '<=', $endDate);
} else {
$fromDate = date('Y-m-d', strtotime('-30 days'));
$fromDate = date('Y-m-d', strtotime('-90 days'));
$toDate = date('Y-m-d 23:59:59');
$builder->where('policy_transaction.created_at >=', $fromDate)
@ -1624,7 +1624,7 @@ class PolicyTransactionModel extends Model
$builder->where('policy_transaction.' . $date_type . '>=', $startDate)
->where('policy_transaction.' . $date_type . '<=', $endDate);
} else {
$fromDate = date('Y-m-d', strtotime('-30 days'));
$fromDate = date('Y-m-d', strtotime('-90 days'));
$toDate = date('Y-m-d 23:59:59');
$builder->where('policy_transaction.created_at >=', $fromDate)
@ -1712,7 +1712,7 @@ class PolicyTransactionModel extends Model
//function for fetch renewal report data
public function getRenewalReportData($start_date = null, $end_date = null, $client_type = null, $client = null, $issuer = null)
{
$fromDate = date('Y-m-d', strtotime('-60 days'));
$fromDate = date('Y-m-d', strtotime('-90 days'));
$toDate = date('Y-m-d 23:59:59');
if (!empty($start_date) && !empty($end_date)) {
@ -1806,4 +1806,307 @@ class PolicyTransactionModel extends Model
return $result[0];
}
public function reportBDSNew(
$start_date = 0,
$end_date = 0,
$client_id = 0,
$insurer_id = 0,
$policy_type_id = 0,
$date_type = 0,
$issuer = 0,
$client_branch_id = 0,
$insurer_branch_id = 0,
$client_policy_id = 0,
$user_id = 0,
$where = []
) {
$date_condition = '';
// ==============================
// DATE FILTER FOR STATEMENT MONTH
// ==============================
if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) {
$date_condition = "
AND insurer_statements.month >= '{$start_date}'
AND insurer_statements.month <= '{$end_date}'
";
}
// ==============================
// BASE QUERY
// ==============================
$builder = $this->db->table('policy_transaction')
->select("
policy_transaction.*,
DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date,
DATE_FORMAT(
IF(policy_transaction.month IS NULL,
policy_transaction.policy_issue_date,
policy_transaction.month
), '%b %Y'
) AS policy_issue_month,
CASE
WHEN clients.client_type = 1 THEN 'Group'
WHEN clients.client_type = 2 THEN 'Retail'
ELSE '-'
END AS client_type,
CASE
WHEN policy_transaction.revenue_type = 'NA' THEN 'Fresh'
ELSE 'Renewal'
END AS revenue_type,
CASE
WHEN policy_transaction.action_type = 'inception' THEN 'Policy'
ELSE 'Endorsement'
END AS action_type,
clients.client_name AS client_name,
clients.short_name AS client_short_name,
client_branch.branch_name AS client_branch_name,
client_branch.address1 AS client_address,
policy_type.policy_type,
policy_type.bap,
insurers.name AS insurer_name,
insurers.short_name AS insurer_short_name,
insurer_branch.branch_name AS insurer_branch_name,
insurer_branch.branch_code AS insurer_branch_code,
user_profiles.first_name AS user_name,
vehicle.vehicle_no,
tpa.name AS tpa_name,
pt_co_share_details.remark AS remarks,
pt_co_share_details.cop_amt AS bp_amt,
pt_co_share_details.exp_amt,
pt_co_share_details.id AS pt_id,
sales_user.first_name AS salse_person_name,
service_user.first_name AS service_person_name,
ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) AS premium_wo_gst,
ROUND((ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) * 18 / 100), 2) AS gst_amount,
ROUND(
ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) +
ROUND((ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) * 18 / 100), 2),
2) AS total_premium,
ROUND(pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) AS tp_or_ter,
DATEDIFF(policy_transaction.policy_end_date, CURDATE()) AS days,
(pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per) AS agreed_tp_or_ter_per,
pt_co_share_details.agreed_bp_per,
-- ==============================
-- SUBQUERY: Total IRDA Amount
-- ==============================
ROUND((
SELECT (
SUM(co_share_stmt_details.actual_bp_brokerage_amt) +
SUM(co_share_stmt_details.actual_tp_brokerage_amt) +
SUM(co_share_stmt_details.actual_tep_brokerage_amt) +
SUM(co_share_stmt_details.reward)
)
FROM co_share_stmt_details
JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id
AND co_share_stmt_details.is_active = 1
AND insurer_statements.is_active = 1
{$date_condition}
), 2) AS total_irda_amt,
-- Reward Only
ROUND((
SELECT SUM(co_share_stmt_details.reward)
FROM co_share_stmt_details
JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id
AND co_share_stmt_details.is_active = 1
AND insurer_statements.is_active = 1
{$date_condition}
), 2) AS reward,
-- Billed Amount
ROUND((
SELECT SUM(
COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) +
COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) +
COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) +
COALESCE(co_share_stmt_details.reward, 0)
)
FROM co_share_stmt_details
JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id
JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id
AND co_share_stmt_details.is_active = 1
AND pt_table.is_active = 1
AND insurer_statements.is_active = 1
AND insurer_statements.invoice_status IS NOT NULL
{$date_condition}
), 2) AS billed_amt,
-- Unbilled Amount
ROUND(
(
(
SELECT
SUM(
COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) +
COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) +
COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) +
COALESCE(co_share_stmt_details.reward, 0)
)
FROM co_share_stmt_details
JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id
AND co_share_stmt_details.is_active = 1
{$date_condition}
)
-
(
SELECT
SUM(
COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) +
COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) +
COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) +
COALESCE(co_share_stmt_details.reward, 0)
)
FROM co_share_stmt_details
JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id
JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id
AND co_share_stmt_details.is_active = 1
AND pt_table.is_active = 1
AND insurer_statements.is_active = 1
AND insurer_statements.invoice_status IS NULL
{$date_condition}
)
), 2) AS unbilled_amt,
created_user.first_name AS user_name,
CASE
WHEN pt_co_share_details.co_share_type IN (0, 1) THEN policy_transaction.policy_no
WHEN pt_co_share_details.co_share_type > 1 THEN
CASE
WHEN pt_co_share_details.follower_policy_no IS NULL OR pt_co_share_details.follower_policy_no = ''
THEN policy_transaction.policy_no
ELSE pt_co_share_details.follower_policy_no
END
ELSE policy_transaction.policy_no
END AS policy_no
")
// ==============================
// JOINS
// ==============================
->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
->join('clients', 'clients.id = policy_transaction.client_id')
->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left')
->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
->join('user_profiles', 'policy_transaction.created_by = user_profiles.id', 'left')
->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left')
->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
->join('insurer_branch', 'pt_co_share_details.insurer_branch_id = insurer_branch.id', 'left')
->join('tpa', 'policy_transaction.tpa_id = tpa.id', 'left')
->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left')
->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left')
->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left')
->join('user_profiles AS created_user', 'policy_transaction.created_by = created_user.id', 'left')
->where('policy_transaction.is_active', 1)
->where('pt_co_share_details.is_active', 1);
// ==============================
// ROLE-BASED FILTERS
// ==============================
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());
}
}
// ==============================
// ADDITIONAL FILTERS
// ==============================
if (!empty($where)) {
log_message('info', 'Where condition: ' . json_encode($where));
$builder->where($where);
}
if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') {
$startDate = date('Y-m-d 00:00:00', strtotime($start_date));
$endDate = date('Y-m-d 23:59:59', strtotime($end_date));
$builder->where("policy_transaction.{$date_type} >=", $startDate)
->where("policy_transaction.{$date_type} <=", $endDate);
}
// JOIN FOR STATEMENT MONTH FILTER
if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) {
$startDate = date('Y-m-d', strtotime($start_date));
$endDate = date('Y-m-d', strtotime($end_date));
$builder->join('co_share_stmt_details', 'pt_co_share_details.id = co_share_stmt_details.co_share_id', 'left')
->join('insurer_statements', 'co_share_stmt_details.statement_id = insurer_statements.id', 'left')
->where('insurer_statements.is_active', 1)
->where('insurer_statements.month >=', $startDate)
->where('insurer_statements.month <=', $endDate)
->groupBy('co_share_stmt_details.co_share_id');
}
// ==============================
// FILTER BY IDs
// ==============================
if ($client_id != 0) $builder->where('policy_transaction.client_id', $client_id);
if ($insurer_id != 0) $builder->where('policy_transaction.insurer_id', $insurer_id);
if ($client_branch_id != 0) $builder->where('policy_transaction.client_branch_id', $client_branch_id);
if ($insurer_branch_id != 0) $builder->where('policy_transaction.insurer_branch_id', $insurer_branch_id);
if ($client_policy_id != 0) $builder->where('policy_transaction.client_policy_id', $client_policy_id);
if ($user_id != 0) $builder->where('policy_transaction.created_by', $user_id);
if ($policy_type_id != 0) $builder->where('client_policy.policy_type_id', $policy_type_id);
if ($issuer != 0) $builder->where('policy_transaction.issuer', $issuer);
// ==============================
// DEFAULT 90-DAY FILTER
// ==============================
if (
$client_id == 0 &&
$insurer_id == 0 &&
$policy_type_id == 0 &&
$date_type == 0 &&
$issuer == 0
) {
$fromDate = date('Y-m-d', strtotime('-90 days'));
$toDate = date('Y-m-d 23:59:59');
if (empty($where)) {
$builder->where('policy_transaction.created_at >=', $fromDate)
->where('policy_transaction.created_at <=', $toDate);
}
}
// ==============================
// ORDER & EXECUTION
// ==============================
$builder->orderBy('policy_transaction.id', 'desc');
$result = $builder->get()->getResultArray();
// Uncomment if you need to debug SQL
// dd($this->db->getLastQuery());
return $result;
}
}

57
app/Models/RTOModel.php Normal file
View File

@ -0,0 +1,57 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class RTOModel extends Model
{
protected $table = 'rto_master';
protected $primaryKey = 'id';
protected $allowedFields = [
'id',
'rto_state',
'rto_code',
'rto_name',
'created_at',
'created_by',
'updated_at',
'updated_by',
'is_active',
];
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = ["checkAndADDCreatedByValue"];
protected $afterInsert = [];
protected $beforeUpdate = ["checkAndUpdateUpdatedByValue"];
protected $afterUpdate = [];
protected $beforeFind = [];
protected $afterFind = [];
protected $beforeDelete = [];
protected $afterDelete = [];
protected function checkAndADDCreatedByValue(array $data)
{
// Check if 'updated_by' value is null or empty
if (empty($data['data']['created_by'])) {
// Set 'updated_by' value to the current session user ID
$data['data']['created_by'] = get_session_userid();
}
return $data;
}
protected function checkAndUpdateUpdatedByValue(array $data)
{
// Check if 'updated_by' value is null or empty
if (empty($data['data']['updated_by'])) {
// Set 'updated_by' value to the current session user ID
$data['data']['updated_by'] = get_session_userid();
}
return $data;
}}

View File

@ -25,6 +25,7 @@ class VehicleModel extends Model
'is_active',
'created_by',
'updated_by',
'rto_id',
];

View File

@ -0,0 +1,54 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class VehicleTypeModel extends Model
{
protected $table = 'vehicle_type';
protected $primaryKey = 'id';
protected $allowedFields = [
'id',
'vehicle_type',
'created_at',
'created_by',
'updated_at',
'updated_by',
'is_active',
];
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = ["checkAndADDCreatedByValue"];
protected $afterInsert = [];
protected $beforeUpdate = ["checkAndUpdateUpdatedByValue"];
protected $afterUpdate = [];
protected $beforeFind = [];
protected $afterFind = [];
protected $beforeDelete = [];
protected $afterDelete = [];
protected function checkAndADDCreatedByValue(array $data)
{
// Check if 'updated_by' value is null or empty
if (empty($data['data']['created_by'])) {
// Set 'updated_by' value to the current session user ID
$data['data']['created_by'] = get_session_userid();
}
return $data;
}
protected function checkAndUpdateUpdatedByValue(array $data)
{
// Check if 'updated_by' value is null or empty
if (empty($data['data']['updated_by'])) {
// Set 'updated_by' value to the current session user ID
$data['data']['updated_by'] = get_session_userid();
}
return $data;
}}

View File

@ -208,7 +208,7 @@
<?php if(in_array(get_role_id(), [1,2,3,5]) || (get_role_id() == 4 && in_array(MANAGEMENT_TEAM_ID, user_team()) || in_array(FINANCE_TEAM_ID, user_team()) || in_array(BUSINESS_TEAM_ID, user_team()))) { ?>
<li class="nav-item d-flex justify-content-center align-items-center">
<!-- <li class="nav-item d-flex justify-content-center align-items-center">
<a href="#bds-dash-tab" data-toggle="tab" aria-expanded="true" class="nav-link px-3 py-1 dash-anchor nav-dash" id="bds_tab">
<img src="<?= base_url() . "public"; ?>/assets/images/inactive_bds.png" alt="Logo" height="14" class="inactive_bds">
<img src="<?= base_url() . "public"; ?>/assets/images/active_bds.png" alt="Logo" height="14"
@ -217,7 +217,7 @@
<span class="d-none d-sm-inline-block dash-tab dash-tab-font">BDS</span>
</a>
</li>
&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp; -->
<?php } ?>
<?php if ((get_role_id() == STAFF_ROLE_ID && in_array(CLAIMS_TEAM_ID,user_team())) || in_array(get_role_id(),[1,5])) :?>
@ -262,7 +262,7 @@
<?php endif; ?>
<?php if(in_array(get_role_id(), [1,2,3,5]) || (get_role_id() == 4 && in_array(MANAGEMENT_TEAM_ID, user_team()) || in_array(FINANCE_TEAM_ID, user_team()) || in_array(BUSINESS_TEAM_ID, user_team()))) { ?>
<?php include('bds_dash.php'); ?>
<!-- <?php //include('bds_dash.php'); ?> -->
<?php } ?>
<?php if ((get_role_id() == STAFF_ROLE_ID && in_array(ENROLLMENT_TEAM_ID,user_team())) || in_array(get_role_id(),[1,5])) :?>
<?php include("leads_dash.php") ?>

View File

@ -46,7 +46,7 @@
<div class="form-row">
<div class="form-group col-md-6">
<label for="insurer_branch_id">Insurer Branch<span class="text-danger">*</span></label>
<select class="form-control <?= !isset($CD_Master_Data) ? 'readonly-select' : '' ?>" id="insurer_branch_id" name="insurer_branch_id" required>
<select class="form-control <?= !isset($CD_Master_Data) ? 'readonly-select' : '' ?>" id="insurer_branch_id" name="insurer_branch_id" onchange="checkDuplicateCdAccount(this)" required>
<option value="">Select Insurer Branch</option>
<?php if(isset($insurer_branch) && !empty($insurer_branch))
{ foreach($insurer_branch as $branch) { ?>
@ -229,11 +229,11 @@
$('#opening_bal').prop("disabled", false);
if(isCdMasterPage == true){
$('#client_id').val('').change();
$('#insurer_id_for_cd').val('').change();
$('#insurer_branch_id').val('').change();
$('#cd_client_id').val('').select2();
$('#insurer_id_for_cd').val('').select2();
$('#insurer_branch_id').val('').select2();
$('#client_id').prop("disabled", false);
$('#cd_client_id').prop("disabled", false);
$('#insurer_id_for_cd').prop("disabled", false);
$('#insurer_branch_id').prop("disabled", false);
@ -266,7 +266,7 @@
);
});
$branchSelect.val('').trigger('change.select2');
$branchSelect.val('').select2();
}
function showCdMasterAddModal(){
@ -301,5 +301,43 @@
$('#cd_ac_no_for_cd_master').append(option);
}
function checkDuplicateCdAccount(){
let url = '<?= base_url('util/checkDuplicateCdAccount') ?>';
let client_id = $('#cd_client_id').val();
let insurer_id = $('#insurer_id_for_cd').val();
let insurer_branch_id = $('#insurer_branch_id').val();
console.log({client_id, insurer_id, insurer_branch_id});
// Data to send in the AJAX request
let requestData = {
client_id: client_id,
insurer_id: insurer_id,
insurer_branch_id: insurer_branch_id,
};
if(client_id != "" && insurer_id != "" && insurer_branch_id != ""){
// Send AJAX request
sendAjaxRequestForGlobal(url, 'GET', requestData, function(response) {
console.log('Data fetched successfully:', response);
if (response.status == true) {
console.log('No dublicate found');
} else {
$('#cd_client_id').val('').select2();
$('#insurer_id_for_cd').val('').select2();
$('#insurer_branch_id').val('').select2();
toastr.warning(response.message, 'WARNING');
}
}, function(xhr, status, error) {
console.error('Error fetching data:', error);
console.error(xhr.responseText);
toastr.error('An error occurred while checking the CD amount.', 'ERROR');
});
}
}
</script>

View File

@ -323,7 +323,7 @@ table.dataTable thead th {
$('#cd_client_id').prop("disabled", true);
$('#insurer_id_for_cd').val(res.data.insurer_id).change();
$('#insurer_id_for_cd').prop("disabled", true);
$('#insurer_branch_id').val(res.data.insurer_id).change();
$('#insurer_branch_id').val(res.data.insurer_branch_id).select2();
$('#insurer_branch_id').prop("disabled", true);
$('#opening_date').val(res.data.opening_date);
$('#cd_ac_no_for_cd_master').val(res.data.cd_ac_no);

View File

@ -986,55 +986,108 @@ function validateDuplicateByClientBranch(input, field, submitButId) {
let message = label ? label + " is duplicate!" : "Value is duplicate!";
console.log(`cId: ${clientId} | bId: ${branchId}`);
// Don't forgot be careful
// 1 Local duplication check (User entered)
let isLocalDuplicate = false;
$('input[name="' + field + '[]"]').each(function(index) {
let compareVal = $(this).val().trim();
console.log(`Entered value: ${value} | Contact ${index+1} value: ${$(this).val()}`);
if (this !== input && $(this).val().trim() === value) {
if (this !== input && compareVal !== '' && compareVal === value) {
isLocalDuplicate = true;
return false; // break loop
return false;
}
});
if (isLocalDuplicate) {
console.log(`r u n Local`);
console.log(`btn Dis - true`);
console.log(`duplicate found for ${field}`);
toastr.warning(message, 'WARNING');
$('#' + submitButId).prop('disabled', true);
return; // dont call server if duplicate in UI
return;
}
// important Skip empty values
if (value === '') {
checkAllFieldsValid(submitButId);
return;
}
// Don't forgot be careful
// 2 Server-side duplicate check (DB)
if (!isLocalDuplicate && value !== '') {
$.ajax({
url: '<?= base_url("client/others/check-duplicate") ?>',
type: 'POST',
data: {
client_id: clientId,
branch_id: branchId,
value: value,
field: field
},
dataType: 'json',
success: function(response) {
if (response.isDuplicate) {
console.log(`r u n Server`);
console.log(`btn Dis - true`);
toastr.warning(message, 'WARNING');
$('#' + submitButId).prop('disabled', true);
} else {
console.log(`btn Dis - false`);
$('#' + submitButId).prop('disabled', false);
}
},
error: function(xhr, status, error) {
console.error('AJAX Error:', error);
$.ajax({
url: '<?= base_url("client/others/check-duplicate") ?>',
type: 'POST',
data: {
client_id: clientId,
branch_id: branchId,
value: value,
field: field
},
dataType: 'json',
success: function(response) {
if (response.isDuplicate) {
console.log(`r u n Server`);
console.log(`duplicate found for ${field}`);
toastr.warning(message, 'WARNING');
$('#' + submitButId).prop('disabled', true);
} else {
console.log(`No duplicate for ${field}`);
checkAllFieldsValid(submitButId);
}
});
},
error: function(xhr, status, error) {
console.error('AJAX Error:', error);
}
});
}
// recheck all contacts before enabling submit
function checkAllFieldsValid(submitButId) {
let emailDuplicates = false;
let mobileDuplicates = false;
// cross check all EMAIL duplicates
let emailSeen = [];
$('input[name="email[]"]').each(function() {
let val = $(this).val().trim();
if (val && emailSeen.includes(val)) {
emailDuplicates = true;
} else if (val) {
emailSeen.push(val);
}
});
// cross check all MOBILE duplicates
let mobileSeen = [];
$('input[name="mobile[]"]').each(function() {
let val = $(this).val().trim();
if (val && mobileSeen.includes(val)) {
mobileDuplicates = true;
} else if (val) {
mobileSeen.push(val);
}
});
if (emailDuplicates || mobileDuplicates) {
$('#' + submitButId).prop('disabled', true);
// show correct message based on whats duplicated
if (emailDuplicates && mobileDuplicates) {
toastr.warning("Email and Mobile values are duplicate!", "WARNING");
console.log('Both Email and Mobile duplicates');
} else if (emailDuplicates) {
toastr.warning("Email duplicate!", "WARNING");
console.log('Cross Check Email duplicates');
} else if (mobileDuplicates) {
toastr.warning("Mobile duplicate!", "WARNING");
console.log('Cross Check Mobile duplicates');
}
console.log(`btn Dis - true`);
} else {
console.log('unique — enable');
console.log(`btn Dis - false`);
$('#' + submitButId).prop('disabled', false);
}
}

View File

@ -27,13 +27,88 @@
</style>
<style>
.switch-label {
position: relative;
display: inline-flex;
align-items: center;
gap: 10px;
cursor: pointer;
font-weight: 500;
color: #333;
justify-content: flex-end;
margin-right: 40px;
}
.switch-label input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: relative;
width: 50px;
height: 25px;
background-color: #fff;
border-radius: 25px;
box-shadow: 0 0 5px rgba(0,0,0,0.2);
transition: 0.3s;
}
.slider::before {
content: "";
position: absolute;
height: 19px;
width: 19px;
left: 3px;
top: 3px;
background-color: #ccc;
border-radius: 50%;
transition: 0.3s;
}
input:checked + .slider {
background-color: #ff4d4d; /* red when ON */
}
input:checked + .slider::before {
transform: translateX(25px);
background-color: #fff;
}
.switch-text {
user-select: none;
}
#table-client-policy_wrapper .row>.col-sm-12.col-md-6:first-child{
display: none;
}
#table-client-policy_filter{
text-align: left;
}
</style>
<div class="save-indicator" id="saveIndicator">Saved</div>
<div class="tab-pane fade" id="police-tab">
<div class="row float-right" style="padding-bottom: 10px; position: relative;right: 13px;">
<div class="row" style="padding-bottom: 10px; position: relative;right: 13px; justify-content: end;">
<button type="button" id="BtnAdd" class="btn btn-primary waves-effect waves-light btnAdd btn-sm" style="position: relative;right: 10px;"><span class="mdi mdi-plus-box-outline" aria-hidden="true" style="padding: 5px 10px;"></span>Add Policy</button>
<button type="button" id="BtnAddSuccess" class="btn btn-success waves-effect waves-light BtnAddSuccess btn-sm" onclick="showModal()"><span class="mdi mdi-plus-box-outline" aria-hidden="true" style="padding: 5px 10px;"></span>Add Policy From Lead</button>
</div>
<br>
<div class="" style="padding-bottom: 10px; position: absolute;
right: 0;">
<label class="switch-label">
<input type="checkbox" id="chk-show-expired">
<span class="slider"></span>
<span class="switch-text">Expired Policies</span>
</label>
</div>
<div class="table-responsive" id="table_list">
<table data-custom-table-css="table" class="table table-borderless table mb-0" id="table-client-policy">
@ -308,6 +383,8 @@
// Get today's date
var today = new Date();
const showExpired = $('#chk-show-expired').is(':checked');
var startDatePicker = flatpickr("#start_date", {
dateFormat: "d-m-Y",
defaultDate: today,
@ -412,37 +489,42 @@
var policy_name_data = `${item.policy_type_name ?? ''}` + ' - ' + `${item.policy_no ?? ''}`;
if(showExpired == false && checkDateStatus(item.policy_end_date) != 'Expired'){
policyTable += `
<tr>
<td>${item.insurer_short} - ${item.insurer_branch_name}</td>
<td>${policy_name_data}</td>
<td>${item.branch_name ? item.branch_name : ' - '}</td>
<td>${tpaValue}</td>
<td>${(item.policy_start_date)} / ${(item.policy_end_date)}</td>
<td>${checkDateStatus(item.policy_end_date, 1)}</td>
<td>
<div class="btn-group dropdown">
<a href="javascript: void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm" data-toggle="dropdown"aria-expanded="false"><i class="mdi mdi-dots-horizontal"></i></a>
<div class="dropdown-menu dropdown-menu-right">
<a href="#" data-id="${item.id}" id="${item.policy_id}" class="dropdown-item btnPolicyEdit"><i class="mdi mdi-lead-pencil mr-2 text-muted font-18 vertical-middle"></i>Edit</a>
<a href="#" data-id="${item.id}" id="${search_term}" data-typeid="${item.policy_type_id}" class="dropdown-item btnPolicyMaster" ><i class="mdi mdi-wrench mr-2 text-muted font-18 vertical-middle"></i>Terms</a>
<a href="#" data-id="${item.id}" id="${search_term}" data-typeid="${item.policy_type_id}" class="dropdown-item btnPolicyModel" data-toggle="modal" data-target="#bs-example-modal-lg"><i class="mdi mdi-book-open mr-2 text-muted font-18 vertical-middle"></i>Rack Rate</a>`;
// Conditionally render the delete option based on the role
if (role !== 3 && role !== 4) {
policyTable += `
<a href="#" data-id="${item.id}" id="${search_term}" data-typeid="${item.policy_type_id}" class="dropdown-item" onclick="removepolicy(this)"><i class="mdi mdi-delete mr-2 text-muted font-18 vertical-middle"></i>Delete</a>`;
}
<tr>
<td>${item.insurer_short} - ${item.insurer_branch_name}</td>
<td>${policy_name_data}</td>
<td>${item.branch_name ? item.branch_name : ' - '}</td>
<td>${tpaValue}</td>
<td>${(item.policy_start_date)} / ${(item.policy_end_date)}</td>
<td>${checkDateStatus(item.policy_end_date, 1)}</td>
<td>
<div class="btn-group dropdown">
<a href="javascript: void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm" data-toggle="dropdown"aria-expanded="false"><i class="mdi mdi-dots-horizontal"></i></a>
<div class="dropdown-menu dropdown-menu-right">
<a href="#" data-id="${item.id}" id="${item.policy_id}" class="dropdown-item btnPolicyEdit"><i class="mdi mdi-lead-pencil mr-2 text-muted font-18 vertical-middle"></i>Edit</a>
<a href="#" data-id="${item.id}" id="${search_term}" data-typeid="${item.policy_type_id}" class="dropdown-item btnPolicyMaster" ><i class="mdi mdi-wrench mr-2 text-muted font-18 vertical-middle"></i>Terms</a>
<a href="#" data-id="${item.id}" id="${search_term}" data-typeid="${item.policy_type_id}" class="dropdown-item btnPolicyModel" data-toggle="modal" data-target="#bs-example-modal-lg"><i class="mdi mdi-book-open mr-2 text-muted font-18 vertical-middle"></i>Rack Rate</a>`;
policyTable += `
</div>
</div>
</td>
</tr>
`;
// Conditionally render the delete option based on the role
if (role != 3 && role != 4) {
policyTable += `
<a href="#" data-id="${item.id}" id="${search_term}" data-typeid="${item.policy_type_id}" class="dropdown-item" onclick="removepolicy(this)"><i class="mdi mdi-delete mr-2 text-muted font-18 vertical-middle"></i>Delete</a>`;
}
policyTable += `
</div>
</div>
</td>
</tr>
`;
}
});
@ -452,9 +534,11 @@
$('#table-client-policy').DataTable({
paging: true,
searching: false,
// ordering: false
paging: true,
searching: true,
autoWidth: false,
responsive: true,
});
@ -658,35 +742,41 @@
var policy_name_data = `${item.policy_type_name ?? ''}` + ' - ' + `${item.policy_no ?? ''}`;
policyTable += `
<tr>
<td>${item.insurer_short} - ${item.insurer_branch_name}</td>
<td>${policy_name_data}</td>
<td>${item.branch_name ? item.branch_name : ' - '}</td>
<td>${tpaValue}</td>
<td>${(item.policy_start_date)} / ${(item.policy_end_date)}</td>
<td>${checkDateStatus(item.policy_end_date, 1)}</td>
<td>
<div class="btn-group dropdown">
<a href="javascript: void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm" data-toggle="dropdown"aria-expanded="false"><i class="mdi mdi-dots-horizontal"></i></a>
<div class="dropdown-menu dropdown-menu-right">
<a href="#" data-id="${item.id}" id="${item.policy_id}" class="dropdown-item btnPolicyEdit"><i class="mdi mdi-lead-pencil mr-2 text-muted font-18 vertical-middle"></i>Edit</a>
<a href="#" data-id="${item.id}" id="${search_term}" data-typeid="${item.policy_type_id}" class="dropdown-item btnPolicyMaster" ><i class="mdi mdi-wrench mr-2 text-muted font-18 vertical-middle"></i>Terms</a>
<a href="#" data-id="${item.id}" id="${search_term}" data-typeid="${item.policy_type_id}" class="dropdown-item btnPolicyModel" data-toggle="modal" data-target="#bs-example-modal-lg"><i class="mdi mdi-book-open mr-2 text-muted font-18 vertical-middle"></i>Rack Rate</a>`;
// Conditionally render the delete option based on the role
if (role !== 3 && role !== 4) {
if(checkDateStatus(item.policy_end_date) != 'Expired'){
policyTable += `
<a href="#" data-id="${item.id}" id="${search_term}" data-typeid="${item.policy_type_id}" class="dropdown-item" onclick="removepolicy(this)"><i class="mdi mdi-delete-outline mr-2 text-muted font-18 vertical-middle"></i>Delete</a>`;
<tr>
<td>${item.insurer_short} - ${item.insurer_branch_name}</td>
<td>${policy_name_data}</td>
<td>${item.branch_name ? item.branch_name : ' - '}</td>
<td>${tpaValue}</td>
<td>${(item.policy_start_date)} / ${(item.policy_end_date)}</td>
<td>${checkDateStatus(item.policy_end_date, 1)}</td>
<td>
<div class="btn-group dropdown">
<a href="javascript: void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm" data-toggle="dropdown"aria-expanded="false"><i class="mdi mdi-dots-horizontal"></i></a>
<div class="dropdown-menu dropdown-menu-right">
<a href="#" data-id="${item.id}" id="${item.policy_id}" class="dropdown-item btnPolicyEdit"><i class="mdi mdi-lead-pencil mr-2 text-muted font-18 vertical-middle"></i>Edit</a>
<a href="#" data-id="${item.id}" id="${search_term}" data-typeid="${item.policy_type_id}" class="dropdown-item btnPolicyMaster" ><i class="mdi mdi-wrench mr-2 text-muted font-18 vertical-middle"></i>Terms</a>
<a href="#" data-id="${item.id}" id="${search_term}" data-typeid="${item.policy_type_id}" class="dropdown-item btnPolicyModel" data-toggle="modal" data-target="#bs-example-modal-lg"><i class="mdi mdi-book-open mr-2 text-muted font-18 vertical-middle"></i>Rack Rate</a>`;
// Conditionally render the delete option based on the role
if (role != 3 && role != 4) {
policyTable += `
<a href="#" data-id="${item.id}" id="${search_term}" data-typeid="${item.policy_type_id}" class="dropdown-item" onclick="removepolicy(this)"><i class="mdi mdi-delete-outline mr-2 text-muted font-18 vertical-middle"></i>Delete</a>`;
}
policyTable += `
</div>
</div>
</td>
</tr>
`;
}
policyTable += `
</div>
</div>
</td>
</tr>
`;
});
$('#policy_table').append(policyTable);
// console.log(policyTable);
@ -713,6 +803,9 @@
//console.log('Unknown error occurred', 'Warning');
}
}, 1000);
},
complete :function(){
console.log('AJAX request completed');
}
});
@ -749,6 +842,17 @@
if(response.status == false && response.insurer_id != 'undefined'){
toastr.warning('The CD Account Number not found.', 'Warning');
$('#cd_ac_no').empty();
$('#cd_ac_no').append($('<option>', {
value: '',
text: 'Select CD Account Number'
}));
$('#cd_ac_no').append($('<option>', {
value: 'add_cd',
text: '+ Add New CD'
}));
return;
}
appendCDACNO(response.data)
@ -1713,15 +1817,18 @@
//console.log('appendCDACNO', select);
$('#cd_ac_no').empty();
$('#cd_ac_no').append($('<option>', {
value: '',
text: 'Select CD Account Number'
}));
$('#cd_ac_no').append($('<option>', {
value: 'add_cd',
text: '+ Add New CD'
}));
if(data.length == 0){
$('#cd_ac_no').append($('<option>', {
value: 'add_cd',
text: '+ Add New CD'
}));
}
$.each(data, function(index, item) {
const option = $('<option>', {
@ -2286,4 +2393,139 @@
}, 2000);
}
</script>
</script>
<script>
$(document).ready(function () {
$('#chk-show-expired').on('change', function () {
const showExpired = $(this).is(':checked');
let policyTable = '';
let data = <?= isset($client_policy) ? json_encode($client_policy) : '[]' ?>;
let role = data.role
delete data.role;
console.log("checkbox working");
$.each(data, function(index, item) {
// console.log('step 1');
let patternGMC = /gmc/i; // Case insensitive pattern for 'gmc'
let patternGPA = /gpa/i; // Case insensitive pattern for 'gpa'
let subject = item.policy_type_name;
//console.log('search terms subject', subject);
if (patternGMC.test(subject)) {
search_term = 'GMC';
} else if (patternGPA.test(subject)) {
search_term = 'GPA';
} else {
search_term = subject; // Set default value if neither 'GMC' nor 'GPA' exists
}
let tpaValue = 'TPA Unavailable';
if (item.tpa_short && item.tpa_branch_code) {
tpaValue = item.tpa_short + '-' + item.tpa_branch_code;
}
let policy_name_data = `${item.policy_type_name ?? ''}` + ' - ' + `${item.policy_no ?? ''}`;
if(showExpired == true && checkDateStatus(item.policy_end_date) == 'Expired'){
policyTable += `
<tr>
<td>${item.insurer_short} - ${item.insurer_branch_name}</td>
<td>${policy_name_data}</td>
<td>${item.branch_name ? item.branch_name : ' - '}</td>
<td>${tpaValue}</td>
<td>${(item.policy_start_date)} / ${(item.policy_end_date)}</td>
<td>${checkDateStatus(item.policy_end_date, 1)}</td>
<td>
<div class="btn-group dropdown">
<a href="javascript: void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm" data-toggle="dropdown"aria-expanded="false"><i class="mdi mdi-dots-horizontal"></i></a>
<div class="dropdown-menu dropdown-menu-right">
<a href="#" data-id="${item.id}" id="${item.policy_id}" class="dropdown-item btnPolicyEdit"><i class="mdi mdi-lead-pencil mr-2 text-muted font-18 vertical-middle"></i>Edit</a>
<a href="#" data-id="${item.id}" id="${search_term}" data-typeid="${item.policy_type_id}" class="dropdown-item btnPolicyMaster" ><i class="mdi mdi-wrench mr-2 text-muted font-18 vertical-middle"></i>Terms</a>
<a href="#" data-id="${item.id}" id="${search_term}" data-typeid="${item.policy_type_id}" class="dropdown-item btnPolicyModel" data-toggle="modal" data-target="#bs-example-modal-lg"><i class="mdi mdi-book-open mr-2 text-muted font-18 vertical-middle"></i>Rack Rate</a>`;
// Conditionally render the delete option based on the role
if (role != 3 && role != 4) {
policyTable += `
<a href="#" data-id="${item.id}" id="${search_term}" data-typeid="${item.policy_type_id}" class="dropdown-item" onclick="removepolicy(this)"><i class="mdi mdi-delete mr-2 text-muted font-18 vertical-middle"></i>Delete</a>`;
}
policyTable += `
</div>
</div>
</td>
</tr>
`;
}
if(showExpired == false && checkDateStatus(item.policy_end_date) != 'Expired'){
policyTable += `
<tr>
<td>${item.insurer_short} - ${item.insurer_branch_name}</td>
<td>${policy_name_data}</td>
<td>${item.branch_name ? item.branch_name : ' - '}</td>
<td>${tpaValue}</td>
<td>${(item.policy_start_date)} / ${(item.policy_end_date)}</td>
<td>${checkDateStatus(item.policy_end_date, 1)}</td>
<td>
<div class="btn-group dropdown">
<a href="javascript: void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm" data-toggle="dropdown"aria-expanded="false"><i class="mdi mdi-dots-horizontal"></i></a>
<div class="dropdown-menu dropdown-menu-right">
<a href="#" data-id="${item.id}" id="${item.policy_id}" class="dropdown-item btnPolicyEdit"><i class="mdi mdi-lead-pencil mr-2 text-muted font-18 vertical-middle"></i>Edit</a>
<a href="#" data-id="${item.id}" id="${search_term}" data-typeid="${item.policy_type_id}" class="dropdown-item btnPolicyMaster" ><i class="mdi mdi-wrench mr-2 text-muted font-18 vertical-middle"></i>Terms</a>
<a href="#" data-id="${item.id}" id="${search_term}" data-typeid="${item.policy_type_id}" class="dropdown-item btnPolicyModel" data-toggle="modal" data-target="#bs-example-modal-lg"><i class="mdi mdi-book-open mr-2 text-muted font-18 vertical-middle"></i>Rack Rate</a>`;
// Conditionally render the delete option based on the role
if (role != 3 && role != 4) {
policyTable += `
<a href="#" data-id="${item.id}" id="${search_term}" data-typeid="${item.policy_type_id}" class="dropdown-item" onclick="removepolicy(this)"><i class="mdi mdi-delete mr-2 text-muted font-18 vertical-middle"></i>Delete</a>`;
}
policyTable += `
</div>
</div>
</td>
</tr>
`;
}
});
const table = $('#table-client-policy').DataTable();
table.clear().destroy();
$('#table-client-policy tbody').html(policyTable); // replace tbody content
$('#table-client-policy').DataTable({
paging: true,
searching: true,
autoWidth: false,
responsive: true,
});
});
});
</script>

View File

@ -508,7 +508,7 @@
</table> -->
<!-- <button type="button" id="add_row_btn" class="btn btn-secondary float-right mt-2"><i class="fa fa-plus"></i></button> -->
<div class="payment-card">
<div class="payment-card" id="default_payment_card">
<input type="hidden" class="form-control" name="pk[]" placeholder="Enter Amount">
<div class="row">
<div class="col">
@ -959,19 +959,54 @@
return parts[2] + '/' + parts[1] + '/' + parts[0]; // Rearrange to DD-MM-YYYY
}
function togglePaymentCardRequired(flag) {
// Select the default payment card container
const card = document.getElementById("default_payment_card");
if (!card) return;
// Select all input elements inside the card
const inputs = card.querySelectorAll("input");
inputs.forEach(input => {
if (flag) {
input.setAttribute("required", "required");
} else {
input.removeAttribute("required");
}
});
}
function showInvoiceStatusModal(event) {
console.log('############ showInvoiceStatusModal function called ##################');
var modal_received_amt_div = document.getElementById('modal_received_amt_div');
modal_received_amt_div.style.display = 'none';
// alert();
// console.log(event.target.data)
var dataId = event.target.getAttribute('data-id');
// make sure event exists
event = event || window.event;
// the element actually clicked
const clicked = event.target;
// find the nearest ancestor <a> (or element) that has data-id
const anchor = clicked.closest('a[data-id], .btnEdit');
if (!anchor) {
console.warn('Could not find element with data-id');
return;
}
const dataId = anchor.getAttribute('data-id');
const expAmt = anchor.getAttribute('data-exp-amt');
const receivedAmt = anchor.getAttribute('data-received-amt');
console.log('stmt id :', dataId, expAmt, receivedAmt);
var dataExpAmt = event.target.getAttribute('data-exp-amt');
var dataReceivedAmt = event.target.getAttribute('data-received-amt');
// Set the value to a hidden input field in the modal
document.getElementById('hidden_statement_id').value = dataId;
// document.getElementById('modal_exp_amt').value = dataExpAmt;
document.getElementById('modal_received_amt').value = dataReceivedAmt;
document.getElementById('modal_received_amt').value = receivedAmt;
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
@ -981,10 +1016,78 @@
method: 'get',
// data: { id: dataId },
// dataType: 'json',
// success: function(response) {
// $('.loader').fadeOut();
// $('.loader-mask').delay(10).fadeOut('slow');
// console.log(response);
// // Assuming response contains the necessary data
// if (response.dataStatus === true && response.code === 200) {
// // Populate modal fields
// if (response.data.invoice_status !== null) {
// var inv_status_element = document.getElementById('invoice_status');
// inv_status_element.value = response.data.invoice_status;
// var event = new Event('change');
// inv_status_element.dispatchEvent(event);
// }
// document.getElementById('invoice_no_modal').value = response.data.invoice_no;
// document.getElementById('invoice_date_modal').value = response.data.invoice_date === '' ? <?php echo date('d-m-Y') ?> : response.data.invoice_date;
// document.getElementById('invoice_amount_no_modal').value = response.data.invoice_amount;
// document.getElementById('invoice_value_modal').value = response.data.invoice_value;
// document.getElementById('gst_per_modal').value = response.data.gst_per;
// document.getElementById('gst_value_modal').value = response.data.gst_value;
// console.log('response.data.gst_value - ' + response.data.gst_value);
// if (response.data.gst_value == 0 || response.data.gst_value == '' || response.data.gst_value == null) {
// calcGSTValue();
// }
// if (!$('#invoice_date_modal').val()) {
// // alert('nope');
// // Set today's date as the default date
// $('#invoice_date_modal').datepicker('setDate', new Date());
// }
// // Clear existing rows in the payment table
// var paymentTableBody = document.querySelector('#payment_table_modal tbody');
// // var paymentTableBody = document.getElementById('payment_card_container');
// console.log('response.data.payments.length', response.data.payments.length)
// // Populate payment table rows
// if (response.data.payments.length) {
// paymentTableBody.innerHTML = '';
// response.data.payments.forEach(function(payment) {
// var row = paymentTableBody.insertRow();
// row.innerHTML = `
// <td style="display: none;"><input type="hidden" class="form-control" name="pk[]" value="${payment.id}"></td>
// <td><input type="number" class="form-control" name="received_amount[]" placeholder="Enter Amount" value="${payment.inv_amt}" onchange="checkInvAmont(event)" required step="0.01"></td>
// <td><input type="number" class="form-control" name="gst_amount[]" placeholder="Enter Amount" value="${payment.gst}" onchange="checkInvAmont(event)" required step="0.01"></td>
// <td><input type="number" class="form-control" name="tds[]" placeholder="Enter Amount" value="${payment.tds}" onchange="checkInvAmont(event)" required></td>
// <td><input type="text" class="form-control" name="utr_no[]" placeholder="Enter UTR No" value="${payment.utr_no}" required></td>
// <td><input type="text" class="form-control payment_date" name="payment_date[]" value="${formatDateToDMY(payment.received_date)}" required readonly></td>
// <td><i class="mdi mdi-delete mr-2 font-18 vertical-middle text-danger remove-row" style="text-align: center;"></i></td>
// `;
// });
// }
// $('.payment_date').datepicker({
// format: 'dd/mm/yyyy',
// autoclose: true
// });
// // Show the modal
// var myModal = new bootstrap.Modal(document.getElementById('invoice_modal'));
// myModal.show();
// } else {
// // Handle error if the response is not successful
// console.error('Failed to fetch data:', response);
// alert("Something went wrong! Couldn't get data");
// }
// },
success: function(response) {
$('.loader').fadeOut();
$('.loader-mask').delay(10).fadeOut('slow');
console.log(response);
// Assuming response contains the necessary data
if (response.dataStatus === true && response.code === 200) {
// Populate modal fields
@ -996,46 +1099,84 @@
}
document.getElementById('invoice_no_modal').value = response.data.invoice_no;
document.getElementById('invoice_date_modal').value = response.data.invoice_date === '' ? <?php echo date('d-m-Y') ?> : response.data.invoice_date;
document.getElementById('invoice_date_modal').value = response.data.invoice_date === '' ? '<?php echo date('d-m-Y') ?>' : response.data.invoice_date;
document.getElementById('invoice_amount_no_modal').value = response.data.invoice_amount;
document.getElementById('invoice_value_modal').value = response.data.invoice_value;
document.getElementById('gst_per_modal').value = response.data.gst_per;
document.getElementById('gst_value_modal').value = response.data.gst_value;
console.log('response.data.gst_value - ' + response.data.gst_value);
if (response.data.gst_value == 0 || response.data.gst_value == '' || response.data.gst_value == null) {
calcGSTValue();
}
if (!$('#invoice_date_modal').val()) {
// alert('nope');
// Set today's date as the default date
$('#invoice_date_modal').datepicker('setDate', new Date());
}
// Clear existing rows in the payment table
var paymentTableBody = document.querySelector('#payment_table_modal tbody');
// Clear existing payment cards in the container
var defaultPaymentCardContainer = document.getElementById('default_payment_card');
defaultPaymentCardContainer.style.display = 'block';
togglePaymentCardRequired(true);
var paymentCardContainer = document.getElementById('payment_card_container');
paymentCardContainer.innerHTML = '';
console.log('response.data.payments.length', response.data.payments.length)
// Populate payment table rows
console.log('response.data.payments.length', response.data.payments.length);
// Populate payment cards
if (response.data.payments.length) {
paymentTableBody.innerHTML = '';
response.data.payments.forEach(function(payment) {
var row = paymentTableBody.insertRow();
row.innerHTML = `
<td style="display: none;"><input type="hidden" class="form-control" name="pk[]" value="${payment.id}"></td>
<td><input type="number" class="form-control" name="received_amount[]" placeholder="Enter Amount" value="${payment.inv_amt}" onchange="checkInvAmont(event)" required step="0.01"></td>
<td><input type="number" class="form-control" name="gst_amount[]" placeholder="Enter Amount" value="${payment.gst}" onchange="checkInvAmont(event)" required step="0.01"></td>
<td><input type="number" class="form-control" name="tds[]" placeholder="Enter Amount" value="${payment.tds}" onchange="checkInvAmont(event)" required></td>
<td><input type="text" class="form-control" name="utr_no[]" placeholder="Enter UTR No" value="${payment.utr_no}" required></td>
<td><input type="text" class="form-control payment_date" name="payment_date[]" value="${formatDateToDMY(payment.received_date)}" required readonly></td>
<td><i class="mdi mdi-delete mr-2 font-18 vertical-middle text-danger remove-row" style="text-align: center;"></i></td>
defaultPaymentCardContainer.style.display = 'none';
togglePaymentCardRequired(false);
// if (defaultPaymentCardContainer) {
// defaultPaymentCardContainer.remove();
// }
response.data.payments.forEach(function(payment, index) {
var paymentCard = document.createElement('div');
paymentCard.className = 'payment-card';
paymentCard.innerHTML = `
<input type="hidden" class="form-control" name="pk[]" value="${payment.id}">
<div class="row">
<div class="col">
<label>Invoice value</label>
<input type="number" class="form-control" name="received_amount[]" placeholder="Enter Amount" value="${payment.inv_amt}" required step="0.01" onchange="checkInvAmont(event)">
</div>
<div class="col">
<label>GST</label>
<input type="number" class="form-control" name="gst_amount[]" placeholder="Enter GST" value="${payment.gst}" required step="0.01" onchange="checkInvAmont(event)">
</div>
<div class="col">
<label>TDS</label>
<input type="number" class="form-control" name="tds[]" placeholder="Enter TDS" value="${payment.tds}" onchange="checkInvAmont(event)" required>
</div>
<div class="col">
<label>UTR Number</label>
<input type="text" class="form-control" name="utr_no[]" placeholder="Enter UTR No" value="${payment.utr_no}" required>
</div>
<div class="col">
<label>Date</label>
<input type="text" class="form-control payment_date" name="payment_date[]" value="${formatDateToDMY(payment.received_date)}" placeholder="dd/mm/yyyy" required readonly>
</div>
<div class="col-auto d-flex align-items-end">
<button type="button" class="btn btn-danger btn-sm remove-row">
<i class="mdi mdi-delete"></i>
</button>
</div>
</div>
`;
paymentCardContainer.appendChild(paymentCard);
});
}
// Initialize datepicker for all payment date fields
$('.payment_date').datepicker({
format: 'dd/mm/yyyy',
autoclose: true
});
// Show the modal
var myModal = new bootstrap.Modal(document.getElementById('invoice_modal'));
myModal.show();

View File

@ -149,7 +149,7 @@
<style>
.nav-bar {
position: fixed !important;
z-index: 2;
z-index: 4;
width: 90%;
margin-left: 120px !important;
background: #fff;
@ -1792,6 +1792,15 @@
<li>
<a href="<?= base_url('/user/list') ?>"> Users </a>
</li>
<li>
<a href="<?= base_url('/util/nhanceBranchMaster') ?>"> Nhance Branch </a>
</li>
<li>
<a href="<?= base_url('/util/vehicleTypeMaster') ?>"> Vehicle Type </a>
</li>
<li>
<a href="<?= base_url('/util/rtoMaster') ?>"> RTO </a>
</li>
<?php } ?>

View File

@ -452,6 +452,58 @@ if (isset($selected_lead_type)) {
$('#salse_person_id').trigger('change');
}
// $('#client_name').on('input', generateShortName);
let shortNameTimer;
$('#client_name').on('input', function() {
clearTimeout(shortNameTimer);
shortNameTimer = setTimeout(generateShortName, 200);
});
function generateShortName() {
let clientInput = $("#client_name");
let shortInput = $("#client_short_name");
let newClientName = clientInput.val().trim();
console.log(`LN : NEW - ${newClientName}`);
if (newClientName.length == 0) {
shortInput.val('');
return;
}
let shortName = newClientName.substring(0, 10).replace(/\s+/g, '').toUpperCase();
makeUniqueShortName(shortName);
}
function makeUniqueShortName(baseName) {
let input = $("#client_short_name")[0];
checkDuplicateTableFieldValue("clients", "short_name", baseName, function(isDuplicate) {
if (isDuplicate) {
let counter = 1;
function tryNext() {
let padded = String(counter).padStart(3, '0'); // 001, 002, 003
let newName = baseName + padded;
checkDuplicateTableFieldValue("clients", "short_name", newName, function(exists) {
if (exists) {
counter++;
tryNext();
} else {
$("#client_short_name").val(newName);
validateInput(input, "clients", "short_name");
}
});
}
tryNext();
} else {
$("#client_short_name").val(baseName);
validateInput(input, "clients", "short_name");
}
});
}
function validateInput(input, table, field){
let client_type = $('#client_type').val();

View File

@ -300,126 +300,123 @@ table.dataTable tbody td {
<script>
document.addEventListener("DOMContentLoaded", function () {
const table = document.getElementById("tickets-table");
function createCustomDropdown(row) {
const originalDropdown = row.querySelector('.dropdown-menu');
if (!originalDropdown) return null;
// New menu
document.addEventListener("DOMContentLoaded", function () {
const table = document.getElementById("tickets-table");
const customDropdown = document.createElement('div');
customDropdown.className = 'custom-dropdown-menu';
// Clone the items but remove their original click handlers
const items = originalDropdown.querySelectorAll('.dropdown-item');
items.forEach(item => {
const newItem = item.cloneNode(true);
// Preserve the attributes but remove the onclick
newItem.removeAttribute('onclick');
customDropdown.appendChild(newItem);
});
return customDropdown;
}
let activeDropdown = null;
table.querySelectorAll("tbody tr").forEach(row => {
const customDropdown = createCustomDropdown(row);
if (!customDropdown) return;
document.body.appendChild(customDropdown);
row.addEventListener("click", function(event) {
// Ignore clicks on the action column
if (event.target.closest('td:last-child')) {
return;
}
if (activeDropdown) {
activeDropdown.style.display = 'none';
}
const rect = event.target.getBoundingClientRect();
function createCustomDropdown(row) {
const originalDropdown = row.querySelector('.dropdown-menu');
if (!originalDropdown) return null;
customDropdown.style.display = 'block';
customDropdown.style.position = 'fixed';
customDropdown.style.left = `${rect.left}px`;
customDropdown.style.top = `${rect.bottom + 5}px`;
const customDropdown = document.createElement('div');
customDropdown.className = 'custom-dropdown-menu';
activeDropdown = customDropdown;
event.stopPropagation();
});
// Clone the items but remove their original click handlers
const items = originalDropdown.querySelectorAll('.dropdown-item');
items.forEach(item => {
const newItem = item.cloneNode(true);
// Preserve the attributes but remove the onclick
newItem.removeAttribute('onclick');
customDropdown.appendChild(newItem);
});
return customDropdown;
}
// Handle clicks on dropdown items
customDropdown.querySelectorAll('.dropdown-item').forEach(item => {
item.addEventListener('click', function(e) {
console.log("##############");
e.preventDefault();
e.stopPropagation();
let activeDropdown = null;
// Get the data-id and other attributes from the original button
const originalItem = row.querySelector(`.dropdown-item[data-id="${this.getAttribute('data-id')}"]`);
// For edit functionality
if (this.classList.contains('btnEdit')) {
const id = this.getAttribute('data-id');
const lead_form_type = this.getAttribute('data-ft');
console.log('second drop lead_form_type', lead_form_type)
if (id) {
getLeadsDataForEdit(id, lead_form_type);
}
}else if (this.classList.contains('btnHistory')) {
let lead_id = this.getAttribute('data-id');
if(lead_id){ console.log("******** Clicked from td lead_id-", lead_id); getLeadsDataForMailHistory(lead_id); }
else{ console.log("******** Clicked from td but i don`t have lead_id"); }
}
else{
const onclickAttr = this.getAttribute('onclick');
if (onclickAttr) {
eval(onclickAttr);
}
}
// For RFQ links
const href = this.getAttribute('href');
if (href && href !== '#' && !this.classList.contains('btnEdit')) {
window.location.href = href;
table.querySelectorAll("tbody tr").forEach(row => {
const customDropdown = createCustomDropdown(row);
if (!customDropdown) return;
document.body.appendChild(customDropdown);
row.addEventListener("click", function(event) {
// Ignore clicks on the action column
if (event.target.closest('td:last-child')) {
return;
}
// Close the dropdown
if (activeDropdown) {
activeDropdown.style.display = 'none';
activeDropdown = null;
}
const rect = event.target.getBoundingClientRect();
customDropdown.style.display = 'block';
customDropdown.style.position = 'fixed';
customDropdown.style.left = `${rect.left}px`;
customDropdown.style.top = `${rect.bottom + 5}px`;
activeDropdown = customDropdown;
event.stopPropagation();
});
// Handle clicks on dropdown items
customDropdown.querySelectorAll('.dropdown-item').forEach(item => {
item.addEventListener('click', function(e) {
console.log("##############");
e.preventDefault();
e.stopPropagation();
// Get the data-id and other attributes from the original button
const originalItem = row.querySelector(`.dropdown-item[data-id="${this.getAttribute('data-id')}"]`);
// For edit functionality
if (this.classList.contains('btnEdit')) {
const id = this.getAttribute('data-id');
const lead_form_type = this.getAttribute('data-ft');
console.log('second drop lead_form_type', lead_form_type)
if (id) {
getLeadsDataForEdit(id, lead_form_type);
}
}else if (this.classList.contains('btnHistory')) {
let lead_id = this.getAttribute('data-id');
if(lead_id){ console.log("******** Clicked from td lead_id-", lead_id); getLeadsDataForMailHistory(lead_id); }
else{ console.log("******** Clicked from td but i don`t have lead_id"); }
}
else{
const onclickAttr = this.getAttribute('onclick');
if (onclickAttr) {
eval(onclickAttr);
}
}
// For RFQ links
const href = this.getAttribute('href');
if (href && href !== '#' && !this.classList.contains('btnEdit')) {
window.location.href = href;
}
// Close the dropdown
if (activeDropdown) {
activeDropdown.style.display = 'none';
activeDropdown = null;
}
});
});
});
// Close dropdown when clicking outside
document.addEventListener("click", function() {
if (activeDropdown) {
activeDropdown.style.display = 'none';
activeDropdown = null;
}
});
document.addEventListener("click", function(e) {
if (e.target.closest(".btnHistory")) {
let lead_id = e.target.closest(".btnHistory").dataset.id;
console.log("******** in triple dot id available - " + lead_id);
getLeadsDataForMailHistory(lead_id);
}
else{ console.log("******** in triple dot but id not available"); }
});
});
// Close dropdown when clicking outside
document.addEventListener("click", function() {
if (activeDropdown) {
activeDropdown.style.display = 'none';
activeDropdown = null;
}
});
document.addEventListener("click", function(e) {
if (e.target.closest(".btnHistory")) {
let lead_id = e.target.closest(".btnHistory").dataset.id;
console.log("******** in triple dot id available - " + lead_id);
getLeadsDataForMailHistory(lead_id);
}
else{ console.log("******** in triple dot but id not available"); }
});
});
</script>
<script>
// Datatable document ready
$(document).ready(function() {
@ -504,141 +501,143 @@ document.addEventListener("DOMContentLoaded", function () {
function getLeadsDataForMailHistory(lead_id){
console.log("******** Inside Fnz :", lead_id);
let url = '<?= base_url('/util/getLeadEmailHistory/') ?>' + lead_id;
console.log("******** Fetching:", url);
console.log("******** Inside Fnz :", lead_id);
let url = '<?= base_url('/util/getLeadEmailHistory/') ?>' + lead_id;
console.log("******** Fetching:", url);
fetch(url, {
method: "GET",
headers: { "Accept": "application/json" }
})
.then(response => response.json())
.then(response => {
let container = document.querySelector(".history-container");
container.innerHTML = "";
if (response.status === "success" && response.data.length > 0) {
console.log("******** 1" + response.status);
let table = `
<div class="table-responsive">
<table data-custom-table-css="table" id="historytable" class="table table-striped mb-0 nowrap" cellspacing="0" id="tickets-table">
fetch(url, {
method: "GET",
headers: { "Accept": "application/json" }
})
.then(response => response.json())
.then(response => {
let container = document.querySelector(".history-container");
container.innerHTML = "";
if (response.status === "success" && response.data.length > 0) {
console.log("******** 1" + response.status);
let table = `
<div class="table-responsive">
<table data-custom-table-css="table" id="historytable" class="table table-striped mb-0 nowrap" cellspacing="0" id="tickets-table">
<thead class="bg-light">
<tr>
<th><div class="column-header">S.No&nbsp;</div></th>
<th><div class="column-header">From Mail&nbsp;</div></th>
<th><div class="column-header">To Mail&nbsp;</div></th>
<th><div class="column-header">BCC&nbsp;</div></th>
<th><div class="column-header">CC&nbsp;</div></th>
<th><div class="column-header">Type&nbsp;</div></th>
<th><div class="column-header">Status&nbsp;</div></th>
<th><div class="column-header">Date/Time&nbsp;</div></th>
</tr>
</thead>
<tbody>
`;
<thead class="bg-light">
<tr>
<th><div class="column-header">S.No&nbsp;</div></th>
<th><div class="column-header">From Mail&nbsp;</div></th>
<th><div class="column-header">To Mail&nbsp;</div></th>
<th><div class="column-header">BCC&nbsp;</div></th>
<th><div class="column-header">CC&nbsp;</div></th>
<th><div class="column-header">Type&nbsp;</div></th>
<th><div class="column-header">Status&nbsp;</div></th>
<th><div class="column-header">Date/Time&nbsp;</div></th>
</tr>
</thead>
<tbody>
`;
response.data.forEach((row, index) => {
let formattedDate = "-";
let statusValue = "-";
if (row.received_message) {
if (row.received_message.toLowerCase().includes("error")) {
statusValue = "Failed";
} else {
statusValue = "Success";
}
}
if (row.created_at) {
let dt = new Date(row.created_at);
let dateStr = dt.toLocaleDateString("en-GB", {
day: "2-digit",
month: "long",
year: "numeric"
});
let timeStr = dt.toLocaleTimeString("en-US", {
hour: "2-digit",
minute: "2-digit",
hour12: true
}).toLowerCase();
formattedDate = `${dateStr} ${timeStr}`;
}
let fromMails = "-";
if (row.from_mail) {
fromMails = row.from_mail
.split(",") // split by comma
.map(m => m.trim().replace(/^"|"$/g, "")) // trim + remove quotes at start/end
.filter(m => m !== "") // remo
.join("<br>"); // join with line break
}
let toMails = "-";
if (row.mail) {
toMails = row.mail
.split(",")
.map(m => m.trim().replace(/^"|"$/g, ""))
.filter(m => m !== "")
.join("<br>");
}
let ccMails = "-";
if (row.cc && row.cc.trim() !== "") {
ccMails = row.cc
.split(",")
.map(m => m.trim().replace(/^"|"$/g, ""))
.filter(m => m !== "")
.join("<br>");
}
let bccMails = "-";
if (row.bcc && row.bcc.trim() !== "") {
bccMails = row.bcc
.split(",")
.map(m => m.trim().replace(/^"|"$/g, ""))
.filter(m => m !== "")
.join("<br>");
}
response.data.forEach((row, index) => {
let formattedDate = "-";
let statusValue = "-";
if (row.received_message) {
if (row.received_message.toLowerCase().includes("error")) {
statusValue = "Failed";
} else {
statusValue = "Success";
}
}
if (row.created_at) {
let dt = new Date(row.created_at);
let dateStr = dt.toLocaleDateString("en-GB", {
day: "2-digit",
month: "long",
year: "numeric"
});
let timeStr = dt.toLocaleTimeString("en-US", {
hour: "2-digit",
minute: "2-digit",
hour12: true
}).toLowerCase();
formattedDate = `${dateStr} ${timeStr}`;
}
let fromMails = "-";
if (row.from_mail) {
fromMails = row.from_mail
.split(",") // split by comma
.map(m => m.trim().replace(/^"|"$/g, "")) // trim + remove quotes at start/end
.filter(m => m !== "") // remo
.join("<br>"); // join with line break
}
let toMails = "-";
if (row.mail) {
toMails = row.mail
.split(",")
.map(m => m.trim().replace(/^"|"$/g, ""))
.filter(m => m !== "")
.join("<br>");
}
let ccMails = "-";
if (row.cc && row.cc.trim() !== "") {
ccMails = row.cc
.split(",")
.map(m => m.trim().replace(/^"|"$/g, ""))
.filter(m => m !== "")
.join("<br>");
}
let bccMails = "-";
if (row.bcc && row.bcc.trim() !== "") {
bccMails = row.bcc
.split(",")
.map(m => m.trim().replace(/^"|"$/g, ""))
.filter(m => m !== "")
.join("<br>");
}
table += `
<tr>
<td style="white-space: nowrap !important;">${index + 1}</td>
<td style="white-space: nowrap !important;">${fromMails}</td>
<td style="white-space: nowrap !important;">${toMails}</td>
<td style="white-space: nowrap !important;">${bccMails ? bccMails : '-'}</td>
<td style="white-space: nowrap !important;">${ccMails ? ccMails : '-'}</td>
<td style="white-space: nowrap !important;">${row.mail_type ? row.mail_type.toUpperCase() : '-'}</td>
<td style="white-space: nowrap !important;">${statusValue ? statusValue.toUpperCase() : '-'}</td>
<td style="white-space: nowrap !important;">${formattedDate}</td>
</tr>
`;
});
table += `</tbody></table>`;
container.innerHTML = table;
// show modal (if using Bootstrap 5)
} else {
container.innerHTML = `
<div class="d-flex justify-content-center align-items-center" style="height: 50vh; width:100%;">
<p class="text-center font-color-black"><i>${response.message ?? "No History Available"}</i></p>
</div>
`;
}
// Show modal always
new bootstrap.Modal(document.getElementById("EmailModal")).show();
})
.catch(error => {
console.log("******** 3" + error);
document.querySelector(".history-container").innerHTML = `
<div class="d-flex justify-content-center align-items-center" style="height: 50vh; width:100%;">
<p class="text-center font-color-black"><i>No Data Found</i></p>
</div>
`;
let EmailModal = new bootstrap.Modal(document.getElementById("EmailModal"));
EmailModal.show();
console.error(error);
table += `
<tr>
<td style="white-space: nowrap !important;">${index + 1}</td>
<td style="white-space: nowrap !important;">${fromMails}</td>
<td style="white-space: nowrap !important;">${toMails}</td>
<td style="white-space: nowrap !important;">${bccMails ? bccMails : '-'}</td>
<td style="white-space: nowrap !important;">${ccMails ? ccMails : '-'}</td>
<td style="white-space: nowrap !important;">${row.mail_type ? row.mail_type.toUpperCase() : '-'}</td>
<td style="white-space: nowrap !important;">${statusValue ? statusValue.toUpperCase() : '-'}</td>
<td style="white-space: nowrap !important;">${formattedDate}</td>
</tr>
`;
});
}
table += `</tbody></table>`;
container.innerHTML = table;
// show modal (if using Bootstrap 5)
} else {
container.innerHTML = `
<div class="d-flex justify-content-center align-items-center" style="height: 50vh; width:100%;">
<p class="text-center font-color-black"><i>${response.message ?? "No History Available"}</i></p>
</div>
`;
}
// Show modal always
new bootstrap.Modal(document.getElementById("EmailModal")).show();
})
.catch(error => {
console.log("******** 3" + error);
document.querySelector(".history-container").innerHTML = `
<div class="d-flex justify-content-center align-items-center" style="height: 50vh; width:100%;">
<p class="text-center font-color-black"><i>No Data Found</i></p>
</div>
`;
let EmailModal = new bootstrap.Modal(document.getElementById("EmailModal"));
EmailModal.show();
console.error(error);
});
}
</script>
<script>
function selectOption(element, radioId) {
// Remove selected class from all options
document.querySelectorAll('.radio-option').forEach(option => {

View File

@ -0,0 +1,291 @@
<style>
.dataTables_filter {
position: absolute;
}
</style>
<!-- End ADD and EDIT Page HTML -->
<div class="row" id="List-page">
<div class="col-12">
<div class="card">
<div class="card-body maincard">
<table data-custom-table-css="table" class="table table-sm m-0 table-centered dt-responsive nowrap w-100" cellspacing="a" id="user-table">
<thead class="bg-light">
<tr>
<th class="font-weight-medium">S.No.</th>
<th class="font-weight-medium">Branch Name</th>
<!-- <th class="font-weight-medium">Status</th> -->
<th class="font-weight-medium">Action</th>
</tr>
</thead>
<tbody>
<?php if(isset($data)) { $slno = 1; ?>
<?php foreach($data as $index => $row) { ?>
<tr>
<td class="text-center"><?= $slno++; ?></td>
<td><?= $row['branch_name']; ?></td>
<!-- <td>
<span class="<?php if($row['is_active'] == 1){ echo 'badge badge-primary'; }else{ echo 'badge badge-danger'; } ?>">
<?php if($row['is_active'] == 1){ echo 'Active'; }else{ echo 'In-Active'; } ?>
</span>
</td> -->
<td>
<div class="btn-group dropdown" style="position: relative !important;left:0px !important;top:0px !important;">
<a href="javascript: void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm" data-toggle="dropdown" aria-expanded="false"><i class="mdi mdi-dots-horizontal"></i></a>
<div class="dropdown-menu dropdown-menu-right" style="cursor: pointer;">
<a class="dropdown-item" data-id="<?= $row['id']; ?>" onclick="handleSaveEditAndDelete('edit', this)">
<i class="mdi mdi-pencil mr-2 text-muted font-18 vertical-middle"></i>Edit
</a>
<?php if ($row['is_active'] == 1): ?>
<a class="dropdown-item" data-id="<?= $row['id']; ?>" onclick="handleSaveEditAndDelete('remove', this)">
<i class="mdi mdi-delete mr-2 text-muted font-18 vertical-middle"></i>Delete
</a>
<?php endif; ?>
</div>
</div>
</td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td colspan="3" class="text-center">No data available</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- modal content -->
<div id="con-close-modal" class="modal fade app-font-family" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;" data-backdrop="static">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="modalLabel">Add Branch</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body p-4">
<!-- <form class="parsley-examples" id="nhanceBranchForm" enctype="multipart/form-data"> -->
<form id="nhanceBranchForm" enctype="multipart/form-data">
<input type="hidden" name="pk" id="nhance_branch_id"/>
<div class="form-group">
<div class="form-row">
<div class="form-group col-md-12">
<label for="branch_name">Branch Name<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="branch_name" name="branch_name" placeholder="Enter Branch Name" required>
</div>
</div>
</div>
<div class="form-group text-right m-b-0">
<button type="button" class="btn app-btn-secondary waves-effect waves-light" id="btnSubmit" onclick="handleSaveEditAndDelete('submit')">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
var table;
$(document).ready(function () {
var ticketsTable = $('#user-table');
ticketsTable.DataTable({
scrollX: true,
dom: "<'row'<'col-sm-7'f><'col-sm-5 text-right'B>>" + // Filter left, buttons right
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>", // Pagination at the bottom, without page length selector
buttons: [
{
text: 'Add',
className: 'btn app-btn-primary mr-2',
action: function(e, dt, node, config) {
openModal()
}
},
{
extend: 'collection',
text: '<span class=" btn-custom"> Export </span><i class="mdi mdi-menu-down"></i>',
className: 'btn app-btn-secondary ',
buttons: [
{
extend: 'csv',
text: '<i class="mdi mdi-file-delimited " ></i><span class=" btn-custom"> CSV </span>',
title: 'Policy-Tranction-Inception-List',
className: 'app-btn-primary ',
exportOptions: {
columns: ':not(:last-child)'
},
}
]
}
],
language: {
search: `
<div class="datatable-search-wrapper">
_INPUT_
<i class="mdi mdi-magnify datatable-search-icon"></i>
</div>`,
searchPlaceholder: "Search"
},
paging: true, // Enable pagination
pageLength: 10, // Set default number of rows per page (optional)
// ordering: false,
});
});
$('.close').click(function(){
resetValues()
})
function openModal(){
var myModal = new bootstrap.Modal(document.getElementById('con-close-modal'));
myModal.show();
}
// old Version
// function handleSaveEditAndDelete(type = 'submit', pk = null){
// let url = '<?= base_url('util/nhanceBranchMaster') ?>';
// let method = "POST";
// let requestData = {};
// $('#modalLabel').text('Add Branch');
// requestData.pk = pk;
// if(type == 'submit'){
// $("#nhanceBranchForm").find("input, select, textarea").each(function () {
// let name = $(this).attr("name");
// let value = $.trim($(this).val());
// if (name) requestData[name] = value;
// });
// }
// if(type == 'remove'){
// method = "DELETE";
// }else if (type == 'edit'){
// method = "GET"
// }
// console.log("type", type)
// console.log("url", url)
// console.log("method", method)
// console.log("requestData", requestData)
// $('.loader').fadeIn();
// $('.loader-mask').fadeIn();
// // Send AJAX request
// sendAjaxRequestForGlobal(url, method, requestData, function(response) {
// console.log('Data fetched successfully:', response);
// if (response.status) {
// if(type == 'edit'){
// $('#modalLabel').text('Edit Branch');
// appendEditData(response.data);
// }else{
// toastr.success(response.message, 'SUCCESS');
// }
// } else {
// toastr.warning(response.message, 'WARNING');
// }
// $('.loader').fadeOut();
// $('.loader-mask').delay(350).fadeOut('slow');
// }, function(xhr, status, error) {
// console.error('Error fetching data:', error);
// console.error(xhr.responseText);
// $('.loader').fadeOut();
// $('.loader-mask').delay(350).fadeOut('slow');
// });
// }
function handleSaveEditAndDelete(type = 'submit', el = null) {
let url = '<?= base_url('util/nhanceBranchMaster') ?>';
let method = "POST";
let requestData = {};
let pk = null;
// If element is passed (from edit/remove button), get its data-id
if (el) { pk = $(el).data('id'); }
requestData.pk = pk;
if(type == 'submit'){
$("#nhanceBranchForm").find("input, select, textarea").each(function () {
let name = $(this).attr("name");
let value = $.trim($(this).val());
if (name) requestData[name] = value;
});
}
if(type == 'remove'){
method = "DELETE";
} else if (type == 'edit'){
method = "GET";
$('#modalLabel').text('Edit Branch');
$('#nhanceBranchForm')[0].reset();
}
console.log("type", type)
console.log("url", url)
console.log("method", method)
console.log("requestData", requestData)
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
// Send AJAX request
sendAjaxRequestForGlobal(url, method, requestData, function(response) {
console.log('Data fetched successfully:', response);
if (response.status) {
if(type == 'edit'){
appendEditData(response.data);
} else if(type == 'remove'){
toastr.success(response.message, 'Success');
if(el) $(el).closest('tr').remove();
window.location.reload();
} else if(type == 'submit'){
toastr.success(response.message, 'Success');
var myModal = new bootstrap.Modal(document.getElementById('con-close-modal'));
myModal.hide();
$('#nhanceBranchForm')[0].reset();
window.location.reload();
}
} else {
toastr.warning(response.message, 'Warning');
}
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
}, function(xhr, status, error) {
console.error('Error fetching data:', error);
console.error(xhr.responseText);
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
});
}
function resetValues(){
$('#modalLabel').text('Add Branch');
$('#nhanceBranchForm')[0].reset();
}
function appendEditData(data){
$('#nhance_branch_id').val(data[0]['id']);
$('#branch_name').val(data[0]['branch_name']);
openModal()
}
</script>

File diff suppressed because it is too large Load Diff

View File

@ -327,7 +327,7 @@ table.dataTable thead th {
<?php foreach ($endorsement_data_list as $index => $row) { ?>
<tr>
<td class="text-center"><?php echo $index + 1; ?></td>
<td><?php echo $issuer[$row['issuer']] ?: 'N/A'; ?></td><!-- Issuer -->
<td><?php echo $issuer[$row['issuer']] ?? 'N/A'; ?></td><!-- Issuer -->
<td><?php echo $row['client_short_name'] ?: 'N/A'; ?></td><!-- Client -->
<td><?php echo $row['client_branch_name'] ?: 'N/A'; ?></td><!-- Branch -->
<td><?php echo $row['insurer_short_name'] ?: 'N/A'; ?></td><!-- Insurer -->
@ -346,6 +346,9 @@ table.dataTable thead th {
<a class="dropdown-item btnEdit" data-id="<?= $row['id']; ?>" onclick="getPolicyTransactionDataForEndorsementEdit('<?= htmlspecialchars($row['id'], ENT_QUOTES) ?>')">
<i class="mdi mdi-pencil mr-2 text-muted font-18 vertical-middle"></i>Edit
</a>
<a class="dropdown-item delete" data-id="<?= $row['id'];?>" onclick="removePolicyTransaction(this, '<?= htmlspecialchars($row['id'], ENT_QUOTES) ?>', <?= $row['policy_type_id'] ?>)">
<i class="mdi mdi-delete mr-2 text-muted font-18 vertical-middle"></i>Delete
</a>
</div>
</div>
</td>
@ -689,7 +692,7 @@ table.dataTable thead th {
});
}
function appendPolicies(data) {
function appendPolicies(data, policy_id=null) {
if (!data) {
toastr.warning("There are no policies in Inception for the selected client and branch.");
@ -717,9 +720,15 @@ table.dataTable thead th {
'data-iep': item.iep,
'data-itp': item.itp,
'data-bap': item.bap,
'data-allocg': item.allocg,
'data-tpa': item.tpa_branch_id + '-' + item.tpa_id,
'data-ptid': item.policy_type_id,
});
if (policy_id == item.id) {
option.attr('selected', true);
}
$('#client_policy_id').append(option);
});
}
@ -978,4 +987,41 @@ table.dataTable thead th {
$('#date_div').hide()
}
}
function removePolicyTransaction(input, pt_id, policy_type_id) {
let string = "Do you want to delete this transaction?";
if(policy_type_id > 7){
string = "Do you want to delete this transaction? Deleting this will also remove the linked CRM policy entry.";
}
confirmActionSweertAlert(string, "Yes, Proceed!", "No, Cancel").then((confirmed) => {
if (confirmed) {
let type = '1';
let url = '<?= base_url('policy_tranction/inception/removePolicyTransaction/') ?>' + pt_id + '/' + type;
// Include `pt_id` in the AJAX request if necessary
let requestData = {
pt_id: pt_id ,
type: 1 ,
};
sendAjaxRequestForGlobal(url, 'GET', requestData, function(response) {
console.log('Data fetched successfully:', response);
if (response.status === true) {
toastr.success(response.message, 'SUCCESS');
window.location.reload();
} else {
toastr.warning(response.message, 'WARNING');
}
}, function(xhr, status, error) {
console.error('Error fetching data:', error);
console.error(xhr.responseText);
});
}
});
}
</script>

File diff suppressed because it is too large Load Diff

View File

@ -570,6 +570,7 @@ $(document).ready(function() {
className: 'btn app-btn-primary mr-2',
action: function (e, dt, node, config) {
hide_list_show_add();
addInsurerColumn() ;
}
},
{
@ -806,9 +807,11 @@ function appendVehicles(data, vehicle_id = null)
}));
$.each(data, function(index, item) {
var displayValue = item.vehicle_no ? item.vehicle_no : item.rc;
var dbValue = item.id
var option = $('<option>', {
value: item.id,
text: item.vehicle_no ?? item.rc,
value: dbValue,
text: displayValue,
'data-cid': item.owner,
'data-bid': item.branch_id,
'data-cty': item.client_type,

View File

@ -79,36 +79,36 @@ table.dataTable tbody td {
<thead class="bg-light">
<tr>
<th>S. No</th>
<th>User</th>
<th style="display: none;">User</th>
<th>Month</th>
<th>Business Type</th>
<th>Client Type</th>
<!-- <th style="display: none;">Business Type</th> -->
<th style="display: none;">Client Type</th>
<th>Insured Name</th>
<th>Policy/<br>Endorsement</th>
<th>Policy Type</th>
<th>BAP Group</th>
<th>Vehicle Number</th>
<th style="display: none;">BAP Group</th>
<th style="display: none;">Vehicle Number</th>
<th>Policy No</th>
<th>Endorsement No</th>
<th>Insurer Name</th>
<!-- <th style="display: none;">Insurer Name</th> -->
<th>Insurer Branch</th>
<th>TPA</th>
<th>Endorsement <br> Effective Date</th>
<th>Policy <br> Effective Date</th>
<th>Policy <br> Expiry Date</th>
<th>Reference</th>
<th>Remarks</th>
<th>Base Premium</th>
<th>Terrorism/TP</th>
<th>Premium <br> (without GST)</th>
<th>GST @ 18%</th>
<!-- <th style="display: none;">TPA</th> -->
<th style="display: none;">Endorsement <br> Effective Date</th>
<th style="display: none;">Policy <br> Effective Date</th>
<th style="display: none;">Policy <br> Expiry Date</th>
<th style="display: none;">Reference</th>
<th style="display: none;">Remarks</th>
<th>BP Premium</th>
<th>TP/Ter Premium</th>
<th style="display: none;">Premium <br> (without GST)</th>
<!-- <th style="display: none;">GST @ 18%</th> -->
<th>Total Premium</th>
<th>Base <br> Revenue %</th>
<th>TP / Terrorism <br> Revenue %</th>
<th>Rewards</th>
<th>Total IRDA <br> Revenue INR</th>
<th>Billed Amount</th>
<th>UnBilled Amount</th>
<th>BP %</th>
<th>TP/Ter %</th>
<th style="display: none;">Rewards</th>
<th>Agreed Amount</th>
<th>Invoiced Amount</th>
<th>Outstanding Amount</th>
</tr>
</thead>
@ -116,34 +116,40 @@ table.dataTable tbody td {
<?php if (isset($report_list)) { ?>
<?php foreach($report_list as $index => $row){ ?>
<tr>
<td><?= $index + 1 ?></td>
<td><?php echo $row['user_name'] ?: 'N/A'; ?></td>
<td><?= $index + 1 ?> &nbsp; <a href="<?php
if($row['action_type'] == "inception"){
echo base_url('policy_tranction/inception/list') . '?pt_id=' . $row['id'] ;
}else{
echo base_url('policy_tranction/endorsement/list') . '?pt_id=' . $row['id'] ;
}
?>" class="mdi mdi-pencil" ></a> </td>
<td style="display: none;"><?php echo $row['user_name'] ?: 'N/A'; ?></td>
<td><?php echo $row['policy_issue_month'] ?: 'N/A'; ?></td>
<td><?php echo $row['revenue_type'] ?: 'N/A'; ?></td>
<td><?php echo $row['client_type'] ?: 'N/A'; ?></td>
<!-- <td style="display: none;"><?php echo $row['revenue_type'] ?: 'N/A'; ?></td> -->
<td style="display: none;"><?php echo $row['client_type'] ?: 'N/A'; ?></td>
<td><?php echo $row['client_name'] ?: 'N/A'; ?></td>
<td><?php echo $row['action_type'] ?: 'N/A'; ?></td>
<td><?php echo $row['policy_type'] ?: 'N/A'; ?></td>
<td><?php echo $row['bap'] ?: 'N/A'; ?></td>
<td><?php echo $row['vehicle_no'] ?: 'N/A'; ?></td>
<td style="display: none;"><?php echo $row['bap'] ?: 'N/A'; ?></td>
<td style="display: none;"><?php echo $row['vehicle_no'] ?: 'N/A'; ?></td>
<td><?php echo $row['policy_no'] ?: 'N/A'; ?></td>
<td><?php echo $row['endorsement_no'] ?: 'N/A'; ?></td>
<td><?php echo $row['insurer_name'] ?: 'N/A'; ?> </td>
<!-- <td style="display: none;"><?php echo $row['insurer_name'] ?: 'N/A'; ?> </td> -->
<td><?php echo $row['insurer_branch_name'] ?: 'N/A'; ?></td>
<td><?php echo $row['tpa_name']; ?></td>
<td><?php echo empty($row['endorse_eff_date']) ? 'N/A' : date('d/m/Y', strtotime($row['endorse_eff_date'])) ?></td>
<td><?php echo empty($row['policy_start_date']) ? 'N/A' : date('d/m/Y', strtotime($row['policy_start_date'])); ?></td>
<td><?php echo empty($row['policy_end_date']) ? 'N/A' : date('d/m/Y', strtotime($row['policy_end_date'])); ?></td>
<td><?php echo $row['ref'] ?: 'N/A'; ?></td>
<td><?php echo $row['remarks'] ?: 'N/A'; ?></td>
<!-- <td style="display: none;"><?php echo $row['tpa_name']; ?></td> -->
<td style="display: none;"><?php echo empty($row['endorse_eff_date']) ? 'N/A' : date('d/m/Y', strtotime($row['endorse_eff_date'])) ?></td>
<td style="display: none;"><?php echo empty($row['policy_start_date']) ? 'N/A' : date('d/m/Y', strtotime($row['policy_start_date'])); ?></td>
<td style="display: none;"><?php echo empty($row['policy_end_date']) ? 'N/A' : date('d/m/Y', strtotime($row['policy_end_date'])); ?></td>
<td style="display: none;"><?php echo $row['ref'] ?: 'N/A'; ?></td>
<td style="display: none;"><?php echo $row['remarks'] ?: 'N/A'; ?></td>
<td class="right-align-input"><?php echo $row['bp_amt']; ?></td>
<td class="right-align-input"><?php echo $row['tp_or_ter']; ?></td>
<td class="right-align-input"><?php echo $row['premium_wo_gst']; ?></td>
<td class="right-align-input"><?php echo $row['gst_amount']; ?></td>
<td class="right-align-input" style="display: none;"><?php echo $row['premium_wo_gst']; ?></td>
<!-- <td class="right-align-input" style="display: none;"><?php echo $row['gst_amount']; ?></td> -->
<td class="right-align-input"><?php echo $row['total_premium']; ?></td>
<td class="right-align-input"><?php echo $row['agreed_bp_per']; ?>&nbsp;%</td>
<td class="right-align-input"><?php echo $row['agreed_tp_or_ter_per'];?>&nbsp;%</td>
<td class="right-align-input"><?php echo isset($row['reward']) ? $row['reward'] : '0.00'; ?></td>
<td class="right-align-input" style="display: none;"><?php echo isset($row['reward']) ? $row['reward'] : '0.00'; ?></td>
<?php $total_irda_amt = empty($row['total_irda_amt']) ? $row['exp_amt'] : $row['total_irda_amt']; ?>
<td class="right-align-input" onclick="showCoShareStatementDetails(this)" data-id="<?= $row['pt_id'] ?>"><?php echo $total_irda_amt; ?></td>
@ -415,33 +421,64 @@ $(document).ready(function() {
paging: true, // Enable pagination
pageLength: 10, // Set default number of rows per page (optional)
ordering: false,
"footerCallback": function(row, data, start, end, display) {
// "footerCallback": function(row, data, start, end, display) {
// var api = this.api();
// // Calculate column totals
// var totalPremium = api.column(23).data().reduce(function(a, b) {
// return parseFloat(a) + parseFloat(b) || 0;
// }, 0);
// var total_rewards = api.column(26).data().reduce(function(a, b) {
// return parseFloat(a) + parseFloat(b) || 0;
// }, 0); // Add initial value 0 here
// console.log('total_rewards - ' + total_rewards);
// var totalIrda = api.column(27).data().reduce(function(a, b) {
// return parseFloat(a) + parseFloat(b) || 0;
// }, 0);
// var totalBilled = api.column(28).data().reduce(function(a, b) {
// return parseFloat(a) + parseFloat(b) || 0;
// }, 0);
// var totalUnbilled = api.column(29).data().reduce(function(a, b) {
// return parseFloat(a) + parseFloat(b) || 0;
// }, 0);
// // Update the totals in the div above the table
// $('#total_premium').text(totalPremium.toFixed(2));
// $('#total_rewards').text(total_rewards.toFixed(2));
// $('#total_irda').text(totalIrda.toFixed(2));
// $('#total_billed').text(totalBilled.toFixed(2));
// $('#total_unbilled').text(totalUnbilled.toFixed(2));
// }
"footerCallback": function(row, data, start, end, display) {
var api = this.api();
// Calculate column totals
var totalPremium = api.column(23).data().reduce(function(a, b) {
return parseFloat(a) + parseFloat(b) || 0;
// Calculate column totals (adjust indices based on VISIBLE columns)
var totalPremium = api.column(20, {search: 'applied'}).data().reduce(function(a, b) {
return parseFloat(a) + parseFloat(b || 0);
}, 0);
var total_rewards = api.column(26).data().reduce(function(a, b) {
return parseFloat(a) + parseFloat(b) || 0;
}, 0); // Add initial value 0 here
console.log('total_rewards - ' + total_rewards);
var totalIrda = api.column(27).data().reduce(function(a, b) {
return parseFloat(a) + parseFloat(b) || 0;
var total_rewards = api.column(23, {search: 'applied'}).data().reduce(function(a, b) {
return parseFloat(a) + parseFloat(b || 0);
}, 0);
var totalBilled = api.column(28).data().reduce(function(a, b) {
return parseFloat(a) + parseFloat(b) || 0;
var totalIrda = api.column(24, {search: 'applied'}).data().reduce(function(a, b) {
return parseFloat(a) + parseFloat(b || 0);
}, 0);
var totalUnbilled = api.column(29).data().reduce(function(a, b) {
return parseFloat(a) + parseFloat(b) || 0;
var totalBilled = api.column(25, {search: 'applied'}).data().reduce(function(a, b) {
return parseFloat(a) + parseFloat(b || 0);
}, 0);
// Update the totals in the div above the table
var totalUnbilled = api.column(26, {search: 'applied'}).data().reduce(function(a, b) {
return parseFloat(a) + parseFloat(b || 0);
}, 0);
// Update the totals
$('#total_premium').text(totalPremium.toFixed(2));
$('#total_rewards').text(total_rewards.toFixed(2));
$('#total_irda').text(totalIrda.toFixed(2));

View File

@ -0,0 +1,255 @@
<style>
.dataTables_filter {
position: absolute;
}
</style>
<!-- End ADD and EDIT Page HTML -->
<div class="row" id="List-page">
<div class="col-12">
<div class="card">
<div class="card-body maincard">
<table data-custom-table-css="table" class="table table-sm m-0 table-centered dt-responsive nowrap w-100" cellspacing="a" id="user-table">
<thead class="bg-light">
<tr>
<th class="font-weight-medium">S.No.</th>
<th class="font-weight-medium">RTO Office at</th>
<th class="font-weight-medium">RTO Code</th>
<th class="font-weight-medium">RTO State</th>
<!-- <th class="font-weight-medium">Status</th> -->
<th class="font-weight-medium">Action</th>
</tr>
</thead>
<tbody>
<?php if(isset($data)) { $slno = 1; ?>
<?php foreach($data as $index => $row) { ?>
<tr>
<td class="text-center"><?= $slno++; ?></td>
<td><?= $row['rto_name']; ?></td>
<td><?= $row['rto_code']; ?></td>
<td><?= $row['rto_state']; ?></td>
<!-- <td>
<span class="<?php if($row['is_active'] == 1){ echo 'badge badge-primary'; }else{ echo 'badge badge-danger'; } ?>">
<?php if($row['is_active'] == 1){ echo 'Active'; }else{ echo 'In-Active'; } ?>
</span>
</td> -->
<td>
<div class="btn-group dropdown" style="position: relative !important;left:0px !important;top:0px !important;">
<a href="javascript: void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm" data-toggle="dropdown" aria-expanded="false"><i class="mdi mdi-dots-horizontal"></i></a>
<div class="dropdown-menu dropdown-menu-right" style="cursor: pointer;">
<a class="dropdown-item" data-id="<?= $row['id']; ?>" onclick="handleSaveEditAndDelete('edit', this)">
<i class="mdi mdi-pencil mr-2 text-muted font-18 vertical-middle"></i>Edit
</a>
<?php if ($row['is_active'] == 1): ?>
<a class="dropdown-item" data-id="<?= $row['id']; ?>" onclick="handleSaveEditAndDelete('remove', this)">
<i class="mdi mdi-delete mr-2 text-muted font-18 vertical-middle"></i>Delete
</a>
<?php endif; ?>
</div>
</div>
</td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td colspan="3" class="text-center">No data available</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- modal content -->
<div id="con-close-modal" class="modal fade app-font-family" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;" data-backdrop="static">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="modalLabel">Add RTO Details</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body p-4">
<!-- <form class="parsley-examples" id="RTOForm" enctype="multipart/form-data"> -->
<form id="RTOForm" enctype="multipart/form-data">
<input type="hidden" name="pk" id="rto_id"/>
<div class="form-group">
<div class="form-row">
<div class="form-group col-md-12">
<label for="rto_name">RTO Office Name<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="rto_name" name="rto_name" placeholder="Enter RTO Office Name" required>
</div>
<div class="form-group col-md-12">
<label for="rto_code">RTO Code<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="rto_code" name="rto_code"
placeholder="Enter RTO Code" required
maxlength="2"
inputmode="numeric"
pattern="[0-9]{2}"
oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0,2);">
</div>
<div class="form-group col-md-12">
<label for="rto_state">RTO State<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="rto_state" name="rto_state"
placeholder="Enter RTO State" required
maxlength="2"
pattern="[A-Z]{2}"
oninput="this.value = this.value.replace(/[^A-Za-z]/g, '').toUpperCase().slice(0,2);">
</div>
</div>
</div>
<div class="form-group text-right m-b-0">
<button type="button" class="btn app-btn-secondary waves-effect waves-light" id="btnSubmit" onclick="handleSaveEditAndDelete('submit')">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
var table;
$(document).ready(function () {
var ticketsTable = $('#user-table');
ticketsTable.DataTable({
scrollX: true,
dom: "<'row'<'col-sm-7'f><'col-sm-5 text-right'B>>" + // Filter left, buttons right
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>", // Pagination at the bottom, without page length selector
buttons: [
{
text: 'Add',
className: 'btn app-btn-primary mr-2',
action: function(e, dt, node, config) {
openModal()
}
},
{
extend: 'collection',
text: '<span class=" btn-custom"> Export </span><i class="mdi mdi-menu-down"></i>',
className: 'btn app-btn-secondary ',
buttons: [
{
extend: 'csv',
text: '<i class="mdi mdi-file-delimited " ></i><span class=" btn-custom"> CSV </span>',
title: 'RTO',
className: 'app-btn-primary ',
exportOptions: {
columns: ':not(:last-child)'
},
}
]
}
],
language: {
search: `
<div class="datatable-search-wrapper">
_INPUT_
<i class="mdi mdi-magnify datatable-search-icon"></i>
</div>`,
searchPlaceholder: "Search"
},
paging: true, // Enable pagination
pageLength: 10, // Set default number of rows per page (optional)
// ordering: false,
});
});
$('.close').click(function(){
resetValues()
})
function openModal(){
var myModal = new bootstrap.Modal(document.getElementById('con-close-modal'));
myModal.show();
}
function handleSaveEditAndDelete(type = 'submit', el = null) {
let url = '<?= base_url('util/rtoMaster') ?>';
let method = "POST";
let requestData = {};
let pk = null;
// If element is passed (from edit/remove button), get its data-id
if (el) { pk = $(el).data('id'); }
requestData.pk = pk;
if(type == 'submit'){
$("#RTOForm").find("input, select, textarea").each(function () {
let name = $(this).attr("name");
let value = $.trim($(this).val());
if (name) requestData[name] = value;
});
}
if(type == 'remove'){
method = "DELETE";
} else if (type == 'edit'){
method = "GET";
$('#modalLabel').text('Edit RTO details');
$('#vehicleTypeForm')[0].reset();
}
console.log("type", type)
console.log("url", url)
console.log("method", method)
console.log("requestData", requestData)
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
// Send AJAX request
sendAjaxRequestForGlobal(url, method, requestData, function(response) {
console.log('Data fetched successfully:', response);
if (response.status) {
if(type == 'edit'){
appendEditData(response.data);
} else if(type == 'remove'){
toastr.success(response.message, 'Success');
if(el) $(el).closest('tr').remove();
window.location.reload();
} else if(type == 'submit'){
toastr.success(response.message, 'Success');
var myModal = new bootstrap.Modal(document.getElementById('con-close-modal'));
myModal.hide();
resetValues();
window.location.reload();
}
} else {
toastr.warning(response.message, 'Warning');
}
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
}, function(xhr, status, error) {
console.error('Error fetching data:', error);
console.error(xhr.responseText);
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
});
}
function resetValues(){
$('#modalLabel').text('Add RTO Details');
$('#RTOForm')[0].reset();
}
function appendEditData(data){
$('#rto_id').val(data[0]['id']);
$('#rto_name').val(data[0]['rto_name']);
$('#rto_code').val(data[0]['rto_code']);
$('#rto_state').val(data[0]['rto_state']);
openModal()
}
</script>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,231 @@
<style>
.dataTables_filter {
position: absolute;
}
</style>
<!-- End ADD and EDIT Page HTML -->
<div class="row" id="List-page">
<div class="col-12">
<div class="card">
<div class="card-body maincard">
<table data-custom-table-css="table" class="table table-sm m-0 table-centered dt-responsive nowrap w-100" cellspacing="a" id="user-table">
<thead class="bg-light">
<tr>
<th class="font-weight-medium">S.No.</th>
<th class="font-weight-medium">Vehicle Type</th>
<!-- <th class="font-weight-medium">Status</th> -->
<th class="font-weight-medium">Action</th>
</tr>
</thead>
<tbody>
<?php if(isset($data)) { $slno = 1; ?>
<?php foreach($data as $index => $row) { ?>
<tr>
<td class="text-center"><?= $slno++; ?></td>
<td><?= $row['vehicle_type']; ?></td>
<!-- <td>
<span class="<?php if($row['is_active'] == 1){ echo 'badge badge-primary'; }else{ echo 'badge badge-danger'; } ?>">
<?php if($row['is_active'] == 1){ echo 'Active'; }else{ echo 'In-Active'; } ?>
</span>
</td> -->
<td>
<div class="btn-group dropdown" style="position: relative !important;left:0px !important;top:0px !important;">
<a href="javascript: void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm" data-toggle="dropdown" aria-expanded="false"><i class="mdi mdi-dots-horizontal"></i></a>
<div class="dropdown-menu dropdown-menu-right" style="cursor: pointer;">
<a class="dropdown-item" data-id="<?= $row['id']; ?>" onclick="handleSaveEditAndDelete('edit', this)">
<i class="mdi mdi-pencil mr-2 text-muted font-18 vertical-middle"></i>Edit
</a>
<?php if ($row['is_active'] == 1): ?>
<a class="dropdown-item" data-id="<?= $row['id']; ?>" onclick="handleSaveEditAndDelete('remove', this)">
<i class="mdi mdi-delete mr-2 text-muted font-18 vertical-middle"></i>Delete
</a>
<?php endif; ?>
</div>
</div>
</td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td colspan="3" class="text-center">No data available</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- modal content -->
<div id="con-close-modal" class="modal fade app-font-family" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;" data-backdrop="static">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="modalLabel">Add Vehicle Type</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body p-4">
<!-- <form class="parsley-examples" id="vehicleTypeForm" enctype="multipart/form-data"> -->
<form id="vehicleTypeForm" enctype="multipart/form-data">
<input type="hidden" name="pk" id="vehicle_type_id"/>
<div class="form-group">
<div class="form-row">
<div class="form-group col-md-12">
<label for="vehicle_type">Vehicle Type<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="vehicle_type" name="vehicle_type" placeholder="Enter Vehicle Type" required>
</div>
</div>
</div>
<div class="form-group text-right m-b-0">
<button type="button" class="btn app-btn-secondary waves-effect waves-light" id="btnSubmit" onclick="handleSaveEditAndDelete('submit')">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
var table;
$(document).ready(function () {
var ticketsTable = $('#user-table');
ticketsTable.DataTable({
scrollX: true,
dom: "<'row'<'col-sm-7'f><'col-sm-5 text-right'B>>" + // Filter left, buttons right
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>", // Pagination at the bottom, without page length selector
buttons: [
{
text: 'Add',
className: 'btn app-btn-primary mr-2',
action: function(e, dt, node, config) {
openModal()
}
},
{
extend: 'collection',
text: '<span class=" btn-custom"> Export </span><i class="mdi mdi-menu-down"></i>',
className: 'btn app-btn-secondary ',
buttons: [
{
extend: 'csv',
text: '<i class="mdi mdi-file-delimited " ></i><span class=" btn-custom"> CSV </span>',
title: 'Policy-Tranction-Inception-List',
className: 'app-btn-primary ',
exportOptions: {
columns: ':not(:last-child)'
},
}
]
}
],
language: {
search: `
<div class="datatable-search-wrapper">
_INPUT_
<i class="mdi mdi-magnify datatable-search-icon"></i>
</div>`,
searchPlaceholder: "Search"
},
paging: true, // Enable pagination
pageLength: 10, // Set default number of rows per page (optional)
// ordering: false,
});
});
$('.close').click(function(){
resetValues()
})
function openModal(){
var myModal = new bootstrap.Modal(document.getElementById('con-close-modal'));
myModal.show();
}
function handleSaveEditAndDelete(type = 'submit', el = null) {
let url = '<?= base_url('util/vehicleTypeMaster') ?>';
let method = "POST";
let requestData = {};
let pk = null;
// If element is passed (from edit/remove button), get its data-id
if (el) { pk = $(el).data('id'); }
requestData.pk = pk;
if(type == 'submit'){
$("#vehicleTypeForm").find("input, select, textarea").each(function () {
let name = $(this).attr("name");
let value = $.trim($(this).val());
if (name) requestData[name] = value;
});
}
if(type == 'remove'){
method = "DELETE";
} else if (type == 'edit'){
method = "GET";
$('#modalLabel').text('Edit Vehicle Type');
$('#vehicleTypeForm')[0].reset();
}
console.log("type", type)
console.log("url", url)
console.log("method", method)
console.log("requestData", requestData)
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
// Send AJAX request
sendAjaxRequestForGlobal(url, method, requestData, function(response) {
console.log('Data fetched successfully:', response);
if (response.status) {
if(type == 'edit'){
appendEditData(response.data);
} else if(type == 'remove'){
toastr.success(response.message, 'Success');
if(el) $(el).closest('tr').remove();
window.location.reload();
} else if(type == 'submit'){
toastr.success(response.message, 'Success');
var myModal = new bootstrap.Modal(document.getElementById('con-close-modal'));
myModal.hide();
resetValues();
window.location.reload();
}
} else {
toastr.warning(response.message, 'Warning');
}
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
}, function(xhr, status, error) {
console.error('Error fetching data:', error);
console.error(xhr.responseText);
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
});
}
function resetValues(){
$('#modalLabel').text('Add Vehicle Type');
$('#vehicleTypeForm')[0].reset();
}
function appendEditData(data){
$('#vehicle_type_id').val(data[0]['id']);
$('#vehicle_type').val(data[0]['vehicle_type']);
openModal()
}
</script>

View File

@ -1360,7 +1360,7 @@ $(document).ready(function () {
if (lead_status != "won") {
console.log("Lead status is not 'won', setting interval for submitData");
// startInterval();
startInterval();
} else {
console.log("Lead status is 'won', submitData will not be called");
}
@ -1557,8 +1557,8 @@ function saveFamilyMembersDetails() {
function resetFamiliyDialogModalValues() {
$('#familiy_dialog_row_index').val('');
$('#familiy_dialog_column_index').val('');
// $('#familiy_dialog_row_index').val('');
// $('#familiy_dialog_column_index').val('');
// Reset Self
$('#family_self').prop('checked', true);
@ -3751,6 +3751,8 @@ function setCellInnerHTMLByCellIndex(tableId, rowIndex, colIndex, htmlContent) {
// Set the innerHTML of the cell
cell.innerHTML = htmlContent;
console.log(`Updated cell at row ${rowIndex}, column ${colIndex} with content: ${htmlContent}`);
$('#familiy_dialog_row_index').val('');
$('#familiy_dialog_column_index').val('');
} else {
console.error(`Column index ${colIndex} does not exist in row ${rowIndex}`);
}

Binary file not shown.

View File

@ -0,0 +1,280 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Health Insurance E-Card</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
/* font-family: 'Lato', sans-serif; */
background-color: #fff;
padding: 5px;
}
.card-container {
display: table;
width: 100%;
max-width: 750px;
margin: 0 auto;
table-layout: fixed;
border-spacing: 5px 0;
margin-bottom: 5px;
}
.card {
display: table-cell;
background: white;
width: 50%;
padding: 10px;
border: 1px solid #ddd;
vertical-align: top;
}
.card-header {
display: table;
width: 100%;
margin-bottom: 10px;
table-layout: fixed;
}
.logo-left {
display: table-cell;
width: 35px;
vertical-align: middle;
}
.logo-left img {
width: 48px;
height: 32px;
}
.logo-right {
display: table-cell;
text-align: right;
vertical-align: middle;
}
.logo-right img {
width: 65px;
height: 32px;
}
.card-body {
position: relative;
padding-left: 65px;
min-height: 80px;
}
.n-logo {
position: absolute;
left: 5px;
top: 30px;
width: 55px;
}
.n-logo img {
width: 55px;
height: auto;
}
.details {
width: 100%;
margin-left: 16px;
}
.details-table {
width: 100%;
border-collapse: collapse;
font-size: 10px;
line-height: 1.4;
}
.details-table td {
padding: 1px 1px;
vertical-align: top;
}
.detail-label {
width: 65px;
font-weight: 600;
color: #333;
white-space: nowrap;
}
.detail-separator {
width: 8px;
text-align: center;
color: #666;
}
.detail-value {
color: #333;
word-break: break-word;
white-space: normal;
font-weight: 300;
}
.support-section {
font-size: 7.5px;
}
.support-title {
color: #ff6b35;
font-weight: 600;
margin-bottom: 6px;
font-size: 10px;
}
.support-details {
font-size: 8px;
font-weight: 500;
line-height: 1.4;
color: #333;
margin-top: 0px;
}
.level-title {
font-weight: 500;
margin-top: 4px;
margin-bottom: 2px;
}
.cashless-title {
color: #ff6b35;
font-weight: 600;
margin-top: 0px;
margin-bottom: 3px;
font-size: 10px;
}
.footer-note {
text-align: center;
margin-top: 8px;
font-size: 8px;
color: #666;
}
.card-header img[src=""],
.card-header img:not([src]) {
opacity: 0;
visibility: hidden;
display: none;
}
</style>
</head>
<body>
<div class="card-container">
<!-- Front Card -->
<div class="card">
<div class="card-header">
<div class="logo-left">
<img src="{INSURER_LOGO}" alt=" " onerror="this.style.visibility='hidden';">
</div>
<div class="logo-right">
<img src="{TPA_LOGO}" alt=" " onerror="this.style.visibility='hidden';">
</div>
</div>
<div class="card-body">
<div class="n-logo">
<img src="{NHANCE_N_LOGO}" alt=" " onerror="this.style.visibility='hidden';">
</div>
<div class="details">
<table class="details-table">
<tbody>
<tr>
<td class="detail-label">Policy Holder</td>
<td class="detail-separator">:</td>
<td class="detail-value">{CLIENT_NAME}</td>
</tr>
<tr>
<td class="detail-label">Insurer</td>
<td class="detail-separator">:</td>
<td class="detail-value">{INSURER_NAME}</td>
</tr>
<tr>
<td class="detail-label">TPA</td>
<td class="detail-separator">:</td>
<td class="detail-value">{TPA_NAME}</td>
</tr>
<tr>
<td class="detail-label">Primary Insured</td>
<td class="detail-separator">:</td>
<td class="detail-value">{SELF_NAME}</td>
</tr>
<tr>
<td class="detail-label">Beneficiary Name</td>
<td class="detail-separator">:</td>
<td class="detail-value">{NAME}</td>
</tr>
<tr>
<td class="detail-label">Member ID</td>
<td class="detail-separator">:</td>
<td class="detail-value">{TPA_ID}</td>
</tr>
<tr>
<td class="detail-label">Employee Code</td>
<td class="detail-separator">:</td>
<td class="detail-value">{EMP_ID}</td>
</tr>
<tr>
<td class="detail-label">Relation</td>
<td class="detail-separator">:</td>
<td class="detail-value">{RELATION}</td>
</tr>
<tr>
<td class="detail-label">Policy Period</td>
<td class="detail-separator">:</td>
<td class="detail-value">{POLICY_START_DATE} to {POLICY_DATE}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- Back Card -->
<div class="card">
<div class="card-header">
<div class="logo-left">
<img src="{INSURER_LOGO}" alt=" " onerror="this.style.visibility='hidden';">
</div>
<div class="logo-right">
<img src="{TPA_LOGO}" alt=" " onerror="this.style.visibility='hidden';">
</div>
</div>
<div class="card-body">
<div class="n-logo">
<img src="{NHANCE_N_LOGO}" alt=" " onerror="this.style.visibility='hidden';">
</div>
<div class="details">
<div class="support-section">
<div class="support-title">For support :</div>
<div class="support-details">
{LEVELS}
<div class="cashless-title">For cashless claims:</div>
<div>Share a valid ID with this E-card at the Hospital Insurance Desk.</div>
{NETWORK_HOSPITAL}
</div>
</div>
</div>
</div>
<div class="footer-note">
This E-Card is non-transferable and valid only at network (cashless) hospitals
</div>
</div>
</div>
</body>
</html>