forked from UKSOURCE/cms.lams
feat(cms): enhance content editors and implement automatic ID generation
Improve the CMS administration interface across multiple pages (Accreditation, Admissions, History, Partnerships, and Policies) with a focus on usability and data integrity. Key changes include: - Implement `ensureUniqueIds` utility to automatically generate and maintain unique slugs for content items, removing the need for manual ID entry in the UI. - Refactor the Admissions calculator to support detailed per-option editing via a new dedicated view and routes. - Replace basic datalists with a custom, searchable icon combobox component for better visual selection. - Update `_renderSingletonPageView` to handle active tab persistence via query parameters. - Streamline editor configurations by removing redundant fields and improving help text. - Enhance the Admissions "Key Dates" editor with a dynamic table interface for managing columns and rows. - Normalize data payloads in controllers to ensure consistent API responses and internal linking.
This commit is contained in:
@@ -11,6 +11,11 @@ function createRenderSingletonPageView({
|
||||
const frontendUrl = process.env.FRONTEND_URL || "http://localhost:3000";
|
||||
const backendUrl =
|
||||
process.env.BACKEND_URL ?? `${req.protocol}://${req.get("host")}`;
|
||||
const defaultTab = editorConfig.tabs[0]?.key;
|
||||
const requestedTab = req.query.tab;
|
||||
const activeTab = editorConfig.tabs.some((tab) => tab.key === requestedTab)
|
||||
? requestedTab
|
||||
: defaultTab;
|
||||
|
||||
return res.render(view, {
|
||||
layout: "layouts/main",
|
||||
@@ -18,7 +23,7 @@ function createRenderSingletonPageView({
|
||||
subtitle: editorConfig.subtitle,
|
||||
data,
|
||||
editorConfig,
|
||||
activeTab: req.query.tab || editorConfig.tabs[0].key,
|
||||
activeTab,
|
||||
frontendUrl,
|
||||
backendUrl,
|
||||
previewUrl: `${frontendUrl}${editorConfig.previewPath}`,
|
||||
|
||||
@@ -3,12 +3,101 @@ const AUDIT_ACTIONS = require("../constants/auditAction");
|
||||
const admissionsConfig = require("../utils/contentEditors/admissionsConfig");
|
||||
const createPageContentController = require("./_createPageContentController");
|
||||
const createRenderSingletonPageView = require("./_renderSingletonPageView");
|
||||
const jsonHelper = require("../utils/jsonHelper");
|
||||
const writeAuditLog = require("../audit/writeAuditLog");
|
||||
const diffObject = require("../audit/diffObject");
|
||||
const { ensureUniqueIds } = require("../utils/contentEditorIds");
|
||||
const { ICON_OPTIONS } = require("../utils/contentEditors/sharedFields");
|
||||
|
||||
function normalizePositiveAmount(value, fallback = "1") {
|
||||
const match = String(value || "").match(/\d[\d,]*/);
|
||||
const numericValue = Number((match ? match[0] : "").replace(/,/g, ""));
|
||||
return numericValue > 0 ? String(numericValue) : fallback;
|
||||
}
|
||||
|
||||
function normalizeCalculatorOption(option, index, calculator) {
|
||||
const source = typeof option === "string" ? { label: option } : { ...(option || {}) };
|
||||
|
||||
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 || ""),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeCalculator(calculator) {
|
||||
const nextCalculator = { ...(calculator || {}) };
|
||||
const legacyOptions = Array.isArray(nextCalculator.modelOptions) ? nextCalculator.modelOptions : [];
|
||||
const rawOptions = Array.isArray(nextCalculator.options) && nextCalculator.options.length
|
||||
? nextCalculator.options
|
||||
: legacyOptions;
|
||||
|
||||
nextCalculator.title = String(nextCalculator.title || "");
|
||||
nextCalculator.description = String(nextCalculator.description || "");
|
||||
nextCalculator.cta = {
|
||||
label: String(nextCalculator?.cta?.label || "").slice(0, 15),
|
||||
href: String(nextCalculator?.cta?.href || ""),
|
||||
};
|
||||
|
||||
nextCalculator.options = ensureUniqueIds(
|
||||
rawOptions.slice(0, 3).map((option, index) => normalizeCalculatorOption(option, index, nextCalculator)),
|
||||
(item) => item.id,
|
||||
(item) => item.label,
|
||||
"calculator-option",
|
||||
);
|
||||
|
||||
delete nextCalculator.modelOptions;
|
||||
delete nextCalculator.paceLabel;
|
||||
delete nextCalculator.minPaceLabel;
|
||||
delete nextCalculator.maxPaceLabel;
|
||||
delete nextCalculator.resultLabel;
|
||||
delete nextCalculator.monthlyAmount;
|
||||
delete nextCalculator.monthlySuffix;
|
||||
delete nextCalculator.noteIcon;
|
||||
delete nextCalculator.note;
|
||||
|
||||
return nextCalculator;
|
||||
}
|
||||
|
||||
function normalizeAdmissionsPayload(rawPayload) {
|
||||
const payload = JSON.parse(JSON.stringify(rawPayload || {}));
|
||||
|
||||
payload.process = {
|
||||
...(payload.process || {}),
|
||||
id: "admissions-process",
|
||||
};
|
||||
payload.eligibility = {
|
||||
...(payload.eligibility || {}),
|
||||
id: "eligibility",
|
||||
};
|
||||
payload.tuition = {
|
||||
...(payload.tuition || {}),
|
||||
id: "tuition-breakdown",
|
||||
};
|
||||
payload.keyDates = {
|
||||
...(payload.keyDates || {}),
|
||||
id: "key-dates",
|
||||
};
|
||||
payload.calculator = normalizeCalculator(payload.calculator);
|
||||
|
||||
return payload;
|
||||
}
|
||||
|
||||
const controller = createPageContentController({
|
||||
model: AdmissionsPage,
|
||||
modelName: "AdmissionsPage",
|
||||
auditAction: AUDIT_ACTIONS.UPDATE_ADMISSIONS,
|
||||
editorConfig: admissionsConfig,
|
||||
preparePayload: normalizeAdmissionsPayload,
|
||||
normalizeForEditor: normalizeAdmissionsPayload,
|
||||
normalizeForApi: normalizeAdmissionsPayload,
|
||||
});
|
||||
|
||||
controller.index = async function index(req, res) {
|
||||
@@ -17,6 +106,7 @@ controller.index = async function index(req, res) {
|
||||
model: AdmissionsPage,
|
||||
editorConfig: admissionsConfig,
|
||||
view: "admin/admissions/index",
|
||||
normalizeForEditor: normalizeAdmissionsPayload,
|
||||
})(req, res);
|
||||
} catch (error) {
|
||||
console.error("admissions index error:", error);
|
||||
@@ -25,4 +115,100 @@ controller.index = async function index(req, res) {
|
||||
}
|
||||
};
|
||||
|
||||
controller.editCalculatorOption = async function editCalculatorOption(req, res) {
|
||||
try {
|
||||
const optionId = String(req.params.optionId || "");
|
||||
const doc = await AdmissionsPage.getSingle();
|
||||
const data = normalizeAdmissionsPayload(doc.toObject());
|
||||
const option = data.calculator.options.find((item) => item.id === optionId);
|
||||
|
||||
if (!option) {
|
||||
req.flash("error_msg", "Calculator option not found");
|
||||
return req.session.save(() => res.redirect("/admin/admissions?tab=calculator"));
|
||||
}
|
||||
|
||||
const frontendUrl = process.env.FRONTEND_URL || "http://localhost:3000";
|
||||
const backendUrl =
|
||||
process.env.BACKEND_URL ?? `${req.protocol}://${req.get("host")}`;
|
||||
|
||||
return res.render("admin/admissions/calculator-option", {
|
||||
layout: "layouts/main",
|
||||
title: `Edit ${option.label}`,
|
||||
subtitle: "Update the calculator option details",
|
||||
option,
|
||||
iconOptions: ICON_OPTIONS,
|
||||
editorConfig: admissionsConfig,
|
||||
previewUrl: `${frontendUrl}${admissionsConfig.previewPath}`,
|
||||
currentPath: req.path,
|
||||
backendUrl,
|
||||
user: req.session.user,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("admissions calculator option index error:", error);
|
||||
req.flash("error_msg", "Error loading calculator option");
|
||||
return req.session.save(() => res.redirect("/admin/admissions?tab=calculator"));
|
||||
}
|
||||
};
|
||||
|
||||
controller.updateCalculatorOption = async function updateCalculatorOption(req, res) {
|
||||
try {
|
||||
const optionId = String(req.params.optionId || "");
|
||||
const doc = await AdmissionsPage.getSingle();
|
||||
const beforeData = JSON.parse(JSON.stringify(doc.toObject()));
|
||||
const payload = normalizeAdmissionsPayload(beforeData);
|
||||
const optionIndex = payload.calculator.options.findIndex((item) => item.id === optionId);
|
||||
|
||||
if (optionIndex === -1) {
|
||||
req.flash("error_msg", "Calculator option not found");
|
||||
return req.session.save(() => res.redirect("/admin/admissions?tab=calculator"));
|
||||
}
|
||||
|
||||
payload.calculator.options[optionIndex] = {
|
||||
...payload.calculator.options[optionIndex],
|
||||
label: String(req.body.label || "").trim().slice(0, 12),
|
||||
paceLabel: String(req.body.paceLabel || "").trim(),
|
||||
minPaceLabel: String(req.body.minPaceLabel || "").trim(),
|
||||
maxPaceLabel: String(req.body.maxPaceLabel || "").trim(),
|
||||
resultLabel: String(req.body.resultLabel || "").trim(),
|
||||
monthlyAmount: normalizePositiveAmount(req.body.monthlyAmount, payload.calculator.options[optionIndex].monthlyAmount || "1"),
|
||||
monthlySuffix: String(req.body.monthlySuffix || "").trim(),
|
||||
noteIcon: String(req.body.noteIcon || "").trim(),
|
||||
note: String(req.body.note || "").trim(),
|
||||
};
|
||||
|
||||
const normalizedPayload = normalizeAdmissionsPayload(payload);
|
||||
doc.set(normalizedPayload);
|
||||
Object.keys(normalizedPayload).forEach((key) => doc.markModified(key));
|
||||
await doc.save();
|
||||
|
||||
const afterData = JSON.parse(JSON.stringify(doc.toObject()));
|
||||
const changes = diffObject(beforeData, afterData);
|
||||
|
||||
if (changes.length > 0) {
|
||||
await writeAuditLog({
|
||||
model: "AdmissionsPage",
|
||||
documentId: doc._id,
|
||||
action: AUDIT_ACTIONS.UPDATE_ADMISSIONS,
|
||||
before: beforeData,
|
||||
after: afterData,
|
||||
changes,
|
||||
req,
|
||||
});
|
||||
}
|
||||
|
||||
const finalData = await AdmissionsPage
|
||||
.findOne()
|
||||
.select("-_id -__v -createdAt -updatedAt")
|
||||
.lean();
|
||||
jsonHelper.writeJsonFile(admissionsConfig.dataFile, normalizeAdmissionsPayload(finalData));
|
||||
|
||||
req.flash("success_msg", "Calculator option updated successfully");
|
||||
return req.session.save(() => res.redirect(`/admin/admissions/calculator/${optionId}`));
|
||||
} catch (error) {
|
||||
console.error("admissions calculator option update error:", error);
|
||||
req.flash("error_msg", `Error updating calculator option: ${error.message}`);
|
||||
return req.session.save(() => res.redirect(`/admin/admissions/calculator/${req.params.optionId}`));
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = controller;
|
||||
|
||||
@@ -3,12 +3,109 @@ const AUDIT_ACTIONS = require("../constants/auditAction");
|
||||
const historyConfig = require("../utils/contentEditors/historyConfig");
|
||||
const createPageContentController = require("./_createPageContentController");
|
||||
const createRenderSingletonPageView = require("./_renderSingletonPageView");
|
||||
const { ensureUniqueIds } = require("../utils/contentEditorIds");
|
||||
|
||||
function getFrontendUrl(req) {
|
||||
return (process.env.FRONTEND_URL || "http://localhost:3000").replace(/\/$/, "");
|
||||
}
|
||||
|
||||
function normalizeInternalHistoryHref(rawHref, req) {
|
||||
const href = String(rawHref || "").trim();
|
||||
|
||||
if (!href) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (href.startsWith("#")) {
|
||||
return href;
|
||||
}
|
||||
|
||||
if (href.startsWith("/")) {
|
||||
return href;
|
||||
}
|
||||
|
||||
const frontendUrl = getFrontendUrl(req);
|
||||
|
||||
try {
|
||||
const url = new URL(href);
|
||||
const frontendOrigin = new URL(frontendUrl).origin;
|
||||
|
||||
if (url.origin !== frontendOrigin) {
|
||||
throw new Error("Highlight link only supports internal anchors or frontend paths.");
|
||||
}
|
||||
|
||||
return `${url.pathname}${url.search}${url.hash}` || "/";
|
||||
} catch (error) {
|
||||
if (href.startsWith("http://") || href.startsWith("https://")) {
|
||||
throw new Error("Highlight link only supports internal anchors or frontend paths.");
|
||||
}
|
||||
|
||||
return href.startsWith("?") ? `/about/history${href}` : `/${href.replace(/^\/+/, "")}`;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeHistoryForApi(rawData, req) {
|
||||
const data = JSON.parse(JSON.stringify(rawData || {}));
|
||||
const href = data?.highlight?.href;
|
||||
const frontendUrl = getFrontendUrl(req);
|
||||
const backendUrl = `${req.protocol}://${req.get("host")}`.replace(/\/$/, "");
|
||||
|
||||
if (!href || href.startsWith("#")) {
|
||||
return data;
|
||||
}
|
||||
|
||||
if (/^https?:\/\//i.test(href)) {
|
||||
try {
|
||||
const url = new URL(href);
|
||||
const frontendOrigin = new URL(frontendUrl).origin;
|
||||
const backendOrigin = new URL(backendUrl).origin;
|
||||
|
||||
if (url.origin === frontendOrigin) {
|
||||
data.highlight.href = `${frontendUrl}${url.pathname}${url.search}${url.hash}`;
|
||||
return data;
|
||||
}
|
||||
|
||||
if (url.origin === backendOrigin) {
|
||||
data.highlight.href = `${frontendUrl}/about/history${url.hash || ""}`;
|
||||
return data;
|
||||
}
|
||||
} catch {
|
||||
data.highlight.href = `${frontendUrl}/about/history`;
|
||||
return data;
|
||||
}
|
||||
|
||||
data.highlight.href = `${frontendUrl}/about/history`;
|
||||
return data;
|
||||
}
|
||||
|
||||
data.highlight.href = `${frontendUrl}${href.startsWith("/") ? href : `/${href}`}`;
|
||||
return data;
|
||||
}
|
||||
|
||||
const controller = createPageContentController({
|
||||
model: HistoryPage,
|
||||
modelName: "HistoryPage",
|
||||
auditAction: AUDIT_ACTIONS.UPDATE_HISTORY,
|
||||
editorConfig: historyConfig,
|
||||
preparePayload(rawPayload, { req }) {
|
||||
const payload = JSON.parse(JSON.stringify(rawPayload || {}));
|
||||
|
||||
if (payload.highlight) {
|
||||
payload.highlight.href = normalizeInternalHistoryHref(payload.highlight.href, req);
|
||||
}
|
||||
|
||||
if (payload.timeline && Array.isArray(payload.timeline.items)) {
|
||||
payload.timeline.items = ensureUniqueIds(
|
||||
payload.timeline.items,
|
||||
(item) => item.id,
|
||||
(item, index) => item.title || item.year || `milestone-${index + 1}`,
|
||||
"milestone",
|
||||
);
|
||||
}
|
||||
|
||||
return payload;
|
||||
},
|
||||
normalizeForApi: normalizeHistoryForApi,
|
||||
});
|
||||
|
||||
controller.index = async function index(req, res) {
|
||||
|
||||
@@ -3,6 +3,7 @@ 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 toInquiryField(id, field, type, width) {
|
||||
return {
|
||||
@@ -52,17 +53,30 @@ function prepareInquiryPayload(payload) {
|
||||
const fields = Array.isArray(normalized?.inquiryForm?.fields)
|
||||
? normalized.inquiryForm.fields
|
||||
: [];
|
||||
const partners = Array.isArray(normalized?.directory?.partners)
|
||||
? normalized.directory.partners
|
||||
: [];
|
||||
|
||||
return {
|
||||
...normalized,
|
||||
directory: {
|
||||
...normalized.directory,
|
||||
partners: ensureUniqueIds(
|
||||
partners,
|
||||
(partner) => partner.id,
|
||||
(partner, index) => partner.name || partner.category || `partner-${index + 1}`,
|
||||
"partner",
|
||||
),
|
||||
},
|
||||
inquiryForm: {
|
||||
...normalized.inquiryForm,
|
||||
fields: fields.map((field, index) => ({
|
||||
id:
|
||||
String(field.id || `field-${index + 1}`)
|
||||
.trim()
|
||||
.replace(/\s+/g, "")
|
||||
.replace(/[^a-zA-Z0-9_-]/g, "") || `field-${index + 1}`,
|
||||
fields: ensureUniqueIds(
|
||||
fields,
|
||||
(field) => field.id,
|
||||
(field, index) => field.label || field.placeholder || `field-${index + 1}`,
|
||||
"field",
|
||||
).map((field) => ({
|
||||
id: field.id,
|
||||
label: field.label || "",
|
||||
placeholder: field.placeholder || "",
|
||||
type: field.type || "text",
|
||||
|
||||
@@ -9,6 +9,7 @@ const createRenderSingletonPageView = require("./_renderSingletonPageView");
|
||||
const writeAuditLog = require("../audit/writeAuditLog");
|
||||
const diffObject = require("../audit/diffObject");
|
||||
const jsonHelper = require("../utils/jsonHelper");
|
||||
const { ensureUniqueIds } = require("../utils/contentEditorIds");
|
||||
|
||||
function formatLastUpdated(date = new Date()) {
|
||||
return `Last updated: ${new Intl.DateTimeFormat("en-US", {
|
||||
@@ -18,9 +19,26 @@ function formatLastUpdated(date = new Date()) {
|
||||
}).format(date)}`;
|
||||
}
|
||||
|
||||
function withLastUpdated(payload) {
|
||||
function withLastUpdated(payload, { beforeData } = {}) {
|
||||
const existingPolicies = Array.isArray(beforeData?.policies) ? beforeData.policies : [];
|
||||
|
||||
const policies = ensureUniqueIds(
|
||||
Array.isArray(payload.policies) ? payload.policies : [],
|
||||
(policy) => policy.id,
|
||||
(policy, index) => policy.navLabel || policy.title || `policy-${index + 1}`,
|
||||
"policy",
|
||||
).map((policy) => {
|
||||
const existingPolicy = existingPolicies.find((item) => item.id === policy.id);
|
||||
|
||||
return {
|
||||
...policy,
|
||||
sections: Array.isArray(existingPolicy?.sections) ? existingPolicy.sections : [],
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
...payload,
|
||||
policies,
|
||||
hero: {
|
||||
...(payload.hero || {}),
|
||||
lastUpdated: formatLastUpdated(),
|
||||
|
||||
Reference in New Issue
Block a user