Spaces:
Runtime error
Runtime error
Update templates/knowledgebase.html
Browse files17 unmodified lines18192021222324253 unmodified lines293031323334352 unmodified lines3839404142434419 unmodified lines6465666768697071727374757677787945 unmodified lines1251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591602 unmodified lines1631641651661671681691701711721731741751761771781791801811821831 unmodified line1851861871881891901911 unmodified line1931941951961971981992 unmodified lines2022032042052062072087 unmodified lines21621721821922022122222322422522622722822937 unmodified lines2672682692702712722731 unmodified line2752762772782792802812822832842852862872882892 unmodified lines2922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264271 unmodified line4294304314324334344354364374384394404414424434444454464474484495 unmodified lines4554564574584594604614624634641 unmodified line46646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966014 unmodified lines67567667767867968068168268313 unmodified lines69769869970070170270370470570670710 unmodified lines7187197207217227237242 unmodified lines72772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976017 unmodified lines<style>body {background-color: transparent !important;}.content-wrapper{flex: 1;overflow-y: auto;}3 unmodified linesflex-direction: column;height: 100vh;}.modal-content {background-color: #fff;2 unmodified lines.content-header {padding: 1rem;}h1 {text-align: center;margin-bottom: 30px;19 unmodified linesmargin-right: 7.5px;}.text-wrap {white-space: normal !important;word-break: break-word;}div.dataTables_wrapper div.dataTables_length select{width: 60px;display: inline-block;}th {white-space: nowrap;}45 unmodified lines/* Delete column */width: auto;}.alert {position: relative;padding: 15px;margin-bottom: 20px;border: 1px solid transparent;border-radius: 4px;}.alert-success {color: #3c763d;background-color: #dff0d8;border-color: #d6e9c6;}.alert-danger {color: #a94442;background-color: #f2dede;border-color: #ebccd1;}.close {position: absolute;bottom: 10px;right: 10px;border: none;background: none;font-size: 16px;cursor: pointer;}</style></head>2 unmodified lines<div class="wrapper"><div class="main-header" style="border-bottom: none;"><div class="container mt-2"><div class="form-group left-align" ><label for="company" class="mr-1" style="margin-left:-40px; margin-top: 12px;">Company Name <span class="text-danger">*</span></label><select type="text" id="company" name="company" class="form-control" style="width:20%;margin-left:-40px;"required><option value="" selected>Select</option></select><div class="col-12 d-flex justify-content-end mb-3"><button class="btn btn-primary" style="margin-top:-40px;margin-right: -10px;position: fixed;"id="add" data-action="add">Add</button></div></div></div><div class="row"><div id="message-container" style="margin-left: 200px;width:600px;"></div></div><section class="content" id="contentSection" style="display: none;"><div class="container-fluid"><div>1 unmodified line<!-- <label for="company_id">company_id</label>---><input type="hidden" id="company_id" name="company_id" class="form-control" required></div><div class="row"><div class="col-12"><div class="card"><div id="message-container">1 unmodified line<table id="knowledgeTable" class="table table-bordered table-striped"><thead><tr><th>Sno</th><th>Document Name</th><th>Document Description</th>2 unmodified lines<th>View</th><th>Edit</th><th>Delete</th><!-- <th style="display:none;">Company ID</th> --></tr></thead><tbody>7 unmodified lines</div></section></div><div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel"aria-hidden="true"><div class="modal-dialog" role="document"><div class="modal-content"><div class="modal-header"><h5 class="modal-title" id="addModalLabel">Add Document Details</h5><button type="button" class="btn-close" data-dismiss="modal" ><span aria-hidden="true" data-backdrop="static" data-keyboard="false"></span></button></div>37 unmodified lines</div><div class="modal-footer"><!-- <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> --><button type="button" id="saveupdate" class="btn btn-primary" style="display: none;">Update</button><button type="button" id="save" onclick="save_file()" class="btn btn-primary">Save</button></div></div>1 unmodified line</div></div>{%include 'footer.html'%}<!-- JavaScript to handle modal display --><script>document.addEventListener("DOMContentLoaded", function () {now = new Date().toISOString().replace('T', ' ').substr(0, 19);document.getElementById('lastUpdated').value = now;const inputs = document.querySelectorAll("#documentForm input, textarea");inputs.forEach((input, index) => {input.addEventListener("keydown", function (event) {if (event.key === "Enter") {2 unmodified lines}});});function moveToNextInput(inputs, currentIndex) {const nextInput = inputs[currentIndex + 1];if (nextInput) {nextInput.focus();} else {// Optionally, submit the form or trigger the save buttondocument.getElementById("save").focus();}}// $(document).on('click', '.btn-view', function () {// const companyId = $(this).data('id');// console.log("company_id in view",companyId);// viewCompany(companyId);// });// // Edit knowledge base details// $(document).on('click', '.btn-edit', function () {// const companyId = $(this).data('id');// console.log("company_id in edit",companyId);// editCompany(companyId);// });// // Delete company// $(document).on('click', '.btn-delete', function () {// const kid = $(this).data('id'); // Get the company ID from the da// console.log("company_id in delete",kid);// if (confirm("Are you sure you want to delete this company?")) {// deleteCompany(kid); // Call the delete function with the company ID// }// });fetchCompanies();const companySelect = document.getElementById('company');const documentForm = document.getElementById('documentForm');const table = $('#knowledgeTable').DataTable(); // Initialize DataTable at the startcompanySelect.addEventListener('change', async function () {$("#message-container").empty();const selectedCompanyName = companySelect.options[companySelect.selectedIndex].text;console.log(`Selected Company Name: ${selectedCompanyName}`);if (selectedCompanyName !== "Select") {try {const response = await fetch(`/api/company_id?company_name=${encodeURIComponent(selectedCompanyName)}`);if (!response.ok) {contentSection.style.display = 'none';displayErrorMessage("Knowledgebase details do not exist for this company. Please fill in the details.");throw new Error('Network response was not ok');}const data = await response.json();console.log('data returned', data);const companyId = data.company_id;document.getElementById('company_id').value = companyId;if (companyId) {try {const Response = await fetch(`/api/document_upload?company_id=${companyId}&company_name=${selectedCompanyName}`);const connectorsResponse = await Response.json();console.log("knowledge data table after connecting to table", connectorsResponse);table.clear();if (!Array.isArray(connectorsResponse) || connectorsResponse.length === 0) {//displayEmptyTable();displayErrorMessage("Knowledgebase details do not exist for this company. Please fill in the details.");contentSection.style.display = 'none';} else {connectorsResponse.forEach((company, index) => {table.row.add([index + 1,company.document_name,company.document_desc,company.version,company.vectorDBflag,`<a href='#' class='btn btn-info btn-sm'data-kid-id='${company.row_id}' data-action="view" onclick='viewCompany(this)''><i class='fas fa-eye'></i></a>`,`<a href='#' class='btn btn-warning btn-sm'data-kid-id='${company.row_id}' data-action="edit" onclick='editCompany(this)'><i class='fas fa-edit'></i></a>`,`<a href='#' class='btn btn-danger btn-sm' data-kid-id='${company.row_id}' onclick='deleteCompany(this)'><i class='fas fa-trash'></i></a>`,company.row_id// "<a href='#' class='btn btn-info btn-sm'><i class='fas fa-eye'></i></a>",// "<a href='#' class='btn btn-warning btn-sm'><i class='fas fa-edit'></i></a>",// "<a href='#' class='btn btn-danger btn-sm'><i class='fas fa-trash'></i></button>"]).draw(false);});contentSection.style.display = 'block';}} catch (error) {console.error('Error fetching company documents:', error);//displayEmptyTable();displayErrorMessage("Knowledgebase details1 do not exist for this company. Please fill in the details.");contentSection.style.display = 'none';}} else {// displayEmptyTable();displayErrorMessage("Details for knowledgebase do not exist for this company. Please fill in the details.");}} catch (error) {console.error('No details for this company ID or data documents:', error);// displayEmptyTable();displayErrorMessage("Knowledgebase details do not exist for this company. Please fill in the details.");contentSection.style.display = 'none';}} else {table.clear().draw();document.getElementById('contentSection').style.display = 'none';clearFormFields();}});function displayErrorMessage(message) {const messageContainer = document.getElementById('message-container');if (messageContainer) {messageContainer.innerHTML = `<div class='alert alert-danger'>${message}</div>`;}}});function clearFormFields() {document.getElementById('file-name').textContent=""document.getElementById('uploadFile').value = "";document.getElementById('documentName').value = "";document.getElementById('documentDescription').value = "";document.getElementById('department').value = "";document.getElementById('version').value = "";//document.getElementById('lastUpdated').value = "";}1 unmodified line// Show modal function$('#add').on('click', function () {$('#documentName').removeAttr('readonly');$('#documentDescription').removeAttr('readonly');$('#department').removeAttr('readonly');$('#version').removeAttr('readonly');$('#lastUpdated').removeAttr('readonly');const modalTitle = document.getElementById('addModalLabel');modalTitle.textContent = 'Add Knowledgebase Details';$('#uploadFile').show();$('#saveupdate').hide();$('#save').show();clearFormFields();$('#message-container').empty(); // Clear the message container$('#addModal').modal('show');});$('.modal-footer .btn-secondary, .modal-header .btn-close').on('click', function () {$('#addModal').modal('hide');});5 unmodified linesfunction viewCompany(button) {var companyId = $(button).data('kid-id');const modalTitle = document.getElementById('addModalLabel');modalTitle.textContent = 'View Knowledgebase Details';$.getJSON(`/api/getknowledgebase/${companyId}`, function (company) {$('#uploadFile').hide();$('#file-name').text(company.file_path).attr('readonly','readonly');$('#documentName').val(company.document_name).attr('readonly', 'readonly');$('#documentDescription').val(company.document_desc).attr('readonly', 'readonly');$('#department').val(company.department).attr('readonly', 'readonly');1 unmodified line//$('#lastUpdated').val(company.last_updated).attr('readonly', 'readonly');var lastUpdated = company.last_updated;$('#lastUpdated').val(lastUpdated).attr('readonly', 'readonly');$('#save').hide();$('#saveupdate').hide();$('#addModal').modal('show');}).fail(function () {alert("Error retrieving knowledge base details.");});}// Edit knowledge base detailsfunction editCompany(button) {var companyId = $(button).data('kid-id');const modalTitle = document.getElementById('addModalLabel');modalTitle.textContent = 'Edit Knowledgebase Details';// Fetch company details by ID$.getJSON(`/api/getknowledgebase/${companyId}`, function (company) {const fileName = company.file_path.split('/').pop();const fileContent = new Blob([""], { type: 'text/plain' });const file = new File([fileContent], fileName, { type: fileContent.type });const dataTransfer = new DataTransfer();dataTransfer.items.add(file);// Set the file input's files property to the created fileconst fileInput = document.getElementById('uploadFile');fileInput.files = dataTransfer.files;// Check if the input element is of type 'file'if (fileInput.type === 'file') {console.log("The input is of type 'file'.");} else {console.log("The input is NOT of type 'file'.");}// Check if the value is of type 'File'const files = fileInput.files;if (files.length > 0 && files[0] instanceof File) {console.log("The value is of type 'File':", files[0].name);} else {console.log("No file is selected or the value is not of type 'File'.");}$('#uploadFileLabel').text(files[0].name);$('#uploadFile').text(files[0].name)$('#documentName').val(company.document_name);$('#documentDescription').val(company.document_desc);$('#department').val(company.department);$('#version').val(company.version);$('#lastUpdated').val(company.last_updated);$('#company_id').val(company.company_id);// Show/hide appropriate elements$('#uploadFile').show(); // Hide the file upload field$('#save').hide(); // Hide the default save button$('#saveupdate').show(); // Show the update button// Ensure fields are editable$('#documentName').removeAttr('readonly');$('#documentDescription').removeAttr('readonly');$('#department').removeAttr('readonly');$('#version').removeAttr('readonly');$('#lastUpdated').removeAttr('readonly');$('#company_id').val(company.company_id); // Ensure company_id is included if necessary// Show the modal$('#addModal').modal('show');// Set up the click event for the update button$('#saveupdate').off('click').on('click', function () {saveupdate(companyId,files[0].name); // Pass the company ID for updating});}).fail(function () {alert("Error retrieving knowledge base details.");});}function saveupdate(companyId, filename) {const formData = new FormData();const fileInput = document.getElementById("uploadFile");const uploadFile = fileInput.files[0]; // Get the file objectconst company_id=document.getElementById("company_id").value;formData.append("company_id", $('#company_id').val());formData.append("documentName", $('#documentName').val());formData.append("documentDescription", $('#documentDescription').val());formData.append("department", $('#department').val());formData.append("version", $('#version').val());formData.append("vectorDBFlag", 'NO');formData.append("lastUpdated", $('#lastUpdated').val());console.log("company_id to table refresh",company_id)// Append the file only if it exists, otherwise, append the filenameif (uploadFile) {formData.append("file_path", uploadFile); // Append the file object} else {formData.append("file_path", filename); // Append the existing filename}$.ajax({url: `/api/putknowledgebase/${companyId}`,type: 'PUT',data: formData,processData: false, // Required for FormDatacontentType: false, // Required for FormDatasuccess: function (response) {// alert('Knowledgebase details updated successfully.');const messageContainer = document.getElementById('message-container');if(messageContainer)messageContainer.innerHTML = `<div class='alert alert-success'>Knowledgebasse Data updated successfully<button class='close' onclick='dismissMessage()'>OK</button></div>`;$('#addModal').modal('hide'); // Close the modal after savingfetchUpdatedDocuments(company_id);},error: function () {const messageContainer = document.getElementById('message-container');if(messageContainer)messageContainer.innerHTML = `<div class='alert alert-danger'>No changes have been made to update knowledgebase details.<button class='close' onclick='dismissMessage()'>OK</button></div>`;$('#addModal').modal('hide');// alert('Form has no changes to update knowledge base details.');}});}async function fetchUpdatedDocuments(company_id) {console.log("company_id",company_id);var table = $('#knowledgeTable').DataTable();const Response = await fetch(`/api/document_update?company_id=${company_id}`);const connectorsResponse = await Response.json();console.log("knowledge data table after connecting to table", connectorsResponse);table.clear();if (!Array.isArray(connectorsResponse) || connectorsResponse.length === 0) {//displayEmptyTable();displayErrorMessage("Knowledgebase details do not exist for this company. Please fill in the details.");contentSection.style.display = 'none';} else {connectorsResponse.forEach((company, index) => {table.row.add([index + 1,company.document_name,company.document_desc,company.version,company.vectorDBflag,`<a href='#' class='btn btn-info btn-sm'data-kid-id='${company.row_id}' data-action="view" onclick='viewCompany(this)''><i class='fas fa-eye'></i></a>`,`<a href='#' class='btn btn-warning btn-sm'data-kid-id='${company.row_id}' data-action="edit" onclick='editCompany(this)'><i class='fas fa-edit'></i></a>`,//`<a href='#' class='btn btn-danger btn-sm' onclick='deleteCompany(${company.company_id})'><i class='fas fa-trash'></i></a>`,`<a href='#' class='btn btn-danger btn-sm' data-kid-id='${company.row_id}' onclick='deleteCompany(this)'><i class='fas fa-trash'></i></a>`,company.row_id// "<a href='#' class='btn btn-info btn-sm'><i class='fas fa-eye'></i></a>",// "<a href='#' class='btn btn-warning btn-sm'><i class='fas fa-edit'></i></a>",// "<a href='#' class='btn btn-danger btn-sm'><i class='fas fa-trash'></i></button>"]).draw(false);});contentSection.style.display = 'block';}}// Delete companyfunction deleteCompany(button) {var companyId = $(button).data('kid-id');console.log("k_id deleted",companyId);$.ajax({type: "DELETE",url: `/api/delknowledgebase/${companyId}`,success: function () {var table = $('#knowledgeTable').DataTable();table.row($(button).closest('tr')).remove().draw();const messageContainer = document.getElementById('message-container');if(messageContainer)messageContainer.innerHTML = `<div class='alert alert-danger'>Knowledgebase data deleted successfully.<button class='close' onclick='dismissMessage()'>OK</button></div>`;// alert("Knowledgebase data deleted successfully.");fetchCompanies(); // Refresh the table},error: function (xhr) {alert("Error deleting company: " + xhr.responseJSON.detail);}});}function save_file() {const form = document.getElementById('documentForm');14 unmodified lines//const formData = new FormData();var formData = new FormData($('#documentForm')[0]);const vectorDBFlag = "NO"; // Example valueconst view = "<a href='#' class='btn btn-info btn-sm'><i class='fas fa-eye'></i></a>";const edit = "<a href='#' class='btn btn-warning btn-sm'><i class='fas fa-edit'></i></a>";const dele= "<a href='#' class='btn btn-danger btn-sm'><i class='fas fa-trash'></i></a>";formData.append("uploadFile", uploadFile);13 unmodified linesif (!response.ok) {throw new Error('Network response was not ok');}return response.text();}).then(data => {var table = $('#knowledgeTable').DataTable();var rowCount = table.rows().count();table.row.add([rowCount + 1,documentName,10 unmodified linesmessageContainer.innerHTML = `<div class='alert alert-success'>Knowledgebase Data saved successfully<button class='close' onclick='dismissMessage()'>OK</button></div>`;// alert('Document saved successfully');$('#addModal').modal('hide');2 unmodified lines.catch(error => console.error('Error:', error));}function dismissMessage() {const messageContainer = document.getElementById('message-container');if (messageContainer) {messageContainer.innerHTML = '';}}async function fetchCompanies() {try {const response = await fetch('/api/companies');if (!response.ok) {throw new Error('Network response was not ok');}const data = await response.json();displayCompanies(data.companies);} catch (error) {console.error('Error fetching companies:', error);}}function displayCompanies(companies) {const companySelect = document.getElementById('company');companySelect.innerHTML = '<option value="" selected>Select</option>'; // Reset the dropdowncompanies.forEach(company => {const option = document.createElement('option');option.value = company.name;option.textContent = company.name;companySelect.appendChild(option);});}</script></body>17 unmodified lines1819202122232425263 unmodified lines303132333435362 unmodified lines3940414243444519 unmodified lines656667686970717273747576777879808145 unmodified lines1271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611622 unmodified lines1651661671681691701711721731741751761771781791801811821831841851 unmodified line1871881891901911921931941 unmodified line1961971981992002012022 unmodified lines2052062072082092102117 unmodified lines21922022122222322422522622722822923023123237 unmodified lines2702712722732742752762771 unmodified line2792802812822832842852862872882892902912922932942952962972982992 unmodified lines3023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983991 unmodified line4014024034044054064074084094104114124134144154164174184195 unmodified lines4254264274284294304314324334344354361 unmodified line43843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062114 unmodified lines63663763863964064164264364413 unmodified lines65865966066166266366466566666766866967067167210 unmodified lines6836846856866876886892 unmodified lines69269369469569669769869970070170270317 unmodified lines<style>body {background-color: transparent !important;}.content-wrapper {flex: 1;overflow-y: auto;}3 unmodified linesflex-direction: column;height: 100vh;}.modal-content {background-color: #fff;2 unmodified lines.content-header {padding: 1rem;}h1 {text-align: center;margin-bottom: 30px;19 unmodified linesmargin-right: 7.5px;}.text-wrap {white-space: normal !important;word-break: break-word;}div.dataTables_wrapper div.dataTables_length select {width: 60px;display: inline-block;}th {white-space: nowrap;}45 unmodified lines/* Delete column */width: auto;}.alert {position: relative;padding: 15px;margin-bottom: 20px;border: 1px solid transparent;border-radius: 4px;}.alert-success {color: #3c763d;background-color: #dff0d8;border-color: #d6e9c6;}.alert-danger {color: #a94442;background-color: #f2dede;border-color: #ebccd1;}.close {position: absolute;bottom: 10px;right: 10px;border: none;background: none;font-size: 16px;cursor: pointer;}</style></head>2 unmodified lines<div class="wrapper"><div class="main-header" style="border-bottom: none;"><div class="container mt-2"><div id="company-select" class="form-group left-align"><!-- <label for="company" class="mr-1" style="margin-left:-40px; margin-top: 12px;">Company Name <span class="text-danger">*</span></label><select type="text" id="company" name="company" class="form-control" style="width:20%;margin-left:-40px;"required><option value="" selected>Select</option></select> --><div class="col-12 d-flex justify-content-end mb-3"><button class="btn btn-primary" style="margin-top:10px;margin-right: -10px;position: fixed;"id="add" data-action="add">Add</button></div></div></div><div class="row"><div id="message-container" style="margin-left: 200px;width:600px;"></div></div><h3 id="company_name" style="margin-left: 400px;">{{company_name}}</h3><section class="content" id="contentSection" style="display: none;"><div class="container-fluid"><div>1 unmodified line<!-- <label for="company_id">company_id</label>---><input type="hidden" id="company_id" name="company_id" class="form-control" required></div><h4 id="selectedCompany" style="margin-left: 300px;"></h4><div class="row" style="margin-top: 50px;"><div class="col-12"><div class="card"><div id="message-container">1 unmodified line<table id="knowledgeTable" class="table table-bordered table-striped"><thead><tr><th>Sno</th><th>Document Name</th><th>Document Description</th>2 unmodified lines<th>View</th><th>Edit</th><th>Delete</th><!-- <th style="display:none;">Company ID</th> --></tr></thead><tbody>7 unmodified lines</div></section></div><div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel"aria-hidden="true"><div class="modal-dialog" role="document"><div class="modal-content"><div class="modal-header"><h5 class="modal-title" id="addModalLabel">Add Document Details</h5><button type="button" class="btn-close" data-dismiss="modal"><span aria-hidden="true" data-backdrop="static" data-keyboard="false"></span></button></div>37 unmodified lines</div><div class="modal-footer"><!-- <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> --><button type="button" id="saveupdate" class="btn btn-primary"style="display: none;">Update</button><button type="button" id="save" onclick="save_file()" class="btn btn-primary">Save</button></div></div>1 unmodified line</div></div>{%include 'footer.html'%}<script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script><script src="https://cdn.datatables.net/1.10.25/js/dataTables.bootstrap4.min.js"></script><script>var table = $('#knowledgeTable').DataTable();const role = sessionStorage.getItem('userRole');const company_name=sessionStorage.getItem('company_name');console.log("company_name",company_name);// document.getElementById('company_name').textContent = company_name;document.addEventListener("DOMContentLoaded", function () {now = new Date().toISOString().replace('T', ' ').substr(0, 19);document.getElementById('lastUpdated').value = now;const inputs = document.querySelectorAll("#documentForm input, textarea");inputs.forEach((input, index) => {input.addEventListener("keydown", function (event) {if (event.key === "Enter") {2 unmodified lines}});});const passedCompanyName=sessionStorage.getItem('company_name')document.getElementById('selectedCompany').innerText = `Company name: ${passedCompanyName}`;console.log('Current role:', role); // Debug statement to check the roleconst company_id=sessionStorage.getItem('company_id');document.getElementById("company_id").value=company_id;console.log("inside knowledgebaae sessionstorage",company_id);data_get_from_db(company_id);const companySelect = document.getElementById('company');const documentForm = document.getElementById('documentForm');});function moveToNextInput(inputs, currentIndex) {const nextInput = inputs[currentIndex + 1];if (nextInput) {nextInput.focus();} else {// Optionally, submit the form or trigger the save buttondocument.getElementById("save").focus();}}async function data_get_from_db(company_id) {if (company_id) {try {const Response = await fetch(`/api/document_upload?company_id=${company_id}`);console.log("responce from api :==> ", Response)const connectorsResponse = await Response.json();console.log("knowledge data table after connecting to table", connectorsResponse);const table = $('#knowledgeTable').DataTable(); // Initialize DataTable at the starttable.clear();if (!Array.isArray(connectorsResponse) || connectorsResponse.length === 0) {// displayEmptyTable();displayErrorMessage("Document details do not exist for this company. Please fill in the details.");contentSection.style.display = 'none';} else {console.log('company data retrived succesfully ! .........')connectorsResponse.forEach((company, index) => {table.row.add([index + 1,company.document_name,company.document_desc,company.version,company.vectorDBflag,`<a href='#' class='btn btn-info btn-sm'data-kid-id='${company.row_id}' data-action="view" onclick='viewCompany(this)''><i class='fas fa-eye'></i></a>`,`<a href='#' class='btn btn-warning btn-sm'data-kid-id='${company.row_id}' data-action="edit" onclick='editCompany(this)'><i class='fas fa-edit'></i></a>`,`<a href='#' class='btn btn-danger btn-sm' data-kid-id='${company.row_id}' onclick='deleteCompany(this)'><i class='fas fa-trash'></i></a>`,company.row_id// "<a href='#' class='btn btn-info btn-sm'><i class='fas fa-eye'></i></a>",// "<a href='#' class='btn btn-warning btn-sm'><i class='fas fa-edit'></i></a>",// "<a href='#' class='btn btn-danger btn-sm'><i class='fas fa-trash'></i></button>"]).draw(false);});contentSection.style.display = 'block';}} catch (error) {console.error('Error fetching company documents:', error);//displayEmptyTable();displayErrorMessage("Document details1 do not exist for this company. Please fill in the details.");contentSection.style.display = 'none';}} else {// displayEmptyTable();displayErrorMessage("Details for knowledgebase do not exist for this company. Please fill in the details.");}}function displayErrorMessage(message) {const messageContainer = document.getElementById('message-container');if (messageContainer) {messageContainer.innerHTML = `<div class='alert alert-danger'>${message}</div>`;}}function clearFormFields() {document.getElementById('file-name').textContent = ""document.getElementById('uploadFile').value = "";document.getElementById('documentName').value = "";document.getElementById('documentDescription').value = "";document.getElementById('department').value = "";document.getElementById('version').value = "";// document.getElementById('lastUpdated').value = "";}1 unmodified line// Show modal function$('#add').on('click', function () {$('#documentName').removeAttr('readonly');$('#documentDescription').removeAttr('readonly');$('#department').removeAttr('readonly');$('#version').removeAttr('readonly');$('#lastUpdated').removeAttr('readonly');const modalTitle = document.getElementById('addModalLabel');modalTitle.textContent = 'Add Document Details';$('#save').show();$('#uploadFile').show();$('#saveupdate').hide();clearFormFields();$('#message-container').empty(); // Clear the message container$('#addModal').modal('show');});$('.modal-footer .btn-secondary, .modal-header .btn-close').on('click', function () {$('#addModal').modal('hide');});5 unmodified linesfunction viewCompany(button) {var companyId = $(button).data('kid-id');const modalTitle = document.getElementById('addModalLabel');modalTitle.textContent = 'View Document Details';if(companyId){$.getJSON(`/api/getknowledgebase/${companyId}`, function (company) {$('#uploadFile').hide();$('#file-name').text(company.file_path).attr('readonly', 'readonly');$('#documentName').val(company.document_name).attr('readonly', 'readonly');$('#documentDescription').val(company.document_desc).attr('readonly', 'readonly');$('#department').val(company.department).attr('readonly', 'readonly');1 unmodified line//$('#lastUpdated').val(company.last_updated).attr('readonly', 'readonly');var lastUpdated = company.last_updated;$('#lastUpdated').val(lastUpdated).attr('readonly', 'readonly');$('#save').hide();// Disable the "Save" button when the modal opens$('#addModal').modal('show');}).fail(function () {alert("Error retrieving knowledge base check the sidepane working.");});}}// Edit knowledge base detailsfunction editCompany(button) {var companyId = $(button).data('kid-id');const modalTitle = document.getElementById('addModalLabel');modalTitle.textContent = 'Edit Document Details';// Fetch company details by IDif(companyId){$.getJSON(`/api/getknowledgebase/${companyId}`, function (company) {const fileName = company.file_path.split('/').pop();const fileContent = new Blob([""], { type: 'text/plain' });const file = new File([fileContent], fileName, { type: fileContent.type });const dataTransfer = new DataTransfer();dataTransfer.items.add(file);// Set the file input's files property to the created fileconst fileInput = document.getElementById('uploadFile');fileInput.files = dataTransfer.files;// Check if the input element is of type 'file'if (fileInput.type === 'file') {console.log("The input is of type 'file'.");} else {console.log("The input is NOT of type 'file'.");}// Check if the value is of type 'File'const files = fileInput.files;if (files.length > 0 && files[0] instanceof File) {console.log("The value is of type 'File':", files[0].name);} else {console.log("No file is selected or the value is not of type 'File'.");}$('#uploadFileLabel').text(files[0].name);$('#uploadFile').text(files[0].name)$('#documentName').val(company.document_name);$('#documentDescription').val(company.document_desc);$('#department').val(company.department);$('#version').val(company.version);$('#lastUpdated').val(company.last_updated).attr('readonly', 'readonly');$('#company_id').val(company.company_id);// Show/hide appropriate elements$('#uploadFile').show(); // Hide the file upload field$('#save').hide(); // Hide the default save button$('#saveupdate').show(); // Show the update button// Ensure fields are editable$('#documentName').removeAttr('readonly');$('#documentDescription').removeAttr('readonly');$('#department').removeAttr('readonly');$('#version').removeAttr('readonly');// $('#lastUpdated').removeAttr('readonly');$('#company_id').val(company.company_id); // Ensure company_id is included if necessary// Show the modal$('#addModal').modal('show');// Set up the click event for the update button$('#saveupdate').off('click').on('click', function () {saveupdate(companyId, files[0].name); // Pass the company ID for updating});}).fail(function () {alert("Error retrieving knowledge base error 2 details.");});}}// Delete companyfunction deleteCompany(button) {var companyId = $(button).data('kid-id');console.log("k_id deleted", companyId);$.ajax({type: "DELETE",url: `/api/delknowledgebase/${companyId}`,success: function () {var table = $('#knowledgeTable').DataTable();table.row($(button).closest('tr')).remove().draw();alert("Company deleted successfully.");fetchCompanies(); // Refresh the table},error: function (xhr) {alert("Error deleting company: " + xhr.responseJSON.detail);}});}function saveupdate(companyId, filename) {const formData = new FormData();const fileInput = document.getElementById("uploadFile");const uploadFile = fileInput.files[0]; // Get the file objectconst company_id = document.getElementById("company_id").value;formData.append("company_id", $('#company_id').val());formData.append("documentName", $('#documentName').val());formData.append("documentDescription", $('#documentDescription').val());formData.append("department", $('#department').val());formData.append("version", $('#version').val());formData.append("vectorDBFlag", 'NO');formData.append("lastUpdated", $('#lastUpdated').val());console.log("company_id to table refresh", company_id)// Append the file only if it exists, otherwise, append the filenameif (uploadFile) {formData.append("file_path", uploadFile); // Append the file object} else {formData.append("file_path", filename); // Append the existing filename}$.ajax({url: `/api/putknowledgebase/${companyId}`,type: 'PUT',data: formData,processData: false, // Required for FormDatacontentType: false, // Required for FormDatasuccess: function (response) {// alert('Knowledgebase details updated successfully.');const messageContainer = document.getElementById('message-container');if (messageContainer)messageContainer.innerHTML = `<div class='alert alert-success'>Data saved successfully<button class='close' onclick='dismissMessage()'>OK</button></div>`;$('#addModal').modal('hide'); // Close the modal after savingfetchUpdatedDocuments(company_id);},error: function () {alert('Form has no changes to update knowledge base details.');}});}async function fetchUpdatedDocuments(company_id) {console.log("company_id", company_id);var table = $('#knowledgeTable').DataTable();const Response = await fetch(`/api/document_update?company_id=${company_id}`);const connectorsResponse = await Response.json();console.log("knowledge data table after connecting to table", connectorsResponse);table.clear();if (!Array.isArray(connectorsResponse) || connectorsResponse.length === 0) {//displayEmptyTable();displayErrorMessage("Document details do not exist for this company. Please fill in the details.");contentSection.style.display = 'none';} else {connectorsResponse.forEach((company, index) => {table.row.add([index + 1,company.document_name,company.document_desc,company.version,company.vectorDBflag,`<a href='#' class='btn btn-info btn-sm'data-kid-id='${company.row_id}' data-action="view" onclick='viewCompany(this)''><i class='fas fa-eye'></i></a>`,`<a href='#' class='btn btn-warning btn-sm'data-kid-id='${company.row_id}' data-action="edit" onclick='editCompany(this)'><i class='fas fa-edit'></i></a>`,//`<a href='#' class='btn btn-danger btn-sm' onclick='deleteCompany(${company.company_id})'><i class='fas fa-trash'></i></a>`,`<a href='#' class='btn btn-danger btn-sm' data-kid-id='${company.row_id}' onclick='deleteCompany(this)'><i class='fas fa-trash'></i></a>`,company.row_id// "<a href='#' class='btn btn-info btn-sm'><i class='fas fa-eye'></i></a>",// "<a href='#' class='btn btn-warning btn-sm'><i class='fas fa-edit'></i></a>",// "<a href='#' class='btn btn-danger btn-sm'><i class='fas fa-trash'></i></button>"]).draw(false);});contentSection.style.display = 'block';}}function save_file() {const form = document.getElementById('documentForm');14 unmodified lines//const formData = new FormData();var formData = new FormData($('#documentForm')[0]);const vectorDBFlag = "NO"; // Example value// const view = "<a href='#' class='btn btn-info btn-sm'><i class='fas fa-eye'></i></a>";// const edit = "<a href='#' class='btn btn-warning btn-sm'><i class='fas fa-edit'></i></a>";// const dele= "<a href='#' class='btn btn-danger btn-sm'><i class='fas fa-trash'></i></a>";formData.append("uploadFile", uploadFile);13 unmodified linesif (!response.ok) {throw new Error('Network response was not ok');}return response.json();}).then(data => {const row_id=data.row_id;var table = $('#knowledgeTable').DataTable();var rowCount = table.rows().count();const view=`<a href='#' class='btn btn-info btn-sm'data-kid-id='${row_id}' data-action="view" onclick='viewCompany(this)''><i class='fas fa-eye'></i></a>`;const edit=`<a href='#' class='btn btn-warning btn-sm'data-kid-id='${row_id}' data-action="edit" onclick='editCompany(this)'><i class='fas fa-edit'></i></a>`;const dele= `<a href='#' class='btn btn-danger btn-sm' data-kid-id='${row_id}' onclick='deleteCompany(this)'><i class='fas fa-trash'></i></a>`;table.row.add([rowCount + 1,documentName,10 unmodified linesmessageContainer.innerHTML = `<div class='alert alert-success'>Knowledgebase Data saved successfully<button class='close' style='font-size:medium;margin-top:6px;' onclick='dismissMessage()'>OK</button></div>`;// alert('Document saved successfully');$('#addModal').modal('hide');2 unmodified lines.catch(error => console.error('Error:', error));}function dismissMessage() {const messageContainer = document.getElementById('message-container');if (messageContainer) {messageContainer.innerHTML = '';}}</script></body>
templates/knowledgebase.html+311-368