From 47d2a7fc3e477471c62c38695b94c2b99bf8b51c Mon Sep 17 00:00:00 2001 From: Hisham Aburaqibah Date: Mon, 28 Sep 2026 12:50:16 +0200 Subject: [PATCH] fix(cms): hardcode styled email templates --- apps/cms/.env.example | 8 +- .../content-types/email-settings/schema.json | 31 ------- apps/cms/src/bootstrap/email-settings.ts | 58 ------------ apps/cms/src/bootstrap/index.ts | 3 - apps/cms/src/components/email/template.json | 35 ------- apps/cms/src/lib/application-mail.ts | 17 ++-- apps/cms/src/lib/email-template-defaults.ts | 18 ++-- apps/cms/src/lib/email-templates.ts | 49 +--------- apps/cms/src/lib/event-mail.ts | 92 ++++++++++--------- apps/cms/types/generated/components.d.ts | 28 ------ apps/cms/types/generated/contentTypes.d.ts | 40 -------- 11 files changed, 70 insertions(+), 309 deletions(-) delete mode 100644 apps/cms/src/api/email-settings/content-types/email-settings/schema.json delete mode 100644 apps/cms/src/bootstrap/email-settings.ts delete mode 100644 apps/cms/src/components/email/template.json diff --git a/apps/cms/.env.example b/apps/cms/.env.example index 085a1a7..f2ea0b9 100644 --- a/apps/cms/.env.example +++ b/apps/cms/.env.example @@ -158,10 +158,10 @@ DEFAULT_REPLY_TO=support@yourdomain.com # confirmation, event-reminder and application-acknowledgement e-mails # (src/lib/event-mail.ts, src/lib/application-mail.ts). # -# The subject and body of those e-mails are editable in the CMS (the -# email-settings single type); the SHARP-ER / EU / partner logo header needs -# PUBLIC_URL (above) to build absolute image URLs - without it the mail falls -# back to a text wordmark. +# Their bilingual copy is hardcoded in src/lib/email-template-defaults.ts. +# Every message uses the styled HTML layout in src/lib/event-mail.ts. The +# SHARP-ER / EU / partner logos need PUBLIC_URL (above) to build absolute image +# URLs - without it the mail falls back to a text wordmark. # Production only - switching the upload provider to S3. Uncomment these after # adding @strapi/provider-upload-aws-s3 and editing the upload block in diff --git a/apps/cms/src/api/email-settings/content-types/email-settings/schema.json b/apps/cms/src/api/email-settings/content-types/email-settings/schema.json deleted file mode 100644 index bc8add4..0000000 --- a/apps/cms/src/api/email-settings/content-types/email-settings/schema.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "kind": "singleType", - "collectionName": "email_settings", - "info": { - "singularName": "email-settings", - "pluralName": "email-settings-list", - "displayName": "Email Settings", - "description": "The outbound email templates (registration confirmation, waitlist, reminder, application acknowledgement). Markdown bodies become HTML at send time. The values seeded here on first boot are also the defaults the mails fall back to when the row is missing. Read by the mail jobs only; not exposed over the public API." - }, - "options": { - "draftAndPublish": false - }, - "pluginOptions": { - "i18n": { - "localized": true - } - }, - "attributes": { - "templates": { - "type": "component", - "repeatable": true, - "component": "email.template", - "required": true, - "pluginOptions": { - "i18n": { - "localized": true - } - } - } - } -} \ No newline at end of file diff --git a/apps/cms/src/bootstrap/email-settings.ts b/apps/cms/src/bootstrap/email-settings.ts deleted file mode 100644 index 3602165..0000000 --- a/apps/cms/src/bootstrap/email-settings.ts +++ /dev/null @@ -1,58 +0,0 @@ -import type { Core } from '@strapi/strapi'; - -import { - DEFAULT_EMAIL_TEMPLATES, - EMAIL_TEMPLATE_KEYS, - type EmailTemplateKey, -} from '../lib/email-template-defaults'; -import { LOG_PREFIX } from './constants'; - -const EMAIL_SETTINGS_UID = 'api::email-settings.email-settings'; - -/** - * The `email.template` component payload for one locale of one template. - * `enabled` stays on so the shipped wording is the live configuration, keeping - * code defaults and CMS state in agreement on a fresh database. - */ -const templateRow = (key: EmailTemplateKey, locale: 'en' | 'ar') => ({ - key, - enabled: true, - subject: DEFAULT_EMAIL_TEMPLATES[key][locale].subject, - body: DEFAULT_EMAIL_TEMPLATES[key][locale].body, -}); - -/** - * Create the `email-settings` single type if the database does not have one - * yet, so the four email templates exist and are editable in the admin panel - * after the very first boot — carrying the shipped default copy. Never - * overwrites an existing row, so editor customisation survives every restart. - */ -export const ensureEmailSettings = async (strapi: Core.Strapi): Promise => { - const existing = await strapi - .documents(EMAIL_SETTINGS_UID) - .findFirst({}); - - if (existing) { - return; - } - - const templatesFor = (locale: 'en' | 'ar') => - EMAIL_TEMPLATE_KEYS.map((key) => templateRow(key, locale)); - - /* Arabic first — it is the default locale and the one a single type is - created on — then the English translation is written onto the same - document, which is how Strapi 5 models one document in two locales. */ - const created = await strapi.documents(EMAIL_SETTINGS_UID).create({ - locale: 'ar', - data: { templates: templatesFor('ar') }, - }); - await strapi.documents(EMAIL_SETTINGS_UID).update({ - documentId: created.documentId, - locale: 'en', - data: { templates: templatesFor('en') }, - }); - - strapi.log.info( - `${LOG_PREFIX} created email-settings single type with the four default email templates.` - ); -}; \ No newline at end of file diff --git a/apps/cms/src/bootstrap/index.ts b/apps/cms/src/bootstrap/index.ts index 23a46e9..6f8aa54 100644 --- a/apps/cms/src/bootstrap/index.ts +++ b/apps/cms/src/bootstrap/index.ts @@ -2,7 +2,6 @@ import type { Core } from '@strapi/strapi'; import { revokePublicAuthActions } from './auth-permissions'; import { LOG_PREFIX } from './constants'; -import { ensureEmailSettings } from './email-settings'; import { ensureLocales } from './locales'; import { ensurePublicPermissions } from './public-permissions'; import { ensurePartnerReviewPermissions } from './partner-review-permissions'; @@ -11,7 +10,6 @@ import { ensurePartnerRelationLabels } from './partner-relation-labels'; import { ensureReminderSettings } from './reminder-settings'; export { revokePublicAuthActions } from './auth-permissions'; -export { ensureEmailSettings } from './email-settings'; export { ensureLocales } from './locales'; export { ensurePublicPermissions } from './public-permissions'; export { ensureReminderSettings } from './reminder-settings'; @@ -34,7 +32,6 @@ export const runBootstrap = async ({ strapi }: { strapi: Core.Strapi }): Promise await ensurePublicPermissions(strapi); await revokePublicAuthActions(strapi); await ensureReminderSettings(strapi); - await ensureEmailSettings(strapi); await ensurePartnerReviewPermissions(strapi); await ensurePartnerReviewLayouts(strapi); await ensurePartnerRelationLabels(strapi); diff --git a/apps/cms/src/components/email/template.json b/apps/cms/src/components/email/template.json deleted file mode 100644 index 59b0711..0000000 --- a/apps/cms/src/components/email/template.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "collectionName": "components_email_templates", - "info": { - "displayName": "Email Template", - "icon": "envelop", - "description": "One outbound email template: a subject plus a markdown body. The body is converted to HTML at send time. Placeholders: {event}, {date} and {call}. A placeholder whose value is missing collapses together with the word before it, so \"for {call}\" (and \"على {call}\") reads cleanly when there is no call." - }, - "options": {}, - "attributes": { - "key": { - "type": "enumeration", - "enum": [ - "confirmation", - "waitlist", - "event-reminder", - "application-acknowledgement" - ], - "required": true - }, - "enabled": { - "type": "boolean", - "default": true, - "description": "Off reverts this email to the shipped default copy." - }, - "subject": { - "type": "string", - "required": true, - "maxLength": 250 - }, - "body": { - "type": "richtext", - "required": true - } - } -} \ No newline at end of file diff --git a/apps/cms/src/lib/application-mail.ts b/apps/cms/src/lib/application-mail.ts index 84817bc..283f02c 100644 --- a/apps/cms/src/lib/application-mail.ts +++ b/apps/cms/src/lib/application-mail.ts @@ -11,19 +11,18 @@ * retried by nothing today but is visible in the admin panel as a null. * * The (Get Involved) section form can submit an application with no - * opportunity relation. The mail then drops the call name and stays a plain - * acknowledgement, so the promise holds for both entry points. + * opportunity relation. The mail then drops the call name and uses the + * no-call acknowledgement, so the promise holds for both entry points. * - * COPY IS CMS-DRIVEN like the event mails: subject and body come from the - * `email-settings` single type's `application-acknowledgement` template, whose - * shipped default is the approved wording. The call name fills the `{call}` + * Copy is hardcoded in `email-template-defaults.ts`, and this message uses the + * same styled HTML layout as the event emails. The call name fills the `{call}` * placeholder; when there is no call name the placeholder and its preceding * word collapse, leaving the no-call variant automatically. */ import type { Core } from '@strapi/strapi'; -import { resolveEmailTemplate } from './email-templates'; +import { DEFAULT_EMAIL_TEMPLATES } from './email-template-defaults'; import { buildBilingualMail, trySendMail } from './event-mail'; const OPPORTUNITY_UID = 'api::opportunity.opportunity'; @@ -85,10 +84,8 @@ export async function sendApplicationAcknowledgement({ opportunityReference: OpportunityReference; }): Promise { try { - const [opportunity, template] = await Promise.all([ - fetchBilingualOpportunity(strapi, opportunityReference), - resolveEmailTemplate(strapi, 'application-acknowledgement'), - ]); + const opportunity = await fetchBilingualOpportunity(strapi, opportunityReference); + const template = DEFAULT_EMAIL_TEMPLATES['application-acknowledgement']; const callEn = opportunity.en?.title || undefined; const callAr = opportunity.ar?.title || opportunity.en?.title || undefined; diff --git a/apps/cms/src/lib/email-template-defaults.ts b/apps/cms/src/lib/email-template-defaults.ts index 79ce2ae..1b41449 100644 --- a/apps/cms/src/lib/email-template-defaults.ts +++ b/apps/cms/src/lib/email-template-defaults.ts @@ -1,12 +1,9 @@ /** - * email-template-defaults — the shipped subject and body for every email the - * CMS sends. + * email-template-defaults — the hardcoded subject and body for every email + * the CMS sends. * - * These are the "default for each email template": first-boot writes them into - * the `email-settings` single type (src/bootstrap/email-settings.ts) so editors - * start from a working, editable baseline, and they remain the fallback in code - * when the single type is missing, unreadable or a template is switched off — - * which is what keeps the mails sending even if nothing was ever configured. + * This is the source of truth for outbound email copy. Changing a template + * requires a code change and review; the CMS does not store editable copies. * * The copy is the wording the mail modules hard-coded before this file existed, * which itself mirrors the approved web copy (apps/web i18n messages and @@ -37,8 +34,8 @@ export type LocalisedEmailTemplate = { /** * The two approved acknowledgement wordings, kept for their exact strings: - * the with-call variant is the shipped default and the no-call variant is what - * the placeholder collapse reproduces when there is no opportunity. + * the no-call variant is what placeholder collapse produces when there is no + * opportunity. */ const ACKNOWLEDGEMENT_WITH_CALL = { ar: 'شكرًا لك — استلمنا طلبك على {call}. سيراجع فريقنا طلبك ويتواصل معك عبر البريد الإلكتروني.', @@ -46,8 +43,7 @@ const ACKNOWLEDGEMENT_WITH_CALL = { } as const; /** - * The plain acknowledgement (no call), reproduced verbatim so editors can - * compare against the collapsed form when the placeholder is empty. + * The plain acknowledgement (no call), reproduced verbatim for reference. */ const ACKNOWLEDGEMENT_WITHOUT_CALL = { ar: 'شكرًا لك — استلمنا طلبك. سيراجع فريقنا طلبك ويتواصل معك عبر البريد الإلكتروني.', diff --git a/apps/cms/src/lib/email-templates.ts b/apps/cms/src/lib/email-templates.ts index ef8bce3..339787c 100644 --- a/apps/cms/src/lib/email-templates.ts +++ b/apps/cms/src/lib/email-templates.ts @@ -1,53 +1,8 @@ /** - * email-templates — resolve hardcoded copy and shared placeholders for the - * outbound mails. - * - * The subjects and markdown bodies live in email-template-defaults.ts. This - * resolver returns those values directly; the CMS has no runtime copy source. - * - * resolveEmailTemplate the subject/body pair for a key, per locale, each - * locale falling back to its own code default when - * the row is missing, switched off or unreadable. - * fillPlaceholders the {event} / {date} / {call} substitution, shared - * by both mail modules. An empty value removes the - * placeholder together with the word before it, so - * "for {call}" / "على {call}" collapse cleanly when - * there is no call (see the component description). + * email-templates — shared placeholder interpolation for hardcoded outbound + * email templates. Subjects and bodies live in email-template-defaults.ts. */ -import type { Core } from '@strapi/strapi'; - -import { - DEFAULT_EMAIL_TEMPLATES, - type EmailTemplateKey, - type LocalisedEmailTemplate, -} from './email-template-defaults'; - -/* --------------------------------------------------------------------------- - TEMPLATES - ------------------------------------------------------------------------ */ - -/** The hardcoded per-locale subject/body for one template key. */ -export type ResolvedEmailTemplate = { - ar: LocalisedEmailTemplate; - en: LocalisedEmailTemplate; -}; - -/** - * The subject and body for one template key, per locale. The retained Strapi - * argument keeps callers stable while all senders move to the static source. - */ -export function resolveEmailTemplate( - _strapi: Core.Strapi, - key: EmailTemplateKey -): ResolvedEmailTemplate { - return DEFAULT_EMAIL_TEMPLATES[key]; -} - -/* --------------------------------------------------------------------------- - PLACEHOLDERS - ------------------------------------------------------------------------ */ - /** Literal values for {event} / {date} / {call}, per locale, unescaped. */ export type PlaceholderValues = Readonly>; diff --git a/apps/cms/src/lib/event-mail.ts b/apps/cms/src/lib/event-mail.ts index 791630f..3240450 100644 --- a/apps/cms/src/lib/event-mail.ts +++ b/apps/cms/src/lib/event-mail.ts @@ -14,23 +14,16 @@ * The Arabic block always comes first and is marked dir="rtl"; the English * block follows inside the same message. Subjects are bilingual too. * - * COPY IS CMS-DRIVEN. The subject and body for each mail come from the - * `email-settings` single type — markdown bodies, converted to HTML at send - * time (see lib/markdown.ts) — with the shipped approved copy as the fallback - * (see lib/email-template-defaults.ts). This module owns the chrome around - * that copy: the event lookups, the {event} / {date} placeholders, the venue - * or join-online line, and the logo header/footer (SHARP-ER logo, EU badge - * and the consortium partner logos, read from `site-settings`). + * COPY IS HARDCODED in lib/email-template-defaults.ts. This module owns the + * shared styled HTML layout, event lookups, the {event} / {date} placeholders, + * venue or join-online line, and EU/partner branding. */ import type { Core } from '@strapi/strapi'; import { buildEventCalendar } from './event-calendar'; -import { - resolveEmailTemplate, - fillPlaceholders, - type PlaceholderValues, -} from './email-templates'; +import { DEFAULT_EMAIL_TEMPLATES } from './email-template-defaults'; +import { fillPlaceholders, type PlaceholderValues } from './email-templates'; import { mdToHtml, mdToText, escapeHtml } from './markdown'; const EVENT_UID = 'api::event.event'; @@ -401,27 +394,46 @@ export function buildBilingualMail(opts: { Object.entries(values).map(([name, value]) => [name, escapeHtml(value)]) ); - const html = ` + const subject = `${fillPlaceholders(subjectAr, varsAr)} | ${fillPlaceholders(subjectEn, varsEn)}`; + + const html = ` + + + + + ${escapeHtml(subject)} ${renderJsonLd(jsonLd)} - ${renderBrandHeader()} -
-
- ${fillPlaceholders(mdToHtml(bodyAr), escaped(varsAr))} - ${locationHtml(locationLine?.ar)} -
-
-
- ${fillPlaceholders(mdToHtml(bodyEn), escaped(varsEn))} - ${locationHtml(locationLine?.en)} -
-
-

- ${FOOTER.ar} -

-

- ${FOOTER.en} -

- ${renderPartnerLogos()}`; + + + + +
+ + +
+ ${renderBrandHeader()} +
+
+ ${fillPlaceholders(mdToHtml(bodyAr), escaped(varsAr))} + ${locationHtml(locationLine?.ar)} +
+
 
+
+ ${fillPlaceholders(mdToHtml(bodyEn), escaped(varsEn))} + ${locationHtml(locationLine?.en)} +
+
+

+ ${FOOTER.ar} +

+

+ ${FOOTER.en} +

+ ${renderPartnerLogos()} +
+
+ +`; const text = [ fillPlaceholders(mdToText(bodyAr), varsAr), @@ -437,7 +449,7 @@ export function buildBilingualMail(opts: { .join('\n'); return { - subject: `${fillPlaceholders(subjectAr, varsAr)} | ${fillPlaceholders(subjectEn, varsEn)}`, + subject, text, html, }; @@ -489,7 +501,7 @@ type MailOptions = { to: string; subject: string; text: string; - html?: string; + html: string; attachments?: MailAttachment[]; }; @@ -553,10 +565,8 @@ export async function sendRegistrationConfirmation({ try { const isWaitlist = state === 'waitlisted'; - const [event, template] = await Promise.all([ - fetchBilingualEvent(strapi, eventReference), - resolveEmailTemplate(strapi, isWaitlist ? 'waitlist' : 'confirmation'), - ]); + const event = await fetchBilingualEvent(strapi, eventReference); + const template = DEFAULT_EMAIL_TEMPLATES[isWaitlist ? 'waitlist' : 'confirmation']; if (!event.en && !event.ar) { strapi.log.warn( @@ -623,10 +633,8 @@ export async function sendEventReminderMail({ reservation: ReservationIdentity; }): Promise { try { - const [event, template] = await Promise.all([ - fetchBilingualEvent(strapi, eventReference), - resolveEmailTemplate(strapi, 'event-reminder'), - ]); + const event = await fetchBilingualEvent(strapi, eventReference); + const template = DEFAULT_EMAIL_TEMPLATES['event-reminder']; if (!event.en && !event.ar) { strapi.log.warn( diff --git a/apps/cms/types/generated/components.d.ts b/apps/cms/types/generated/components.d.ts index 8375dfa..4df8e31 100644 --- a/apps/cms/types/generated/components.d.ts +++ b/apps/cms/types/generated/components.d.ts @@ -110,33 +110,6 @@ export interface BlocksVideoEmbed extends Struct.ComponentSchema { }; } -export interface EmailTemplate extends Struct.ComponentSchema { - collectionName: 'components_email_templates'; - info: { - description: 'One outbound email template: a subject plus a markdown body. The body is converted to HTML at send time. Placeholders: {event}, {date} and {call}. A placeholder whose value is missing collapses together with the word before it, so "for {call}" (and "\u0639\u0644\u0649 {call}") reads cleanly when there is no call.'; - displayName: 'Email Template'; - icon: 'envelop'; - }; - attributes: { - body: Schema.Attribute.RichText & Schema.Attribute.Required; - enabled: Schema.Attribute.Boolean & Schema.Attribute.DefaultTo; - key: Schema.Attribute.Enumeration< - [ - 'confirmation', - 'waitlist', - 'event-reminder', - 'application-acknowledgement', - ] - > & - Schema.Attribute.Required; - subject: Schema.Attribute.String & - Schema.Attribute.Required & - Schema.Attribute.SetMinMaxLength<{ - maxLength: 250; - }>; - }; -} - export interface NavigationFooterColumn extends Struct.ComponentSchema { collectionName: 'components_navigation_footer_columns'; info: { @@ -393,7 +366,6 @@ declare module '@strapi/strapi' { 'blocks.quote': BlocksQuote; 'blocks.rich-text': BlocksRichText; 'blocks.video-embed': BlocksVideoEmbed; - 'email.template': EmailTemplate; 'navigation.footer-column': NavigationFooterColumn; 'navigation.nav-group': NavigationNavGroup; 'page.band-intro': PageBandIntro; diff --git a/apps/cms/types/generated/contentTypes.d.ts b/apps/cms/types/generated/contentTypes.d.ts index 9e63361..aa1b12e 100644 --- a/apps/cms/types/generated/contentTypes.d.ts +++ b/apps/cms/types/generated/contentTypes.d.ts @@ -852,45 +852,6 @@ export interface ApiContactSubmissionContactSubmission }; } -export interface ApiEmailSettingsEmailSettings extends Struct.SingleTypeSchema { - collectionName: 'email_settings'; - info: { - description: 'The outbound email templates (registration confirmation, waitlist, reminder, application acknowledgement). Markdown bodies become HTML at send time. The values seeded here on first boot are also the defaults the mails fall back to when the row is missing. Read by the mail jobs only; not exposed over the public API.'; - displayName: 'Email Settings'; - pluralName: 'email-settings-list'; - singularName: 'email-settings'; - }; - options: { - draftAndPublish: false; - }; - pluginOptions: { - i18n: { - localized: true; - }; - }; - attributes: { - createdAt: Schema.Attribute.DateTime; - createdBy: Schema.Attribute.Relation<'oneToOne', 'admin::user'> & - Schema.Attribute.Private; - locale: Schema.Attribute.String; - localizations: Schema.Attribute.Relation< - 'oneToMany', - 'api::email-settings.email-settings' - >; - publishedAt: Schema.Attribute.DateTime; - templates: Schema.Attribute.Component<'email.template', true> & - Schema.Attribute.Required & - Schema.Attribute.SetPluginOptions<{ - i18n: { - localized: true; - }; - }>; - updatedAt: Schema.Attribute.DateTime; - updatedBy: Schema.Attribute.Relation<'oneToOne', 'admin::user'> & - Schema.Attribute.Private; - }; -} - export interface ApiEventRegistrationEventRegistration extends Struct.CollectionTypeSchema { collectionName: 'event_registrations'; @@ -2869,7 +2830,6 @@ declare module '@strapi/strapi' { 'api::application.application': ApiApplicationApplication; 'api::contact-page.contact-page': ApiContactPageContactPage; 'api::contact-submission.contact-submission': ApiContactSubmissionContactSubmission; - 'api::email-settings.email-settings': ApiEmailSettingsEmailSettings; 'api::event-registration.event-registration': ApiEventRegistrationEventRegistration; 'api::event.event': ApiEventEvent; 'api::faq.faq': ApiFaqFaq;