forked from UKSOURCE/cms.lams
feat(cms): enhance content editors with dynamic UI configs and validation
Implement a more flexible, configuration-driven approach for CMS editors across accreditation, admissions, and partnerships modules. - Move UI labels, help texts, and field limits from hardcoded views to `editorUi` configurations in config files. - Add server-side and client-side validation to prevent duplicate category tabs in accreditation and partnerships editors. - Refactor partnership and admission views to dynamically render tabs and fields based on the provided configuration. - Update field length constraints and default values across multiple content editors to better align with frontend requirements. - Improve the admissions calculator editor with dynamic field configurations and default value fallbacks.
This commit is contained in:
@@ -9,6 +9,34 @@ const controller = createPageContentController({
|
||||
modelName: "AccreditationPage",
|
||||
auditAction: AUDIT_ACTIONS.UPDATE_ACCREDITATION,
|
||||
editorConfig: accreditationConfig,
|
||||
preparePayload(rawPayload) {
|
||||
const payload = JSON.parse(JSON.stringify(rawPayload || {}));
|
||||
const tabs = Array.isArray(payload?.grid?.tabs) ? payload.grid.tabs : [];
|
||||
const seenTabs = new Set();
|
||||
const duplicateTabs = [];
|
||||
|
||||
tabs.forEach((tab) => {
|
||||
const normalizedTab = String(tab || "").trim().toLowerCase();
|
||||
if (!normalizedTab) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (seenTabs.has(normalizedTab)) {
|
||||
duplicateTabs.push(String(tab || "").trim());
|
||||
return;
|
||||
}
|
||||
|
||||
seenTabs.add(normalizedTab);
|
||||
});
|
||||
|
||||
if (duplicateTabs.length > 0) {
|
||||
throw new Error(
|
||||
`Category tab already exists: ${duplicateTabs[0]}. Please use unique tab names.`,
|
||||
);
|
||||
}
|
||||
|
||||
return payload;
|
||||
},
|
||||
});
|
||||
|
||||
controller.index = async function index(req, res) {
|
||||
|
||||
@@ -9,6 +9,38 @@ const diffObject = require("../audit/diffObject");
|
||||
const { ensureUniqueIds } = require("../utils/contentEditorIds");
|
||||
const { ICON_OPTIONS } = require("../utils/contentEditors/sharedFields");
|
||||
|
||||
function getAdmissionsEditorUi() {
|
||||
return admissionsConfig.editorUi || {};
|
||||
}
|
||||
|
||||
function getDefaultCalculatorOptionValues() {
|
||||
return getAdmissionsEditorUi().calculator?.defaultOption || {};
|
||||
}
|
||||
|
||||
function getCalculatorOptionFieldConfig(fieldKey) {
|
||||
const calculatorTab = (admissionsConfig.tabs || []).find((tab) => tab.key === "calculator");
|
||||
const calculatorFields = calculatorTab?.schema?.fields || [];
|
||||
const optionsField = calculatorFields.find((field) => field.key === "options");
|
||||
const optionItemFields = optionsField?.itemSchema?.fields || [];
|
||||
|
||||
return optionItemFields.find((field) => field.key === fieldKey) || {};
|
||||
}
|
||||
|
||||
function hasDuplicateCalculatorOptionLabel(options, currentOptionId, nextLabel) {
|
||||
const normalizedLabel = String(nextLabel || "").trim().toLowerCase();
|
||||
if (!normalizedLabel) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (options || []).some((option) => {
|
||||
if (String(option?.id || "") === String(currentOptionId || "")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return String(option?.label || "").trim().toLowerCase() === normalizedLabel;
|
||||
});
|
||||
}
|
||||
|
||||
function normalizePositiveAmount(value, fallback = "1") {
|
||||
const match = String(value || "").match(/\d[\d,]*/);
|
||||
const numericValue = Number((match ? match[0] : "").replace(/,/g, ""));
|
||||
@@ -17,18 +49,25 @@ function normalizePositiveAmount(value, fallback = "1") {
|
||||
|
||||
function normalizeCalculatorOption(option, index, calculator) {
|
||||
const source = typeof option === "string" ? { label: option } : { ...(option || {}) };
|
||||
const defaultOption = getDefaultCalculatorOptionValues();
|
||||
const labelMaxLength = getCalculatorOptionFieldConfig("label").maxLength || 12;
|
||||
|
||||
return {
|
||||
...source,
|
||||
label: String(source.label || source.title || `Option ${index + 1}`).slice(0, 12),
|
||||
paceLabel: String(source.paceLabel || calculator.paceLabel || "Target Pace"),
|
||||
minPaceLabel: String(source.minPaceLabel || calculator.minPaceLabel || "Relaxed"),
|
||||
maxPaceLabel: String(source.maxPaceLabel || calculator.maxPaceLabel || "Accelerated"),
|
||||
resultLabel: String(source.resultLabel || calculator.resultLabel || "Estimated Monthly Payment"),
|
||||
monthlyAmount: normalizePositiveAmount(source.monthlyAmount || calculator.monthlyAmount || "299", "299"),
|
||||
monthlySuffix: String(source.monthlySuffix || calculator.monthlySuffix || "/mo"),
|
||||
noteIcon: String(source.noteIcon || calculator.noteIcon || "fa-bolt"),
|
||||
note: String(source.note || calculator.note || ""),
|
||||
label: String(source.label || source.title || `Option ${index + 1}`).slice(0, labelMaxLength),
|
||||
paceLabel: String(source.paceLabel || calculator.paceLabel || defaultOption.paceLabel || "Target Pace"),
|
||||
minPaceLabel: String(source.minPaceLabel || calculator.minPaceLabel || defaultOption.minPaceLabel || "Relaxed"),
|
||||
maxPaceLabel: String(source.maxPaceLabel || calculator.maxPaceLabel || defaultOption.maxPaceLabel || "Accelerated"),
|
||||
resultLabel: String(
|
||||
source.resultLabel || calculator.resultLabel || defaultOption.resultLabel || "Estimated Monthly Payment",
|
||||
),
|
||||
monthlyAmount: normalizePositiveAmount(
|
||||
source.monthlyAmount || calculator.monthlyAmount || defaultOption.monthlyAmount || "299",
|
||||
String(defaultOption.monthlyAmount || "299"),
|
||||
),
|
||||
monthlySuffix: String(source.monthlySuffix || calculator.monthlySuffix || defaultOption.monthlySuffix || "/mo"),
|
||||
noteIcon: String(source.noteIcon || calculator.noteIcon || defaultOption.noteIcon || "fa-bolt"),
|
||||
note: String(source.note || calculator.note || defaultOption.note || ""),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -174,12 +213,41 @@ controller.editCalculatorOption = async function editCalculatorOption(req, res)
|
||||
const frontendUrl = process.env.FRONTEND_URL || "http://localhost:3000";
|
||||
const backendUrl =
|
||||
process.env.BACKEND_URL ?? `${req.protocol}://${req.get("host")}`;
|
||||
const fieldKeys = [
|
||||
"label",
|
||||
"paceLabel",
|
||||
"minPaceLabel",
|
||||
"maxPaceLabel",
|
||||
"resultLabel",
|
||||
"monthlyAmount",
|
||||
"monthlySuffix",
|
||||
"noteIcon",
|
||||
"note",
|
||||
];
|
||||
const fieldConfig = fieldKeys.reduce((acc, key) => {
|
||||
acc[key] = getCalculatorOptionFieldConfig(key);
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
return res.render("admin/admissions/calculator-option", {
|
||||
layout: "layouts/main",
|
||||
title: `Edit ${option.label}`,
|
||||
subtitle: "Update the calculator option details",
|
||||
option,
|
||||
existingOptionLabels: data.calculator.options
|
||||
.filter((item) => item.id !== optionId)
|
||||
.map((item) => item.label)
|
||||
.filter(Boolean),
|
||||
fieldLimits: {
|
||||
label: fieldConfig.label.maxLength || 12,
|
||||
paceLabel: fieldConfig.paceLabel.maxLength || 20,
|
||||
minPaceLabel: fieldConfig.minPaceLabel.maxLength || 7,
|
||||
maxPaceLabel: fieldConfig.maxPaceLabel.maxLength || 7,
|
||||
resultLabel: fieldConfig.resultLabel.maxLength || 40,
|
||||
monthlySuffix: fieldConfig.monthlySuffix.maxLength || 10,
|
||||
note: fieldConfig.note.maxLength || 60,
|
||||
},
|
||||
fieldConfig,
|
||||
iconOptions: ICON_OPTIONS,
|
||||
editorConfig: admissionsConfig,
|
||||
previewUrl: `${frontendUrl}${admissionsConfig.previewPath}`,
|
||||
@@ -207,9 +275,15 @@ controller.updateCalculatorOption = async function updateCalculatorOption(req, r
|
||||
return req.session.save(() => res.redirect("/admin/admissions?tab=calculator"));
|
||||
}
|
||||
|
||||
const nextLabel = String(req.body.label || "").trim().slice(0, getCalculatorOptionFieldConfig("label").maxLength || 12);
|
||||
if (hasDuplicateCalculatorOptionLabel(payload.calculator.options, optionId, nextLabel)) {
|
||||
req.flash("error_msg", `Option label "${nextLabel}" already exists. Please use a unique label.`);
|
||||
return req.session.save(() => res.redirect(`/admin/admissions/calculator/${optionId}`));
|
||||
}
|
||||
|
||||
payload.calculator.options[optionIndex] = {
|
||||
...payload.calculator.options[optionIndex],
|
||||
label: String(req.body.label || "").trim().slice(0, 12),
|
||||
label: nextLabel,
|
||||
paceLabel: String(req.body.paceLabel || "").trim(),
|
||||
minPaceLabel: String(req.body.minPaceLabel || "").trim(),
|
||||
maxPaceLabel: String(req.body.maxPaceLabel || "").trim(),
|
||||
|
||||
@@ -2,9 +2,71 @@ const PartnershipsPage = require("../models/partnerships");
|
||||
const AUDIT_ACTIONS = require("../constants/auditAction");
|
||||
const partnershipsConfig = require("../utils/contentEditors/partnershipsConfig");
|
||||
const createPageContentController = require("./_createPageContentController");
|
||||
const createRenderSingletonPageView = require("./_renderSingletonPageView");
|
||||
const { ensureUniqueIds } = require("../utils/contentEditorIds");
|
||||
|
||||
function getTabConfig(tabKey) {
|
||||
return (partnershipsConfig.tabs || []).find((tab) => tab.key === tabKey) || {};
|
||||
}
|
||||
|
||||
function getObjectField(tabKey, fieldKey) {
|
||||
const fields = getTabConfig(tabKey)?.schema?.fields || [];
|
||||
return fields.find((field) => field.key === fieldKey) || {};
|
||||
}
|
||||
|
||||
function getArrayItemField(tabKey, arrayKey, fieldKey) {
|
||||
const arrayField = getObjectField(tabKey, arrayKey);
|
||||
const itemFields = arrayField?.itemSchema?.fields || [];
|
||||
return itemFields.find((field) => field.key === fieldKey) || {};
|
||||
}
|
||||
|
||||
function getPartnershipsEditorUi() {
|
||||
return {
|
||||
hero: {
|
||||
badge: getObjectField("hero", "badge"),
|
||||
title: getObjectField("hero", "title"),
|
||||
description: getObjectField("hero", "description"),
|
||||
linkLabel: getObjectField("hero", "linkLabel"),
|
||||
image: getObjectField("hero", "image"),
|
||||
imageAlt: getObjectField("hero", "imageAlt"),
|
||||
},
|
||||
directory: {
|
||||
heading: getObjectField("directory", "heading"),
|
||||
description: getObjectField("directory", "description"),
|
||||
tabs: getObjectField("directory", "tabs"),
|
||||
partnerFields: {
|
||||
name: getArrayItemField("directory", "partners", "name"),
|
||||
category: getArrayItemField("directory", "partners", "category"),
|
||||
summary: getArrayItemField("directory", "partners", "summary"),
|
||||
logo: getArrayItemField("directory", "partners", "logo"),
|
||||
logoAlt: getArrayItemField("directory", "partners", "logoAlt"),
|
||||
about: getArrayItemField("directory", "partners", "about"),
|
||||
collabType: getArrayItemField("directory", "partners", "collabType"),
|
||||
benefits: getArrayItemField("directory", "partners", "benefits"),
|
||||
},
|
||||
tabsFrontendHint: partnershipsConfig.editorUi?.directory?.tabsFrontendHint || "",
|
||||
partnersHelpText: partnershipsConfig.editorUi?.directory?.partnersHelpText || "",
|
||||
},
|
||||
cta: {
|
||||
heading: getObjectField("cta", "heading"),
|
||||
description: getObjectField("cta", "description"),
|
||||
buttonLabel: getObjectField("cta", "buttonLabel"),
|
||||
},
|
||||
inquiryForm: {
|
||||
title: getObjectField("inquiryForm", "title"),
|
||||
fields: getObjectField("inquiryForm", "fields"),
|
||||
fieldFields: {
|
||||
label: getArrayItemField("inquiryForm", "fields", "label"),
|
||||
placeholder: getArrayItemField("inquiryForm", "fields", "placeholder"),
|
||||
type: getArrayItemField("inquiryForm", "fields", "type"),
|
||||
width: getArrayItemField("inquiryForm", "fields", "width"),
|
||||
options: getArrayItemField("inquiryForm", "fields", "options"),
|
||||
required: getArrayItemField("inquiryForm", "fields", "required"),
|
||||
},
|
||||
fieldsHelpText: partnershipsConfig.editorUi?.inquiryForm?.fieldsHelpText || "",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function toInquiryField(id, field, type, width) {
|
||||
return {
|
||||
id,
|
||||
@@ -53,9 +115,34 @@ function prepareInquiryPayload(payload) {
|
||||
const fields = Array.isArray(normalized?.inquiryForm?.fields)
|
||||
? normalized.inquiryForm.fields
|
||||
: [];
|
||||
const tabs = Array.isArray(normalized?.directory?.tabs)
|
||||
? normalized.directory.tabs
|
||||
: [];
|
||||
const partners = Array.isArray(normalized?.directory?.partners)
|
||||
? normalized.directory.partners
|
||||
: [];
|
||||
const seenTabs = new Set();
|
||||
const duplicateTabs = [];
|
||||
|
||||
tabs.forEach((tab) => {
|
||||
const normalizedTab = String(tab || "").trim().toLowerCase();
|
||||
if (!normalizedTab) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (seenTabs.has(normalizedTab)) {
|
||||
duplicateTabs.push(String(tab || "").trim());
|
||||
return;
|
||||
}
|
||||
|
||||
seenTabs.add(normalizedTab);
|
||||
});
|
||||
|
||||
if (duplicateTabs.length > 0) {
|
||||
throw new Error(
|
||||
`Category tab already exists: ${duplicateTabs[0]}. Please use unique tab names.`,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
...normalized,
|
||||
@@ -100,12 +187,32 @@ const controller = createPageContentController({
|
||||
|
||||
controller.index = async function index(req, res) {
|
||||
try {
|
||||
return await createRenderSingletonPageView({
|
||||
model: PartnershipsPage,
|
||||
const doc = await PartnershipsPage.getSingle();
|
||||
const rawData = doc.toObject();
|
||||
const data = normalizeInquiryForm(rawData);
|
||||
const frontendUrl = process.env.FRONTEND_URL || "http://localhost:3000";
|
||||
const backendUrl =
|
||||
process.env.BACKEND_URL ?? `${req.protocol}://${req.get("host")}`;
|
||||
const defaultTab = partnershipsConfig.tabs[0]?.key;
|
||||
const requestedTab = req.query.tab;
|
||||
const activeTab = partnershipsConfig.tabs.some((tab) => tab.key === requestedTab)
|
||||
? requestedTab
|
||||
: defaultTab;
|
||||
|
||||
return res.render("admin/partnerships/index", {
|
||||
layout: "layouts/main",
|
||||
title: partnershipsConfig.title,
|
||||
subtitle: partnershipsConfig.subtitle,
|
||||
data,
|
||||
editorConfig: partnershipsConfig,
|
||||
view: "admin/partnerships/index",
|
||||
normalizeForEditor: normalizeInquiryForm,
|
||||
})(req, res);
|
||||
editorUi: getPartnershipsEditorUi(),
|
||||
activeTab,
|
||||
frontendUrl,
|
||||
backendUrl,
|
||||
previewUrl: `${frontendUrl}${partnershipsConfig.previewPath}`,
|
||||
currentPath: req.path,
|
||||
user: req.session.user,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("partnerships index error:", error);
|
||||
req.flash("error_msg", "Error loading Partnerships Management");
|
||||
|
||||
Reference in New Issue
Block a user