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.
175 lines
5.5 KiB
JavaScript
175 lines
5.5 KiB
JavaScript
const PoliciesPage = require("../models/policiesPage");
|
|
const AUDIT_ACTIONS = require("../constants/auditAction");
|
|
const {
|
|
baseConfig: policiesConfig,
|
|
createPoliciesSectionEditorConfig,
|
|
} = require("../utils/contentEditors/policiesConfig");
|
|
const createPageContentController = require("./_createPageContentController");
|
|
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", {
|
|
year: "numeric",
|
|
month: "long",
|
|
day: "numeric",
|
|
}).format(date)}`;
|
|
}
|
|
|
|
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(),
|
|
},
|
|
};
|
|
}
|
|
|
|
const baseController = createPageContentController({
|
|
model: PoliciesPage,
|
|
modelName: "PoliciesPage",
|
|
auditAction: AUDIT_ACTIONS.UPDATE_POLICIES,
|
|
editorConfig: policiesConfig,
|
|
preparePayload: withLastUpdated,
|
|
});
|
|
|
|
module.exports = {
|
|
...baseController,
|
|
async index(req, res) {
|
|
try {
|
|
return await createRenderSingletonPageView({
|
|
model: PoliciesPage,
|
|
editorConfig: policiesConfig,
|
|
view: "admin/policies/index",
|
|
})(req, res);
|
|
} catch (error) {
|
|
console.error("policies index error:", error);
|
|
req.flash("error_msg", "Error loading Policies Management");
|
|
return req.session.save(() => res.redirect("/admin/dashboard"));
|
|
}
|
|
},
|
|
|
|
async editSections(req, res) {
|
|
try {
|
|
const doc = await PoliciesPage.getSingle();
|
|
const data = doc.toObject();
|
|
const policy = (data.policies || []).find(
|
|
(item) => item.id === req.params.policyId,
|
|
);
|
|
|
|
if (!policy) {
|
|
req.flash("error_msg", "Policy not found");
|
|
return req.session.save(() => res.redirect("/admin/policies"));
|
|
}
|
|
|
|
const frontendUrl = process.env.FRONTEND_URL || "http://localhost:3000";
|
|
const backendUrl =
|
|
process.env.BACKEND_URL ?? `${req.protocol}://${req.get("host")}`;
|
|
const editorConfig = createPoliciesSectionEditorConfig(
|
|
policy,
|
|
data.policies || [],
|
|
);
|
|
|
|
return res.render("admin/policies/sections", {
|
|
layout: "layouts/main",
|
|
title: editorConfig.title,
|
|
subtitle: editorConfig.subtitle,
|
|
data: { sections: policy.sections || [] },
|
|
editorConfig,
|
|
activeTab: "sections",
|
|
frontendUrl,
|
|
backendUrl,
|
|
previewUrl: `${frontendUrl}${editorConfig.previewPath}`,
|
|
currentPath: req.path,
|
|
user: req.session.user,
|
|
});
|
|
} catch (error) {
|
|
console.error("policies section index error:", error);
|
|
req.flash("error_msg", "Error loading policy sections");
|
|
return req.session.save(() => res.redirect("/admin/policies"));
|
|
}
|
|
},
|
|
|
|
async updateSections(req, res) {
|
|
try {
|
|
const payload =
|
|
typeof req.body.pageJson === "string"
|
|
? JSON.parse(req.body.pageJson)
|
|
: req.body.pageJson || {};
|
|
const doc = await PoliciesPage.getSingle();
|
|
const beforeData = JSON.parse(JSON.stringify(doc.toObject()));
|
|
const policyIndex = (doc.policies || []).findIndex(
|
|
(item) => item.id === req.params.policyId,
|
|
);
|
|
|
|
if (policyIndex === -1) {
|
|
req.flash("error_msg", "Policy not found");
|
|
return req.session.save(() => res.redirect("/admin/policies"));
|
|
}
|
|
|
|
doc.policies[policyIndex].sections = Array.isArray(payload.sections)
|
|
? payload.sections
|
|
: [];
|
|
doc.hero = {
|
|
...(doc.hero || {}),
|
|
lastUpdated: formatLastUpdated(),
|
|
};
|
|
doc.markModified("policies");
|
|
doc.markModified("hero");
|
|
await doc.save();
|
|
|
|
const afterData = JSON.parse(JSON.stringify(doc.toObject()));
|
|
const changes = diffObject(beforeData, afterData);
|
|
|
|
if (changes.length > 0) {
|
|
await writeAuditLog({
|
|
model: "PoliciesPage",
|
|
documentId: doc._id,
|
|
action: AUDIT_ACTIONS.UPDATE_POLICIES,
|
|
before: beforeData,
|
|
after: afterData,
|
|
changes,
|
|
req,
|
|
});
|
|
}
|
|
|
|
const finalData = await PoliciesPage.findOne()
|
|
.select("-_id -__v -createdAt -updatedAt")
|
|
.lean();
|
|
jsonHelper.writeJsonFile(policiesConfig.dataFile, finalData);
|
|
|
|
req.flash("success_msg", "Policy sections updated successfully");
|
|
return req.session.save(() =>
|
|
res.redirect(`/admin/policies/${req.params.policyId}/section`),
|
|
);
|
|
} catch (error) {
|
|
console.error("policies section update error:", error);
|
|
req.flash("error_msg", `Error updating policy sections: ${error.message}`);
|
|
return req.session.save(() =>
|
|
res.redirect(`/admin/policies/${req.params.policyId}/section`),
|
|
);
|
|
}
|
|
},
|
|
};
|