From 936a874f27e593d3f209f864619fc7d5cddb9338 Mon Sep 17 00:00:00 2001 From: "Schero D." Date: Thu, 19 Nov 2026 00:08:07 +0100 Subject: [PATCH] feat: provider templates for SendGrid and Mailgun Re-applies #20's own changes (0f3b79f..882a86a) on top of 4.7.0, which already contains #23. Conflicts resolved in favour of main: the 4.6.3 dialog labelling, the 4.7.0 send paths with the Mail Send hint and the Strapi 5.63 dev dependencies. The CHANGELOG [Unreleased] section holds only the provider-template entries plus a Verification section. Adds the provider-template screens to the StrictMode admin tests: the templates page loads the overview once, the preview and core-email design dialogs open and close cleanly, and a stale list starts exactly one background sync under StrictMode. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 26 + README.md | 38 +- .../TemplateCodeSnippetsModal.jsx | 27 +- .../src/pages/EmailDesigner/TemplateList.jsx | 141 ++- .../ConvertForProviderPanel.jsx | 115 +++ .../providerTemplates/CoreDesignAlert.jsx | 79 ++ .../providerTemplates/CoreDesignDialog.jsx | 265 ++++++ .../providerTemplates/Notice.jsx | 59 ++ .../ProviderTemplateDialog.jsx | 578 ++++++++++++ .../ProviderTemplatesSection.jsx | 260 ++++++ .../providerTemplateStyles.js | 78 ++ .../providerTemplateUtils.js | 147 +++ .../providerTemplates/useProviderTemplates.js | 113 +++ admin/src/pages/HomePage.jsx | 7 + admin/src/translations/de.json | 120 ++- admin/src/translations/en.json | 120 ++- admin/src/translations/es.json | 120 ++- admin/src/translations/fr.json | 120 ++- admin/src/translations/pt.json | 120 ++- .../2026-11-17-provider-templates.md | 271 ++++++ docs/api.md | 51 +- docs/sending.md | 69 +- docs/site/img/core-email-design.webp | Bin 0 -> 42608 bytes docs/site/img/provider-template-dialog.webp | Bin 0 -> 49678 bytes docs/site/img/provider-templates.webp | Bin 0 -> 45172 bytes docs/site/img/readme/provider-templates.webp | Bin 0 -> 67018 bytes docs/site/index.html | 81 +- docs/upgrading.md | 4 + server/src/bootstrap.js | 131 +++ server/src/content-types/index.js | 4 + .../provider-template/schema.json | 81 ++ server/src/controllers/index.js | 2 + server/src/controllers/provider-templates.js | 242 +++++ server/src/routes/admin.js | 92 ++ server/src/services/email-router.js | 357 +++++++- server/src/services/index.js | 2 + server/src/services/provider-templates.js | 769 ++++++++++++++++ server/src/utils/client-errors.js | 7 +- server/src/utils/core-mail-payload.js | 245 +++++ server/src/utils/html-design.js | 146 +++ server/src/utils/plain-json.js | 213 +++++ server/src/utils/provider-api.js | 358 ++++++++ server/src/utils/template-syntax.js | 438 +++++++++ server/src/utils/template-variables.js | 561 ++++++++++++ server/src/validation.js | 36 + tests/accounts-oauth-hardening.test.js | 2 +- tests/admin/strict-mode.test.jsx | 156 +++- tests/fixtures/golden/core-reset-mailgun.json | 30 + .../fixtures/golden/core-reset-sendgrid.json | 54 ++ tests/fixtures/golden/core-reset-smtp.json | 49 + .../golden/local-mailgun-untracked.json | 35 + tests/fixtures/golden/local-mailgun.json | 53 ++ .../golden/local-sendgrid-untracked.json | 55 ++ tests/fixtures/golden/local-sendgrid.json | 79 ++ tests/fixtures/golden/local-smtp.json | 50 + tests/fixtures/golden/plain-sendgrid.json | 59 ++ .../fixtures/openapi/sendgrid-templates.json | 411 +++++++++ tests/golden-send-payloads.test.js | 389 ++++++++ tests/helpers/fake-template-providers.js | 242 +++++ tests/helpers/live-env.js | 175 ++++ tests/helpers/provider-template-strapi.js | 181 ++++ tests/live/provider-send.live.test.js | 398 ++++---- tests/live/provider-templates.live.test.js | 359 ++++++++ tests/live/sendgrid-account.live.test.js | 474 ++++++++++ tests/provider-template-utils.test.js | 582 ++++++++++++ tests/provider-templates-contract.test.js | 410 +++++++++ tests/provider-templates-integration.test.js | 855 ++++++++++++++++++ tests/provider-templates-units.test.js | 256 ++++++ tests/route-inventory.test.js | 14 +- 69 files changed, 11792 insertions(+), 269 deletions(-) create mode 100644 admin/src/pages/EmailDesigner/providerTemplates/ConvertForProviderPanel.jsx create mode 100644 admin/src/pages/EmailDesigner/providerTemplates/CoreDesignAlert.jsx create mode 100644 admin/src/pages/EmailDesigner/providerTemplates/CoreDesignDialog.jsx create mode 100644 admin/src/pages/EmailDesigner/providerTemplates/Notice.jsx create mode 100644 admin/src/pages/EmailDesigner/providerTemplates/ProviderTemplateDialog.jsx create mode 100644 admin/src/pages/EmailDesigner/providerTemplates/ProviderTemplatesSection.jsx create mode 100644 admin/src/pages/EmailDesigner/providerTemplates/providerTemplateStyles.js create mode 100644 admin/src/pages/EmailDesigner/providerTemplates/providerTemplateUtils.js create mode 100644 admin/src/pages/EmailDesigner/providerTemplates/useProviderTemplates.js create mode 100644 docs/acceptance/2026-11-17-provider-templates.md create mode 100644 docs/site/img/core-email-design.webp create mode 100644 docs/site/img/provider-template-dialog.webp create mode 100644 docs/site/img/provider-templates.webp create mode 100644 docs/site/img/readme/provider-templates.webp create mode 100644 server/src/content-types/provider-template/schema.json create mode 100644 server/src/controllers/provider-templates.js create mode 100644 server/src/services/provider-templates.js create mode 100644 server/src/utils/core-mail-payload.js create mode 100644 server/src/utils/html-design.js create mode 100644 server/src/utils/plain-json.js create mode 100644 server/src/utils/provider-api.js create mode 100644 server/src/utils/template-syntax.js create mode 100644 server/src/utils/template-variables.js create mode 100644 tests/fixtures/golden/core-reset-mailgun.json create mode 100644 tests/fixtures/golden/core-reset-sendgrid.json create mode 100644 tests/fixtures/golden/core-reset-smtp.json create mode 100644 tests/fixtures/golden/local-mailgun-untracked.json create mode 100644 tests/fixtures/golden/local-mailgun.json create mode 100644 tests/fixtures/golden/local-sendgrid-untracked.json create mode 100644 tests/fixtures/golden/local-sendgrid.json create mode 100644 tests/fixtures/golden/local-smtp.json create mode 100644 tests/fixtures/golden/plain-sendgrid.json create mode 100644 tests/fixtures/openapi/sendgrid-templates.json create mode 100644 tests/golden-send-payloads.test.js create mode 100644 tests/helpers/fake-template-providers.js create mode 100644 tests/helpers/live-env.js create mode 100644 tests/helpers/provider-template-strapi.js create mode 100644 tests/live/provider-templates.live.test.js create mode 100644 tests/live/sendgrid-account.live.test.js create mode 100644 tests/provider-template-utils.test.js create mode 100644 tests/provider-templates-contract.test.js create mode 100644 tests/provider-templates-integration.test.js create mode 100644 tests/provider-templates-units.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e98bed..e5c5d6a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,29 @@ +## [Unreleased] + +### Added + +* **provider templates:** SendGrid dynamic templates and Mailgun templates (domain and account level) appear read-only under **Email Templates → Provider templates** as soon as a SendGrid or Mailgun account exists. Sync reads them with the stored account key (never writes to the provider), follows the providers' pagination, uses the EU hosts for EU accounts, and refreshes itself when the list is older than 10 minutes. A template whose remote id disappears but whose name still exists on the account (a database moved to another environment) is matched by name. +* **provider templates:** preview dialog with a sandboxed preview, the detected variables, a code example, a test send (to your own admin address by default, with the same sample values as local templates), an optional local fallback template, and **Copy as Magic Mail template** (HTML copy; Handlebars blocks become Mustache sections and anything that does not carry over is listed). +* **sending:** `send({ to, providerTemplate: ':', data })` sends a synced template. The same `data` object that local templates render with Mustache is sent as SendGrid `dynamic_template_data` or Mailgun `t:variables`, converted to plain JSON (dates as ISO strings, no functions, no cycles) and checked against the provider limits (Mailgun: 16 KB for all send options; Magic Mail bounds template data to 1 MB). Routing, rules, failover, quotas and logs work as before, but only between accounts that have the template. Strict by default: a missing template or a provider refusal is a clear error; a local fallback template is sent only when it is configured and no provider accepted the message. The log stores the template key and variable names, never the values. +* **core emails:** password reset and email confirmation can use a provider template (**Core emails → Design**). Magic Mail sends the familiar users-permissions names (`URL`, `TOKEN`/`CODE`, `USER`, `SERVER_URL`, `ADMIN_URL`) plus `url` (the finished link), `baseUrl`, `serverUrl`, `adminUrl`, `user`, `token`/`code` and `meta` (`templateKey`, `payloadVersion: 1`, `coreEmailType`). `USER` contains only `id`, `email`, `username`, `firstname`, `lastname`. Optional fallback to the Magic Mail designer version. A red notice on the Core emails tab and the dashboard names core emails whose template is not available. +* **templates:** **Convert for SendGrid or Mailgun** in the code snippets dialog turns a local template's Mustache logic into Handlebars for upload at the provider. +* **admin API:** `GET /magic-mail/provider-templates`, `POST /magic-mail/provider-templates/sync`, `GET /magic-mail/provider-templates/:key`, `POST /magic-mail/provider-templates/:key/test-send`, `PUT /magic-mail/provider-templates/:key/settings`, `POST /magic-mail/provider-templates/:key/copy`, `GET /magic-mail/designer/templates/:id/provider-html`, `GET /magic-mail/designer/core-designs`, `PUT /magic-mail/designer/core/:coreEmailType/design`. Existing permissions: `read` (sync is read-only at the provider and rate limited), `test-send`, `manage`; the core-email routes also need the users-permissions email-template permissions. + +### Security + +* Provider ids are never accepted from callers, only synced keys. The public Content API send routes do not accept `providerTemplate`. +* Template previews render in a sandboxed iframe without scripts. Provider requests go only to the fixed SendGrid and Mailgun hosts, with timeouts and response size limits; paging URLs from the provider are never requested directly. + +### Migration + +* Provider templates: nothing to do. A new collection `magic_mail_provider_templates` is created on start; nothing changes for accounts without SendGrid or Mailgun. Sends without a provider template are byte-identical to 4.7.0 (golden payload tests). Provider-template sends are not queued in the outbox in this release. +* To sync SendGrid templates, the SendGrid key also needs **Template Engine → Read Access** (sending alone needs only **Mail Send**). + +### Verification + +* SendGrid: tested live against the real SendGrid API on 2026-11-18, every send in sandbox mode: template sync with pagination, variable detection and preview, template sends, unknown and malformed template ids, the 1 MB data bound, and the template life cycle with temporary templates (no version, a first and a second active version, deleted and re-created under the same name, deleted for good). Temporary objects were deleted afterwards. The EU host could not be tested live (no EU subuser). +* Mailgun: verified against Mailgun's official OpenAPI specification and with tests, but not yet against the live Mailgun API. Please report anything unexpected. + # [4.7.0](https://github.com/Schero94/Magic-Mail/compare/v4.6.3...v4.7.0) (2026-11-18) diff --git a/README.md b/README.md index 3d30b0e..6d223bc 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,7 @@ MagicMail sends email only. It is MIT licensed, with no license key, tiers or us - **Outbox with retries.** Opt-in per send or for every failed send: 3 retries by default (after 1, 5 and 15 minutes, configurable from 1 to 10), idempotency keys, and an Outbox tab where you retry, discard or mark uncertain mails as sent. - **Delivery webhooks.** Signed SendGrid and Mailgun webhooks record bounces, blocks, complaints, deferrals, deliveries and unsubscribes on the delivery log, feed the suppression list and emit events other plugins can listen to. - **Templates.** A visual editor (Unlayer) or plain HTML and text, Mustache variables, versions with restore, import and export, plus the Users & Permissions reset and confirmation mails. +- **Provider templates.** Keep designing in SendGrid or Mailgun: their templates appear read-only in MagicMail, with preview, test send and the same template data your code already passes. Routing, failover and logs stay in MagicMail, and the password-reset and confirmation mails can use them too. - **Analytics.** A delivery log with server-side search, open and click tracking with truncated IPs and configurable retention. - **Several instances.** Railway replicas or pm2 workers on one database work without sticky sessions or Redis. - **Admin in five languages.** English, German, French, Spanish and Portuguese, in light and dark mode. @@ -78,6 +79,10 @@ All screenshots show synthetic data (`example.test` addresses) on an isolated St ![Email templates: totals, the custom and core email tabs, and a table of four templates with ID, name, category, status and actions](https://raw.githubusercontent.com/Schero94/Magic-Mail/main/docs/site/img/readme/templates.webp) +**Provider templates**: with a SendGrid or Mailgun account, their templates appear under your own, with the provider, the change date there, the accounts that have them and their status. + +![Provider templates: SendGrid and Mailgun templates with provider badge, key, change date at the provider, account and status under the local templates](https://raw.githubusercontent.com/Schero94/Magic-Mail/main/docs/site/img/readme/provider-templates.webp) + **Analytics**: totals and the delivery log with server-side search, delivery status, opens and clicks per email. ![Analytics: sent, opened, clicked and bounced totals and the delivery log with recipient, subject, status, template, time, opens and clicks](https://raw.githubusercontent.com/Schero94/Magic-Mail/main/docs/site/img/readme/analytics.webp) @@ -159,20 +164,33 @@ await strapi.plugin('magic-mail').service('email-router').send({ // → { success: true, accountUsed: 'Transactional SMTP', messageId: '<…>', emailId: '…' } ``` -All send options, attachments, unsubscribe headers, provider setup, routing rules and templates: [Sending guide](https://github.com/Schero94/Magic-Mail/blob/main/docs/sending.md). HTTP routes: [API reference](https://github.com/Schero94/Magic-Mail/blob/main/docs/api.md). +Designed your email in SendGrid or Mailgun? Send the synced template with the same data a MagicMail template gets (only accounts that have the template send it): + +```javascript +await strapi + .plugin('magic-mail') + .service('email-router') + .send({ + to: 'customer@example.com', + providerTemplate: 'sendgrid:welcome-email', // key shown in Email Templates → Provider templates + data: { name: 'Ada', user: { email: 'customer@example.com' } }, + }); +``` + +All send options, attachments, unsubscribe headers, provider setup, routing rules, templates and [provider templates](https://github.com/Schero94/Magic-Mail/blob/main/docs/sending.md#provider-templates-sendgrid-mailgun): [Sending guide](https://github.com/Schero94/Magic-Mail/blob/main/docs/sending.md). HTTP routes: [API reference](https://github.com/Schero94/Magic-Mail/blob/main/docs/api.md). ## Permissions MagicMail registers six admin actions under **Settings → Administration Panel → Roles → Plugins → MagicMail**: -| Action | Grants | -| --------------------------------- | --------------------------------------------------------------------------------------------------------------- | -| `plugin::magic-mail.access` | The MagicMail menu entry and page. No API access by itself | -| `plugin::magic-mail.read` | Read accounts, routing rules, templates, analytics and settings; render and export templates; the settings link | -| `plugin::magic-mail.manage` | Create, update and delete accounts, rules, templates, logs and settings; OAuth setup | -| `plugin::magic-mail.test-send` | Send test emails (account test, Strapi-service test, template test); 10 per minute per admin | -| `plugin::magic-mail.queue.read` | The Outbox tab and queue statistics (no mail content) | -| `plugin::magic-mail.queue.manage` | Retry, discard, mark as sent and delete outbox mails | +| Action | Grants | +| --------------------------------- | ------------------------------------------------------------------------------------------------------------------ | +| `plugin::magic-mail.access` | The MagicMail menu entry and page. No API access by itself | +| `plugin::magic-mail.read` | Read accounts, routing rules, templates, analytics and settings; render and export templates; the settings link | +| `plugin::magic-mail.manage` | Create, update and delete accounts, rules, templates, logs and settings; OAuth setup | +| `plugin::magic-mail.test-send` | Send test emails (account test, Strapi-service test, template and provider-template test); 10 per minute per admin | +| `plugin::magic-mail.queue.read` | The Outbox tab and queue statistics (no mail content) | +| `plugin::magic-mail.queue.manage` | Retry, discard, mark as sent and delete outbox mails | Typical roles: @@ -256,7 +274,7 @@ npm run verify npm run verify:runtime ``` -`npm run test:live` runs the opt-in suite against the real SendGrid and Mailgun APIs (SendGrid sandbox mode and Mailgun test mode, nothing is delivered; Mailgun bills test-mode messages). It reads `~/.config/magic-mail-live/.env` with `SENDGRID_API_KEY`, `SENDGRID_FROM`, `MAILGUN_API_KEY`, `MAILGUN_DOMAIN`, `MAILGUN_REGION`, `LIVE_TEST_RECIPIENT` and optionally `SENDGRID_REGION`, `SENDGRID_EU_API_KEY`, `SENDGRID_EU_FROM`, `MAILGUN_FROM`, `MAILGUN_EU_DOMAIN`, `MAILGUN_EU_API_KEY`; without the file every live test is skipped. Never commit that file. +`npm run test:live` runs the opt-in live suites against the real SendGrid and Mailgun APIs: the send paths (`tests/live/provider-send.live.test.js`), the provider-template flows (`tests/live/provider-templates.live.test.js`) and the rest of the SendGrid integration (`tests/live/sendgrid-account.live.test.js`: restricted API keys, template versions, read-only account checks; it creates temporary `magic-mail-live-*` API keys and templates and deletes them again, so its key needs full access). SendGrid runs in sandbox mode and Mailgun in test mode, so nothing is delivered (Mailgun bills test-mode messages). Credentials come only from `~/.config/magic-mail-live/.env` and are never printed. `LIVE_PROVIDERS` (environment variable or a line in that file) picks the providers: `sendgrid`, `mailgun` or `sendgrid,mailgun`; without it, every provider whose required variables are complete runs. Tests of a provider that is not selected are skipped with the reason. For SendGrid only: `LIVE_PROVIDERS=sendgrid npm run test:live`. Required per provider: SendGrid needs `SENDGRID_API_KEY`, `SENDGRID_FROM`, `LIVE_TEST_RECIPIENT` and, for the template suite, `SENDGRID_TEMPLATE_ID`; Mailgun needs `MAILGUN_API_KEY`, `MAILGUN_DOMAIN`, `MAILGUN_REGION`, `LIVE_TEST_RECIPIENT` and, for the template suite, `MAILGUN_TEMPLATE`. Optional: `SENDGRID_REGION`, `SENDGRID_EU_API_KEY`, `SENDGRID_EU_FROM`, `MAILGUN_FROM`, `MAILGUN_EU_DOMAIN`, `MAILGUN_EU_API_KEY`. Without the file, or when a selected provider misses a variable, the template suite fails with the file name and the missing variable names (the send suite reports those tests as skipped). It never runs in CI. Never commit that file. `npm run test:admin` renders every admin entry point (the five sections of the MagicMail page with their dialogs, the template editor, the Plugin Settings page) inside `React.StrictMode` with the providers of the Strapi admin, in jsdom with a fake network. It fails on a mutation sent twice, a read repeated without aborting the first one, an interval, listener, connection or observer left after unmount, and any console error or warning. A separate CI job runs the same tests against React 19 for information only: the plugin's peer range is React 18, like the Strapi 5 admin. diff --git a/admin/src/pages/EmailDesigner/TemplateCodeSnippetsModal.jsx b/admin/src/pages/EmailDesigner/TemplateCodeSnippetsModal.jsx index de3bfb8..ca77bda 100644 --- a/admin/src/pages/EmailDesigner/TemplateCodeSnippetsModal.jsx +++ b/admin/src/pages/EmailDesigner/TemplateCodeSnippetsModal.jsx @@ -6,6 +6,7 @@ import { useCopyToClipboard } from '../../hooks/useCopyToClipboard'; import { useMagicMailIntl } from '../../hooks/useMagicMailIntl'; import { useReturnFocus } from '../../hooks/useReturnFocus'; import { buildCodeSnippets, snippetText } from './codeSnippets'; +import { ConvertForProviderPanel } from './providerTemplates/ConvertForProviderPanel'; import { AccentText, CodeBlock, @@ -38,9 +39,17 @@ const CodeTokens = ({ tokens }) => /** * "Code snippets" dialog for one template. * - * @param {{template: object|null, isOpen: boolean, onClose: () => void}} props + * With a SendGrid or Mailgun account (`providerEnabled`), an extra section + * converts the template for the provider ("Convert for provider"). + * + * @param {{template: object|null, isOpen: boolean, onClose: () => void, providerEnabled?: boolean}} props */ -export const TemplateCodeSnippetsModal = ({ template, isOpen, onClose }) => { +export const TemplateCodeSnippetsModal = ({ + template, + isOpen, + onClose, + providerEnabled = false, +}) => { const { t } = useMagicMailIntl(); const copy = useCopyToClipboard(); const [copiedKey, setCopiedKey] = useState(null); @@ -187,6 +196,20 @@ export const TemplateCodeSnippetsModal = ({ template, isOpen, onClose }) => { ); })} + {providerEnabled ? ( + + + + + + + + + + + ) : null} diff --git a/admin/src/pages/EmailDesigner/TemplateList.jsx b/admin/src/pages/EmailDesigner/TemplateList.jsx index 65acbe0..517254c 100644 --- a/admin/src/pages/EmailDesigner/TemplateList.jsx +++ b/admin/src/pages/EmailDesigner/TemplateList.jsx @@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef, useState } from 'react'; import { useFetchClient, useNotification } from '@strapi/strapi/admin'; import { useNavigate } from 'react-router-dom'; import { + Box, Button, Divider, Flex, @@ -25,6 +26,7 @@ import { PaperPlane, Pencil, Trash, + Palette, Upload, WarningCircle, } from '@strapi/icons'; @@ -66,6 +68,12 @@ import { TemplateCodeSnippetsModal } from './TemplateCodeSnippetsModal'; import { TemplateTestSendModal } from './TemplateTestSendModal'; import { downloadBlob } from './editorUtils'; import { PAGE_SIZE_OPTIONS, filterTemplates, getCategoryVariant } from './templateListUtils'; +import { useProviderTemplates } from './providerTemplates/useProviderTemplates'; +import { ProviderTemplatesSection } from './providerTemplates/ProviderTemplatesSection'; +import { ProviderTemplateDialog } from './providerTemplates/ProviderTemplateDialog'; +import { CoreDesignDialog } from './providerTemplates/CoreDesignDialog'; +import { Notice } from './providerTemplates/Notice'; +import { providerName, statusInfo } from './providerTemplates/providerTemplateUtils'; import { Container, EmptyButtonGroup, @@ -123,6 +131,31 @@ const TemplateList = () => { const canExport = canRead; const canImport = canManage; + // Provider templates (SendGrid / Mailgun): everything below stays hidden + // until the overview reports at least one such account. + const providerTemplates = useProviderTemplates({ enabled: canRead }); + const providerEnabled = providerTemplates.overview?.enabled === true; + const [openProviderKey, setOpenProviderKey] = useState(null); + const [coreDesigns, setCoreDesigns] = useState(null); + const [coreDesignFor, setCoreDesignFor] = useState(null); + + // Core-mail design choices; a role without the users-permissions template + // permission gets a 403 and simply does not see the design column. + useEffect(() => { + if (!providerEnabled) return undefined; + let ignore = false; + get('/magic-mail/designer/core-designs') + .then((response) => { + if (!ignore) setCoreDesigns(response?.data?.data ?? null); + }) + .catch(() => { + if (!ignore) setCoreDesigns(null); + }); + return () => { + ignore = true; + }; + }, [get, providerEnabled, providerTemplates.overview]); + const coreEmailTypes = [ { type: 'reset-password', @@ -733,10 +766,51 @@ const TemplateList = () => { {renderTableBody()} + + setOpenProviderKey(template.key)} + /> ); }; + const showDesignColumn = providerEnabled && coreDesigns !== null; + const unusableCoreDesigns = showDesignColumn + ? coreEmailTypes.filter((coreEmail) => coreDesigns[coreEmail.type]?.usable === false) + : []; + + /** Design cell of a core email row: designer or provider template (+ problem badge). */ + const renderCoreDesign = (coreEmail) => { + const design = coreDesigns?.[coreEmail.type]; + if (!design || design.mode !== 'provider') { + return ( + + {t('templates.coreDesign.designerShort', 'Magic Mail designer')} + + ); + } + const status = statusInfo(design.status); + return ( + + + {t('templates.coreDesign.providerShort', '{name} ({provider})', { + name: design.templateName ?? design.providerTemplate, + provider: providerName(design.provider), + })} + + {design.usable ? null : ( + {t(status.id, status.label)} + )} + + ); + }; + return (
@@ -815,11 +889,33 @@ const TemplateList = () => { + {unusableCoreDesigns.length > 0 ? ( + + + {t( + 'templates.coreDesign.staleBody', + '{names}: these emails fail until the template is available again and synced, or until you switch back to the Magic Mail designer.', + { names: unusableCoreDesigns.map((coreEmail) => coreEmail.name).join(', ') } + )} + + + ) : null} + - + {t('templates.core.table.type', 'Email type')} + {showDesignColumn ? ( + {t('templates.core.table.design', 'Design')} + ) : null} {t('templates.table.actions', 'Actions')} @@ -841,8 +937,27 @@ const TemplateList = () => { + {showDesignColumn ? ( + + {renderCoreDesign(coreEmail)} + + ) : null} + {showDesignColumn && canManage ? ( + setCoreDesignFor(coreEmail)} + > + + ) : null} { template={codeTemplate} isOpen={codeTemplate !== null} onClose={() => setCodeTemplate(null)} + providerEnabled={providerEnabled} + /> + + setOpenProviderKey(null)} + canManage={canManage} + canTestSend={canTestSend} + localTemplates={templates} + onChanged={providerTemplates.reload} + /> + + setCoreDesignFor(null)} + onSaved={(design) => + setCoreDesigns((current) => + current && design && coreDesignFor + ? { ...current, [coreDesignFor.type]: design } + : current + ) + } /> { + const { t } = useMagicMailIntl(); + const { get } = useFetchClient(); + const copy = useCopyToClipboard(); + const [result, setResult] = useState(null); + const [failed, setFailed] = useState(false); + + useEffect(() => { + let ignore = false; + get(`/magic-mail/designer/templates/${encodeURIComponent(templateReferenceId)}/provider-html`) + .then((response) => { + if (!ignore) setResult(response?.data?.data ?? null); + }) + .catch(() => { + if (!ignore) setFailed(true); + }); + return () => { + ignore = true; + }; + }, [get, templateReferenceId]); + + if (failed) { + return ( + + {t('templates.convert.failure', 'The template could not be converted.')} + + ); + } + if (!result) { + return ( + + {t('templates.convert.loading', 'Converting...')} + + ); + } + + return ( + + + {t( + 'templates.convert.description', + 'Paste this HTML into a SendGrid dynamic template or a Mailgun template, then sync. Variables keep their names; only logic blocks change.' + )} + + {result.warnings.length > 0 ? ( + + + {result.warnings.slice(0, 8).map((warning, index) => { + const info = conversionWarning(warning.code); + return ( +
  • + {t('templates.provider.copy.warningLine', 'Line {line}: {message}', { + line: warning.line, + message: t(info.id, info.label), + })} +
  • + ); + })} +
    +
    + ) : null} + + + {t('templates.convert.subject', 'Subject')} + + {result.subject} + + + + {t('templates.convert.html', 'HTML')} + + {result.html} + + + + copy(result.html, { success: t('templates.convert.copied', 'HTML copied.') }) + } + > + {t('templates.convert.copyHtml', 'Copy HTML')} + + + copy(result.subject, { + success: t('templates.convert.subjectCopied', 'Subject copied.'), + }) + } + > + {t('templates.convert.copySubject', 'Copy subject')} + + +
    + ); +}; + +export default ConvertForProviderPanel; diff --git a/admin/src/pages/EmailDesigner/providerTemplates/CoreDesignAlert.jsx b/admin/src/pages/EmailDesigner/providerTemplates/CoreDesignAlert.jsx new file mode 100644 index 0000000..1690081 --- /dev/null +++ b/admin/src/pages/EmailDesigner/providerTemplates/CoreDesignAlert.jsx @@ -0,0 +1,79 @@ +import { useEffect, useState } from 'react'; +import { useFetchClient } from '@strapi/strapi/admin'; +import { useNavigate } from 'react-router-dom'; +import { Box } from '@strapi/design-system'; +import { TertiaryButton } from '../../../components/StyledButtons'; +import { useMagicMailIntl } from '../../../hooks/useMagicMailIntl'; +import { Notice } from './Notice'; + +const CORE_NAMES = { + 'reset-password': { id: 'templates.core.resetPassword.name', label: 'Reset password' }, + 'email-confirmation': { + id: 'templates.core.emailConfirmation.name', + label: 'Email address confirmation', + }, +}; + +/** + * Dashboard notice: a core email uses a provider template that is deleted or + * has no active version, so those emails fail. Renders nothing otherwise, and + * nothing without a SendGrid or Mailgun account (`enabled`). + * + * @param {{enabled: boolean}} props + * @returns {import('react').ReactElement|null} + */ +export const CoreDesignAlert = ({ enabled }) => { + const { t } = useMagicMailIntl(); + const { get } = useFetchClient(); + const navigate = useNavigate(); + const [designs, setDesigns] = useState(null); + + useEffect(() => { + if (!enabled) return undefined; + let ignore = false; + get('/magic-mail/designer/core-designs') + .then((response) => { + if (!ignore) setDesigns(response?.data?.data ?? null); + }) + .catch(() => { + // No users-permissions template permission or no data: no notice. + if (!ignore) setDesigns(null); + }); + return () => { + ignore = true; + }; + }, [enabled, get]); + + const broken = Object.entries(designs ?? {}).filter(([, design]) => design?.usable === false); + if (!enabled || broken.length === 0) return null; + + return ( + + navigate('/plugins/magic-mail/designer')}> + {t('templates.coreDesign.openTemplates', 'Open email templates')} + + } + > + {t( + 'templates.coreDesign.staleBody', + '{names}: these emails fail until the template is available again and synced, or until you switch back to the Magic Mail designer.', + { + names: broken + .map(([type]) => t(CORE_NAMES[type]?.id ?? type, CORE_NAMES[type]?.label ?? type)) + .join(', '), + } + )} + + + ); +}; + +export default CoreDesignAlert; diff --git a/admin/src/pages/EmailDesigner/providerTemplates/CoreDesignDialog.jsx b/admin/src/pages/EmailDesigner/providerTemplates/CoreDesignDialog.jsx new file mode 100644 index 0000000..ce89caa --- /dev/null +++ b/admin/src/pages/EmailDesigner/providerTemplates/CoreDesignDialog.jsx @@ -0,0 +1,265 @@ +import { useEffect, useState } from 'react'; +import { useFetchClient, useNotification } from '@strapi/strapi/admin'; +import { + Box, + Checkbox, + Field, + Flex, + Modal, + SingleSelect, + SingleSelectOption, + Typography, +} from '@strapi/design-system'; +import { GradientButton, TertiaryButton } from '../../../components/StyledButtons'; +import { useMagicMailIntl } from '../../../hooks/useMagicMailIntl'; +import { useReturnFocus } from '../../../hooks/useReturnFocus'; +import { + ScrollableDialogBody, + StyledModalContent, + StyledModalFooter, + StyledModalHeader, +} from '../templateListStyles'; +import { Notice } from './Notice'; +import { missingCoreVariables, providerName, statusInfo } from './providerTemplateUtils'; +import { VariableItem, VariableList } from './providerTemplateStyles'; + +const DESIGNER = '__designer__'; + +/** + * Chooses the design of one core email: the Magic Mail designer (default) or + * a synced provider template. One choice, one Save. + * + * @param {object} props + * @param {{type: string, name: string}|null} props.coreEmail - Open for this core email; null closes + * @param {object|undefined} props.design - Current design entry (GET /designer/core-designs) + * @param {object[]} props.templates - Synced provider templates (overview.templates) + * @param {() => void} props.onClose + * @param {(design: object) => void} props.onSaved + * @returns {import('react').ReactElement} + */ +export const CoreDesignDialog = ({ coreEmail, design, templates, onClose, onSaved }) => { + const { t } = useMagicMailIntl(); + const { get, put } = useFetchClient(); + const { toggleNotification } = useNotification(); + const isOpen = Boolean(coreEmail); + const returnFocus = useReturnFocus(isOpen); + + const initialChoice = design?.providerTemplate ?? DESIGNER; + const [choice, setChoice] = useState(initialChoice); + const [fallback, setFallback] = useState(design?.fallbackToDesigner === true); + const [saving, setSaving] = useState(false); + const [variables, setVariables] = useState(null); + + // Start from the stored choice each time the dialog opens. + const [openedFor, setOpenedFor] = useState(null); + if ((coreEmail?.type ?? null) !== openedFor) { + setOpenedFor(coreEmail?.type ?? null); + setChoice(initialChoice); + setFallback(design?.fallbackToDesigner === true); + setVariables(null); + } + + useEffect(() => { + if (!isOpen || choice === DESIGNER) return undefined; + let ignore = false; + get(`/magic-mail/provider-templates/${encodeURIComponent(choice)}`) + .then((response) => { + if (!ignore) setVariables(response?.data?.data?.variables ?? []); + }) + .catch(() => { + if (!ignore) setVariables([]); + }); + return () => { + ignore = true; + }; + }, [choice, get, isOpen]); + + const selected = templates.find((template) => template.key === choice) ?? null; + const dirty = + choice !== initialChoice || + (choice !== DESIGNER && fallback !== (design?.fallbackToDesigner === true)); + const sent = design?.variables ?? []; + const missing = choice !== DESIGNER && variables ? missingCoreVariables(variables, sent) : []; + // Templates that can be chosen: usable ones, plus the stored one even when stale. + const options = templates.filter( + (template) => template.usable || template.key === design?.providerTemplate + ); + + const handleClose = () => { + if (!saving) onClose(); + }; + + /** Saves the choice; the dialog stays open on errors. */ + const save = async (event) => { + event?.preventDefault?.(); + if (!coreEmail || saving || !dirty) return; + setSaving(true); + try { + const response = await put( + `/magic-mail/designer/core/${encodeURIComponent(coreEmail.type)}/design`, + choice === DESIGNER + ? { providerTemplate: null } + : { providerTemplate: choice, fallbackToDesigner: fallback } + ); + toggleNotification({ + type: 'success', + message: + choice === DESIGNER + ? t('templates.coreDesign.savedDesigner', '{name} now uses the Magic Mail designer.', { + name: coreEmail.name, + }) + : t('templates.coreDesign.savedProvider', '{name} now uses "{template}".', { + name: coreEmail.name, + template: selected?.name ?? choice, + }), + }); + onSaved(response?.data?.data); + onClose(); + } catch (error) { + toggleNotification({ + type: 'danger', + message: + error?.response?.data?.error?.message || + t('templates.coreDesign.failure', 'The design could not be saved.'), + }); + } finally { + setSaving(false); + } + }; + + return ( + !open && handleClose()}> + +
    + + + {t('templates.coreDesign.title', 'Design of {name}', { name: coreEmail?.name ?? '' })} + + + + + + {t('templates.coreDesign.label', 'Design')} + setChoice(String(value))} + disabled={saving} + > + + {t('templates.coreDesign.designer', 'Magic Mail designer (default)')} + + {options.map((template) => ( + + {t('templates.coreDesign.option', '{name} ({provider})', { + name: template.name, + provider: providerName(template.provider), + })} + + ))} + + + + + {choice !== DESIGNER && selected && !selected.usable ? ( + + {t( + 'templates.coreDesign.staleSelected', + 'This template is "{status}". Sends fail until it is available again.', + { + status: t(statusInfo(selected.status).id, statusInfo(selected.status).label), + } + )} + + ) : null} + + {choice !== DESIGNER ? ( + <> + + + {t('templates.coreDesign.sentHeading', 'Variables Magic Mail sends')} + + + {t( + 'templates.coreDesign.sentHint', + 'Use these names in the provider template. "url" is the finished link with the code.' + )} + + + {sent + .filter((name) => !name.startsWith('meta.') && !name.startsWith('USER.')) + .map((name) => ( + + {name} + + ))} + + + + {missing.length > 0 ? ( + + {t('templates.coreDesign.missingBody', 'These render empty: {names}', { + names: missing.join(', '), + })} + + ) : null} + + + setFallback(value === true)} + disabled={saving} + > + {t( + 'templates.coreDesign.fallback', + 'If the provider template fails, send the Magic Mail designer version instead' + )} + + + + {t( + 'templates.coreDesign.fallbackHint', + 'Off: the email fails with a clear error and nothing else is sent.' + )} + + + + + ) : null} + + + + + {t('common.cancel', 'Cancel')} + + + {t('common.save', 'Save')} + + +
    +
    +
    + ); +}; + +export default CoreDesignDialog; diff --git a/admin/src/pages/EmailDesigner/providerTemplates/Notice.jsx b/admin/src/pages/EmailDesigner/providerTemplates/Notice.jsx new file mode 100644 index 0000000..f69fcd4 --- /dev/null +++ b/admin/src/pages/EmailDesigner/providerTemplates/Notice.jsx @@ -0,0 +1,59 @@ +import { Box, Flex, Typography } from '@strapi/design-system'; +import { CheckCircle, Information, WarningCircle } from '@strapi/icons'; + +const TONES = { + danger: { background: 'danger100', border: 'danger200', icon: 'danger600', Icon: WarningCircle }, + warning: { + background: 'warning100', + border: 'warning200', + icon: 'warning600', + Icon: WarningCircle, + }, + info: { background: 'primary100', border: 'primary200', icon: 'primary600', Icon: Information }, + success: { + background: 'success100', + border: 'success200', + icon: 'success600', + Icon: CheckCircle, + }, +}; + +/** + * Persistent inline notice (no close button, unlike the DS Alert, whose close + * button is always rendered). Text stays neutral800 for contrast in both + * themes; the tone is carried by the icon, the background and the title. + * + * @param {object} props + * @param {'danger'|'warning'|'info'|'success'} [props.tone='info'] + * @param {string} [props.title] + * @param {import('react').ReactNode} props.children + * @param {import('react').ReactNode} [props.action] - Optional button under the text + * @param {'alert'|'status'|'note'} [props.role='note'] + * @returns {import('react').ReactElement} + */ +export const Notice = ({ tone = 'info', title, children, action, role = 'note' }) => { + const style = TONES[tone] ?? TONES.info; + const Icon = style.Icon; + return ( + + + + + + {title ? ( + + {title} + + ) : null} + + {children} + + {action ? {action} : null} + + + + ); +}; + +export default Notice; diff --git a/admin/src/pages/EmailDesigner/providerTemplates/ProviderTemplateDialog.jsx b/admin/src/pages/EmailDesigner/providerTemplates/ProviderTemplateDialog.jsx new file mode 100644 index 0000000..caea0de --- /dev/null +++ b/admin/src/pages/EmailDesigner/providerTemplates/ProviderTemplateDialog.jsx @@ -0,0 +1,578 @@ +import { useEffect, useRef, useState } from 'react'; +import { useFetchClient, useNotification } from '@strapi/strapi/admin'; +import { useNavigate } from 'react-router-dom'; +import { + Box, + Field, + Flex, + Loader, + Modal, + SingleSelect, + SingleSelectOption, + TextInput, + Typography, +} from '@strapi/design-system'; +import { CheckIcon, ClipboardDocumentIcon, PaperAirplaneIcon } from '@heroicons/react/24/outline'; +import { GradientButton, SecondaryButton, TertiaryButton } from '../../../components/StyledButtons'; +import { ConfirmDialog } from '../../../components/shared/ConfirmDialog'; +import { StatusBadge } from '../../../components/shared/table'; +import { useCopyToClipboard } from '../../../hooks/useCopyToClipboard'; +import { useFormatters } from '../../../hooks/useFormatters'; +import { useMagicMailIntl } from '../../../hooks/useMagicMailIntl'; +import { useReturnFocus } from '../../../hooks/useReturnFocus'; +import { validateTestSendInput } from '../templateListUtils'; +import { + CodeModalContent, + ScrollableDialogBody, + StyledModalFooter, + StyledModalHeader, +} from '../templateListStyles'; +import { Notice } from './Notice'; +import { conversionWarning, providerName, statusInfo } from './providerTemplateUtils'; +import { ConvertedCode, PreviewFrame, VariableList, VariableItem } from './providerTemplateStyles'; + +const NO_FALLBACK = '__none__'; + +/** + * Preview dialog of one provider template: read-only preview, detected + * variables, the code to send it, the optional local fallback and a test + * send. One primary action ("Send test"); "Copy as Magic Mail template" is + * the secondary action. + * + * @param {object} props + * @param {string|null} props.templateKey - Key of the template to show; null closes + * @param {() => void} props.onClose + * @param {boolean} props.canManage - May set the fallback and copy + * @param {boolean} props.canTestSend - May send a test + * @param {Array<{templateReferenceId: number, name: string}>} props.localTemplates + * @param {() => void} props.onChanged - Called after the fallback changed + * @returns {import('react').ReactElement} + */ +export const ProviderTemplateDialog = ({ + templateKey, + onClose, + canManage, + canTestSend, + localTemplates, + onChanged, +}) => { + const { t } = useMagicMailIntl(); + const { get, post, put } = useFetchClient(); + const { toggleNotification } = useNotification(); + const { formatDateTime } = useFormatters(); + const navigate = useNavigate(); + const copy = useCopyToClipboard(); + const isOpen = Boolean(templateKey); + const returnFocus = useReturnFocus(isOpen); + + const [detail, setDetail] = useState(null); + const [loadError, setLoadError] = useState(false); + const [reloadKey, setReloadKey] = useState(0); + const [recipient, setRecipient] = useState(''); + const [recipientError, setRecipientError] = useState(null); + const [sending, setSending] = useState(false); + const [savingFallback, setSavingFallback] = useState(false); + const [copying, setCopying] = useState(false); + const [confirmCopy, setConfirmCopy] = useState(false); + const [snippetCopied, setSnippetCopied] = useState(false); + const copiedTimer = useRef(null); + + useEffect(() => () => clearTimeout(copiedTimer.current), []); + + // Reset when another template opens (adjusted while rendering). + const [shownKey, setShownKey] = useState(null); + if (templateKey !== shownKey) { + setShownKey(templateKey); + setDetail(null); + setLoadError(false); + setRecipient(''); + setRecipientError(null); + setConfirmCopy(false); + } + + useEffect(() => { + if (!templateKey) return undefined; + let ignore = false; + get(`/magic-mail/provider-templates/${encodeURIComponent(templateKey)}`) + .then((response) => { + if (!ignore) setDetail(response?.data?.data ?? null); + }) + .catch(() => { + if (!ignore) setLoadError(true); + }); + return () => { + ignore = true; + }; + }, [get, templateKey, reloadKey]); + + const busy = sending || copying || savingFallback; + const handleClose = () => { + if (!busy) onClose(); + }; + + /** Sends the template to the given address, or to the signed-in admin. */ + const sendTest = async (event) => { + event?.preventDefault?.(); + if (sending || !detail) return; + let to; + if (recipient.trim()) { + const result = validateTestSendInput({ to: recipient, cc: '' }); + if (!result.valid) { + setRecipientError( + t( + 'templates.testSend.errors.toInvalid', + 'Enter a valid email address, for example name@example.com.' + ) + ); + return; + } + to = result.to; + } + setRecipientError(null); + setSending(true); + try { + const response = await post( + `/magic-mail/provider-templates/${encodeURIComponent(detail.key)}/test-send`, + to ? { to } : {} + ); + toggleNotification({ + type: 'success', + message: t('templates.provider.testSend.success', 'Test email sent to {email}.', { + email: response?.data?.data?.recipient ?? to ?? '', + }), + }); + } catch (error) { + toggleNotification({ + type: 'danger', + message: + error?.response?.data?.error?.message || + t('templates.testSend.failure', 'The test email could not be sent.'), + }); + } finally { + setSending(false); + } + }; + + /** Saves the local fallback template right away. */ + const changeFallback = async (value) => { + if (!detail || savingFallback) return; + const next = value === NO_FALLBACK ? null : Number(value); + setSavingFallback(true); + try { + const response = await put( + `/magic-mail/provider-templates/${encodeURIComponent(detail.key)}/settings`, + { fallbackTemplateReferenceId: next } + ); + setDetail((current) => ({ + ...current, + fallbackTemplateReferenceId: response?.data?.data?.fallbackTemplateReferenceId ?? null, + })); + toggleNotification({ + type: 'success', + message: + next === null + ? t( + 'templates.provider.fallback.cleared', + 'Fallback removed. Failed sends report an error.' + ) + : t('templates.provider.fallback.saved', 'Fallback template saved.'), + }); + onChanged?.(); + } catch (error) { + toggleNotification({ + type: 'danger', + message: + error?.response?.data?.error?.message || + t('templates.provider.fallback.failure', 'The fallback could not be saved.'), + }); + } finally { + setSavingFallback(false); + } + }; + + /** Creates the local copy and opens it in the designer. */ + const copyAsLocal = async () => { + if (!detail || copying) return; + setCopying(true); + try { + const response = await post( + `/magic-mail/provider-templates/${encodeURIComponent(detail.key)}/copy` + ); + const created = response?.data?.data; + toggleNotification({ + type: created?.warnings?.length ? 'warning' : 'success', + message: created?.warnings?.length + ? t( + 'templates.provider.copy.successWithWarnings', + 'Copy created. Check the marked blocks in the designer before you use it.' + ) + : t('templates.provider.copy.success', 'Copy created as a Magic Mail template.'), + }); + setConfirmCopy(false); + onClose(); + if (created?.templateReferenceId) { + navigate(`/plugins/magic-mail/designer/${created.templateReferenceId}`); + } + } catch (error) { + toggleNotification({ + type: 'danger', + message: + error?.response?.data?.error?.message || + t('templates.provider.copy.failure', 'The template could not be copied.'), + }); + } finally { + setCopying(false); + } + }; + + const startCopy = () => { + if (detail?.copyWarnings?.length) setConfirmCopy(true); + else copyAsLocal(); + }; + + const copySnippet = async () => { + const copied = await copy(detail?.usage ?? '', { + success: t('templates.code.copied', 'Code copied to clipboard'), + }); + if (!copied) return; + setSnippetCopied(true); + clearTimeout(copiedTimer.current); + copiedTimer.current = setTimeout(() => setSnippetCopied(false), 2000); + }; + + const status = detail ? statusInfo(detail.status) : null; + const provider = detail ? providerName(detail.provider) : ''; + const notSentInTest = (detail?.variables ?? []).filter((variable) => !variable.inSample); + const fallbackValue = + detail?.fallbackTemplateReferenceId != null + ? String(detail.fallbackTemplateReferenceId) + : NO_FALLBACK; + + const renderBody = () => { + if (loadError) { + return ( + { + setLoadError(false); + setReloadKey((key) => key + 1); + }} + > + {t('common.table.retry', 'Try again')} + + } + > + {t( + 'templates.provider.detail.errorHint', + 'Sync the provider templates and open it again.' + )} + + ); + } + if (!detail) { + return ( + + {t('templates.provider.detail.loading', 'Loading template...')} + + ); + } + return ( + + + {provider} + {t(status.id, status.label)} + + {t('templates.provider.detail.changed', 'Changed at {provider}: {date}', { + provider, + date: formatDateTime(detail.updatedAtProvider), + })} + + + + {detail.status === 'missing' || detail.status === 'unpublished' ? ( + + {t( + 'templates.provider.detail.staleBody', + 'Sends with this template fail with a clear error until it is available again and synced.' + )} + + ) : null} + {detail.status === 'matchedByName' ? ( + + {t( + 'templates.provider.detail.matchedBody', + 'The id at the provider changed, for example after this database was moved to another environment. Magic Mail uses the template with the same name.' + )} + + ) : null} + + + + {t('templates.provider.detail.preview', 'Preview')} + + + {t( + 'templates.provider.detail.previewHint', + '{provider} fills the placeholders when it sends. Subject: {subject}', + { provider, subject: detail.subject || '-' } + )} + + {detail.previewHtml ? ( + + ) : ( + + {detail.previewTooLarge + ? t( + 'templates.provider.detail.previewTooLarge', + 'This template is too large to preview here. Open it at the provider.' + ) + : t( + 'templates.provider.detail.previewEmpty', + 'There is no active version to preview.' + )} + + )} + + + + + {t('templates.provider.detail.variables', 'Variables')} + + + {t( + 'templates.provider.detail.variablesHint', + 'Pass these in data when you send. Names stay the same as in Magic Mail templates; the test send uses the sample values name and email.' + )} + + {detail.variables.length === 0 ? ( + + {t('templates.provider.detail.noVariables', 'This template uses no variables.')} + + ) : ( + + {detail.variables.map((variable) => ( + + {variable.path} + {variable.scoped ? ( + + {t('templates.provider.variable.inList', 'In a list')} + + ) : variable.inSample ? ( + + {t('templates.provider.variable.inTest', 'In test send')} + + ) : ( + + {t('templates.provider.variable.notInTest', 'Empty in test send')} + + )} + + ))} + + )} + {notSentInTest.length > 0 ? ( + + {t( + 'templates.provider.detail.notInTestHint', + 'Variables marked "Empty in test send" render empty in the test email. Your code provides them.' + )} + + ) : null} + + + + + {t('templates.provider.detail.code', 'Send it from code')} + + {detail.usage} + + + + + + {canManage ? ( + + {t('templates.provider.fallback.label', 'Fallback template')} + changeFallback(String(value))} + > + + {t('templates.provider.fallback.none', 'Report an error (recommended)')} + + {(localTemplates ?? []).map((template) => ( + + {template.name} + + ))} + + + + ) : null} + + {canTestSend ? ( + + {t('templates.provider.testSend.recipient', 'Send test to')} + setRecipient(event.target.value)} + disabled={sending} + /> + + + + ) : null} + + ); + }; + + return ( + <> + !open && handleClose()}> + +
    + + + {detail?.name ?? t('templates.provider.detail.title', 'Provider template')} + + + + {renderBody()} + + + + {t('common.close', 'Close')} + + + {canManage && detail?.previewHtml ? ( + + {t('templates.provider.copy.button', 'Copy as Magic Mail template')} + + ) : null} + {canTestSend && detail ? ( + + ) : null} + + +
    +
    +
    + + setConfirmCopy(false)} + > + + {(detail?.copyWarnings ?? []).slice(0, 8).map((warning, index) => { + const info = conversionWarning(warning.code); + return ( +
  • + + {t('templates.provider.copy.warningLine', 'Line {line}: {message}', { + line: warning.line, + message: t(info.id, info.label), + })} + +
  • + ); + })} +
    +
    + + ); +}; + +export default ProviderTemplateDialog; diff --git a/admin/src/pages/EmailDesigner/providerTemplates/ProviderTemplatesSection.jsx b/admin/src/pages/EmailDesigner/providerTemplates/ProviderTemplatesSection.jsx new file mode 100644 index 0000000..c114db1 --- /dev/null +++ b/admin/src/pages/EmailDesigner/providerTemplates/ProviderTemplatesSection.jsx @@ -0,0 +1,260 @@ +import { + Button, + Flex, + IconButton, + Tbody, + Td, + Th, + Thead, + Tr, + Typography, + VisuallyHidden, +} from '@strapi/design-system'; +import { ArrowClockwise, Cloud, Eye } from '@strapi/icons'; +import { SectionHeading } from '../../../components/shared/Headings'; +import { + DataTable, + EmptyState, + LoadErrorState, + StatusBadge, + StyledTable, + keepNativeButtonKeys, +} from '../../../components/shared/table'; +import { useMagicMailIntl } from '../../../hooks/useMagicMailIntl'; +import { useFormatters } from '../../../hooks/useFormatters'; +import { SectionHeaderRow, TemplatesContainer } from '../templateListStyles'; +import { Notice } from './Notice'; +import { KeyText } from './providerTemplateStyles'; +import { providerName, statusInfo } from './providerTemplateUtils'; + +/** + * Account sync error codes from the server (services/provider-templates.js). + * @type {Record} + */ +const ACCOUNT_ERRORS = { + AUTH: { + id: 'templates.provider.accountError.auth', + label: 'The API key was rejected or may not read templates.', + }, + RATE_LIMITED: { + id: 'templates.provider.accountError.rateLimited', + label: 'The provider rate limit was reached. Try again in a minute.', + }, + CREDENTIALS: { + id: 'templates.provider.accountError.credentials', + label: 'The stored credentials can not be read. Enter the API key again.', + }, + NOT_FOUND: { + id: 'templates.provider.accountError.notFound', + label: 'The provider did not find this account or domain.', + }, + default: { + id: 'templates.provider.accountError.unavailable', + label: 'The provider could not be reached.', + }, +}; + +/** + * "Provider templates" section under the local templates. Rendered only when + * a SendGrid or Mailgun account exists (progressive disclosure); read-only: + * every row opens the preview dialog. + * + * @param {object} props + * @param {object|null} props.overview - GET /provider-templates data + * @param {boolean} props.loading + * @param {boolean} props.error - The overview could not be loaded + * @param {boolean} props.syncing + * @param {() => void} props.onSync + * @param {() => void} props.onRetry + * @param {(template: object) => void} props.onOpen + * @returns {import('react').ReactElement|null} + */ +export const ProviderTemplatesSection = ({ + overview, + loading, + error, + syncing, + onSync, + onRetry, + onOpen, +}) => { + const { t } = useMagicMailIntl(); + const { formatDateTime, formatRelative } = useFormatters(); + + if (loading && !overview) return null; + if (error && !overview) { + return ( + + {t('templates.provider.heading', 'Provider templates')} + + + + + ); + } + if (!overview?.enabled) return null; + + const templates = overview.templates ?? []; + const failedAccounts = (overview.accounts ?? []).filter((account) => account.error); + const lastSynced = overview.lastSyncedAt + ? t('templates.provider.lastSynced', 'Last synced {time}.', { + time: formatRelative(overview.lastSyncedAt), + }) + : t('templates.provider.neverSynced', 'Not synced yet.'); + const columns = { + name: t('templates.provider.table.name', 'Template'), + changed: t('templates.provider.table.changed', 'Changed at provider'), + accounts: t('templates.provider.table.accounts', 'Accounts'), + status: t('templates.provider.table.status', 'Status'), + actions: t('templates.table.actions', 'Actions'), + }; + + const syncButton = ( + + ); + + const renderBody = () => { + if (templates.length === 0) { + return ( + + ); + } + return ( + + + + {columns.name} + {columns.changed} + {columns.accounts} + {columns.status} + + {columns.actions} + + + + + {templates.map((template) => { + const status = statusInfo(template.status); + return ( + + + + + + {template.name} + + {providerName(template.provider)} + + {template.key} + + + + + {formatDateTime(template.updatedAtProvider)} + + + + + {template.accounts.map((account) => account.name).join(', ')} + + + + {t(status.id, status.label)} + + + + onOpen(template)} + > + + + + + ); + })} + + + ); + }; + + return ( + + + + {t('templates.provider.heading', 'Provider templates')} + + {t( + 'templates.provider.description', + 'Read-only templates from your SendGrid and Mailgun accounts.' + )}{' '} + {lastSynced} + + + {templates.length > 0 ? syncButton : null} + + + {failedAccounts.length > 0 ? ( + + {failedAccounts.map((account) => { + const info = ACCOUNT_ERRORS[account.error] ?? ACCOUNT_ERRORS.default; + return ( + + {t(info.id, info.label)}{' '} + {t( + 'templates.provider.accountError.keep', + 'Its templates keep their last synced state.' + )} + + ); + })} + + ) : null} + + + {renderBody()} + + + ); +}; + +export default ProviderTemplatesSection; diff --git a/admin/src/pages/EmailDesigner/providerTemplates/providerTemplateStyles.js b/admin/src/pages/EmailDesigner/providerTemplates/providerTemplateStyles.js new file mode 100644 index 0000000..0f42bb8 --- /dev/null +++ b/admin/src/pages/EmailDesigner/providerTemplates/providerTemplateStyles.js @@ -0,0 +1,78 @@ +/** + * Styles of the provider template dialogs. Theme tokens only (dark mode), + * DS spacing, no fixed widths so the dialogs shrink to 320px. + */ +import styled from 'styled-components'; +import { color, theme, LIGHT_FALLBACK_COLORS } from '../../../utils/theme'; + +/** + * Sandboxed email preview (no scripts, no same-origin access). The email is + * shown on the light DS canvas in both admin themes, like a mail client: + * provider templates rarely set a text colour, so a dark canvas would render + * black text on a dark background. + */ +export const PreviewFrame = styled.iframe` + display: block; + width: 100%; + height: 320px; + border: 1px solid ${color('neutral200')}; + border-radius: ${theme.borderRadius.md}; + background: ${LIGHT_FALLBACK_COLORS.neutral0}; + color-scheme: light; + + ${({ theme: dsTheme }) => dsTheme.breakpoints?.medium ?? '@media (min-width: 768px)'} { + height: 420px; + } +`; + +/** Detected variables as a wrapping list of name + badge pairs. */ +export const VariableList = styled.ul` + display: flex; + flex-wrap: wrap; + gap: ${({ theme: dsTheme }) => dsTheme.spaces[2]}; + margin: 0; + padding: 0; + list-style: none; +`; + +export const VariableItem = styled.li` + display: inline-flex; + align-items: center; + gap: ${({ theme: dsTheme }) => dsTheme.spaces[2]}; + max-width: 100%; + padding: ${({ theme: dsTheme }) => `${dsTheme.spaces[1]} ${dsTheme.spaces[2]}`}; + border: 1px solid ${color('neutral200')}; + border-radius: ${theme.borderRadius.sm}; + background: ${color('neutral100')}; + + code { + font-family: 'SF Mono', Monaco, 'Cascadia Code', monospace; + font-size: ${({ theme: dsTheme }) => dsTheme.fontSizes[1]}; + color: ${color('neutral800')}; + overflow-wrap: anywhere; + } +`; + +/** Read-only converted HTML for "Convert for provider". */ +export const ConvertedCode = styled.pre` + margin: 0; + max-height: 280px; + overflow: auto; + padding: ${({ theme: dsTheme }) => dsTheme.spaces[4]}; + border: 1px solid ${color('neutral200')}; + border-radius: ${theme.borderRadius.md}; + background: ${color('neutral100')}; + color: ${color('neutral800')}; + font-family: 'SF Mono', Monaco, 'Cascadia Code', monospace; + font-size: ${({ theme: dsTheme }) => dsTheme.fontSizes[1]}; + white-space: pre-wrap; + overflow-wrap: anywhere; +`; + +/** The template key under the name: small, secondary, copyable. */ +export const KeyText = styled.code` + font-family: 'SF Mono', Monaco, 'Cascadia Code', monospace; + font-size: ${({ theme: dsTheme }) => dsTheme.fontSizes[1]}; + color: ${color('neutral600')}; + overflow-wrap: anywhere; +`; diff --git a/admin/src/pages/EmailDesigner/providerTemplates/providerTemplateUtils.js b/admin/src/pages/EmailDesigner/providerTemplates/providerTemplateUtils.js new file mode 100644 index 0000000..35ff675 --- /dev/null +++ b/admin/src/pages/EmailDesigner/providerTemplates/providerTemplateUtils.js @@ -0,0 +1,147 @@ +/** + * Pure helpers for the provider template screens (status mapping, labels, + * variable checks). No React, so node --test can load them. + */ + +/** Display names of the template providers (brand names, not translated). */ +export const PROVIDER_NAMES = Object.freeze({ sendgrid: 'SendGrid', mailgun: 'Mailgun' }); + +/** + * One status mapping for every provider template screen: badge tone, label + * id and English default, and whether sending works. + * + * - ok: ready to send + * - matchedByName: ready; found by name after its id changed (other environment) + * - unpublished: the template has no active version at the provider + * - missing: the template was deleted at the provider (or not found on sync) + */ +export const PROVIDER_STATUS = Object.freeze({ + ok: { tone: 'success', id: 'templates.provider.status.ok', label: 'Ready', usable: true }, + matchedByName: { + tone: 'secondary', + id: 'templates.provider.status.matchedByName', + label: 'Matched by name', + usable: true, + }, + unpublished: { + tone: 'warning', + id: 'templates.provider.status.unpublished', + label: 'No active version', + usable: false, + }, + missing: { + tone: 'danger', + id: 'templates.provider.status.missing', + label: 'Deleted at provider', + usable: false, + }, +}); + +/** + * @param {string} status + * @returns {{tone: string, id: string, label: string, usable: boolean}} + */ +export const statusInfo = (status) => PROVIDER_STATUS[status] ?? PROVIDER_STATUS.missing; + +/** + * @param {string} provider + * @returns {string} Brand name, or the raw value for an unknown provider + */ +export const providerName = (provider) => PROVIDER_NAMES[provider] ?? String(provider ?? ''); + +/** + * Plain-language messages for the conversion warning codes reported by the + * server (utils/template-syntax.js). + */ +export const CONVERSION_WARNINGS = Object.freeze({ + SECTION_AMBIGUOUS: { + id: 'templates.provider.warning.sectionAmbiguous', + label: 'A Mustache section became an "if" block. Use "each" instead if the value is a list.', + }, + HELPER_UNSUPPORTED: { + id: 'templates.provider.warning.helperUnsupported', + label: 'A helper such as "equal" has no Mustache version. The tag was kept; edit it by hand.', + }, + ELSE_IF_UNSUPPORTED: { + id: 'templates.provider.warning.elseIfUnsupported', + label: '"else if" has no Mustache version. The block was kept; edit it by hand.', + }, + DATA_VARIABLE_UNSUPPORTED: { + id: 'templates.provider.warning.dataVariableUnsupported', + label: 'Loop variables such as @index or ../ have no Mustache version.', + }, + EACH_ELSE_UNSUPPORTED: { + id: 'templates.provider.warning.eachElseUnsupported', + label: '"else" inside a loop has no Mustache version. The block was kept.', + }, + UNBALANCED_BLOCK: { + id: 'templates.provider.warning.unbalanced', + label: 'A block is not closed correctly. It was copied unchanged.', + }, + UNBALANCED_SECTION: { + id: 'templates.provider.warning.unbalanced', + label: 'A block is not closed correctly. It was copied unchanged.', + }, + PARTIAL_UNSUPPORTED: { + id: 'templates.provider.warning.partialUnsupported', + label: 'Partials are not supported. The tag was kept.', + }, + DELIMITER_UNSUPPORTED: { + id: 'templates.provider.warning.delimiterUnsupported', + label: 'Changed delimiters are not supported. The rest was copied unchanged.', + }, + PATH_UNSUPPORTED: { + id: 'templates.provider.warning.pathUnsupported', + label: 'A variable name with special characters was kept unchanged.', + }, + UNSUPPORTED_TAG: { + id: 'templates.provider.warning.unsupportedTag', + label: 'A tag could not be converted and was kept unchanged.', + }, + TOO_LARGE: { + id: 'templates.provider.warning.tooLarge', + label: 'The template is too large to check completely.', + }, +}); + +/** + * @param {string} code + * @returns {{id: string, label: string}} + */ +export const conversionWarning = (code) => + CONVERSION_WARNINGS[code] ?? CONVERSION_WARNINGS.UNSUPPORTED_TAG; + +/** + * Variables a template expects that Magic Mail does not send for a core mail. + * Scoped variables (inside each/with) are relative and never reported. + * + * @param {Array<{path: string, root: string, scoped?: boolean}>} templateVariables + * @param {string[]} sentNames - Names Magic Mail sends (`USER.email`, `url`, ...) + * @returns {string[]} Missing paths, sorted + */ +export const missingCoreVariables = (templateVariables, sentNames) => { + const sent = new Set(sentNames || []); + const roots = new Set((sentNames || []).map((name) => name.split('.')[0])); + return (templateVariables || []) + .filter((variable) => !variable.scoped) + .filter((variable) => { + if (sent.has(variable.path)) return false; + // `USER` and `user` are objects: a known root with an unknown field is missing. + if (variable.path === variable.root) return !roots.has(variable.root); + return true; + }) + .map((variable) => variable.path) + .sort(); +}; + +/** + * True when the last sync is older than ten minutes (or never ran). + * + * @param {string|null|undefined} lastSyncedAt + * @param {number} [now] + * @returns {boolean} + */ +export const isSyncStale = (lastSyncedAt, now = Date.now()) => { + const time = lastSyncedAt ? Date.parse(lastSyncedAt) : NaN; + return !Number.isFinite(time) || now - time > 10 * 60 * 1000; +}; diff --git a/admin/src/pages/EmailDesigner/providerTemplates/useProviderTemplates.js b/admin/src/pages/EmailDesigner/providerTemplates/useProviderTemplates.js new file mode 100644 index 0000000..aea8ee8 --- /dev/null +++ b/admin/src/pages/EmailDesigner/providerTemplates/useProviderTemplates.js @@ -0,0 +1,113 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import { useFetchClient, useNotification } from '@strapi/strapi/admin'; +import { useMagicMailIntl } from '../../../hooks/useMagicMailIntl'; + +/** + * Loads the provider-template overview and keeps it fresh. + * + * - Loads once when `enabled` (read permission) is true. + * - When the server reports `stale` (no sync in the last ten minutes) and a + * SendGrid or Mailgun account exists, one background sync runs. + * - `sync()` re-reads all provider accounts (the "Sync" button). + * + * @param {{enabled: boolean}} options + * @returns {{overview: object|null, loading: boolean, error: boolean, syncing: boolean, sync: () => Promise, reload: () => void}} + * @sideeffect GET /magic-mail/provider-templates; POST /magic-mail/provider-templates/sync + */ +export const useProviderTemplates = ({ enabled }) => { + const { get, post } = useFetchClient(); + const { toggleNotification } = useNotification(); + const { t } = useMagicMailIntl(); + const [overview, setOverview] = useState(null); + const [loading, setLoading] = useState(Boolean(enabled)); + const [error, setError] = useState(false); + const [syncing, setSyncing] = useState(false); + const [reloadKey, setReloadKey] = useState(0); + const autoSynced = useRef(false); + const mounted = useRef(true); + + useEffect(() => { + mounted.current = true; + return () => { + mounted.current = false; + }; + }, []); + + const runSync = useCallback( + async ({ force, quiet }) => { + setSyncing(true); + try { + const response = await post('/magic-mail/provider-templates/sync', { force }); + if (!mounted.current) return; + const data = response?.data?.data ?? null; + setOverview(data); + setError(false); + if (!quiet) { + const failed = (data?.accounts ?? []).filter((account) => account.error).length; + toggleNotification({ + type: failed > 0 ? 'warning' : 'success', + message: + failed > 0 + ? t( + 'templates.provider.sync.partial', + 'Synced. {count, plural, one {# account} other {# accounts}} could not be read.', + { count: failed } + ) + : t('templates.provider.sync.success', 'Provider templates synced.'), + }); + } + } catch (syncError) { + if (!mounted.current) return; + const status = syncError?.response?.status; + toggleNotification({ + type: 'danger', + message: + status === 429 + ? t( + 'templates.provider.sync.rateLimited', + 'Too many syncs in a short time. Try again in a minute.' + ) + : t('templates.provider.sync.failure', 'Provider templates could not be synced.'), + }); + } finally { + if (mounted.current) setSyncing(false); + } + }, + [post, t, toggleNotification] + ); + + useEffect(() => { + if (!enabled) return undefined; + let ignore = false; + get('/magic-mail/provider-templates') + .then((response) => { + if (ignore) return; + const data = response?.data?.data ?? null; + setOverview(data); + setError(false); + setLoading(false); + if (data?.enabled && data?.stale && !autoSynced.current) { + autoSynced.current = true; + runSync({ force: false, quiet: true }); + } + }) + .catch(() => { + if (ignore) return; + setError(true); + setLoading(false); + }); + return () => { + ignore = true; + }; + }, [enabled, get, reloadKey, runSync]); + + const sync = useCallback(() => runSync({ force: true, quiet: false }), [runSync]); + const reload = useCallback(() => { + setLoading(true); + setReloadKey((key) => key + 1); + }, []); + + return { overview, loading: enabled && loading, error, syncing, sync, reload }; +}; + +export default useProviderTemplates; diff --git a/admin/src/pages/HomePage.jsx b/admin/src/pages/HomePage.jsx index a31829d..7e44ef7 100644 --- a/admin/src/pages/HomePage.jsx +++ b/admin/src/pages/HomePage.jsx @@ -48,6 +48,7 @@ import { import { GradientButton } from '../components/StyledButtons'; import { brand, theme } from '../utils/theme'; import { TestEmailModal } from './Accounts/TestEmailModal'; +import { CoreDesignAlert } from './EmailDesigner/providerTemplates/CoreDesignAlert'; import { AccountsContainer, Container, @@ -667,6 +668,12 @@ const HomePage = () => { ) : null} + account?.provider === 'sendgrid' || account?.provider === 'mailgun' + )} + /> + {!loadError && ( diff --git a/admin/src/translations/de.json b/admin/src/translations/de.json index 92e35fa..4b58c02 100644 --- a/admin/src/translations/de.json +++ b/admin/src/translations/de.json @@ -929,5 +929,123 @@ "accountModal.sendgrid.regionHint": "Wählen Sie EU nur für einen regionalen EU-Subuser. EU-Konten werden über api.eu.sendgrid.com aufgerufen, alle anderen über api.sendgrid.com.", "accountModal.sendgrid.region": "SendGrid-Region", "accountModal.sendgrid.regionGlobal": "Global (api.sendgrid.com)", - "accountModal.sendgrid.regionEu": "EU (api.eu.sendgrid.com)" + "accountModal.sendgrid.regionEu": "EU (api.eu.sendgrid.com)", + "templates.coreDesign.designerShort": "Magic-Mail-Designer", + "templates.coreDesign.providerShort": "{name} ({provider})", + "templates.coreDesign.staleTitle": "Eine Systemmail nutzt eine Provider-Vorlage, die nicht verfügbar ist", + "templates.coreDesign.staleBody": "{names}: Diese E-Mails schlagen fehl, bis die Vorlage wieder verfügbar und synchronisiert ist oder bis Sie zum Magic-Mail-Designer zurückwechseln.", + "templates.core.table.design": "Design", + "templates.coreDesign.choose": "Design von {name} wählen", + "templates.convert.title": "Für SendGrid oder Mailgun umwandeln", + "templates.provider.status.ok": "Bereit", + "templates.provider.status.matchedByName": "Über Namen zugeordnet", + "templates.provider.status.unpublished": "Keine aktive Version", + "templates.provider.status.missing": "Beim Provider gelöscht", + "templates.provider.warning.sectionAmbiguous": "Ein Mustache-Abschnitt wurde zu einem \"if\"-Block. Verwenden Sie stattdessen \"each\", wenn der Wert eine Liste ist.", + "templates.provider.warning.helperUnsupported": "Ein Helper wie \"equal\" hat keine Mustache-Entsprechung. Das Tag wurde beibehalten; bitte von Hand anpassen.", + "templates.provider.warning.elseIfUnsupported": "\"else if\" hat keine Mustache-Entsprechung. Der Block wurde beibehalten; bitte von Hand anpassen.", + "templates.provider.warning.dataVariableUnsupported": "Schleifenvariablen wie @index oder ../ haben keine Mustache-Entsprechung.", + "templates.provider.warning.eachElseUnsupported": "\"else\" in einer Schleife hat keine Mustache-Entsprechung. Der Block wurde beibehalten.", + "templates.provider.warning.unbalanced": "Ein Block ist nicht korrekt geschlossen. Er wurde unverändert übernommen.", + "templates.provider.warning.partialUnsupported": "Partials werden nicht unterstützt. Das Tag wurde beibehalten.", + "templates.provider.warning.delimiterUnsupported": "Geänderte Trennzeichen werden nicht unterstützt. Der Rest wurde unverändert übernommen.", + "templates.provider.warning.pathUnsupported": "Ein Variablenname mit Sonderzeichen wurde unverändert übernommen.", + "templates.provider.warning.unsupportedTag": "Ein Tag konnte nicht umgewandelt werden und wurde unverändert übernommen.", + "templates.provider.warning.tooLarge": "Die Vorlage ist zu groß, um sie vollständig zu prüfen.", + "templates.convert.failure": "Die Vorlage konnte nicht umgewandelt werden.", + "templates.convert.loading": "Wird umgewandelt...", + "templates.convert.description": "Fügen Sie dieses HTML in eine dynamische SendGrid-Vorlage oder eine Mailgun-Vorlage ein und synchronisieren Sie danach. Variablen behalten ihre Namen; nur Logikblöcke ändern sich.", + "templates.convert.warningsTitle": "Prüfen Sie diese Blöcke", + "templates.provider.copy.warningLine": "Zeile {line}: {message}", + "templates.convert.subject": "Betreff", + "templates.convert.html": "HTML", + "templates.convert.copied": "HTML kopiert.", + "templates.convert.copyHtml": "HTML kopieren", + "templates.convert.subjectCopied": "Betreff kopiert.", + "templates.convert.copySubject": "Betreff kopieren", + "templates.provider.sync.partial": "Synchronisiert. {count, plural, one {# Konto konnte} other {# Konten konnten}} nicht gelesen werden.", + "templates.provider.sync.success": "Provider-Vorlagen synchronisiert.", + "templates.provider.sync.rateLimited": "Zu viele Synchronisierungen in kurzer Zeit. Versuchen Sie es in einer Minute erneut.", + "templates.provider.sync.failure": "Die Provider-Vorlagen konnten nicht synchronisiert werden.", + "templates.coreDesign.openTemplates": "E-Mail-Vorlagen öffnen", + "templates.provider.testSend.success": "Test-E-Mail an {email} gesendet.", + "templates.provider.fallback.cleared": "Ersatz entfernt. Fehlgeschlagene Sendungen melden einen Fehler.", + "templates.provider.fallback.saved": "Ersatzvorlage gespeichert.", + "templates.provider.fallback.failure": "Der Ersatz konnte nicht gespeichert werden.", + "templates.provider.copy.successWithWarnings": "Kopie erstellt. Prüfen Sie die markierten Blöcke im Designer, bevor Sie sie verwenden.", + "templates.provider.copy.success": "Kopie als Magic-Mail-Vorlage erstellt.", + "templates.provider.copy.failure": "Die Vorlage konnte nicht kopiert werden.", + "templates.provider.detail.error": "Diese Vorlage konnte nicht geladen werden.", + "templates.provider.detail.errorHint": "Synchronisieren Sie die Provider-Vorlagen und öffnen Sie sie erneut.", + "templates.provider.detail.loading": "Vorlage wird geladen...", + "templates.provider.detail.changed": "Geändert bei {provider}: {date}", + "templates.provider.detail.missingTitle": "Bei {provider} gelöscht", + "templates.provider.detail.unpublishedTitle": "Keine aktive Version bei {provider}", + "templates.provider.detail.staleBody": "Sendungen mit dieser Vorlage schlagen mit einer klaren Fehlermeldung fehl, bis sie wieder verfügbar und synchronisiert ist.", + "templates.provider.detail.matchedTitle": "Über Namen zugeordnet", + "templates.provider.detail.matchedBody": "Die ID beim Provider hat sich geändert, zum Beispiel weil diese Datenbank in eine andere Umgebung übernommen wurde. Magic Mail verwendet die Vorlage mit demselben Namen.", + "templates.provider.detail.preview": "Vorschau", + "templates.provider.detail.previewHint": "{provider} füllt die Platzhalter beim Versand. Betreff: {subject}", + "templates.provider.detail.previewTitle": "Vorschau von {name}", + "templates.provider.detail.previewTooLarge": "Diese Vorlage ist zu groß für eine Vorschau. Öffnen Sie sie beim Provider.", + "templates.provider.detail.previewEmpty": "Es gibt keine aktive Version für eine Vorschau.", + "templates.provider.detail.variables": "Variablen", + "templates.provider.detail.variablesHint": "Übergeben Sie diese beim Senden in data. Die Namen sind dieselben wie in Magic-Mail-Vorlagen; der Testversand nutzt die Beispielwerte name und email.", + "templates.provider.detail.noVariables": "Diese Vorlage nutzt keine Variablen.", + "templates.provider.variable.inList": "In einer Liste", + "templates.provider.variable.inTest": "Im Testversand", + "templates.provider.variable.notInTest": "Im Testversand leer", + "templates.provider.detail.notInTestHint": "Variablen mit \"Im Testversand leer\" bleiben in der Test-E-Mail leer. Ihr Code liefert sie.", + "templates.provider.detail.code": "Aus Code senden", + "templates.provider.detail.copyCode": "Codebeispiel kopieren", + "templates.provider.fallback.hint": "Wird nur verwendet, wenn nichts gesendet wurde: Die Vorlage ist gelöscht oder unveröffentlicht, oder der Provider hat die E-Mail abgelehnt. Ohne Ersatz schlägt der Versand mit einem Fehler fehl.", + "templates.provider.fallback.label": "Ersatzvorlage", + "templates.provider.fallback.none": "Fehler melden (empfohlen)", + "templates.provider.testSend.hint": "Leer lassen, um den Test an Ihre eigene Admin-E-Mail-Adresse zu senden.", + "templates.provider.testSend.recipient": "Test senden an", + "templates.provider.testSend.placeholder": "Ihre Admin-E-Mail-Adresse", + "templates.provider.detail.title": "Provider-Vorlage", + "templates.provider.copy.button": "Als Magic-Mail-Vorlage kopieren", + "templates.provider.testSend.submit": "Test senden", + "templates.provider.copy.confirmTitle": "Mit Änderungen kopieren?", + "templates.provider.copy.confirmBody": "Einige Handlebars-Logik lässt sich nicht exakt in Magic-Mail-Vorlagen übernehmen:", + "templates.provider.copy.confirm": "Trotzdem kopieren", + "templates.provider.heading": "Provider-Vorlagen", + "templates.provider.error.title": "Provider-Vorlagen konnten nicht geladen werden", + "templates.provider.error.description": "Prüfen Sie Ihre Verbindung und Berechtigungen und versuchen Sie es erneut.", + "templates.provider.lastSynced": "Zuletzt synchronisiert {time}.", + "templates.provider.neverSynced": "Noch nicht synchronisiert.", + "templates.provider.table.name": "Vorlage", + "templates.provider.table.changed": "Beim Provider geändert", + "templates.provider.table.accounts": "Konten", + "templates.provider.table.status": "Status", + "templates.provider.syncing": "Wird synchronisiert...", + "templates.provider.sync": "Synchronisieren", + "templates.provider.empty.syncingTitle": "Ihre Provider-Vorlagen werden gelesen...", + "templates.provider.empty.title": "Keine Provider-Vorlagen gefunden", + "templates.provider.empty.description": "Erstellen Sie eine dynamische Vorlage bei SendGrid oder eine Vorlage bei Mailgun und wählen Sie dann Synchronisieren. Magic Mail listet sie hier auf und kann sie mit Ihrem Routing, Failover und Protokoll senden.", + "templates.provider.open": "{name} öffnen", + "templates.provider.description": "Schreibgeschützte Vorlagen aus Ihren SendGrid- und Mailgun-Konten.", + "templates.provider.accountError.title": "{account} ({provider}) konnte nicht gelesen werden", + "templates.provider.accountError.keep": "Seine Vorlagen behalten den zuletzt synchronisierten Stand.", + "templates.provider.accountError.auth": "Der API-Schlüssel wurde abgelehnt oder darf keine Vorlagen lesen.", + "templates.provider.accountError.rateLimited": "Das Ratenlimit des Providers wurde erreicht. Versuchen Sie es in einer Minute erneut.", + "templates.provider.accountError.credentials": "Die gespeicherten Zugangsdaten können nicht gelesen werden. Geben Sie den API-Schlüssel erneut ein.", + "templates.provider.accountError.notFound": "Der Provider hat dieses Konto oder diese Domain nicht gefunden.", + "templates.provider.accountError.unavailable": "Der Provider war nicht erreichbar.", + "templates.coreDesign.savedDesigner": "{name} nutzt jetzt den Magic-Mail-Designer.", + "templates.coreDesign.savedProvider": "{name} nutzt jetzt \"{template}\".", + "templates.coreDesign.failure": "Das Design konnte nicht gespeichert werden.", + "templates.coreDesign.title": "Design von {name}", + "templates.coreDesign.hint": "Mit einer Provider-Vorlage erstellt SendGrid oder Mailgun diese E-Mail. Routing, Failover und Protokoll bleiben in Magic Mail.", + "templates.coreDesign.label": "Design", + "templates.coreDesign.designer": "Magic-Mail-Designer (Standard)", + "templates.coreDesign.option": "{name} ({provider})", + "templates.coreDesign.staleSelected": "Diese Vorlage hat den Status \"{status}\". Sendungen schlagen fehl, bis sie wieder verfügbar ist.", + "templates.coreDesign.sentHeading": "Variablen, die Magic Mail sendet", + "templates.coreDesign.sentHint": "Verwenden Sie diese Namen in der Provider-Vorlage. \"url\" ist der fertige Link mit dem Code.", + "templates.coreDesign.missingTitle": "Die Vorlage nutzt Variablen, die Magic Mail nicht sendet", + "templates.coreDesign.missingBody": "Diese bleiben leer: {names}", + "templates.coreDesign.fallback": "Wenn die Provider-Vorlage fehlschlägt, stattdessen die Version aus dem Magic-Mail-Designer senden", + "templates.coreDesign.fallbackHint": "Aus: Die E-Mail schlägt mit einer klaren Fehlermeldung fehl und es wird nichts anderes gesendet." } diff --git a/admin/src/translations/en.json b/admin/src/translations/en.json index 740957c..1ca4bca 100644 --- a/admin/src/translations/en.json +++ b/admin/src/translations/en.json @@ -929,5 +929,123 @@ "accountModal.sendgrid.regionHint": "Use EU only for an EU regional subuser. EU accounts are called through api.eu.sendgrid.com, all others through api.sendgrid.com.", "accountModal.sendgrid.region": "SendGrid region", "accountModal.sendgrid.regionGlobal": "Global (api.sendgrid.com)", - "accountModal.sendgrid.regionEu": "EU (api.eu.sendgrid.com)" + "accountModal.sendgrid.regionEu": "EU (api.eu.sendgrid.com)", + "templates.coreDesign.designerShort": "Magic Mail designer", + "templates.coreDesign.providerShort": "{name} ({provider})", + "templates.coreDesign.staleTitle": "A core email uses a provider template that is not available", + "templates.coreDesign.staleBody": "{names}: these emails fail until the template is available again and synced, or until you switch back to the Magic Mail designer.", + "templates.core.table.design": "Design", + "templates.coreDesign.choose": "Choose design of {name}", + "templates.convert.title": "Convert for SendGrid or Mailgun", + "templates.provider.status.ok": "Ready", + "templates.provider.status.matchedByName": "Matched by name", + "templates.provider.status.unpublished": "No active version", + "templates.provider.status.missing": "Deleted at provider", + "templates.provider.warning.sectionAmbiguous": "A Mustache section became an \"if\" block. Use \"each\" instead if the value is a list.", + "templates.provider.warning.helperUnsupported": "A helper such as \"equal\" has no Mustache version. The tag was kept; edit it by hand.", + "templates.provider.warning.elseIfUnsupported": "\"else if\" has no Mustache version. The block was kept; edit it by hand.", + "templates.provider.warning.dataVariableUnsupported": "Loop variables such as @index or ../ have no Mustache version.", + "templates.provider.warning.eachElseUnsupported": "\"else\" inside a loop has no Mustache version. The block was kept.", + "templates.provider.warning.unbalanced": "A block is not closed correctly. It was copied unchanged.", + "templates.provider.warning.partialUnsupported": "Partials are not supported. The tag was kept.", + "templates.provider.warning.delimiterUnsupported": "Changed delimiters are not supported. The rest was copied unchanged.", + "templates.provider.warning.pathUnsupported": "A variable name with special characters was kept unchanged.", + "templates.provider.warning.unsupportedTag": "A tag could not be converted and was kept unchanged.", + "templates.provider.warning.tooLarge": "The template is too large to check completely.", + "templates.convert.failure": "The template could not be converted.", + "templates.convert.loading": "Converting...", + "templates.convert.description": "Paste this HTML into a SendGrid dynamic template or a Mailgun template, then sync. Variables keep their names; only logic blocks change.", + "templates.convert.warningsTitle": "Check these blocks", + "templates.provider.copy.warningLine": "Line {line}: {message}", + "templates.convert.subject": "Subject", + "templates.convert.html": "HTML", + "templates.convert.copied": "HTML copied.", + "templates.convert.copyHtml": "Copy HTML", + "templates.convert.subjectCopied": "Subject copied.", + "templates.convert.copySubject": "Copy subject", + "templates.provider.sync.partial": "Synced. {count, plural, one {# account} other {# accounts}} could not be read.", + "templates.provider.sync.success": "Provider templates synced.", + "templates.provider.sync.rateLimited": "Too many syncs in a short time. Try again in a minute.", + "templates.provider.sync.failure": "Provider templates could not be synced.", + "templates.coreDesign.openTemplates": "Open email templates", + "templates.provider.testSend.success": "Test email sent to {email}.", + "templates.provider.fallback.cleared": "Fallback removed. Failed sends report an error.", + "templates.provider.fallback.saved": "Fallback template saved.", + "templates.provider.fallback.failure": "The fallback could not be saved.", + "templates.provider.copy.successWithWarnings": "Copy created. Check the marked blocks in the designer before you use it.", + "templates.provider.copy.success": "Copy created as a Magic Mail template.", + "templates.provider.copy.failure": "The template could not be copied.", + "templates.provider.detail.error": "This template could not be loaded.", + "templates.provider.detail.errorHint": "Sync the provider templates and open it again.", + "templates.provider.detail.loading": "Loading template...", + "templates.provider.detail.changed": "Changed at {provider}: {date}", + "templates.provider.detail.missingTitle": "Deleted at {provider}", + "templates.provider.detail.unpublishedTitle": "No active version at {provider}", + "templates.provider.detail.staleBody": "Sends with this template fail with a clear error until it is available again and synced.", + "templates.provider.detail.matchedTitle": "Matched by name", + "templates.provider.detail.matchedBody": "The id at the provider changed, for example after this database was moved to another environment. Magic Mail uses the template with the same name.", + "templates.provider.detail.preview": "Preview", + "templates.provider.detail.previewHint": "{provider} fills the placeholders when it sends. Subject: {subject}", + "templates.provider.detail.previewTitle": "Preview of {name}", + "templates.provider.detail.previewTooLarge": "This template is too large to preview here. Open it at the provider.", + "templates.provider.detail.previewEmpty": "There is no active version to preview.", + "templates.provider.detail.variables": "Variables", + "templates.provider.detail.variablesHint": "Pass these in data when you send. Names stay the same as in Magic Mail templates; the test send uses the sample values name and email.", + "templates.provider.detail.noVariables": "This template uses no variables.", + "templates.provider.variable.inList": "In a list", + "templates.provider.variable.inTest": "In test send", + "templates.provider.variable.notInTest": "Empty in test send", + "templates.provider.detail.notInTestHint": "Variables marked \"Empty in test send\" render empty in the test email. Your code provides them.", + "templates.provider.detail.code": "Send it from code", + "templates.provider.detail.copyCode": "Copy the code example", + "templates.provider.fallback.hint": "Used only when nothing was sent: the template is deleted or unpublished, or the provider refused the email. Without a fallback, the send fails with an error.", + "templates.provider.fallback.label": "Fallback template", + "templates.provider.fallback.none": "Report an error (recommended)", + "templates.provider.testSend.hint": "Leave empty to send the test to your own admin email address.", + "templates.provider.testSend.recipient": "Send test to", + "templates.provider.testSend.placeholder": "Your admin email address", + "templates.provider.detail.title": "Provider template", + "templates.provider.copy.button": "Copy as Magic Mail template", + "templates.provider.testSend.submit": "Send test", + "templates.provider.copy.confirmTitle": "Copy with changes?", + "templates.provider.copy.confirmBody": "Some Handlebars logic can not be carried over to Magic Mail templates exactly:", + "templates.provider.copy.confirm": "Copy anyway", + "templates.provider.heading": "Provider templates", + "templates.provider.error.title": "Provider templates could not be loaded", + "templates.provider.error.description": "Check your connection and permissions, then try again.", + "templates.provider.lastSynced": "Last synced {time}.", + "templates.provider.neverSynced": "Not synced yet.", + "templates.provider.table.name": "Template", + "templates.provider.table.changed": "Changed at provider", + "templates.provider.table.accounts": "Accounts", + "templates.provider.table.status": "Status", + "templates.provider.syncing": "Syncing...", + "templates.provider.sync": "Sync", + "templates.provider.empty.syncingTitle": "Reading your provider templates...", + "templates.provider.empty.title": "No provider templates found", + "templates.provider.empty.description": "Create a dynamic template at SendGrid or a template at Mailgun, then select Sync. Magic Mail lists it here and can send it with your routing, failover and logs.", + "templates.provider.open": "Open {name}", + "templates.provider.description": "Read-only templates from your SendGrid and Mailgun accounts.", + "templates.provider.accountError.title": "{account} ({provider}) could not be read", + "templates.provider.accountError.keep": "Its templates keep their last synced state.", + "templates.provider.accountError.auth": "The API key was rejected or may not read templates.", + "templates.provider.accountError.rateLimited": "The provider rate limit was reached. Try again in a minute.", + "templates.provider.accountError.credentials": "The stored credentials can not be read. Enter the API key again.", + "templates.provider.accountError.notFound": "The provider did not find this account or domain.", + "templates.provider.accountError.unavailable": "The provider could not be reached.", + "templates.coreDesign.savedDesigner": "{name} now uses the Magic Mail designer.", + "templates.coreDesign.savedProvider": "{name} now uses \"{template}\".", + "templates.coreDesign.failure": "The design could not be saved.", + "templates.coreDesign.title": "Design of {name}", + "templates.coreDesign.hint": "With a provider template, SendGrid or Mailgun renders this email. Routing, failover and logs stay in Magic Mail.", + "templates.coreDesign.label": "Design", + "templates.coreDesign.designer": "Magic Mail designer (default)", + "templates.coreDesign.option": "{name} ({provider})", + "templates.coreDesign.staleSelected": "This template is \"{status}\". Sends fail until it is available again.", + "templates.coreDesign.sentHeading": "Variables Magic Mail sends", + "templates.coreDesign.sentHint": "Use these names in the provider template. \"url\" is the finished link with the code.", + "templates.coreDesign.missingTitle": "The template uses variables Magic Mail does not send", + "templates.coreDesign.missingBody": "These render empty: {names}", + "templates.coreDesign.fallback": "If the provider template fails, send the Magic Mail designer version instead", + "templates.coreDesign.fallbackHint": "Off: the email fails with a clear error and nothing else is sent." } diff --git a/admin/src/translations/es.json b/admin/src/translations/es.json index 85ddea6..c4a4f3b 100644 --- a/admin/src/translations/es.json +++ b/admin/src/translations/es.json @@ -929,5 +929,123 @@ "accountModal.sendgrid.regionHint": "Elija EU solo para un subusuario regional de la EU. Las cuentas de la EU se llaman a través de api.eu.sendgrid.com; todas las demás, a través de api.sendgrid.com.", "accountModal.sendgrid.region": "Región de SendGrid", "accountModal.sendgrid.regionGlobal": "Global (api.sendgrid.com)", - "accountModal.sendgrid.regionEu": "EU (api.eu.sendgrid.com)" + "accountModal.sendgrid.regionEu": "EU (api.eu.sendgrid.com)", + "templates.coreDesign.designerShort": "Diseñador de Magic Mail", + "templates.coreDesign.providerShort": "{name} ({provider})", + "templates.coreDesign.staleTitle": "Un correo del sistema usa una plantilla del proveedor que no está disponible", + "templates.coreDesign.staleBody": "{names}: estos correos fallan hasta que la plantilla vuelva a estar disponible y sincronizada, o hasta que vuelva al diseñador de Magic Mail.", + "templates.core.table.design": "Diseño", + "templates.coreDesign.choose": "Elegir el diseño de {name}", + "templates.convert.title": "Convertir para SendGrid o Mailgun", + "templates.provider.status.ok": "Lista", + "templates.provider.status.matchedByName": "Asociada por nombre", + "templates.provider.status.unpublished": "Sin versión activa", + "templates.provider.status.missing": "Eliminada en el proveedor", + "templates.provider.warning.sectionAmbiguous": "Una sección de Mustache se convirtió en un bloque \"if\". Use \"each\" en su lugar si el valor es una lista.", + "templates.provider.warning.helperUnsupported": "Un helper como \"equal\" no tiene equivalente en Mustache. La etiqueta se ha conservado; edítela manualmente.", + "templates.provider.warning.elseIfUnsupported": "\"else if\" no tiene equivalente en Mustache. El bloque se ha conservado; edítelo manualmente.", + "templates.provider.warning.dataVariableUnsupported": "Las variables de bucle como @index o ../ no tienen equivalente en Mustache.", + "templates.provider.warning.eachElseUnsupported": "\"else\" dentro de un bucle no tiene equivalente en Mustache. El bloque se ha conservado.", + "templates.provider.warning.unbalanced": "Un bloque no está cerrado correctamente. Se ha copiado sin cambios.", + "templates.provider.warning.partialUnsupported": "Los partials no son compatibles. La etiqueta se ha conservado.", + "templates.provider.warning.delimiterUnsupported": "Los delimitadores modificados no son compatibles. El resto se ha copiado sin cambios.", + "templates.provider.warning.pathUnsupported": "Un nombre de variable con caracteres especiales se ha conservado sin cambios.", + "templates.provider.warning.unsupportedTag": "Una etiqueta no se pudo convertir y se ha conservado sin cambios.", + "templates.provider.warning.tooLarge": "La plantilla es demasiado grande para comprobarla por completo.", + "templates.convert.failure": "No se pudo convertir la plantilla.", + "templates.convert.loading": "Convirtiendo...", + "templates.convert.description": "Pegue este HTML en una plantilla dinámica de SendGrid o en una plantilla de Mailgun y, a continuación, sincronice. Las variables conservan sus nombres; solo cambian los bloques lógicos.", + "templates.convert.warningsTitle": "Revise estos bloques", + "templates.provider.copy.warningLine": "Línea {line}: {message}", + "templates.convert.subject": "Asunto", + "templates.convert.html": "HTML", + "templates.convert.copied": "HTML copiado.", + "templates.convert.copyHtml": "Copiar HTML", + "templates.convert.subjectCopied": "Asunto copiado.", + "templates.convert.copySubject": "Copiar asunto", + "templates.provider.sync.partial": "Sincronizado. {count, plural, one {# cuenta no se pudo leer} other {# cuentas no se pudieron leer}}.", + "templates.provider.sync.success": "Plantillas del proveedor sincronizadas.", + "templates.provider.sync.rateLimited": "Demasiadas sincronizaciones en poco tiempo. Vuelva a intentarlo en un minuto.", + "templates.provider.sync.failure": "No se pudieron sincronizar las plantillas del proveedor.", + "templates.coreDesign.openTemplates": "Abrir plantillas de correo", + "templates.provider.testSend.success": "Correo de prueba enviado a {email}.", + "templates.provider.fallback.cleared": "Plantilla de respaldo eliminada. Los envíos fallidos informan de un error.", + "templates.provider.fallback.saved": "Plantilla de respaldo guardada.", + "templates.provider.fallback.failure": "No se pudo guardar la plantilla de respaldo.", + "templates.provider.copy.successWithWarnings": "Copia creada. Revise los bloques marcados en el diseñador antes de usarla.", + "templates.provider.copy.success": "Copia creada como plantilla de Magic Mail.", + "templates.provider.copy.failure": "No se pudo copiar la plantilla.", + "templates.provider.detail.error": "No se pudo cargar esta plantilla.", + "templates.provider.detail.errorHint": "Sincronice las plantillas del proveedor y vuelva a abrirla.", + "templates.provider.detail.loading": "Cargando plantilla...", + "templates.provider.detail.changed": "Modificada en {provider}: {date}", + "templates.provider.detail.missingTitle": "Eliminada en {provider}", + "templates.provider.detail.unpublishedTitle": "Sin versión activa en {provider}", + "templates.provider.detail.staleBody": "Los envíos con esta plantilla fallan con un error claro hasta que vuelva a estar disponible y sincronizada.", + "templates.provider.detail.matchedTitle": "Asociada por nombre", + "templates.provider.detail.matchedBody": "El ID en el proveedor cambió, por ejemplo, después de mover esta base de datos a otro entorno. Magic Mail usa la plantilla con el mismo nombre.", + "templates.provider.detail.preview": "Vista previa", + "templates.provider.detail.previewHint": "{provider} rellena los marcadores de posición al enviar. Asunto: {subject}", + "templates.provider.detail.previewTitle": "Vista previa de {name}", + "templates.provider.detail.previewTooLarge": "Esta plantilla es demasiado grande para mostrar una vista previa aquí. Ábrala en el proveedor.", + "templates.provider.detail.previewEmpty": "No hay ninguna versión activa para mostrar una vista previa.", + "templates.provider.detail.variables": "Variables", + "templates.provider.detail.variablesHint": "Páselas en data al enviar. Los nombres son los mismos que en las plantillas de Magic Mail; el envío de prueba usa los valores de ejemplo name y email.", + "templates.provider.detail.noVariables": "Esta plantilla no usa variables.", + "templates.provider.variable.inList": "En una lista", + "templates.provider.variable.inTest": "En el envío de prueba", + "templates.provider.variable.notInTest": "Vacía en el envío de prueba", + "templates.provider.detail.notInTestHint": "Las variables marcadas como \"Vacía en el envío de prueba\" quedan vacías en el correo de prueba. Su código las proporciona.", + "templates.provider.detail.code": "Enviar desde el código", + "templates.provider.detail.copyCode": "Copiar el ejemplo de código", + "templates.provider.fallback.hint": "Solo se usa cuando no se envió nada: la plantilla se eliminó o no está publicada, o el proveedor rechazó el correo. Sin una plantilla de respaldo, el envío falla con un error.", + "templates.provider.fallback.label": "Plantilla de respaldo", + "templates.provider.fallback.none": "Informar de un error (recomendado)", + "templates.provider.testSend.hint": "Déjelo vacío para enviar la prueba a su propia dirección de correo de administrador.", + "templates.provider.testSend.recipient": "Enviar prueba a", + "templates.provider.testSend.placeholder": "Su dirección de correo de administrador", + "templates.provider.detail.title": "Plantilla del proveedor", + "templates.provider.copy.button": "Copiar como plantilla de Magic Mail", + "templates.provider.testSend.submit": "Enviar prueba", + "templates.provider.copy.confirmTitle": "¿Copiar con cambios?", + "templates.provider.copy.confirmBody": "Parte de la lógica de Handlebars no se puede trasladar con exactitud a las plantillas de Magic Mail:", + "templates.provider.copy.confirm": "Copiar de todos modos", + "templates.provider.heading": "Plantillas del proveedor", + "templates.provider.error.title": "No se pudieron cargar las plantillas del proveedor", + "templates.provider.error.description": "Compruebe su conexión y sus permisos y vuelva a intentarlo.", + "templates.provider.lastSynced": "Última sincronización: {time}.", + "templates.provider.neverSynced": "Aún no se ha sincronizado.", + "templates.provider.table.name": "Plantilla", + "templates.provider.table.changed": "Modificada en el proveedor", + "templates.provider.table.accounts": "Cuentas", + "templates.provider.table.status": "Estado", + "templates.provider.syncing": "Sincronizando...", + "templates.provider.sync": "Sincronizar", + "templates.provider.empty.syncingTitle": "Leyendo sus plantillas del proveedor...", + "templates.provider.empty.title": "No se encontraron plantillas del proveedor", + "templates.provider.empty.description": "Cree una plantilla dinámica en SendGrid o una plantilla en Mailgun y, a continuación, seleccione Sincronizar. Magic Mail la muestra aquí y puede enviarla con su enrutamiento, conmutación por error y registros.", + "templates.provider.open": "Abrir {name}", + "templates.provider.description": "Plantillas de solo lectura de sus cuentas de SendGrid y Mailgun.", + "templates.provider.accountError.title": "No se pudo leer {account} ({provider})", + "templates.provider.accountError.keep": "Sus plantillas conservan el último estado sincronizado.", + "templates.provider.accountError.auth": "La clave de API se rechazó o no tiene permiso para leer plantillas.", + "templates.provider.accountError.rateLimited": "Se alcanzó el límite de solicitudes del proveedor. Vuelva a intentarlo en un minuto.", + "templates.provider.accountError.credentials": "No se pueden leer las credenciales guardadas. Vuelva a introducir la clave de API.", + "templates.provider.accountError.notFound": "El proveedor no encontró esta cuenta o este dominio.", + "templates.provider.accountError.unavailable": "No se pudo contactar con el proveedor.", + "templates.coreDesign.savedDesigner": "{name} ahora usa el diseñador de Magic Mail.", + "templates.coreDesign.savedProvider": "{name} ahora usa \"{template}\".", + "templates.coreDesign.failure": "No se pudo guardar el diseño.", + "templates.coreDesign.title": "Diseño de {name}", + "templates.coreDesign.hint": "Con una plantilla del proveedor, SendGrid o Mailgun genera este correo. El enrutamiento, la conmutación por error y los registros permanecen en Magic Mail.", + "templates.coreDesign.label": "Diseño", + "templates.coreDesign.designer": "Diseñador de Magic Mail (predeterminado)", + "templates.coreDesign.option": "{name} ({provider})", + "templates.coreDesign.staleSelected": "Esta plantilla tiene el estado \"{status}\". Los envíos fallan hasta que vuelva a estar disponible.", + "templates.coreDesign.sentHeading": "Variables que envía Magic Mail", + "templates.coreDesign.sentHint": "Use estos nombres en la plantilla del proveedor. \"url\" es el enlace final con el código.", + "templates.coreDesign.missingTitle": "La plantilla usa variables que Magic Mail no envía", + "templates.coreDesign.missingBody": "Estas quedan vacías: {names}", + "templates.coreDesign.fallback": "Si la plantilla del proveedor falla, enviar en su lugar la versión del diseñador de Magic Mail", + "templates.coreDesign.fallbackHint": "Desactivado: el correo falla con un error claro y no se envía nada más." } diff --git a/admin/src/translations/fr.json b/admin/src/translations/fr.json index ba93299..f24fad5 100644 --- a/admin/src/translations/fr.json +++ b/admin/src/translations/fr.json @@ -929,5 +929,123 @@ "accountModal.sendgrid.regionHint": "Choisissez EU uniquement pour un sous-utilisateur régional EU. Les comptes EU sont appelés via api.eu.sendgrid.com, tous les autres via api.sendgrid.com.", "accountModal.sendgrid.region": "Région SendGrid", "accountModal.sendgrid.regionGlobal": "Mondiale (api.sendgrid.com)", - "accountModal.sendgrid.regionEu": "EU (api.eu.sendgrid.com)" + "accountModal.sendgrid.regionEu": "EU (api.eu.sendgrid.com)", + "templates.coreDesign.designerShort": "Éditeur Magic Mail", + "templates.coreDesign.providerShort": "{name} ({provider})", + "templates.coreDesign.staleTitle": "Un e-mail système utilise un modèle de fournisseur qui n'est pas disponible", + "templates.coreDesign.staleBody": "{names} : ces e-mails échouent jusqu'à ce que le modèle soit de nouveau disponible et synchronisé, ou jusqu'à ce que vous reveniez à l'éditeur Magic Mail.", + "templates.core.table.design": "Design", + "templates.coreDesign.choose": "Choisir le design de {name}", + "templates.convert.title": "Convertir pour SendGrid ou Mailgun", + "templates.provider.status.ok": "Prêt", + "templates.provider.status.matchedByName": "Associé par nom", + "templates.provider.status.unpublished": "Aucune version active", + "templates.provider.status.missing": "Supprimé chez le fournisseur", + "templates.provider.warning.sectionAmbiguous": "Une section Mustache est devenue un bloc \"if\". Utilisez plutôt \"each\" si la valeur est une liste.", + "templates.provider.warning.helperUnsupported": "Un helper tel que \"equal\" n'a pas d'équivalent Mustache. La balise a été conservée ; modifiez-la manuellement.", + "templates.provider.warning.elseIfUnsupported": "\"else if\" n'a pas d'équivalent Mustache. Le bloc a été conservé ; modifiez-le manuellement.", + "templates.provider.warning.dataVariableUnsupported": "Les variables de boucle telles que @index ou ../ n'ont pas d'équivalent Mustache.", + "templates.provider.warning.eachElseUnsupported": "\"else\" dans une boucle n'a pas d'équivalent Mustache. Le bloc a été conservé.", + "templates.provider.warning.unbalanced": "Un bloc n'est pas fermé correctement. Il a été copié sans modification.", + "templates.provider.warning.partialUnsupported": "Les partials ne sont pas pris en charge. La balise a été conservée.", + "templates.provider.warning.delimiterUnsupported": "Les délimiteurs modifiés ne sont pas pris en charge. Le reste a été copié sans modification.", + "templates.provider.warning.pathUnsupported": "Un nom de variable contenant des caractères spéciaux a été conservé sans modification.", + "templates.provider.warning.unsupportedTag": "Une balise n'a pas pu être convertie et a été conservée sans modification.", + "templates.provider.warning.tooLarge": "Le modèle est trop volumineux pour être vérifié entièrement.", + "templates.convert.failure": "Le modèle n'a pas pu être converti.", + "templates.convert.loading": "Conversion...", + "templates.convert.description": "Collez ce HTML dans un modèle dynamique SendGrid ou un modèle Mailgun, puis synchronisez. Les variables conservent leur nom ; seuls les blocs logiques changent.", + "templates.convert.warningsTitle": "Vérifiez ces blocs", + "templates.provider.copy.warningLine": "Ligne {line} : {message}", + "templates.convert.subject": "Objet", + "templates.convert.html": "HTML", + "templates.convert.copied": "HTML copié.", + "templates.convert.copyHtml": "Copier le HTML", + "templates.convert.subjectCopied": "Objet copié.", + "templates.convert.copySubject": "Copier l'objet", + "templates.provider.sync.partial": "Synchronisé. {count, plural, one {# compte n'a pas pu être lu} other {# comptes n'ont pas pu être lus}}.", + "templates.provider.sync.success": "Modèles du fournisseur synchronisés.", + "templates.provider.sync.rateLimited": "Trop de synchronisations en peu de temps. Réessayez dans une minute.", + "templates.provider.sync.failure": "Les modèles du fournisseur n'ont pas pu être synchronisés.", + "templates.coreDesign.openTemplates": "Ouvrir les modèles d'e-mail", + "templates.provider.testSend.success": "E-mail de test envoyé à {email}.", + "templates.provider.fallback.cleared": "Modèle de secours supprimé. Les envois échoués signalent une erreur.", + "templates.provider.fallback.saved": "Modèle de secours enregistré.", + "templates.provider.fallback.failure": "Le modèle de secours n'a pas pu être enregistré.", + "templates.provider.copy.successWithWarnings": "Copie créée. Vérifiez les blocs signalés dans l'éditeur avant de l'utiliser.", + "templates.provider.copy.success": "Copie créée comme modèle Magic Mail.", + "templates.provider.copy.failure": "Le modèle n'a pas pu être copié.", + "templates.provider.detail.error": "Ce modèle n'a pas pu être chargé.", + "templates.provider.detail.errorHint": "Synchronisez les modèles du fournisseur, puis ouvrez-le de nouveau.", + "templates.provider.detail.loading": "Chargement du modèle...", + "templates.provider.detail.changed": "Modifié chez {provider} : {date}", + "templates.provider.detail.missingTitle": "Supprimé chez {provider}", + "templates.provider.detail.unpublishedTitle": "Aucune version active chez {provider}", + "templates.provider.detail.staleBody": "Les envois avec ce modèle échouent avec une erreur explicite jusqu'à ce qu'il soit de nouveau disponible et synchronisé.", + "templates.provider.detail.matchedTitle": "Associé par nom", + "templates.provider.detail.matchedBody": "L'ID chez le fournisseur a changé, par exemple après le transfert de cette base de données vers un autre environnement. Magic Mail utilise le modèle portant le même nom.", + "templates.provider.detail.preview": "Aperçu", + "templates.provider.detail.previewHint": "{provider} remplit les espaces réservés lors de l'envoi. Objet : {subject}", + "templates.provider.detail.previewTitle": "Aperçu de {name}", + "templates.provider.detail.previewTooLarge": "Ce modèle est trop volumineux pour être prévisualisé ici. Ouvrez-le chez le fournisseur.", + "templates.provider.detail.previewEmpty": "Il n'existe aucune version active à prévisualiser.", + "templates.provider.detail.variables": "Variables", + "templates.provider.detail.variablesHint": "Transmettez-les dans data lors de l'envoi. Les noms sont les mêmes que dans les modèles Magic Mail ; l'envoi de test utilise les valeurs d'exemple name et email.", + "templates.provider.detail.noVariables": "Ce modèle n'utilise aucune variable.", + "templates.provider.variable.inList": "Dans une liste", + "templates.provider.variable.inTest": "Dans l'envoi de test", + "templates.provider.variable.notInTest": "Vide dans l'envoi de test", + "templates.provider.detail.notInTestHint": "Les variables marquées \"Vide dans l'envoi de test\" restent vides dans l'e-mail de test. Votre code les fournit.", + "templates.provider.detail.code": "Envoyer depuis le code", + "templates.provider.detail.copyCode": "Copier l'exemple de code", + "templates.provider.fallback.hint": "Utilisé uniquement si rien n'a été envoyé : le modèle est supprimé ou non publié, ou le fournisseur a refusé l'e-mail. Sans modèle de secours, l'envoi échoue avec une erreur.", + "templates.provider.fallback.label": "Modèle de secours", + "templates.provider.fallback.none": "Signaler une erreur (recommandé)", + "templates.provider.testSend.hint": "Laissez vide pour envoyer le test à votre propre adresse e-mail d'administrateur.", + "templates.provider.testSend.recipient": "Envoyer le test à", + "templates.provider.testSend.placeholder": "Votre adresse e-mail d'administrateur", + "templates.provider.detail.title": "Modèle du fournisseur", + "templates.provider.copy.button": "Copier comme modèle Magic Mail", + "templates.provider.testSend.submit": "Envoyer le test", + "templates.provider.copy.confirmTitle": "Copier avec des modifications ?", + "templates.provider.copy.confirmBody": "Une partie de la logique Handlebars ne peut pas être reprise exactement dans les modèles Magic Mail :", + "templates.provider.copy.confirm": "Copier quand même", + "templates.provider.heading": "Modèles du fournisseur", + "templates.provider.error.title": "Les modèles du fournisseur n'ont pas pu être chargés", + "templates.provider.error.description": "Vérifiez votre connexion et vos autorisations, puis réessayez.", + "templates.provider.lastSynced": "Dernière synchronisation {time}.", + "templates.provider.neverSynced": "Pas encore synchronisé.", + "templates.provider.table.name": "Modèle", + "templates.provider.table.changed": "Modifié chez le fournisseur", + "templates.provider.table.accounts": "Comptes", + "templates.provider.table.status": "Statut", + "templates.provider.syncing": "Synchronisation...", + "templates.provider.sync": "Synchroniser", + "templates.provider.empty.syncingTitle": "Lecture de vos modèles du fournisseur...", + "templates.provider.empty.title": "Aucun modèle du fournisseur trouvé", + "templates.provider.empty.description": "Créez un modèle dynamique chez SendGrid ou un modèle chez Mailgun, puis sélectionnez Synchroniser. Magic Mail l'affiche ici et peut l'envoyer avec votre routage, votre basculement et vos journaux.", + "templates.provider.open": "Ouvrir {name}", + "templates.provider.description": "Modèles en lecture seule issus de vos comptes SendGrid et Mailgun.", + "templates.provider.accountError.title": "{account} ({provider}) n'a pas pu être lu", + "templates.provider.accountError.keep": "Ses modèles conservent leur dernier état synchronisé.", + "templates.provider.accountError.auth": "La clé API a été refusée ou n'est pas autorisée à lire les modèles.", + "templates.provider.accountError.rateLimited": "La limite de requêtes du fournisseur a été atteinte. Réessayez dans une minute.", + "templates.provider.accountError.credentials": "Les identifiants enregistrés ne peuvent pas être lus. Saisissez de nouveau la clé API.", + "templates.provider.accountError.notFound": "Le fournisseur n'a pas trouvé ce compte ou ce domaine.", + "templates.provider.accountError.unavailable": "Le fournisseur n'a pas pu être joint.", + "templates.coreDesign.savedDesigner": "{name} utilise désormais l'éditeur Magic Mail.", + "templates.coreDesign.savedProvider": "{name} utilise désormais \"{template}\".", + "templates.coreDesign.failure": "Le design n'a pas pu être enregistré.", + "templates.coreDesign.title": "Design de {name}", + "templates.coreDesign.hint": "Avec un modèle du fournisseur, SendGrid ou Mailgun génère cet e-mail. Le routage, le basculement et les journaux restent dans Magic Mail.", + "templates.coreDesign.label": "Design", + "templates.coreDesign.designer": "Éditeur Magic Mail (par défaut)", + "templates.coreDesign.option": "{name} ({provider})", + "templates.coreDesign.staleSelected": "Ce modèle a le statut \"{status}\". Les envois échouent jusqu'à ce qu'il soit de nouveau disponible.", + "templates.coreDesign.sentHeading": "Variables envoyées par Magic Mail", + "templates.coreDesign.sentHint": "Utilisez ces noms dans le modèle du fournisseur. \"url\" est le lien final contenant le code.", + "templates.coreDesign.missingTitle": "Le modèle utilise des variables que Magic Mail n'envoie pas", + "templates.coreDesign.missingBody": "Celles-ci restent vides : {names}", + "templates.coreDesign.fallback": "Si le modèle du fournisseur échoue, envoyer à la place la version de l'éditeur Magic Mail", + "templates.coreDesign.fallbackHint": "Désactivé : l'e-mail échoue avec une erreur explicite et rien d'autre n'est envoyé." } diff --git a/admin/src/translations/pt.json b/admin/src/translations/pt.json index 886e4aa..b28d4b9 100644 --- a/admin/src/translations/pt.json +++ b/admin/src/translations/pt.json @@ -929,5 +929,123 @@ "accountModal.sendgrid.regionHint": "Escolha EU apenas para um subusuário regional da EU. As contas da EU são chamadas por meio de api.eu.sendgrid.com; todas as outras, por meio de api.sendgrid.com.", "accountModal.sendgrid.region": "Região do SendGrid", "accountModal.sendgrid.regionGlobal": "Global (api.sendgrid.com)", - "accountModal.sendgrid.regionEu": "EU (api.eu.sendgrid.com)" + "accountModal.sendgrid.regionEu": "EU (api.eu.sendgrid.com)", + "templates.coreDesign.designerShort": "Designer do Magic Mail", + "templates.coreDesign.providerShort": "{name} ({provider})", + "templates.coreDesign.staleTitle": "Um e-mail do sistema usa um modelo do provedor que não está disponível", + "templates.coreDesign.staleBody": "{names}: esses e-mails falham até que o modelo esteja disponível novamente e sincronizado, ou até que você volte para o designer do Magic Mail.", + "templates.core.table.design": "Design", + "templates.coreDesign.choose": "Escolher o design de {name}", + "templates.convert.title": "Converter para SendGrid ou Mailgun", + "templates.provider.status.ok": "Pronto", + "templates.provider.status.matchedByName": "Associado pelo nome", + "templates.provider.status.unpublished": "Nenhuma versão ativa", + "templates.provider.status.missing": "Excluído no provedor", + "templates.provider.warning.sectionAmbiguous": "Uma seção Mustache se tornou um bloco \"if\". Use \"each\" em vez disso se o valor for uma lista.", + "templates.provider.warning.helperUnsupported": "Um helper como \"equal\" não tem equivalente em Mustache. A tag foi mantida; edite-a manualmente.", + "templates.provider.warning.elseIfUnsupported": "\"else if\" não tem equivalente em Mustache. O bloco foi mantido; edite-o manualmente.", + "templates.provider.warning.dataVariableUnsupported": "Variáveis de loop como @index ou ../ não têm equivalente em Mustache.", + "templates.provider.warning.eachElseUnsupported": "\"else\" dentro de um loop não tem equivalente em Mustache. O bloco foi mantido.", + "templates.provider.warning.unbalanced": "Um bloco não está fechado corretamente. Ele foi copiado sem alterações.", + "templates.provider.warning.partialUnsupported": "Partials não são suportados. A tag foi mantida.", + "templates.provider.warning.delimiterUnsupported": "Delimitadores alterados não são suportados. O restante foi copiado sem alterações.", + "templates.provider.warning.pathUnsupported": "Um nome de variável com caracteres especiais foi mantido sem alterações.", + "templates.provider.warning.unsupportedTag": "Uma tag não pôde ser convertida e foi mantida sem alterações.", + "templates.provider.warning.tooLarge": "O modelo é grande demais para ser verificado por completo.", + "templates.convert.failure": "Não foi possível converter o modelo.", + "templates.convert.loading": "Convertendo...", + "templates.convert.description": "Cole este HTML em um modelo dinâmico do SendGrid ou em um modelo do Mailgun e depois sincronize. As variáveis mantêm seus nomes; apenas os blocos de lógica mudam.", + "templates.convert.warningsTitle": "Verifique estes blocos", + "templates.provider.copy.warningLine": "Linha {line}: {message}", + "templates.convert.subject": "Assunto", + "templates.convert.html": "HTML", + "templates.convert.copied": "HTML copiado.", + "templates.convert.copyHtml": "Copiar HTML", + "templates.convert.subjectCopied": "Assunto copiado.", + "templates.convert.copySubject": "Copiar assunto", + "templates.provider.sync.partial": "Sincronizado. {count, plural, one {# conta não pôde ser lida} other {# contas não puderam ser lidas}}.", + "templates.provider.sync.success": "Modelos do provedor sincronizados.", + "templates.provider.sync.rateLimited": "Muitas sincronizações em pouco tempo. Tente novamente em um minuto.", + "templates.provider.sync.failure": "Não foi possível sincronizar os modelos do provedor.", + "templates.coreDesign.openTemplates": "Abrir modelos de e-mail", + "templates.provider.testSend.success": "E-mail de teste enviado para {email}.", + "templates.provider.fallback.cleared": "Modelo de reserva removido. Envios com falha informam um erro.", + "templates.provider.fallback.saved": "Modelo de reserva salvo.", + "templates.provider.fallback.failure": "Não foi possível salvar o modelo de reserva.", + "templates.provider.copy.successWithWarnings": "Cópia criada. Verifique os blocos marcados no designer antes de usá-la.", + "templates.provider.copy.success": "Cópia criada como modelo do Magic Mail.", + "templates.provider.copy.failure": "Não foi possível copiar o modelo.", + "templates.provider.detail.error": "Não foi possível carregar este modelo.", + "templates.provider.detail.errorHint": "Sincronize os modelos do provedor e abra-o novamente.", + "templates.provider.detail.loading": "Carregando modelo...", + "templates.provider.detail.changed": "Alterado em {provider}: {date}", + "templates.provider.detail.missingTitle": "Excluído em {provider}", + "templates.provider.detail.unpublishedTitle": "Nenhuma versão ativa em {provider}", + "templates.provider.detail.staleBody": "Os envios com este modelo falham com um erro claro até que ele esteja disponível novamente e sincronizado.", + "templates.provider.detail.matchedTitle": "Associado pelo nome", + "templates.provider.detail.matchedBody": "O ID no provedor mudou, por exemplo, depois que este banco de dados foi movido para outro ambiente. O Magic Mail usa o modelo com o mesmo nome.", + "templates.provider.detail.preview": "Pré-visualização", + "templates.provider.detail.previewHint": "{provider} preenche os espaços reservados no envio. Assunto: {subject}", + "templates.provider.detail.previewTitle": "Pré-visualização de {name}", + "templates.provider.detail.previewTooLarge": "Este modelo é grande demais para ser pré-visualizado aqui. Abra-o no provedor.", + "templates.provider.detail.previewEmpty": "Não há nenhuma versão ativa para pré-visualizar.", + "templates.provider.detail.variables": "Variáveis", + "templates.provider.detail.variablesHint": "Passe-as em data ao enviar. Os nomes são os mesmos dos modelos do Magic Mail; o envio de teste usa os valores de exemplo name e email.", + "templates.provider.detail.noVariables": "Este modelo não usa variáveis.", + "templates.provider.variable.inList": "Em uma lista", + "templates.provider.variable.inTest": "No envio de teste", + "templates.provider.variable.notInTest": "Vazia no envio de teste", + "templates.provider.detail.notInTestHint": "As variáveis marcadas como \"Vazia no envio de teste\" ficam vazias no e-mail de teste. O seu código as fornece.", + "templates.provider.detail.code": "Enviar a partir do código", + "templates.provider.detail.copyCode": "Copiar o exemplo de código", + "templates.provider.fallback.hint": "Usado apenas quando nada foi enviado: o modelo foi excluído ou não está publicado, ou o provedor recusou o e-mail. Sem um modelo de reserva, o envio falha com um erro.", + "templates.provider.fallback.label": "Modelo de reserva", + "templates.provider.fallback.none": "Informar um erro (recomendado)", + "templates.provider.testSend.hint": "Deixe em branco para enviar o teste para o seu próprio endereço de e-mail de administrador.", + "templates.provider.testSend.recipient": "Enviar teste para", + "templates.provider.testSend.placeholder": "Seu endereço de e-mail de administrador", + "templates.provider.detail.title": "Modelo do provedor", + "templates.provider.copy.button": "Copiar como modelo do Magic Mail", + "templates.provider.testSend.submit": "Enviar teste", + "templates.provider.copy.confirmTitle": "Copiar com alterações?", + "templates.provider.copy.confirmBody": "Parte da lógica Handlebars não pode ser transferida exatamente para os modelos do Magic Mail:", + "templates.provider.copy.confirm": "Copiar mesmo assim", + "templates.provider.heading": "Modelos do provedor", + "templates.provider.error.title": "Não foi possível carregar os modelos do provedor", + "templates.provider.error.description": "Verifique sua conexão e suas permissões e tente novamente.", + "templates.provider.lastSynced": "Última sincronização: {time}.", + "templates.provider.neverSynced": "Ainda não sincronizado.", + "templates.provider.table.name": "Modelo", + "templates.provider.table.changed": "Alterado no provedor", + "templates.provider.table.accounts": "Contas", + "templates.provider.table.status": "Status", + "templates.provider.syncing": "Sincronizando...", + "templates.provider.sync": "Sincronizar", + "templates.provider.empty.syncingTitle": "Lendo seus modelos do provedor...", + "templates.provider.empty.title": "Nenhum modelo do provedor encontrado", + "templates.provider.empty.description": "Crie um modelo dinâmico no SendGrid ou um modelo no Mailgun e depois selecione Sincronizar. O Magic Mail o lista aqui e pode enviá-lo com seu roteamento, failover e logs.", + "templates.provider.open": "Abrir {name}", + "templates.provider.description": "Modelos somente leitura das suas contas do SendGrid e do Mailgun.", + "templates.provider.accountError.title": "Não foi possível ler {account} ({provider})", + "templates.provider.accountError.keep": "Seus modelos mantêm o último estado sincronizado.", + "templates.provider.accountError.auth": "A chave de API foi recusada ou não tem permissão para ler modelos.", + "templates.provider.accountError.rateLimited": "O limite de requisições do provedor foi atingido. Tente novamente em um minuto.", + "templates.provider.accountError.credentials": "Não é possível ler as credenciais armazenadas. Informe a chave de API novamente.", + "templates.provider.accountError.notFound": "O provedor não encontrou esta conta ou este domínio.", + "templates.provider.accountError.unavailable": "Não foi possível acessar o provedor.", + "templates.coreDesign.savedDesigner": "{name} agora usa o designer do Magic Mail.", + "templates.coreDesign.savedProvider": "{name} agora usa \"{template}\".", + "templates.coreDesign.failure": "Não foi possível salvar o design.", + "templates.coreDesign.title": "Design de {name}", + "templates.coreDesign.hint": "Com um modelo do provedor, o SendGrid ou o Mailgun gera este e-mail. Roteamento, failover e logs permanecem no Magic Mail.", + "templates.coreDesign.label": "Design", + "templates.coreDesign.designer": "Designer do Magic Mail (padrão)", + "templates.coreDesign.option": "{name} ({provider})", + "templates.coreDesign.staleSelected": "Este modelo está com o status \"{status}\". Os envios falham até que ele esteja disponível novamente.", + "templates.coreDesign.sentHeading": "Variáveis que o Magic Mail envia", + "templates.coreDesign.sentHint": "Use estes nomes no modelo do provedor. \"url\" é o link final com o código.", + "templates.coreDesign.missingTitle": "O modelo usa variáveis que o Magic Mail não envia", + "templates.coreDesign.missingBody": "Estas ficam vazias: {names}", + "templates.coreDesign.fallback": "Se o modelo do provedor falhar, enviar em vez disso a versão do designer do Magic Mail", + "templates.coreDesign.fallbackHint": "Desativado: o e-mail falha com um erro claro e nada mais é enviado." } diff --git a/docs/acceptance/2026-11-17-provider-templates.md b/docs/acceptance/2026-11-17-provider-templates.md new file mode 100644 index 0000000..ddafe4b --- /dev/null +++ b/docs/acceptance/2026-11-17-provider-templates.md @@ -0,0 +1,271 @@ +# Acceptance: provider templates (SendGrid, Mailgun) + +Branch `feat/provider-templates` (PR #20) against `main`. It was developed stacked on `fix/provider-send-paths` (PR #23, SendGrid EU region and safer SendGrid/Mailgun send paths), which shipped as 4.7.0; #20 was then re-applied on top of 4.7.0. Planned release: 4.8.0. + +**Status: SendGrid accepted, Mailgun spec-verified only.** On 2026-11-18 every SendGrid check passed against the real SendGrid API (sends in sandbox mode only) and the Event Webhook was tested end to end; see [Live suite](#live-suite) and [SendGrid full integration](#sendgrid-full-integration-2026-11-18). Mailgun has not run against the real API yet (no Mailgun credentials); it is verified against the official OpenAPI specification and with tests. On 2026-11-19 the maintainer approved releasing on this basis; #23 shipped as 4.7.0 and this branch was re-applied on top of it (StrictMode admin tests for the provider-template screens added). The SendGrid live suite passed again on the re-applied branch (48 tests, 30 passed, 0 failed, 18 skipped; account clean afterwards). + +## Scope + +The P1 plan in the workbench (`docs/plans/2026-11-16-strapi-rfc-opportunities.md`), following Strapi RFC [#27752](https://github.com/strapi/strapi/discussions/27752): + +- read-only sync of templates +- preview, detected variables and test send +- sending with the same `data` object +- routing to the accounts that have the template +- strict errors, with an opt-in local fallback +- a design choice for the core emails, with payload v1 +- copy and convert between template formats +- name re-match +- security and privacy rules +- no raw provider ids on the public Content API + +## Evidence + +### 1. Old features unchanged + +| Check | Result | +| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Golden provider payloads | `tests/golden-send-payloads.test.js`, 9 tests. Recorded **before** any send code changed (commit `dc80386` after the rebase, the first commit of the branch). Covers local-template sends through SendGrid and Mailgun (with and without tracking, marketing and high priority), SMTP/nodemailer, a plain HTML send, and the users-permissions password-reset mail through the provider wrapper for SendGrid, Mailgun and SMTP. Re-recorded once on top of #23 (see [Stacked on #23](#stacked-on-23-2026-11-18)); otherwise unchanged at the end of the branch. | +| Existing suites | `npm test` on the stacked branch (2026-11-18): 693 tests, 690 passed, 0 failures, 3 skipped (PostgreSQL multi-process tests without `MAGIC_MAIL_TEST_PG_URL`, the same 3 as before). One timing test that was already there (`rate limiter does not sweep...`) can fail when the machine is under heavy load; it passes alone and in CI. | +| Browser regression (phase A) | Accounts, routing, templates, designer, analytics, outbox and plugin settings at 1440 px, light and dark, on SQLite and PostgreSQL. Every screen loads, document overflow is 0 and there are 0 plugin console messages. Without a SendGrid or Mailgun account, nothing new is visible: no provider section, no Design column and no Convert section. | + +### 2. Unit, integration and contract tests + +| Suite | Tests | +| ---------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `tests/provider-template-utils.test.js` | 51: variable detection; Mustache to Handlebars and back; plain-JSON conversion; time budgets on 50 000-character adversarial inputs | +| `tests/provider-templates-units.test.js` | 9: core payload v1, user allowlist, link building, the core-mail capture (TTL, size bound, single use), provider API helpers, key slugs, HTML copy design, admin controller (key validation, test-send default recipient, the convert route) | +| `tests/provider-templates-integration.test.js` | 22, against fake SendGrid and Mailgun HTTP servers: paginated sync, EU base URLs, Mailgun domain and account scope, a domain-only key, 429/401 during sync (previous rows kept), deleted and unpublished templates, name re-match, removed accounts, the same `data` as `dynamic_template_data` / `t:variables` (and the same visible Mustache output), subject rules, 16 KB and 1 MB limits, cyclic data, failover on 429 only between accounts that have the template, an explicit account without the template, raw ids and combinations rejected, the public Content API schema rejecting `providerTemplate`, the opt-in fallback (400: fallback; 500: no fallback; stale: fallback), core mails through the wrapper (payload v1, strict, designer fallback), copy and convert | +| `tests/provider-templates-contract.test.js` | 8. Checks 20 recorded exchanges against the official OpenAPI documents, each as a request and as a fake response. Also: the pinning checksums, the 3 listed spec deviations, 4 negative checks (the checker catches a wrong key, a bad parameter, an undocumented form field and an unknown host) and the live-suite switches `sandbox_mode` / `o:testmode` | + +Pinned specs (SHA-256 of the official source file): + +- SendGrid: `twilio/sendgrid-oai` at commit `51a0dee5a218634f0775cdc589e3d728136674de` + - `tsg_templates_v3.json`: `d38d9f0c…` + - `tsg_mail_v3.json`: `1bf9b256…` +- Mailgun: API reference bundle `mailgun.json`, retrieved 2026-11-17: `3bf29afd…` + +Spec deviations, each re-checked by the live suite: + +1. The SendGrid spec types template ids as 36-character UUIDs. Dynamic template ids are `d-` plus 32 hex characters. +2. The Mailgun spec marks `subject` as required on messages. Its own field description says it is not required with a template that has a Subject header. +3. Already in 4.5.0 and unchanged here (locked by the golden tests): top-level `custom_args` is sent as an object, while the spec says string. + +### 3. Browser acceptance + +Host setup: + +- Evidence run on commit `29ea4c9` (branch rebased onto main 4.5.1), 2026-11-17, Node 22. Isolated Strapi 5.62.0 host on port 1395, admin built from the packed tarball of this branch. The installed `dist/server/index.js` was compared with the tarball and the branch build: identical. +- React, react-dom, styled-components and react-router-dom are each installed once (deduped). +- Synthetic data only: `example.test` accounts and fixed synthetic templates. +- Secrets are random (`.env`, mode 600, never printed). +- Egress is blocked by a preload. Only loopback is allowed, and the four provider hosts are redirected to the local fake servers. 0 egress attempts were recorded. +- SQLite and PostgreSQL 16. +- Scripts and raw results stay outside the repository (scratch directory); screenshots were checked before use. + +| Phase | SQLite | PostgreSQL | +| --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | +| A: regression and "nothing new without a provider account" | pass | pass | +| B: all new click paths, light and dark, measurements at 1440/768/390/320 (52 measured states) | pass | pass | +| C: de, fr, es, pt at 1440 and 320 (list and dialog): no ICU or message-id leaks, no overflow | pass | pass | +| Read-only role (access + read + users-permissions read) | API: list, detail and sync 200; test-send, fallback, copy and core-design 403; anonymous 401. UI: no Send test, Copy, fallback or Design actions. | same | +| Forced states (`page.route`, UI only) | load error with Try again, retry recovers; empty list with the next step and a Sync button; account error notice | n/a | +| Plugin console messages (errors and warnings) | 0 | 0 | + +Measurements: + +- Document overflow is 0 and no element is outside the viewport in every measured state. +- `lowContrast` hits are white text on the existing brand gradients (page header, gradient buttons, dialog header). `measure.js` cannot see gradients; the contrast was checked by eye on the screenshots. These elements already existed. +- `smallTargets`: the Design-dialog checkbox box is 20 × 20 px (DS `Checkbox`). Its label is part of the same control and can be clicked, so this is the WCAG 2.5.8 equivalent-target exception. + +Keyboard: + +- Escape closes the dialogs, and focus returns to the "Open