forked from UKSOURCE/cms.lams
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.
215 lines
8.2 KiB
JavaScript
215 lines
8.2 KiB
JavaScript
const AdmissionsPage = require("../models/admissionsPage");
|
|
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) {
|
|
try {
|
|
return await createRenderSingletonPageView({
|
|
model: AdmissionsPage,
|
|
editorConfig: admissionsConfig,
|
|
view: "admin/admissions/index",
|
|
normalizeForEditor: normalizeAdmissionsPayload,
|
|
})(req, res);
|
|
} catch (error) {
|
|
console.error("admissions index error:", error);
|
|
req.flash("error_msg", "Error loading Admissions Management");
|
|
return req.session.save(() => res.redirect("/admin/dashboard"));
|
|
}
|
|
};
|
|
|
|
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;
|