WIP: reference site — File field on the quote form, mail sink smoke test

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-13 16:34:34 +01:00
co-authored by Claude Fable 5.2
parent b7fb1b0e31
commit 387debc88c
8 changed files with 170 additions and 4 deletions
+2
View File
@@ -56,4 +56,6 @@ INDEXNOW_KEY=
E2E_ADMIN_EMAIL=[email protected]
E2E_ADMIN_PASSWORD=e2e-RC2nC29eKC8HJHfg
E2E_TOTP_SECRET=JPURUZNWYTZX2L42MT4SS7736WWNQWBL
# Port of the mail sink the smoke tests start (e2e/smtp-sink.ts); create-test-admin.ts points e-mail sending at it
E2E_SMTP_PORT=2526
# @starter:endif
+12 -1
View File
@@ -3,7 +3,8 @@
* the real 2FA screen instead of skipping it. LOCAL / CI database only:
* pnpm payload run e2e/create-test-admin.ts
* Values come from E2E_ADMIN_EMAIL / E2E_ADMIN_PASSWORD / E2E_TOTP_SECRET (.env.example). Not a seed: seeds
* never create users (docs/seeding.md).
* never create users (docs/seeding.md). It also points e-mail sending at the tests' local mail sink
* (E2E_SMTP_PORT, default 2526).
*/
import config from '@payload-config'
import { isLocalDatabase } from '@intecion/ipal-kit/seed'
@@ -23,4 +24,14 @@ if (found.docs[0]) {
await payload.create({ collection: 'users', data: data as never, overrideAccess: true })
}
console.log(`[e2e] test admin ready: ${email}`)
// E-mail for the smoke tests goes to a local sink the test itself starts (e2e/smtp-sink.ts), so the test can
// read what the site sent — the form file as an attachment. Without the sink running, sends simply fail.
const smtpPort = Number(process.env.E2E_SMTP_PORT ?? 2526)
await payload.updateGlobal({
slug: 'site-integrations',
data: { emailTransport: 'smtp', smtpFromAddress: '[email protected]', smtpHost: '127.0.0.1', smtpPassword: 'e2e-sink', smtpPort, smtpUser: 'e2e' } as never,
overrideAccess: true,
})
console.log(`[e2e] e-mail sending points at the local sink 127.0.0.1:${smtpPort}`)
process.exit(0)
+67
View File
@@ -1,5 +1,6 @@
import { expect, type Page, test } from '@playwright/test'
import { attachmentOf, startSmtpSink } from './smtp-sink'
import { totp } from './totp'
/**
@@ -66,6 +67,72 @@ for (const l of LOCALES) {
})
}
// Files on forms (forms: { attachments: true }): e-mailed to the studio, never stored. A real browser, the real
// endpoint and a local mail sink — the file must arrive as an attachment of the staff e-mail only.
test.describe('the quote form sends a file by e-mail', () => {
const PDF = Buffer.concat([Buffer.from('%PDF-1.7\n1 0 obj\n<<>>\nendobj\n%%EOF\n'), Buffer.alloc(200_000, 0x20)])
let sink: Awaited<ReturnType<typeof startSmtpSink>>
test.beforeAll(async () => {
sink = await startSmtpSink(Number(process.env.E2E_SMTP_PORT ?? 2526))
})
test.afterAll(async () => {
await sink.close()
})
async function fillQuote(page: Page) {
await page.goto('/en/quote')
await rejectCookies(page)
const form = page.locator('form[data-ipal="form"]').first()
await form.locator('input[name="name"]').fill('Test Smoke')
await form.locator('input[name="email"]').fill('[email protected]')
await form.locator('button[type="submit"]').click() // Next
await form.locator('input[name="scope"][value="building"]').check()
await form.locator('input[name="area"][value="s"]').check()
await form.locator('input[name="consent"]').check()
return form
}
test('a wrong file is refused at the field; a PDF arrives attached to the staff e-mail, not the customer one', async ({ page }) => {
const form = await fillQuote(page)
const input = form.locator('input[type="file"][name="attachment"]')
await expect(input).toHaveAttribute('accept', /\.pdf/)
// a type the field does not accept: the message shows at once, by the field
await input.setInputFiles({ buffer: Buffer.from('MZ'), mimeType: 'application/octet-stream', name: 'plan.exe' })
await expect(form.locator('[id$="attachment-error"]')).toContainText('plan.exe')
// keyboard: the Remove button is a real button — focus it and press Enter
await form.getByRole('button', { name: /Remove plan\.exe/ }).focus()
await page.keyboard.press('Enter')
await expect(form.locator('[data-ipal="form-files"] li')).toHaveCount(0)
// a program renamed to .pdf passes the browser check and is stopped by the server (content, not name)
await input.setInputFiles({ buffer: Buffer.concat([Buffer.from('MZ\x90\x00'), Buffer.alloc(2000)]), mimeType: 'application/pdf', name: 'plan.pdf' })
await expect(form.locator('input[name="cf-turnstile-response"]')).not.toHaveValue('', { timeout: 15_000 })
await form.locator('button[type="submit"]').click()
await expect(form.locator('[id$="attachment-error"]')).toContainText('not an accepted file type', { timeout: 15_000 })
expect(sink.messages).toHaveLength(0)
// the real file
await input.setInputFiles({ buffer: PDF, mimeType: 'application/pdf', name: 'Floor plan (ground).pdf' })
await expect(form.locator('[data-ipal="form-files"] li')).toContainText('Floor plan (ground).pdf')
await expect(form.locator('input[name="cf-turnstile-response"]')).not.toHaveValue('', { timeout: 15_000 })
const posted = page.waitForResponse((r) => r.url().includes('/api/ipal/forms/submit') && r.request().method() === 'POST')
await form.locator('button[type="submit"]').click()
expect((await posted).status()).toBe(200)
await expect(page.locator('[data-ipal="form-success"]')).toBeVisible({ timeout: 15_000 })
await expect.poll(() => sink.messages.length, { timeout: 15_000 }).toBe(2)
const staff = sink.messages.find((m) => !m.to.join().includes('[email protected]'))!
const customer = sink.messages.find((m) => m.to.join().includes('[email protected]'))!
const attached = attachmentOf(staff.data, 'Floor plan (ground).pdf')
expect(attached && Buffer.compare(attached, PDF)).toBe(0)
const text = (raw: string) => raw.replace(/=\n/g, '') // undo quoted-printable soft line breaks
expect(text(staff.data)).toContain('not checked for viruses')
expect(customer.data).not.toContain('Content-Disposition: attachment')
expect(text(customer.data)).toContain('Floor plan (ground).pdf') // the name in the summary, never the file
})
})
test('every sitemap URL answers 200 with a title, canonical, hreflang and JSON-LD', async ({ page, request }) => {
const xml = await (await request.get('/sitemap.xml')).text()
const urls = [...xml.matchAll(/<loc>([^<]+)<\/loc>/g)].map((m) => new URL(m[1]).pathname)
+64
View File
@@ -0,0 +1,64 @@
import { createServer, type Server } from 'node:net'
export type SinkMessage = { data: string; to: string[] }
/**
* A mail sink for the smoke tests: just enough SMTP for nodemailer to log in and deliver. It keeps every
* message in memory, so a test can read what the site really sent (recipients, attachments).
* e2e/create-test-admin.ts points Site integrations → E-mail sending at it (127.0.0.1:E2E_SMTP_PORT).
*/
export function startSmtpSink(port: number): Promise<{ close: () => Promise<void>; messages: SinkMessage[] }> {
const messages: SinkMessage[] = []
const server: Server = createServer((socket) => {
const mail: SinkMessage = { data: '', to: [] }
let inData = false
let buffer = ''
const reply = (line: string) => socket.write(`${line}\r\n`)
reply('220 localhost ESMTP smoke-sink')
socket.on('error', () => undefined)
socket.on('data', (chunk) => {
buffer += chunk.toString('latin1')
let index: number
while ((index = buffer.indexOf('\r\n')) >= 0) {
const line = buffer.slice(0, index)
buffer = buffer.slice(index + 2)
if (inData) {
if (line === '.') {
inData = false
messages.push({ ...mail, to: [...mail.to] })
reply('250 2.0.0 Ok: queued')
} else {
mail.data += `${line}\n`
}
continue
}
const command = line.toUpperCase()
if (command.startsWith('EHLO')) {socket.write('250-localhost\r\n250-AUTH PLAIN LOGIN\r\n250 8BITMIME\r\n')}
else if (command.startsWith('AUTH PLAIN')) {reply('235 2.7.0 Authentication successful')}
else if (command.startsWith('MAIL FROM:')) {reply('250 2.1.0 Ok')}
else if (command.startsWith('RCPT TO:')) {
mail.to.push(line.slice(8).trim())
reply('250 2.1.5 Ok')
} else if (command === 'DATA') {
inData = true
reply('354 End data with <CR><LF>.<CR><LF>')
} else if (command === 'QUIT') {
reply('221 2.0.0 Bye')
socket.end()
} else {reply('502 5.5.2 Command not recognized')}
}
})
})
return new Promise((resolve, reject) => {
server.once('error', reject)
server.listen(port, '127.0.0.1', () => resolve({ close: () => new Promise((done) => server.close(() => done())), messages }))
})
}
/** The decoded bytes of the attachment named `filename` in a raw message, or null. */
export function attachmentOf(raw: string, filename: string): Buffer | null {
const at = raw.indexOf(`filename=${filename}`) >= 0 ? raw.indexOf(`filename=${filename}`) : raw.indexOf(`filename="${filename}"`)
if (at < 0) {return null}
const body = raw.slice(raw.indexOf('\n\n', at) + 2)
return Buffer.from(body.slice(0, body.indexOf('\n--')).replace(/\s+/g, ''), 'base64')
}
@@ -17,6 +17,11 @@ export const formClasses: BuilderFormClassNames = {
fields: 'grid grid-cols-12 gap-4',
form: 'grid gap-6',
formError: 'rounded-control bg-danger-surface p-3 text-danger',
file: 'block w-full text-fg file:mr-3 file:rounded-control file:border-0 file:bg-surface-muted file:px-3 file:py-2 file:text-fg-strong',
fileItem: 'flex flex-wrap items-center gap-2',
fileList: 'mt-2 grid gap-1 text-sm',
fileRemove: 'underline underline-offset-2',
help: 'mt-1 text-sm text-fg-muted',
input: control,
label: 'mb-1 block font-medium text-fg-strong',
legend: 'mb-1 font-medium text-fg-strong',
+6 -1
View File
@@ -69,7 +69,12 @@ export default buildConfig({
// @starter:endif
],
},
forms: { redirectRelationships: ['pages'], emailLayout: true },
// @starter:if demo
// attachments: the Quote form takes floor plans and photos — e-mailed to the studio, never stored (forms.md "Files")
forms: { attachments: true, emailLayout: true, redirectRelationships: ['pages'] },
// @starter:else
//: forms: { redirectRelationships: ['pages'], emailLayout: true }, // files on forms: add `attachments: true` (forms.md "Files")
// @starter:endif
// @starter:if twoFactor
twoFactor: { issuer: 'Example Studio', plugin: payloadTotp },
// @starter:else
+2 -2
View File
@@ -240,8 +240,8 @@ export async function seedDemoPages(seed: Seeder, media: Record<string, string>)
{
blockType: 'richText',
content: rich(
['Wycena obejmuje zakres prac, podział na etapy, harmonogram i warunki płatności. Im więcej wiemy na starcie, tym dokładniejsza będzie: podaj lokalizację, przybliżoną powierzchnię, rodzaj budynku albo wnętrza i planowany termin rozpoczęcia. Jeśli masz rzuty, zdjęcia, mapę do celów projektowych albo wypis z planu miejscowego, wspomnij o nich w formularzu — poprosimy o pliki w odpowiedzi. Wycena jest bezpłatna i do niczego nie zobowiązuje.'],
['The quote covers the scope of work, the stages, the schedule and the payment terms. The more we know at the start, the more precise it is: tell us the location, the rough floor area, the type of building or interior and when you plan to start. If you have floor plans, photos, a survey map or an extract from the local plan, mention them in the form — we will ask for the files in our reply. The quote is free and commits you to nothing.'],
['Wycena obejmuje zakres prac, podział na etapy, harmonogram i warunki płatności. Im więcej wiemy na starcie, tym dokładniejsza będzie: podaj lokalizację, przybliżoną powierzchnię, rodzaj budynku albo wnętrza i planowany termin rozpoczęcia. Jeśli masz rzuty, zdjęcia, mapę do celów projektowych albo wypis z planu miejscowego, dołącz je w formularzu (PDF, JPG lub PNG). Wycena jest bezpłatna i do niczego nie zobowiązuje.'],
['The quote covers the scope of work, the stages, the schedule and the payment terms. The more we know at the start, the more precise it is: tell us the location, the rough floor area, the type of building or interior and when you plan to start. If you have floor plans, photos, a survey map or an extract from the local plan, attach them in the form (PDF, JPG or PNG). The quote is free and commits you to nothing.'],
),
variant: 'narrow',
},
+12
View File
@@ -84,6 +84,18 @@ export async function seedForms(seed: Seeder, notifyTo: string) {
required: true,
},
{ blockType: 'date', label: tx('Planowany start', 'Planned start'), name: 'start' },
// @starter:if demo
// A File field (forms: { attachments: true }): sent with the notification to the studio, never stored on the site.
{
allowedTypes: ['pdf', 'jpg', 'png'],
blockType: 'file',
help: tx('Rzuty, zdjęcia lub mapa: PDF, JPG lub PNG, razem do 10 MB.', 'Floor plans, photos or a map: PDF, JPG or PNG, up to 10 MB together.'),
label: tx('Załączniki (opcjonalnie)', 'Attachments (optional)'),
maxFiles: 3,
maxSizeMB: 10,
name: 'attachment',
},
// @starter:endif
{ blockType: 'message', message: rich(tx('Dane przetwarzamy wyłącznie w celu przygotowania wyceny.', 'We use your data only to prepare the quote.')) },
consent,
],