Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -4,8 +4,6 @@ import { sendEmailMailjet } from "./MailjetEmailService";
const emailLogger = createScopedLogger("email");
type EmailProvider = "mailjet";
export async function sendEmail({
request,
to,
@@ -68,6 +68,41 @@ describe("sendEmailMailjet", () => {
);
});
test("preserves portal tenant and source metadata for the final worker feature gate", async () => {
const queue = createQueueMock();
await sendEmailMailjet(
{
data: {
to: "customer@example.com",
subject: "Portal sign-in",
body: "<p>Sign in</p>",
alias: "magic-link",
source: "portal-auth-mail",
tenantId: "tenant_portal_1",
priorityOverride: "critical",
},
},
{ queue }
);
const descriptor = buildTransactionalMailJob({
to: ["customer@example.com"],
subject: "Portal sign-in",
html: "<p>Sign in</p>",
tenantId: "tenant_portal_1",
metadata: { alias: "magic-link", source: "portal-auth-mail" },
});
expect(queue.add).toHaveBeenCalledWith(
"send-transactional-email",
descriptor.payload,
expect.objectContaining({
...buildRetryJobOptions(descriptor),
priority: 1,
})
);
});
test("fails closed when Redis is missing without falling back to synchronous mail", async () => {
await expect(sendEmailMailjet(
{
@@ -8,7 +8,7 @@ import {
type RedisConnectionEnv,
type TypedQueue,
} from "@hivegrid/queue";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
export type SendEmailMailjetDependencies = {
env?: RedisConnectionEnv;
@@ -23,7 +23,9 @@ export async function sendEmailMailjet(
to: string;
subject?: string;
body?: string;
text?: string;
alias?: string;
source?: string;
data?: {
[key: string]: any;
};
@@ -35,20 +37,26 @@ export async function sendEmailMailjet(
dependencies: SendEmailMailjetDependencies = {}
) {
const mailProvider = dependencies.queue
? createTransactionalQueueProvider(dependencies.queue, data.alias, data.data)
: createTransactionalQueueProviderFromEnv(dependencies.env, data.alias, data.data);
? createTransactionalQueueProvider(dependencies.queue, data.alias, data.data, data.source)
: createTransactionalQueueProviderFromEnv(dependencies.env, data.alias, data.data, data.source);
return await mailProvider.send({
to: [data.to],
subject: data.subject,
html: data.body,
text: data.text,
tenantId: data.tenantId,
priorityOverride: data.priorityOverride,
...(data.attachments && data.attachments.length > 0 ? { attachments: data.attachments } : {}),
});
}
function createTransactionalQueueProviderFromEnv(env?: RedisConnectionEnv, alias?: string, templateData?: Record<string, unknown>): MailProvider {
function createTransactionalQueueProviderFromEnv(
env?: RedisConnectionEnv,
alias?: string,
templateData?: Record<string, unknown>,
source?: string
): MailProvider {
const connection = env ? resolveRedisConnectionOptions({ env }) : resolveRedisConnectionOptionsFromProcessEnv();
if (!connection) {
@@ -72,7 +80,7 @@ function createTransactionalQueueProviderFromEnv(env?: RedisConnectionEnv, alias
const { createQueue } = (await import(/* @vite-ignore */ queueRuntimeModule)) as typeof import("@hivegrid/queue/runtime");
const queue = createQueue(queueNames.email, { connection });
try {
return await createTransactionalQueueProvider(queue, alias, templateData).send(input);
return await createTransactionalQueueProvider(queue, alias, templateData, source).send(input);
} finally {
await queue.close();
}
@@ -80,21 +88,31 @@ function createTransactionalQueueProviderFromEnv(env?: RedisConnectionEnv, alias
};
}
function createTransactionalQueueProvider(queue: TypedQueue<typeof queueNames.email>, alias?: string, templateData?: Record<string, unknown>): MailProvider {
function createTransactionalQueueProvider(
queue: TypedQueue<typeof queueNames.email>,
alias?: string,
templateData?: Record<string, unknown>,
source?: string
): MailProvider {
return {
id: "queue",
async send(input) {
const descriptor = buildTransactionalMailJob({
to: input.to.map((recipient) => (typeof recipient === "string" ? recipient : recipient.email)),
subject: input.subject,
text: input.text,
html: input.html,
templateData,
// Forward attachments (e.g. AK-P16b booking .ics) — the payload already
// supports them; only this provider hop was dropping the field.
...(input.attachments && input.attachments.length > 0 ? { attachments: input.attachments } : {}),
metadata: alias ? { alias } : undefined,
...(input.tenantId !== undefined && input.tenantId !== null ? { tenantId: input.tenantId } : {}),
metadata: alias || source ? { ...(alias ? { alias } : {}), ...(source ? { source } : {}) } : undefined,
});
const job = await enqueueJob(queue, descriptor, {
...(input.tenantId !== undefined ? { tenantId: input.tenantId } : {}),
...(input.priorityOverride !== undefined ? { priorityOverride: input.priorityOverride } : {}),
});
const job = await enqueueJob(queue, descriptor);
return {
provider: "queue",
@@ -56,6 +56,7 @@ describe("queueTransactionalEmail", () => {
to: "user@example.com",
subject: "Reset password",
body: "<p>Reset</p>",
text: "Reset",
alias: "password-reset",
tenantId: "tenant_1",
userId: "user_1",
@@ -71,6 +72,7 @@ describe("queueTransactionalEmail", () => {
const descriptor = buildTransactionalMailJob({
to: ["user@example.com"],
subject: "Reset password",
text: "Reset",
html: "<p>Reset</p>",
templateData: { action_url: "https://example.com/reset" },
tenantId: "tenant_1",
@@ -104,6 +106,36 @@ describe("queueTransactionalEmail", () => {
expect(runtimeQueue.close).toHaveBeenCalledOnce();
});
test("uses only an opaque verification idempotency key in BullMQ job identity and metadata", async () => {
const add = vi.fn(async () => ({ id: "job_opaque" }));
const queue = { add } as unknown as TypedQueue<typeof queueNames.email>;
const email = "ada@example.com";
const verificationToken = "raw-verification-capability";
const creationRequestKey = "d7077797-054b-497a-b1ce-8e4f36257a96";
const opaqueKey = "registration-verification:registration_1:184a82a6628ec5c7d863148d76f5598a";
await queueTransactionalEmail(
{
to: email,
subject: "Verify your email",
body: `<a href="https://example.test/verify/${verificationToken}">Verify</a>`,
alias: "email-verification",
idempotencyKey: opaqueKey,
},
{ queue }
);
const [, payload, options] = add.mock.calls[0] ?? [];
const serializedIdentity = JSON.stringify({
jobId: options?.jobId,
metadata: payload?.metadata,
});
expect(serializedIdentity).toContain(opaqueKey);
expect(serializedIdentity).not.toContain(email);
expect(serializedIdentity).not.toContain(verificationToken);
expect(serializedIdentity).not.toContain(creationRequestKey);
});
test("propagates enqueue failures without synchronous mail fallback", async () => {
const enqueueError = new Error("queue unavailable");
const add = vi.fn(async () => {
@@ -12,10 +12,13 @@ export type QueueTransactionalEmailInput = {
to: string;
subject?: string;
body?: string;
text?: string;
alias?: string;
tenantId?: string;
userId?: string;
data?: Record<string, unknown>;
/** Stable, non-PII key used to collapse ambiguous enqueue retries. */
idempotencyKey?: string;
/**
* Explicit BullMQ priority for this mail job. Use `"critical"` for
* auth-flow mails (password-reset, magic-link, invitation, verification)
@@ -24,11 +27,10 @@ export type QueueTransactionalEmailInput = {
priorityOverride?: "critical" | "high" | "normal" | "low";
};
export type QueueTransactionalEmailResult =
| {
enqueued: true;
jobId?: string;
};
export type QueueTransactionalEmailResult = {
enqueued: true;
jobId?: string;
};
type QueueTransactionalEmailDependencies = {
env?: RedisConnectionEnv;
@@ -67,17 +69,20 @@ export async function queueTransactionalEmail(
const descriptor = buildTransactionalMailJob({
to: [input.to],
subject: input.subject,
text: input.text,
html: input.body,
templateData: input.data,
tenantId: input.tenantId,
userId: input.userId,
metadata: {
alias: input.alias,
...(input.idempotencyKey ? { idempotencyKey: input.idempotencyKey } : {}),
},
});
const job = await enqueueJob(queue, descriptor, {
...(input.tenantId !== undefined ? { tenantId: input.tenantId } : {}),
...(input.priorityOverride !== undefined ? { priorityOverride: input.priorityOverride } : {}),
...(input.idempotencyKey ? { idempotencyKey: input.idempotencyKey } : {}),
});
return {
@@ -67,7 +67,7 @@ describe("TransactionalEmailSettings.server", () => {
const result = await updateMailjetSettings(form);
expect(result).toEqual({ success: false, error: "Only Mailjet is supported for transactional email." });
expect(result).toEqual({ success: false, errorKey: "settings.admin.transactionalEmails.errors.unsupportedProvider" });
expect(updateAppConfigurationMock).not.toHaveBeenCalled();
});
@@ -76,7 +76,7 @@ describe("TransactionalEmailSettings.server", () => {
const result = await updateMailjetSettings(form);
expect(result).toEqual({ success: false, error: "Mailjet API keys are configured through environment variables only." });
expect(result).toEqual({ success: false, errorKey: "settings.admin.transactionalEmails.errors.apiKeyEnvironmentOnly" });
expect(updateAppConfigurationMock).not.toHaveBeenCalled();
});
@@ -20,7 +20,12 @@ export type MailjetProviderStatus = {
export type UpdateMailjetSettingsResult =
| { success: true }
| { success: false; error: string };
| {
success: false;
errorKey:
| "settings.admin.transactionalEmails.errors.unsupportedProvider"
| "settings.admin.transactionalEmails.errors.apiKeyEnvironmentOnly";
};
export async function getMailjetProviderStatus({ request }: { request: Request }): Promise<MailjetProviderStatus> {
await getAppConfiguration({ request });
@@ -51,11 +56,11 @@ export async function getMailjetProviderStatus({ request }: { request: Request }
export async function updateMailjetSettings(form: FormData): Promise<UpdateMailjetSettingsResult> {
const provider = form.get("emailProvider")?.toString();
if (provider !== MAILJET_PROVIDER_ID) {
return { success: false, error: "Only Mailjet is supported for transactional email." };
return { success: false, errorKey: "settings.admin.transactionalEmails.errors.unsupportedProvider" };
}
if (form.get("apiKey")?.toString().trim()) {
return { success: false, error: "Mailjet API keys are configured through environment variables only." };
return { success: false, errorKey: "settings.admin.transactionalEmails.errors.apiKeyEnvironmentOnly" };
}
await updateAppConfiguration({
@@ -26,12 +26,17 @@ describe("EmailTemplates", () => {
const rendered = EmailTemplates.WELCOME_EMAIL.parse({
appConfiguration,
data: { name: "Ada", action_url: actionUrl },
locale: "en",
});
expect(rendered.subject).toBe("Welcome to Acme Portal, Ada!");
expect(rendered.subject).toBe("Welcome to Acme Portal, Ada");
expect(rendered.body).toContain(actionUrl);
expect(rendered.body).toContain("Acme Portal");
expect(rendered.body).toContain('<html lang="en">');
expect(rendered.body.startsWith("<!DOCTYPE html>")).toBe(true);
expect(rendered.text).toContain("Great to have you here, Ada");
expect(rendered.text).toContain("Booked features unlock after payment is confirmed");
expect(rendered.text).toContain("Continue setup");
expect(rendered.data).toEqual({ name: "Ada", action_url: actionUrl });
});
@@ -57,7 +62,7 @@ describe("EmailTemplates", () => {
},
});
expect(rendered.subject).toBe("Grace invited you to Example Org on Acme Portal");
expect(rendered.subject).toBe("Grace invited you to Example Org in Acme Portal");
expect(rendered.body).toContain("Grace");
expect(rendered.body).toContain("Example Org");
expect(rendered.body).toContain(actionUrl);
@@ -69,9 +74,57 @@ describe("EmailTemplates", () => {
data: { name: "Ada", action_url: actionUrl },
});
expect(rendered.subject).toBe("Verify your Acme Portal email address");
expect(rendered.subject).toBe("Please confirm your email address");
expect(rendered.body).toContain(actionUrl);
expect(rendered.body).toMatch(/expires? in 30 minutes/i);
expect(rendered.text).toContain("review your plan, add-ons, and payment method");
expect(rendered.text).toContain("Features unlock only after payment is confirmed");
expect(rendered.body).toContain("This confirmation link is valid for 24 hours");
});
it("uses localized verification preview, expiry, outro and footer without English fallbacks", () => {
const translations: Record<string, string> = {
"emailVerification.subject": "Bestätige deine E-Mail-Adresse bei Acme Portal",
"emailVerification.previewText": "E-Mail-Adresse bei Acme Portal bestätigen",
"emailVerification.eyebrow": "E-Mail-Bestätigung",
"emailVerification.title_named": "Danke fürs Anmelden, Ada!",
"emailVerification.intro": "Bestätige deine E-Mail-Adresse, um die Einrichtung abzuschließen.",
"emailVerification.actionLabel": "E-Mail bestätigen",
"emailVerification.outro": "Wenn du diese Bestätigung nicht angefordert hast, kannst du diese E-Mail ignorieren.",
"emailVerification.expiresText": "Dieser Bestätigungslink ist 24 Stunden gültig und kann nur einmal verwendet werden.",
"common.signoff.closing": "Viele Grüße",
"common.signoff.team": "Dein Acme-Team",
"common.legal.privacyLabel": "Datenschutz",
"common.legal.termsLabel": "AGB",
"common.legal.imprintLabel": "Impressum",
"common.legal.unsubscribeLabel": "Abmelden",
"common.support.htmlBefore": "Bei Fragen kannst du uns gerne",
"common.support.emailLinkLabel": "eine E-Mail schreiben",
"common.support.htmlAfter": ".",
};
const rendered = EmailTemplates.VERIFICATION_EMAIL.parse({
appConfiguration,
data: { name: "Ada", action_url: actionUrl },
t: (key) => translations[key] ?? key,
locale: "de",
});
expect(rendered.body).toContain("Dieser Bestätigungslink ist 24 Stunden gültig");
expect(rendered.body).toContain("Wenn du diese Bestätigung nicht angefordert hast");
expect(rendered.body).toContain("Datenschutz");
expect(rendered.body).toContain('<html lang="de">');
expect(rendered.body).not.toContain("This confirmation link");
expect(rendered.body).not.toContain("If you did not request");
});
it.each(["pl", "ru", "uk", "hu"] as const)("sets the React email document language to %s", (locale) => {
const rendered = EmailTemplates.WELCOME_EMAIL.parse({
appConfiguration,
data: { name: "Ada", action_url: actionUrl },
t: (key) => key,
locale,
});
expect(rendered.body).toContain(`<html lang="${locale}">`);
});
it("renders account setup emails via the welcome template with plan-aware copy", () => {
@@ -81,7 +134,7 @@ describe("EmailTemplates", () => {
});
expect(rendered.subject).toBe("Finish setting up your Acme Portal account");
expect(rendered.body).toContain("Pro plan");
expect(rendered.body).toContain("Pro access");
expect(rendered.body).toContain("ada@example.com");
expect(rendered.body).toContain(actionUrl);
});
@@ -92,7 +145,7 @@ describe("EmailTemplates", () => {
data: { action_url: actionUrl },
});
expect(rendered.subject).toBe(`Welcome to ${defaultBrandTokens.productName}!`);
expect(rendered.subject).toBe(`Welcome to ${defaultBrandTokens.productName}`);
expect(rendered.body).toContain(defaultBrandTokens.productName);
});
@@ -111,7 +164,15 @@ describe("EmailTemplates", () => {
"welcome.title_named": `Hallo ${vars?.name}!`,
"welcome.intro": `Danke fuer ${vars?.productName}.`,
"welcome.actionLabel": "Einloggen",
"common.signoff.thanks": "Danke,",
"common.signoff.closing": "Viele Grüße",
"common.signoff.team": "Dein Acme-Team",
"common.legal.privacyLabel": "Datenschutz",
"common.legal.termsLabel": "AGB",
"common.legal.imprintLabel": "Impressum",
"common.legal.unsubscribeLabel": "Abmelden",
"common.support.htmlBefore": "Bei Fragen kannst du uns gerne",
"common.support.emailLinkLabel": "eine E-Mail schreiben",
"common.support.htmlAfter": ".",
};
return values[key] ?? key;
},
@@ -120,13 +181,22 @@ describe("EmailTemplates", () => {
expect(withTranslator.subject).toBe("Willkommen bei Acme Portal, Ada!");
expect(withTranslator.body).toContain("Hallo Ada!");
expect(withTranslator.body).toContain("Einloggen");
expect(withTranslator.body).toContain("Danke,");
expect(withTranslator.body).toContain("Viele Grüße");
expect(withTranslator.body).toContain("Dein Acme-Team");
expect(withTranslator.body).toContain('<html lang="de">');
expect(withTranslator.body).toContain("Datenschutz");
expect(withTranslator.body).toContain("Bei Fragen kannst du uns gerne");
expect(withTranslator.body).toContain("eine E-Mail schreiben");
expect(withTranslator.body).not.toMatch(/<br\s*\/?>-<br\s*\/?>/u);
expect(withTranslator.text).toContain("Hallo Ada!");
expect(withTranslator.text).toContain("Datenschutz");
expect(withTranslator.text).not.toContain("\n-\n");
expect(withTranslator.body).not.toEqual(baseline.body);
});
it("localizes registry descriptions when a mail translator is available", () => {
const t = (key: string) => (key === "registry.welcomeDescription" ? "Lokalisierte Willkommensbeschreibung" : key);
expect(EmailTemplates.WELCOME_EMAIL.describe(t)).toBe("Lokalisierte Willkommensbeschreibung");
expect(EmailTemplates.WELCOME_EMAIL.description).toBe("Welcome email with login link");
expect(EmailTemplates.WELCOME_EMAIL.description).toBe("Welcome email with setup link");
});
});
@@ -1,6 +1,8 @@
import { resolveTransactionalBrandTokens } from "@hivegrid/brand";
import { buildBrand, renderTransactionalEmail, type MailBrand } from "@hivegrid/mail";
import { AppConfiguration } from "~/utils/db/appConfiguration.db.server";
import { defaultLocale, normalizeLocaleCandidate } from "@hivegrid/i18n";
import { buildBrand, renderTransactionalEmail, type MailBrand, type MailFooterCopy, type MailLanguage } from "@hivegrid/mail";
import type { AppConfiguration } from "~/utils/db/appConfiguration.db.server";
import { localizedMailChrome } from "./LocalizedMailChrome";
/**
* Legacy template identifiers preserved for downstream call-sites.
@@ -28,9 +30,9 @@ export type MailTranslator = (key: string, vars?: Record<string, unknown>) => st
export type EmailTemplateParseInput<TData extends EmailTemplateData = EmailTemplateData> = {
appConfiguration: AppConfiguration;
data: TData;
/** Reserved for future i18n hooks. Currently a no-op. */
/** Mail namespace translator used for content and shared mail chrome. */
t?: MailTranslator;
/** User/request locale (informational; reserved for future i18n hooks). */
/** User/request locale normalized to the supported mail document languages. */
locale?: string;
};
@@ -41,6 +43,7 @@ type EmailTemplate<TData extends EmailTemplateData = EmailTemplateData> = {
parse: (input: EmailTemplateParseInput<TData>) => {
subject: string;
body: string;
text: string;
data: TData;
};
};
@@ -76,58 +79,155 @@ function description(key: string, fallback: string) {
};
}
function normalizeMailLanguage(locale?: string): MailLanguage {
return normalizeLocaleCandidate(locale) ?? defaultLocale;
}
function mailChrome(
t: MailTranslator | undefined,
locale?: string
): {
language: MailLanguage;
footerCopy: MailFooterCopy;
} {
if (t) return localizedMailChrome(t, locale);
const language = normalizeMailLanguage(locale);
const fallback = {
de: {
privacyLabel: "Datenschutz",
termsLabel: "AGB",
imprintLabel: "Impressum",
unsubscribeLabel: "Abmelden",
supportBefore: "Du hast Fragen? Dann",
supportLinkLabel: "schreib uns gerne",
supportAfter: ".",
signoffClosing: "Viele Grüße",
signoffTeam: "Dein HiveGrid-Team",
},
en: {
privacyLabel: "Privacy",
termsLabel: "Terms",
imprintLabel: "Imprint",
unsubscribeLabel: "Unsubscribe",
supportBefore: "Questions? Feel free to",
supportLinkLabel: "email us",
supportAfter: ".",
signoffClosing: "Kind regards,",
signoffTeam: "Your HiveGrid team",
},
pl: {
privacyLabel: "Polityka prywatności",
termsLabel: "Regulamin",
imprintLabel: "Nota prawna",
unsubscribeLabel: "Zrezygnuj z subskrypcji",
supportBefore: "Masz pytania?",
supportLinkLabel: "Napisz do nas",
supportAfter: ".",
signoffClosing: "Pozdrawiamy,",
signoffTeam: "Zespół HiveGrid",
},
ru: {
privacyLabel: "Конфиденциальность",
termsLabel: "Условия",
imprintLabel: "Правовая информация",
unsubscribeLabel: "Отписаться",
supportBefore: "Есть вопросы?",
supportLinkLabel: "Напишите нам",
supportAfter: ".",
signoffClosing: "С наилучшими пожеланиями,",
signoffTeam: "Команда HiveGrid",
},
uk: {
privacyLabel: "Конфіденційність",
termsLabel: "Умови",
imprintLabel: "Правова інформація",
unsubscribeLabel: "Відписатися",
supportBefore: "Є запитання?",
supportLinkLabel: "Напишіть нам",
supportAfter: ".",
signoffClosing: "З найкращими побажаннями,",
signoffTeam: "Команда HiveGrid",
},
hu: {
privacyLabel: "Adatvédelem",
termsLabel: "ÁSZF",
imprintLabel: "Impresszum",
unsubscribeLabel: "Leiratkozás",
supportBefore: "Kérdésed van?",
supportLinkLabel: "Írj nekünk",
supportAfter: ".",
signoffClosing: "Üdvözlettel,",
signoffTeam: "A HiveGrid csapata",
},
}[language];
return {
language,
footerCopy: {
privacyLabel: mailText(t, "common.legal.privacyLabel", fallback.privacyLabel),
termsLabel: mailText(t, "common.legal.termsLabel", fallback.termsLabel),
imprintLabel: mailText(t, "common.legal.imprintLabel", fallback.imprintLabel),
unsubscribeLabel: mailText(t, "common.legal.unsubscribeLabel", fallback.unsubscribeLabel),
supportBefore: mailText(t, "common.support.htmlBefore", fallback.supportBefore),
supportLinkLabel: mailText(t, "common.support.emailLinkLabel", fallback.supportLinkLabel),
supportAfter: mailText(t, "common.support.htmlAfter", fallback.supportAfter),
signoffClosing: mailText(t, "common.signoff.closing", fallback.signoffClosing),
signoffTeam: mailText(t, "common.signoff.team", fallback.signoffTeam),
},
};
}
const WELCOME_EMAIL: EmailTemplate<{ name?: string; action_url: string }> = {
name: "welcome",
...description("registry.welcomeDescription", "Welcome email with login link"),
parse: ({ appConfiguration, data, t }) => {
...description("registry.welcomeDescription", "Welcome email with setup link"),
parse: ({ appConfiguration, data, t, locale }) => {
const brand = brandFor(appConfiguration);
const subject = data.name
? mailText(t, "welcome.subject_named", "Welcome to {{productName}}, {{name}}!", { productName: brand.productName, name: data.name })
: mailText(t, "welcome.subject", "Welcome to {{productName}}!", { productName: brand.productName });
const { html } = renderTransactionalEmail("welcome", {
? mailText(t, "welcome.subject_named", "Welcome to {{productName}}, {{name}}", { productName: brand.productName, name: data.name })
: mailText(t, "welcome.subject", "Welcome to {{productName}}", { productName: brand.productName });
const { html, text } = renderTransactionalEmail("welcome", {
brand,
...mailChrome(t, locale),
recipientName: data.name,
actionUrl: data.action_url,
subject,
eyebrow: mailText(t, "welcome.eyebrow", "Welcome"),
title: data.name
? mailText(t, "welcome.title_named", "Welcome, {{name}}!", { name: data.name })
: mailText(t, "welcome.title", "Welcome!"),
intro: mailText(t, "welcome.intro", "Thanks for trying {{productName}}.", { productName: brand.productName }),
actionLabel: mailText(t, "welcome.actionLabel", "Click here to log in"),
signoffThanks: mailText(t, "common.signoff.thanks", "Thanks,"),
? mailText(t, "welcome.title_named", "Great to have you here, {{name}}", { name: data.name })
: mailText(t, "welcome.title", "Great to have you here"),
intro: mailText(t, "welcome.intro", "Your {{productName}} account has been created. Sign in to review your plan and finish setup. Booked features unlock after payment is confirmed.", {
productName: brand.productName,
}),
actionLabel: mailText(t, "welcome.actionLabel", "Continue setup"),
});
return { subject, body: html, data };
return { subject, body: html, text, data };
},
};
const PASSWORD_RESET_EMAIL: EmailTemplate<{ name?: string; action_url: string }> = {
name: "password-reset",
...description("registry.passwordResetDescription", "Email sent to users who requested a password reset"),
parse: ({ appConfiguration, data, t }) => {
parse: ({ appConfiguration, data, t, locale }) => {
const brand = brandFor(appConfiguration);
const subject = mailText(t, "passwordReset.subject", "Reset your {{productName}} password", { productName: brand.productName });
const { html } = renderTransactionalEmail("password-reset", {
const { html, text } = renderTransactionalEmail("password-reset", {
brand,
...mailChrome(t, locale),
recipientName: data.name,
actionUrl: data.action_url,
subject,
eyebrow: mailText(t, "passwordReset.eyebrow", "Password reset"),
title: data.name
? mailText(t, "passwordReset.title_named", "Hello, {{name}}!", { name: data.name })
: mailText(t, "passwordReset.title", "Hello!"),
intro: mailText(t, "passwordReset.intro", "You recently requested to reset your password for your {{productName}} account.", {
? mailText(t, "passwordReset.title_named", "Choose a new password, {{name}}", { name: data.name })
: mailText(t, "passwordReset.title", "Choose a new password"),
intro: mailText(t, "passwordReset.intro", "We received a request to reset the password for your {{productName}} account.", {
productName: brand.productName,
}),
actionLabel: mailText(t, "passwordReset.actionLabel", "Reset password"),
outro: mailText(
t,
"passwordReset.outro",
"If you did not request a password reset, please ignore this email or contact support if you have questions."
),
signoffThanks: mailText(t, "common.signoff.thanks", "Thanks,"),
actionLabel: mailText(t, "passwordReset.actionLabel", "Choose a new password"),
outro: mailText(t, "passwordReset.outro", "If you did not make this request, you can ignore this email. Your current password will remain unchanged."),
});
return { subject, body: html, data };
return { subject, body: html, text, data };
},
};
@@ -139,7 +239,7 @@ const USER_INVITATION_EMAIL: EmailTemplate<{
}> = {
name: "user-invitation",
...description("registry.userInvitationDescription", "Email sent to users who are invited to join an organization"),
parse: ({ appConfiguration, data, t }) => {
parse: ({ appConfiguration, data, t, locale }) => {
const brand = brandFor(appConfiguration);
const vars = {
productName: brand.productName,
@@ -147,87 +247,81 @@ const USER_INVITATION_EMAIL: EmailTemplate<{
senderOrganization: data.invite_sender_organization,
name: data.name,
};
const subject = mailText(t, "userInvitation.subject", "{{senderName}} invited you to {{senderOrganization}} on {{productName}}", vars);
const { html } = renderTransactionalEmail("invitation", {
const subject = mailText(t, "userInvitation.subject", "{{senderName}} invited you to {{senderOrganization}} in {{productName}}", vars);
const { html, text } = renderTransactionalEmail("invitation", {
brand,
...mailChrome(t, locale),
recipientName: data.name,
senderName: data.invite_sender_name,
senderOrganization: data.invite_sender_organization,
actionUrl: data.action_url,
subject,
eyebrow: mailText(t, "userInvitation.eyebrow", "Invitation"),
title: data.name ? mailText(t, "userInvitation.title_named", "Hello, {{name}}!", vars) : mailText(t, "userInvitation.title", "Hello!"),
intro: mailText(
t,
"userInvitation.intro",
"{{senderName}} with {{senderOrganization}} has invited you to use {{productName}} to collaborate with them.",
vars
),
title: data.name
? mailText(t, "userInvitation.title_named", "{{name}}, you have been invited", vars)
: mailText(t, "userInvitation.title", "An invitation to collaborate"),
intro: mailText(t, "userInvitation.intro", "{{senderName}} invited you to collaborate with {{senderOrganization}} in {{productName}}.", vars),
actionLabel: mailText(t, "userInvitation.actionLabel", "Join {{senderOrganization}}", vars),
signoffThanks: mailText(t, "common.signoff.thanks", "Thanks,"),
});
return { subject, body: html, data };
return { subject, body: html, text, data };
},
};
const VERIFICATION_EMAIL: EmailTemplate<{ name?: string; action_url: string }> = {
name: "email-verification",
...description("registry.emailVerificationDescription", "Email sent to users to verify their email address"),
parse: ({ appConfiguration, data, t }) => {
parse: ({ appConfiguration, data, t, locale }) => {
const brand = brandFor(appConfiguration);
const vars = { productName: brand.productName, name: data.name };
const subject = mailText(t, "emailVerification.subject", "Verify your {{productName}} email address", vars);
const { html } = renderTransactionalEmail("magic-link", {
const subject = mailText(t, "emailVerification.subject", "Please confirm your email address", vars);
const { html, text } = renderTransactionalEmail("magic-link", {
brand,
...mailChrome(t, locale),
recipientName: data.name,
actionUrl: data.action_url,
subject,
previewText: mailText(t, "emailVerification.previewText", "Verify your email address with {{productName}}", vars),
eyebrow: mailText(t, "emailVerification.eyebrow", "Email verification"),
title: data.name
? mailText(t, "emailVerification.title_named", "Thanks for signing up, {{name}}!", vars)
: mailText(t, "emailVerification.title", "Thanks for signing up!"),
intro: mailText(t, "emailVerification.intro", "Confirm your email address to finish setting up your {{productName}} account.", vars),
actionLabel: mailText(t, "emailVerification.actionLabel", "Click here to verify your email"),
expiresInMinutes: 30,
signoffThanks: mailText(t, "common.signoff.thanks", "Thanks,"),
title: data.name ? mailText(t, "emailVerification.title_named", "Almost there, {{name}}", vars) : mailText(t, "emailVerification.title", "Almost there"),
intro: mailText(
t,
"emailVerification.intro",
"Confirm your email address. Then set your password and review your plan, add-ons, and payment method. Features unlock only after payment is confirmed.",
vars
),
actionLabel: mailText(t, "emailVerification.actionLabel", "Confirm email address"),
outro: mailText(t, "emailVerification.outro", "If you did not request this confirmation, you can safely ignore this email."),
expiresText: mailText(t, "emailVerification.expiresText", "This confirmation link is valid for {{expiresInHours}} hours and can only be used once.", {
expiresInHours: 24,
}),
expiresInMinutes: 24 * 60,
});
return { subject, body: html, data };
return { subject, body: html, text, data };
},
};
const ACCOUNT_SETUP_EMAIL: EmailTemplate<{ email: string; plan: string; action_url: string }> = {
name: "account-setup",
...description("registry.accountSetupDescription", "Email sent to users to set up their account"),
parse: ({ appConfiguration, data, t }) => {
parse: ({ appConfiguration, data, t, locale }) => {
const brand = brandFor(appConfiguration);
const vars = { productName: brand.productName, plan: data.plan, email: data.email };
const subject = mailText(t, "accountSetup.subject", "Finish setting up your {{productName}} account", vars);
const { html } = renderTransactionalEmail("welcome", {
const { html, text } = renderTransactionalEmail("welcome", {
brand,
...mailChrome(t, locale),
actionUrl: data.action_url,
subject,
eyebrow: mailText(t, "accountSetup.eyebrow", "Account setup"),
title: mailText(t, "accountSetup.title", "Almost there - let's get you started", vars),
intro: mailText(
t,
"accountSetup.intro",
"Thanks for subscribing to the {{plan}} plan. Use the button below to finish setting up your account for {{email}}.",
vars
),
actionLabel: mailText(t, "accountSetup.actionLabel", "Set up account"),
signoffThanks: mailText(t, "common.signoff.thanks", "Thanks,"),
title: mailText(t, "accountSetup.title", "Your account is waiting for you", vars),
intro: mailText(t, "accountSetup.intro", "Your {{plan}} access for {{email}} is ready. Choose your password and start using {{productName}}.", vars),
actionLabel: mailText(t, "accountSetup.actionLabel", "Finish account setup"),
});
return { subject, body: html, data };
return { subject, body: html, text, data };
},
};
const allTemplates = [
WELCOME_EMAIL,
PASSWORD_RESET_EMAIL,
USER_INVITATION_EMAIL,
VERIFICATION_EMAIL,
ACCOUNT_SETUP_EMAIL,
];
const allTemplates = [WELCOME_EMAIL, PASSWORD_RESET_EMAIL, USER_INVITATION_EMAIL, VERIFICATION_EMAIL, ACCOUNT_SETUP_EMAIL];
export default {
allTemplates,
@@ -0,0 +1,35 @@
import type { MailFooterCopy, MailLanguage } from "@hivegrid/mail";
import { defaultLocale, normalizeLocaleCandidate } from "@hivegrid/i18n";
import type { MailTranslator } from "~/locale/mail-translator.server";
export type LocalizedMailChrome = {
readonly language: MailLanguage;
readonly footerCopy: MailFooterCopy;
};
function normalizeMailLanguage(locale?: string): MailLanguage {
return normalizeLocaleCandidate(locale) ?? defaultLocale;
}
/**
* Resolves the shared, user-visible mail footer from the same locale as the
* message body. Direct React-email call sites must pass this chrome explicitly
* so they cannot silently fall back to the package's English preview defaults.
*/
export function localizedMailChrome(t: MailTranslator, locale?: string): LocalizedMailChrome {
return {
language: normalizeMailLanguage(locale),
footerCopy: {
privacyLabel: t("common.legal.privacyLabel"),
termsLabel: t("common.legal.termsLabel"),
imprintLabel: t("common.legal.imprintLabel"),
unsubscribeLabel: t("common.legal.unsubscribeLabel"),
supportBefore: t("common.support.htmlBefore"),
supportLinkLabel: t("common.support.emailLinkLabel"),
supportAfter: t("common.support.htmlAfter"),
signoffClosing: t("common.signoff.closing"),
signoffTeam: t("common.signoff.team"),
},
};
}