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

@@ -306,53 +306,93 @@
showSpinner(); showSpinner();
// Update data to server using POST const apiToken = getSetting("API_TOKEN"); // dynamic token
$.post('php/server/devices.php?action=setDeviceData', { const host = window.location.hostname;
mac: $('#NEWDEV_devMac').val(), const port = getSetting("GRAPHQL_PORT");
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()),
createNew: createNew
}, function(msg) {
showMessage(msg);
// Remove navigation prompt "Are you sure you want to leave..." 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
};
$.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) {
if (resp && resp.success) {
showMessage("Device saved successfully");
} else {
showMessage("Device update returned an unexpected response");
}
// Remove navigation prompt
window.onbeforeunload = null; window.onbeforeunload = null;
somethingChanged = false; somethingChanged = false;
// refresh API // Refresh API
updateApi("devices,appevents"); updateApi("devices,appevents");
// Callback function // Callback
if (typeof refreshCallback == 'function') { if (typeof refreshCallback === "function") {
refreshCallback(direction); refreshCallback(direction);
} }
// Everything loaded
hideSpinner(); hideSpinner();
},
error: function (xhr) {
if (xhr.status === 403) {
showMessage("Unauthorized invalid API token");
} else {
showMessage("Failed to save device (" + xhr.status + ")");
}
hideSpinner();
}
}); });
} }

View File

@@ -32,7 +32,6 @@
switch ($action) { switch ($action) {
// check server/api_server/api_server_start.py for equivalents // check server/api_server/api_server_start.py for equivalents
case 'getServerDeviceData': getServerDeviceData(); break; // equivalent: get_device_data case 'getServerDeviceData': getServerDeviceData(); break; // equivalent: get_device_data
case 'setDeviceData': setDeviceData(); break; // equivalent: set_device_data
case 'deleteDevice': deleteDevice(); break; // equivalent: delete_device(mac) case 'deleteDevice': deleteDevice(); break; // equivalent: delete_device(mac)
case 'deleteAllWithEmptyMACs': deleteAllWithEmptyMACs(); break; // equivalent: delete_all_with_empty_macs case 'deleteAllWithEmptyMACs': deleteAllWithEmptyMACs(); break; // equivalent: delete_all_with_empty_macs

View File

@@ -345,8 +345,7 @@ function formatDataSize(bytes) {
function loadInterfaces() { function loadInterfaces() {
const apiToken = getSetting("API_TOKEN"); // replace with dynamic token if available const apiToken = getSetting("API_TOKEN");
const host = window.location.hostname; const host = window.location.hostname;
const port = getSetting("GRAPHQL_PORT"); const port = getSetting("GRAPHQL_PORT");

View File

@@ -500,6 +500,7 @@ class DeviceInstance:
def setDeviceData(self, mac, data): def setDeviceData(self, mac, data):
"""Update or create a device.""" """Update or create a device."""
try:
if data.get("createNew", False): if data.get("createNew", False):
sql = """ sql = """
INSERT INTO Devices ( INSERT INTO Devices (
@@ -590,6 +591,21 @@ class DeviceInstance:
conn.commit() conn.commit()
conn.close() conn.close()
return {"success": True} return {"success": True}
except Exception as e:
if conn:
conn.rollback()
# Optional: your existing logger
mylog("none", f"[DeviceInstance] setDeviceData({mac}) failed: {e}")
return {
"success": False,
"error": str(e)
}
finally:
if conn:
conn.close()
def deleteDeviceByMAC(self, mac): def deleteDeviceByMAC(self, mac):
"""Delete a device by MAC.""" """Delete a device by MAC."""