Files
ipal-kit/test/mailMethodColumnMissing.test.ts
Radosław SmolińskiandClaude Fable 5.2 ee8ea42956 E-mail: "Sending method" is an explicit choice - IWSN (built-in), Own SMTP server, Microsoft Graph (deprecated)
What is chosen is what is used. The choice is the stored field `emailMethod` of Site integrations (empty until
somebody chooses); `emailTransport` of 1.6 - 1.17.0 stays, hidden.

- no silent switch: a chosen method that cannot be used (SMTP incomplete, Graph without GRAPH_*) fails loudly
  - status smtp-incomplete / graph-not-set-up, state block, doctor mail-method - and nothing is sent another way
- upgrade writes nothing and loses no mail: until somebody chooses, the order of 1.17.0 applies and the field
  shows its result as selected; the first save of the panel's form stores the choice
- only the chosen method's fields are shown; the test e-mail names the method (Graph too)
- mail: { relay: false } does not offer "IWSN" (the stored values stay three: one SQL enum for every project)
- Postgres / SQLite: one migration (a column). Before it runs the plugin's readers read the global without the
  field, mail goes the old way, one loud log line and the doctor say what to do
- getMailMethod, setMailMethod, resolveMailMethod, readMailSettings, mailMethodColumnMissing exported
- tests on SQLite, Postgres and MongoDB, with and without the migration; docs, AGENT.md, skills, changelog

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 22:39:03 +01:00

99 lines
5.9 KiB
TypeScript

/**
* 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()
})