FIX_FAQ Module API AND WEB

This commit is contained in:
sanjeev.p 2025-12-18 17:47:55 +05:30
parent 206d6d28d3
commit 464b394231
7 changed files with 559 additions and 4 deletions

View File

@ -654,7 +654,8 @@ $routes->group("employeeRest", ["filter" => ['appSignature' , 'authJWT']], funct
$routes->post("ticketSave", "ThzController::ticketSave");
});
//API FAQ
$routes->match(['get','post','delete'], 'FAQ', 'AppContentManagementController::FAQ');
//claims
$routes->post('initiateClaim',"EmployeeRestController::initiateClaim");
@ -791,6 +792,9 @@ $routes->post('ticketAutoFetchDetails',"ThzController::ticketAutoFetchDetails");
$routes->match(['get','post','put'], 'ticketType', 'ThzController::ticketType');
$routes->get("ticketHistoryList", "ThzController::ticketHistoryList");
// General FAQ
$routes->match(['get','post','delete'], 'FAQ', 'AppContentManagementController::FAQ');
//for testing
$routes->group('test', function($routes) {

View File

@ -11,6 +11,7 @@ use CodeIgniter\API\ResponseTrait;
use App\Models\AddImgModel;
use App\Models\FEContentModel;
use App\Models\ClientModel;
use App\Models\FAQModel;
class AppContentManagementController extends AdminController
{
@ -19,6 +20,7 @@ class AppContentManagementController extends AdminController
protected $addImgModel;
protected $feContentModel;
protected $clientModel;
protected $faqModel;
public function __construct()
@ -27,6 +29,7 @@ class AppContentManagementController extends AdminController
$this->addImgModel = new AddImgModel();
$this->feContentModel = new FEContentModel();
$this->clientModel = new ClientModel();
$this->faqModel = new FAQModel();
}
//listing
public function add_image_index()
@ -156,4 +159,139 @@ class AppContentManagementController extends AdminController
echo view('layout/footer');
}
//
// public function FAQ()
// {
// $data['tab_name'] = "FAQ's";
// $data['page_name'] = "FAQ's";
// return $this->loadLayout('faq_list', $data);
// $returnType = strtolower($this->request->getGet('return_type') ?? 'api');
// $data = $this->request->getGet();
// $faq_list = $this->faqModel->select('*')->where('is_active', 1)->orderBy('id', 'desc')->findAll();
// if ($returnType === 'api') {
// if (empty($faq_list)) {
// $this->myLogger->logme('error', 'empty tickets in ticket list: ' . json_encode($faq));
// return $this->response->setJSON([ 'status' => 'error','message' => 'No Details found'])->setStatusCode(404);
// }
// } else {
// $data['tab_name'] = "FAQ's";
// $data['page_name'] = "FAQ's";
// return $this->loadLayout('faq_list', $data);
// }
// return $this->response->setJSON([
// 'status' => 'success',
// 'data' => [],
// ])->setStatusCode(200);
// }
public function FAQ()
{
$method = strtolower($this->request->getMethod());
$returnType = strtolower($this->request->getGet('return_type') ?? 'api');
$ref = ['timestamp' => date('Y-m-d H:i:s')];
try {
// --- 1. POST: CREATE OR UPDATE ---
if ($method === 'post') {
$id = $this->request->getPost('faq_id');
$data = array_filter($this->request->getPost(), fn($v) => $v !== '' && $v !== null);
if (empty($id)) {
$status = $this->faqModel->insert($data);
$msg = "Created";
} else {
$status = $this->faqModel->update($id, $data);
$msg = "Updated";
}
// if ($returnType === 'web') {
// return redirect()->back()->with($status ? 'success' : 'error', "FAQ $msg " . ($status ? 'successfully' : 'failed'));
// }
// return $this->response->setJSON([
// ])->setStatusCode($result ? 200 : 400);
return $this->response->setJSON([
'status' => $status ? 'success' : 'error',
'message' => "FAQ $msg " . ($status ? 'successfully' : 'failed'),
'code' => $status ? 200 : 400,
'data' => $data,
'ref' => $ref
])->setStatusCode($status ? 200 : 400);
}
// --- 2. GET: FETCH LIST OR SINGLE ---
elseif ($method === 'get') {
$id = $this->request->getGet('faq_id');
if (!empty($id)) {
// $row = $this->faqModel->where('is_active', 1)->find($id);
$row = $this->faqModel->find($id);
$data['faq_list'] = $row ? [$row] : [];
} else {
// $data['faq_list'] = $this->faqModel->where('is_active', 1)->orderBy('id', 'desc')->findAll();
$data['faq_list'] = $this->faqModel->orderBy('id', 'desc')->findAll();
}
if ($returnType === 'web') {
$data['tab_name'] = "FAQ's";
$data['page_name'] = "FAQ's";
// print_r($data);die;
return $this->loadLayout('faq_list', $data);
}
// API Response Logic
if (empty($data['faq_list'])) {
return $this->response->setJSON([
'status' => $returnType === 'web' ? false : 'error',
'message' => 'No data found',
'code' => 404,
'data' => [],
'ref' => $ref
])->setStatusCode(200); // Using 200 with error status is common for mobile apps to prevent crashes
}
return $this->response->setJSON([
'status' => $returnType === 'web' ? true : 'success',
'message' => 'Data retrieved',
'code' => 200,
'data' => $data,
'ref' => $ref
])->setStatusCode(200);
}
// --- 3. DELETE: SOFT DELETE ---
elseif ($method === 'delete') {
$id = $this->request->getGet('faq_id');
$status = (!empty($id)) ? $this->faqModel->update($id, ['is_active' => 0]) : false;
return $this->response->setJSON([
'status' => $status ? ($returnType === 'web' ? true : 'success') : ($returnType === 'web' ? false : 'error'),
'message' => $status ? 'Data removed successfully' : 'Failed to remove or ID missing',
'code' => $status ? 200 : 400,
'data' => [],
'ref' => $ref
])->setStatusCode( 200 );
}
} catch (\Throwable $e) {
$msg = $e->getMessage();
return $this->response->setJSON([
'status' => $returnType === 'web' ? false : 'error',
'code' => 500,
'message' => $msg,
'ref' => ['file' => $e->getFile(), 'line' => $e->getLine()]
])->setStatusCode(500);
}
}
}

56
app/Models/FAQModel.php Normal file
View File

@ -0,0 +1,56 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class FAQModel extends Model
{
protected $table = 'partner_faq';
protected $primaryKey = 'id';
protected $allowedFields = [
'id',
'category',
'question',
'answer',
'created_on',
'created_by',
'updated_on',
'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;
}
}

355
app/Views/faq_list.php Normal file
View File

@ -0,0 +1,355 @@
<style>
.dataTables_filter {
position: absolute;
}
.dataTables_length label {height: 21px !important;}
</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">Category</th>
<th class="font-weight-medium">Question</th>
<th class="font-weight-medium">Answer</th>
<th class="font-weight-medium">Status</th>
<th class="font-weight-medium">Action</th>
</tr>
</thead>
<tbody>
<?php if(isset($faq_list)) { $slno = 1; ?>
<?php foreach($faq_list as $index => $row) { ?>
<tr>
<td class="text-center"><?= $slno++; ?></td>
<td><?php $category = $row['category'] ? $row['category'] : 'N/A';
echo (strlen($category) > 50)
? htmlspecialchars(substr($category, 0, 50)) . "..."
: htmlspecialchars($category);
?></td>
<td><?php $question = $row['question'] ? $row['question'] : 'N/A';
echo (strlen($question) > 50)
? htmlspecialchars(substr($question, 0, 50)) . "..."
: htmlspecialchars($question);
?></td>
<td><?php $answer = $row['answer'] ? $row['answer'] : 'N/A';
echo (strlen($answer) > 50)
? htmlspecialchars(substr($answer, 0, 50)) . "..."
: htmlspecialchars($answer);
?></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="6" 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 modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="modalLabel">Add FAQ 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="FAQForm" enctype="multipart/form-data">
<input type="hidden" name="faq_id" id="faq_id"/>
<div class="form-group">
<div class="form-row">
<div class="form-group col-md-12">
<label for="category">Category<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="category" name="category" placeholder="Enter Category" required>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label for="question">Question<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="question" name="question" placeholder="Enter Question" required>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label for="answer">Answer<span class="text-danger">*</span></label>
<!-- <textarea id="answer" name="answer" class="form-control" required></textarea> -->
<textarea id="answer" name="answer" class="form-control answer" rows="7">
<!-- <h5>Hello {USER_NAME}, </h5>
<p>We create simple, flat & responsive custom mail template.</p>
<p>Please, write text here!</p> -->
</textarea>
</div>
</div>
</div>
<div class="form-group text-right m-b-0">
<button type="submit" class="btn app-btn-secondary" id="btnSubmit">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- <script src="https://cdn.ckeditor.com/ckeditor5/39.0.1/classic/ckeditor.js"></script> -->
<script>
// let faqEditor;
let editor;
// ClassicEditor
// .create(document.querySelector('#answer'))
// .then(editor => {
// faqEditor = editor; // Save the instance here
// })
// .catch(error => { console.error(error); });
var table;
$(document).ready(function () {
//JoDit editor
const editorConfig = {
buttons: [
"undo", "redo", "|",
"paragraph",
"bold", "italic", "strikethrough", "|",
"superscript", "subscript", "|",
"ul", "ol", "|",
"outdent", "indent", "|",
"blockquote", "table", "|",
"align", "fontsize", "|",
"source"
],
controls: {
paragraph: {
list: {
p: "Normal",
h1: "Heading 1",
h2: "Heading 2",
h3: "Heading 3",
h4: "Heading 4"
}
}
},
fontsize: ["8px", "10px", "12px", "14px", "16px", "18px", "20px", "22px", "24px"], // Font sizes in pixels
showPlaceholder: false,
toolbarButtonSize: "small",
toolbarAdaptive: false,
saveHeightInStorage: true,
minHeight: 400,
height: 400, // Optional fixed height
defaultMode: "1", // Start in WYSIWYG mode
enableDragAndDropFileToEditor: true, // Allow file uploads via drag and drop
placeholder: "Start typing here...", // Optional placeholder text
};
// 2. Initialize
editor = Jodit.make("#answer", editorConfig);
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
dom: "<'row'<'col-sm-7'f><'col-sm-5 text-right'B>>" + // Filter left, buttons right
"<'row'<'col-sm-12'tr>>" +
"<'row align-items-center'<'col-5 text-start'i><'col-7 d-flex justify-content-end align-items-center'<'me-2'l>p>>",
lengthMenu: [[10, 20, 50, 100], [10, 20, 50, 100]],
buttons: [
{
text: 'Add',
className: 'btn app-btn-primary mr-2',
action: function(e, dt, node, config) {
resetValues();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: 'FAQ-List',
className: 'app-btn-primary ',
exportOptions: {
columns: ':not(:last-child)'
},
}
]
}
],
language: {
search: `
<div class="datatable-search-wrapper" style="position:relative; display:inline-block;">
_INPUT_
<i class="mdi mdi-magnify datatable-search-icon"
style="position:absolute; right:10px; top:50%; transform:translateY(-50%); color:#666;"></i>
<i class="mdi mdi-close-circle datatable-clear-icon"
style="position:absolute; right:10px; top:50%; transform:translateY(-50%); color:#666; display:none;"></i>
</div>`,
searchPlaceholder: "Search",
emptyTable: '<div class="text-center text-muted">No Data found</div>'
},
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 form = document.getElementById('FAQForm');
let url = '<?= base_url('FAQ') ?>';
let method = "POST";
let faq_id = el ? $(el).data('id') : null;
let formData;
if (type === 'submit') {
if (editor) {
$('#answer').val(editor.value);
}
// CREATE FORMDATA FROM FORM
formData = new FormData(form);
formData.set('return_type', 'web');
} else if (type == 'edit') {
method = "GET";
if (faq_id) url += '?faq_id=' + faq_id ;
$('#modalLabel').text('Edit FAQ Details');
$('#FAQForm')[0].reset();
} else if (type == 'remove') {
method = "DELETE";
if (faq_id) url += '?faq_id=' + faq_id ;
}
$('.loader, .loader-mask').fadeIn();
$.ajax({
url: url,
type: method,
data: (type === 'submit') ? formData : null,
processData: false,
contentType: false,
dataType: 'json',
success: function (response) {
console.log('Response:', response);
if (response.status === 'success' || response.status === true) {
if (type == 'edit') {
let record = response.data.faq_list[0]; // single record
appendEditData(record);
} else if(type == 'remove'){
toastr.success(response.message, 'Success');
// if(el) $(el).closest('tr').remove();
window.location.reload();
// window.location.href = "<?= base_url('FAQ?return_type=web') ?>";
} else if(type == 'submit'){
toastr.success(response.message, 'Success');
var myModal = new bootstrap.Modal(document.getElementById('con-close-modal'));
myModal.hide();
$('#FAQForm')[0].reset();
window.location.reload();
}
} else {
toastr.warning(response.message, 'Warning');
}
$('.loader, .loader-mask').fadeOut();
},
error: function () {
$('.loader, .loader-mask').fadeOut();
}
});
}
function resetValues(){
$('#modalLabel').text('Add FAQ Details');
$('#FAQForm')[0].reset();
if (typeof editor !== 'undefined') {
editor.value = '';
}
}
function appendEditData(data) {
$('#FAQForm')[0].reset();
$('#faq_id').val(data.id);
$('#category').val(data.category);
$('#question').val(data.question);
if (editor) {
editor.value = data.answer || '';
}
openModal();
}
$('#FAQForm').on('submit', function(e) {
e.preventDefault();
const form = this;
// HTML5 built-in validation
if (!form.checkValidity()) {
form.reportValidity(); // shows required/pattern tooltips
return;
}
if (typeof editor !== 'undefined') {
// Strip HTML tags and trim whitespace to see if there is actual text
const plainText = editor.value.replace(/<[^>]*>/g, '').trim();
// Check if it's truly empty or just contains empty tags like <p><br></p>
if (editor.value === '' || plainText === '') {
toastr.warning("Answer is required", 'Warning');
return; // Stop the function here
}
}
// If valid, submit via AJAX
handleSaveEditAndDelete('submit');
});
</script>

View File

@ -2098,6 +2098,9 @@
<li>
<a href="<?= base_url('/frontend_content') ?>">Front-end Content</a>
</li>
<li>
<a href="<?= base_url('/FAQ?return_type=web') ?>"> FAQ's </a>
</li>
</ul>
</div>
</li>

View File

@ -107,7 +107,7 @@
text: 'Add',
className: 'btn app-btn-primary mr-2',
action: function(e, dt, node, config) {
openModal()
resetValues();openModal();
}
},
{
@ -150,7 +150,6 @@
})
function openModal(){
resetValues();
var myModal = new bootstrap.Modal(document.getElementById('con-close-modal'));
myModal.show();
}

View File

@ -226,7 +226,7 @@
text: 'Add',
className: 'btn app-btn-primary mr-2',
action: function(e, dt, node, config) {
openModal()
resetValues();openModal();
}
},
{