diff --git a/.gitignore b/.gitignore index fe5c5c5..4d99324 100644 --- a/.gitignore +++ b/.gitignore @@ -22,6 +22,7 @@ pids #cursor .cursor package-lock.json +AGENTS.md .vscode .kiro/ diff --git a/constants/auditAction.js b/constants/auditAction.js index 73b978e..a6a9790 100644 --- a/constants/auditAction.js +++ b/constants/auditAction.js @@ -22,6 +22,11 @@ const AUDIT_ACTIONS = Object.freeze({ // About Us UPDATE_ABOUT_US: "UPDATE_ABOUT_US", + UPDATE_PARTNERSHIPS: "UPDATE_PARTNERSHIPS", + UPDATE_HISTORY: "UPDATE_HISTORY", + UPDATE_ACCREDITATION: "UPDATE_ACCREDITATION", + UPDATE_ADMISSIONS: "UPDATE_ADMISSIONS", + UPDATE_POLICIES: "UPDATE_POLICIES", // Header UPDATE_HEADER: "UPDATE_HEADER", diff --git a/controllers/_createPageContentController.js b/controllers/_createPageContentController.js new file mode 100644 index 0000000..56a1ace --- /dev/null +++ b/controllers/_createPageContentController.js @@ -0,0 +1,121 @@ +const { addBaseUrlToImages } = require("../utils/imageHelper"); +const jsonHelper = require("../utils/jsonHelper"); +const writeAuditLog = require("../audit/writeAuditLog"); +const diffObject = require("../audit/diffObject"); + +function createPageContentController({ + model, + modelName, + auditAction, + editorConfig, + normalizeForEditor, + normalizeForApi, + preparePayload, +}) { + return { + async index(req, res) { + try { + const doc = await model.getSingle(); + const rawData = doc.toObject(); + const data = normalizeForEditor ? normalizeForEditor(rawData, req) : rawData; + const frontendUrl = process.env.FRONTEND_URL || "http://localhost:3000"; + const backendUrl = + process.env.BACKEND_URL ?? `${req.protocol}://${req.get("host")}`; + + res.render("admin/pageContent/index", { + layout: "layouts/main", + title: editorConfig.title, + subtitle: editorConfig.subtitle, + data, + editorConfig, + activeTab: req.query.tab || editorConfig.tabs[0].key, + frontendUrl, + backendUrl, + previewUrl: `${frontendUrl}${editorConfig.previewPath}`, + currentPath: req.path, + user: req.session.user, + }); + } catch (error) { + console.error(`${editorConfig.key} index error:`, error); + req.flash("error_msg", `Error loading ${editorConfig.title}`); + return req.session.save(() => res.redirect("/admin/dashboard")); + } + }, + + async update(req, res) { + try { + const rawPayload = + typeof req.body.pageJson === "string" + ? JSON.parse(req.body.pageJson) + : req.body.pageJson || {}; + + const activeTab = req.body.activeTab || editorConfig.tabs[0].key; + const doc = await model.getSingle(); + const beforeData = JSON.parse(JSON.stringify(doc.toObject())); + const payload = preparePayload + ? preparePayload(rawPayload, { req, doc, beforeData }) + : rawPayload; + + doc.set(payload); + Object.keys(payload).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: modelName, + documentId: doc._id, + action: auditAction, + before: beforeData, + after: afterData, + changes, + req, + }); + } + + const finalData = await model + .findOne() + .select("-_id -__v -createdAt -updatedAt") + .lean(); + jsonHelper.writeJsonFile(editorConfig.dataFile, finalData); + + req.flash("success_msg", `${editorConfig.title} updated successfully`); + return req.session.save(() => + res.redirect(`${editorConfig.routeBase}?tab=${activeTab}`), + ); + } catch (error) { + console.error(`${editorConfig.key} update error:`, error); + req.flash( + "error_msg", + `Error updating ${editorConfig.title}: ${error.message}`, + ); + return req.session.save(() => + res.redirect( + `${editorConfig.routeBase}?tab=${req.body.activeTab || ""}`, + ), + ); + } + }, + + async api(req, res) { + try { + const doc = await model.getSingle(); + const rawData = doc.toObject(); + const backendUrl = + process.env.BACKEND_URL ?? `${req.protocol}://${req.get("host")}`; + const normalized = normalizeForApi ? normalizeForApi(rawData, req) : rawData; + const processed = addBaseUrlToImages(normalized, backendUrl); + return res.json(processed); + } catch (error) { + console.error(`${editorConfig.key} api error:`, error); + return res + .status(500) + .json({ error: `Error loading ${editorConfig.key} data` }); + } + }, + }; +} + +module.exports = createPageContentController; diff --git a/controllers/_renderSingletonPageView.js b/controllers/_renderSingletonPageView.js new file mode 100644 index 0000000..e70650d --- /dev/null +++ b/controllers/_renderSingletonPageView.js @@ -0,0 +1,36 @@ +function createRenderSingletonPageView({ + model, + editorConfig, + view, + normalizeForEditor, +}) { + return async function renderSingletonPageView(req, res) { + const doc = await model.getSingle(); + const rawData = doc.toObject(); + const data = normalizeForEditor ? normalizeForEditor(rawData, req) : rawData; + 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", + title: editorConfig.title, + subtitle: editorConfig.subtitle, + data, + editorConfig, + activeTab, + frontendUrl, + backendUrl, + previewUrl: `${frontendUrl}${editorConfig.previewPath}`, + currentPath: req.path, + user: req.session.user, + }); + }; +} + +module.exports = createRenderSingletonPageView; diff --git a/controllers/accreditationController.js b/controllers/accreditationController.js new file mode 100644 index 0000000..705038f --- /dev/null +++ b/controllers/accreditationController.js @@ -0,0 +1,56 @@ +const AccreditationPage = require("../models/accreditationPage"); +const AUDIT_ACTIONS = require("../constants/auditAction"); +const accreditationConfig = require("../utils/contentEditors/accreditationConfig"); +const createPageContentController = require("./_createPageContentController"); +const createRenderSingletonPageView = require("./_renderSingletonPageView"); + +const controller = createPageContentController({ + model: AccreditationPage, + 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) { + try { + return await createRenderSingletonPageView({ + model: AccreditationPage, + editorConfig: accreditationConfig, + view: "admin/accreditation/index", + })(req, res); + } catch (error) { + console.error("accreditation index error:", error); + req.flash("error_msg", "Error loading Accreditation Management"); + return req.session.save(() => res.redirect("/admin/dashboard")); + } +}; + +module.exports = controller; diff --git a/controllers/admissionsController.js b/controllers/admissionsController.js new file mode 100644 index 0000000..2a082aa --- /dev/null +++ b/controllers/admissionsController.js @@ -0,0 +1,332 @@ +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 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, "")); + return numericValue > 0 ? String(numericValue) : fallback; +} + +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, 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 || ""), + }; +} + +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 normalizeTuitionPoint(point, index) { + if (point && typeof point === "object" && !Array.isArray(point)) { + const numericValue = Number(point.value); + return { + time: String(point.time || point.label || `Year ${index + 1}`), + value: Number.isFinite(numericValue) && numericValue >= 0 ? numericValue : 0, + }; + } + + const numericValue = Number(point); + return { + time: `Year ${index + 1}`, + value: Number.isFinite(numericValue) && numericValue >= 0 ? numericValue : 0, + }; +} + +function normalizeTuitionSeries(series, index) { + const source = typeof series === "string" ? { label: series } : { ...(series || {}) }; + const rawPoints = Array.isArray(source.points) && source.points.length + ? source.points + : Array.isArray(source.values) + ? source.values + : []; + + return { + label: String(source.label || `Series ${index + 1}`).slice(0, 40), + color: String(source.color || "#0F172A"), + points: rawPoints.map(normalizeTuitionPoint), + }; +} + +function normalizeTuition(tuition) { + const nextTuition = { ...(tuition || {}) }; + + nextTuition.title = String(nextTuition.title || ""); + nextTuition.chartTitle = String(nextTuition.chartTitle || ""); + nextTuition.chartDescription = String(nextTuition.chartDescription || ""); + nextTuition.series = Array.isArray(nextTuition.series) + ? nextTuition.series.map(normalizeTuitionSeries) + : []; + + return nextTuition; +} + +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 = { + ...normalizeTuition(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")}`; + 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}`, + 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")); + } + + 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: nextLabel, + 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; diff --git a/controllers/historyPageController.js b/controllers/historyPageController.js new file mode 100644 index 0000000..794418b --- /dev/null +++ b/controllers/historyPageController.js @@ -0,0 +1,125 @@ +const HistoryPage = require("../models/historyPage"); +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) { + try { + return await createRenderSingletonPageView({ + model: HistoryPage, + editorConfig: historyConfig, + view: "admin/history/index", + })(req, res); + } catch (error) { + console.error("history index error:", error); + req.flash("error_msg", "Error loading History Management"); + return req.session.save(() => res.redirect("/admin/dashboard")); + } +}; + +module.exports = controller; diff --git a/controllers/partnershipsController.js b/controllers/partnershipsController.js new file mode 100644 index 0000000..be5df7e --- /dev/null +++ b/controllers/partnershipsController.js @@ -0,0 +1,223 @@ +const PartnershipsPage = require("../models/partnerships"); +const AUDIT_ACTIONS = require("../constants/auditAction"); +const partnershipsConfig = require("../utils/contentEditors/partnershipsConfig"); +const createPageContentController = require("./_createPageContentController"); +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, + label: field?.label || "", + placeholder: field?.placeholder || "", + type, + width, + required: true, + options: Array.isArray(field?.options) ? field.options : [], + }; +} + +function normalizeInquiryForm(data) { + if (!data?.inquiryForm) { + return data; + } + + if (Array.isArray(data.inquiryForm.fields)) { + return data; + } + + const legacyFields = data.inquiryForm.fields || {}; + + return { + ...data, + inquiryForm: { + ...data.inquiryForm, + fields: [ + toInquiryField("firstName", legacyFields.firstName, "text", "half"), + toInquiryField("lastName", legacyFields.lastName, "text", "half"), + toInquiryField("organization", legacyFields.organization, "text", "full"), + toInquiryField( + "partnershipType", + legacyFields.partnershipType, + "select", + "full", + ), + toInquiryField("message", legacyFields.message, "textarea", "full"), + ].filter((field) => field.label || field.placeholder || field.id), + }, + }; +} + +function prepareInquiryPayload(payload) { + const normalized = normalizeInquiryForm(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, + directory: { + ...normalized.directory, + partners: ensureUniqueIds( + partners, + (partner) => partner.id, + (partner, index) => partner.name || partner.category || `partner-${index + 1}`, + "partner", + ), + }, + inquiryForm: { + ...normalized.inquiryForm, + 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", + width: field.width || "full", + required: Boolean(field.required), + options: Array.isArray(field.options) ? field.options.filter(Boolean) : [], + })), + }, + }; +} + +const controller = createPageContentController({ + model: PartnershipsPage, + modelName: "PartnershipsPage", + auditAction: AUDIT_ACTIONS.UPDATE_PARTNERSHIPS, + editorConfig: partnershipsConfig, + normalizeForEditor: normalizeInquiryForm, + normalizeForApi: normalizeInquiryForm, + preparePayload: prepareInquiryPayload, +}); + +controller.index = async function index(req, res) { + try { + 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, + 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"); + return req.session.save(() => res.redirect("/admin/dashboard")); + } +}; + +module.exports = controller; diff --git a/controllers/policiesController.js b/controllers/policiesController.js new file mode 100644 index 0000000..65dc7c9 --- /dev/null +++ b/controllers/policiesController.js @@ -0,0 +1,222 @@ +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"); +const { + normalizePolicy, + normalizePoliciesDocument, + validateContent, +} = require("../utils/policiesBlockContent"); + +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); + const normalizedExistingPolicy = normalizePolicy(existingPolicy || policy); + + return { + ...policy, + content: normalizedExistingPolicy.content, + }; + }); + + return { + ...payload, + policies, + hero: { + ...(payload.hero || {}), + lastUpdated: formatLastUpdated(), + }, + }; +} + +const baseController = createPageContentController({ + model: PoliciesPage, + modelName: "PoliciesPage", + auditAction: AUDIT_ACTIONS.UPDATE_POLICIES, + editorConfig: policiesConfig, + normalizeForEditor: normalizePoliciesDocument, + normalizeForApi: normalizePoliciesDocument, + 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 = normalizePoliciesDocument(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: { + policy, + content: policy.content, + }, + 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")); + } + + const policyIds = (doc.policies || []) + .map((item) => item.id) + .filter(Boolean); + const validation = validateContent(payload.content, policyIds); + + if (validation.errors.length > 0) { + req.flash("error_msg", validation.errors.join(" ")); + return req.session.save(() => + res.redirect(`/admin/policies/${req.params.policyId}/section`), + ); + } + + const normalizedPolicies = (doc.policies || []).map((item) => + normalizePolicy(JSON.parse(JSON.stringify(item))), + ); + const currentPolicy = normalizedPolicies[policyIndex]; + const updatedPolicy = { + ...currentPolicy, + content: validation.content, + }; + + delete updatedPolicy.sections; + delete updatedPolicy.contentByLanguage; + normalizedPolicies.splice(policyIndex, 1, updatedPolicy); + const nextHero = { + ...(doc.hero || {}), + lastUpdated: formatLastUpdated(), + }; + await PoliciesPage.updateOne( + { _id: doc._id }, + { + $set: { + policies: normalizedPolicies, + hero: nextHero, + }, + }, + ); + + const reloadedDoc = await PoliciesPage.findById(doc._id); + const afterData = JSON.parse(JSON.stringify(reloadedDoc.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 = normalizePoliciesDocument( + (await PoliciesPage.findOne() + .select("-_id -__v -createdAt -updatedAt") + .lean()) || {}, + ); + jsonHelper.writeJsonFile(policiesConfig.dataFile, finalData); + + const successMessage = validation.warnings.length + ? `Policy content updated with warnings: ${validation.warnings.join(" ")}` + : "Policy content updated successfully"; + req.flash("success_msg", successMessage); + const redirectUrl = + req.body.intent === "save-back" + ? "/admin/policies?tab=policies" + : `/admin/policies/${req.params.policyId}/section`; + return req.session.save(() => + res.redirect(redirectUrl), + ); + } 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`), + ); + } + }, +}; diff --git a/data/accreditation.json b/data/accreditation.json new file mode 100644 index 0000000..a8e498c --- /dev/null +++ b/data/accreditation.json @@ -0,0 +1,78 @@ +{ + "hero": { + "badge": "Accreditation Save Check", + "title": "ACCREDITATION AND RECOGNITION", + "description": "At the London Academy of Management and Sciences (LAMS), we are committed to maintaining the highest academic standards and delivering quality education that aligns with international benchmarks. Our accreditations reflect our dedication to excellence, credibility, and continuous improvement in higher education and professional learning." + }, + "grid": { + "tabs": [ + "All", + "Registry", + "Certification", + "Accreditation", + "Quality Assurance" + ], + "items": [ + { + "id": "ukrlp", + "icon": "fa-graduation-cap", + "image": "/uploads/accreditation/ukrlp.png", + "status": "Active", + "category": "Registry", + "title": "UKRLP", + "description": "The UK Register of Learning Providers is a national register in the United Kingdom for verified organizations delivering education and training. Inclusion confirms a validation process and official listing as a recognized learning provider, supporting transparency and enabling stakeholders to verify provider details.", + "scopeLabel": "Scope", + "scope": "All Programs", + "validUntilLabel": "Valid Until", + "validUntil": "Ongoing", + "buttonLabel": "View Certificate", + "certificateHref": "#" + }, + { + "id": "ico", + "icon": "fa-check-double", + "image": "/uploads/accreditation/ico.png", + "status": "Active", + "category": "Certification", + "title": "ICO", + "description": "The International Certification Organization is an international certification body that assesses educational institutions against quality management, operational, and governance standards. ICO certification indicates alignment with internationally accepted frameworks and compliance with structured quality and administrative practices.", + "scopeLabel": "Scope", + "scope": "Quality Management", + "validUntilLabel": "Valid Until", + "validUntil": "Ongoing", + "buttonLabel": "View Certificate", + "certificateHref": "#" + }, + { + "id": "head", + "icon": "fa-building-columns", + "image": "/uploads/accreditation/head.png", + "status": "Active", + "category": "Accreditation", + "title": "HEAD", + "description": "The Higher Education Accreditation Division is an independent accreditation body focused on evaluating higher education institutions. HEAD assesses academic quality, institutional governance, curriculum design, and internal quality assurance mechanisms, reflecting adherence to established standards for higher education delivery and institutional effectiveness.", + "scopeLabel": "Scope", + "scope": "Higher Education", + "validUntilLabel": "Valid Until", + "validUntil": "Ongoing", + "buttonLabel": "View Certificate", + "certificateHref": "#" + }, + { + "id": "qahe", + "icon": "fa-award", + "image": "/uploads/accreditation/QAHE.png", + "status": "Active", + "category": "Quality Assurance", + "title": "QAHE", + "description": "Quality Assurance in Higher Education is an international quality assurance agency that evaluates institutions based on academic standards, teaching and learning processes, assessment practices, and institutional management systems. QAHE accreditation signifies that an institution meets defined benchmarks for quality assurance and continuous improvement within the higher education sector.", + "scopeLabel": "Scope", + "scope": "Quality Assurance", + "validUntilLabel": "Valid Until", + "validUntil": "Ongoing", + "buttonLabel": "View Certificate", + "certificateHref": "#" + } + ] + } +} diff --git a/data/admissions.json b/data/admissions.json new file mode 100644 index 0000000..5d6155f --- /dev/null +++ b/data/admissions.json @@ -0,0 +1,239 @@ +{ + "hero": { + "badge": "Your Path Starts HereYour Path Starts He", + "title": "Admissions & Transparent TuitionAdmissions & Transparent TuitionAdmissions & Tra", + "description": "We believe high-quality education should be accessible to everyone. Explore our straightforward admissions process and flexible payment models designed to fit your life.We believe high-quality education should be accessible to everyone. Exp", + "primaryCta": { + "label": "Start ApplicationStart ApplicationStart ApplicationStart App", + "href": "http://localhost:3001/admin/admissions" + }, + "secondaryCta": { + "label": "View TuitionView TuitionView TuitionView TuitionView Tuition", + "href": "http://localhost:3001/admin/admissions" + }, + "image": "/uploads/admissions/Colorful_Square_Background.png", + "imageAlt": "View TuitionView TuitionView TuitionView TuitionView TuitionView TuitionView TuitionView TuitionView TuitionView Tuition" + }, + "process": { + "id": "admissions-process", + "title": "Admissions ProcessAdmissions ProcessAdmissions ProcessAdmiss", + "description": "Our streamlined process gets you from application to enrolled in days, not months. No application fees, no standardized tests.Our streamlined process gets you from application to e", + "steps": [ + { + "number": "01", + "title": "Send Transcripts", + "description": "Request official transcripts from previous institutions for credit evaluation.", + "active": true + }, + { + "number": "02", + "title": "Submit Application", + "description": "Fill out our online form in under 15 minutes. Basic personal and educational history required.", + "active": true + }, + { + "number": "03", + "title": "Choose Payment Plan", + "description": "Select between our monthly subscription or pay-per-course model.", + "active": false + } + ] + }, + "eligibility": { + "id": "eligibility", + "title": "Eligibility & Transfer CreditsEligibility & Transfer Credits", + "cards": [ + { + "title": "Basic EligibilityBasic EligibilityBasic Eligibilit", + "icon": "fa-check-circle", + "items": [ + "High school diploma or equivalentHigh school diploma or equivalentHigh school diploma or equivalentHigh school diploma o", + "Minimum 2.0 GPA for transfer studentsMinimum 2.0 GPA for transfer studentsMinimum 2.0 GPA for transfer studentsMinimum 2", + "English proficiency if applicableEnglish proficiency if applicableEnglish proficiency if applicableEnglish proficiency i" + ] + }, + { + "title": "Transfer PolicyTransfer PolicyTransfer PolicyTrans", + "icon": "fa-exchange-alt", + "items": [ + "Up to 90 credits accepted for Bachelor'sUp to 90 credits accepted for Bachelor'sUp to 90 credits accepted for Bachelor's", + "Free unofficial evaluation within 48 hoursFree unofficial evaluation within 48 hoursFree unofficial evaluation within 48", + "Credit for prior learning and certificationsCredit for prior learning and certificationsCredit for prior learning and ce" + ] + } + ] + }, + "tuition": { + "id": "tuition-breakdown", + "title": "Tuition BreakdownTuition BreakdownTuition BreakdownTuition B", + "chartTitle": "Savings vs. Traditional UniversitySavings vs. Traditional Un", + "chartDescription": "Estimated total cost for a 4-year degreeEstimated total cost for a 4-year degreeEstimated total cost for a 4-year degreeEstimated total cost", + "series": [ + { + "label": "Traditional University", + "color": "#850f0f", + "points": [ + { + "time": "Year 1", + "value": 25000 + }, + { + "time": "Year 2", + "value": 49998 + }, + { + "time": "Year 3", + "value": 30000 + }, + { + "time": "Year 4", + "value": 100000 + }, + { + "time": "Year 5", + "value": 120000 + }, + { + "time": "Year 6", + "value": 500000 + } + ] + }, + { + "label": "LAMS", + "color": "#a700b3", + "points": [ + { + "time": "Year 1", + "value": 3588 + }, + { + "time": "Year 2", + "value": 7176 + }, + { + "time": "Year 3", + "value": 10764 + }, + { + "time": "Year 4", + "value": 10000 + } + ] + } + ] + }, + "keyDates": { + "id": "key-dates", + "title": "Key Dates & Deadlines", + "columns": [ + { + "id": "Term", + "label": "Term" + }, + { + "id": "Application-Deadline", + "label": "Application Deadline" + }, + { + "id": "Classes-Start", + "label": "Classes Start" + }, + { + "id": "column-4", + "label": "Column 4" + } + ], + "rows": [ + { + "id": "row-1", + "cells": [ + "Fall Term 1", + "August 15, 2026August 15, 2026August 15, 2026August 15, 2026", + "September 1, 2026September 1, 2026September 1, 2026September", + "September 1, 2026September 1, 2026September 1, 2026September" + ] + }, + { + "id": "row-2", + "cells": [ + "Fall Term 2", + "October 15, 2026October 15, 2026October 15, 2026October 15, ", + "November 1, 2026November 1, 2026November 1, 2026November 1, ", + "September 1, 2026September 1, 2026September 1, 2026September" + ] + }, + { + "id": "row-3", + "cells": [ + "Spring Term 1", + "December 15, 2026December 15, 2026December 15, 2026December ", + "January 5, 2027", + "September 1, 2026September 1, 2026September 1, 2026September" + ] + } + ] + }, + "calculator": { + "title": "Affordability Calculator", + "description": "Estimate your monthly investment.", + "cta": { + "label": "Apply Now", + "href": "#apply" + }, + "options": [ + { + "id": "subscription", + "label": "Subscription", + "paceLabel": "Target PaceTarget PaceTarget P", + "minPaceLabel": "RelaxedRelaxedRelaxe", + "maxPaceLabel": "AcceleratedAccelerat", + "resultLabel": "Estimated Monthly PaymentEstimated Month", + "monthlyAmount": "5000000", + "monthlySuffix": "/mo", + "noteIcon": "fa-bolt", + "note": "Flat rate, unlimited coursesFlat rate, unlimited coursesFlat" + }, + { + "id": "per-course", + "label": "Per Course", + "paceLabel": "Target Pace", + "minPaceLabel": "Relaxed", + "maxPaceLabel": "Accelerated", + "resultLabel": "Estimated Monthly Payment", + "monthlyAmount": "500", + "monthlySuffix": "/mo", + "noteIcon": "fa-bolt", + "note": "Flat rate, unlimited courses" + }, + { + "id": "d-course", + "label": "D Course", + "paceLabel": "Target Pace", + "minPaceLabel": "Relaxed", + "maxPaceLabel": "Accelerated", + "resultLabel": "Estimated Monthly Payment", + "monthlyAmount": "500", + "monthlySuffix": "/mo", + "noteIcon": "fa-bolt", + "note": "Flat rate, unlimited courses" + } + ] + }, + "scholarships": { + "title": "Scholarships & Aid", + "icon": "fa-award", + "items": [ + { + "title": "Working Adult GrantWorking Adult GrantWorking Adul", + "amount": "Up to $1,500", + "description": "For students employed full-time while studying.For students employed full-time while studying.For students employed full-time while studying.For students employ" + }, + { + "title": "Military Discount", + "amount": "15% Off", + "description": "For students employed full-time while studying.For students employed full-time while studying.For students employed full-time while studying.For students employ" + } + ] + } +} \ No newline at end of file diff --git a/data/history.json b/data/history.json new file mode 100644 index 0000000..cef9de3 --- /dev/null +++ b/data/history.json @@ -0,0 +1,112 @@ +{ + "highlight": { + "icon": "fa-magnifying-glass", + "text": "2025 Milestone Reached: A Rapidly Growing Global Community!2025 Milestone Reached: A Rapidly Growing Global Co", + "linkLabel": "Read Full StoryRead Full Story", + "href": "/admin/history" + }, + "hero": { + "badge": "Our JourneyOur JourneyOur JourneyOur Jou", + "title": "Building the Future of Education.Building the Future of Education.Building the Future of E", + "description": "From our humble beginnings to becoming a global leader in online education, explore the key moments that define our legacy.From our humble beginnings to becoming a global leader in online education, explore the key momen" + }, + "filters": { + "yearOptions": [ + "All Years", + "2020 - Present", + "2010 - 2019", + "2005 - 2009", + "2015 - 2019" + ], + "categoryOptions": [ + "All Categories", + "Academic Programs", + "Global Expansion", + "Technology & Innovation", + "Student Experience", + "Awards & Recognition" + ] + }, + "timeline": { + "items": [ + { + "id": "student-experience-innovation", + "year": "2026", + "yearRange": "2020 - Present", + "category": "Student Experience", + "categoryLabel": "Student Experience", + "title": "Innovation in Student Experience", + "description": "Enhanced student support through integrated digital services, academic advising, and career development platforms.", + "image": "/uploads/history/Colorful_Square_Background.png", + "imageAlt": "", + "stats": [], + "featured": true + }, + { + "id": "international-partnerships-expansion", + "year": "2025", + "yearRange": "2020 - Present", + "category": "Global Expansion", + "categoryLabel": "Global", + "title": "Expansion of International Partnerships", + "description": "Established collaborations with academic institutions and industry partners across regions, enabling dual qualifications and cross-border learning opportunities.", + "image": "/uploads/history/7281.jpg", + "imageAlt": "", + "stats": [], + "featured": false + }, + { + "id": "academic-programmes-expansion", + "year": "2024", + "yearRange": "2020 - Present", + "category": "Academic Programs", + "categoryLabel": "Academic", + "title": "Expansion of Academic Programmes", + "description": "Launched a portfolio of undergraduate and postgraduate programmes designed to meet global market demands and emerging industry needs.", + "image": "/uploads/history/2024.png", + "imageAlt": "", + "stats": [], + "featured": false + }, + { + "id": "ai-enhanced-learning-platform", + "year": "2024", + "yearRange": "2020 - Present", + "category": "Technology & Innovation", + "categoryLabel": "Technology", + "title": "Launch of AI-Enhanced Learning Platform", + "description": "Introduced an adaptive digital learning system that personalises study pathways and enhances student engagement and outcomes.", + "image": "/uploads/history/ai-enhanced-learning-platform.png", + "imageAlt": "Abstract artificial intelligence and digital learning visualization", + "stats": [], + "featured": false + }, + { + "id": "strategic-academic-framework", + "year": "2023", + "yearRange": "2020 - Present", + "category": "Academic Programs", + "categoryLabel": "Academic", + "title": "Strategic Academic Framework Introduced", + "description": "Established a future-focused academic model aligned with international standards, integrating applied learning, digital competencies, and global perspectives.", + "image": "/uploads/history/7281.jpg", + "imageAlt": "", + "stats": [], + "featured": false + }, + { + "id": "strategic-academic-framework", + "year": "2027", + "yearRange": "2020 - Present", + "category": "All Categories", + "categoryLabel": "Academic", + "title": "Strategic Academic Framework Introduced", + "description": "Established a future-focused academic model aligned with international standards, integrating applied learning, digital competencies, and global perspectives.", + "image": "/uploads/history/kVI17_2B.webp", + "imageAlt": "aaa", + "stats": [], + "featured": true + } + ] + } +} diff --git a/data/partnerships.json b/data/partnerships.json new file mode 100644 index 0000000..e3790bd --- /dev/null +++ b/data/partnerships.json @@ -0,0 +1,150 @@ +{ + "hero": { + "badge": "Global NetworkGlobal NetworkGlobal Netwo", + "title": "Industry & Academic Partnerships.Industry & Academic Partnerships.Industry & Academic Part", + "description": "Global NetworkGlobal NetworkGlobal NetwoGlobal NetworkGlobal NetworkGlobal NetwoGlobal NetworkGlobal NetworkGlobal NetwoGlobal NetworkGlobal NetworkGlobal NetwoGlobal NetworkGlobal NetworkGlobal NetwoGlobal NetworkGlobal", + "linkLabel": "Explore DirectoryExplore DirectoryExplor", + "image": "/uploads/partnerships/kVI17_2B.webp", + "imageAlt": "Modern university campus and corporate office buildingModern university campus and corporate office buildingModern unive" + }, + "directory": { + "heading": "Partner DirectoryPartner DirectoryPartne", + "description": "Discover the organizations shaping the future of education with us.Discover the organizations shaping the future of education with us.Discover the organizations shaping the future ", + "tabs": [ + "All PartnersAll PartnersAll Pa", + "IndustryIndustryIndustryIndust", + "AcademicAcademicAcademicAcadem", + "CommunityCommunityCommunityCom", + "hehehehehehehehehehehehehehehe", + "hehehehehehehhehehehehehehhehe" + ], + "partners": [ + { + "id": "techvanguardtechvanguardtechvanguardtechvanguardte", + "name": "TechvanguardTechvanguardTechvanguardTechvanguardTechvanguardTechvanguardTechvanguardTechva", + "category": "IndustryIndustryIndustryIndust", + "summary": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIn", + "logo": "/uploads/partnerships/tech-logo.png", + "logoAlt": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustry", + "about": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIn", + "collabType": "IndustryIndustryIndustryIndustryIndustry", + "benefits": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIn" + }, + { + "id": "IndustryIndustryIndustryIndustryIndustryIndustryIn", + "name": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIn", + "category": "IndustryIndustryIndustryIndust", + "summary": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIn", + "logo": "/uploads/partnerships/royalcosmetics.png", + "logoAlt": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustry", + "about": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustry", + "collabType": "Industry Partner", + "benefits": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndust" + }, + { + "id": "IndustryIndustryIndustryIndustryIndustryIndustryIn", + "name": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIn", + "category": "IndustryIndustryIndustryIndust", + "summary": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIn", + "logo": "/uploads/partnerships/swiss.jpg", + "logoAlt": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustry", + "about": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustry", + "collabType": "IndustryIndustryIndustryIndustryIndustry", + "benefits": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndust" + }, + { + "id": "IndustryIndustryIndustryIndustryIndustryIndustryIn", + "name": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIn", + "category": "IndustryIndustryIndustryIndust", + "summary": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIn", + "logo": "/uploads/partnerships/uldp.jpg", + "logoAlt": "Université Libérale de Paris logo", + "about": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustry", + "collabType": "IndustryIndustryIndustryIndustryIndustry", + "benefits": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndust" + }, + { + "id": "IndustryIndustryIndustryIndustryIndustryIndustryIn", + "name": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIn", + "category": "IndustryIndustryIndustryIndust", + "summary": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIn", + "logo": "/uploads/partnerships/ENG_main_2022-05-20-070029_kstp.jpg", + "logoAlt": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustry", + "about": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustry", + "collabType": "IndustryIndustryIndustryIndustryIndustry", + "benefits": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndust" + }, + { + "id": "IndustryIndustryIndustryIndustryIndustryIndustryIn", + "name": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIn", + "category": "IndustryIndustryIndustryIndust", + "summary": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIn", + "logo": "/uploads/partnerships/horizons.jpg", + "logoAlt": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustry", + "about": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustry", + "collabType": "IndustryIndustryIndustryIndustryIndustry", + "benefits": "IndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryInIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndustryIndust" + } + ] + }, + "cta": { + "heading": "Join the ecosystem", + "description": "Partner with London Academy of Management and Sciences to build talent pipelines, collaborate on research, and shape the next generation of leaders.Partner with London Academy of Management and Sciences to build talent p", + "buttonLabel": "Become a partnerBecome a partnerBecome a" + }, + "inquiryForm": { + "title": "Partnership InquiryPartnership InquiryPartnership InquiryPar", + "fields": [ + { + "id": "firstName", + "label": "Partnership InquiryPartnership", + "placeholder": "Partnership InquiryPartnership InquiryPa", + "type": "text", + "width": "half", + "required": false, + "options": [] + }, + { + "id": "lastName", + "label": "Partnership InquiryPartnership", + "placeholder": "Partnership InquiryPartnership InquiryPa", + "type": "text", + "width": "half", + "required": true, + "options": [] + }, + { + "id": "organization", + "label": "Partnership InquiryPartnership InquiryPa", + "placeholder": "Partnership InquiryPartnership InquiryPartnership InquiryPar", + "type": "text", + "width": "full", + "required": true, + "options": [] + }, + { + "id": "partnershipType", + "label": "Partnership InquiryPartnership InquiryPa", + "placeholder": "", + "type": "select", + "width": "full", + "required": true, + "options": [ + "Partnership InquiryPartnership InquiryPartnership ", + "Partnership InquiryPartnership InquiryPartnership ", + "Partnership InquiryPartnership InquiryPartnership ", + "Partnership InquiryPartnership InquiryPartnership " + ] + }, + { + "id": "message", + "label": "Partnership InquiryPartnership", + "placeholder": "Partnership InquiryPartnership InquiryPartnership InquiryPartnership InquiryPart", + "type": "textarea", + "width": "full", + "required": true, + "options": [] + } + ] + } +} diff --git a/data/policies.json b/data/policies.json new file mode 100644 index 0000000..e848f85 --- /dev/null +++ b/data/policies.json @@ -0,0 +1,334 @@ +{ + "hero": { + "badge": "Policies", + "icon": "fa-scale-balanced", + "titlePrefix": "Our Commitment to", + "titleHighlight": "Transparency", + "description": "Review our policies, terms of service, and commitments to privacy and accessibility. We believe in clear, straightforward communication with our academic community.", + "lastUpdated": "Last updated: April 22, 2026" + }, + "sidebar": { + "heading": "Policies", + "helperText": "Need clarification on a policy?", + "contactLabel": "Contact Policy Team", + "contactHref": "/contact" + }, + "policies": [ + { + "id": "privacy", + "navLabel": "Privacy Policy", + "title": "Privacy Policy", + "effectiveDate": "Effective Date: September 15, 2025", + "intro": "At LAMS, we are committed to protecting your privacy and ensuring the security of your personal information. This Privacy Policy outlines how we collect, use, and safeguard the data of our students, applicants, and website visitors.", + "content": { + "blocks": [ + { + "id": "1-information-we-collect-qa-20260422-041603", + "type": "heading", + "level": 2, + "html": "1. Information We Collect QA 20260422 041603" + }, + { + "id": "1-information-we-collect-qa-20260422-041603-intro", + "type": "paragraph", + "html": "

We collect information directly from students and applicants. Validation marker QA 20260422 041603.

" + }, + { + "id": "block-1776821411652-j34gz", + "type": "quote", + "html": "

Quote QA 20260422 0127

", + "caption": "QA Source" + }, + { + "id": "1-information-we-collect-qa-20260422-041603-2", + "type": "list", + "style": "unordered", + "items": [ + { + "id": "personal-identification-information-such-as-name-address-email-address-phone-number-date-of-birth-and-government-issued-id-numbers-where-required", + "html": "

Personal identification information such as name, address, email address, phone number, date of birth, and government-issued ID numbers where required.

" + }, + { + "id": "financial-information-such-as-payment-details-financial-aid-applications-and-billing-history", + "html": "

Financial information such as payment details, financial aid applications, and billing history.

" + }, + { + "id": "audit-ready-retention-notice-qa-20260422-041603", + "html": "

Audit-ready retention notice QA 20260422 041603

" + } + ] + }, + { + "id": "3-data-sharing-and-third-parties", + "type": "heading", + "level": 2, + "html": "3. Data Sharing and Third Parties" + }, + { + "id": "we-do-not-sell-your-personal-information-we-may-share-your-data-with-trusted-third-party-service-providers-who-assist-us-in-operating-our-university-including-learning-management-systems-and-payment-processors-these-partners-are-bound-by-strict-confidentiality-agreements-for-more-details-refer-to-our-vendor-data-processing-addendum", + "type": "paragraph", + "html": "

We do not sell your personal information. We may share your data with trusted third-party service providers who assist us in operating our university, including learning management systems and payment processors. These partners are bound by strict confidentiality agreements. For more details, refer to our Vendor Data Processing Addendum.

" + }, + { + "id": "if-you-have-questions-about-this-policy-please-contact-our-data-protection-officer-at-privacy-lams-edu", + "type": "paragraph", + "html": "

If you have questions about this policy, please contact our Data Protection Officer at privacy@LAMS.edu.

" + }, + { + "id": "for-policy-navigation-see-terms-of-use-qa-20260422-041603", + "type": "paragraph", + "html": "

For policy navigation, see Terms of Use QA 20260422 041603.

" + }, + { + "id": "2-how-we-use-your-information", + "type": "heading", + "level": 2, + "html": "2. How We Use Your Information" + }, + { + "id": "2-how-we-use-your-information-intro", + "type": "paragraph", + "html": "

Your information is primarily used to provide educational services and manage your student journey. Specific uses include:

" + }, + { + "id": "2-how-we-use-your-information-2", + "type": "list", + "style": "unordered", + "items": [ + { + "id": "processing-admissions-applications-and-enrollment", + "html": "

Processing admissions applications and enrollment.

" + }, + { + "id": "delivering-course-materials-grades-and-academic-advising", + "html": "

Delivering course materials, grades, and academic advising.

" + }, + { + "id": "processing-tuition-payments-and-administering-financial-aid", + "html": "

Processing tuition payments and administering financial aid.

" + }, + { + "id": "communicating-important-university-updates-and-policy-changes", + "html": "

Communicating important university updates and policy changes.

" + } + ] + } + ] + } + }, + { + "id": "terms", + "navLabel": "Terms of Use", + "title": "Terms of Use", + "effectiveDate": "Effective Date: January 1, 2025", + "intro": "Welcome to LAMS. By accessing our website, student portal, or utilizing our educational services, you agree to be bound by these Terms of Use and our Privacy Policy.", + "content": { + "blocks": [ + { + "id": "1-academic-integrity", + "type": "heading", + "level": 2, + "html": "1. Academic Integrity" + }, + { + "id": "as-a-student-of-lams-you-are-expected-to-uphold-the-highest-standards-of-academic-honesty-plagiarism-cheating-and-the-unauthorized-sharing-of-course-materials-are-strictly-prohibited-and-may-result-in-disciplinary-action", + "type": "paragraph", + "html": "

As a student of LAMS, you are expected to uphold the highest standards of academic honesty. Plagiarism, cheating, and the unauthorized sharing of course materials are strictly prohibited and may result in disciplinary action.

" + }, + { + "id": "2-account-security", + "type": "heading", + "level": 2, + "html": "2. Account Security" + }, + { + "id": "you-are-responsible-for-maintaining-the-confidentiality-of-your-student-portal-credentials-you-must-immediately-notify-the-it-helpdesk-of-any-unauthorized-use-of-your-account", + "type": "paragraph", + "html": "

You are responsible for maintaining the confidentiality of your student portal credentials. You must immediately notify the IT Helpdesk of any unauthorized use of your account.

" + }, + { + "id": "course-materials", + "type": "callout", + "tone": "info", + "title": "Course Materials", + "icon": "fa-book-open", + "html": "

All course content provided via the learning management system is the intellectual property of LAMS or its licensors. It is for personal educational use only.

" + }, + { + "id": "subscription-terms", + "type": "callout", + "tone": "info", + "title": "Subscription Terms", + "icon": "fa-credit-card", + "html": "

Monthly subscriptions automatically renew unless canceled prior to the billing cycle. See the Financial Policies for refund criteria.

Financial Policies

" + } + ] + } + }, + { + "id": "accessibility", + "navLabel": "Accessibility Statement", + "title": "Accessibility Statement", + "effectiveDate": "Effective Date: September 15, 2025", + "intro": "LAMS is committed to providing digital learning experiences that are accessible to all students, applicants, faculty, and visitors.", + "content": { + "blocks": [ + { + "id": "1-our-accessibility-commitments", + "type": "heading", + "level": 2, + "html": "1. Our Accessibility Commitments" + }, + { + "id": "1-our-accessibility-commitments-2", + "type": "list", + "style": "unordered", + "items": [ + { + "id": "we-design-learning-materials-and-digital-services-with-accessibility-in-mind", + "html": "

We design learning materials and digital services with accessibility in mind.

" + }, + { + "id": "we-review-core-student-journeys-for-keyboard-access-screen-reader-support-and-readable-contrast", + "html": "

We review core student journeys for keyboard access, screen reader support, and readable contrast.

" + }, + { + "id": "we-provide-reasonable-accommodations-through-our-student-support-and-advising-teams", + "html": "

We provide reasonable accommodations through our student support and advising teams.

" + } + ] + }, + { + "id": "2-requesting-support", + "type": "heading", + "level": 2, + "html": "2. Requesting Support" + }, + { + "id": "if-you-encounter-an-accessibility-barrier-contact-our-support-team-so-we-can-review-the-issue-and-provide-an-appropriate-path-forward", + "type": "paragraph", + "html": "

If you encounter an accessibility barrier, contact our support team so we can review the issue and provide an appropriate path forward.

" + } + ] + } + }, + { + "id": "cookies", + "navLabel": "Cookie Preferences", + "title": "Cookie Preferences", + "effectiveDate": "Effective Date: September 15, 2025", + "intro": "We use cookies and similar technologies to operate our website, understand usage patterns, and improve the student experience.", + "content": { + "blocks": [ + { + "id": "1-cookie-categories", + "type": "heading", + "level": 2, + "html": "1. Cookie Categories" + }, + { + "id": "1-cookie-categories-2", + "type": "list", + "style": "unordered", + "items": [ + { + "id": "essential-cookies-keep-core-services-such-as-authentication-and-security-running", + "html": "

Essential cookies keep core services such as authentication and security running.

" + }, + { + "id": "analytics-cookies-help-us-understand-aggregate-site-usage-and-improve-content", + "html": "

Analytics cookies help us understand aggregate site usage and improve content.

" + }, + { + "id": "preference-cookies-remember-non-sensitive-choices-such-as-language-and-display-settings", + "html": "

Preference cookies remember non-sensitive choices such as language and display settings.

" + } + ] + }, + { + "id": "2-managing-preferences", + "type": "heading", + "level": 2, + "html": "2. Managing Preferences" + }, + { + "id": "you-can-manage-cookies-through-your-browser-settings-some-essential-cookies-cannot-be-disabled-because-they-are-required-for-secure-access-to-student-services", + "type": "paragraph", + "html": "

You can manage cookies through your browser settings. Some essential cookies cannot be disabled because they are required for secure access to student services.

" + } + ] + } + }, + { + "navLabel": "hehehehehehehehehehehehehehehehehehehehe", + "title": "hehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehe", + "effectiveDate": "Effective Date: April 22, 2026", + "intro": "hehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehe", + "id": "hehehe", + "content": { + "blocks": [ + { + "id": "block-1776828969787-k3scn", + "type": "heading", + "level": 1, + "html": "

hehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehe

" + }, + { + "id": "block-1776828970153-r5lpx", + "type": "paragraph", + "html": "

Paragraph persist QA 2.

" + }, + { + "id": "block-1776828972201-p2bgf", + "type": "list", + "style": "ordered", + "items": [ + { + "id": "block-1776828972201-p2bgf-item-1", + "html": "

Item A2

" + }, + { + "id": "block-1776828972201-p2bgf-item-2", + "html": "

hehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehe

" + } + ] + }, + { + "id": "block-1776828974269-s4z7m", + "type": "quote", + "html": "

hehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehe

", + "caption": "Persist Source 2" + }, + { + "id": "block-1776828976335-unxd1", + "type": "callout", + "tone": "success", + "title": "Callout Persist 2", + "icon": "fa-circle-check", + "html": "

hehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehe

" + }, + { + "id": "block-1776828978384-r45ps", + "type": "divider" + }, + { + "id": "block-1776829917567-zycm5", + "type": "callout", + "tone": "success", + "title": "Callout save repro", + "icon": "fa-c", + "html": "

hehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehe

" + }, + { + "id": "block-1776829967348-g03qc", + "type": "callout", + "tone": "warning", + "title": "Callout save fixed", + "icon": "fa-envelope", + "html": "

Callout body fixed persist

" + } + ] + } + } + ] +} \ No newline at end of file diff --git a/models/_createSingletonPageModel.js b/models/_createSingletonPageModel.js new file mode 100644 index 0000000..dd5f920 --- /dev/null +++ b/models/_createSingletonPageModel.js @@ -0,0 +1,28 @@ +const mongoose = require("mongoose"); +const jsonHelper = require("../utils/jsonHelper"); + +function createSingletonPageModel(modelName, collectionName, dataFileName) { + const schema = new mongoose.Schema( + {}, + { + strict: false, + timestamps: true, + collection: collectionName, + }, + ); + + schema.statics.getSingle = async function getSingle() { + let doc = await this.findOne(); + + if (!doc) { + const defaultData = jsonHelper.readJsonFile(dataFileName) || {}; + doc = await this.create(defaultData); + } + + return doc; + }; + + return mongoose.model(modelName, schema); +} + +module.exports = createSingletonPageModel; diff --git a/models/accreditationPage.js b/models/accreditationPage.js new file mode 100644 index 0000000..76cd648 --- /dev/null +++ b/models/accreditationPage.js @@ -0,0 +1,7 @@ +const createSingletonPageModel = require("./_createSingletonPageModel"); + +module.exports = createSingletonPageModel( + "AccreditationPage", + "accreditation_pages", + "accreditation", +); diff --git a/models/admissionsPage.js b/models/admissionsPage.js new file mode 100644 index 0000000..d0634b3 --- /dev/null +++ b/models/admissionsPage.js @@ -0,0 +1,7 @@ +const createSingletonPageModel = require("./_createSingletonPageModel"); + +module.exports = createSingletonPageModel( + "AdmissionsPage", + "admissions_pages", + "admissions", +); diff --git a/models/historyPage.js b/models/historyPage.js new file mode 100644 index 0000000..8d56d22 --- /dev/null +++ b/models/historyPage.js @@ -0,0 +1,7 @@ +const createSingletonPageModel = require("./_createSingletonPageModel"); + +module.exports = createSingletonPageModel( + "HistoryPage", + "history_pages", + "history", +); diff --git a/models/partnerships.js b/models/partnerships.js new file mode 100644 index 0000000..470202f --- /dev/null +++ b/models/partnerships.js @@ -0,0 +1,7 @@ +const createSingletonPageModel = require("./_createSingletonPageModel"); + +module.exports = createSingletonPageModel( + "PartnershipsPage", + "partnerships_pages", + "partnerships", +); diff --git a/models/policiesPage.js b/models/policiesPage.js new file mode 100644 index 0000000..07c9f0a --- /dev/null +++ b/models/policiesPage.js @@ -0,0 +1,7 @@ +const createSingletonPageModel = require("./_createSingletonPageModel"); + +module.exports = createSingletonPageModel( + "PoliciesPage", + "policies_pages", + "policies", +); diff --git a/public/js/page-content-editor.js b/public/js/page-content-editor.js new file mode 100644 index 0000000..d4ce3a2 --- /dev/null +++ b/public/js/page-content-editor.js @@ -0,0 +1,871 @@ +(function () { + const config = window.pageEditorConfig; + const initialData = window.pageEditorData; + const backendUrl = (window.pageEditorBackendUrl || "").replace(/\/$/, ""); + const form = document.getElementById("pageContentForm"); + const pageJsonInput = document.getElementById("pageJson"); + const activeTabInput = document.getElementById("activeTabInput"); + + if (!config || !initialData || !form || !pageJsonInput || !activeTabInput) { + return; + } + + const state = JSON.parse(JSON.stringify(initialData)); + const iconOptions = Array.from( + new Set( + (config.tabs || []) + .flatMap((tab) => collectIcons(tab.schema)) + .filter(Boolean), + ), + ); + + ensureIconDatalist(iconOptions); + renderAllSections(); + + document.querySelectorAll("[data-tab-key]").forEach((tabTrigger) => { + tabTrigger.addEventListener("shown.bs.tab", function () { + const tabKey = this.dataset.tabKey; + + if (!tabKey) { + return; + } + + activeTabInput.value = tabKey; + updateTabUrl(tabKey); + }); + }); + + form.addEventListener("submit", function () { + pageJsonInput.value = JSON.stringify(state); + }); + + form.addEventListener("reset", function () { + window.setTimeout(function () { + Object.keys(state).forEach((key) => delete state[key]); + Object.assign(state, JSON.parse(JSON.stringify(initialData))); + renderAllSections(); + }, 0); + }); + + function renderAllSections() { + config.tabs.forEach((tab) => renderSection(tab.key)); + } + + function updateTabUrl(tabKey) { + const url = new URL(window.location.href); + url.searchParams.set("tab", tabKey); + window.history.replaceState( + {}, + "", + `${url.pathname}?${url.searchParams.toString()}${url.hash}`, + ); + } + + function renderSection(tabKey) { + const tab = config.tabs.find((item) => item.key === tabKey); + const container = document.querySelector( + `.page-editor-section[data-section-key="${tabKey}"]`, + ); + + if (!tab || !container) return; + + container.innerHTML = ""; + renderField(tab.schema, container, state, tab.schema.key, tabKey, { + path: tab.schema.key, + root: state, + item: null, + }); + } + + function renderField(schema, container, parent, key, tabKey, context) { + if (schema.visibleWhen && !passesVisibility(schema.visibleWhen, parent, context)) { + return; + } + + if (schema.type === "object") { + if (!isObject(parent[key])) { + parent[key] = {}; + } + + const groupWrapper = document.createElement("div"); + groupWrapper.className = "row g-3"; + container.appendChild(groupWrapper); + + (schema.fields || []).forEach((field) => { + renderField(field, groupWrapper, parent[key], field.key, tabKey, { + path: appendPath(context.path, field.key), + root: context.root, + item: parent[key], + }); + }); + return; + } + + if (schema.type === "array") { + if (!Array.isArray(parent[key])) { + parent[key] = []; + } + + applyAutoSequenceToArray(schema, parent[key]); + + const col = createCol(schema.colClass || "col-12"); + const card = document.createElement("div"); + card.className = "border rounded-3 bg-light-subtle p-3"; + + const header = document.createElement("div"); + header.className = "d-flex justify-content-between align-items-center mb-3 gap-3"; + header.innerHTML = ` +
+ + ${schema.helpText ? `
${escapeHtml(schema.helpText)}
` : ""} +
+ + `; + + header.querySelector("button").addEventListener("click", function () { + parent[key].push(createDefaultValue(schema.itemSchema)); + applyAutoSequenceToArray(schema, parent[key]); + renderSection(tabKey); + }); + + card.appendChild(header); + + if (parent[key].length === 0) { + const empty = document.createElement("div"); + empty.className = "text-muted small"; + empty.textContent = schema.emptyText || `No ${schema.itemLabel || "items"} yet.`; + card.appendChild(empty); + } else { + const list = document.createElement("div"); + list.className = "page-editor-array-list"; + card.appendChild(list); + + parent[key].forEach((item, index) => { + const itemCard = document.createElement("div"); + itemCard.className = "card shadow-sm border-0 mb-3"; + itemCard.dataset.index = String(index); + + const itemHeader = document.createElement("div"); + itemHeader.className = "card-header bg-white d-flex justify-content-between align-items-center gap-2 flex-wrap"; + + const title = getArrayItemTitle(schema, item, index); + const subtitle = getArrayItemSubtitle(schema, item); + itemHeader.innerHTML = ` +
+ ${ + schema.sortable + ? '' + : "" + } +
+
${escapeHtml(title)}
+ ${subtitle ? `
${escapeHtml(subtitle)}
` : ""} +
+
+
+ ${renderItemActions(schema.itemActions, item)} + +
+ `; + + itemHeader + .querySelector('[data-remove-item="true"]') + .addEventListener("click", function () { + parent[key].splice(index, 1); + applyAutoSequenceToArray(schema, parent[key]); + renderSection(tabKey); + }); + + itemHeader.querySelectorAll("[data-item-href]").forEach((actionButton) => { + actionButton.addEventListener("click", function () { + window.location.href = actionButton.dataset.itemHref; + }); + }); + + const itemBody = document.createElement("div"); + itemBody.className = "card-body"; + + if (schema.itemSchema.type === "primitive") { + renderPrimitiveArrayItem(schema, itemBody, parent[key], index, tabKey, context); + } else if (schema.itemSchema.type === "variant") { + renderVariantArrayItem( + schema.itemSchema, + itemBody, + parent[key], + index, + tabKey, + { + path: appendPath(context.path, String(index)), + root: context.root, + item: parent[key][index], + }, + ); + } else { + const bodyRow = document.createElement("div"); + bodyRow.className = "row g-3"; + itemBody.appendChild(bodyRow); + + (schema.itemSchema.fields || []).forEach((field) => { + renderField(field, bodyRow, parent[key][index], field.key, tabKey, { + path: appendPath(context.path, `${index}.${field.key}`), + root: context.root, + item: parent[key][index], + }); + }); + } + + itemCard.appendChild(itemHeader); + itemCard.appendChild(itemBody); + list.appendChild(itemCard); + }); + + if (schema.sortable && window.Sortable) { + window.Sortable.create(list, { + animation: 150, + handle: ".drag-handle", + onEnd: function (event) { + if ( + typeof event.oldIndex !== "number" || + typeof event.newIndex !== "number" || + event.oldIndex === event.newIndex + ) { + return; + } + + const movedItem = parent[key].splice(event.oldIndex, 1)[0]; + parent[key].splice(event.newIndex, 0, movedItem); + applyAutoSequenceToArray(schema, parent[key]); + renderSection(tabKey); + }, + }); + } + } + + col.appendChild(card); + container.appendChild(col); + return; + } + + if (schema.type === "checkbox") { + renderCheckbox(schema, container, parent, key); + return; + } + + renderLeafField(schema, container, parent, key, context); + } + + function renderPrimitiveArrayItem(arraySchema, container, targetArray, index, tabKey, context) { + const fieldSchema = arraySchema.itemSchema; + const row = document.createElement("div"); + row.className = "row g-3"; + container.appendChild(row); + + const holder = { value: targetArray[index] || "" }; + renderLeafField( + { + key: "value", + label: fieldSchema.label || arraySchema.itemLabel || "Value", + type: fieldSchema.fieldType || "text", + maxLength: fieldSchema.maxLength, + placeholder: fieldSchema.placeholder, + helpText: fieldSchema.helpText, + rows: fieldSchema.fieldType === "textarea" ? 3 : undefined, + }, + row, + holder, + "value", + { + path: appendPath(context.path, String(index)), + root: context.root, + item: holder, + }, + ); + + const input = row.querySelector("input, textarea, select"); + if (input) { + const sync = function () { + targetArray[index] = + fieldSchema.fieldType === "number" ? Number(holder.value || 0) : holder.value; + }; + input.addEventListener("input", sync); + input.addEventListener("change", sync); + } + } + + function renderVariantArrayItem(variantSchema, container, targetArray, index, tabKey, context) { + const item = targetArray[index]; + if (!isObject(item)) { + targetArray[index] = {}; + } + + const currentType = + targetArray[index][variantSchema.discriminator] || + variantSchema.options[0].value; + targetArray[index][variantSchema.discriminator] = currentType; + + const currentVariant = variantSchema.variants[currentType]; + + const typeRow = document.createElement("div"); + typeRow.className = "row g-3 mb-2"; + container.appendChild(typeRow); + + renderLeafField( + { + key: variantSchema.discriminator, + label: "Section type", + type: "select", + options: variantSchema.options, + }, + typeRow, + targetArray[index], + variantSchema.discriminator, + context, + ); + + const selectInput = typeRow.querySelector("select"); + if (selectInput) { + selectInput.addEventListener("change", function () { + const newType = this.value; + targetArray[index] = { type: newType }; + renderSection(tabKey); + }); + } + + if (currentVariant && currentVariant.schema) { + const sectionRow = document.createElement("div"); + sectionRow.className = "row g-3"; + container.appendChild(sectionRow); + + (currentVariant.schema.fields || []).forEach((field) => { + renderField(field, sectionRow, targetArray[index], field.key, tabKey, { + path: appendPath(context.path, field.key), + root: context.root, + item: targetArray[index], + }); + }); + } + } + + function renderLeafField(schema, container, parent, key, context) { + if (schema.type === "hidden") { + if (typeof parent[key] === "undefined" || parent[key] === null) { + parent[key] = schema.defaultValue || ""; + } + return; + } + + if (typeof parent[key] === "undefined" || parent[key] === null) { + parent[key] = schema.type === "number" ? 0 : ""; + } + + const col = createCol(schema.colClass || inferColClass(schema.type)); + const label = document.createElement("label"); + label.className = "form-label fw-semibold"; + label.textContent = schema.label || key; + col.appendChild(label); + + if (schema.type === "textarea") { + const textarea = document.createElement("textarea"); + textarea.className = "form-control"; + textarea.rows = schema.rows || 4; + textarea.value = parent[key] || ""; + if (schema.placeholder) textarea.placeholder = schema.placeholder; + if (schema.maxLength) textarea.maxLength = schema.maxLength; + textarea.addEventListener("input", function () { + parent[key] = textarea.value; + updateCounter(counter, textarea.value.length, schema.maxLength); + }); + col.appendChild(textarea); + const counter = appendHelp(col, schema, parent[key]); + container.appendChild(col); + return; + } + + if (schema.type === "image") { + const group = document.createElement("div"); + group.className = "input-group"; + + const input = document.createElement("input"); + input.type = "text"; + input.className = "form-control"; + input.value = parent[key] || ""; + input.addEventListener("input", function () { + parent[key] = input.value; + preview.src = resolveImageUrl(input.value); + preview.classList.toggle("d-none", !input.value); + }); + + const button = document.createElement("button"); + button.type = "button"; + button.className = "btn btn-outline-primary"; + button.innerHTML = 'Upload'; + button.addEventListener("click", function () { + openImagePicker(schema.imageType || config.imageType, function (path) { + parent[key] = path; + input.value = path; + preview.src = resolveImageUrl(path); + preview.classList.toggle("d-none", !path); + }); + }); + + group.appendChild(input); + group.appendChild(button); + col.appendChild(group); + + const preview = document.createElement("img"); + preview.className = "img-thumbnail uploaded-preview mt-2"; + preview.style.maxHeight = "200px"; + preview.src = resolveImageUrl(parent[key]); + preview.classList.toggle("d-none", !parent[key]); + col.appendChild(preview); + + appendHelp(col, schema, parent[key], schema.imageHint); + container.appendChild(col); + return; + } + + if (schema.type === "icon") { + renderIconField(schema, col, parent, key); + container.appendChild(col); + return; + } + + if (schema.type === "select") { + const input = document.createElement("select"); + input.className = "form-select"; + const options = resolveOptions(schema, context.root); + options.forEach((option) => { + const optionEl = document.createElement("option"); + if (typeof option === "string") { + optionEl.value = option; + optionEl.textContent = option; + } else { + optionEl.value = option.value; + optionEl.textContent = option.label; + } + input.appendChild(optionEl); + }); + input.value = parent[key] || input.options[0]?.value || ""; + parent[key] = input.value; + input.addEventListener("change", function () { + parent[key] = input.value; + renderAllSections(); + }); + col.appendChild(input); + appendHelp(col, schema, parent[key]); + container.appendChild(col); + return; + } + + if (schema.type === "combobox") { + const input = document.createElement("input"); + const listId = `list-${sanitizeId(context.path)}-${sanitizeId(key)}`; + input.className = "form-control"; + input.type = "text"; + input.value = parent[key] || ""; + if (schema.placeholder) input.placeholder = schema.placeholder; + if (schema.maxLength) input.maxLength = schema.maxLength; + input.setAttribute("list", listId); + input.addEventListener("input", function () { + parent[key] = input.value; + updateCounter(counter, input.value.length, schema.maxLength); + }); + + const dataList = document.createElement("datalist"); + dataList.id = listId; + resolveOptions(schema, context.root).forEach((option) => { + const item = document.createElement("option"); + item.value = typeof option === "string" ? option : option.value; + item.label = typeof option === "string" ? option : option.label; + dataList.appendChild(item); + }); + + col.appendChild(input); + col.appendChild(dataList); + const counter = appendHelp(col, schema, parent[key]); + container.appendChild(col); + return; + } + + const input = document.createElement("input"); + input.className = "form-control"; + input.type = + schema.type === "number" || schema.type === "color" ? schema.type : "text"; + input.value = parent[key] || ""; + if (schema.placeholder) input.placeholder = schema.placeholder; + if (schema.maxLength) input.maxLength = schema.maxLength; + if (schema.step) input.step = schema.step; + input.addEventListener("input", function () { + parent[key] = schema.type === "number" ? Number(input.value || 0) : input.value; + updateCounter(counter, String(input.value || "").length, schema.maxLength); + }); + + col.appendChild(input); + const counter = appendHelp(col, schema, parent[key]); + container.appendChild(col); + } + + function renderIconField(schema, col, parent, key) { + const selected = parent[key] || ""; + const wrapper = document.createElement("div"); + wrapper.className = "border rounded-3 bg-white p-3"; + + const top = document.createElement("div"); + top.className = "d-flex gap-2 align-items-center mb-3"; + + const input = document.createElement("input"); + input.type = "text"; + input.className = "form-control"; + input.value = selected; + input.placeholder = "fa-shield-check"; + input.setAttribute("list", "cms-icon-options"); + top.appendChild(input); + + const preview = document.createElement("div"); + preview.className = "border rounded-2 px-3 d-flex align-items-center justify-content-center"; + preview.style.width = "52px"; + preview.innerHTML = selected + ? `` + : '--'; + top.appendChild(preview); + wrapper.appendChild(top); + + const grid = document.createElement("div"); + grid.className = "d-flex flex-wrap gap-2"; + (schema.options || []).forEach((option) => { + const button = document.createElement("button"); + button.type = "button"; + button.className = `btn btn-sm ${selected === option ? "btn-primary" : "btn-outline-secondary"}`; + button.innerHTML = `${escapeHtml(option)}`; + button.addEventListener("click", function () { + parent[key] = option; + input.value = option; + preview.innerHTML = ``; + renderAllSections(); + }); + grid.appendChild(button); + }); + wrapper.appendChild(grid); + + input.addEventListener("input", function () { + parent[key] = input.value; + preview.innerHTML = input.value + ? `` + : '--'; + }); + + col.appendChild(wrapper); + appendHelp(col, schema, parent[key]); + } + + function renderCheckbox(schema, container, parent, key) { + if (typeof parent[key] !== "boolean") { + parent[key] = Boolean(parent[key]); + } + + const col = createCol(schema.colClass || "col-12"); + const wrapper = document.createElement("div"); + wrapper.className = "form-check mt-4"; + + const input = document.createElement("input"); + input.type = "checkbox"; + input.className = "form-check-input"; + input.checked = parent[key]; + input.addEventListener("change", function () { + parent[key] = input.checked; + }); + + const label = document.createElement("label"); + label.className = "form-check-label fw-semibold"; + label.textContent = schema.label || key; + + wrapper.appendChild(input); + wrapper.appendChild(label); + col.appendChild(wrapper); + if (schema.helpText) { + const help = document.createElement("div"); + help.className = "form-text"; + help.textContent = schema.helpText; + col.appendChild(help); + } + container.appendChild(col); + } + + function appendHelp(col, schema, value, extraHint) { + const wrapper = document.createElement("div"); + wrapper.className = "d-flex justify-content-between gap-3"; + + const help = document.createElement("div"); + help.className = "form-text"; + help.textContent = [schema.helpText, extraHint].filter(Boolean).join(" "); + wrapper.appendChild(help); + + let counter = null; + if (schema.maxLength) { + counter = document.createElement("div"); + counter.className = "form-text text-end ms-auto"; + updateCounter(counter, String(value || "").length, schema.maxLength); + wrapper.appendChild(counter); + } + + if (help.textContent || counter) { + col.appendChild(wrapper); + } + + return counter; + } + + function updateCounter(counter, currentLength, maxLength) { + if (!counter || !maxLength) return; + counter.textContent = `${currentLength}/${maxLength}`; + } + + function openImagePicker(imageType, onSuccess) { + const fileInput = document.createElement("input"); + fileInput.type = "file"; + fileInput.accept = "image/*"; + fileInput.style.display = "none"; + document.body.appendChild(fileInput); + + fileInput.addEventListener("change", async function () { + if (!fileInput.files || !fileInput.files[0]) { + fileInput.remove(); + return; + } + + try { + const formData = new FormData(); + formData.append("image", fileInput.files[0]); + + const response = await fetch( + `/admin/upload/image?imageType=${encodeURIComponent(imageType)}`, + { + method: "POST", + body: formData, + }, + ); + const result = await response.json(); + + if (!result.success || !result.path) { + throw new Error(result.error || "Upload failed"); + } + + onSuccess(result.path); + showToast("Success", "Image uploaded successfully", "success"); + } catch (error) { + showToast("Error", error.message || "Upload failed", "danger"); + } finally { + fileInput.remove(); + } + }); + + fileInput.click(); + } + + function showToast(title, message, type) { + const container = + document.querySelector(".toast-container") || createToastContainer(); + const toast = document.createElement("div"); + toast.className = `toast align-items-center text-white bg-${type || "info"} border-0`; + toast.setAttribute("role", "alert"); + toast.innerHTML = `
${escapeHtml( + title, + )}: ${escapeHtml(message)}
`; + container.appendChild(toast); + new bootstrap.Toast(toast, { autohide: true, delay: 3000 }).show(); + toast.addEventListener("hidden.bs.toast", function () { + toast.remove(); + }); + } + + function createToastContainer() { + const container = document.createElement("div"); + container.className = "toast-container position-fixed top-0 end-0 p-3"; + document.body.appendChild(container); + return container; + } + + function createDefaultValue(schema) { + if (!schema) return ""; + if (schema.type === "primitive") return schema.fieldType === "number" ? 0 : ""; + if (schema.type === "variant") { + return { [schema.discriminator]: schema.options[0].value }; + } + if (schema.type === "object") { + const value = {}; + (schema.fields || []).forEach((field) => { + if (field.type === "array") value[field.key] = []; + else if (field.type === "object") value[field.key] = createDefaultValue(field); + else if (field.type === "checkbox") value[field.key] = false; + else if (field.type === "number") value[field.key] = 0; + else value[field.key] = field.defaultValue || ""; + }); + return value; + } + return ""; + } + + function createCol(colClass) { + const div = document.createElement("div"); + div.className = colClass; + return div; + } + + function inferColClass(type) { + if (type === "textarea" || type === "image" || type === "icon") return "col-12"; + if (type === "checkbox") return "col-12"; + return "col-md-6"; + } + + function resolveImageUrl(path) { + if (!path) return ""; + if (/^https?:\/\//i.test(path)) return path; + if (path.startsWith("/")) return `${backendUrl}${path}`; + return `${backendUrl}/${path}`; + } + + function resolveOptions(schema, root) { + if (schema.optionsPath) { + const value = getValueByPath(root, schema.optionsPath); + return Array.isArray(value) ? value : []; + } + return schema.options || []; + } + + function collectIcons(schema) { + if (!schema) return []; + if (schema.type === "icon") return schema.options || []; + if (schema.type === "object") return (schema.fields || []).flatMap(collectIcons); + if (schema.type === "array") return collectIcons(schema.itemSchema); + if (schema.type === "variant") { + return Object.values(schema.variants || {}).flatMap((variant) => + collectIcons(variant.schema), + ); + } + return []; + } + + function ensureIconDatalist(options) { + const existing = document.getElementById("cms-icon-options"); + if (existing) existing.remove(); + + const dataList = document.createElement("datalist"); + dataList.id = "cms-icon-options"; + options.forEach((option) => { + const item = document.createElement("option"); + item.value = option; + dataList.appendChild(item); + }); + document.body.appendChild(dataList); + } + + function applyAutoSequenceToArray(schema, targetArray) { + if (!schema || !Array.isArray(targetArray) || schema.itemSchema.type !== "object") { + return; + } + + (schema.itemSchema.fields || []).forEach((field) => { + if (field.type !== "hidden" || !field.autoSequence) { + return; + } + + targetArray.forEach((item, index) => { + const value = String(index + 1); + const padLength = field.autoSequence.padLength || 0; + item[field.key] = padLength > 0 ? value.padStart(padLength, "0") : value; + }); + }); + } + + function getArrayItemTitle(schema, item, index) { + const value = + item && schema.itemTitleKey && typeof item[schema.itemTitleKey] !== "undefined" + ? item[schema.itemTitleKey] + : null; + + return value || `${schema.itemLabel || "Item"} ${index + 1}`; + } + + function getArrayItemSubtitle(schema, item) { + if (!item || !schema.itemSubtitleKey) return ""; + return item[schema.itemSubtitleKey] || ""; + } + + function renderItemActions(actions, item) { + if (!Array.isArray(actions) || !actions.length || !item) { + return ""; + } + + return actions + .map((action) => { + const href = fillTemplate(action.hrefTemplate, item); + if (!href) return ""; + return ``; + }) + .join(""); + } + + function passesVisibility(condition, parent, context) { + if (!condition || !condition.path) return true; + const target = + condition.path === "$item" + ? context.item + : getValueByPath(parent, condition.path) ?? + getValueByPath(context.item, condition.path) ?? + getValueByPath(context.root, condition.path); + + if (Array.isArray(condition.equals)) { + return condition.equals.includes(target); + } + + return target === condition.equals; + } + + function appendPath(basePath, segment) { + return basePath ? `${basePath}.${segment}` : segment; + } + + function getValueByPath(target, path) { + if (!target || !path) return undefined; + return String(path) + .split(".") + .reduce((current, segment) => { + if (current === null || typeof current === "undefined") return undefined; + return current[segment]; + }, target); + } + + function fillTemplate(template, item) { + if (!template) return ""; + return template.replace(/\{([^}]+)\}/g, function (_, key) { + return item[key] || ""; + }); + } + + function sanitizeId(value) { + return String(value || "") + .replace(/[^a-zA-Z0-9_-]+/g, "-") + .replace(/^-+|-+$/g, ""); + } + + function isObject(value) { + return Boolean(value) && typeof value === "object" && !Array.isArray(value); + } + + function escapeHtml(value) { + return String(value || "") + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); + } +})(); diff --git a/public/js/policies-block-editor.js b/public/js/policies-block-editor.js new file mode 100644 index 0000000..a00284f --- /dev/null +++ b/public/js/policies-block-editor.js @@ -0,0 +1,1353 @@ +(function () { + const root = document.getElementById("policyBlockEditor"); + const form = document.getElementById("policyBlockEditorForm"); + const pageJsonInput = document.getElementById("pageJson"); + const intentInput = document.getElementById("editorIntent"); + const blockList = document.getElementById("blockList"); + const previewContent = document.getElementById("previewContent"); + const blockTypeSelect = document.getElementById("blockTypeSelect"); + const addBlockButton = document.getElementById("addBlockButton"); + const toggleFullscreenButton = document.getElementById("toggleFullscreenButton"); + const validationBanner = document.getElementById("validationBanner"); + const validationSummary = document.getElementById("validationSummary"); + const previewDevice = document.getElementById("previewDevice"); + const dropIndicator = document.getElementById("dropIndicator"); + const floatingToolbar = document.getElementById("floatingToolbar"); + const linkPopover = document.getElementById("linkPopover"); + const slashMenu = document.getElementById("slashMenu"); + const linkUrlInput = document.getElementById("linkUrlInput"); + const linkPolicySelect = document.getElementById("linkPolicySelect"); + const saveLinkButton = document.getElementById("saveLinkButton"); + const removeLinkButton = document.getElementById("removeLinkButton"); + const data = readJsonScript("policyBlockEditorDataPayload"); + const config = readJsonScript("policyBlockEditorConfigData"); + + if (!root || !form || !pageJsonInput || !blockList || !previewContent || !data || !config) { + return; + } + + const defaultContent = { + content: { blocks: [] }, + }; + + const state = JSON.parse(JSON.stringify(data.content ? data : defaultContent)); + state.policy = data.policy; + state.content = state.content || defaultContent.content; + + const ui = { + previewMode: "desktop", + selectedBlockId: null, + targetedPreviewBlockId: null, + hoveredPreviewBlockId: null, + pendingLinkRange: null, + slashContext: null, + toolbarTarget: null, + sortable: null, + previewTargetTimer: null, + isFullscreen: false, + }; + + const stylePalette = [ + { value: "info", label: "Info" }, + { value: "warning", label: "Warning" }, + { value: "success", label: "Success" }, + ]; + const iconOptions = Array.isArray(config.iconOptions) ? config.iconOptions : []; + + bindStaticEvents(); + render(); + window.policyBlockEditorDebug = { + getState: function () { + return JSON.parse(JSON.stringify(state)); + }, + moveBlockById: function (language, blockId, newIndex) { + const blocks = getBlocks(); + const oldIndex = blocks.findIndex((block) => block.id === blockId); + if (oldIndex === -1) { + return false; + } + moveBlock(oldIndex, newIndex); + return true; + }, + }; + + function bindStaticEvents() { + root.querySelectorAll("[data-preview-mode]").forEach((button) => { + button.addEventListener("click", function () { + ui.previewMode = this.dataset.previewMode; + updatePreviewModeButtons(); + }); + }); + + addBlockButton.addEventListener("click", function () { + insertBlock(blockTypeSelect.value || "paragraph"); + }); + + if (toggleFullscreenButton) { + toggleFullscreenButton.addEventListener("click", function () { + setEditorFullscreen(!ui.isFullscreen); + }); + } + + form.querySelectorAll("[data-intent]").forEach((button) => { + button.addEventListener("click", function () { + intentInput.value = this.dataset.intent || "save"; + }); + }); + + form.addEventListener("submit", function (event) { + const validation = validateState(); + if (validation.errors.length > 0) { + event.preventDefault(); + renderValidation(validation); + showToast("Validation", "Fix the highlighted content before saving.", "danger"); + return; + } + + pageJsonInput.value = JSON.stringify({ + content: state.content, + }); + }); + + document.addEventListener("selectionchange", handleSelectionChange); + root.addEventListener( + "wheel", + function (event) { + if (!ui.isFullscreen) { + return; + } + + const interactiveTarget = event.target.closest( + ".icon-combobox-panel, .icon-combobox-options", + ); + if (interactiveTarget) { + return; + } + + root.scrollTop += event.deltaY; + event.preventDefault(); + }, + { passive: false }, + ); + document.addEventListener("click", handleGlobalClick); + document.addEventListener("keydown", function (event) { + if (event.key === "Escape") { + if (ui.isFullscreen) { + setEditorFullscreen(false); + } + hideFloatingToolbar(); + hideLinkPopover(); + hideSlashMenu(); + } + }); + + floatingToolbar.addEventListener("mousedown", function (event) { + event.preventDefault(); + }); + + floatingToolbar.addEventListener("click", function (event) { + const target = event.target.closest("[data-command]"); + if (!target) { + return; + } + + const command = target.dataset.command; + if (command === "openLink") { + openLinkPopover(); + return; + } + + if (target.matches('input[type="color"]')) { + return; + } + + applyCommand(command); + }); + + floatingToolbar.querySelectorAll('input[type="color"]').forEach((input) => { + input.addEventListener("input", function () { + applyCommand(this.dataset.command, this.value); + }); + }); + + saveLinkButton.addEventListener("click", applyLinkFromPopover); + removeLinkButton.addEventListener("click", removeCurrentLink); + + slashMenu.querySelectorAll("[data-slash-type]").forEach((button) => { + button.addEventListener("click", function () { + insertSlashCommand(this.dataset.slashType); + }); + }); + } + + function getBlocks() { + return state.content.blocks; + } + + function setBlockSelection(blockId) { + ui.selectedBlockId = blockId; + renderBlockSelection(); + renderPreviewSelection(); + } + + function render() { + hideFloatingToolbar(); + hideLinkPopover(); + hideSlashMenu(); + updatePreviewModeButtons(); + updateFullscreenToggle(); + renderBlocks(); + renderPreview(); + renderValidation(validateState()); + } + + function setEditorFullscreen(nextValue) { + ui.isFullscreen = Boolean(nextValue); + root.classList.toggle("is-editor-fullscreen", ui.isFullscreen); + document.body.classList.toggle("policy-editor-fullscreen", ui.isFullscreen); + updateFullscreenToggle(); + } + + function updateFullscreenToggle() { + if (!toggleFullscreenButton) { + return; + } + + const label = toggleFullscreenButton.querySelector('[data-role="fullscreen-label"]'); + const icon = toggleFullscreenButton.querySelector('[data-role="fullscreen-icon"]'); + toggleFullscreenButton.setAttribute("aria-pressed", ui.isFullscreen ? "true" : "false"); + toggleFullscreenButton.classList.toggle("btn-outline-secondary", !ui.isFullscreen); + toggleFullscreenButton.classList.toggle("btn-outline-primary", ui.isFullscreen); + + if (label) { + label.textContent = ui.isFullscreen ? "Exit full screen" : "Full screen edit"; + } + + if (icon) { + icon.className = `fas ${ui.isFullscreen ? "fa-compress" : "fa-expand"} me-2`; + } + } + + function updatePreviewModeButtons() { + root.querySelectorAll("[data-preview-mode]").forEach((button) => { + button.classList.toggle("is-active", button.dataset.previewMode === ui.previewMode); + }); + + previewDevice.dataset.mode = ui.previewMode; + } + + function createBlock(type) { + const id = `block-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`; + if (type === "heading") { + return { + id, + type, + level: 2, + html: "", + }; + } + + if (type === "list") { + return { + id, + type, + style: "unordered", + items: [ + { id: `${id}-item-1`, html: "" }, + { id: `${id}-item-2`, html: "" }, + ], + }; + } + + if (type === "quote") { + return { + id, + type, + html: "", + caption: "", + }; + } + + if (type === "divider") { + return { id, type }; + } + + if (type === "callout") { + return { + id, + type, + tone: "info", + title: "", + icon: "fa-circle-info", + html: "", + }; + } + + return { + id, + type: "paragraph", + html: "", + }; + } + + function insertBlock(type, index) { + const blocks = getBlocks(); + const nextBlock = createBlock(type); + const insertIndex = typeof index === "number" ? index : blocks.length; + blocks.splice(insertIndex, 0, nextBlock); + setBlockSelection(nextBlock.id); + render(); + } + + function duplicateBlock(blockId) { + const blocks = getBlocks(); + const index = blocks.findIndex((block) => block.id === blockId); + if (index === -1) { + return; + } + + const source = JSON.parse(JSON.stringify(blocks[index])); + source.id = `block-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`; + if (source.items) { + source.items = source.items.map((item, itemIndex) => ({ + ...item, + id: `${source.id}-item-${itemIndex + 1}`, + })); + } + + blocks.splice(index + 1, 0, source); + setBlockSelection(source.id); + render(); + } + + function deleteBlock(blockId) { + const blocks = getBlocks(); + const index = blocks.findIndex((block) => block.id === blockId); + if (index === -1) { + return; + } + + blocks.splice(index, 1); + if (ui.selectedBlockId === blockId) { + ui.selectedBlockId = null; + } + render(); + } + + function moveBlock(oldIndex, newIndex) { + const blocks = getBlocks(); + if ( + oldIndex === newIndex || + oldIndex < 0 || + newIndex < 0 || + oldIndex >= blocks.length || + newIndex >= blocks.length + ) { + return; + } + + const [moved] = blocks.splice(oldIndex, 1); + blocks.splice(newIndex, 0, moved); + render(); + } + + function renderBlocks() { + const blocks = getBlocks(); + blockList.innerHTML = ""; + + if (blocks.length === 0) { + const empty = document.createElement("div"); + empty.className = "text-muted border rounded-4 p-4 text-center"; + empty.innerHTML = 'No blocks yet. Add your first block to start editing.'; + blockList.appendChild(empty); + return; + } + + const validation = validateState(); + + blocks.forEach((block, index) => { + const card = document.createElement("article"); + card.className = "block-card"; + card.dataset.blockId = block.id; + card.classList.toggle( + "is-invalid", + validation.blockIssues[block.id]?.length > 0, + ); + card.classList.toggle("is-selected", ui.selectedBlockId === block.id); + + card.innerHTML = ` +
+
+
${index + 1}
+
+
${block.type}
+
${describeBlock(block)}
+
+
+
+ + + + + +
+
+
+ `; + + const body = card.querySelector(".block-body"); + renderBlockBody(block, body, index); + + card.addEventListener("click", function () { + setBlockSelection(block.id); + }); + + card.querySelector('[data-action="duplicate"]').addEventListener("click", function (event) { + event.stopPropagation(); + duplicateBlock(block.id); + }); + + card.querySelector('[data-action="target-preview"]').addEventListener("click", function (event) { + event.stopPropagation(); + focusPreviewBlock(block.id); + }); + + card.querySelector('[data-action="delete"]').addEventListener("click", function (event) { + event.stopPropagation(); + deleteBlock(block.id); + }); + + card.querySelector('[data-action="collapse"]').addEventListener("click", function (event) { + event.stopPropagation(); + card.classList.toggle("is-collapsed"); + }); + + blockList.appendChild(card); + }); + + initializeSortable(); + renderBlockSelection(); + } + + function initializeSortable() { + if (ui.sortable) { + ui.sortable.destroy(); + ui.sortable = null; + } + + if (!window.Sortable || blockList.children.length < 2) { + return; + } + + ui.sortable = window.Sortable.create(blockList, { + animation: 180, + handle: ".drag-handle", + ghostClass: "sortable-ghost", + chosenClass: "sortable-chosen", + onStart: function () { + dropIndicator.classList.remove("is-visible"); + }, + onEnd: function (event) { + if ( + typeof event.oldIndex !== "number" || + typeof event.newIndex !== "number" || + event.oldIndex === event.newIndex + ) { + return; + } + + moveBlock(event.oldIndex, event.newIndex); + }, + }); + } + + function renderBlockBody(block, body, index) { + if (block.type === "heading") { + body.innerHTML = ` +
+
+ + +
+
+ `; + const editor = createEditable(block.html, "Heading text"); + editor.dataset.blockId = block.id; + editor.dataset.field = "html"; + body.appendChild(editor); + bindEditable(editor, function (value) { + block.html = value; + }); + body.querySelector('[data-field="level"]').addEventListener("change", function () { + block.level = Number(this.value); + render(); + }); + return; + } + + if (block.type === "paragraph") { + const editor = createEditable(block.html, "Write a paragraph. Type / for commands."); + editor.dataset.blockId = block.id; + editor.dataset.field = "html"; + body.appendChild(editor); + bindEditable(editor, function (value) { + block.html = value; + }, { slashEnabled: true, blockIndex: index }); + return; + } + + if (block.type === "quote") { + body.innerHTML = ` +
+
+ + +
+
+ `; + const editor = createEditable(block.html, "Quote content"); + editor.dataset.blockId = block.id; + editor.dataset.field = "html"; + body.appendChild(editor); + bindEditable(editor, function (value) { + block.html = value; + }); + body.querySelector('[data-field="caption"]').addEventListener("input", function () { + block.caption = this.value; + renderPreview(); + renderValidation(validateState()); + }); + return; + } + + if (block.type === "divider") { + body.innerHTML = ` +
+ Divider blocks render as a semantic separator in the preview. They are useful between long content groups. +
+ `; + return; + } + + if (block.type === "callout") { + body.innerHTML = ` +
+
+ + +
+
+ +
+ + ${block.icon ? `` : ""} + + + +
+
+
+ + +
+
+ `; + const editor = createEditable(block.html, "Callout body"); + editor.dataset.blockId = block.id; + editor.dataset.field = "html"; + body.appendChild(editor); + bindEditable(editor, function (value) { + block.html = value; + }); + + initializeIconPicker(body.querySelector('[data-role="icon-picker-group"]'), block); + + body.querySelectorAll("input[data-field], select[data-field], textarea[data-field]").forEach((input) => { + const syncField = function () { + block[this.dataset.field] = this.value; + renderPreview(); + renderValidation(validateState()); + }; + input.addEventListener("input", syncField); + input.addEventListener("change", syncField); + }); + return; + } + + body.innerHTML = ` +
+
+ + +
+
+
+ + `; + + body.querySelector('[data-field="style"]').addEventListener("change", function () { + block.style = this.value; + renderPreview(); + renderValidation(validateState()); + }); + + const listItems = body.querySelector(".list-items"); + (block.items || []).forEach((item, itemIndex) => { + const row = document.createElement("div"); + row.className = "list-item"; + row.innerHTML = ` +
${itemIndex + 1}
+
+ + `; + const content = row.querySelector(".list-item-content"); + content.innerHTML = item.html || ""; + content.dataset.blockId = block.id; + content.dataset.itemId = item.id; + bindEditable(content, function (value) { + item.html = value; + }, { slashEnabled: true, blockIndex: index }); + row.querySelector("button").addEventListener("click", function () { + block.items.splice(itemIndex, 1); + render(); + }); + listItems.appendChild(row); + }); + + body.querySelector('[data-action="add-list-item"]').addEventListener("click", function () { + block.items.push({ + id: `${block.id}-item-${Date.now()}`, + html: "", + }); + render(); + }); + } + + function createEditable(html, placeholder) { + const editor = document.createElement("div"); + editor.className = "block-content"; + editor.contentEditable = "true"; + editor.spellcheck = true; + editor.dataset.placeholder = placeholder || ""; + editor.innerHTML = html || ""; + return editor; + } + + function initializeIconPicker(wrapper, block) { + if (!wrapper) { + return; + } + + const input = wrapper.querySelector('input[data-field="icon"]'); + const button = wrapper.querySelector('[data-action="pick-icon"]'); + + if (!input || !button) { + return; + } + + const syncIconValue = function (value) { + const nextValue = String(value || "").trim(); + input.value = nextValue; + input.dataset.iconPickerPreviewPrefix = resolveCalloutIconPreviewPrefix(nextValue); + block.icon = nextValue; + syncCalloutIconPreview(input); + renderPreview(); + renderValidation(validateState()); + }; + + input.addEventListener("click", function () { + openSharedIconPicker(input, syncIconValue); + }); + + button.addEventListener("click", function () { + openSharedIconPicker(input, syncIconValue); + }); + + syncIconValue(block.icon || ""); + } + + function openSharedIconPicker(input, onPicked) { + if (!window.IconPicker || typeof window.IconPicker.open !== "function") { + return; + } + + patchSharedIconPicker(); + window.__policyBlockIconPickerInput = input; + window.__policyBlockIconPickerOnPicked = onPicked; + window.IconPicker.open(input); + } + + function patchSharedIconPicker() { + if (!window.IconPicker || window.IconPicker.__policyBlockPatched) { + return; + } + + const originalPick = typeof window.IconPicker.pick === "function" + ? window.IconPicker.pick.bind(window.IconPicker) + : null; + + if (!originalPick) { + return; + } + + const patchedPick = function (value) { + originalPick(value); + + const activeInput = window.__policyBlockIconPickerInput; + const onPicked = window.__policyBlockIconPickerOnPicked; + + if (!activeInput || typeof onPicked !== "function") { + return; + } + + activeInput.dataset.iconPickerPreviewPrefix = extractIconStyle(value) + || resolveCalloutIconPreviewPrefix(activeInput.value || value); + + onPicked(extractIconName(value)); + activeInput.dispatchEvent(new Event("input", { bubbles: true })); + activeInput.dispatchEvent(new Event("change", { bubbles: true })); + + window.__policyBlockIconPickerInput = null; + window.__policyBlockIconPickerOnPicked = null; + }; + + window.IconPicker.pick = patchedPick; + window.IconPickerPick = patchedPick; + window.IconPicker.__policyBlockPatched = true; + } + + function syncCalloutIconPreview(input) { + if (!input) { + return; + } + + const previewCell = input.closest(".input-group")?.querySelector(".icon-preview-cell"); + if (!previewCell) { + return; + } + + const previewClass = resolveCalloutIconPreviewClass(input.value, input); + previewCell.innerHTML = previewClass ? `` : ""; + + loadIconStyleLookup().then(function () { + const nextPrefix = resolveCalloutIconPreviewPrefix(input.value, input); + if (nextPrefix !== input.dataset.iconPickerPreviewPrefix) { + input.dataset.iconPickerPreviewPrefix = nextPrefix; + const refreshedPreviewClass = resolveCalloutIconPreviewClass(input.value, input); + previewCell.innerHTML = refreshedPreviewClass + ? `` + : ""; + } + }); + } + + function resolveCalloutIconPreviewClass(iconName, input) { + const normalizedValue = String(iconName || "").trim(); + if (!normalizedValue) { + return ""; + } + + return `${resolveCalloutIconPreviewPrefix(normalizedValue, input)} ${normalizedValue}`.trim(); + } + + function resolveCalloutIconPreviewPrefix(iconName, input) { + const explicitPrefix = String(input?.dataset?.iconPickerPreviewPrefix || "").trim(); + if (explicitPrefix && explicitPrefix !== "fa-solid") { + return explicitPrefix; + } + + const normalizedIconName = extractIconName(iconName); + const knownStyles = window.__policyBlockIconStyleLookup?.[normalizedIconName] || []; + + if (knownStyles.includes("fa-brands")) return "fa-brands"; + if (knownStyles.includes("fa-regular")) return "fa-regular"; + if (knownStyles.includes("fa-solid")) return "fa-solid"; + + return explicitPrefix || "fa-solid"; + } + + function extractIconName(value) { + return String(value || "") + .trim() + .split(/\s+/) + .find( + (token) => + /^fa-[a-z0-9-]+$/i.test(token) && !/^fa-(solid|regular|brands)$/i.test(token), + ) || ""; + } + + function extractIconStyle(value) { + return String(value || "") + .trim() + .split(/\s+/) + .find((token) => /^fa-(solid|regular|brands)$/i.test(token)) || ""; + } + + function loadIconStyleLookup() { + if (window.__policyBlockIconStyleLookupPromise) { + return window.__policyBlockIconStyleLookupPromise; + } + + window.__policyBlockIconStyleLookupPromise = fetch("/js/fa-icons.json") + .then((response) => { + if (!response.ok) { + throw new Error(`HTTP ${response.status}`); + } + return response.json(); + }) + .then((json) => { + const lookup = {}; + Object.entries(json || {}).forEach(([name, meta]) => { + lookup[`fa-${name}`] = (meta.styles || []) + .filter((style) => ["solid", "regular", "brands"].includes(style)) + .map((style) => `fa-${style}`); + }); + window.__policyBlockIconStyleLookup = lookup; + return lookup; + }) + .catch(() => { + window.__policyBlockIconStyleLookup = window.__policyBlockIconStyleLookup || {}; + return window.__policyBlockIconStyleLookup; + }); + + return window.__policyBlockIconStyleLookupPromise; + } + + function bindEditable(element, onChange, options) { + element.addEventListener("input", function () { + normalizeEditorHtml(element); + onChange(element.innerHTML); + renderPreview(); + renderValidation(validateState()); + }); + + element.addEventListener("focus", function () { + ui.toolbarTarget = element; + setBlockSelection(element.dataset.blockId); + }); + + element.addEventListener("keydown", function (event) { + if (event.key === "Tab" && element.closest(".list-item-content")) { + event.preventDefault(); + document.execCommand("insertHTML", false, "    "); + return; + } + + if (options?.slashEnabled && event.key === "/") { + ui.slashContext = { + blockIndex: options.blockIndex, + blockId: element.dataset.blockId, + target: element, + }; + const range = window.getSelection()?.getRangeAt(0); + if (range) { + window.setTimeout(function () { + showSlashMenu(range); + }, 0); + } + } + }); + } + + function normalizeEditorHtml(element) { + if (!element.innerHTML.trim()) { + element.innerHTML = ""; + } + } + + function handleSelectionChange() { + const selection = window.getSelection(); + if (!selection || selection.rangeCount === 0 || selection.isCollapsed) { + hideFloatingToolbar(); + return; + } + + const anchorNode = selection.anchorNode?.parentElement; + const editable = anchorNode?.closest(".block-content, .list-item-content"); + if (!editable) { + hideFloatingToolbar(); + return; + } + + ui.toolbarTarget = editable; + const range = selection.getRangeAt(0); + const rect = range.getBoundingClientRect(); + if (!rect.width && !rect.height) { + hideFloatingToolbar(); + return; + } + + floatingToolbar.style.top = `${Math.max(rect.top - 56, 12)}px`; + floatingToolbar.style.left = `${Math.max(rect.left + rect.width / 2 - 160, 12)}px`; + floatingToolbar.classList.add("is-visible"); + } + + function handleGlobalClick(event) { + if (!floatingToolbar.contains(event.target) && !event.target.closest(".block-content, .list-item-content")) { + hideFloatingToolbar(); + } + + if (!linkPopover.contains(event.target) && !event.target.closest('[data-command="openLink"]')) { + hideLinkPopover(); + } + + if (!slashMenu.contains(event.target) && !event.target.closest(".block-content, .list-item-content")) { + hideSlashMenu(); + } + } + + function hideFloatingToolbar() { + floatingToolbar.classList.remove("is-visible"); + } + + function showSlashMenu(range) { + const rect = range.getBoundingClientRect(); + slashMenu.style.top = `${rect.bottom + 8}px`; + slashMenu.style.left = `${Math.max(rect.left, 12)}px`; + slashMenu.classList.add("is-visible"); + } + + function hideSlashMenu() { + slashMenu.classList.remove("is-visible"); + ui.slashContext = null; + } + + function insertSlashCommand(type) { + hideSlashMenu(); + + if (type === "link") { + openLinkPopover(); + return; + } + + if (!ui.slashContext) { + insertBlock(type); + return; + } + + const blocks = getBlocks(); + const index = blocks.findIndex((block) => block.id === ui.slashContext.blockId); + insertBlock(type, index + 1); + } + + function applyCommand(command, value) { + if (!ui.toolbarTarget) { + return; + } + + ui.toolbarTarget.focus(); + + if (command === "toggleCode") { + document.execCommand("insertHTML", false, `${getSelectedText()}`); + } else if (command === "toggleHighlight") { + document.execCommand("hiliteColor", false, "#fef08a"); + } else { + document.execCommand(command, false, value); + } + + ui.toolbarTarget.dispatchEvent(new Event("input", { bubbles: true })); + } + + function getSelectedText() { + return window.getSelection ? window.getSelection().toString() : ""; + } + + function openLinkPopover() { + const selection = window.getSelection(); + if (!selection || selection.rangeCount === 0) { + return; + } + + ui.pendingLinkRange = selection.getRangeAt(0).cloneRange(); + const rect = ui.pendingLinkRange.getBoundingClientRect(); + linkPopover.style.top = `${rect.bottom + 12}px`; + linkPopover.style.left = `${Math.max(rect.left - 60, 12)}px`; + linkPopover.classList.add("is-visible"); + + const anchor = selection.anchorNode?.parentElement?.closest("a"); + linkUrlInput.value = anchor?.getAttribute("href") || ""; + linkPolicySelect.value = anchor?.getAttribute("data-policy-id") || ""; + } + + function hideLinkPopover() { + linkPopover.classList.remove("is-visible"); + } + + function applyLinkFromPopover() { + if (!ui.pendingLinkRange) { + return; + } + + const selection = window.getSelection(); + selection.removeAllRanges(); + selection.addRange(ui.pendingLinkRange); + + const internalPolicyId = linkPolicySelect.value; + const href = linkUrlInput.value.trim(); + const selectedText = getSelectedText() || href || internalPolicyId || "link"; + + if (internalPolicyId) { + document.execCommand( + "insertHTML", + false, + `${selectedText}`, + ); + } else if (href) { + document.execCommand("createLink", false, href); + } + + if (ui.toolbarTarget) { + ui.toolbarTarget.dispatchEvent(new Event("input", { bubbles: true })); + } + + hideLinkPopover(); + } + + function removeCurrentLink() { + if (!ui.toolbarTarget) { + return; + } + + ui.toolbarTarget.focus(); + document.execCommand("unlink", false); + ui.toolbarTarget.dispatchEvent(new Event("input", { bubbles: true })); + hideLinkPopover(); + } + + function describeBlock(block) { + if (block.type === "heading") { + return `H${block.level || 2}`; + } + if (block.type === "list") { + return `${block.style === "ordered" ? "Numbered" : "Bullet"} list`; + } + if (block.type === "callout") { + return `${block.tone || "info"} callout`; + } + return "Rich text"; + } + + function validateState() { + const errors = []; + const warnings = []; + const blockIssues = {}; + const validPolicyIds = [state.policy.id].concat((config.policyOptions || []).map((item) => item.value)); + + let h1Count = 0; + getBlocks().forEach((block) => { + const issues = []; + if (block.type === "heading" && Number(block.level) === 1) { + h1Count += 1; + } + + if (block.type === "divider") { + blockIssues[block.id] = issues; + return; + } + + if (block.type === "list") { + if (!block.items?.length) { + issues.push("List needs at least one item."); + } + block.items?.forEach((item, index) => { + if (!stripHtml(item.html)) { + issues.push(`List item ${index + 1} is empty.`); + } + issues.push(...collectLinkIssues(item.html, validPolicyIds)); + }); + } else if (block.type === "callout") { + if (!stripHtml(block.html) && !stripHtml(block.title)) { + issues.push("Callout is empty."); + } + issues.push(...collectLinkIssues(block.html, validPolicyIds)); + } else if (!stripHtml(block.html)) { + issues.push("Block is empty."); + } else { + issues.push(...collectLinkIssues(block.html, validPolicyIds)); + } + + warnings.push(...issues); + blockIssues[block.id] = issues; + }); + + if (h1Count > 1) { + errors.push("Content has more than one H1."); + } + + if (getBlocks().length === 0) { + warnings.push("Content is empty."); + } + + return { + errors, + warnings, + blockIssues, + }; + } + + function collectLinkIssues(html, validPolicyIds) { + const issues = []; + const anchorRegex = /]*)>/gi; + let match = anchorRegex.exec(String(html || "")); + while (match) { + const attrs = {}; + String(match[1]).replace(/([a-zA-Z_:][a-zA-Z0-9:._-]*)\s*=\s*("([^"]*)"|'([^']*)')/g, function (_, key, __, a, b) { + attrs[key] = a || b || ""; + return _; + }); + const href = String(attrs.href || "").trim(); + const policyId = String(attrs["data-policy-id"] || "").trim(); + const kind = String(attrs["data-link-kind"] || ""); + + if (kind === "internal") { + if (!policyId || !validPolicyIds.includes(policyId)) { + issues.push("Internal link target is invalid."); + } + } else if (!href || !/^(https?:\/\/|mailto:|tel:|\/|#)/i.test(href)) { + issues.push("Link URL is invalid."); + } + + match = anchorRegex.exec(String(html || "")); + } + + return issues; + } + + function renderValidation(validation) { + const hasMessages = validation.errors.length > 0 || validation.warnings.length > 0; + validationBanner.classList.toggle("is-visible", hasMessages); + validationSummary.innerHTML = hasMessages + ? validation.errors.concat(validation.warnings).slice(0, 8).map((item) => `
${escapeHtml(item)}
`).join("") + : ""; + + blockList.querySelectorAll(".block-card").forEach((card) => { + const issues = validation.blockIssues[card.dataset.blockId] || []; + card.classList.toggle("is-invalid", issues.length > 0); + }); + } + + function renderPreview() { + const blocks = getBlocks(); + previewContent.innerHTML = ""; + + if (blocks.length === 0) { + previewContent.innerHTML = '
No content yet.
'; + return; + } + + blocks.forEach((block) => { + const node = document.createElement("section"); + node.className = "preview-block"; + node.dataset.previewBlockId = block.id; + node.addEventListener("mouseenter", function () { + ui.hoveredPreviewBlockId = block.id; + renderBlockSelection(); + }); + node.addEventListener("mouseleave", function () { + ui.hoveredPreviewBlockId = null; + renderBlockSelection(); + }); + node.addEventListener("click", function () { + setBlockSelection(block.id); + document.querySelector(`[data-block-id="${block.id}"]`)?.scrollIntoView({ + behavior: "smooth", + block: "center", + }); + }); + + if (block.type === "heading") { + const tagName = `h${block.level || 2}`; + const heading = document.createElement(tagName); + heading.className = block.level === 1 ? "display-6 fw-bold" : block.level === 2 ? "h3 fw-bold" : "h5 fw-semibold"; + heading.innerHTML = block.html || ""; + node.appendChild(heading); + } else if (block.type === "paragraph") { + const wrapper = document.createElement("div"); + wrapper.innerHTML = block.html || ""; + node.appendChild(wrapper); + } else if (block.type === "quote") { + const blockquote = document.createElement("blockquote"); + blockquote.className = "border-start border-4 ps-3 my-2"; + blockquote.innerHTML = block.html || ""; + node.appendChild(blockquote); + if (block.caption) { + const cite = document.createElement("div"); + cite.className = "small text-muted"; + cite.textContent = block.caption; + node.appendChild(cite); + } + } else if (block.type === "divider") { + const divider = document.createElement("hr"); + node.appendChild(divider); + } else if (block.type === "list") { + const list = document.createElement(block.style === "ordered" ? "ol" : "ul"); + list.className = "ps-4"; + (block.items || []).forEach((item) => { + const li = document.createElement("li"); + li.innerHTML = item.html || ""; + list.appendChild(li); + }); + node.appendChild(list); + } else if (block.type === "callout") { + const callout = document.createElement("div"); + callout.className = "callout-block"; + callout.dataset.tone = block.tone || "info"; + callout.innerHTML = ` + ${block.title ? `
${escapeHtml(block.title)}
` : ""} +
${block.html || ""}
+ `; + node.appendChild(callout); + } + + previewContent.appendChild(node); + }); + + renderPreviewSelection(); + bindPreviewInternalLinks(); + } + + function bindPreviewInternalLinks() { + previewContent.querySelectorAll("a[data-policy-id]").forEach((link) => { + link.addEventListener("click", function (event) { + event.preventDefault(); + showToast("Internal link", `Targets policy "${link.dataset.policyId}" on the public page.`, "info"); + }); + }); + } + + function renderBlockSelection() { + blockList.querySelectorAll(".block-card").forEach((card) => { + const isSelected = card.dataset.blockId === ui.selectedBlockId; + const isPreviewHovered = card.dataset.blockId === ui.hoveredPreviewBlockId; + card.classList.toggle("is-selected", isSelected || isPreviewHovered); + }); + } + + function renderPreviewSelection() { + previewContent.querySelectorAll(".preview-block").forEach((node) => { + const blockId = node.dataset.previewBlockId; + node.classList.toggle( + "is-highlighted", + blockId === ui.selectedBlockId || blockId === ui.hoveredPreviewBlockId, + ); + node.classList.toggle("is-targeted", blockId === ui.targetedPreviewBlockId); + }); + } + + function focusPreviewBlock(blockId) { + setBlockSelection(blockId); + const node = previewContent.querySelector(`[data-preview-block-id="${blockId}"]`); + if (!node) { + return; + } + + if (ui.previewTargetTimer) { + window.clearTimeout(ui.previewTargetTimer); + } + + ui.targetedPreviewBlockId = blockId; + renderPreviewSelection(); + node.scrollIntoView({ + behavior: "smooth", + block: "center", + inline: "nearest", + }); + + ui.previewTargetTimer = window.setTimeout(function () { + ui.targetedPreviewBlockId = null; + renderPreviewSelection(); + ui.previewTargetTimer = null; + }, 1600); + } + + function escapeHtml(value) { + return String(value || "") + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); + } + + function escapeAttribute(value) { + return escapeHtml(value).replace(/`/g, "`"); + } + + function stripHtml(value) { + return String(value || "") + .replace(//gi, " ") + .replace(/<[^>]+>/g, " ") + .replace(/ /gi, " ") + .replace(/\s+/g, " ") + .trim(); + } + + function showToast(title, message, type) { + if (window.bootstrap && typeof bootstrap.Toast === "function") { + const container = + document.querySelector(".toast-container") || createToastContainer(); + const toast = document.createElement("div"); + toast.className = `toast align-items-center text-white bg-${type || "info"} border-0`; + toast.setAttribute("role", "alert"); + toast.innerHTML = `
${escapeHtml(title)}: ${escapeHtml(message)}
`; + container.appendChild(toast); + new bootstrap.Toast(toast, { autohide: true, delay: 2500 }).show(); + toast.addEventListener("hidden.bs.toast", function () { + toast.remove(); + }); + return; + } + window.alert(`${title}: ${message}`); + } + + function createToastContainer() { + const container = document.createElement("div"); + container.className = "toast-container position-fixed top-0 end-0 p-3"; + document.body.appendChild(container); + return container; + } + + function readJsonScript(id) { + const node = document.getElementById(id); + if (!node) { + return null; + } + + try { + return JSON.parse(node.textContent || "null"); + } catch (error) { + console.error(`Failed to parse JSON script "${id}"`, error); + return null; + } + } +})(); diff --git a/public/uploads/accreditation/QAHE.png b/public/uploads/accreditation/QAHE.png new file mode 100644 index 0000000..e0d2a39 Binary files /dev/null and b/public/uploads/accreditation/QAHE.png differ diff --git a/public/uploads/accreditation/head.png b/public/uploads/accreditation/head.png new file mode 100644 index 0000000..a03985a Binary files /dev/null and b/public/uploads/accreditation/head.png differ diff --git a/public/uploads/accreditation/ico.png b/public/uploads/accreditation/ico.png new file mode 100644 index 0000000..48f2f18 Binary files /dev/null and b/public/uploads/accreditation/ico.png differ diff --git a/public/uploads/accreditation/ukrlp.png b/public/uploads/accreditation/ukrlp.png new file mode 100644 index 0000000..52d75a3 Binary files /dev/null and b/public/uploads/accreditation/ukrlp.png differ diff --git a/public/uploads/admissions/hero-students.png b/public/uploads/admissions/hero-students.png new file mode 100644 index 0000000..613bff8 Binary files /dev/null and b/public/uploads/admissions/hero-students.png differ diff --git a/public/uploads/history/2023.png b/public/uploads/history/2023.png new file mode 100644 index 0000000..c6c8269 Binary files /dev/null and b/public/uploads/history/2023.png differ diff --git a/public/uploads/history/2024.png b/public/uploads/history/2024.png new file mode 100644 index 0000000..54c73ba Binary files /dev/null and b/public/uploads/history/2024.png differ diff --git a/public/uploads/history/2025.png b/public/uploads/history/2025.png new file mode 100644 index 0000000..92ab1fd Binary files /dev/null and b/public/uploads/history/2025.png differ diff --git a/public/uploads/history/2026.png b/public/uploads/history/2026.png new file mode 100644 index 0000000..452275f Binary files /dev/null and b/public/uploads/history/2026.png differ diff --git a/public/uploads/history/ai-enhanced-learning-platform.png b/public/uploads/history/ai-enhanced-learning-platform.png new file mode 100644 index 0000000..b442d1a Binary files /dev/null and b/public/uploads/history/ai-enhanced-learning-platform.png differ diff --git a/public/uploads/partnerships/ENG_main_2022-05-20-070029_kstp.jpg b/public/uploads/partnerships/ENG_main_2022-05-20-070029_kstp.jpg new file mode 100644 index 0000000..ea08995 Binary files /dev/null and b/public/uploads/partnerships/ENG_main_2022-05-20-070029_kstp.jpg differ diff --git a/public/uploads/partnerships/hero-campus-corporate.png b/public/uploads/partnerships/hero-campus-corporate.png new file mode 100644 index 0000000..17c1ad8 Binary files /dev/null and b/public/uploads/partnerships/hero-campus-corporate.png differ diff --git a/public/uploads/partnerships/horizons.jpg b/public/uploads/partnerships/horizons.jpg new file mode 100644 index 0000000..acc37b1 Binary files /dev/null and b/public/uploads/partnerships/horizons.jpg differ diff --git a/public/uploads/partnerships/royalcosmetics.png b/public/uploads/partnerships/royalcosmetics.png new file mode 100644 index 0000000..0426816 Binary files /dev/null and b/public/uploads/partnerships/royalcosmetics.png differ diff --git a/public/uploads/partnerships/swiss.jpg b/public/uploads/partnerships/swiss.jpg new file mode 100644 index 0000000..3c70d89 Binary files /dev/null and b/public/uploads/partnerships/swiss.jpg differ diff --git a/public/uploads/partnerships/tech-logo.png b/public/uploads/partnerships/tech-logo.png new file mode 100644 index 0000000..63189ff Binary files /dev/null and b/public/uploads/partnerships/tech-logo.png differ diff --git a/public/uploads/partnerships/uldp.jpg b/public/uploads/partnerships/uldp.jpg new file mode 100644 index 0000000..fba5eb8 Binary files /dev/null and b/public/uploads/partnerships/uldp.jpg differ diff --git a/routes/admin.js b/routes/admin.js index a7026d7..3270216 100644 --- a/routes/admin.js +++ b/routes/admin.js @@ -7,7 +7,12 @@ const uploadController = require("../controllers/uploadController"); const homeController = require("../controllers/homeController"); const headerController = require("../controllers/headerController"); const footerController = require("../controllers/footerController"); -const aboutController = require("../controllers/aboutController"); +const aboutUsController = require("../controllers/aboutUsController"); +const partnershipsController = require("../controllers/partnershipsController"); +const historyPageController = require("../controllers/historyPageController"); +const accreditationController = require("../controllers/accreditationController"); +const admissionsController = require("../controllers/admissionsController"); +const policiesController = require("../controllers/policiesController"); const formController = require("../controllers/formController"); const contactController = require("../controllers/contactController"); const studentSupportController = require("../controllers/studentSupportController"); @@ -49,9 +54,55 @@ router.param("code", (req, res, next, code) => { next(); }); -// About -router.get("/about", ensureAuthenticated, aboutController.index); -router.post("/about/update", ensureAuthenticated, aboutController.update); +// About Us +router.get("/about-us", ensureAuthenticated, aboutUsController.index); +router.post("/about-us/update", ensureAuthenticated, aboutUsController.update); +router.get("/partnerships", ensureAuthenticated, partnershipsController.index); +router.post( + "/partnerships/update", + ensureAuthenticated, + partnershipsController.update, +); +router.get("/history", ensureAuthenticated, historyPageController.index); +router.post("/history/update", ensureAuthenticated, historyPageController.update); +router.get( + "/accreditation", + ensureAuthenticated, + accreditationController.index, +); +router.post( + "/accreditation/update", + ensureAuthenticated, + accreditationController.update, +); +router.get("/admissions", ensureAuthenticated, admissionsController.index); +router.get( + "/admissions/calculator/:optionId", + ensureAuthenticated, + admissionsController.editCalculatorOption, +); +router.post( + "/admissions/calculator/:optionId/update", + ensureAuthenticated, + admissionsController.updateCalculatorOption, +); +router.post( + "/admissions/update", + ensureAuthenticated, + admissionsController.update, +); +router.get("/policies", ensureAuthenticated, policiesController.index); +router.post("/policies/update", ensureAuthenticated, policiesController.update); +router.get( + "/policies/:policyId/section", + ensureAuthenticated, + policiesController.editSections, +); +router.post( + "/policies/:policyId/section/update", + ensureAuthenticated, + policiesController.updateSections, +); // Booking admin CRUD removed diff --git a/routes/index.js b/routes/index.js index 44db690..611afee 100644 --- a/routes/index.js +++ b/routes/index.js @@ -2,7 +2,12 @@ const express = require("express"); const path = require("path"); const router = express.Router(); const homeController = require("../controllers/homeController"); -const aboutController = require("../controllers/aboutController"); +const aboutUsController = require("../controllers/aboutUsController"); +const partnershipsController = require("../controllers/partnershipsController"); +const historyPageController = require("../controllers/historyPageController"); +const accreditationController = require("../controllers/accreditationController"); +const admissionsController = require("../controllers/admissionsController"); +const policiesController = require("../controllers/policiesController"); const headerController = require("../controllers/headerController"); const socialLinkController = require("../controllers/socialLinkController"); @@ -38,7 +43,17 @@ router.get("/", (req, res) => { router.get("/api/home", homeController.api); // API để lấy dữ liệu about -router.get("/api/about", aboutController.api); +router.get("/api/about", aboutUsController.getAbout); +router.put("/api/about", aboutUsController.updateAbout); +router.get("/api/partnerships", partnershipsController.api); +router.get("/api/history", historyPageController.api); +router.get("/api/accreditation", accreditationController.api); +router.get("/api/admissions", admissionsController.api); +router.get("/api/policies", policiesController.api); + +// Public about-us page and API (legacy support) +router.get("/about-us", aboutUsController.getAbout); +router.get("/api/about-us", aboutUsController.getAbout); // Header API route router.get("/api/header", headerController.api); diff --git a/scripts/2026_04_20_122800_partnerships.js b/scripts/2026_04_20_122800_partnerships.js new file mode 100644 index 0000000..33c3985 --- /dev/null +++ b/scripts/2026_04_20_122800_partnerships.js @@ -0,0 +1,8 @@ +const migrateSingletonPage = require("./_migrate-singleton-page"); + +migrateSingletonPage({ + migrationName: "import_partnerships_content", + modelPath: "../models/partnerships", + dataFile: "partnerships.json", + label: "Partnerships", +}); diff --git a/scripts/2026_04_20_122810_history.js b/scripts/2026_04_20_122810_history.js new file mode 100644 index 0000000..1a6a65f --- /dev/null +++ b/scripts/2026_04_20_122810_history.js @@ -0,0 +1,8 @@ +const migrateSingletonPage = require("./_migrate-singleton-page"); + +migrateSingletonPage({ + migrationName: "import_history_content", + modelPath: "../models/historyPage", + dataFile: "history.json", + label: "History", +}); diff --git a/scripts/2026_04_20_122820_accreditation.js b/scripts/2026_04_20_122820_accreditation.js new file mode 100644 index 0000000..caf220d --- /dev/null +++ b/scripts/2026_04_20_122820_accreditation.js @@ -0,0 +1,8 @@ +const migrateSingletonPage = require("./_migrate-singleton-page"); + +migrateSingletonPage({ + migrationName: "import_accreditation_content", + modelPath: "../models/accreditationPage", + dataFile: "accreditation.json", + label: "Accreditation", +}); diff --git a/scripts/2026_04_20_122830_admissions.js b/scripts/2026_04_20_122830_admissions.js new file mode 100644 index 0000000..6671dcb --- /dev/null +++ b/scripts/2026_04_20_122830_admissions.js @@ -0,0 +1,8 @@ +const migrateSingletonPage = require("./_migrate-singleton-page"); + +migrateSingletonPage({ + migrationName: "import_admissions_content", + modelPath: "../models/admissionsPage", + dataFile: "admissions.json", + label: "Admissions", +}); diff --git a/scripts/2026_04_20_122840_policies.js b/scripts/2026_04_20_122840_policies.js new file mode 100644 index 0000000..fb0e247 --- /dev/null +++ b/scripts/2026_04_20_122840_policies.js @@ -0,0 +1,8 @@ +const migrateSingletonPage = require("./_migrate-singleton-page"); + +migrateSingletonPage({ + migrationName: "import_policies_content", + modelPath: "../models/policiesPage", + dataFile: "policies.json", + label: "Policies", +}); diff --git a/scripts/_migrate-singleton-page.js b/scripts/_migrate-singleton-page.js new file mode 100644 index 0000000..af2192e --- /dev/null +++ b/scripts/_migrate-singleton-page.js @@ -0,0 +1,38 @@ +require("dotenv").config(); +const fs = require("fs").promises; +const path = require("path"); +const connectDB = require("../config/database"); + +async function migrateSingletonPage({ + migrationName, + modelPath, + dataFile, + label, +}) { + try { + await connectDB(); + console.log(`🚀 Starting migration: ${migrationName}...`); + + const Model = require(modelPath); + console.log(`✅ ${label} model registered successfully`); + + const dataPath = path.join(__dirname, "..", "data", dataFile); + const raw = await fs.readFile(dataPath, "utf8"); + const pageData = JSON.parse(raw); + console.log(`📖 ${label} data loaded from: ${dataPath}`); + + await Model.deleteMany({}); + console.log(`🧹 Existing ${label} documents cleared`); + + const created = await Model.create(pageData); + console.log(`✅ ${label} document created with _id: ${created._id.toString()}`); + + console.log(`🎉 Migration ${migrationName} completed successfully.`); + process.exit(0); + } catch (error) { + console.error(`❌ Migration ${migrationName} failed:`, error); + process.exit(1); + } +} + +module.exports = migrateSingletonPage; diff --git a/utils/contentEditorIds.js b/utils/contentEditorIds.js new file mode 100644 index 0000000..e6ff2d9 --- /dev/null +++ b/utils/contentEditorIds.js @@ -0,0 +1,35 @@ +function slugifyContentId(value, fallback = "item") { + const normalized = String(value || "") + .trim() + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, ""); + + return normalized || fallback; +} + +function ensureUniqueIds(items, getExistingId, getSourceValue, fallbackPrefix) { + const usedIds = new Set(); + + return (Array.isArray(items) ? items : []).map((item, index) => { + const existingId = String(getExistingId(item, index) || "").trim(); + let nextId = existingId || slugifyContentId(getSourceValue(item, index), `${fallbackPrefix}-${index + 1}`); + let suffix = 2; + + while (usedIds.has(nextId)) { + nextId = `${existingId || slugifyContentId(getSourceValue(item, index), fallbackPrefix)}-${suffix}`; + suffix += 1; + } + + usedIds.add(nextId); + return { + ...item, + id: nextId, + }; + }); +} + +module.exports = { + slugifyContentId, + ensureUniqueIds, +}; diff --git a/utils/contentEditors/accreditationConfig.js b/utils/contentEditors/accreditationConfig.js new file mode 100644 index 0000000..a0ce8f6 --- /dev/null +++ b/utils/contentEditors/accreditationConfig.js @@ -0,0 +1,84 @@ +const { + text, + textarea, + image, + icon, + select, + combobox, + object, + stringList, + objectList, +} = require("./sharedFields"); + +const statusOptions = [ + { value: "Active", label: "Active" }, + { value: "Inactive", label: "Inactive" }, +]; + +module.exports = { + key: "accreditation", + title: "Accreditation Management", + subtitle: "Manage the content for the accreditation page", + routeBase: "/admin/accreditation", + apiPath: "/api/accreditation", + previewPath: "/about/accreditation", + dataFile: "accreditation", + imageType: "accreditation", + tabs: [ + { + key: "hero", + label: "Hero", + icon: "fas fa-image", + schema: object("hero", "Hero", [ + text("badge", "Eyebrow label", { maxLength: 30 }), + text("title", "Headline", { maxLength: 60 }), + textarea("description", "Supporting text", { maxLength: 420, rows: 5 }), + ]), + }, + { + key: "grid", + label: "Accreditation Grid", + icon: "fas fa-table-cells-large", + schema: object("grid", "Accreditation grid", [ + stringList("tabs", "Category tabs", { + itemLabel: "Tab", + maxLength: 30, + sortable: true, + helpText: "Add and reorder the category tabs shown on the page.", + }), + objectList( + "items", + "Accreditation cards", + [ + icon("icon", "Fallback icon"), + image("image", "Card image", { + imageHint: "Recommended 118x58 px minimum visible ratio", + helpText: "Logo or badge shown at the top of the card.", + }), + select("status", "Status", statusOptions), + combobox("category", "Category", { + maxLength: 30, + optionsPath: "grid.tabs", + }), + text("title", "Card title", { + maxLength: 17, + helpText: "Keep this very short. Around 17 characters fits best in the card title area.", + }), + textarea("description", "Card description", { + maxLength: 300, + rows: 5, + helpText: "Keep this concise. Around 300 characters fits best in the card description area.", + }), + ], + { + itemLabel: "Accreditation", + sortable: true, + itemTitleKey: "title", + itemSubtitleKey: "category", + emptyText: "No accreditation cards yet.", + }, + ), + ]), + }, + ], +}; diff --git a/utils/contentEditors/admissionsConfig.js b/utils/contentEditors/admissionsConfig.js new file mode 100644 index 0000000..e9bcb55 --- /dev/null +++ b/utils/contentEditors/admissionsConfig.js @@ -0,0 +1,290 @@ +const { + text, + hidden, + textarea, + image, + icon, + checkbox, + object, + stringList, + objectList, + linkFields, +} = require("./sharedFields"); + +module.exports = { + key: "admissions", + title: "Admissions Management", + subtitle: "Manage the content for the admissions page", + routeBase: "/admin/admissions", + apiPath: "/api/admissions", + previewPath: "/admissions", + dataFile: "admissions", + imageType: "admissions", + editorUi: { + keyDates: { + tableLabel: "Key dates table", + tableHelpText: "Manage the table directly by adding or removing columns and rows.", + addColumnLabel: "Add Column", + addRowLabel: "Add Row", + columnPlaceholder: "Column name", + emptyRowsText: "No rows yet.", + actionsLabel: "Actions", + columnLabelMaxLength: 40, + cellMaxLength: 60, + }, + calculator: { + ctaLabel: "Primary button", + ctaHelpText: "This button appears at the bottom of the calculator card.", + optionsLabel: "Calculator options", + optionsHelpText: "Each option has its own pricing labels, amount, note, and icon. Open the edit page to update the option details.", + optionsEmptyText: "No calculator options yet.", + addOptionLabel: "Add calculator option", + maxOptions: 3, + limitHelpText: "You can add up to 3 calculator options.", + defaultOption: { + paceLabel: "Target Pace", + minPaceLabel: "Relaxed", + maxPaceLabel: "Accelerated", + resultLabel: "Estimated Monthly Payment", + monthlyAmount: "299", + monthlySuffix: "/mo", + noteIcon: "fa-bolt", + note: "", + }, + }, + }, + tabs: [ + { + key: "hero", + label: "Hero", + icon: "fas fa-image", + schema: object("hero", "Hero", [ + text("badge", "Eyebrow label", { maxLength: 40 }), + text("title", "Headline", { maxLength: 80 }), + textarea("description", "Supporting text", { maxLength: 240, rows: 4 }), + object("primaryCta", "Primary button", linkFields("Primary button")), + object("secondaryCta", "Secondary button", linkFields("Secondary button")), + image("image", "Hero image", { + imageHint: "Recommended 720x646 px", + helpText: "Large image rendered in the right hero panel.", + }), + text("imageAlt", "Hero image alt text", { maxLength: 120 }), + ]), + }, + { + key: "process", + label: "Admissions Process", + icon: "fas fa-list-ol", + schema: object("process", "Admissions process", [ + text("title", "Section title", { maxLength: 60 }), + textarea("description", "Section description", { + maxLength: 180, + rows: 3, + }), + objectList( + "steps", + "Steps", + [ + hidden("number", { autoSequence: { padLength: 2 } }), + text("title", "Step title", { maxLength: 50 }), + textarea("description", "Step description", { + maxLength: 180, + rows: 3, + }), + checkbox("active", "Highlight this step"), + ], + { + itemLabel: "Step", + sortable: true, + itemTitleKey: "title", + itemSubtitleKey: "number", + emptyText: "No process steps yet.", + }, + ), + ]), + }, + { + key: "eligibility", + label: "Eligibility", + icon: "fas fa-check-circle", + schema: object("eligibility", "Eligibility", [ + text("title", "Section title", { maxLength: 60 }), + objectList( + "cards", + "Eligibility cards", + [ + text("title", "Card title", { maxLength: 50 }), + icon("icon", "Card icon"), + stringList("items", "Checklist items", { + itemLabel: "Checklist item", + maxLength: 120, + sortable: true, + }), + ], + { + itemLabel: "Card", + sortable: true, + itemTitleKey: "title", + emptyText: "No eligibility cards yet.", + }, + ), + ]), + }, + { + key: "tuition", + label: "Tuition", + icon: "fas fa-chart-column", + schema: object("tuition", "Tuition", [ + text("title", "Section title", { maxLength: 45 }), + text("chartTitle", "Chart title", { maxLength: 40 }), + textarea("chartDescription", "Chart description", { + maxLength: 140, + rows: 3, + }), + objectList( + "series", + "Chart series", + [ + text("label", "Series label", { maxLength: 20 }), + { key: "color", label: "Series color", type: "color" }, + objectList( + "points", + "Data points", + [ + text("time", "Time label", { + maxLength: 14, + placeholder: "Year 1", + }), + { + key: "value", + label: "Value", + type: "number", + min: 0, + }, + ], + { + itemLabel: "Point", + sortable: true, + itemTitleKey: "time", + itemSubtitleKey: "value", + helpText: "Each chart point requires both a time label and a numeric value.", + emptyText: "No data points yet.", + }, + ), + ], + { + itemLabel: "Series", + sortable: true, + itemTitleKey: "label", + emptyText: "No chart series yet.", + }, + ), + ]), + }, + { + key: "keyDates", + label: "Key Dates", + icon: "fas fa-calendar-days", + schema: object("keyDates", "Key dates", [ + text("title", "Section title", { maxLength: 60 }), + ]), + }, + { + key: "calculator", + label: "Calculator", + icon: "fas fa-calculator", + schema: object("calculator", "Calculator", [ + text("title", "Card title", { maxLength: 60 }), + textarea("description", "Card description", { + maxLength: 120, + rows: 3, + }), + object("cta", "Button", linkFields("Button")), + objectList( + "options", + "Calculator options", + [ + hidden("id"), + text("label", "Option label", { + maxLength: 12, + helpText: "This label appears in the calculator option switcher.", + }), + text("paceLabel", "Pace label", { + maxLength: 20, + helpText: "This appears above the pace slider.", + }), + text("minPaceLabel", "Minimum pace label", { + maxLength: 7, + helpText: "This appears on the left side of the pace slider.", + }), + text("maxPaceLabel", "Maximum pace label", { + maxLength: 7, + helpText: "This appears on the right side of the pace slider.", + }), + text("resultLabel", "Result label", { + maxLength: 40, + helpText: "This label appears above the calculated amount.", + }), + text("monthlyAmount", "Monthly amount", { + maxLength: 20, + helpText: "Enter digits only. The currency symbol is added on the website automatically.", + }), + text("monthlySuffix", "Monthly suffix", { + maxLength: 10, + helpText: "Example: /mo", + }), + icon("noteIcon", "Note icon", { + helpText: "Choose the icon shown beside the note.", + }), + text("note", "Note text", { + maxLength: 60, + helpText: "This short note appears under the amount.", + }), + ], + { + itemLabel: "Option", + sortable: true, + itemTitleKey: "label", + emptyText: "No calculator options yet.", + itemActions: [ + { + label: "Edit option", + icon: "fas fa-pen", + className: "btn btn-outline-primary btn-sm", + hrefTemplate: "/admin/admissions/calculator/{id}", + }, + ], + }, + ), + ]), + }, + { + key: "scholarships", + label: "Scholarships", + icon: "fas fa-award", + schema: object("scholarships", "Scholarships", [ + text("title", "Card title", { maxLength: 50 }), + icon("icon", "Card icon"), + objectList( + "items", + "Scholarship items", + [ + text("title", "Title", { maxLength: 40 }), + text("amount", "Amount", { maxLength: 12 }), + textarea("description", "Description", { + maxLength: 160, + rows: 3, + }), + ], + { + itemLabel: "Scholarship item", + sortable: true, + itemTitleKey: "title", + itemSubtitleKey: "amount", + emptyText: "No scholarship items yet.", + }, + ), + ]), + }, + ], +}; diff --git a/utils/contentEditors/historyConfig.js b/utils/contentEditors/historyConfig.js new file mode 100644 index 0000000..342d210 --- /dev/null +++ b/utils/contentEditors/historyConfig.js @@ -0,0 +1,123 @@ +const { + text, + textarea, + image, + icon, + checkbox, + url, + combobox, + object, + stringList, + objectList, +} = require("./sharedFields"); + +module.exports = { + key: "history", + title: "History Management", + subtitle: "Manage the content for the history page", + routeBase: "/admin/history", + apiPath: "/api/history", + previewPath: "/about/history", + dataFile: "history", + imageType: "history", + tabs: [ + { + key: "highlight", + label: "Highlight Bar", + icon: "fas fa-star", + schema: object("highlight", "Highlight bar", [ + icon("icon", "Highlight icon"), + text("text", "Message", { maxLength: 110 }), + text("linkLabel", "Link label", { maxLength: 30 }), + url("href", "Link URL", { + maxLength: 255, + helpText: "Use an anchor or website path only. Examples: #milestones, /about/history, /contact", + }), + ]), + }, + { + key: "hero", + label: "Hero", + icon: "fas fa-image", + schema: object("hero", "Hero", [ + text("badge", "Eyebrow label", { maxLength: 40 }), + text("title", "Headline", { maxLength: 90 }), + textarea("description", "Supporting text", { maxLength: 220, rows: 4 }), + ]), + }, + { + key: "filters", + label: "Filter Controls", + icon: "fas fa-filter", + schema: object("filters", "Filter controls", [ + stringList("yearOptions", "Year options", { + itemLabel: "Year option", + maxLength: 30, + sortable: true, + helpText: "Reorder these options to change the order in the Year range dropdown.", + }), + stringList("categoryOptions", "Category options", { + itemLabel: "Category option", + maxLength: 40, + sortable: true, + }), + ]), + }, + { + key: "timeline", + label: "Timeline", + icon: "fas fa-clock-rotate-left", + schema: object("timeline", "Timeline", [ + objectList( + "items", + "Milestones", + [ + text("year", "Year", { + maxLength: 4, + }), + combobox("yearRange", "Year range", { + maxLength: 30, + optionsPath: "filters.yearOptions", + }), + combobox("category", "Category", { + maxLength: 40, + optionsPath: "filters.categoryOptions", + }), + text("categoryLabel", "Category badge label", { maxLength: 25 }), + text("title", "Milestone title", { maxLength: 90 }), + textarea("description", "Description", { + maxLength: 260, + rows: 4, + }), + image("image", "Milestone image", { + imageHint: "Recommended 436x190 px, 16:9 aspect ratio.", + helpText: "Wide image used inside the milestone card.", + }), + text("imageAlt", "Image alt text", { maxLength: 120 }), + objectList( + "stats", + "Stats", + [ + text("value", "Value", { maxLength: 24 }), + text("label", "Label", { maxLength: 50 }), + ], + { + itemLabel: "Stat", + sortable: true, + emptyText: "No stats yet.", + }, + ), + checkbox("featured", "Featured milestone"), + ], + { + itemLabel: "Milestone", + sortable: true, + itemTitleKey: "title", + itemSubtitleKey: "year", + emptyText: "No milestones yet.", + }, + ), + ]), + }, + ], +}; diff --git a/utils/contentEditors/partnershipsConfig.js b/utils/contentEditors/partnershipsConfig.js new file mode 100644 index 0000000..9fbfdbf --- /dev/null +++ b/utils/contentEditors/partnershipsConfig.js @@ -0,0 +1,156 @@ +const { + text, + textarea, + image, + checkbox, + select, + combobox, + object, + stringList, + objectList, +} = require("./sharedFields"); + +const inquiryFieldOptions = [ + { value: "text", label: "Single line text" }, + { value: "textarea", label: "Paragraph" }, + { value: "select", label: "Dropdown" }, +]; + +const widthOptions = [ + { value: "half", label: "Half width" }, + { value: "full", label: "Full width" }, +]; + +module.exports = { + key: "partnerships", + title: "Partnerships Management", + subtitle: "Manage the content for the partnerships page", + routeBase: "/admin/partnerships", + apiPath: "/api/partnerships", + previewPath: "/about/partnerships", + dataFile: "partnerships", + imageType: "partnerships", + editorUi: { + directory: { + tabsFrontendHint: "The frontend shows up to 3 direct tabs. Additional tabs move into a More dropdown.", + partnersHelpText: "Each partner card keeps its own open or closed state automatically.", + }, + inquiryForm: { + fieldsHelpText: "Manage labels, placeholders, type, width, and dropdown options.", + }, + }, + tabs: [ + { + key: "hero", + label: "Hero", + icon: "fas fa-image", + schema: object("hero", "Hero", [ + text("badge", "Eyebrow label", { maxLength: 40 }), + text("title", "Headline", { maxLength: 90 }), + textarea("description", "Supporting text", { maxLength: 220, rows: 4 }), + text("linkLabel", "Scroll link label", { maxLength: 40 }), + image("image", "Hero image", { + imageHint: "Recommended 720x630 px", + helpText: "Upload the image shown in the right hero panel.", + }), + text("imageAlt", "Hero image alt text", { maxLength: 120 }), + ]), + }, + { + key: "directory", + label: "Partner Directory", + icon: "fas fa-handshake", + schema: object("directory", "Partner directory", [ + text("heading", "Section heading", { maxLength: 70 }), + textarea("description", "Section description", { + maxLength: 180, + rows: 3, + }), + stringList("tabs", "Category tabs", { + itemLabel: "Category tab", + maxLength: 30, + placeholder: "Industry", + sortable: true, + helpText: "Add and reorder the category tabs shown on the page.", + }), + objectList( + "partners", + "Partners", + [ + text("name", "Partner name", { maxLength: 90 }), + combobox("category", "Category", { + maxLength: 30, + optionsPath: "directory.tabs", + }), + textarea("summary", "Card summary", { + maxLength: 130, + rows: 3, + helpText: "Keep this short. Around 130 characters works best in the card layout.", + }), + image("logo", "Partner logo", { + imageHint: "Recommended 105x80 px minimum visible ratio", + helpText: "Use a clean logo with transparent or simple background.", + }), + text("logoAlt", "Logo alt text", { maxLength: 120 }), + textarea("about", "About text", { maxLength: 600, rows: 5 }), + text("collabType", "Collaboration type", { maxLength: 40 }), + textarea("benefits", "Benefits", { maxLength: 240, rows: 4 }), + ], + { + itemLabel: "Partner", + sortable: true, + itemTitleKey: "name", + itemSubtitleKey: "category", + emptyText: "No partners yet.", + }, + ), + ]), + }, + { + key: "cta", + label: "Call To Action", + icon: "fas fa-bullhorn", + schema: object("cta", "Call to action", [ + text("heading", "Headline", { maxLength: 80 }), + textarea("description", "Supporting text", { + maxLength: 220, + rows: 4, + }), + text("buttonLabel", "Button label", { maxLength: 40 }), + ]), + }, + { + key: "inquiryForm", + label: "Inquiry Form", + icon: "fas fa-envelope", + schema: object("inquiryForm", "Inquiry form", [ + text("title", "Modal title", { maxLength: 35 }), + objectList( + "fields", + "Form fields", + [ + text("label", "Field label", { maxLength: 40 }), + text("placeholder", "Placeholder text", { maxLength: 80 }), + select("type", "Field type", inquiryFieldOptions), + select("width", "Field width", widthOptions), + stringList("options", "Dropdown options", { + itemLabel: "Option", + maxLength: 50, + sortable: true, + helpText: "Only used when the field type is Dropdown.", + visibleWhen: { path: "type", equals: "select" }, + }), + checkbox("required", "Required field"), + ], + { + itemLabel: "Field", + sortable: true, + itemTitleKey: "label", + itemSubtitleKey: "type", + emptyText: "No inquiry fields yet.", + }, + ), + ]), + }, + ], +}; diff --git a/utils/contentEditors/policiesConfig.js b/utils/contentEditors/policiesConfig.js new file mode 100644 index 0000000..97f132d --- /dev/null +++ b/utils/contentEditors/policiesConfig.js @@ -0,0 +1,112 @@ +const { + ICON_OPTIONS, + text, + date, + textarea, + icon, + url, + combobox, + object, + objectList, + stringList, + variantList, +} = require("./sharedFields"); + +const baseConfig = { + key: "policies", + title: "Policies Management", + subtitle: "Manage policy metadata and block-based content for the policies page", + routeBase: "/admin/policies", + apiPath: "/api/policies", + previewPath: "/policies", + dataFile: "policies", + imageType: "policies", + tabs: [ + { + key: "hero", + label: "Hero", + icon: "fas fa-scale-balanced", + schema: object("hero", "Hero", [ + text("badge", "Eyebrow label", { maxLength: 40 }), + icon("icon", "Hero icon", { + helpText: "Policies uses icon-only controls and does not require image upload.", + }), + text("titlePrefix", "Headline prefix", { maxLength: 50 }), + text("titleHighlight", "Headline highlight", { maxLength: 40 }), + textarea("description", "Supporting text", { + maxLength: 220, + rows: 4, + }), + ]), + }, + { + key: "sidebar", + label: "Sidebar", + icon: "fas fa-bars", + schema: object("sidebar", "Sidebar", [ + text("heading", "Sidebar heading", { maxLength: 30 }), + text("helperText", "Helper text", { maxLength: 60 }), + text("contactLabel", "Contact link label", { maxLength: 25 }), + url("contactHref", "Contact URL", { maxLength: 255 }), + ]), + }, + { + key: "policies", + label: "Policies", + icon: "fas fa-file-lines", + schema: objectList( + "policies", + "Policies", + [ + text("navLabel", "Sidebar label", { maxLength: 40 }), + text("title", "Policy title", { maxLength: 70 }), + date("effectiveDate", "Effective date", { + helpText: "Pick a calendar date. It will be saved in the standard policy display format.", + }), + textarea("intro", "Intro text", { maxLength: 260, rows: 4 }), + ], + { + itemLabel: "Policy", + sortable: true, + itemTitleKey: "title", + itemSubtitleKey: "effectiveDate", + emptyText: "No policies yet.", + itemActions: [ + { + label: "Edit Content", + icon: "fas fa-pen-to-square", + hrefTemplate: "/admin/policies/{id}/section", + className: "btn btn-outline-primary btn-sm", + }, + ], + }, + ), + }, + ], +}; + +function createPoliciesSectionEditorConfig(policy, allPolicies = []) { + const policyOptions = allPolicies + .filter((item) => item.id && item.id !== policy.id) + .map((item) => ({ + value: item.id, + label: item.title || item.navLabel || item.id, + })); + + return { + key: "policyContent", + title: `Policy Content: ${policy.title || policy.id}`, + subtitle: "Edit block-based policy content with realtime preview", + routeBase: `/admin/policies/${policy.id}/section`, + previewPath: "/policies", + imageType: "policies", + policyId: policy.id, + policyOptions, + iconOptions: ICON_OPTIONS, + }; +} + +module.exports = { + baseConfig, + createPoliciesSectionEditorConfig, +}; diff --git a/utils/contentEditors/sharedFields.js b/utils/contentEditors/sharedFields.js new file mode 100644 index 0000000..23f5791 --- /dev/null +++ b/utils/contentEditors/sharedFields.js @@ -0,0 +1,193 @@ +const ICON_OPTIONS = [ + "fa-scale-balanced", + "fa-shield-check", + "fa-magnifying-glass", + "fa-graduation-cap", + "fa-check-double", + "fa-building-columns", + "fa-award", + "fa-trophy", + "fa-arrow-down", + "fa-arrow-right", + "fa-check-circle", + "fa-exchange-alt", + "fa-bolt", + "fa-book-open", + "fa-credit-card", + "fa-calendar-days", + "fa-envelope", + "fa-file-lines", + "fa-globe", + "fa-briefcase", + "fa-handshake", + "fa-circle-info", + "fa-star", + "fa-list-check", +]; + +const text = (key, label, options = {}) => ({ + key, + label, + type: "text", + ...options, +}); + +const date = (key, label, options = {}) => ({ + key, + label, + type: "date", + ...options, +}); + +const hidden = (key, options = {}) => ({ + key, + type: "hidden", + ...options, +}); + +const textarea = (key, label, options = {}) => ({ + key, + label, + type: "textarea", + rows: options.rows || 4, + ...options, +}); + +const image = (key, label, options = {}) => ({ + key, + label, + type: "image", + ...options, +}); + +const icon = (key, label, options = {}) => ({ + key, + label, + type: "icon", + options: options.options || ICON_OPTIONS, + ...options, +}); + +const checkbox = (key, label, options = {}) => ({ + key, + label, + type: "checkbox", + ...options, +}); + +const url = (key, label, options = {}) => ({ + key, + label, + type: "url", + ...options, +}); + +const select = (key, label, options = [], extra = {}) => ({ + key, + label, + type: "select", + options, + ...extra, +}); + +const combobox = (key, label, options = {}) => ({ + key, + label, + type: "combobox", + ...options, +}); + +const object = (key, label, fields, options = {}) => ({ + key, + label, + type: "object", + fields, + ...options, +}); + +const stringList = (key, label, options = {}) => ({ + key, + label, + type: "array", + itemLabel: options.itemLabel || "Item", + sortable: options.sortable, + addLabel: options.addLabel, + helpText: options.helpText, + emptyText: options.emptyText, + itemSchema: { + type: "primitive", + fieldType: options.fieldType || "text", + label: options.itemLabel || "Item", + maxLength: options.maxLength, + min: options.min, + max: options.max, + step: options.step, + placeholder: options.placeholder, + helpText: options.itemHelpText, + }, + ...options, +}); + +const objectList = (key, label, fields, options = {}) => ({ + key, + label, + type: "array", + itemLabel: options.itemLabel || "Item", + sortable: options.sortable, + addLabel: options.addLabel, + helpText: options.helpText, + emptyText: options.emptyText, + itemTitleKey: options.itemTitleKey, + itemSubtitleKey: options.itemSubtitleKey, + itemActions: options.itemActions, + itemSchema: { + type: "object", + fields, + }, + ...options, +}); + +const variantList = (key, label, variants, options = {}) => ({ + key, + label, + type: "array", + itemLabel: options.itemLabel || "Item", + sortable: options.sortable, + addLabel: options.addLabel, + helpText: options.helpText, + emptyText: options.emptyText, + itemSchema: { + type: "variant", + discriminator: "type", + options: Object.keys(variants).map((value) => ({ + value, + label: variants[value].label, + })), + variants, + }, + ...options, +}); + +const linkFields = (prefix = "Link") => [ + text("label", `${prefix} label`, { maxLength: 40 }), + url("href", `${prefix} URL`, { maxLength: 255 }), +]; + +module.exports = { + ICON_OPTIONS, + text, + date, + hidden, + textarea, + image, + icon, + checkbox, + url, + select, + combobox, + object, + stringList, + objectList, + variantList, + linkFields, +}; diff --git a/utils/policiesBlockContent.js b/utils/policiesBlockContent.js new file mode 100644 index 0000000..720ce91 --- /dev/null +++ b/utils/policiesBlockContent.js @@ -0,0 +1,404 @@ +const { ensureUniqueIds, slugifyContentId } = require("./contentEditorIds"); + +const BLOCK_TYPES = new Set([ + "heading", + "paragraph", + "list", + "quote", + "divider", + "callout", +]); + +function createBlockId(prefix, value, index) { + return slugifyContentId(value, `${prefix}-${index + 1}`); +} + +function stripHtml(html = "") { + return String(html || "") + .replace(//gi, " ") + .replace(/<\/p>/gi, " ") + .replace(/<[^>]+>/g, " ") + .replace(/ /gi, " ") + .replace(/\s+/g, " ") + .trim(); +} + +function escapeHtml(value = "") { + return String(value) + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} + +function ensureParagraphHtml(value = "") { + const raw = String(value || "").trim(); + if (!raw) { + return ""; + } + + if (/<[a-z][\s\S]*>/i.test(raw)) { + return raw; + } + + return `

${escapeHtml(raw)}

`; +} + +function createInternalAnchor(policyId, label) { + return `${escapeHtml(label)}`; +} + +function createExternalAnchor(href, label) { + return `${escapeHtml(label)}`; +} + +function paragraphToHtml(paragraph = {}) { + const text = String(paragraph.text || ""); + const links = Array.isArray(paragraph.links) ? paragraph.links : []; + let html = escapeHtml(text); + + links.forEach((link, index) => { + const label = String(link.label || "").trim(); + if (!label) { + return; + } + + const anchor = link.tabId + ? createInternalAnchor(link.tabId, label) + : link.href + ? createExternalAnchor(link.href, label) + : escapeHtml(label); + + if (html.includes(escapeHtml(label))) { + html = html.replace(escapeHtml(label), anchor); + return; + } + + const suffix = index === 0 ? "" : " "; + html = `${html}${suffix}${anchor}`; + }); + + return `

${html}

`; +} + +function legacySectionToBlocks(section = {}, sectionIndex = 0) { + const blocks = []; + const heading = String(section.heading || section.title || "").trim(); + + if (heading) { + blocks.push({ + id: createBlockId("heading", heading, sectionIndex), + type: "heading", + level: 2, + html: `${escapeHtml(heading)}`, + }); + } + + if (section.type === "text") { + const paragraphs = Array.isArray(section.paragraphs) ? section.paragraphs : []; + paragraphs.forEach((paragraph, paragraphIndex) => { + blocks.push({ + id: createBlockId( + "paragraph", + paragraph.text || `${heading || "paragraph"}-${paragraphIndex + 1}`, + paragraphIndex, + ), + type: "paragraph", + html: paragraphToHtml(paragraph), + }); + }); + return blocks; + } + + if (section.type === "list") { + if (section.intro) { + blocks.push({ + id: createBlockId("paragraph", `${heading || "list"}-intro`, sectionIndex), + type: "paragraph", + html: ensureParagraphHtml(section.intro), + }); + } + + blocks.push({ + id: createBlockId("list", heading || `list-${sectionIndex + 1}`, sectionIndex), + type: "list", + style: "unordered", + items: (Array.isArray(section.items) ? section.items : []).map((item, itemIndex) => ({ + id: createBlockId("item", item || `item-${itemIndex + 1}`, itemIndex), + html: ensureParagraphHtml(item), + })), + }); + return blocks; + } + + if (section.type === "cards") { + const cards = Array.isArray(section.cards) ? section.cards : []; + cards.forEach((card, cardIndex) => { + const description = String(card.description || ""); + const linkHtml = card.link?.tabId + ? `

${createInternalAnchor(card.link.tabId, card.link.label || "Open")}

` + : card.link?.href + ? `

${createExternalAnchor(card.link.href, card.link.label || card.link.href)}

` + : ""; + + blocks.push({ + id: createBlockId("callout", card.title || `card-${cardIndex + 1}`, cardIndex), + type: "callout", + tone: "info", + title: String(card.title || ""), + icon: String(card.icon || ""), + html: `${ensureParagraphHtml(description)}${linkHtml}`, + }); + }); + } + + return blocks; +} + +function legacySectionsToBlocks(sections = []) { + return ensureUniqueIds( + (Array.isArray(sections) ? sections : []).flatMap(legacySectionToBlocks), + (block) => block.id, + (block, index) => stripHtml(block.html) || `${block.type}-${index + 1}`, + "block", + ); +} + +function normalizeListItems(items = []) { + return ensureUniqueIds( + (Array.isArray(items) ? items : []) + .map((item, index) => { + if (typeof item === "string") { + return { + id: createBlockId("item", item, index), + html: ensureParagraphHtml(item), + }; + } + + return { + id: item.id || createBlockId("item", stripHtml(item.html), index), + html: ensureParagraphHtml(item.html), + }; + }) + .filter((item) => item.html), + (item) => item.id, + (item, index) => stripHtml(item.html) || `item-${index + 1}`, + "item", + ); +} + +function normalizeBlock(block = {}, index = 0) { + const type = BLOCK_TYPES.has(block.type) ? block.type : "paragraph"; + const normalized = { + id: + block.id || + createBlockId(type, block.title || stripHtml(block.html) || type, index), + type, + }; + + if (type === "heading") { + normalized.level = [1, 2, 3].includes(Number(block.level)) + ? Number(block.level) + : 2; + normalized.html = ensureParagraphHtml(block.html || block.content || block.title || ""); + return normalized; + } + + if (type === "paragraph" || type === "quote") { + normalized.html = ensureParagraphHtml(block.html || block.content || ""); + if (type === "quote") { + normalized.caption = String(block.caption || ""); + } + return normalized; + } + + if (type === "list") { + normalized.style = block.style === "ordered" ? "ordered" : "unordered"; + normalized.items = normalizeListItems(block.items); + return normalized; + } + + if (type === "divider") { + return normalized; + } + + normalized.tone = ["info", "warning", "success"].includes(block.tone) + ? block.tone + : "info"; + normalized.title = String(block.title || ""); + normalized.icon = String(block.icon || ""); + normalized.html = ensureParagraphHtml(block.html || block.content || ""); + return normalized; +} + +function normalizeContent(content = {}) { + const blocks = ensureUniqueIds( + (Array.isArray(content.blocks) ? content.blocks : []).map(normalizeBlock), + (block) => block.id, + (block, index) => stripHtml(block.title || block.html) || `${block.type}-${index + 1}`, + "block", + ); + + return { + blocks, + }; +} + +function createEmptyContent() { + return { + blocks: [], + }; +} + +function normalizePolicyContent(policy = {}) { + if (policy.content && typeof policy.content === "object") { + return normalizeContent(policy.content); + } + + if (policy.contentByLanguage && typeof policy.contentByLanguage === "object") { + const englishContent = policy.contentByLanguage.en || policy.contentByLanguage.vi; + return normalizeContent(englishContent || createEmptyContent()); + } + + const migratedBlocks = legacySectionsToBlocks(policy.sections); + return normalizeContent({ blocks: migratedBlocks }); +} + +function normalizePolicy(policy = {}) { + const normalized = { + ...policy, + content: normalizePolicyContent(policy), + }; + + delete normalized.sections; + delete normalized.contentByLanguage; + return normalized; +} + +function normalizePoliciesDocument(data = {}) { + return { + ...data, + policies: (Array.isArray(data.policies) ? data.policies : []).map(normalizePolicy), + }; +} + +function parseAnchorAttributes(source = "") { + const attributes = {}; + const regex = /([a-zA-Z_:][a-zA-Z0-9:._-]*)\s*=\s*("([^"]*)"|'([^']*)')/g; + let match = regex.exec(source); + + while (match) { + attributes[match[1]] = match[3] || match[4] || ""; + match = regex.exec(source); + } + + return attributes; +} + +function collectLinkErrors(html = "", validPolicyIds = []) { + const errors = []; + const anchorRegex = /]*)>/gi; + let match = anchorRegex.exec(String(html || "")); + + while (match) { + const attrs = parseAnchorAttributes(match[1]); + const href = String(attrs.href || "").trim(); + const policyId = String(attrs["data-policy-id"] || "").trim(); + const isInternal = String(attrs["data-link-kind"] || "") === "internal"; + + if (isInternal) { + if (!policyId || !validPolicyIds.includes(policyId)) { + errors.push("Internal link points to an invalid policy."); + } + } else if ( + href && + !/^(https?:\/\/|mailto:|tel:|\/|#)/i.test(href) + ) { + errors.push(`Invalid link URL "${href}".`); + } + + if (!isInternal && !href) { + errors.push("Link is missing a URL."); + } + + match = anchorRegex.exec(String(html || "")); + } + + return errors; +} + +function validateBlocks(blocks = [], validPolicyIds = []) { + const errors = []; + const warnings = []; + let h1Count = 0; + + blocks.forEach((block, index) => { + const label = `Block ${index + 1}`; + + if (block.type === "heading" && Number(block.level) === 1) { + h1Count += 1; + } + + if (block.type === "divider") { + return; + } + + if (block.type === "list") { + if (!Array.isArray(block.items) || block.items.length === 0) { + warnings.push(`${label} has no list items.`); + } + + block.items.forEach((item, itemIndex) => { + if (!stripHtml(item.html)) { + warnings.push(`${label} item ${itemIndex + 1} is empty.`); + } + }); + + errors.push(...collectLinkErrors(JSON.stringify(block.items), validPolicyIds)); + return; + } + + if (block.type === "callout" && !stripHtml(block.html) && !stripHtml(block.title)) { + warnings.push(`${label} is empty.`); + } else if (!stripHtml(block.html) && block.type !== "divider") { + warnings.push(`${label} is empty.`); + } + + errors.push(...collectLinkErrors(block.html, validPolicyIds)); + }); + + if (h1Count > 1) { + errors.push( + `Content has ${h1Count} H1 blocks. Only one H1 is allowed.`, + ); + } + + return { errors, warnings }; +} + +function validateContent(content = {}, policyIds = []) { + const normalized = normalizeContent(content || createEmptyContent()); + const { errors, warnings } = validateBlocks(normalized.blocks, policyIds); + + if (normalized.blocks.length === 0) { + warnings.push("Content is empty."); + } + + return { + content: normalized, + errors: Array.from(new Set(errors)), + warnings: Array.from(new Set(warnings)), + }; +} + +module.exports = { + createEmptyContent, + normalizePolicy, + normalizePoliciesDocument, + normalizePolicyContent, + validateContent, + stripHtml, +}; diff --git a/views/admin/accreditation/index.ejs b/views/admin/accreditation/index.ejs new file mode 100644 index 0000000..737bfd3 --- /dev/null +++ b/views/admin/accreditation/index.ejs @@ -0,0 +1,63 @@ +
+
+
+

<%= title %>

+

<%= subtitle %>

+
+ +
+ +
+
+
+ + + +
+
+ +
+ +
+ <%- include("partials/hero-tab", { activeTab }) %> + <%- include("partials/grid-tab", { activeTab }) %> +
+
+ +
+ + +
+
+
+
+
+ + +<%- include("partials/editor-script") %> + + + + diff --git a/views/admin/accreditation/partials/editor-script.ejs b/views/admin/accreditation/partials/editor-script.ejs new file mode 100644 index 0000000..f088024 --- /dev/null +++ b/views/admin/accreditation/partials/editor-script.ejs @@ -0,0 +1,1066 @@ + + diff --git a/views/admin/accreditation/partials/grid-tab.ejs b/views/admin/accreditation/partials/grid-tab.ejs new file mode 100644 index 0000000..4dd5707 --- /dev/null +++ b/views/admin/accreditation/partials/grid-tab.ejs @@ -0,0 +1,13 @@ +
+
+
+
Accreditation Grid
+
+
+
+
+
+
+ + + diff --git a/views/admin/accreditation/partials/hero-tab.ejs b/views/admin/accreditation/partials/hero-tab.ejs new file mode 100644 index 0000000..491c454 --- /dev/null +++ b/views/admin/accreditation/partials/hero-tab.ejs @@ -0,0 +1,13 @@ +
+
+
+
Hero
+
+
+
+
+
+
+ + + diff --git a/views/admin/accreditation/partials/trust-banner-tab.ejs b/views/admin/accreditation/partials/trust-banner-tab.ejs new file mode 100644 index 0000000..bec62fe --- /dev/null +++ b/views/admin/accreditation/partials/trust-banner-tab.ejs @@ -0,0 +1,13 @@ +
+
+
+
Trust Banner
+
+
+
+
+
+
+ + + diff --git a/views/admin/admissions/calculator-option.ejs b/views/admin/admissions/calculator-option.ejs new file mode 100644 index 0000000..5839e97 --- /dev/null +++ b/views/admin/admissions/calculator-option.ejs @@ -0,0 +1,392 @@ +
+
+
+

<%= title %>

+

<%= subtitle %>

+
+ +
+ +
+
+
+
+
+
Option Details
+
+
+
+
+ + +
+
<%= fieldConfig.label?.helpText || "" %>
+
0/<%= fieldLimits.label %>
+
+
+ +
+ + +
+
<%= fieldConfig.paceLabel?.helpText || "" %>
+
0/<%= fieldLimits.paceLabel %>
+
+
+ +
+ + +
+
<%= fieldConfig.minPaceLabel?.helpText || "" %>
+
0/<%= fieldLimits.minPaceLabel %>
+
+
+ +
+ + +
+
<%= fieldConfig.maxPaceLabel?.helpText || "" %>
+
0/<%= fieldLimits.maxPaceLabel %>
+
+
+ +
+ + +
+
<%= fieldConfig.resultLabel?.helpText || "" %>
+
0/<%= fieldLimits.resultLabel %>
+
+
+ +
+ + +
+
<%= fieldConfig.monthlyAmount?.helpText || "" %>
+
+
+ +
+ + +
+
<%= fieldConfig.monthlySuffix?.helpText || "" %>
+
0/<%= fieldLimits.monthlySuffix %>
+
+
+ +
+ +
+ + + +
+
+
<%= fieldConfig.noteIcon?.helpText || "" %>
+
+
+ +
+ + +
+
<%= fieldConfig.note?.helpText || "" %>
+
0/<%= fieldLimits.note %>
+
+
+
+
+
+ +
+ + + Cancel + + +
+
+
+
+
+ + diff --git a/views/admin/admissions/index.ejs b/views/admin/admissions/index.ejs new file mode 100644 index 0000000..6bf5ada --- /dev/null +++ b/views/admin/admissions/index.ejs @@ -0,0 +1,68 @@ +
+
+
+

<%= title %>

+

<%= subtitle %>

+
+ +
+ +
+
+
+ + + +
+
+ +
+ +
+ <%- include("partials/hero-tab", { activeTab }) %> + <%- include("partials/process-tab", { activeTab }) %> + <%- include("partials/eligibility-tab", { activeTab }) %> + <%- include("partials/tuition-tab", { activeTab }) %> + <%- include("partials/key-dates-tab", { activeTab }) %> + <%- include("partials/calculator-tab", { activeTab }) %> + <%- include("partials/scholarships-tab", { activeTab }) %> +
+
+ +
+ + +
+
+
+
+
+ + +<%- include("partials/editor-script") %> + + + + diff --git a/views/admin/admissions/partials/calculator-tab.ejs b/views/admin/admissions/partials/calculator-tab.ejs new file mode 100644 index 0000000..cc8d1e6 --- /dev/null +++ b/views/admin/admissions/partials/calculator-tab.ejs @@ -0,0 +1,13 @@ +
+
+
+
Calculator
+
+
+
+
+
+
+ + + diff --git a/views/admin/admissions/partials/editor-script.ejs b/views/admin/admissions/partials/editor-script.ejs new file mode 100644 index 0000000..88c317d --- /dev/null +++ b/views/admin/admissions/partials/editor-script.ejs @@ -0,0 +1,1943 @@ + + diff --git a/views/admin/admissions/partials/eligibility-tab.ejs b/views/admin/admissions/partials/eligibility-tab.ejs new file mode 100644 index 0000000..587c41b --- /dev/null +++ b/views/admin/admissions/partials/eligibility-tab.ejs @@ -0,0 +1,13 @@ +
+
+
+
Eligibility
+
+
+
+
+
+
+ + + diff --git a/views/admin/admissions/partials/hero-tab.ejs b/views/admin/admissions/partials/hero-tab.ejs new file mode 100644 index 0000000..491c454 --- /dev/null +++ b/views/admin/admissions/partials/hero-tab.ejs @@ -0,0 +1,13 @@ +
+
+
+
Hero
+
+
+
+
+
+
+ + + diff --git a/views/admin/admissions/partials/key-dates-tab.ejs b/views/admin/admissions/partials/key-dates-tab.ejs new file mode 100644 index 0000000..4fb5d84 --- /dev/null +++ b/views/admin/admissions/partials/key-dates-tab.ejs @@ -0,0 +1,13 @@ +
+
+
+
Key Dates
+
+
+
+
+
+
+ + + diff --git a/views/admin/admissions/partials/process-tab.ejs b/views/admin/admissions/partials/process-tab.ejs new file mode 100644 index 0000000..fb01646 --- /dev/null +++ b/views/admin/admissions/partials/process-tab.ejs @@ -0,0 +1,13 @@ +
+
+
+
Admissions Process
+
+
+
+
+
+
+ + + diff --git a/views/admin/admissions/partials/scholarships-tab.ejs b/views/admin/admissions/partials/scholarships-tab.ejs new file mode 100644 index 0000000..a330d20 --- /dev/null +++ b/views/admin/admissions/partials/scholarships-tab.ejs @@ -0,0 +1,13 @@ +
+
+
+
Scholarships
+
+
+
+
+
+
+ + + diff --git a/views/admin/admissions/partials/tuition-tab.ejs b/views/admin/admissions/partials/tuition-tab.ejs new file mode 100644 index 0000000..5f6704d --- /dev/null +++ b/views/admin/admissions/partials/tuition-tab.ejs @@ -0,0 +1,13 @@ +
+
+
+
Tuition
+
+
+
+
+
+
+ + + diff --git a/views/admin/history/index.ejs b/views/admin/history/index.ejs new file mode 100644 index 0000000..b2063b5 --- /dev/null +++ b/views/admin/history/index.ejs @@ -0,0 +1,65 @@ +
+
+
+

<%= title %>

+

<%= subtitle %>

+
+ +
+ +
+
+
+ + + +
+
+ +
+ +
+ <%- include("partials/highlight-tab", { activeTab }) %> + <%- include("partials/hero-tab", { activeTab }) %> + <%- include("partials/filters-tab", { activeTab }) %> + <%- include("partials/timeline-tab", { activeTab }) %> +
+
+ +
+ + +
+
+
+
+
+ + +<%- include("partials/editor-script") %> + + + + diff --git a/views/admin/history/partials/editor-script.ejs b/views/admin/history/partials/editor-script.ejs new file mode 100644 index 0000000..e478419 --- /dev/null +++ b/views/admin/history/partials/editor-script.ejs @@ -0,0 +1,995 @@ + + diff --git a/views/admin/history/partials/filters-tab.ejs b/views/admin/history/partials/filters-tab.ejs new file mode 100644 index 0000000..8584999 --- /dev/null +++ b/views/admin/history/partials/filters-tab.ejs @@ -0,0 +1,13 @@ +
+
+
+
Filter Controls
+
+
+
+
+
+
+ + + diff --git a/views/admin/history/partials/hero-tab.ejs b/views/admin/history/partials/hero-tab.ejs new file mode 100644 index 0000000..491c454 --- /dev/null +++ b/views/admin/history/partials/hero-tab.ejs @@ -0,0 +1,13 @@ +
+
+
+
Hero
+
+
+
+
+
+
+ + + diff --git a/views/admin/history/partials/highlight-tab.ejs b/views/admin/history/partials/highlight-tab.ejs new file mode 100644 index 0000000..31c2aea --- /dev/null +++ b/views/admin/history/partials/highlight-tab.ejs @@ -0,0 +1,13 @@ +
+
+
+
Highlight Bar
+
+
+
+
+
+
+ + + diff --git a/views/admin/history/partials/timeline-tab.ejs b/views/admin/history/partials/timeline-tab.ejs new file mode 100644 index 0000000..508ceaa --- /dev/null +++ b/views/admin/history/partials/timeline-tab.ejs @@ -0,0 +1,13 @@ +
+
+
+
Timeline
+
+
+
+
+
+
+ + + diff --git a/views/admin/partnerships/index.ejs b/views/admin/partnerships/index.ejs new file mode 100644 index 0000000..b44a7eb --- /dev/null +++ b/views/admin/partnerships/index.ejs @@ -0,0 +1,68 @@ +
+
+
+

<%= title %>

+

<%= subtitle %>

+
+ +
+ +
+
+
+ + + +
+
+ +
+ +
+ <%- include("partials/hero-tab", { activeTab, data, backendUrl, editorUi }) %> + <%- include("partials/directory-tab", { activeTab, data, editorUi }) %> + <%- include("partials/cta-tab", { activeTab, data, editorUi }) %> + <%- include("partials/inquiry-form-tab", { activeTab, data, editorUi }) %> +
+
+ +
+ + +
+
+
+
+
+ +<%- include("partials/templates", { editorUi }) %> + + +<%- include("partials/editor-script") %> + + + + diff --git a/views/admin/partnerships/partials/cta-tab.ejs b/views/admin/partnerships/partials/cta-tab.ejs new file mode 100644 index 0000000..6fdc5b2 --- /dev/null +++ b/views/admin/partnerships/partials/cta-tab.ejs @@ -0,0 +1,27 @@ +
+ <% const ctaUi = editorUi.cta || {}; %> +
+
+
Call To Action
+
+
+
+
+ + +
+
+ + +
+
+ + +
+
+
+
+
+ + + diff --git a/views/admin/partnerships/partials/directory-tab.ejs b/views/admin/partnerships/partials/directory-tab.ejs new file mode 100644 index 0000000..cfbc648 --- /dev/null +++ b/views/admin/partnerships/partials/directory-tab.ejs @@ -0,0 +1,49 @@ +
+ <% const directoryUi = editorUi.directory || {}; %> +
+
+
Partner Directory
+
+
+
+
+ + +
+
+ + +
+
+ +
+
+
+ +
<%= directoryUi.tabsFrontendHint || directoryUi.tabs?.helpText || "" %>
+
+
+
+ +
+ +
+
+
+ +
<%= directoryUi.partnersHelpText || directoryUi.partners?.helpText || "" %>
+
+
+
+ +
+
+
+
+ + + diff --git a/views/admin/partnerships/partials/editor-script.ejs b/views/admin/partnerships/partials/editor-script.ejs new file mode 100644 index 0000000..24da14d --- /dev/null +++ b/views/admin/partnerships/partials/editor-script.ejs @@ -0,0 +1,620 @@ + diff --git a/views/admin/partnerships/partials/hero-tab.ejs b/views/admin/partnerships/partials/hero-tab.ejs new file mode 100644 index 0000000..655d6d6 --- /dev/null +++ b/views/admin/partnerships/partials/hero-tab.ejs @@ -0,0 +1,46 @@ +
+ <% const heroUi = editorUi.hero || {}; %> +
+
+
Hero
+
+
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+ + +
+
<%= [heroUi.image?.helpText, heroUi.image?.imageHint].filter(Boolean).join(" ") %>
+ +
+
+ + +
+
+
+
+
+ + + diff --git a/views/admin/partnerships/partials/inquiry-form-tab.ejs b/views/admin/partnerships/partials/inquiry-form-tab.ejs new file mode 100644 index 0000000..0328e78 --- /dev/null +++ b/views/admin/partnerships/partials/inquiry-form-tab.ejs @@ -0,0 +1,32 @@ +
+ <% const inquiryUi = editorUi.inquiryForm || {}; %> +
+
+
Inquiry Form
+
+
+
+
+ + +
+
+ +
+
+
+ +
<%= inquiryUi.fieldsHelpText || inquiryUi.fields?.helpText || "" %>
+
+
+
+ +
+
+
+
+ + + diff --git a/views/admin/partnerships/partials/templates.ejs b/views/admin/partnerships/partials/templates.ejs new file mode 100644 index 0000000..6d0c05a --- /dev/null +++ b/views/admin/partnerships/partials/templates.ejs @@ -0,0 +1,179 @@ +<% const directoryUi = editorUi.directory || {}; %> +<% const partnerFields = directoryUi.partnerFields || {}; %> +<% const inquiryUi = editorUi.inquiryForm || {}; %> +<% const inquiryFieldFields = inquiryUi.fieldFields || {}; %> + + + + + + + + diff --git a/views/admin/policies/index.ejs b/views/admin/policies/index.ejs new file mode 100644 index 0000000..baebcc2 --- /dev/null +++ b/views/admin/policies/index.ejs @@ -0,0 +1,62 @@ +
+
+
+

<%= title %>

+

<%= subtitle %>

+
+ +
+ +
+
+
+ + + +
+
+ +
+ +
+ <%- include("partials/hero-tab", { activeTab }) %> + <%- include("partials/sidebar-tab", { activeTab }) %> + <%- include("partials/policies-tab", { activeTab }) %> +
+
+ +
+ + +
+
+
+
+
+ + + + +<%- include("partials/editor-script") %> + + + + diff --git a/views/admin/policies/partials/editor-script.ejs b/views/admin/policies/partials/editor-script.ejs new file mode 100644 index 0000000..41152f0 --- /dev/null +++ b/views/admin/policies/partials/editor-script.ejs @@ -0,0 +1,1084 @@ + + diff --git a/views/admin/policies/partials/hero-tab.ejs b/views/admin/policies/partials/hero-tab.ejs new file mode 100644 index 0000000..cdf0857 --- /dev/null +++ b/views/admin/policies/partials/hero-tab.ejs @@ -0,0 +1,13 @@ +
+
+
+
Hero
+
+
+
+
+
+
+ + + diff --git a/views/admin/policies/partials/policies-tab.ejs b/views/admin/policies/partials/policies-tab.ejs new file mode 100644 index 0000000..6c07c77 --- /dev/null +++ b/views/admin/policies/partials/policies-tab.ejs @@ -0,0 +1,13 @@ +
+
+
+
Policies
+
+
+
+
+
+
+ + + diff --git a/views/admin/policies/partials/sidebar-tab.ejs b/views/admin/policies/partials/sidebar-tab.ejs new file mode 100644 index 0000000..0e20cbe --- /dev/null +++ b/views/admin/policies/partials/sidebar-tab.ejs @@ -0,0 +1,13 @@ + + + + diff --git a/views/admin/policies/sections.ejs b/views/admin/policies/sections.ejs new file mode 100644 index 0000000..639ca65 --- /dev/null +++ b/views/admin/policies/sections.ejs @@ -0,0 +1,896 @@ + + +
+
+ + + +
+
+
+
+
+

Modern CMS Editor

+

<%= data.policy.title %>

+
+ + + +
+
+ +
+ +
+
Validation needed before saving
+
+
+
+ +
+
+
+
+
+
+
+ + +
+ + +
+
+ +
+
+ + + + + + + + + + + +
+
+ + + +
+
+ + + + + + +
+
+ + + + diff --git a/views/layouts/main.ejs b/views/layouts/main.ejs index 3313781..a05e893 100644 --- a/views/layouts/main.ejs +++ b/views/layouts/main.ejs @@ -283,18 +283,22 @@ .fixed-bottom-buttons { position: fixed; - bottom: 0; + left: 0; right: 0; - padding: 1rem; + bottom: 0; + padding: 0.875rem 1.5rem; z-index: 1000; - width: 25%; display: flex; justify-content: flex-end; - gap: 0.5rem; + gap: 0.75rem; + background: rgba(255, 255, 255, 0.96); + border-top: 1px solid rgba(15, 23, 42, 0.08); + box-shadow: 0 -4px 6px -1px rgba(0, 0, 0, 0.08); + backdrop-filter: blur(8px); } .fixed-bottom-buttons .btn { - min-width: 120px; + min-width: 136px; display: inline-flex; align-items: center; justify-content: center; @@ -303,7 +307,318 @@ /* Add padding to prevent content from being hidden behind fixed buttons */ .content-with-fixed-buttons { - padding-bottom: 80px; + padding-bottom: 110px; + } + + .content-with-fixed-buttons .card { + border: 1px solid rgba(148, 163, 184, 0.16) !important; + box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04), 0 8px 24px rgba(15, 23, 42, 0.04) !important; + } + + .content-with-fixed-buttons .card-header { + background: #fff; + border-bottom: 1px solid rgba(148, 163, 184, 0.14); + padding: 0.875rem 1rem; + } + + .content-with-fixed-buttons .card-body { + padding: 1rem; + } + + .content-with-fixed-buttons .form-control, + .content-with-fixed-buttons .form-select { + background: #fff; + border: 1px solid rgba(148, 163, 184, 0.18); + box-shadow: none; + } + + .content-with-fixed-buttons .form-control:focus, + .content-with-fixed-buttons .form-select:focus { + border-color: rgba(184, 183, 106, 0.55); + box-shadow: 0 0 0 0.2rem rgba(184, 183, 106, 0.12); + } + + .content-with-fixed-buttons .form-text { + color: #94a3b8; + font-size: 0.75rem; + margin-top: 0.4rem; + } + + .content-with-fixed-buttons .card-header-tabs { + margin-bottom: -0.875rem; + } + + .content-with-fixed-buttons .nav-tabs { + border-bottom: 0; + gap: 0.25rem; + } + + .content-with-fixed-buttons .nav-tabs .nav-link { + border: 0; + border-radius: 8px 8px 0 0; + color: #64748b; + padding: 0.75rem 0.95rem; + } + + .content-with-fixed-buttons .nav-tabs .nav-link.active { + color: #0f172a; + background: rgba(248, 250, 252, 0.96); + box-shadow: inset 0 -2px 0 var(--primary-color); + } + + .cms-editor-group { + background: #f8fafc; + border: 1px solid rgba(148, 163, 184, 0.12); + border-radius: 12px; + padding: 1rem; + } + + .cms-item-card { + background: #f8fafc; + border: 1px solid rgba(148, 163, 184, 0.12) !important; + border-radius: 12px; + box-shadow: none !important; + } + + .cms-item-card .card-header { + background: transparent; + border-bottom: 1px solid rgba(148, 163, 184, 0.1); + padding: 0.75rem 0.875rem; + } + + .cms-item-card .card-body { + background: transparent; + padding: 0.875rem; + } + + .cms-item-card.is-collapsed .card-body { + display: none; + } + + .cms-item-card .drag-handle { + background: transparent; + border: 0; + color: #94a3b8; + padding: 0.25rem 0.375rem; + box-shadow: none; + } + + .cms-item-card .drag-handle:hover { + color: #475569; + background: rgba(255, 255, 255, 0.75); + } + + .cms-collapse-toggle { + display: inline-flex; + align-items: center; + justify-content: center; + width: 30px; + height: 30px; + border: 0; + background: transparent; + color: #94a3b8; + border-radius: 999px; + } + + .cms-collapse-toggle:hover { + background: rgba(148, 163, 184, 0.12); + color: #475569; + } + + .cms-collapse-toggle i { + transition: transform 0.18s ease; + } + + .cms-item-card.is-collapsed .cms-collapse-toggle i { + transform: rotate(-90deg); + } + + .cms-remove-button { + border: 0; + background: transparent; + color: #94a3b8; + padding: 0.25rem; + box-shadow: none; + } + + .cms-remove-button:hover { + color: #ef4444; + background: transparent; + } + + .cms-add-button { + width: 100%; + border: 1px dashed rgba(148, 163, 184, 0.55); + border-radius: 10px; + background: rgba(255, 255, 255, 0.7); + color: #475569; + padding: 0.8rem 1rem; + font-weight: 600; + } + + .cms-add-button:hover { + background: #fff; + border-color: rgba(184, 183, 106, 0.65); + color: var(--primary-dark); + } + + .field-meta-row { + display: flex; + justify-content: space-between; + align-items: flex-start; + gap: 0.75rem; + margin-top: 0.35rem; + } + + .field-char-count { + color: #94a3b8; + font-size: 0.75rem; + white-space: nowrap; + margin-left: auto; + } + + .cms-icon-combobox { + position: relative; + } + + .cms-icon-dropdown-trigger { + width: 100%; + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.75rem; + border: 1px solid rgba(148, 163, 184, 0.18); + border-radius: 10px; + background: #fff; + padding: 0.75rem; + color: #334155; + text-align: left; + } + + .cms-icon-dropdown-trigger:hover { + border-color: rgba(184, 183, 106, 0.55); + background: rgba(248, 250, 252, 0.96); + } + + .cms-icon-combobox.is-open .cms-icon-dropdown-trigger { + border-color: rgba(184, 183, 106, 0.65); + box-shadow: 0 0 0 0.2rem rgba(184, 183, 106, 0.12); + } + + .cms-icon-dropdown-value { + display: flex; + align-items: center; + gap: 0.75rem; + min-width: 0; + flex: 1; + } + + .cms-icon-dropdown-text { + min-width: 0; + display: flex; + flex-direction: column; + gap: 0.1rem; + } + + .cms-icon-dropdown-text strong, + .cms-icon-dropdown-text span { + display: block; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .cms-icon-dropdown-caret { + color: #94a3b8; + transition: transform 0.18s ease; + } + + .cms-icon-combobox.is-open .cms-icon-dropdown-caret { + transform: rotate(180deg); + } + + .cms-icon-preview { + width: 44px; + min-width: 44px; + height: 44px; + display: inline-flex; + align-items: center; + justify-content: center; + border: 1px solid rgba(148, 163, 184, 0.18); + border-radius: 8px; + background: #fff; + color: #334155; + } + + .cms-icon-dropdown-panel { + position: absolute; + top: calc(100% + 0.5rem); + left: 0; + right: 0; + z-index: 30; + background: #fff; + border: 1px solid rgba(148, 163, 184, 0.18); + border-radius: 10px; + padding: 0.75rem; + box-shadow: 0 10px 30px rgba(15, 23, 42, 0.12); + } + + .cms-icon-dropdown-panel .form-control { + margin-bottom: 0.75rem; + } + + .cms-icon-options { + max-height: 220px; + overflow: auto; + display: flex; + flex-direction: column; + gap: 0.375rem; + } + + .cms-icon-option { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.75rem; + width: 100%; + border: 1px solid rgba(148, 163, 184, 0.18); + background: #fff; + color: #334155; + border-radius: 8px; + padding: 0.55rem 0.7rem; + text-align: left; + font-size: 0.875rem; + } + + .cms-icon-option-main { + min-width: 0; + display: flex; + align-items: center; + gap: 0.625rem; + } + + .cms-icon-option-main span { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .cms-icon-option:hover { + border-color: rgba(184, 183, 106, 0.55); + background: rgba(248, 250, 252, 0.96); + color: #0f172a; + } + + .cms-icon-option.is-active { + border-color: rgba(184, 183, 106, 0.65); + background: rgba(184, 183, 106, 0.12); + color: #0f172a; + } + + .cms-icon-option-empty { + color: #94a3b8; + font-size: 0.75rem; + padding: 0.5rem 0.25rem 0; } main { @@ -720,9 +1035,19 @@ -