FE+BE: init check work, removed legacy setDeviceData

Signed-off-by: jokob-sk <jokob.sk@gmail.com>
This commit is contained in:
jokob-sk
2025-12-18 09:02:57 +11:00
parent bc76c04f9e
commit daa720ab94
4 changed files with 325 additions and 271 deletions

View File

@@ -14,21 +14,21 @@
<!-- Buttons -->
<div class="col-xs-12">
<div class="pull-right">
<button type="button"
class="btn btn-default pa-btn pa-btn-delete"
style="margin-left:0px;"
id="btnDelete"
onclick="askDeleteDevice()">
<i class="fas fa-trash-alt"></i>
<?= lang('DevDetail_button_Delete');?>
<button type="button"
class="btn btn-default pa-btn pa-btn-delete"
style="margin-left:0px;"
id="btnDelete"
onclick="askDeleteDevice()">
<i class="fas fa-trash-alt"></i>
<?= lang('DevDetail_button_Delete');?>
</button>
<button type="button"
class="btn btn-primary pa-btn"
style="margin-left:6px; "
id="btnSave"
onclick="setDeviceData()" >
<button type="button"
class="btn btn-primary pa-btn"
style="margin-left:6px; "
id="btnSave"
onclick="setDeviceData()" >
<i class="fas fa-save"></i>
<?= lang('DevDetail_button_Save');?>
<?= lang('DevDetail_button_Save');?>
</button>
</div>
</div>
@@ -36,8 +36,8 @@
<script defer>
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// Get plugin and settings data from API endpoints
function getDeviceData(){
@@ -45,8 +45,8 @@
console.log(mac);
// get data from server
$.get('php/server/devices.php?action=getServerDeviceData&mac='+ mac + '&period='+ period, function(data) {
// get data from server
$.get('php/server/devices.php?action=getServerDeviceData&mac='+ mac + '&period='+ period, function(data) {
// show loading dialog
showSpinner()
@@ -55,30 +55,30 @@
// some race condition, need to implement delay
setTimeout(() => {
$.get('php/server/query_json.php', {
file: 'table_settings.json',
// nocache: Date.now()
},
function(res) {
$.get('php/server/query_json.php', {
file: 'table_settings.json',
// nocache: Date.now()
},
function(res) {
settingsData = res["data"];
// columns to hide
hiddenFields = ["NEWDEV_devScan", "NEWDEV_devPresentLastScan" ]
// columns to disable/readonly - conditional depending if a new dummy device is created
disabledFields = mac == "new" ? ["NEWDEV_devLastNotification", "NEWDEV_devFirstConnection", "NEWDEV_devLastConnection"] : ["NEWDEV_devLastNotification", "NEWDEV_devFirstConnection", "NEWDEV_devLastConnection", "NEWDEV_devMac", "NEWDEV_devLastIP", "NEWDEV_devSyncHubNode", "NEWDEV_devFQDN" ];
// Grouping of fields into categories with associated documentation links
const fieldGroups = {
// Group for device main information
DevDetail_MainInfo_Title: {
data: ["devMac", "devLastIP", "devName", "devOwner", "devType", "devVendor", "devGroup", "devIcon", "devLocation", "devComments"],
data: ["devMac", "devLastIP", "devName", "devOwner", "devType", "devVendor", "devGroup", "devIcon", "devLocation", "devComments"],
docs: "https://github.com/jokob-sk/NetAlertX/blob/main/docs/DEVICE_MANAGEMENT.md",
iconClass: "fa fa-pencil",
inputGroupClasses: "field-group main-group col-lg-4 col-sm-6 col-xs-12",
labelClasses: "col-sm-4 col-xs-12 control-label",
inputClasses: "col-sm-8 col-xs-12 input-group"
},
},
// Group for event and alert settings
DevDetail_EveandAl_Title: {
data: ["devAlertEvents", "devAlertDown", "devSkipRepeated", "devReqNicsOnline", "devChildrenNicsDynamic"],
@@ -150,14 +150,14 @@
// Loop over each field group to generate sections for each category
Object.entries(fieldGroups).forEach(([groupName, obj]) => {
const groupDiv = $('<div>').addClass(obj.inputGroupClasses); // Create a div for each group with responsive Bootstrap classes
// Add group title and documentation link
groupDiv.append(`<h5><i class="${obj.iconClass}"></i> ${getString(groupName)}
groupDiv.append(`<h5><i class="${obj.iconClass}"></i> ${getString(groupName)}
<span class="helpIconSmallTopRight">
<a target="_blank" href="${obj.docs}">
<i class="fa fa-circle-question"></i>
</a>
</span>
</span>
</h5>
<hr>
`);
@@ -174,8 +174,8 @@
fieldData = fieldData == null ? "" : fieldData;
fieldOptionsOverride = null;
// console.log(setting.setKey);
// console.log(fieldData);
// console.log(setting.setKey);
// console.log(fieldData);
// Additional form elements like the random MAC address button for devMac
let inlineControl = "";
@@ -183,7 +183,7 @@
if (setting.setKey == "NEWDEV_devMac" && deviceData["devIsRandomMAC"] == true) {
inlineControl += `<span class="input-group-addon pointer"
title="${getString("RandomMAC_hover")}">
<a href="https://github.com/jokob-sk/NetAlertX/blob/main/docs/RANDOM_MAC.md" target="_blank">
<a href="https://github.com/jokob-sk/NetAlertX/blob/main/docs/RANDOM_MAC.md" target="_blank">
<i class="fa-solid fa-shuffle"></i>
</a>
</span>`;
@@ -204,15 +204,15 @@
<i class="fa-solid fa-dice" ></i>
</span>`;
}
// handle devChildrenDynamic or NEWDEV_devChildrenNicsDynamic - selected values and options are the same
if (
Array.isArray(fieldData) &&
(setting.setKey == "NEWDEV_devChildrenDynamic" ||
setting.setKey == "NEWDEV_devChildrenNicsDynamic" )
)
{
fieldDataNew = []
if (
Array.isArray(fieldData) &&
(setting.setKey == "NEWDEV_devChildrenDynamic" ||
setting.setKey == "NEWDEV_devChildrenNicsDynamic" )
)
{
fieldDataNew = []
fieldData.forEach(child => {
fieldDataNew.push(child.devMac)
})
@@ -222,10 +222,10 @@
// Generate the input field HTML
const inputFormHtml = `<div class="form-group col-xs-12">
<label id="${setting.setKey}_label" class="${obj.labelClasses}" > ${setting.setName}
<label id="${setting.setKey}_label" class="${obj.labelClasses}" > ${setting.setName}
<i my-set-key="${setting.setKey}"
title="${getString("Settings_Show_Description")}"
class="fa fa-circle-info pointer helpIconSmallTopRight"
title="${getString("Settings_Show_Description")}"
class="fa fa-circle-info pointer helpIconSmallTopRight"
onclick="showDescriptionPopup(this)">
</i>
</label>
@@ -247,29 +247,29 @@
updateAllIconPreviews();
// update readonly fields
handleReadOnly(settingsData, disabledFields);
handleReadOnly(settingsData, disabledFields);
};
// console.log(relevantSettings)
generateSimpleForm(relevantSettings);
toggleNetworkConfiguration(mac == 'Internet')
toggleNetworkConfiguration(mac == 'Internet')
initSelect2();
initHoverNodeInfo();
hideSpinner();
})
}, 100);
});
}
// ----------------------------------------
// Handle the read-only fields
@@ -306,62 +306,102 @@
showSpinner();
// Update data to server using POST
$.post('php/server/devices.php?action=setDeviceData', {
mac: $('#NEWDEV_devMac').val(),
name: encodeURIComponent($('#NEWDEV_devName').val().replace(/'/g, "")),
owner: encodeURIComponent($('#NEWDEV_devOwner').val().replace(/'/g, "")),
type: $('#NEWDEV_devType').val().replace(/'/g, ""),
vendor: encodeURIComponent($('#NEWDEV_devVendor').val().replace(/'/g, "")),
icon: encodeURIComponent($('#NEWDEV_devIcon').val()),
favorite: ($('#NEWDEV_devFavorite')[0].checked * 1),
group: encodeURIComponent($('#NEWDEV_devGroup').val().replace(/'/g, "")),
location: encodeURIComponent($('#NEWDEV_devLocation').val().replace(/'/g, "")),
comments: encodeURIComponent(encodeSpecialChars($('#NEWDEV_devComments').val())),
networknode: $('#NEWDEV_devParentMAC').val(),
networknodeport: $('#NEWDEV_devParentPort').val(),
ssid: $('#NEWDEV_devSSID').val(),
networksite: $('#NEWDEV_devSite').val(),
staticIP: ($('#NEWDEV_devStaticIP')[0].checked * 1),
scancycle: "1",
alertevents: ($('#NEWDEV_devAlertEvents')[0].checked * 1),
alertdown: ($('#NEWDEV_devAlertDown')[0].checked * 1),
skiprepeated: $('#NEWDEV_devSkipRepeated').val().split(' ')[0],
relType: $('#NEWDEV_devParentRelType').val().replace(/'/g, ""),
reqNics: ($('#NEWDEV_devReqNicsOnline')[0].checked * 1),
newdevice: ($('#NEWDEV_devIsNew')[0].checked * 1),
archived: ($('#NEWDEV_devIsArchived')[0].checked * 1),
devFirstConnection: ($('#NEWDEV_devFirstConnection').val()),
devLastConnection: ($('#NEWDEV_devLastConnection').val()),
devCustomProps: btoa(JSON.stringify(collectTableData("#NEWDEV_devCustomProps_table"))),
ip: ($('#NEWDEV_devLastIP').val()),
const apiToken = getSetting("API_TOKEN"); // dynamic token
const host = window.location.hostname;
const port = getSetting("GRAPHQL_PORT");
mac = $('#NEWDEV_devMac').val();
// Build payload for new endpoint
const payload = {
devName: $('#NEWDEV_devName').val().replace(/'/g, ""),
devOwner: $('#NEWDEV_devOwner').val().replace(/'/g, ""),
devType: $('#NEWDEV_devType').val().replace(/'/g, ""),
devVendor: $('#NEWDEV_devVendor').val().replace(/'/g, ""),
devIcon: $('#NEWDEV_devIcon').val(),
devFavorite: ($('#NEWDEV_devFavorite')[0].checked * 1),
devGroup: $('#NEWDEV_devGroup').val().replace(/'/g, ""),
devLocation: $('#NEWDEV_devLocation').val().replace(/'/g, ""),
devComments: encodeSpecialChars($('#NEWDEV_devComments').val()),
devParentMAC: $('#NEWDEV_devParentMAC').val(),
devParentPort: $('#NEWDEV_devParentPort').val(),
devParentRelType: $('#NEWDEV_devParentRelType').val().replace(/'/g, ""),
devSSID: $('#NEWDEV_devSSID').val(),
devSite: $('#NEWDEV_devSite').val(),
devStaticIP: ($('#NEWDEV_devStaticIP')[0].checked * 1),
devScan: 1,
devAlertEvents: ($('#NEWDEV_devAlertEvents')[0].checked * 1),
devAlertDown: ($('#NEWDEV_devAlertDown')[0].checked * 1),
devSkipRepeated: $('#NEWDEV_devSkipRepeated').val().split(' ')[0],
devReqNicsOnline: ($('#NEWDEV_devReqNicsOnline')[0].checked * 1),
devIsNew: ($('#NEWDEV_devIsNew')[0].checked * 1),
devIsArchived: ($('#NEWDEV_devIsArchived')[0].checked * 1),
devFirstConnection: $('#NEWDEV_devFirstConnection').val(),
devLastConnection: $('#NEWDEV_devLastConnection').val(),
devLastIP: $('#NEWDEV_devLastIP').val(),
devCustomProps: btoa(
JSON.stringify(collectTableData("#NEWDEV_devCustomProps_table"))
),
createNew: createNew
}, function(msg) {
showMessage(msg);
};
// Remove navigation prompt "Are you sure you want to leave..."
window.onbeforeunload = null;
somethingChanged = false;
// refresh API
updateApi("devices,appevents");
$.ajax({
url: "http://" + host + ":" + port + "/device/" + encodeURIComponent(mac),
type: "POST",
headers: {
"Authorization": "Bearer " + apiToken,
"Content-Type": "application/json"
},
data: JSON.stringify(payload),
success: function (resp) {
// Callback function
if (typeof refreshCallback == 'function') {
refreshCallback(direction);
if (resp && resp.success) {
showMessage("Device saved successfully");
} else {
showMessage("Device update returned an unexpected response");
}
// Remove navigation prompt
window.onbeforeunload = null;
somethingChanged = false;
// Refresh API
updateApi("devices,appevents");
// Callback
if (typeof refreshCallback === "function") {
refreshCallback(direction);
}
hideSpinner();
},
error: function (xhr) {
if (xhr.status === 403) {
showMessage("Unauthorized invalid API token");
} else {
showMessage("Failed to save device (" + xhr.status + ")");
}
hideSpinner();
}
// Everything loaded
hideSpinner();
});
}
//-----------------------------------------------------------------------------------
// Disables or enables network configuration for the root node
function toggleNetworkConfiguration(disable) {
if (disable) {
if (disable) {
// Completely disable the NEWDEV_devParentMAC <select> and NEWDEV_devParentPort
$('#NEWDEV_devParentMAC').prop('disabled', true).val("").prop('selectedIndex', 0);
$('#NEWDEV_devParentMAC').prop('disabled', true).val("").prop('selectedIndex', 0);
$('#NEWDEV_devParentMAC').empty() // Remove all options
.append('<option value="">Root Node</option>')
$('#NEWDEV_devParentPort').prop('disabled', true);
@@ -380,7 +420,7 @@
// INIT with polling for panel element visibility
// -----------------------------------------------
var deviceDetailsPageInitialized = false;
var deviceDetailsPageInitialized = false;
function initdeviceDetailsPage()
{