feat(admin): mail preview field with sandboxed HTML and test send
- Add MailPreviewField (POST /mail/preview + /mail/test-send, empty sandbox iframe) - Register mailpreview as valueless/group-labelled; SettingsFormView FORM_VALUES/FORM_LOCALE - Smoke tests for srcdoc, sequence guard, 422 keep-last, and 429 Retry-After Plan 35-03, task 1 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -125,6 +125,16 @@ export type FileItem = Schemas['cabana.FileItem']
|
||||
export type FileMutationResult = Schemas['cabana.FileMutationResult']
|
||||
/** Body of a caption save: title and description, omitted keys unchanged. */
|
||||
export type AdminFileCaptionRequest = Schemas['cabana.AdminFileCaptionRequest']
|
||||
/** Body of POST /mail/preview and POST /mail/test-send. */
|
||||
export type AdminMailPreviewRequest = Schemas['cabana.AdminMailPreviewRequest']
|
||||
/** Answer of POST /mail/preview: subject, HTML and plain text. */
|
||||
export type AdminMailPreviewResult = Schemas['cabana.AdminMailPreviewResult']
|
||||
/** Answer of POST /mail/test-send: the administrator's own email. */
|
||||
export type AdminMailTestSendResult = Schemas['cabana.AdminMailTestSendResult']
|
||||
/** One mail library image with absolute public URLs. */
|
||||
export type AdminMailImage = Schemas['cabana.AdminMailImage']
|
||||
/** Meta of GET /mail/images (canUpload, paging). */
|
||||
export type AdminMailImagesMeta = Schemas['cabana.AdminMailImagesMeta']
|
||||
/** Body of a relation link: the ids and, for one id, its pivot values. */
|
||||
export type AdminRelationLinkRequest = Schemas['cabana.AdminRelationLinkRequest']
|
||||
/** A fileupload field's preview thumbnail mode. */
|
||||
|
||||
350
admin/src/components/form/fields/MailPreviewField.vue
Normal file
350
admin/src/components/form/fields/MailPreviewField.vue
Normal file
@@ -0,0 +1,350 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, inject, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { Send } from '@lucide/vue'
|
||||
import { api } from '../../../api/client'
|
||||
import type { AdminRecord } from '../../../api/types'
|
||||
import { t } from '../../../app/i18n'
|
||||
import { currentUser } from '../../../state/useAuth'
|
||||
import { showToast } from '../../../state/useToasts'
|
||||
import Button from '../../ui/Button.vue'
|
||||
import type { FieldControlProps } from '../control'
|
||||
import { FORM_VALUES } from '../formContext'
|
||||
|
||||
// Live mail preview (D-16) and test send (D-17). The iframe's srcdoc is only
|
||||
// the server's rendered HTML from a 2xx answer; the SPA never builds mail
|
||||
// markup. Test send posts the same draft with no recipient; the server sends
|
||||
// to the signed-in administrator only.
|
||||
const props = defineProps<FieldControlProps>()
|
||||
|
||||
const PREVIEW_DEBOUNCE_MS = 500
|
||||
const emptyValues = ref<AdminRecord>({})
|
||||
const formValues = inject(FORM_VALUES, emptyValues)
|
||||
|
||||
const mode = computed(() => {
|
||||
const value = props.field.mode
|
||||
return typeof value === 'string' && value !== '' ? value : 'template'
|
||||
})
|
||||
const branding = computed(() => mode.value === 'branding')
|
||||
const adminEmail = computed(() => currentUser.value?.email ?? '')
|
||||
|
||||
const format = ref<'html' | 'text'>('html')
|
||||
const subject = ref('')
|
||||
const html = ref('')
|
||||
const text = ref('')
|
||||
const hasRender = ref(false)
|
||||
const loading = ref(false)
|
||||
const previewError = ref('')
|
||||
const testError = ref('')
|
||||
const testBusy = ref(false)
|
||||
const testBlockedUntil = ref(0)
|
||||
const now = ref(Date.now())
|
||||
|
||||
let sequence = 0
|
||||
let previewTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let blockTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let clockTimer: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
const contentKey = computed(() => {
|
||||
switch (mode.value) {
|
||||
case 'layout':
|
||||
case 'partial':
|
||||
return 'content_html'
|
||||
case 'branding':
|
||||
return ''
|
||||
default:
|
||||
return 'body'
|
||||
}
|
||||
})
|
||||
|
||||
const draftEmpty = computed(() => {
|
||||
const key = contentKey.value
|
||||
if (key === '') {
|
||||
return false
|
||||
}
|
||||
const raw = formValues.value[key]
|
||||
return raw === null || raw === undefined || String(raw).trim() === ''
|
||||
})
|
||||
|
||||
const testDisabled = computed(() => testBusy.value || testBlockedUntil.value > now.value)
|
||||
|
||||
const sampleNote = computed(() =>
|
||||
mode.value === 'template'
|
||||
? t('backend::lang.mail.preview.sample_note')
|
||||
: t('backend::lang.mail.preview.sample_content_note'),
|
||||
)
|
||||
|
||||
function cancelTimer() {
|
||||
if (previewTimer !== null) {
|
||||
clearTimeout(previewTimer)
|
||||
previewTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
function refusalMessage(error: unknown): string {
|
||||
const details = (error as { error?: { details?: Record<string, unknown>; message?: string } } | undefined)?.error
|
||||
?.details
|
||||
const fromDetails = details?.message
|
||||
if (typeof fromDetails === 'string' && fromDetails !== '') {
|
||||
return fromDetails
|
||||
}
|
||||
const top = (error as { error?: { message?: string } } | undefined)?.error?.message
|
||||
if (typeof top === 'string' && top !== '') {
|
||||
return top
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
function schedulePreview() {
|
||||
cancelTimer()
|
||||
previewTimer = setTimeout(() => {
|
||||
previewTimer = null
|
||||
void renderPreview()
|
||||
}, PREVIEW_DEBOUNCE_MS)
|
||||
}
|
||||
|
||||
async function renderPreview() {
|
||||
if (draftEmpty.value) {
|
||||
sequence++
|
||||
loading.value = false
|
||||
previewError.value = ''
|
||||
return
|
||||
}
|
||||
const current = ++sequence
|
||||
loading.value = true
|
||||
try {
|
||||
const { data, error, response } = await api.POST('/mail/preview', {
|
||||
body: {
|
||||
mode: mode.value,
|
||||
id: props.recordId ?? 0,
|
||||
values: { ...formValues.value },
|
||||
},
|
||||
})
|
||||
if (current !== sequence) {
|
||||
return
|
||||
}
|
||||
if (data) {
|
||||
subject.value = data.data.subject
|
||||
html.value = data.data.html
|
||||
text.value = data.data.text
|
||||
hasRender.value = true
|
||||
previewError.value = ''
|
||||
return
|
||||
}
|
||||
if (response.status === 422) {
|
||||
const message = refusalMessage(error)
|
||||
previewError.value = hasRender.value
|
||||
? t('backend::lang.mail.preview.failed', { message })
|
||||
: t('backend::lang.mail.preview.failed_first', { message })
|
||||
return
|
||||
}
|
||||
previewError.value = t('backend::lang.mail.preview.unavailable')
|
||||
} catch {
|
||||
if (current !== sequence) {
|
||||
return
|
||||
}
|
||||
previewError.value = t('backend::lang.mail.preview.unavailable')
|
||||
} finally {
|
||||
if (current === sequence) {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function retryAfterSeconds(response: Response): number {
|
||||
const raw = response.headers.get('Retry-After')
|
||||
const parsed = raw ? Number.parseInt(raw, 10) : NaN
|
||||
return Number.isFinite(parsed) && parsed > 0 ? parsed : 60
|
||||
}
|
||||
|
||||
function armTestBlock(seconds: number) {
|
||||
testBlockedUntil.value = Date.now() + seconds * 1000
|
||||
now.value = Date.now()
|
||||
if (blockTimer !== null) {
|
||||
clearTimeout(blockTimer)
|
||||
}
|
||||
blockTimer = setTimeout(() => {
|
||||
blockTimer = null
|
||||
testBlockedUntil.value = 0
|
||||
now.value = Date.now()
|
||||
}, seconds * 1000)
|
||||
if (clockTimer === null) {
|
||||
clockTimer = setInterval(() => {
|
||||
now.value = Date.now()
|
||||
if (testBlockedUntil.value <= now.value && clockTimer !== null) {
|
||||
clearInterval(clockTimer)
|
||||
clockTimer = null
|
||||
}
|
||||
}, 250)
|
||||
}
|
||||
}
|
||||
|
||||
async function onTestSend() {
|
||||
if (branding.value || testDisabled.value || draftEmpty.value) {
|
||||
return
|
||||
}
|
||||
testBusy.value = true
|
||||
testError.value = ''
|
||||
try {
|
||||
const { data, error, response } = await api.POST('/mail/test-send', {
|
||||
body: {
|
||||
mode: mode.value,
|
||||
id: props.recordId ?? 0,
|
||||
values: { ...formValues.value },
|
||||
},
|
||||
})
|
||||
if (data) {
|
||||
showToast(t('backend::lang.mail.preview.test_sent', { email: data.data.email }))
|
||||
return
|
||||
}
|
||||
const status = response.status
|
||||
if (status === 429) {
|
||||
const seconds = retryAfterSeconds(response)
|
||||
armTestBlock(seconds)
|
||||
testError.value = t('backend::lang.mail.preview.test_limited', { seconds })
|
||||
return
|
||||
}
|
||||
if (status === 422) {
|
||||
testError.value = t('backend::lang.mail.preview.test_invalid', { message: refusalMessage(error) })
|
||||
return
|
||||
}
|
||||
if (status === 403) {
|
||||
showToast(error?.error.message || t('backend::lang.form.forbidden'), 'danger')
|
||||
return
|
||||
}
|
||||
if (status >= 500) {
|
||||
showToast(t('backend::lang.mail.preview.test_failed'), 'danger')
|
||||
return
|
||||
}
|
||||
showToast(error?.error.message || t('backend::lang.mail.preview.test_failed'), 'danger')
|
||||
} catch {
|
||||
showToast(t('backend::lang.mail.preview.test_failed'), 'danger')
|
||||
} finally {
|
||||
testBusy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => formValues.value,
|
||||
() => {
|
||||
if (draftEmpty.value) {
|
||||
cancelTimer()
|
||||
sequence++
|
||||
loading.value = false
|
||||
previewError.value = ''
|
||||
return
|
||||
}
|
||||
schedulePreview()
|
||||
},
|
||||
{ deep: true },
|
||||
)
|
||||
|
||||
onMounted(() => {
|
||||
void renderPreview()
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
cancelTimer()
|
||||
sequence++
|
||||
if (blockTimer !== null) {
|
||||
clearTimeout(blockTimer)
|
||||
}
|
||||
if (clockTimer !== null) {
|
||||
clearInterval(clockTimer)
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-2" data-mail-preview>
|
||||
<div class="overflow-hidden rounded-inner border border-border">
|
||||
<div class="flex flex-wrap items-center gap-2 border-b border-border bg-subtle p-1">
|
||||
<div role="tablist" class="inline-flex gap-1 rounded-inner border border-border bg-subtle p-1">
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
data-mail-preview-format="html"
|
||||
:aria-selected="format === 'html' ? 'true' : 'false'"
|
||||
:class="format === 'html' ? 'bg-surface text-text shadow-tab' : 'text-muted hover:text-text'"
|
||||
class="inline-flex h-[34px] items-center gap-2 rounded-tab px-4 font-semibold transition-colors duration-150 ease-out"
|
||||
@click="format = 'html'"
|
||||
>
|
||||
{{ t('backend::lang.mail.preview.html') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
data-mail-preview-format="text"
|
||||
:aria-selected="format === 'text' ? 'true' : 'false'"
|
||||
:class="format === 'text' ? 'bg-surface text-text shadow-tab' : 'text-muted hover:text-text'"
|
||||
class="inline-flex h-[34px] items-center gap-2 rounded-tab px-4 font-semibold transition-colors duration-150 ease-out"
|
||||
@click="format = 'text'"
|
||||
>
|
||||
{{ t('backend::lang.mail.preview.text') }}
|
||||
</button>
|
||||
</div>
|
||||
<p role="status" class="ml-auto px-2 text-[13px] text-muted" data-mail-preview-status>
|
||||
{{ loading ? t('backend::lang.mail.preview.rendering') : '' }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<p
|
||||
v-if="previewError"
|
||||
role="alert"
|
||||
data-mail-preview-error
|
||||
class="border-b border-border px-4 py-2 text-[13px] text-danger"
|
||||
>
|
||||
{{ previewError }}
|
||||
</p>
|
||||
|
||||
<div
|
||||
v-if="!branding && (hasRender || !draftEmpty)"
|
||||
class="flex gap-2 border-b border-border px-4 py-3"
|
||||
data-mail-preview-subject
|
||||
>
|
||||
<span class="font-semibold">{{ t('backend::lang.mail.preview.subject') }}</span>
|
||||
<span class="min-w-0 break-words">{{ subject }}</span>
|
||||
</div>
|
||||
|
||||
<div v-if="draftEmpty" class="px-4 py-3 text-center text-[13px] text-muted" data-mail-preview-empty>
|
||||
{{ t('backend::lang.mail.preview.empty') }}
|
||||
</div>
|
||||
<iframe
|
||||
v-else-if="format === 'html'"
|
||||
sandbox=""
|
||||
referrerpolicy="no-referrer"
|
||||
:srcdoc="html"
|
||||
:title="t('backend::lang.mail.preview.frame_title')"
|
||||
class="block h-[640px] w-full border-0 bg-white"
|
||||
data-mail-preview-frame
|
||||
/>
|
||||
<pre
|
||||
v-else
|
||||
class="m-0 max-h-[640px] overflow-auto bg-surface px-4 py-3 font-mono text-[13px] whitespace-pre-wrap"
|
||||
data-mail-preview-text
|
||||
>{{ text }}</pre
|
||||
>
|
||||
</div>
|
||||
|
||||
<p class="text-[13px] text-muted" data-mail-preview-note>{{ sampleNote }}</p>
|
||||
<p v-if="field.comment" class="text-[13px] text-muted" data-mail-preview-comment>{{ field.comment }}</p>
|
||||
|
||||
<div v-if="!branding" class="flex flex-wrap items-center gap-2" data-mail-preview-test>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:icon="Send"
|
||||
:disabled="testDisabled || draftEmpty"
|
||||
data-mail-preview-test-send
|
||||
@click="onTestSend"
|
||||
>
|
||||
{{ testBusy ? t('backend::lang.mail.preview.test_sending') : t('backend::lang.mail.preview.test_send') }}
|
||||
</Button>
|
||||
<p class="text-[13px] text-muted" data-mail-preview-test-hint>
|
||||
{{ t('backend::lang.mail.preview.test_hint', { email: adminEmail }) }}
|
||||
</p>
|
||||
<p v-if="testError" role="alert" class="basis-full text-[13px] text-danger" data-mail-preview-test-error>
|
||||
{{ testError }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -33,6 +33,9 @@
|
||||
// Phase 18.1 adds the taglist control (D-17): tags edited as chips with an
|
||||
// input that adds a tag on Enter or a comma, the field's options offered as
|
||||
// suggestions; the value is a list of strings (array mode).
|
||||
// Phase 35 adds the mail editor controls: mailpreview is valueless and
|
||||
// group-labelled (live postcard HTML in a sandboxed iframe plus test send);
|
||||
// codeeditor, colorpicker and mailimage follow in the same phase.
|
||||
import type { Component } from 'vue'
|
||||
import type { FormField } from '../../api/types'
|
||||
import CheckboxField from './fields/CheckboxField.vue'
|
||||
@@ -53,6 +56,7 @@ import SwitchField from './fields/SwitchField.vue'
|
||||
import TextField from './fields/TextField.vue'
|
||||
import TextareaField from './fields/TextareaField.vue'
|
||||
import MarkdownField from './fields/MarkdownField.vue'
|
||||
import MailPreviewField from './fields/MailPreviewField.vue'
|
||||
import MoneyField from './fields/MoneyField.vue'
|
||||
import TaglistField from './fields/TaglistField.vue'
|
||||
import MLTextField from './fields/MLTextField.vue'
|
||||
@@ -98,6 +102,7 @@ const renderers = new Map<string, Component>([
|
||||
['repeater', RepeaterField],
|
||||
['money', MoneyField],
|
||||
['taglist', TaglistField],
|
||||
['mailpreview', MailPreviewField],
|
||||
])
|
||||
|
||||
/** Types whose control shows the label itself (toggle cards, relation manager). */
|
||||
@@ -111,7 +116,7 @@ const selfLabelled = new Set<string>(['switch', 'checkbox', RELATION_MANAGER])
|
||||
const recordBound = new Set<string>([RELATION_MANAGER])
|
||||
|
||||
/** Types that hold no form value: never part of the save body (D-09). */
|
||||
const valueless = new Set<string>([RELATION_MANAGER, 'widget', 'partial', 'fileupload'])
|
||||
const valueless = new Set<string>([RELATION_MANAGER, 'widget', 'partial', 'fileupload', 'mailpreview'])
|
||||
|
||||
/**
|
||||
* Types whose control is a group rather than one focusable element: the
|
||||
@@ -126,6 +131,7 @@ const groupLabelledTypes = new Set<string>([
|
||||
'mltextarea',
|
||||
'mlmarkdown',
|
||||
'repeater',
|
||||
'mailpreview',
|
||||
])
|
||||
|
||||
export function rendererFor(type: string): Component {
|
||||
|
||||
@@ -5,11 +5,11 @@ import { ArrowLeft } from '@lucide/vue'
|
||||
import { api } from '../api/client'
|
||||
import type { AdminRecord, FormField, FormView } from '../api/types'
|
||||
import { shortcutHint } from '../app/hotkeys'
|
||||
import { t } from '../app/i18n'
|
||||
import { currentLocale, t } from '../app/i18n'
|
||||
import FormErrorBanner from '../components/form/FormErrorBanner.vue'
|
||||
import FormGrid from '../components/form/FormGrid.vue'
|
||||
import FormTabs from '../components/form/FormTabs.vue'
|
||||
import { SETTINGS_SECRETS } from '../components/form/formContext'
|
||||
import { FORM_LOCALE, FORM_VALUES, SETTINGS_SECRETS } from '../components/form/formContext'
|
||||
import {
|
||||
DEFAULT_TAB,
|
||||
contextAllows,
|
||||
@@ -52,6 +52,9 @@ const busy = ref(false)
|
||||
const activeTab = ref(DEFAULT_TAB)
|
||||
|
||||
provide(SETTINGS_SECRETS, computed(() => secrets.value))
|
||||
// Phase 35: mailpreview on Branding reads the unsaved draft (UI-SPEC C8).
|
||||
provide(FORM_VALUES, computed(() => values.value))
|
||||
provide(FORM_LOCALE, computed(() => schema.value?.meta.locale || currentLocale.value))
|
||||
|
||||
const fields = computed(() => (schema.value?.fields ?? []).filter((field) => contextAllows(field, 'update')))
|
||||
const fieldNames = computed(() => fields.value.map((field) => field.name))
|
||||
|
||||
@@ -108,6 +108,12 @@
|
||||
},
|
||||
"rowStateDisabled": {
|
||||
"other": "Inactive"
|
||||
},
|
||||
"rowStateCustomized": {
|
||||
"other": "Customized"
|
||||
},
|
||||
"rowStateOutdated": {
|
||||
"other": "Outdated"
|
||||
}
|
||||
},
|
||||
"meta": {
|
||||
|
||||
4
admin/tests/fixtures/roster.list-schema.json
vendored
4
admin/tests/fixtures/roster.list-schema.json
vendored
@@ -37,7 +37,9 @@
|
||||
"selected": { "other": ":count selected" },
|
||||
"rowStateDeleted": { "other": "Deleted" },
|
||||
"rowStateNegative": { "other": "Blocked" },
|
||||
"rowStateDisabled": { "other": "Not active" }
|
||||
"rowStateDisabled": { "other": "Not active" },
|
||||
"rowStateCustomized": { "other": "Customized" },
|
||||
"rowStateOutdated": { "other": "Outdated" }
|
||||
},
|
||||
"meta": { "locale": "en" }
|
||||
},
|
||||
|
||||
@@ -39,7 +39,9 @@
|
||||
"selected": { "other": "Selected :count" },
|
||||
"rowStateDeleted": { "other": "Deleted" },
|
||||
"rowStateNegative": { "other": "Blocked" },
|
||||
"rowStateDisabled": { "other": "Inactive" }
|
||||
"rowStateDisabled": { "other": "Inactive" },
|
||||
"rowStateCustomized": { "other": "Customized" },
|
||||
"rowStateOutdated": { "other": "Outdated" }
|
||||
},
|
||||
"meta": { "locale": "en" }
|
||||
},
|
||||
|
||||
211
admin/tests/form/mail-smoke.test.ts
Normal file
211
admin/tests/form/mail-smoke.test.ts
Normal file
@@ -0,0 +1,211 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'
|
||||
import { computed, ref } from 'vue'
|
||||
import type { FormField } from '../../src/api/types'
|
||||
import { setBundle } from '../../src/app/i18n'
|
||||
import MailPreviewField from '../../src/components/form/fields/MailPreviewField.vue'
|
||||
import { FORM_VALUES } from '../../src/components/form/formContext'
|
||||
import { setCurrentUser } from '../../src/state/useAuth'
|
||||
import { clearToasts, toasts } from '../../src/state/useToasts'
|
||||
import { API, mockApi, profile, requestsTo, resetState, type Reply, wait } from '../helpers'
|
||||
import { langFixture } from '../fixtures/typed'
|
||||
|
||||
const mailPreviewBundle = {
|
||||
...langFixture.data,
|
||||
'backend::lang.mail.preview.html': { other: 'HTML' },
|
||||
'backend::lang.mail.preview.text': { other: 'Plain text' },
|
||||
'backend::lang.mail.preview.subject': { other: 'Subject' },
|
||||
'backend::lang.mail.preview.frame_title': { other: 'Preview of the HTML message' },
|
||||
'backend::lang.mail.preview.rendering': { other: 'Rendering preview…' },
|
||||
'backend::lang.mail.preview.empty': { other: 'Nothing to preview yet. Write the message first.' },
|
||||
'backend::lang.mail.preview.failed': {
|
||||
other: 'The draft cannot be rendered: :message The preview shows the last version that rendered.',
|
||||
},
|
||||
'backend::lang.mail.preview.failed_first': { other: 'The draft cannot be rendered: :message' },
|
||||
'backend::lang.mail.preview.unavailable': { other: 'Preview unavailable. It updates again with your next edit.' },
|
||||
'backend::lang.mail.preview.sample_note': {
|
||||
other: 'Variables are filled with sample values. A variable without a sample shows as [name].',
|
||||
},
|
||||
'backend::lang.mail.preview.sample_content_note': { other: 'Previewed with sample content.' },
|
||||
'backend::lang.mail.preview.test_send': { other: 'Send test to me' },
|
||||
'backend::lang.mail.preview.test_sending': { other: 'Sending…' },
|
||||
'backend::lang.mail.preview.test_hint': {
|
||||
other: 'Sends the current draft, unsaved changes included, to :email.',
|
||||
},
|
||||
'backend::lang.mail.preview.test_sent': { other: 'Test message sent to :email.' },
|
||||
'backend::lang.mail.preview.test_limited': {
|
||||
other: 'You have sent too many test messages. Try again in :seconds s.',
|
||||
},
|
||||
'backend::lang.mail.preview.test_invalid': { other: 'Fix the draft before sending a test: :message' },
|
||||
'backend::lang.mail.preview.test_failed': {
|
||||
other: 'The test message could not be sent. Check the mail settings and the application log.',
|
||||
},
|
||||
}
|
||||
|
||||
const PREVIEW = `${API}/mail/preview`
|
||||
const TEST_SEND = `${API}/mail/test-send`
|
||||
|
||||
function previewField(mode = 'template'): FormField {
|
||||
return { name: '_preview', label: 'Preview', type: 'mailpreview', mode } as FormField
|
||||
}
|
||||
|
||||
function okPreview(html = '<p>Hello</p>', subject = 'Welcome', text = 'Hello'): Reply {
|
||||
return { body: { data: { html, subject, text }, meta: {} } }
|
||||
}
|
||||
|
||||
function mountPreview(values: Record<string, unknown>, field: FormField = previewField(), recordId: number | null = 3) {
|
||||
const valuesRef = ref(values)
|
||||
return mount(MailPreviewField, {
|
||||
props: { field, modelValue: null, controlId: 'f-preview', recordId },
|
||||
global: {
|
||||
provide: {
|
||||
[FORM_VALUES as symbol]: computed(() => valuesRef.value),
|
||||
},
|
||||
},
|
||||
attachTo: document.body,
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetState()
|
||||
setBundle(mailPreviewBundle, 'en')
|
||||
clearToasts()
|
||||
setCurrentUser(profile.data)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
document.body.innerHTML = ''
|
||||
clearToasts()
|
||||
})
|
||||
|
||||
enableAutoUnmount(afterEach)
|
||||
|
||||
describe('MailPreviewField', () => {
|
||||
it('binds a sandboxed srcdoc iframe to the server html only', async () => {
|
||||
const calls = mockApi({ [`POST ${PREVIEW}`]: okPreview('<p>Rendered</p>') })
|
||||
const wrapper = mountPreview({ body: 'hi' })
|
||||
await flushPromises()
|
||||
|
||||
const frame = wrapper.find('[data-mail-preview-frame]')
|
||||
expect(frame.exists()).toBe(true)
|
||||
expect(frame.attributes('sandbox')).toBe('')
|
||||
expect(frame.attributes('src')).toBeUndefined()
|
||||
expect(frame.attributes('srcdoc')).toBe('<p>Rendered</p>')
|
||||
expect(requestsTo(calls, 'POST', PREVIEW)).toHaveLength(1)
|
||||
const body = await requestsTo(calls, 'POST', PREVIEW)[0]!.clone().json()
|
||||
expect(body).toEqual({ mode: 'template', id: 3, values: { body: 'hi' } })
|
||||
})
|
||||
|
||||
it('drops a stale preview answer via the sequence guard', async () => {
|
||||
let resolveFirst!: (reply: Reply) => void
|
||||
const first = new Promise<Reply>((resolve) => {
|
||||
resolveFirst = resolve
|
||||
})
|
||||
let calls = 0
|
||||
mockApi({
|
||||
[`POST ${PREVIEW}`]: async () => {
|
||||
calls++
|
||||
if (calls === 1) {
|
||||
return first
|
||||
}
|
||||
return okPreview('<p>Second</p>', 'Second')
|
||||
},
|
||||
})
|
||||
const values = ref({ body: 'one' })
|
||||
const wrapper = mount(MailPreviewField, {
|
||||
props: { field: previewField(), modelValue: null, controlId: 'f-preview', recordId: 1 },
|
||||
global: { provide: { [FORM_VALUES as symbol]: computed(() => values.value) } },
|
||||
attachTo: document.body,
|
||||
})
|
||||
await flushPromises()
|
||||
values.value = { body: 'two' }
|
||||
await wait(520)
|
||||
await flushPromises()
|
||||
resolveFirst(okPreview('<p>First</p>', 'First'))
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.find('[data-mail-preview-frame]').attributes('srcdoc')).toBe('<p>Second</p>')
|
||||
expect(wrapper.find('[data-mail-preview-subject]').text()).toContain('Second')
|
||||
})
|
||||
|
||||
it('keeps the previous srcdoc after a 422 and shows the failed line', async () => {
|
||||
let n = 0
|
||||
mockApi({
|
||||
[`POST ${PREVIEW}`]: () => {
|
||||
n++
|
||||
if (n === 1) {
|
||||
return okPreview('<p>Good</p>')
|
||||
}
|
||||
return {
|
||||
status: 422,
|
||||
body: {
|
||||
error: {
|
||||
code: 'validation_failed',
|
||||
message: 'Validation failed',
|
||||
details: { field: 'body', rule: 'unsafe', message: 'script refused' },
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
})
|
||||
const values = ref({ body: 'ok' })
|
||||
const wrapper = mount(MailPreviewField, {
|
||||
props: { field: previewField(), modelValue: null, controlId: 'f-preview', recordId: 1 },
|
||||
global: { provide: { [FORM_VALUES as symbol]: computed(() => values.value) } },
|
||||
attachTo: document.body,
|
||||
})
|
||||
await flushPromises()
|
||||
expect(wrapper.find('[data-mail-preview-frame]').attributes('srcdoc')).toBe('<p>Good</p>')
|
||||
|
||||
values.value = { body: 'bad' }
|
||||
await wait(520)
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.find('[data-mail-preview-frame]').attributes('srcdoc')).toBe('<p>Good</p>')
|
||||
expect(wrapper.find('[data-mail-preview-error]').text()).toContain('script refused')
|
||||
})
|
||||
|
||||
it('disables the test-send button after a 429 with Retry-After', async () => {
|
||||
mockApi({
|
||||
[`POST ${PREVIEW}`]: okPreview(),
|
||||
[`POST ${TEST_SEND}`]: {
|
||||
status: 429,
|
||||
headers: { 'Retry-After': '30' },
|
||||
body: { error: { code: 'rate_limited', message: 'Too many', details: {} } },
|
||||
},
|
||||
})
|
||||
const wrapper = mountPreview({ body: 'hi' })
|
||||
await flushPromises()
|
||||
|
||||
await wrapper.find('[data-mail-preview-test-send]').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
const button = wrapper.find('[data-mail-preview-test-send]')
|
||||
expect(button.attributes('disabled')).toBeDefined()
|
||||
expect(wrapper.find('[data-mail-preview-test-error]').text()).toContain('30')
|
||||
})
|
||||
|
||||
it('sends nothing for an empty draft', async () => {
|
||||
const calls = mockApi({ [`POST ${PREVIEW}`]: okPreview() })
|
||||
const wrapper = mountPreview({ body: ' ' })
|
||||
await flushPromises()
|
||||
|
||||
expect(requestsTo(calls, 'POST', PREVIEW)).toHaveLength(0)
|
||||
expect(wrapper.find('[data-mail-preview-empty]').exists()).toBe(true)
|
||||
expect(wrapper.find('[data-mail-preview-frame]').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('toasts the returned email on a successful test send', async () => {
|
||||
mockApi({
|
||||
[`POST ${PREVIEW}`]: okPreview(),
|
||||
[`POST ${TEST_SEND}`]: { body: { data: { email: 'dev@example.test' }, meta: {} } },
|
||||
})
|
||||
const wrapper = mountPreview({ body: 'hi' })
|
||||
await flushPromises()
|
||||
await wrapper.find('[data-mail-preview-test-send]').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(toasts.value[0]?.text).toContain('dev@example.test')
|
||||
})
|
||||
})
|
||||
@@ -37,12 +37,17 @@ export const profile = {
|
||||
export interface Reply {
|
||||
status?: number
|
||||
body: unknown
|
||||
/** Extra response headers (for example Retry-After on a 429). */
|
||||
headers?: Record<string, string>
|
||||
}
|
||||
|
||||
export type Route = Reply | ((request: Request) => Reply | Promise<Reply>)
|
||||
|
||||
export function json(status: number, body: unknown): Response {
|
||||
return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })
|
||||
export function json(status: number, body: unknown, headers: Record<string, string> = {}): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json', ...headers },
|
||||
})
|
||||
}
|
||||
|
||||
export const notFound = { error: { code: 'not_found', message: 'Not found', details: {} } }
|
||||
@@ -58,7 +63,7 @@ export function mockApi(routes: Record<string, Route>): Request[] {
|
||||
return json(404, notFound)
|
||||
}
|
||||
const reply = typeof route === 'function' ? await route(request.clone()) : route
|
||||
return json(reply.status ?? 200, reply.body)
|
||||
return json(reply.status ?? 200, reply.body, reply.headers)
|
||||
})
|
||||
return calls
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user