* fix(inbox): trace every received mail and file multi-recipient mail once per inbox (#2181) A mail sent to both the +lev and +ver address of one inbox was read as its first recipient only, and an attachment whose processing threw left no row at all: the webhook answered 200, Resend never retried, and the document was gone with nothing for the user to find. Prod showed both shapes for the reporter (a +lev mail Resend accepted with zero inbox rows, and the second PDF of the +ver mail missing). - The webhook now reads every shared-domain recipient, groups them per inbox, files once per inbox with a company-scoped dedupe key, and resolves contradicting tags (+lev and +ver on one mail) to no hint so extraction classifies. - The per-attachment catch writes an error row instead of only a console line. - One InboundMailReceived behandlingshistorik event per mail and inbox records recipients, tags, hint, conflict and the outcome per attachment (filed, duplicate, rejected, failed). No sender or subject, matching the existing PII rule. - GET /inbound-history?days=30 serves those events, company-scoped, and the inbox workspace shows them under Källor as "Inkomna mejl", each filed row a click away. - The list says how many rows the type filter is hiding, with a click back to all types. - Migration 20260903190000 registers the event type and replaces the (email, attachment) unique index with (company, email, attachment). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CoG2CXf8B33Q5wp8gk4kW4 * fix(inbox): keep addresses and sender-typed tags out of the mail record, and let redelivery heal a transient failure Skeptic pass on #2244, two refutations: - The InboundMailReceived payload carried the recipient addresses and every plus-tag verbatim. An enskild firma's inbox local part is the owner's name, the tag is whatever the sender typed, and processing_history is append-only and outside the erasure path; a numeric tag also tripped the PII validator so the record was silently dropped. The event now carries inbox_id, the documented tags (+lev/+ver), an unknown-tag count and the outcome codes. The history route resolves inbox_id to the company's own address at read time. The DB strip trigger from 20260901110000 covers the new type (and is recreated, since staging skipped that file). - The catch-path error row made a Resend redelivery report "duplicate", so a transient download or storage failure that used to self-heal on retry became permanent. The row is marked transient and a redelivery replaces it; rejections (bad type, too large) stay duplicates. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CoG2CXf8B33Q5wp8gk4kW4 * fix(inbox): cap inbound fan-out, flag a truncated mail history, and name a replaced transient row Review pass on #2244: Superagent (bound the number of inboxes one mail can fan out to: five), CodeRabbit (the history route now returns has_more past 200 rows and the panel says so instead of "every mail"), and the Swedish accounting review (a redelivery that replaces a transient error row names the replaced row on the InboundMailReceived record, so the replacement leaves a trace). The migration comment states why the index swap is not CONCURRENTLY: Supabase branching applies migrations in a transaction. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(inbox): resolve every addressed inbox and record the ones past the fan-out cap CodeRabbit and the Swedish accounting review on #2244: slicing recipient groups before the lookup let five unknown local parts starve a real inbox and left companies past the cap with no trace. Every addressed inbox is now resolved (one cheap lookup each), the first five are processed, and the rest get their own InboundMailReceived record with outcome fan_out_capped, shown in the panel as "not processed". Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * chore(inbox): move the inbound-mail migration past the parties versions merged tonight Main moved party_decision_undo to 20260904000100 and added 20260904000200 (#2257, #2258). A version below prod's head is skipped by Supabase branching, so 20260903190000 becomes 20260904001000 unchanged. Staging re-tracked under the new version. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
148 lines
5.6 KiB
TypeScript
148 lines
5.6 KiB
TypeScript
import { describe, it, expect } from 'vitest'
|
|
import { randomUUID } from 'node:crypto'
|
|
import { getClient, getPool } from '@/tests/pg/setup'
|
|
import { seedCompany } from '@/tests/pg/fixtures'
|
|
|
|
/**
|
|
* Migration 20260904001000 (#2181): the InboundMailReceived catalog row, and
|
|
* the per-attachment idempotency index on invoice_inbox_items becoming
|
|
* company-scoped so one mail addressed to two inboxes files once per inbox.
|
|
* tests/pg/processing-event-types.pg.test.ts already proves every emitted
|
|
* type is registered; this file pins the two behaviours the webhook now
|
|
* relies on.
|
|
*/
|
|
describe('InboundMailReceived event type (#2181)', () => {
|
|
it('is registered in the catalog', async () => {
|
|
const { rows } = await getPool().query(
|
|
`SELECT 1 FROM public.processing_event_types WHERE event_type = 'InboundMailReceived'`,
|
|
)
|
|
expect(rows).toHaveLength(1)
|
|
})
|
|
|
|
it('still refuses an unregistered event type through the FK', async () => {
|
|
const { companyId } = await seedCompany()
|
|
const client = await getClient()
|
|
try {
|
|
await client.query('BEGIN')
|
|
await expect(
|
|
client.query(
|
|
`INSERT INTO public.processing_history
|
|
(company_id, correlation_id, aggregate_type, aggregate_id, event_type,
|
|
payload, actor, occurred_at)
|
|
VALUES ($1, $2, 'System', $2, 'InboundMailReceivedTypo', '{}'::jsonb,
|
|
'{"type":"system","id":"inbound-mail-received-test"}', now())`,
|
|
[companyId, randomUUID()],
|
|
),
|
|
).rejects.toMatchObject({ code: '23503' })
|
|
} finally {
|
|
await client.query('ROLLBACK').catch(() => {})
|
|
client.release()
|
|
}
|
|
})
|
|
})
|
|
|
|
describe('InboundMailReceived DB-side PII strip (#2181)', () => {
|
|
it('drops address and free-text keys on insert but keeps the ids and codes', async () => {
|
|
const { companyId } = await seedCompany()
|
|
const client = await getClient()
|
|
try {
|
|
await client.query('BEGIN')
|
|
const aggregateId = randomUUID()
|
|
const { rows } = await client.query<{ payload: Record<string, unknown> }>(
|
|
`INSERT INTO public.processing_history
|
|
(company_id, correlation_id, aggregate_type, aggregate_id, event_type,
|
|
payload, actor, occurred_at)
|
|
VALUES ($1, $2, 'System', $2, 'InboundMailReceived', $3::jsonb,
|
|
'{"type":"system","id":"inbound-mail-received-test"}', now())
|
|
RETURNING payload`,
|
|
[
|
|
companyId,
|
|
aggregateId,
|
|
JSON.stringify({
|
|
recipients: ['anna-andersson-x7f2+lev@example.test'],
|
|
to: ['anna-andersson-x7f2+lev@example.test'],
|
|
from: 'avsandare@example.test',
|
|
subject: 'Faktura',
|
|
inbox_id: aggregateId,
|
|
tags: ['lev'],
|
|
unknown_tag_count: 0,
|
|
outcome: 'attachments',
|
|
}),
|
|
],
|
|
)
|
|
expect(rows[0].payload).not.toHaveProperty('recipients')
|
|
expect(rows[0].payload).not.toHaveProperty('to')
|
|
expect(rows[0].payload).not.toHaveProperty('from')
|
|
expect(rows[0].payload).not.toHaveProperty('subject')
|
|
expect(rows[0].payload).toMatchObject({ inbox_id: aggregateId, tags: ['lev'], unknown_tag_count: 0, outcome: 'attachments' })
|
|
} finally {
|
|
await client.query('ROLLBACK').catch(() => {})
|
|
client.release()
|
|
}
|
|
})
|
|
})
|
|
|
|
describe('invoice_inbox_items idempotency per company (#2181)', () => {
|
|
async function insertItem(
|
|
client: Awaited<ReturnType<typeof getClient>>,
|
|
companyId: string,
|
|
userId: string,
|
|
emailId: string,
|
|
attachmentId: string | null,
|
|
) {
|
|
return client.query(
|
|
`INSERT INTO public.invoice_inbox_items
|
|
(company_id, user_id, status, source, resend_email_id, resend_attachment_id)
|
|
VALUES ($1, $2, 'received', 'email', $3, $4)
|
|
RETURNING id`,
|
|
[companyId, userId, emailId, attachmentId],
|
|
)
|
|
}
|
|
|
|
it('lets two companies file the same mail attachment, and refuses a repeat for one company', async () => {
|
|
const a = await seedCompany()
|
|
const b = await seedCompany()
|
|
const emailId = randomUUID()
|
|
const attachmentId = randomUUID()
|
|
const client = await getClient()
|
|
try {
|
|
await client.query('BEGIN')
|
|
await insertItem(client, a.companyId, a.userId, emailId, attachmentId)
|
|
// Before the migration this insert hit the (email, attachment) unique
|
|
// index and the second inbox's copy was lost.
|
|
await insertItem(client, b.companyId, b.userId, emailId, attachmentId)
|
|
|
|
// A Resend retry for the same company still dedupes at the index.
|
|
await client.query('SAVEPOINT repeat')
|
|
await expect(
|
|
insertItem(client, a.companyId, a.userId, emailId, attachmentId),
|
|
).rejects.toMatchObject({ code: '23505' })
|
|
await client.query('ROLLBACK TO SAVEPOINT repeat')
|
|
|
|
const { rows } = await client.query<{ n: string }>(
|
|
`SELECT count(*)::text AS n FROM public.invoice_inbox_items
|
|
WHERE resend_email_id = $1 AND resend_attachment_id = $2`,
|
|
[emailId, attachmentId],
|
|
)
|
|
expect(rows[0].n).toBe('2')
|
|
} finally {
|
|
await client.query('ROLLBACK').catch(() => {})
|
|
client.release()
|
|
}
|
|
})
|
|
|
|
it('keeps the old single-company index gone', async () => {
|
|
const { rows } = await getPool().query<{ indexname: string }>(
|
|
`SELECT indexname FROM pg_indexes
|
|
WHERE tablename = 'invoice_inbox_items'
|
|
AND indexname IN (
|
|
'idx_invoice_inbox_items_resend_email_attachment',
|
|
'idx_invoice_inbox_items_company_resend_email_attachment'
|
|
)`,
|
|
)
|
|
expect(rows.map((r) => r.indexname)).toEqual([
|
|
'idx_invoice_inbox_items_company_resend_email_attachment',
|
|
])
|
|
})
|
|
})
|