Redmind_GPT_API / templates /API_connectors.html
Redmind's picture
Update templates/API_connectors.html
c9f725a verified
<!DOCTYPE html>
<html>
<head>
<title>API Connectors</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<!-- Include AdminLTE CSS -->
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/adminlte.min.css">
<!-- Include DataTables CSS -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/dataTables.bootstrap4.min.css">
<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>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" />
<style>
.form-group {
margin-top: -10px;
}
.card {
padding: 0;
margin-top: -15px;
margin-left: -40px;
}
.header-row {
display: flex;
justify-content: space-between;
align-items: center;
}
.table-container {
width: 100%;
overflow-x: auto;
}
.wrapper {
display: flex;
flex-direction: column;
height: 100vh;
}
.content-wrapper {
flex: 1;
overflow-y: auto;
}
.content-header {
padding: 5px;
}
th,
td {
white-space: nowrap;
}
th:nth-child(1),
td:nth-child(1) {
/* Sno column */
width: 5%;
}
div.dataTables_wrapper div.dataTables_length select {
width: 60px;
display: inline-block;
}
th:nth-child(2),
td:nth-child(2) {
/* API Name column */
width: 20%;
}
th:nth-child(3),
td:nth-child(3) {
/* API Endpoint column */
width: 40%;
}
th:nth-child(4),
td:nth-child(4) {
/* Auth/Bearer token column */
width: 5%;
}
th:nth-child(5),
td:nth-child(5) {
/* View column */
width: 5%;
}
th:nth-child(6),
td:nth-child(6) {
/* View column */
width: 5%;
}
.reduced-width {
width: 25%;
}
div.dataTables_wrapper div.dataTables_length select {
width: 60px;
display: inline-block;
}
</style>
</head>
<body>
{% include 'sidepane.html' %}
<div class="wrapper">
<div class="main-header" style="border-bottom: none;">
<!-- Content Header (Page header) -->
<div class="content-header">
<div class="container-fluid">
<div class="container mt-2">
<div class="form-group left-align"id="company-select">
<h4 id="selectedCompany" style="margin-left: 300px;"></h4>
<!-- <div class="col-12 d-flex justify-content-end mb-3">
<button class="btn btn-primary"
style="margin-top: -40px;margin-right: -25px;position: fixed;" id="add">Add</button>
</div> -->
</div>
<div class="row">
<div id="message-container" style="margin-left: 200px; width:500px;"></div>
</div>
</div>
</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 class="form-group">
<!-- <label for="company_id">company_id</label>--->
<input type="hidden" id="company_id" name="company_id" class="form-control" required>
</div>
</div>
<!-- Main content -->
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body table-container">
<table id="apiTable" class="table table-bordered table-striped">
<thead>
<tr>
<th>Sno</th>
<th>API Name</th>
<th>API Endpoint</th>
<th>View</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<!-- <tr>
<td>1</td>
<td>Warehouse</td>
<td>http://193.203.162.39:9090/nxt-wms/userWarehouse/fetchWarehouseForUserId
</td>
<td><button class="btn btn-primary viewButton">View</button></td>
</tr>
<tr>
<td>2</td>
<td>customer</td>
<td>http://193.203.162.39:9090/nxt-wms/userCustomer/fetchCustomerForUserId
</td>
<td><button class="btn btn-primary viewButton">View</button></td>
</tr>
<tr>
<td>3</td>
<td>SKU</td>
<td>http://193.203.162.39:9090/nxt-wms/sku/autoComplete?</td>
<td><button class="btn btn-primary viewButton">View</button></td>
</tr>
<tr>
<td>4</td>
<td>ASN</td>
<td>http://193.203.162.39:9090/nxt-wms/trnHeader</td>
<td><button class="btn btn-primary viewButton">View</button></td>
</tr> -->
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel"
aria-hidden="true">
<div class="modal-dialog" style="margin-top: -10px;" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addModalLabel">Add API Details</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true" data-backdrop="static" data-keyboard="false">&times;</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<!-- <label for="company_id">company_id</label>--->
<input type="hidden" id="company_id" name="company_id" class="form-control" required>
</div>
<form id="documentForm">
<div class="form-group">
<label for="APIName">API Name <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="APIName" name="APIName" required>
</div>
<div class="form-group">
<label for="APIEndpoint">API Endpoint <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="APIEndpoint" name="APIEndpoint" required>
</div>
<div class="form-group">
<label for="Auth_Bearer">Auth/Bearer token <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="Auth_Bearer" name="Auth_Bearer" required>
</div>
<div class="form-group">
<label for="Inputjson">Input parameter <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="Inputjson" name="Inputjson" required>
</div>
<div class="form-group">
<label for="OutputJson">Output Json <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="OutputJson" name="OutputJson" required>
</div>
<div class="form-group">
<label for="Description">Description <span class="text-danger">*</span></label>
<textarea class="form-control" id="Description" name="Description" rows="3"
required></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<!-- <button type="button" class="btn btn-secondary" data-bs-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>
</div>
</div>
{%include 'footer.html'%}
<!-- Include DataTables JS and your custom script -->
<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>
$(document).ready(function () {
// Show modal function
$('#add').on('click', function () {
const modalTitle = document.getElementById('addModalLabel');
modalTitle.textContent = 'Add API Details';
clearFormFields();
$('#save').show();
$('#saveupdate').hide();
$('#message-container').empty(); // Clear the message container
$('#addModal').modal('show');
});
$('.modal-footer .btn-secondary, .modal-header .close').on('click', function () {
$('#addModal').modal('hide');
});
// $('#apiTable').DataTable({
// autoWidth: false
// });
});
var table = $('#apiTable').DataTable();
const role = sessionStorage.getItem('userRole');
console.log('Current role:', role); // Debug statement to check the role
const company_name=sessionStorage.getItem('company_name');
console.log("company_name",company_name);
// document.getElementById('company_name').textContent = company_name;
const passedCompanyName = sessionStorage.getItem('company_name')
document.getElementById('selectedCompany').innerText = `Company Name: ${passedCompanyName}`;
const company_id = sessionStorage.getItem('company_id');
document.getElementById("company_id").value = 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 button
document.getElementById("save").focus();
}
}
function displayErrorMessage(message) {
const messageContainer = document.getElementById('message-container');
if (messageContainer) {
messageContainer.innerHTML = `<div class='alert alert-danger'>${message}</div>`;
}
}
async function data_get_from_db(companyId) {
if (companyId) {
try {
console.log('comp_id',companyId)
const Response = await fetch(`/api/get_api_connectors?company_id=${companyId}`);
console.log("responce from api :==> ", Response)
const connectorsResponse = await Response.json();
console.log("knowledge data table after connecting to table", connectorsResponse);
console.log("api connector data table after connecting to table", connectorsResponse);
const table = $('#apiTable').DataTable(); // Initialize DataTable at the start
table.clear();
if (!Array.isArray(connectorsResponse)) {
throw new TypeError('Expected an array of companies');
displayErrorMessage("Data do not exist for this company. Please fill in the details by clicking add button.");
contentSection.style.display = 'none';
} else {
connectorsResponse.forEach((company, index) => {
table.row.add([
index + 1,
company.APIName,
company.APIEndpoint,
`<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>`,
]).draw(false);
});
contentSection.style.display = 'block';
}
} catch (error) {
console.error('Error fetching company documents:', error);
//displayEmptyTable();
displayErrorMessage("Data do not exist for this company. Please fill in the details by clicking add button.");
contentSection.style.display = 'none';
}
}
else {
// displayEmptyTable();
displayErrorMessage("Document details2 for knowledge do not exist for this company. Please fill in the details.");
}
}
function viewCompany(button) {
var companyId = $(button).data('kid-id');
const modalTitle = document.getElementById('addModalLabel');
modalTitle.textContent = 'View API Details';
if(companyId)
{
$.getJSON(`/api/viewapiconnectors/${companyId}`, function (company) {
$('#APIName').val(company.api_name).attr('readonly', 'readonly');
$('#APIEndpoint').val(company.api_endpoint).attr('readonly', 'readonly');
$('#Auth_Bearer').val(company.auth_token).attr('readonly', 'readonly');
$('#Inputjson').val(company.input_param).attr('readonly', 'readonly');
$('#OutputJson').val(company.output_json).attr('readonly', 'readonly');
$('#Description').val(company.description).attr('readonly', 'readonly');
$('#save').hide();
$('#saveupdate').hide();
$('#addModal').modal('show');
}).fail(function () {
alert("Error retrieving API details.");
});
}
}
// Edit knowledge base details
function editCompany(button) {
var companyId = $(button).data('kid-id');
const modalTitle = document.getElementById('addModalLabel');
modalTitle.textContent = 'Edit API Details';
if(companyId)
{
// Fetch company details by ID
$.getJSON(`/api/viewapiconnectors/${companyId}`, function (company) {
$('#APIName').val(company.api_name);
$('#APIEndpoint').val(company.api_endpoint);
$('#Auth_Bearer').val(company.auth_token);
$('#Inputjson').val(company.input_param);
$('#OutputJson').val(company.output_json);
$('#Description').val(company.description);
// 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
$('#APIName').removeAttr('readonly');
$('#APIEndpoint').removeAttr('readonly');
$('#Auth_Bearer').removeAttr('readonly');
$('#Inputjson').removeAttr('readonly');
$('#OutputJson').removeAttr('readonly');
$('#Description').removeAttr('readonly');
// Show the modal
$('#addModal').modal('show');
// Set up the click event for the update button
$('#saveupdate').off('click').on('click', function () {
saveupdate(companyId); // Pass the company ID for updating
});
}).fail(function () {
alert("Error in retrieving API details.");
});
}
}
function saveupdate(companyId, filename) {
const formData = new FormData();
const company_id = document.getElementById("company_id").value;
formData.append("company_id", $('#company_id').val());
formData.append("APIName", $('#APIName').val());
formData.append("APIEndpoint", $('#APIEndpoint').val());
formData.append("Auth_Bearer", $('#Auth_Bearer').val());
formData.append("Inputjson", $('#Inputjson').val());
formData.append("OutputJson", $('#OutputJson').val());
formData.append("Description", $('#Description').val());
console.log("company_id to table refresh", company_id)
const messageContainer = document.getElementById('message-container');
$.ajax({
url: `/api/editapiconnectors/${companyId}`,
type: 'PUT',
data: formData,
processData: false, // Required for FormData
contentType: false, // Required for FormData
success: function (response) {
// alert('Knowledgebase details updated successfully.');
if (messageContainer)
messageContainer.innerHTML = `
<div class='alert alert-success'>
API Data Updated successfully
<button class='close' onclick='dismissMessage()'>OK</button>
</div>`;
$('#addModal').modal('hide'); // Close the modal after saving
fetchUpdatedDocuments(company_id);
},
error: function () {
alert('Form has no changes to update knowledge base details.');
}
});
}
function dismissMessage() {
const messageContainer = document.getElementById('message-container');
if (messageContainer) {
messageContainer.innerHTML = '';
}
}
async function fetchUpdatedDocuments(company_id) {
console.log("company_id:", company_id);
var table = $('#apiTable').DataTable();
try {
const response = await fetch(`/api/api_updatetable?company_id=${company_id}`);
const connectorsResponse = await response.json();
console.log("Fetched connectorsResponse:", connectorsResponse);
table.clear(); // Clear existing data in the table
if (!Array.isArray(connectorsResponse) || connectorsResponse.length === 0) {
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.api_name,
company.api_endpoint,
`<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
]);
});
table.draw(false); // Draw the table with the new data
contentSection.style.display = 'block';
}
} catch (error) {
console.error("Error fetching updated documents:", error);
displayErrorMessage("There was an error fetching the updated documents.");
}
}
// Delete company
function deleteCompany(button) {
var companyId = $(button).data('kid-id');
console.log("k_id deleted", companyId);
$.ajax({
type: "DELETE",
url: `/api/deleteapi/${companyId}`,
success: function () {
var table = $('#apiTable').DataTable();
table.row($(button).closest('tr')).remove().draw();
const messageContainer = document.getElementById('message-container');
if (messageContainer)
messageContainer.innerHTML = `
<div class='alert alert-danger'>
API Data Deleted successfully
<button class='close' onclick='dismissMessage()'>OK</button>
</div>`;
//alert("Company deleted successfully.");
fetchCompanies(); // Refresh the table
},
error: function (xhr) {
alert("Error deleting company: " + xhr.responseJSON.detail);
}
});
}
function save_file() {
const form = document.getElementById('documentForm');
const messageContainer = document.getElementById('message-container');
// Check if the form is valid
if (!form.checkValidity()) {
// If the form is invalid, show validation messages and stop the submission
form.reportValidity();
return;
}
const company_id = $('#company_id').val();
const APIName = $('#APIName').val();
const APIEndpoint = $('#APIEndpoint').val();
const Auth_Bearer = $('#Auth_Bearer').val();
const Inputjson = $('#Inputjson').val();
const OutputJson = $('#OutputJson').val();
const Description = $('#Description').val();
var formData = new FormData($('#documentForm')[0]);
formData.append("company_id", company_id),
formData.append("api_name", APIName),
formData.append("api_endpoint", APIEndpoint),
formData.append("auth_bearer", Auth_Bearer),
formData.append("input_json", Inputjson),
formData.append("output_json", OutputJson),
formData.append("description", Description)
//const formData = new FormData();
fetch('/api/save_api_details', {
method: 'POST',
body: formData
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
row_id = data.row_id;
var table = $('#apiTable').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,
APIName,
APIEndpoint,
view,
edit,
dele
]).draw(false);
// alert('Document saved successfully');
if (messageContainer)
messageContainer.innerHTML = `
<div class='alert alert-success'>
API Data saved successfully
<button class='close' onclick='dismissMessage()'>OK</button>
</div>`;
$('#addModal').modal('hide');
document.getElementById('contentSection').style.display = 'block'; // Show the table section
})
.catch(error => console.error('Error:', error));
}
function clearFormFields() {
document.getElementById('APIName').value = "";
document.getElementById('APIEndpoint').value = "";
document.getElementById('Auth_Bearer').value = "";
document.getElementById('Inputjson').value = "";
document.getElementById('OutputJson').value = "";
document.getElementById('Description').value = "";
}
</script>
</body>
</html>