Added new menu jsons

This commit is contained in:
znetsixe
2025-11-13 19:39:48 +01:00
parent 5df3881375
commit f2c9134b64
13 changed files with 2851 additions and 148 deletions

View File

@@ -1,62 +1,83 @@
// asset.js
const fs = require('fs');
const path = require('path');
const { assetCategoryManager } = require('../../datasets/assetData');
class AssetMenu {
/** Define path where to find data of assets in constructor for now */
constructor(relPath = '../../datasets/assetData') {
this.baseDir = path.resolve(__dirname, relPath);
this.assetData = this._loadJSON('assetData');
constructor({ manager = assetCategoryManager, softwareType = null } = {}) {
this.manager = manager;
this.softwareType = softwareType;
this.categories = this.manager
.listCategories({ withMeta: true })
.reduce((map, meta) => {
map[meta.softwareType] = this.manager.getCategory(meta.softwareType);
return map;
}, {});
}
_loadJSON(...segments) {
const filePath = path.resolve(this.baseDir, ...segments) + '.json';
try {
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
} catch (err) {
throw new Error(`Failed to load ${filePath}: ${err.message}`);
normalizeCategory(key) {
const category = this.categories[key];
if (!category) {
return null;
}
}
/**
* ADD THIS METHOD
* Compiles all menu data from the file system into a single nested object.
* This is run once on the server to pre-load everything.
* @returns {object} A comprehensive object with all menu options.
*/
getAllMenuData() {
// load the raw JSON once
const data = this._loadJSON('assetData');
const allData = {};
data.suppliers.forEach(sup => {
allData[sup.name] = {};
sup.categories.forEach(cat => {
allData[sup.name][cat.name] = {};
cat.types.forEach(type => {
// here: store the full array of model objects, not just names
allData[sup.name][cat.name][type.name] = type.models;
});
});
});
return allData;
return {
...category,
label: category.label || category.softwareType || key,
suppliers: (category.suppliers || []).map((supplier) => ({
...supplier,
id: supplier.id || supplier.name,
types: (supplier.types || []).map((type) => ({
...type,
id: type.id || type.name,
models: (type.models || []).map((model) => ({
...model,
id: model.id || model.name,
units: model.units || []
}))
}))
}))
};
}
/**
* Convert the static initEditor function to a string that can be served to the client
* @param {string} nodeName - The name of the node type
* @returns {string} JavaScript code as a string
*/
getClientInitCode(nodeName) {
// step 1: get the two helper strings
const htmlCode = this.getHtmlInjectionCode(nodeName);
const dataCode = this.getDataInjectionCode(nodeName);
const eventsCode = this.getEventInjectionCode(nodeName);
const saveCode = this.getSaveInjectionCode(nodeName);
resolveCategoryForNode(nodeName) {
const keys = Object.keys(this.categories);
if (keys.length === 0) {
return null;
}
if (this.softwareType && this.categories[this.softwareType]) {
return this.softwareType;
}
return `
if (nodeName) {
const normalized = typeof nodeName === 'string' ? nodeName.toLowerCase() : nodeName;
if (normalized && this.categories[normalized]) {
return normalized;
}
}
return keys[0];
}
getAllMenuData(nodeName) {
const categoryKey = this.resolveCategoryForNode(nodeName);
const selectedCategories = {};
if (categoryKey && this.categories[categoryKey]) {
selectedCategories[categoryKey] = this.normalizeCategory(categoryKey);
}
return {
categories: selectedCategories,
defaultCategory: categoryKey
};
}
getClientInitCode(nodeName) {
const htmlCode = this.getHtmlInjectionCode(nodeName);
const dataCode = this.getDataInjectionCode(nodeName);
const eventsCode = this.getEventInjectionCode(nodeName);
const saveCode = this.getSaveInjectionCode(nodeName);
return `
// --- AssetMenu for ${nodeName} ---
window.EVOLV.nodes.${nodeName}.assetMenu =
window.EVOLV.nodes.${nodeName}.assetMenu || {};
@@ -66,103 +87,276 @@ getClientInitCode(nodeName) {
${eventsCode}
${saveCode}
// wire it all up when the editor loads
window.EVOLV.nodes.${nodeName}.assetMenu.initEditor = function(node) {
// ------------------ BELOW sequence is important! -------------------------------
console.log('Initializing asset properties for ${nodeName}…');
console.log('Initializing asset properties for ${nodeName}');
this.injectHtml();
// load the data and wire up events
// this will populate the fields and set up the event listeners
this.wireEvents(node);
// this will load the initial data into the fields
// this is important to ensure the fields are populated correctly
this.loadData(node);
};
`;
}
}
getDataInjectionCode(nodeName) {
getDataInjectionCode(nodeName) {
return `
// Asset Data loader for ${nodeName}
// Asset data loader for ${nodeName}
window.EVOLV.nodes.${nodeName}.assetMenu.loadData = function(node) {
const data = window.EVOLV.nodes.${nodeName}.menuData.asset;
const menuAsset = window.EVOLV.nodes.${nodeName}.menuData.asset || {};
const categories = menuAsset.categories || {};
const defaultCategory = menuAsset.defaultCategory || Object.keys(categories)[0] || null;
const elems = {
supplier: document.getElementById('node-input-supplier'),
category: document.getElementById('node-input-category'),
type: document.getElementById('node-input-assetType'),
model: document.getElementById('node-input-model'),
unit: document.getElementById('node-input-unit')
type: document.getElementById('node-input-assetType'),
model: document.getElementById('node-input-model'),
unit: document.getElementById('node-input-unit')
};
function populate(el, opts, sel) {
const old = el.value;
el.innerHTML = '<option value="">Select…</option>';
(opts||[]).forEach(o=>{
function populate(selectEl, items = [], selectedValue, mapFn, placeholderText = 'Select...') {
const previous = selectEl.value;
const mapper = typeof mapFn === 'function'
? mapFn
: (value) => ({ value, label: value });
selectEl.innerHTML = '';
const placeholder = document.createElement('option');
placeholder.value = '';
placeholder.textContent = placeholderText;
placeholder.disabled = true;
placeholder.selected = true;
selectEl.appendChild(placeholder);
items.forEach((item) => {
const option = mapper(item);
if (!option || typeof option.value === 'undefined') {
return;
}
const opt = document.createElement('option');
opt.value = o; opt.textContent = o;
el.appendChild(opt);
opt.value = option.value;
opt.textContent = option.label;
selectEl.appendChild(opt);
});
el.value = sel||"";
if(el.value!==old) el.dispatchEvent(new Event('change'));
if (selectedValue) {
selectEl.value = selectedValue;
if (!selectEl.value) {
selectEl.value = '';
}
} else {
selectEl.value = '';
}
if (selectEl.value !== previous) {
selectEl.dispatchEvent(new Event('change'));
}
}
// initial population
populate(elems.supplier, Object.keys(data), node.supplier);
const resolveCategoryKey = () => {
if (node.softwareType && categories[node.softwareType]) {
return node.softwareType;
}
if (node.category && categories[node.category]) {
return node.category;
}
return defaultCategory;
};
const categoryKey = resolveCategoryKey();
node.category = categoryKey;
const activeCategory = categoryKey ? categories[categoryKey] : null;
const suppliers = activeCategory ? activeCategory.suppliers : [];
populate(
elems.supplier,
suppliers,
node.supplier,
(supplier) => ({ value: supplier.id || supplier.name, label: supplier.name }),
suppliers.length ? 'Select...' : 'No suppliers available'
);
const activeSupplier = suppliers.find(
(supplier) => (supplier.id || supplier.name) === node.supplier
);
const types = activeSupplier ? activeSupplier.types : [];
populate(
elems.type,
types,
node.assetType,
(type) => ({ value: type.id || type.name, label: type.name }),
activeSupplier ? 'Select...' : 'Awaiting Supplier Selection'
);
const activeType = types.find(
(type) => (type.id || type.name) === node.assetType
);
const models = activeType ? activeType.models : [];
populate(
elems.model,
models,
node.model,
(model) => ({ value: model.id || model.name, label: model.name }),
activeType ? 'Select...' : 'Awaiting Type Selection'
);
const activeModel = models.find(
(model) => (model.id || model.name) === node.model
);
populate(
elems.unit,
activeModel ? activeModel.units || [] : [],
node.unit,
(unit) => ({ value: unit, label: unit }),
activeModel ? 'Select...' : activeType ? 'Awaiting Model Selection' : 'Awaiting Type Selection'
);
};
`
`;
}
getEventInjectionCode(nodeName) {
getEventInjectionCode(nodeName) {
return `
// Asset Event wiring for ${nodeName}
// Asset event wiring for ${nodeName}
window.EVOLV.nodes.${nodeName}.assetMenu.wireEvents = function(node) {
const data = window.EVOLV.nodes.${nodeName}.menuData.asset;
const menuAsset = window.EVOLV.nodes.${nodeName}.menuData.asset || {};
const categories = menuAsset.categories || {};
const defaultCategory = menuAsset.defaultCategory || Object.keys(categories)[0] || null;
const elems = {
supplier: document.getElementById('node-input-supplier'),
category: document.getElementById('node-input-category'),
type: document.getElementById('node-input-assetType'),
model: document.getElementById('node-input-model'),
unit: document.getElementById('node-input-unit')
type: document.getElementById('node-input-assetType'),
model: document.getElementById('node-input-model'),
unit: document.getElementById('node-input-unit')
};
function populate(el, opts, sel) {
const old = el.value;
el.innerHTML = '<option value="">Select…</option>';
(opts||[]).forEach(o=>{
function populate(selectEl, items = [], selectedValue, mapFn, placeholderText = 'Select...') {
const previous = selectEl.value;
const mapper = typeof mapFn === 'function'
? mapFn
: (value) => ({ value, label: value });
selectEl.innerHTML = '';
const placeholder = document.createElement('option');
placeholder.value = '';
placeholder.textContent = placeholderText;
placeholder.disabled = true;
placeholder.selected = true;
selectEl.appendChild(placeholder);
items.forEach((item) => {
const option = mapper(item);
if (!option || typeof option.value === 'undefined') {
return;
}
const opt = document.createElement('option');
opt.value = o; opt.textContent = o;
el.appendChild(opt);
opt.value = option.value;
opt.textContent = option.label;
selectEl.appendChild(opt);
});
el.value = sel||"";
if(el.value!==old) el.dispatchEvent(new Event('change'));
if (selectedValue) {
selectEl.value = selectedValue;
if (!selectEl.value) {
selectEl.value = '';
}
} else {
selectEl.value = '';
}
if (selectEl.value !== previous) {
selectEl.dispatchEvent(new Event('change'));
}
}
elems.supplier.addEventListener('change', ()=>{
populate(elems.category,
elems.supplier.value? Object.keys(data[elems.supplier.value]||{}) : [],
node.category);
const resolveCategoryKey = () => {
if (node.softwareType && categories[node.softwareType]) {
return node.softwareType;
}
if (node.category && categories[node.category]) {
return node.category;
}
return defaultCategory;
};
const getActiveCategory = () => {
const key = resolveCategoryKey();
return key ? categories[key] : null;
};
node.category = resolveCategoryKey();
elems.supplier.addEventListener('change', () => {
const category = getActiveCategory();
const supplier = category
? category.suppliers.find(
(item) => (item.id || item.name) === elems.supplier.value
)
: null;
const types = supplier ? supplier.types : [];
populate(
elems.type,
types,
node.assetType,
(type) => ({ value: type.id || type.name, label: type.name }),
supplier ? 'Select...' : 'Awaiting Supplier Selection'
);
populate(elems.model, [], '', undefined, 'Awaiting Type Selection');
populate(elems.unit, [], '', undefined, 'Awaiting Type Selection');
});
elems.category.addEventListener('change', ()=>{
const s=elems.supplier.value, c=elems.category.value;
populate(elems.type,
(s&&c)? Object.keys(data[s][c]||{}) : [],
node.assetType);
elems.type.addEventListener('change', () => {
const category = getActiveCategory();
const supplier = category
? category.suppliers.find(
(item) => (item.id || item.name) === elems.supplier.value
)
: null;
const type = supplier
? supplier.types.find(
(item) => (item.id || item.name) === elems.type.value
)
: null;
const models = type ? type.models : [];
populate(
elems.model,
models,
node.model,
(model) => ({ value: model.id || model.name, label: model.name }),
type ? 'Select...' : 'Awaiting Type Selection'
);
populate(
elems.unit,
[],
'',
undefined,
type ? 'Awaiting Model Selection' : 'Awaiting Type Selection'
);
});
elems.type.addEventListener('change', ()=>{
const s=elems.supplier.value, c=elems.category.value, t=elems.type.value;
const md = (s&&c&&t)? data[s][c][t]||[] : [];
populate(elems.model, md.map(m=>m.name), node.model);
});
elems.model.addEventListener('change', ()=>{
const s=elems.supplier.value, c=elems.category.value, t=elems.type.value, m=elems.model.value;
const md = (s&&c&&t)? data[s][c][t]||[] : [];
const entry = md.find(x=>x.name===m);
populate(elems.unit, entry? entry.units : [], node.unit);
elems.model.addEventListener('change', () => {
const category = getActiveCategory();
const supplier = category
? category.suppliers.find(
(item) => (item.id || item.name) === elems.supplier.value
)
: null;
const type = supplier
? supplier.types.find(
(item) => (item.id || item.name) === elems.type.value
)
: null;
const model = type
? type.models.find(
(item) => (item.id || item.name) === elems.model.value
)
: null;
populate(
elems.unit,
model ? model.units || [] : [],
node.unit,
(unit) => ({ value: unit, label: unit }),
model ? 'Select...' : type ? 'Awaiting Model Selection' : 'Awaiting Type Selection'
);
});
};
`
`;
}
/**
* Generate HTML template for asset fields
*/
getHtmlTemplate() {
return `
<!-- Asset Properties -->
@@ -172,10 +366,6 @@ getEventInjectionCode(nodeName) {
<label for="node-input-supplier"><i class="fa fa-industry"></i> Supplier</label>
<select id="node-input-supplier" style="width:70%;"></select>
</div>
<div class="form-row">
<label for="node-input-category"><i class="fa fa-sitemap"></i> Category</label>
<select id="node-input-category" style="width:70%;"></select>
</div>
<div class="form-row">
<label for="node-input-assetType"><i class="fa fa-puzzle-piece"></i> Type</label>
<select id="node-input-assetType" style="width:70%;"></select>
@@ -192,12 +382,11 @@ getEventInjectionCode(nodeName) {
`;
}
/**
* Get client-side HTML injection code
*/
getHtmlInjectionCode(nodeName) {
const htmlTemplate = this.getHtmlTemplate().replace(/`/g, '\\`').replace(/\$/g, '\\$');
const htmlTemplate = this.getHtmlTemplate()
.replace(/`/g, '\\`')
.replace(/\$/g, '\\$');
return `
// Asset HTML injection for ${nodeName}
window.EVOLV.nodes.${nodeName}.assetMenu.injectHtml = function() {
@@ -210,33 +399,53 @@ getEventInjectionCode(nodeName) {
`;
}
/**
* Returns the JS that injects the saveEditor function
*/
getSaveInjectionCode(nodeName) {
return `
// Asset Save injection for ${nodeName}
// Asset save handler for ${nodeName}
window.EVOLV.nodes.${nodeName}.assetMenu.saveEditor = function(node) {
console.log('Saving asset properties for ${nodeName}');
const fields = ['supplier','category','assetType','model','unit'];
const errors = [];
fields.forEach(f => {
const el = document.getElementById(\`node-input-\${f}\`);
node[f] = el ? el.value : '';
});
if (node.assetType && !node.unit) errors.push('Unit must be set when type is specified.');
if (!node.unit) errors.push('Unit is required.');
errors.forEach(e=>RED.notify(e,'error'));
// --- DEBUG: show exactly what was saved ---
const saved = fields.reduce((o,f) => { o[f] = node[f]; return o; }, {});
console.log('→ assetMenu.saveEditor result:', saved);
console.log('Saving asset properties for ${nodeName}');
const menuAsset = window.EVOLV.nodes.${nodeName}.menuData.asset || {};
const categories = menuAsset.categories || {};
const defaultCategory = menuAsset.defaultCategory || Object.keys(categories)[0] || null;
const resolveCategoryKey = () => {
if (node.softwareType && categories[node.softwareType]) {
return node.softwareType;
}
if (node.category && categories[node.category]) {
return node.category;
}
return defaultCategory || '';
};
return errors.length===0;
node.category = resolveCategoryKey();
const fields = ['supplier', 'assetType', 'model', 'unit'];
const errors = [];
fields.forEach((field) => {
const el = document.getElementById(\`node-input-\${field}\`);
node[field] = el ? el.value : '';
});
if (node.assetType && !node.unit) {
errors.push('Unit must be set when a type is specified.');
}
if (!node.unit) {
errors.push('Unit is required.');
}
errors.forEach((msg) => RED.notify(msg, 'error'));
const saved = fields.reduce((acc, field) => {
acc[field] = node[field];
return acc;
}, {});
console.log('[AssetMenu] save result:', saved);
return errors.length === 0;
};
`;
}
}
module.exports = AssetMenu;