diff --git a/backend/migrations/core/101_add_customer_gallery_assigned_template.js b/backend/migrations/core/101_add_customer_gallery_assigned_template.js
new file mode 100644
index 00000000..557c400b
--- /dev/null
+++ b/backend/migrations/core/101_add_customer_gallery_assigned_template.js
@@ -0,0 +1,243 @@
+/**
+ * Migration: Add `customer_gallery_assigned` email template.
+ *
+ * Sent when an admin adds new gallery assignments to an existing
+ * customer via the "Manage galleries" dialog on the customer detail
+ * page. Digest-style — one email per save listing every newly added
+ * gallery, not one email per gallery (admins often set up new clients
+ * by adding several galleries in a single sitting).
+ *
+ * Variables:
+ * - customer_name greeting name (display name / first name / email local)
+ * - gallery_count integer (string) — number of newly added galleries
+ * - singular "true" when count === 1 (drives intro wording)
+ * - multiple "true" when count > 1
+ * - gallery_list_html pre-rendered
with names + dates; passes
+ * through unescaped because the service builds it
+ * from trusted DB fields (event_name from
+ * admin-owned rows + server-rendered dates).
+ * - gallery_list_text newline-separated plain-text equivalent for
+ * the text/plain body.
+ * - dashboard_link URL of /customer/dashboard on the configured
+ * frontend origin.
+ *
+ * Category + flag: 'customers' + customerPortal — categorisation
+ * scaffold from migration 098. When the customer portal flag is off,
+ * the Templates admin UI chips this card "Feature off" but it's still
+ * editable.
+ *
+ * Translations: en + de hand-translated; nl/pt/ru/fr machine-generated
+ * and flagged for native review per project convention.
+ *
+ * Idempotent: skips if the template_key already exists.
+ */
+
+const TRANSLATIONS = {
+ en: {
+ subject: 'New gallery access on your account',
+ body_html: `
You have new gallery access
+
Hi {{customer_name}},
+{{#if singular}}
Your photographer just gave you access to a new gallery on your account:
{{/if}}{{#if multiple}}
Your photographer just gave you access to {{gallery_count}} new galleries on your account:
If the button doesn't work, copy and paste this link into your browser:
+{{dashboard_link}}
`,
+ body_text: `You have new gallery access
+
+Hi {{customer_name}},
+
+Your photographer just gave you access to {{gallery_count}} new gallery (or galleries) on your account:
+
+{{gallery_list_text}}
+
+Open your dashboard: {{dashboard_link}}`,
+ },
+ de: {
+ subject: 'Neue Galerie in deinem Konto verfügbar',
+ body_html: `
Du hast Zugriff auf neue Galerien
+
Hallo {{customer_name}},
+{{#if singular}}
Dein Fotograf hat dir gerade Zugriff auf eine neue Galerie in deinem Konto gegeben:
{{/if}}{{#if multiple}}
Dein Fotograf hat dir gerade Zugriff auf {{gallery_count}} neue Galerien in deinem Konto gegeben:
Werkt de knop niet? Kopieer dan deze link in uw browser:
+{{dashboard_link}}
`,
+ body_text: `U heeft toegang tot nieuwe galerijen
+
+Hallo {{customer_name}},
+
+Uw fotograaf heeft u zojuist toegang gegeven tot {{gallery_count}} nieuwe galerij(en) in uw account:
+
+{{gallery_list_text}}
+
+Dashboard: {{dashboard_link}}`,
+ },
+ pt: {
+ subject: 'Nova galeria disponível em sua conta',
+ body_html: `
Você tem acesso a novas galerias
+
Olá {{customer_name}},
+{{#if singular}}
Seu fotógrafo acabou de lhe dar acesso a uma nova galeria em sua conta:
{{/if}}{{#if multiple}}
Seu fotógrafo acabou de lhe dar acesso a {{gallery_count}} novas galerias em sua conta:
Se o botão não funcionar, copie este link no navegador:
+{{dashboard_link}}
`,
+ body_text: `Você tem acesso a novas galerias
+
+Olá {{customer_name}},
+
+Seu fotógrafo acabou de lhe dar acesso a {{gallery_count}} nova(s) galeria(s) em sua conta:
+
+{{gallery_list_text}}
+
+Painel: {{dashboard_link}}`,
+ },
+ ru: {
+ subject: 'Новая галерея доступна в вашем аккаунте',
+ body_html: `
У вас новый доступ к галереям
+
Здравствуйте, {{customer_name}}!
+{{#if singular}}
Ваш фотограф только что предоставил вам доступ к новой галерее в вашем аккаунте:
{{/if}}{{#if multiple}}
Ваш фотограф только что предоставил вам доступ к {{gallery_count}} новым галереям в вашем аккаунте:
Если кнопка не работает, скопируйте эту ссылку в браузер:
+{{dashboard_link}}
`,
+ body_text: `У вас новый доступ к галереям
+
+Здравствуйте, {{customer_name}}!
+
+Ваш фотограф только что предоставил вам доступ к {{gallery_count}} новым галереям в вашем аккаунте:
+
+{{gallery_list_text}}
+
+Личный кабинет: {{dashboard_link}}`,
+ },
+};
+
+exports.up = async function(knex) {
+ if (!(await knex.schema.hasTable('email_templates'))) return;
+
+ const existing = await knex('email_templates')
+ .where({ template_key: 'customer_gallery_assigned' })
+ .first();
+ if (existing) {
+ console.log(' customer_gallery_assigned template already exists, skipping insert');
+ return;
+ }
+
+ // Detect schema variant (legacy per-column vs normalized translations).
+ // Newer installs have the email_template_translations table from
+ // migration 075; older ones might still have subject_en/de/... columns
+ // and NOT NULL constraints on the legacy columns. Cover both.
+ const cols = await knex('email_templates').columnInfo();
+ const hasTranslationsTable = await knex.schema.hasTable('email_template_translations');
+
+ const enContent = TRANSLATIONS.en;
+
+ // Build the master row. category/subcategory/feature_flag columns
+ // were added in migration 098 — guard so this migration works on
+ // a slightly older install too.
+ const masterRow = {
+ template_key: 'customer_gallery_assigned',
+ variables: JSON.stringify([
+ 'customer_name',
+ 'gallery_count',
+ 'singular',
+ 'multiple',
+ 'gallery_list_html',
+ 'gallery_list_text',
+ 'dashboard_link',
+ ]),
+ };
+ if ('category' in cols) masterRow.category = 'customers';
+ if ('subcategory' in cols) masterRow.subcategory = null;
+ if ('feature_flag' in cols) masterRow.feature_flag = 'customerPortal';
+ if ('created_at' in cols) masterRow.created_at = new Date();
+ if ('updated_at' in cols) masterRow.updated_at = new Date();
+
+ // Populate any legacy subject_*/body_html_*/body_text_* columns the
+ // schema still carries. Fallback content for non-en locales is the
+ // English string — the translations table below has the real
+ // per-locale copy. This only matters if the install hasn't run
+ // migration 075 yet, which is rare but possible.
+ for (const colName of Object.keys(cols)) {
+ if (colName === 'subject' || /^subject_[a-z]{2,3}$/i.test(colName)) {
+ masterRow[colName] = enContent.subject;
+ } else if (colName === 'body_html' || /^body_html_[a-z]{2,3}$/i.test(colName)) {
+ masterRow[colName] = enContent.body_html;
+ } else if (colName === 'body_text' || /^body_text_[a-z]{2,3}$/i.test(colName)) {
+ masterRow[colName] = enContent.body_text;
+ }
+ }
+
+ const inserted = await knex('email_templates').insert(masterRow).returning('id');
+ const templateId = typeof inserted[0] === 'object' ? inserted[0].id : inserted[0];
+
+ if (hasTranslationsTable && templateId) {
+ for (const [language, content] of Object.entries(TRANSLATIONS)) {
+ await knex('email_template_translations').insert({
+ template_id: templateId,
+ language,
+ subject: content.subject,
+ body_html: content.body_html,
+ body_text: content.body_text,
+ created_at: new Date(),
+ updated_at: new Date(),
+ });
+ }
+ }
+
+ console.log(' customer_gallery_assigned template inserted with 6 translations');
+};
+
+exports.down = async function(knex) {
+ if (!(await knex.schema.hasTable('email_templates'))) return;
+ await knex('email_templates').where({ template_key: 'customer_gallery_assigned' }).del();
+};
diff --git a/backend/server.js b/backend/server.js
index 5048b4a1..dd0d9ee2 100644
--- a/backend/server.js
+++ b/backend/server.js
@@ -568,30 +568,36 @@ app.use('/api/admin/photo-export', require('./src/routes/adminPhotoExport'));
app.use('/api/admin/css-templates', require('./src/routes/adminCssTemplates'));
app.use('/api/admin/events', require('./src/routes/adminEventRename'));
app.use('/api/admin/users', require('./src/routes/adminUsers'));
-// Customer portal (#354). The customerPortal feature flag is enforced
-// in TWO places:
+// Customer portal (#354). The customerPortal feature flag is a
+// VISIBILITY toggle for the admin surface, not a kill switch for
+// customer access. Enforcement:
+//
// 1. Frontend: RequireFeature guards + AdminSidebar visibility
-// (handles navigation cleanly when an admin is using the app).
-// 2. Backend: the requireCustomerPortalEnabled middleware below.
-// Belt-and-braces — a stale tab, a saved bookmark, or any
-// third-party API client trying to hit /api/customer/* or
-// /api/admin/customers/* gets a 410 Gone the moment the toggle
-// is flipped off. Includes /api/customer/auth/login: flag off
-// = nobody can log in until the admin re-enables, including
-// already-issued customers (their sessions still have valid
-// JWTs but every API call returns 410 → frontend boots them
-// out). PR #458 deliberate departure from the prior design
-// that left login alive when the rest of the surface was off.
-const {
- requireCustomerPortalEnabled,
- requireCustomerPortalEnabledAdmin,
-} = require('./src/middleware/requireCustomerPortal');
-
-app.use('/api/admin/customers', requireCustomerPortalEnabledAdmin, require('./src/routes/adminCustomers'));
+// hide the Clients section when the flag is off. Customer-side
+// /customer/* surfaces stay reachable.
+// 2. Backend: NO route-level gate. The admin surface is gated by
+// adminAuth + permission checks (admin still has rights to
+// manage customer records even if the section is hidden in
+// their UI). The customer surface is gated by customerAuth +
+// is_active checks on customer_accounts.
+//
+// For close-to-realtime access changes use the dedicated tools:
+// - Revoke a customer's access to ONE gallery → "Manage galleries"
+// dialog removes the event_customer_assignments row, which
+// verifyGalleryAccess re-checks on every customer-minted JWT.
+// - Lock out a customer entirely → "Deactivate" sets is_active=false
+// and bumps password_changed_at, killing every outstanding JWT.
+// - Toggle per-customer feature surfaces (calendar/quotes/bills)
+// → toggles on the customer detail page.
+//
+// Putting the global flag in the kill-switch role was a mistake — a
+// stray click in Settings → Features would lock every paying
+// customer out at once. PR-revert moved the gate back to per-record.
+app.use('/api/admin/customers', require('./src/routes/adminCustomers'));
// Customer-side surface (#354). Strictly separate from /api/admin/* —
// distinct token type, distinct cookie, distinct middleware.
-app.use('/api/customer/auth', requireCustomerPortalEnabled, require('./src/routes/customerAuth'));
-app.use('/api/customer', requireCustomerPortalEnabled, require('./src/routes/customer'));
+app.use('/api/customer/auth', require('./src/routes/customerAuth'));
+app.use('/api/customer', require('./src/routes/customer'));
app.use('/api/admin/event-types', require('./src/routes/adminEventTypes'));
app.use('/api/admin/api-tokens', require('./src/routes/adminApiTokens'));
app.use('/api/admin/webhooks', require('./src/routes/adminWebhooks'));
diff --git a/backend/src/middleware/gallery.js b/backend/src/middleware/gallery.js
index 03f01a75..f22051ab 100644
--- a/backend/src/middleware/gallery.js
+++ b/backend/src/middleware/gallery.js
@@ -120,7 +120,36 @@ async function verifyGalleryAccess(req, res, next) {
logger.warn('[verifyGalleryAccess] Event not found for slug', { slug: requestedSlug || 'no-slug', tokenEventId: decoded.eventId });
return res.status(404).json({ error: 'Gallery not found or expired' });
}
-
+
+ // Customer-minted gallery JWTs (#354): when the customer obtained
+ // this token via /api/customer/events/:slug/access-token, the
+ // payload carries `via:'customer'` and `customerId`. The admin
+ // can revoke the customer's access at any time by removing the
+ // event_customer_assignments row from the "Manage galleries"
+ // dialog on the customer detail page. Re-check that row here so
+ // the revocation takes effect on the customer's very next
+ // request — no token-blacklisting machinery required.
+ if (decoded.via === 'customer' && decoded.customerId) {
+ const assignment = await withRetry(async () => {
+ return await db('event_customer_assignments')
+ .where({
+ event_id: event.id,
+ customer_account_id: decoded.customerId,
+ })
+ .first();
+ });
+ if (!assignment) {
+ logger.info('[verifyGalleryAccess] Customer assignment revoked, rejecting token', {
+ customerId: decoded.customerId,
+ eventId: event.id,
+ });
+ return res.status(403).json({
+ error: 'Access to this gallery has been revoked',
+ code: 'CUSTOMER_ASSIGNMENT_REVOKED',
+ });
+ }
+ }
+
logger.debug('[verifyGalleryAccess] Event located', { eventId: event.id, slug: event.slug });
req.event = event;
req.accessLevel = decoded.accessLevel || 'guest';
diff --git a/backend/src/middleware/requireCustomerPortal.js b/backend/src/middleware/requireCustomerPortal.js
deleted file mode 100644
index 5b307e71..00000000
--- a/backend/src/middleware/requireCustomerPortal.js
+++ /dev/null
@@ -1,62 +0,0 @@
-/**
- * Customer portal feature-flag gate.
- *
- * Blocks every /api/customer/* and /api/admin/customers/* endpoint
- * when the `customerPortal` flag is off. Returns 410 Gone so the
- * frontend can distinguish "feature has been disabled" from "you
- * don't have access" (which would be 403) — useful for the customer
- * dashboard's auto-redirect on a soft-kill scenario.
- *
- * Reads the flag via customerAccountsService.isCustomerPortalEnabled
- * (which itself reads from the maintainer's feature_flags table),
- * so a single source of truth.
- */
-
-const customerAccountsService = require('../services/customerAccountsService');
-const logger = require('../utils/logger');
-
-async function isEnabled() {
- try {
- return await customerAccountsService.isCustomerPortalEnabled();
- } catch (err) {
- // Defensive: if the lookup throws (DB unavailable, table missing
- // mid-migration), fail closed so an enabled-by-default fallback
- // can't accidentally expose customer surfaces during boot.
- logger.warn('requireCustomerPortal: feature flag lookup failed, treating as off', {
- error: err?.message,
- });
- return false;
- }
-}
-
-/**
- * Customer-facing endpoints. Returns 410 with a code the frontend
- * can interpret to clear stale session storage + redirect to
- * /admin/login.
- */
-async function requireCustomerPortalEnabled(req, res, next) {
- if (await isEnabled()) return next();
- return res.status(410).json({
- error: 'Customer portal is disabled',
- code: 'CUSTOMER_PORTAL_DISABLED',
- });
-}
-
-/**
- * Admin-facing /api/admin/customers/* endpoints. Same gate, same
- * status code — keeps the contract consistent across both halves of
- * the customer-portal surface. The sidebar UI already hides the
- * entry, but a stale tab or direct API call must also be blocked.
- */
-async function requireCustomerPortalEnabledAdmin(req, res, next) {
- if (await isEnabled()) return next();
- return res.status(410).json({
- error: 'Customer portal is disabled',
- code: 'CUSTOMER_PORTAL_DISABLED',
- });
-}
-
-module.exports = {
- requireCustomerPortalEnabled,
- requireCustomerPortalEnabledAdmin,
-};
diff --git a/backend/src/routes/adminCustomers.js b/backend/src/routes/adminCustomers.js
index 07579db8..54d7a8ae 100644
--- a/backend/src/routes/adminCustomers.js
+++ b/backend/src/routes/adminCustomers.js
@@ -310,4 +310,35 @@ router.post('/:id/password-reset', [
successResponse(res, { email: result.email, expiresAt: result.expiresAt });
}));
+/**
+ * PUT /api/admin/customers/:id/events — replace the customer's full
+ * event assignment list. Backs the "Manage galleries" dialog on the
+ * customer detail page. Body is `{ event_ids: number[] }`. Empty
+ * array clears every assignment.
+ *
+ * Access revocation is implicit: gallery middleware checks for a
+ * live event_customer_assignments row whenever it decodes a
+ * customer-minted gallery JWT, so removing an assignment here
+ * immediately blocks the customer's next gallery request without
+ * needing to enumerate + revoke any active tokens. Permission tier
+ * is customers.create (same as invite + deactivate) — managing
+ * which galleries a customer can see is a write-class operation
+ * on the customer record.
+ */
+router.put('/:id/events', [
+ adminAuth,
+ requirePermission('customers.create'),
+ param('id').isInt({ min: 1 }),
+ body('event_ids').isArray(),
+ body('event_ids.*').isInt({ min: 1 }),
+], handleAsync(async (req, res) => {
+ validateRequest(req);
+ const result = await customerAccountsService.setAssignmentsForCustomer(
+ parseInt(req.params.id, 10),
+ req.body.event_ids,
+ req.admin.id,
+ );
+ successResponse(res, result);
+}));
+
module.exports = router;
diff --git a/backend/src/routes/customerAuth.js b/backend/src/routes/customerAuth.js
index 87eb7b4b..8de968d8 100644
--- a/backend/src/routes/customerAuth.js
+++ b/backend/src/routes/customerAuth.js
@@ -48,15 +48,20 @@ const TOKEN_TTL_SECONDS = 24 * 60 * 60; // mirrors admin tokens
// ---- login -------------------------------------------------------------
-// Flag-gate note: this route IS now gated by the customerPortal feature
-// flag via the requireCustomerPortalEnabled middleware mounted in
-// server.js (`app.use('/api/customer/auth', requireCustomerPortalEnabled, …)`).
-// When the admin flips the toggle off in Settings → Features, every
-// customer-side endpoint — including login — returns 410. The previous
-// design left login reachable while the rest of the surface was gated;
-// that was confusing and asymmetric. Single source of truth wins.
-// To lock out a specific customer without disabling the feature for
-// everyone, deactivate the account (customer_accounts.is_active = false).
+// The customerPortal feature flag deliberately does NOT gate this route.
+// Flipping the master toggle off in Settings → Features hides the
+// admin-side Clients section (sidebar entry, /admin/clients pages) but
+// must not revoke access for customers who already accepted an
+// invitation — that would mean a stray click in the Features tab
+// locks every paying customer out at once.
+//
+// To revoke access at the customer level, use the per-record tools:
+// - "Deactivate" on the customer detail page → sets
+// customer_accounts.is_active = false AND bumps password_changed_at,
+// which customerAuth rejects below + on every protected route.
+// - "Manage galleries" dialog → removes event_customer_assignments
+// rows, which verifyGalleryAccess re-checks on customer-minted
+// gallery JWTs (instant per-gallery revocation).
router.post('/login', [
body('email').isEmail().normalizeEmail().withMessage('Valid email is required'),
body('password').isString().notEmpty(),
diff --git a/backend/src/services/customerAccountsService.js b/backend/src/services/customerAccountsService.js
index 1271f58f..96255c6d 100644
--- a/backend/src/services/customerAccountsService.js
+++ b/backend/src/services/customerAccountsService.js
@@ -638,6 +638,185 @@ async function setAssignmentsForEvent(eventId, targetCustomerIds, adminId, trx =
return { added: toAdd.length, removed: toRemove.length };
}
+/**
+ * Inverse of setAssignmentsForEvent: replace the full set of events a
+ * single customer is assigned to. Backs the "Manage galleries" dialog
+ * on the customer detail page — admins pick from every available
+ * event and we diff against the existing row set.
+ *
+ * Returns { added, removed } so the caller can surface a useful toast.
+ *
+ * `targetEventIds` may be empty to clear every assignment.
+ *
+ * Access revocation: removing a row from event_customer_assignments
+ * is enough on its own — gallery middleware (galleryMiddleware.js)
+ * checks for a live assignment whenever it decodes a JWT minted via
+ * the customer access-token endpoint (decoded.via === 'customer').
+ * No separate revoked_tokens write needed; the customer's next
+ * request 401s the moment this transaction commits.
+ */
+async function setAssignmentsForCustomer(customerId, targetEventIds, adminId, trx = db) {
+ const wanted = new Set((targetEventIds || []).map(Number).filter((n) => Number.isFinite(n) && n > 0));
+ const existing = await trx('event_customer_assignments')
+ .where('customer_account_id', customerId)
+ .select('id', 'event_id');
+ const existingIds = new Set(existing.map((r) => r.event_id));
+
+ const toAdd = [...wanted].filter((id) => !existingIds.has(id));
+ const toRemove = existing.filter((r) => !wanted.has(r.event_id));
+
+ if (toRemove.length > 0) {
+ await trx('event_customer_assignments')
+ .whereIn('id', toRemove.map((r) => r.id))
+ .del();
+ }
+
+ // Collect the event IDs that actually landed in the DB (i.e. survived
+ // the archived/missing filter) so the post-commit notifier knows
+ // exactly which galleries to mention in the email. Empty by default.
+ let addedEventIds = [];
+
+ if (toAdd.length > 0) {
+ // Validate the events exist + are not archived before inserting.
+ // Mirrors the customer-side check in setAssignmentsForEvent so an
+ // admin can't accidentally pin a customer to an archived event
+ // that they couldn't actually open anyway.
+ const valid = await trx('events')
+ .whereIn('id', toAdd)
+ .where('is_archived', formatBoolean(false))
+ .pluck('id');
+ const validSet = new Set(valid);
+ const ignored = toAdd.filter((id) => !validSet.has(id));
+ if (ignored.length > 0) {
+ logger.warn('Ignoring missing/archived event ids in customer assignment', {
+ customerId, ignored,
+ });
+ }
+ const rows = [...validSet].map((eventId) => ({
+ event_id: eventId,
+ customer_account_id: customerId,
+ assigned_by_admin_id: adminId,
+ assigned_at: new Date(),
+ }));
+ if (rows.length > 0) {
+ await trx('event_customer_assignments').insert(rows);
+ addedEventIds = rows.map((r) => r.event_id);
+ }
+ }
+
+ // Notify the customer about newly-accessible galleries. Best-effort
+ // — a failure here must not roll back the assignment write, so we
+ // fire-and-forget after the transactional work is done and swallow
+ // any throw with a warn log. Skipped when no new rows were added.
+ if (addedEventIds.length > 0) {
+ notifyCustomerOfNewAssignments(customerId, addedEventIds).catch((err) => {
+ logger.warn('Failed to queue customer_gallery_assigned email', {
+ customerId, addedEventIds, error: err?.message,
+ });
+ });
+ }
+
+ return { added: toAdd.length, removed: toRemove.length, addedEventIds };
+}
+
+/**
+ * Queue a `customer_gallery_assigned` email summarising newly-granted
+ * gallery access for one customer. Called by setAssignmentsForCustomer
+ * after the transaction commits.
+ *
+ * Rules:
+ * - One email per save (digest), not one per gallery.
+ * - Archived + expired events are filtered out — the customer would
+ * hit a "this gallery has expired" notice anyway, so naming them
+ * in the email just confuses people.
+ * - Deactivated customers (is_active=false) get no email — their
+ * login is off, so a "you have new access" message would be
+ * misleading.
+ * - Customers without an email on file are skipped (silently —
+ * should never happen for accepted accounts but defensive).
+ * - Email failures are logged but never bubble up; the caller's
+ * `.catch` handler logs again at a more specific call site.
+ */
+async function notifyCustomerOfNewAssignments(customerId, addedEventIds) {
+ if (!addedEventIds || addedEventIds.length === 0) return;
+
+ const customer = await db('customer_accounts')
+ .where({ id: customerId, is_active: formatBoolean(true) })
+ .select('id', 'email', 'display_name', 'first_name', 'preferred_language')
+ .first();
+ if (!customer || !customer.email) {
+ logger.info('Skip customer_gallery_assigned email: customer missing/inactive/no email', {
+ customerId,
+ });
+ return;
+ }
+
+ // Filter the added events to those the customer can actually open.
+ // Archived events are hard-skipped; expired ones (expires_at in the
+ // past) would render as "Expired DD MMM" in the dashboard and lead
+ // to a confusing "I clicked the link in the email and got a 410"
+ // experience — drop those too.
+ const now = new Date();
+ const events = await db('events')
+ .whereIn('id', addedEventIds)
+ .where('is_archived', formatBoolean(false))
+ .andWhere(function() {
+ this.whereNull('expires_at').orWhere('expires_at', '>', now);
+ })
+ .orderBy('event_date', 'desc')
+ .select('id', 'slug', 'event_name', 'event_date');
+
+ if (events.length === 0) {
+ logger.info('Skip customer_gallery_assigned email: all added events archived/expired', {
+ customerId, addedEventIds,
+ });
+ return;
+ }
+
+ // Build the gallery list block. HTML is whitelisted via
+ // HTML_PASSTHROUGH_KEYS in emailProcessor so the
survives the
+ // body-html escaping pass. Names + dates come from admin-controlled
+ // DB rows; the date is server-rendered.
+ const { formatDate } = require('../utils/dateFormatter');
+ const { escapeHtml } = require('../utils/formatters');
+ const language = customer.preferred_language || 'en';
+
+ const formattedRows = await Promise.all(events.map(async (ev) => ({
+ name: ev.event_name || ev.slug,
+ date: ev.event_date ? await formatDate(ev.event_date, language) : '',
+ })));
+
+ const galleryListHtml = `