Merge claude/mail-transport-choice: "Sending method" is an explicit choice in the panel (IWSN, own SMTP, Graph); nothing changes until another option is picked
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
+24
-1
@@ -699,7 +699,7 @@ describe('iapl-doctor: first-seen dates', () => {
|
||||
})
|
||||
|
||||
describe('e-mail: transport, the mail service, Graph, the confirm route', () => {
|
||||
const ids = ['mail-transport', 'mail-non-public', 'mail-relay-state', 'mail-reply-address', 'mail-graph-deprecated', 'mail-relay-route']
|
||||
const ids = ['mail-transport', 'mail-method', 'mail-non-public', 'mail-relay-state', 'mail-reply-address', 'mail-graph-deprecated', 'mail-relay-route']
|
||||
const relay = (extra: object = {}) => ({ connected: true, disconnected: false, nameReplaced: false, state: 'active', ...extra })
|
||||
const mail = (extra: object = {}) => ({ graphEnv: false, relay: relay(), replyAddress: true, status: null, transport: 'relay', ...extra })
|
||||
const run = async (deep: null | object, files: Record<string, string> = {}) =>
|
||||
@@ -740,6 +740,29 @@ describe('e-mail: transport, the mail service, Graph, the confirm route', () =>
|
||||
expect(await run(mail({ nonPublic: true, nonPublicBy: 'noindex', otherHostEntries: true }))).toEqual(['mail-non-public:info'])
|
||||
})
|
||||
|
||||
test('mail-method: a chosen method that cannot be used is an error; nothing chosen yet is information', async () => {
|
||||
const find = async (deep: object) => (await doctor(project({ ...base(), 'src/payload.config.ts': 'iapl({ forms: {} })' }), ids, { deepStatus: { mail: mail(deep) } })).findings.filter((f) => f.rule === 'mail-method')
|
||||
const smtp = await find({ methodChosen: true, methodProblem: 'smtp-incomplete', relay: relay({ connected: false, state: undefined }), replyAddress: false, transport: 'smtp' })
|
||||
expect(smtp.map((f) => f.severity)).toEqual(['error'])
|
||||
expect(smtp[0].message).toContain('e-mails are not sent')
|
||||
expect(smtp[0].fix).toContain('server, user name and password')
|
||||
const graph = await find({ methodChosen: true, methodProblem: 'graph-not-set-up', relay: relay({ connected: false, state: undefined }), replyAddress: false, transport: 'graph' })
|
||||
expect(graph.map((f) => f.severity)).toEqual(['error'])
|
||||
expect(graph[0].message).toContain('GRAPH_*')
|
||||
const open = await find({ methodChosen: false })
|
||||
expect(open.map((f) => f.severity)).toEqual(['info'])
|
||||
expect(open[0].message).toContain('the built-in service')
|
||||
expect(open[0].message).toContain('the way it did before the upgrade')
|
||||
expect(open[0].fix).toContain('nothing to do')
|
||||
expect(await find({ methodChosen: true })).toEqual([])
|
||||
// Postgres / SQLite whose 1.17.1 migration has not run
|
||||
const column = await find({ methodChosen: false, methodColumnMissing: true })
|
||||
expect(column.map((f) => f.severity)).toEqual(['error'])
|
||||
expect(column[0].message).toContain('no column for "Sending method"')
|
||||
expect(column[0].fix).toContain('migrate:create')
|
||||
expect(await find({ methodChosen: false, relay: null, transport: 'none' })).toEqual([]) // that is mail-transport's error
|
||||
})
|
||||
|
||||
test('mail-non-public: says which signal makes the site a non-public copy — the development pattern, or IAPL_NOINDEX', async () => {
|
||||
const find = async (deep: object) => (await doctor(project({ ...base(), 'src/payload.config.ts': 'iapl({ forms: {} })' }), ids, { deepStatus: { mail: mail(deep) } })).findings
|
||||
const byHost = await find({ nonPublic: true, nonPublicBy: 'development-host', nonPublicPattern: '*.dev.netscale.pl' })
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* Postgres / SQLite upgraded to 1.17.1 WITHOUT the migration that adds the column of "Sending method"
|
||||
* (`emailMethod`), against the real adapter: the site must keep working — e-mail the way it went before, the
|
||||
* other integrations readable — say loudly what to do, and pick the choice up once the column exists.
|
||||
* SQLite in memory by default; `IPAL_TEST_POSTGRES_URI` runs it on Postgres. Not for MongoDB (no columns).
|
||||
*/
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, expect, test, vi } from 'vitest'
|
||||
|
||||
import { mailAdapter } from '../src/modules/email/mailAdapter.js'
|
||||
import { getMailMethod, setMailMethod } from '../src/modules/email/method.js'
|
||||
import { createFakeRelay } from '../src/modules/email/relay/fake.js'
|
||||
import { mailPanelState } from '../src/modules/email/relay/panel.js'
|
||||
import { getSiteIntegrations, mailMethodColumnMissing, resetMailMethodColumnMissing } from '../src/modules/payload/getSiteIntegrations.js'
|
||||
import { iapl } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
import { testDatabase } from './http/db.js'
|
||||
import { startPayloadServer, type TestServer } from './http/server.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
|
||||
|
||||
const sql = !process.env.IPAL_TEST_MONGO_URI
|
||||
const HOST = 'example.com'
|
||||
let payload: Payload
|
||||
let server: TestServer
|
||||
const fake = createFakeRelay({ allow: [HOST], callSite: async (url, init) => fetch(`${server.url}${new URL(url).pathname}`, { ...init, redirect: 'manual' }) })
|
||||
|
||||
beforeAll(async () => {
|
||||
if (!sql) {return}
|
||||
const config = buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-method-column-media') } }],
|
||||
db: testDatabase('methodcol'),
|
||||
editor: lexicalEditor(),
|
||||
email: mailAdapter(),
|
||||
plugins: [iapl({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, mail: { relay: { fetchImpl: fake.fetch, url: fake.url } }, twoFactor: false })],
|
||||
secret: 'integration-test-secret-0123456789',
|
||||
serverURL: `https://${HOST}`,
|
||||
telemetry: false,
|
||||
})
|
||||
payload = await getPayload({ config })
|
||||
server = await startPayloadServer(config)
|
||||
}, 120_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await server?.close()
|
||||
await payload?.destroy?.()
|
||||
resetMailMethodColumnMissing()
|
||||
})
|
||||
|
||||
test.skipIf(!sql)('without the column: one loud line, mail and the other settings keep working by the order of 1.17.0; with it: the choice works', async () => {
|
||||
// the site as 1.17.0 left it: a row with settings, sending through the service
|
||||
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { ga4MeasurementId: 'G-BEFORE1', smtpFromName: 'Kancelaria Example' } as never })
|
||||
const db = payload.db as unknown as { client?: { execute: (q: string) => Promise<unknown> }; pool?: { query: (q: string) => Promise<unknown> }; schemaName?: string }
|
||||
const run = (statement: string) => (db.pool ? db.pool.query(statement) : db.client!.execute(statement))
|
||||
const table = db.pool && db.schemaName ? `"${db.schemaName}"."site_integrations"` : '"site_integrations"'
|
||||
await run(`ALTER TABLE ${table} DROP COLUMN "email_method"`)
|
||||
resetMailMethodColumnMissing()
|
||||
|
||||
const error = vi.spyOn(payload.logger, 'error').mockImplementation(() => undefined as never)
|
||||
// Payload's own read of the global fails — that is the panel page …
|
||||
await expect(payload.findGlobal({ slug: 'site-integrations' as never })).rejects.toThrow()
|
||||
// … the plugin's readers do not: analytics and Turnstile settings are there
|
||||
expect(await getSiteIntegrations<{ ga4MeasurementId?: string }>(payload)).toMatchObject({ ga4MeasurementId: 'G-BEFORE1' })
|
||||
expect(mailMethodColumnMissing()).toBe(true)
|
||||
expect(error).toHaveBeenCalledTimes(1)
|
||||
expect(String(error.mock.calls[0]?.[0])).toMatch(/the column for "emailMethod".*is missing.*keeps working.*migrate:create/s)
|
||||
// e-mail leaves the way it did before the upgrade (no SMTP server: the service), and says nothing more
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
expect(await mailPanelState({ payload }, undefined)).toMatchObject({ methodChosen: false, methodColumnMissing: true, transport: 'relay' })
|
||||
expect(await payload.sendEmail({ html: '<p>Hello.</p>', subject: 'Before the migration', to: '[email protected]' })).toMatchObject({ transport: 'relay' })
|
||||
expect(fake.outbox.at(-1)).toMatchObject({ subject: 'Before the migration' })
|
||||
await getSiteIntegrations(payload)
|
||||
expect(error).toHaveBeenCalledTimes(1) // once, not on every read
|
||||
// the method cannot be chosen yet
|
||||
await expect(setMailMethod(payload, 'smtp')).rejects.toThrow()
|
||||
|
||||
// the migration: the column is there → reads are whole again, the choice is stored and used
|
||||
await run(`ALTER TABLE ${table} ADD COLUMN "email_method" ${db.pool && db.schemaName ? `"${db.schemaName}"."enum_site_integrations_email_method"` : 'text'}`)
|
||||
resetMailMethodColumnMissing() // (a running process looks again within a minute; a deploy restarts it anyway)
|
||||
expect((await getSiteIntegrations<{ emailMethod?: string }>(payload)).emailMethod).toBe('relay') // shown as selected
|
||||
expect(mailMethodColumnMissing()).toBe(false)
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
await setMailMethod(payload, 'smtp')
|
||||
expect(await getMailMethod(payload)).toBe('smtp')
|
||||
expect(await mailPanelState({ payload }, undefined)).toMatchObject({ methodChosen: true, methodProblem: 'smtp-incomplete', transport: 'smtp' })
|
||||
expect((await mailPanelState({ payload }, undefined)).methodColumnMissing).toBeUndefined()
|
||||
const before = fake.requests.length
|
||||
expect(await payload.sendEmail({ html: '<p>Hello.</p>', subject: 'After', to: '[email protected]' })).toMatchObject({ code: 'not-configured', sent: false })
|
||||
expect(fake.requests).toHaveLength(before)
|
||||
error.mockRestore()
|
||||
})
|
||||
@@ -0,0 +1,380 @@
|
||||
/**
|
||||
* "Sending method" on a running Payload (SQLite by default; MongoDB and Postgres through
|
||||
* IPAL_TEST_MONGO_URI / IPAL_TEST_POSTGRES_URI — test/http/db.ts): the explicit choice of 1.17.1.
|
||||
* - upgrade: a site of 1.17.0 or 1.16.x, with nothing chosen, shows the method it sends through today and
|
||||
* keeps sending; nothing is written by reading;
|
||||
* - the first save of the panel's form stores the choice; from then on what is chosen is what is used —
|
||||
* an unusable choice fails loudly and nothing leaves another way;
|
||||
* - the choice is the stored field `emailMethod`, empty until somebody chooses (Postgres / SQLite: a column —
|
||||
* test/mailMethodColumnMissing.test.ts is the site whose migration has not run).
|
||||
*/
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { mailAdapter, resolveMailMethod, resolveMailTransport } from '../src/modules/email/mailAdapter.js'
|
||||
import { getMailMethod, setMailMethod } from '../src/modules/email/method.js'
|
||||
import { createFakeRelay } from '../src/modules/email/relay/fake.js'
|
||||
import { mailPanelState } from '../src/modules/email/relay/panel.js'
|
||||
import { SECRET_CLEAR } from '../src/modules/secrets/writeOnly.js'
|
||||
import { iapl } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
import { testDatabase } from './http/db.js'
|
||||
import { startPayloadServer, type TestServer } from './http/server.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
|
||||
|
||||
const PASSWORD = 'a-long-test-password-1'
|
||||
const HOST = 'example.com'
|
||||
const GRAPH_ENV = ['GRAPH_TENANT_ID', 'GRAPH_CLIENT_ID', 'GRAPH_CLIENT_SECRET', 'GRAPH_SENDER']
|
||||
// a mail server nobody listens on: an SMTP attempt fails at once, and is told apart from "not attempted"
|
||||
const SMTP = { smtpHost: '127.0.0.1', smtpPassword: 'smtp-test-password', smtpPort: 9, smtpUser: 'mailer' }
|
||||
const NO_SMTP = { smtpHost: null, smtpPassword: SECRET_CLEAR, smtpPort: 587, smtpUser: null }
|
||||
const MESSAGE = { html: '<p>Hello.</p>', subject: 'New enquiry', to: '[email protected]' }
|
||||
|
||||
let server: TestServer
|
||||
let payload: Payload
|
||||
let admin: Record<string, string>
|
||||
|
||||
const fake = createFakeRelay({
|
||||
allow: [HOST],
|
||||
callSite: async (url, init) => fetch(`${server.url}${new URL(url).pathname}`, { ...init, redirect: 'manual' }),
|
||||
})
|
||||
|
||||
const makeConfig = (mail?: Parameters<typeof iapl>[0]['mail'], name = 'mailmethod') =>
|
||||
buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-mail-method-media') } }],
|
||||
db: testDatabase(name),
|
||||
editor: lexicalEditor(),
|
||||
email: mailAdapter({ smtp: { connectionTimeout: 2000 } as never }),
|
||||
plugins: [iapl({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, mail, twoFactor: false })],
|
||||
secret: 'integration-test-secret-0123456789',
|
||||
serverURL: `https://${HOST}`,
|
||||
telemetry: false,
|
||||
})
|
||||
|
||||
const api = (pathname: string, init: RequestInit = {}) =>
|
||||
fetch(`${server.url}/api${pathname}`, { ...init, headers: { 'content-type': 'application/json', ...admin, ...(init.headers as Record<string, string>) } })
|
||||
/** The global as the panel reads it. */
|
||||
const read = async () => (await (await api('/globals/site-integrations?depth=0')).json()) as Record<string, unknown>
|
||||
/** A save the way the panel's form makes it: the whole document, with what the form shows. */
|
||||
const saveForm = async (change: Record<string, unknown> = {}) => {
|
||||
const { id: _i, createdAt: _c, emailStatus: _s, globalType: _g, smtpPassword: _p, turnstileStatus: _t, updatedAt: _u, ...form } = await read()
|
||||
return api('/globals/site-integrations', { body: JSON.stringify({ ...form, ...change }), method: 'POST' })
|
||||
}
|
||||
/** A site as an older version left it: the stored fields only, nothing chosen. */
|
||||
const asStored = async (data: Record<string, unknown>) => {
|
||||
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { emailMethod: null, emailStatus: { checkedAt: null, code: null, message: null, since: null, state: null }, emailTransport: 'smtp', ...NO_SMTP, ...data } as never })
|
||||
}
|
||||
const state = () => mailPanelState({ payload }, undefined)
|
||||
const send = () => payload.sendEmail(MESSAGE) as Promise<{ code?: string; sent?: boolean; transport?: string }>
|
||||
const relayCalls = () => fake.requests.filter((r) => r.path === '/v1/send').length
|
||||
const status = async () => ((await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0 })) as unknown as { emailStatus?: { code?: string; state?: string } }).emailStatus
|
||||
|
||||
beforeAll(async () => {
|
||||
const config = makeConfig({ relay: { fetchImpl: fake.fetch, url: fake.url } })
|
||||
payload = await getPayload({ config })
|
||||
server = await startPayloadServer(config)
|
||||
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'] } as never })
|
||||
const res = await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: '[email protected]', password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })
|
||||
admin = { authorization: `JWT ${((await res.json()) as { token: string }).token}` }
|
||||
}, 120_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await server?.close()
|
||||
await payload?.destroy?.()
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
for (const name of GRAPH_ENV) {vi.stubEnv(name, '')}
|
||||
})
|
||||
afterEach(() => vi.unstubAllEnvs())
|
||||
|
||||
describe('upgrade, with no edit: the site shows the method it sends through today, and keeps sending', () => {
|
||||
test('a 1.17.0 site that sends through the service because SMTP is empty: "IWSN" is selected, mail leaves through it, reading writes nothing', async () => {
|
||||
await asStored({ smtpFromAddress: '[email protected]', smtpFromName: 'Kancelaria Example' })
|
||||
expect((await read()).emailMethod).toBe('relay')
|
||||
expect(await state()).toMatchObject({ methodChosen: false, transport: 'relay' })
|
||||
const before = relayCalls()
|
||||
expect(await send()).toMatchObject({ transport: 'relay' })
|
||||
expect(relayCalls()).toBe(before + 1)
|
||||
expect(fake.outbox.at(-1)).toMatchObject({ subject: 'New enquiry' })
|
||||
// the stored field is what it was, and nothing was chosen on the site's behalf
|
||||
expect((await read()).emailTransport).toBe('smtp')
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
})
|
||||
|
||||
test('a site with its SMTP server filled in: "Own SMTP server" is selected, the service is not contacted', async () => {
|
||||
await asStored(SMTP)
|
||||
expect((await read()).emailMethod).toBe('smtp')
|
||||
expect(await state()).toMatchObject({ methodChosen: false, transport: 'smtp' })
|
||||
const before = fake.requests.length
|
||||
const sent = await send().catch((e: Error) => ({ code: 'threw', error: e.message, sent: false }))
|
||||
expect(sent.sent).not.toBe(true) // nobody listens on the port: SMTP was tried, and only SMTP
|
||||
expect(fake.requests).toHaveLength(before)
|
||||
expect((await status())?.code).toBe('smtp-error')
|
||||
})
|
||||
|
||||
test('a Graph site: "Microsoft Graph (deprecated)" is selected — with the choice stored as `graph`, or with only the GRAPH_* variables', async () => {
|
||||
for (const name of GRAPH_ENV) {vi.stubEnv(name, 'x')}
|
||||
await asStored({ emailTransport: 'graph' })
|
||||
expect((await read()).emailMethod).toBe('graph')
|
||||
expect(await state()).toMatchObject({ methodChosen: false, transport: 'graph' })
|
||||
await asStored({})
|
||||
expect((await read()).emailMethod).toBe('graph')
|
||||
// and with SMTP filled in beside the variables: SMTP, as in 1.17.0 and 1.16
|
||||
await asStored(SMTP)
|
||||
expect((await read()).emailMethod).toBe('smtp')
|
||||
})
|
||||
|
||||
test('1.16.x straight to 1.17.1: "Graph" stored without the variables and SMTP filled in → SMTP; half an SMTP set-up → the service, with the hint', async () => {
|
||||
await asStored({ emailTransport: 'graph', ...SMTP })
|
||||
expect((await read()).emailMethod).toBe('smtp')
|
||||
expect(await state()).toMatchObject({ methodChosen: false, transport: 'smtp' })
|
||||
await asStored({ smtpHost: 'smtp.example.com', smtpUser: 'mailer' })
|
||||
expect((await read()).emailMethod).toBe('relay')
|
||||
expect(await state()).toMatchObject({ methodChosen: false, smtpIncomplete: true, transport: 'relay' })
|
||||
const before = relayCalls()
|
||||
expect(await send()).toMatchObject({ transport: 'relay' })
|
||||
expect(relayCalls()).toBe(before + 1)
|
||||
})
|
||||
|
||||
test('a new site (nothing ever saved): "IWSN" is selected', async () => {
|
||||
await asStored({})
|
||||
expect((await read()).emailMethod).toBe('relay')
|
||||
})
|
||||
})
|
||||
|
||||
describe('the choice: what is chosen is what is used', () => {
|
||||
test('the owner\'s rule: saving without picking another option stores nothing and changes nothing; picking another one stores it', async () => {
|
||||
// an upgraded site on the service: the form is saved as it is, twice — nothing is chosen, mail goes as before
|
||||
await asStored({})
|
||||
for (const change of [{}, { smtpFromName: 'Kancelaria Example' }]) {
|
||||
const saved = await saveForm(change)
|
||||
expect(saved.status).toBe(200)
|
||||
expect(((await saved.json()) as { result: { emailMethod: string } }).result.emailMethod).toBe('relay')
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
}
|
||||
expect(await state()).toMatchObject({ methodChosen: false, transport: 'relay' })
|
||||
// …and it still follows what is filled in, as before (the old order): an SMTP server is filled in → SMTP
|
||||
await payload.updateGlobal({ slug: 'site-integrations' as never, data: SMTP as never })
|
||||
expect((await read()).emailMethod).toBe('smtp')
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
// a Graph site saved as it is stays a Graph site (the old order), with the variables
|
||||
for (const name of GRAPH_ENV) {vi.stubEnv(name, 'x')}
|
||||
await asStored({ emailTransport: 'graph' })
|
||||
await saveForm({})
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
expect(await read()).toMatchObject({ emailMethod: 'graph', emailTransport: 'graph' })
|
||||
for (const name of GRAPH_ENV) {vi.stubEnv(name, '')}
|
||||
// picking ANOTHER option stores it, and the answer shows it; the stored field of 1.17.0 follows
|
||||
await asStored({})
|
||||
const changed = await saveForm({ emailMethod: 'graph' })
|
||||
expect(((await changed.json()) as { result: { emailMethod: string; emailTransport: string } }).result).toMatchObject({ emailMethod: 'graph', emailTransport: 'graph' })
|
||||
expect(await getMailMethod(payload)).toBe('graph')
|
||||
// once chosen, a save that keeps it keeps it, and the method no longer follows what is filled in
|
||||
await saveForm({ emailMethod: 'relay' })
|
||||
expect(await getMailMethod(payload)).toBe('relay')
|
||||
await saveForm({ smtpFromName: 'Kancelaria Example' })
|
||||
expect(await getMailMethod(payload)).toBe('relay')
|
||||
await payload.updateGlobal({ slug: 'site-integrations' as never, data: SMTP as never })
|
||||
expect(await state()).toMatchObject({ methodChosen: true, transport: 'relay' })
|
||||
await saveForm({ emailMethod: 'smtp' })
|
||||
expect(await read()).toMatchObject({ emailMethod: 'smtp', emailTransport: 'smtp' })
|
||||
})
|
||||
|
||||
test('the state block is told whether Graph could send, for its warning before the save', async () => {
|
||||
await asStored({})
|
||||
expect((await state()).graphReady).toBe(false)
|
||||
for (const name of GRAPH_ENV) {vi.stubEnv(name, 'x')}
|
||||
expect((await state()).graphReady).toBe(true)
|
||||
})
|
||||
|
||||
test('"IWSN" chosen: the service carries the mail although an SMTP server is filled in and the GRAPH_* variables are set', async () => {
|
||||
await asStored(SMTP)
|
||||
await saveForm({ emailMethod: 'relay' })
|
||||
for (const name of GRAPH_ENV) {vi.stubEnv(name, 'x')}
|
||||
expect(await state()).toMatchObject({ methodChosen: true, transport: 'relay' })
|
||||
const before = relayCalls()
|
||||
expect(await send()).toMatchObject({ transport: 'relay' })
|
||||
expect(relayCalls()).toBe(before + 1)
|
||||
expect((await read()).emailMethod).toBe('relay')
|
||||
})
|
||||
|
||||
test('"Own SMTP server" chosen with nothing filled in: the mail fails and says so — nothing goes through the service', async () => {
|
||||
await asStored({})
|
||||
expect((await saveForm({ emailMethod: 'smtp' })).status).toBe(200)
|
||||
expect(await state()).toMatchObject({ methodChosen: true, methodProblem: 'smtp-incomplete', transport: 'smtp' })
|
||||
const before = fake.requests.length
|
||||
expect(await send()).toMatchObject({ code: 'not-configured', sent: false })
|
||||
expect(fake.requests).toHaveLength(before)
|
||||
expect(await status()).toMatchObject({ code: 'smtp-incomplete', state: 'degraded' })
|
||||
// the test e-mail says the same to the admin, and still nothing leaves another way
|
||||
const tested = await api('/ipal/test-email', { body: JSON.stringify({ to: '[email protected]' }), method: 'POST' })
|
||||
expect(tested.status).toBe(502)
|
||||
expect(fake.requests).toHaveLength(before)
|
||||
// the form still shows what was chosen, not what would work
|
||||
expect((await read()).emailMethod).toBe('smtp')
|
||||
})
|
||||
|
||||
test('"Microsoft Graph" chosen on a server without GRAPH_*: fails loudly; neither SMTP (filled in) nor the service is tried', async () => {
|
||||
await asStored(SMTP)
|
||||
await saveForm({ emailMethod: 'graph' })
|
||||
expect(await state()).toMatchObject({ methodChosen: true, methodProblem: 'graph-not-set-up', transport: 'graph' })
|
||||
const before = fake.requests.length
|
||||
expect(await send()).toMatchObject({ code: 'graph-not-set-up', sent: false })
|
||||
expect(fake.requests).toHaveLength(before)
|
||||
expect(await status()).toMatchObject({ code: 'graph-not-set-up', state: 'degraded' }) // not `smtp-error`: SMTP was not tried
|
||||
const tested = await api('/ipal/test-email', { body: JSON.stringify({ to: '[email protected]' }), method: 'POST' })
|
||||
expect(tested.status).toBe(502)
|
||||
expect(((await tested.json()) as { code: string; error: string })).toMatchObject({ code: 'graph-not-set-up' })
|
||||
// with the variables the problem is gone (no send here: that would call Microsoft)
|
||||
for (const name of GRAPH_ENV) {vi.stubEnv(name, 'x')}
|
||||
expect((await state()).methodProblem).toBeUndefined()
|
||||
})
|
||||
|
||||
test('the test e-mail names the method that carried it', async () => {
|
||||
await asStored({ smtpFromName: 'Kancelaria Example' })
|
||||
await saveForm({ emailMethod: 'relay' })
|
||||
const tested = await api('/ipal/test-email', { body: JSON.stringify({ to: '[email protected]' }), method: 'POST' })
|
||||
expect(tested.status).toBe(200)
|
||||
expect(await tested.json()).toMatchObject({ ok: true, transport: 'relay' })
|
||||
})
|
||||
|
||||
test('a save that names nothing about e-mail leaves the choice alone; the old field written alone means what it meant', async () => {
|
||||
await asStored({})
|
||||
await setMailMethod(payload, 'smtp')
|
||||
expect((await api('/globals/site-integrations', { body: JSON.stringify({ ga4MeasurementId: 'G-TEST123' }), method: 'POST' })).status).toBe(200)
|
||||
expect(await getMailMethod(payload)).toBe('smtp')
|
||||
// a script from before 1.17.1 writes `emailTransport`: the order of 1.17.0 applies again
|
||||
expect((await api('/globals/site-integrations', { body: JSON.stringify({ emailTransport: 'graph' }), method: 'POST' })).status).toBe(200)
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
expect((await read()).emailMethod).toBe('relay') // Graph stored, no variables, no SMTP: the service, as in 1.17.0
|
||||
// the Local API, and the building blocks
|
||||
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { emailMethod: 'smtp' } as never })
|
||||
expect(await getMailMethod(payload)).toBe('smtp')
|
||||
await setMailMethod(payload, null)
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
await expect(setMailMethod(payload, 'sendmail' as never)).rejects.toThrow('not a sending method')
|
||||
// a value that is not a method is refused by the field
|
||||
expect((await api('/globals/site-integrations', { body: JSON.stringify({ emailMethod: 'sendmail' }), method: 'POST' })).status).toBe(400)
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
})
|
||||
|
||||
test('only an admin reaches the choice; a save that only records the sending status does not store one', async () => {
|
||||
await asStored({})
|
||||
expect((await fetch(`${server.url}/api/globals/site-integrations`, { body: JSON.stringify({ emailMethod: 'smtp' }), headers: { 'content-type': 'application/json' }, method: 'POST' })).status).toBeGreaterThanOrEqual(401)
|
||||
// the plugin's own writes (the status after a send) and a partial save carry the method the read SHOWED — it must not become a choice
|
||||
await send()
|
||||
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpFromName: 'Kancelaria Example' } as never })
|
||||
expect((await api('/globals/site-integrations', { body: JSON.stringify({ ga4MeasurementId: 'G-TEST456' }), method: 'POST' })).status).toBe(200)
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
expect((await read()).emailMethod).toBe('relay')
|
||||
})
|
||||
})
|
||||
|
||||
describe('review M-1, M-2', () => {
|
||||
test('M-1: the plugin\'s own status write never stores a choice — a failed send, then a send that works again', async () => {
|
||||
// an upgraded site with an SMTP server nobody listens on: nothing chosen, SMTP shown
|
||||
await asStored(SMTP)
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
await send().catch(() => undefined)
|
||||
expect((await status())?.state).toBe('degraded') // the status WAS written
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
// the admin empties the SMTP server later: the site goes back to the service, as the old order says
|
||||
await payload.updateGlobal({ slug: 'site-integrations' as never, data: NO_SMTP as never })
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
// (emptying the server cleared the old status; a status written the plugin's way, then a send that works: degraded → ok)
|
||||
await payload.updateGlobal({ slug: 'site-integrations' as never, context: { ipalIntegrationStatus: true }, data: { emailStatus: { code: 'relay-error', state: 'degraded' } } as never })
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
expect(await send()).toMatchObject({ transport: 'relay' })
|
||||
expect((await status())?.state).toBe('ok')
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
expect((await read()).emailMethod).toBe('relay')
|
||||
// and a stored choice survives the same writes
|
||||
await setMailMethod(payload, 'smtp')
|
||||
await send()
|
||||
expect((await status())?.code).toBe('smtp-incomplete')
|
||||
expect(await getMailMethod(payload)).toBe('smtp')
|
||||
await setMailMethod(payload, 'relay')
|
||||
await send()
|
||||
expect(await getMailMethod(payload)).toBe('relay')
|
||||
})
|
||||
|
||||
test('M-2: anything but null or one of the three values is refused with 400, and nothing is stored', async () => {
|
||||
await asStored({})
|
||||
for (const bad of [0, 1, true, ['relay'], { method: 'relay' }, 'sendmail', '', 'RELAY']) {
|
||||
const res = await api('/globals/site-integrations', { body: JSON.stringify({ emailMethod: bad }), method: 'POST' })
|
||||
expect(res.status, JSON.stringify(bad)).toBe(400)
|
||||
await expect(payload.updateGlobal({ slug: 'site-integrations' as never, data: { emailMethod: bad } as never }), JSON.stringify(bad)).rejects.toThrow()
|
||||
}
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
expect((await api('/globals/site-integrations', { body: JSON.stringify({ emailMethod: null }), method: 'POST' })).status).toBe(200)
|
||||
expect((await api('/globals/site-integrations', { body: JSON.stringify({ emailMethod: 'smtp' }), method: 'POST' })).status).toBe(200)
|
||||
expect(await getMailMethod(payload)).toBe('smtp')
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveMailMethod', () => {
|
||||
const full = { smtpHost: 'smtp.example.com', smtpPassword: 'x', smtpUser: 'u' }
|
||||
const half = { smtpHost: 'smtp.example.com' }
|
||||
const on = { graphEnv: true, relay: true }
|
||||
const off = { graphEnv: false, relay: true }
|
||||
|
||||
test.each([
|
||||
// chosen, settings, env → method, problem
|
||||
['relay', full, on, 'relay', undefined],
|
||||
['relay', {}, off, 'relay', undefined],
|
||||
['smtp', full, on, 'smtp', undefined],
|
||||
['smtp', half, on, 'smtp', 'smtp-incomplete'],
|
||||
['smtp', {}, off, 'smtp', 'smtp-incomplete'],
|
||||
['graph', full, on, 'graph', undefined],
|
||||
['graph', full, off, 'graph', 'graph-not-set-up'],
|
||||
['graph', {}, off, 'graph', 'graph-not-set-up'],
|
||||
] as const)('chosen %s, %j, %j → %s (%s)', (chosen, settings, state, method, problem) => {
|
||||
expect(resolveMailMethod(settings, { ...state, chosen })).toEqual({ explicit: true, method, ...(problem ? { problem } : {}) })
|
||||
})
|
||||
|
||||
test('nothing chosen: the order of 1.17.0, never a problem; "IWSN" chosen with the service switched off counts as nothing chosen', () => {
|
||||
for (const settings of [{}, half, full, { emailTransport: 'graph' as const }, { emailTransport: 'graph' as const, ...full }]) {
|
||||
for (const state of [on, off, { graphEnv: true, relay: false }, { graphEnv: false, relay: false }]) {
|
||||
expect(resolveMailMethod(settings, { ...state, chosen: null })).toEqual({ explicit: false, method: resolveMailTransport(settings, state) })
|
||||
expect(resolveMailMethod(settings, { ...state, chosen: 'relay', relay: false })).toEqual({ explicit: false, method: resolveMailTransport(settings, { ...state, relay: false }) })
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('where the choice is stored', () => {
|
||||
test('in the global\'s own field: empty until somebody chooses, then the method; the three values are the same with the service on and off', async () => {
|
||||
await asStored({})
|
||||
const db = payload.db as unknown as { connection?: { collection: (n: string) => { findOne: (q: object) => Promise<null | Record<string, unknown>> } }; tables?: Record<string, Record<string, unknown>> }
|
||||
const raw = async (): Promise<unknown> => {
|
||||
if (db.tables) {return ((await payload.findGlobal({ slug: 'site-integrations' as never, context: { iaplStoredMailMethod: true }, depth: 0 })) as unknown as { emailMethod?: unknown }).emailMethod ?? null}
|
||||
return (await db.connection!.collection('globals').findOne({ globalType: 'site-integrations' }))?.emailMethod ?? null
|
||||
}
|
||||
expect(await raw()).toBeNull()
|
||||
await saveForm({ emailMethod: 'smtp' })
|
||||
expect(await raw()).toBe('smtp')
|
||||
if (db.tables) {expect(Object.keys(db.tables.site_integrations).map((c) => c.toLowerCase())).toEqual(expect.arrayContaining(['emailtransport', 'emailmethod']))}
|
||||
await setMailMethod(payload, null)
|
||||
expect(await raw()).toBeNull()
|
||||
})
|
||||
|
||||
test('`mail: { relay: false }`: the option "IWSN" is not offered, and a stored choice of it counts as none', async () => {
|
||||
const methods = (config: Awaited<ReturnType<typeof makeConfig>>) => {
|
||||
const field = JSON.stringify(config.globals?.find((g) => g.slug === 'site-integrations')?.fields).match(/"name":"emailMethod".*?"options":\[(.*?)\]/)?.[1] ?? ''
|
||||
return [...field.matchAll(/"value":"(\w+)"/g)].map((m) => m[1])
|
||||
}
|
||||
expect(methods(await makeConfig(undefined, 'methodson'))).toEqual(['relay', 'smtp', 'graph'])
|
||||
// the stored values are the same (one SQL enum for every project); the option is not offered and not accepted
|
||||
expect(methods(await makeConfig({ relay: false }, 'methodsoff'))).toEqual(['relay', 'smtp', 'graph'])
|
||||
expect(JSON.stringify((await makeConfig({ relay: false }, 'methodsoff2')).globals?.find((g) => g.slug === 'site-integrations')?.fields ?? '')).not.toBe('')
|
||||
})
|
||||
})
|
||||
@@ -340,6 +340,8 @@ describe('switched off, and what did not change', () => {
|
||||
const on = names(await makeConfig(undefined, 'fieldson'))
|
||||
expect(on).toEqual(names(await makeConfig({ relay: false }, 'fieldsoff')))
|
||||
expect(on).toEqual([
|
||||
// new in 1.17.1 (Postgres / SQLite: one migration); the same three values with the service on and off
|
||||
'emailMethod:select(relay|smtp|graph)',
|
||||
'emailTransport:select(smtp|graph)',
|
||||
'smtpFromAddress:email',
|
||||
'smtpFromName:text',
|
||||
|
||||
Reference in New Issue
Block a user