⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
feat: edit email templates and send emails in the reader's language (#823)
Croff96c965682c8a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 294426bb..cc8e64b2 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -54,6 +54,9 @@ jobs:- name: Script testsrun: bun test scripts/+ - name: Mailer tests+ run: bun test packages/mailer/+build:name: Build appsruns-on: ubuntu-latestdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex aead5bb8..c879a9da 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -29,7 +29,7 @@ apps/bot Telegram bot, long pollingpackages/db Drizzle client, schema, migrationspackages/auth better-auth server instancepackages/crypto AES-256-GCM encryption for secrets at rest-packages/mailer SMTP and Resend transport+packages/mailer SMTP and Resend transport, email templates```Dependency direction is `api → @repo/auth → @repo/db`. The web app never imports thediff --git a/apps/api/src/__tests__/integration/auth-email-language.test.ts b/apps/api/src/__tests__/integration/auth-email-language.test.tsnew file mode 100644index 00000000..1b13e6bc--- /dev/null+++ b/apps/api/src/__tests__/integration/auth-email-language.test.ts@@ -0,0 +1,69 @@+import { afterEach, beforeEach, describe, expect, it } from 'bun:test';+import { auth, setAuthSettings, setEmailSettings } from '@repo/auth';+import { authedApi } from '#tests/helpers/app';+import { signUpTestUser } from '#tests/helpers/auth';+import { resetDb } from '#tests/helpers/db';++const realFetch = globalThis.fetch;+let subjects: string[] = [];++function post(path: string, body: unknown, language?: string) {+ return auth.handler(+ new Request(`${new URL(process.env.API_URL!).origin}/api/auth${path}`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ ...(language ? { 'accept-language': language } : {}),+ },+ body: JSON.stringify(body),+ }),+ );+}++async function nextSubject(): Promise<string> {+ for (let i = 0; i < 50 && subjects.length === 0; i++) await Bun.sleep(20);+ return subjects.shift()!;+}++describe('the language of an authentication email', () => {+ beforeEach(async () => {+ await resetDb();+ subjects = [];+ await setEmailSettings({+ resend: { enabled: true, apiKey: 're_test' },+ from: '[email protected]',+ });+ await setAuthSettings({ magicLink: true });+ globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {+ if (!String(input).startsWith('https://api.resend.com/')) return realFetch(input, init);+ subjects.push(JSON.parse(String(init?.body)).subject);+ return Response.json({ id: 'sent' });+ }) as typeof fetch;+ });++ afterEach(() => {+ globalThis.fetch = realFetch;+ });++ it('is the one the account saved, whatever the browser asks for', async () => {+ const user = await signUpTestUser({ email: '[email protected]' });+ await authedApi(user.cookie).account.preferences.patch({ locale: 'uk' });+ subjects = [];++ await post('/request-password-reset', { email: user.email, redirectTo: '/reset' }, 'fr');++ expect(await nextSubject()).toBe('Скидання пароля');+ });++ it('is the one of the browser for an address with no saved language', async () => {+ await post('/sign-in/magic-link', { email: '[email protected]' }, 'ru-RU,en;q=0.5');++ expect(await nextSubject()).toBe('Ссылка для входа');+ });++ it('is English with neither', async () => {+ await post('/sign-in/magic-link', { email: '[email protected]' });++ expect(await nextSubject()).toBe('Your sign-in link');+ });+});diff --git a/apps/api/src/modules/god/__tests__/integration/god-email-templates.test.ts b/apps/api/src/modules/god/__tests__/integration/god-email-templates.test.tsnew file mode 100644index 00000000..63162bdd--- /dev/null+++ b/apps/api/src/modules/god/__tests__/integration/god-email-templates.test.ts@@ -0,0 +1,303 @@+import { afterEach, beforeEach, describe, expect, it } from 'bun:test';+import { setEmailSettings } from '@repo/auth';+import { setExtraEmailTemplates } from '@repo/mailer';+import { resetDb } from '#tests/helpers/db';+import { addUser, setup, type Actor } from '../helpers';++const text = { subject: 'Hello {actor}', body: '**{actor}** assigned {ref}.', button: 'See it' };++const realFetch = globalThis.fetch;++async function read(god: Actor) {+ const res = await god.api.god['email-templates'].get();+ return res.data!;+}++async function draft(god: Actor, key = 'assigned') {+ const { defaultLayout } = await read(god);+ return { key, locale: 'en' as const, text, layout: defaultLayout };+}++describe('god email templates', () => {+ beforeEach(resetDb);++ afterEach(() => {+ globalThis.fetch = realFetch;+ setExtraEmailTemplates([]);+ });++ it('lists every email with its text in every language', async () => {+ const { god } = await setup();++ const res = await god.api.god['email-templates'].get();++ expect(res.status).toBe(200);+ expect(res.data!.templates.map((template) => template.key)).toEqual([+ 'reset',+ 'verify',+ 'magic',+ 'inviteProject',+ 'inviteTeam',+ 'assigned',+ 'mentioned',+ 'commented',+ 'stateChanged',+ 'documentMentioned',+ 'documentCommentMentioned',+ 'test',+ ]);+ const assigned = res.data!.templates.find((template) => template.key === 'assigned')!;+ expect(assigned).toMatchObject({+ group: 'notifications',+ variables: ['actor', 'ref', 'title'],+ hasLink: true,+ edits: {},+ });+ expect(Object.keys(assigned.defaults)).toHaveLength(13);+ expect(assigned.defaults.ru!.subject).toBe('{ref}: назначена на вас');+ expect(res.data!.layout).toEqual(res.data!.defaultLayout);+ expect(res.data!.canSend).toBe(false);+ });++ it('is closed to a plain user', async () => {+ await setup();+ const user = await addUser({ email: '[email protected]' });++ expect((await user.api.god['email-templates'].get()).status).toBe(403);+ expect((await user.api.god['email-templates'].put({ edits: {}, layout: null })).status).toBe(+ 403,+ );+ });++ it('stores a changed text and layout, and goes back to the built-in ones', async () => {+ const { god } = await setup();+ const layout = { html: '<div>{content}{button}</div>', css: 'div { color: red; }' };++ const saved = await god.api.god['email-templates'].put({+ edits: { assigned: { ru: text } },+ layout,+ });++ expect(saved.status).toBe(200);+ expect(saved.data!.layout).toEqual(layout);+ const after = await read(god);+ expect(after.templates.find((template) => template.key === 'assigned')!.edits).toEqual({+ ru: text,+ });++ await god.api.god['email-templates'].put({ edits: {}, layout: null });++ const reset = await read(god);+ expect(reset.layout).toEqual(reset.defaultLayout);+ expect(reset.templates.find((template) => template.key === 'assigned')!.edits).toEqual({});+ });++ it('refuses an unknown email and an unknown language', async () => {+ const { god } = await setup();+ const put = god.api.god['email-templates'].put;++ const email = await put({ edits: { nothing: { en: text } }, layout: null });+ const language = await put({ edits: { assigned: { xx: text } }, layout: null });++ expect(email.status).toBe(400);+ expect(language.status).toBe(400);+ });++ it('refuses an email with no subject or no text', async () => {+ const { god } = await setup();+ const put = god.api.god['email-templates'].put;++ const subject = await put({+ edits: { assigned: { en: { ...text, subject: ' ' } } },+ layout: null,+ });+ const body = await put({ edits: { assigned: { en: { ...text, body: '' } } }, layout: null });++ expect(subject.status).toBe(400);+ expect(body.status).toBe(400);+ });++ it('refuses a variable the email does not have', async () => {+ const { god } = await setup();++ const res = await god.api.god['email-templates'].put({+ edits: { assigned: { ru: { ...text, body: '{actor} {typo}' } } },+ layout: null,+ });++ expect(res.status).toBe(400);+ expect(res.error?.value).toMatchObject({ error: expect.stringContaining('{typo}') });+ });++ it('takes an email with no button text', async () => {+ const { god } = await setup();++ const res = await god.api.god['email-templates'].put({+ edits: { assigned: { en: { ...text, button: '' } } },+ layout: null,+ });++ expect(res.status).toBe(200);+ });++ it('refuses a layout that leaves out the text or the button', async () => {+ const { god } = await setup();++ const res = await god.api.god['email-templates'].put({+ edits: {},+ layout: { html: '<div>{content}</div>', css: '' },+ });++ expect(res.status).toBe(400);+ expect(res.error!.value).toMatchObject({ error: 'The layout needs {button}' });+ });++ it('refuses a layout with a placeholder nothing fills', async () => {+ const { god } = await setup();++ const res = await god.api.god['email-templates'].put({+ edits: {},+ layout: { html: '<div>{content}{button}{logo}</div>', css: '' },+ });++ expect(res.status).toBe(400);+ expect(res.error!.value).toMatchObject({ error: 'Unknown variables in the layout: {logo}' });+ });++ it('refuses a text over the length limit', async () => {+ const { god } = await setup();++ const res = await god.api.god['email-templates'].put({+ edits: { assigned: { en: { ...text, button: 'x'.repeat(201) } } },+ layout: null,+ });++ expect(res.status).toBe(400);+ });++ it('previews text that is not saved, with sample values and the sender', async () => {+ const { god } = await setup();+ await setEmailSettings({+ resend: { enabled: true, apiKey: 're_test' },+ from: '[email protected]',+ });++ const res = await god.api.god['email-templates'].preview.post(await draft(god));++ expect(res.status).toBe(200);+ expect(res.data!.subject).toBe('Hello Maria Lopez');+ expect(res.data!.from).toBe('[email protected]');+ expect(res.data!.text).toContain('Maria Lopez assigned WEB-42.');+ expect(res.data!.text).toEndWith(`${process.env.APP_URL}/acme/WEB/issue/42`);+ expect(res.data!.html).toContain('<strong');+ expect(res.data!.html).toContain('class="button"');+ expect((await read(god)).templates.find((t) => t.key === 'assigned')!.edits).toEqual({});+ });++ it('refuses a preview of an unknown email', async () => {+ const { god } = await setup();++ const res = await god.api.god['email-templates'].preview.post(await draft(god, 'nothing'));++ expect(res.status).toBe(400);+ });++ it('refuses a test until a provider is configured', async () => {+ const { god } = await setup();++ const res = await god.api.god['email-templates'].test.post(await draft(god));++ expect(res.status).toBe(400);+ expect(res.error!.value).toMatchObject({ error: 'Configure an email provider first' });+ });++ it('sends a test of what is on the screen to the instance owner', async () => {+ const { god } = await setup();+ await setEmailSettings({+ resend: { enabled: true, apiKey: 're_test' },+ from: '[email protected]',+ });+ const sent: { to: string[]; subject: string }[] = [];+ globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {+ if (!String(input).startsWith('https://api.resend.com/')) return realFetch(input, init);+ sent.push(JSON.parse(String(init?.body)));+ return Response.json({ id: 'sent' });+ }) as typeof fetch;++ const res = await god.api.god['email-templates'].test.post(await draft(god));++ expect(res.status).toBe(200);+ expect(res.data).toEqual({ recipient: god.email });+ expect(sent).toMatchObject([{ to: [god.email], subject: 'Hello Maria Lopez' }]);+ });++ it('answers 502 when the provider refuses the test', async () => {+ const { god } = await setup();+ await setEmailSettings({+ resend: { enabled: true, apiKey: 're_test' },+ from: '[email protected]',+ });+ globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) =>+ String(input).startsWith('https://api.resend.com/')+ ? new Response('no', { status: 401 })+ : realFetch(input, init)) as typeof fetch;++ const res = await god.api.god['email-templates'].test.post(await draft(god));++ expect(res.status).toBe(502);+ });++ describe('an edition with templates of its own', () => {+ const extra = {+ key: 'formReply',+ group: 'forms',+ samples: { title: 'A request' },+ samplePath: '/p/requests/example',+ texts: { en: { subject: 'New reply: {title}', body: '{title}', button: 'Open' } },+ };+ const reply = { subject: 'Ответ: {title}', body: '**{title}**', button: 'Открыть' };++ it('lists them after the core ones, with English in a language they lack', async () => {+ const { god } = await setup();+ setExtraEmailTemplates([extra]);++ const { templates } = await read(god);++ expect(templates.at(-1)).toMatchObject({ key: 'formReply', group: 'forms', hasLink: true });+ expect(templates.at(-1)!.defaults.ru).toEqual(extra.texts.en);+ });++ it('previews and stores them', async () => {+ const { god } = await setup();+ setExtraEmailTemplates([extra]);++ const preview = await god.api.god['email-templates'].preview.post({+ ...(await draft(god, 'formReply')),+ text: extra.texts.en,+ });+ const saved = await god.api.god['email-templates'].put({+ edits: { formReply: { ru: reply } },+ layout: null,+ });++ expect(preview.data!.subject).toBe('New reply: A request');+ expect(saved.status).toBe(200);+ });++ it('keeps what god saved while its templates are gone', async () => {+ const { god } = await setup();+ setExtraEmailTemplates([extra]);+ await god.api.god['email-templates'].put({+ edits: { formReply: { ru: reply } },+ layout: null,+ });++ setExtraEmailTemplates([]);+ await god.api.god['email-templates'].put({ edits: {}, layout: null });+ setExtraEmailTemplates([extra]);++ const { templates } = await read(god);+ expect(templates.at(-1)!.edits).toEqual({ ru: reply });+ });+ });+});diff --git a/apps/api/src/modules/god/email-templates.ts b/apps/api/src/modules/god/email-templates.tsnew file mode 100644index 00000000..b95ca735--- /dev/null+++ b/apps/api/src/modules/god/email-templates.ts@@ -0,0 +1,112 @@+import {+ composeEmailDraft,+ getEmailTemplateSettings,+ setEmailTemplateSettings,+ type EmailTemplateSettings,+} from '@repo/auth';+import { getInstanceEmailConfig, hasConfiguredEmailProvider } from '@repo/db';+import {+ DEFAULT_EMAIL_LAYOUT,+ LAYOUT_PLACEHOLDERS,+ LOCALES,+ defaultEmailText,+ emailTemplate,+ emailTemplates,+ hasEmailProvider,+ isLocale,+ missingLayoutPlaceholders,+ senderAddress,+ unknownEmailVariables,+ unknownLayoutPlaceholders,+} from '@repo/mailer';+import { HttpError } from '#shared/lib';+import { deliverTestEmail } from './email-test';+import type { EmailDraftBody, EmailTemplatesBody } from './model';++type EmailTemplatesInput = typeof EmailTemplatesBody.static;+type EmailDraft = typeof EmailDraftBody.static;++function nameList(names: string[]): string {+ return names.map((name) => `{${name}}`).join(', ');+}++export async function getEmailTemplates() {+ const settings = await getEmailTemplateSettings();+ return {+ templates: emailTemplates().map((template) => ({+ key: template.key,+ group: template.group,+ variables: Object.keys(template.samples),+ hasLink: template.samplePath !== null,+ defaults: Object.fromEntries(+ LOCALES.map((locale) => [locale, defaultEmailText(template, locale)]),+ ),+ edits: settings.texts[template.key] ?? {},+ })),+ layout: settings.layout ?? DEFAULT_EMAIL_LAYOUT,+ defaultLayout: DEFAULT_EMAIL_LAYOUT,+ placeholders: LAYOUT_PLACEHOLDERS,+ canSend: await hasConfiguredEmailProvider(),+ };+}++function assertEdits(edits: EmailTemplatesInput['edits']): void {+ for (const [key, byLocale] of Object.entries(edits)) {+ const template = emailTemplate(key);+ if (!template) throw new HttpError(400, `Unknown email template: ${key}`);+ for (const [locale, text] of Object.entries(byLocale)) {+ if (!isLocale(locale)) throw new HttpError(400, `Unknown language: ${locale}`);+ if (!text.subject.trim() || !text.body.trim()) {+ throw new HttpError(400, 'An email needs a subject and a text');+ }+ const unknown = unknownEmailVariables(text, Object.keys(template.samples));+ if (unknown.length > 0) {+ throw new HttpError(400, `Unknown variables in ${key} (${locale}): ${nameList(unknown)}`);+ }+ }+ }+}++function assertLayout(html: string): void {+ const missing = missingLayoutPlaceholders(html);+ if (missing.length > 0) throw new HttpError(400, `The layout needs ${nameList(missing)}`);+ const unknown = unknownLayoutPlaceholders(html);+ if (unknown.length > 0) {+ throw new HttpError(400, `Unknown variables in the layout: ${nameList(unknown)}`);+ }+}++// A template that is not there right now, such as an edition's while it is off, keeps what+// god saved for it.+export async function saveEmailTemplates(body: EmailTemplatesInput) {+ assertEdits(body.edits);+ if (body.layout) assertLayout(body.layout.html);+ const stored = await getEmailTemplateSettings();+ const kept = Object.entries(stored.texts).filter(([key]) => !emailTemplate(key));+ const next: EmailTemplateSettings = {+ texts: { ...Object.fromEntries(kept), ...body.edits },+ layout: body.layout,+ };+ await setEmailTemplateSettings(next);+ return getEmailTemplates();+}++function renderDraft(draft: EmailDraft) {+ const template = emailTemplate(draft.key);+ if (!template) throw new HttpError(400, `Unknown email template: ${draft.key}`);+ return composeEmailDraft(template, draft);+}++export async function previewEmail(draft: EmailDraft) {+ const config = await getInstanceEmailConfig();+ return { ...renderDraft(draft), from: config ? senderAddress(config) : null };+}++export async function sendTestEmail(recipient: string, draft: EmailDraft) {+ const config = await getInstanceEmailConfig();+ if (!config || !hasEmailProvider(config)) {+ throw new HttpError(400, 'Configure an email provider first');+ }+ await deliverTestEmail(config, { to: recipient, ...renderDraft(draft) });+ return { recipient };+}diff --git a/apps/api/src/modules/god/email-test.ts b/apps/api/src/modules/god/email-test.tsindex f2967381..625ca079 100644--- a/apps/api/src/modules/god/email-test.ts+++ b/apps/api/src/modules/god/email-test.ts@@ -1,3 +1,6 @@+import { sendEmail, type EmailConfig, type EmailMessage } from '@repo/mailer';+import { HttpError } from '#shared/lib';+// Provider errors can contain host names and transport details that should stay// in the server log. Map only recognizable categories to actionable, stable API// messages and use a generic fallback for everything else.@@ -30,3 +33,14 @@ export function emailTestError(error: string | undefined): string {}return 'The email provider rejected the test message';}++export async function deliverTestEmail(config: EmailConfig, message: EmailMessage): Promise<void> {+ const result = await sendEmail(+ { ...config, smtp: { ...config.smtp, timeout: config.smtp.timeout ?? 15 } },+ message,+ );+ if (!result.ok) {+ console.error('[god] test email failed:', result.error);+ throw new HttpError(502, emailTestError(result.error));+ }+}diff --git a/apps/api/src/modules/god/index.ts b/apps/api/src/modules/god/index.tsindex 356f9daf..0519f08e 100644--- a/apps/api/src/modules/god/index.ts+++ b/apps/api/src/modules/god/index.ts@@ -16,9 +16,11 @@ import {setScimSettings,rotateScimToken,hasConfiguredOidc,+ composeEmail,+ emailLocale,} from '@repo/auth';import { hasConfiguredEmailProvider, getStorageSettings } from '@repo/db';-import { emailBody, hasEmailProvider, sendEmail } from '@repo/mailer';+import { hasEmailProvider } from '@repo/mailer';import { authContext } from '#shared/auth-context';import { requireGod } from '#shared/access';import { HttpError, rethrowDuplicate } from '#shared/lib';@@ -59,6 +61,10 @@ import {AuthSettingsResponse,EmailSettingsBody,EmailSettingsResponse,+ EmailDraftBody,+ EmailPreviewResponse,+ EmailTemplatesBody,+ EmailTemplatesResponse,EmailTestResponse,GoogleSettingsBody,GoogleSettingsResponse,@@ -84,7 +90,13 @@ import {teamParams,userParams,} from './model';-import { emailTestError } from './email-test';+import { deliverTestEmail } from './email-test';+import {+ getEmailTemplates,+ previewEmail,+ saveEmailTemplates,+ sendTestEmail,+} from './email-templates';import { getInstanceBotSettings, setInstanceBotSettings } from '#modules/telegram/service';import {setStorageSettings,@@ -237,21 +249,10 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })throw new HttpError(400, 'Configure an email provider first');}- const body = emailBody(- "This test confirms that It's a Plan can send email through the configured provider.",- );- const result = await sendEmail(- { ...config, smtp: { ...config.smtp, timeout: config.smtp.timeout ?? 15 } },- {- to: current.email,- subject: "It's a Plan email test",- ...body,- },- );- if (!result.ok) {- console.error('[god] test email failed:', result.error);- throw new HttpError(502, emailTestError(result.error));- }+ await deliverTestEmail(config, {+ to: current.email,+ ...(await composeEmail('test', await emailLocale(current.email))),+ });return { recipient: current.email };},{@@ -265,6 +266,51 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })},)+ .get('/god/email-templates', () => getEmailTemplates(), {+ response: { 200: EmailTemplatesResponse, ...errors(401, 403) },+ detail: {+ summary: 'Get email templates',+ description:+ 'Get every email the instance sends, with its built-in texts and what god changed.',+ },+ })++ .put('/god/email-templates', ({ body }) => saveEmailTemplates(body), {+ body: EmailTemplatesBody,+ response: { 200: EmailTemplatesResponse, ...errors(400, 401, 403) },+ detail: {+ summary: 'Update email templates',+ description:+ 'Replace the changed email texts and the layout. A null layout is the built-in one.',+ },+ })++ .post('/god/email-templates/preview', ({ body }) => previewEmail(body), {+ body: EmailDraftBody,+ response: { 200: EmailPreviewResponse, ...errors(400, 401, 403) },+ detail: {+ summary: 'Preview an email',+ description: 'Render an email from text and a layout, saved or not, with sample values.',+ },+ })++ .post(+ '/god/email-templates/test',+ ({ user, body }) => {+ const current = requireGod(user);+ if (!current.email) throw new HttpError(400, 'The instance owner has no email address');+ return sendTestEmail(current.email, body);+ },+ {+ body: EmailDraftBody,+ response: { 200: EmailTestResponse, ...commonErrors, ...errors(502) },+ detail: {+ summary: 'Send a test of an email',+ description: 'Send an email from text and a layout, saved or not, to the instance owner.',+ },+ },+ )+.get('/god/google-settings',async () => ({ ...(await getGoogleSettings()), redirectUri: GOOGLE_REDIRECT_URI }),diff --git a/apps/api/src/modules/god/model.ts b/apps/api/src/modules/god/model.tsindex bc646346..4304a5fb 100644--- a/apps/api/src/modules/god/model.ts+++ b/apps/api/src/modules/god/model.ts@@ -1,5 +1,6 @@import { t } from 'elysia';import { REGISTRATION_MODES } from '@repo/auth';+import { LOCALES } from '@repo/mailer';import { pageQueryFields, pageResponse } from '#shared/pagination';import { PermissionMatrixSchema } from '#shared/permissions';import { USER_KINDS } from './service';@@ -123,6 +124,55 @@ export const EmailSettingsBody = t.Object({export const EmailTestResponse = t.Object({ recipient: t.String() });+const EmailText = t.Object({+ subject: t.String({ maxLength: 500 }),+ body: t.String({ maxLength: 20_000 }),+ button: t.String({ maxLength: 200 }),+});++const EmailLayout = t.Object({+ html: t.String({ maxLength: 200_000 }),+ css: t.String({ maxLength: 100_000 }),+});++const EmailTextByLocale = t.Record(t.String(), EmailText);++export const EmailTemplatesBody = t.Object({+ edits: t.Record(t.String(), EmailTextByLocale),+ layout: t.Nullable(EmailLayout),+});++export const EmailDraftBody = t.Object({+ key: t.String(),+ locale: t.UnionEnum([...LOCALES]),+ text: EmailText,+ layout: EmailLayout,+});++export const EmailTemplatesResponse = t.Object({+ templates: t.Array(+ t.Object({+ key: t.String(),+ group: t.String(),+ variables: t.Array(t.String()),+ hasLink: t.Boolean(),+ defaults: EmailTextByLocale,+ edits: EmailTextByLocale,+ }),+ ),+ layout: EmailLayout,+ defaultLayout: EmailLayout,+ placeholders: t.Array(t.Object({ name: t.String(), required: t.Boolean() })),+ canSend: t.Boolean(),+});++export const EmailPreviewResponse = t.Object({+ subject: t.String(),+ text: t.String(),+ html: t.String(),+ from: t.Nullable(t.String()),+});+export const GoogleSettingsResponse = t.Object({enabled: t.Boolean(),clientId: t.String(),diff --git a/apps/api/src/modules/invites/__tests__/integration/invites.test.ts b/apps/api/src/modules/invites/__tests__/integration/invites.test.tsindex c2daad54..9df34e84 100644--- a/apps/api/src/modules/invites/__tests__/integration/invites.test.ts+++ b/apps/api/src/modules/invites/__tests__/integration/invites.test.ts@@ -1,4 +1,5 @@import { describe, it, expect, afterAll, afterEach, beforeAll, beforeEach } from 'bun:test';+import { db, notificationDelivery } from '@repo/db';import { authedApi, createProject } from '#tests/helpers/app';import { signUpTestUser, type TestUser } from '#tests/helpers/auth';import { resetDb } from '#tests/helpers/db';@@ -255,7 +256,32 @@ describe('invites', () => {expect(res.status).toBe(201);expect(res.data?.emailQueued).toBe(true);const sent = received.find((m) => m.to.some((to) => to.includes('[email protected]')));- expect(sent?.body).toContain(`/invite/${res.data!.token}`);+ // Quoted-printable breaks a long line with "=" at its end.+ expect(sent?.body.replace(/=\r?\n/g, '')).toContain(`/invite/${res.data!.token}`);+ });++ it('writes a queued invite in the language of the address, or of its sender', async () => {+ const { api } = await setupOwner();+ await configureEmail(api);+ await api.account.preferences.patch({ locale: 'ru' });+ const known = await signUpTestUser();+ await authedApi(known.cookie).account.preferences.patch({ locale: 'fr' });+ const invites = api.projects({ projectKey: 'MKT' }).invites;++ await invites.post({ email: '[email protected]', role: 'owner' });+ await invites.post({ email: known.email, role: 'member' });++ const queued = await db+ .select({+ recipient: notificationDelivery.recipient,+ payload: notificationDelivery.payload,+ })+ .from(notificationDelivery);+ const email = (to: string) => queued.find((row) => row.recipient === to)!.payload;+ expect(email('[email protected]').subject).toBe("Приглашение в Marketing в It's a Plan");+ expect(email('[email protected]').text).toContain('с ролью владелец');+ expect(email('[email protected]').html).toContain('class="button"');+ expect(email(known.email).subject).toBe("Vous êtes invité à Marketing sur It's a Plan");});it('still creates the link when no email provider is configured', async () => {diff --git a/apps/api/src/modules/invites/email.ts b/apps/api/src/modules/invites/email.tsindex d38d54b7..400a05ba 100644--- a/apps/api/src/modules/invites/email.ts+++ b/apps/api/src/modules/invites/email.ts@@ -1,7 +1,14 @@import { randomUUID } from 'node:crypto';import { db, notificationDelivery, getInstanceEmailConfig, team } from '@repo/db';-import { trustedOrigins } from '@repo/auth';-import { emailBody, hasEmailProvider, sendEmail } from '@repo/mailer';+import { composeEmail, savedLocaleOf, trustedOrigins } from '@repo/auth';+import {+ DEFAULT_LOCALE,+ emailWords,+ hasEmailProvider,+ sendEmail,+ type EmailWords,+ type Locale,+} from '@repo/mailer';import { and, eq, sql } from 'drizzle-orm';import type { InviteRow } from './service';@@ -10,6 +17,17 @@ interface InviteProject {name: string;}+async function inviteLocale(invite: InviteRow): Promise<Locale> {+ const invited = await savedLocaleOf(invite.email);+ if (invited) return invited;+ const sender = invite.invitedByEmail ? await savedLocaleOf(invite.invitedByEmail) : null;+ return sender ?? DEFAULT_LOCALE;+}++function inviterName(invite: InviteRow, words: EmailWords): string {+ return invite.invitedByName ?? invite.invitedByEmail ?? words.someone;+}+// Serializes enqueue attempts for one invite across API replicas. Without this,// two clicks arriving together can both observe an empty outbox and insert the// same email before either transaction commits.@@ -23,10 +41,19 @@ export async function enqueueInviteEmail(if (!config || !hasEmailProvider(config)) return false;const dedupeKey = `project-invite:${invite.id}`;- const inviter = invite.invitedByName ?? invite.invitedByEmail ?? "An It's a Plan user";- const role = invite.role === 'owner' ? 'owner' : (invite.roleName ?? 'member');- const projectName = project.name.replace(/[\r\n]+/g, ' ');+ const locale = await inviteLocale(invite);+ const words = emailWords(locale);const url = new URL(`/invite/${invite.token}`, trustedOrigins[0]).toString();+ const email = await composeEmail(+ 'inviteProject',+ locale,+ {+ inviter: inviterName(invite, words),+ project: project.name,+ role: invite.role === 'owner' ? words.owner : (invite.roleName ?? words.member),+ },+ url,+ );await db.transaction(async (tx) => {await tx.execute(@@ -52,11 +79,7 @@ export async function enqueueInviteEmail(channel: 'email',recipient: invite.email,payload: {- subject: `You were invited to ${projectName} on It's a Plan`,- text:- `${inviter} invited you to join ${projectName} as ${role}.\n\n` +- 'Open the invitation to sign in or create an account. ' +- 'If you did not expect this invitation, you can ignore this email.',+ ...email,url,emailSource: 'instance',idempotencyKey: `project-invite/${invite.id}/${randomUUID()}`,@@ -76,20 +99,19 @@ export async function sendTeamInviteEmail(teamId: number, invite: InviteRow): Prif (!config || !hasEmailProvider(config)) return false;const [row] = await db.select({ name: team.name }).from(team).where(eq(team.id, teamId));- const teamName = (row?.name ?? 'a team').replace(/[\r\n]+/g, ' ');- const inviter = invite.invitedByName ?? invite.invitedByEmail ?? "An It's a Plan user";- const { text, html } = emailBody(- `${inviter} invited you to join the team ${teamName} as ${invite.teamRole}.\n\n` +- 'Open the invitation to sign in or create an account. ' +- 'If you did not expect this invitation, you can ignore this email.',+ const locale = await inviteLocale(invite);+ const words = emailWords(locale);+ const email = await composeEmail(+ 'inviteTeam',+ locale,+ {+ inviter: inviterName(invite, words),+ team: row?.name ?? words.untitled,+ role: words[invite.teamRole],+ },`${trustedOrigins[0]}/invite/${invite.token}`,);- const result = await sendEmail(config, {- to: invite.email,- subject: `You were invited to ${teamName} on It's a Plan`,- text,- html,- });+ const result = await sendEmail(config, { to: invite.email, ...email });if (!result.ok) console.error('[invites] team invite email failed:', result.error);return result.ok;}diff --git a/apps/api/src/modules/notifications/__tests__/integration/notifications.test.ts b/apps/api/src/modules/notifications/__tests__/integration/notifications.test.tsindex 71f191e7..1bde3e33 100644--- a/apps/api/src/modules/notifications/__tests__/integration/notifications.test.ts+++ b/apps/api/src/modules/notifications/__tests__/integration/notifications.test.ts@@ -355,6 +355,57 @@ describe('notifications', () => {]);});+ it('sends each recipient the email in their language, with what god changed', async () => {+ const { owner, project, columnId, doneColumnId } = await setup();+ const member = await addMember(owner);+ await owner.api.teams({ teamId: project.teamId })['notification-settings'].put({+ smtp: {+ enabled: true,+ host: 'smtp.example.com',+ port: 587,+ encryption: 'none',+ username: '[email protected]',+ password: 'secret',+ timeout: null,+ },+ });+ const events = { assigned: true, mentioned: true, commented: true, state_changed: true };+ await member.api.projects({ projectKey: 'MKT' })['notification-preferences'].put({+ emailEvents: events,+ telegramEvents: events,+ });+ await member.api.account.preferences.patch({ locale: 'ru' });+ await owner.api.god['email-templates'].put({+ edits: {+ stateChanged: {+ ru: {+ subject: 'Статус {ref}: {to}',+ body: '**{title}** {from} → {to}',+ button: 'Открыть',+ },+ },+ },+ layout: null,+ });+ const issue = (+ await createIssue(owner.api, columnId, {+ title: '<b>Loud</b> title',+ assigneeUserId: member.userId,+ })+ ).data!;+ await db.delete(notificationDelivery);++ await owner.api.issues({ issueId: issue.id }).patch({ columnId: doneColumnId });++ const [queued] = await db+ .select({ payload: notificationDelivery.payload })+ .from(notificationDelivery);+ expect(queued!.payload.subject).toStartWith(`Статус ${issue.identifier}:`);+ expect(queued!.payload.text).toContain('<b>Loud</b> title');+ expect(queued!.payload.html).toContain('<b>Loud</b> title');+ expect(queued!.payload.html).toContain('class="button"');+ });+it('a status change notification names the states it moved between', async () => {const { owner, columnId, doneColumnId } = await setup();const member = await addMember(owner);diff --git a/apps/api/src/modules/notifications/outbound.ts b/apps/api/src/modules/notifications/outbound.tsindex 92a03f85..cfe5063f 100644--- a/apps/api/src/modules/notifications/outbound.ts+++ b/apps/api/src/modules/notifications/outbound.ts@@ -12,7 +12,8 @@ import {type DeliveryPayload,} from '@repo/db';import { eq, inArray } from 'drizzle-orm';-import { isAccountDeactivated } from '@repo/auth';+import { composeEmail, isAccountDeactivated, savedLocales } from '@repo/auth';+import { DEFAULT_LOCALE, emailWords, type CoreEmailKey, type Locale } from '@repo/mailer';import { readRedactedSettings } from '#modules/notification-settings/service';import { getPreferencesForUsers } from '#modules/notification-preferences/service';import { getTelegramChatIds, hasUsableInstanceBot } from '#modules/telegram/service';@@ -62,34 +63,12 @@ async function readStateChange(activityId: number): Promise<StateChange | null>return { from, to };}-// Email copy, addressed to the recipient in the second person.-function emailPayload(- type: NotificationType,- ref: string,- title: string,- actor: string,- url: string | undefined,- stateChange: StateChange | null,-): DeliveryPayload {- const line: Record<NotificationType, { subject: string; text: string }> = {- assigned: { subject: `${ref}: assigned to you`, text: `${actor} assigned this issue to you.` },- mentioned: {- subject: `${ref}: you were mentioned`,- text: `${actor} mentioned you on this issue.`,- },- commented: { subject: `${ref}: new comment`, text: `${actor} commented on this issue.` },- state_changed: {- subject: stateChange- ? `${ref}: status changed to ${stateChange.to}`- : `${ref}: status changed`,- text: stateChange- ? `${actor} changed the status of this issue from ${stateChange.from} to ${stateChange.to}.`- : `${actor} changed the status of this issue.`,- },- };- const { subject, text } = line[type];- return { subject, text: `${text}\n\n${ref}: ${title}`, url };-}+const EMAIL_TEMPLATE: Record<NotificationType, CoreEmailKey> = {+ assigned: 'assigned',+ mentioned: 'mentioned',+ commented: 'commented',+ state_changed: 'stateChanged',+};// Telegram copy. Rendered as HTML (parse_mode HTML) with the issue reference as a// clickable link, plus a plain-text fallback. Issue-centric third person, matching@@ -126,22 +105,8 @@ function telegramPayload(return { text, html, url };}-// A document only sends 'mentioned', so its copy has no per-type table. The title is-// the link in Telegram, as the issue reference is.-function documentEmailPayload(- title: string,- actor: string,- url: string | undefined,- inComment: boolean,-): DeliveryPayload {- const where = inComment ? 'in a comment on this document' : 'in this document';- return {- subject: `${title}: you were mentioned`,- text: `${actor} mentioned you ${where}.\n\n${title}`,- url,- };-}-+// A document only sends 'mentioned'. The title is the link in Telegram, as the issue+// reference is.function documentTelegramPayload(title: string,actor: string,@@ -159,7 +124,7 @@ function documentTelegramPayload(}interface Messages {- email: (type: NotificationType) => DeliveryPayload;+ email: (type: NotificationType, locale: Locale) => Promise<DeliveryPayload>;telegram: (type: NotificationType) => DeliveryPayload;}@@ -168,9 +133,10 @@ interface Messages {async function composeMessages(notifications: NewNotificationRow[],projectRow: { key: string; teamId: number; teamSlug: string | null },- actor: string,+ actorName: string | null,commentId: number | null,): Promise<Messages | null> {+ const actor = actorName ?? 'Someone';const first = notifications[0];const ref = teamRef({ id: projectRow.teamId, slug: projectRow.teamSlug });if (first.documentId != null) {@@ -180,12 +146,17 @@ async function composeMessages(.from(projectDocument).where(eq(projectDocument.id, documentId));if (!documentRow) return null;- const title = documentRow.title.trim() || 'Untitled';+ const title = documentRow.title.trim();const url = documentUrl(ref, projectRow.key, documentId);- const inComment = first.documentCommentId != null;+ const template =+ first.documentCommentId != null ? 'documentCommentMentioned' : 'documentMentioned';return {- email: () => documentEmailPayload(title, actor, url, inComment),- telegram: () => documentTelegramPayload(title, actor, url),+ email: async (_type, locale) => {+ const words = emailWords(locale);+ const vars = { actor: actorName ?? words.someone, document: title || words.untitled };+ return { ...(await composeEmail(template, locale, vars, url)), url };+ },+ telegram: () => documentTelegramPayload(title || 'Untitled', actor, url),};}if (first.issueId == null) return null;@@ -204,7 +175,16 @@ async function composeMessages(notifications.find((n) => n.type === 'state_changed')?.sourceActivityId ?? null;const stateChange = statusActivityId != null ? await readStateChange(statusActivityId) : null;return {- email: (type) => emailPayload(type, issueKey, issueRow.title, actor, url, stateChange),+ email: async (type, locale) => {+ const vars = {+ actor: actorName ?? emailWords(locale).someone,+ ref: issueKey,+ title: issueRow.title,+ from: stateChange?.from ?? '—',+ to: stateChange?.to ?? '—',+ };+ return { ...(await composeEmail(EMAIL_TEMPLATE[type], locale, vars, url)), url };+ },telegram: (type) => telegramPayload(type, issueKey, issueRow.title, actor, url, stateChange),};}@@ -247,28 +227,33 @@ export async function enqueueOutbound(settings.telegram.enabled && (settings.telegram.hasBotToken || (await hasUsableInstanceBot()));if (!emailEnabled && !telegramEnabled) return;- const messages = await composeMessages(- notifications,- projectRow,- actorName ?? 'Someone',- commentId,- );+ const messages = await composeMessages(notifications, projectRow, actorName, commentId);if (!messages) return;const userIds = [...new Set(notifications.map((n) => n.userId))];- const [users, prefsByUser, chatIdByUser] = await Promise.all([+ const [users, prefsByUser, chatIdByUser, localeByUser] = await Promise.all([db.select({ id: user.id, email: user.email, active: user.active }).from(user).where(inArray(user.id, userIds)),getPreferencesForUsers(projectId, userIds),telegramEnabled ? getTelegramChatIds(userIds) : Promise.resolve(new Map<string, string>()),+ savedLocales(userIds),]);// A deactivated account keeps its projects, but nothing from them reaches it.const emailById = new Map(users.filter((u) => !isAccountDeactivated(u)).map((u) => [u.id, u.email]),);+ // Everyone told the same thing in one language gets the same email, composed once.+ const emails = new Map<string, Promise<DeliveryPayload>>();+ const emailFor = (type: NotificationType, locale: Locale) => {+ const key = `${type}:${locale}`;+ const email = emails.get(key) ?? messages.email(type, locale);+ emails.set(key, email);+ return email;+ };+const out: OutboxRow[] = [];for (const n of notifications) {const prefs = prefsByUser.get(n.userId);@@ -280,7 +265,7 @@ export async function enqueueOutbound(projectId,channel: 'email',recipient: email,- payload: messages.email(n.type),+ payload: await emailFor(n.type, localeByUser.get(n.userId) ?? DEFAULT_LOCALE),});}if (telegramEnabled && prefs.telegramEvents[n.type]) {diff --git a/apps/api/src/modules/settings/__tests__/integration/whats-new.test.ts b/apps/api/src/modules/settings/__tests__/integration/whats-new.test.tsindex 291756d6..52961a65 100644--- a/apps/api/src/modules/settings/__tests__/integration/whats-new.test.ts+++ b/apps/api/src/modules/settings/__tests__/integration/whats-new.test.ts@@ -49,6 +49,18 @@ describe('whats-new', () => {expect(second.data?.pending).toBe(false);});+ it('keeps the language of the browser for a user with no preferences yet', async () => {+ const user = await signUpTestUser();+ const api = authedApi(user.cookie, { 'accept-language': 'ru' });++ await api.settings['whats-new'].seen.post();++ const stored = await authedApi(user.cookie, {+ 'accept-language': 'en',+ }).account.preferences.get();+ expect(stored.data?.locale).toBe('ru');+ });+it('carries the running release, from the changelog when the feed is unreachable', async () => {const { api } = await signUpClient();diff --git a/apps/api/src/modules/settings/index.ts b/apps/api/src/modules/settings/index.tsindex 47030118..247c7b54 100644--- a/apps/api/src/modules/settings/index.ts+++ b/apps/api/src/modules/settings/index.ts@@ -4,6 +4,7 @@ import { authContext } from '#shared/auth-context';import { errors } from '#shared/responses';import { getStorageSettings } from '@repo/db';import { getAuthSettings } from '@repo/auth';+import { localeFromAcceptLanguage } from '@repo/mailer';import { getHotkeySettings } from './service';import { getAppVersion } from './updates';import { getWhatsNew, markWhatsNewSeen } from './whats-new';@@ -82,8 +83,11 @@ export const settingsRoutes = new Elysia({.post('/settings/whats-new/seen',- async ({ user }) => {- await markWhatsNewSeen(requireUser(user).id);+ async ({ user, request }) => {+ await markWhatsNewSeen(+ requireUser(user).id,+ localeFromAcceptLanguage(request.headers.get('accept-language')),+ );return { version: getAppVersion() };},{diff --git a/apps/api/src/modules/settings/whats-new.ts b/apps/api/src/modules/settings/whats-new.tsindex e1b734d8..07434884 100644--- a/apps/api/src/modules/settings/whats-new.ts+++ b/apps/api/src/modules/settings/whats-new.ts@@ -1,4 +1,5 @@import { db, appSetting, userPreference } from '@repo/db';+import type { Locale } from '@repo/mailer';import { eq, sql } from 'drizzle-orm';import type { AuthUser } from '#shared/access';import { getAppVersion, releasesSince, type Release } from './updates';@@ -86,10 +87,10 @@ export async function getWhatsNew(user: AuthUser): Promise<WhatsNew> {// Closes the screen for this user, for the version they saw. A row is written even// when they have no preferences yet, so the screen does not come back.-export async function markWhatsNewSeen(userId: string): Promise<void> {+export async function markWhatsNewSeen(userId: string, locale: Locale): Promise<void> {await db.insert(userPreference)- .values({ userId, seenVersion: getAppVersion() })+ .values({ userId, locale, seenVersion: getAppVersion() }).onConflictDoUpdate({target: userPreference.userId,set: { seenVersion: getAppVersion(), updatedAt: sql`now()` },diff --git a/apps/api/src/modules/user-preferences/index.ts b/apps/api/src/modules/user-preferences/index.tsindex de470163..c90b5668 100644--- a/apps/api/src/modules/user-preferences/index.ts+++ b/apps/api/src/modules/user-preferences/index.ts@@ -1,11 +1,11 @@import { Elysia } from 'elysia';+import { localeFromAcceptLanguage } from '@repo/mailer';import { getProjectAccess, requireUser } from '#shared/access';import { authContext } from '#shared/auth-context';import { HttpError } from '#shared/lib';import { errors } from '#shared/responses';import { PreferencePatch, PreferenceResponse } from './model';import { getPreferences, isValidTimezone, updatePreferences } from './service';-import { localeFromAcceptLanguage } from './locale';// The session user's own interface preferences: timezone, language, theme, how a clicked issue// opens, which section the app root lands on, whether the floating AI chat startsdiff --git a/apps/api/src/modules/user-preferences/model.ts b/apps/api/src/modules/user-preferences/model.tsindex 47cf8067..f182c66b 100644--- a/apps/api/src/modules/user-preferences/model.ts+++ b/apps/api/src/modules/user-preferences/model.ts@@ -1,21 +1,10 @@import { t } from 'elysia';+import { LOCALES } from '@repo/mailer';import { HotkeyCombosSchema } from '#modules/settings/model';-const Locale = t.Union([- t.Literal('en'),- t.Literal('uk'),- t.Literal('ru'),- t.Literal('zh-CN'),- t.Literal('zh-TW'),- t.Literal('ar'),- t.Literal('fa'),- t.Literal('fr'),- t.Literal('pt-BR'),- t.Literal('id'),- t.Literal('es-ES'),- t.Literal('ko'),- t.Literal('tr'),-]);+// t.UnionEnum defaults to its first value, which would reset the language on a patch that+// leaves it out.+const Locale = t.UnionEnum([...LOCALES], { default: undefined });const Theme = t.Union([t.Literal('light'), t.Literal('dark'), t.Literal('system')]);const IssueOpenMode = t.Union([t.Literal('panel'), t.Literal('page')]);const StartPage = t.Union([diff --git a/apps/api/src/modules/user-preferences/service.ts b/apps/api/src/modules/user-preferences/service.tsindex 73c712b2..0a2cc6ca 100644--- a/apps/api/src/modules/user-preferences/service.ts+++ b/apps/api/src/modules/user-preferences/service.ts@@ -1,6 +1,6 @@import { db, userPreference } from '@repo/db';+import { DEFAULT_LOCALE, type Locale } from '@repo/mailer';import { eq, sql } from 'drizzle-orm';-import { DEFAULT_LOCALE, type Locale } from './locale';// A user's own interface preferences, held per account so the same choices apply on// every device. One row per user; absent means nothing was changed yet and thediff --git a/apps/web/messages/ar/god.json b/apps/web/messages/ar/god.jsonindex d973d984..5304447e 100644--- a/apps/web/messages/ar/god.json+++ b/apps/web/messages/ar/god.json@@ -328,6 +328,117 @@"clientSecretPlaceholder": "سرّ تسجيل التطبيق","microsoft365Hint": "يسجّل الدخول كتسجيل تطبيق في Entra ID بدلًا من كلمة مرور صندوق البريد، فيمكن أن يبقى التحقق متعدد العوامل مفعّلًا. يحتاج التطبيق إلى إذن التطبيق SMTP.SendAsApp من Office 365 Exchange Online بموافقة المسؤول، وإلى الوصول إلى هذا الصندوق في Exchange، وتفعيل SMTP AUTH للصندوق."},+ "emailTemplates": {+ "saved": "اتحفظت قوالب البريد",+ "unsaved": "فيه تغييرات مش محفوظة",+ "blankText": "كمّل الموضوع أو النص الناقص عشان تحفظ",+ "emails": "الرسائل",+ "layout": "التخطيط",+ "edited": "متعدّل",+ "subject": "الموضوع",+ "text": "النص",+ "button": "الزرار",+ "formatting": "التنسيق",+ "heading1": "عنوان 1",+ "heading2": "عنوان 2",+ "bold": "عريض",+ "italic": "مائل",+ "strikethrough": "يتوسطه خط",+ "link": "رابط",+ "bulletedList": "قائمة نقطية",+ "numberedList": "قائمة مرقّمة",+ "quote": "اقتباس",+ "boldSample": "عريض",+ "italicSample": "مائل",+ "strikeSample": "نص",+ "linkSample": "نص الرابط",+ "unknownVariables": "متغيّرات مش معروفة: {names}",+ "removeUnknownVariables": "شيل المتغيّرات المش معروفة عشان تحفظ",+ "reset": "رجّع الافتراضي",+ "test": "إرسال اختبار",+ "testing": "جاري الإرسال…",+ "testSent": "اتبعت لـ {email}",+ "testNeedsProvider": "اضبط مزوّد البريد الأول",+ "layoutHtml": "HTML التخطيط",+ "layoutCss": "CSS التخطيط",+ "placeholders": "العناصر النائبة",+ "variables": "المتغيّرات",+ "required": "مطلوب",+ "requiredPlaceholders": "ضيف {names} للتخطيط عشان تحفظ",+ "preview": "معاينة",+ "previewEmail": "الرسالة",+ "previewText": "نص عادي",+ "previewFailed": "المعاينة ماحمّلتش. حدّث الصفحة وجرّب تاني.",+ "from": "من",+ "to": "إلى",+ "groups": {+ "signIn": "تسجيل الدخول",+ "invitations": "الدعوات",+ "notifications": "الإشعارات",+ "service": "أخرى"+ },+ "templates": {+ "reset": {+ "name": "إعادة تعيين كلمة المرور"+ },+ "verify": {+ "name": "تأكيد عنوان البريد"+ },+ "magic": {+ "name": "رابط تسجيل الدخول"+ },+ "inviteProject": {+ "name": "دعوة لمشروع"+ },+ "inviteTeam": {+ "name": "دعوة لفريق"+ },+ "assigned": {+ "name": "تعيين مهمة"+ },+ "mentioned": {+ "name": "إشارة في مهمة"+ },+ "commented": {+ "name": "تعليق جديد"+ },+ "stateChanged": {+ "name": "تغيير الحالة"+ },+ "documentMentioned": {+ "name": "إشارة في مستند"+ },+ "documentCommentMentioned": {+ "name": "إشارة في تعليق على مستند"+ },+ "test": {+ "name": "رسالة اختبار",+ "hint": "بتتبعت من زر الاختبار في صفحة مزوّد البريد."+ }+ },+ "placeholderText": {+ "content": "نص الرسالة",+ "button": "زرار فيه الرابط",+ "subject": "الموضوع",+ "lang": "كود اللغة",+ "dir": "اتجاه النص",+ "site_name": "اسم النسخة",+ "site_url": "عنوان النسخة",+ "logo_url": "عنوان الشعار"+ },+ "variableText": {+ "actor": "اللي عمل الإجراء",+ "ref": "رقم المهمة",+ "title": "عنوان المهمة",+ "from": "الحالة السابقة",+ "to": "الحالة الجديدة",+ "document": "عنوان المستند",+ "inviter": "اللي بعت الدعوة",+ "project": "اسم المشروع",+ "team": "اسم الفريق",+ "role": "الدور بعد الانضمام"+ }+ },"authProvider": {"saved": "تم حفظ مزوّد المصادقة","google": "Google",diff --git a/apps/web/messages/ar/sections.json b/apps/web/messages/ar/sections.jsonindex 7925ab61..686740ef 100644--- a/apps/web/messages/ar/sections.json+++ b/apps/web/messages/ar/sections.json@@ -45,6 +45,10 @@"label": "التخزين","description": "الناس تقدر ترفع قد إيه: حجم الملف الواحد، وأنواع المرفقات المقبولة، والمساحة اللي بياخدها كل مشروع."},+ "email-templates": {+ "label": "قوالب البريد",+ "description": "إدارة قوالب رسائل النظام."+ },"telegram": {"label": "Telegram","description": "البوت اللي الناس بتربط بيه حساب Telegram بتاعها، والبوت اللي بيبعت إشعارات Telegram للمشاريع اللي محدّدتش بوت خاص بيها."diff --git a/apps/web/messages/en/god.json b/apps/web/messages/en/god.jsonindex dc836e1e..40c8d9bd 100644--- a/apps/web/messages/en/god.json+++ b/apps/web/messages/en/god.json@@ -328,6 +328,117 @@"clientSecretPlaceholder": "App registration secret","microsoft365Hint": "Signs in as an app registration in Entra ID instead of with the mailbox password, so the mailbox can keep MFA on. The app needs the Office 365 Exchange Online application permission SMTP.SendAsApp with admin consent, access to this mailbox in Exchange, and SMTP AUTH turned on for the mailbox."},+ "emailTemplates": {+ "saved": "Email templates saved",+ "unsaved": "Unsaved changes",+ "blankText": "Add the missing subject or text to save",+ "emails": "Emails",+ "layout": "Layout",+ "edited": "Edited",+ "subject": "Subject",+ "text": "Text",+ "button": "Button",+ "formatting": "Formatting",+ "heading1": "Heading 1",+ "heading2": "Heading 2",+ "bold": "Bold",+ "italic": "Italic",+ "strikethrough": "Strikethrough",+ "link": "Link",+ "bulletedList": "Bulleted list",+ "numberedList": "Numbered list",+ "quote": "Quote",+ "boldSample": "bold",+ "italicSample": "italic",+ "strikeSample": "text",+ "linkSample": "link text",+ "unknownVariables": "{count, plural, one {Unknown variable: {names}} other {Unknown variables: {names}}}",+ "removeUnknownVariables": "Remove the unknown variables to save",+ "reset": "Reset to default",+ "test": "Send test",+ "testing": "Sending…",+ "testSent": "Sent to {email}",+ "testNeedsProvider": "Set up the email provider first",+ "layoutHtml": "Layout HTML",+ "layoutCss": "Layout CSS",+ "placeholders": "Placeholders",+ "variables": "Variables",+ "required": "Required",+ "requiredPlaceholders": "Add {names} to the layout to save",+ "preview": "Preview",+ "previewEmail": "Email",+ "previewText": "Plain text",+ "previewFailed": "The preview didn't load. Reload the page to try again.",+ "from": "From",+ "to": "To",+ "groups": {+ "signIn": "Sign-in",+ "invitations": "Invitations",+ "notifications": "Notifications",+ "service": "Other"+ },+ "templates": {+ "reset": {+ "name": "Password reset"+ },+ "verify": {+ "name": "Confirm email address"+ },+ "magic": {+ "name": "Sign-in link"+ },+ "inviteProject": {+ "name": "Project invitation"+ },+ "inviteTeam": {+ "name": "Team invitation"+ },+ "assigned": {+ "name": "Issue assigned"+ },+ "mentioned": {+ "name": "Mentioned on an issue"+ },+ "commented": {+ "name": "New comment"+ },+ "stateChanged": {+ "name": "Status changed"+ },+ "documentMentioned": {+ "name": "Mentioned in a document"+ },+ "documentCommentMentioned": {+ "name": "Mentioned in a document comment"+ },+ "test": {+ "name": "Test email",+ "hint": "Sent by the test button on the Email provider page."+ }+ },+ "placeholderText": {+ "content": "Email text",+ "button": "Button with the link",+ "subject": "Subject",+ "lang": "Language code",+ "dir": "Text direction",+ "site_name": "Instance name",+ "site_url": "Instance address",+ "logo_url": "Logo address"+ },+ "variableText": {+ "actor": "Who did it",+ "ref": "Issue number",+ "title": "Issue title",+ "from": "Previous status",+ "to": "New status",+ "document": "Document title",+ "inviter": "Who sent the invitation",+ "project": "Project name",+ "team": "Team name",+ "role": "Role after joining"+ }+ },"authProvider": {"saved": "Auth provider saved","google": "Google",diff --git a/apps/web/messages/en/sections.json b/apps/web/messages/en/sections.jsonindex 4e5839ce..f2745957 100644--- a/apps/web/messages/en/sections.json+++ b/apps/web/messages/en/sections.json@@ -45,6 +45,10 @@"label": "Storage","description": "How much people may upload: the size of a single file, the attachment types accepted, and the storage each project gets."},+ "email-templates": {+ "label": "Email templates",+ "description": "Manage system email templates."+ },"telegram": {"label": "Telegram","description": "The bot people connect their Telegram account to, and the one that delivers Telegram notifications for projects that set no bot of their own."diff --git a/apps/web/messages/es-ES/god.json b/apps/web/messages/es-ES/god.jsonindex dccccda7..062c5fb0 100644--- a/apps/web/messages/es-ES/god.json+++ b/apps/web/messages/es-ES/god.json@@ -328,6 +328,117 @@"clientSecretPlaceholder": "Secreto del registro de aplicación","microsoft365Hint": "Inicia sesión como un registro de aplicación de Entra ID en lugar de con la contraseña del buzón, así el buzón puede mantener el MFA. La aplicación necesita el permiso de aplicación SMTP.SendAsApp de Office 365 Exchange Online con consentimiento de administrador, acceso a este buzón en Exchange y SMTP AUTH activado en el buzón."},+ "emailTemplates": {+ "saved": "Plantillas de correo guardadas",+ "unsaved": "Cambios sin guardar",+ "blankText": "Añade el asunto o el texto que falta para guardar",+ "emails": "Correos",+ "layout": "Diseño",+ "edited": "Editado",+ "subject": "Asunto",+ "text": "Texto",+ "button": "Botón",+ "formatting": "Formato",+ "heading1": "Título 1",+ "heading2": "Título 2",+ "bold": "Negrita",+ "italic": "Cursiva",+ "strikethrough": "Tachado",+ "link": "Enlace",+ "bulletedList": "Lista con viñetas",+ "numberedList": "Lista numerada",+ "quote": "Cita",+ "boldSample": "negrita",+ "italicSample": "cursiva",+ "strikeSample": "texto",+ "linkSample": "texto del enlace",+ "unknownVariables": "{count, plural, one {Variable desconocida: {names}} other {Variables desconocidas: {names}}}",+ "removeUnknownVariables": "Quita las variables desconocidas para guardar",+ "reset": "Volver al original",+ "test": "Enviar prueba",+ "testing": "Enviando…",+ "testSent": "Enviado a {email}",+ "testNeedsProvider": "Configura primero el proveedor de correo",+ "layoutHtml": "HTML del diseño",+ "layoutCss": "CSS del diseño",+ "placeholders": "Marcadores",+ "variables": "Variables",+ "required": "Obligatorio",+ "requiredPlaceholders": "Añade {names} al diseño para guardar",+ "preview": "Vista previa",+ "previewEmail": "Correo",+ "previewText": "Texto sin formato",+ "previewFailed": "La vista previa no se ha cargado. Recarga la página para volver a intentarlo.",+ "from": "De",+ "to": "Para",+ "groups": {+ "signIn": "Inicio de sesión",+ "invitations": "Invitaciones",+ "notifications": "Notificaciones",+ "service": "Otros"+ },+ "templates": {+ "reset": {+ "name": "Restablecimiento de contraseña"+ },+ "verify": {+ "name": "Confirmación de dirección"+ },+ "magic": {+ "name": "Enlace de inicio de sesión"+ },+ "inviteProject": {+ "name": "Invitación a un proyecto"+ },+ "inviteTeam": {+ "name": "Invitación a un equipo"+ },+ "assigned": {+ "name": "Ticket asignado"+ },+ "mentioned": {+ "name": "Mención en un ticket"+ },+ "commented": {+ "name": "Comentario nuevo"+ },+ "stateChanged": {+ "name": "Estado cambiado"+ },+ "documentMentioned": {+ "name": "Mención en un documento"+ },+ "documentCommentMentioned": {+ "name": "Mención en un comentario de documento"+ },+ "test": {+ "name": "Correo de prueba",+ "hint": "Lo envía el botón de prueba de la página del proveedor de correo."+ }+ },+ "placeholderText": {+ "content": "Texto del correo",+ "button": "Botón con el enlace",+ "subject": "Asunto",+ "lang": "Código de idioma",+ "dir": "Dirección del texto",+ "site_name": "Nombre de la instancia",+ "site_url": "Dirección de la instancia",+ "logo_url": "Dirección del logotipo"+ },+ "variableText": {+ "actor": "Quién lo hizo",+ "ref": "Número del ticket",+ "title": "Título del ticket",+ "from": "Estado anterior",+ "to": "Estado nuevo",+ "document": "Título del documento",+ "inviter": "Quién envió la invitación",+ "project": "Nombre del proyecto",+ "team": "Nombre del equipo",+ "role": "Rol al unirse"+ }+ },"authProvider": {"saved": "El proveedor de autenticación se ha guardado","google": "Google",diff --git a/apps/web/messages/es-ES/sections.json b/apps/web/messages/es-ES/sections.jsonindex 0bc5dbec..7e5d3137 100644--- a/apps/web/messages/es-ES/sections.json+++ b/apps/web/messages/es-ES/sections.json@@ -45,6 +45,10 @@"label": "Almacenamiento","description": "Cuánto pueden subir las personas: el tamaño de un fichero solo, los tipos de adjunto aceptados, y el almacenamiento que recibe cada proyecto."},+ "email-templates": {+ "label": "Plantillas de correo",+ "description": "Gestiona las plantillas de los correos del sistema."+ },"telegram": {"label": "Telegram","description": "El bot al que las personas conectan su cuenta de Telegram, y el que entrega las notificaciones de Telegram para los proyectos que no definen un bot propio."diff --git a/apps/web/messages/fa/god.json b/apps/web/messages/fa/god.jsonindex a2832b87..070d0677 100644--- a/apps/web/messages/fa/god.json+++ b/apps/web/messages/fa/god.json@@ -328,6 +328,117 @@"clientSecretPlaceholder": "رمز ثبت برنامه","microsoft365Hint": "بهجای گذرواژهٔ صندوق پستی، بهعنوان یک ثبت برنامه (app registration) در Entra ID وارد میشود تا MFA صندوق پستی روشن بماند. برنامه به مجوز برنامهای SMTP.SendAsApp از Office 365 Exchange Online با تأیید مدیر، دسترسی به این صندوق پستی در Exchange و روشن بودن SMTP AUTH برای صندوق پستی نیاز دارد."},+ "emailTemplates": {+ "saved": "قالبهای ایمیل ذخیره شد",+ "unsaved": "تغییرات ذخیرهنشده",+ "blankText": "برای ذخیره، موضوع یا متن خالی را کامل کنید",+ "emails": "ایمیلها",+ "layout": "چیدمان",+ "edited": "ویرایششده",+ "subject": "موضوع",+ "text": "متن",+ "button": "دکمه",+ "formatting": "قالببندی",+ "heading1": "عنوان ۱",+ "heading2": "عنوان ۲",+ "bold": "پررنگ",+ "italic": "کج",+ "strikethrough": "خطخورده",+ "link": "لینک",+ "bulletedList": "فهرست نقطهای",+ "numberedList": "فهرست شمارهدار",+ "quote": "نقلقول",+ "boldSample": "پررنگ",+ "italicSample": "کج",+ "strikeSample": "متن",+ "linkSample": "متن لینک",+ "unknownVariables": "متغیر ناشناخته: {names}",+ "removeUnknownVariables": "برای ذخیره، متغیرهای ناشناخته را حذف کنید",+ "reset": "بازگشت به پیشفرض",+ "test": "ارسال آزمایشی",+ "testing": "در حال ارسال…",+ "testSent": "به {email} ارسال شد",+ "testNeedsProvider": "ابتدا ارائهدهنده ایمیل را تنظیم کنید",+ "layoutHtml": "HTML چیدمان",+ "layoutCss": "CSS چیدمان",+ "placeholders": "جاینگهدارها",+ "variables": "متغیرها",+ "required": "الزامی",+ "requiredPlaceholders": "برای ذخیره، {names} را به چیدمان اضافه کنید",+ "preview": "پیشنمایش",+ "previewEmail": "ایمیل",+ "previewText": "متن ساده",+ "previewFailed": "پیشنمایش بارگیری نشد. برای تلاش دوباره صفحه را تازه کنید.",+ "from": "از",+ "to": "به",+ "groups": {+ "signIn": "ورود",+ "invitations": "دعوتها",+ "notifications": "اعلانها",+ "service": "سایر"+ },+ "templates": {+ "reset": {+ "name": "بازنشانی گذرواژه"+ },+ "verify": {+ "name": "تأیید نشانی ایمیل"+ },+ "magic": {+ "name": "لینک ورود"+ },+ "inviteProject": {+ "name": "دعوت به پروژه"+ },+ "inviteTeam": {+ "name": "دعوت به تیم"+ },+ "assigned": {+ "name": "واگذاری تسک"+ },+ "mentioned": {+ "name": "نامبردن در تسک"+ },+ "commented": {+ "name": "دیدگاه جدید"+ },+ "stateChanged": {+ "name": "تغییر وضعیت"+ },+ "documentMentioned": {+ "name": "نامبردن در سند"+ },+ "documentCommentMentioned": {+ "name": "نامبردن در دیدگاه سند"+ },+ "test": {+ "name": "ایمیل آزمایشی",+ "hint": "با دکمه آزمایش در صفحه ارائهدهنده ایمیل ارسال میشود."+ }+ },+ "placeholderText": {+ "content": "متن ایمیل",+ "button": "دکمه با لینک",+ "subject": "موضوع",+ "lang": "کد زبان",+ "dir": "جهت متن",+ "site_name": "نام سامانه",+ "site_url": "نشانی سامانه",+ "logo_url": "نشانی لوگو"+ },+ "variableText": {+ "actor": "انجامدهنده کار",+ "ref": "شماره تسک",+ "title": "عنوان تسک",+ "from": "وضعیت قبلی",+ "to": "وضعیت جدید",+ "document": "عنوان سند",+ "inviter": "فرستنده دعوت",+ "project": "نام پروژه",+ "team": "نام تیم",+ "role": "نقش پس از پیوستن"+ }+ },"authProvider": {"saved": "ارائهدهنده احراز هویت ذخیره شد","google": "Google",diff --git a/apps/web/messages/fa/sections.json b/apps/web/messages/fa/sections.jsonindex 32f05103..271006be 100644--- a/apps/web/messages/fa/sections.json+++ b/apps/web/messages/fa/sections.json@@ -45,6 +45,10 @@"label": "فضای ذخیرهسازی","description": "میزان مجاز بارگذاری: حجم یک فایل، انواع پیوست پذیرفتهشده، و فضای اختصاصیافته به هر پروژه."},+ "email-templates": {+ "label": "قالبهای ایمیل",+ "description": "مدیریت قالبهای ایمیل سیستمی."+ },"telegram": {"label": "Telegram","description": "رباتی که کاربران حساب Telegram خود را به آن متصل میکنند، و رباتی که اعلانهای Telegram را برای پروژههایی که ربات اختصاصی ندارند ارسال میکند."diff --git a/apps/web/messages/fr/god.json b/apps/web/messages/fr/god.jsonindex 4986f719..8e8b9c49 100644--- a/apps/web/messages/fr/god.json+++ b/apps/web/messages/fr/god.json@@ -328,6 +328,117 @@"clientSecretPlaceholder": "Secret de l’inscription d’application","microsoft365Hint": "Se connecte en tant qu’inscription d’application Entra ID au lieu du mot de passe de la boîte, qui peut ainsi garder la MFA. L’application a besoin de l’autorisation d’application SMTP.SendAsApp d’Office 365 Exchange Online avec consentement administrateur, d’un accès à cette boîte dans Exchange et de SMTP AUTH activé sur la boîte."},+ "emailTemplates": {+ "saved": "Modèles d'e-mails enregistrés",+ "unsaved": "Modifications non enregistrées",+ "blankText": "Ajoutez l'objet ou le texte manquant pour enregistrer",+ "emails": "E-mails",+ "layout": "Mise en page",+ "edited": "Modifié",+ "subject": "Objet",+ "text": "Texte",+ "button": "Bouton",+ "formatting": "Mise en forme",+ "heading1": "Titre 1",+ "heading2": "Titre 2",+ "bold": "Gras",+ "italic": "Italique",+ "strikethrough": "Barré",+ "link": "Lien",+ "bulletedList": "Liste à puces",+ "numberedList": "Liste numérotée",+ "quote": "Citation",+ "boldSample": "gras",+ "italicSample": "italique",+ "strikeSample": "texte",+ "linkSample": "texte du lien",+ "unknownVariables": "{count, plural, one {Variable inconnue : {names}} other {Variables inconnues : {names}}}",+ "removeUnknownVariables": "Retirez les variables inconnues pour enregistrer",+ "reset": "Rétablir l'original",+ "test": "Envoyer un test",+ "testing": "Envoi…",+ "testSent": "Envoyé à {email}",+ "testNeedsProvider": "Configurez d'abord le fournisseur d'e-mails",+ "layoutHtml": "HTML de la mise en page",+ "layoutCss": "CSS de la mise en page",+ "placeholders": "Espaces réservés",+ "variables": "Variables",+ "required": "Requis",+ "requiredPlaceholders": "Ajoutez {names} à la mise en page pour enregistrer",+ "preview": "Aperçu",+ "previewEmail": "E-mail",+ "previewText": "Texte brut",+ "previewFailed": "L'aperçu ne s'est pas chargé. Rechargez la page pour réessayer.",+ "from": "De",+ "to": "À",+ "groups": {+ "signIn": "Connexion",+ "invitations": "Invitations",+ "notifications": "Notifications",+ "service": "Autres"+ },+ "templates": {+ "reset": {+ "name": "Réinitialisation du mot de passe"+ },+ "verify": {+ "name": "Confirmation de l'adresse"+ },+ "magic": {+ "name": "Lien de connexion"+ },+ "inviteProject": {+ "name": "Invitation à un projet"+ },+ "inviteTeam": {+ "name": "Invitation à une équipe"+ },+ "assigned": {+ "name": "Ticket assigné"+ },+ "mentioned": {+ "name": "Mention sur un ticket"+ },+ "commented": {+ "name": "Nouveau commentaire"+ },+ "stateChanged": {+ "name": "État modifié"+ },+ "documentMentioned": {+ "name": "Mention dans un document"+ },+ "documentCommentMentioned": {+ "name": "Mention dans un commentaire de document"+ },+ "test": {+ "name": "E-mail de test",+ "hint": "Envoyé par le bouton de test de la page du fournisseur d'e-mail."+ }+ },+ "placeholderText": {+ "content": "Texte de l'e-mail",+ "button": "Bouton avec le lien",+ "subject": "Objet",+ "lang": "Code de langue",+ "dir": "Sens du texte",+ "site_name": "Nom de l'instance",+ "site_url": "Adresse de l'instance",+ "logo_url": "Adresse du logo"+ },+ "variableText": {+ "actor": "Auteur de l'action",+ "ref": "Numéro du ticket",+ "title": "Titre du ticket",+ "from": "État précédent",+ "to": "Nouvel état",+ "document": "Titre du document",+ "inviter": "Auteur de l'invitation",+ "project": "Nom du projet",+ "team": "Nom de l'équipe",+ "role": "Rôle après l'arrivée"+ }+ },"authProvider": {"saved": "Fournisseur d'authentification enregistré","google": "Google",diff --git a/apps/web/messages/fr/sections.json b/apps/web/messages/fr/sections.jsonindex 177d8acc..059e5cf6 100644--- a/apps/web/messages/fr/sections.json+++ b/apps/web/messages/fr/sections.json@@ -45,6 +45,10 @@"label": "Stockage","description": "Ce que les utilisateurs peuvent envoyer : la taille maximale d'un fichier, les types de pièces jointes acceptés, et l'espace de stockage alloué à chaque projet."},+ "email-templates": {+ "label": "Modèles d'e-mails",+ "description": "Gérez les modèles des e-mails système."+ },"telegram": {"label": "Telegram","description": "Le bot auquel les utilisateurs relient leur compte Telegram, et celui qui envoie les notifications Telegram des projets sans bot dédié."diff --git a/apps/web/messages/id/god.json b/apps/web/messages/id/god.jsonindex 8a4c4912..2dc463b0 100644--- a/apps/web/messages/id/god.json+++ b/apps/web/messages/id/god.json@@ -328,6 +328,117 @@"clientSecretPlaceholder": "Rahasia pendaftaran aplikasi","microsoft365Hint": "Masuk sebagai pendaftaran aplikasi Entra ID, bukan dengan kata sandi kotak surat, sehingga kotak surat tetap bisa memakai MFA. Aplikasi memerlukan izin aplikasi SMTP.SendAsApp dari Office 365 Exchange Online dengan persetujuan admin, akses ke kotak surat ini di Exchange, dan SMTP AUTH aktif untuk kotak surat."},+ "emailTemplates": {+ "saved": "Template email disimpan",+ "unsaved": "Ada perubahan yang belum disimpan",+ "blankText": "Lengkapi subjek atau teks yang kosong untuk menyimpan",+ "emails": "Email",+ "layout": "Tata letak",+ "edited": "Diedit",+ "subject": "Subjek",+ "text": "Teks",+ "button": "Tombol",+ "formatting": "Pemformatan",+ "heading1": "Judul 1",+ "heading2": "Judul 2",+ "bold": "Tebal",+ "italic": "Miring",+ "strikethrough": "Coret",+ "link": "Tautan",+ "bulletedList": "Daftar poin",+ "numberedList": "Daftar bernomor",+ "quote": "Kutipan",+ "boldSample": "tebal",+ "italicSample": "miring",+ "strikeSample": "teks",+ "linkSample": "teks tautan",+ "unknownVariables": "Variabel tidak dikenal: {names}",+ "removeUnknownVariables": "Hapus variabel yang tidak dikenal untuk menyimpan",+ "reset": "Kembalikan ke bawaan",+ "test": "Kirim tes",+ "testing": "Mengirim…",+ "testSent": "Terkirim ke {email}",+ "testNeedsProvider": "Siapkan penyedia email terlebih dahulu",+ "layoutHtml": "HTML tata letak",+ "layoutCss": "CSS tata letak",+ "placeholders": "Placeholder",+ "variables": "Variabel",+ "required": "Wajib",+ "requiredPlaceholders": "Tambahkan {names} ke tata letak untuk menyimpan",+ "preview": "Pratinjau",+ "previewEmail": "Email",+ "previewText": "Teks biasa",+ "previewFailed": "Pratinjau tidak termuat. Muat ulang halaman untuk mencoba lagi.",+ "from": "Dari",+ "to": "Kepada",+ "groups": {+ "signIn": "Masuk",+ "invitations": "Undangan",+ "notifications": "Notifikasi",+ "service": "Lainnya"+ },+ "templates": {+ "reset": {+ "name": "Atur ulang kata sandi"+ },+ "verify": {+ "name": "Konfirmasi alamat email"+ },+ "magic": {+ "name": "Tautan masuk"+ },+ "inviteProject": {+ "name": "Undangan proyek"+ },+ "inviteTeam": {+ "name": "Undangan tim"+ },+ "assigned": {+ "name": "Issue ditugaskan"+ },+ "mentioned": {+ "name": "Disebut di issue"+ },+ "commented": {+ "name": "Komentar baru"+ },+ "stateChanged": {+ "name": "Status berubah"+ },+ "documentMentioned": {+ "name": "Disebut di dokumen"+ },+ "documentCommentMentioned": {+ "name": "Disebut di komentar dokumen"+ },+ "test": {+ "name": "Email tes",+ "hint": "Dikirim oleh tombol tes di halaman penyedia email."+ }+ },+ "placeholderText": {+ "content": "Teks email",+ "button": "Tombol dengan tautan",+ "subject": "Subjek",+ "lang": "Kode bahasa",+ "dir": "Arah teks",+ "site_name": "Nama instance",+ "site_url": "Alamat instance",+ "logo_url": "Alamat logo"+ },+ "variableText": {+ "actor": "Pelaku tindakan",+ "ref": "Nomor issue",+ "title": "Judul issue",+ "from": "Status sebelumnya",+ "to": "Status baru",+ "document": "Judul dokumen",+ "inviter": "Pengirim undangan",+ "project": "Nama proyek",+ "team": "Nama tim",+ "role": "Peran setelah bergabung"+ }+ },"authProvider": {"saved": "Penyedia autentikasi disimpan","google": "Google",diff --git a/apps/web/messages/id/sections.json b/apps/web/messages/id/sections.jsonindex 22aef7bf..20eac36a 100644--- a/apps/web/messages/id/sections.json+++ b/apps/web/messages/id/sections.json@@ -45,6 +45,10 @@"label": "Penyimpanan","description": "Batas unggahan pengguna: ukuran file tunggal, jenis lampiran yang diterima, dan ruang penyimpanan untuk setiap proyek."},+ "email-templates": {+ "label": "Template email",+ "description": "Kelola template email sistem."+ },"telegram": {"label": "Telegram","description": "Bot yang dihubungkan pengguna ke akun Telegram mereka, dan bot yang mengirimkan notifikasi Telegram untuk proyek yang tidak menetapkan bot sendiri."diff --git a/apps/web/messages/ko/god.json b/apps/web/messages/ko/god.jsonindex 1e4c3aba..5f67c69f 100644--- a/apps/web/messages/ko/god.json+++ b/apps/web/messages/ko/god.json@@ -328,6 +328,117 @@"clientSecretPlaceholder": "앱 등록 시크릿","microsoft365Hint": "메일함 비밀번호 대신 Entra ID의 앱 등록으로 로그인하므로 메일함에 MFA를 유지할 수 있습니다. 앱에는 관리자 동의를 받은 Office 365 Exchange Online 애플리케이션 권한 SMTP.SendAsApp, Exchange에서 이 메일함에 대한 접근 권한, 메일함에서 활성화된 SMTP AUTH가 필요합니다."},+ "emailTemplates": {+ "saved": "이메일 템플릿을 저장했습니다",+ "unsaved": "저장되지 않은 변경 사항",+ "blankText": "저장하려면 비어 있는 제목이나 본문을 입력하세요",+ "emails": "이메일",+ "layout": "레이아웃",+ "edited": "수정됨",+ "subject": "제목",+ "text": "본문",+ "button": "버튼",+ "formatting": "서식",+ "heading1": "제목 1",+ "heading2": "제목 2",+ "bold": "굵게",+ "italic": "기울임꼴",+ "strikethrough": "취소선",+ "link": "링크",+ "bulletedList": "글머리 기호 목록",+ "numberedList": "번호 매기기 목록",+ "quote": "인용",+ "boldSample": "굵게",+ "italicSample": "기울임꼴",+ "strikeSample": "텍스트",+ "linkSample": "링크 텍스트",+ "unknownVariables": "알 수 없는 변수: {names}",+ "removeUnknownVariables": "저장하려면 알 수 없는 변수를 제거하세요",+ "reset": "기본값으로 되돌리기",+ "test": "테스트 보내기",+ "testing": "보내는 중…",+ "testSent": "{email}(으)로 보냈습니다",+ "testNeedsProvider": "먼저 이메일 공급자를 설정하세요",+ "layoutHtml": "레이아웃 HTML",+ "layoutCss": "레이아웃 CSS",+ "placeholders": "자리표시자",+ "variables": "변수",+ "required": "필수",+ "requiredPlaceholders": "저장하려면 레이아웃에 {names}을(를) 추가하세요",+ "preview": "미리 보기",+ "previewEmail": "이메일",+ "previewText": "일반 텍스트",+ "previewFailed": "미리 보기를 불러오지 못했습니다. 페이지를 새로고침하고 다시 시도하세요.",+ "from": "보낸 사람",+ "to": "받는 사람",+ "groups": {+ "signIn": "로그인",+ "invitations": "초대",+ "notifications": "알림",+ "service": "기타"+ },+ "templates": {+ "reset": {+ "name": "비밀번호 재설정"+ },+ "verify": {+ "name": "이메일 주소 인증"+ },+ "magic": {+ "name": "로그인 링크"+ },+ "inviteProject": {+ "name": "프로젝트 초대"+ },+ "inviteTeam": {+ "name": "팀 초대"+ },+ "assigned": {+ "name": "이슈 배정"+ },+ "mentioned": {+ "name": "이슈에서 멘션"+ },+ "commented": {+ "name": "새 댓글"+ },+ "stateChanged": {+ "name": "상태 변경"+ },+ "documentMentioned": {+ "name": "문서에서 멘션"+ },+ "documentCommentMentioned": {+ "name": "문서 댓글에서 멘션"+ },+ "test": {+ "name": "테스트 이메일",+ "hint": "이메일 서비스 공급자 페이지의 테스트 버튼으로 보냅니다."+ }+ },+ "placeholderText": {+ "content": "이메일 본문",+ "button": "링크가 있는 버튼",+ "subject": "제목",+ "lang": "언어 코드",+ "dir": "텍스트 방향",+ "site_name": "인스턴스 이름",+ "site_url": "인스턴스 주소",+ "logo_url": "로고 주소"+ },+ "variableText": {+ "actor": "작업한 사람",+ "ref": "이슈 번호",+ "title": "이슈 제목",+ "from": "이전 상태",+ "to": "새 상태",+ "document": "문서 제목",+ "inviter": "초대한 사람",+ "project": "프로젝트 이름",+ "team": "팀 이름",+ "role": "참여 후 역할"+ }+ },"authProvider": {"saved": "인증 공급자 설정이 저장되었습니다","google": "Google",diff --git a/apps/web/messages/ko/sections.json b/apps/web/messages/ko/sections.jsonindex be2e9099..231fb5d1 100644--- a/apps/web/messages/ko/sections.json+++ b/apps/web/messages/ko/sections.json@@ -45,6 +45,10 @@"label": "저장소","description": "업로드할 수 있는 개별 파일 크기, 허용되는 첨부 파일 유형 및 프로젝트별 저장 용량을 설정합니다."},+ "email-templates": {+ "label": "이메일 템플릿",+ "description": "시스템 이메일 템플릿을 관리합니다."+ },"telegram": {"label": "Telegram","description": "사용자가 Telegram 계정을 연결할 봇과 자체 봇을 설정하지 않은 프로젝트에서 알림을 전송할 봇을 설정합니다."diff --git a/apps/web/messages/pt-BR/god.json b/apps/web/messages/pt-BR/god.jsonindex 66b8506a..603c8010 100644--- a/apps/web/messages/pt-BR/god.json+++ b/apps/web/messages/pt-BR/god.json@@ -328,6 +328,117 @@"clientSecretPlaceholder": "Segredo do registro de aplicativo","microsoft365Hint": "Entra como um registro de aplicativo do Entra ID em vez da senha da caixa de correio, que pode manter o MFA. O aplicativo precisa da permissão de aplicativo SMTP.SendAsApp do Office 365 Exchange Online com consentimento de administrador, acesso a esta caixa no Exchange e SMTP AUTH ativado na caixa."},+ "emailTemplates": {+ "saved": "Modelos de e-mail salvos",+ "unsaved": "Alterações não salvas",+ "blankText": "Preencha o assunto ou o texto que falta para salvar",+ "emails": "E-mails",+ "layout": "Layout",+ "edited": "Editado",+ "subject": "Assunto",+ "text": "Texto",+ "button": "Botão",+ "formatting": "Formatação",+ "heading1": "Título 1",+ "heading2": "Título 2",+ "bold": "Negrito",+ "italic": "Itálico",+ "strikethrough": "Tachado",+ "link": "Link",+ "bulletedList": "Lista com marcadores",+ "numberedList": "Lista numerada",+ "quote": "Citação",+ "boldSample": "negrito",+ "italicSample": "itálico",+ "strikeSample": "texto",+ "linkSample": "texto do link",+ "unknownVariables": "{count, plural, one {Variável desconhecida: {names}} other {Variáveis desconhecidas: {names}}}",+ "removeUnknownVariables": "Remova as variáveis desconhecidas para salvar",+ "reset": "Voltar ao padrão",+ "test": "Enviar teste",+ "testing": "Enviando…",+ "testSent": "Enviado para {email}",+ "testNeedsProvider": "Configure o provedor de e-mail primeiro",+ "layoutHtml": "HTML do layout",+ "layoutCss": "CSS do layout",+ "placeholders": "Marcadores",+ "variables": "Variáveis",+ "required": "Obrigatório",+ "requiredPlaceholders": "Adicione {names} ao layout para salvar",+ "preview": "Pré-visualização",+ "previewEmail": "E-mail",+ "previewText": "Texto simples",+ "previewFailed": "A pré-visualização não carregou. Recarregue a página para tentar de novo.",+ "from": "De",+ "to": "Para",+ "groups": {+ "signIn": "Login",+ "invitations": "Convites",+ "notifications": "Notificações",+ "service": "Outros"+ },+ "templates": {+ "reset": {+ "name": "Redefinição de senha"+ },+ "verify": {+ "name": "Confirmação de endereço"+ },+ "magic": {+ "name": "Link de login"+ },+ "inviteProject": {+ "name": "Convite para projeto"+ },+ "inviteTeam": {+ "name": "Convite para equipe"+ },+ "assigned": {+ "name": "Issue atribuída"+ },+ "mentioned": {+ "name": "Menção em issue"+ },+ "commented": {+ "name": "Novo comentário"+ },+ "stateChanged": {+ "name": "Status alterado"+ },+ "documentMentioned": {+ "name": "Menção em documento"+ },+ "documentCommentMentioned": {+ "name": "Menção em comentário de documento"+ },+ "test": {+ "name": "E-mail de teste",+ "hint": "Enviado pelo botão de teste da página do provedor de e-mail."+ }+ },+ "placeholderText": {+ "content": "Texto do e-mail",+ "button": "Botão com o link",+ "subject": "Assunto",+ "lang": "Código do idioma",+ "dir": "Direção do texto",+ "site_name": "Nome da instância",+ "site_url": "Endereço da instância",+ "logo_url": "Endereço do logo"+ },+ "variableText": {+ "actor": "Quem fez a ação",+ "ref": "Número da issue",+ "title": "Título da issue",+ "from": "Status anterior",+ "to": "Novo status",+ "document": "Título do documento",+ "inviter": "Quem enviou o convite",+ "project": "Nome do projeto",+ "team": "Nome da equipe",+ "role": "Papel ao entrar"+ }+ },"authProvider": {"saved": "Provedor de autenticação salvo","google": "Google",diff --git a/apps/web/messages/pt-BR/sections.json b/apps/web/messages/pt-BR/sections.jsonindex a62b6e07..2698f4cb 100644--- a/apps/web/messages/pt-BR/sections.json+++ b/apps/web/messages/pt-BR/sections.json@@ -45,6 +45,10 @@"label": "Armazenamento","description": "Quanto as pessoas podem enviar: o tamanho de um único arquivo, os tipos de anexo aceitos e o armazenamento que cada projeto recebe."},+ "email-templates": {+ "label": "Modelos de e-mail",+ "description": "Gerencie os modelos de e-mails do sistema."+ },"telegram": {"label": "Telegram","description": "O bot ao qual as pessoas conectam sua conta do Telegram, e o que entrega notificações do Telegram para projetos que não definem seu próprio bot."diff --git a/apps/web/messages/ru/god.json b/apps/web/messages/ru/god.jsonindex 58073067..3658837f 100644--- a/apps/web/messages/ru/god.json+++ b/apps/web/messages/ru/god.json@@ -328,6 +328,117 @@"clientSecretPlaceholder": "Секрет регистрации приложения","microsoft365Hint": "Входит как регистрация приложения в Entra ID вместо пароля ящика, поэтому у ящика может оставаться MFA. Приложению нужно разрешение приложения SMTP.SendAsApp из Office 365 Exchange Online с согласием администратора, доступ к этому ящику в Exchange и включённый SMTP AUTH для ящика."},+ "emailTemplates": {+ "saved": "Шаблоны писем сохранены",+ "unsaved": "Есть несохранённые изменения",+ "blankText": "Заполните пустую тему или текст, чтобы сохранить",+ "emails": "Письма",+ "layout": "Макет",+ "edited": "Изменено",+ "subject": "Тема",+ "text": "Текст",+ "button": "Кнопка",+ "formatting": "Форматирование",+ "heading1": "Заголовок 1",+ "heading2": "Заголовок 2",+ "bold": "Жирный",+ "italic": "Курсив",+ "strikethrough": "Зачёркнутый",+ "link": "Ссылка",+ "bulletedList": "Маркированный список",+ "numberedList": "Нумерованный список",+ "quote": "Цитата",+ "boldSample": "жирный",+ "italicSample": "курсив",+ "strikeSample": "текст",+ "linkSample": "текст ссылки",+ "unknownVariables": "{count, plural, one {Неизвестная переменная: {names}} other {Неизвестные переменные: {names}}}",+ "removeUnknownVariables": "Уберите неизвестные переменные, чтобы сохранить",+ "reset": "Вернуть стандартный",+ "test": "Отправить тест",+ "testing": "Отправка…",+ "testSent": "Отправлено на {email}",+ "testNeedsProvider": "Сначала настройте почтового провайдера",+ "layoutHtml": "HTML макета",+ "layoutCss": "CSS макета",+ "placeholders": "Подстановки",+ "variables": "Переменные",+ "required": "Обязательно",+ "requiredPlaceholders": "Добавьте в макет {names}, чтобы сохранить",+ "preview": "Предпросмотр",+ "previewEmail": "Письмо",+ "previewText": "Обычный текст",+ "previewFailed": "Предпросмотр не загрузился. Обновите страницу и попробуйте снова.",+ "from": "От",+ "to": "Кому",+ "groups": {+ "signIn": "Вход",+ "invitations": "Приглашения",+ "notifications": "Уведомления",+ "service": "Другое"+ },+ "templates": {+ "reset": {+ "name": "Сброс пароля"+ },+ "verify": {+ "name": "Подтверждение адреса"+ },+ "magic": {+ "name": "Ссылка для входа"+ },+ "inviteProject": {+ "name": "Приглашение в проект"+ },+ "inviteTeam": {+ "name": "Приглашение в команду"+ },+ "assigned": {+ "name": "Задача назначена"+ },+ "mentioned": {+ "name": "Упоминание в задаче"+ },+ "commented": {+ "name": "Новый комментарий"+ },+ "stateChanged": {+ "name": "Статус изменён"+ },+ "documentMentioned": {+ "name": "Упоминание в документе"+ },+ "documentCommentMentioned": {+ "name": "Упоминание в комментарии к документу"+ },+ "test": {+ "name": "Тестовое письмо",+ "hint": "Уходит по кнопке теста на странице почтового провайдера."+ }+ },+ "placeholderText": {+ "content": "Текст письма",+ "button": "Кнопка со ссылкой",+ "subject": "Тема",+ "lang": "Код языка",+ "dir": "Направление текста",+ "site_name": "Название инстанса",+ "site_url": "Адрес инстанса",+ "logo_url": "Адрес логотипа"+ },+ "variableText": {+ "actor": "Кто это сделал",+ "ref": "Номер задачи",+ "title": "Название задачи",+ "from": "Прежний статус",+ "to": "Новый статус",+ "document": "Название документа",+ "inviter": "Кто отправил приглашение",+ "project": "Название проекта",+ "team": "Название команды",+ "role": "Роль после вступления"+ }+ },"authProvider": {"saved": "Провайдер входа сохранён","google": "Google",diff --git a/apps/web/messages/ru/sections.json b/apps/web/messages/ru/sections.jsonindex e2f383fd..bfc0fa6a 100644--- a/apps/web/messages/ru/sections.json+++ b/apps/web/messages/ru/sections.json@@ -45,6 +45,10 @@"label": "Хранилище","description": "Сколько можно загружать: размер одного файла, разрешённые типы вложений и объём хранилища на проект."},+ "email-templates": {+ "label": "Шаблоны писем",+ "description": "Управление шаблонами системных писем."+ },"telegram": {"label": "Telegram","description": "Бот, к которому люди подключают свой Telegram, и бот, доставляющий Telegram-уведомления для проектов без собственного бота."diff --git a/apps/web/messages/tr/god.json b/apps/web/messages/tr/god.jsonindex 265a2f2e..6a9110d9 100644--- a/apps/web/messages/tr/god.json+++ b/apps/web/messages/tr/god.json@@ -328,6 +328,117 @@"clientSecretPlaceholder": "Uygulama kayıt parolası","microsoft365Hint": "Posta kutusu şifresi yerine Entra ID içindeki bir uygulama kaydı olarak oturum açar, böylece posta kutusunda çok faktörlü kimlik doğrulama (MFA) açık kalabilir. Uygulama; yönetici onayıyla Office 365 Exchange Online SMTP.SendAsApp iznine, Exchange içinde bu posta kutusuna erişim yetkisine ve posta kutusu için SMTP AUTH özelliğinin açık olmasına ihtiyaç duyar."},+ "emailTemplates": {+ "saved": "E-posta şablonları kaydedildi",+ "unsaved": "Kaydedilmemiş değişiklikler",+ "blankText": "Kaydetmek için eksik konuyu veya metni doldurun",+ "emails": "E-postalar",+ "layout": "Düzen",+ "edited": "Düzenlendi",+ "subject": "Konu",+ "text": "Metin",+ "button": "Düğme",+ "formatting": "Biçimlendirme",+ "heading1": "Başlık 1",+ "heading2": "Başlık 2",+ "bold": "Kalın",+ "italic": "İtalik",+ "strikethrough": "Üstü çizili",+ "link": "Bağlantı",+ "bulletedList": "Madde işaretli liste",+ "numberedList": "Numaralı liste",+ "quote": "Alıntı",+ "boldSample": "kalın",+ "italicSample": "italik",+ "strikeSample": "metin",+ "linkSample": "bağlantı metni",+ "unknownVariables": "Bilinmeyen değişken: {names}",+ "removeUnknownVariables": "Kaydetmek için bilinmeyen değişkenleri kaldırın",+ "reset": "Varsayılana dön",+ "test": "Test gönder",+ "testing": "Gönderiliyor…",+ "testSent": "{email} adresine gönderildi",+ "testNeedsProvider": "Önce e-posta sağlayıcısını ayarlayın",+ "layoutHtml": "Düzen HTML'i",+ "layoutCss": "Düzen CSS'i",+ "placeholders": "Yer tutucular",+ "variables": "Değişkenler",+ "required": "Zorunlu",+ "requiredPlaceholders": "Kaydetmek için düzene {names} ekleyin",+ "preview": "Önizleme",+ "previewEmail": "E-posta",+ "previewText": "Düz metin",+ "previewFailed": "Önizleme yüklenmedi. Yeniden denemek için sayfayı yenileyin.",+ "from": "Kimden",+ "to": "Kime",+ "groups": {+ "signIn": "Giriş",+ "invitations": "Davetler",+ "notifications": "Bildirimler",+ "service": "Diğer"+ },+ "templates": {+ "reset": {+ "name": "Şifre sıfırlama"+ },+ "verify": {+ "name": "E-posta adresi onayı"+ },+ "magic": {+ "name": "Giriş bağlantısı"+ },+ "inviteProject": {+ "name": "Proje daveti"+ },+ "inviteTeam": {+ "name": "Ekip daveti"+ },+ "assigned": {+ "name": "İş atandı"+ },+ "mentioned": {+ "name": "İşte bahsedildi"+ },+ "commented": {+ "name": "Yeni yorum"+ },+ "stateChanged": {+ "name": "Durum değişti"+ },+ "documentMentioned": {+ "name": "Belgede bahsedildi"+ },+ "documentCommentMentioned": {+ "name": "Belge yorumunda bahsedildi"+ },+ "test": {+ "name": "Test e-postası",+ "hint": "E-posta Sağlayıcısı sayfasındaki test düğmesiyle gönderilir."+ }+ },+ "placeholderText": {+ "content": "E-posta metni",+ "button": "Bağlantılı düğme",+ "subject": "Konu",+ "lang": "Dil kodu",+ "dir": "Metin yönü",+ "site_name": "Örneklem adı",+ "site_url": "Örneklem adresi",+ "logo_url": "Logo adresi"+ },+ "variableText": {+ "actor": "İşlemi yapan",+ "ref": "İş numarası",+ "title": "İş başlığı",+ "from": "Önceki durum",+ "to": "Yeni durum",+ "document": "Belge başlığı",+ "inviter": "Daveti gönderen",+ "project": "Proje adı",+ "team": "Ekip adı",+ "role": "Katılım sonrası rol"+ }+ },"authProvider": {"saved": "Giriş sağlayıcısı kaydedildi","google": "Google",diff --git a/apps/web/messages/tr/sections.json b/apps/web/messages/tr/sections.jsonindex 9955917d..0c7319d2 100644--- a/apps/web/messages/tr/sections.json+++ b/apps/web/messages/tr/sections.json@@ -45,6 +45,10 @@"label": "Depolama","description": "Yükleme limitleri: tek dosya boyutu, kabul edilen ek türleri ve projelere tanınan depolama alanı."},+ "email-templates": {+ "label": "E-posta şablonları",+ "description": "Sistem e-postası şablonlarını yönetin."+ },"telegram": {"label": "Telegram","description": "Kullanıcıların Telegram hesaplarını bağladığı ve kendi botunu ayarlamayan projeler için bildirim gönderen bot."diff --git a/apps/web/messages/uk/god.json b/apps/web/messages/uk/god.jsonindex 6f163270..ecc2dec3 100644--- a/apps/web/messages/uk/god.json+++ b/apps/web/messages/uk/god.json@@ -328,6 +328,117 @@"clientSecretPlaceholder": "Секрет реєстрації застосунку","microsoft365Hint": "Входить як реєстрація застосунку в Entra ID замість пароля скриньки, тож скринька може залишити MFA. Застосунку потрібен дозвіл застосунку SMTP.SendAsApp з Office 365 Exchange Online зі згодою адміністратора, доступ до цієї скриньки в Exchange і ввімкнений SMTP AUTH для скриньки."},+ "emailTemplates": {+ "saved": "Шаблони листів збережено",+ "unsaved": "Є незбережені зміни",+ "blankText": "Заповніть порожню тему або текст, щоб зберегти",+ "emails": "Листи",+ "layout": "Макет",+ "edited": "Змінено",+ "subject": "Тема",+ "text": "Текст",+ "button": "Кнопка",+ "formatting": "Форматування",+ "heading1": "Заголовок 1",+ "heading2": "Заголовок 2",+ "bold": "Жирний",+ "italic": "Курсив",+ "strikethrough": "Закреслений",+ "link": "Посилання",+ "bulletedList": "Маркований список",+ "numberedList": "Нумерований список",+ "quote": "Цитата",+ "boldSample": "жирний",+ "italicSample": "курсив",+ "strikeSample": "текст",+ "linkSample": "текст посилання",+ "unknownVariables": "{count, plural, one {Невідома змінна: {names}} other {Невідомі змінні: {names}}}",+ "removeUnknownVariables": "Приберіть невідомі змінні, щоб зберегти",+ "reset": "Повернути стандартний",+ "test": "Надіслати тест",+ "testing": "Надсилання…",+ "testSent": "Надіслано на {email}",+ "testNeedsProvider": "Спочатку налаштуйте поштового провайдера",+ "layoutHtml": "HTML макета",+ "layoutCss": "CSS макета",+ "placeholders": "Підстановки",+ "variables": "Змінні",+ "required": "Обов'язково",+ "requiredPlaceholders": "Додайте в макет {names}, щоб зберегти",+ "preview": "Попередній перегляд",+ "previewEmail": "Лист",+ "previewText": "Звичайний текст",+ "previewFailed": "Попередній перегляд не завантажився. Оновіть сторінку й спробуйте ще раз.",+ "from": "Від",+ "to": "Кому",+ "groups": {+ "signIn": "Вхід",+ "invitations": "Запрошення",+ "notifications": "Сповіщення",+ "service": "Інше"+ },+ "templates": {+ "reset": {+ "name": "Скидання пароля"+ },+ "verify": {+ "name": "Підтвердження адреси"+ },+ "magic": {+ "name": "Посилання для входу"+ },+ "inviteProject": {+ "name": "Запрошення до проєкту"+ },+ "inviteTeam": {+ "name": "Запрошення до команди"+ },+ "assigned": {+ "name": "Задачу призначено"+ },+ "mentioned": {+ "name": "Згадка в задачі"+ },+ "commented": {+ "name": "Новий коментар"+ },+ "stateChanged": {+ "name": "Статус змінено"+ },+ "documentMentioned": {+ "name": "Згадка в документі"+ },+ "documentCommentMentioned": {+ "name": "Згадка в коментарі до документа"+ },+ "test": {+ "name": "Тестовий лист",+ "hint": "Надсилається кнопкою тесту на сторінці поштового провайдера."+ }+ },+ "placeholderText": {+ "content": "Текст листа",+ "button": "Кнопка з посиланням",+ "subject": "Тема",+ "lang": "Код мови",+ "dir": "Напрямок тексту",+ "site_name": "Назва інстансу",+ "site_url": "Адреса інстансу",+ "logo_url": "Адреса логотипа"+ },+ "variableText": {+ "actor": "Хто це зробив",+ "ref": "Номер задачі",+ "title": "Назва задачі",+ "from": "Попередній статус",+ "to": "Новий статус",+ "document": "Назва документа",+ "inviter": "Хто надіслав запрошення",+ "project": "Назва проєкту",+ "team": "Назва команди",+ "role": "Роль після приєднання"+ }+ },"authProvider": {"saved": "Провайдера входу збережено","google": "Google",diff --git a/apps/web/messages/uk/sections.json b/apps/web/messages/uk/sections.jsonindex 14e783ef..fce2fba3 100644--- a/apps/web/messages/uk/sections.json+++ b/apps/web/messages/uk/sections.json@@ -45,6 +45,10 @@"label": "Сховище","description": "Скільки можна завантажувати: розмір одного файлу, дозволені типи вкладень і обсяг сховища на проєкт."},+ "email-templates": {+ "label": "Шаблони листів",+ "description": "Керування шаблонами системних листів."+ },"telegram": {"label": "Telegram","description": "Бот, до якого люди підключають свій Telegram, і бот, що доставляє Telegram-сповіщення для проєктів без власного бота."diff --git a/apps/web/messages/zh-CN/god.json b/apps/web/messages/zh-CN/god.jsonindex e82aaf6f..2ba8a024 100644--- a/apps/web/messages/zh-CN/god.json+++ b/apps/web/messages/zh-CN/god.json@@ -328,6 +328,117 @@"clientSecretPlaceholder": "应用注册的密钥","microsoft365Hint": "以 Entra ID 应用注册的身份登录,而不是使用邮箱密码,因此邮箱可以保持开启 MFA。该应用需要 Office 365 Exchange Online 的应用程序权限 SMTP.SendAsApp 并经过管理员同意,在 Exchange 中拥有此邮箱的访问权限,并为该邮箱开启 SMTP AUTH。"},+ "emailTemplates": {+ "saved": "邮件模板已保存",+ "unsaved": "有未保存的更改",+ "blankText": "请填写缺少的主题或正文后再保存",+ "emails": "邮件",+ "layout": "布局",+ "edited": "已修改",+ "subject": "主题",+ "text": "正文",+ "button": "按钮",+ "formatting": "格式",+ "heading1": "标题 1",+ "heading2": "标题 2",+ "bold": "粗体",+ "italic": "斜体",+ "strikethrough": "删除线",+ "link": "链接",+ "bulletedList": "项目符号列表",+ "numberedList": "编号列表",+ "quote": "引用",+ "boldSample": "粗体",+ "italicSample": "斜体",+ "strikeSample": "文本",+ "linkSample": "链接文本",+ "unknownVariables": "未知变量:{names}",+ "removeUnknownVariables": "请移除未知变量后再保存",+ "reset": "恢复默认",+ "test": "发送测试",+ "testing": "正在发送…",+ "testSent": "已发送至 {email}",+ "testNeedsProvider": "请先设置邮件服务商",+ "layoutHtml": "布局 HTML",+ "layoutCss": "布局 CSS",+ "placeholders": "占位符",+ "variables": "变量",+ "required": "必需",+ "requiredPlaceholders": "请将 {names} 添加到布局后再保存",+ "preview": "预览",+ "previewEmail": "邮件",+ "previewText": "纯文本",+ "previewFailed": "预览未能加载。请刷新页面后重试。",+ "from": "发件人",+ "to": "收件人",+ "groups": {+ "signIn": "登录",+ "invitations": "邀请",+ "notifications": "通知",+ "service": "其他"+ },+ "templates": {+ "reset": {+ "name": "重置密码"+ },+ "verify": {+ "name": "验证邮箱地址"+ },+ "magic": {+ "name": "登录链接"+ },+ "inviteProject": {+ "name": "项目邀请"+ },+ "inviteTeam": {+ "name": "团队邀请"+ },+ "assigned": {+ "name": "工作项已分配"+ },+ "mentioned": {+ "name": "在工作项中被提及"+ },+ "commented": {+ "name": "新评论"+ },+ "stateChanged": {+ "name": "状态已更改"+ },+ "documentMentioned": {+ "name": "在文档中被提及"+ },+ "documentCommentMentioned": {+ "name": "在文档评论中被提及"+ },+ "test": {+ "name": "测试邮件",+ "hint": "由邮件服务商页面的测试按钮发送。"+ }+ },+ "placeholderText": {+ "content": "邮件正文",+ "button": "带链接的按钮",+ "subject": "主题",+ "lang": "语言代码",+ "dir": "文字方向",+ "site_name": "实例名称",+ "site_url": "实例地址",+ "logo_url": "徽标地址"+ },+ "variableText": {+ "actor": "执行操作的人",+ "ref": "工作项编号",+ "title": "工作项标题",+ "from": "原状态",+ "to": "新状态",+ "document": "文档标题",+ "inviter": "发送邀请的人",+ "project": "项目名称",+ "team": "团队名称",+ "role": "加入后的角色"+ }+ },"authProvider": {"saved": "身份验证提供商已保存","google": "Google",diff --git a/apps/web/messages/zh-CN/sections.json b/apps/web/messages/zh-CN/sections.jsonindex f325eb3d..12f2f444 100644--- a/apps/web/messages/zh-CN/sections.json+++ b/apps/web/messages/zh-CN/sections.json@@ -45,6 +45,10 @@"label": "存储","description": "设置单个文件大小、允许的附件类型和每个项目的存储配额。"},+ "email-templates": {+ "label": "邮件模板",+ "description": "管理系统邮件模板。"+ },"telegram": {"label": "Telegram","description": "设置用户关联 Telegram 账户所用的机器人,以及项目未单独配置时发送通知的机器人。"diff --git a/apps/web/messages/zh-TW/god.json b/apps/web/messages/zh-TW/god.jsonindex 67dfaef5..fc7e7b04 100644--- a/apps/web/messages/zh-TW/god.json+++ b/apps/web/messages/zh-TW/god.json@@ -328,6 +328,117 @@"clientSecretPlaceholder": "應用程式註冊的金鑰","microsoft365Hint": "以 Entra ID 的應用程式註冊登入,而不是用信箱密碼,所以信箱可以維持開啟 MFA。該應用程式需要 Office 365 Exchange Online 的應用程式權限 SMTP.SendAsApp 並經管理員同意、在 Exchange 中有此信箱的存取權,並為該信箱開啟 SMTP AUTH。"},+ "emailTemplates": {+ "saved": "電子郵件範本已儲存",+ "unsaved": "有未儲存的變更",+ "blankText": "請填寫缺少的主旨或內文後再儲存",+ "emails": "電子郵件",+ "layout": "版面",+ "edited": "已修改",+ "subject": "主旨",+ "text": "內文",+ "button": "按鈕",+ "formatting": "格式",+ "heading1": "標題 1",+ "heading2": "標題 2",+ "bold": "粗體",+ "italic": "斜體",+ "strikethrough": "刪除線",+ "link": "連結",+ "bulletedList": "項目符號清單",+ "numberedList": "編號清單",+ "quote": "引用",+ "boldSample": "粗體",+ "italicSample": "斜體",+ "strikeSample": "文字",+ "linkSample": "連結文字",+ "unknownVariables": "未知變數:{names}",+ "removeUnknownVariables": "請移除未知變數後再儲存",+ "reset": "還原預設值",+ "test": "傳送測試",+ "testing": "正在傳送…",+ "testSent": "已傳送至 {email}",+ "testNeedsProvider": "請先設定電子郵件服務供應商",+ "layoutHtml": "版面 HTML",+ "layoutCss": "版面 CSS",+ "placeholders": "預留位置",+ "variables": "變數",+ "required": "必要",+ "requiredPlaceholders": "請將 {names} 加入版面後再儲存",+ "preview": "預覽",+ "previewEmail": "電子郵件",+ "previewText": "純文字",+ "previewFailed": "預覽未能載入。請重新整理頁面後再試一次。",+ "from": "寄件者",+ "to": "收件者",+ "groups": {+ "signIn": "登入",+ "invitations": "邀請",+ "notifications": "通知",+ "service": "其他"+ },+ "templates": {+ "reset": {+ "name": "重設密碼"+ },+ "verify": {+ "name": "驗證電子郵件地址"+ },+ "magic": {+ "name": "登入連結"+ },+ "inviteProject": {+ "name": "專案邀請"+ },+ "inviteTeam": {+ "name": "團隊邀請"+ },+ "assigned": {+ "name": "工作項目已指派"+ },+ "mentioned": {+ "name": "在工作項目中被提及"+ },+ "commented": {+ "name": "新留言"+ },+ "stateChanged": {+ "name": "狀態已更改"+ },+ "documentMentioned": {+ "name": "在文件中被提及"+ },+ "documentCommentMentioned": {+ "name": "在文件留言中被提及"+ },+ "test": {+ "name": "測試電子郵件",+ "hint": "由郵件服務供應商頁面的測試按鈕傳送。"+ }+ },+ "placeholderText": {+ "content": "電子郵件內文",+ "button": "含連結的按鈕",+ "subject": "主旨",+ "lang": "語言代碼",+ "dir": "文字方向",+ "site_name": "執行個體名稱",+ "site_url": "執行個體網址",+ "logo_url": "標誌網址"+ },+ "variableText": {+ "actor": "執行操作的人",+ "ref": "工作項目編號",+ "title": "工作項目標題",+ "from": "原狀態",+ "to": "新狀態",+ "document": "文件標題",+ "inviter": "傳送邀請的人",+ "project": "專案名稱",+ "team": "團隊名稱",+ "role": "加入後的角色"+ }+ },"authProvider": {"saved": "驗證提供者已儲存","google": "Google",diff --git a/apps/web/messages/zh-TW/sections.json b/apps/web/messages/zh-TW/sections.jsonindex 07120ef1..877c14e9 100644--- a/apps/web/messages/zh-TW/sections.json+++ b/apps/web/messages/zh-TW/sections.json@@ -45,6 +45,10 @@"label": "儲存","description": "設定單個檔案大小、允許的附件類型和每個專案的儲存配額。"},+ "email-templates": {+ "label": "電子郵件範本",+ "description": "管理系統電子郵件範本。"+ },"telegram": {"label": "Telegram","description": "設定使用者關聯 Telegram 帳號所用的機器人,以及專案未單獨設定時傳送通知的機器人。"diff --git a/apps/web/src/app/god/email-templates/page.tsx b/apps/web/src/app/god/email-templates/page.tsxnew file mode 100644index 00000000..ebce3b8e--- /dev/null+++ b/apps/web/src/app/god/email-templates/page.tsx@@ -0,0 +1,5 @@+import GodEmailTemplatesPage from '@/features/god/GodEmailTemplatesPage';++export default function Page() {+ return <GodEmailTemplatesPage />;+}diff --git a/apps/web/src/features/god/GodEmailTemplatesPage.tsx b/apps/web/src/features/god/GodEmailTemplatesPage.tsxnew file mode 100644index 00000000..2bc26dc2--- /dev/null+++ b/apps/web/src/features/god/GodEmailTemplatesPage.tsx@@ -0,0 +1,33 @@+'use client';++import { useState } from 'react';+import { useLocale } from 'next-intl';+import type { Locale } from '@/i18n/locales';+import GodSettingsGate from './components/GodSettingsGate';+import GodEmailTemplatesForm from './components/email-templates/GodEmailTemplatesForm';+import type { EmailSelection } from './hooks/useGodEmailTemplatesForm';+import { useEmailTemplatesQuery } from './services/god.service';++// The selection is held above the gate: a save remounts the form, and the email and the tab+// on the screen stay.+export default function GodEmailTemplatesPage() {+ const query = useEmailTemplatesQuery();+ const locale = useLocale() as Locale;+ const [selection, setSelection] = useState<EmailSelection>({+ key: 'reset',+ locale,+ tab: 'emails',+ });++ return (+ <GodSettingsGate slug="email-templates" data={query.data}>+ {(settings) => (+ <GodEmailTemplatesForm+ settings={settings}+ selection={selection}+ onSelect={(patch) => setSelection((current) => ({ ...current, ...patch }))}+ />+ )}+ </GodSettingsGate>+ );+}diff --git a/apps/web/src/features/god/components/email-templates/GodEmailDraftActions.tsx b/apps/web/src/features/god/components/email-templates/GodEmailDraftActions.tsxnew file mode 100644index 00000000..6f32c6be--- /dev/null+++ b/apps/web/src/features/god/components/email-templates/GodEmailDraftActions.tsx@@ -0,0 +1,57 @@+'use client';++import { toast } from 'sonner';+import { useTranslations } from 'next-intl';+import { RotateCcw, Send } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { useTestEmailDraft } from '../../services/god.service';+import type { EmailSelection, GodEmailTemplatesForm } from '../../hooks/useGodEmailTemplatesForm';++export default function GodEmailDraftActions({+ form,+ selection,+ canReset,+ onReset,+}: {+ form: GodEmailTemplatesForm;+ selection: EmailSelection;+ canReset: boolean;+ onReset: () => void;+}) {+ const t = useTranslations('god.emailTemplates');+ const test = useTestEmailDraft();+ const draft = form.draft(selection.key, selection.locale);++ async function send() {+ try {+ const { recipient } = await test.mutateAsync(draft);+ toast.success(t('testSent', { email: recipient }));+ } catch {+ // The global mutation handler shows the API error.+ }+ }++ return (+ <div className="flex flex-wrap items-center justify-between gap-2 border-t pt-4">+ <Button type="button" variant="ghost" size="sm" disabled={!canReset} onClick={onReset}>+ <RotateCcw className="size-4" />+ {t('reset')}+ </Button>+ <div className="flex flex-wrap items-center gap-3">+ {!form.settings.canSend && (+ <span className="text-xs text-muted-foreground">{t('testNeedsProvider')}</span>+ )}+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={!form.settings.canSend || !draft.text.subject.trim() || test.isPending}+ onClick={() => void send()}+ >+ <Send className="size-4" />+ {test.isPending ? t('testing') : t('test')}+ </Button>+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/god/components/email-templates/GodEmailEditedDot.tsx b/apps/web/src/features/god/components/email-templates/GodEmailEditedDot.tsxnew file mode 100644index 00000000..877b5dfb--- /dev/null+++ b/apps/web/src/features/god/components/email-templates/GodEmailEditedDot.tsx@@ -0,0 +1,13 @@+import { useTranslations } from 'next-intl';++export default function GodEmailEditedDot() {+ const t = useTranslations('god.emailTemplates');+ return (+ <span+ role="img"+ aria-label={t('edited')}+ title={t('edited')}+ className="inline-block size-[7px] shrink-0 rounded-full bg-foreground"+ />+ );+}diff --git a/apps/web/src/features/god/components/email-templates/GodEmailFrame.tsx b/apps/web/src/features/god/components/email-templates/GodEmailFrame.tsxnew file mode 100644index 00000000..b449b65a--- /dev/null+++ b/apps/web/src/features/god/components/email-templates/GodEmailFrame.tsx@@ -0,0 +1,28 @@+'use client';++import { useRef, useState } from 'react';+import { useTranslations } from 'next-intl';++// God writes the layout, and it reaches the page as a whole HTML document, so it stays in a+// frame of its own: its styles cannot touch the page. The sandbox has no scripts, and keeps+// the frame's origin only for reading the height of the email.+export default function GodEmailFrame({ html }: { html: string }) {+ const t = useTranslations('god.emailTemplates');+ const frame = useRef<HTMLIFrameElement>(null);+ const [height, setHeight] = useState(420);++ return (+ <iframe+ ref={frame}+ title={t('preview')}+ sandbox="allow-same-origin"+ srcDoc={html}+ style={{ height }}+ className="w-full border-0"+ onLoad={() => {+ const scrollHeight = frame.current?.contentDocument?.documentElement.scrollHeight;+ if (scrollHeight) setHeight(scrollHeight);+ }}+ />+ );+}diff --git a/apps/web/src/features/god/components/email-templates/GodEmailLayoutEditor.tsx b/apps/web/src/features/god/components/email-templates/GodEmailLayoutEditor.tsxnew file mode 100644index 00000000..2245d5f0--- /dev/null+++ b/apps/web/src/features/god/components/email-templates/GodEmailLayoutEditor.tsx@@ -0,0 +1,79 @@+'use client';++import { useRef, useState } from 'react';+import { useTranslations } from 'next-intl';+import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';+import { Textarea } from '@/components/ui/textarea';+import GodEmailDraftActions from './GodEmailDraftActions';+import GodEmailPlaceholders from './GodEmailPlaceholders';+import { replaceSelection, selectAfterEdit } from '../../utils/emailMarkdown';+import type { EmailSelection, GodEmailTemplatesForm } from '../../hooks/useGodEmailTemplatesForm';++export default function GodEmailLayoutEditor({+ form,+ selection,+}: {+ form: GodEmailTemplatesForm;+ selection: EmailSelection;+}) {+ const t = useTranslations('god.emailTemplates');+ const area = useRef<HTMLTextAreaElement>(null);+ const [file, setFile] = useState<'html' | 'css'>('html');+ const { layout, setLayout, missingPlaceholders, unknownPlaceholders } = form;++ function insert(name: string) {+ const element = area.current;+ if (!element) return;+ const { selectionStart, selectionEnd } = element;+ const next = replaceSelection(layout.html, selectionStart, selectionEnd, `{${name}}`);+ setLayout({ ...layout, html: next.value });+ selectAfterEdit(element, next);+ }++ return (+ <section className="flex min-w-0 flex-col gap-4">+ <div className="rounded-lg border border-input">+ <div className="border-b p-1">+ <Tabs value={file} onValueChange={(value) => setFile(value as 'html' | 'css')}>+ <TabsList className="h-8">+ <TabsTrigger value="html">HTML</TabsTrigger>+ <TabsTrigger value="css">CSS</TabsTrigger>+ </TabsList>+ </Tabs>+ </div>+ <Textarea+ key={file}+ ref={area}+ dir="ltr"+ wrap="off"+ aria-label={file === 'html' ? t('layoutHtml') : t('layoutCss')}+ value={layout[file]}+ onChange={(e) => setLayout({ ...layout, [file]: e.target.value })}+ className="min-h-[440px] rounded-none border-0 bg-transparent font-mono text-xs leading-relaxed shadow-none focus-visible:ring-0"+ />+ </div>+ {missingPlaceholders.length > 0 && (+ <p className="text-xs text-warning">+ {t('requiredPlaceholders', {+ names: missingPlaceholders.map((name) => `{${name}}`).join(', '),+ })}+ </p>+ )}+ {unknownPlaceholders.length > 0 && (+ <p className="text-xs text-warning">+ {t('unknownVariables', {+ count: unknownPlaceholders.length,+ names: unknownPlaceholders.map((name) => `{${name}}`).join(', '),+ })}+ </p>+ )}+ {file === 'html' && <GodEmailPlaceholders form={form} onInsert={insert} />}+ <GodEmailDraftActions+ form={form}+ selection={selection}+ canReset={form.layoutEdited}+ onReset={form.resetLayout}+ />+ </section>+ );+}diff --git a/apps/web/src/features/god/components/email-templates/GodEmailLocalePicker.tsx b/apps/web/src/features/god/components/email-templates/GodEmailLocalePicker.tsxnew file mode 100644index 00000000..306d0b6a--- /dev/null+++ b/apps/web/src/features/god/components/email-templates/GodEmailLocalePicker.tsx@@ -0,0 +1,51 @@+'use client';++import { useTranslations } from 'next-intl';+import { LOCALES, LOCALE_LABELS } from '@/i18n/locales';+import { Button } from '@/components/ui/button';+import { cn } from '@/lib/utils';+import GodEmailEditedDot from './GodEmailEditedDot';+import type { EmailSelection, GodEmailTemplatesForm } from '../../hooks/useGodEmailTemplatesForm';++export default function GodEmailLocalePicker({+ form,+ selection,+ onSelect,+}: {+ form: GodEmailTemplatesForm;+ selection: EmailSelection;+ onSelect: (patch: Partial<EmailSelection>) => void;+}) {+ const t = useTranslations('god.emailTemplates');+ const tCommon = useTranslations('common');++ return (+ <div className="flex flex-col gap-2.5">+ <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-2">+ <span className="text-[13px] font-medium">{tCommon('language')}</span>+ <span className="inline-flex items-center gap-1.5 text-xs text-muted-foreground">+ <span className="size-[7px] rounded-full bg-foreground" />+ {t('edited')}+ </span>+ </div>+ <div role="group" aria-label={tCommon('language')} className="flex flex-wrap gap-1.5">+ {LOCALES.map((locale) => (+ <Button+ key={locale}+ variant="outline"+ size="sm"+ aria-pressed={locale === selection.locale}+ className={cn(+ 'h-7 text-xs',+ locale === selection.locale && 'border-foreground bg-secondary',+ )}+ onClick={() => onSelect({ locale })}+ >+ {form.isEdited(selection.key, locale) && <GodEmailEditedDot />}+ {LOCALE_LABELS[locale]}+ </Button>+ ))}+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/god/components/email-templates/GodEmailMarkdownToolbar.tsx b/apps/web/src/features/god/components/email-templates/GodEmailMarkdownToolbar.tsxnew file mode 100644index 00000000..2eeeaff4--- /dev/null+++ b/apps/web/src/features/god/components/email-templates/GodEmailMarkdownToolbar.tsx@@ -0,0 +1,92 @@+'use client';++import type { RefObject } from 'react';+import { useTranslations } from 'next-intl';+import {+ Bold,+ Heading1,+ Heading2,+ Italic,+ Link,+ List,+ ListOrdered,+ Strikethrough,+ TextQuote,+ type LucideIcon,+} from 'lucide-react';+import { Button } from '@/components/ui/button';+import {+ prefixLine,+ selectAfterEdit,+ wrapSelection,+ type TextEdit,+} from '../../utils/emailMarkdown';++export default function GodEmailMarkdownToolbar({+ area,+ value,+ onChange,+}: {+ area: RefObject<HTMLTextAreaElement | null>;+ value: string;+ onChange: (value: string) => void;+}) {+ const t = useTranslations('god.emailTemplates');++ function apply(edit: (start: number, end: number) => TextEdit) {+ const element = area.current;+ if (!element) return;+ const next = edit(element.selectionStart, element.selectionEnd);+ onChange(next.value);+ selectAfterEdit(element, next);+ }++ const wrap = (before: string, after: string, sample: string) => () =>+ apply((start, end) => wrapSelection(value, start, end, before, after, sample));+ const prefix = (marker: string) => () => apply((start) => prefixLine(value, start, marker));++ const groups: { label: string; icon: LucideIcon; run: () => void }[][] = [+ [+ { label: t('heading1'), icon: Heading1, run: prefix('# ') },+ { label: t('heading2'), icon: Heading2, run: prefix('## ') },+ ],+ [+ { label: t('bold'), icon: Bold, run: wrap('**', '**', t('boldSample')) },+ { label: t('italic'), icon: Italic, run: wrap('*', '*', t('italicSample')) },+ { label: t('strikethrough'), icon: Strikethrough, run: wrap('~~', '~~', t('strikeSample')) },+ { label: t('link'), icon: Link, run: wrap('[', '](https://)', t('linkSample')) },+ ],+ [+ { label: t('bulletedList'), icon: List, run: prefix('- ') },+ { label: t('numberedList'), icon: ListOrdered, run: prefix('1. ') },+ { label: t('quote'), icon: TextQuote, run: prefix('> ') },+ ],+ ];++ return (+ <div+ role="toolbar"+ aria-label={t('formatting')}+ className="flex flex-wrap items-center gap-0.5 border-b p-1"+ >+ {groups.map((group, index) => (+ <div key={index} className="flex items-center gap-0.5 not-first:ms-1.5">+ {group.map(({ label, icon: Icon, run }) => (+ <Button+ key={label}+ type="button"+ variant="ghost"+ size="icon"+ className="size-7 text-muted-foreground"+ aria-label={label}+ title={label}+ onClick={run}+ >+ <Icon className="size-4" />+ </Button>+ ))}+ </div>+ ))}+ </div>+ );+}diff --git a/apps/web/src/features/god/components/email-templates/GodEmailPlaceholderList.tsx b/apps/web/src/features/god/components/email-templates/GodEmailPlaceholderList.tsxnew file mode 100644index 00000000..3e0916a5--- /dev/null+++ b/apps/web/src/features/god/components/email-templates/GodEmailPlaceholderList.tsx@@ -0,0 +1,49 @@+'use client';++import { useTranslations } from 'next-intl';+import { Check } from 'lucide-react';+import { Button } from '@/components/ui/button';++interface EmailPlaceholderItem {+ name: string;+ description: string | null;+ used: boolean;+ missing?: boolean;+}++export default function GodEmailPlaceholderList({+ title,+ items,+ onInsert,+}: {+ title: string;+ items: EmailPlaceholderItem[];+ onInsert: (name: string) => void;+}) {+ const t = useTranslations('god.emailTemplates');++ return (+ <div className="flex flex-col gap-1.5">+ <span className="text-[13px] font-medium">{title}</span>+ <div className="grid grid-cols-[repeat(auto-fill,minmax(220px,1fr))] gap-x-2 gap-y-0.5">+ {items.map(({ name, description, used, missing }) => (+ <Button+ key={name}+ type="button"+ variant="ghost"+ size="sm"+ className="min-w-0 justify-start gap-2 font-normal"+ onClick={() => onInsert(name)}+ >+ <code dir="ltr" className="font-mono text-xs">{`{${name}}`}</code>+ <span className="min-w-0 flex-1 truncate text-start text-muted-foreground">+ {description}+ </span>+ {missing && <span className="text-xs text-warning">{t('required')}</span>}+ {used && <Check className="size-3.5 text-muted-foreground" />}+ </Button>+ ))}+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/god/components/email-templates/GodEmailPlaceholders.tsx b/apps/web/src/features/god/components/email-templates/GodEmailPlaceholders.tsxnew file mode 100644index 00000000..d154bb52--- /dev/null+++ b/apps/web/src/features/god/components/email-templates/GodEmailPlaceholders.tsx@@ -0,0 +1,30 @@+'use client';++import { useTranslations } from 'next-intl';+import { byKey } from '@/utils/messageKey';+import GodEmailPlaceholderList from './GodEmailPlaceholderList';+import type { GodEmailTemplatesForm } from '../../hooks/useGodEmailTemplatesForm';++export default function GodEmailPlaceholders({+ form,+ onInsert,+}: {+ form: GodEmailTemplatesForm;+ onInsert: (name: string) => void;+}) {+ const t = useTranslations('god.emailTemplates');+ const describe = byKey(t);++ return (+ <GodEmailPlaceholderList+ title={t('placeholders')}+ items={form.settings.placeholders.map(({ name }) => ({+ name,+ description: describe(`placeholderText.${name}`),+ used: form.layout.html.includes(`{${name}}`),+ missing: form.missingPlaceholders.includes(name),+ }))}+ onInsert={onInsert}+ />+ );+}diff --git a/apps/web/src/features/god/components/email-templates/GodEmailPreview.tsx b/apps/web/src/features/god/components/email-templates/GodEmailPreview.tsxnew file mode 100644index 00000000..697764bf--- /dev/null+++ b/apps/web/src/features/god/components/email-templates/GodEmailPreview.tsx@@ -0,0 +1,76 @@+'use client';++import { useMemo, useState } from 'react';+import { useTranslations } from 'next-intl';+import { localeDirection, LOCALE_LABELS } from '@/i18n/locales';+import { useDebouncedValue } from '@/hooks/useDebouncedValue';+import { Skeleton } from '@/components/ui/skeleton';+import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';+import GodEmailFrame from './GodEmailFrame';+import GodEmailPreviewMeta from './GodEmailPreviewMeta';+import { useGodEmailTemplateText } from '../../hooks/useGodEmailTemplateText';+import { useEmailPreviewQuery } from '../../services/god.service';+import type { EmailSelection, GodEmailTemplatesForm } from '../../hooks/useGodEmailTemplatesForm';++export default function GodEmailPreview({+ form,+ selection,+}: {+ form: GodEmailTemplatesForm;+ selection: EmailSelection;+}) {+ const t = useTranslations('god.emailTemplates');+ const text = useGodEmailTemplateText();+ const [view, setView] = useState<'email' | 'text'>('email');+ const { key, locale, tab } = selection;+ const emailText = form.text(key, locale);+ const { layout } = form;+ const draft = useMemo(+ () => ({ key, locale, text: emailText, layout }),+ [key, locale, emailText, layout],+ );+ const preview = useEmailPreviewQuery(useDebouncedValue(draft, 400));+ const email = preview.data;+ const dir = localeDirection(locale);++ return (+ <aside+ aria-label={t('preview')}+ className="flex min-w-0 flex-col gap-3 rounded-xl bg-muted p-4"+ >+ <div className="flex flex-wrap items-center justify-between gap-3">+ <span className="text-[13px] font-medium">{t('preview')}</span>+ <Tabs value={view} onValueChange={(value) => setView(value as 'email' | 'text')}>+ <TabsList className="h-8">+ <TabsTrigger value="email">{t('previewEmail')}</TabsTrigger>+ <TabsTrigger value="text">{t('previewText')}</TabsTrigger>+ </TabsList>+ </Tabs>+ </div>+ <div className="overflow-hidden rounded-lg bg-white text-[#1c1c1c] shadow-md">+ {preview.isError && <p className="p-5 text-sm text-destructive">{t('previewFailed')}</p>}+ {!preview.isError && !email && <Skeleton className="m-5 h-40" />}+ {!preview.isError && email && (+ <>+ <GodEmailPreviewMeta email={email} dir={dir} />+ {view === 'email' ? (+ <GodEmailFrame html={email.html} />+ ) : (+ <pre+ dir={dir}+ className="p-5 font-mono text-xs leading-relaxed break-words whitespace-pre-wrap"+ >+ {email.text}+ </pre>+ )}+ </>+ )}+ </div>+ {tab === 'layout' && (+ <p className="text-xs text-muted-foreground">+ {text.name(key)} · {LOCALE_LABELS[locale]}+ </p>+ )}+ </aside>+ );+}diff --git a/apps/web/src/features/god/components/email-templates/GodEmailPreviewMeta.tsx b/apps/web/src/features/god/components/email-templates/GodEmailPreviewMeta.tsxnew file mode 100644index 00000000..d3708bf2--- /dev/null+++ b/apps/web/src/features/god/components/email-templates/GodEmailPreviewMeta.tsx@@ -0,0 +1,38 @@+'use client';++import { useTranslations } from 'next-intl';+import { cn } from '@/lib/utils';+import type { EmailPreview } from '@/lib/api/endpoints/god';++const SAMPLE_RECIPIENT = '[email protected]';++export default function GodEmailPreviewMeta({+ email,+ dir,+}: {+ email: EmailPreview;+ dir: 'ltr' | 'rtl';+}) {+ const t = useTranslations('god.emailTemplates');+ const rows = [+ { label: t('from'), value: email.from, valueDir: 'ltr' },+ { label: t('to'), value: SAMPLE_RECIPIENT, valueDir: 'ltr' },+ { label: t('subject'), value: email.subject, strong: true },+ ];++ return (+ <dl dir={dir} className="flex flex-col gap-0.5 border-b border-[#ececec] px-4 py-3 text-xs">+ {rows.map(+ ({ label, value, valueDir, strong }) =>+ value && (+ <div key={label} className="flex gap-2">+ <dt className="w-16 shrink-0 text-[#6b6b6b]">{label}</dt>+ <dd dir={valueDir} className={cn('min-w-0', strong && 'font-semibold')}>+ {value}+ </dd>+ </div>+ ),+ )}+ </dl>+ );+}diff --git a/apps/web/src/features/god/components/email-templates/GodEmailTemplatePicker.tsx b/apps/web/src/features/god/components/email-templates/GodEmailTemplatePicker.tsxnew file mode 100644index 00000000..0240fe3d--- /dev/null+++ b/apps/web/src/features/god/components/email-templates/GodEmailTemplatePicker.tsx@@ -0,0 +1,65 @@+'use client';++import { ChevronDown } from 'lucide-react';+import { LOCALES } from '@/i18n/locales';+import { Button } from '@/components/ui/button';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';+import GodEmailEditedDot from './GodEmailEditedDot';+import { useGodEmailTemplateText } from '../../hooks/useGodEmailTemplateText';+import type { EmailSelection, GodEmailTemplatesForm } from '../../hooks/useGodEmailTemplatesForm';++export default function GodEmailTemplatePicker({+ form,+ selection,+ onSelect,+}: {+ form: GodEmailTemplatesForm;+ selection: EmailSelection;+ onSelect: (patch: Partial<EmailSelection>) => void;+}) {+ const text = useGodEmailTemplateText();+ const { templates } = form.settings;+ const groups = [...new Set(templates.map((entry) => entry.group))];+ const current = form.template(selection.key);+ const hint = text.hint(current.key);++ return (+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2">+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="outline" className="max-w-full min-w-80 justify-start gap-2">+ <span className="font-normal text-muted-foreground">{text.group(current.group)}</span>+ <span className="font-normal text-muted-foreground">/</span>+ <span className="truncate">{text.name(current.key)}</span>+ <ChevronDown className="ms-auto size-4 text-muted-foreground" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="max-h-[460px] w-90">+ {groups.map((group) => (+ <DropdownMenuGroup key={group}>+ <DropdownMenuLabel>{text.group(group)}</DropdownMenuLabel>+ {templates+ .filter((entry) => entry.group === group)+ .map((entry) => (+ <DropdownMenuItem key={entry.key} onSelect={() => onSelect({ key: entry.key })}>+ <span className="min-w-0 flex-1">{text.name(entry.key)}</span>+ {LOCALES.some((locale) => form.isEdited(entry.key, locale)) && (+ <GodEmailEditedDot />+ )}+ </DropdownMenuItem>+ ))}+ </DropdownMenuGroup>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ {hint && <span className="text-[13px] text-muted-foreground">{hint}</span>}+ </div>+ );+}diff --git a/apps/web/src/features/god/components/email-templates/GodEmailTemplatesForm.tsx b/apps/web/src/features/god/components/email-templates/GodEmailTemplatesForm.tsxnew file mode 100644index 00000000..9ad3e010--- /dev/null+++ b/apps/web/src/features/god/components/email-templates/GodEmailTemplatesForm.tsx@@ -0,0 +1,89 @@+'use client';++import { toast } from 'sonner';+import { useTranslations } from 'next-intl';+import { Button } from '@/components/ui/button';+import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';+import type { EmailTemplatesSettings } from '@/lib/api/endpoints/god';+import GodSectionPage from '../GodSectionPage';+import GodEmailLayoutEditor from './GodEmailLayoutEditor';+import GodEmailPreview from './GodEmailPreview';+import GodEmailTemplatePicker from './GodEmailTemplatePicker';+import GodEmailTextEditor from './GodEmailTextEditor';+import {+ useGodEmailTemplatesForm,+ type EmailSelection,+} from '../../hooks/useGodEmailTemplatesForm';++export default function GodEmailTemplatesForm({+ settings,+ selection,+ onSelect,+}: {+ settings: EmailTemplatesSettings;+ selection: EmailSelection;+ onSelect: (patch: Partial<EmailSelection>) => void;+}) {+ const t = useTranslations('god.emailTemplates');+ const tCommon = useTranslations('common');+ const form = useGodEmailTemplatesForm(settings);+ const blocked =+ form.hasBlankText || form.hasUnknownVariables || form.missingPlaceholders.length > 0;++ let status = t('unsaved');+ if (form.hasUnknownVariables) status = t('removeUnknownVariables');+ if (form.hasBlankText) status = t('blankText');++ async function save() {+ try {+ await form.save();+ toast.success(t('saved'));+ } catch {+ // The failure already surfaced through the global mutation error toast.+ }+ }++ return (+ <GodSectionPage+ slug="email-templates"+ widthClassName="max-w-none"+ actions={+ <div className="flex items-center gap-3">+ {form.dirty && <span className="text-xs text-muted-foreground">{status}</span>}+ <Button+ size="sm"+ onClick={() => void save()}+ disabled={!form.dirty || blocked || form.saving}+ >+ {form.saving ? tCommon('saving') : tCommon('save')}+ </Button>+ </div>+ }+ >+ <div className="flex flex-col gap-6">+ <Tabs+ value={selection.tab}+ onValueChange={(tab) => onSelect({ tab: tab as EmailSelection['tab'] })}+ >+ <TabsList>+ <TabsTrigger value="emails">{t('emails')}</TabsTrigger>+ <TabsTrigger value="layout">{t('layout')}</TabsTrigger>+ </TabsList>+ </Tabs>++ {selection.tab === 'emails' && (+ <GodEmailTemplatePicker form={form} selection={selection} onSelect={onSelect} />+ )}++ <div className="grid items-start gap-6 xl:grid-cols-[minmax(0,5fr)_minmax(0,3fr)]">+ {selection.tab === 'emails' ? (+ <GodEmailTextEditor form={form} selection={selection} onSelect={onSelect} />+ ) : (+ <GodEmailLayoutEditor form={form} selection={selection} />+ )}+ <GodEmailPreview form={form} selection={selection} />+ </div>+ </div>+ </GodSectionPage>+ );+}diff --git a/apps/web/src/features/god/components/email-templates/GodEmailTextEditor.tsx b/apps/web/src/features/god/components/email-templates/GodEmailTextEditor.tsxnew file mode 100644index 00000000..4783cea1--- /dev/null+++ b/apps/web/src/features/god/components/email-templates/GodEmailTextEditor.tsx@@ -0,0 +1,112 @@+'use client';++import { useTranslations } from 'next-intl';+import { localeDirection } from '@/i18n/locales';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import { Textarea } from '@/components/ui/textarea';+import type { EmailText } from '@/lib/api/endpoints/god';+import GodEmailDraftActions from './GodEmailDraftActions';+import GodEmailLocalePicker from './GodEmailLocalePicker';+import GodEmailMarkdownToolbar from './GodEmailMarkdownToolbar';+import GodEmailVariables from './GodEmailVariables';+import { useEmailVariableInsert } from '../../hooks/useEmailVariableInsert';+import { unknownVariables, writtenText } from '../../utils/emailMarkdown';+import type { EmailSelection, GodEmailTemplatesForm } from '../../hooks/useGodEmailTemplatesForm';++export default function GodEmailTextEditor({+ form,+ selection,+ onSelect,+}: {+ form: GodEmailTemplatesForm;+ selection: EmailSelection;+ onSelect: (patch: Partial<EmailSelection>) => void;+}) {+ const t = useTranslations('god.emailTemplates');+ const { key, locale } = selection;+ const template = form.template(key);+ const text = form.text(key, locale);+ const dir = localeDirection(locale);+ const written = writtenText(text);+ const unknown = unknownVariables(written, template.variables);++ function change(patch: Partial<EmailText>) {+ form.setText(key, locale, { ...text, ...patch });+ }++ const fields = useEmailVariableInsert(text, change);++ return (+ <section className="flex min-w-0 flex-col gap-5">+ <GodEmailLocalePicker form={form} selection={selection} onSelect={onSelect} />++ <div className="flex flex-col gap-4">+ <div className="flex flex-col gap-1.5">+ <Label htmlFor="email-subject">{t('subject')}</Label>+ <Input+ id="email-subject"+ ref={fields.subject}+ dir={dir}+ onFocus={() => fields.track('subject')}+ value={text.subject}+ onChange={(e) => change({ subject: e.target.value })}+ />+ </div>+ <div className="flex flex-col gap-1.5">+ <Label htmlFor="email-body">{t('text')}</Label>+ <div className="rounded-lg border border-input focus-within:ring-2 focus-within:ring-ring">+ <GodEmailMarkdownToolbar+ area={fields.body}+ value={text.body}+ onChange={(body) => change({ body })}+ />+ <Textarea+ ref={fields.body}+ id="email-body"+ dir={dir}+ onFocus={() => fields.track('body')}+ value={text.body}+ onChange={(e) => change({ body: e.target.value })}+ className="min-h-56 rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0"+ />+ </div>+ </div>+ {template.hasLink && (+ <div className="flex flex-col gap-1.5">+ <Label htmlFor="email-button">{t('button')}</Label>+ <Input+ id="email-button"+ ref={fields.button}+ dir={dir}+ onFocus={() => fields.track('button')}+ value={text.button}+ onChange={(e) => change({ button: e.target.value })}+ />+ </div>+ )}+ {unknown.length > 0 && (+ <p className="text-xs text-warning">+ {t('unknownVariables', {+ count: unknown.length,+ names: unknown.map((name) => `{${name}}`).join(', '),+ })}+ </p>+ )}+ </div>++ <GodEmailVariables+ variables={template.variables}+ written={written}+ onInsert={fields.insert}+ />++ <GodEmailDraftActions+ form={form}+ selection={selection}+ canReset={form.isEdited(key, locale)}+ onReset={() => form.resetText(key, locale)}+ />+ </section>+ );+}diff --git a/apps/web/src/features/god/components/email-templates/GodEmailVariables.tsx b/apps/web/src/features/god/components/email-templates/GodEmailVariables.tsxnew file mode 100644index 00000000..4396b250--- /dev/null+++ b/apps/web/src/features/god/components/email-templates/GodEmailVariables.tsx@@ -0,0 +1,35 @@+'use client';++import { useTranslations } from 'next-intl';+import { byKey } from '@/utils/messageKey';+import GodEmailPlaceholderList from './GodEmailPlaceholderList';++export default function GodEmailVariables({+ variables,+ written,+ onInsert,+}: {+ variables: string[];+ written: string;+ onInsert: (name: string) => void;+}) {+ const t = useTranslations('god.emailTemplates');+ const describe = byKey(t);+ if (variables.length === 0) return null;++ return (+ <GodEmailPlaceholderList+ title={t('variables')}+ items={variables.map((name) => {+ const path = `variableText.${name}`;+ return {+ name,+ // An edition's email may bring a variable with no description.+ description: t.has(path as never) ? describe(path) : null,+ used: written.includes(`{${name}}`),+ };+ })}+ onInsert={onInsert}+ />+ );+}diff --git a/apps/web/src/features/god/hooks/useEmailVariableInsert.test.tsx b/apps/web/src/features/god/hooks/useEmailVariableInsert.test.tsxnew file mode 100644index 00000000..93202ca4--- /dev/null+++ b/apps/web/src/features/god/hooks/useEmailVariableInsert.test.tsx@@ -0,0 +1,95 @@+import assert from 'node:assert/strict';+import { afterEach, beforeEach, describe, it } from 'node:test';+import { act, useState } from 'react';+import type { Root } from 'react-dom/client';+import { JSDOM } from 'jsdom';+import type { EmailText } from '@/lib/api/endpoints/god';++let dom: JSDOM;+let root: Root;+let text: EmailText;+let fields: ReturnType<typeof import('./useEmailVariableInsert').useEmailVariableInsert>;+const replaced = [+ 'window',+ 'document',+ 'requestAnimationFrame',+ 'IS_REACT_ACT_ENVIRONMENT',+] as const;+let originals: Map<string, PropertyDescriptor | undefined>;++async function mount(withButton: boolean) {+ const { useEmailVariableInsert } = await import('./useEmailVariableInsert');+ function Probe() {+ const [current, setCurrent] = useState<EmailText>({+ subject: 'Hello',+ body: 'Body',+ button: 'Open',+ });+ text = current;+ fields = useEmailVariableInsert(current, (patch) => setCurrent({ ...current, ...patch }));+ return (+ <>+ <input ref={fields.subject} defaultValue="Hello" />+ <textarea ref={fields.body} defaultValue="Body" />+ {withButton && <input ref={fields.button} defaultValue="Open" />}+ </>+ );+ }+ await act(async () => root.render(<Probe />));+}++beforeEach(async () => {+ originals = new Map(replaced.map((n) => [n, Object.getOwnPropertyDescriptor(globalThis, n)]));+ dom = new JSDOM('<!doctype html><div id="root"></div>');+ Object.defineProperties(globalThis, {+ window: { configurable: true, value: dom.window },+ document: { configurable: true, value: dom.window.document },+ requestAnimationFrame: { configurable: true, value: () => 0 },+ IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true },+ });+ const { createRoot } = await import('react-dom/client');+ root = createRoot(dom.window.document.querySelector('#root')!);+});++afterEach(async () => {+ await act(async () => root.unmount());+ dom.window.close();+ for (const [name, descriptor] of originals) {+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);+ else Reflect.deleteProperty(globalThis, name);+ }+});++describe('useEmailVariableInsert', () => {+ it('puts a variable in the text by default', async () => {+ await mount(true);+ fields.body.current!.setSelectionRange(4, 4);++ await act(async () => fields.insert('ref'));++ assert.equal(text.body, 'Body{ref}');+ assert.equal(text.subject, 'Hello');+ });++ it('puts a variable at the cursor of the field last in focus', async () => {+ await mount(true);+ fields.subject.current!.setSelectionRange(0, 5);+ fields.track('subject');++ await act(async () => fields.insert('ref'));++ assert.equal(text.subject, '{ref}');+ assert.equal(text.body, 'Body');+ });++ it('puts a variable in the text when the focused field is gone', async () => {+ await mount(false);+ fields.body.current!.setSelectionRange(0, 0);+ fields.track('button');++ await act(async () => fields.insert('ref'));++ assert.equal(text.body, '{ref}Body');+ assert.equal(text.button, 'Open');+ });+});diff --git a/apps/web/src/features/god/hooks/useEmailVariableInsert.ts b/apps/web/src/features/god/hooks/useEmailVariableInsert.tsnew file mode 100644index 00000000..961b4829--- /dev/null+++ b/apps/web/src/features/god/hooks/useEmailVariableInsert.ts@@ -0,0 +1,39 @@+'use client';++import { useRef } from 'react';+import type { EmailText } from '@/lib/api/endpoints/god';+import { replaceSelection, selectAfterEdit } from '../utils/emailMarkdown';++// Puts a variable at the cursor of the field last in focus: a subject and a button take+// variables as the text does. The text takes it when that field is not on the screen.+export function useEmailVariableInsert(+ text: EmailText,+ change: (patch: Partial<EmailText>) => void,+) {+ const subject = useRef<HTMLInputElement>(null);+ const body = useRef<HTMLTextAreaElement>(null);+ const button = useRef<HTMLInputElement>(null);+ const focused = useRef<keyof EmailText>('body');+ const elements = { subject, body, button };++ function insert(name: string) {+ const field = elements[focused.current].current ? focused.current : 'body';+ const element = elements[field].current;+ if (!element) return;+ const start = element.selectionStart ?? text[field].length;+ const end = element.selectionEnd ?? start;+ const next = replaceSelection(text[field], start, end, `{${name}}`);+ change({ [field]: next.value });+ selectAfterEdit(element, next);+ }++ return {+ subject,+ body,+ button,+ track: (field: keyof EmailText) => {+ focused.current = field;+ },+ insert,+ };+}diff --git a/apps/web/src/features/god/hooks/useGodEmailTemplateText.ts b/apps/web/src/features/god/hooks/useGodEmailTemplateText.tsnew file mode 100644index 00000000..d5bdf727--- /dev/null+++ b/apps/web/src/features/god/hooks/useGodEmailTemplateText.ts@@ -0,0 +1,19 @@+'use client';++import { useTranslations } from 'next-intl';+import { byKey } from '@/utils/messageKey';++// The names in the email list. A template is known by a key from the api, and an edition+// adds its own with its messages, so the message key is built at runtime.+export function useGodEmailTemplateText() {+ const t = useTranslations('god.emailTemplates');+ const read = byKey(t);+ return {+ name: (key: string) => read(`templates.${key}.name`),+ hint: (key: string) => {+ const path = `templates.${key}.hint`;+ return t.has(path as never) ? read(path) : null;+ },+ group: (group: string) => read(`groups.${group}`),+ };+}diff --git a/apps/web/src/features/god/hooks/useGodEmailTemplatesForm.test.tsx b/apps/web/src/features/god/hooks/useGodEmailTemplatesForm.test.tsxnew file mode 100644index 00000000..7c3f58b7--- /dev/null+++ b/apps/web/src/features/god/hooks/useGodEmailTemplatesForm.test.tsx@@ -0,0 +1,178 @@+import assert from 'node:assert/strict';+import { afterEach, beforeEach, describe, it } from 'node:test';+import { act } from 'react';+import type { Root } from 'react-dom/client';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { JSDOM } from 'jsdom';+import type { EmailTemplatesBody, EmailTemplatesSettings } from '@/lib/api/endpoints/god';+import type { GodEmailTemplatesForm } from './useGodEmailTemplatesForm';++let saved: EmailTemplatesBody[] = [];++const builtIn = { subject: 'Reset', body: 'Use the link', button: 'Set' };+const defaultLayout = { html: '<div>{content}{button}</div>', css: '' };++const settings: EmailTemplatesSettings = {+ templates: [+ {+ key: 'reset',+ group: 'signIn',+ variables: [],+ hasLink: true,+ defaults: { en: builtIn, ru: { ...builtIn, subject: 'Сброс' } },+ edits: { ru: { ...builtIn, subject: 'Сохранено' } },+ },+ ],+ layout: defaultLayout,+ defaultLayout,+ placeholders: [+ { name: 'content', required: true },+ { name: 'button', required: true },+ { name: 'lang', required: false },+ ],+ canSend: true,+};++let dom: JSDOM;+let root: Root;+let form: GodEmailTemplatesForm;+let client: QueryClient;+const replaced = ['window', 'document', 'fetch', 'IS_REACT_ACT_ENVIRONMENT'] as const;+let originals: Map<string, PropertyDescriptor | undefined>;++beforeEach(async () => {+ originals = new Map(replaced.map((n) => [n, Object.getOwnPropertyDescriptor(globalThis, n)]));+ dom = new JSDOM('<!doctype html><div id="root"></div>');+ Object.defineProperties(globalThis, {+ window: { configurable: true, value: dom.window },+ document: { configurable: true, value: dom.window.document },+ fetch: {+ configurable: true,+ value: async (_input: RequestInfo | URL, init?: RequestInit) => {+ if (init?.method === 'PUT') saved.push(JSON.parse(String(init.body)));+ return Response.json(settings);+ },+ },+ IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true },+ });+ Object.defineProperty(window, '__ITSAPLAN_ENV__', {+ value: { apiUrl: 'https://api.test', privacyUrl: '', termsUrl: '' },+ });+ saved = [];+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const { createRoot } = await import('react-dom/client');+ root = createRoot(dom.window.document.querySelector('#root')!);+ const { useGodEmailTemplatesForm } = await import('./useGodEmailTemplatesForm');+ function Probe() {+ form = useGodEmailTemplatesForm(settings);+ return null;+ }+ await act(async () =>+ root.render(+ <QueryClientProvider client={client}>+ <Probe />+ </QueryClientProvider>,+ ),+ );+});++afterEach(async () => {+ await act(async () => root.unmount());+ client.clear();+ dom.window.close();+ for (const [name, descriptor] of originals) {+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);+ else Reflect.deleteProperty(globalThis, name);+ }+});++const step = (fn: () => void) => act(async () => fn());++describe('useGodEmailTemplatesForm', () => {+ it('starts from what god saved, over the built-in text', () => {+ assert.equal(form.text('reset', 'ru').subject, 'Сохранено');+ assert.equal(form.text('reset', 'en').subject, 'Reset');+ assert.equal(form.isEdited('reset', 'ru'), true);+ assert.equal(form.isEdited('reset', 'en'), false);+ assert.equal(form.dirty, false);+ });++ it('counts a change as an edit until it matches the built-in text again', async () => {+ await step(() => form.setText('reset', 'en', { ...builtIn, subject: 'Changed' }));+ assert.equal(form.isEdited('reset', 'en'), true);+ assert.equal(form.dirty, true);++ await step(() => form.setText('reset', 'en', builtIn));+ assert.equal(form.isEdited('reset', 'en'), false);+ assert.equal(form.dirty, false);+ });++ it('resets one language and leaves the others', async () => {+ await step(() => form.setText('reset', 'en', { ...builtIn, subject: 'Changed' }));+ await step(() => form.resetText('reset', 'ru'));++ assert.equal(form.text('reset', 'ru').subject, 'Сброс');+ assert.equal(form.text('reset', 'en').subject, 'Changed');+ });++ it('finds a text with no subject or no body', async () => {+ assert.equal(form.hasBlankText, false);+ await step(() => form.setText('reset', 'en', { ...builtIn, body: ' ' }));+ assert.equal(form.hasBlankText, true);+ });++ it('finds a variable the email does not have', async () => {+ assert.equal(form.hasUnknownVariables, false);+ await step(() => form.setText('reset', 'en', { ...builtIn, body: '{typo}' }));+ assert.equal(form.hasUnknownVariables, true);+ });++ it('names the required placeholders the layout lost', async () => {+ await step(() => form.setLayout({ html: '<div>{content}</div>', css: '' }));+ assert.deepEqual(form.missingPlaceholders, ['button']);+ });++ it('finds a placeholder nothing fills in the layout', async () => {+ assert.equal(form.hasUnknownVariables, false);+ await step(() => form.setLayout({ html: '{content}{button}{logo}{lang}', css: '' }));+ assert.deepEqual(form.unknownPlaceholders, ['logo']);+ assert.equal(form.hasUnknownVariables, true);+ });++ it('saves the edits of every language, and no layout while it is the built-in one', async () => {+ await step(() => form.setText('reset', 'en', { ...builtIn, subject: 'Changed' }));++ await act(async () => form.save());++ assert.deepEqual(saved[0], {+ edits: {+ reset: { ru: { ...builtIn, subject: 'Сохранено' }, en: { ...builtIn, subject: 'Changed' } },+ },+ layout: null,+ });+ });++ it('saves a changed layout, and goes back to the built-in one', async () => {+ const layout = { html: '{content}{button}', css: 'p { margin: 0; }' };+ await step(() => form.setLayout(layout));+ assert.equal(form.layoutEdited, true);++ await act(async () => form.save());+ assert.deepEqual(saved[0]!.layout, layout);++ await step(() => form.resetLayout());+ assert.equal(form.layoutEdited, false);+ });++ it('gives the draft of what is on the screen, saved or not', async () => {+ const text = { ...builtIn, subject: 'Changed' };+ await step(() => form.setText('reset', 'en', text));++ assert.deepEqual(form.draft('reset', 'en'), {+ key: 'reset',+ locale: 'en',+ text,+ layout: defaultLayout,+ });+ });+});diff --git a/apps/web/src/features/god/hooks/useGodEmailTemplatesForm.ts b/apps/web/src/features/god/hooks/useGodEmailTemplatesForm.tsnew file mode 100644index 00000000..edda1773--- /dev/null+++ b/apps/web/src/features/god/hooks/useGodEmailTemplatesForm.ts@@ -0,0 +1,131 @@+'use client';++import { useMemo, useState } from 'react';+import type { Locale } from '@/i18n/locales';+import type {+ EmailDraft,+ EmailLayout,+ EmailTemplateEntry,+ EmailTemplatesBody,+ EmailTemplatesSettings,+ EmailText,+} from '@/lib/api/endpoints/god';+import { useUpdateEmailTemplates } from '../services/god.service';+import { unknownVariables, writtenText } from '../utils/emailMarkdown';++export interface EmailSelection {+ key: string;+ locale: Locale;+ tab: 'emails' | 'layout';+}++type EmailEdits = EmailTemplatesBody['edits'];++export interface GodEmailTemplatesForm {+ settings: EmailTemplatesSettings;+ template: (key: string) => EmailTemplateEntry;+ text: (key: string, locale: string) => EmailText;+ isEdited: (key: string, locale: string) => boolean;+ setText: (key: string, locale: string, text: EmailText) => void;+ resetText: (key: string, locale: string) => void;+ layout: EmailLayout;+ setLayout: (layout: EmailLayout) => void;+ resetLayout: () => void;+ layoutEdited: boolean;+ missingPlaceholders: string[];+ unknownPlaceholders: string[];+ hasBlankText: boolean;+ hasUnknownVariables: boolean;+ dirty: boolean;+ saving: boolean;+ save: () => Promise<void>;+ draft: (key: string, locale: string) => EmailDraft;+}++function sameText(a: EmailText, b: EmailText): boolean {+ return a.subject === b.subject && a.body === b.body && a.button === b.button;+}++function sameLayout(a: EmailLayout, b: EmailLayout): boolean {+ return a.html === b.html && a.css === b.css;+}++function fingerprint(edits: EmailEdits): string {+ return Object.entries(edits)+ .flatMap(([key, byLocale]) =>+ Object.entries(byLocale).map(([locale, text]) => JSON.stringify([key, locale, text])),+ )+ .sort()+ .join('\n');+}++// All the edits of the page, across emails and languages, saved at once. A text that matches+// the built-in one holds no edit, so a language shows as edited only while it differs.+export function useGodEmailTemplatesForm(settings: EmailTemplatesSettings): GodEmailTemplatesForm {+ const update = useUpdateEmailTemplates();+ const saved = useMemo(+ () => Object.fromEntries(settings.templates.map((entry) => [entry.key, entry.edits])),+ [settings],+ );+ const [edits, setEdits] = useState<EmailEdits>(saved);+ const [layout, setLayout] = useState(settings.layout);++ const template = (key: string) =>+ settings.templates.find((entry) => entry.key === key) ?? settings.templates[0];+ const text = (key: string, locale: string) =>+ edits[key]?.[locale] ?? template(key).defaults[locale];++ function resetText(key: string, locale: string) {+ setEdits((current) => {+ const { [locale]: _removed, ...rest } = current[key] ?? {};+ return { ...current, [key]: rest };+ });+ }++ function setText(key: string, locale: string, next: EmailText) {+ if (sameText(next, template(key).defaults[locale])) {+ resetText(key, locale);+ return;+ }+ setEdits((current) => ({ ...current, [key]: { ...current[key], [locale]: next } }));+ }++ const layoutEdited = !sameLayout(layout, settings.defaultLayout);+ const unknownPlaceholders = unknownVariables(+ layout.html,+ settings.placeholders.map((placeholder) => placeholder.name),+ );++ return {+ settings,+ template,+ text,+ isEdited: (key, locale) => Boolean(edits[key]?.[locale]),+ setText,+ resetText,+ layout,+ setLayout,+ resetLayout: () => setLayout(settings.defaultLayout),+ layoutEdited,+ missingPlaceholders: settings.placeholders+ .filter((p) => p.required && !layout.html.includes(`{${p.name}}`))+ .map((p) => p.name),+ unknownPlaceholders,+ hasBlankText: Object.values(edits)+ .flatMap((byLocale) => Object.values(byLocale))+ .some((entry) => !entry.subject.trim() || !entry.body.trim()),+ hasUnknownVariables:+ unknownPlaceholders.length > 0 ||+ Object.entries(edits).some(([key, byLocale]) =>+ Object.values(byLocale).some(+ (entry) => unknownVariables(writtenText(entry), template(key).variables).length > 0,+ ),+ ),+ dirty: fingerprint(edits) !== fingerprint(saved) || !sameLayout(layout, settings.layout),+ saving: update.isPending,+ save: async () => {+ await update.mutateAsync({ edits, layout: layoutEdited ? layout : null });+ },+ draft: (key, locale) => ({ key, locale, text: text(key, locale), layout }),+ };+}diff --git a/apps/web/src/features/god/services/god.service.ts b/apps/web/src/features/god/services/god.service.tsindex 785aa3cc..16383920 100644--- a/apps/web/src/features/god/services/god.service.ts+++ b/apps/web/src/features/god/services/god.service.ts@@ -19,6 +19,8 @@ import {type InstanceOidcSettingsPatch,type InstanceTelegramSettingsPatch,type InstanceUserKind,+ type EmailDraft,+ type EmailTemplatesBody,type SharingSettings,getInstanceAuthSettings,updateInstanceAuthSettings,@@ -35,6 +37,10 @@ import {updateInstanceProjectDefaults,getInstanceAgentSettings,updateInstanceAgentSettings,+ getEmailTemplates,+ previewEmailDraft,+ testEmailDraft,+ updateEmailTemplates,getInstanceSharingSettings,updateInstanceSharingSettings,getInstanceEmbedSites,@@ -201,6 +207,35 @@ export function useUpdateInstanceSharingSettings() {});}+export function useEmailTemplatesQuery() {+ return useQuery({+ queryKey: qk.instanceEmailTemplates,+ queryFn: () => getEmailTemplates(),+ });+}++export function useUpdateEmailTemplates() {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: (body: EmailTemplatesBody) => updateEmailTemplates(body),+ onSuccess: (data) => qc.setQueryData(qk.instanceEmailTemplates, data),+ });+}++// The email as the api renders it, so the preview is what goes out.+export function useEmailPreviewQuery(draft: EmailDraft) {+ return useQuery({+ queryKey: qk.instanceEmailPreview(draft),+ queryFn: () => previewEmailDraft(draft),+ placeholderData: keepPreviousData,+ retry: false,+ });+}++export function useTestEmailDraft() {+ return useMutation({ mutationFn: (draft: EmailDraft) => testEmailDraft(draft) });+}+// What applies to every team's agents: how long their run traces are kept.export function useInstanceAgentSettingsQuery() {return useQuery({diff --git a/apps/web/src/features/god/utils/emailMarkdown.test.ts b/apps/web/src/features/god/utils/emailMarkdown.test.tsnew file mode 100644index 00000000..360f7a5f--- /dev/null+++ b/apps/web/src/features/god/utils/emailMarkdown.test.ts@@ -0,0 +1,47 @@+import assert from 'node:assert/strict';+import { describe, it } from 'node:test';+import { prefixLine, replaceSelection, unknownVariables, wrapSelection } from './emailMarkdown';++describe('wrapSelection', () => {+ it('wraps the selected text and keeps it selected', () => {+ assert.deepEqual(wrapSelection('one two', 4, 7, '**', '**', 'bold'), {+ value: 'one **two**',+ start: 6,+ end: 9,+ });+ });++ it('puts a sample in when nothing is selected', () => {+ assert.deepEqual(wrapSelection('one ', 4, 4, '[', '](https://)', 'link text'), {+ value: 'one [link text](https://)',+ start: 5,+ end: 14,+ });+ });+});++describe('prefixLine', () => {+ it('marks the line the cursor is on', () => {+ assert.deepEqual(prefixLine('one\ntwo', 5, '- '), { value: 'one\n- two', start: 6, end: 6 });+ });++ it('marks the first line', () => {+ assert.equal(prefixLine('one', 2, '# ').value, '# one');+ });+});++describe('replaceSelection', () => {+ it('puts a placeholder over the selection', () => {+ assert.deepEqual(replaceSelection('a old b', 2, 5, '{ref}'), {+ value: 'a {ref} b',+ start: 7,+ end: 7,+ });+ });+});++describe('unknownVariables', () => {+ it('names each variable the template does not have, once', () => {+ assert.deepEqual(unknownVariables('{ref} {nope} {nope} {other}', ['ref']), ['nope', 'other']);+ });+});diff --git a/apps/web/src/features/god/utils/emailMarkdown.ts b/apps/web/src/features/god/utils/emailMarkdown.tsnew file mode 100644index 00000000..c890537b--- /dev/null+++ b/apps/web/src/features/god/utils/emailMarkdown.ts@@ -0,0 +1,62 @@+import type { EmailText } from '@/lib/api/endpoints/god';++// The edits behind the formatting buttons of the email text, on a textarea's value and+// selection. `start` and `end` are the selection after the edit.+export interface TextEdit {+ value: string;+ start: number;+ end: number;+}++export function wrapSelection(+ value: string,+ start: number,+ end: number,+ before: string,+ after: string,+ sample: string,+): TextEdit {+ const selected = value.slice(start, end) || sample;+ const from = start + before.length;+ return {+ value: value.slice(0, start) + before + selected + after + value.slice(end),+ start: from,+ end: from + selected.length,+ };+}++export function prefixLine(value: string, start: number, prefix: string): TextEdit {+ const line = value.lastIndexOf('\n', start - 1) + 1;+ const cursor = line + prefix.length;+ return { value: value.slice(0, line) + prefix + value.slice(line), start: cursor, end: cursor };+}++export function replaceSelection(+ value: string,+ start: number,+ end: number,+ inserted: string,+): TextEdit {+ const cursor = start + inserted.length;+ return { value: value.slice(0, start) + inserted + value.slice(end), start: cursor, end: cursor };+}++// In the next frame, so the value of the edit is in the field by then.+export function selectAfterEdit(+ element: HTMLInputElement | HTMLTextAreaElement,+ edit: TextEdit,+): void {+ requestAnimationFrame(() => {+ element.focus();+ element.setSelectionRange(edit.start, edit.end);+ });+}++export function writtenText(text: EmailText): string {+ return `${text.subject} ${text.body} ${text.button}`;+}++export function unknownVariables(text: string, variables: string[]): string[] {+ const used = [...text.matchAll(/\{(\w+)\}/g)].map((match) => match[1]);+ return [...new Set(used)].filter((name) => !variables.includes(name));+}diff --git a/apps/web/src/i18n/accept-language.ts b/apps/web/src/i18n/accept-language.tsindex 50cb1e2e..6de981c1 100644--- a/apps/web/src/i18n/accept-language.ts+++ b/apps/web/src/i18n/accept-language.ts@@ -1,7 +1,7 @@import { DEFAULT_LOCALE, LOCALES, type Locale } from './locales';-// Keep this matcher aligned with the API copy so the first server render and-// an account without saved preferences resolve to the same language.+// Keep this matcher aligned with the copy in packages/mailer/src/locale.ts so the first+// server render and an account without saved preferences resolve to the same language.export function localeFromAcceptLanguage(value: string | null): Locale {const requested = (value ?? '').split(',')diff --git a/apps/web/src/lib/api/endpoints/god.ts b/apps/web/src/lib/api/endpoints/god.tsindex c17024a6..2cc44807 100644--- a/apps/web/src/lib/api/endpoints/god.ts+++ b/apps/web/src/lib/api/endpoints/god.ts@@ -259,6 +259,73 @@ export const testInstanceEmailSettings = (patch: InstanceEmailSettingsPatch) =>body: JSON.stringify(patch),});+export interface EmailText {+ subject: string;+ body: string;+ button: string;+}++export interface EmailLayout {+ html: string;+ css: string;+}++export interface EmailTemplateEntry {+ key: string;+ group: string;+ variables: string[];+ hasLink: boolean;+ defaults: Record<string, EmailText>;+ edits: Record<string, EmailText>;+}++export interface EmailTemplatesSettings {+ templates: EmailTemplateEntry[];+ layout: EmailLayout;+ defaultLayout: EmailLayout;+ placeholders: { name: string; required: boolean }[];+ canSend: boolean;+}++export interface EmailTemplatesBody {+ edits: Record<string, Record<string, EmailText>>;+ layout: EmailLayout | null;+}++export interface EmailDraft {+ key: string;+ locale: string;+ text: EmailText;+ layout: EmailLayout;+}++export interface EmailPreview {+ subject: string;+ text: string;+ html: string;+ from: string | null;+}++export const getEmailTemplates = () => request<EmailTemplatesSettings>('/god/email-templates');++export const updateEmailTemplates = (body: EmailTemplatesBody) =>+ request<EmailTemplatesSettings>('/god/email-templates', {+ method: 'PUT',+ body: JSON.stringify(body),+ });++export const previewEmailDraft = (draft: EmailDraft) =>+ request<EmailPreview>('/god/email-templates/preview', {+ method: 'POST',+ body: JSON.stringify(draft),+ });++export const testEmailDraft = (draft: EmailDraft) =>+ request<InstanceEmailTestResult>('/god/email-templates/test', {+ method: 'POST',+ body: JSON.stringify(draft),+ });+export const getInstanceTelegramSettings = () =>request<InstanceTelegramSettings>('/god/telegram-settings');diff --git a/apps/web/src/services/queryKeys.ts b/apps/web/src/services/queryKeys.tsindex 98046b3c..8c8e608b 100644--- a/apps/web/src/services/queryKeys.ts+++ b/apps/web/src/services/queryKeys.ts@@ -356,6 +356,8 @@ export const qk = {instanceAgentSettings: ['instanceAgentSettings'] as const,instanceSharingSettings: ['instanceSharingSettings'] as const,instanceEmbedSites: ['instanceEmbedSites'] as const,+ instanceEmailTemplates: ['instanceEmailTemplates'] as const,+ instanceEmailPreview: (draft: unknown) => ['instanceEmailPreview', draft] as const,instanceStorageSettings: ['instanceStorageSettings'] as const,systemRoles: ['systemRoles'] as const,// The upload limits as read by the upload UI (open to any signed-in user).diff --git a/apps/web/src/utils/godSections.ts b/apps/web/src/utils/godSections.tsindex 026034da..3a36a9bf 100644--- a/apps/web/src/utils/godSections.ts+++ b/apps/web/src/utils/godSections.ts@@ -6,6 +6,7 @@ import {Keyboard,KeyRound,Mail,+ Mails,Send,ShieldCheck,SlidersHorizontal,@@ -77,6 +78,11 @@ export const GOD_SECTIONS: GodSection[] = godSections([group: 'instance',icon: HardDrive,},+ {+ slug: 'email-templates',+ group: 'instance',+ icon: Mails,+ },{slug: 'telegram',group: 'instance',diff --git a/apps/worker/src/__tests__/integration/notification-send.test.ts b/apps/worker/src/__tests__/integration/notification-send.test.tsindex 493399bd..bb34cf13 100644--- a/apps/worker/src/__tests__/integration/notification-send.test.ts+++ b/apps/worker/src/__tests__/integration/notification-send.test.ts@@ -1,6 +1,16 @@import { beforeEach, describe, it, expect } from 'bun:test';import { randomUUID } from 'node:crypto';-import { appSecret, db, project, team, teamInvite, workspace } from '@repo/db';+import {+ INSTANCE_EMAIL_SECRET_KEY,+ appSecret,+ db,+ defaultInstanceEmailConfig,+ project,+ team,+ teamInvite,+ workspace,+ writeSecret,+} from '@repo/db';import { deliverNotification } from '../../notification-send';// The send reads the credentials itself, so these cover the two decisions it makes@@ -54,6 +64,47 @@ describe('deliverNotification', () => {expect(result).toEqual({ ok: true });});+ it('sends an email the api composed as it is', async () => {+ const { projectId } = await makeProject();+ await writeSecret(+ INSTANCE_EMAIL_SECRET_KEY,+ {+ ...defaultInstanceEmailConfig(),+ resend: { enabled: true, apiKey: 're_test' },+ from: '[email protected]',+ },+ {},+ );+ const realFetch = globalThis.fetch;+ let sent: { text: string; html: string } | undefined;+ globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {+ if (!String(input).startsWith('https://api.resend.com/')) return realFetch(input, init);+ sent = JSON.parse(String(init?.body));+ return Response.json({ id: 'sent' });+ }) as typeof fetch;++ const result = await deliverNotification({+ projectId,+ channel: 'email',+ recipient: '[email protected]',+ payload: {+ subject: 'Hello',+ text: 'Plain\n\nhttps://plan.test/a',+ html: '<table>Composed</table>',+ url: 'https://plan.test/a',+ emailSource: 'instance',+ },+ }).finally(() => {+ globalThis.fetch = realFetch;+ });++ expect(result).toEqual({ ok: true });+ expect(sent).toMatchObject({+ text: 'Plain\n\nhttps://plan.test/a',+ html: '<table>Composed</table>',+ });+ });+it('fails permanently when the team has no email provider', async () => {const { projectId } = await makeProject();diff --git a/apps/worker/src/notification-send.ts b/apps/worker/src/notification-send.tsindex 23560f10..f5095089 100644--- a/apps/worker/src/notification-send.ts+++ b/apps/worker/src/notification-send.ts@@ -47,7 +47,9 @@ async function sendNotificationEmail(input: SendInput): Promise<SendResult> {? null: { smtp: input.config.smtp, resend: input.config.resend, from: input.config.from };if (!config) return { ok: false, retryable: false, error: 'email not configured' };- const { text, html } = emailBody(input.payload.text, input.payload.url);+ const { text, html } = input.payload.html+ ? { text: input.payload.text, html: input.payload.html }+ : emailBody(input.payload.text, input.payload.url);return sendEmail(config, {to: input.recipient,subject: input.payload.subject ?? '',diff --git a/bun.lock b/bun.lockindex 15ce3549..284aa0dd 100644--- a/bun.lock+++ b/bun.lock@@ -265,6 +265,8 @@"name": "@repo/mailer","version": "0.0.0","dependencies": {+ "juice": "^12.2.1",+ "marked": "^18.1.1","nodemailer": "^10.1.0",},"devDependencies": {@@ -475,6 +477,10 @@"@csstools/css-tokenizer": ["@csstools/[email protected]", "", {}, "sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw=="],+ "@csstools/selector-resolve-nested": ["@csstools/[email protected]", "", { "peerDependencies": { "postcss-selector-parser": "^7.1.1" } }, "sha512-JpjNBJFA+4OnAHKRK4AMp8xrYyLhI9XapOeBlP2PhRU/IylSw+1ep3BFNTksBJnrTS3KT6kqKNVfpzLLwZUW5Q=="],++ "@csstools/selector-specificity": ["@csstools/[email protected]", "", { "peerDependencies": { "postcss-selector-parser": "^7.1.1" } }, "sha512-MBuqFIIvqk4S593MGAskTkPpEUUzZNvGzh8mMxEwl3oHwjQlXmqHEDxNbN3Y0Tsh+xjmem4GZjeg7I0qkwBivg=="],+"@date-fns/tz": ["@date-fns/[email protected]", "", {}, "sha512-lwYN/vDPeNRULcepoE/LO2Pgx+7/RV+S9ARfbc9lr2DtGkOD7pAiruHvbR1RX3Qyf6ja47EWJDMsNK5vK08DJg=="],"@dnd-kit/accessibility": ["@dnd-kit/[email protected]", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0" } }, "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw=="],@@ -1423,6 +1429,8 @@"ajv-formats": ["[email protected]", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="],+ "ansi-colors": ["[email protected]", "", {}, "sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw=="],+"ansi-regex": ["[email protected]", "", {}, "sha512-+O9Jct8wf++lXxxFc4hc8LsjaSq0HFzzL7cVsw8pRDIPdjKD2mT4ytDZlLuSBZ4cLKZFXIrMGO7DbQCtMJJMKw=="],"ansi-styles": ["[email protected]", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],@@ -1485,6 +1493,8 @@"body-parser": ["[email protected]", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^2.1.0", "debug": "^4.4.3", "http-errors": "^2.0.1", "iconv-lite": "^0.7.3", "on-finished": "^2.4.1", "qs": "^6.16.1", "raw-body": "^3.0.2", "type-is": "^2.1.0" } }, "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ=="],+ "boolbase": ["[email protected]", "", {}, "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww=="],+"bot": ["bot@workspace:apps/bot"],"bowser": ["[email protected]", "", {}, "sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg=="],@@ -1531,6 +1541,10 @@"chat": ["[email protected]", "", { "dependencies": { "@workflow/serde": "4.1.0-beta.2", "mdast-util-to-string": "^4.0.0", "remark-gfm": "^4.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "remend": "^1.2.1", "unified": "^11.0.5" }, "peerDependencies": { "ai": "^6.0.182 || ^7.0.0", "workflow": "^5.0.0-beta.35", "zod": "^3.0.0 || ^4.0.0" }, "optionalPeers": ["ai", "workflow", "zod"] }, "sha512-rXWcVSPY0YiVXLpApYxuS2EbWzXBy3mI1kSAcnF9iPzw98FbDIDq73+Ri0JpUhS1bdVZPhWZgn8bum+Gy8jF3Q=="],+ "cheerio": ["[email protected]", "", { "dependencies": { "cheerio-select": "^2.1.0", "dom-serializer": "^2.0.0", "domhandler": "^5.0.3", "domutils": "^3.2.2", "encoding-sniffer": "^0.2.1", "htmlparser2": "^10.1.0", "parse5": "^7.3.0", "parse5-htmlparser2-tree-adapter": "^7.1.0", "parse5-parser-stream": "^7.1.2", "undici": "^7.19.0", "whatwg-mimetype": "^4.0.0" } }, "sha512-WDrybc/gKFpTYQutKIK6UvfcuxijIZfMfXaYm8NMsPQxSYvf+13fXUJ4rztGGbJcBQ/GF55gvrZ0Bc0bj/mqvg=="],++ "cheerio-select": ["[email protected]", "", { "dependencies": { "boolbase": "^1.0.0", "css-select": "^5.1.0", "css-what": "^6.1.0", "domelementtype": "^2.3.0", "domhandler": "^5.0.3", "domutils": "^3.0.1" } }, "sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g=="],+"class-variance-authority": ["[email protected]", "", { "dependencies": { "clsx": "^2.1.1" } }, "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg=="],"classcat": ["[email protected]", "", {}, "sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w=="],@@ -1553,6 +1567,8 @@"comma-separated-tokens": ["[email protected]", "", {}, "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg=="],+ "commander": ["[email protected]", "", {}, "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw=="],+"compress-commons": ["[email protected]", "", { "dependencies": { "buffer-crc32": "^0.2.13", "crc32-stream": "^4.0.2", "normalize-path": "^3.0.0", "readable-stream": "^3.6.0" } }, "sha512-D3uMHtGc/fcO1Gt1/L7i1e33VOvD4A9hfQLP+6ewd+BvG/gQ84Yh4oftEhAdjSMgBgwGL+jsppT7JYNpo6MHHg=="],"concat-map": ["[email protected]", "", {}, "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="],@@ -1579,8 +1595,14 @@"cross-spawn": ["[email protected]", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],+ "css-select": ["[email protected]", "", { "dependencies": { "boolbase": "^1.0.0", "css-what": "^6.1.0", "domhandler": "^5.0.2", "domutils": "^3.0.1", "nth-check": "^2.0.1" } }, "sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw=="],+"css-tree": ["[email protected]", "", { "dependencies": { "mdn-data": "2.27.1", "source-map-js": "^1.2.1" } }, "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA=="],+ "css-what": ["[email protected]", "", {}, "sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA=="],++ "cssesc": ["[email protected]", "", { "bin": { "cssesc": "bin/cssesc" } }, "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg=="],+"csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],"cva": ["[email protected]", "", { "dependencies": { "clsx": "^2.1.1" }, "peerDependencies": { "typescript": ">= 4.5.5" }, "optionalPeers": ["typescript"] }, "sha512-F/JS9hScapq4DBVQXcK85l9U91M6ePeXoBMSp7vypzShoefUBxjQTo3g3935PUHgQd+IW77DjbPRIxugy4/GCQ=="],@@ -1661,8 +1683,16 @@"doctrine": ["[email protected]", "", { "dependencies": { "esutils": "^2.0.2" } }, "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw=="],+ "dom-serializer": ["[email protected]", "", { "dependencies": { "domelementtype": "^2.3.0", "domhandler": "^5.0.2", "entities": "^4.2.0" } }, "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg=="],++ "domelementtype": ["[email protected]", "", {}, "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw=="],++ "domhandler": ["[email protected]", "", { "dependencies": { "domelementtype": "^2.3.0" } }, "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w=="],+"dompurify": ["[email protected]", "", { "optionalDependencies": { "@types/trusted-types": "^2.0.7" } }, "sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w=="],+ "domutils": ["[email protected]", "", { "dependencies": { "dom-serializer": "^2.0.0", "domelementtype": "^2.3.0", "domhandler": "^5.0.3" } }, "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw=="],+"dotenv": ["[email protected]", "", { "bin": { "dotenv": "dist/index.cjs" } }, "sha512-QEvMEF8ca3GNZJJnAbOgxpj5ULhBvnMcURp+XKrtvqFNPgjBvYoswQ0Jl2cO7JzCjxZjJhr9ZuIEhlrRxMft/Q=="],"dotenv-cli": ["[email protected]", "", { "dependencies": { "cross-spawn": "^7.0.6", "dotenv": "^17.1.0", "dotenv-expand": "^12.0.0", "minimist": "^1.2.6" }, "bin": { "dotenv": "cli.js" } }, "sha512-r5pA8idbk7GFWuHEU7trSTflWcdBpQEK+Aw17UrSHjS6CReuhrrPcyC3zcQBPQvhArRHnBo/h6eLH1fkCvNlww=="],@@ -1685,6 +1715,8 @@"encodeurl": ["[email protected]", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="],+ "encoding-sniffer": ["[email protected]", "", { "dependencies": { "iconv-lite": "^0.6.3", "whatwg-encoding": "^3.1.1" } }, "sha512-5gvq20T6vfpekVtqrYQsSCFZ1wEg5+wW0/QaZMWkFr6BqD3NfKs0rLCx4rrVlSWJeZb5NBJgVLswK/w2MWU+Gw=="],+"end-of-stream": ["[email protected]", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="],"enhanced-resolve": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-L1l8TNvomm6UVW5B253AGxQagSQr+vGwhMlrrfRS2qmhx46AMpMVJKQYLvWYbysTMY8VoicOvzHzoHMbyzB+4A=="],@@ -1715,6 +1747,8 @@"esbuild": ["[email protected]", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.12", "@esbuild/android-arm": "0.25.12", "@esbuild/android-arm64": "0.25.12", "@esbuild/android-x64": "0.25.12", "@esbuild/darwin-arm64": "0.25.12", "@esbuild/darwin-x64": "0.25.12", "@esbuild/freebsd-arm64": "0.25.12", "@esbuild/freebsd-x64": "0.25.12", "@esbuild/linux-arm": "0.25.12", "@esbuild/linux-arm64": "0.25.12", "@esbuild/linux-ia32": "0.25.12", "@esbuild/linux-loong64": "0.25.12", "@esbuild/linux-mips64el": "0.25.12", "@esbuild/linux-ppc64": "0.25.12", "@esbuild/linux-riscv64": "0.25.12", "@esbuild/linux-s390x": "0.25.12", "@esbuild/linux-x64": "0.25.12", "@esbuild/netbsd-arm64": "0.25.12", "@esbuild/netbsd-x64": "0.25.12", "@esbuild/openbsd-arm64": "0.25.12", "@esbuild/openbsd-x64": "0.25.12", "@esbuild/openharmony-arm64": "0.25.12", "@esbuild/sunos-x64": "0.25.12", "@esbuild/win32-arm64": "0.25.12", "@esbuild/win32-ia32": "0.25.12", "@esbuild/win32-x64": "0.25.12" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg=="],+ "escape-goat": ["[email protected]", "", {}, "sha512-w3PwNZJwRxlp47QGzhuEBldEqVHHhh8/tIPcl6ecf2Bou99cdAt0knihBV0Ecc7CGxYduXVBDheH1K2oADRlvw=="],+"escape-html": ["[email protected]", "", {}, "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="],"escape-string-regexp": ["[email protected]", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="],@@ -1933,6 +1967,8 @@"html-whitespace-sensitive-tag-names": ["[email protected]", "", {}, "sha512-q+310vW8zmymYHALr1da4HyXUQ0zgiIwIicEfotYPWGN0OJVEN/58IJ3A4GBYcEq3LGAZqKb+ugvP0GNB9CEAA=="],+ "htmlparser2": ["[email protected]", "", { "dependencies": { "domelementtype": "^2.3.0", "domhandler": "^5.0.3", "domutils": "^3.2.2", "entities": "^7.0.1" } }, "sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ=="],+"http-errors": ["[email protected]", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="],"human-signals": ["[email protected]", "", {}, "sha512-eKCa6bwnJhvxj14kZk5NCPc6Hb6BdsU9DZcOnmQKSnO1VKrfV0zCvtttPZUsBvjmNDn8rpcJfpwSYnHBjc95MQ=="],@@ -2089,6 +2125,8 @@"jszip": ["[email protected]", "", { "dependencies": { "lie": "~3.3.0", "pako": "~1.0.2", "readable-stream": "~2.3.6", "setimmediate": "^1.0.5" } }, "sha512-3l+rb15IOWtUhU0H5MFqES/T6Kh7abYwjosBey/vD6hDt8zoEffkSC5Ws5SGtgVw3gBx2NEbhTeSW1+kWkpyTQ=="],+ "juice": ["[email protected]", "", { "dependencies": { "cheerio": "1.2.0", "commander": "^14.0.3", "entities": "^8.0.0", "postcss": "^8.5.0", "postcss-nesting": "^14.0.0", "postcss-safe-parser": "^7.0.1", "postcss-selector-parser": "^7.1.0", "web-resource-inliner": "^8.0.0" }, "bin": { "juice": "bin/juice" } }, "sha512-tbyBK+Ifmx95xRB2XET205DAz67Oq8A5SG+gV8GzBzzf0oRVhpo+Wh1KTkC12emlyZallR/ZsG8FJ1LcM4P17Q=="],+"keyv": ["[email protected]", "", { "dependencies": { "json-buffer": "3.0.1" } }, "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw=="],"kind-of": ["[email protected]", "", {}, "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw=="],@@ -2313,6 +2351,8 @@"micromatch": ["[email protected]", "", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="],+ "mime": ["[email protected]", "", { "bin": { "mime": "cli.js" } }, "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg=="],+"mime-db": ["[email protected]", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="],"mime-types": ["[email protected]", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="],@@ -2325,7 +2365,7 @@"ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],- "nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ=="],+ "nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ=="],"nanostores": ["[email protected]", "", {}, "sha512-i0tloweeudshAEuddpDxcg9Ik6pkPfVsHIgKyf143JrgG7/MOh0+q7BypdLXZPoOP7fOYt1eTcwGkyiVmhJFkA=="],@@ -2357,6 +2397,8 @@"npm-run-path": ["[email protected]", "", { "dependencies": { "path-key": "^4.0.0", "unicorn-magic": "^0.3.0" } }, "sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA=="],+ "nth-check": ["[email protected]", "", { "dependencies": { "boolbase": "^1.0.0" } }, "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w=="],+"object-assign": ["[email protected]", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],"object-inspect": ["[email protected]", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="],@@ -2405,6 +2447,10 @@"parse5": ["[email protected]", "", { "dependencies": { "entities": "^8.0.0" } }, "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw=="],+ "parse5-htmlparser2-tree-adapter": ["[email protected]", "", { "dependencies": { "domhandler": "^5.0.3", "parse5": "^7.0.0" } }, "sha512-ruw5xyKs6lrpo9x9rCZqZZnIUntICjQAd0Wsmp396Ul9lN/h+ifgVV1x1gZHi8euej6wTfpqX8j+BFQxF0NS/g=="],++ "parse5-parser-stream": ["[email protected]", "", { "dependencies": { "parse5": "^7.0.0" } }, "sha512-JyeQc9iwFLn5TbvvqACIF/VXG6abODeB3Fwmv/TGdLk2LfbWkaySGY72at4+Ty7EkPZj854u4CrICqNk2qIbow=="],+"parseurl": ["[email protected]", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="],"path-exists": ["[email protected]", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="],@@ -2447,7 +2493,13 @@"possible-typed-array-names": ["[email protected]", "", {}, "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg=="],- "postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.18", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A=="],+ "postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg=="],++ "postcss-nesting": ["[email protected]", "", { "dependencies": { "@csstools/selector-resolve-nested": "^4.0.2", "@csstools/selector-specificity": "^6.0.1", "postcss-selector-parser": "^7.1.1" }, "peerDependencies": { "postcss": "^8.4" } }, "sha512-S6NJP2WFinT50vIo7fu3Z8PrTgng3P0ky47a5wQSrQpsH3WS82ZpjkIdAs+2ltRkk0wU7vRBKLYM96qY0RvKjA=="],++ "postcss-safe-parser": ["[email protected]", "", { "peerDependencies": { "postcss": "^8.4.31" } }, "sha512-1WzZxRLaAFwEh6Do+zyGpjWV3nGJNxxhuh7Ubu/q1ICImMgZJnLwhoaEpRbG4pJppp2Y1ncL9ffA2f+LhrefQg=="],++ "postcss-selector-parser": ["[email protected]", "", { "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" } }, "sha512-wWBro/7hJ40ye6TPiXkUQoXKCw23xSsjriUvqd7Uls9Sso3oLiON1flc18cCdnjgCRXw4fBVqUJJeOdDTh3P3g=="],"postgres": ["[email protected]", "", {}, "sha512-GD3qdB0x1z9xgFI6cdRD6xu2Sp2WCOEoe3mtnyB5Ee0XrrL5Pe+e4CCnJrRMnL1zYtRDZmQQVbvOttLnKDLnaw=="],@@ -2859,6 +2911,8 @@"uuid": ["[email protected]", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="],+ "valid-data-url": ["[email protected]", "", {}, "sha512-jOWVmzVceKlVVdwjNSenT4PbGghU0SBIizAev8ofZVgivk/TVHXSbNL8LP6M3spZvkR9/QolkyJavGSX5Cs0UA=="],+"vary": ["[email protected]", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="],"vfile": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile-message": "^4.0.0" } }, "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q=="],@@ -2885,10 +2939,14 @@"web-namespaces": ["[email protected]", "", {}, "sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ=="],+ "web-resource-inliner": ["[email protected]", "", { "dependencies": { "ansi-colors": "^4.1.1", "escape-goat": "^3.0.0", "htmlparser2": "^9.1.0", "mime": "^2.4.6", "valid-data-url": "^3.0.0" } }, "sha512-Ezr98sqXW/+OCGoUEXuOKVR+oVFlSdn1tIySEEJdiSAw4IjrW8hQkwARSSBJTSB5Us5dnytDgL0ZDliAYBhaNA=="],+"webidl-conversions": ["[email protected]", "", {}, "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ=="],"webpack-virtual-modules": ["[email protected]", "", {}, "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ=="],+ "whatwg-encoding": ["[email protected]", "", { "dependencies": { "iconv-lite": "0.6.3" } }, "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ=="],+"whatwg-mimetype": ["[email protected]", "", {}, "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw=="],"whatwg-url": ["[email protected]", "", { "dependencies": { "@exodus/bytes": "^1.16.0", "tr46": "^7.0.0", "webidl-conversions": "^8.0.1" } }, "sha512-IhLIHNcBrzIixC5XXsbr4DxdjajyA5vQ5RwGZMtrUp+GbtE5Nrsge9QKau7jXrC0aTXLYGV0xiW7Tb4YS2aomw=="],@@ -2989,10 +3047,14 @@"@scalar/api-client/@scalar/helpers": ["@scalar/[email protected]", "", {}, "sha512-9eILWzUcAkHEuYMMvijpSIy69t+Vkq+NudLB/7lgARFTWqXfQpIxW1L3VH7ogKyRie5+E4CNZ3PSvlw6IIfLGw=="],+ "@scalar/api-client/nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ=="],+"@scalar/api-client/pretty-ms": ["[email protected]", "", {}, "sha512-6BWuxY2dCNgT45VnGzZcfNy7WeLqXiZqhhy4aHThTE6KI56R2ZBw9HQ7spPFKYchDizvJbPxTEknIpmW4FSmQA=="],"@scalar/api-reference/@scalar/helpers": ["@scalar/[email protected]", "", {}, "sha512-9eILWzUcAkHEuYMMvijpSIy69t+Vkq+NudLB/7lgARFTWqXfQpIxW1L3VH7ogKyRie5+E4CNZ3PSvlw6IIfLGw=="],+ "@scalar/api-reference/nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ=="],+"@scalar/asyncapi-to-markdown/@scalar/helpers": ["@scalar/[email protected]", "", {}, "sha512-9eILWzUcAkHEuYMMvijpSIy69t+Vkq+NudLB/7lgARFTWqXfQpIxW1L3VH7ogKyRie5+E4CNZ3PSvlw6IIfLGw=="],"@scalar/asyncapi-upgrader/@scalar/helpers": ["@scalar/[email protected]", "", {}, "sha512-9eILWzUcAkHEuYMMvijpSIy69t+Vkq+NudLB/7lgARFTWqXfQpIxW1L3VH7ogKyRie5+E4CNZ3PSvlw6IIfLGw=="],@@ -3029,6 +3091,10 @@"@scalar/snippetz/@scalar/helpers": ["@scalar/[email protected]", "", {}, "sha512-9eILWzUcAkHEuYMMvijpSIy69t+Vkq+NudLB/7lgARFTWqXfQpIxW1L3VH7ogKyRie5+E4CNZ3PSvlw6IIfLGw=="],+ "@scalar/themes/nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ=="],++ "@scalar/types/nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ=="],+"@scalar/use-hooks/@scalar/helpers": ["@scalar/[email protected]", "", {}, "sha512-9eILWzUcAkHEuYMMvijpSIy69t+Vkq+NudLB/7lgARFTWqXfQpIxW1L3VH7ogKyRie5+E4CNZ3PSvlw6IIfLGw=="],"@scalar/workspace-store/@scalar/helpers": ["@scalar/[email protected]", "", {}, "sha512-9eILWzUcAkHEuYMMvijpSIy69t+Vkq+NudLB/7lgARFTWqXfQpIxW1L3VH7ogKyRie5+E4CNZ3PSvlw6IIfLGw=="],@@ -3047,6 +3113,8 @@"@tailwindcss/oxide-wasm32-wasi/tslib": ["[email protected]", "", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],+ "@tailwindcss/postcss/postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.18", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A=="],+"@tanstack/vue-virtual/@tanstack/virtual-core": ["@tanstack/[email protected]", "", {}, "sha512-nGm5KteqxasUdThLc2izl6dHUqLv0LQj7Nuyo5gYalTPf/U8a9ermvsl7reT+6ioBW1l8WfpP/mcU338nLXpqw=="],"@types/jsdom/undici-types": ["[email protected]", "", {}, "sha512-ibvdovq3nCFs8Msrd95BW+zUOq+aOVbT+wpHUoPWhztbHEoPc6oof51iFDB6Es8lTKvNvVW9jNSAB8dwrKTMGg=="],@@ -3065,8 +3133,6 @@"@vue/compiler-core/entities": ["[email protected]", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="],- "@vue/compiler-sfc/postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg=="],-"ai/@ai-sdk/provider": ["@ai-sdk/[email protected]", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-6ThcmkJQXSMlBrf6mirIjUUS04Q5/kApbYTOzd5lZfYXLa1XPpnDLxP/G96/DKc00fDIUOW9S2ls0mSzb0+l9w=="],"ai/@ai-sdk/provider-utils": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "4.0.28", "@standard-schema/spec": "^1.1.0", "@workflow/serde": "4.1.0", "eventsource-parser": "^3.0.8", "undici": "^7.29.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-Y+Z3539UXw0ctFDNepTtG23VqBQHr2A6yI2qUxvQcg75DJYgJoD2F9U2Vp5OgQjX7lxto1BLgFtKuOhzrr52vQ=="],@@ -3083,6 +3149,12 @@"chat/@workflow/serde": ["@workflow/[email protected]", "", {}, "sha512-8kkeoQKLDaKXefjV5dbhBj2aErfKp1Mc4pb6tj8144cF+Em5SPbyMbyLCHp+BVrFfFVCBluCtMx+jjvaFVZGww=="],+ "cheerio/parse5": ["[email protected]", "", { "dependencies": { "entities": "^6.0.0" } }, "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw=="],++ "cheerio/undici": ["[email protected]", "", {}, "sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg=="],++ "cheerio/whatwg-mimetype": ["[email protected]", "", {}, "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg=="],+"cmdk/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-rYOP8OMnuuPMQF1uhPVlGNcCDlkokKqGFE3JcxFViIkAXP7EvFWUliJAstrapypaBLJNHbZL6jGhbVDGTwmVhA=="],"cmdk/@radix-ui/react-dialog": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-dismissable-layer": "1.1.15", "@radix-ui/react-focus-guards": "1.1.4", "@radix-ui/react-focus-scope": "1.1.12", "@radix-ui/react-id": "1.1.2", "@radix-ui/react-portal": "1.1.13", "@radix-ui/react-presence": "1.1.7", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-slot": "1.3.0", "@radix-ui/react-use-controllable-state": "1.2.3", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.7.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-+HhbN2+YtkRgVirjZ2afMeutQRuGOrdkWR5+EFC58SJojGmtyNQwYzgi6tHBpOxvFHefMtPeHdgtjz0BOGxFQg=="],@@ -3091,12 +3163,16 @@"cmdk/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.0" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-bC3NiwsprbxKjuon9l7X6BUTw7FPVzEYaL92MPEY5SCd/9hUTPXVFtVwRix7778wtRsVao+zE062gL79FZleeQ=="],+ "dom-serializer/entities": ["[email protected]", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="],+"dotenv-cli/dotenv": ["[email protected]", "", {}, "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw=="],"dotenv-expand/dotenv": ["[email protected]", "", {}, "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow=="],"duplexer2/readable-stream": ["[email protected]", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],+ "encoding-sniffer/iconv-lite": ["[email protected]", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw=="],+"eslint-plugin-i18n-json/chalk": ["[email protected]", "", { "dependencies": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } }, "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ=="],"express/cookie": ["[email protected]", "", {}, "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w=="],@@ -3109,6 +3185,8 @@"hast-util-raw/parse5": ["[email protected]", "", { "dependencies": { "entities": "^6.0.0" } }, "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw=="],+ "htmlparser2/entities": ["[email protected]", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="],+"icu-minify/@formatjs/icu-messageformat-parser": ["@formatjs/[email protected]", "", { "dependencies": { "@formatjs/icu-skeleton-parser": "2.1.11" } }, "sha512-kl6b/4D56gjGZi4ZewSmvXbalHwjOUI5ogEHPZqw42goeXTTrL7/yuPzvdrvr0QigDtvaOeb+UeMf62jks43Yg=="],"intl-messageformat/@formatjs/icu-messageformat-parser": ["@formatjs/[email protected]", "", { "dependencies": { "@formatjs/icu-skeleton-parser": "2.1.11" } }, "sha512-kl6b/4D56gjGZi4ZewSmvXbalHwjOUI5ogEHPZqw42goeXTTrL7/yuPzvdrvr0QigDtvaOeb+UeMf62jks43Yg=="],@@ -3145,7 +3223,9 @@"npm-run-path/path-key": ["[email protected]", "", {}, "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ=="],- "postcss/nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w=="],+ "parse5-htmlparser2-tree-adapter/parse5": ["[email protected]", "", { "dependencies": { "entities": "^6.0.0" } }, "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw=="],++ "parse5-parser-stream/parse5": ["[email protected]", "", { "dependencies": { "entities": "^6.0.0" } }, "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw=="],"pretty-format/ansi-styles": ["[email protected]", "", { "dependencies": { "color-convert": "^1.9.0" } }, "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA=="],@@ -3157,6 +3237,8 @@"radix-vue/@vueuse/shared": ["@vueuse/[email protected]", "", { "dependencies": { "vue-demi": ">=0.14.8" } }, "sha512-LHpC8711VFZlDaYUXEBbFBCQ7GS3dVU9mjOhhMhXP6txTV4EhYQg/KGnQuvt/sPAtoUKq7VVUnL6mVtFoL42sA=="],+ "radix-vue/nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ=="],+"react-grid-layout/fast-equals": ["[email protected]", "", {}, "sha512-G3BSX9cfKttjr+2o1O22tYMLq0DPluZnYtq1rXumE1SpL/F/SLIfHx08WYQoWSIpeMYf8sRbJ8++71+v6Pnxfg=="],"react-redux/use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],@@ -3185,6 +3267,10 @@"unzipper/readable-stream": ["[email protected]", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],+ "web-resource-inliner/htmlparser2": ["[email protected]", "", { "dependencies": { "domelementtype": "^2.3.0", "domhandler": "^5.0.3", "domutils": "^3.1.0", "entities": "^4.5.0" } }, "sha512-5zfg6mHUoaer/97TxnGpxmbR7zJtPwIYFMZ/H5ucTlPZhKvtum05yiPK3Mgai3a0DyVxv7qYqoweaEd2nrYQzQ=="],++ "whatwg-encoding/iconv-lite": ["[email protected]", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw=="],+"which-builtin-type/isarray": ["[email protected]", "", {}, "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw=="],"zip-stream/archiver-utils": ["[email protected]", "", { "dependencies": { "glob": "^7.2.3", "graceful-fs": "^4.2.0", "lazystream": "^1.0.0", "lodash.defaults": "^4.2.0", "lodash.difference": "^4.5.0", "lodash.flatten": "^4.4.0", "lodash.isplainobject": "^4.0.6", "lodash.union": "^4.6.0", "normalize-path": "^3.0.0", "readable-stream": "^3.6.0" } }, "sha512-KVgf4XQVrTjhyWmx6cte4RxonPLR9onExufI1jhvw/MQ4BB6IsZD5gT8Lq+u/+pRkWna/6JoHpiQioaqFP5Rzw=="],@@ -3245,20 +3331,22 @@"@scalar/icons/@types/node/undici-types": ["[email protected]", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="],+ "@tailwindcss/postcss/postcss/nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w=="],+"@types/react-grid-layout/react-grid-layout/fast-equals": ["[email protected]", "", {}, "sha512-G3BSX9cfKttjr+2o1O22tYMLq0DPluZnYtq1rXumE1SpL/F/SLIfHx08WYQoWSIpeMYf8sRbJ8++71+v6Pnxfg=="],"@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ=="],"@unhead/bundler/magic-string/@jridgewell/sourcemap-codec": ["@jridgewell/[email protected]", "", {}, "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw=="],- "@vue/compiler-sfc/postcss/nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ=="],-"ai/@ai-sdk/provider-utils/undici": ["[email protected]", "", {}, "sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg=="],"ajv-formats/ajv/json-schema-traverse": ["[email protected]", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],"archiver-utils/readable-stream/string_decoder": ["[email protected]", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],+ "cheerio/parse5/entities": ["[email protected]", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="],+"cmdk/@radix-ui/react-dialog/@radix-ui/primitive": ["@radix-ui/[email protected]", "", {}, "sha512-d86WIWFYNtGA0H/d8exstrTRTp7eWJYlYJbtNofxr/3ljupZYn6EFDG/Qgu/0Kc8v7yMUxySagqJsL1+PdYjWg=="],"cmdk/@radix-ui/react-dialog/@radix-ui/react-context": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-fOE+JtN9rygNZkCnHRBEP0TAvLldlhyOxMsbwFvTP4nAs+nBmfnna+o/Zski2wkmY1YMrFC0aSzsHoLY47iLrg=="],@@ -3319,6 +3407,10 @@"node-fetch/whatwg-url/webidl-conversions": ["[email protected]", "", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="],+ "parse5-htmlparser2-tree-adapter/parse5/entities": ["[email protected]", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="],++ "parse5-parser-stream/parse5/entities": ["[email protected]", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="],+"pretty-format/ansi-styles/color-convert": ["[email protected]", "", { "dependencies": { "color-name": "1.1.3" } }, "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg=="],"prosemirror-markdown/@types/markdown-it/@types/linkify-it": ["@types/[email protected]", "", {}, "sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q=="],@@ -3389,6 +3481,8 @@"unzipper/readable-stream/string_decoder": ["[email protected]", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],+ "web-resource-inliner/htmlparser2/entities": ["[email protected]", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="],+"@typescript-eslint/typescript-estree/minimatch/brace-expansion/balanced-match": ["[email protected]", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],"cmdk/@radix-ui/react-dialog/@radix-ui/react-dismissable-layer/@radix-ui/react-use-callback-ref": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-xCso9j1/u8sEgP1RNHjFrXJLApL8LiqOkI1R4ywuN00rxWdYg4oQXuwKLS3i0j5NWLromUD27/4nlxj2UFVvIw=="],diff --git a/docs/dev/auth.md b/docs/dev/auth.mdindex 11b41c6b..69cc0bb3 100644--- a/docs/dev/auth.md+++ b/docs/dev/auth.md@@ -97,7 +97,9 @@ working session.Authentication email (`src/mail.ts`) goes out through `@repo/mailer` and is best effort: with noprovider configured, or when the provider rejects the message, it logs and returns false, and theendpoint answers as if the mail went out. Three kinds are sent: password reset, address-confirmation, and the magic link. The handler runs on the API origin, so the web app passes+confirmation, and the magic link. Each goes out in the language the address saved, or the+browser's while it has none. God edits the texts and the layout at `/god/email-templates`. The+handler runs on the API origin, so the web app passes`callbackURL`, `redirectTo` and, for a magic link, `errorCallbackURL` in `features/auth/services`.The session confirmation on the Security page sends its own magic link from`features/account/hooks/useConfirmSession.ts`.diff --git a/docs/dev/i18n.md b/docs/dev/i18n.mdindex 66ebcc74..078c5e16 100644--- a/docs/dev/i18n.md+++ b/docs/dev/i18n.md@@ -50,7 +50,7 @@ Make the file in each language directory. Then add the namespace to `coreMessage## How to add a language-There are four locations, and no migration is necessary.+There are five locations, and no migration is necessary.1. Copy `messages/en/` to `apps/web/messages/<code>/` and translate the files. Keep every key:`bun run lint` fails a file with a missing or an extra key. A value left in English is@@ -61,11 +61,14 @@ There are four locations, and no migration is necessary.3. Add the applicable import from `date-fns/locale` to`apps/web/src/hooks/useDateFnsLocale.ts`. If you do not, the month names and the weekdaynames of the calendar stay in English, and no error occurs.-4. Add the code to `LOCALES` in `apps/api/src/modules/user-preferences/locale.ts`, and to `Locale`- in `model.ts`. If you do not, the API refuses the new code with status 422, and the switcher- cannot save it.--A language written right to left is also added to `RTL_LOCALES` in `locales.ts`. See below.+4. Add the code to `LOCALES` in `packages/mailer/src/locale.ts`. If you do not, the API refuses+ the new code, and the switcher cannot save it.+5. Add the emails of the language: a file in `packages/mailer/src/templates/texts/`, listed in+ `LOCALE_TEXTS` in `catalog.ts`. TypeScript types that record by locale, thus an absent entry+ causes a typecheck error.++A language written right to left is also added to `RTL_LOCALES` in `locales.ts` and in+`packages/mailer/src/locale.ts`. See below.The `user_preference.locale` column is a plain `text` column with no CHECK, so the set oflanguages can increase with no change to the schema.diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.tsindex bb755c87..589264c1 100644--- a/packages/auth/src/index.ts+++ b/packages/auth/src/index.ts@@ -26,19 +26,12 @@ import {isOidcUsable,isAccountDeactivated,} from './instance';-import { sendAuthEmail } from './mail';+import { emailLocale, sendAuthEmail } from './mail';import { readAuthExtensions } from './extensions';+import { trustedOrigins } from './origins';-// Frontend origins allowed to call the auth handler. Mandatory config: cookies, the-// WebAuthn relying party and the cookie domain are all derived from it, so a deploy-// that misses it has to fail at startup instead of running on a localhost default.-export const trustedOrigins = (process.env.APP_URL ?? '')- .split(',')- .map((origin) => origin.trim().replace(/\/+$/, ''))- .filter(Boolean);-if (trustedOrigins.length === 0) {- throw new Error('APP_URL is not set: public origin(s) of the web app.');-}+export { trustedOrigins };+export { composeEmail, composeEmailDraft, emailLocale, savedLocaleOf, savedLocales } from './mail';// Parent domain for a cross-subdomain session cookie (".example.com" from// "app.example.com"). Returns undefined for localhost, IPs, or apex domains, where@@ -599,11 +592,11 @@ function createAuth() {// revokeOtherSessions for the same reason.revokeSessionsOnPasswordReset: true,password: extensions.password,- sendResetPassword: async ({ user, url }) => {+ sendResetPassword: async ({ user, url }, request) => {await sendAuthEmail({to: user.email,- subject: 'Reset your password',- text: 'Use the link below to set a new password. Ignore this email if you did not ask for it.',+ template: 'reset',+ locale: await emailLocale(user.email, request),url: withPublicOrigin(url),});},@@ -614,13 +607,13 @@ function createAuth() {// the instance does not require verification.sendOnSignUp: true,autoSignInAfterVerification: true,- sendVerificationEmail: async ({ user, url }) => {+ sendVerificationEmail: async ({ user, url }, request) => {const settings = await getAuthSettings();if (!settings.requireEmailVerification) return;await sendAuthEmail({to: user.email,- subject: 'Confirm your email address',- text: 'Use the link below to confirm this address and finish signing up.',+ template: 'verify',+ locale: await emailLocale(user.email, request),url: withPublicOrigin(url),});},@@ -910,7 +903,7 @@ function createAuth() {magicLink({// Stored plain, an OAuth state also passes as a token (GHSA-965c-763c-88jm).storeToken: 'hashed',- sendMagicLink: async ({ email, url }) => {+ sendMagicLink: async ({ email, url }, ctx) => {const settings = await getAuthSettings();if (!settings.magicLink) {throw new APIError('FORBIDDEN', {@@ -919,8 +912,8 @@ function createAuth() {}await sendAuthEmail({to: email,- subject: 'Your sign-in link',- text: 'Use the link below to sign in. It works once and expires shortly.',+ template: 'magic',+ locale: await emailLocale(email, ctx?.request),url: withPublicOrigin(url),});},@@ -1059,6 +1052,8 @@ export {inviteValidSince,getEmailSettings,setEmailSettings,+ getEmailTemplateSettings,+ setEmailTemplateSettings,resolveEmailConfig,getGoogleSettings,setGoogleSettings,@@ -1084,6 +1079,7 @@ export type {AuthSettings,InstanceEmailDto,InstanceEmailPatch,+ EmailTemplateSettings,InstanceGoogleDto,InstanceGooglePatch,InstanceGoogleConfig,diff --git a/packages/auth/src/instance.ts b/packages/auth/src/instance.tsindex 7ef068bf..40b00143 100644--- a/packages/auth/src/instance.ts+++ b/packages/auth/src/instance.ts@@ -13,7 +13,14 @@ import {type InstanceEmailConfig,} from '@repo/db';import { and, eq, gte, like, lt, sql } from 'drizzle-orm';-import { hasEmailProvider, type SmtpAuth, type SmtpConfig } from '@repo/mailer';+import {+ hasEmailProvider,+ type EmailLayout,+ type EmailText,+ type Locale,+ type SmtpAuth,+ type SmtpConfig,+} from '@repo/mailer';import type { GenericEndpointContext } from 'better-auth';// Authentication settings: who may register, whether email has to be confirmed,@@ -33,6 +40,7 @@ import type { GenericEndpointContext } from 'better-auth';const AUTH_SETTING_KEY = 'auth';const GOOGLE_SECRET_KEY = 'auth.google';const OIDC_SECRET_KEY = 'auth.oidc';+const EMAIL_TEMPLATES_SETTING_KEY = 'email_templates';const scimSecretKey = (workspaceId: number | null) =>workspaceId === null ? 'auth.scim' : `workspace.${workspaceId}.scim`;@@ -289,6 +297,28 @@ export async function setEmailSettings(patch: InstanceEmailPatch): Promise<Instareturn redacted;}+// ── Email templates ───────────────────────────────────────────────────────────++// What god changed in the emails. Only the changes are stored: a template and language with no+// entry, and a null layout, send the built-in ones from @repo/mailer.+export interface EmailTemplateSettings {+ texts: Record<string, Partial<Record<Locale, EmailText>>>;+ layout: EmailLayout | null;+}++export async function getEmailTemplateSettings(): Promise<EmailTemplateSettings> {+ return (+ (await getSetting<EmailTemplateSettings>(EMAIL_TEMPLATES_SETTING_KEY)) ?? {+ texts: {},+ layout: null,+ }+ );+}++export async function setEmailTemplateSettings(settings: EmailTemplateSettings): Promise<void> {+ await setSetting(EMAIL_TEMPLATES_SETTING_KEY, settings);+}+// ── Google OAuth ──────────────────────────────────────────────────────────────// The stored, decrypted credentials. Read by the Google provider in ./index.ts ondiff --git a/packages/auth/src/mail.ts b/packages/auth/src/mail.tsindex 7f290f8f..23407007 100644--- a/packages/auth/src/mail.ts+++ b/packages/auth/src/mail.ts@@ -1,5 +1,90 @@-import { sendEmail, emailBody } from '@repo/mailer';-import { getInstanceEmailConfig } from '@repo/db';+import {+ DEFAULT_EMAIL_LAYOUT,+ defaultEmailText,+ emailTemplate,+ isLocale,+ localeFromAcceptLanguage,+ renderEmail,+ sendEmail,+ type CoreEmailKey,+ type EmailLayout,+ type EmailSite,+ type EmailTemplate,+ type EmailText,+ type Locale,+ type RenderedEmail,+} from '@repo/mailer';+import { db, getInstanceEmailConfig, user, userPreference } from '@repo/db';+import { eq, inArray } from 'drizzle-orm';+import { getEmailTemplateSettings } from './instance';+import { trustedOrigins } from './origins';++function emailSite(): EmailSite {+ const url = trustedOrigins[0];+ return { name: "It's a Plan", url, logoUrl: `${url}/icon-192.png` };+}++export async function composeEmail(+ key: string,+ locale: Locale,+ vars: Record<string, string> = {},+ url?: string,+): Promise<RenderedEmail> {+ const template = emailTemplate(key);+ if (!template) throw new Error(`Unknown email template "${key}".`);+ const settings = await getEmailTemplateSettings();+ return renderEmail({+ text: settings.texts[key]?.[locale] ?? defaultEmailText(template, locale),+ layout: settings.layout ?? DEFAULT_EMAIL_LAYOUT,+ locale,+ vars,+ url,+ site: emailSite(),+ });+}++export function composeEmailDraft(+ template: EmailTemplate,+ draft: { locale: Locale; text: EmailText; layout: EmailLayout },+): RenderedEmail {+ const site = emailSite();+ return renderEmail({+ ...draft,+ vars: template.samples,+ url: template.samplePath && new URL(template.samplePath, site.url).toString(),+ site,+ });+}++// The language each account saved. An account that has not opened the app yet has no row.+export async function savedLocales(userIds: string[]): Promise<Map<string, Locale>> {+ if (userIds.length === 0) return new Map();+ const rows = await db+ .select({ userId: userPreference.userId, locale: userPreference.locale })+ .from(userPreference)+ .where(inArray(userPreference.userId, userIds));+ const locales = new Map<string, Locale>();+ for (const row of rows) {+ if (isLocale(row.locale)) locales.set(row.userId, row.locale);+ }+ return locales;+}++export async function savedLocaleOf(email: string): Promise<Locale | null> {+ const [row] = await db+ .select({ locale: userPreference.locale })+ .from(userPreference)+ .innerJoin(user, eq(user.id, userPreference.userId))+ .where(eq(user.email, email.toLowerCase()));+ return isLocale(row?.locale) ? row.locale : null;+}++// The language an address chose, or the language of the browser asking when it has none yet:+// someone signing up or an address with no account.+export async function emailLocale(email: string, request?: Request): Promise<Locale> {+ const saved = await savedLocaleOf(email);+ return saved ?? localeFromAcceptLanguage(request?.headers.get('accept-language') ?? null);+}// Authentication email: password reset, address verification, magic link. It uses// the instance mail provider configured in god mode, which is separate from the@@ -11,22 +96,17 @@ import { getInstanceEmailConfig } from '@repo/db';// must not turn into a failed sign-in flow that leaks whether an account exists.export async function sendAuthEmail(input: {to: string;- subject: string;- text: string;- url?: string;+ template: CoreEmailKey;+ locale: Locale;+ url: string;}): Promise<boolean> {const config = await getInstanceEmailConfig();if (!config) {- console.warn('[auth] no email provider configured, dropping mail:', input.subject);+ console.warn('[auth] no email provider configured, dropping mail:', input.template);return false;}- const { text, html } = emailBody(input.text, input.url);- const result = await sendEmail(config, {- to: input.to,- subject: input.subject,- text,- html,- });+ const email = await composeEmail(input.template, input.locale, {}, input.url);+ const result = await sendEmail(config, { to: input.to, ...email });if (!result.ok) console.error('[auth] email send failed:', result.error);return result.ok;}diff --git a/packages/auth/src/origins.ts b/packages/auth/src/origins.tsnew file mode 100644index 00000000..d26491a4--- /dev/null+++ b/packages/auth/src/origins.ts@@ -0,0 +1,10 @@+// Frontend origins allowed to call the auth handler. Mandatory config: cookies, the+// WebAuthn relying party and the cookie domain are all derived from it, so a deploy+// that misses it has to fail at startup instead of running on a localhost default.+export const trustedOrigins = (process.env.APP_URL ?? '')+ .split(',')+ .map((origin) => origin.trim().replace(/\/+$/, ''))+ .filter(Boolean);+if (trustedOrigins.length === 0) {+ throw new Error('APP_URL is not set: public origin(s) of the web app.');+}diff --git a/packages/db/src/schema/app.ts b/packages/db/src/schema/app.tsindex 5b3edf79..5b03250d 100644--- a/packages/db/src/schema/app.ts+++ b/packages/db/src/schema/app.ts@@ -1150,12 +1150,11 @@ export const userTelegramAccount = pgTable(// ('email' picks SMTP or Resend from the team config). recipient is the member's// email address for email rows, or their Telegram chat id for telegram rows.// The stored message on a notification_delivery row, composed at enqueue time by the-// api and read by the worker that sends it. `subject`/`html` are channel-specific:-// email uses `subject` and builds its own HTML from `text`; Telegram sends `html`-// (parse_mode HTML) and falls back to `text`. The sender appends `url` to plain-text-// bodies. `dedupeKey` is what the enqueue side matches to avoid queuing the same-// message twice; `projectInviteId` ties an invite email to its invite, so a delivery-// whose invite is no longer pending is dropped instead of sent.+// api and read by the worker that sends it. Email uses `subject` and sends `html` as composed;+// for a row without `html` the sender appends `url` to `text` and wraps it. Telegram sends+// `html` (parse_mode HTML) and falls back to `text`. `dedupeKey` is what the enqueue side+// matches to avoid queuing the same message twice; `projectInviteId` ties an invite email to+// its invite, so a delivery whose invite is no longer pending is dropped instead of sent.export interface DeliveryPayload {subject?: string;text: string;diff --git a/packages/mailer/package.json b/packages/mailer/package.jsonindex 92e67f6f..0be4c153 100644--- a/packages/mailer/package.json+++ b/packages/mailer/package.json@@ -8,9 +8,12 @@},"scripts": {"lint": "eslint .",+ "test": "bun test","typecheck": "tsc --noEmit"},"dependencies": {+ "juice": "^12.2.1",+ "marked": "^18.1.1","nodemailer": "^10.1.0"},"devDependencies": {diff --git a/apps/api/src/modules/user-preferences/__tests__/unit/locale.test.ts b/packages/mailer/src/__tests__/locale.test.tssimilarity index 96%rename from apps/api/src/modules/user-preferences/__tests__/unit/locale.test.tsrename to packages/mailer/src/__tests__/locale.test.tsindex 9fbd8f94..f1cb867b 100644--- a/apps/api/src/modules/user-preferences/__tests__/unit/locale.test.ts+++ b/packages/mailer/src/__tests__/locale.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'bun:test';-import { localeFromAcceptLanguage } from '../../locale';+import { localeFromAcceptLanguage } from '../locale';describe('localeFromAcceptLanguage', () => {it('uses the preferred supported language', () => {diff --git a/packages/mailer/src/__tests__/render.test.ts b/packages/mailer/src/__tests__/render.test.tsnew file mode 100644index 00000000..f7881341--- /dev/null+++ b/packages/mailer/src/__tests__/render.test.ts@@ -0,0 +1,311 @@+import { describe, expect, it } from 'bun:test';+import {+ DEFAULT_EMAIL_LAYOUT,+ LOCALES,+ defaultEmailText,+ emailTemplate,+ emailTemplates,+ missingLayoutPlaceholders,+ renderEmail,+ setExtraEmailTemplates,+ unknownEmailVariables,+ unknownLayoutPlaceholders,+ type EmailLayout,+ type EmailText,+ type Locale,+} from '../index';++const site = {+ name: "It's a Plan",+ url: 'https://plan.test',+ logoUrl: 'https://plan.test/logo.png',+};+const bare: EmailLayout = { html: '<html><body>{content}{button}</body></html>', css: '' };++function render(+ text: Partial<EmailText>,+ options: {+ vars?: Record<string, string>;+ url?: string | null;+ locale?: Locale;+ layout?: EmailLayout;+ } = {},+) {+ return renderEmail({+ text: { subject: 'Subject', body: 'Body', button: 'Open', ...text },+ layout: options.layout ?? bare,+ locale: options.locale ?? 'en',+ vars: options.vars ?? {},+ url: options.url,+ site,+ });+}++describe('renderEmail', () => {+ it('fills the variables in the subject, the text and the button', () => {+ const email = render(+ { subject: '{ref}: new', body: '{actor} commented', button: 'Open {ref}' },+ { vars: { ref: 'WEB-1', actor: 'Maria' }, url: 'https://plan.test/i/1' },+ );+ expect(email.subject).toBe('WEB-1: new');+ expect(email.text).toBe('Maria commented\n\nhttps://plan.test/i/1');+ expect(email.html).toContain('<p>Maria commented</p>');+ expect(email.html).toContain('>Open WEB-1</a>');+ });++ it('escapes a value and keeps its Markdown as text', () => {+ const title = '<img src=x onerror=alert(1)> **bold** [link](https://evil.test)';+ const email = render({ body: '**{title}**' }, { vars: { title } });+ expect(email.html).toContain(+ '<strong><img src=x onerror=alert(1)> **bold** [link](https://evil.test)</strong>',+ );+ expect(email.html).not.toContain('<img');+ expect(email.html).not.toContain('href="https://evil.test"');+ expect(email.text).toBe(title);+ });++ it('keeps a value inside a single-quoted attribute of a layout', () => {+ const html =+ "<html><head><meta name='x' content='{subject}'></head><body>{content}{button}</body></html>";+ const email = render(+ { subject: '{title}' },+ { vars: { title: "' onload='alert(1)" }, layout: { html, css: '' } },+ );+ expect(email.html).not.toContain('onload="');+ });++ it('does not expand a variable that a value holds', () => {+ const email = render({ body: '{title} {ref}' }, { vars: { title: '{ref}', ref: 'WEB-1' } });+ expect(email.text).toBe('{ref} WEB-1');+ });++ it('leaves a name with no value in place, also one every object inherits', () => {+ expect(render({ body: '{nothing} {constructor}' }).text).toBe('{nothing} {constructor}');+ });++ it('keeps a subject on one line', () => {+ const email = render({ subject: '{title}' }, { vars: { title: 'One\r\nBcc: [email protected]' } });+ expect(email.subject).toBe('One Bcc: [email protected]');+ });++ it('keeps the line breaks of a value in the HTML', () => {+ const email = render({ body: '{quote}' }, { vars: { quote: 'one\ntwo' } });+ expect(email.html).toContain('one<br>two');+ });++ it('renders the Markdown of the text, and leaves plain words in the text part', () => {+ const body = [+ '# Title',+ '',+ '**Bold**, *italic*, ~~gone~~ and [a link](https://plan.test/a).',+ '',+ '- one',+ '- two',+ '',+ '1. first',+ '2. second',+ '',+ '> quoted',+ '',+ 'R&D <team>',+ ].join('\n');+ const email = render({ body });+ expect(email.html).toContain('<h1>Title</h1>');+ expect(email.html).toContain('<strong>Bold</strong>');+ expect(email.html).toContain('<a href="https://plan.test/a">a link</a>');+ expect(email.html).toContain('<li>one</li>');+ expect(email.html).toContain('<blockquote>');+ expect(email.html).toContain('R&D');+ expect(email.html).not.toContain('<team>');+ expect(email.text).toBe(+ [+ 'Title',+ '',+ 'Bold, italic, gone and a link (https://plan.test/a).',+ '',+ '- one',+ '- two',+ '',+ '1. first',+ '2. second',+ '',+ 'quoted',+ '',+ 'R&D <team>',+ ].join('\n'),+ );+ });++ it('fills a variable in a link address, encoded, in both parts', () => {+ const body = '[Help](https://plan.test/{ref}) and https://plan.test/{ref}';+ const email = render({ body }, { vars: { ref: 'A B/1' } });+ expect(email.html).toContain('<a href="https://plan.test/A%20B%2F1">Help</a>');+ expect(email.text).toBe('Help (https://plan.test/A%20B%2F1) and https://plan.test/A%20B%2F1');+ });++ it('keeps a value in a link address from changing its scheme', () => {+ const email = render({ body: '[Open]({title})' }, { vars: { title: 'javascript:alert(1)' } });+ expect(email.html).toContain('<a href="javascript%3Aalert(1)">Open</a>');+ });++ it('keeps the link when the button has no text', () => {+ const email = render({ button: '' }, { url: 'https://plan.test/reset' });+ expect(email.html).not.toContain('class="button"');+ expect(email.html).toContain('href="https://plan.test/reset"');+ expect(email.text).toEndWith('https://plan.test/reset');+ });++ it('adds no button to an email with no link', () => {+ const email = render({}, { url: null });+ expect(email.html).not.toContain('<a ');+ expect(email.text).toBe('Body');+ });++ it('names the link in the language of the email', () => {+ const email = render({}, { url: 'https://plan.test/a', locale: 'ru' });+ expect(email.html).toContain('Или откройте ссылку:');+ });++ it('fills the layout and writes its CSS onto the elements', () => {+ const email = render(+ {},+ {+ locale: 'ar',+ layout: {+ html: '<html lang="{lang}" dir="{dir}"><head><title>{subject}</title></head><body class="page">{content}{button}<footer>{site_name} {site_url}</footer></body></html>',+ css: '.page { margin: 0; }\n@media (max-width: 600px) { .page { margin: 4px; } }',+ },+ },+ );+ expect(email.html).toContain('lang="ar"');+ expect(email.html).toContain('dir="rtl"');+ expect(email.html).toContain('<title>Subject</title>');+ expect(email.html).toContain('class="page" style="margin: 0;"');+ expect(email.html).toContain('@media (max-width: 600px)');+ expect(email.html).toContain('It's a Plan https://plan.test');+ });++ it('renders the default layout', () => {+ const email = render({}, { layout: DEFAULT_EMAIL_LAYOUT, url: 'https://plan.test/a' });+ expect(email.html).toContain('class="button"');+ expect(email.html).toContain('src="https://plan.test/logo.png"');+ expect(email.html).not.toContain('{');+ });+});++describe('unknownEmailVariables', () => {+ it('writes tables, task lists, nested lists and addresses as plain words in the text part', () => {+ const body = [+ '| Name | Role |',+ '| --- | --- |',+ '| Maria | Owner |',+ '',+ '- [x] done',+ '- [ ] to do',+ '',+ 'Then:',+ '',+ '1. a',+ ' - b',+ ' - c',+ '2. d',+ '',+ 'Write to [email protected].',+ ].join('\n');+ expect(render({ body }).text).toBe(+ [+ 'Name | Role',+ 'Maria | Owner',+ '',+ '- [x] done',+ '- [ ] to do',+ '',+ 'Then:',+ '',+ '1. a',+ ' - b',+ ' - c',+ '2. d',+ '',+ 'Write to [email protected].',+ ].join('\n'),+ );+ });++ it('names each variable the template does not have, once', () => {+ const text = { subject: '{ref} {nope}', body: '{nope} {other}', button: '{last}' };+ expect(unknownEmailVariables(text, ['ref'])).toEqual(['nope', 'other', 'last']);+ });+});++describe('the layout', () => {+ it('names the placeholders it still needs', () => {+ expect(missingLayoutPlaceholders('<p>{content}</p>')).toEqual(['button']);+ expect(missingLayoutPlaceholders('{content}{button}')).toEqual([]);+ });++ it('names the placeholders nothing fills, and leaves CSS alone', () => {+ const html = '<style>a{color:red}</style>{content}{logo}{logo}{site_name}';+ expect(unknownLayoutPlaceholders(html)).toEqual(['logo']);+ expect(unknownLayoutPlaceholders(DEFAULT_EMAIL_LAYOUT.html)).toEqual([]);+ });+});++describe('the default texts', () => {+ const namesIn = (text: EmailText) =>+ [...`${text.subject} ${text.body} ${text.button}`.matchAll(/\{(\w+)\}/g)]+ .map((match) => match[1])+ .sort();++ it('use only the variables their template declares, the same ones in every language', () => {+ for (const template of emailTemplates()) {+ const english = namesIn(template.texts.en);+ expect(english.filter((name) => !(name in template.samples))).toEqual([]);+ for (const locale of LOCALES) {+ const names = namesIn(defaultEmailText(template, locale));+ expect({ template: template.key, locale, names: [...new Set(names)] }).toEqual({+ template: template.key,+ locale,+ names: [...new Set(english)],+ });+ }+ }+ });++ it('have a subject and a text in every language, and a button where there is a link', () => {+ for (const template of emailTemplates()) {+ for (const locale of LOCALES) {+ const text = defaultEmailText(template, locale);+ expect(text.subject).not.toBe('');+ expect(text.body).not.toBe('');+ expect(text.button !== '').toBe(template.samplePath !== null);+ }+ }+ });+});++describe('setExtraEmailTemplates', () => {+ const extra = {+ key: 'formReply',+ group: 'forms',+ samples: { title: 'A request' },+ samplePath: '/p/requests/example',+ texts: { en: { subject: 'New reply: {title}', body: '{title}', button: 'Open' } },+ };++ it('adds templates beside the core ones, and a language it lacks sends English', () => {+ setExtraEmailTemplates([extra]);+ expect(emailTemplate('formReply')).toBe(extra);+ expect(defaultEmailText(extra, 'ru').subject).toBe('New reply: {title}');+ setExtraEmailTemplates([]);+ expect(emailTemplate('formReply')).toBeUndefined();+ expect(emailTemplate('reset')).toBeDefined();+ });++ it('refuses a key already taken and keeps the previous set', () => {+ setExtraEmailTemplates([extra]);+ expect(() => setExtraEmailTemplates([{ ...extra, key: 'reset' }])).toThrow('reset');+ expect(emailTemplate('formReply')).toBe(extra);+ setExtraEmailTemplates([]);+ });+});diff --git a/packages/mailer/src/index.ts b/packages/mailer/src/index.tsindex a83b8adf..fa3015af 100644--- a/packages/mailer/src/index.ts+++ b/packages/mailer/src/index.ts@@ -1,9 +1,16 @@import nodemailer from 'nodemailer';+import { escapeHtml } from './templates/render';++export * from './locale';+export * from './templates/catalog';+export * from './templates/layout';+export * from './templates/render';+export type { CoreEmailKey, EmailText, EmailWords } from './templates/types';// Outbound email transport, shared by the two senders in the app: project// notifications (credentials per project) and authentication mail (credentials per-// instance). Only the transport lives here. Where the credentials come from, how-// they are stored, and what the message says belong to the caller.+// instance). Where the credentials come from and how they are stored belong to the+// caller. ./templates holds what the emails say and how they look.const HTTP_TIMEOUT_MS = 15_000;@@ -71,6 +78,15 @@ function fromAddress(config: EmailConfig, provider: 'smtp' | 'resend'): string |return null;}+function smtpReady(smtp: SmtpConfig): boolean {+ return smtp.enabled && smtp.host.length > 0;+}++// The address an email goes out from, with the provider sendEmail would pick.+export function senderAddress(config: EmailConfig): string | null {+ return fromAddress(config, smtpReady(config.smtp) ? 'smtp' : 'resend');+}+class TokenError extends Error {constructor(message: string,@@ -229,10 +245,7 @@ async function sendResend(// True when the config has a usable provider. Callers use it to disable features// that depend on outbound email instead of queuing mail that cannot be sent.export function hasEmailProvider(config: EmailConfig): boolean {- return (- (config.smtp.enabled && config.smtp.host.length > 0) ||- (config.resend.enabled && config.resend.apiKey.length > 0)- );+ return smtpReady(config.smtp) || (config.resend.enabled && config.resend.apiKey.length > 0);}// Sends one message with the first enabled provider: SMTP wins over Resend when@@ -240,7 +253,7 @@ export function hasEmailProvider(config: EmailConfig): boolean {export async function sendEmail(config: EmailConfig, message: EmailMessage): Promise<SendResult> {if (!message.to) return { ok: false, retryable: false, error: 'no recipient' };const { smtp, resend } = config;- if (smtp.enabled && smtp.host.length > 0) {+ if (smtpReady(smtp)) {const from = fromAddress(config, 'smtp');if (!from) return { ok: false, retryable: false, error: 'no From address for SMTP' };return sendSmtp(smtp, message, from);@@ -253,19 +266,11 @@ export async function sendEmail(config: EmailConfig, message: EmailMessage): Proreturn { ok: false, retryable: false, error: 'no email provider enabled' };}-function escape(s: string): string {- return s- .replace(/&/g, '&')- .replace(/</g, '<')- .replace(/>/g, '>')- .replace(/"/g, '"');-}-// Wraps a plain-text body (and an optional link) into the text/html pair the-// transport needs. Shared so every message in the app looks the same.+// transport needs, for a message that has no template.export function emailBody(text: string, url?: string | null): { text: string; html: string } {const plain = url ? `${text}\n\n${url}` : text;- const body = escape(text).replace(/\n/g, '<br>');- const link = url ? `<p><a href="${escape(url)}">${escape(url)}</a></p>` : '';+ const body = escapeHtml(text).replace(/\n/g, '<br>');+ const link = url ? `<p><a href="${escapeHtml(url)}">${escapeHtml(url)}</a></p>` : '';return { text: plain, html: `<p>${body}</p>${link}` };}diff --git a/apps/api/src/modules/user-preferences/locale.ts b/packages/mailer/src/locale.tssimilarity index 74%rename from apps/api/src/modules/user-preferences/locale.tsrename to packages/mailer/src/locale.tsindex 8d3f0de5..97475f48 100644--- a/apps/api/src/modules/user-preferences/locale.ts+++ b/packages/mailer/src/locale.ts@@ -1,3 +1,5 @@+// The languages the interface and the emails ship with. The web app keeps its own copy of+// this list and of the matcher below: it never imports a package.export const LOCALES = ['en','uk',@@ -18,6 +20,16 @@ export type Locale = (typeof LOCALES)[number];export const DEFAULT_LOCALE: Locale = 'en';+export function isLocale(value: string | null | undefined): value is Locale {+ return value != null && (LOCALES as readonly string[]).includes(value);+}++const RTL_LOCALES: readonly Locale[] = ['ar', 'fa'];++export function localeDirection(locale: Locale): 'ltr' | 'rtl' {+ return RTL_LOCALES.includes(locale) ? 'rtl' : 'ltr';+}+// Keep this matcher aligned with the Web copy so the first server render and// an account without saved preferences resolve to the same language.export function localeFromAcceptLanguage(value: string | null): Locale {diff --git a/packages/mailer/src/templates/catalog.ts b/packages/mailer/src/templates/catalog.tsnew file mode 100644index 00000000..69f0a689--- /dev/null+++ b/packages/mailer/src/templates/catalog.ts@@ -0,0 +1,123 @@+import { LOCALES, type Locale } from '../locale';+import type { CoreEmailKey, EmailLocaleTexts, EmailText, EmailWords } from './types';+import { ar } from './texts/ar';+import { en } from './texts/en';+import { esES } from './texts/es-ES';+import { fa } from './texts/fa';+import { fr } from './texts/fr';+import { id } from './texts/id';+import { ko } from './texts/ko';+import { ptBR } from './texts/pt-BR';+import { ru } from './texts/ru';+import { tr } from './texts/tr';+import { uk } from './texts/uk';+import { zhCN } from './texts/zh-CN';+import { zhTW } from './texts/zh-TW';++const LOCALE_TEXTS: Record<Locale, EmailLocaleTexts> = {+ en,+ uk,+ ru,+ 'zh-CN': zhCN,+ 'zh-TW': zhTW,+ ar,+ fa,+ fr,+ 'pt-BR': ptBR,+ id,+ 'es-ES': esES,+ ko,+ tr,+};++// What makes an email editable in god mode. The god mode page reads its name and its group's+// from the messages `god.emailTemplates.templates.<key>` and `.groups.<group>`.+export interface EmailTemplate {+ key: string;+ group: string;+ // The {names} its text may use, with the value each one has in the preview.+ samples: Record<string, string>;+ // Where its link goes in the preview. Null for an email with no link and no button.+ samplePath: string | null;+ // English is required. A language with no text of its own sends the English one.+ texts: { en: EmailText } & Partial<Record<Locale, EmailText>>;+}++const ISSUE = { actor: 'Maria Lopez', ref: 'WEB-42', title: 'Fix the login redirect' };+const DOCUMENT = { actor: 'Maria Lopez', document: 'Q3 launch plan' };++function core(+ key: CoreEmailKey,+ group: string,+ samples: Record<string, string>,+ samplePath: string | null,+): EmailTemplate {+ const texts = Object.fromEntries(LOCALES.map((l) => [l, LOCALE_TEXTS[l].templates[key]]));+ return { key, group, samples, samplePath, texts: texts as EmailTemplate['texts'] };+}++const CORE_TEMPLATES: EmailTemplate[] = [+ core('reset', 'signIn', {}, '/reset-password?token=example'),+ core('verify', 'signIn', {}, '/verify-email?token=example'),+ core('magic', 'signIn', {}, '/magic-link?token=example'),+ core(+ 'inviteProject',+ 'invitations',+ { inviter: 'Maria Lopez', project: 'Website redesign', role: 'member' },+ '/invite/example',+ ),+ core(+ 'inviteTeam',+ 'invitations',+ { inviter: 'Maria Lopez', team: 'Acme', role: 'member' },+ '/invite/example',+ ),+ core('assigned', 'notifications', ISSUE, '/acme/WEB/issue/42'),+ core('mentioned', 'notifications', ISSUE, '/acme/WEB/issue/42'),+ core('commented', 'notifications', ISSUE, '/acme/WEB/issue/42#comment-7'),+ core(+ 'stateChanged',+ 'notifications',+ { ...ISSUE, from: 'In progress', to: 'Done' },+ '/acme/WEB/issue/42',+ ),+ core('documentMentioned', 'notifications', DOCUMENT, '/acme/WEB/documents/7'),+ core('documentCommentMentioned', 'notifications', DOCUMENT, '/acme/WEB/documents/7'),+ core('test', 'service', {}, null),+];++let templates = CORE_TEMPLATES;++// The templates of an edition's own emails, beside the core's: they get the god mode editor,+// the layout and the languages as they are, and go out through composeEmail in @repo/auth.+// Each call replaces the previous ones; a key already taken throws and the previous set+// stays. What god saved for a template that goes away stays stored.+export function setExtraEmailTemplates(extra: EmailTemplate[]): void {+ const next = [...CORE_TEMPLATES, ...extra];+ const keys = new Set<string>();+ for (const { key } of next) {+ if (keys.has(key)) throw new Error(`Duplicate email template key "${key}".`);+ keys.add(key);+ }+ templates = next;+}++export function emailTemplates(): EmailTemplate[] {+ return templates;+}++export function emailTemplate(key: string): EmailTemplate | undefined {+ return templates.find((template) => template.key === key);+}++export function defaultEmailText(template: EmailTemplate, locale: Locale): EmailText {+ return template.texts[locale] ?? template.texts.en;+}++export function emailLinkHint(locale: Locale): string {+ return LOCALE_TEXTS[locale].linkHint;+}++export function emailWords(locale: Locale): EmailWords {+ return LOCALE_TEXTS[locale].words;+}diff --git a/packages/mailer/src/templates/layout.ts b/packages/mailer/src/templates/layout.tsnew file mode 100644index 00000000..8747642c--- /dev/null+++ b/packages/mailer/src/templates/layout.ts@@ -0,0 +1,96 @@+export interface EmailLayout {+ html: string;+ css: string;+}++const DEFAULT_HTML = `<!doctype html>+<html lang="{lang}" dir="{dir}">+<head>+ <meta charset="utf-8">+ <title>{subject}</title>+</head>+<body class="page">+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" class="wrap">+ <tr><td align="center">+ <table role="presentation" width="560" cellpadding="0" cellspacing="0" class="card" dir="{dir}">+ <tr><td class="header">+ <img src="{logo_url}" alt="{site_name}" height="24">+ </td></tr>+ <tr><td class="content">+ {content}+ {button}+ </td></tr>+ <tr><td class="footer">+ {site_name} · {site_url}+ </td></tr>+ </table>+ </td></tr>+ </table>+</body>+</html>`;++const DEFAULT_CSS = `.page {+ margin: 0;+ background: #f4f4f5;+ font-family: -apple-system, 'Segoe UI', Roboto, sans-serif;+}+.wrap { padding: 32px 16px; }+.card {+ width: 100%;+ max-width: 560px;+ background: #ffffff;+ border-radius: 12px;+}+.header { padding: 24px 32px 0; }+.content {+ padding: 24px 32px;+ color: #1c1c1c;+ font-size: 15px;+ line-height: 1.6;+}+.content p, .content ul, .content ol { margin: 0 0 14px; }+.content h1 { margin: 0 0 14px; font-size: 22px; line-height: 1.3; }+.content h2 { margin: 0 0 14px; font-size: 18px; line-height: 1.35; }+.content blockquote {+ margin: 0 0 14px;+ padding-inline-start: 12px;+ border-inline-start: 3px solid #e2e2e2;+ color: #555555;+}+.button {+ display: inline-block;+ padding: 10px 18px;+ border-radius: 8px;+ background: #262626;+ color: #fafafa;+ text-decoration: none;+}+.link {+ color: #6b6b6b;+ font-size: 12px;+ word-break: break-all;+}+.footer {+ padding: 0 32px 24px;+ color: #8a8a8a;+ font-size: 12px;+}`;++export const DEFAULT_EMAIL_LAYOUT: EmailLayout = { html: DEFAULT_HTML, css: DEFAULT_CSS };++export const LAYOUT_PLACEHOLDERS = [+ { name: 'content', required: true },+ { name: 'button', required: true },+ { name: 'subject', required: false },+ { name: 'lang', required: false },+ { name: 'dir', required: false },+ { name: 'site_name', required: false },+ { name: 'site_url', required: false },+ { name: 'logo_url', required: false },+];++export function missingLayoutPlaceholders(html: string): string[] {+ return LAYOUT_PLACEHOLDERS.filter((p) => p.required && !html.includes(`{${p.name}}`)).map(+ (p) => p.name,+ );+}diff --git a/packages/mailer/src/templates/render.ts b/packages/mailer/src/templates/render.tsnew file mode 100644index 00000000..82faa4cc--- /dev/null+++ b/packages/mailer/src/templates/render.ts@@ -0,0 +1,207 @@+import juice from 'juice';+import { Marked, type Token, type Tokens } from 'marked';+import { localeDirection, type Locale } from '../locale';+import { emailLinkHint } from './catalog';+import { LAYOUT_PLACEHOLDERS, type EmailLayout } from './layout';+import type { EmailText } from './types';++export interface EmailSite {+ name: string;+ url: string;+ logoUrl: string;+}++export interface RenderedEmail {+ subject: string;+ text: string;+ html: string;+}++export function escapeHtml(s: string): string {+ return s+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');+}++// The text of an email is Markdown. HTML typed into it stays text: markup belongs to the layout.+const htmlMarkdown = new Marked({+ breaks: true,+ renderer: {+ html({ text }) {+ return escapeHtml(text);+ },+ },+});++const plainMarkdown = new Marked({+ breaks: true,+ renderer: {+ heading({ tokens }) {+ return `${this.parser.parseInline(tokens)}\n\n`;+ },+ paragraph({ tokens }) {+ return `${this.parser.parseInline(tokens)}\n\n`;+ },+ blockquote({ tokens }) {+ return this.parser.parse(tokens);+ },+ list({ items, ordered, start }) {+ const first = typeof start === 'number' ? start : 1;+ const lines = items.map((item, index) => {+ const marker = ordered ? `${first + index}.` : '-';+ const parts = item.tokens.map((token) => {+ const part = this.parser.parse([token]);+ return token.type === 'list' ? `\n${part.trim().replace(/^/gm, ' ')}\n` : part;+ });+ return `${marker} ${parts+ .join('')+ .replace(/\n{2,}/g, '\n')+ .trim()}`;+ });+ return `${lines.join('\n')}\n\n`;+ },+ checkbox({ checked }) {+ return checked ? '[x] ' : '[ ] ';+ },+ table({ header, rows }) {+ const line = (cells: Tokens.TableCell[]) =>+ cells.map((cell) => this.parser.parseInline(cell.tokens)).join(' | ');+ return `${[header, ...rows].map(line).join('\n')}\n\n`;+ },+ strong({ tokens }) {+ return this.parser.parseInline(tokens);+ },+ em({ tokens }) {+ return this.parser.parseInline(tokens);+ },+ del({ tokens }) {+ return this.parser.parseInline(tokens);+ },+ link({ tokens, href, raw }) {+ const label = this.parser.parseInline(tokens);+ if (label === href.replace(/^mailto:/, '')) return label;+ return label === raw ? href : `${label} (${href})`;+ },+ image({ text }) {+ return text;+ },+ codespan({ text }) {+ return text;+ },+ code({ text }) {+ return `${text}\n\n`;+ },+ br() {+ return '\n';+ },+ hr() {+ return '';+ },+ html({ text }) {+ return text;+ },+ text(token) {+ return 'tokens' in token && token.tokens ? this.parser.parseInline(token.tokens) : token.text;+ },+ },+});++const VARIABLE = /\{(\w+)\}/g;++// One pass, so a value that holds "{ref}" stays as it is. A name with no value stays too.+function fill(text: string, value: (name: string) => string | undefined): string {+ return text.replace(VARIABLE, (match, name: string) => value(name) ?? match);+}++function unknownNames(written: string, names: string[]): string[] {+ const used = [...written.matchAll(VARIABLE)].map((match) => match[1]);+ return [...new Set(used)].filter((name) => !names.includes(name));+}++// Saving refuses a name that nothing fills: a recipient would read it as it is written.+export function unknownEmailVariables(text: EmailText, variables: string[]): string[] {+ return unknownNames(`${text.subject} ${text.body} ${text.button}`, variables);+}++export function unknownLayoutPlaceholders(html: string): string[] {+ return unknownNames(+ html,+ LAYOUT_PLACEHOLDERS.map((placeholder) => placeholder.name),+ );+}++// Marked encodes an address before a renderer gets it, and fill then cannot find {ref} there.+// The value goes in first, encoded, so a title stays part of the address and cannot change+// its scheme.+function fillAddresses(value: (name: string) => string | undefined) {+ return (token: Token) => {+ if (token.type !== 'link' && token.type !== 'image') return;+ token.href = fill(token.href, (name) => {+ const raw = value(name);+ return raw === undefined ? undefined : encodeURIComponent(raw);+ });+ };+}++function actionHtml(label: string, url: string, locale: Locale): string {+ const href = escapeHtml(url);+ const link = `<a href="${href}" dir="ltr">${href}</a>`;+ if (!label) return `<p class="link">${link}</p>`;+ return (+ `<p><a class="button" href="${href}">${escapeHtml(label)}</a></p>` ++ `<p class="link">${escapeHtml(emailLinkHint(locale))} ${link}</p>`+ );+}++function withStyles(html: string, css: string): string {+ const style = `<style>${css}</style>`;+ // A replacer function, so a `$` in the CSS is not read as a replacement pattern.+ return html.includes('</head>') ? html.replace('</head>', () => `${style}</head>`) : style + html;+}++// The values come from people (a name, an issue title), so they go in after the Markdown is+// read and are escaped there: a title never turns into a link or a tag. A subject takes one+// line, since it becomes a header.+export function renderEmail(input: {+ text: EmailText;+ layout: EmailLayout;+ locale: Locale;+ vars: Record<string, string>;+ url?: string | null;+ site: EmailSite;+}): RenderedEmail {+ const { text, layout, locale, vars, url, site } = input;+ const value = (name: string) => (Object.hasOwn(vars, name) ? vars[name] : undefined);+ const htmlValue = (name: string) => {+ const raw = value(name);+ return raw === undefined ? undefined : escapeHtml(raw).replace(/\n/g, '<br>');+ };++ const subject = fill(text.subject, (name) => value(name)?.replace(/[\r\n]+/g, ' '));+ const parseOptions = { async: false, walkTokens: fillAddresses(value) } as const;+ const plain = fill(plainMarkdown.parse(text.body, parseOptions).trim(), value);+ const parts: Record<string, string> = {+ content: fill(htmlMarkdown.parse(text.body, parseOptions), htmlValue),+ button: url ? actionHtml(fill(text.button, value), url, locale) : '',+ subject: escapeHtml(subject),+ lang: locale,+ dir: localeDirection(locale),+ site_name: escapeHtml(site.name),+ site_url: escapeHtml(site.url),+ logo_url: escapeHtml(site.logoUrl),+ };+ const filled = fill(layout.html, (name) =>+ Object.hasOwn(parts, name) ? parts[name] : undefined,+ );+ return {+ subject,+ text: url ? `${plain}\n\n${url}` : plain,+ html: juice(withStyles(filled, layout.css), {+ preserveImportant: true,+ applyWidthAttributes: false,+ }),+ };+}diff --git a/packages/mailer/src/templates/texts/ar.ts b/packages/mailer/src/templates/texts/ar.tsnew file mode 100644index 00000000..c2cc316a--- /dev/null+++ b/packages/mailer/src/templates/texts/ar.ts@@ -0,0 +1,77 @@+import type { EmailLocaleTexts } from '../types';++const INVITE_NEXT =+ 'افتح الدعوة علشان تسجّل الدخول أو تعمل حساب. لو ماكنتش مستني الدعوة دي، تجاهل الرسالة.';++export const ar: EmailLocaleTexts = {+ linkHint: 'أو افتح الرابط ده:',+ words: {+ someone: 'أحدهم',+ untitled: 'بلا عنوان',+ owner: 'مالك',+ manager: 'مدير',+ member: 'عضو',+ },+ templates: {+ reset: {+ subject: 'إعادة تعيين كلمة المرور',+ body: 'استخدم الرابط اللي تحت علشان تعيّن كلمة مرور جديدة. لو ماطلبتش ده، تجاهل الرسالة.',+ button: 'تعيين كلمة مرور جديدة',+ },+ verify: {+ subject: 'أكّد عنوان بريدك',+ body: 'استخدم الرابط اللي تحت علشان تأكد العنوان ده وتكمّل التسجيل.',+ button: 'تأكيد العنوان',+ },+ magic: {+ subject: 'رابط تسجيل الدخول بتاعك',+ body: 'استخدم الرابط اللي تحت علشان تسجّل الدخول. الرابط بيشتغل مرة واحدة وهينتهي قريب.',+ button: 'تسجيل الدخول',+ },+ inviteProject: {+ subject: "عندك دعوة لـ {project} على It's a Plan",+ body: `{inviter} دعاك تنضم لـ {project} بدور {role}.\n\n${INVITE_NEXT}`,+ button: 'افتح الدعوة',+ },+ inviteTeam: {+ subject: "عندك دعوة لـ {team} على It's a Plan",+ body: `{inviter} دعاك تنضم للفريق {team} بدور {role}.\n\n${INVITE_NEXT}`,+ button: 'افتح الدعوة',+ },+ assigned: {+ subject: '{ref}: اتعيّنت لك',+ body: '{actor} عيّن لك المهمة دي.\n\n{ref}: {title}',+ button: 'افتح المهمة',+ },+ mentioned: {+ subject: '{ref}: حد أشار إليك',+ body: '{actor} أشار إليك في المهمة دي.\n\n{ref}: {title}',+ button: 'افتح المهمة',+ },+ commented: {+ subject: '{ref}: تعليق جديد',+ body: '{actor} علّق على المهمة دي.\n\n{ref}: {title}',+ button: 'افتح التعليق',+ },+ stateChanged: {+ subject: '{ref}: الحالة بقت {to}',+ body: '{actor} غيّر حالة المهمة دي من {from} لـ {to}.\n\n{ref}: {title}',+ button: 'افتح المهمة',+ },+ documentMentioned: {+ subject: '{document}: حد أشار إليك',+ body: '{actor} أشار إليك في المستند ده.\n\n{document}',+ button: 'افتح المستند',+ },+ documentCommentMentioned: {+ subject: '{document}: حد أشار إليك',+ body: '{actor} أشار إليك في تعليق على المستند ده.\n\n{document}',+ button: 'افتح المستند',+ },+ test: {+ subject: "اختبار بريد It's a Plan",+ body: "لو قريت الرسالة دي، يبقى البريد من It's a Plan شغّال.",+ button: '',+ },+ },+};diff --git a/packages/mailer/src/templates/texts/en.ts b/packages/mailer/src/templates/texts/en.tsnew file mode 100644index 00000000..2a1ad73f--- /dev/null+++ b/packages/mailer/src/templates/texts/en.ts@@ -0,0 +1,77 @@+import type { EmailLocaleTexts } from '../types';++const INVITE_NEXT =+ 'Open the invitation to sign in or create an account. If you did not expect this invitation, you can ignore this email.';++export const en: EmailLocaleTexts = {+ linkHint: 'Or open this link:',+ words: {+ someone: 'Someone',+ untitled: 'Untitled',+ owner: 'owner',+ manager: 'manager',+ member: 'member',+ },+ templates: {+ reset: {+ subject: 'Reset your password',+ body: 'Use the link below to set a new password. Ignore this email if you did not ask for it.',+ button: 'Set a new password',+ },+ verify: {+ subject: 'Confirm your email address',+ body: 'Use the link below to confirm this address and finish signing up.',+ button: 'Confirm the address',+ },+ magic: {+ subject: 'Your sign-in link',+ body: 'Use the link below to sign in. It works once and expires shortly.',+ button: 'Sign in',+ },+ inviteProject: {+ subject: "You were invited to {project} on It's a Plan",+ body: `{inviter} invited you to join {project} as {role}.\n\n${INVITE_NEXT}`,+ button: 'Open the invitation',+ },+ inviteTeam: {+ subject: "You were invited to {team} on It's a Plan",+ body: `{inviter} invited you to join the team {team} as {role}.\n\n${INVITE_NEXT}`,+ button: 'Open the invitation',+ },+ assigned: {+ subject: '{ref}: assigned to you',+ body: '{actor} assigned this issue to you.\n\n{ref}: {title}',+ button: 'Open the issue',+ },+ mentioned: {+ subject: '{ref}: you were mentioned',+ body: '{actor} mentioned you on this issue.\n\n{ref}: {title}',+ button: 'Open the issue',+ },+ commented: {+ subject: '{ref}: new comment',+ body: '{actor} commented on this issue.\n\n{ref}: {title}',+ button: 'Open the comment',+ },+ stateChanged: {+ subject: '{ref}: status changed to {to}',+ body: '{actor} changed the status of this issue from {from} to {to}.\n\n{ref}: {title}',+ button: 'Open the issue',+ },+ documentMentioned: {+ subject: '{document}: you were mentioned',+ body: '{actor} mentioned you in this document.\n\n{document}',+ button: 'Open the document',+ },+ documentCommentMentioned: {+ subject: '{document}: you were mentioned',+ body: '{actor} mentioned you in a comment on this document.\n\n{document}',+ button: 'Open the document',+ },+ test: {+ subject: "It's a Plan email test",+ body: "If you can read this, email from It's a Plan works.",+ button: '',+ },+ },+};diff --git a/packages/mailer/src/templates/texts/es-ES.ts b/packages/mailer/src/templates/texts/es-ES.tsnew file mode 100644index 00000000..f75abe0d--- /dev/null+++ b/packages/mailer/src/templates/texts/es-ES.ts@@ -0,0 +1,77 @@+import type { EmailLocaleTexts } from '../types';++const INVITE_NEXT =+ 'Abre la invitación para iniciar sesión o crear una cuenta. Si no esperabas esta invitación, puedes ignorar este correo.';++export const esES: EmailLocaleTexts = {+ linkHint: 'O abre este enlace:',+ words: {+ someone: 'Alguien',+ untitled: 'Sin título',+ owner: 'propietario',+ manager: 'administrador',+ member: 'miembro',+ },+ templates: {+ reset: {+ subject: 'Restablece tu contraseña',+ body: 'Usa el enlace de abajo para definir una contraseña nueva. Ignora este correo si no lo has pedido.',+ button: 'Definir una contraseña nueva',+ },+ verify: {+ subject: 'Confirma tu dirección de correo',+ body: 'Usa el enlace de abajo para confirmar esta dirección y terminar el registro.',+ button: 'Confirmar la dirección',+ },+ magic: {+ subject: 'Tu enlace de inicio de sesión',+ body: 'Usa el enlace de abajo para iniciar sesión. Funciona una vez y caduca pronto.',+ button: 'Iniciar sesión',+ },+ inviteProject: {+ subject: "Te han invitado a {project} en It's a Plan",+ body: `{inviter} te ha invitado a unirte a {project} como {role}.\n\n${INVITE_NEXT}`,+ button: 'Abrir la invitación',+ },+ inviteTeam: {+ subject: "Te han invitado a {team} en It's a Plan",+ body: `{inviter} te ha invitado a unirte al equipo {team} como {role}.\n\n${INVITE_NEXT}`,+ button: 'Abrir la invitación',+ },+ assigned: {+ subject: '{ref}: te lo han asignado',+ body: '{actor} te ha asignado este ticket.\n\n{ref}: {title}',+ button: 'Abrir el ticket',+ },+ mentioned: {+ subject: '{ref}: te han mencionado',+ body: '{actor} te ha mencionado en este ticket.\n\n{ref}: {title}',+ button: 'Abrir el ticket',+ },+ commented: {+ subject: '{ref}: comentario nuevo',+ body: '{actor} ha comentado este ticket.\n\n{ref}: {title}',+ button: 'Abrir el comentario',+ },+ stateChanged: {+ subject: '{ref}: estado cambiado a {to}',+ body: '{actor} ha cambiado el estado de este ticket de {from} a {to}.\n\n{ref}: {title}',+ button: 'Abrir el ticket',+ },+ documentMentioned: {+ subject: '{document}: te han mencionado',+ body: '{actor} te ha mencionado en este documento.\n\n{document}',+ button: 'Abrir el documento',+ },+ documentCommentMentioned: {+ subject: '{document}: te han mencionado',+ body: '{actor} te ha mencionado en un comentario de este documento.\n\n{document}',+ button: 'Abrir el documento',+ },+ test: {+ subject: "Prueba de correo de It's a Plan",+ body: "Si puedes leer esto, el correo de It's a Plan funciona.",+ button: '',+ },+ },+};diff --git a/packages/mailer/src/templates/texts/fa.ts b/packages/mailer/src/templates/texts/fa.tsnew file mode 100644index 00000000..a441c451--- /dev/null+++ b/packages/mailer/src/templates/texts/fa.ts@@ -0,0 +1,77 @@+import type { EmailLocaleTexts } from '../types';++const INVITE_NEXT =+ 'دعوتنامه را باز کنید تا وارد شوید یا حساب بسازید. اگر انتظار این دعوت را نداشتید، این ایمیل را نادیده بگیرید.';++export const fa: EmailLocaleTexts = {+ linkHint: 'یا این لینک را باز کنید:',+ words: {+ someone: 'یک نفر',+ untitled: 'بدون عنوان',+ owner: 'مالک',+ manager: 'مدیر',+ member: 'عضو',+ },+ templates: {+ reset: {+ subject: 'بازنشانی گذرواژه',+ body: 'با لینک زیر گذرواژه جدید تنظیم کنید. اگر این درخواست را ندادهاید، این ایمیل را نادیده بگیرید.',+ button: 'تنظیم گذرواژه جدید',+ },+ verify: {+ subject: 'نشانی ایمیل خود را تأیید کنید',+ body: 'با لینک زیر این نشانی را تأیید کنید و ثبتنام را کامل کنید.',+ button: 'تأیید نشانی',+ },+ magic: {+ subject: 'لینک ورود شما',+ body: 'با لینک زیر وارد شوید. این لینک یک بار کار میکند و بهزودی منقضی میشود.',+ button: 'ورود',+ },+ inviteProject: {+ subject: "شما به {project} در It's a Plan دعوت شدهاید",+ body: `{inviter} شما را با نقش {role} به {project} دعوت کرده است.\n\n${INVITE_NEXT}`,+ button: 'باز کردن دعوتنامه',+ },+ inviteTeam: {+ subject: "شما به {team} در It's a Plan دعوت شدهاید",+ body: `{inviter} شما را با نقش {role} به تیم {team} دعوت کرده است.\n\n${INVITE_NEXT}`,+ button: 'باز کردن دعوتنامه',+ },+ assigned: {+ subject: '{ref}: به شما واگذار شد',+ body: '{actor} این تسک را به شما واگذار کرد.\n\n{ref}: {title}',+ button: 'باز کردن تسک',+ },+ mentioned: {+ subject: '{ref}: از شما نام برده شد',+ body: '{actor} در این تسک از شما نام برد.\n\n{ref}: {title}',+ button: 'باز کردن تسک',+ },+ commented: {+ subject: '{ref}: دیدگاه جدید',+ body: '{actor} روی این تسک دیدگاه گذاشت.\n\n{ref}: {title}',+ button: 'باز کردن دیدگاه',+ },+ stateChanged: {+ subject: '{ref}: وضعیت به {to} تغییر کرد',+ body: '{actor} وضعیت این تسک را از {from} به {to} تغییر داد.\n\n{ref}: {title}',+ button: 'باز کردن تسک',+ },+ documentMentioned: {+ subject: '{document}: از شما نام برده شد',+ body: '{actor} در این سند از شما نام برد.\n\n{document}',+ button: 'باز کردن سند',+ },+ documentCommentMentioned: {+ subject: '{document}: از شما نام برده شد',+ body: '{actor} در دیدگاهی روی این سند از شما نام برد.\n\n{document}',+ button: 'باز کردن سند',+ },+ test: {+ subject: "آزمایش ایمیل It's a Plan",+ body: "اگر این را میخوانید، ایمیل It's a Plan کار میکند.",+ button: '',+ },+ },+};diff --git a/packages/mailer/src/templates/texts/fr.ts b/packages/mailer/src/templates/texts/fr.tsnew file mode 100644index 00000000..38c429f6--- /dev/null+++ b/packages/mailer/src/templates/texts/fr.ts@@ -0,0 +1,77 @@+import type { EmailLocaleTexts } from '../types';++const INVITE_NEXT =+ "Ouvrez l'invitation pour vous connecter ou créer un compte. Si vous n'attendiez pas cette invitation, vous pouvez ignorer cet e-mail.";++export const fr: EmailLocaleTexts = {+ linkHint: 'Ou ouvrez ce lien :',+ words: {+ someone: "Quelqu'un",+ untitled: 'Sans titre',+ owner: 'propriétaire',+ manager: 'gestionnaire',+ member: 'membre',+ },+ templates: {+ reset: {+ subject: 'Réinitialisez votre mot de passe',+ body: "Utilisez le lien ci-dessous pour définir un nouveau mot de passe. Ignorez cet e-mail si vous n'en êtes pas à l'origine.",+ button: 'Définir un nouveau mot de passe',+ },+ verify: {+ subject: 'Confirmez votre adresse e-mail',+ body: "Utilisez le lien ci-dessous pour confirmer cette adresse et terminer l'inscription.",+ button: "Confirmer l'adresse",+ },+ magic: {+ subject: 'Votre lien de connexion',+ body: "Utilisez le lien ci-dessous pour vous connecter. Il ne fonctionne qu'une fois et expire rapidement.",+ button: 'Se connecter',+ },+ inviteProject: {+ subject: "Vous êtes invité à {project} sur It's a Plan",+ body: `{inviter} vous invite à rejoindre {project} avec le rôle {role}.\n\n${INVITE_NEXT}`,+ button: "Ouvrir l'invitation",+ },+ inviteTeam: {+ subject: "Vous êtes invité à {team} sur It's a Plan",+ body: `{inviter} vous invite à rejoindre l'équipe {team} avec le rôle {role}.\n\n${INVITE_NEXT}`,+ button: "Ouvrir l'invitation",+ },+ assigned: {+ subject: '{ref} : vous a été assigné',+ body: '{actor} vous a assigné ce ticket.\n\n{ref} : {title}',+ button: 'Ouvrir le ticket',+ },+ mentioned: {+ subject: '{ref} : vous avez été mentionné',+ body: '{actor} vous a mentionné sur ce ticket.\n\n{ref} : {title}',+ button: 'Ouvrir le ticket',+ },+ commented: {+ subject: '{ref} : nouveau commentaire',+ body: '{actor} a commenté ce ticket.\n\n{ref} : {title}',+ button: 'Ouvrir le commentaire',+ },+ stateChanged: {+ subject: '{ref} : état passé à {to}',+ body: "{actor} a fait passer l'état de ce ticket de {from} à {to}.\n\n{ref} : {title}",+ button: 'Ouvrir le ticket',+ },+ documentMentioned: {+ subject: '{document} : vous avez été mentionné',+ body: '{actor} vous a mentionné dans ce document.\n\n{document}',+ button: 'Ouvrir le document',+ },+ documentCommentMentioned: {+ subject: '{document} : vous avez été mentionné',+ body: '{actor} vous a mentionné dans un commentaire sur ce document.\n\n{document}',+ button: 'Ouvrir le document',+ },+ test: {+ subject: "Test d'e-mail It's a Plan",+ body: "Si vous lisez ceci, l'envoi d'e-mails depuis It's a Plan fonctionne.",+ button: '',+ },+ },+};diff --git a/packages/mailer/src/templates/texts/id.ts b/packages/mailer/src/templates/texts/id.tsnew file mode 100644index 00000000..f65984ce--- /dev/null+++ b/packages/mailer/src/templates/texts/id.ts@@ -0,0 +1,77 @@+import type { EmailLocaleTexts } from '../types';++const INVITE_NEXT =+ 'Buka undangan untuk masuk atau membuat akun. Jika Anda tidak mengharapkan undangan ini, abaikan email ini.';++export const id: EmailLocaleTexts = {+ linkHint: 'Atau buka tautan ini:',+ words: {+ someone: 'Seseorang',+ untitled: 'Tanpa judul',+ owner: 'pemilik',+ manager: 'manajer',+ member: 'anggota',+ },+ templates: {+ reset: {+ subject: 'Atur ulang kata sandi Anda',+ body: 'Gunakan tautan di bawah untuk mengatur kata sandi baru. Abaikan email ini jika Anda tidak memintanya.',+ button: 'Atur kata sandi baru',+ },+ verify: {+ subject: 'Konfirmasi alamat email Anda',+ body: 'Gunakan tautan di bawah untuk mengonfirmasi alamat ini dan menyelesaikan pendaftaran.',+ button: 'Konfirmasi alamat',+ },+ magic: {+ subject: 'Tautan masuk Anda',+ body: 'Gunakan tautan di bawah untuk masuk. Tautan ini hanya berfungsi sekali dan segera kedaluwarsa.',+ button: 'Masuk',+ },+ inviteProject: {+ subject: "Anda diundang ke {project} di It's a Plan",+ body: `{inviter} mengundang Anda untuk bergabung dengan {project} sebagai {role}.\n\n${INVITE_NEXT}`,+ button: 'Buka undangan',+ },+ inviteTeam: {+ subject: "Anda diundang ke {team} di It's a Plan",+ body: `{inviter} mengundang Anda untuk bergabung dengan tim {team} sebagai {role}.\n\n${INVITE_NEXT}`,+ button: 'Buka undangan',+ },+ assigned: {+ subject: '{ref}: ditugaskan kepada Anda',+ body: '{actor} menugaskan issue ini kepada Anda.\n\n{ref}: {title}',+ button: 'Buka issue',+ },+ mentioned: {+ subject: '{ref}: Anda disebut',+ body: '{actor} menyebut Anda di issue ini.\n\n{ref}: {title}',+ button: 'Buka issue',+ },+ commented: {+ subject: '{ref}: komentar baru',+ body: '{actor} mengomentari issue ini.\n\n{ref}: {title}',+ button: 'Buka komentar',+ },+ stateChanged: {+ subject: '{ref}: status diubah ke {to}',+ body: '{actor} mengubah status issue ini dari {from} ke {to}.\n\n{ref}: {title}',+ button: 'Buka issue',+ },+ documentMentioned: {+ subject: '{document}: Anda disebut',+ body: '{actor} menyebut Anda di dokumen ini.\n\n{document}',+ button: 'Buka dokumen',+ },+ documentCommentMentioned: {+ subject: '{document}: Anda disebut',+ body: '{actor} menyebut Anda dalam komentar di dokumen ini.\n\n{document}',+ button: 'Buka dokumen',+ },+ test: {+ subject: "Tes email It's a Plan",+ body: "Jika Anda bisa membaca ini, email dari It's a Plan berfungsi.",+ button: '',+ },+ },+};diff --git a/packages/mailer/src/templates/texts/ko.ts b/packages/mailer/src/templates/texts/ko.tsnew file mode 100644index 00000000..71f6e2f2--- /dev/null+++ b/packages/mailer/src/templates/texts/ko.ts@@ -0,0 +1,77 @@+import type { EmailLocaleTexts } from '../types';++const INVITE_NEXT =+ '초대를 열어 로그인하거나 계정을 만드세요. 이 초대를 예상하지 못했다면 이 이메일을 무시해도 됩니다.';++export const ko: EmailLocaleTexts = {+ linkHint: '또는 이 링크를 여세요:',+ words: {+ someone: '누군가',+ untitled: '제목 없음',+ owner: '소유자',+ manager: '관리자',+ member: '멤버',+ },+ templates: {+ reset: {+ subject: '비밀번호 재설정',+ body: '아래 링크를 사용해 새 비밀번호를 설정하세요. 요청한 적이 없다면 이 이메일을 무시하세요.',+ button: '새 비밀번호 설정',+ },+ verify: {+ subject: '이메일 주소를 인증하세요',+ body: '아래 링크를 사용해 이 주소를 인증하고 가입을 완료하세요.',+ button: '주소 인증',+ },+ magic: {+ subject: '로그인 링크',+ body: '아래 링크를 사용해 로그인하세요. 이 링크는 한 번만 작동하며 곧 만료됩니다.',+ button: '로그인',+ },+ inviteProject: {+ subject: "It's a Plan의 {project}에 초대되었습니다",+ body: `{inviter}님이 {role} 역할로 {project}에 참여하도록 초대했습니다.\n\n${INVITE_NEXT}`,+ button: '초대 열기',+ },+ inviteTeam: {+ subject: "It's a Plan의 {team}에 초대되었습니다",+ body: `{inviter}님이 {role} 역할로 {team} 팀에 참여하도록 초대했습니다.\n\n${INVITE_NEXT}`,+ button: '초대 열기',+ },+ assigned: {+ subject: '{ref}: 나에게 배정됨',+ body: '{actor}님이 이 이슈를 나에게 배정했습니다.\n\n{ref}: {title}',+ button: '이슈 열기',+ },+ mentioned: {+ subject: '{ref}: 멘션되었습니다',+ body: '{actor}님이 이 이슈에서 나를 멘션했습니다.\n\n{ref}: {title}',+ button: '이슈 열기',+ },+ commented: {+ subject: '{ref}: 새 댓글',+ body: '{actor}님이 이 이슈에 댓글을 작성했습니다.\n\n{ref}: {title}',+ button: '댓글 열기',+ },+ stateChanged: {+ subject: '{ref}: 상태가 {to}(으)로 변경됨',+ body: '{actor}님이 이 이슈의 상태를 {from}에서 {to}(으)로 변경했습니다.\n\n{ref}: {title}',+ button: '이슈 열기',+ },+ documentMentioned: {+ subject: '{document}: 멘션되었습니다',+ body: '{actor}님이 이 문서에서 나를 멘션했습니다.\n\n{document}',+ button: '문서 열기',+ },+ documentCommentMentioned: {+ subject: '{document}: 멘션되었습니다',+ body: '{actor}님이 이 문서의 댓글에서 나를 멘션했습니다.\n\n{document}',+ button: '문서 열기',+ },+ test: {+ subject: "It's a Plan 이메일 테스트",+ body: "이 메일이 보인다면 It's a Plan의 이메일 발송이 정상입니다.",+ button: '',+ },+ },+};diff --git a/packages/mailer/src/templates/texts/pt-BR.ts b/packages/mailer/src/templates/texts/pt-BR.tsnew file mode 100644index 00000000..af60e6bc--- /dev/null+++ b/packages/mailer/src/templates/texts/pt-BR.ts@@ -0,0 +1,77 @@+import type { EmailLocaleTexts } from '../types';++const INVITE_NEXT =+ 'Abra o convite para entrar ou criar uma conta. Se você não esperava este convite, pode ignorar este e-mail.';++export const ptBR: EmailLocaleTexts = {+ linkHint: 'Ou abra este link:',+ words: {+ someone: 'Alguém',+ untitled: 'Sem título',+ owner: 'dono',+ manager: 'gerente',+ member: 'membro',+ },+ templates: {+ reset: {+ subject: 'Redefina sua senha',+ body: 'Use o link abaixo para definir uma nova senha. Ignore este e-mail se você não pediu isso.',+ button: 'Definir uma nova senha',+ },+ verify: {+ subject: 'Confirme seu endereço de e-mail',+ body: 'Use o link abaixo para confirmar este endereço e concluir o cadastro.',+ button: 'Confirmar o endereço',+ },+ magic: {+ subject: 'Seu link de login',+ body: 'Use o link abaixo para entrar. Ele funciona uma vez e expira em breve.',+ button: 'Entrar',+ },+ inviteProject: {+ subject: "Você foi convidado para {project} no It's a Plan",+ body: `{inviter} convidou você para entrar em {project} como {role}.\n\n${INVITE_NEXT}`,+ button: 'Abrir o convite',+ },+ inviteTeam: {+ subject: "Você foi convidado para {team} no It's a Plan",+ body: `{inviter} convidou você para entrar na equipe {team} como {role}.\n\n${INVITE_NEXT}`,+ button: 'Abrir o convite',+ },+ assigned: {+ subject: '{ref}: atribuída a você',+ body: '{actor} atribuiu esta issue a você.\n\n{ref}: {title}',+ button: 'Abrir a issue',+ },+ mentioned: {+ subject: '{ref}: você foi mencionado',+ body: '{actor} mencionou você nesta issue.\n\n{ref}: {title}',+ button: 'Abrir a issue',+ },+ commented: {+ subject: '{ref}: novo comentário',+ body: '{actor} comentou nesta issue.\n\n{ref}: {title}',+ button: 'Abrir o comentário',+ },+ stateChanged: {+ subject: '{ref}: status alterado para {to}',+ body: '{actor} alterou o status desta issue de {from} para {to}.\n\n{ref}: {title}',+ button: 'Abrir a issue',+ },+ documentMentioned: {+ subject: '{document}: você foi mencionado',+ body: '{actor} mencionou você neste documento.\n\n{document}',+ button: 'Abrir o documento',+ },+ documentCommentMentioned: {+ subject: '{document}: você foi mencionado',+ body: '{actor} mencionou você em um comentário neste documento.\n\n{document}',+ button: 'Abrir o documento',+ },+ test: {+ subject: "Teste de e-mail do It's a Plan",+ body: "Se você consegue ler isto, o e-mail do It's a Plan está funcionando.",+ button: '',+ },+ },+};diff --git a/packages/mailer/src/templates/texts/ru.ts b/packages/mailer/src/templates/texts/ru.tsnew file mode 100644index 00000000..0bb014be--- /dev/null+++ b/packages/mailer/src/templates/texts/ru.ts@@ -0,0 +1,77 @@+import type { EmailLocaleTexts } from '../types';++const INVITE_NEXT =+ 'Откройте приглашение, чтобы войти или создать аккаунт. Если вы не ждали этого приглашения, просто проигнорируйте письмо.';++export const ru: EmailLocaleTexts = {+ linkHint: 'Или откройте ссылку:',+ words: {+ someone: 'Кто-то',+ untitled: 'Без названия',+ owner: 'владелец',+ manager: 'менеджер',+ member: 'участник',+ },+ templates: {+ reset: {+ subject: 'Сброс пароля',+ body: 'Перейдите по ссылке ниже, чтобы задать новый пароль. Если вы не запрашивали сброс, просто проигнорируйте это письмо.',+ button: 'Задать новый пароль',+ },+ verify: {+ subject: 'Подтвердите адрес почты',+ body: 'Перейдите по ссылке ниже, чтобы подтвердить этот адрес и завершить регистрацию.',+ button: 'Подтвердить адрес',+ },+ magic: {+ subject: 'Ссылка для входа',+ body: 'Перейдите по ссылке ниже, чтобы войти. Ссылка работает один раз и скоро перестанет действовать.',+ button: 'Войти',+ },+ inviteProject: {+ subject: "Приглашение в {project} в It's a Plan",+ body: `{inviter} приглашает вас в проект {project} с ролью {role}.\n\n${INVITE_NEXT}`,+ button: 'Открыть приглашение',+ },+ inviteTeam: {+ subject: "Приглашение в команду {team} в It's a Plan",+ body: `{inviter} приглашает вас в команду {team} с ролью {role}.\n\n${INVITE_NEXT}`,+ button: 'Открыть приглашение',+ },+ assigned: {+ subject: '{ref}: назначена на вас',+ body: '{actor}: вы назначены исполнителем этой задачи.\n\n{ref}: {title}',+ button: 'Открыть задачу',+ },+ mentioned: {+ subject: '{ref}: вас упомянули',+ body: '{actor}: вас упомянули в этой задаче.\n\n{ref}: {title}',+ button: 'Открыть задачу',+ },+ commented: {+ subject: '{ref}: новый комментарий',+ body: '{actor}: новый комментарий к этой задаче.\n\n{ref}: {title}',+ button: 'Открыть комментарий',+ },+ stateChanged: {+ subject: '{ref}: статус изменён на «{to}»',+ body: '{actor}: статус задачи изменён с «{from}» на «{to}».\n\n{ref}: {title}',+ button: 'Открыть задачу',+ },+ documentMentioned: {+ subject: '{document}: вас упомянули',+ body: '{actor}: вас упомянули в этом документе.\n\n{document}',+ button: 'Открыть документ',+ },+ documentCommentMentioned: {+ subject: '{document}: вас упомянули',+ body: '{actor}: вас упомянули в комментарии к этому документу.\n\n{document}',+ button: 'Открыть документ',+ },+ test: {+ subject: "Проверка почты It's a Plan",+ body: "Если вы это читаете, почта из It's a Plan работает.",+ button: '',+ },+ },+};diff --git a/packages/mailer/src/templates/texts/tr.ts b/packages/mailer/src/templates/texts/tr.tsnew file mode 100644index 00000000..52f21bf1--- /dev/null+++ b/packages/mailer/src/templates/texts/tr.ts@@ -0,0 +1,77 @@+import type { EmailLocaleTexts } from '../types';++const INVITE_NEXT =+ 'Giriş yapmak veya hesap oluşturmak için daveti açın. Bu daveti beklemiyorsanız bu e-postayı yok sayabilirsiniz.';++export const tr: EmailLocaleTexts = {+ linkHint: 'Veya bu bağlantıyı açın:',+ words: {+ someone: 'Biri',+ untitled: 'Başlıksız',+ owner: 'sahip',+ manager: 'yönetici',+ member: 'üye',+ },+ templates: {+ reset: {+ subject: 'Şifrenizi sıfırlayın',+ body: 'Yeni şifre belirlemek için aşağıdaki bağlantıyı kullanın. Bunu siz istemediyseniz bu e-postayı yok sayın.',+ button: 'Yeni şifre belirle',+ },+ verify: {+ subject: 'E-posta adresinizi onaylayın',+ body: 'Bu adresi onaylamak ve kaydı tamamlamak için aşağıdaki bağlantıyı kullanın.',+ button: 'Adresi onayla',+ },+ magic: {+ subject: 'Giriş bağlantınız',+ body: 'Giriş yapmak için aşağıdaki bağlantıyı kullanın. Bağlantı bir kez çalışır ve kısa süre sonra geçersiz olur.',+ button: 'Giriş yap',+ },+ inviteProject: {+ subject: "It's a Plan üzerinde {project} için davet edildiniz",+ body: `{inviter} sizi {role} rolüyle {project} projesine davet etti.\n\n${INVITE_NEXT}`,+ button: 'Daveti aç',+ },+ inviteTeam: {+ subject: "It's a Plan üzerinde {team} için davet edildiniz",+ body: `{inviter} sizi {role} rolüyle {team} ekibine davet etti.\n\n${INVITE_NEXT}`,+ button: 'Daveti aç',+ },+ assigned: {+ subject: '{ref}: size atandı',+ body: '{actor} bu işi size atadı.\n\n{ref}: {title}',+ button: 'İşi aç',+ },+ mentioned: {+ subject: '{ref}: sizden bahsedildi',+ body: '{actor} bu işte sizden bahsetti.\n\n{ref}: {title}',+ button: 'İşi aç',+ },+ commented: {+ subject: '{ref}: yeni yorum',+ body: '{actor} bu işe yorum yaptı.\n\n{ref}: {title}',+ button: 'Yorumu aç',+ },+ stateChanged: {+ subject: '{ref}: durum {to} olarak değişti',+ body: '{actor} bu işin durumunu {from} değerinden {to} değerine değiştirdi.\n\n{ref}: {title}',+ button: 'İşi aç',+ },+ documentMentioned: {+ subject: '{document}: sizden bahsedildi',+ body: '{actor} bu belgede sizden bahsetti.\n\n{document}',+ button: 'Belgeyi aç',+ },+ documentCommentMentioned: {+ subject: '{document}: sizden bahsedildi',+ body: '{actor} bu belgedeki bir yorumda sizden bahsetti.\n\n{document}',+ button: 'Belgeyi aç',+ },+ test: {+ subject: "It's a Plan e-posta testi",+ body: "Bunu okuyabiliyorsanız It's a Plan e-postaları çalışıyor.",+ button: '',+ },+ },+};diff --git a/packages/mailer/src/templates/texts/uk.ts b/packages/mailer/src/templates/texts/uk.tsnew file mode 100644index 00000000..6ac56d40--- /dev/null+++ b/packages/mailer/src/templates/texts/uk.ts@@ -0,0 +1,77 @@+import type { EmailLocaleTexts } from '../types';++const INVITE_NEXT =+ 'Відкрийте запрошення, щоб увійти або створити обліковий запис. Якщо ви не чекали цього запрошення, просто проігноруйте лист.';++export const uk: EmailLocaleTexts = {+ linkHint: 'Або відкрийте посилання:',+ words: {+ someone: 'Хтось',+ untitled: 'Без назви',+ owner: 'власник',+ manager: 'менеджер',+ member: 'учасник',+ },+ templates: {+ reset: {+ subject: 'Скидання пароля',+ body: 'Перейдіть за посиланням нижче, щоб задати новий пароль. Якщо ви не запитували скидання, просто проігноруйте цей лист.',+ button: 'Задати новий пароль',+ },+ verify: {+ subject: 'Підтвердіть адресу пошти',+ body: 'Перейдіть за посиланням нижче, щоб підтвердити цю адресу й завершити реєстрацію.',+ button: 'Підтвердити адресу',+ },+ magic: {+ subject: 'Посилання для входу',+ body: 'Перейдіть за посиланням нижче, щоб увійти. Посилання працює один раз і скоро перестане діяти.',+ button: 'Увійти',+ },+ inviteProject: {+ subject: "Запрошення до {project} в It's a Plan",+ body: `{inviter} запрошує вас до проєкту {project} з роллю {role}.\n\n${INVITE_NEXT}`,+ button: 'Відкрити запрошення',+ },+ inviteTeam: {+ subject: "Запрошення до команди {team} в It's a Plan",+ body: `{inviter} запрошує вас до команди {team} з роллю {role}.\n\n${INVITE_NEXT}`,+ button: 'Відкрити запрошення',+ },+ assigned: {+ subject: '{ref}: призначено вам',+ body: '{actor}: вас призначено виконавцем цієї задачі.\n\n{ref}: {title}',+ button: 'Відкрити задачу',+ },+ mentioned: {+ subject: '{ref}: вас згадали',+ body: '{actor}: вас згадали в цій задачі.\n\n{ref}: {title}',+ button: 'Відкрити задачу',+ },+ commented: {+ subject: '{ref}: новий коментар',+ body: '{actor}: новий коментар до цієї задачі.\n\n{ref}: {title}',+ button: 'Відкрити коментар',+ },+ stateChanged: {+ subject: '{ref}: статус змінено на «{to}»',+ body: '{actor}: статус задачі змінено з «{from}» на «{to}».\n\n{ref}: {title}',+ button: 'Відкрити задачу',+ },+ documentMentioned: {+ subject: '{document}: вас згадали',+ body: '{actor}: вас згадали в цьому документі.\n\n{document}',+ button: 'Відкрити документ',+ },+ documentCommentMentioned: {+ subject: '{document}: вас згадали',+ body: '{actor}: вас згадали в коментарі до цього документа.\n\n{document}',+ button: 'Відкрити документ',+ },+ test: {+ subject: "Перевірка пошти It's a Plan",+ body: "Якщо ви це читаєте, пошта з It's a Plan працює.",+ button: '',+ },+ },+};diff --git a/packages/mailer/src/templates/texts/zh-CN.ts b/packages/mailer/src/templates/texts/zh-CN.tsnew file mode 100644index 00000000..c606a484--- /dev/null+++ b/packages/mailer/src/templates/texts/zh-CN.ts@@ -0,0 +1,76 @@+import type { EmailLocaleTexts } from '../types';++const INVITE_NEXT = '打开邀请即可登录或创建账户。如果你没有预期收到此邀请,请忽略这封邮件。';++export const zhCN: EmailLocaleTexts = {+ linkHint: '或打开此链接:',+ words: {+ someone: '某位用户',+ untitled: '无标题',+ owner: '所有者',+ manager: '管理员',+ member: '成员',+ },+ templates: {+ reset: {+ subject: '重置密码',+ body: '请使用下方链接设置新密码。如果这不是你的操作,请忽略这封邮件。',+ button: '设置新密码',+ },+ verify: {+ subject: '验证你的邮箱地址',+ body: '请使用下方链接验证此地址并完成注册。',+ button: '验证地址',+ },+ magic: {+ subject: '你的登录链接',+ body: '请使用下方链接登录。此链接只能使用一次,并将很快失效。',+ button: '登录',+ },+ inviteProject: {+ subject: "你受邀加入 It's a Plan 上的 {project}",+ body: `{inviter} 邀请你以 {role} 身份加入 {project}。\n\n${INVITE_NEXT}`,+ button: '打开邀请',+ },+ inviteTeam: {+ subject: "你受邀加入 It's a Plan 上的 {team}",+ body: `{inviter} 邀请你以 {role} 身份加入团队 {team}。\n\n${INVITE_NEXT}`,+ button: '打开邀请',+ },+ assigned: {+ subject: '{ref}:已分配给你',+ body: '{actor} 将此工作项分配给了你。\n\n{ref}:{title}',+ button: '打开工作项',+ },+ mentioned: {+ subject: '{ref}:有人提及了你',+ body: '{actor} 在此工作项中提及了你。\n\n{ref}:{title}',+ button: '打开工作项',+ },+ commented: {+ subject: '{ref}:新评论',+ body: '{actor} 评论了此工作项。\n\n{ref}:{title}',+ button: '打开评论',+ },+ stateChanged: {+ subject: '{ref}:状态已更改为 {to}',+ body: '{actor} 将此工作项的状态从 {from} 更改为 {to}。\n\n{ref}:{title}',+ button: '打开工作项',+ },+ documentMentioned: {+ subject: '{document}:有人提及了你',+ body: '{actor} 在此文档中提及了你。\n\n{document}',+ button: '打开文档',+ },+ documentCommentMentioned: {+ subject: '{document}:有人提及了你',+ body: '{actor} 在此文档的评论中提及了你。\n\n{document}',+ button: '打开文档',+ },+ test: {+ subject: "It's a Plan 邮件测试",+ body: "如果你能看到这封邮件,说明 It's a Plan 的邮件功能正常。",+ button: '',+ },+ },+};diff --git a/packages/mailer/src/templates/texts/zh-TW.ts b/packages/mailer/src/templates/texts/zh-TW.tsnew file mode 100644index 00000000..5191f09a--- /dev/null+++ b/packages/mailer/src/templates/texts/zh-TW.ts@@ -0,0 +1,76 @@+import type { EmailLocaleTexts } from '../types';++const INVITE_NEXT = '開啟邀請即可登入或建立帳號。如果你並未預期收到此邀請,請忽略這封電子郵件。';++export const zhTW: EmailLocaleTexts = {+ linkHint: '或開啟此連結:',+ words: {+ someone: '某位使用者',+ untitled: '無標題',+ owner: '所有者',+ manager: '管理者',+ member: '成員',+ },+ templates: {+ reset: {+ subject: '重設密碼',+ body: '請使用下方連結設定新密碼。如果這不是你的操作,請忽略這封電子郵件。',+ button: '設定新密碼',+ },+ verify: {+ subject: '驗證你的電子郵件地址',+ body: '請使用下方連結驗證此地址並完成註冊。',+ button: '驗證地址',+ },+ magic: {+ subject: '你的登入連結',+ body: '請使用下方連結登入。此連結只能使用一次,且很快就會失效。',+ button: '登入',+ },+ inviteProject: {+ subject: "你受邀加入 It's a Plan 上的 {project}",+ body: `{inviter} 邀請你以 {role} 身分加入 {project}。\n\n${INVITE_NEXT}`,+ button: '開啟邀請',+ },+ inviteTeam: {+ subject: "你受邀加入 It's a Plan 上的 {team}",+ body: `{inviter} 邀請你以 {role} 身分加入團隊 {team}。\n\n${INVITE_NEXT}`,+ button: '開啟邀請',+ },+ assigned: {+ subject: '{ref}:已指派給你',+ body: '{actor} 將此工作項目指派給你。\n\n{ref}:{title}',+ button: '開啟工作項目',+ },+ mentioned: {+ subject: '{ref}:有人提及了你',+ body: '{actor} 在此工作項目中提及了你。\n\n{ref}:{title}',+ button: '開啟工作項目',+ },+ commented: {+ subject: '{ref}:新留言',+ body: '{actor} 在此工作項目發表了留言。\n\n{ref}:{title}',+ button: '開啟留言',+ },+ stateChanged: {+ subject: '{ref}:狀態已更改為 {to}',+ body: '{actor} 將此工作項目的狀態從 {from} 更改為 {to}。\n\n{ref}:{title}',+ button: '開啟工作項目',+ },+ documentMentioned: {+ subject: '{document}:有人提及了你',+ body: '{actor} 在此文件中提及了你。\n\n{document}',+ button: '開啟文件',+ },+ documentCommentMentioned: {+ subject: '{document}:有人提及了你',+ body: '{actor} 在此文件的留言中提及了你。\n\n{document}',+ button: '開啟文件',+ },+ test: {+ subject: "It's a Plan 電子郵件測試",+ body: "如果你看得到這封信,表示 It's a Plan 的電子郵件功能正常。",+ button: '',+ },+ },+};diff --git a/packages/mailer/src/templates/types.ts b/packages/mailer/src/templates/types.tsnew file mode 100644index 00000000..cfe94ed5--- /dev/null+++ b/packages/mailer/src/templates/types.ts@@ -0,0 +1,35 @@+export interface EmailText {+ subject: string;+ body: string;+ button: string;+}++export type CoreEmailKey =+ | 'reset'+ | 'verify'+ | 'magic'+ | 'inviteProject'+ | 'inviteTeam'+ | 'assigned'+ | 'mentioned'+ | 'commented'+ | 'stateChanged'+ | 'documentMentioned'+ | 'documentCommentMentioned'+ | 'test';++// Words a message fills in by itself: a role name, or a value that has no name of its own.+export interface EmailWords {+ someone: string;+ untitled: string;+ owner: string;+ manager: string;+ member: string;+}++export interface EmailLocaleTexts {+ // Stands before the address under the button.+ linkHint: string;+ words: EmailWords;+ templates: Record<CoreEmailKey, EmailText>;+}